using FinancialApi.Domain; using Wolverine.Attributes; using Wolverine.Persistence; namespace FinancialApi.Application; public record ApplyFeeCommand(int AccountId, decimal Amount); public record FeeAppliedEvent(int AccountId, decimal Amount); public record FeePair(Account Source, Account Destination, DateTimeOffset TimeStamp); public static class ApplyFeeHandler { public static async Task LoadAsync( ApplyFeeCommand cmd, IAccountQuery query, TimeProvider timeProvider) { var source = await query.FindByIdAsync(cmd.AccountId); var dest = await query.FindByIdAsync(99999); if (source == null || dest == null) { throw new InvalidOperationException($"Cannot process transfer. Account(s) not found."); } return new FeePair(source, dest, timeProvider.GetUtcNow()); } public static ( IStorageAction CustomerWrite, IStorageAction RevenueWrite, IStorageAction JournalWrite, FeeAppliedEvent Event ) Handle( ApplyFeeCommand cmd, FeePair pair ) { var updatedSource = pair.Source.ApplyPosting(cmd.Amount, EntryType.Debit); var updatedRevenue = pair.Destination.ApplyPosting(cmd.Amount, EntryType.Credit); var lines = new List { new(updatedSource.Id, cmd.Amount, EntryType.Debit), new(updatedRevenue.Id, cmd.Amount, EntryType.Credit) }; var journalEntry = BalancedJournal.Create(Guid.NewGuid(), $"Service Fee Applied: {cmd.Amount} to Account {cmd.AccountId}", pair.TimeStamp, lines); var @event = new FeeAppliedEvent(cmd.AccountId, cmd.Amount); return ( Storage.Update(updatedSource), Storage.Update(updatedRevenue), Storage.Insert(journalEntry.Entry), @event ); } }