示例#1
0
        public static void SeedProcedure()
        {
            PaymentContext context = new PaymentContext();

            int entitiesToGenerate = SetEntitiesToGenerate();

            Console.WriteLine("Generating values...");

            User[] userEntities = GenerateUsers(entitiesToGenerate);
            context.Users.AddRange(userEntities);

            CreditCard[] creditCards = GenerateUsersCreditCards(entitiesToGenerate);
            context.CreditCards.AddRange(creditCards);

            BankAccount[] bankAccounts = GenerateBankAccounts(entitiesToGenerate);
            context.BankAccounts.AddRange(bankAccounts);

            context.SaveChanges();

            // Add payments methods
            PaymentMethod[] paymentMethods = GeneratePaymentMethods(context);
            context.PaymentMethods.AddRange(paymentMethods);

            context.SaveChanges();

            Console.WriteLine("Seed data successful!");
        }
示例#2
0
        public Payment Create(Payment payment)
        {
            var user = _user_context.Users.Find(payment.UserId);

            if (user == null)
            {
                throw new AppException("User not found, wrong id or id field is missing");
            }

            if (payment.Amount <= 0)
            {
                throw new AppException("Amount required");
            }
            else if (payment.Amount > 200000)
            {
                throw new AppException("Maximum value is 200000");
            }

            payment.Date = System.DateTime.Now;
            _context.Payments.Add(payment);
            _context.SaveChanges();


            //update user balance by payment amount

            user.Balance += payment.Amount;
            _user_context.Users.Update(user);
            _user_context.SaveChanges();


            return(payment);
        }
        /// <summary>
        /// Creates a payment. Creates new customer or adds payment to existing customer
        /// </summary>
        /// <param name="id"></param>
        /// <param name="email"></param>
        /// <param name="firstName"></param>
        /// <param name="lastName"></param>
        /// <param name="cardnumber"></param>
        /// <param name="month"></param>
        /// <param name="year"></param>
        /// <param name="cvc"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public async Task <dynamic> PayByCreditCard(string id, string email, string firstName, string lastName, string cardnumber, int month, int year, string cvc, int value)
        {
            try
            {
                StripeConfiguration.ApiKey = key;
                Models.Customer customer = await context.customers.Where(c => c.accountId == id).FirstOrDefaultAsync();

                Stripe.Customer paymentCustomer = new Stripe.Customer();

                //create new customer if it doesn't exists
                if (customer == null)
                {
                    paymentCustomer = await PostCustomer(id, email, firstName, lastName);

                    customer            = new Models.Customer();
                    customer.accountId  = id;
                    customer.customerId = paymentCustomer.Id;
                    await context.customers.AddAsync(customer);

                    context.SaveChanges();
                }

                //setup token options
                TokenCreateOptions optionstoken = new TokenCreateOptions
                {
                    Card = new TokenCardOptions
                    {
                        Number   = cardnumber,
                        ExpMonth = month,
                        ExpYear  = year,
                        Cvc      = cvc
                    }
                };

                TokenService tokenService = new TokenService();
                Token        token        = await tokenService.CreateAsync(optionstoken);

                //setup payment options
                ChargeCreateOptions options = new ChargeCreateOptions
                {
                    Amount      = value,
                    Currency    = "eur",
                    Description = "Parking spot reservation. Date: " + DateTime.Now.ToString("dd/MM/yyyy HH:mm"),
                    Source      = token.Id,
                    Customer    = customer.customerId
                };

                ChargeService service = new ChargeService();
                Charge        charge  = await service.CreateAsync(options);

                return(charge.Paid);
            }
            catch (Exception)
            {
                throw;
            }
        }
示例#4
0
        private void ButtonRemoveClicked(object sender, EventArgs e)
        {
            if (!_db.Payments.Any())
            {
                return;
            }

            _db.Payments.Remove(_view.ListBoxDataSelectedItem);
            _db.SaveChanges();
        }
示例#5
0
 public ActionResult Create(Payment payment)
 {
     if (ModelState.IsValid)
     {
         _ctxPayment.Payments.Add(payment);
         _ctxPayment.SaveChanges();
         return(RedirectToAction("Index"));
     }
     return(View(payment));
 }
 public void Add(Payment item)
 {
     try
     {
         _context.Payment.Add(item);
         _context.SaveChanges();
     }
     catch (Exception)
     {
         throw;
     }
 }
        public void GivenAPaymentRecordIdTheExistsInTheContextIsProvided_WhenGettingIt_ThenItReturnsThePaymentRecord()
        {
            // Given

            using var localTestContext = new PaymentContext(new DbContextOptionsBuilder <PaymentContext>()
                                                            .UseInMemoryDatabase(databaseName: $"PaymentDatabase-Test-{Guid.NewGuid()}")
                                                            .Options);

            var mockedLogger        = Substitute.For <ILogger <Domain.PaymentRepository.PaymentRepository> >();
            var mockedDataEncryptor = Substitute.For <IDataEncryptor>();

            var realPaymentRepository = new Domain.PaymentRepository.PaymentRepository(mockedLogger, localTestContext, mockedDataEncryptor);

            var expectedId = Guid.NewGuid();

            var expectedPaymentRecord = new PaymentRecord {
                PaymentGatewayId = expectedId
            };

            localTestContext.Payments.Add(expectedPaymentRecord);
            localTestContext.SaveChanges();

            // When

            var response = realPaymentRepository.Get(expectedId).GetAwaiter().GetResult();

            // Then

            response.Should().NotBeNull();
            response.Should().BeOfType <PaymentRecord>();
            response.PaymentGatewayId.Should().Be(expectedId);
        }
示例#8
0
        public void Confirm(Guid paymentId)
        {
            var payment = _paymentContext.Payments.FirstOrDefault(p => p.ID == paymentId);

            payment.State = UserPaymentState.Confirmed;

            _paymentContext.Payments.Attach(payment);

            var entry = _paymentContext.Entry(payment);

            //entry.State = EntityState.Modified;

            entry.Property(e => e.State).IsModified = true;

            _paymentContext.SaveChanges();
        }
示例#9
0
        protected void BtnSave_Click(object sender, EventArgs e)
        {
            using (var ctx = new PaymentContext())
            {
                var mode = new PaymentMode();

                mode.Mode = TxtMode.Text;

                int UserId = Convert.ToInt32(((System.Web.Security.FormsIdentity)HttpContext.Current.User.Identity).Ticket.UserData);

                mode.UserProfileId = UserId;

                mode.IsDeleted = false;

                if (ctx.PaymentModes.Any(x => (x.Mode == TxtMode.Text) && x.UserProfileId == UserId))
                {
                    LblMessage.Text = null;
                    LblError.Text   = "* Payment mode already exists!";
                }
                else
                {
                    ctx.PaymentModes.Add(mode);
                    ctx.SaveChanges();
                    LblError.Text   = null;
                    LblMessage.Text = "Payment mode Added";
                }
            }
            GridViewModes.DataBind();
            TxtMode.Text = null;
        }
        protected void BtnSave_Click(object sender, EventArgs e)
        {
            bool amountIsValid = true;

            using (var ctx = new PaymentContext())
            {
                var payment = new Payment();
                payment.TransactionDate = DateTime.Parse(TxtDate.Text);

                payment.UserProfileId = Convert.ToInt32(((System.Web.Security.FormsIdentity)HttpContext.Current.User.Identity).Ticket.UserData);
                try
                {
                    payment.Amount = decimal.Parse(TxtAmount.Text);
                }
                catch
                {
                    amountIsValid = false;
                }

                payment.CategoryId = int.Parse(DropDownCategory.SelectedValue);

                payment.IsCredit = CheckBoxIsCredit.Checked;

                try
                {
                    payment.BeneficiaryId = int.Parse(DropDownBeneficiary.SelectedValue);
                }
                catch
                {
                    payment.BeneficiaryId = null;
                }

                payment.PaymentModeId = int.Parse(DropDownMode.SelectedValue);

                payment.PaymentDetails = TxtDetails.Text;

                if (amountIsValid)
                {
                    ctx.Payments.Add(payment);
                    ctx.SaveChanges();
                    TxtDate.Text   = null;
                    TxtAmount.Text = null;
                    DropDownCategory.SelectedValue    = null;
                    CheckBoxIsCredit.Checked          = false;
                    DropDownBeneficiary.SelectedValue = null;
                    TxtDetails.Text = null;
                    LblError.Text   = null;
                    LblMessage.Text = "Payment Added";
                }
                else
                {
                    if (!amountIsValid)
                    {
                        LblError.Text = "Invalid Amount!";
                    }
                }
            }
        }
示例#11
0
 public async Task <PaymentLog> SavePaymentLog(PaymentLog model)
 {
     if (model != null)
     {
         PaymentContext.PaymentLog.Add(model);
         PaymentContext.SaveChanges();
     }
     return(model);
 }
示例#12
0
        public bool Delete(int id)
        {
            try
            {
                var paymentItem = context.Payments.Find(id);

                if (paymentItem != null)
                {
                    context.Payments.Remove(paymentItem);
                    context.SaveChanges();
                    return(true);
                }
                return(false);
            }
            catch (Exception)
            {
                throw;
            }
        }
        public void Post(string buyerId, [FromBody] decimal amount)
        {
            Guid guid = new Guid(buyerId);

            var userAccount = _context.Accounts.Single(x => x.BuyerId == guid);

            userAccount.AmountAvailable += amount;
            _context.SaveChanges();

            _endpoint.Publish(new AccountDepositIntegrationEvent("bob", amount, userAccount.AmountAvailable));
        }
示例#14
0
        public async Task <Order> UpgradePaymentType(string orderCode, int PaymentTypeId)
        {
            var orderMaster = await PaymentContext.Order.FirstOrDefaultAsync(p => p.OrderCode == orderCode);

            if (orderMaster != null)
            {
                orderMaster.PaymentType_ID = PaymentTypeId;
                PaymentContext.SaveChanges();
            }
            return(orderMaster);
        }
示例#15
0
        public async Task <Order> FinishUpgradeBrand(string orderCode, int PaymentStatusId)
        {
            var output = new Order();
            var item   = await PaymentContext.Order.FirstOrDefaultAsync(p => p.OrderCode == orderCode);

            if (item != null)
            {
                item.PaymentStatus_ID = PaymentStatusId;
                PaymentContext.SaveChanges();
            }
            return(output);
        }
示例#16
0
        public static void InitializeDbForTests(PaymentContext db)
        {
            // Use a lock to avoid this method calling twice
            // Ref: https://github.com/dotnet/aspnetcore/issues/20307
            lock (_lock)
            {
                if (!_hasInstance)
                {
                    db.Users.AddRange(GetSeedingUsers());
                    db.SaveChanges();
                    foreach (var user in db.Users)
                    {
                        db.UserAccounts.Add(GetSeedingAccountForUser(user.Id));
                        db.Payments.AddRange(GetSeedingPaymentsForUser(user.Id));
                    }
                    db.SaveChanges();

                    _hasInstance = true;
                }
            }
        }
示例#17
0
        private void ViewAddButtonClicked(object sender, EventArgs e)
        {
            Payment payment = new Payment
            {
                Name            = _view.NameText,
                Liter           = double.Parse(_view.LiterText),
                Pay             = double.Parse(_view.PayText),
                PaymentDateTime = DateTime.Parse(_view.PaymentDateTimeText)
            };

            _db.Payments.Add(payment);
            _db.SaveChanges();
        }
示例#18
0
        // [ActionName ("Create")] su dung cai nay khi phuong thuc Create ben duoi khac ten, vi du CreatePayment()
        public IActionResult Create(Payment payment)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    context.Payment.Add(payment);
                    context.SaveChanges();
                    ViewBag.Msg = "Congratulation!";
                }
                else
                {
                    ViewBag.Msg = "Fail...";
                }
            }
            catch (Exception e)
            {
                ViewBag.Msg = e.Message;
            }

            return(View());
        }
示例#19
0
        private void ViewAddButtonClick(object sender, EventArgs e)
        {
            Payment payment = new Payment
            {
                Name          = _view.NameText,
                Liter         = _view.LiterText,
                PricePerLiter = _view.PricePerLiterText,
                Price         = _view.PriceText,
                DateTime      = DateTime.Now
            };

            _db.payments.Add(payment);
            _db.SaveChanges();
        }
        internal static void UpdateProductsFromEventProduct(EventProduct eventProduct, PaymentContext context)
        {
            // get the list of all Products associated with this record
            var products = context.Product.Where(p => p.EventProductId == eventProduct.EventProductId && p.StateCode == 0).ToList();

            // update their amount fields
            foreach (var curProduct in products)
            {
                curProduct.AmountNonreceiptable = eventProduct.AmountNonReceiptable ?? 0;
                curProduct.AmountReceipted      = eventProduct.AmountReceipted ?? 0;
                curProduct.SyncDate             = null;
                context.Update(curProduct);
            }

            context.SaveChanges();
        }
        internal static void UpdateTicketsFromEventTicket(EventTicket eventTicket, PaymentContext context)
        {
            // get the list of all Tickets associated with this record
            var tickets = context.Ticket.Where(t => t.EventTicketId == eventTicket.EvenTicketId && t.StateCode == 0);

            // update their amount fields
            foreach (var curTicket in tickets)
            {
                curTicket.AmountNonreceiptable = eventTicket.AmountNonReceiptable ?? 0;
                curTicket.AmountReceipted      = eventTicket.AmountReceipted ?? 0;
                curTicket.SyncDate             = null;
                context.Update(curTicket);
            }

            context.SaveChanges();
        }
示例#22
0
        public async Task <PaymentDto> Handle(UpdatePaymentCommand request, CancellationToken cancellationToken)
        {
            var data = await _context.AllPayments.FindAsync(request.Data.Attributes.id);

            data.transaction_id   = request.Data.Attributes.transaction_id;
            data.payment_type     = request.Data.Attributes.payment_type;
            data.gross_amount     = request.Data.Attributes.gross_amount;
            data.transaction_time = DateTime.Now;
            _context.SaveChanges();

            return(new PaymentDto()
            {
                message = "Payment has been modified",
                success = true
            });
        }
示例#23
0
        public ActionResult <IEnumerable <string> > PostPayment(Payment payment)
        {
            if (payment.cardNumber != null && payment.expiryDate != null && payment.amount > 0 && payment.currency != null && payment.cvv != null)
            {
                payment.status = obtainStatus(payment);
                _paymentContext.Payment.Add(payment);
                _paymentContext.SaveChanges();

                Log log = new Log(DateTime.Now, "Merchant processed payment " + payment.paymentID);
                _logContext.Log.Add(log);
                _logContext.SaveChanges();

                return(new string[] { "Payment ID: " + payment.paymentID.ToString(), "Status: " + payment.status });
            }
            return(new string[] { "Some fields are missing!" });
        }
示例#24
0
        //Generate the next payment to 30 days from todays date
        public void GenerateNextPayment()
        {
            Payment      Next;
            Subscription Sub;

            using (var db = new PaymentContext())
            {
                Next        = db.Payment.Create();
                Next.Amount = 15;
                Next.Date   = DateTime.Now.AddDays(30);
                Next.Status = "pending";
                Sub         = db.Subscription.Include("Payments").First(x => x.UserProfileId.Equals(WebSecurity.CurrentUserId));
                Sub.Payments.Add(Next);
                db.SaveChanges();
            }
        }
示例#25
0
        //Register a new subscription
        public void CreateSub()
        {
            Subscription NewSubscription;

            using (var db = new SubscriptionContext())
            {
                NewSubscription          = db.Subscription.Create();
                NewSubscription.Status   = "active";
                NewSubscription.Payments = new List <Payment>();

                using (var db2 = new PaymentContext())
                {
                    Payment FirstPayment = db2.Payment.Create();
                    FirstPayment.Amount = 15.0f;
                    FirstPayment.Date   = DateTime.Now;
                    FirstPayment.Status = "cancelled";
                    //  FirstPayment.Subscription = NewSubscription;
                    //  FirstPayment.SubscriptionId = NewSubscription.UserProfileId;
                    db2.Payment.Add(FirstPayment);


                    Payment SecondPayment = db2.Payment.Create();
                    SecondPayment.Amount = 15.0f;
                    SecondPayment.Date   = DateTime.Now.AddDays(30.0);
                    SecondPayment.Status = "pending";
                    //   SecondPayment.Subscription = NewSubscription;
                    //   SecondPayment.SubscriptionId = NewSubscription.UserProfileId;
                    db2.Payment.Add(SecondPayment);


                    //Store subscription info
                    using (var db3 = new UsersContext())
                    {
                        UserProfile CurrentUser = db3.UserProfiles.Include("Subscription").First(x => x.UserId.Equals(WebSecurity.CurrentUserId));
                        CurrentUser.Subscription = NewSubscription;
                        NewSubscription.Payments.Add(FirstPayment);
                        NewSubscription.Payments.Add(SecondPayment);
                        NewSubscription.UserProfile   = CurrentUser;
                        NewSubscription.UserProfileId = CurrentUser.UserId;
                        db3.SaveChanges();
                    }
                    db2.SaveChanges();
                    db.Subscription.Add(NewSubscription);
                    db.SaveChanges();
                }
            }
        }
示例#26
0
        public IActionResult Create(Payment payment, int pay_id, List <IFormFile> file, List <double> Claim, List <string> Text)
        {
            if (ModelState.IsValid)
            {
                db.Payments.Add(payment);
                double SSum = 0;

                for (int i = 0; i < Claim.Count(); i++)
                {
                    Position pos = new Position {
                        PaymentId = payment.PaymentId
                    };

                    if (i < file.Count() && file[i] != null)
                    {
                        byte[] file_byte = null;

                        //считываем переданный файл в массив байтов
                        using (var binaryReader = new BinaryReader(file[i].OpenReadStream()))
                        {
                            file_byte = binaryReader.ReadBytes((int)file[i].Length);
                        }

                        //установка массива байтов
                        pos.FileByte = file_byte;
                        pos.FileType = file[i].ContentType;
                        pos.FileName = file[i].FileName;
                    }
                    pos.Claim = Claim[i];
                    SSum     += Claim[i];
                    pos.Text  = Text[i];
                    db.Positions.Add(pos);
                }

                payment.Sum = SSum;

                db.SaveChanges();
                return(RedirectToAction("Withdraw", new { str = "Заявка, " + payment.FullName + ", была успешно создана!" }));
            }
            else
            {
                ViewBag.NPos = 1;
                return(View(payment));
            }
        }
示例#27
0
        public async Task <Guid> RecordPaymentAsync(PaymentRequest payment)
        {
            DateTime timeMark     = DateTime.Now;
            Guid     newSessionId = (await _context.Sessions.AddAsync(new Session()
            {
                CreationDateTime = timeMark,
                ExpirationDateTime = timeMark.Add(SessionExpirationTimeSpan)
            })).Entity.Id;
            await _context.Payments.AddAsync(new Payment()
            {
                SessionId = newSessionId,
                Sum       = payment.Sum,
                Purpose   = payment.Purpose
            });

            _context.SaveChanges();
            return(newSessionId);
        }
示例#28
0
        //Call this function when the user pays his pending invoices and reactives his subscription
        public void PayAllOverdues()
        {
            List <Payment> Payments;

            using (var db = new PaymentContext())
            {
                Payments = db.Payment.Where(x => x.SubscriptionId.Equals(WebSecurity.CurrentUserId) && x.Status.Equals("overdue")).ToList();

                foreach (var debt in Payments)
                {
                    debt.Status          = "cancelled";
                    db.Entry(debt).State = EntityState.Modified;
                }
                db.SaveChanges();
                GenerateNextPayment();
                ReactiveSubscription(WebSecurity.CurrentUserId);
            }
        }
        internal static void UpdateSponsorshipsFromEventSponsorship(EventSponsorship eventSponsorship,
                                                                    PaymentContext context)
        {
            // get the list of all Sponsorships associated with this record
            var sponsorships =
                context.Sponsorship.Where(s => s.EventSponsorshipId == eventSponsorship.EventSponsorshipId && s.StateCode == 0).ToList();

            // update their amount fields
            foreach (var curSponsorship in sponsorships)
            {
                curSponsorship.AmountNonreceiptable = eventSponsorship.AmountNonReceiptable ?? 0;
                curSponsorship.AmountReceipted      = eventSponsorship.AmountReceipted ?? 0;
                curSponsorship.SyncDate             = null;
                context.Update(curSponsorship);
            }

            context.SaveChanges();
        }
示例#30
0
        public ActionResult PaymentForm([Bind(Exclude = "Id")] Forms f)
        {
            if (!ModelState.IsValid)
            {
                return(View());
            }

            pm.Form.Add(f);
            pm.SaveChanges();

            var id = pm.Form.Max(x => x.Id);

            return(View("ListNP", pm.GetPos(id).ToList()));
        }