Compare commits

...
10 Commits
47 changed files with 1577 additions and 239 deletions

No files matched your search

@@ -0,0 +1,146 @@
[*]
charset = utf-8-bom
end_of_line = crlf
trim_trailing_whitespace = false
insert_final_newline = false
indent_style = space
indent_size = 4
# Microsoft .NET properties
csharp_preferred_modifier_order = public, private, protected, internal, file, new, static, abstract, virtual, sealed, readonly, override, extern, unsafe, volatile, async, required:suggestion
csharp_style_prefer_utf8_string_literals = true:suggestion
csharp_style_var_elsewhere = true:suggestion
csharp_style_var_for_built_in_types = true:suggestion
csharp_style_var_when_type_is_apparent = true:suggestion
dotnet_naming_rule.interfaces_rule.import_to_resharper = True
dotnet_naming_rule.interfaces_rule.resharper_description = Interfaces
dotnet_naming_rule.interfaces_rule.resharper_guid = a7a3339e-4e89-4319-9735-a9dc4cb74cc7
dotnet_naming_rule.interfaces_rule.severity = warning
dotnet_naming_rule.interfaces_rule.style = i_upper_camel_case_style
dotnet_naming_rule.interfaces_rule.symbols = interfaces_symbols
dotnet_naming_rule.unity_serialized_field_rule.import_to_resharper = True
dotnet_naming_rule.unity_serialized_field_rule.resharper_description = Unity serialized field
dotnet_naming_rule.unity_serialized_field_rule.resharper_guid = 5f0fdb63-c892-4d2c-9324-15c80b22a7ef
dotnet_naming_rule.unity_serialized_field_rule.severity = warning
dotnet_naming_rule.unity_serialized_field_rule.style = lower_camel_case_style
dotnet_naming_rule.unity_serialized_field_rule.symbols = unity_serialized_field_symbols
dotnet_naming_rule.unity_serialized_field_rule_1.import_to_resharper = True
dotnet_naming_rule.unity_serialized_field_rule_1.resharper_description = Unity serialized field
dotnet_naming_rule.unity_serialized_field_rule_1.resharper_guid = 5f0fdb63-c892-4d2c-9324-15c80b22a7ef
dotnet_naming_rule.unity_serialized_field_rule_1.severity = warning
dotnet_naming_rule.unity_serialized_field_rule_1.style = lower_camel_case_style
dotnet_naming_rule.unity_serialized_field_rule_1.symbols = unity_serialized_field_symbols_1
dotnet_naming_rule.unity_serialized_field_rule_2.import_to_resharper = True
dotnet_naming_rule.unity_serialized_field_rule_2.resharper_description = Unity serialized field
dotnet_naming_rule.unity_serialized_field_rule_2.resharper_guid = 5f0fdb63-c892-4d2c-9324-15c80b22a7ef
dotnet_naming_rule.unity_serialized_field_rule_2.severity = warning
dotnet_naming_rule.unity_serialized_field_rule_2.style = lower_camel_case_style
dotnet_naming_rule.unity_serialized_field_rule_2.symbols = unity_serialized_field_symbols_2
dotnet_naming_style.i_upper_camel_case_style.capitalization = pascal_case
dotnet_naming_style.i_upper_camel_case_style.required_prefix = I
dotnet_naming_style.lower_camel_case_style.capitalization = camel_case
dotnet_naming_symbols.interfaces_symbols.applicable_accessibilities = *
dotnet_naming_symbols.interfaces_symbols.applicable_kinds = interface
dotnet_naming_symbols.interfaces_symbols.resharper_applicable_kinds = interface
dotnet_naming_symbols.interfaces_symbols.resharper_required_modifiers = any
dotnet_naming_symbols.unity_serialized_field_symbols.applicable_accessibilities = *
dotnet_naming_symbols.unity_serialized_field_symbols.applicable_kinds =
dotnet_naming_symbols.unity_serialized_field_symbols.resharper_applicable_kinds = unity_serialised_field
dotnet_naming_symbols.unity_serialized_field_symbols.resharper_required_modifiers = instance
dotnet_naming_symbols.unity_serialized_field_symbols_1.applicable_accessibilities = *
dotnet_naming_symbols.unity_serialized_field_symbols_1.applicable_kinds =
dotnet_naming_symbols.unity_serialized_field_symbols_1.resharper_applicable_kinds = unity_serialised_field
dotnet_naming_symbols.unity_serialized_field_symbols_1.resharper_required_modifiers = instance
dotnet_naming_symbols.unity_serialized_field_symbols_2.applicable_accessibilities = *
dotnet_naming_symbols.unity_serialized_field_symbols_2.applicable_kinds =
dotnet_naming_symbols.unity_serialized_field_symbols_2.resharper_applicable_kinds = unity_serialised_field
dotnet_naming_symbols.unity_serialized_field_symbols_2.resharper_required_modifiers = instance
dotnet_style_parentheses_in_arithmetic_binary_operators = never_if_unnecessary:none
dotnet_style_parentheses_in_other_binary_operators = always_for_clarity:none
dotnet_style_parentheses_in_relational_binary_operators = never_if_unnecessary:none
dotnet_style_predefined_type_for_locals_parameters_members = true:suggestion
dotnet_style_predefined_type_for_member_access = true:suggestion
dotnet_style_qualification_for_event = false:suggestion
dotnet_style_qualification_for_field = false:suggestion
dotnet_style_qualification_for_method = false:suggestion
dotnet_style_qualification_for_property = false:suggestion
dotnet_style_require_accessibility_modifiers = for_non_interface_members:suggestion
# ReSharper properties
resharper_align_linq_query = true
resharper_autodetect_indent_settings = true
resharper_braces_for_for = required
resharper_braces_for_foreach = required
resharper_braces_for_ifelse = required
resharper_braces_for_while = required
resharper_cpp_insert_final_newline = true
resharper_csharp_empty_block_style = together_same_line
resharper_csharp_int_align_comments = true
resharper_csharp_wrap_after_declaration_lpar = true
resharper_csharp_wrap_after_invocation_lpar = true
resharper_csharp_wrap_arguments_style = chop_if_long
resharper_csharp_wrap_before_declaration_rpar = true
resharper_csharp_wrap_before_invocation_rpar = true
resharper_csharp_wrap_parameters_style = chop_if_long
resharper_formatter_off_tag = @formatter:off
resharper_formatter_on_tag = @formatter:on
resharper_formatter_tags_enabled = true
resharper_keep_existing_expr_member_arrangement = false
resharper_keep_existing_initializer_arrangement = false
resharper_keep_existing_linebreaks = false
resharper_place_field_attribute_on_same_line = if_owner_is_single_line
resharper_place_method_attribute_on_same_line = if_owner_is_single_line
resharper_show_autodetect_configure_formatting_tip = false
resharper_use_indent_from_vs = false
resharper_wrap_before_primary_constructor_declaration_rpar = true
resharper_wrap_chained_method_calls = chop_always
# ReSharper inspection severities
resharper_arrange_redundant_parentheses_highlighting = hint
resharper_arrange_this_qualifier_highlighting = hint
resharper_arrange_type_member_modifiers_highlighting = hint
resharper_arrange_type_modifiers_highlighting = hint
resharper_built_in_type_reference_style_for_member_access_highlighting = hint
resharper_built_in_type_reference_style_highlighting = hint
resharper_enforce_do_while_statement_braces_highlighting = warning
resharper_enforce_fixed_statement_braces_highlighting = warning
resharper_enforce_foreach_statement_braces_highlighting = warning
resharper_enforce_for_statement_braces_highlighting = warning
resharper_enforce_if_statement_braces_highlighting = warning
resharper_enforce_lock_statement_braces_highlighting = warning
resharper_enforce_using_statement_braces_highlighting = warning
resharper_enforce_while_statement_braces_highlighting = warning
resharper_mvc_action_not_resolved_highlighting = warning
resharper_mvc_area_not_resolved_highlighting = warning
resharper_mvc_controller_not_resolved_highlighting = warning
resharper_mvc_masterpage_not_resolved_highlighting = warning
resharper_mvc_partial_view_not_resolved_highlighting = warning
resharper_mvc_template_not_resolved_highlighting = warning
resharper_mvc_view_component_not_resolved_highlighting = warning
resharper_mvc_view_component_view_not_resolved_highlighting = warning
resharper_mvc_view_not_resolved_highlighting = warning
resharper_razor_assembly_not_resolved_highlighting = warning
resharper_redundant_base_qualifier_highlighting = warning
resharper_suggest_var_or_type_built_in_types_highlighting = hint
resharper_suggest_var_or_type_elsewhere_highlighting = hint
resharper_suggest_var_or_type_simple_types_highlighting = hint
resharper_web_config_module_not_resolved_highlighting = warning
resharper_web_config_type_not_resolved_highlighting = warning
resharper_web_config_wrong_module_highlighting = warning
[{*.yaml,*.yml}]
indent_style = space
indent_size = 2
[{tsconfig.app.json,tsconfig.base.json,tsconfig.e2e.json,tsconfig.editor.json,tsconfig.json,tsconfig.lib.json,tsconfig.spec.json,tsconfig.test.json}]
indent_style = space
indent_size = 2
[{*.har,*.jsb2,*.jsb3,*.json,*.jsonc,*.postman_collection,*.postman_collection.json,*.postman_environment,*.postman_environment.json,.babelrc,.eslintrc,.prettierrc,.stylelintrc,.ws-context,jest.config}]
indent_style = space
indent_size = 2
[*.{appxmanifest,asax,ascx,aspx,axaml,blockshader,c,c++,c++m,cc,ccm,cginc,compute,cp,cpp,cppm,cs,cshtml,cu,cuh,cxx,cxxm,dtd,fs,fsi,fsscript,fsx,fx,fxh,h,h++,hh,hlsl,hlsli,hlslinc,hp,hpp,hxx,icc,inc,inl,ino,ipp,ixx,master,ml,mli,mpp,mq4,mq5,mqh,mxx,nuspec,paml,pssl,pssli,razor,resw,resx,shader,shaderFoundry,skin,tcc,tpp,urtshader,usf,ush,uxml,vb,xaml,xamlx,xoml,xsd}]
indent_style = space
indent_size = 4
tab_width = 4
@@ -1,34 +1,129 @@
using System.Security.Cryptography; using FinancialApi.Application.Commands;
using FinancialApi.Application.Commands;
using FinancialApi.Application.Handlers; using FinancialApi.Application.Handlers;
using FinancialApi.Application.Models; using FinancialApi.Application.Models;
using FinancialApi.Domain;
using FinancialApi.Domain.Entities; using FinancialApi.Domain.Entities;
using FinancialApi.Domain.Exceptions;
using FluentAssertions; using FluentAssertions;
using FluentAssertions.Execution; using FluentAssertions.Execution;
using Microsoft.Extensions.Time.Testing;
namespace FinancialApi.Application.UnitTests; namespace FinancialApi.Application.UnitTests;
public class ApplyFeeHandlerTests public class ApplyFeeHandlerTests
{ {
[Fact] public class SpendAccount
public void GivenValidAccounts_BasicFee_ShouldValidateEverything() {
[Theory]
[InlineData(100.0, 20.0, 80.0)]
[InlineData(199.78, 10.0, 189.78)]
[InlineData(200000, 0.09, 199999.91)]
[InlineData(1000, 1000, 0)]
public void GivenStartingBalanceGreaterThanFee_ApplyFee_ShouldBeExpectedBalance(
decimal startingBalance,
decimal feeAmount,
decimal expectedBalance
)
{ {
// Arrange // Arrange
var command = new ApplyFeeCommand(1, 100); var timeProvider = new FakeTimeProvider();
var account = new Account(1, 100, "Debit"); var command = new ApplyFeeCommand(1, feeAmount);
var revenueAccount = new Account(99999, 0, "Credit"); var account = new Account(1, startingBalance, AccountType.Spend);
var pair = new FeeContext(account, revenueAccount, TimeProvider.System.GetUtcNow()); var revenueAccount = new Account(99999, 0, AccountType.Revenue);
var feeContext = new FeeContext(account, revenueAccount, timeProvider.GetUtcNow());
// Act // Act
var intents = ApplyFeeHandler.Handle(command, pair); var (customerWrite, revenueWrite, journalWrite, @event) = ApplyFeeHandler.Handle(command, feeContext);
// Assert // Assert
using var _ = new AssertionScope(); using var _ = new AssertionScope();
intents.CustomerWrite.Entity.Balance.Should().Be(account.Balance - command.Amount); customerWrite.Entity.Balance.Should()
intents.RevenueWrite.Entity.Balance.Should().Be(revenueAccount.Balance + command.Amount); .Be(expectedBalance);
intents.JournalWrite.Entity.Lines.Count.Should().BeGreaterThanOrEqualTo(2); }
intents.Event.AccountId.Should().Be(account.Id);
intents.Event.Amount.Should().Be(command.Amount); [Theory]
[InlineData(100.0, 110.0)]
[InlineData(199.78, 200.0)]
[InlineData(200000, 200000.01)]
[InlineData(1000, 1999999)]
public void GivenStartingBalanceLessThanFee_ApplyFee_ShouldFail(decimal startingBalance, decimal feeAmount)
{
// Arrange
var timeProvider = new FakeTimeProvider();
var command = new ApplyFeeCommand(1, feeAmount);
var account = new Account(1, startingBalance, AccountType.Spend);
var revenueAccount = new Account(99999, 0, AccountType.Revenue);
var feeContext = new FeeContext(account, revenueAccount, timeProvider.GetUtcNow());
// Act
var act = () => ApplyFeeHandler.Handle(command, feeContext);
// Assert
using var _ = new AssertionScope();
act.Should()
.Throw<InsufficientFundsException>();
}
}
public class BorrowAccount
{
[Theory]
[InlineData(100.0, 20.0, 80.0)]
[InlineData(199.78, 10.0, 189.78)]
[InlineData(200000, 0.09, 199999.91)]
[InlineData(1000, 1000, 0)]
public void GivenStartingBalanceGreaterThanFee_ApplyFee_ShouldBeExpectedBalance(
decimal startingBalance,
decimal feeAmount,
decimal expectedBalance
)
{
// Arrange
var timeProvider = new FakeTimeProvider();
var command = new ApplyFeeCommand(1, feeAmount);
var account = new Account(1, startingBalance, AccountType.Borrow);
var revenueAccount = new Account(99999, 0, AccountType.Revenue);
var feeContext = new FeeContext(account, revenueAccount, timeProvider.GetUtcNow());
// Act
var (customerWrite, revenueWrite, journalWrite, @event) = ApplyFeeHandler.Handle(command, feeContext);
// Assert
using var _ = new AssertionScope();
customerWrite.Entity.Balance.Should()
.Be(expectedBalance);
}
[Theory]
[InlineData(100.0, 110.0, -10.0)]
[InlineData(199.78, 200.0, -0.22)]
[InlineData(200000, 200000.01, -0.01)]
[InlineData(1000, 1999999, -1998999)]
public void GivenStartingBalanceLessThanFee_ApplyFee_ShouldBeExpectedBalance(
decimal startingBalance,
decimal feeAmount,
decimal expectedBalance
)
{
// Arrange
var timeProvider = new FakeTimeProvider();
var command = new ApplyFeeCommand(1, feeAmount);
var account = new Account(1, startingBalance, AccountType.Borrow);
var revenueAccount = new Account(99999, 0, AccountType.Revenue);
var feeContext = new FeeContext(account, revenueAccount, timeProvider.GetUtcNow());
// Act
var (customerWrite, revenueWrite, journalWrite, @event) = ApplyFeeHandler.Handle(command, feeContext);
// Assert
using var _ = new AssertionScope();
customerWrite.Entity.Balance.Should()
.Be(expectedBalance);
revenueWrite.Entity.Balance.Should()
.Be(feeAmount);
journalWrite.Should()
.NotBeNull();
@event.Should()
.NotBeNull();
}
} }
} }
@@ -0,0 +1,67 @@
using FinancialApi.Application.Commands;
using FinancialApi.Application.Handlers;
using FinancialApi.Application.Models;
using FinancialApi.Domain.Entities;
using FinancialApi.Domain.Events;
using FluentAssertions;
using FluentAssertions.Execution;
using Microsoft.Extensions.Time.Testing;
using Wolverine.Persistence;
namespace FinancialApi.Application.UnitTests;
public class ReverseJournalHandlerTests
{
[Fact]
public void GivenValidJournalEntry_Reversal_ShouldResetAccountBalances()
{
// Arrange
var timeProvider = new FakeTimeProvider();
var expectedSourceAccountBalance = 100.0m;
var expectedDestAccountBalance = 100.0m;
var (initialSourceAccountWrite, initialDestAccountWrite, initialJournalWrite, initialEvent) =
CreateInitialTransferTransaction(
expectedSourceAccountBalance,
expectedDestAccountBalance,
10,
timeProvider
);
var command = new ReverseJournalCommand(initialJournalWrite.Entity.Id, "Invalid Transaction");
var context = new JournalReversalContext(
initialJournalWrite.Entity,
[initialSourceAccountWrite.Entity, initialDestAccountWrite.Entity],
timeProvider.GetUtcNow()
);
// Act
var (journalWrite, accountWrites, @event) = ReverseJournalHandler.Handle(command, context);
// Assert
using var _ = new AssertionScope();
accountWrites[0]
.Entity.Balance.Should()
.Be(expectedSourceAccountBalance);
accountWrites[1]
.Entity.Balance.Should()
.Be(expectedDestAccountBalance);
journalWrite.Entity.Lines.Should()
.HaveCount(initialJournalWrite.Entity.Lines.Count);
}
private (IStorageAction<Account> SourceWrite, IStorageAction<Account> DestWrite, IStorageAction<BalancedJournalEntry>
JournalWrite, FundsTransferredEvent Event) CreateInitialTransferTransaction(
decimal sourceStartingBalance,
decimal destStartingBalance,
decimal transferAmount,
TimeProvider timeProvider
)
{
var command = new TransferFundsCommand(1, 2, transferAmount);
var sourceAccount = new Account(1, sourceStartingBalance, AccountType.Spend);
var destAccount = new Account(2, destStartingBalance, AccountType.Spend);
var transferContext = new TransferContext(sourceAccount, destAccount, timeProvider.GetUtcNow());
// Act
return TransferFundsHandler.Handle(command, transferContext);
}
}
@@ -0,0 +1,154 @@
using FinancialApi.Application.Commands;
using FinancialApi.Application.Handlers;
using FinancialApi.Application.Models;
using FinancialApi.Domain.Entities;
using FinancialApi.Domain.Exceptions;
using FluentAssertions;
using FluentAssertions.Execution;
using Microsoft.Extensions.Time.Testing;
namespace FinancialApi.Application.UnitTests;
public class TransferFundsHandlerTests
{
public class LiabilityAccount
{
[Theory]
[InlineData(100.0, 20.0, 80.0)]
[InlineData(199.78, 10.0, 189.78)]
[InlineData(200000, 0.09, 199999.91)]
[InlineData(1000, 1000, 0)]
public void GivenStartingBalanceGreaterThanTransfer_ApplyFee_ShouldBeExpectedBalance(
decimal startingBalance,
decimal feeAmount,
decimal expectedBalance
)
{
// Arrange
var timeProvider = new FakeTimeProvider();
var command = new TransferFundsCommand(1, 2, feeAmount);
var sourceAccount = new Account(1, startingBalance, AccountType.Spend);
var destAccount = new Account(2, 0, AccountType.Spend);
var transferContext = new TransferContext(sourceAccount, destAccount, timeProvider.GetUtcNow());
// Act
var (customerWrite, revenueWrite, journalWrite, @event) =
TransferFundsHandler.Handle(command, transferContext);
// Assert
using var _ = new AssertionScope();
customerWrite.Entity.Balance.Should()
.Be(expectedBalance);
}
[Theory]
[InlineData(100.0, 110.0)]
[InlineData(199.78, 200.0)]
[InlineData(200000, 200000.01)]
[InlineData(1000, 1999999)]
public void GivenStartingBalanceLessThanTransfer_ApplyFee_ShouldFail(decimal startingBalance, decimal feeAmount)
{
// Arrange
var timeProvider = new FakeTimeProvider();
var command = new TransferFundsCommand(1, 2, feeAmount);
var sourceAccount = new Account(1, startingBalance, AccountType.Spend);
var destAccount = new Account(2, 0, AccountType.Spend);
var transferContext = new TransferContext(sourceAccount, destAccount, timeProvider.GetUtcNow());
// Act
var act = () => TransferFundsHandler.Handle(command, transferContext);
// Assert
using var _ = new AssertionScope();
act.Should()
.Throw<InsufficientFundsException>();
}
}
public class CreditAccount
{
[Theory]
[InlineData(100.0, 20.0, 80.0)]
[InlineData(199.78, 10.0, 189.78)]
[InlineData(200000, 0.09, 199999.91)]
[InlineData(1000, 1000, 0)]
public void GivenStartingBalanceGreaterThanFee_ApplyFee_ShouldBeExpectedBalance(
decimal startingBalance,
decimal feeAmount,
decimal expectedBalance
)
{
// Arrange
var timeProvider = new FakeTimeProvider();
var command = new TransferFundsCommand(1, 2, feeAmount);
var sourceAccount = new Account(1, startingBalance, AccountType.Borrow);
var destAccount = new Account(2, 0, AccountType.Borrow);
var transferContext = new TransferContext(sourceAccount, destAccount, timeProvider.GetUtcNow());
// Act
var (customerWrite, revenueWrite, journalWrite, @event) =
TransferFundsHandler.Handle(command, transferContext);
// Assert
using var _ = new AssertionScope();
customerWrite.Entity.Balance.Should()
.Be(expectedBalance);
}
[Theory]
[InlineData(100.0, 110.0, -10.0)]
[InlineData(199.78, 200.0, -0.22)]
[InlineData(200000, 200000.01, -0.01)]
[InlineData(1000, 1999999, -1998999)]
public void GivenStartingBalanceLessThanFee_ApplyFee_ShouldSucceed(
decimal startingBalance,
decimal feeAmount,
decimal expectedBalance
)
{
// Arrange
var timeProvider = new FakeTimeProvider();
var command = new TransferFundsCommand(1, 2, feeAmount);
var sourceAccount = new Account(1, startingBalance, AccountType.Borrow);
var destAccount = new Account(2, 0, AccountType.Borrow);
var transferContext = new TransferContext(sourceAccount, destAccount, timeProvider.GetUtcNow());
// Act
var act = () => TransferFundsHandler.Handle(command, transferContext);
// Assert
using var _ = new AssertionScope();
act.Should()
.NotThrow();
}
[Theory]
[InlineData(100.0, 110.0, -10.0)]
[InlineData(199.78, 200.0, -0.22)]
[InlineData(200000, 200000.01, -0.01)]
[InlineData(1000, 1999999, -1998999)]
public void GivenStartingBalanceLessThanFee_ApplyFee_ShouldBeExpectedBalance(
decimal startingBalance,
decimal feeAmount,
decimal expectedBalance
)
{
// Arrange
var timeProvider = new FakeTimeProvider();
var command = new TransferFundsCommand(1, 2, feeAmount);
var sourceAccount = new Account(1, startingBalance, AccountType.Borrow);
var destAccount = new Account(2, 0, AccountType.Borrow);
var transferContext = new TransferContext(sourceAccount, destAccount, timeProvider.GetUtcNow());
// Act
var (customerWrite, revenueWrite, journalWrite, @event) =
TransferFundsHandler.Handle(command, transferContext);
// Assert
using var _ = new AssertionScope();
customerWrite.Entity.Balance.Should()
.Be(expectedBalance);
}
}
}
@@ -1,3 +1,3 @@
namespace FinancialApi.Application.Commands; namespace FinancialApi.Application.Commands;
public abstract record TransferFundsCommand(int SourceAccountId, int DestinationAccountId, decimal Amount); public record TransferFundsCommand(int SourceAccountId, int DestinationAccountId, decimal Amount);
@@ -1,63 +1,51 @@
using FinancialApi.Application.Commands; using FinancialApi.Application.Commands;
using FinancialApi.Application.Events;
using FinancialApi.Application.Interfaces; using FinancialApi.Application.Interfaces;
using FinancialApi.Application.Models; using FinancialApi.Application.Models;
using FinancialApi.Domain;
using FinancialApi.Domain.Aggregates; using FinancialApi.Domain.Aggregates;
using FinancialApi.Domain.Entities; using FinancialApi.Domain.Entities;
using FinancialApi.Domain.Events;
using Wolverine.Persistence; using Wolverine.Persistence;
namespace FinancialApi.Application.Handlers; namespace FinancialApi.Application.Handlers;
public static class ApplyFeeHandler public static class ApplyFeeHandler
{ {
public static async Task<FeeContext> LoadAsync( public static async Task<FeeContext> LoadAsync(ApplyFeeCommand cmd, IAccountQuery query, TimeProvider timeProvider)
ApplyFeeCommand cmd,
IAccountQuery query, TimeProvider timeProvider)
{ {
var source = await query.FindByIdAsync(cmd.AccountId); var source = await query.FindByIdAsync(cmd.AccountId);
var dest = await query.FindByIdAsync(99999); var dest = await query.FindByIdAsync(99999);
if (source == null || dest == null) if (source == null || dest == null)
{ {
throw new InvalidOperationException($"Cannot process transfer. Account(s) not found."); throw new InvalidOperationException("Cannot process transfer. Account(s) not found.");
} }
return new FeeContext(source, dest, timeProvider.GetUtcNow()); return new FeeContext(source, dest, timeProvider.GetUtcNow());
} }
public static ( public static ( IStorageAction<Account> CustomerWrite, IStorageAction<Account> RevenueWrite,
IStorageAction<Account> CustomerWrite, IStorageAction<BalancedJournalEntry> JournalWrite, FeeAppliedEvent Event ) Handle(
IStorageAction<Account> RevenueWrite,
IStorageAction<JournalEntry> JournalWrite,
FeeAppliedEvent Event
)
Handle(
ApplyFeeCommand cmd, ApplyFeeCommand cmd,
FeeContext context FeeContext context
) )
{ {
var updatedSource = context.Source.ApplyPosting(cmd.Amount, EntryType.Debit); var updatedSource = context.Source.ApplyPosting(cmd.Amount, EntryType.Debit);
var updatedRevenue = context.Destination.ApplyPosting(cmd.Amount, EntryType.Credit); var updatedRevenue = context.Destination.ApplyPosting(cmd.Amount, EntryType.Credit);
var serviceFee = 0.5m;
var lines = new List<JournalLine> var lines = new List<JournalLine>
{ {
new(updatedSource.Id, cmd.Amount, EntryType.Debit), new(updatedSource.Id, cmd.Amount, EntryType.Debit), new(updatedRevenue.Id, cmd.Amount, EntryType.Credit)
new(updatedRevenue.Id, cmd.Amount - serviceFee, EntryType.Credit),
new(updatedRevenue.Id, serviceFee, EntryType.Credit)
}; };
var journalEntry = BalancedJournal.Create(Guid.NewGuid(), var journalEntry = BalancedJournal.Create(
Guid.NewGuid(),
$"Service Fee Applied: {cmd.Amount} to Account {cmd.AccountId}", $"Service Fee Applied: {cmd.Amount} to Account {cmd.AccountId}",
context.TimeStamp, lines); context.TimeStamp,
lines
);
var @event = new FeeAppliedEvent(cmd.AccountId, cmd.Amount); var @event = new FeeAppliedEvent(cmd.AccountId, cmd.Amount);
return ( return (Storage.Update(updatedSource), Storage.Update(updatedRevenue), Storage.Insert(journalEntry.Entry),
Storage.Update(updatedSource), @event);
Storage.Update(updatedRevenue),
Storage.Insert(journalEntry.Entry),
@event
);
} }
} }
@@ -1,24 +1,18 @@
using FinancialApi.Application.Events; using FinancialApi.Domain.Events;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
namespace FinancialApi.Application.Handlers; namespace FinancialApi.Application.Handlers;
public static class FinancialEventHandler public static class FinancialEventHandler
{ {
public static void Handle( public static void Handle(FeeAppliedEvent @event, IEventTracker store, ILogger logger)
FeeAppliedEvent @event,
IEventTracker store,
ILogger logger)
{ {
var message = $"FeeApplied: ${@event.Amount} moved from Account {@event.AccountId} to Account 99999."; var message = $"FeeApplied: ${@event.Amount} moved from Account {@event.AccountId} to Account 99999.";
logger.LogInformation("BACKGROUND EVENT FIRED: {Message}", message); logger.LogInformation("BACKGROUND EVENT FIRED: {Message}", message);
store.Add(message); store.Add(message);
} }
public static void Handle( public static void Handle(FundsTransferredEvent @event, IEventTracker store, ILogger logger)
FundsTransferredEvent @event,
IEventTracker store,
ILogger logger)
{ {
var message = var message =
$"FundsTransferred: ${@event.Amount} moved from Account {@event.SourceAccountId} to Account {@event.DestinationAccountId}."; $"FundsTransferred: ${@event.Amount} moved from Account {@event.SourceAccountId} to Account {@event.DestinationAccountId}.";
@@ -26,10 +20,7 @@ public static class FinancialEventHandler
store.Add(message); store.Add(message);
} }
public static void Handle( public static void Handle(JournalReversedEvent @event, IEventTracker store, ILogger logger)
JournalReversedEvent @event,
IEventTracker store,
ILogger logger)
{ {
var message = var message =
$"JournalReversed: Original Entry {@event.OriginalJournalId} was reversed by Entry {@event.ReversalJournalId}."; $"JournalReversed: Original Entry {@event.OriginalJournalId} was reversed by Entry {@event.ReversalJournalId}.";
@@ -1,48 +1,59 @@
using FinancialApi.Application.Commands; using FinancialApi.Application.Commands;
using FinancialApi.Application.Events;
using FinancialApi.Application.Interfaces; using FinancialApi.Application.Interfaces;
using FinancialApi.Application.Models; using FinancialApi.Application.Models;
using FinancialApi.Domain;
using FinancialApi.Domain.Aggregates; using FinancialApi.Domain.Aggregates;
using FinancialApi.Domain.Entities; using FinancialApi.Domain.Entities;
using FinancialApi.Domain.Events;
using Wolverine.Persistence; using Wolverine.Persistence;
namespace FinancialApi.Application.Handlers; namespace FinancialApi.Application.Handlers;
public static class ReverseJournalHandler public static class ReverseJournalHandler
{ {
public static async Task<JournalReversalContext?> LoadAsync(ReverseJournalCommand cmd, IReversalQuery query, public static async Task<JournalReversalContext?> LoadAsync(
TimeProvider timeProvider) ReverseJournalCommand cmd,
IReversalQuery query,
TimeProvider timeProvider
)
{ {
var data = await query.GetReversalDataAsync(cmd.OriginalJournalId); var (journalEnty, accounts) = await query.GetReversalDataAsync(cmd.OriginalJournalId);
return data ?? throw new InvalidOperationException($"Journal Entry {cmd.OriginalJournalId} does not exist"); if (journalEnty == null)
{
throw new InvalidOperationException("Journal not found");
} }
public static ( if (accounts == null)
IStorageAction<JournalEntry> JournalWrite,
UnitOfWork<Account> AccountWrites,
JournalReversedEvent Event)
Handle(ReverseJournalCommand cmd, JournalReversalContext context)
{ {
var reversalJournal = throw new InvalidOperationException("Journal accounts not found");
BalancedJournal.CreateReversal(context.OriginalJournalEntry, $"Reversal: {cmd.Reason}", context.TimeStamp); }
return new JournalReversalContext(journalEnty, accounts, timeProvider.GetUtcNow()) ??
throw new InvalidOperationException($"Journal Entry {cmd.OriginalJournalId} does not exist");
}
public static (IStorageAction<BalancedJournalEntry> JournalWrite, UnitOfWork<Account> AccountWrites, JournalReversedEvent
Event) Handle(ReverseJournalCommand cmd, JournalReversalContext context)
{
var reversalJournal = BalancedJournal.CreateReversal(
context.OriginalBalancedJournalEntry,
$"Reversal: {cmd.Reason}",
context.TimeStamp
);
var accountState = context.AffectedAccounts.ToDictionary(a => a.Id); var accountState = context.AffectedAccounts.ToDictionary(a => a.Id);
reversalJournal.Entry.Lines.ForEach(l => reversalJournal.Entry.Lines.ForEach(l =>
{ {
var currentAccount = accountState[l.AccountId]; var currentAccount = accountState[l.AccountId];
accountState[l.AccountId] = currentAccount.ApplyPosting(l.Amount, l.Type); accountState[l.AccountId] = currentAccount.ApplyPosting(l.Amount, l.Type);
}); }
);
var accountUow = new UnitOfWork<Account>(); var accountUow = new UnitOfWork<Account>();
foreach (var account in accountState.Values) foreach (var account in accountState.Values)
{ {
accountUow.Update(account); accountUow.Update(account);
} }
return ( return (Storage.Insert(reversalJournal.Entry), accountUow,
Storage.Insert(reversalJournal.Entry), new JournalReversedEvent(cmd.OriginalJournalId, reversalJournal.Entry.Id));
accountUow,
new JournalReversedEvent(cmd.OriginalJournalId, reversalJournal.Entry.Id)
);
} }
} }
@@ -1,36 +1,37 @@
using FinancialApi.Application.Commands; using FinancialApi.Application.Commands;
using FinancialApi.Application.Events;
using FinancialApi.Application.Interfaces; using FinancialApi.Application.Interfaces;
using FinancialApi.Application.Models; using FinancialApi.Application.Models;
using FinancialApi.Domain;
using FinancialApi.Domain.Aggregates; using FinancialApi.Domain.Aggregates;
using FinancialApi.Domain.Entities; using FinancialApi.Domain.Entities;
using FinancialApi.Domain.Events;
using Wolverine.Persistence; using Wolverine.Persistence;
namespace FinancialApi.Application.Handlers; namespace FinancialApi.Application.Handlers;
public static class TransferFundsHandler public static class TransferFundsHandler
{ {
public static async Task<TransferContext?> LoadAsync(TransferFundsCommand cmd, IAccountQuery query, public static async Task<TransferContext?> LoadAsync(
TimeProvider timeProvider) TransferFundsCommand cmd,
IAccountQuery query,
TimeProvider timeProvider
)
{ {
var source = await query.FindByIdAsync(cmd.SourceAccountId); var source = await query.FindByIdAsync(cmd.SourceAccountId);
var dest = await query.FindByIdAsync(cmd.DestinationAccountId); var dest = await query.FindByIdAsync(cmd.DestinationAccountId);
if (source == null || dest == null) return null; if (source == null || dest == null)
{
return null;
}
return new TransferContext(source, dest, timeProvider.GetUtcNow()); return new TransferContext(source, dest, timeProvider.GetUtcNow());
} }
public static ( public static (IStorageAction<Account> SourceWrite, IStorageAction<Account> DestWrite, IStorageAction<BalancedJournalEntry>
IStorageAction<Account> SourceWrite, JournalWrite, FundsTransferredEvent Event) Handle(TransferFundsCommand cmd, TransferContext context)
IStorageAction<Account> DestWrite,
IStorageAction<JournalEntry> JournalWrite,
FundsTransferredEvent Event
) Handle(TransferFundsCommand cmd, TransferContext context)
{ {
var updatedSource = context.Source.Debit(cmd.Amount); var updatedSource = context.Source.ApplyPosting(cmd.Amount, EntryType.Debit);
var updatedDest = context.Destination.Credit(cmd.Amount); var updatedDest = context.Destination.ApplyPosting(cmd.Amount, EntryType.Credit);
var lines = new List<JournalLine> var lines = new List<JournalLine>
{ {
@@ -38,18 +39,15 @@ public static class TransferFundsHandler
new(context.Destination.Id, cmd.Amount, EntryType.Credit) new(context.Destination.Id, cmd.Amount, EntryType.Credit)
}; };
var journalEntry = var journalEntry = BalancedJournal.Create(
BalancedJournal.Create(Guid.NewGuid(), Guid.NewGuid(),
$"Transfer: {cmd.Amount} from {cmd.SourceAccountId} to {cmd.DestinationAccountId}", $"Transfer: {cmd.Amount} from {cmd.SourceAccountId} to {cmd.DestinationAccountId}",
context.TimeStamp, lines); context.TimeStamp,
lines
);
var @event = new FundsTransferredEvent(cmd.SourceAccountId, cmd.DestinationAccountId, cmd.Amount); var @event = new FundsTransferredEvent(cmd.SourceAccountId, cmd.DestinationAccountId, cmd.Amount);
return ( return (Storage.Update(updatedSource), Storage.Update(updatedDest), Storage.Insert(journalEntry.Entry), @event);
Storage.Update(updatedSource),
Storage.Update(updatedDest),
Storage.Insert(journalEntry.Entry),
@event
);
} }
} }
@@ -1,4 +1,3 @@
using FinancialApi.Domain;
using FinancialApi.Domain.Entities; using FinancialApi.Domain.Entities;
namespace FinancialApi.Application.Interfaces; namespace FinancialApi.Application.Interfaces;
@@ -1,10 +1,8 @@
using FinancialApi.Application.Commands; using FinancialApi.Domain.Entities;
using FinancialApi.Application.Handlers;
using FinancialApi.Application.Models;
namespace FinancialApi.Application.Interfaces; namespace FinancialApi.Application.Interfaces;
public interface IReversalQuery public interface IReversalQuery
{ {
Task<JournalReversalContext?> GetReversalDataAsync(Guid journalEntryId); Task<(BalancedJournalEntry?, List<Account>?)> GetReversalDataAsync(Guid journalEntryId);
} }
@@ -1,4 +1,3 @@
using FinancialApi.Domain;
using FinancialApi.Domain.Entities; using FinancialApi.Domain.Entities;
namespace FinancialApi.Application.Models; namespace FinancialApi.Application.Models;
@@ -1,9 +1,9 @@
using FinancialApi.Domain;
using FinancialApi.Domain.Entities; using FinancialApi.Domain.Entities;
namespace FinancialApi.Application.Models; namespace FinancialApi.Application.Models;
public record JournalReversalContext( public record JournalReversalContext(
JournalEntry OriginalJournalEntry, BalancedJournalEntry OriginalBalancedJournalEntry,
IReadOnlyList<Account> AffectedAccounts, IReadOnlyList<Account> AffectedAccounts,
DateTimeOffset TimeStamp); DateTimeOffset TimeStamp
);
@@ -1,4 +1,3 @@
using FinancialApi.Domain;
using FinancialApi.Domain.Entities; using FinancialApi.Domain.Entities;
namespace FinancialApi.Application.Models; namespace FinancialApi.Application.Models;
@@ -0,0 +1,55 @@
using FinancialApi.Domain.Entities;
using FinancialApi.Domain.Exceptions;
using FluentAssertions;
namespace FinancialApi.Domain.Tests;
public class AccountTests
{
[Theory]
[InlineData(AccountType.Borrow)]
public void CreateBorrowAccountType_ShouldAllowNegativeBalance(AccountType accountType)
{
var act = () => new Account(1, -100, accountType);
act()
.Balance.Should()
.BeNegative();
}
[Theory]
[InlineData(AccountType.Revenue)]
[InlineData(AccountType.Spend)]
public void CreateDebitAccountType_ShouldNotAllowNegativeBalance(AccountType accountType)
{
var act = () => new Account(1, -100, accountType);
act.Should()
.Throw<InvalidStartingBalanceException>();
}
[Theory]
[InlineData(AccountType.Borrow)]
public void GivenCreditAccountType_ShouldAllowNegativeBalance(AccountType accountType)
{
var account = new Account(1, 0, accountType);
var updatedAccount = account.ApplyPosting(100, EntryType.Debit);
updatedAccount.Balance.Should()
.BeNegative();
}
[Theory]
[InlineData(AccountType.Revenue)]
[InlineData(AccountType.Spend)]
public void GivenDebitAccountType_ShouldNotAllowNegativeBalance(AccountType accountType)
{
var account = new Account(1, 0, accountType);
var act = () => account.ApplyPosting(100, EntryType.Debit);
act.Should()
.Throw<InsufficientFundsException>();
}
}
@@ -0,0 +1,54 @@
using FinancialApi.Domain.Aggregates;
using FinancialApi.Domain.Entities;
using FinancialApi.Domain.Exceptions;
using FluentAssertions;
using Microsoft.Extensions.Time.Testing;
namespace FinancialApi.Domain.Tests;
public class BalancedJournalEntryTests
{
[Fact]
public void GivenBalanceJournal_ShouldSucceed()
{
// Arrange
var timeProvider = new FakeTimeProvider();
List<JournalLine> lines = [new(1, 100, EntryType.Debit), new(1, 100, EntryType.Credit)];
// Act
var act = () => BalancedJournal.Create(Guid.NewGuid(), "Transfer", timeProvider.GetUtcNow(), lines);
// Assert
act.Should()
.NotThrow();
}
[Fact]
public void GivenUnbalancedJournal_ShouldFail()
{
// Arrange
var timeProvider = new FakeTimeProvider();
List<JournalLine> lines = [new(1, 10, EntryType.Debit), new(1, 100, EntryType.Credit)];
// Act
var act = () => BalancedJournal.Create(Guid.NewGuid(), "Transfer", timeProvider.GetUtcNow(), lines);
// Assert
act.Should()
.Throw<GaapViolationException>();
}
[Fact]
public void GivenEmptyJournal_ShouldFail()
{
// Arrange
var timeProvider = new FakeTimeProvider();
// Act
var act = () => BalancedJournal.Create(Guid.NewGuid(), "Transfer", timeProvider.GetUtcNow(), []);
// Assert
act.Should()
.Throw<GaapViolationException>();
}
}
@@ -0,0 +1,32 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<IsPackable>false</IsPackable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="coverlet.collector" Version="6.0.4"/>
<PackageReference Include="FluentAssertions" Version="8.10.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.14.1"/>
<PackageReference Include="xunit" Version="2.9.3"/>
<PackageReference Include="xunit.runner.visualstudio" Version="3.1.4"/>
</ItemGroup>
<ItemGroup>
<Using Include="Xunit"/>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\FinancialApi.Domain\FinancialApi.Domain.csproj" />
</ItemGroup>
<ItemGroup>
<Reference Include="Microsoft.Extensions.TimeProvider.Testing">
<HintPath>..\..\..\..\..\..\.nuget\packages\microsoft.extensions.timeprovider.testing\10.6.0\lib\net10.0\Microsoft.Extensions.TimeProvider.Testing.dll</HintPath>
</Reference>
</ItemGroup>
</Project>
@@ -1,32 +1,44 @@
using FinancialApi.Domain.Entities; using FinancialApi.Domain.Entities;
using FinancialApi.Domain.Exceptions;
namespace FinancialApi.Domain.Aggregates; namespace FinancialApi.Domain.Aggregates;
public record BalancedJournal public record BalancedJournal
{ {
public JournalEntry Entry { get; } public BalancedJournalEntry Entry { get; }
private BalancedJournal(JournalEntry entry) => Entry = entry; private BalancedJournal(BalancedJournalEntry entry)
{
Entry = entry;
}
public static BalancedJournal Create(Guid id, string description, DateTimeOffset createdAt, List<JournalLine> lines) public static BalancedJournal Create(Guid id, string description, DateTimeOffset createdAt, List<JournalLine> lines)
{ {
var debits = lines.Where(l => l.Type == EntryType.Debit).Sum(l => l.Amount); if (lines.Count(l => l.Type == EntryType.Debit) == 0)
var credits = lines.Where(l => l.Type == EntryType.Credit).Sum(l => l.Amount);
if (debits != credits)
{ {
throw new InvalidOperationException( throw new GaapViolationException($"GAAP Violation: A journal entry needs at least one debit line.");
$"GAAP Violation: Total Debits ({debits}) must equal Total Credits ({credits})!"
);
} }
return new(new JournalEntry(id, description, createdAt, lines)); if (lines.Count(l => l.Type == EntryType.Credit) == 0)
{
throw new GaapViolationException($"A journal entry needs at least one credit line.");
} }
public static BalancedJournal CreateReversal(JournalEntry original, string reason, DateTimeOffset now) var debits = lines.Where(l => l.Type == EntryType.Debit)
.Sum(l => l.Amount);
var credits = lines.Where(l => l.Type == EntryType.Credit)
.Sum(l => l.Amount);
return debits != credits
? throw new GaapViolationException($"Total Debits ({debits}) must equal Total Credits ({credits})!")
: new BalancedJournal(new BalancedJournalEntry(id, description, createdAt, lines));
}
public static BalancedJournal CreateReversal(BalancedJournalEntry original, string reason, DateTimeOffset now)
{ {
var reversedLines = original.Lines.Select(l => var reversedLines = original.Lines.Select(l =>
l with { Type = l.Type == EntryType.Debit ? EntryType.Credit : EntryType.Debit }) l with { Type = l.Type == EntryType.Debit ? EntryType.Credit : EntryType.Debit }
)
.ToList(); .ToList();
return Create(Guid.NewGuid(), reason, now, reversedLines); return Create(Guid.NewGuid(), reason, now, reversedLines);
@@ -1,54 +1,53 @@
namespace FinancialApi.Domain.Entities; using FinancialApi.Domain.Exceptions;
public record Account(int Id, decimal Balance, string AccountType) namespace FinancialApi.Domain.Entities;
public enum AccountType
{ {
Spend,
Borrow,
Revenue
}
public record Account
{
public Account(int Id, decimal Balance, AccountType Type)
{
this.Id = Id;
this.Balance = Balance;
this.Type = Type;
if (Balance < 0 && Type is AccountType.Spend or AccountType.Revenue)
{
throw new InvalidStartingBalanceException("Insufficient funds.");
}
}
public Account ApplyPosting(decimal amount, EntryType entryType) public Account ApplyPosting(decimal amount, EntryType entryType)
{ {
if (amount <= 0) if (amount <= 0)
{ {
throw new ArgumentException("Credit amount must be positive."); throw new ArgumentException("Amount must be positive.");
} }
var newBalance = Balance; var newBalance = entryType == EntryType.Credit ? Balance + amount : Balance - amount;
if (AccountType == "Revenue")
{
newBalance = entryType == EntryType.Credit ? newBalance + amount : newBalance - amount;
}
else
{
newBalance = entryType == EntryType.Debit ? newBalance - amount : newBalance + amount;
}
if (newBalance < 0 && AccountType == "Liability") if (newBalance < 0 && Type is AccountType.Spend or AccountType.Revenue)
{ {
throw new InvalidOperationException("Insufficient funds."); throw new InsufficientFundsException("Insufficient funds.");
} }
return this with { Balance = newBalance }; return this with { Balance = newBalance };
} }
public Account Debit(decimal amount) public int Id { get; init; }
{ public decimal Balance { get; init; }
if (amount <= 0) public AccountType Type { get; init; }
{
throw new ArgumentException("Debit amount must be positive.");
}
if (Balance - amount < 0) public void Deconstruct(out int Id, out decimal Balance, out AccountType Type)
{ {
throw new InvalidOperationException("Insufficient funds."); Id = this.Id;
} Balance = this.Balance;
Type = this.Type;
return this with { Balance = Balance - amount };
}
public Account Credit(decimal amount)
{
if (amount <= 0)
{
throw new ArgumentException("Credit amount must be positive.");
}
return this with { Balance = Balance + amount };
} }
} }
@@ -1,17 +1,15 @@
namespace FinancialApi.Domain.Entities; namespace FinancialApi.Domain.Entities;
public record JournalEntry public record BalancedJournalEntry
{ {
public Guid Id { get; init; } public Guid Id { get; init; }
public string Description { get; init; } public string Description { get; init; } = null!;
public DateTimeOffset CreatedAt { get; init; } public DateTimeOffset CreatedAt { get; init; }
public List<JournalLine> Lines { get; init; } = []; public List<JournalLine> Lines { get; init; } = [];
internal JournalEntry() internal BalancedJournalEntry() { }
{
}
internal JournalEntry(Guid id, string description, DateTimeOffset createdAt, List<JournalLine> lines) internal BalancedJournalEntry(Guid id, string description, DateTimeOffset createdAt, List<JournalLine> lines)
{ {
Lines = lines; Lines = lines;
Id = id; Id = id;
@@ -1,3 +1,3 @@
namespace FinancialApi.Application.Events; namespace FinancialApi.Domain.Events;
public record FeeAppliedEvent(int AccountId, decimal Amount); public record FeeAppliedEvent(int AccountId, decimal Amount);
@@ -1,3 +1,3 @@
namespace FinancialApi.Application.Events; namespace FinancialApi.Domain.Events;
public record FundsTransferredEvent(int SourceAccountId, int DestinationAccountId, decimal Amount); public record FundsTransferredEvent(int SourceAccountId, int DestinationAccountId, decimal Amount);
@@ -1,4 +1,4 @@
namespace FinancialApi.Application.Events; namespace FinancialApi.Domain.Events;
public interface IEventTracker public interface IEventTracker
{ {
@@ -1,3 +1,3 @@
namespace FinancialApi.Application.Events; namespace FinancialApi.Domain.Events;
public record JournalReversedEvent(Guid OriginalJournalId, Guid ReversalJournalId); public record JournalReversedEvent(Guid OriginalJournalId, Guid ReversalJournalId);
@@ -0,0 +1,3 @@
namespace FinancialApi.Domain.Exceptions;
public class GaapViolationException(string message) : Exception(message);
@@ -0,0 +1,3 @@
namespace FinancialApi.Domain.Exceptions;
public class InsufficientFundsException(string message) : GaapViolationException(message);
@@ -0,0 +1,3 @@
namespace FinancialApi.Domain.Exceptions;
public class InvalidStartingBalanceException(string message) : GaapViolationException(message);
@@ -0,0 +1,221 @@
namespace FinancialApi.Domain;
public interface IFinancialError
{
int ErrorCode { get; }
string Message { get; }
Exception? Exception { get; }
}
public sealed class FinancialError : IFinancialError
{
public FinancialError(int errorCode, string message, Exception? exception = null)
{
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(errorCode);
ErrorCode = errorCode;
Message = message ?? throw new ArgumentNullException(nameof(message));
Exception = exception;
}
public int ErrorCode { get; }
public string Message { get; }
public Exception? Exception { get; }
public override string ToString() => $"Error: {ErrorCode} - {Message}{(Exception == null ? "" : $"\n{Exception}")}";
}
public sealed class FinancialResult<T>
{
private readonly T? _resultValue;
private readonly FinancialError? _resultError;
public FinancialResult(T resultValue)
{
IsError = false;
_resultValue = resultValue;
_resultError = null;
}
public FinancialResult(FinancialError resultError)
{
IsError = true;
_resultValue = default;
_resultError = resultError;
}
public bool IsError { get; }
/// <summary>
/// Error indicator
/// </summary>
public bool IsSuccess => !IsError;
/// <summary>
/// Result Values
/// </summary>
public T? Value => _resultValue;
public FinancialError? Error => _resultError;
public static implicit operator FinancialResult<T>(T resultValue) => new(resultValue);
public static implicit operator FinancialResult<T>(FinancialError resultError) => new(resultError);
public static FinancialResult<T> Success(T successValue)
{
return new FinancialResult<T>(successValue);
}
public static FinancialResult<T> Failure(FinancialError failureValue)
{
return new FinancialResult<T>(failureValue);
}
public TResult Match<TResult>(
Func<T, TResult> success,
Func<FinancialError, TResult> failure,
Func<TResult> nullValue
)
{
return IsError switch
{
false when _resultValue == null => nullValue(),
true => failure(_resultError!),
_ => success(_resultValue)
};
}
public TResult Match<TResult>(Func<T, TResult> success, Func<FinancialError, TResult> failure)
{
return IsError switch
{
true => failure(_resultError!),
_ => success(_resultValue!)
};
}
public TResult? Match<TResult>(Func<T, TResult> success)
{
return IsError switch
{
true => default,
_ => success(_resultValue!)
};
}
public void Match(Action<T> success, Action<FinancialError> failure, Action nullValue)
{
switch (IsError)
{
case false when _resultValue == null:
nullValue.Invoke();
return;
case true:
failure.Invoke(_resultError!);
return;
default:
success(_resultValue);
break;
}
}
public void Match(Action<T> success, Action<FinancialError> failure)
{
switch (IsError)
{
case true:
failure.Invoke(_resultError!);
return;
default:
success(_resultValue!);
break;
}
}
public void Match(Action<T> success)
{
if (IsError)
{
return;
}
success(_resultValue!);
}
public async Task<TResult> MatchAsync<TResult>(
Func<T, Task<TResult>> success,
Func<FinancialError, Task<TResult>> failure,
Func<Task<TResult>> nullValue
)
{
return IsError switch
{
false when _resultValue == null => await nullValue(),
true => await failure(_resultError!),
_ => await success(_resultValue)
};
}
public async Task<TResult> MatchAsync<TResult>(
Func<T, Task<TResult>> success,
Func<FinancialError, Task<TResult>> failure
)
{
return IsError switch
{
true => await failure(_resultError!),
_ => await success(_resultValue!)
};
}
public async Task<TResult?> MatchAsync<TResult>(Func<T, Task<TResult>> success)
{
return IsError switch
{
true => default,
_ => await success(_resultValue!)
};
}
public async Task MatchAsync(Func<T, Task> success, Func<FinancialError, Task> failure, Func<Task> nullValue)
{
switch (IsError)
{
case false when _resultValue == null:
await nullValue.Invoke();
return;
case true:
await failure.Invoke(_resultError!);
return;
default:
await success(_resultValue!);
break;
}
}
public async Task MatchAsync(Func<T, Task> success, Func<FinancialError, Task> failure)
{
switch (IsError)
{
case true:
await failure.Invoke(_resultError!);
return;
default:
await success(_resultValue!);
break;
}
}
public async Task MatchAsync(Func<T, Task> success)
{
if (IsError)
{
return;
}
await success(_resultValue!);
}
}
@@ -0,0 +1,35 @@
using FinancialApi.Application.Commands;
using FinancialApi.Application.Interfaces;
using FinancialApi.Domain.Entities;
using FinancialApi.Domain.Events;
using FluentAssertions;
using Wolverine;
using Wolverine.Tracking;
namespace FinancialApi.Infrastructure.Tests;
internal class FakeAccountQuery : IAccountQuery
{
public Task<Account?> FindByIdAsync(int id) => Task.FromResult(new Account(id, 100.00m, AccountType.Spend))!;
}
public class ApplyFeeIntegrationTests(WolverineTestFixture fixture) : IClassFixture<WolverineTestFixture>
{
[Fact]
public async Task GivenValidCommand_WhenApplyingFee_ShouldPublishFeeAppliedEvent()
{
// Arrange
var command = new ApplyFeeCommand(1, 100);
// Act
var session = await fixture.Host.InvokeMessageAndWaitAsync(command);
// Assert
session.Sent.AllMessages()
.ShouldHaveMessageOfType<FeeAppliedEvent>();
session.Sent.MessagesOf<FeeAppliedEvent>()
.Count()
.Should()
.Be(1);
}
}
@@ -0,0 +1,41 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<IsPackable>false</IsPackable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="coverlet.collector" Version="6.0.4"/>
<PackageReference Include="FluentAssertions" Version="8.10.0" />
<PackageReference Include="Microsoft.Extensions.Hosting.Abstractions" Version="10.0.10" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.14.1"/>
<PackageReference Include="NSubstitute" Version="6.0.0" />
<PackageReference Include="WolverineFx" Version="6.24.1" />
<PackageReference Include="WolverineFx.RuntimeCompilation" Version="6.24.1" />
<PackageReference Include="xunit" Version="2.9.3"/>
<PackageReference Include="xunit.runner.visualstudio" Version="3.1.4"/>
</ItemGroup>
<ItemGroup>
<Using Include="Xunit"/>
</ItemGroup>
<ItemGroup>
<Reference Include="Microsoft.Extensions.Hosting">
<HintPath>..\..\..\..\..\..\.nuget\packages\microsoft.extensions.hosting\10.0.0\lib\net10.0\Microsoft.Extensions.Hosting.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Extensions.Hosting.Abstractions" />
<Reference Include="Microsoft.Extensions.TimeProvider.Testing">
<HintPath>..\..\..\..\..\..\.nuget\packages\microsoft.extensions.timeprovider.testing\10.6.0\lib\net10.0\Microsoft.Extensions.TimeProvider.Testing.dll</HintPath>
</Reference>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\FinancialApi.Application\FinancialApi.Application.csproj" />
<ProjectReference Include="..\FinancialApi.Infrastructure\FinancialApi.Infrastructure.csproj" />
</ItemGroup>
</Project>
@@ -0,0 +1,34 @@
using FinancialApi.Application.Handlers;
using FinancialApi.Application.Interfaces;
using FinancialApi.Domain.Events;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Time.Testing;
using Wolverine;
namespace FinancialApi.Infrastructure.Tests;
public class WolverineTestFixture : IDisposable
{
public IHost Host { get; }
public WolverineTestFixture()
{
// We build and start the host ONCE here
Host = Microsoft.Extensions.Hosting.Host.CreateDefaultBuilder()
.ConfigureServices((context, services) =>
{
services.AddSingleton<IAccountQuery>(_ => new FakeAccountQuery());
services.AddSingleton<TimeProvider>(_ => new FakeTimeProvider());
services.AddSingleton<IEventTracker>(_ => new DemoEventStore());
}
)
.UseWolverine(opts => { opts.Discovery.IncludeAssembly(typeof(ApplyFeeHandler).Assembly); })
.Start();
}
public void Dispose()
{
Host.Dispose();
}
}
@@ -1,5 +1,4 @@
using FinancialApi.Domain; using FinancialApi.Domain.Entities;
using FinancialApi.Domain.Entities;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
namespace FinancialApi.Infrastructure; namespace FinancialApi.Infrastructure;
@@ -7,29 +6,37 @@ namespace FinancialApi.Infrastructure;
public class AccountDbContext(DbContextOptions<AccountDbContext> options) : DbContext(options) public class AccountDbContext(DbContextOptions<AccountDbContext> options) : DbContext(options)
{ {
public DbSet<Account> Accounts => Set<Account>(); public DbSet<Account> Accounts => Set<Account>();
public DbSet<JournalEntry> JournalEntries => Set<JournalEntry>(); public DbSet<BalancedJournalEntry> JournalEntries => Set<BalancedJournalEntry>();
protected override void OnModelCreating(ModelBuilder modelBuilder) protected override void OnModelCreating(ModelBuilder modelBuilder)
{ {
modelBuilder.Entity<Account>() modelBuilder.Entity<Account>()
.HasKey(x => x.Id); .HasKey(x => x.Id);
modelBuilder.Entity<Account>().HasData( modelBuilder.Entity<Account>()
new Account(1, 10000000.00m, "Credit"), .HasData(
new Account(2, 50000000.00m, "Liability"), new Account(1, 10000000.00m, AccountType.Borrow),
new Account(99999, 0.00m, "Revenue") new Account(2, 50000000.00m, AccountType.Spend),
new Account(99999, 0.00m, AccountType.Revenue)
); );
modelBuilder.Entity<JournalEntry>(builder => modelBuilder.Entity<BalancedJournalEntry>(builder =>
{ {
builder.HasKey(x => x.Id); builder.HasKey(x => x.Id);
builder.OwnsMany(x => x.Lines, line => builder.OwnsMany(
x => x.Lines,
line =>
{ {
line.WithOwner().HasForeignKey("JournalEntryId"); line.WithOwner()
line.Property<int>("Id").ValueGeneratedOnAdd(); .HasForeignKey("JournalEntryId");
line.Property<int>("Id")
.ValueGeneratedOnAdd();
line.HasKey("Id"); line.HasKey("Id");
line.Property(x => x.Type).HasConversion<string>(); line.Property(x => x.Type)
}); .HasConversion<string>();
}); }
);
}
);
} }
} }
@@ -1,5 +1,4 @@
using FinancialApi.Application.Interfaces; using FinancialApi.Application.Interfaces;
using FinancialApi.Domain;
using FinancialApi.Domain.Entities; using FinancialApi.Domain.Entities;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
@@ -7,9 +6,9 @@ namespace FinancialApi.Infrastructure;
public class AccountQuery(AccountDbContext db) : IAccountQuery public class AccountQuery(AccountDbContext db) : IAccountQuery
{ {
public Task<Account?> FindByIdAsync(int id) public async Task<Account?> FindByIdAsync(int id)
{ {
return db.Accounts.AsNoTracking() return await db.Accounts.AsNoTracking()
.FirstOrDefaultAsync(x => x.Id == id); .FirstOrDefaultAsync(x => x.Id == id);
} }
} }
@@ -1,6 +1,6 @@
using FinancialApi.Application.Events; using FinancialApi.Domain.Events;
namespace FinancialApi; namespace FinancialApi.Infrastructure;
public class DemoEventStore : IEventTracker public class DemoEventStore : IEventTracker
{ {
@@ -0,0 +1,114 @@
// <auto-generated />
using System;
using FinancialApi.Infrastructure;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
#nullable disable
namespace FinancialApi.Infrastructure.Migrations
{
[DbContext(typeof(AccountDbContext))]
[Migration("20260729103021_AccountTypes")]
partial class AccountTypes
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder.HasAnnotation("ProductVersion", "10.0.9");
modelBuilder.Entity("FinancialApi.Domain.Entities.Account", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<decimal>("Balance")
.HasColumnType("TEXT");
b.Property<int>("Type")
.HasColumnType("INTEGER");
b.HasKey("Id");
b.ToTable("Accounts");
b.HasData(
new
{
Id = 1,
Balance = 10000000.00m,
Type = 2
},
new
{
Id = 2,
Balance = 50000000.00m,
Type = 0
},
new
{
Id = 99999,
Balance = 0.00m,
Type = 3
});
});
modelBuilder.Entity("FinancialApi.Domain.Entities.JournalEntry", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("TEXT");
b.Property<string>("Description")
.IsRequired()
.HasColumnType("TEXT");
b.HasKey("Id");
b.ToTable("JournalEntries");
});
modelBuilder.Entity("FinancialApi.Domain.Entities.JournalEntry", b =>
{
b.OwnsMany("FinancialApi.Domain.Entities.JournalLine", "Lines", b1 =>
{
b1.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b1.Property<int>("AccountId")
.HasColumnType("INTEGER");
b1.Property<decimal>("Amount")
.HasColumnType("TEXT");
b1.Property<Guid>("JournalEntryId")
.HasColumnType("TEXT");
b1.Property<string>("Type")
.IsRequired()
.HasColumnType("TEXT");
b1.HasKey("Id");
b1.HasIndex("JournalEntryId");
b1.ToTable("JournalLine");
b1.WithOwner()
.HasForeignKey("JournalEntryId");
});
b.Navigation("Lines");
});
#pragma warning restore 612, 618
}
}
}
@@ -0,0 +1,82 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace FinancialApi.Infrastructure.Migrations
{
/// <inheritdoc />
public partial class AccountTypes : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "AccountType",
table: "Accounts");
migrationBuilder.AddColumn<int>(
name: "Type",
table: "Accounts",
type: "INTEGER",
nullable: false,
defaultValue: 0);
migrationBuilder.UpdateData(
table: "Accounts",
keyColumn: "Id",
keyValue: 1,
column: "Type",
value: 2);
migrationBuilder.UpdateData(
table: "Accounts",
keyColumn: "Id",
keyValue: 2,
column: "Type",
value: 0);
migrationBuilder.UpdateData(
table: "Accounts",
keyColumn: "Id",
keyValue: 99999,
column: "Type",
value: 3);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "Type",
table: "Accounts");
migrationBuilder.AddColumn<string>(
name: "AccountType",
table: "Accounts",
type: "TEXT",
nullable: false,
defaultValue: "");
migrationBuilder.UpdateData(
table: "Accounts",
keyColumn: "Id",
keyValue: 1,
column: "AccountType",
value: "Credit");
migrationBuilder.UpdateData(
table: "Accounts",
keyColumn: "Id",
keyValue: 2,
column: "AccountType",
value: "Liability");
migrationBuilder.UpdateData(
table: "Accounts",
keyColumn: "Id",
keyValue: 99999,
column: "AccountType",
value: "Revenue");
}
}
}
@@ -0,0 +1,114 @@
// <auto-generated />
using System;
using FinancialApi.Infrastructure;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
#nullable disable
namespace FinancialApi.Infrastructure.Migrations
{
[DbContext(typeof(AccountDbContext))]
[Migration("20260731073046_UpdateAccountTypes")]
partial class UpdateAccountTypes
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder.HasAnnotation("ProductVersion", "10.0.9");
modelBuilder.Entity("FinancialApi.Domain.Entities.Account", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<decimal>("Balance")
.HasColumnType("TEXT");
b.Property<int>("Type")
.HasColumnType("INTEGER");
b.HasKey("Id");
b.ToTable("Accounts");
b.HasData(
new
{
Id = 1,
Balance = 10000000.00m,
Type = 1
},
new
{
Id = 2,
Balance = 50000000.00m,
Type = 0
},
new
{
Id = 99999,
Balance = 0.00m,
Type = 2
});
});
modelBuilder.Entity("FinancialApi.Domain.Entities.BalancedJournalEntry", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("TEXT");
b.Property<string>("Description")
.IsRequired()
.HasColumnType("TEXT");
b.HasKey("Id");
b.ToTable("JournalEntries");
});
modelBuilder.Entity("FinancialApi.Domain.Entities.BalancedJournalEntry", b =>
{
b.OwnsMany("FinancialApi.Domain.Entities.JournalLine", "Lines", b1 =>
{
b1.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b1.Property<int>("AccountId")
.HasColumnType("INTEGER");
b1.Property<decimal>("Amount")
.HasColumnType("TEXT");
b1.Property<Guid>("JournalEntryId")
.HasColumnType("TEXT");
b1.Property<string>("Type")
.IsRequired()
.HasColumnType("TEXT");
b1.HasKey("Id");
b1.HasIndex("JournalEntryId");
b1.ToTable("JournalLine");
b1.WithOwner()
.HasForeignKey("JournalEntryId");
});
b.Navigation("Lines");
});
#pragma warning restore 612, 618
}
}
}
@@ -0,0 +1,46 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace FinancialApi.Infrastructure.Migrations
{
/// <inheritdoc />
public partial class UpdateAccountTypes : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.UpdateData(
table: "Accounts",
keyColumn: "Id",
keyValue: 1,
column: "Type",
value: 1);
migrationBuilder.UpdateData(
table: "Accounts",
keyColumn: "Id",
keyValue: 99999,
column: "Type",
value: 2);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.UpdateData(
table: "Accounts",
keyColumn: "Id",
keyValue: 1,
column: "Type",
value: 2);
migrationBuilder.UpdateData(
table: "Accounts",
keyColumn: "Id",
keyValue: 99999,
column: "Type",
value: 3);
}
}
}
@@ -17,19 +17,18 @@ namespace FinancialApi.Infrastructure.Migrations
#pragma warning disable 612, 618 #pragma warning disable 612, 618
modelBuilder.HasAnnotation("ProductVersion", "10.0.9"); modelBuilder.HasAnnotation("ProductVersion", "10.0.9");
modelBuilder.Entity("FinancialApi.Application.Account", b => modelBuilder.Entity("FinancialApi.Domain.Entities.Account", b =>
{ {
b.Property<int>("Id") b.Property<int>("Id")
.ValueGeneratedOnAdd() .ValueGeneratedOnAdd()
.HasColumnType("INTEGER"); .HasColumnType("INTEGER");
b.Property<string>("AccountType")
.IsRequired()
.HasColumnType("TEXT");
b.Property<decimal>("Balance") b.Property<decimal>("Balance")
.HasColumnType("TEXT"); .HasColumnType("TEXT");
b.Property<int>("Type")
.HasColumnType("INTEGER");
b.HasKey("Id"); b.HasKey("Id");
b.ToTable("Accounts"); b.ToTable("Accounts");
@@ -38,24 +37,24 @@ namespace FinancialApi.Infrastructure.Migrations
new new
{ {
Id = 1, Id = 1,
AccountType = "Credit", Balance = 10000000.00m,
Balance = 10000000.00m Type = 1
}, },
new new
{ {
Id = 2, Id = 2,
AccountType = "Liability", Balance = 50000000.00m,
Balance = 50000000.00m Type = 0
}, },
new new
{ {
Id = 99999, Id = 99999,
AccountType = "Revenue", Balance = 0.00m,
Balance = 0.00m Type = 2
}); });
}); });
modelBuilder.Entity("FinancialApi.Application.JournalEntry", b => modelBuilder.Entity("FinancialApi.Domain.Entities.BalancedJournalEntry", b =>
{ {
b.Property<Guid>("Id") b.Property<Guid>("Id")
.ValueGeneratedOnAdd() .ValueGeneratedOnAdd()
@@ -73,9 +72,9 @@ namespace FinancialApi.Infrastructure.Migrations
b.ToTable("JournalEntries"); b.ToTable("JournalEntries");
}); });
modelBuilder.Entity("FinancialApi.Application.JournalEntry", b => modelBuilder.Entity("FinancialApi.Domain.Entities.BalancedJournalEntry", b =>
{ {
b.OwnsMany("FinancialApi.Application.JournalLine", "Lines", b1 => b.OwnsMany("FinancialApi.Domain.Entities.JournalLine", "Lines", b1 =>
{ {
b1.Property<int>("Id") b1.Property<int>("Id")
.ValueGeneratedOnAdd() .ValueGeneratedOnAdd()
@@ -1,32 +1,30 @@
using FinancialApi.Application.Commands;
using FinancialApi.Application.Handlers;
using FinancialApi.Application.Interfaces; using FinancialApi.Application.Interfaces;
using FinancialApi.Application.Models; using FinancialApi.Domain.Entities;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
namespace FinancialApi.Infrastructure; namespace FinancialApi.Infrastructure;
public class ReversalQuery(AccountDbContext db, TimeProvider timeProvider) : IReversalQuery public class ReversalQuery(AccountDbContext db) : IReversalQuery
{ {
public async Task<JournalReversalContext?> GetReversalDataAsync(Guid journalEntryId) public async Task<(BalancedJournalEntry?, List<Account>?)> GetReversalDataAsync(Guid journalEntryId)
{ {
var entry = await db.JournalEntries var entry = await db.JournalEntries.Include(x => x.Lines)
.Include(x => x.Lines)
.AsNoTracking() .AsNoTracking()
.FirstOrDefaultAsync(x => x.Id == journalEntryId); .FirstOrDefaultAsync(x => x.Id == journalEntryId);
if (entry == null) if (entry == null)
{ {
return null; return (null, null);
} }
var accountIds = entry.Lines.Select(l => l.AccountId).Distinct().ToList(); var accountIds = entry.Lines.Select(l => l.AccountId)
.Distinct()
.ToList();
var accounts = await db.Accounts var accounts = await db.Accounts.AsNoTracking()
.AsNoTracking()
.Where(a => accountIds.Contains(a.Id)) .Where(a => accountIds.Contains(a.Id))
.ToListAsync(); .ToListAsync();
return new JournalReversalContext(entry, accounts, timeProvider.GetUtcNow()); return (entry, accounts);
} }
} }
@@ -33,7 +33,8 @@ public static class Extensions
// Turn on service discovery by default // Turn on service discovery by default
http.AddServiceDiscovery(); http.AddServiceDiscovery();
}); }
);
// Uncomment the following to restrict the allowed schemes for service discovery. // Uncomment the following to restrict the allowed schemes for service discovery.
// builder.Services.Configure<ServiceDiscoveryOptions>(options => // builder.Services.Configure<ServiceDiscoveryOptions>(options =>
@@ -51,7 +52,8 @@ public static class Extensions
{ {
logging.IncludeFormattedMessage = true; logging.IncludeFormattedMessage = true;
logging.IncludeScopes = true; logging.IncludeScopes = true;
}); }
);
builder.Services.AddOpenTelemetry() builder.Services.AddOpenTelemetry()
.WithMetrics(metrics => .WithMetrics(metrics =>
@@ -59,20 +61,22 @@ public static class Extensions
metrics.AddAspNetCoreInstrumentation() metrics.AddAspNetCoreInstrumentation()
.AddHttpClientInstrumentation() .AddHttpClientInstrumentation()
.AddRuntimeInstrumentation(); .AddRuntimeInstrumentation();
}) }
)
.WithTracing(tracing => .WithTracing(tracing =>
{ {
tracing.AddSource(builder.Environment.ApplicationName) tracing.AddSource(builder.Environment.ApplicationName)
.AddAspNetCoreInstrumentation(tracing => .AddAspNetCoreInstrumentation(tracing =>
// Exclude health check requests from tracing // Exclude health check requests from tracing
tracing.Filter = context => tracing.Filter = context =>
!context.Request.Path.StartsWithSegments(HealthEndpointPath) !context.Request.Path.StartsWithSegments(HealthEndpointPath) &&
&& !context.Request.Path.StartsWithSegments(AlivenessEndpointPath) !context.Request.Path.StartsWithSegments(AlivenessEndpointPath)
) )
// Uncomment the following line to enable gRPC instrumentation (requires the OpenTelemetry.Instrumentation.GrpcNetClient package) // Uncomment the following line to enable gRPC instrumentation (requires the OpenTelemetry.Instrumentation.GrpcNetClient package)
//.AddGrpcClientInstrumentation() //.AddGrpcClientInstrumentation()
.AddHttpClientInstrumentation(); .AddHttpClientInstrumentation();
}); }
);
builder.AddOpenTelemetryExporters(); builder.AddOpenTelemetryExporters();
@@ -86,7 +90,8 @@ public static class Extensions
if (useOtlpExporter) if (useOtlpExporter)
{ {
builder.Services.AddOpenTelemetry().UseOtlpExporter(); builder.Services.AddOpenTelemetry()
.UseOtlpExporter();
} }
// Uncomment the following lines to enable the Azure Monitor exporter (requires the Azure.Monitor.OpenTelemetry.AspNetCore package) // Uncomment the following lines to enable the Azure Monitor exporter (requires the Azure.Monitor.OpenTelemetry.AspNetCore package)
@@ -119,10 +124,10 @@ public static class Extensions
app.MapHealthChecks(HealthEndpointPath); app.MapHealthChecks(HealthEndpointPath);
// Only health checks tagged with the "live" tag must pass for app to be considered alive // Only health checks tagged with the "live" tag must pass for app to be considered alive
app.MapHealthChecks(AlivenessEndpointPath, new HealthCheckOptions app.MapHealthChecks(
{ AlivenessEndpointPath,
Predicate = r => r.Tags.Contains("live") new HealthCheckOptions { Predicate = r => r.Tags.Contains("live") }
}); );
} }
return app; return app;
@@ -1,3 +1,4 @@
using FinancialApi.Domain.Exceptions;
using Microsoft.AspNetCore.Diagnostics; using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
@@ -8,9 +9,10 @@ public class DomainExceptionHandler : IExceptionHandler
public async ValueTask<bool> TryHandleAsync( public async ValueTask<bool> TryHandleAsync(
HttpContext httpContext, HttpContext httpContext,
Exception exception, Exception exception,
CancellationToken cancellationToken) CancellationToken cancellationToken
)
{ {
if (exception is not (InvalidOperationException or ArgumentException)) if (exception is not (InvalidOperationException or ArgumentException or GaapViolationException))
{ {
return false; return false;
} }
@@ -27,6 +29,5 @@ public class DomainExceptionHandler : IExceptionHandler
await httpContext.Response.WriteAsJsonAsync(problemDetails, cancellationToken); await httpContext.Response.WriteAsJsonAsync(problemDetails, cancellationToken);
return true; return true;
} }
} }
@@ -7,8 +7,8 @@ Accept: application/json
Content-Type: application/json Content-Type: application/json
{ {
"accountId": 1, "accountId": 2,
"amount": 50.0 "amount": 100
} }
### Transfer Between Accounts ### Transfer Between Accounts
@@ -28,7 +28,7 @@ POST {{FinancialApi_HostAddress}}/journal/reverse
Content-Type: application/json Content-Type: application/json
{ {
"originalJournalId": "FD2BFD8E-7C85-4CAD-A12B-CCBCD7C12B4A", "originalJournalId": "E7FB25DB-406F-4063-A4B0-DE6BB8292437",
"reason": "Incorrect Account Fee" "reason": "Incorrect Account Fee"
} }
@@ -1,8 +1,8 @@
using FinancialApi; using FinancialApi;
using FinancialApi.Application.Commands; using FinancialApi.Application.Commands;
using FinancialApi.Application.Events;
using FinancialApi.Application.Handlers; using FinancialApi.Application.Handlers;
using FinancialApi.Application.Interfaces; using FinancialApi.Application.Interfaces;
using FinancialApi.Domain.Events;
using FinancialApi.Infrastructure; using FinancialApi.Infrastructure;
using FinancialApi.ServiceDefaults; using FinancialApi.ServiceDefaults;
using JasperFx.Resources; using JasperFx.Resources;
@@ -19,8 +19,7 @@ builder.Services.AddProblemDetails();
var connectionString = "Data Source=demo.db"; var connectionString = "Data Source=demo.db";
builder.Services.AddDbContext<AccountDbContext>(options => builder.Services.AddDbContext<AccountDbContext>(options => options.UseSqlite(connectionString));
options.UseSqlite(connectionString));
builder.Services.AddScoped<IAccountQuery, AccountQuery>(); builder.Services.AddScoped<IAccountQuery, AccountQuery>();
builder.Services.AddScoped<IReversalQuery, ReversalQuery>(); builder.Services.AddScoped<IReversalQuery, ReversalQuery>();
@@ -39,7 +38,8 @@ builder.Host.UseWolverine(opts =>
opts.PersistMessagesWithSqlite(connectionString); opts.PersistMessagesWithSqlite(connectionString);
opts.UseEntityFrameworkCoreTransactions(); opts.UseEntityFrameworkCoreTransactions();
opts.Policies.AutoApplyTransactions(); opts.Policies.AutoApplyTransactions();
}); }
);
builder.Host.UseResourceSetupOnStartup(); builder.Host.UseResourceSetupOnStartup();
var app = builder.Build(); var app = builder.Build();
@@ -60,25 +60,36 @@ if (app.Environment.IsDevelopment())
app.UseHttpsRedirection(); app.UseHttpsRedirection();
app.MapPost("/accounts/apply-fee", async (ApplyFeeCommand cmd, IMessageBus bus) => app.MapPost(
"/accounts/apply-fee",
async (ApplyFeeCommand cmd, IMessageBus bus) =>
{ {
await bus.InvokeAsync(cmd); await bus.InvokeAsync(cmd);
return Results.Accepted(); return Results.Accepted();
}); }
);
app.MapPost("/accounts/transfer", async (TransferFundsCommand cmd, IMessageBus bus) => app.MapPost(
"/accounts/transfer",
async (TransferFundsCommand cmd, IMessageBus bus) =>
{ {
await bus.InvokeAsync(cmd); await bus.InvokeAsync(cmd);
return Results.Accepted(); return Results.Accepted();
}); }
);
app.MapPost("/journal/reverse", async (ReverseJournalCommand cmd, IMessageBus bus) => app.MapPost(
"/journal/reverse",
async (ReverseJournalCommand cmd, IMessageBus bus) =>
{ {
await bus.InvokeAsync(cmd); await bus.InvokeAsync(cmd);
return Results.Accepted(); return Results.Accepted();
}); }
);
app.MapGet("/events", (IEventTracker tracker) => app.MapGet(
"/events",
(IEventTracker tracker) =>
{ {
if (tracker is DemoEventStore store) if (tracker is DemoEventStore store)
{ {
@@ -86,6 +97,7 @@ app.MapGet("/events", (IEventTracker tracker) =>
} }
return Results.NotFound(); return Results.NotFound();
}); }
);
app.Run(); app.Run();
@@ -12,6 +12,10 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FinancialApi.Domain", "Fina
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FinancialApi.Application.UnitTests", "FinancialApi.Application.UnitTests\FinancialApi.Application.UnitTests.csproj", "{93DBA3AA-3C03-431C-A41C-DDADFAC964D5}" Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FinancialApi.Application.UnitTests", "FinancialApi.Application.UnitTests\FinancialApi.Application.UnitTests.csproj", "{93DBA3AA-3C03-431C-A41C-DDADFAC964D5}"
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FinancialApi.Domain.Tests", "FinancialApi.Domain.Tests\FinancialApi.Domain.Tests.csproj", "{C15E3FE0-6E3D-4FFC-892E-D469536ADC13}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FinancialApi.Infrastructure.Tests", "FinancialApi.Infrastructure.Tests\FinancialApi.Infrastructure.Tests.csproj", "{8C1BA932-16F2-42B3-A07C-C589C31044B3}"
EndProject
Global Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU Debug|Any CPU = Debug|Any CPU
@@ -42,5 +46,13 @@ Global
{93DBA3AA-3C03-431C-A41C-DDADFAC964D5}.Debug|Any CPU.Build.0 = Debug|Any CPU {93DBA3AA-3C03-431C-A41C-DDADFAC964D5}.Debug|Any CPU.Build.0 = Debug|Any CPU
{93DBA3AA-3C03-431C-A41C-DDADFAC964D5}.Release|Any CPU.ActiveCfg = Release|Any CPU {93DBA3AA-3C03-431C-A41C-DDADFAC964D5}.Release|Any CPU.ActiveCfg = Release|Any CPU
{93DBA3AA-3C03-431C-A41C-DDADFAC964D5}.Release|Any CPU.Build.0 = Release|Any CPU {93DBA3AA-3C03-431C-A41C-DDADFAC964D5}.Release|Any CPU.Build.0 = Release|Any CPU
{C15E3FE0-6E3D-4FFC-892E-D469536ADC13}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{C15E3FE0-6E3D-4FFC-892E-D469536ADC13}.Debug|Any CPU.Build.0 = Debug|Any CPU
{C15E3FE0-6E3D-4FFC-892E-D469536ADC13}.Release|Any CPU.ActiveCfg = Release|Any CPU
{C15E3FE0-6E3D-4FFC-892E-D469536ADC13}.Release|Any CPU.Build.0 = Release|Any CPU
{8C1BA932-16F2-42B3-A07C-C589C31044B3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{8C1BA932-16F2-42B3-A07C-C589C31044B3}.Debug|Any CPU.Build.0 = Debug|Any CPU
{8C1BA932-16F2-42B3-A07C-C589C31044B3}.Release|Any CPU.ActiveCfg = Release|Any CPU
{8C1BA932-16F2-42B3-A07C-C589C31044B3}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection EndGlobalSection
EndGlobal EndGlobal
@@ -1,7 +1,15 @@
<wpf:ResourceDictionary xml:space="preserve" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:s="clr-namespace:System;assembly=mscorlib" xmlns:ss="urn:shemas-jetbrains-com:settings-storage-xaml" xmlns:wpf="http://schemas.microsoft.com/winfx/2006/xaml/presentation"> <wpf:ResourceDictionary xml:space="preserve" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:s="clr-namespace:System;assembly=mscorlib" xmlns:ss="urn:shemas-jetbrains-com:settings-storage-xaml" xmlns:wpf="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<s:String x:Key="/Default/CodeInspection/ExcludedFiles/FilesAndFoldersToSkip2/=7020124F_002D9FFC_002D4AC3_002D8F3D_002DAAB8E0240759_002Ff_003AConfiguredTaskAwaitable_002Ecs_002Fl_003A_002E_002E_003F_002E_002E_003F_002E_002E_003F_002E_002E_003F_002E_002E_003F_002Econfig_003FJetBrains_003FRider2026_002E2_003Fresharper_002Dhost_003FDecompilerCache_003Fdecompiler_003Fe929cb9673c947ad9269facdac90006adb3400_003F14_003Fd939fe0a_003FConfiguredTaskAwaitable_002Ecs/@EntryIndexedValue">ForceIncluded</s:String>
<s:String x:Key="/Default/CodeInspection/ExcludedFiles/FilesAndFoldersToSkip2/=7020124F_002D9FFC_002D4AC3_002D8F3D_002DAAB8E0240759_002Ff_003AConstructorBindingFactory_002Ecs_002Fl_003A_002E_002E_003F_002E_002E_003F_002E_002E_003F_002E_002E_003F_002E_002E_003F_002Econfig_003FJetBrains_003FRider2026_002E1_003Fresharper_002Dhost_003FDecompilerCache_003Fdecompiler_003Fda476e261fcf49b394c1074b25b4cdce2b2960_003Fd4_003Fb1aa95c1_003FConstructorBindingFactory_002Ecs/@EntryIndexedValue">ForceIncluded</s:String> <s:String x:Key="/Default/CodeInspection/ExcludedFiles/FilesAndFoldersToSkip2/=7020124F_002D9FFC_002D4AC3_002D8F3D_002DAAB8E0240759_002Ff_003AConstructorBindingFactory_002Ecs_002Fl_003A_002E_002E_003F_002E_002E_003F_002E_002E_003F_002E_002E_003F_002E_002E_003F_002Econfig_003FJetBrains_003FRider2026_002E1_003Fresharper_002Dhost_003FDecompilerCache_003Fdecompiler_003Fda476e261fcf49b394c1074b25b4cdce2b2960_003Fd4_003Fb1aa95c1_003FConstructorBindingFactory_002Ecs/@EntryIndexedValue">ForceIncluded</s:String>
<s:String x:Key="/Default/CodeInspection/ExcludedFiles/FilesAndFoldersToSkip2/=7020124F_002D9FFC_002D4AC3_002D8F3D_002DAAB8E0240759_002Ff_003AConstructorBindingFactory_002Ecs_002Fl_003A_002E_002E_003F_002E_002E_003F_002E_002E_003F_002E_002E_003F_002E_002E_003F_002Econfig_003FJetBrains_003FRider2026_002E2_003Fresharper_002Dhost_003FDecompilerCache_003Fdecompiler_003Fda476e261fcf49b394c1074b25b4cdce2b2960_003Fb3_003F33475782_003FConstructorBindingFactory_002Ecs/@EntryIndexedValue">ForceIncluded</s:String>
<s:String x:Key="/Default/CodeInspection/ExcludedFiles/FilesAndFoldersToSkip2/=7020124F_002D9FFC_002D4AC3_002D8F3D_002DAAB8E0240759_002Ff_003ADbContext_002Ecs_002Fl_003A_002E_002E_003F_002E_002E_003F_002E_002E_003F_002E_002E_003F_002E_002E_003F_002Econfig_003FJetBrains_003FRider2026_002E2_003Fresharper_002Dhost_003FDecompilerCache_003Fdecompiler_003Fda476e261fcf49b394c1074b25b4cdce2b2960_003F37_003F1b1010ed_003FDbContext_002Ecs/@EntryIndexedValue">ForceIncluded</s:String>
<s:String x:Key="/Default/CodeInspection/ExcludedFiles/FilesAndFoldersToSkip2/=7020124F_002D9FFC_002D4AC3_002D8F3D_002DAAB8E0240759_002Ff_003AIWolverineHandler_002Ecs_002Fl_003A_002E_002E_003F_002E_002E_003F_002E_002E_003F_002E_002E_003F_002E_002E_003F_002Econfig_003FJetBrains_003FRider2026_002E2_003Fresharper_002Dhost_003FSourcesCache_003Fc2ddfdf7a216a59ed0f8739e93a88d24d346f54097c7eba6ba93c55690d4_003FIWolverineHandler_002Ecs/@EntryIndexedValue">ForceIncluded</s:String>
<s:String x:Key="/Default/CodeInspection/ExcludedFiles/FilesAndFoldersToSkip2/=7020124F_002D9FFC_002D4AC3_002D8F3D_002DAAB8E0240759_002Ff_003ALateBoundTestFramework_002Ecs_002Fl_003A_002E_002E_003F_002E_002E_003F_002E_002E_003F_002E_002E_003F_002E_002E_003F_002Econfig_003FJetBrains_003FRider2026_002E1_003Fresharper_002Dhost_003FSourcesCache_003Fcffa676d9bfc6c7a1c9d0d25ead15b3b0c9e12e3187bf397eaa52260e5fd91_003FLateBoundTestFramework_002Ecs/@EntryIndexedValue">ForceIncluded</s:String> <s:String x:Key="/Default/CodeInspection/ExcludedFiles/FilesAndFoldersToSkip2/=7020124F_002D9FFC_002D4AC3_002D8F3D_002DAAB8E0240759_002Ff_003ALateBoundTestFramework_002Ecs_002Fl_003A_002E_002E_003F_002E_002E_003F_002E_002E_003F_002E_002E_003F_002E_002E_003F_002Econfig_003FJetBrains_003FRider2026_002E1_003Fresharper_002Dhost_003FSourcesCache_003Fcffa676d9bfc6c7a1c9d0d25ead15b3b0c9e12e3187bf397eaa52260e5fd91_003FLateBoundTestFramework_002Ecs/@EntryIndexedValue">ForceIncluded</s:String>
<s:String x:Key="/Default/CodeInspection/ExcludedFiles/FilesAndFoldersToSkip2/=7020124F_002D9FFC_002D4AC3_002D8F3D_002DAAB8E0240759_002Ff_003AMessageContext_002Ecs_002Fl_003A_002E_002E_003F_002E_002E_003F_002E_002E_003F_002E_002E_003F_002E_002E_003F_002Econfig_003FJetBrains_003FRider2026_002E2_003Fresharper_002Dhost_003FSourcesCache_003Fb263759e5fefb34bcd589e63aeba791cef6f591ecbc93d1a7e62befa9e8bc6_003FMessageContext_002Ecs/@EntryIndexedValue">ForceIncluded</s:String>
<s:String x:Key="/Default/CodeInspection/ExcludedFiles/FilesAndFoldersToSkip2/=7020124F_002D9FFC_002D4AC3_002D8F3D_002DAAB8E0240759_002Ff_003ARelationalLoggerExtensions_002Ecs_002Fl_003A_002E_002E_003F_002E_002E_003F_002E_002E_003F_002E_002E_003F_002E_002E_003F_002Econfig_003FJetBrains_003FRider2026_002E2_003Fresharper_002Dhost_003FSourcesCache_003Fb797502679b4aa8376708777b4db8d11e31a798d7e6bead76c15bdfa30834892_003FRelationalLoggerExtensions_002Ecs/@EntryIndexedValue">ForceIncluded</s:String>
<s:String x:Key="/Default/CodeInspection/ExcludedFiles/FilesAndFoldersToSkip2/=7020124F_002D9FFC_002D4AC3_002D8F3D_002DAAB8E0240759_002Ff_003AThrowHelper_002Ecs_002Fl_003A_002E_002E_003F_002E_002E_003F_002E_002E_003F_002E_002E_003F_002E_002E_003F_002Econfig_003FJetBrains_003FRider2026_002E2_003Fresharper_002Dhost_003FDecompilerCache_003Fdecompiler_003Fe929cb9673c947ad9269facdac90006adb3400_003Ff0_003F6b0e8a92_003FThrowHelper_002Ecs/@EntryIndexedValue">ForceIncluded</s:String>
<s:String x:Key="/Default/CodeInspection/ExcludedFiles/FilesAndFoldersToSkip2/=7020124F_002D9FFC_002D4AC3_002D8F3D_002DAAB8E0240759_002Ff_003AWolverineRuntime_002EHostService_002Ecs_002Fl_003A_002E_002E_003F_002E_002E_003F_002E_002E_003F_002E_002E_003F_002E_002E_003F_002Econfig_003FJetBrains_003FRider2026_002E1_003Fresharper_002Dhost_003FSourcesCache_003F97bae8f1ffdd86c14edef353d7a85d3d3773b56c68e3a62e8815d1afaacbe797_003FWolverineRuntime_002EHostService_002Ecs/@EntryIndexedValue">ForceIncluded</s:String> <s:String x:Key="/Default/CodeInspection/ExcludedFiles/FilesAndFoldersToSkip2/=7020124F_002D9FFC_002D4AC3_002D8F3D_002DAAB8E0240759_002Ff_003AWolverineRuntime_002EHostService_002Ecs_002Fl_003A_002E_002E_003F_002E_002E_003F_002E_002E_003F_002E_002E_003F_002E_002E_003F_002Econfig_003FJetBrains_003FRider2026_002E1_003Fresharper_002Dhost_003FSourcesCache_003F97bae8f1ffdd86c14edef353d7a85d3d3773b56c68e3a62e8815d1afaacbe797_003FWolverineRuntime_002EHostService_002Ecs/@EntryIndexedValue">ForceIncluded</s:String>
<s:String x:Key="/Default/Environment/UnitTesting/UnitTestSessionStore/Sessions/=b53aee56_002D76e6_002D4473_002D9a54_002Dc62cf61dc263/@EntryIndexedValue">&lt;SessionState ContinuousTestingMode="0" IsActive="True" Name="Test1" xmlns="urn:schemas-jetbrains-com:jetbrains-ut-session"&gt; <s:String x:Key="/Default/Environment/UnitTesting/UnitTestSessionStore/Sessions/=ea7499a6_002Ddeba_002D4139_002Dac76_002D505e3f7f2642/@EntryIndexedValue">&lt;SessionState ContinuousTestingMode="0" IsActive="True" Name="All tests from Solution" xmlns="urn:schemas-jetbrains-com:jetbrains-ut-session"&gt;
&lt;Solution /&gt; &lt;Solution /&gt;
&lt;/SessionState&gt;</s:String></wpf:ResourceDictionary> &lt;/SessionState&gt;</s:String>
</wpf:ResourceDictionary>
+7 -1
View File
@@ -1,4 +1,4 @@
[tools] [tools]
dotnet = "10" dotnet = "10"
[tasks.restore] [tasks.restore]
@@ -12,3 +12,9 @@ run = "dotnet build"
[tasks.clean] [tasks.clean]
run = "fd -I \"bin|obj\" -td -X rm -r && dotnet clean" run = "fd -I \"bin|obj\" -td -X rm -r && dotnet clean"
[tasks.migrate]
usage = '''
arg "<name>" help="Migration Name"
'''
run = "dotnet ef migrations add \"${usage_name?}\" --startup-project FinancialApi --project FinancialApi.Infrastructure"