public DistributionCommands( IEntityRepository repository, IFlowDistributor distributor, ITimeService timeService, ICurrentSession currentSession) { _repository = repository; _distributor = distributor; _timeService = timeService; _currentSession = currentSession; }
public async Task Distribute(IEntityRepository repository, IFlowDistributor distributor) { var accountIds = Accounts.Select(x => x.Id).ToList(); var accountsQueries = repository.GetQuery <Account>(); var accounts = await accountsQueries .Where(x => accountIds.Contains(x.Id)) .Select(x => x.ToModel()) .ToListAsync() .ConfigureAwait(false); accounts.ForEach(x => { var account = Accounts.First(a => a.Id == x.Id); account.Balance = x.AvailBalance; (x as IFlowEndPoint).FlowRule = new DistributionFlowRule { CanFlow = account.CanFlow, Destination = FlowDestination.Source }; }); var flowIds = ExpenseFlows.Select(x => x.Id).ToList(); var flowQueries = repository.GetQuery <ExpenseFlow>(); var flows = await flowQueries .Where(x => flowIds.Contains(x.Id)) .Select(x => x.ToModel()) .ToListAsync() .ConfigureAwait(false); flows.ForEach(x => { var expenseFlow = ExpenseFlows.First(s => s.Id == x.Id); expenseFlow.Balance = x.Balance; x.FlowRule = new DistributionFlowRule { CanFlow = expenseFlow.CanFlow, Destination = FlowDestination.Recipient, Rule = expenseFlow.Rule, Amount = expenseFlow.Amount }; }); var endPoints = new List <IFlowEndPoint>(); endPoints.AddRange(accounts); endPoints.AddRange(flows); distributor.Distribute(endPoints); DistributionFlows = distributor.FlowRecords .Select(x => new DistributionFlowModel { SourceId = x.Source.Id, SourceName = x.Source.Name, RecipientId = x.Recipient.Id, RecipientName = x.Recipient.Name, Amount = x.Amount, AmountFormatted = x.Amount.ToMoney() }).ToList(); Accounts.ForEach(x => { if (!x.CanFlow) { return; } var withdrawTotal = distributor.FlowRecords.Where(f => f.Source.Id == x.Id).Sum(f => f.Amount); if (withdrawTotal > 0) { x.WithdrawTotal = $"\u2013{withdrawTotal.ToMoney()}"; } x.Result = (x.Balance - withdrawTotal).ToMoney(); }); ExpenseFlows.ForEach(x => { if (!x.CanFlow) { return; } var topupTotal = distributor.FlowRecords.Where(f => f.Recipient.Id == x.Id).Sum(f => f.Amount); if (topupTotal > 0) { x.TopupTotal = $"+{topupTotal.ToMoney()}"; } x.Result = (x.Balance + topupTotal).ToMoney(); }); }