Ejemplo n.º 1
0
        public async Task AddPayment(PayOrder model, int corpClientId, long userId)
        {
            if (model.Amount <= 0)
            {
                throw new BusinessException("O valor do pagamento deve ser maior que zero");
            }

            var currentOrder = await GetByNumber(model.OrderNumber, corpClientId);

            var payments = await transactionApp.GetTransactions(currentOrder.OrderId, corpClientId);

            var totalPaid = payments.Where(p => (p.IsOrderPrincipalAmount ?? false)).Sum(s => s.Amount);

            if (totalPaid + model.Amount > currentOrder.ItemsTotalAfterDiscounts)
            {
                throw new BusinessException("O valor total pago não pode ser maior que o total da venda");
            }

            var nextPaymentStatus = (totalPaid + model.Amount == currentOrder.ItemsTotalAfterDiscounts) ?
                                    PaymentStatusEnum.Pago : PaymentStatusEnum.ParcialmentePago;

            using var trans = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled);
            await orderApp.Update(new UpdateOrder
            {
                CompleteBy      = currentOrder.CompleteBy,
                FreightPrice    = currentOrder.FreightPrice,
                OrderNumber     = currentOrder.OrderNumber,
                PaymentStatusId = nextPaymentStatus
            }, corpClientId);

            await transactionApp.AddTransaction(new NewTransaction
            {
                Amount                 = model.Amount,
                CorpClientId           = corpClientId,
                Date                   = DateTimeOffset.UtcNow,
                Description            = $"Recebimento referente ao Pedido #{currentOrder.OrderNumber}",
                MerchantName           = currentOrder.Customer.Name,
                OrderId                = currentOrder.OrderId,
                TransactionTypeId      = model.OrderPaymentMethod,
                TransactionStatusId    = 1,
                IsOrderPrincipalAmount = true
            }, userId);

            if (model.Tip > 0)
            {
                await transactionApp.AddTransaction(new NewTransaction
                {
                    Amount                 = model.Tip,
                    CorpClientId           = corpClientId,
                    Date                   = DateTimeOffset.UtcNow,
                    Description            = $"Recebimento de Tips referente ao Pedido #{currentOrder.OrderNumber}",
                    MerchantName           = currentOrder.Customer.Name,
                    OrderId                = currentOrder.OrderId,
                    TransactionTypeId      = model.TipPaymentMethod,
                    TransactionStatusId    = 1,
                    IsOrderPrincipalAmount = false
                }, userId);
            }
            trans.Complete();
        }