// PUT: odata/PaymentDetails(5)
        public async Task <IHttpActionResult> Put([FromODataUri] int key, Delta <PaymentDetail> patch)
        {
            Validate(patch.GetEntity());

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

            PaymentDetail paymentDetail = await db.PaymentDetails.FindAsync(key);

            if (paymentDetail == null)
            {
                return(NotFound());
            }

            patch.Put(paymentDetail);

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

            return(Updated(paymentDetail));
        }
Пример #2
0
        public IHttpActionResult GetPaymentDetail(int id)
        {
            PaymentDetail paymentDetail = db.PaymentDetails.Find(id);

            if (paymentDetail == null)
            {
                return(NotFound());
            }

            var resultSet = new
            {
                paymentDetail.PaymentDetailId,
                paymentDetail.CustomerId,
                paymentDetail.CCNumber,
                paymentDetail.ExpDate,
                paymentDetail.CCV,
                paymentDetail.StreetAddress,
                paymentDetail.City,
                paymentDetail.State,
                paymentDetail.Zip
            };

            return(Ok(resultSet));
        }
Пример #3
0
 public async Task UpdatePaymentDetail(PaymentDetail paymentDetail)
 {
     await this._ctx.SaveChangesAsync();
 }
Пример #4
0
        public bool MakePayment(PaymentDetail paymentDetail, string token)
        {
            // TODO: Implements

            return(true);
        }
        public IHttpActionResult BuyMotorWeb([FromBody] MotorDetails motorDetails)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest("Invalid Motor details"));
            }

            var userFound = _context.AspNetUsers.FirstOrDefault(u => u.Email == motorDetails.Email || u.PhoneNumber == motorDetails.PhoneNo);

            var regTime   = DateTime.UtcNow;
            var timeStamp = new DateTimeOffset(regTime).ToUnixTimeSeconds();


            if (userFound == null)
            {
                try
                {
                    //var user = Mapper.Map<UserInputDTO, AspNetUser>(userInput);
                    userFound = new AspNetUser
                    {
                        Firstname            = motorDetails.Firstname,
                        Surname              = motorDetails.Surname,
                        Email                = motorDetails.Email,
                        PhoneNumber          = motorDetails.PhoneNo,
                        UserName             = motorDetails.Email,
                        IsCoperate           = motorDetails.UsageType.ToString() == "2",
                        RegCode              = motorDetails.RegNo,
                        CompanyName          = motorDetails.companyName != "" ? motorDetails.companyName : null,
                        RegisterationDate    = regTime,
                        Address              = motorDetails.InsuredAddress,
                        EmailConfirmed       = false,
                        PhoneNumberConfirmed = false,
                        TwoFactorEnabled     = false,
                        LockoutEnabled       = false,
                        AccessFailedCount    = 0,
                        IsMobile             = false,
                        IsDeleted            = false,
                        Id = generateID() + "-" + RandomID()
                    };
                    _context.AspNetUsers.Add(userFound);
                    _context.SaveChanges();

                    userFound = _context.AspNetUsers.FirstOrDefault(u => u.Email == motorDetails.Email);                     // || u.PhoneNumber == motorDetails.PhoneNo
                }
                catch (DbEntityValidationException e)
                {
                    return(Ok(e));
                }
            }


            //save the vehicle details
            var vehicledetailsInput = new VehicledetailsInputDTO
            {
                ChasisNo = motorDetails.ChasisNo,
                EngineNo = motorDetails.EngineNo,
                RegNo    = motorDetails.RegNo
            };

            var vehicleDetail = Mapper.Map <VehicledetailsInputDTO, VehicleDetail>(vehicledetailsInput);

            _context.VehicleDetails.Add(vehicleDetail);
            _context.SaveChanges();

            var vehicleDetailFound = _context.VehicleDetails.FirstOrDefault(vd => vd.RegNo == motorDetails.RegNo && vd.ChasisNo == motorDetails.ChasisNo && vd.EngineNo == motorDetails.EngineNo);
            //
            //save the vehicle
            var vehicle = new Vehicle
            {
                UserID          = userFound.Id,
                VehicleMake     = motorDetails.VehicleMake,
                VehicleModel    = motorDetails.VehicleModel,
                VehicleDetailID = vehicleDetailFound.ID,
                VehicleDate     = motorDetails.VehicleDate,
                VehicleType     = vehicleType(motorDetails.UsageType.ToString()),
                CoverType       = userType(motorDetails.UserType.ToString()) + " |" + motorClass(motorDetails.MotorClass.ToString()) + " |" + cardDuration(motorDetails.carduration.ToString()),
                VehicleValue    = motorDetails.VehicleValue.ToString()
            };

            // var vehicle = Mapper.Map<VehicleInputDTO, Vehicle>(vehiclerInput);
            _context.Vehicles.Add(vehicle);
            _context.SaveChanges();

            var vehicleFound = _context.Vehicles.FirstOrDefault(v => v.VehicleDetailID == vehicleDetailFound.ID);

            // var intPremium = Convert.ToDouble(motorDetails.premium);

            byte[] filebaseDocBytes = Convert.FromBase64String(motorDetails.filebase64doc);
            byte[] filebaseIdBytes  = Convert.FromBase64String(motorDetails.filebase64ID);

            //var transRef = "NSI" + RandomID() + "-" + generateID();
            var transRef = "NSI" + generateID();

            transRef = transRef.Substring(0, 11);
            var custDocument = new CustDocument
            {
                IdType          = "motor",
                FileType        = motorDetails.filetypeID,
                FileTypeLicence = motorDetails.filetypedoc,
                IsAchived       = false,
                UserId          = userFound.Id,
                UploadedDate    = regTime,
                IdMeans         = filebaseIdBytes,
                IdLicense       = filebaseDocBytes,
                TransRef        = transRef
            };

            _context.CustDocuments.Add(custDocument);
            _context.SaveChanges();

            // Check if there is a promo
            //if (modelDetails.IsDstv)
            //{

            //}
            //Insert  Quote table // approve should be updated after payment is done
            var quote = new Quote()
            {
                UserId             = userFound.Id,
                VehicleID          = vehicleFound.ID,
                InitialPremium     = (decimal)motorDetails.premium,
                PurchaseDiscount   = (decimal)motorDetails.purchaseDiscount,
                FinalPremium       = ((decimal)motorDetails.premium - (decimal)motorDetails.purchaseDiscount),
                FinalPremiumString = ((decimal)motorDetails.premium - (decimal)motorDetails.purchaseDiscount).ToString(),
                Approved           = false,
                IsComprehensive    = motorClass(motorDetails.MotorClass.ToString()) == "Comprehensive",
                CanPay             = true,
                Cover           = cardDuration(motorDetails.carduration.ToString()),
                IsMobile        = false,
                TransactionDate = regTime,
                IsRenewal       = false,
                isDeleted       = false,
                // MyTimestamp = Convert.FromBase64String(timeStamp.ToString()),
                BizId          = 1,
                HasExcess      = false,
                UsageType      = usageType(motorDetails.UsageType.ToString()),
                Referral       = motorDetails.reference,
                Name           = motorDetails.Surname + " " + motorDetails.Firstname,
                Coverperiod    = motorDetails.carduration,
                InsuredName    = motorDetails.Surname + " " + motorDetails.Firstname,
                InsuredAddress = motorDetails.InsuredAddress,
                Reference      = (motorDetails.reference == null || motorDetails.reference == "") ? "N/A" : motorDetails.reference,
                IsLive         = false,
                StateId        = Convert.ToInt32(motorDetails.state),
                LgaId          = Convert.ToInt32(motorDetails.lga)
            };

            _context.Quotes.Add(quote);
            _context.SaveChanges();

            var quoteFound = _context.Quotes.FirstOrDefault(q => q.UserId == userFound.Id && q.VehicleID == vehicleFound.ID);

            // Add to payment table
            var motorPayment = new PaymentDetail()
            {
                UserID          = userFound.Id,
                txtRef          = transRef,
                QuoteID         = quoteFound.ID,
                amount          = quoteFound.FinalPremium,
                AmountString    = quoteFound.FinalPremium.ToString(),
                TransactionDate = regTime
            };

            _context.PaymentDetails.Add(motorPayment);
            _context.SaveChanges();

            //update promo table if promo
            //var promo = _context.Promos.FirstOrDefault(p=>p.Code == motorDetails.promoCode);
            //if (promo != null)
            //{
            //    promo.transactionRef = motorDetails.promoCode;
            //    _context.SaveChanges();
            //}


            var motorPaymentFound = _context.PaymentDetails.FirstOrDefault(p => p.UserID == userFound.Id && p.txtRef == transRef);

            var intPremium  = (int)quoteFound.FinalPremium;
            var premiumKobo = intPremium * 100;


            var productID = "6205";

            var pay_item_id = "101";

            var payment_redirect_url = ConfigurationManager.AppSettings["return_url"];

            var MAC_KEY = ConfigurationManager.AppSettings["MAC_KEY"];
            // txn_ref + product_id + pay_item_id + amount + site_redirect_url + MacKey
            // var Hash = (transRef + quoteFound.VehicleID.ToString() + motorPaymentFound.ID.ToString() + intPremium.ToString() + payment_redirect_url + MAC_KEY);
            var Hash = (transRef + productID + pay_item_id + premiumKobo.ToString() + payment_redirect_url + MAC_KEY);

            Hash = GenSHA512(Hash);

            var motorResponse = new MotorResponseDTO
            {
                businessClass    = "motor",
                customerName     = userFound.Surname + " " + userFound.Firstname,
                hash             = Hash,
                premium          = premiumKobo,
                premiumString    = intPremium.ToString(),
                quoteID          = quoteFound.ID,
                reference        = (motorDetails.reference == null || motorDetails.reference == "") ? "N/A" : motorDetails.reference,
                transactionRefNo = transRef,
                vehicledetail    = vehicle.VehicleMake + " " + vehicle.VehicleModel + " " + vehicle.VehicleDate,
                payItemId        = pay_item_id
                                   // payItemId = motorPaymentFound.ID.ToString()
            };

            //send email
            //var description = userType(motorDetails.UserType.ToString()) + " |" +
            //				  motorClass(motorDetails.MotorClass.ToString()) + " |" +
            //				  cardDuration(motorDetails.carduration.ToString());

            //SendEmail(userFound, motorDetails, description, intPremium.ToString("C"));


            return(Ok(motorResponse));
        }
 public bool AddPayment(PaymentDetail paymentDetail)
 {
     paymentDetails.Add(paymentDetail);
     return(true);
 }
        public void CreateTransaction_IsSuccessful()
        {
            //Arrange
            var order = new Order()
            {
                BillingInformation = new DeliveryInformation()
                {
                    Address1           = "1 Beehive Avenue",
                    Address2           = "Somewhere",
                    CityTown           = "Wellington",
                    Country            = "New Zealand",
                    DeliveryMethod     = "Standard",
                    Email              = "*****@*****.**",
                    FirstName          = "John",
                    LastName           = "Smith",
                    Phone              = "02112345678",
                    PostalCode         = "6021",
                    TermsAndConditions = true
                },
                Customer        = null,
                OrderedProducts = new List <OrderedProduct>()
                {
                    new OrderedProduct()
                    {
                        Price     = 200.00m,
                        ProductId = 1,
                        SizeId    = 1
                    }
                },
                OrderStatus     = "Ongoing",
                PaymentReceived = true,
                ReferenceNumber = string.Empty
            };

            var paymentDetail = new PaymentDetail()
            {
                NameOnCard      = "Mr John Smith",
                CardNumber      = "483501234567",
                CardType        = "VISA",
                ExpiryDateMonth = "08",
                ExpiryDateYear  = "24",
                CCV             = "140"
            };

            var transaction = new Transaction()
            {
                Id             = 1,
                Order          = order,
                PaymentDetails = paymentDetail,
                AddressDetails = new Address()
                {
                    Address1 = "1 Beehive Avenue",
                    Address2 = "Somewhere",
                    City     = "Wellington",
                    PostCode = "6021",
                    Region   = "Greater Wellington",
                    Country  = "New Zealand",
                }
            };

            _mockTransactionRepository
            .Setup(x => x.Create(It.IsAny <Transaction>()))
            .Returns(transaction);

            //Act
            var result = _transactionService.Create(order, paymentDetail);

            //Assert
            Assert.IsNotNull(result);
            Assert.IsTrue(result.Id == 1);
            Assert.AreEqual(result.Order.BillingInformation.Address1, order.BillingInformation.Address1);
            Assert.AreEqual(result.Order.BillingInformation.Address2, order.BillingInformation.Address2);
            Assert.AreEqual(result.PaymentDetails.NameOnCard, paymentDetail.NameOnCard);
            Assert.AreEqual(result.PaymentDetails.CCV, paymentDetail.CCV);
        }
        public async Task <ActionResult <PaymentDetail> > GetPaymentDetail(int id)
        {
            PaymentDetail paymentDetail = await _context.PaymentDetails.FindAsync(id).ConfigureAwait(false);

            return(paymentDetail ?? (ActionResult <PaymentDetail>)NotFound());
        }
Пример #9
0
        protected override void RunSample()
        {
            // ### Api Context
            // Pass in a `APIContext` object to authenticate
            // the call and to send a unique request id
            // (that ensures idempotency). The SDK generates
            // a request id if you do not pass one explicitly.
            // See [Configuration.cs](/Source/Configuration.html) to know more about APIContext.
            var apiContext = Configuration.GetAPIContext();

            // ### Create an invoice
            // For demonstration purposes, we will create a new invoice for this sample.
            var invoice = new Invoice()
            {
                // #### Merchant Information
                // Information about the merchant who is sending the invoice.
                merchant_info = new MerchantInfo()
                {
                    email         = "*****@*****.**",
                    first_name    = "Dennis",
                    last_name     = "Doctor",
                    business_name = "Medical Professionals, LLC",
                    phone         = new Phone()
                    {
                        country_code    = "001",
                        national_number = "4083741550"
                    },
                    address = new InvoiceAddress()
                    {
                        line1        = "1234 Main St.",
                        city         = "Portland",
                        state        = "OR",
                        postal_code  = "97217",
                        country_code = "US"
                    }
                },
                // #### Billing Information
                // Email address of invoice recipient and optional billing information.
                // > Note: PayPal currently only allows one recipient.
                billing_info = new List <BillingInfo>()
                {
                    new BillingInfo()
                    {
                        // **(Required)** Email address of the invoice recipient.
                        email = "*****@*****.**"
                    }
                },
                // #### Invoice Items
                // List of items to be included in the invoice.
                // > Note: 100 max per invoice.
                items = new List <InvoiceItem>()
                {
                    new InvoiceItem()
                    {
                        name       = "Sutures",
                        quantity   = 100,
                        unit_price = new Currency()
                        {
                            currency = "USD",
                            value    = "5"
                        }
                    }
                },
                // #### Invoice Note
                // Note to the payer. Maximum length is 4000 characters.
                note = "Medical Invoice 16 Jul, 2013 PST",
                // #### Payment Term
                // **(Optional)** Specifies the payment deadline for the invoice.
                // > Note: Either `term_type` or `due_date` can be sent, **but not both.**
                payment_term = new PaymentTerm()
                {
                    term_type = "NET_30"
                },
                // #### Shipping Information
                // Shipping information for entities to whom items are being shipped.
                shipping_info = new ShippingInfo()
                {
                    first_name    = "Sally",
                    last_name     = "Patient",
                    business_name = "Not applicable",
                    address       = new InvoiceAddress()
                    {
                        line1        = "1234 Broad St.",
                        city         = "Portland",
                        state        = "OR",
                        postal_code  = "97216",
                        country_code = "US"
                    }
                }
            };

            // ^ Ignore workflow code segment
            #region Track Workflow
            this.flow.AddNewRequest("Create the invoice", invoice);
            #endregion

            // Create the invoice
            var createdInvoice = invoice.Create(apiContext);

            // ^ Ignore workflow code segment
            #region Track Workflow
            this.flow.RecordResponse(createdInvoice);
            this.flow.AddNewRequest("Send the invoice", createdInvoice);
            #endregion

            // Send the created invoice
            createdInvoice.Send(apiContext);

            // ^ Ignore workflow code segment
            #region Track Workflow
            this.flow.RecordActionSuccess("Invoice sent successfully.");
            #endregion

            // Use the `PaymentDetail` object to specify the details of the payment.
            var paymentDetail = new PaymentDetail
            {
                method = "CASH",
                date   = "2014-07-06 03:30:00 PST",
                note   = "Cash received."
            };

            // ^ Ignore workflow code segment
            #region Track Workflow
            this.flow.AddNewRequest("Mark the invoice as paid", paymentDetail);
            #endregion

            // Mark the invoice as paid.
            createdInvoice.RecordPayment(apiContext, paymentDetail);

            // ^ Ignore workflow code segment
            #region Track Workflow
            this.flow.RecordActionSuccess("Invoice successfully updated.");
            #endregion

            // Use the `PaymentDetail` object to specify the details of the payment.
            var refundDetail = new RefundDetail
            {
                date = "2014-07-06 03:30:00 PST",
                note = "Refund provided by cash."
            };

            // ^ Ignore workflow code segment
            #region Track Workflow
            this.flow.AddNewRequest("Mark the invoice as refunded", refundDetail);
            #endregion

            createdInvoice.RecordRefund(apiContext, refundDetail);

            // ^ Ignore workflow code segment
            #region Track Workflow
            this.flow.RecordActionSuccess("Invoice successfully updated.");
            #endregion

            // ^ Ignore workflow code segment
            #region Track Workflow
            this.flow.AddNewRequest("Fetch details about the invoice", refundDetail);
            #endregion

            // The external payment will now be attached to the details of your invoice
            var invoiceDetails = Invoice.Get(apiContext, createdInvoice.id);

            // ^ Ignore workflow code segment
            #region Track Workflow
            this.flow.RecordResponse(invoiceDetails);
            this.flow.RecordActionSuccess("Invoice details fetched.");
            #endregion

            // ^ Ignore workflow code segment
            #region Track Workflow
            this.flow.AddNewRequest("Delete the external refund");
            #endregion

            // Delete external refund
            Invoice.DeleteExternalRefund(apiContext, invoiceDetails.id, invoiceDetails.refunds[0].transaction_id);

            // ^ Ignore workflow code segment
            #region Track Workflow
            this.flow.RecordActionSuccess("External Refund deleted successfully");
            #endregion
        }
Пример #10
0
 //***Commit the changes to the database
 public bool FinalizeChanges(PaymentDetail PaymentDetail)
 {
     //***call the PaymentDetailDB method that will commit the changes to the database
     return(PaymentDetailDB.UpdateDataSource(PaymentDetail));
 }
Пример #11
0
 public void InsertPaymentByStudent(PaymentDetail paymentDetail)
 {
     paymentDetail.PaymentDate = DateTime.Now;
     _smsdb.PaymentDetails.Add(paymentDetail);
     Save();
 }
Пример #12
0
        public IActionResult PostPaymentDetail(PaymentDetail paymentDetail)
        {
            _paymentDetailService.Create(paymentDetail);

            return(CreatedAtAction("GetPaymentDetail", new { id = paymentDetail.Id }, paymentDetail));
        }
        public IActionResult Post([FromBody] PolicyOutlaySave policyOutlaySave)
        {
            int idPolicyOutlay = 0;

            if (!ModelState.IsValid)
            {
                return(BadRequest());
            }
            using (var transaction = new TransactionScope())
            {
                try
                {
                    string idUser = User.Claims.Where(c => c.Type.Equals(ClaimTypes.PrimarySid)).FirstOrDefault().Value;
                    policyOutlaySave.PolicyOutlay.IdUser       = int.Parse(idUser);
                    policyOutlaySave.PolicyOutlay.CreationDate = DateTime.Now;
                    idPolicyOutlay = _unitOfWork.PolicyOutlay.Insert(policyOutlaySave.PolicyOutlay);

                    // Actualizamos las cuotas financiadas con el día de pago real
                    IEnumerable <PolicyFeeFinancialList> policyFees = _unitOfWork.PolicyFeeFinancial.PolicyFeeFinancialListByPolicy(policyOutlaySave.PolicyOutlay.IdPolicy, false);
                    foreach (PolicyFeeFinancialList item in policyFees)
                    {
                        if (item.DatePayment.HasValue)
                        {
                            int day     = policyOutlaySave.PolicyOutlay.PayDay;
                            int lastDay = DateTime.DaysInMonth(item.DatePayment.Value.Year, item.DatePayment.Value.Month);
                            if (day >= lastDay)
                            {
                                day = lastDay;
                            }
                            DateTime datePayment = new DateTime(item.DatePayment.Value.Year, item.DatePayment.Value.Month, day);
                            item.DatePayment = datePayment;
                            _unitOfWork.PolicyFeeFinancial.Update(item);
                        }
                    }
                    Policy   policy   = _unitOfWork.Policy.GetById(policyOutlaySave.PolicyOutlay.IdPolicy);
                    Customer customer = _unitOfWork.Customer.InsuredListByPolicy(policyOutlaySave.PolicyOutlay.IdPolicy).FirstOrDefault();

                    //Debemos generar el recaudo L3 aplicando el desembolso
                    PaymentType paymentType = _unitOfWork.PaymentType.GetList().Where(p => p.Id.Equals("L3")).FirstOrDefault();
                    paymentType.Number = paymentType.Number + 1;
                    _unitOfWork.PaymentType.Update(paymentType);
                    Payment payment = new Payment();
                    payment.DateCreated   = DateTime.Now;
                    payment.DatePayment   = policyOutlaySave.DatePayment;
                    payment.IdPaymentType = "L3";
                    payment.IdUser        = int.Parse(idUser);
                    payment.IdCustomer    = customer.Id;
                    payment.Number        = paymentType.Number;
                    //payment.PaidDestination = "A";
                    payment.State         = "A";
                    payment.Observation   = "DESEMBOLSO";
                    payment.Total         = (float)policy.TotalValue;
                    payment.TotalReceived = (float)policy.TotalValue;
                    payment.TotalValue    = (float)policy.TotalValue;
                    int idPayment = _unitOfWork.Payment.Insert(payment);
                    policyOutlaySave.PolicyOutlay.Id        = idPolicyOutlay;
                    policyOutlaySave.PolicyOutlay.IdPayment = idPayment;
                    _unitOfWork.PolicyOutlay.Update(policyOutlaySave.PolicyOutlay);
                    PaymentDetail paymentDetail = new PaymentDetail();
                    paymentDetail.DatePayFinancial = DateTime.Now;
                    paymentDetail.DueInterestValue = 0;
                    paymentDetail.FeeNumber        = 1;
                    paymentDetail.IdPayment        = idPayment;
                    paymentDetail.IdPolicy         = policy.Id;
                    paymentDetail.InitialFee       = false;
                    paymentDetail.Value            = (float)policy.TotalValue;
                    paymentDetail.ValueOwnProduct  = 0;
                    _unitOfWork.PaymentDetail.Insert(paymentDetail);

                    //Debemos guardar el documento digital y asociarlo al recaudo
                    DigitalizedFile digitalizedFile = policyOutlaySave.DigitalizedFile;
                    if (digitalizedFile != null)
                    {
                        digitalizedFile.IdPayment   = idPayment;
                        digitalizedFile.Date        = DateTime.Now;
                        digitalizedFile.Description = "DESEMBOLSO CREDITO #: " + policyOutlaySave.PolicyOutlay.CreditNumber + ", RECAUDO: L3-" + payment.Number.ToString();
                        _unitOfWork.DigitalizedFile.Insert(digitalizedFile);
                    }

                    transaction.Complete();
                }
                catch (Exception ex)
                {
                    transaction.Dispose();
                    return(StatusCode(500, "Internal server error: " + ex.Message));
                }
            }
            return(Ok(idPolicyOutlay));
        }
Пример #14
0
        public void ConvertDollarsToPennies(PaymentDetailData.ConvertDollarsToPenniesData data)
        {
            var pennies = PaymentDetail.ConvertDollarstoPennies(data.StringValue);

            Assert.AreEqual(data.Pennies, pennies);
        }
Пример #15
0
 public int UpdatePaymentDetail(PaymentDetail _PaymentDetails)
 {
     return(_PaymentDetailRepository.Update(_PaymentDetails));
 }
Пример #16
0
        private void btnReport_Click(object sender, EventArgs e)
        {
            StudentByBus studentbus = new StudentByBus();
            StudentByBus CurrentStudentbus = new StudentByBus();
            string CurrentBusStopName = "";
            BusSetup bussetup = BusSetupDAO.SelectByBusYearAndRange(this.intSchoolYear.Value, cboBusRange.Text);
            //List<string> newStuNumberList = new List<string>();
            List<string> StudentIDList = K12.Presentation.NLDPanels.Student.SelectedSource;
            List<StudentRecord> stuRec = Student.SelectByIDs(StudentIDList);
            Dictionary<string, StudentByBus> studentbusRecord = new Dictionary<string, StudentByBus>();

            studentbus = StudentByBusDAO.SelectByBusYearAndTimeNameAndStudntID(this.intSchoolYear.Value, this.cboBusRange.Text, StudentIDList[0]);
            if (studentbus != null)
            {
                if (textBusStop.Text != "" && textBusStop.Text != studentbus.BusStopID)
                    studentbus.BusStopID = textBusStop.Text;
                BusStop buses = BusStopDAO.SelectByBusTimeNameAndByStopID(bussetup.BusTimeName, textBusStop.Text);
                CurrentBusStopName = buses.BusStopName;
                int total = 0;
                if (studentbus.DateCount > 0)
                    total = buses.BusMoney * studentbus.DateCount;
                else
                    total = buses.BusMoney * bussetup.DateCount;
                int div_value = total / 10;
                if ((total - div_value * 10) < 5)
                    studentbus.BusMoney = div_value * 10;
                else
                    studentbus.BusMoney = div_value * 10 + 10;
                studentbus.Save();
                CurrentStudentbus = studentbus;
            }
            else
            {
                StudentByBus newstudentbus = new StudentByBus();
                if (textBusStop.Text != "")
                    newstudentbus.BusStopID = textBusStop.Text;
                BusStop buses = BusStopDAO.SelectByBusTimeNameAndByStopID(bussetup.BusTimeName, textBusStop.Text);
                CurrentBusStopName = buses.BusStopName;
                newstudentbus.BusRangeName = cboBusRange.Text;
                newstudentbus.BusStopID = textBusStop.Text;
                newstudentbus.BusTimeName = bussetup.BusTimeName;
                newstudentbus.ClassName = stuRec[0].Class.Name;
                newstudentbus.ClassID = stuRec[0].Class.ID;
                newstudentbus.DateCount = bussetup.DateCount;
                newstudentbus.SchoolYear = bussetup.BusYear;
                newstudentbus.StudentID = stuRec[0].ID;
                int total = buses.BusMoney * bussetup.DateCount;
                int div_value = total / 10;
                if ((total - div_value * 10) < 5)
                    newstudentbus.BusMoney = div_value * 10;
                else
                    newstudentbus.BusMoney = div_value * 10 + 10;
                newstudentbus.Save();

                CurrentStudentbus = newstudentbus;
            }

            //if (!File.Exists(Application.StartupPath + "\\Customize\\校車繳費單樣版.doc"))
            //{
            //    MessageBox.Show("『" + Application.StartupPath + "\\Customize\\校車繳費單樣版.doc』檔案不存在,請確認後重新執行!");
            //    return;
            //}

            //if (!File.Exists(Application.StartupPath + "\\Customize\\校車繳費單樣版-現有學生.doc"))
            //{
            //    MessageBox.Show("『" + Application.StartupPath + "\\Customize\\校車繳費單樣版-現有學生.doc』檔案不存在,請確認後重新執行!");
            //    return;
            //}

            //Document Template = new Document(Application.StartupPath + "\\Customize\\校車繳費單樣版-現有學生.doc");
            Document Template = new Aspose.Words.Document(new MemoryStream(Properties.Resources.校車繳費單樣版_現有學生));
            //Document Template = new Document();
            //mPreference = TemplatePreference.GetInstance();
            //if (mPreference.UseDefaultTemplate)
            //    Template = new Aspose.Words.Document(new MemoryStream(Properties.Resources.校車繳費單樣版_新生));
            //else
            //    Template = new Aspose.Words.Document(mPreference.CustomizeTemplate);

            Document doc = new Document();

            Payment SelectPayment = cboPayment.SelectedItem as Payment;

            //新增收費明細。
            List<PaymentDetail> StudentDetails = new List<PaymentDetail>();

            SelectPayment.FillFull();
            List<PaymentDetail> AllStudentdetail = PaymentDetail.GetByTarget("Student", StudentIDList);
            List<PaymentDetail> Studentdetail = new List<PaymentDetail>();
            List<PaymentDetail> CurrentDetails = new List<PaymentDetail>();
            List<PaymentHistory> historys = new List<PaymentHistory>();
            List<string> ids = new List<string>();
            foreach (PaymentDetail var in AllStudentdetail)
            {
                if (var.Extensions["校車收費年度"] != intSchoolYear.Value.ToString() || var.Extensions["校車收費名稱"] != cboBusRange.SelectedItem.ToString())
                    continue;
                Studentdetail.Add(var);
            }

            if (Studentdetail.Count == 0)
            {
                PaymentDetail detail = new PaymentDetail(SelectPayment);    //設定「收費明細」所屬的收費。

                detail.RefTargetID = stuRec[0].ID;//搭乘校車新生ID。
                detail.RefTargetType = "Student";
                detail.Amount = CurrentStudentbus.BusMoney;                  //要收多少錢。
                //detail.Extensions.Add("校車收費年度", intSchoolYear.Value.ToString());
                detail.Extensions.Add("校車收費年度", SelectPayment.SchoolYear.ToString());
                detail.Extensions.Add("校車收費學期", SelectPayment.Semester.ToString());
                detail.Extensions.Add("校車收費名稱", cboBusRange.SelectedItem.ToString());
                detail.Extensions.Add("MergeField::代碼", textBusStop.Text);
                detail.Extensions.Add("MergeField::站名", CurrentBusStopName);
                detail.Extensions.Add("MergeField::" + "學號", stuRec[0].StudentNumber);
                detail.Extensions.Add("MergeField::" + "姓名", stuRec[0].Name);
                detail.Extensions.Add("MergeField::" + "班級", stuRec[0].Class.Name);
                detail.Extensions.Add("開始日期", bussetup.BusStartDate.ToString());
                detail.Extensions.Add("結束日期", bussetup.BusEndDate.ToString());
                detail.Extensions.Add("搭車天數", CurrentStudentbus.DateCount.ToString());
                StudentDetails.Add(detail);                                 //先加到一個 List 中。

                List<string> detailIDs = new List<string>();
                detailIDs = PaymentDetail.Insert(StudentDetails.ToArray());     //新增到資料庫中。

                CurrentDetails = PaymentDetail.GetByIDs(detailIDs.ToArray());

                foreach (PaymentDetail pd in CurrentDetails)
                {
                    MotherForm.SetStatusBarMessage("條碼產生中....");
                    Application.DoEvents();
                    //新增一筆繳費記錄。
                    PaymentHistory history = new PaymentHistory(pd);
                    history.Amount = pd.Amount; //通常會與金額與繳費明細一樣。
                    ((Payment)cboPayment.SelectedItem).CalculateReceiptBarcode(history); //計算條碼資料,計算時需要「Payment」物件。
                    historys.Add(history);
                }
                ids = PaymentHistory.Insert(historys);
            }
            else
            {
                foreach (PaymentDetail pdetail in Studentdetail)
                {
                    CurrentDetails.Add(pdetail);
                    if (pdetail.Extensions["校車收費名稱"] == cboBusRange.SelectedItem.ToString() && int.Parse(pdetail.Extensions["校車收費年度"]) == intSchoolYear.Value)
                    {
                        if ((pdetail.Extensions["MergeField::代碼"] != textBusStop.Text && pdetail.Extensions["MergeField::站名"] != CurrentBusStopName) || int.Parse(pdetail.Extensions["搭車天數"]) != CurrentStudentbus.DateCount)
                        {
                            if (CurrentStudentbus.DateCount > 0)
                            {
                                pdetail.Extensions["搭車天數"] = CurrentStudentbus.DateCount.ToString();
                                pdetail.Amount = CurrentStudentbus.BusMoney;
                            }

                            List<PaymentDetail> pdetails = new List<PaymentDetail>();
                            pdetail.Amount = CurrentStudentbus.BusMoney;
                            pdetail.Extensions["MergeField::代碼"] = textBusStop.Text;
                            pdetail.Extensions["MergeField::站名"] = CurrentBusStopName;
                            pdetails.Add(pdetail);
                            PaymentDetail.Update(pdetails.ToArray()); //更新到資料庫中。

                            //註銷先前之繳費單
                            pdetail.CancelExistReceipts();

                            foreach (PaymentDetail pd in CurrentDetails)
                            {
                                MotherForm.SetStatusBarMessage("條碼產生中....");
                                Application.DoEvents();
                                //新增一筆繳費記錄。
                                PaymentHistory history = new PaymentHistory(pd);
                                history.Amount = pd.Amount; //通常會與金額與繳費明細一樣。
                                ((Payment)cboPayment.SelectedItem).CalculateReceiptBarcode(history); //計算條碼資料,計算時需要「Payment」物件。
                                historys.Add(history);
                            }
                            ids = PaymentHistory.Insert(historys);
                            continue;
                        }
                        else
                        {
                            pdetail.FillHistories();

                            IList<PaymentHistory> historyss = pdetail.Histories;
                            if (historyss == null)
                                return;
                            foreach (PaymentHistory history in historyss)
                            {
                                if (history.Receipt.Cancelled)
                                    continue;
                                else
                                {
                                    ids.Add(history.UID);
                                    break;
                                }
                            }
                        }
                    }
                }
            }

            historys = PaymentHistory.GetByIDs(ids.ToArray());
            //產生繳費單
            ReceiptDocument rdoc = new ReceiptDocument(Template); //如果要自定樣版,可以用這個建構式。
            List<PaymentReceipt> prRecood = new List<PaymentReceipt>();
            foreach (PaymentHistory history in historys)
            {
                MotherForm.SetStatusBarMessage("繳費單產生中....");
                Application.DoEvents();
                prRecood.Add(history.Receipt);
            }
            doc = rdoc.Generate2(prRecood);

            if (doc.Sections.Count != 0)
            {
                string path = Path.Combine(Application.StartupPath, "Reports");
                string reportName = "繳費單";
                if (!Directory.Exists(path))
                    Directory.CreateDirectory(path);
                path = Path.Combine(path, reportName + ".doc");

                if (File.Exists(path))
                {
                    int i = 1;
                    while (true)
                    {
                        string newPath = Path.GetDirectoryName(path) + "\\" + Path.GetFileNameWithoutExtension(path) + (i++) + Path.GetExtension(path);
                        if (!File.Exists(newPath))
                        {
                            path = newPath;
                            break;
                        }
                    }
                }

                try
                {
                    doc.Save(path, SaveFormat.Doc);
                    System.Diagnostics.Process.Start(path);
                }
                catch
                {
                    System.Windows.Forms.SaveFileDialog sd1 = new System.Windows.Forms.SaveFileDialog();
                    sd1.Title = "另存新檔";
                    sd1.FileName = "繳費單.doc";
                    sd1.Filter = "Word檔案 (*.doc)|*.doc|所有檔案 (*.*)|*.*";
                    if (sd1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                    {
                        try
                        {
                            doc.Save(sd1.FileName, SaveFormat.Doc);
                            System.Diagnostics.Process.Start(sd1.FileName);
                        }
                        catch
                        {
                            System.Windows.Forms.MessageBox.Show("指定路徑無法存取。", "建立檔案失敗", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
                            return;
                        }
                    }
                }
            }

            MotherForm.SetStatusBarMessage("繳費單產生完成。");
            this.Close();
        }
Пример #17
0
        private void btnReport_Click(object sender, EventArgs e)
        {
            if (cboDept.Text == "")
            {
                MessageBox.Show("請選擇科別再重新執行!");
                return;
            }
            List<StudentByBus> studentbus = new List<StudentByBus>();
            StudentByBus CurrentStudentbus = new StudentByBus();
            BusSetup bussetup = BusSetupDAO.SelectByBusYearAndRange(this.intSchoolYear.Value, cboBusRange.Text);
            //List<string> newStuNumberList = new List<string>();
            List<string> AllStudentIDList = new List<string>();
            List<string> StudentIDList = new List<string>();
            List<SHStudentRecord> stuRec = new List<SHStudentRecord>();
            Dictionary<string, StudentByBus> studentbusRecord = new Dictionary<string, StudentByBus>();
            Dictionary<string, List<SHStudentRecord>> studentClassRecord = new Dictionary<string, List<SHStudentRecord>>();
            studentbus = StudentByBusDAO.SelectByBusYearAndTimeName(this.intSchoolYear.Value, this.cboBusRange.Text);
            Dictionary<string, BusStop> BusStopRecord = new Dictionary<string, BusStop>();
            List<BusStop> BusStops = new List<BusStop>();
            if (this.cboBusRange.Text.IndexOf("夜輔") >= 0)
                BusStops = BusStopDAO.SelectByBusTimeName("夜輔");
            else
                BusStops = BusStopDAO.SelectByBusTimeName("日校校車");

            foreach (BusStop var in BusStops)
            {
                if (!BusStopRecord.ContainsKey(var.BusStopID))
                    BusStopRecord.Add(var.BusStopID, var);
            }

            int nowSet = 0;
            int nowPercent = 0;
            foreach (StudentByBus var in studentbus)
            {
                MotherForm.SetStatusBarMessage("正在讀取學生搭車資料", nowSet++ * 10 / studentbus.Count);
                if (var.BusStopID == "0000")
                    continue;
                //if (var.comment != "99測試")
                //    continue;

                if (!studentbusRecord.ContainsKey(var.StudentID))
                    studentbusRecord.Add(var.StudentID, var);
                if (!AllStudentIDList.Contains(var.StudentID))
                    AllStudentIDList.Add(var.StudentID);
            }

            stuRec = SHStudent.SelectByIDs(AllStudentIDList);
            Dictionary<int, string> ClassIDs = new Dictionary<int, string>();
            List<int> orderClassIDs = new List<int>();
            int orderval = 0;
            nowPercent = 10;
            nowSet = 0;
            foreach (SHStudentRecord var in stuRec)
            {
                MotherForm.SetStatusBarMessage("正在讀取學生資料", nowPercent + nowSet++ * 50 / stuRec.Count);
                if (var.Status != StudentRecord.StudentStatus.一般)
                    continue;
                if (cboDept.Text != "")
                {
                    if (cboDept.Text == "多媒體設計科")
                    {
                        if (var.Department.Name.IndexOf("多媒體") < 0)
                            continue;
                    }
                    else
                    {
                        if (var.Department.Name != cboDept.Text)
                            continue;
                    }
                }

                if (int.Parse(var.Class.GradeYear.ToString()) == 3)
                    orderval = 47 + int.Parse(var.Class.DisplayOrder);
                else
                    orderval = (int.Parse(var.Class.GradeYear.ToString()) - 1) * 23 + int.Parse(var.Class.DisplayOrder);
                if (!ClassIDs.ContainsKey(orderval))
                {
                    ClassIDs.Add(orderval, var.Class.ID);
                    orderClassIDs.Add(orderval);
                }

                if (!studentClassRecord.ContainsKey(var.Class.ID))
                    studentClassRecord.Add(var.Class.ID, new List<SHStudentRecord>());
                if (!studentClassRecord[var.Class.ID].Contains(var))
                    studentClassRecord[var.Class.ID].Add(var);
                if (!StudentIDList.Contains(var.ID))
                    StudentIDList.Add(var.ID);
            }

            orderClassIDs.Sort();
            int stucount = 0;
            for (int i = 0; i < orderClassIDs.Count; i++)
            {
                studentClassRecord[ClassIDs[orderClassIDs[i]]].Sort(CompareStudentNumber);
                stucount += studentClassRecord[ClassIDs[orderClassIDs[i]]].Count;
            }

            //if (!File.Exists(Application.StartupPath + "\\Customize\\校車繳費單樣版.doc"))
            //{
            //    MessageBox.Show("『" + Application.StartupPath + "\\Customize\\校車繳費單樣版.doc』檔案不存在,請確認後重新執行!");
            //    return;
            //}

            //if (!File.Exists(Application.StartupPath + "\\Customize\\校車繳費單樣版-現有學生.doc"))
            //{
            //    MessageBox.Show("『" + Application.StartupPath + "\\Customize\\校車繳費單樣版-現有學生.doc』檔案不存在,請確認後重新執行!");
            //    return;
            //}

            //Document Template = new Document(Application.StartupPath + "\\Customize\\校車繳費單樣版-現有學生.doc");
            Document Template = new Aspose.Words.Document(new MemoryStream(Properties.Resources.校車繳費單樣版_現有學生));
            //Document Template = new Document();
            //mPreference = TemplatePreference.GetInstance();
            //if (mPreference.UseDefaultTemplate)
            //    Template = new Aspose.Words.Document(new MemoryStream(Properties.Resources.校車繳費單樣版_新生));
            //else
            //    Template = new Aspose.Words.Document(mPreference.CustomizeTemplate);

            Document doc = new Document();

            Payment SelectPayment = cboPayment.SelectedItem as Payment;

            //新增收費明細。
            List<PaymentDetail> StudentDetails = new List<PaymentDetail>();

            SelectPayment.FillFull();
            List<PaymentDetail> AllStudentdetail = PaymentDetail.GetByTarget("Student", StudentIDList);
            List<PaymentDetail> Studentdetail = new List<PaymentDetail>();
            List<PaymentDetail> CurrentDetails = new List<PaymentDetail>();
            List<PaymentHistory> historys = new List<PaymentHistory>();
            List<string> ids = new List<string>();
            foreach (PaymentDetail var in AllStudentdetail)
            {
                if (var.Extensions["校車收費年度"] != intSchoolYear.Value.ToString() || var.Extensions["校車收費名稱"] != cboBusRange.SelectedItem.ToString())
                    continue;
                Studentdetail.Add(var);
            }

            int paymentcount = 0;
            nowPercent = 60;
            nowSet = 0;
            string oldclass = "";
            bool loseHistory = false;
            if (Studentdetail.Count == 0)
            {
                for (int i = 0; i < orderClassIDs.Count; i++)
                    foreach (SHStudentRecord nsr in studentClassRecord[ClassIDs[orderClassIDs[i]]])
                    {
                        MotherForm.SetStatusBarMessage("正在產生校車繳費資料", nowPercent + nowSet++ * 30 / stucount);
                        PaymentDetail detail = new PaymentDetail(SelectPayment);    //設定「收費明細」所屬的收費。

                        detail.RefTargetID = nsr.ID;                                //搭乘校車學生ID。
                        detail.RefTargetType = "Student";
                        detail.Amount = studentbusRecord.ContainsKey(nsr.ID) ? studentbusRecord[nsr.ID].BusMoney : 0;  //要收多少錢。
                        //detail.Extensions.Add("校車收費年度", intSchoolYear.Value.ToString());
                        detail.Extensions.Add("校車收費年度", SelectPayment.SchoolYear.ToString());
                        detail.Extensions.Add("校車收費學期", SelectPayment.Semester.ToString());
                        detail.Extensions.Add("校車收費名稱", cboBusRange.SelectedItem.ToString());
                        detail.Extensions.Add("MergeField::代碼", studentbusRecord.ContainsKey(nsr.ID) ? studentbusRecord[nsr.ID].BusStopID : "");
                        detail.Extensions.Add("MergeField::站名", studentbusRecord.ContainsKey(nsr.ID) ? BusStopRecord[studentbusRecord[nsr.ID].BusStopID].BusStopName : "");
                        detail.Extensions.Add("MergeField::" + "學號", nsr.StudentNumber);
                        detail.Extensions.Add("MergeField::" + "姓名", nsr.Name);
                        detail.Extensions.Add("MergeField::" + "班級", nsr.Class.Name.Substring(0, 3));
                        detail.Extensions.Add("開始日期", bussetup.BusStartDate.ToString());
                        detail.Extensions.Add("結束日期", bussetup.BusEndDate.ToString());
                        detail.Extensions.Add("搭車天數", studentbusRecord[nsr.ID].DateCount.ToString());
                        StudentDetails.Add(detail);                                 //先加到一個 List 中。
                        paymentcount++;
                    }
                List<string> detailIDs = new List<string>();
                detailIDs = PaymentDetail.Insert(StudentDetails.ToArray());       //新增到資料庫中。

                //如果要馬上使用物件的話,需要用回傳的 UID 清單再將資料 Select 出來
                //因為這樣物件中才會包含 UID 資料。
                CurrentDetails = PaymentDetail.GetByIDs(detailIDs.ToArray());
                foreach (PaymentDetail pd in CurrentDetails)
                {
                    if (oldclass != pd.Extensions["MergeField::" + "班級"])
                        MotherForm.SetStatusBarMessage(pd.Extensions["MergeField::" + "班級"] + "條碼產生中....", 90);
                    Application.DoEvents();
                    //新增一筆繳費記錄。
                    PaymentHistory history = new PaymentHistory(pd);
                    history.Amount = pd.Amount; //通常會與金額與繳費明細一樣。
                    ((Payment)cboPayment.SelectedItem).CalculateReceiptBarcode(history); //計算條碼資料,計算時需要「Payment」物件。
                    historys.Add(history);
                    oldclass = pd.Extensions["MergeField::" + "班級"];
                }
                ids = PaymentHistory.Insert(historys);
            }
            else
            {
                foreach (PaymentDetail pdetail in Studentdetail)
                {
                    if (paymentcount == 0)
                        MotherForm.SetStatusBarMessage("正在讀取校車繳費資料", nowPercent + nowSet++ * 30 / stucount);
                    CurrentDetails.Add(pdetail);
                    pdetail.FillHistories();
                    if (pdetail.Extensions["校車收費名稱"] == cboBusRange.SelectedItem.ToString() && int.Parse(pdetail.Extensions["校車收費年度"]) == intSchoolYear.Value)
                    {
                        if (CancelExist.Checked)
                        {
                            //註銷先前之繳費單
                            pdetail.CancelExistReceipts();

                            if (studentbusRecord[pdetail.RefTargetID].DateCount > 0)
                            {
                                pdetail.Extensions["搭車天數"] = studentbusRecord[pdetail.RefTargetID].DateCount.ToString();
                                pdetail.Amount = studentbusRecord.ContainsKey(pdetail.RefTargetID) ? studentbusRecord[pdetail.RefTargetID].BusMoney : 0;  //要收多少錢。
                            }

                            if (pdetail.Extensions["MergeField::" + "班級"].Length > 3)
                                pdetail.Extensions["MergeField::" + "班級"] = pdetail.Extensions["MergeField::" + "班級"].Substring(0, 3);
                            PaymentDetail.Update(pdetail);

                            if (oldclass != pdetail.Extensions["MergeField::" + "班級"])
                                MotherForm.SetStatusBarMessage(pdetail.Extensions["MergeField::" + "班級"] + "條碼產生中....", 90);
                            Application.DoEvents();
                            //新增一筆繳費記錄。
                            PaymentHistory history = new PaymentHistory(pdetail);
                            history.Amount = pdetail.Amount;                                        //通常會與金額與繳費明細一樣。
                            ((Payment)cboPayment.SelectedItem).CalculateReceiptBarcode(history);    //計算條碼資料,計算時需要「Payment」物件。
                            historys.Add(history);
                            paymentcount++;
                        }
                        else
                        {
                            //if (!pdetail.Extensions.ContainsKey("MergeField::站名"))
                            //    pdetail.Extensions.Add("MergeField::站名", BusStopRecord[studentbusRecord["19998"].BusStopID].BusStopName);
                            //PaymentDetail.Update(pdetail);

                            if (oldclass != pdetail.Extensions["MergeField::" + "班級"])
                                MotherForm.SetStatusBarMessage(pdetail.Extensions["MergeField::" + "班級"] + "條碼產生中....", 90);

                            IList<PaymentHistory> historyss = pdetail.Histories;

                            if (historyss == null)
                                return;

                            if (historyss.Count == 0)
                            {
                                Application.DoEvents();
                                //新增一筆繳費記錄。
                                PaymentHistory history = new PaymentHistory(pdetail);
                                history.Amount = pdetail.Amount; //通常會與金額與繳費明細一樣。
                                ((Payment)cboPayment.SelectedItem).CalculateReceiptBarcode(history); //計算條碼資料,計算時需要「Payment」物件。
                                historys.Add(history);
                                loseHistory = true;
                            }
                            else
                            {
                                foreach (PaymentHistory history in historyss)
                                {
                                    //if (!history.Receipt.Extensions.ContainsKey("MergeField::站名"))
                                    //    history.Receipt.Extensions.Add("MergeField::站名", BusStopRecord[studentbusRecord["19764"].BusStopID].BusStopName);
                                    //PaymentHistory.Update(history);

                                    ((Payment)cboPayment.SelectedItem).CalculateReceiptBarcode(history); //計算條碼資料,計算時需要「Payment」物件。
                                    ids.Add(history.UID);
                                }
                            }
                            paymentcount++;
                        }
                    }
                    oldclass = pdetail.Extensions["MergeField::" + "班級"];
                }
                if (CancelExist.Checked || (loseHistory && historys.Count > 0))
                    ids = PaymentHistory.Insert(historys);
            }

            historys = PaymentHistory.GetByIDs(ids.ToArray());
            Dictionary<string, Dictionary<string, PaymentHistory>> StudentHistorys = new Dictionary<string, Dictionary<string, PaymentHistory>>();
            Dictionary<string, List<string>> StudentNumberList = new Dictionary<string, List<string>>();
            foreach (PaymentHistory history in historys)
            {
                if (!StudentHistorys.ContainsKey(history.PaymentDetail.Extensions["MergeField::班級"]))
                    StudentHistorys.Add(history.PaymentDetail.Extensions["MergeField::班級"], new Dictionary<string, PaymentHistory>());
                if (!StudentHistorys[history.PaymentDetail.Extensions["MergeField::班級"]].ContainsKey(history.PaymentDetail.Extensions["MergeField::學號"]))
                    StudentHistorys[history.PaymentDetail.Extensions["MergeField::班級"]].Add(history.PaymentDetail.Extensions["MergeField::學號"], history);
                if (!StudentNumberList.ContainsKey(history.PaymentDetail.Extensions["MergeField::班級"]))
                    StudentNumberList.Add(history.PaymentDetail.Extensions["MergeField::班級"], new List<string>());
                if (!StudentNumberList[history.PaymentDetail.Extensions["MergeField::班級"]].Contains(history.PaymentDetail.Extensions["MergeField::學號"]))
                    StudentNumberList[history.PaymentDetail.Extensions["MergeField::班級"]].Add(history.PaymentDetail.Extensions["MergeField::學號"]);
            }
            foreach (string var in StudentNumberList.Keys)
                StudentNumberList[var].Sort();

            //產生繳費單
            ReceiptDocument rdoc = new ReceiptDocument(Template); //如果要自定樣版,可以用這個建構式。
            List<PaymentReceipt> prRecood = new List<PaymentReceipt>();
            nowPercent = 90;
            nowSet = 0;
            foreach (string var in StudentHistorys.Keys)
            {
                for (int i = 0; i < StudentNumberList[var].Count; i++)
                {
                    //MotherForm.SetStatusBarMessage("繳費單產生中....");
                    MotherForm.SetStatusBarMessage(var + "繳費單產生中....", nowPercent + nowSet++ * 10 / historys.Count);
                    Application.DoEvents();
                    prRecood.Add(StudentHistorys[var][StudentNumberList[var][i]].Receipt);
                }
                // 產生現有學生校車用繳費單
                doc = rdoc.Generate2(prRecood);
                if (doc.Sections.Count != 0)
                {
                    Completed(doc, var);
                }
                prRecood.Clear();
            }

            MotherForm.SetStatusBarMessage("繳費單產生完成共" + paymentcount + "筆。");
            this.Close();
        }
        public ActionResult Edit([Bind(Include = "StudentId,Standard,Stream,Year,College,FirstName,LastName,Email,Phone,DoB,RollNo,Address,City,Courses,PayingAmt,SelectedCourses,ProfilePic")] Student student, HttpPostedFileBase dpUploader)
        {
            if (ModelState.IsValid)
            {
                student.Address = Sanitizer.GetSafeHtmlFragment(student.Address);
                var selectedCourse = student.SelectedCourses;

                decimal totalCourseFee = 0;

                /*to rmove all existing courses and add new */
                var item = db.Entry <Student>(student);
                item.State = EntityState.Modified;

                // item.Collection(i => i.LstCourse).Load();
                // student.LstCourse.Clear();
                PaymentDetail existingPaymentRecord = db.PaymentDetails.Where(p => p.StudentId == student.StudentId).OrderByDescending(p => p.PaymentDate).FirstOrDefault();
                var           payment = new PaymentDetail();
                payment.StudentId = student.StudentId;

                payment.PayingAmount = student.PayingAmt;
                payment.PaymentDate  = DateTime.Now;

                if (selectedCourse != null)
                {
                    foreach (var course in selectedCourse)
                    {
                        Course c = db.Courses.Find(course);
                        student.LstCourse.Add(c);
                        totalCourseFee += c.Fee;
                    }

                    if (existingPaymentRecord != null)
                    {
                        totalCourseFee += existingPaymentRecord.TotalAmount;
                    }
                    decimal prevSum = 0;
                    IEnumerable <PaymentDetail> details = db.PaymentDetails.Where(p => p.StudentId == student.StudentId).ToList();
                    if (details != null)
                    {
                        prevSum = details.Sum(s => s.PayingAmount);
                    }

                    payment.BalanceAmount = totalCourseFee - (student.PayingAmt + prevSum);
                    //(existingPaymentRecord.BalanceAmount - student.PayingAmt) + totalCourseFee;
                    payment.TotalAmount = totalCourseFee;
                    db.PaymentDetails.Add(payment);
                }
                else
                {
                    if (existingPaymentRecord != null && student.PayingAmt > 0)
                    {
                        payment.BalanceAmount = existingPaymentRecord.BalanceAmount - student.PayingAmt;
                        payment.TotalAmount   = existingPaymentRecord.TotalAmount;
                        db.PaymentDetails.Add(payment);
                    }
                }


                if (dpUploader != null && dpUploader.ContentLength > 0)
                {
                    string _FileName = Path.GetExtension(dpUploader.FileName);
                    string _path     = Path.Combine(Server.MapPath(@"~/UploadedFiles/ProfilePics/"), _FileName);
                    dpUploader.SaveAs(_path);
                    student.ProfilePic = _FileName;
                }

                db.SaveChanges();


                return(RedirectToAction("Index"));
            }
            return(View(student));
        }
Пример #19
0
 public void CommitTransaction(PaymentDetail paymentDetail)
 {
     // TODO: Implements commit
 }
Пример #20
0
 public string AddPayment(PaymentDetail detail)
 {
     return(Repository.AddPayment(Mapper.Map <DataModels.Payment.PaymentDetail>(detail)));
 }
Пример #21
0
 public async Task <bool> AddCard(PaymentDetail paymentDetail)
 {
     return(await _repositroy.AddCard(paymentDetail));
 }
Пример #22
0
        private void btnReport_Click(object sender, EventArgs e)
        {
            List<StudentByBus> studentbus = new List<StudentByBus>();
            StudentByBus CurrentStudentbus = new StudentByBus();
            string CurrentBusStopName = "";
            BusSetup bussetup = BusSetupDAO.SelectByBusYearAndRange(this.intSchoolYear.Value, cboBusRange.Text);
            //List<string> newStuNumberList = new List<string>();
            List<string> newStudentIDList = new List<string>();
            List<MySchoolModule.NewStudentRecord> newStu = new List<MySchoolModule.NewStudentRecord>();
            Dictionary<string, StudentByBus> studentbusRecord = new Dictionary<string, StudentByBus>();
            foreach (MySchoolModule.NewStudentRecord nsr in NewStudent.Instance.SelectedList)
            {
                //if (!newStuNumberList.Contains(nsr.Number))
                //    newStuNumberList.Add(nsr.Number);
                if (!newStudentIDList.Contains(nsr.UID))
                    newStudentIDList.Add(nsr.UID);
                newStu.Add(nsr);
            }

            studentbus = StudentByBusDAO.SelectByBusYearAndTimeNameAndStudntList(this.intSchoolYear.Value, cboBusRange.Text, newStudentIDList);
            foreach (StudentByBus var in studentbus)
                if (!studentbusRecord.ContainsKey(var.StudentID))
                    studentbusRecord.Add(var.StudentID, var);

            //if (!File.Exists(Application.StartupPath + "\\Customize\\校車繳費單樣版.doc"))
            //{
            //    MessageBox.Show("『" + Application.StartupPath + "\\Customize\\校車繳費單樣版.doc』檔案不存在,請確認後重新執行!");
            //    return;
            //}

            //if (!File.Exists(Application.StartupPath + "\\Customize\\校車繳費單樣版-新生.doc"))
            //{
            //    MessageBox.Show("『" + Application.StartupPath + "\\Customize\\校車繳費單樣版-新生.doc』檔案不存在,請確認後重新執行!");
            //    return;
            //}

            //Document Template = new Document(Application.StartupPath + "\\Customize\\校車繳費單樣版-新生.doc");
            Document Template = new Aspose.Words.Document(new MemoryStream(Properties.Resources.校車繳費單樣版_新生));
            //Document Template = new Document();
            //mPreference = TemplatePreference.GetInstance();
            //if (mPreference.UseDefaultTemplate)
            //    Template = new Aspose.Words.Document(new MemoryStream(Properties.Resources.校車繳費單樣版_新生));
            //else
            //    Template = new Aspose.Words.Document(mPreference.CustomizeTemplate);

            Document doc = new Document();

            Payment SelectPayment = cboPayment.SelectedItem as Payment;

            //新增收費明細。
            List<PaymentDetail> StudentDetails = new List<PaymentDetail>();

            SelectPayment.FillFull();
            List<PaymentDetail> Studentdetail = PaymentDetail.GetByTarget("NewStudent", newStudentIDList);
            List<PaymentDetail> CurrentDetails = new List<PaymentDetail>();
            List<PaymentHistory> historys = new List<PaymentHistory>();
            List<string> ids = new List<string>();
            if (Studentdetail.Count == 0)
            {
                foreach (MySchoolModule.NewStudentRecord nsr in NewStudent.Instance.SelectedList)
                {
                    PaymentDetail detail = new PaymentDetail(SelectPayment);    //設定「收費明細」所屬的收費。

                    detail.RefTargetID = NewStudent.Instance.SelectedList[0].UID;//搭乘校車新生ID。
                    detail.RefTargetType = "NewStudent";
                    detail.Amount = studentbusRecord[nsr.UID].BusMoney;                  //要收多少錢。
                    detail.Extensions.Add("校車收費年度", SelectPayment.SchoolYear.ToString());
                    detail.Extensions.Add("校車收費學期", SelectPayment.Semester.ToString());
                    detail.Extensions.Add("校車收費名稱", cboBusRange.SelectedItem.ToString());
                    detail.Extensions.Add("MergeField::代碼", textBusStop.Text);
                    detail.Extensions.Add("MergeField::站名", CurrentBusStopName);
                    detail.Extensions.Add("MergeField::" + "學號", NewStudent.Instance.SelectedList[0].Number);
                    detail.Extensions.Add("MergeField::" + "姓名", NewStudent.Instance.SelectedList[0].Name);
                    detail.Extensions.Add("MergeField::" + "科別", NewStudent.Instance.SelectedList[0].Dept);
                    detail.Extensions.Add("開始日期", bussetup.BusStartDate.ToString());
                    detail.Extensions.Add("結束日期", bussetup.BusEndDate.ToString());
                    detail.Extensions.Add("搭車天數", studentbusRecord[nsr.UID].DateCount.ToString());
                    StudentDetails.Add(detail);                                 //先加到一個 List 中。
                }
                List<string> detailIDs = new List<string>();
                detailIDs = PaymentDetail.Insert(StudentDetails.ToArray());     //新增到資料庫中。

                //如果要馬上使用物件的話,需要用回傳的 UID 清單再將資料 Select 出來
                //因為這樣物件中才會包含 UID 資料。
                CurrentDetails = PaymentDetail.GetByIDs(detailIDs.ToArray());

                foreach (PaymentDetail pd in CurrentDetails)
                {
                    MotherForm.SetStatusBarMessage("條碼產生中....");
                    Application.DoEvents();
                    //新增一筆繳費記錄。
                    PaymentHistory history = new PaymentHistory(pd);
                    history.Amount = pd.Amount; //通常會與金額與繳費明細一樣。
                    ((Payment)cboPayment.SelectedItem).CalculateReceiptBarcode(history); //計算條碼資料,計算時需要「Payment」物件。
                    historys.Add(history);
                }
                ids = PaymentHistory.Insert(historys);
            }
            else
            {
                foreach (PaymentDetail pdetail in Studentdetail)
                {
                    CurrentDetails.Add(pdetail);
                    pdetail.FillHistories();
                    if (pdetail.Extensions["校車收費名稱"] == cboBusRange.SelectedItem.ToString() && int.Parse(pdetail.Extensions["校車收費年度"]) == intSchoolYear.Value)
                    {
                        if (CancelExist.Checked)
                        {
                            //註銷先前之繳費單
                            pdetail.CancelExistReceipts();

                            if (studentbusRecord[pdetail.RefTargetID].DateCount > 0)
                            {
                                pdetail.Extensions["搭車天數"] = studentbusRecord[pdetail.RefTargetID].DateCount.ToString();
                                pdetail.Amount = studentbusRecord.ContainsKey(pdetail.RefTargetID) ? studentbusRecord[pdetail.RefTargetID].BusMoney : 0;
                                PaymentDetail.Update(pdetail);
                            }

                            MotherForm.SetStatusBarMessage("條碼產生中....");
                            Application.DoEvents();
                            //新增一筆繳費記錄。
                            PaymentHistory history = new PaymentHistory(pdetail);
                            history.Amount = pdetail.Amount;                                        //通常會與金額與繳費明細一樣。
                            ((Payment)cboPayment.SelectedItem).CalculateReceiptBarcode(history);    //計算條碼資料,計算時需要「Payment」物件。
                            historys.Add(history);
                        }
                        else
                        {
                            IList<PaymentHistory> historyss = pdetail.Histories;

                            if (historyss == null)
                                return;
                            foreach (PaymentHistory history in historyss)
                            {
                                ((Payment)cboPayment.SelectedItem).CalculateReceiptBarcode(history); //計算條碼資料,計算時需要「Payment」物件。
                                ids.Add(history.UID);
                            }
                        }
                    }
                }
                if (CancelExist.Checked)
                    ids = PaymentHistory.Insert(historys);
            }

            historys = PaymentHistory.GetByIDs(ids.ToArray());
            //產生繳費單
            ReceiptDocument rdoc = new ReceiptDocument(Template); //如果要自定樣版,可以用這個建構式。
            List<PaymentReceipt> prRecood = new List<PaymentReceipt>();
            foreach (PaymentHistory history in historys)
            {
                MotherForm.SetStatusBarMessage("繳費單產生中....");
                Application.DoEvents();
                prRecood.Add(history.Receipt);
            }
            doc = rdoc.Generate1(prRecood);

            if (doc.Sections.Count != 0)
            {
                string path = Path.Combine(Application.StartupPath, "Reports");
                string reportName = "繳費單";
                if (!Directory.Exists(path))
                    Directory.CreateDirectory(path);
                path = Path.Combine(path, reportName + ".doc");

                if (File.Exists(path))
                {
                    int i = 1;
                    while (true)
                    {
                        string newPath = Path.GetDirectoryName(path) + "\\" + Path.GetFileNameWithoutExtension(path) + (i++) + Path.GetExtension(path);
                        if (!File.Exists(newPath))
                        {
                            path = newPath;
                            break;
                        }
                    }
                }

                try
                {
                    doc.Save(path, SaveFormat.Doc);
                    System.Diagnostics.Process.Start(path);
                }
                catch
                {
                    System.Windows.Forms.SaveFileDialog sd1 = new System.Windows.Forms.SaveFileDialog();
                    sd1.Title = "另存新檔";
                    sd1.FileName = "繳費單.doc";
                    sd1.Filter = "Word檔案 (*.doc)|*.doc|所有檔案 (*.*)|*.*";
                    if (sd1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                    {
                        try
                        {
                            doc.Save(sd1.FileName, SaveFormat.Doc);
                            System.Diagnostics.Process.Start(sd1.FileName);
                        }
                        catch
                        {
                            System.Windows.Forms.MessageBox.Show("指定路徑無法存取。", "建立檔案失敗", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
                            return;
                        }
                    }
                }
            }

            MotherForm.SetStatusBarMessage("繳費單產生完成。");
            this.Close();
        }
Пример #23
0
 public async Task <bool> EditCard(int id, PaymentDetail paymentDetail)
 {
     return(await _repositroy.EditCardDetail(id, paymentDetail));
 }
Пример #24
0
        private void BtnSave_Click(object sender, EventArgs e)
        {
            //throw new NotImplementedException();
            Boolean chk1 = setPayment();

            if (chk1 == false)
            {
                MessageBox.Show("", "Error");
                return;
            }
            if (MessageBox.Show("ต้องการ บันทึกช้อมูล ", "", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2) == DialogResult.OK)
            {
                String re = "";
                re = xC.accDB.pytDB.insertPayment(pyt, xC.userId);
                int chk = 0, chkD = 0;
                if (int.TryParse(re, out chk))
                {
                    foreach (Row rowB in grfPay.Rows)
                    {
                        if (rowB[colPdID] == null)
                        {
                            continue;
                        }
                        Decimal       amtE = 0, amtI = 0;
                        PaymentDetail pytd = new PaymentDetail();
                        Decimal.TryParse(rowB[colPdAmtE].ToString(), out amtE);
                        Decimal.TryParse(rowB[colPdAmtI].ToString(), out amtI);
                        amtE += amtI;
                        pytd.payment_detail_id = "";
                        pytd.payment_id        = re;
                        pytd.billing_id        = rowB[colPdBllId].ToString();
                        pytd.job_id            = rowB[colPdJobId].ToString();
                        pytd.job_code          = rowB[colPdJobNo].ToString();
                        pytd.amount            = amtE.ToString();
                        pytd.active            = "1";
                        pytd.remark            = "";
                        pytd.date_create       = "";
                        pytd.date_modi         = "";
                        pytd.date_cancel       = "";
                        pytd.user_create       = "";
                        pytd.user_modi         = "";
                        pytd.user_cancel       = "";
                        pytd.billing_detail_id = rowB[colPdBlldId].ToString();
                        String re1 = "";
                        re1 = xC.accDB.pytdDB.insertPaymentDetail(pytd, xC.userId);
                        if (int.TryParse(re1, out chk))
                        {
                            chkD++;
                            Debtor dtr = new Debtor();
                            dtr.debtor_id = "";
                            dtr.cus_id    = cus.cust_id;
                            if (!pytd.amount.Equals("0"))
                            {
                                dtr.amount = pytd.amount;
                            }
                            else
                            {
                                dtr.amount = "0";
                            }

                            dtr.billing_detail_id = "";
                            dtr.payment_detail_id = re1;
                            dtr.job_id            = pytd.job_id;
                            dtr.remark            = "";
                            dtr.status_debtor     = "2";    // รับชำระ
                            dtr.comp_id           = cop.comp_id;
                            xC.accDB.dtrDB.insertDebtor(dtr, xC.userId);
                        }
                    }
                }
            }
        }
 private void Create_INSERT_Command(PaymentDetail myPaymentDetail)
 {
     //Create the command that must be used to insert values into the Books table..
     daMain.InsertCommand = new SqlCommand("INSERT into PaymentDetails (PaymentID, CreditCardNumber, ExpiryMonth, ExpiryYear, CVC) VALUES (@PaymentID, @CreditCardNumber, @ExpiryMonth, @ExpiryYear, @CVC)", cnMain);
     Build_INSERT_Parameters(myPaymentDetail);
 }
        private async Task <SummaryDetailDto> GetSummaryHelper(int shopId, DateTime DateFrom, DateTime DateTo)
        {
            //0. connect to shop db

            var _docketDataService      = new ShopDataService <Docket>();
            var _returnDataService      = new ShopDataService <Return>();
            var _returnsLineDataService = new ShopDataService <ReturnsLine>();
            var _docketLineDataService  = new ShopDataService <DocketLine>();
            var _paymentDataService     = new ShopDataService <Payments>();
            var _stockDataService       = new ShopDataService <Stock>();

            //1. create dto
            SummaryDetailDto dto = new SummaryDetailDto();

            //2. fetch values from DB
            IEnumerable <Docket> dockets = await _docketDataService.Query(d => d.docket_date >= DateFrom && d.docket_date <= DateTo);

            IEnumerable <int>    docket_ids = dockets.Select(d => d.docket_id).ToList();
            IEnumerable <Return> returns    = await _returnDataService.Query(d => d.returns_date >= DateFrom && d.returns_date <= DateTo);

            IEnumerable <int>         returns_ids  = returns.Select(r => r.returns_id).ToList();
            IEnumerable <ReturnsLine> returnslines = await _returnsLineDataService.Query(rl => returns_ids.Contains(rl.returns_id));

            IEnumerable <DocketLine> docketLines = await _docketLineDataService.Query(dl => docket_ids.Contains(dl.docket_id));


            #region - calculate Avg_Item_Per_Sale
            /** calculate Avg_Item_Per_Sale */
            List <double> sum_sales_by_quantity = new List <double>(); //mean: save the total quantity for every sales
            foreach (var temp_id in docket_ids)
            {
                double sum_dl = 0;
                foreach (var dl in docketLines)
                {
                    if (temp_id == dl.docket_id)
                    {
                        sum_dl += dl.quantity;
                    }
                }
                sum_sales_by_quantity.Add(sum_dl);
            }

            //will be called in value mapping of dto.Avg_Item_Per_Sale
            #endregion

            #region - get payment data
            IEnumerable <Payments> payments = await _paymentDataService.Query(p => p.docket_date >= DateFrom && p.docket_date <= DateTo);

            List <PaymentDetail> paymentDetails = new List <PaymentDetail>();

            foreach (var item in payments.GroupBy(p => p.paymenttype))
            {
                PaymentDetail pd = new PaymentDetail();
                pd.paymenttype = item.Select(i => i.paymenttype).First();
                pd.amount      = item.Sum(i => i.amount);
                paymentDetails.Add(pd);
            }
            #endregion

            #region - create hourly summary
            double[] arr_hour_sale = new double[24];
            for (int i = 1; i < 25; i++)
            {
                arr_hour_sale[i - 1] = (double)dockets.Where(d => d.docket_date.Hour > i - 1 && d.docket_date.Hour <= i).Sum(d => d.total_inc);
            }
            #endregion

            #region -custom data group
            var custom1_db = await _stockDataService.GetSingle(s => s.custom1 != null);

            var custom2_db = await _stockDataService.GetSingle(s => s.custom2 != null);


            CustomDataItem custom1 = new CustomDataItem
            {
                Name     = custom1_db.custom1,
                Quantity = 0,
                Amount   = 0
            };

            CustomDataItem custom2 = new CustomDataItem
            {
                Name     = custom2_db.custom2,
                Quantity = 0,
                Amount   = 0
            };

            CustomDataItem others = new CustomDataItem
            {
                Name     = "others",
                Quantity = 0,
                Amount   = 0
            };

            CustomDataItem extra = new CustomDataItem
            {
                Name     = "extra",
                Quantity = 0,
                Amount   = 0
            };

            foreach (var dl in docketLines)
            {
                string cat1 = _stockDataService.GetSingleEnity(s => s.stock_id == dl.stock_id).cat1;
                if (cat1 != "TASTE" && cat1 != "EXTRA")
                {
                    if (dl.size_level == 1)
                    {
                        custom1.Quantity = custom1.Quantity + dl.quantity;
                        custom1.Amount   = Math.Round((custom1.Amount + (double)dl.sell_inc * dl.quantity) * 100) / 100;
                    }
                    else if (dl.size_level == 2)
                    {
                        custom2.Quantity = custom2.Quantity + dl.quantity;
                        custom2.Amount   = Math.Round((custom2.Amount + (double)dl.sell_inc * dl.quantity) * 100) / 100;
                    }
                    else
                    {
                        others.Quantity = others.Quantity + dl.quantity;
                        others.Amount   = Math.Round((others.Amount + (double)dl.sell_inc * dl.quantity) * 100) / 100;
                    }
                }
                else
                {
                    extra.Quantity = extra.Quantity + dl.quantity;
                    extra.Amount   = Math.Round((extra.Amount + (double)dl.sell_inc * dl.quantity) * 100) / 100;
                }
            }
            List <CustomDataItem> customer_data_sum = new List <CustomDataItem>();
            customer_data_sum.Add(custom1);
            customer_data_sum.Add(custom2);
            customer_data_sum.Add(others);
            customer_data_sum.Add(extra);


            #endregion
            dto.Total_Sales            = (double)dockets.Sum(d => d.total_inc);
            dto.Number_Of_Transactions = dockets.Count();
            dto.Total_Refund           = (double)returns.Sum(r => r.total_inc);
            dto.Total_Discount         = (double)dockets.Sum(d => d.discount);
            if (dto.Number_Of_Transactions == 0)
            {
                dto.Avg_Sales_Value = 0;
            }
            else
            {
                dto.Avg_Sales_Value = Math.Round(dto.Total_Sales / dto.Number_Of_Transactions, 2);
            }
            dto.Avg_Item_Per_Sale = (sum_sales_by_quantity.Count() > 0)?Math.Round(sum_sales_by_quantity.Average(), 2):0;
            dto.Hourly_Sales      = arr_hour_sale;
            dto.PaymentSum        = paymentDetails;
            dto.CustomDataSum     = customer_data_sum;
            //return dto
            return(dto);
        }
 private void Create_UPDATE_Command(PaymentDetail myPaymentDetail)
 {
     daMain.UpdateCommand = new SqlCommand("UPDATE PaymentDetails SET CreditCardNumber =@CreditCardNumber, ExpiryMonth =@ExpiryMonth, ExpiryYear =@ExpiryYear, CVC = @CVC " + "WHERE PaymentID = @Original_ID", cnMain);
     Build_UPDATE_Parameters(myPaymentDetail);
 }
        private void dataGridView1_SelectionChanged(object sender, EventArgs e)
        {
            if (dataGridView1.SelectedRows.Count > 0)
            {
                DataGridViewRow row = dataGridView1.SelectedRows[0];
                int             id  = (int)row.Cells[PaymentIdColumn.Name].Value;

                decimal amountPaid = row.Cells[TotalAmountColumn.Name].Value != null ?
                                     (decimal)row.Cells[TotalAmountColumn.Name].Value : 0;

                VoucherNumberTextbox.Text = row.Cells[VoucherNumberColumn.Name].Value != null ?
                                            row.Cells[VoucherNumberColumn.Name].Value.ToString() : "-";
                AmountPaidTextbox.Text = amountPaid.ToString("Php #,##0.00");
                CustomerTextbox.Text   = row.Cells[CustomerColumn.Name].Value != null ?
                                         row.Cells[CustomerColumn.Name].Value.ToString() : "-";
                DateTextbox.Text = row.Cells[DateColumn.Name].Value != null ?
                                   ((DateTime)row.Cells[DateColumn.Name].Value).ToShortDateString() : "-";
                CashTextbox.Text = row.Cells[CashColumn.Name].Value != null ?
                                   ((decimal)row.Cells[CashColumn.Name].Value).ToString("Php #,##0.00") : "Php 0.00";
                CheckTextbox.Text = row.Cells[CheckColumn.Name].Value != null ?
                                    ((decimal)row.Cells[CheckColumn.Name].Value).ToString("Php #,##0.00") : "Php 0.00";

                PaymentDetail details = this.paymentDetailController.FetchPaymentDetailById(id);

                if (details != null)
                {
                    saleDisplayModelBindingSource.DataSource = null;
                    if (details.SalesPayments.Any())
                    {
                        var sales = details.SalesPayments
                                    .Where(a => a.SalesId != null)
                                    .Select(a => new SaleDisplayModel()
                        {
                            InvoiceNumber = a.Sale.InvoiceNumber,
                            Date          = a.Sale.Date.Value,
                            TotalAmount   = a.Amount.HasValue ? a.Amount.Value : 0
                        });
                        saleDisplayModelBindingSource.DataSource = sales;
                    }
                    dataGridView2.ClearSelection();

                    checkColumnModelBindingSource.DataSource = null;
                    List <Check> checkList = details.Check.ToList();
                    if (details.Check.Any())
                    {
                        var checks = details.Check.Select(a => new CheckColumnModel()
                        {
                            CheckNumber = a.CheckNumber,
                            Bank        = a.Bank,
                            Branch      = a.Branch,
                            Amount      = a.Amount.HasValue ? a.Amount.Value : 0
                        });
                        checkColumnModelBindingSource.DataSource = checks;
                    }
                    dataGridView3.ClearSelection();

                    CreditTextbox.Text = details.SalesPayments.Where(a => a.SalesReturnDetailId != null)
                                         .Sum(a => a.Amount).GetValue().ToString("Php #,##0.00");
                    AmountDueTextbox.Text = details.SalesPayments.Where(a => a.SalesId != null).Sum(a => a.Amount).GetValue().ToString("Php #,##0.00");
                    DiscountTextbox.Text  = details.Discount.GetValue().ToString("Php #,##0.00");
                    TaxTextbox.Text       = details.WitholdingTax.GetValue().ToString("Php #,##0.00");

                    decimal totalAmountDue = details.TotalAmountDue.GetValue();
                    TotalDueTextbox.Text = totalAmountDue.ToString("Php #,##0.00");

                    if (amountPaid == 0)
                    {
                        StatusTextbox.Text = "Not Paid";
                    }
                    else if (amountPaid == totalAmountDue)
                    {
                        StatusTextbox.Text = "Fully Paid";
                    }
                    else if (amountPaid < totalAmountDue)
                    {
                        StatusTextbox.Text = "Partially Paid";
                    }
                }
            }
            else
            {
                VoucherNumberTextbox.Text = "-";
                AmountPaidTextbox.Text    = "Php 0.00";
                CustomerTextbox.Text      = "-";
                DateTextbox.Text          = "-";
                CashTextbox.Text          = "Php 0.00";
                CheckTextbox.Text         = "Php 0.00";

                saleDisplayModelBindingSource.DataSource = null;
                checkColumnModelBindingSource.DataSource = null;
                AmountDueTextbox.Text = "Php 0.00";
                CreditTextbox.Text    = "Php 0.00";
                DiscountTextbox.Text  = "Php 0.00";
                TaxTextbox.Text       = "Php 0.00";
                TotalDueTextbox.Text  = "Php 0.00";
            }
        }
Пример #29
0
 public void CommitTransaction(PaymentDetail paymentDetail)
 {
     // Implements commit transaction
 }
Пример #30
0
        public async Task AddPaymentDetail(PaymentDetail payment)
        {
            await this._ctx.PaymentDetails.AddAsync(payment);

            await this._ctx.SaveChangesAsync();
        }
        public async Task <ActionResult <bool> > WireDepositForPayment(string accountId, [FromBody] PaymentDetail detail)
        {
            var rlt = await Task.Run <bool>(() => svc.WireDepositForPayment(accountId, detail));

            return(Ok(rlt));
        }
Пример #32
0
 public IRockResponse <int> CreatePaymentDetails(PaymentDetail paymentDetail)
 {
     return(Create(paymentDetail, "api/financialpaymentdetails/"));
 }
Пример #33
0
        public Guid AddPayment(PaymentTypeName model, List <PaymentTypeViewModel> ptvm, int[] noMonth)
        {
            Payment payment = new Payment();

            payment.Id              = Guid.NewGuid();
            payment.InvoiceNo       = RandomString(5);
            payment.StudentId       = model.StudentId;
            payment.GrandTotal      = model.TotalSemesterFees;
            payment.Discount        = model.Discount;
            payment.PaidAmount      = model.PaidAmount;
            payment.Due             = model.Due;
            payment.PaymentDate     = model.PaymentDate;
            payment.PaymentMethodId = model.PaymentMethodId;
            payment.SemesterId      = model.SemesterId;
            if (model.PaymentMethodId == 2)
            {
                payment.BankId    = model.BankId;
                payment.CheckNo   = model.CheckNo;
                payment.CheckDate = model.CheckDate;
            }
            else
            {
                payment.BankId    = 0;
                payment.CheckNo   = null;
                payment.CheckDate = null;
            }

            _context.Payments.Add(payment);

            var stdSemester = from std in _context.Students.ToList()
                              join smt in _context.Semesters.ToList() on std.SemesterId equals smt.Id
                              where std.Id == model.StudentId
                              select new { SemesterId = std.SemesterId };

            foreach (var item in ptvm)
            {
                if ((item.Amount > 0 && item.IsChecked == true))
                {
                    if (item.Id == 3)
                    {
                        foreach (var pMonth in noMonth)
                        {
                            PaymentDetail pd = new PaymentDetail();
                            pd.PaymentTypeID = item.Id;
                            pd.PayAmount     = item.Amount;
                            pd.PaymentsId    = payment.Id;
                            pd.PayMonth      = pMonth;
                            _context.PaymentDetails.Add(pd);
                        }
                    }
                    else
                    {
                        PaymentDetail pd = new PaymentDetail();
                        pd.PaymentTypeID = item.Id;
                        pd.PayAmount     = item.Amount;
                        pd.PaymentsId    = payment.Id;
                        _context.PaymentDetails.Add(pd);
                    }
                }
            }

            _context.SaveChanges();

            return(payment.Id);
        }