58 lines
2.1 KiB
C#
58 lines
2.1 KiB
C#
using FinancialApi.Application;
|
|
using Microsoft.EntityFrameworkCore;
|
|
using Wolverine.Attributes;
|
|
using Wolverine.Persistence;
|
|
|
|
namespace FinancialApi.Infrastructure;
|
|
|
|
public record TransferFundsCommand(int SourceAccountId, int DestinationAccountId, decimal Amount);
|
|
|
|
public record FundsTransferredEvent(int SourceAccountId, int DestinationAccountId, decimal Amount);
|
|
|
|
// A simple container to pass our loaded entities into the pure function
|
|
public record TransferPair(Account Source, Account Destination);
|
|
|
|
public static class TransferFundsHandler
|
|
{
|
|
public static async Task<TransferPair?> LoadAsync(TransferFundsCommand cmd, AccountDbContext db)
|
|
{
|
|
var source = await db.Accounts.AsNoTracking().FirstOrDefaultAsync(x => x.Id == cmd.SourceAccountId);
|
|
var dest = await db.Accounts.AsNoTracking().FirstOrDefaultAsync(x => x.Id == cmd.DestinationAccountId);
|
|
|
|
if (source == null || dest == null) return null; // Wolverine drops into a 404/Problem if null
|
|
|
|
return new TransferPair(source, dest);
|
|
}
|
|
|
|
[Transactional]
|
|
public static (
|
|
IStorageAction<Account> SourceWrite,
|
|
IStorageAction<Account> DestWrite,
|
|
IStorageAction<JournalEntry> JournalWrite,
|
|
FundsTransferredEvent Event
|
|
) Handle(TransferFundsCommand cmd, TransferPair pair)
|
|
{
|
|
var updatedSource = pair.Source.Debit(cmd.Amount);
|
|
var updatedDest = pair.Destination.Credit(cmd.Amount);
|
|
|
|
var lines = new List<JournalLine>
|
|
{
|
|
new (pair.Source.Id, cmd.Amount, EntryType.Debit),
|
|
new (pair.Destination.Id, cmd.Amount, EntryType.Credit)
|
|
};
|
|
|
|
var journalEntry =
|
|
BalancedJournal.Create(Guid.NewGuid(),
|
|
$"Transfer: {cmd.Amount} from {cmd.SourceAccountId} to {cmd.DestinationAccountId}",
|
|
DateTimeOffset.UtcNow, lines);
|
|
|
|
var @event = new FundsTransferredEvent(cmd.SourceAccountId, cmd.DestinationAccountId, cmd.Amount);
|
|
|
|
return (
|
|
Storage.Update(updatedSource),
|
|
Storage.Update(updatedDest),
|
|
Storage.Insert(journalEntry.Entry),
|
|
@event
|
|
);
|
|
}
|
|
} |