public void Test()
        {
            var brand = new Brand
            {
                Title = "Brand 1"
            };

            var clockType = new ClockType
            {
                Title = "Clock Type 1"
            };

            var payment = new Payment
            {
                Title = "Payment 1"
            };

            var delivery = new Delivery
            {
                Title = "Delivery 1"
            };

            _brandRepository.Add(brand);
            _clockTypeRepository.Add(clockType);
            _paymentRepository.Add(payment);
            _deliveryRepository.Add(delivery);
        }
        public async Task <Payment> ProcessPayment(Payment payment)
        {
            if (payment is null)
            {
                throw new ArgumentNullException(nameof(payment));
            }

            var isCurrencySupported = await _currencyService.IsCurrencySupported(payment.Currency).ConfigureAwait(false);

            if (!isCurrencySupported)
            {
                throw new PaymentAggregateException($"Currency {payment.Currency} is not supported");
            }

            var paymentStatus = await _paymentSenderService.SendPayment(payment).ConfigureAwait(false);

            if (paymentStatus == PaymentStatus.ServiceError)
            {
                throw new PaymentAggregateException("There was in issue with the calling bank");
            }

            var updatedPayment = payment.UpdateStatus(paymentStatus);

            updatedPayment = _paymentRepository.Add(updatedPayment);
            await _paymentRepository.UnitOfWork.SaveChangesAsync().ConfigureAwait(false);

            return(updatedPayment);
        }
Beispiel #3
0
        public int SaveCreditCardDetailModel(CreditCardDetailModel model)
        {
            var ccDetail = Mapper.DynamicMap <tblCreditCardDetail>(model);

            _paymentRepository.Add(ccDetail);
            return(_paymentRepository.SaveChanges());
        }
Beispiel #4
0
        public async Task <bool> ProcessPayment(Payment model)
        {
            model.Id = Guid.NewGuid().ToString();
            await _paymentRepository.Add(model);

            return(await ProcessTransaction(model.Id));
        }
Beispiel #5
0
        public async Task <Models.Payment> AddPayment(PaymentRequest paymentRequest)
        {
            Models.Payment payment = null;
            payment = new Models.Payment
            {
                Amount              = paymentRequest.Amount,
                Currency            = paymentRequest.Currency,
                RequestedOn         = DateTime.Now,
                Status              = PaymentStatus.Requested,
                CardNumber          = paymentRequest.CardNumber,
                Cvv                 = paymentRequest.Cvv,
                ExpiryDate          = paymentRequest.ExpiryDate,
                IdempotencyUniqueId = UniqueIdempotencyId(paymentRequest)
            };

            if (await _paymentRepository.Add(payment) == StoreNewPaymentResult.DuplicateUniqueIdempotencyId)
            {
                return(await _paymentRepository.GetByIdempotencyKey(payment.IdempotencyUniqueId));
            }

            var response = await _bankClient.InitiatePayment(payment);

            payment.Status         = response.PaymentStatus;
            payment.BankIdentifier = response.BankIdentifier;

            await _paymentRepository.Update(payment);

            return(payment);
        }
Beispiel #6
0
        public async Task <PaymentDTO> MakePayment(AddPaymentDTO addPaymentDTO)
        {
            var invoice = await _invoicesRepository.ByID(addPaymentDTO.InvoiceID);


            if (invoice != null && invoice?.Total == addPaymentDTO.PaymentAmount)
            {
                Payment invoicePayment = await _paymentRepository.ByInvoiceID(invoice.InvoiceID);

                //если оплата по счету уже сделана то повторно она не проводится
                if (invoicePayment != null)
                {
                    return(_mapper.Map <PaymentDTO>(invoicePayment));
                }

                Payment newPayment = new Payment()
                {
                    InvoiceID     = invoice.InvoiceID,
                    PaymentAmount = invoice.Total,
                    PaidAt        = DateTime.Now
                };

                Payment addedPayment = await _paymentRepository.Add(newPayment);

                _rmqProducer.PaymentSuccessful(invoice.ShoppingCartID);

                return(_mapper.Map <PaymentDTO>(addedPayment));
            }

            return(new PaymentDTO());
        }
Beispiel #7
0
        public void Vend(VendDTO vend)
        {
            if (vend == null)
            {
                throw new ArgumentNullException("vend");
            }

            if (vend.payment == null)
            {
                throw new ArgumentNullException("payment");
            }

            if (vend.flavour == 0)
            {
                throw new ArgumentException("flavour");
            }

            //if we have db then we should perfrm all actions in this function under transaction
            Payment payment = PaymentMapper.Map(vend.payment);

            _paymentRepository.Add(payment);

            var criteria = new DrinkCanFindCriteria();

            criteria.Flavour = vend.flavour;

            DrinkCan can = _drinkCanRepository.FindByCriteria(criteria).FirstOrDefault();

            _drinkCanRepository.Delete(can);
        }
Beispiel #8
0
        public async Task <ActionResult> Create([FromBody] CreatePaymentRequestModel requestModel)
        {
            if (!EnsureMerchantValidity(out var merchant))
            {
                return(BadRequest(new ErrorResponseModel("missing or invalid merchant header")));
            }

            var creditCardInformation = new CreditCardInformation(requestModel.CreditCardNumber,
                                                                  new ExpiryDate(requestModel.CreditCardExpiryMonth, requestModel.CreditCardExpiryYear),
                                                                  requestModel.CreditCardCcv);

            var paymentAmount = new PaymentAmount(requestModel.Amount, requestModel.CurrencyCode);
            var payment       = Payment.Create(paymentAmount, creditCardInformation, merchant.MerchantId, requestModel.ExternalShopperIdentifier);

            bool wasPaymentSuccessful = await payment.AttemptPayment(merchant.CreditCardInformation, _bankConnectorDS);

            _paymentRepository.Add(payment);
            await _paymentRepository.PersistAsync();

            _logger.LogInformation($"New payment was created with PaymentId: {payment.PaymentId}");

            var responseModel = new CreatePaymentResponseModel
            {
                WasPaymentSuccessful = wasPaymentSuccessful,
                PaymentId            = payment.PaymentId
            };

            return(Accepted(responseModel));
        }
        public async Task <PaymentData> ProcessPayment(PaymentRequest request)
        {
            if (request == null)
            {
                throw new ArgumentNullException(nameof(request));
            }

            var paymentData = BuildPaymentData(request);

            _paymentRepository.Add(paymentData);

            CustomMetrics.PaymentStarted.Inc();
            _logger.LogInformation($"Payment request for {request.Amount} {request.Currency} recieved and given id {paymentData.Id}");

            var bankResponse = await _bankService.ProcessPayment(request);

            var newStatus    = bankResponse.Success ? PaymentStatus.Accepted : PaymentStatus.Rejected;
            var statusString = bankResponse.Success ? "accepted" : "rejected";

            _paymentRepository.Update(paymentData.Id, bankResponse.TransactionId, newStatus);
            _logger.LogInformation($"Transaction {bankResponse.TransactionId} {statusString}");
            CustomMetrics.PaymentCompleted.WithLabels(statusString).Inc();

            return(paymentData);
        }
Beispiel #10
0
        public async Task <Payment> AddPayment(Payment payment)
        {
            var saved = paymentRepository.Add(payment);
            await paymentRepository.Save();

            return(saved);
        }
        public ActionResult ProceedToPayment(FormCollection data)
        {
            RegistrationViewModel obj = new RegistrationViewModel();

            TryUpdateModel(obj);
            GotoPayment(obj);
            Payment payment = new Payment();

            payment.ApplicationNumber = obj.ApplicationNumber;
            payment.Name            = obj.Name;
            payment.Email           = obj.Email;
            payment.Mobile1         = obj.MobileNo;
            payment.Category        = obj.Category;
            payment.TechCat1        = obj.TechCat1;
            payment.TechCat2        = obj.TechCat2;
            payment.TechCat3        = obj.TechCat3;
            payment.TechCat4        = obj.TechCat4;
            payment.NonTechCat1     = obj.NonTechCat1;
            payment.NonTechCat2     = obj.NonTechCat2;
            payment.NonTechCat3     = obj.NonTechCat3;
            payment.NonTechCat4     = obj.NonTechCat4;
            payment.RegistrationFee = obj.RegistrationFee;
            payment.ServiceTax      = obj.ServiceTax;
            payment.Total           = obj.Total;
            payment.AmountReceived  = 0;
            payment.ReferenceNumber = "";

            _paymentRepository.Add(payment);
            unitOfWork.SaveChanges();

            return(View(obj));
        }
        public async Task <PaymentResponse> ProcessPaymentRequest(PaymentRequest paymentRequest)
        {
            if (paymentRequest == null)
            {
                throw new ArgumentNullException("paymentRequest");
            }

            var validationErrors = _paymentRequestValidator.Validate(paymentRequest);

            var merchant = _merchantRepository.GetMerchantById(paymentRequest.MerchantId);

            var payment = _autoMapper.Map <Payment>(paymentRequest);

            payment.Merchant = await merchant;

            if (merchant == null)
            {
                throw new NullReferenceException("Merchant cannot be null");
            }

            payment.PaymentStatuses.Add(new PaymentStatus
            {
                StatusKey      = validationErrors.Any() ? PaymentStatuses.InternalValidationError : PaymentStatuses.PendingSubmission,
                StatusDateTime = _dateTimeProvider.UtcNow
            });

            payment = await _paymentRepository.Add(payment);

            if (validationErrors.Any())
            {
                return(GenerateNewPaymentResponse(payment, validationErrors));
            }

            var bankResponse = await _acquiringBankClient.SubmitPaymentToBank(paymentRequest);

            if (bankResponse == null)
            {
                payment.PaymentStatuses.Add(new PaymentStatus
                {
                    StatusKey      = PaymentStatuses.SubmissionError,
                    StatusDateTime = _dateTimeProvider.UtcNow
                });

                await _paymentRepository.Update(payment);

                return(GenerateNewPaymentResponse(payment));
            }

            payment.BankId = bankResponse.BankId;
            payment.PaymentStatuses.Add(new PaymentStatus
            {
                StatusKey      = bankResponse.PaymentStatus,
                StatusDateTime = bankResponse.StatusDateTime
            });

            payment = await _paymentRepository.Update(payment);

            return(GenerateNewPaymentResponse(payment));
        }
        public async Task <Payment> Create(Payment payment)
        {
            await _paymentRepository.Add(payment);

            await _paymentRepository.Commit();

            return(payment);
        }
Beispiel #14
0
        public void AddPayment(string nameMethod)
        {
            var payment = new PaymentType {
                NameMethod = nameMethod
            };

            _paymentRepository.Add(payment);
            _unitOfWork.Commit();
        }
Beispiel #15
0
        public async Task <IActionResult> PayStandard(Provider provider, int paymentSum, PaymentCard paymentCard, Intent intent)
        {
            TempData["actionInitiated"] = true;
            if (intent == Intent.NoIntent)
            {
                setError(InvalidIntent);
                return(redirectToLandingPage());
            }

            // Let's assume payment sum and payment card gets validated on the client side, so no need to do it here.

            PayResponse response = await rcpgClient.PayStandard(provider, paymentSum, DEFAULT_CURRENCY, paymentCard, intent);

            if (response.PaymentErrors.Any())
            {
                TempData["hasErrors"]        = true;
                TempData["notificationText"] = $"Notikusi kļūda. Kļūdas avots: \"{response.PaymentErrors.First().Source}\", kļūdas kods: \"{response.PaymentErrors.First().ErrorCode}\"";
                return(redirectToLandingPage());
            }

            Payment payment = new Payment()
            {
                Token         = response.PaymentId,
                Sum           = paymentSum,
                Currency      = DEFAULT_CURRENCY,
                Provider      = provider.ToString(),
                Intent        = intent.ToString(),
                TransactionId = response.PaymentId,
                InitiatedOn   = DateTime.Parse(response.ExecutedOn)
            };

            if (intent == Intent.Purchase)
            {
                payment.Status     = PaymentStatus.Captured.ToString();
                payment.CapturedOn = DateTime.Parse(response.ExecutedOn);
            }
            else
            {
                payment.Status = PaymentStatus.Authorized.ToString();
            }
            await paymentRepository.Add(payment);

            return(redirectToAllPayments());
        }
Beispiel #16
0
        private Payment CreateNewPayment()
        {
            var payment = new Payment
            {
                Date = DateTime.Today
            };

            _paymentRepository.Add(payment);
            return(payment);
        }
Beispiel #17
0
        public string MakePayment(int RouteId)
        {
            //var routeToMakePayment = _routeService.getRouteDetail(RouteId);
            //var customerInfor = _customerService.FindCustomerById(routeToMakePayment.CutomerId);
            //var creditCardToMakePayment = _creditCardService.GetCardToPayment(routeToMakePayment.CustomerId);
            var routeToMakePayment      = _routeRepository.Get(x => x.Id == RouteId);
            var customerInfor           = _customerRepository.Get(x => x.Id == routeToMakePayment.CustomerId);
            var creditCardToMakePayment = _creditCardRepository.Get(x => x.Deleted == false && x.CustomerId == routeToMakePayment.CustomerId && x.Isdefault == true);

            //Stripe charge money
            StripeConfiguration.SetApiKey(SETTING.Value.SecretStripe);

            var options = new ChargeCreateOptions
            {
                Amount      = Convert.ToInt64(routeToMakePayment.TotalAmount * 100),
                Currency    = "usd",
                Description = customerInfor.FullName.ToUpper() + "-" + customerInfor.Email + "-" + customerInfor.PhoneNumber +
                              " buy Route Code: " + routeToMakePayment.Code,
                SourceId   = creditCardToMakePayment.CardId, // obtained with Stripe.js,
                CustomerId = customerInfor.StripeId,
            };
            var service = new ChargeService();

            service.ExpandBalanceTransaction = true;
            Charge charge = service.Create(options);


            PaymentCreateViewModel model = new PaymentCreateViewModel();

            model.RouteId        = routeToMakePayment.Id;
            model.CreditCartId   = creditCardToMakePayment.Id;
            model.Description    = "You bought route " + routeToMakePayment.Code + ". Thank you for using our service.";
            model.Amount         = routeToMakePayment.TotalAmount;
            model.Status         = PaymentStatus.Success;
            model.StripeChargeId = charge.Id;
            model.FeeAmount      = Convert.ToDecimal(charge.BalanceTransaction.Fee) / 100;
            var payment = _mapper.Map <PaymentCreateViewModel, Payment>(model); //map từ ViewModel qua Model

            _paymentRepository.Add(payment);
            _unitOfWork.CommitChanges();
            return("");
        }
        public void Add(PaymentDTO recDTO)
        {
            if (recDTO == null)
            {
                throw new ArgumentNullException(string.Format(ValidationConstants.SDataNotFoundWithValue, "Payment"));
            }

            Payment rec = PaymentMapper.Map(recDTO);

            _paymentRepository.Add(rec);
        }
Beispiel #19
0
 private void SaveOrUpdatePayment(Payment payment)
 {
     if (payment.Data.Id == 0)
     {
         paymentRepository.Add(payment.Data);
     }
     else
     {
         paymentRepository.Update(payment.Data);
     }
 }
        public async Task <Models.PaymentResultModel> Handle(
            ProcessPaymentRequestCommand command,
            CancellationToken cancellationToken = default)
        {
            var merchant = await _merchantRepository.GetAsync(command.MerchantId);

            if (merchant == null)
            {
                _logger.LogWarning("Merchant with {id} was not found", command.MerchantId);
                throw new Exception("Merchant was not found");
            }

            var shopperCard = new PaymentCard(
                command.CardNumber,
                command.CardHolderName,
                command.ExpiryMonth,
                command.ExpiryYear);

            var payment = new Payment(
                shopperCard,
                command.MerchantId,
                command.ChargeTotal,
                command.CurrencyCode);

            _paymentRepository.Add(payment);
            await _unitOfWork.CommitAsync();

            try
            {
                var transactionResult = await ProcessPaymentByAcquiringBank(command, merchant.Iban);

                if (transactionResult.Status == TransactionStatus.Accepted)
                {
                    payment.Succeed();
                }
                else
                {
                    payment.Fail();
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Payment transaction with {id} failed to processed by acquiring bank", payment.Id);
                payment.Fail();
            }

            await _unitOfWork.CommitAsync();

            return(new PaymentResultModel
            {
                PaymentId = payment.Id,
                Status = payment.Status
            });
        }
Beispiel #21
0
 public PaymentDto AddPayment(PaymentDto payment, int userId)
 {
     payment.Id = _paymentReposirotry.Add(new Payment()
     {
         Amount        = payment.Amount,
         PaymentDate   = payment.PaymentDate,
         PaymentTypeId = payment.PaymentTypeId,
         PlaceName     = payment.PlaceName,
         UserId        = userId
     }).Id;
     return(payment);
 }
Beispiel #22
0
        public async Task <Result> Handle(CreatePaymentCommand request, CancellationToken cancellationToken)
        {
            // Check if currency is supported for given merchant
            var isCurrencySupported = await _merchantQuery.IsCurrencySupported(request.MerchantId, request.Currency);

            if (!isCurrencySupported)
            {
                return(Result.Fail(ExternalErrorReason.CurrencyNotSupported));
            }

            // Check if card if valid
            var isCardValid = await _cardQuery.IsCardValid(request.CardToken, request.Cvv);

            if (!isCardValid)
            {
                return(Result.Fail <string>(ExternalErrorReason.InvalidCard));
            }

            // Perform risk analysis
            if (!string.IsNullOrEmpty(request.OriginIp) && IPAddress.TryParse(request.OriginIp, out IPAddress ipAddress))
            {
                var riskAnalysisResult = await _riskAnalysisService.GetRiskAnalysis(ipAddress);

                if (!riskAnalysisResult.IsSuccess)
                {
                    return(Result.Fail <string>(riskAnalysisResult.Error));
                }
            }
            var payment = new Payment(request.MerchantId, request.Currency, request.Amount, request.Reference, request.OriginIp,
                                      request.Description);

            payment.SetCardPaymentSource(request.CardToken, request.Cvv);
            if (request.Shipping != null)
            {
                payment.AddBillingAddress(request.Shipping.AddressLine1, request.Shipping.AddressLine2, request.Shipping.City,
                                          request.Shipping.Zip, request.Shipping.State, request.Shipping.Country);
            }
            if (request.Recipient != null)
            {
                payment.SetPaymentRecipient(DateTime.Parse(request.Recipient.DateOfBirth), request.Recipient.AccountNumber, request.Recipient.FirstName,
                                            request.Recipient.LastName, request.Recipient.Zip);
            }
            payment.SetNotificationsForMerchant(request.SuccessUrl, request.ErrorUrl);
            payment.InitiatePayment();

            _paymentRepository.Add(payment);

            var persistenceResult = await _paymentRepository.UnitOfWork.SaveEntitiesAsync(cancellationToken);

            return(persistenceResult.IsSuccess
                ? Result.Ok(payment.PaymentId)
                : Result.Fail <string>(persistenceResult.Error));
        }
        public async Task <IActionResult> Post(CreatingPaymentModel model)
        {
            if (ModelState.IsValid)
            {
                var client = await clientRepository.Read(model.ClientId);

                if (client == null)
                {
                    return(NotFound($"Cliente com Id {model.ClientId} não foi encontrado."));
                }

                var clerk = await userManager.FindByIdAsync(model.ClerkId);

                if (clerk == null)
                {
                    return(NotFound(ErrorResponse.From($"Atendent com o Id {model.ClerkId} não foi encontrado.")));
                }

                if (model.Value <= 0 || model.Value > client.Debt)
                {
                    return(BadRequest($"O valor precisa ser maior que R$ 0 e menor que R$ {client.Debt}"));
                }

                client.Debt        -= model.Value;
                client.LastPurchase = DateTime.Now;

                if (client.Debt == 0)
                {
                    var pendings = await orderRepository.Pending(client.Id);

                    foreach (var order in pendings)
                    {
                        order.Status = Models.OrderModels.Status.Pago;
                    }
                }

                var p = new Payment
                {
                    Client = client,
                    Clerk  = clerk,
                    Amount = model.Value,
                    Date   = DateTime.Now,
                };

                await paymentRepository.Add(p);

                var url     = Url.Action("Get", new { id = p.Id });
                var created = Created(url, p);
                return(created);
            }

            return(BadRequest(ErrorResponse.FromModelState(ModelState)));
        }
Beispiel #24
0
        public IActionResult Post([FromBody] PaymentRequest payReq)
        {
            var payment = _paymentFactory.Create(payReq.Client.Id
                                                 , payReq.Type, payReq.Amount
                                                 , payReq.Buyer.Name, payReq.Buyer.Email, payReq.Buyer.Cpf
                                                 , payReq.Card?.ExpirationDate, payReq.Card?.Cvv, payReq.Card?.HolderName, payReq.Card?.Number);

            var result = payment.Process();

            _paymentRepository.Add(payment);

            return(CreatedAtRoute("GetPayment", new { id = payment.Id }, result));
        }
Beispiel #25
0
 private void AddPaymentToChangeSet(Payment payment)
 {
     payment.ClearPayment();
     PaymentAmountHelper.AddPaymentAmount(payment);
     if (payment.Data.Id == 0)
     {
         paymentRepository.Add(payment.Data);
     }
     else
     {
         paymentRepository.Update(payment.Data);
     }
 }
        // [Route("api/payment/{id}")]
        public IHttpActionResult Post([FromBody] PaymentDTO value)
        {
            try
            {
                if (value == null)
                {
                    return(BadRequest());
                }

                string userName = null;
                if (HttpContext.Current != null && HttpContext.Current.User != null &&
                    HttpContext.Current.User.Identity.Name != null)
                {
                    userName = HttpContext.Current.User.Identity.Name;
                }

                if (value.Amount != value.PaymentItems.Sum(it => it.Amount))
                {
                    return(BadRequest("Invocie Amount Miss Match with total Invoice Item Amount"));
                }

                foreach (var item in value.PaymentItems)
                {
                    var invoice = _InvoiceRepo.Get().FirstOrDefault <Invoice>(i => i.InvoiceNo == item.InvoiceNo);
                    if (invoice == null)
                    {
                        return(BadRequest(item.InvoiceNo + "InvoiceNo not found"));
                    }
                    item.InvoiceID = invoice.ID;
                }

                var payment = value.ToDomain();
                payment.CreateUser  = userName;
                payment.ChangeUser  = userName;
                payment.Concurrency = Guid.NewGuid();
                _PaymentRepo.Add(payment);

                _uow.SaveChanges();

                if (payment.ID > 0)
                {
                    return(Created <PaymentDTO>(Request.RequestUri + "/" + payment.ID, payment.ToDTO()));
                }

                return(BadRequest());
            }
            catch (Exception ex)
            {
                return(InternalServerError());
            }
        }
Beispiel #27
0
        public async Task <CreatePaymentResponse> CreatePayment(CreatePaymentRequest request, Merchant merchant)
        {
            try
            {
                if (merchant == null)
                {
                    return(null);
                }

                _log.LogInformation($"Requesting bank for merchant {merchant.Id} : {request.Amount:C2}");

                var bankResponse = await _bankGateway.SubmitPayment(PaymentMapper.MapGatewayRequest(request));

                _log.LogInformation($"Bank response for merchant {merchant.Id} : {bankResponse.Status} ");



                var payment = await _paymentRepository.Add(PaymentMapper.MapPayment(bankResponse, merchant, _encryptionProvier));

                var isPaymentSuccessfull = bankResponse.Status == BankGatewayPaymentStatus.Successfull;
                var result = new CreatePaymentResponse {
                    IsSuccessfull = isPaymentSuccessfull
                };

                if (isPaymentSuccessfull)
                {
                    result.PaymentId = payment.Id;
                }
                else
                {
                    result.ErrorMessage = "Unable to process payment with Bank";
                }


                _log.LogInformation($"Created  Payment for  merchant {merchant.Id} : {result.PaymentId} ");

                return(result);
            }
            catch (Exception ex)
            {
                _log.LogError("Unabl to process paument", ex);

                return(new CreatePaymentResponse
                {
                    IsSuccessfull = false,
                    ErrorMessage = "An unexpected error occured, please try again later or contact support"
                });
            }
        }
        public IActionResult Create([FromBody] Payment item)
        {
            if (item == null)
            {
                return(BadRequest());
            }

            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            _paymentRepository.Add(item);
            return(CreatedAtRoute("GetPayment", new { id = item.Id, aid = item.AddressId }, item));
        }
Beispiel #29
0
        public async Task <ResultModel> Add(Payment payment)
        {
            var result          = new ResultModel();
            var validatorResult = new PaymentValidator(_paymentRepository, _creditCardRepository).Validate(payment);

            if (!validatorResult.IsValid)
            {
                result.AddNotification(validatorResult.Errors);
                return(result);
            }

            await _paymentRepository.Add(payment);

            return(result);
        }
Beispiel #30
0
        public int AddPaymentRecord(DLModel.Payment modelPayment)
        {
            //  var PaymentSum = _paymentRepository.GetAll(Pay => Pay.InvoiceId == modelPayment.InvoiceId).ToList().Select(Pay => Pay.PaymentAmount == null ? 0 : Pay.PaymentAmount).Sum();
            //PaymentSum = PaymentSum + modelPayment.PaymentAmount;
            DLModel.Invoice InvoiceDetail = _IInvoiceImpl.GetInvoiceDetailsById(modelPayment.InvoiceId);

            //if (modelPayment.PaymentAmount <= InvoiceDetail.InvoiceBalanceAmt)
            //{
            InvoiceDetail.InvoiceBalanceAmt = (InvoiceDetail.InvoiceBalanceAmt - modelPayment.PaymentAmount).Value;
            var updInvoiceBalAmt = _invoiceRepository.Update(InvoiceDetail, inv => inv.InvoiceBalanceAmt);

            return(_paymentRepository.Add((DLModel.Payment) new DLModel.Payment().InjectFrom(modelPayment)).PaymentId);
            //}
            //else
            //    return -1; // Payment Sum amout can't be greater then invoice amount
        }