public async Task <IActionResult> PutPaymentDetail([FromRoute] int id, [FromBody] PaymentDetail paymentDetail)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != paymentDetail.paymentId)
            {
                return(BadRequest());
            }

            _context.Entry(paymentDetail).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!PaymentDetailExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(NoContent());
        }
Ejemplo n.º 2
0
        public async Task <Payment> MakePaymentAsync(Guid userId, PaymentRequestDTO paymentRequest)
        {
            var existPayment = await _context.Payments.FirstOrDefaultAsync(g => g.IdempotanceKey == paymentRequest.IdempotenceKey);

            if (existPayment != null)
            {
                return(existPayment);
            }

            var payment = new Payment()
            {
                Amount         = paymentRequest.Amount,
                Date           = DateTime.UtcNow,
                UserId         = userId,
                IdempotanceKey = paymentRequest.IdempotenceKey,
            };

            try
            {
                _context.Payments.Add(payment);
                var res = await _context.SaveChangesAsync();
            }
            catch (UniqueConstraintException)
            {
                return(await _context.Payments.FirstAsync(g => g.IdempotanceKey == paymentRequest.IdempotenceKey));
            }
            return(payment);
        }
Ejemplo n.º 3
0
        public async Task <IActionResult> PutPayment(string id, Payment payment)
        {
            if (id != payment.fPaymentId)
            {
                return(BadRequest());
            }

            _context.Entry(payment).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!PaymentExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(NoContent());
        }
Ejemplo n.º 4
0
        public async Task <TEntity> Create(TEntity entity)
        {
            var value = await _dbContext.Set <TEntity>().AddAsync(entity);

            await _dbContext.SaveChangesAsync();

            return(value.Entity);
        }
Ejemplo n.º 5
0
        public async Task <IActionResult> Create([Bind("PaymentDetails,CardOwnerName,CardNumber,ExpirationDate,SecurityCode")] PaymentDetail paymentDetail)
        {
            if (ModelState.IsValid)
            {
                _context.Add(paymentDetail);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            return(View(paymentDetail));
        }
Ejemplo n.º 6
0
        public async Task <IActionResult> NotifyAsync(int paymentid)
        {
            //get from db
            var payment = await db.Payments.FindAsync(paymentid);

            //talk to service
            var delta = await service.GetPaymentDeltaAsync(payment);

            MergePayment(payment, delta);

            //store in db
            await db.SaveChangesAsync();

            return(Ok(paymentid));
        }
Ejemplo n.º 7
0
        public async Task <string> CreateInvoiceAsync(CreateInvoiceDto model)
        {
            var invoice = model.MapToInvoice();

            var faker = new Faker();

            invoice.CreationDate    = DateTime.Now;
            invoice.ExternalOrderId = faker.Commerce.Ean13();
            invoice.PaymentFormUrl  = faker.Internet.Url();

            await _context.AddAsync(invoice);

            await _context.SaveChangesAsync();

            return(invoice.PaymentFormUrl);
        }
Ejemplo n.º 8
0
        public async Task <ActionResult <PaymentDetail> > PaymentCheck(PaymentDetail paymentDetail)
        {
            var sessionId = HttpContext.Session.GetString("ID").ToString();

            var tmpdataval = payTmpData["transaction_price"];

            if (string.IsNullOrEmpty(sessionId))
            {
                return(Unauthorized());
            }
            else
            {
                if ((paymentDetail.card_number.ToString().Where((e) => e >= '0' && e <= '9')
                     .Reverse()
                     .Select((e, i) => ((int)e - 48) * (i % 2 == 0 ? 1 : 2))
                     .Sum((e) => e / 10 + e % 10)) % 10 == 0)
                {
                    _context.PaymentHistory.Add(new PaymentActions
                    {
                        appointment       = payTmpData["appointment"],
                        transaction_price = payTmpData["transaction_price"],
                        card_number       = paymentDetail.card_number,
                        card_cvv          = paymentDetail.card_cvv,
                        card_date         = paymentDetail.card_date,
                        date_transaction  = DateTime.Now
                    });
                    await _context.SaveChangesAsync();

                    return(Ok());
                }
                return(BadRequest());
            }
        }
Ejemplo n.º 9
0
        public async Task Consume(ConsumeContext <EventCreatedEvent> context)
        {
            var eventsPresent = await _paymentContext.EventPrices.AnyAsync(e => e.EventId == context.Message.EventId);

            if (!eventsPresent)
            {
                var e = new Event()
                {
                    ClubId      = context.Message.ClubId,
                    EventId     = context.Message.EventId,
                    PublicPrice = context.Message.PublicPrice,
                    EventPrices = new List <EventPrice>()
                };
                foreach (var eventPricePartialEvent in context.Message.EventPrices)
                {
                    e.EventPrices.Add(new EventPrice()
                    {
                        ClubSubscriptionId = eventPricePartialEvent.ClubSubscriptionId,
                        Price = eventPricePartialEvent.Price
                    });
                }

                await _paymentContext.Events.AddAsync(e);

                await _paymentContext.SaveChangesAsync();
            }
        }
Ejemplo n.º 10
0
        public async Task <PaymentExpVat> PostPaymentVat(PostPaymentVAT model)
        {
            var output = new PaymentExpVat();

            try
            {
                output.OrderCode          = model.OrderCode;
                output.CompanyName        = model.CompanyName;
                output.TaxCode            = model.TaxCode;
                output.BuyerName          = model.BuyerName;
                output.CompanyAddress     = model.CompanyAddress;
                output.ReceiveBillAddress = model.ReceiveBillAddress;
                output.CreateBy           = Guid.Parse(model.UserId);
                output.CreateDate         = DateTime.Now;
                output.LastEditBy         = Guid.Parse(model.UserId);
                output.LastEditDate       = DateTime.Now;
                output.Email = model.Email;
                PaymentContext.PaymentExpVat.Add(output);
                await PaymentContext.SaveChangesAsync();
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return(output);
        }
Ejemplo n.º 11
0
        public async Task <BaseDto <Payment_Output> > Handle(DeletePaymentCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var data = await _context.payments.FindAsync(request.id);

                _context.payments.Remove(data);
                await _context.SaveChangesAsync(cancellationToken);

                return(new BaseDto <Payment_Output>
                {
                    message = "Success Delete Payment Data",
                    success = true,
                    data = new Payment_Output
                    {
                        order_id = data.order_id,
                        transaction_id = data.transaction_id,
                        payment_type = data.payment_type,
                        gross_amount = Convert.ToInt64(data.gross_amount),
                        transaction_time = data.transaction_time,
                        transaction_status = data.transaction_status
                    }
                });
            }
            catch (Exception)
            {
                return(new BaseDto <Payment_Output>
                {
                    message = "Failed Delete Payment Data",
                    success = false,
                    data = null
                });
            }
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Adds the payment to database.
        /// </summary>
        /// <param name="payment">The payment.</param>
        /// <returns></returns>
        public async Task <Payment> AddPaymentToDatabase(Payment payment)
        {
            _context.Payments.Add(payment);
            await _context.SaveChangesAsync();

            return(payment);
        }
        public async Task <IActionResult> GetAsync([FromQuery] TransactionRequest transactionRequest)
        {
            var guid     = Guid.NewGuid();
            var response = new TransactionResponse();

            using var contextTransaction = _paymentContext.Database.BeginTransaction();

            try
            {
                var user =
                    _paymentContext.Users
                    .FirstOrDefault(user => user.Token == transactionRequest.Token);

                var procent   = transactionRequest.Value * _systemProcent;
                var actualSum = procent + transactionRequest.Value;

                if (user.Amount < actualSum)
                {
                    return(BadRequest(new TransactionResponse
                    {
                        Description = "Incorrect value",
                    }));
                }

                user.Amount -= actualSum;

                var transaction = new Transaction
                {
                    Guid    = Guid.NewGuid(),
                    UserId  = user.Id,
                    Value   = transactionRequest.Value,
                    Procent = procent
                };

                await _paymentContext.Transactions.AddAsync(transaction);

                await _paymentContext.SaveChangesAsync();

                var rnd = new Random();
                await Task.Delay(rnd.Next(10000, 20000));

                contextTransaction.Commit();
            }
            catch (Exception)
            {
                return(BadRequest(new TransactionResponse
                {
                    Description = "Transaction error",
                }));
            }

            return(Ok(new TransactionResponse
            {
                Guid = guid.ToString(),
                IsSuccess = true,
            }));
        }
Ejemplo n.º 14
0
 public async Task <int> UpdatePayment(PaymentRequest updateData, string status)
 {
     _paymentContext.PaymentStatus.Add(new PaymentStatus()
     {
         PaymentState = status,
         RequestLogId = updateData
     });
     return(await _paymentContext.SaveChangesAsync());
 }
Ejemplo n.º 15
0
        public async Task <IActionResult> Edit(Payment payment, List <double> Claims, List <string> Texts, List <int> PositionId)
        {
            if (ModelState.IsValid)
            {
                payment.Positions = db.Positions.Where(p => p.PaymentId == payment.PaymentId && PositionId.Contains(p.PositionId)).ToList();

                List <Position> del_pos = db.Positions.Where(p => p.PaymentId == payment.PaymentId && !PositionId.Contains(p.PositionId)).ToList();
                foreach (var pos in del_pos)
                {
                    db.Entry(pos).State = EntityState.Deleted;
                }

                db.Payments.Update(payment);
                double SSum = 0;

                for (int i = 0; i < Claims.Count(); i++)
                {
                    if (i < payment.Positions.Count)
                    {
                        payment.Positions[i].Claim = Claims[i];
                        payment.Positions[i].Text  = Texts[i];
                    }
                    else
                    {
                        Position pos = new Position {
                            PaymentId = payment.PaymentId,
                            Claim     = Claims[i],
                            Text      = Texts[i]
                        };
                        payment.Positions.Add(pos);
                    }
                    SSum += Claims[i];
                }
                payment.Sum = SSum;

                await db.SaveChangesAsync();

                return(RedirectToAction("Withdraw", new { str = "Изменения были сохранены!" }));
            }
            else
            {
                return(View(payment));
            }
        }
Ejemplo n.º 16
0
        public async Task UploadImage(string fileName, string OrderCode)
        {
            var orderItem = await PaymentContext.OrderDetail.FirstOrDefaultAsync(p => p.OrderCode == OrderCode);

            if (orderItem != null)
            {
                orderItem.OrderImage = fileName;
                await PaymentContext.SaveChangesAsync();
            }
        }
 public async Task Handle(OrderCreatedIntegrationEvent @event)
 {
     var message      = @event;
     var paymentModel = new PaymentModel()
     {
         OrderId = message.OrderId, CustomerId = message.CustomerId
     };
     var payment = _paymentContext.Payments.Add(paymentModel);
     await _paymentContext.SaveChangesAsync();
 }
Ejemplo n.º 18
0
        public async Task <bool> CommitAsync()
        {
            var result = (await _context.SaveChangesAsync()) > 0;

            if (!result)
            {
                _notification.Handle(new DomainNotification(string.Empty, "an error occurred"));
            }

            return(result);
        }
Ejemplo n.º 19
0
        public async Task <DeleteCommandDto> Handle(DeleteCommand request, CancellationToken cancellationToken)
        {
            var data = await _context.Payments.FindAsync(request.Id);

            _context.Payments.Remove(data);
            await _context.SaveChangesAsync(cancellationToken);

            return(new DeleteCommandDto {
                Message = "Successfull", Success = true
            });
        }
//Following 2 functions - DoPayment and MakePayment do the same functionality - in 2 different styles
        public async Task <Payment> DoPayment(PaymentRequest paymentRequest)
        {
            //style -> RETURN errors as exceptions

            //validate the accounts
            //these calls themselves throw exceptions if the accounts are not valid
            await _bankClient.ValidateAccount(paymentRequest.payee.accountNumber, paymentRequest.payee.ifscCode);

            await _bankClient.ValidateAccount(paymentRequest.beneficiary.accountNumber, paymentRequest.beneficiary.ifscCode);

            //a hard coded sample check representing a biz logic
            if (paymentRequest.amount > 1000000)
            {
                throw new ProcessingException("Amount exceeded permitted limit", null, paymentRequest);
            }

            //create payment entry with initial status "InProgress"
            Payment payment = new Payment(paymentRequest.beneficiary.name, paymentRequest.beneficiary.accountNumber, paymentRequest.beneficiary.ifscCode,
                                          paymentRequest.payee.name, paymentRequest.payee.accountNumber, paymentRequest.payee.ifscCode, paymentRequest.amount, PaymentStatus.InProgress);

            _context.Payments.Add(payment);
            await _context.SaveChangesAsync();

            //TODO - do the transaction {
            //1. debit payee

            //2. credit beneficiary

            //3. update status in database
            payment._status = PaymentStatus.Completed;
            _context.Payments.Update(payment);
            await _context.SaveChangesAsync();

            //END TODO - do the  transaction
            //}

            return(payment);
        }
Ejemplo n.º 21
0
        public async Task <BaseDto <Payment_Input> > Handle(UpdatePaymentCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var data = await _context.payments.FindAsync(request.id);

                var inputData = request.data.attributes;

                var paymentData = BankPayment.payment(inputData);

                data.payment_type       = paymentData.payment_type;
                data.gross_amount       = paymentData.gross_amount.ToString();
                data.order_id           = paymentData.order_id;
                data.transaction_id     = paymentData.transaction_id;
                data.transaction_time   = paymentData.transaction_time;
                data.transaction_status = paymentData.transaction_status;
                data.updated_at         = paymentData.updated_at;

                await _context.SaveChangesAsync(cancellationToken);

                var ordersData = await _context.orders.FindAsync(paymentData.order_id);

                Publisher.Send(ordersData.user_id.ToString(), "push");

                return(new BaseDto <Payment_Input>
                {
                    message = "Success Update Payment Data",
                    success = true,
                    data = new Payment_Input
                    {
                        order_id = data.order_id,
                        payment_type = data.payment_type,
                        gross_amount = Convert.ToInt64(data.gross_amount),
                        bank = inputData.bank
                    }
                });
            }
            catch (Exception)
            {
                return(new BaseDto <Payment_Input>
                {
                    message = "Failed Update Payment Data",
                    success = false,
                    data = null
                });
            }
        }
Ejemplo n.º 22
0
        public async Task CreateRequestForCommandAsync <T>(string id)
        {
            var exists = await ExistAsync(id);

            var request = exists
                ? throw new InvalidOperationException($"Request with {id} already exists")
                : new ClientRequest
                                {
                                    Id   = id,
                                    Name = typeof(T).Name,
                                    Time = DateTime.UtcNow
                                };

            _context.Add <ClientRequest>(request);

            await _context.SaveChangesAsync();
        }
Ejemplo n.º 23
0
        public async Task Consume(ConsumeContext <UserCreatedEvent> context)
        {
            var user = await _paymentContext.Users.FindAsync(context.Message.UserId);

            if (user == null)
            {
                var customer = _stripeService.CreateCustomer(context.Message.Email);
                user = new User()
                {
                    UserId       = context.Message.UserId,
                    StripeUserId = customer.Id
                };
                await _paymentContext.Users.AddAsync(user);

                await _paymentContext.SaveChangesAsync();
            }
        }
Ejemplo n.º 24
0
        public async Task <OrderDTO> DeleteOrderByOrderCode(string OrderCode)
        {
            var orderMaster = await PaymentContext.Order.FirstOrDefaultAsync(p => p.OrderCode == OrderCode);

            if (orderMaster != null)
            {
                PaymentContext.Order.Remove(orderMaster);
                await PaymentContext.SaveChangesAsync();
            }
            var orderDetail = await PaymentContext.OrderDetail.FirstOrDefaultAsync(p => p.OrderCode == OrderCode);

            if (orderDetail != null)
            {
                PaymentContext.OrderDetail.Remove(orderDetail);
                await PaymentContext.SaveChangesAsync();
            }
            return(new OrderDTO());
        }
Ejemplo n.º 25
0
        public async Task <PaymentDTO> Handle(DeletePaymentCommand request, CancellationToken cancellationToken)
        {
            var data = await _context.payment.FindAsync(request.Id);

            if (data == null)
            {
                return(null);
            }
            else
            {
                _context.payment.Remove(data);
                await _context.SaveChangesAsync();

                return(new PaymentDTO {
                    Message = "Successfully deleted data", Success = true
                });
            }
        }
Ejemplo n.º 26
0
        public async Task <UpdateCommandDto> Handle(UpdateCommand request, CancellationToken cancellation)
        {
            var payment = _context.Payments.Find(request.Data.Attributes.Id);

            payment.Order_Id           = request.Data.Attributes.Order_Id;
            payment.Transaction_Id     = request.Data.Attributes.Transaction_Id;
            payment.Payment_Type       = request.Data.Attributes.Payment_Type;
            payment.Gross_Amount       = request.Data.Attributes.Gross_Amount;
            payment.Transaction_Time   = request.Data.Attributes.Transaction_Time;
            payment.Transaction_Status = request.Data.Attributes.Transaction_Status;

            await _context.SaveChangesAsync(cancellation);

            return(new UpdateCommandDto
            {
                Success = true,
                Message = "Payment successfully updated"
            });
        }
Ejemplo n.º 27
0
        public async Task MakePaymentAsync(Guid sessionId, Card paymentCard)
        {
            Payment payment = await _context.Payments
                              .Include(payment => payment.AssociatedSession)
                              .FirstOrDefaultAsync(payment => payment.SessionId.Equals(sessionId) &&
                                                   payment.CardNumber == null &&
                                                   payment.AssociatedSession.ExpirationDateTime > DateTime.Now);

            if (payment == null)
            {
                throw new PaymentException();
            }

            payment.CardNumber = paymentCard.Number;
            _context.Payments.Update(payment);
            if (await _context.SaveChangesAsync() == 0)
            {
                throw new PaymentException();
            }
        }
        public async Task <BaseDTO> Handle(DeletePaymentCommand request, CancellationToken cancellationToken)
        {
            var data = await _context.Payments.FindAsync(request.Id);

            if (data != null)
            {
                _context.Remove(data);
                await _context.SaveChangesAsync();

                return(new BaseDTO
                {
                    Message = "Data has been deleted",
                    Success = true
                });
            }
            else
            {
                return(null);
            }
        }
Ejemplo n.º 29
0
        public async Task <BaseDto <Payment_Input> > Handle(CreatePaymentCommand request, CancellationToken cancellationToken)
        {
            var data = request.data.attributes;

            var paymentData = BankPayment.payment(data);

            _context.payments.Add(paymentData);
            await _context.SaveChangesAsync(cancellationToken);

            var ordersData = await _context.orders.FindAsync(paymentData.order_id);

            Publisher.Send(ordersData.user_id.ToString(), "email");

            return(new BaseDto <Payment_Input>
            {
                message = "Success Add Payment Data",
                success = true,
                data = request.data.attributes
            });
        }
        public async Task Consume(ConsumeContext <ClubSubscriptionCreatedEvent> context)
        {
            var subscription = await _paymentContext.ClubSubscriptions.FindAsync(context.Message.ClubSubscriptionId);

            if (subscription == null)
            {
                Product product = _stripeService.CreateProduct(context.Message.ClubId, context.Message.Name);
                Price   price   = _stripeService.CreatePrice(context.Message.Price, product);
                subscription = new ClubSubscription()
                {
                    ClubSubscriptionId = context.Message.ClubSubscriptionId,
                    ClubId             = context.Message.ClubId,
                    StripePriceId      = price.Id,
                    StripeProductId    = product.Id,
                };
                await _paymentContext.ClubSubscriptions.AddAsync(subscription);

                await _paymentContext.SaveChangesAsync();
            }
        }