예제 #1
0
        public void IsGetLoanSchedulesGivingCorrectResult6()
        {
            var loan = new Loan
            {
                MortgageAmount     = 250000,
                AnnualInterestRate = 5.19,
                AmortizationPeriod = 25
            };

            loan.MonthlyPayment = loan.GetMonthlyPayment();

            Assert.AreEqual(1481.17, loan.MonthlyPayment);

            var loanSchedule = new LoanSchedule();

            var loanList = loanSchedule.GetLoanSchedules(loan);

            var loanSchedule1 = loanList.ElementAt(0);

            Assert.AreEqual(1, loanSchedule1.PaymentNumber);
            Assert.AreEqual(1069.74, loanSchedule1.InterestPaid);
            Assert.AreEqual(411.43, loanSchedule1.PrincipalPaid);
            Assert.AreEqual(249588.57, loanSchedule1.RemainingBalance);

            var loanSchedule300 = loanList.ElementAt(299);

            Assert.AreEqual(300, loanSchedule300.PaymentNumber);
            Assert.AreEqual(6.31, loanSchedule300.InterestPaid);
            Assert.AreEqual(1474.86, loanSchedule300.PrincipalPaid);
            Assert.AreEqual(0.00, loanSchedule300.RemainingBalance);
        }
예제 #2
0
        public void IsGetLoanSchedulesGivingCorrectResult1()
        {
            var loan = new Loan
            {
                MortgageAmount     = 1000,
                AnnualInterestRate = 10,
                AmortizationPeriod = 1
            };

            loan.MonthlyPayment = loan.GetMonthlyPayment();

            Assert.AreEqual(87.82, loan.MonthlyPayment);

            var loanSchedule = new LoanSchedule();

            var loanList = loanSchedule.GetLoanSchedules(loan);

            var loanSchedule1 = loanList.ElementAt(0);

            Assert.AreEqual(1, loanSchedule1.PaymentNumber);
            Assert.AreEqual(8.16, loanSchedule1.InterestPaid);
            Assert.AreEqual(79.66, loanSchedule1.PrincipalPaid);
            Assert.AreEqual(920.34, loanSchedule1.RemainingBalance);

            var loanSchedule2 = loanList.ElementAt(1);

            Assert.AreEqual(2, loanSchedule2.PaymentNumber);
            Assert.AreEqual(7.51, loanSchedule2.InterestPaid);
            Assert.AreEqual(80.31, loanSchedule2.PrincipalPaid);
            Assert.AreEqual(840.03, loanSchedule2.RemainingBalance);

            var loanSchedule6 = loanList.ElementAt(5);

            Assert.AreEqual(6, loanSchedule6.PaymentNumber);
            Assert.AreEqual(4.86, loanSchedule6.InterestPaid);
            Assert.AreEqual(82.96, loanSchedule6.PrincipalPaid);
            Assert.AreEqual(512.20, loanSchedule6.RemainingBalance);

            var loanSchedule7 = loanList.ElementAt(6);

            Assert.AreEqual(7, loanSchedule7.PaymentNumber);
            Assert.AreEqual(4.18, loanSchedule7.InterestPaid);
            Assert.AreEqual(83.64, loanSchedule7.PrincipalPaid);
            Assert.AreEqual(428.56, loanSchedule7.RemainingBalance);

            var loanSchedule11 = loanList.ElementAt(10);

            Assert.AreEqual(11, loanSchedule11.PaymentNumber);
            Assert.AreEqual(1.42, loanSchedule11.InterestPaid);
            Assert.AreEqual(86.40, loanSchedule11.PrincipalPaid);
            Assert.AreEqual(87.13, loanSchedule11.RemainingBalance);

            var loanSchedule12 = loanList.ElementAt(11);

            Assert.AreEqual(12, loanSchedule12.PaymentNumber);
            Assert.AreEqual(0.71, loanSchedule12.InterestPaid);
            Assert.AreEqual(87.13, loanSchedule12.PrincipalPaid);
            Assert.AreEqual(0.00, loanSchedule12.RemainingBalance);
        }
예제 #3
0
 public void SaveLoanSchedule(LoanSchedule model)
 {
     using (LoanPriceEntities context = new LoanPriceEntities())
     {
         if (model.ID > 0)
         {
             context.AddObject("LoanSchedule", model);
         }
         else
         {
             context.AddToLoanSchedules(model);
         }
         context.SaveChanges();
     }
 }
예제 #4
0
        public void IsGetLoanSchedulesGivingCorrectResult2()
        {
            var loan = new Loan
            {
                MortgageAmount     = 5000,
                AnnualInterestRate = 5,
                AmortizationPeriod = 2
            };

            loan.MonthlyPayment = loan.GetMonthlyPayment();

            Assert.AreEqual(219.24, loan.MonthlyPayment);

            var loanSchedule = new LoanSchedule();

            var loanList = loanSchedule.GetLoanSchedules(loan);

            var loanSchedule1 = loanList.ElementAt(0);

            Assert.AreEqual(1, loanSchedule1.PaymentNumber);
            Assert.AreEqual(20.62, loanSchedule1.InterestPaid);
            Assert.AreEqual(198.62, loanSchedule1.PrincipalPaid);
            Assert.AreEqual(4801.38, loanSchedule1.RemainingBalance);

            var loanSchedule2 = loanList.ElementAt(1);

            Assert.AreEqual(2, loanSchedule2.PaymentNumber);
            Assert.AreEqual(19.80, loanSchedule2.InterestPaid);
            Assert.AreEqual(199.44, loanSchedule2.PrincipalPaid);
            Assert.AreEqual(4601.94, loanSchedule2.RemainingBalance);

            var loanSchedule23 = loanList.ElementAt(22);

            Assert.AreEqual(23, loanSchedule23.PaymentNumber);
            Assert.AreEqual(1.80, loanSchedule23.InterestPaid);
            Assert.AreEqual(217.44, loanSchedule23.PrincipalPaid);
            Assert.AreEqual(218.37, loanSchedule23.RemainingBalance);

            var loanSchedule24 = loanList.ElementAt(23);

            Assert.AreEqual(24, loanSchedule24.PaymentNumber);
            Assert.AreEqual(0.90, loanSchedule24.InterestPaid);
            Assert.AreEqual(218.37, loanSchedule24.PrincipalPaid);
            Assert.AreEqual(0.00, loanSchedule24.RemainingBalance);
        }
예제 #5
0
        public void IsGetLoanSchedulesGivingCorrectResult5()
        {
            var loan = new Loan
            {
                MortgageAmount     = 100000,
                AnnualInterestRate = 7.9,
                AmortizationPeriod = 20
            };

            loan.MonthlyPayment = loan.GetMonthlyPayment();

            Assert.AreEqual(822.37, loan.MonthlyPayment);

            var loanSchedule = new LoanSchedule();

            var loanList = loanSchedule.GetLoanSchedules(loan);

            var loanSchedule1 = loanList.ElementAt(0);

            Assert.AreEqual(1, loanSchedule1.PaymentNumber);
            Assert.AreEqual(647.75, loanSchedule1.InterestPaid);
            Assert.AreEqual(174.62, loanSchedule1.PrincipalPaid);
            Assert.AreEqual(99825.38, loanSchedule1.RemainingBalance);

            var loanSchedule2 = loanList.ElementAt(1);

            Assert.AreEqual(2, loanSchedule2.PaymentNumber);
            Assert.AreEqual(646.62, loanSchedule2.InterestPaid);
            Assert.AreEqual(175.75, loanSchedule2.PrincipalPaid);
            Assert.AreEqual(99649.63, loanSchedule2.RemainingBalance);

            var loanSchedule239 = loanList.ElementAt(238);

            Assert.AreEqual(239, loanSchedule239.PaymentNumber);
            Assert.AreEqual(10.55, loanSchedule239.InterestPaid);
            Assert.AreEqual(811.82, loanSchedule239.PrincipalPaid);
            Assert.AreEqual(817.14, loanSchedule239.RemainingBalance);

            var loanSchedule240 = loanList.ElementAt(239);

            Assert.AreEqual(240, loanSchedule240.PaymentNumber);
            Assert.AreEqual(5.29, loanSchedule240.InterestPaid);
            Assert.AreEqual(817.14, loanSchedule240.PrincipalPaid);
            Assert.AreEqual(0.00, loanSchedule240.RemainingBalance);
        }
예제 #6
0
        public void IsGetLoanSchedulesGivingCorrectResult4()
        {
            var loan = new Loan
            {
                MortgageAmount     = 300000,
                AnnualInterestRate = 5.390,
                AmortizationPeriod = 25
            };

            loan.MonthlyPayment = loan.GetMonthlyPayment();

            Assert.AreEqual(1812.01, loan.MonthlyPayment);

            var loanSchedule = new LoanSchedule();

            var loanList = loanSchedule.GetLoanSchedules(loan);

            var loanSchedule1 = loanList.ElementAt(0);

            Assert.AreEqual(1, loanSchedule1.PaymentNumber);
            Assert.AreEqual(1332.61, loanSchedule1.InterestPaid);
            Assert.AreEqual(479.40, loanSchedule1.PrincipalPaid);
            Assert.AreEqual(299520.60, loanSchedule1.RemainingBalance);

            var loanSchedule2 = loanList.ElementAt(1);

            Assert.AreEqual(2, loanSchedule2.PaymentNumber);
            Assert.AreEqual(1330.48, loanSchedule2.InterestPaid);
            Assert.AreEqual(481.53, loanSchedule2.PrincipalPaid);
            Assert.AreEqual(299039.07, loanSchedule2.RemainingBalance);

            var loanSchedule299 = loanList.ElementAt(298);

            Assert.AreEqual(299, loanSchedule299.PaymentNumber);
            Assert.AreEqual(15.99, loanSchedule299.InterestPaid);
            Assert.AreEqual(1796.02, loanSchedule299.PrincipalPaid);
            Assert.AreEqual(1804.55, loanSchedule299.RemainingBalance);

            var loanSchedule300 = loanList.ElementAt(299);

            Assert.AreEqual(300, loanSchedule300.PaymentNumber);
            Assert.AreEqual(8.02, loanSchedule300.InterestPaid);
            Assert.AreEqual(1804.55, loanSchedule300.PrincipalPaid);
            Assert.AreEqual(0.00, loanSchedule300.RemainingBalance);
        }
예제 #7
0
        public void IsGetLoanSchedulesGivingCorrectResult3()
        {
            var loan = new Loan
            {
                MortgageAmount     = 10000,
                AnnualInterestRate = 8.9,
                AmortizationPeriod = 10
            };

            loan.MonthlyPayment = loan.GetMonthlyPayment();

            Assert.AreEqual(125.27, loan.MonthlyPayment);

            var loanSchedule = new LoanSchedule();

            var loanList = loanSchedule.GetLoanSchedules(loan);

            var loanSchedule1 = loanList.ElementAt(0);

            Assert.AreEqual(1, loanSchedule1.PaymentNumber);
            Assert.AreEqual(72.83, loanSchedule1.InterestPaid);
            Assert.AreEqual(52.44, loanSchedule1.PrincipalPaid);
            Assert.AreEqual(9947.56, loanSchedule1.RemainingBalance);

            var loanSchedule2 = loanList.ElementAt(1);

            Assert.AreEqual(2, loanSchedule2.PaymentNumber);
            Assert.AreEqual(72.45, loanSchedule2.InterestPaid);
            Assert.AreEqual(52.82, loanSchedule2.PrincipalPaid);
            Assert.AreEqual(9894.74, loanSchedule2.RemainingBalance);

            var loanSchedule119 = loanList.ElementAt(118);

            Assert.AreEqual(119, loanSchedule119.PaymentNumber);
            Assert.AreEqual(1.80, loanSchedule119.InterestPaid);
            Assert.AreEqual(123.47, loanSchedule119.PrincipalPaid);
            Assert.AreEqual(124.29, loanSchedule119.RemainingBalance);

            var loanSchedule120 = loanList.ElementAt(119);

            Assert.AreEqual(120, loanSchedule120.PaymentNumber);
            Assert.AreEqual(0.91, loanSchedule120.InterestPaid);
            Assert.AreEqual(124.29, loanSchedule120.PrincipalPaid);
            Assert.AreEqual(0.00, loanSchedule120.RemainingBalance);
        }
예제 #8
0
        public void EditSchedule(int loanID, DataTable dt)
        {
            try
            {
                using (LoanPriceEntities context = new LoanPriceEntities())
                {
                    List <LoanSchedule> oldScheduleList = context.LoanSchedules.Where(s => s.LoanID == loanID).ToList();
                    if (oldScheduleList.Count > 0)
                    {
                        LoanScheduleBL loanScheduleBL = new LoanScheduleBL();
                        loanScheduleBL.RemoveLoanSchedule(loanID);

                        for (int i = 0; i < dt.Rows.Count; i++)
                        {
                            // oldScheduleList[i].ID = Convert.ToInt16(dt.Rows[i][0]);

                            //if (i >= oldScheduleList.Count)
                            //{
                            LoanSchedule loanSchedule = new LoanSchedule();
                            loanSchedule.LoanID       = loanID;
                            loanSchedule.StartDate    = Convert.ToDateTime(dt.Rows[i][1].ToString());
                            loanSchedule.EndDate      = Convert.ToDateTime(dt.Rows[i][2].ToString());
                            loanSchedule.CoupFrac     = Convert.ToDecimal(Convert.ToDecimal(dt.Rows[i][3].ToString()).ToString("0.00"));
                            loanSchedule.Notation     = Convert.ToDecimal(dt.Rows[i][4].ToString());
                            loanSchedule.Amortisation = Convert.ToDecimal(Convert.ToDecimal(dt.Rows[i][5].ToString()).ToString("0.00"));
                            loanSchedule.Factor       = Convert.ToDecimal(Convert.ToDecimal(dt.Rows[i][6].ToString()).ToString("0.00000"));
                            if (dt.Rows[i][7] != null)
                            {
                                loanSchedule.Spread = Convert.ToDecimal(Convert.ToDecimal(dt.Rows[i][7].ToString()).ToString("0.00000"));
                            }
                            if (dt.Rows[i][8] != null)
                            {
                                loanSchedule.CouponPaymentDate = Convert.ToDateTime(dt.Rows[i][8].ToString());
                            }
                            if (dt.Rows[i][9] != null)
                            {
                                loanSchedule.RiskFreeDP1 = Convert.ToDecimal(Convert.ToDecimal(dt.Rows[i][9].ToString()).ToString("0.0000000"));
                            }
                            if (dt.Rows[i][10] != null)
                            {
                                loanSchedule.RiskFreeDP2 = Convert.ToDecimal(Convert.ToDecimal(dt.Rows[i][10].ToString()).ToString("0.0000000"));
                            }
                            if (dt.Rows[i][11] != null)
                            {
                                loanSchedule.FloatingRate = Convert.ToDecimal(Convert.ToDecimal(dt.Rows[i][11].ToString()).ToString("0.0000000"));
                            }
                            if (dt.Rows[i][12] != null)
                            {
                                loanSchedule.AllInRate = Convert.ToDecimal(Convert.ToDecimal(dt.Rows[i][12].ToString()).ToString("0.00000"));
                            }
                            if (dt.Rows[i][13] != null)
                            {
                                loanSchedule.Interest = Convert.ToDecimal(Convert.ToDecimal(dt.Rows[i][13].ToString()).ToString("0.00000"));
                            }
                            if (dt.Rows[i][14] != null)
                            {
                                loanSchedule.Days = Convert.ToInt16(dt.Rows[i][14].ToString());
                            }
                            if (dt.Rows[i][15] != null)
                            {
                                loanSchedule.AmortisationInt = Convert.ToDecimal(Convert.ToDecimal(dt.Rows[i][15].ToString()).ToString("0.0000000"));
                            }
                            SaveLoanSchedule(loanSchedule);
                            // }
                            //else
                            //{
                            //    oldScheduleList[i].StartDate = Convert.ToDateTime(dt.Rows[i][1].ToString());
                            //    oldScheduleList[i].EndDate = Convert.ToDateTime(dt.Rows[i][2].ToString());
                            //    oldScheduleList[i].CoupFrac = Convert.ToDecimal(Convert.ToDecimal(dt.Rows[i][3].ToString()).ToString("0.00"));
                            //    oldScheduleList[i].Notation = Convert.ToDecimal(dt.Rows[i][4].ToString());
                            //    oldScheduleList[i].Amortisation = Convert.ToDecimal(Convert.ToDecimal(dt.Rows[i][5].ToString()).ToString("0.00"));
                            //    oldScheduleList[i].Factor = Convert.ToDecimal(Convert.ToDecimal(dt.Rows[i][6].ToString()).ToString("0.00000"));
                            //}
                        }
                    }
                    else
                    {
                        foreach (DataRow dr in dt.Rows)
                        {
                            LoanSchedule loanSchedule = new LoanSchedule();
                            loanSchedule.LoanID            = loanID;
                            loanSchedule.StartDate         = Convert.ToDateTime(dr["StartDate"]);
                            loanSchedule.EndDate           = Convert.ToDateTime(dr["EndDate"]);
                            loanSchedule.CoupFrac          = Convert.ToDecimal(dr["CoupFrac"]);
                            loanSchedule.Notation          = Convert.ToDecimal(dr["Notation"]);
                            loanSchedule.Amortisation      = Convert.ToDecimal(dr["Amortisation"]);
                            loanSchedule.Factor            = Convert.ToDecimal(Convert.ToDecimal(dr["Factor"]).ToString("0.00000"));
                            loanSchedule.Spread            = Convert.ToDecimal(dr["Spread"]);
                            loanSchedule.AllInRate         = Convert.ToDecimal(dr["AllInRate"]);
                            loanSchedule.CouponPaymentDate = Convert.ToDateTime(dr["CouponPaymentDate"]);
                            loanSchedule.RiskFreeDP1       = Convert.ToDecimal(dr["RiskFreeDP1"]);
                            loanSchedule.RiskFreeDP2       = Convert.ToDecimal(dr["RiskFreeDP2"]);
                            loanSchedule.FloatingRate      = Convert.ToDecimal(dr["FloatingRate"]);
                            loanSchedule.Interest          = Convert.ToDecimal(dr["Interest"]);
                            loanSchedule.Days            = Convert.ToInt16(dr["Days"]);
                            loanSchedule.AmortisationInt = Convert.ToDecimal(dr["AmortisationInt"]);
                            SaveLoanSchedule(loanSchedule);
                        }
                    }
                    context.SaveChanges();
                }
            }
            catch (Exception)
            {
            }
        }
예제 #9
0
        public string AddImportedLoans(Loans item)
        {
            LogsBLL logBL = new LogsBLL();
            string  str   = "";

            try
            {
                using (LoanPriceEntities context = new LoanPriceEntities())
                {
                    string codeName = item.CodeName;
                    if (CheckForLoanCode(item.CodeName))
                    {
                        context.AddToLoans(item);
                        context.SaveChanges();
                        //item = GetLoanByCode(codeName);

                        LoanScheduleBL loanScheduleBL = new LoanScheduleBL();
                        string         couponDT       = item.CouponDate.ToString();
                        DateTime       cpnDT;
                        if (couponDT == string.Empty)
                        {
                            cpnDT = AddBusinessDays(DateTime.Now, 10);
                        }
                        else
                        {
                            cpnDT = Convert.ToDateTime(item.CouponDate);
                        }
                        DateTime  tradeDate  = DateTime.Now;
                        DataTable dtSchedule = loanScheduleBL.GenerateTable(15, Convert.ToInt16(item.NoOfAmortisationPoint), Convert.ToDateTime(item.AmortisationsStartPoint), item.CouponFrequency.ToString(), item.Notional.ToString(), Convert.ToDateTime(item.Maturity_Date), Convert.ToDateTime(item.CouponDate), Convert.ToDecimal(item.Margin), Convert.ToString(item.Currency), Convert.ToDateTime(tradeDate), AddBusinessDays(Convert.ToDateTime(tradeDate), 10));
                        if (dtSchedule != null)
                        {
                            try
                            {
                                foreach (DataRow dr in dtSchedule.Rows)
                                {
                                    LoanSchedule loanSchedule = new LoanSchedule();
                                    loanSchedule.LoanID            = item.ID;
                                    loanSchedule.StartDate         = Convert.ToDateTime(dr["StartDate"]);
                                    loanSchedule.EndDate           = Convert.ToDateTime(dr["EndDate"]);
                                    loanSchedule.Notation          = Convert.ToDecimal(dr["Notation"]);
                                    loanSchedule.CoupFrac          = Convert.ToDecimal(dr["CoupFrac"]);
                                    loanSchedule.Amortisation      = Convert.ToDecimal(dr["Amortisation"]);
                                    loanSchedule.Factor            = Convert.ToDecimal(dr["Factor"]);
                                    loanSchedule.CouponPaymentDate = Convert.ToDateTime(dr["CouponPaymentDate"]);
                                    loanSchedule.Spread            = Convert.ToDecimal(dr["Spread"]);
                                    loanSchedule.RiskFreeDP1       = Convert.ToDecimal(dr["RiskFreeDP1"]);
                                    loanSchedule.RiskFreeDP2       = Convert.ToDecimal(dr["RiskFreeDP2"]);
                                    loanSchedule.FloatingRate      = Convert.ToDecimal(dr["FloatingRate"]);
                                    loanSchedule.AllInRate         = Convert.ToDecimal(dr["AllInRate"]);
                                    loanSchedule.Interest          = Convert.ToDecimal(dr["Interest"]);
                                    loanSchedule.Days            = Convert.ToInt16(dr["Days"]);
                                    loanSchedule.AmortisationInt = Convert.ToDecimal(dr["AmortisationInt"]);
                                    loanScheduleBL.SaveLoanSchedule(loanSchedule);
                                }
                            }
                            catch (Exception ex)
                            {
                                str = ex.Message;
                                //  str = ex.Message;
                            }
                        }
                    }
                    else
                    {
                        DuplicateLoan loan = new DuplicateLoan();
                        loan.CodeName        = item.CodeName;
                        loan.Borrower        = item.Borrower;
                        loan.Country         = item.Country;
                        loan.Sector          = item.Sector;
                        loan.Maturity_Date   = item.Maturity_Date;
                        loan.Signing_Date    = item.Signing_Date;
                        loan.FixedOrFloating = item.FixedOrFloating;
                        loan.Margin          = item.Margin;
                        loan.Currency        = item.Currency;
                        loan.CouponFrequency = item.CouponFrequency;
                        loan.FacilitySize    = item.FacilitySize;
                        loan.Bilateral       = item.Bilateral;
                        loan.Amortizing      = item.Amortizing;

                        loan.AmortisationsStartPoint = loan.AmortisationsStartPoint;
                        loan.CouponDate            = loan.CouponDate;
                        loan.Notional              = loan.Notional;
                        loan.NoOfAmortisationPoint = loan.NoOfAmortisationPoint;

                        context.AddToDuplicateLoans(loan); context.SaveChanges();
                    }
                }
            }
            catch (Exception ex)
            {
                str = ex.Message;
                if (ex.InnerException != null)
                {
                    str = str + " :: " + ex.InnerException.Message;
                }
            }
            return(str);
        }
예제 #10
0
        public async Task <(bool Success, string Error, byte[] FileBytes, string FileName)> ExportLoanScheduleByReceiptIdAsync(int clientReceiptId)
        {
            var success = false;
            var error   = "";

            byte[] fileBytes = null;
            var    fileName  = "";

            try
            {
                // fetch client info
                var receiptInfo = await _clientReceiptRepository.FetchFullByIdAsync(clientReceiptId);

                if (receiptInfo != null && receiptInfo.Client != null)
                {
                    // fetch timezone for conversion
                    var timeZone    = _dateTimeService.FetchTimeZoneInfo(Constants.System.TimeZone);
                    var receiptDate = _dateTimeService.ConvertUtcToDateTime(receiptInfo.CreatedUtc, timeZone);

                    // prepare belonging list
                    var belongingsList = await _clientBelongingRepository.ListClientBelongingByReceiptIdAsync(clientReceiptId);

                    decimal loanAmount = 0;

                    if (belongingsList?.Any() == true)
                    {
                        // order by name
                        belongingsList = belongingsList.OrderBy(b => b.Metal).ToList();
                        foreach (var item in belongingsList)
                        {
                            if (item.TransactionAction == Constants.TransactionAction.Loan)
                            {
                                loanAmount += item.FinalPrice ?? 0;
                            }
                        }
                    }

                    var pdfLoanSchedule = new LoanSchedule(billDate: receiptDate, clientNumber: receiptInfo.Client.ReferenceNumber, receiptNumber: receiptInfo.ReceiptNumber,
                                                           clientName: $"{receiptInfo.Client.FirstName } {receiptInfo.Client.LastName}",
                                                           clientAddress: Encryption.Decrypt(receiptInfo.Client.AddressEncrypted, receiptInfo.Client.AddressUniqueKey),
                                                           phoneNumber: Classes.Helper.FormatPhoneNumber(Encryption.Decrypt(receiptInfo.Client.ContactNumberEncrypted, receiptInfo.Client.ContactNumberUniqueKey)),
                                                           emailAddress: receiptInfo.Client.EmailAddress, rootPath: _env.WebRootPath, loanAmount: loanAmount, loanPercent: _globalOptions.LoanPercentForCalc);

                    // Create the document using MigraDoc.
                    var pdfLoanScheduleDocument = pdfLoanSchedule.CreateDocument();
                    pdfLoanScheduleDocument.UseCmykColor = true;

                    // Create a renderer for PDF that uses Unicode font encoding.
                    var pdfRenderer = new PdfDocumentRenderer(true);

                    // Set the MigraDoc document.
                    pdfRenderer.Document = pdfLoanScheduleDocument;

                    // Create the PDF document.
                    pdfRenderer.RenderDocument();

                    // Save the loan schedule document...
                    using (var stream = new MemoryStream())
                    {
                        pdfRenderer.Save(stream, false);
                        fileBytes = stream.ToArray();
                    }

                    fileName = $"{receiptInfo.Client.FirstName}_{receiptInfo.Client.LastName}_{receiptInfo.ReceiptNumber}_LoanSchedule.pdf";
                    success  = true;
                }
                else
                {
                    error = "Unable to locate receipt information";
                }
            }
            catch (Exception ex)
            {
                error = "Somethong went wrong while processing your request.";
                _logger.LogError("ClientService.ExportLoanScheduleByReceiptIdAsync - exception:{@Ex}", args: new object[] { ex });
            }

            return(Success : success, Error : error, FileBytes : fileBytes, FileName : fileName);
        }
예제 #11
0
        public async Task <(bool Success, string Error, byte[] FileBytes, string FileName)> ExportReceiptByReceiptIdAsync(int clientReceiptId)
        {
            var success = false;
            var error   = "";

            byte[] resultBytes = null;
            var    fileName    = "";

            byte[] receiptBytes      = null;
            byte[] loanScheduleBytes = null;

            try
            {
                var extension = "pdf";

                // fetch client info
                var receiptInfo = await _clientReceiptRepository.FetchFullByIdAsync(clientReceiptId);

                if (receiptInfo != null && receiptInfo.Client != null)
                {
                    // fetch timezone for conversion
                    var timeZone    = _dateTimeService.FetchTimeZoneInfo(Constants.System.TimeZone);
                    var receiptDate = _dateTimeService.ConvertUtcToDateTime(receiptInfo.CreatedUtc, timeZone);

                    // prepare belonging list
                    var belongingsList = await _clientBelongingRepository.ListClientBelongingByReceiptIdAsync(clientReceiptId);

                    decimal clientPays      = 0;
                    decimal clientGets      = 0;
                    decimal billAmount      = 0;
                    decimal loanAmount      = 0;
                    bool    clientPaysFinal = false;
                    decimal totalPurchase   = 0;
                    decimal totalSell       = 0;
                    decimal hstTotal        = 0;

                    if (belongingsList?.Any() == true)
                    {
                        // order by name to print in receipt
                        belongingsList = belongingsList.OrderBy(b => b.Metal).ToList();
                        foreach (var item in belongingsList)
                        {
                            // calculate bill amount
                            if (item.BusinessGetsMoney)
                            {
                                clientPays += item.FinalPrice ?? 0;
                            }
                            if (item.BusinessPaysMoney)
                            {
                                clientGets += item.FinalPrice ?? 0;
                            }
                            billAmount      = Math.Abs(clientPays - clientGets);
                            clientPaysFinal = clientPays > clientGets;

                            // determine total loan amount from receipt
                            if (item.TransactionAction == Constants.TransactionAction.Loan)
                            {
                                loanAmount += item.FinalPrice ?? 0;
                            }

                            // determine total purchase amount from receipt
                            if (item.TransactionAction == Constants.TransactionAction.Sell)
                            {
                                // if business sells an item, it is purchase for client
                                totalPurchase += item.FinalPrice ?? 0;
                            }

                            // determine total sell amount from receipt
                            if (item.TransactionAction == Constants.TransactionAction.Purchase)
                            {
                                // if business purchases an item, it is sell for client
                                totalSell += item.FinalPrice ?? 0;
                            }

                            hstTotal += item.HstAmount ?? 0;
                        }
                    }

                    // prepare viewmodel
                    ReceiptViewModel model = new ReceiptViewModel
                    {
                        BillDate            = receiptDate,
                        ClientNumber        = receiptInfo.Client.ReferenceNumber,
                        ReceiptNumber       = receiptInfo.ReceiptNumber,
                        ClientName          = $"{receiptInfo.Client.FirstName} {receiptInfo.Client.LastName}",
                        Address             = Encryption.Decrypt(receiptInfo.Client.AddressEncrypted, receiptInfo.Client.AddressUniqueKey),
                        ContactNumber       = Classes.Helper.FormatPhoneNumber(Encryption.Decrypt(receiptInfo.Client.ContactNumberEncrypted, receiptInfo.Client.ContactNumberUniqueKey)),
                        EmailAddress        = receiptInfo.Client.EmailAddress,
                        ClientPaysFinal     = clientPaysFinal,
                        PrincipalLoanAmount = loanAmount,
                        PurchaseTotal       = totalPurchase,
                        SellTotal           = totalSell,
                        Belongings          = belongingsList,
                        HstTotal            = hstTotal
                    };

                    // calculate final total
                    model.BillAmount = (model.HstTotal + model.PrincipalLoanAmount + model.PurchaseTotal) - model.SellTotal;

                    // generate receipt
                    var pdfReceipt = new Reports.ClientReceipt(model, _env.WebRootPath);

                    // Create the document using MigraDoc.
                    var pdfReceiptDocument = pdfReceipt.CreateDocument();
                    pdfReceiptDocument.UseCmykColor = true;

                    // Create a renderer for PDF that uses Unicode font encoding.
                    var pdfRenderer = new PdfDocumentRenderer(true)
                    {
                        // Set the MigraDoc document.
                        Document = pdfReceiptDocument
                    };

                    // Create the PDF document.
                    pdfRenderer.RenderDocument();

                    // Save the receipt document...
                    using (var stream = new MemoryStream())
                    {
                        pdfRenderer.Save(stream, false);
                        receiptBytes = stream.ToArray();
                    }

                    // assign receipt bytes to result in case there is no loan schedule to add
                    resultBytes = receiptBytes;

                    // generate loan schedule and zip multiple documents, if required
                    if (loanAmount > 0)
                    {
                        var pdfLoanSchedule = new LoanSchedule(billDate: receiptDate, clientNumber: receiptInfo.Client.ReferenceNumber, receiptNumber: receiptInfo.ReceiptNumber,
                                                               clientName: $"{receiptInfo.Client.FirstName} {receiptInfo.Client.LastName}",
                                                               clientAddress: Encryption.Decrypt(receiptInfo.Client.AddressEncrypted, receiptInfo.Client.AddressUniqueKey),
                                                               phoneNumber: Classes.Helper.FormatPhoneNumber(Encryption.Decrypt(receiptInfo.Client.ContactNumberEncrypted, receiptInfo.Client.ContactNumberUniqueKey)),
                                                               emailAddress: receiptInfo.Client.EmailAddress, rootPath: _env.WebRootPath, loanAmount: loanAmount, loanPercent: _globalOptions.LoanPercentForCalc);

                        // Create the document using MigraDoc.
                        var pdfLoanScheduleDocument = pdfLoanSchedule.CreateDocument();
                        pdfLoanScheduleDocument.UseCmykColor = true;

                        // Create a renderer for PDF that uses Unicode font encoding.
                        pdfRenderer = new PdfDocumentRenderer(true)
                        {
                            // Set the MigraDoc document.
                            Document = pdfLoanScheduleDocument
                        };

                        // Create the PDF document.
                        pdfRenderer.RenderDocument();

                        // Save the loan schedule document...
                        using (var stream = new MemoryStream())
                        {
                            pdfRenderer.Save(stream, false);
                            loanScheduleBytes = stream.ToArray();
                        }

                        // zip both documents
                        using (var compressedFileStream = new MemoryStream())
                        {
                            //Create an archive and store the stream in memory.
                            using (var zipArchive = new ZipArchive(compressedFileStream, ZipArchiveMode.Update, false))
                            {
                                // add receipt
                                if (receiptBytes != null)
                                {
                                    var receiptEntry = zipArchive.CreateEntry($"{receiptInfo.Client.FirstName}_{receiptInfo.Client.LastName}_{receiptInfo.ReceiptNumber}_Receipt.pdf");

                                    //Get the stream of the attachment
                                    using (var receiptStream = new MemoryStream(receiptBytes))
                                    {
                                        using (var zipEntryStream = receiptEntry.Open())
                                        {
                                            //Copy the attachment stream to the zip entry stream
                                            receiptStream.CopyTo(zipEntryStream);
                                        }
                                    }
                                }

                                // add loan schedule
                                if (loanScheduleBytes != null)
                                {
                                    var loanScheduleEntry = zipArchive.CreateEntry($"{receiptInfo.Client.FirstName}_{receiptInfo.Client.LastName}_{receiptInfo.ReceiptNumber}_LoanSchedule.pdf");

                                    //Get the stream of the attachment
                                    using (var loanScheduleStream = new MemoryStream(loanScheduleBytes))
                                    {
                                        using (var zipEntryStream = loanScheduleEntry.Open())
                                        {
                                            //Copy the attachment stream to the zip entry stream
                                            loanScheduleStream.CopyTo(zipEntryStream);
                                        }
                                    }
                                }
                            }
                            // override file bytes with zip file
                            resultBytes = compressedFileStream.ToArray();
                            extension   = "zip";
                        }
                    }

                    fileName = $"{receiptInfo.Client.FirstName}_{receiptInfo.Client.LastName}_{receiptInfo.ReceiptNumber}_Receipt.{extension}";
                    success  = true;
                }
                else
                {
                    error = "Unable to locate receipt information";
                }
            }
            catch (Exception ex)
            {
                error = "Somethong went wrong while processing your request.";
                _logger.LogError("ClientService.ExportReceiptByReceiptIdAsync - exception:{@Ex}", args: new object[] { ex });
            }

            return(Success : success, Error : error, FileBytes : resultBytes, FileName : fileName);
        }