public async Task <Transaction> CreateAsync(CreateTransaction create, Action <CreateTransactionOptions>?setOpts = null) { var account = await _repo.GetAsync(create.AccountId, true); var tran = new Calculator().CreateToTransaction(create); var balance = tran.Amount switch { AmountIncomeCompleted am => account.Balance + am, AmountOutcomeProcessing am when account.Balance < am => throw new WPayException(TransactionErrors.NotEnoughMoney, new Dictionary <string, string>() { { "TransactionId", tran.Id.Value.Value.ToString() }, { "AccountId", tran.AccountId.Value.Value.ToString() } }), AmountOutcomeProcessing am => account.Balance - am, _ => throw new InvalidOperationException("Invalid amount") }; account = new Account(account.Id, balance, account.Locked); try { await _repo.UpdateAsync(account); await _repo.CreateAsync(tran); return(tran); } catch (TransactionUniqException) { var options = new CreateTransactionOptions(); setOpts?.Invoke(options); if (options.FailOnExist) { var info = new Dictionary <string, string>() { ["Id"] = create.Id.ToString() }; throw new WPayException(TransactionErrors.AlreadyExist, info); } return(tran); } }
public static TransactionEvent From(Transaction transaction) { var(amountType, amountValue, amountCurrency) = transaction.Amount switch { AmountIncomeCompleted am => (_completedIncome, am.Amount.ToString(), am.Amount.Currency().Code()), AmountOutcomeProcessing am => (_processingOutcome, am.Amount.ToString(), am.Amount.Currency().Code()), AmountOutcomeCancelled am => (_cancelledOutcome, am.Amount.ToString(), am.Amount.Currency().Code()), AmountOutcomeCompleted am => (_completedOutcome, am.Amount.ToString(), am.Amount.Currency().Code()), _ => throw new Exception("Invalid amount") }; return(new TransactionEvent { Id = transaction.Id.Value.Value, AccountId = transaction.AccountId.Value.Value, Label = transaction.Label.Value, Metadata = transaction.Metadata.Value, Description = transaction.Description.Value, AmountType = amountType, AmountCurrency = amountCurrency, AmountValue = amountValue }); } }