Beispiel #1
0
		} // BuildLoan

		/// <summary>
		/// Looks like this method is not used any more (after removing edit loan button from underwriter's
		/// approval dialogue. The button was located in _ProfileTemplateMain.cshtml.
		/// </summary>
		/// <param name="cr"></param>
		/// <param name="amount"></param>
		/// <param name="now"></param>
		/// <returns></returns>
		private Loan CreateLoanFromTemplate(CashRequest cr, decimal amount, DateTime now) {
			var model = EditLoanDetailsModel.Parse(cr.LoanTemplate);
			var loan = _builder.CreateLoan(model);
			loan.LoanType = cr.LoanType;
			loan.CashRequest = cr;

			AdjustDates(now, loan);
			AdjustBalances(amount, loan);

			var c = new LoanRepaymentScheduleCalculator(loan, now, CurrentValues.Instance.AmountToChargeFrom);
			c.GetState();

			if (loan.Id > 0) {
				try {
					ServiceClient serviceClient = new ServiceClient();
					long nlLoanId = serviceClient.Instance.GetLoanByOldID(loan.Id, cr.Customer.Id, 1)
						.Value;
					if (nlLoanId > 0) {
						var nlModel = serviceClient.Instance.GetLoanState(loan.Customer.Id, nlLoanId, DateTime.UtcNow, 1, true).Value;
						log.Msg("<<< NL_Compare: {0}\n===============loan: {1}  >>>", nlModel, loan);
					}
					// ReSharper disable once CatchAllClause
				} catch (Exception ex) {
					log.Msg("<<< NL_Compare fail at: {0}, err: {1}", Environment.StackTrace, ex.Message);
				} // try
			} // if

			loan.LoanSource = cr.LoanSource;
			return loan;
		} // CreateLoanFromTemplate
Beispiel #2
0
        public void create_loan_with_template()
        {
            var cr = new CashRequest()
            {
                InterestRate    = 0.06M,
                RepaymentPeriod = 6,
                LoanType        = new StandardLoanType()
            };

            var loan  = _loanBuilder.CreateLoan(cr, 3000, DateTime.UtcNow);
            var model = _loanDetailsModelBuilder.BuildModel(loan);

            cr.LoanTemplate = model.ToJSON();

            _customer.CashRequests.Add(cr);
            _customer.BankAccount = new BankAccount()
            {
                AccountNumber = "111111", SortCode = "1111111"
            };
            _customer.CreditSum = 3000;

            var loan2 = _lc.CreateLoan(_customer, 10, null, new DateTime(2013, 10, 21));

            Assert.That(loan2.Schedule.Count, Is.EqualTo(6));
            Assert.That(loan2.LoanAmount, Is.EqualTo(10));
            Assert.That(loan2.Schedule[0].LoanRepayment, Is.EqualTo(5));
        }
Beispiel #3
0
		} // constructor

		public Loan CreateLoan(CashRequest cr, decimal amount, DateTime now, int interestOnlyTerm = 0) {
			Loan l = string.IsNullOrEmpty(cr.LoanTemplate)
				? CreateNewLoan(cr, amount, now, cr.RepaymentPeriod, interestOnlyTerm)
				: CreateLoanFromTemplate(cr, amount, now);

			l.CustomerSelectedTerm = cr.RepaymentPeriod;

			return l;
		} // CreateLoan
Beispiel #4
0
        protected void CreateLoan(DateTime startDate, int amount)
        {
            _calculator.Calculate(amount, _loan, startDate);
            _customer.Loans.Add(_loan);
            var cr = new CashRequest();

            _customer.CashRequests.Add(cr);
            _loan.Customer = _customer;
        }
Beispiel #5
0
        private ExecutionResult GetCash(CashRequest request, ExecutionContext context)
        {
            var account = AdbRepository.AccountData.GetEntityById(request.AccountId);

            if (account.Balance > request.Summ)
            {
                account.Balance -= request.Summ;
            }
            AdbRepository.AccountData.Save(account);
            return(new ExecutionResult());
        }
        public void SetUp()
        {
            _loanOriginal = new Loan();
            _cashRequest  = new CashRequest()
            {
                InterestRate = 0.06m, LoanType = new StandardLoanType()
            };
            _calculator = new LoanScheduleCalculator();
            _calculator.Calculate(1000, _loanOriginal, new DateTime(2012, 10, 21));

            _builder = new ChangeLoanDetailsModelBuilder();
        }
        public int ReCalculateRepaymentPeriod(CashRequest cashRequest)
        {
            var result = cashRequest.RepaymentPeriod;

            if (!string.IsNullOrEmpty(cashRequest.LoanTemplate))
            {
                var model = EditLoanDetailsModel.Parse(cashRequest.LoanTemplate);
                var loan  = _builder.CreateLoan(model);
                var start = DateTime.UtcNow;
                var end   = loan.Schedule.Last().Date;
                result = GetTotalMonts(start, end);
            }
            return(result);
        }
Beispiel #8
0
		public void AddOffer() {
			GetLastOffer lastOfferstrategy = new GetLastOffer(374);
			lastOfferstrategy.Execute();
			NL_Offers lastOffer = lastOfferstrategy.Offer;
			long crID = 337;
			long decisionID = 23;

			ICashRequestRepository crRep = ObjectFactory.GetInstance<CashRequestRepository>();
			CashRequest	oldCashRequest = crRep.Get(crID);

			lastOffer.DecisionID = decisionID;
			lastOffer.LoanSourceID = oldCashRequest.LoanSource.ID;
			lastOffer.LoanTypeID = oldCashRequest.LoanType.Id;
			lastOffer.RepaymentIntervalTypeID = (int)RepaymentIntervalTypes.Month;
			lastOffer.StartTime = (DateTime)oldCashRequest.OfferStart;
			lastOffer.EndTime = (DateTime)oldCashRequest.OfferValidUntil;
			lastOffer.RepaymentCount = oldCashRequest.ApprovedRepaymentPeriod ?? 0;
			lastOffer.Amount = (decimal)oldCashRequest.ManagerApprovedSum;
			lastOffer.MonthlyInterestRate = oldCashRequest.InterestRate;
			lastOffer.CreatedTime = DateTime.UtcNow;
			lastOffer.BrokerSetupFeePercent = oldCashRequest.BrokerSetupFeePercent;
			lastOffer.Notes = "bbb";
			lastOffer.DiscountPlanID = oldCashRequest.DiscountPlan.Id;
			lastOffer.IsLoanTypeSelectionAllowed = oldCashRequest.IsLoanTypeSelectionAllowed == 1;
			lastOffer.SendEmailNotification = !oldCashRequest.EmailSendingBanned;
			lastOffer.IsRepaymentPeriodSelectionAllowed = oldCashRequest.IsCustomerRepaymentPeriodSelectionAllowed;
			lastOffer.IsAmountSelectionAllowed = true;

			// offer-fees
			NL_OfferFees setupFee = new NL_OfferFees() {
				LoanFeeTypeID = (int)NLFeeTypes.SetupFee,
				Percent = oldCashRequest.ManualSetupFeePercent,
				//OneTimePartPercent = 1, DistributedPartPercent = 0 // default
			};
			if (oldCashRequest.SpreadSetupFee != null && oldCashRequest.SpreadSetupFee == true) {
				setupFee.LoanFeeTypeID = (int)NLFeeTypes.ServicingFee;
				setupFee.OneTimePartPercent = 0;
				setupFee.DistributedPartPercent = 1;
			}
			List<NL_OfferFees> offerFees = new List<NL_OfferFees>() { setupFee };
			//this.m_oLog.Debug("NL: offer: {0}, offerFees: {1}" + "", lastOffer, offerFees);
			AddOffer offerStrategy = new AddOffer(lastOffer, offerFees);
			offerStrategy.Execute();
			Console.WriteLine(offerStrategy.OfferID);
			Console.WriteLine(offerStrategy.Error);
		}
Beispiel #9
0
        public void create_loan_with_template_and_shift_installments()
        {
            var cr = new CashRequest()
            {
                InterestRate    = 0.06M,
                RepaymentPeriod = 6,
                LoanType        = new StandardLoanType()
            };

            var loan  = _loanBuilder.CreateLoan(cr, 3000, new DateTime(2013, 10, 11));
            var model = _loanDetailsModelBuilder.BuildModel(loan);

            cr.LoanTemplate = model.ToJSON();

            var actual = _loanBuilder.CreateLoan(cr, 10, new DateTime(2013, 11, 5));

            Assert.That(actual.Schedule[0].Date, Is.EqualTo(new DateTime(2013, 12, 6)));
        }
		public bool IsAmountChangingAllowed(CashRequest cr) {
			if (cr == null || string.IsNullOrEmpty(cr.LoanTemplate))
				return true;

			var model = EditLoanDetailsModel.Parse(cr.LoanTemplate);

			//compare number of installments/other actions
			if (model.Items.Count(i => i.Type == "Installment") != cr.RepaymentPeriod)
				return false;
			if (model.Items.Count != cr.RepaymentPeriod)
				return false;

			//compare template balances with actual
			var expectedBalances = cr.LoanType.GetBalances(cr.ApprovedSum(), cr.RepaymentPeriod);
			var actualBalances = model.Items.Where(i => i.Type == "Installment").Select(i => i.Balance);
			if (expectedBalances.Except(actualBalances).Any())
				return false;

			return true;
		}
Beispiel #11
0
        public void create_loan_without_template()
        {
            var cr = new CashRequest()
            {
                InterestRate    = 0.06M,
                RepaymentPeriod = 3,
                LoanType        = new StandardLoanType()
            };

            _customer.CashRequests.Add(cr);
            _customer.BankAccount = new BankAccount()
            {
                AccountNumber = "111111", SortCode = "222222"
            };

            var loan = _lc.CreateLoan(_customer, 10000, null, new DateTime(2013, 10, 21));

            Assert.That(loan.Schedule.Count, Is.EqualTo(3));
            Assert.That(loan.LoanAmount, Is.EqualTo(10000));
        }
Beispiel #12
0
        public JsonResult ActivateMainStrategy(int customerId)
        {
            int underwriterId = this.context.User.Id;

            Customer customer = this.customerRepository.Get(customerId);

            CashRequest cr = customer.LastCashRequest;

            if (cr != null)
            {
                new MainStrategyClient(
                    underwriterId,
                    customer.Id,
                    customer.IsAvoid,
                    NewCreditLineOption.SkipEverythingAndApplyAutoRules,
                    cr.Id,
                    null
                    ).ExecuteAsync();
            }             // if

            return(Json(true));
        }         // ActivateMainStrategy
Beispiel #13
0
        public void create_loan_with_template()
        {
            var cr = new CashRequest()
            {
                InterestRate    = 0.06M,
                RepaymentPeriod = 6,
                LoanType        = new StandardLoanType(),
                DiscountPlan    = new DiscountPlan()
                {
                    ValuesStr = "+0, -10, -20"
                }
            };

            var loan = _loanBuilder.CreateLoan(cr, 3000, DateTime.UtcNow);

            Assert.That(loan.Schedule[0].InterestRate * 100m, Is.EqualTo(6m));
            Assert.That(loan.Schedule[1].InterestRate * 100m, Is.EqualTo(6m - 0.6m));
            Assert.That(loan.Schedule[2].InterestRate * 100m, Is.EqualTo(6m - 1.2m));
            Assert.That(loan.Schedule[3].InterestRate * 100m, Is.EqualTo(6m));
            Assert.That(loan.Schedule[4].InterestRate * 100m, Is.EqualTo(6m));
            Assert.That(loan.Schedule[5].InterestRate * 100m, Is.EqualTo(6m));
        }
Beispiel #14
0
        }         // BuildLoanCost

        private Loan CreateNewLoan()
        {
            var calculator = new LoanScheduleCalculator {
                Interest = Result.InterestRate, Term = Result.RepaymentPeriod,
            };

            CashRequest cr = CreateMinimalCashRequest();

            var loan = new Loan {
                LoanAmount  = Result.OfferedCreditLine,
                Date        = this.rawOfferStart ?? this.now,
                LoanType    = cr.LoanType,
                CashRequest = cr,
                SetupFee    = Result.TotalSetupFee,
                LoanLegalId = null,
            };

            calculator.Calculate(Result.OfferedCreditLine, loan, loan.Date, 0, Result.SpreadSetupFee);

            loan.LoanSource = cr.LoanSource;

            if ((Result.BrokerSetupFee > 0) && (this.brokerID != null))
            {
                loan.BrokerCommissions.Add(new LoanBrokerCommission {
                    Broker   = ObjectFactory.GetInstance <BrokerRepository>().GetByID(this.brokerID.Value),
                    CardInfo = this.brokerCardID == null
                                                ? null
                                                : ObjectFactory.GetInstance <ICardInfoRepository>().GetAll().FirstOrDefault(ci =>
                                                                                                                            ci.Id == this.brokerCardID.Value
                                                                                                                            ),
                    CommissionAmount = Result.BrokerSetupFee,
                    CreateDate       = this.rawOfferStart ?? this.now,
                    Loan             = loan,
                });
            }             // if broker fee & broker

            return(loan);
        }         // CreateNewLoan
Beispiel #15
0
        private EditLoanDetailsModel RecalculateModel(EditLoanDetailsModel model, CashRequest cr, DateTime now)
        {
            model.Validate();

            if (model.HasErrors)
            {
                return(model);
            }

            var loan = this._loanModelBuilder.CreateLoan(model);

            loan.LoanType    = cr.LoanType;
            loan.CashRequest = cr;

            RescheduleSetmodel(model.Id, model);

            try {
                var calc = new LoanRepaymentScheduleCalculator(loan, now, CurrentValues.Instance.AmountToChargeFrom);
                calc.GetState();

                //try {
                //	long nlLoanId = this.serviceClient.Instance.GetLoanByOldID(loan.Id, cr.Customer.Id, this._context.UserId).Value;
                //	if (nlLoanId > 0) {
                //		var nlModel = this.serviceClient.Instance.GetLoanState(loan.Customer.Id, nlLoanId, now, this._context.UserId, true).Value;
                //		Log.InfoFormat("<<< NL_Compare: nlModel : {0} loan: {1}  >>>", nlModel, loan);
                //	}
                //	// ReSharper disable once CatchAllClause
                //} catch (Exception ex) {
                //	Log.InfoFormat("<<< NL_Compare Fail at: {0}, err: {1}", Environment.StackTrace, ex.Message);
                //}
            } catch (Exception e) {
                model.Errors.Add(e.Message);
                return(model);
            }

            return(this._loanModelBuilder.BuildModel(loan));
        }
Beispiel #16
0
        private ExecutionResult GetCash(CashRequest request, ExecutionContext context)
        {
            var account = AdbRepository.AccountData.GetEntityById(request.AccountId);

            AdbRepository.TransactionHistoryData.Save(
                new TransactionHistoryEntity()
            {
                Count        = request.Summ,
                CreateTime   = DateTime.Now,
                CurrencyType = (int)account.CurrencyType,
                FromAccount  = account.Id,
                ToAccount    = GetRepositoryAccount((CurrencyTypeEnum)account.CurrencyType)
            });
            AdbRepository.TransactionHistoryData.Save(
                new TransactionHistoryEntity()
            {
                Count        = request.Summ,
                CreateTime   = DateTime.Now,
                CurrencyType = (int)account.CurrencyType,
                FromAccount  = GetRepositoryAccount((CurrencyTypeEnum)account.CurrencyType),
                ToAccount    = null
            });
            return(context.PreviousResult);
        }
Beispiel #17
0
        public SalaryVoucherResponse SetSalaryVouchers(SalaryVoucherRequest request)
        {
            var     response     = new SalaryVoucherResponse();
            string  currencyCode = "";
            decimal exchangeRate = 1;


            #region Ghi sổ

            if (request.LoadOptions.Contains("SaveSalaryVoucher"))
            {
                // Lấy voucherType là thực chi
                var voucherType = VoucherTypeDao.GetVoucherTypeByCode("SalaryVoucher") ?? new VoucherTypeEntity();
                // Lấy tất cả các loại khoản lương nhân viên
                List <EmployeeEntity> employees = EmployeeDao.GetEmployeesForSalaryInMonthAndRefNo(request.PostedDate, request.RefNo);

                var obj = SalaryVoucherDao.GetSalaryVoucherMonthDate(request.PostedDate).FirstOrDefault();
                if (obj != null)
                {
                    currencyCode = obj.CurrencyCode;
                    exchangeRate = obj.ExchangeRate;
                }

                //string[] words = request.PostedDate.Split('/');//Chuyển lại ngày tháng cho hợp lý trên C# # SQL
                DateTime postedDate = Convert.ToDateTime(request.PostedDate);

                var depositEntity = new DepositEntity()
                {
                    RefId                = 0,
                    RefTypeId            = request.ReftypeId, //
                    RefDate              = postedDate,        //DateTime.Parse(words[1] + "/" + words[0] + "/" + words[2]),
                    RefNo                = request.RefNo,
                    PostedDate           = postedDate,        //DateTime.Parse(words[1] + "/" + words[0] + "/" + words[2]),
                    AccountingObjectType = 1,
                    AccountingObjectId   = null,
                    Trader               = "",
                    CustomerId           = null,
                    VendorId             = null,
                    EmployeeId           = null, // mapper.EmployeeId,
                    BankAccountCode      = "112",
                    CurrencyCode         = currencyCode,
                    ExchangeRate         = exchangeRate,
                    TotalAmountOc        = 0, // employeePayItem.Amount,
                    TotalAmountExchange  = 0, // employeePayItem.Amount,
                    JournalMemo          =
                        "Chứng từ lương tháng " + postedDate.Month + "/" + postedDate.Year,
                };
                depositEntity.DepositDetails = new List <DepositDetailEntity>();
                var cashEntity = new CashEntity
                {
                    RefId               = 0,
                    RefTypeId           = request.ReftypeId, //
                    RefNo               = request.RefNo,
                    RefDate             = postedDate,        //DateTime.Parse(words[1] + "/" + words[0] + "/" + words[2]),
                    PostedDate          = postedDate,        //DateTime.Parse(words[1] + "/" + words[0] + "/" + words[2]),
                    AccountingObjectId  = null,
                    CustomerId          = null,
                    VendorId            = null,
                    Trader              = "",
                    CurrencyCode        = currencyCode,
                    ExchangeRate        = exchangeRate,
                    TotalAmount         = 0,
                    TotalAmountExchange = 0,
                    AccountNumber       = "",
                    JournalMemo         =
                        "Chứng từ lương tháng " + postedDate.Month + "/" + postedDate.Year,
                    DocumentInclude      = "",
                    AccountingObjectType = 1,
                    EmployeeId           = null,
                };
                cashEntity.CashDetails = new List <CashDetailEntity>();

                foreach (var employee in employees)
                {
                    //Từng nhân viên - từng khoảng lương - tiền tương ứng.
                    IList <EmployeePayItemEntity> listPayItems = EmployeePayItemDao.GetEmployeeForViewtEmployeePayItem(employee.EmployeeId, postedDate, exchangeRate);
                    foreach (var employeePayItemEntity in listPayItems)
                    {
                        var payItems = PayItemDao.GetPayItem(employeePayItemEntity.PayItemId);
                        //Chi
                        if (payItems != null && (payItems.CreditAccountCode ?? "").StartsWith("111"))
                        {
                            // khởi tạo phieu chi chi tiết
                            CashDetailEntity cashDetailEntity = new CashDetailEntity()
                            {
                                RefDetailId   = 0,
                                RefId         = 0,
                                AccountNumber = payItems.DebitAccountCode,
                                CorrespondingAccountNumber = payItems.CreditAccountCode,
                                Description        = payItems.PayItemName + " tháng " + postedDate.Month + "/" + postedDate.Year,
                                AmountOc           = employeePayItemEntity.Amount,
                                AmountExchange     = employeePayItemEntity.AmountExchange,
                                VoucherTypeId      = null, //voucherType.VoucherTypeId,
                                BudgetSourceCode   = payItems.BudgetSourceCode,
                                BudgetItemCode     = payItems.BudgetItemCode,
                                AccountingObjectId = null,
                                // dùng tạm MergerFundId để lưu payitemid
                                MergerFundId = payItems.PayItemId
                            };
                            bool flag = false;
                            for (int i = 0; i < cashEntity.CashDetails.Count; i++)
                            {
                                if (cashEntity.CashDetails[i].MergerFundId == cashDetailEntity.MergerFundId && cashEntity.CashDetails[i].CorrespondingAccountNumber == cashDetailEntity.CorrespondingAccountNumber && cashEntity.CashDetails[i].AccountNumber == cashDetailEntity.AccountNumber && cashEntity.CashDetails[i].BudgetItemCode == cashDetailEntity.BudgetItemCode && cashEntity.CashDetails[i].BudgetSourceCode == cashDetailEntity.BudgetSourceCode)
                                {
                                    cashEntity.CashDetails[i].AmountOc       = cashEntity.CashDetails[i].AmountOc + cashDetailEntity.AmountOc;
                                    cashEntity.CashDetails[i].AmountExchange = cashEntity.CashDetails[i].AmountExchange + cashDetailEntity.AmountExchange;
                                    flag = true;
                                }
                            }
                            if (flag == false)
                            {
                                if (cashDetailEntity.AmountOc > 0)
                                {
                                    cashEntity.CashDetails.Add(cashDetailEntity);
                                }
                            }
                            //Tính lại TotalAmountOc - TotalAmountExchange
                            cashEntity.TotalAmount         = cashEntity.TotalAmount + cashDetailEntity.AmountOc;
                            cashEntity.TotalAmountExchange = cashEntity.TotalAmountExchange + cashDetailEntity.AmountExchange;
                            //Get Bank Acount
                            cashEntity.AccountNumber = payItems.CreditAccountCode;
                        }
                        //Nợ
                        if (payItems != null && (payItems.CreditAccountCode ?? "").StartsWith("112"))
                        {
                            DepositDetailEntity depositDetailEntity = new DepositDetailEntity()
                            {
                                RefDetailId = request.ReftypeId,
                                RefId       = 0,
                                Description = payItems.PayItemName + " tháng " + postedDate.Month + "/" + postedDate.Year,

                                AccountNumber = payItems.DebitAccountCode,
                                CorrespondingAccountNumber = payItems.CreditAccountCode,
                                AmountOc           = employeePayItemEntity.Amount,
                                AmountExchange     = employeePayItemEntity.AmountExchange,
                                VoucherTypeId      = null, //voucherType.VoucherTypeId,
                                BudgetSourceCode   = payItems.BudgetSourceCode,
                                AccountingObjectId = null,
                                BudgetItemCode     = payItems.BudgetItemCode,
                                // dùng tạm MergerFundId để lưu payitemid
                                MergerFundId = payItems.PayItemId
                            };
                            bool flag = false;
                            for (int i = 0; i < depositEntity.DepositDetails.Count; i++)
                            {
                                // old
                                //if (depositEntity.DepositDetails[i].CorrespondingAccountNumber == depositDetailEntity.CorrespondingAccountNumber && depositEntity.DepositDetails[i].BudgetItemCode == depositDetailEntity.BudgetItemCode && depositEntity.DepositDetails[i].BudgetSourceCode == depositDetailEntity.BudgetSourceCode)
                                //{
                                //    depositEntity.DepositDetails[i].AmountOc = depositEntity.DepositDetails[i].AmountOc + depositDetailEntity.AmountOc;
                                //    depositEntity.DepositDetails[i].AmountExchange = depositEntity.DepositDetails[i].AmountExchange + depositDetailEntity.AmountExchange;
                                //    flag = true;
                                //}

                                if (depositEntity.DepositDetails[i].MergerFundId == depositDetailEntity.MergerFundId && depositEntity.DepositDetails[i].CorrespondingAccountNumber == depositDetailEntity.CorrespondingAccountNumber && depositEntity.DepositDetails[i].BudgetItemCode == depositDetailEntity.BudgetItemCode && depositEntity.DepositDetails[i].BudgetSourceCode == depositDetailEntity.BudgetSourceCode)
                                {
                                    depositEntity.DepositDetails[i].AmountOc       = depositEntity.DepositDetails[i].AmountOc + depositDetailEntity.AmountOc;
                                    depositEntity.DepositDetails[i].AmountExchange = depositEntity.DepositDetails[i].AmountExchange + depositDetailEntity.AmountExchange;
                                    flag = true;
                                }
                            }
                            if (flag == false)
                            {
                                if (depositDetailEntity.AmountOc > 0)
                                {
                                    depositEntity.DepositDetails.Add(depositDetailEntity);
                                }
                            }
                            //Tính lại TotalAmountOc - TotalAmountExchange
                            depositEntity.TotalAmountOc       = depositEntity.TotalAmountOc + depositDetailEntity.AmountOc;
                            depositEntity.TotalAmountExchange = depositEntity.TotalAmountExchange + depositDetailEntity.AmountExchange;
                            //Get bank Acount
                            depositEntity.BankAccountCode = payItems.CreditAccountCode;
                        }
                    }
                }

                // xóa MergerFundId đi không thì lưu nó lỗi á
                cashEntity.CashDetails.Select(c => { c.MergerFundId = null; return(c); }).ToList();
                depositEntity.DepositDetails.Select(c => { c.MergerFundId = null; return(c); }).ToList();

                long?cashId    = null;
                long?depositId = null;
                //Insert chứng từ phiếu chi
                var cashRequest = new CashRequest();
                var oCashFacade = new CashFacade();
                cashRequest.Action     = PersistType.Insert;
                cashRequest.CashEntity = cashEntity;
                // sinh định khoản đồng thời
                cashRequest.isAutoGenerateParallel = true;
                if (cashRequest.CashEntity.TotalAmount > 0)
                {
                    var cashResponse = oCashFacade.SetCashes(cashRequest);
                    cashId = cashResponse.RefId;
                }

                //Insert chứng từ giấy báo nợ
                var depositRequest = new DepositRequest();
                var oDepositFacade = new DepositFacade();
                depositRequest.Action  = PersistType.Insert;
                depositRequest.Deposit = depositEntity;
                if (depositRequest.Deposit.TotalAmountOc > 0)
                {
                    var depositRespone = oDepositFacade.SetDeposits(depositRequest, true);
                    depositId = depositRespone.RefId;
                }

                // update id phiếu chi, thu tiền gửi vào bảng
                string updateEmployeePayroll = SalaryVoucherDao.Update_EmployeePayroll_Voucher(request.RefNo, cashId, depositId);
            }


            #endregion

            #region Hủy tính ghi sổ + tính lương

            if (request.LoadOptions.Contains("CancelSalaryVoucher"))
            {
                var obj = SalaryVoucherDao.GetSalaryVoucherMonthDateIsPostedDate(request.PostedDate).FirstOrDefault();
                if (obj != null)
                {
                    currencyCode = obj.CurrencyCode;
                }



                var cashRequest = new CashRequest();
                var oCashFacade = new CashFacade();
                cashRequest.Action     = PersistType.Delete;
                cashRequest.CashEntity = CashDao.GetCash(SalaryVoucherDao.GetEmployeePayroll_VoucherID(request.RefNo, 201)); //CashDao.GetCashBySalary(request.ReftypeId, request.PostedDate, request.RefNo, currencyCode);

                var depositRequest = new DepositRequest();
                var oDepositFacade = new DepositFacade();
                depositRequest.Action  = PersistType.Delete;
                depositRequest.Deposit = DepositDao.GetDeposit(SalaryVoucherDao.GetEmployeePayroll_VoucherID(request.RefNo, 301)); //DepositDao.GetDepositsBySalary(request.ReftypeId, request.PostedDate, request.RefNo, currencyCode);

                //Xóa chứng từ lương ở phiểu chi
                if (cashRequest.CashEntity != null)
                {
                    cashRequest.RefId = cashRequest.CashEntity.RefId;
                    cashRequest.CashEntity.CashDetails = CashDetailDao.GetCashDetailsByCash(cashRequest.CashEntity.RefId);
                    if (cashRequest.CashEntity.CashDetails != null)
                    {
                        oCashFacade.SetCashes(cashRequest);
                        response.Message = CashDao.DeleteEmployeePayroll(cashRequest.CashEntity.RefNo,
                                                                         cashRequest.CashEntity.PostedDate.Month + "/" + cashRequest.CashEntity.PostedDate.Day + "/" + cashRequest.CashEntity.PostedDate.Year);
                    }
                }

                //Xóa chứng từ lương ở giấy báo nợ
                if (depositRequest.Deposit != null)
                {
                    depositRequest.RefId = depositRequest.Deposit.RefId;
                    depositRequest.Deposit.DepositDetails = DepositDetailDao.GetDepositDetailsByDeposit(depositRequest.Deposit.RefId);
                    if (depositRequest.Deposit.DepositDetails != null)
                    {
                        oDepositFacade.SetDeposits(depositRequest);
                        response.Message = DepositDao.DeleteEmployeePayroll(depositRequest.Deposit.RefNo,
                                                                            depositRequest.Deposit.PostedDate.Value.Month + "/" + depositRequest.Deposit.PostedDate.Value.Day + "/" + depositRequest.Deposit.PostedDate.Value.Year);
                    }
                }
            }

            #endregion

            #region  Hủy tính lương

            if (request.LoadOptions.Contains("CancelCalc"))
            {
                response.Message = SalaryVoucherDao.CanclCalc(request.PostedDate, request.RefNo);
            }

            #endregion

            return(response);
        }
Beispiel #18
0
        }         // constructor

        public CashRequest CreateQuickOfferCashRequest(Customer customer, int userID)
        {
            var          loanType     = _loanTypes.GetDefault();
            var          loanSource   = _loanSources.GetDefault(customer.Id);
            var          now          = DateTime.UtcNow;
            var          discountPlan = _discounts.GetDefault();
            const string sReason      = "Quick offer taken.";

            // TODO: do something really-really-really better than this.
            var user = _users.GetAll().FirstOrDefault(x => x.Id == 1);

            var cashRequest = new CashRequest {
                CreationDate               = now,
                Customer                   = customer,
                InterestRate               = customer.QuickOffer.ImmediateInterestRate,
                LoanType                   = loanType,
                RepaymentPeriod            = customer.QuickOffer.ImmediateTerm,
                ApprovedRepaymentPeriod    = customer.QuickOffer.ImmediateTerm,
                UseSetupFee                = customer.QuickOffer.ImmediateSetupFee > 0,
                UseBrokerSetupFee          = false,
                DiscountPlan               = discountPlan,
                IsLoanTypeSelectionAllowed = 0,
                OfferValidUntil            = now.AddDays(1),
                OfferStart                 = now,
                LoanSource                 = loanSource, // TODO: can it be EU loan?
                IsCustomerRepaymentPeriodSelectionAllowed = false,
                ManualSetupFeePercent   = customer.QuickOffer.ImmediateSetupFee,
                SystemCalculatedSum     = (double)customer.QuickOffer.Amount,
                ManagerApprovedSum      = (double)customer.QuickOffer.Amount,
                QuickOffer              = customer.QuickOffer,
                SystemDecision          = SystemDecision.Approve,
                SystemDecisionDate      = DateTime.UtcNow,
                UnderwriterDecision     = CreditResultStatus.Approved,
                UnderwriterDecisionDate = DateTime.UtcNow,
                UnderwriterComment      = sReason,
                IdUnderwriter           = user.Id,
                Originator              = EZBob.DatabaseLib.Model.Database.CashRequestOriginator.QuickOffer,
                ExpirianRating          = customer.ExperianConsumerScore,
                UwUpdatedFees           = false,
            };

            customer.CashRequests.Add(cashRequest);

            customer.DateApproved               = DateTime.UtcNow;
            customer.ApprovedReason             = sReason;
            customer.UnderwriterName            = user.Name;
            customer.Status                     = Status.Approved;
            customer.CreditResult               = CreditResultStatus.Approved;
            customer.CreditSum                  = customer.QuickOffer.Amount;
            customer.ManagerApprovedSum         = customer.QuickOffer.Amount;
            customer.OfferStart                 = cashRequest.OfferStart;
            customer.OfferValidUntil            = cashRequest.OfferValidUntil;
            customer.IsLoanTypeSelectionAllowed = 0;
            int validForHours = (int)(cashRequest.OfferValidUntil - cashRequest.OfferStart).Value.TotalHours;

            this.m_oServiceClient.Instance.ApprovedUser(
                user.Id,
                customer.Id,
                customer.QuickOffer.Amount,
                validForHours,
                customer.NumApproves == 1
                );

            this._historyRepository.LogAction(DecisionActions.Approve, sReason, user, customer);

            new Transactional(() => {
                customer.CashRequests.Add(cashRequest);
                this._customerRepository.SaveOrUpdate(customer);
            }).Execute();

            var nlCashRequest = this.m_oServiceClient.Instance.AddCashRequest(userID, new NL_CashRequests {
                CashRequestOriginID = (int)CashRequestOriginator.QuickOffer,
                CustomerID          = customer.Id,
                OldCashRequestID    = cashRequest.Id,
                RequestTime         = now,
                UserID = userID
            });

            Log.DebugFormat("Added NL CashRequestID: {0}, Error: {1}", nlCashRequest.Value, nlCashRequest.Error);

            var nlDecision = this.m_oServiceClient.Instance.AddDecision(userID, customer.Id, new NL_Decisions {
                CashRequestID  = nlCashRequest.Value,
                DecisionTime   = now,
                Notes          = CashRequestOriginator.QuickOffer.DescriptionAttr(),
                DecisionNameID = (int)DecisionActions.Approve,
                UserID         = user.Id
            }, cashRequest.Id, null);

            Log.DebugFormat("Added NL DecisionID: {0}, Error: {1}", nlDecision.Value, nlDecision.Error);

            NL_OfferFees setupFee = new NL_OfferFees()
            {
                LoanFeeTypeID = (int)NLFeeTypes.SetupFee, Percent = customer.QuickOffer.ImmediateSetupFee, OneTimePartPercent = 1, DistributedPartPercent = 0
            };

            if (cashRequest.SpreadSetupFee != null && cashRequest.SpreadSetupFee == true)
            {
                setupFee.LoanFeeTypeID          = (int)NLFeeTypes.ServicingFee;
                setupFee.OneTimePartPercent     = 0;
                setupFee.DistributedPartPercent = 1;
            }
            NL_OfferFees[] ofeerFees = { setupFee };

            var nlOffer = this.m_oServiceClient.Instance.AddOffer(userID, customer.Id, new NL_Offers {
                DecisionID              = nlDecision.Value,
                Amount                  = customer.QuickOffer.Amount,
                CreatedTime             = now,
                StartTime               = now,
                EndTime                 = now.AddDays(1),
                RepaymentIntervalTypeID = (int)RepaymentIntervalTypes.Month,
                LoanSourceID            = loanSource.ID,
                LoanTypeID              = loanType.Id,
                DiscountPlanID          = discountPlan.Id,
                Notes = CashRequestOriginator.QuickOffer.DescriptionAttr(),
                InterestOnlyRepaymentCount        = 0,
                BrokerSetupFeePercent             = 0,
                MonthlyInterestRate               = customer.QuickOffer.ImmediateInterestRate,
                RepaymentCount                    = customer.QuickOffer.ImmediateTerm,
                IsAmountSelectionAllowed          = false,
                IsRepaymentPeriodSelectionAllowed = false,
                IsLoanTypeSelectionAllowed        = false
                                                    // ### defaults, can be ommited
            }, ofeerFees);

            Log.DebugFormat("Added NL OfferID: {0}, Error: {1}", nlOffer.Value, nlOffer.Error);

            //TODO add new cash request / offer / decision
            Log.DebugFormat("add new cash request for customer {0}", customer.Id);

            return(cashRequest);
        }         // CreateQuickOfferCashRequest
Beispiel #19
0
        public JsonResult GetOffer(GetInstantOfferModel model, CompanyInfo company)
        {
            var context  = ObjectFactory.GetInstance <IWorkplaceContext>();
            var response = this.m_oServiceClient.Instance.BrokerInstantOffer(new BrokerInstantOfferRequest {
                Created                    = DateTime.UtcNow,
                BrokerId                   = context.UserId,
                CompanyNameNumber          = model.CompanyNameNumber,
                AnnualTurnover             = model.AnnualTurnover,
                AnnualProfit               = model.AnnualProfit,
                NumOfEmployees             = model.NumOfEmployees,
                MainApplicantCreditScore   = model.MainApplicantCreditScore,
                IsHomeOwner                = model.IsHomeOwner,
                ExperianRefNum             = company.BusRefNum,
                ExperianCompanyName        = company.BusName,
                ExperianCompanyLegalStatus = company.LegalStatus,
                ExperianCompanyPostcode    = company.PostCode
            });

            var loanTypeRepository   = ObjectFactory.GetInstance <LoanTypeRepository>();
            var loanSourceRepository = ObjectFactory.GetInstance <LoanSourceRepository>();
            var loanBuilder          = ObjectFactory.GetInstance <LoanBuilder>();
            var aprCalc = ObjectFactory.GetInstance <APRCalculator>();

            var cr = new CashRequest {
                ApprovedRepaymentPeriod = response.Response.RepaymentPeriod,
                InterestRate            = response.Response.InterestRate,
                LoanType           = loanTypeRepository.Get(response.Response.LoanTypeId),
                LoanSource         = loanSourceRepository.Get(response.Response.LoanSourceId),
                ManagerApprovedSum = response.Response.ApprovedSum,
                UseBrokerSetupFee  = response.Response.UseBrokerSetupFee,
                UseSetupFee        = response.Response.UseSetupFee,
                RepaymentPeriod    = response.Response.RepaymentPeriod,
                LoanLegals         = new List <LoanLegal>()
            };

            var loan = loanBuilder.CreateNewLoan(cr,
                                                 cr.ApprovedSum(),
                                                 DateTime.UtcNow,
                                                 cr.ApprovedRepaymentPeriod.HasValue ? cr.ApprovedRepaymentPeriod.Value : 12);

            var calc = new LoanRepaymentScheduleCalculator(loan, loan.Date, CurrentValues.Instance.AmountToChargeFrom);

            calc.GetState();

            try {
                long nlLoanId = this.m_oServiceClient.Instance.GetLoanByOldID(loan.Id, loan.Customer.Id, context.UserId).Value;
                if (nlLoanId > 0)
                {
                    var nlModel = this.m_oServiceClient.Instance.GetLoanState(loan.Customer.Id, nlLoanId, loan.Date, context.UserId, true).Value;
                    ms_oLog.Info("<<< NL_Compare: {0}\n===============loan: {1}  >>>", nlModel, loan);
                }
                // ReSharper disable once CatchAllClause
            } catch (Exception ex) {
                ms_oLog.Info("<<< NL_Compare fail at: {0}, err: {1}", Environment.StackTrace, ex.Message);
            }

            var apr = loan.LoanAmount == 0 ? 0 : aprCalc.Calculate(loan.LoanAmount, loan.Schedule, loan.SetupFee, loan.Date);

            var loanOffer = LoanOffer.InitFromLoan(loan, apr, null, cr);

            return(Json(loanOffer, JsonRequestBehavior.AllowGet));
        }         // GetOffer
Beispiel #20
0
		} // CreateNewLoan

		public BuiltLoan BuildLoan(CashRequest cr, decimal amount, DateTime now, int term, int interestOnlyTerm = 0) {
			decimal setupFeePct = cr.ManualSetupFeePercent ?? 0;
			decimal brokerFeePct = cr.BrokerSetupFeePercent ?? 0;

			decimal approvedAmount = (decimal)(cr.ManagerApprovedSum ?? cr.SystemCalculatedSum ?? 0);

			if ((cr.Customer.Broker != null) && (approvedAmount != amount)) {
				log.Debug(
					"CreateNewLoan: broker customer '{0}', broker fee in cash request with approved amount {1} is {2}.",
					cr.Customer.Stringify(),
					approvedAmount.ToString("C2"),
					brokerFeePct.ToString("P2")
				);

				Loan firstLoan = cr.Customer.Loans.OrderBy(l => l.Date).FirstOrDefault();

				brokerFeePct = new CommissionCalculator(amount, firstLoan == null ? (DateTime?)null : firstLoan.Date)
					.Calculate()
					.BrokerCommission;

				log.Debug(
					"CreateNewLoan: broker customer '{0}', broker fee adjusted to loan amount {1} is {2}.",
					cr.Customer.Stringify(),
					amount.ToString("C2"),
					brokerFeePct.ToString("P2")
				);
			} // if broker customer

			var fees = new SetupFeeCalculator(setupFeePct, brokerFeePct).Calculate(amount);

			decimal setupFee = fees.Total;
			decimal brokerFee = fees.Broker;

			var calculator = new LoanScheduleCalculator { Interest = cr.InterestRate, Term = term };

			LoanLegal loanLegal = cr.LoanLegals.LastOrDefault();

			var loan = new Loan {
				LoanAmount = amount,
				Date = now,
				LoanType = cr.LoanType,
				CashRequest = cr,
				SetupFee = setupFee,
				LoanLegalId = loanLegal == null ? (int?)null : loanLegal.Id
			};

			calculator.Calculate(amount, loan, loan.Date, interestOnlyTerm, cr.SpreadSetupFee());

			loan.LoanSource = cr.LoanSource;

			if (brokerFee > 0 && cr.Customer.Broker != null) {
				loan.BrokerCommissions.Add(new LoanBrokerCommission {
					Broker = cr.Customer.Broker,
					CardInfo = cr.Customer.Broker.BankAccounts.FirstOrDefault(
						x => x.IsDefault.HasValue && x.IsDefault.Value
					),
					CommissionAmount = brokerFee,
					CreateDate = now,
					Loan = loan,
				});
			} // if broker fee & broker

			return new BuiltLoan {
				Loan = loan,
				BrokerFeePercent = brokerFeePct,
				ManualSetupFeePercent = setupFeePct,
			};
		} // BuildLoan
Beispiel #21
0
		} // CreateLoan

		public Loan CreateNewLoan(CashRequest cr, decimal amount, DateTime now, int term, int interestOnlyTerm = 0) {
			return BuildLoan(cr, amount, now, term, interestOnlyTerm).Loan;
		} // CreateNewLoan
Beispiel #22
0
        public static LoanOffer InitFromLoan(Loan loan, double calculateApr, AgreementModel agreement, CashRequest cr)
        {
            var repaymentPeriod  = _repaymentCalculator.CalculateCountRepayment(loan);
            var apr              = loan.LoanAmount == 0 ? 0 : calculateApr;
            var total            = loan.Schedule.Sum(s => s.AmountDue) + loan.SetupFee;
            var totalPrincipal   = loan.Schedule.Sum(s => s.LoanRepayment);
            var totalInterest    = loan.Schedule.Sum(s => s.Interest) + loan.Charges.Sum(x => x.Amount) + loan.SetupFee;
            var realInterestCost = loan.LoanAmount == 0 ? 0 : (totalInterest / loan.LoanAmount) / (repaymentPeriod / 12.0M);
            var timestamp        = DateTime.UtcNow.Ticks;

            var offer = new LoanOffer();

            offer.Schedule         = loan.Schedule.Select(LoanScheduleExtention.FromLoanScheduleItem).ToArray();
            offer.Apr              = apr;
            offer.SetupFee         = loan.SetupFee;
            offer.Total            = total;
            offer.RealInterestCost = realInterestCost;
            offer.LoanAmount       = loan.LoanAmount;
            offer.TimeStamp        = timestamp;
            offer.TotalInterest    = totalInterest;
            offer.TotalPrincipal   = totalPrincipal;
            offer.Agreement        = agreement;
            offer.Details          = new LoanOfferDetails {
                InterestRate      = cr.InterestRate,
                RepaymentPeriod   = repaymentPeriod,
                OfferedCreditLine = totalPrincipal,
                LoanType          = cr.LoanType.Name,
                IsModified        = !string.IsNullOrEmpty(cr.LoanTemplate),
                Date = loan.Date
            };
            offer.MaxInterestForSource = loan.LoanSource == null ? null : loan.LoanSource.MaxInterest;
            offer.LoanSourceName       = loan.LoanSource == null ? "" : loan.LoanSource.Name;
            offer.ManualAddressWarning = cr.Customer == null ? "" : cr.Customer.ManualAddressWarning();

            return(offer);
        }
Beispiel #23
0
        public JsonResult ChangeCreditLine(
            long id,
            int productID,
            int productTypeID,
            int productSubTypeID,
            int loanType,
            int loanSource,
            double amount,
            decimal interestRate,
            int repaymentPeriod,
            string offerStart,
            string offerValidUntil,
            bool allowSendingEmail,
            int discountPlan,
            decimal?brokerSetupFeePercent,
            decimal?manualSetupFeePercent,
            bool isCustomerRepaymentPeriodSelectionAllowed,
            int isLoanTypeSelectionAllowed,
            bool spreadSetupFee,
            bool feesManuallyUpdated
            )
        {
            CashRequest cr = this.cashRequestsRepository.Get(id);

            if (cr.Id <= 0)
            {
                log.Error("No cash request found");
                return(Json(true));
            }             // if

            new Transactional(() => {
                LoanType loanT    = this.loanTypes.Get(loanType);
                LoanSource source = this.loanSources.Get(loanSource);

                cr.LoanType = loanT;

                int step = CurrentValues.Instance.GetCashSliderStep;
                int sum  = (int)Math.Round(amount / step, MidpointRounding.AwayFromZero) * step;
                cr.ManagerApprovedSum      = sum;
                cr.LoanSource              = source;
                cr.InterestRate            = interestRate;
                cr.RepaymentPeriod         = repaymentPeriod;
                cr.ApprovedRepaymentPeriod = cr.RepaymentPeriod;
                cr.OfferStart              = FormattingUtils.ParseDateWithCurrentTime(offerStart);
                cr.OfferValidUntil         = FormattingUtils.ParseDateWithCurrentTime(offerValidUntil);

                cr.BrokerSetupFeePercent = brokerSetupFeePercent;
                cr.ManualSetupFeePercent = manualSetupFeePercent;
                cr.UwUpdatedFees         = feesManuallyUpdated;

                cr.EmailSendingBanned = !allowSendingEmail;
                cr.LoanTemplate       = null;

                cr.IsLoanTypeSelectionAllowed = isLoanTypeSelectionAllowed;
                cr.IsCustomerRepaymentPeriodSelectionAllowed = isCustomerRepaymentPeriodSelectionAllowed;

                cr.DiscountPlan      = this.discounts.Get(discountPlan);
                cr.SpreadSetupFee    = spreadSetupFee;
                cr.ProductSubTypeID  = productSubTypeID;
                Customer c           = cr.Customer;
                c.OfferStart         = cr.OfferStart;
                c.OfferValidUntil    = cr.OfferValidUntil;
                c.ManagerApprovedSum = sum;

                this.cashRequestsRepository.SaveOrUpdate(cr);
                this.customerRepository.SaveOrUpdate(c);
            }).Execute();

            var decision = this.serviceClient.Instance.AddDecision(this.context.UserId, cr.Customer.Id, new NL_Decisions {
                UserID         = this.context.UserId,
                DecisionTime   = DateTime.UtcNow,
                DecisionNameID = (int)DecisionActions.Waiting,
                Notes          = "Waiting; oldCashRequest: " + cr.Id
            }, cr.Id, null);

            // TODO: save feesManuallyUpdated in new loan structure (EZ-4829)

            log.Info("NL decisionID: {0}, oldCashRequestID: {1}, Error: {2}", decision.Value, cr.Id, decision.Error);

            NL_OfferFees offerFee = new NL_OfferFees()
            {
                LoanFeeTypeID          = (int)NLFeeTypes.SetupFee,
                Percent                = manualSetupFeePercent ?? 0,
                OneTimePartPercent     = 1,
                DistributedPartPercent = 0
            };

            if (cr.SpreadSetupFee != null && cr.SpreadSetupFee == true)
            {
                offerFee.LoanFeeTypeID          = (int)NLFeeTypes.ServicingFee;
                offerFee.OneTimePartPercent     = 0;
                offerFee.DistributedPartPercent = 1;
            }
            NL_OfferFees[] ofeerFees = { offerFee };

            var offer = this.serviceClient.Instance.AddOffer(this.context.UserId, cr.Customer.Id, new NL_Offers {
                DecisionID = decision.Value,
                LoanTypeID = loanType,
                RepaymentIntervalTypeID = (int)DbConstants.RepaymentIntervalTypes.Month,
                LoanSourceID            = loanSource,
                StartTime             = FormattingUtils.ParseDateWithCurrentTime(offerStart),
                EndTime               = FormattingUtils.ParseDateWithCurrentTime(offerValidUntil),
                RepaymentCount        = repaymentPeriod,
                Amount                = (decimal)amount,
                MonthlyInterestRate   = interestRate,
                CreatedTime           = DateTime.UtcNow,
                BrokerSetupFeePercent = brokerSetupFeePercent ?? 0,
                Notes                             = "offer from ChangeCreditLine, ApplicationInfoController",
                DiscountPlanID                    = discountPlan,
                IsLoanTypeSelectionAllowed        = isLoanTypeSelectionAllowed == 1,
                IsRepaymentPeriodSelectionAllowed = isCustomerRepaymentPeriodSelectionAllowed,
                SendEmailNotification             = allowSendingEmail,
                ProductSubTypeID                  = productSubTypeID
                                                    // SetupFeeAddedToLoan = 0 // default 0 TODO EZ-3515
                                                    // InterestOnlyRepaymentCount =
                                                    //IsAmountSelectionAllowed = 1 default 1 always allowed
            }, ofeerFees);

            log.Info("NL--- offerID: {0}, decisionID: {1} oldCashRequestID: {2}, Error: {3}", offer.Value, decision.Value, cr.Id, offer.Error);


            log.Debug("update offer for customer {0} all the offer is changed", cr.Customer.Id);

            return(Json(true));
        }         // ChangeCreditLine
Beispiel #24
0
 public long GetTime(CashRequest data)
 {
     return(data.SystemDecisionDate != null
                ? (data.UnderwriterDecisionDate.Value - data.SystemDecisionDate.Value).Ticks : 0);
 }
Beispiel #25
0
 public bool IsLowSide(CashRequest data)
 {
     return(data.UnderwriterDecision == CreditResultStatus.Rejected && data.SystemDecision != SystemDecision.Reject);
 }
Beispiel #26
0
 public bool IsHighScored(CashRequest data)
 {
     return(data.UnderwriterDecision == CreditResultStatus.Approved && data.SystemDecision != SystemDecision.Approve);
 }
Beispiel #27
0
        public JsonResult CreditLineSigned(
            int customerID              = 0,
            int cashRequestID           = 0,
            string signedName           = "",
            bool creditFacilityAccepted = false
            )
        {
            log.DebugFormat(
                "CreditLineSignatureModel " +
                "customer ID: {0}" +
                "cash request ID: {1}" +
                "signed name: {2}" +
                "credit facility accepted: {3}",
                customerID,
                cashRequestID,
                signedName,
                creditFacilityAccepted
                );

            var customer = this.context.Customer;

            if ((customer == null) || (customer.Id != customerID))
            {
                log.ErrorFormat(
                    "CreditLineSigned: invalid or unmatched customer ({0}) for requested id {1}.",
                    customer.Stringify(),
                    customerID
                    );

                return(Json(new { success = false, error = "Invalid customer name.", }));
            } // if

            CashRequest cashRequest = customer.CashRequests.FirstOrDefault(r => r.Id == cashRequestID);

            if (cashRequest == null)
            {
                log.WarnFormat(
                    "CreditLineSigned: cash request not found by id {0} at customer {1}.",
                    cashRequestID,
                    customer.Stringify()
                    );

                return(Json(new { success = false, error = "Invalid credit line.", }));
            } // if

            bool hasError = !creditFacilityAccepted;

            if (hasError)
            {
                log.WarnFormat(
                    "CreditLineSigned: credit facility not accepted for cash request {0} at customer {1}.",
                    cashRequestID,
                    customer.Stringify()
                    );

                return(Json(new { success = false, error = "You must agree to all agreements.", }));
            } // if

            var productSubTypeID = cashRequest.ProductSubTypeID;
            var originId         = customer.CustomerOrigin.CustomerOriginID;
            var isRegulated      = customer.PersonalInfo.TypeOfBusiness.IsRegulated();

            var loanAgreementTemplates =
                this.serviceClient.Instance.GetLegalDocs(customer.Id, this.context.UserId, originId, isRegulated, productSubTypeID ?? 0)
                .LoanAgreementTemplates.ToDictionary(x => x.TemplateTypeName, x => true);

            customer.LastCashRequest.LoanLegals.Add(new LoanLegal {
                CashRequest                       = cashRequest,
                Created                           = DateTime.UtcNow,
                EUAgreementAgreed                 = false,
                COSMEAgreementAgreed              = false,
                CreditActAgreementAgreed          = false,
                PreContractAgreementAgreed        = false,
                PrivateCompanyLoanAgreementAgreed = false,
                GuarantyAgreementAgreed           = false,
                SignedName                        = signedName,
                NotInBankruptcy                   = false,
                SignedLegalDocs                   = new JavaScriptSerializer().Serialize(loanAgreementTemplates.ToDictionary(x => x.Key.DescriptionAttr(), x => x.Value.ToString()))
            });

            //el: TODO add LoanLegal for offer

            return(Json(new { success = true, error = string.Empty, }));
        } // CreditLineSigned
        /// <summary>
        /// Set the specified request.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <returns>SalaryResponse.</returns>
        public SalaryResponse SetSalaries(SalaryRequest request)
        {
            var response           = new SalaryResponse();
            var obJourentryAccount = new JournalEntryAccountEntity();
            IList <JournalEntryAccountEntity> listJournalEntryAccountEntity = new List <JournalEntryAccountEntity>();
            IList <AccountBalanceEntity>      listAccountBalanceEntity      = new List <AccountBalanceEntity>();
            var mapper = request.Salary;

            if (request.Action != PersistType.Delete)
            {
                if (!mapper.Validate())
                {
                    foreach (string error in mapper.ValidationErrors)
                    {
                        response.Message += error + Environment.NewLine;
                    }
                    response.Acknowledge = AcknowledgeType.Failure;
                    return(response);
                }
            }
            try
            {
                if (request.LoadOptions.Contains("CalSalary"))
                {
                    var lstDeposit = SalaryDao.GetSalaryByRefNo(mapper.RefNo);
                    if (lstDeposit.Count > 0)
                    {
                        response.Message     = "Đã tồn tại số chứng từ " + mapper.RefNo + " !";
                        response.Acknowledge = AcknowledgeType.Failure;
                        return(response);
                    }
                    foreach (var employees in mapper.Employees)
                    {
                        mapper.EmployeeId = employees.EmployeeId;
                        response.SalaryId = SalaryDao.CalSalary(mapper);
                    }
                    var autoNumber = AutoNumberDao.GetAutoNumberByRefType(600);
                    //------------------------------------------------------------------
                    //LinhMC 29/11/2014
                    //Lưu giá trị số tự động tăng theo loại tiền
                    //---------------------------------------------------------------
                    if (request.Salary.CurrencyCode == "USD")
                    {
                        autoNumber.Value += 1;
                    }
                    else
                    {
                        autoNumber.ValueLocalCurency += 1;
                    }


                    response.Message = AutoNumberDao.UpdateAutoNumber(autoNumber);
                }

                if (request.LoadOptions.Contains("SavePostedSalary"))
                {
                    /* Danh sách các khoản lương
                     * Nhân viên liên kết Danh sách các khoản lương
                     * Lưu Chứng từ lương:  Nhân viên lấy từ lấy các khoản lương theo nhân viên==> tổng số tiền lương
                     * ==> Đồng thời lưu vào chứng từ Phiếu chi hoặc Giấy báo Nợ đặt mặc định RefType=600 vs Số chứng từ (RefNo) và ngày chứng từ lương
                     * ==> Khi lưu chứng từ Phiếu Chi hoặc Giấy báo Có được lưu dựa trên cách lưu của Phiếu Chi hoặc Giấy Báo Có
                     * ==> Để xác định chứng từ là Phiếu Chi hay Giấy báo Nợ phải dựa báo TK có trên Danh mục khoản lương
                     */
                    var depositEntity = new DepositEntity()
                    {
                        RefId                = 0,
                        RefTypeId            = mapper.RefTypeId,//
                        RefDate              = mapper.RefDate,
                        RefNo                = mapper.RefNo,
                        PostedDate           = mapper.PostedDate,
                        AccountingObjectType = 0,
                        AccountingObjectId   = null,
                        Trader               = "",
                        CustomerId           = null,
                        VendorId             = null,
                        EmployeeId           = null,// mapper.EmployeeId,
                        BankAccountCode      = "112",
                        CurrencyCode         = mapper.CurrencyCode,
                        ExchangeRate         = mapper.ExchangeRate,
                        TotalAmountOc        = 0, // employeePayItem.Amount,
                        TotalAmountExchange  = 0, // employeePayItem.Amount,
                        JournalMemo          = "Chứng từ lương tháng " + mapper.RefDate.Month + "/" + mapper.RefDate.Year,
                    };
                    depositEntity.DepositDetails = new List <DepositDetailEntity>();
                    var cashEntity = new CashEntity
                    {
                        RefId              = 0,
                        RefTypeId          = mapper.RefTypeId,//
                        RefNo              = mapper.RefNo,
                        RefDate            = mapper.RefDate,
                        PostedDate         = mapper.PostedDate,
                        AccountingObjectId = null,
                        CustomerId         = null,
                        VendorId           = null,
                        Trader             = "",
                        CurrencyCode       = mapper.CurrencyCode,
                        ExchangeRate       = mapper.ExchangeRate,

                        TotalAmount         = 0,
                        TotalAmountExchange = 0,
                        AccountNumber       = "",

                        JournalMemo          = "Chứng từ lương tháng " + mapper.RefDate.Month + "/" + mapper.RefDate.Year,
                        DocumentInclude      = "",
                        AccountingObjectType = 2,
                        //     CashDetails = cashDetails;
                        EmployeeId = null,
                    };
                    cashEntity.CashDetails = new List <CashDetailEntity>();

                    // var lstDeposit = SalaryDao.GetSalaryByRefNo(mapper.RefNo);
                    //if (lstDeposit.Count > 0)
                    //{
                    //    response.Message = "Đã tồn tại số chứng từ " + mapper.RefNo + " !";
                    //    response.Acknowledge = AcknowledgeType.Failure;
                    //    return response;
                    //}
                    //  var Cash
                    mapper.Employees = EmployeeDao.GetEmployeesForSalary(mapper.RefDate, mapper.RefNo);
                    foreach (var employee in mapper.Employees)
                    {
                        //Tính lại lương cho nhân viên trước khi ghi sổ
                        mapper.EmployeeId = employee.EmployeeId;
                        response.SalaryId = SalaryDao.CalSalary(mapper);

                        //Từng nhân viên - từng khoảng lương - tiền tương ứng.
                        IList <EmployeePayItemEntity> listPayItems = EmployeePayItemDao.GetEmployeeForViewtEmployeePayItem(employee.EmployeeId, mapper.RefDate, mapper.ExchangeRate);
                        // mapper.EmployeePayItemId = EmployeePayItemDao.GetEmployeePayItemsByEmployeeId(employee.EmployeeId);
                        foreach (var employeePayItemEntity in listPayItems)
                        {
                            mapper.EmployeePayItemId = employeePayItemEntity.EmployeePayItemId;
                            var payItems = PayItemDao.GetPayItem(employeePayItemEntity.PayItemId);
                            //Chi
                            if (payItems.CreditAccountCode.Substring(0, 3).Contains("111"))
                            {
                                // khởi tạo phieu chi chi tiết
                                CashDetailEntity cashDetailEntity = new CashDetailEntity()
                                {
                                    RefDetailId   = 0,
                                    RefId         = 0,
                                    AccountNumber = payItems.DebitAccountCode,
                                    CorrespondingAccountNumber = payItems.CreditAccountCode,
                                    Description        = payItems.PayItemName + " tháng " + mapper.RefDate.Month + "/" + mapper.RefDate.Year,
                                    AmountOc           = employeePayItemEntity.Amount * mapper.ExchangeRate,
                                    AmountExchange     = employeePayItemEntity.Amount,
                                    VoucherTypeId      = null,
                                    BudgetSourceCode   = payItems.BudgetSourceCode,
                                    BudgetItemCode     = payItems.BudgetItemCode,
                                    AccountingObjectId = null,
                                    MergerFundId       = null
                                };
                                bool flag = false;
                                for (int i = 0; i < cashEntity.CashDetails.Count; i++)
                                {
                                    if (cashEntity.CashDetails[i].CorrespondingAccountNumber == cashDetailEntity.CorrespondingAccountNumber && cashEntity.CashDetails[i].AccountNumber == cashDetailEntity.AccountNumber && cashEntity.CashDetails[i].BudgetItemCode == cashDetailEntity.BudgetItemCode && cashEntity.CashDetails[i].BudgetSourceCode == cashDetailEntity.BudgetSourceCode)
                                    {
                                        cashEntity.CashDetails[i].AmountOc       = cashEntity.CashDetails[i].AmountOc + cashDetailEntity.AmountOc;
                                        cashEntity.CashDetails[i].AmountExchange = cashEntity.CashDetails[i].AmountExchange + cashDetailEntity.AmountExchange;
                                        flag = true;
                                    }
                                }
                                if (flag == false)
                                {
                                    if (cashDetailEntity.AmountOc > 0)
                                    {
                                        cashEntity.CashDetails.Add(cashDetailEntity);
                                    }
                                }
                                //Tính lại TotalAmountOc - TotalAmountExchange
                                cashEntity.TotalAmount         = cashEntity.TotalAmount + cashDetailEntity.AmountOc;
                                cashEntity.TotalAmountExchange = cashEntity.TotalAmountExchange + cashDetailEntity.AmountExchange;
                                //Get Bank Acount
                                cashEntity.AccountNumber = payItems.CreditAccountCode;
                            }
                            //Nợ
                            if (payItems.CreditAccountCode.Substring(0, 3).Contains("112") == true)
                            {
                                DepositDetailEntity depositDetailEntity = new DepositDetailEntity()
                                {
                                    RefDetailId   = mapper.RefTypeId,
                                    RefId         = 0,
                                    Description   = payItems.PayItemName + " tháng " + mapper.RefDate.Month + "/" + mapper.RefDate.Year,
                                    AccountNumber = payItems.DebitAccountCode,
                                    CorrespondingAccountNumber = payItems.CreditAccountCode,
                                    AmountOc           = employeePayItemEntity.Amount * mapper.ExchangeRate,
                                    AmountExchange     = employeePayItemEntity.Amount,
                                    VoucherTypeId      = 1,
                                    BudgetSourceCode   = payItems.BudgetSourceCode,
                                    AccountingObjectId = null,
                                    BudgetItemCode     = payItems.BudgetItemCode,
                                    //DepartmentId = mapper.DepartmentId,
                                    MergerFundId = null
                                };
                                bool flag = false;
                                for (int i = 0; i < depositEntity.DepositDetails.Count; i++)
                                {
                                    if (depositEntity.DepositDetails[i].CorrespondingAccountNumber == depositDetailEntity.CorrespondingAccountNumber && depositEntity.DepositDetails[i].BudgetItemCode == depositDetailEntity.BudgetItemCode && depositEntity.DepositDetails[i].BudgetSourceCode == depositDetailEntity.BudgetSourceCode)
                                    {
                                        depositEntity.DepositDetails[i].AmountOc       = depositEntity.DepositDetails[i].AmountOc + depositDetailEntity.AmountOc;
                                        depositEntity.DepositDetails[i].AmountExchange = depositEntity.DepositDetails[i].AmountExchange + depositDetailEntity.AmountExchange;
                                        flag = true;
                                    }
                                }
                                if (flag == false)
                                {
                                    if (depositDetailEntity.AmountOc > 0)
                                    {
                                        depositEntity.DepositDetails.Add(depositDetailEntity);
                                    }
                                }
                                //Tính lại TotalAmountOc - TotalAmountExchange
                                depositEntity.TotalAmountOc       = depositEntity.TotalAmountOc + depositDetailEntity.AmountOc;
                                depositEntity.TotalAmountExchange = depositEntity.TotalAmountExchange + depositDetailEntity.AmountExchange;
                                //Get bank Acount
                                depositEntity.BankAccountCode = payItems.CreditAccountCode;
                            }
                        }
                    }
                    var autoNumber = AutoNumberDao.GetAutoNumberByRefType(600);
                    //------------------------------------------------------------------
                    //LinhMC 29/11/2014
                    //Lưu giá trị số tự động tăng theo loại tiền
                    //---------------------------------------------------------------
                    if (request.Salary.CurrencyCode == "USD")
                    {
                        autoNumber.Value += 1;
                    }
                    else
                    {
                        autoNumber.ValueLocalCurency += 1;
                    }

                    response.Message = AutoNumberDao.UpdateAutoNumber(autoNumber);
                    // insert or update giấy báo nợ

                    {
                        var checkDepositEntity = DepositDao.GetDepositByRefdateAndReftype(depositEntity);
                        if (checkDepositEntity == null)
                        {
                            if (depositEntity.DepositDetails.Count > 0)
                            {
                                var depositRequest = new DepositRequest();
                                var oDepositFacade = new DepositFacade();
                                depositRequest.Action  = PersistType.Insert;
                                depositRequest.Deposit = depositEntity;
                                oDepositFacade.SetDeposits(depositRequest);
                            }
                        }
                        //Sẽ không còn trường hợp này nữa
                        //else
                        //{
                        //    //Update CheckDepositEntity with amuont depositEntity,..
                        //    checkDepositEntity.DepositDetails = new List<DepositDetailEntity>();
                        //    checkDepositEntity.RefDate = depositEntity.RefDate;
                        //    checkDepositEntity.RefNo = depositEntity.RefNo;
                        //    checkDepositEntity.ExchangeRate = depositEntity.ExchangeRate;
                        //    checkDepositEntity.CurrencyCode = depositEntity.CurrencyCode;
                        //    checkDepositEntity.ExchangeRate = depositEntity.ExchangeRate;
                        //    checkDepositEntity.TotalAmountOc = depositEntity.TotalAmountOc;
                        //    checkDepositEntity.TotalAmountExchange = depositEntity.TotalAmountExchange;
                        //    checkDepositEntity.BankAccountCode = depositEntity.BankAccountCode;
                        //    //Thêm các details mới+
                        //    foreach (var depositDetail in depositEntity.DepositDetails)
                        //    {
                        //        if (!depositDetail.Validate())
                        //        {
                        //            foreach (string error in depositDetail.ValidationErrors)
                        //                response.Message += error + Environment.NewLine;
                        //            response.Acknowledge = AcknowledgeType.Failure;
                        //            return response;
                        //        }
                        //        depositDetail.RefId = checkDepositEntity.RefId;
                        //        checkDepositEntity.DepositDetails.Add(depositDetail);
                        //    }
                        //    var depositRequest = new DepositRequest();
                        //    var oDepositFacade = new DepositFacade();
                        //    depositRequest.Action = PersistType.Update;
                        //    depositRequest.Deposit = checkDepositEntity;
                        //    oDepositFacade.SetDeposits(depositRequest);
                        //}
                    }
                    // Insert phieu chi
                    //if (cashEntity.CashDetails.Count > 0)
                    //{
                    var checkCashEntity = CashDao.GetCashByRefdateAndReftype(cashEntity);
                    if (checkCashEntity == null)
                    {
                        if (cashEntity.CashDetails.Count > 0)
                        {
                            var cashRequest = new CashRequest();
                            var oCashFacade = new CashFacade();
                            cashRequest.Action     = PersistType.Insert;
                            cashRequest.CashEntity = cashEntity;
                            oCashFacade.SetCashes(cashRequest);
                        }
                    }
                    //Sẽ không có trường hợp này nữa
                    //else
                    //{
                    //    //Update
                    //    checkCashEntity.CashDetails = new List<CashDetailEntity>();
                    //    checkCashEntity.RefDate = cashEntity.RefDate;
                    //    checkCashEntity.RefNo = cashEntity.RefNo;
                    //    checkCashEntity.ExchangeRate = cashEntity.ExchangeRate;
                    //    checkCashEntity.CurrencyCode = cashEntity.CurrencyCode;
                    //    checkCashEntity.ExchangeRate = cashEntity.ExchangeRate;
                    //    checkCashEntity.TotalAmount = cashEntity.TotalAmount;
                    //    checkCashEntity.TotalAmountExchange = cashEntity.TotalAmountExchange;
                    //    checkCashEntity.AccountNumber = cashEntity.AccountNumber;
                    //    //Thêm các details mới+
                    //    foreach (var cashDetail in cashEntity.CashDetails)
                    //    {
                    //        if (!cashDetail.Validate())
                    //        {
                    //            foreach (string error in cashDetail.ValidationErrors)
                    //                response.Message += error + Environment.NewLine;
                    //            response.Acknowledge = AcknowledgeType.Failure;
                    //            return response;
                    //        }
                    //        cashDetail.RefId = checkCashEntity.RefId;
                    //        checkCashEntity.CashDetails.Add(cashDetail);
                    //    }
                    //    var cashRequest = new CashRequest();
                    //    var oCashFacade = new CashFacade();
                    //    cashRequest.Action = PersistType.Update;
                    //    cashRequest.CashEntity = checkCashEntity;
                    //    oCashFacade.SetCashes(cashRequest);
                    //}
                }

                if (request.LoadOptions.Contains("CheckCalSalaryState"))
                {
                    var salaries = SalaryDao.GetSalaryByRefDateAndEmployId(mapper.RefDate, mapper.EmployeeId);
                    if (salaries.Count > 0)
                    {
                        response.Acknowledge = AcknowledgeType.Success;
                        response.Message     = @"Nhân viên đã được tính lương !";
                        response.Salary      = salaries[0];
                        return(response);
                    }
                    response.Message = null;
                }

                if (request.LoadOptions.Contains("CheckCalSalaryPostedState"))
                {
                    var salaries = SalaryDao.GetSalaryPostedByRefDateAndEmployId(mapper.RefDate, mapper.EmployeeId);
                    if (salaries.Count > 0)
                    {
                        response.Acknowledge = AcknowledgeType.Success;
                        response.Message     = @"Nhân viên đã được tính lương !";
                        response.Salary      = salaries[0];
                        return(response);
                    }
                    response.Message = null;
                }

                if (request.LoadOptions.Contains("DeleteCalSalary"))
                {
                    //foreach (var employee in mapper.Employees)
                    //{
                    //    mapper.EmployeeId = employee.EmployeeId;
                    //    response.SalaryId = SalaryDao.DeleteCalSalary(mapper);
                    //}

                    var depositEntity = new DepositEntity()
                    {
                        RefId                = 0,
                        RefTypeId            = mapper.RefTypeId,//
                        RefDate              = mapper.RefDate,
                        RefNo                = mapper.RefNo,
                        PostedDate           = mapper.PostedDate,
                        AccountingObjectType = 0,
                        AccountingObjectId   = null,
                        Trader               = "",
                        CustomerId           = null,
                        VendorId             = null,
                        EmployeeId           = null,// mapper.EmployeeId,
                        BankAccountCode      = "112",
                        CurrencyCode         = mapper.CurrencyCode,
                        ExchangeRate         = mapper.ExchangeRate,
                        TotalAmountOc        = 0, // employeePayItem.Amount,
                        TotalAmountExchange  = 0, // employeePayItem.Amount,
                        JournalMemo          = "Chứng từ lương tháng " + mapper.RefDate.Month + "/" + mapper.RefDate.Year,
                    };
                    depositEntity.DepositDetails = new List <DepositDetailEntity>();
                    var cashEntity = new CashEntity()
                    {
                        RefId              = 0,
                        RefTypeId          = mapper.RefTypeId,//
                        RefNo              = mapper.RefNo,
                        RefDate            = mapper.RefDate,
                        PostedDate         = mapper.PostedDate,
                        AccountingObjectId = null,
                        CustomerId         = null,
                        VendorId           = null,
                        Trader             = "",
                        CurrencyCode       = mapper.CurrencyCode,
                        ExchangeRate       = mapper.ExchangeRate,

                        TotalAmount         = 0,
                        TotalAmountExchange = 0,
                        AccountNumber       = "",

                        JournalMemo          = "Chứng từ lương tháng " + mapper.RefDate.Month + "/" + mapper.RefDate.Year,
                        DocumentInclude      = "",
                        AccountingObjectType = 2,
                        //     CashDetails = cashDetails;
                        EmployeeId = null,
                    };
                    cashEntity.CashDetails = new List <CashDetailEntity>();

                    //  var Cash
                    foreach (var employee in mapper.Employees)
                    {
                        //Xóa EmployeePayroll
                        mapper.EmployeeId = employee.EmployeeId;
                        response.SalaryId = SalaryDao.DeleteCalSalary(mapper);
                        //End Xóa EmployeePayroll
                        //Từng nhân viên - từng khoảng lương - tiền tương ứng.
                        IList <EmployeePayItemEntity> listPayItems = EmployeePayItemDao.GetEmployeePayItemsByEmployeeId(employee.EmployeeId);
                        foreach (var employeePayItemEntity in listPayItems)
                        {
                            mapper.EmployeePayItemId = employeePayItemEntity.EmployeePayItemId;
                            var payItems = PayItemDao.GetPayItem(employeePayItemEntity.PayItemId);
                            //Chi
                            if (payItems.CreditAccountCode.Substring(0, 3).Contains("111"))
                            {
                                // khởi tạo phieu chi chi tiết
                                var cashDetailEntity = new CashDetailEntity()
                                {
                                    RefDetailId   = 0,
                                    RefId         = 0,
                                    AccountNumber = payItems.DebitAccountCode,
                                    CorrespondingAccountNumber = payItems.CreditAccountCode,
                                    Description        = payItems.PayItemName + " tháng " + mapper.RefDate.Month + "/" + mapper.RefDate.Year,
                                    AmountOc           = employeePayItemEntity.Amount,
                                    AmountExchange     = employeePayItemEntity.Amount / mapper.ExchangeRate,
                                    VoucherTypeId      = null,
                                    BudgetSourceCode   = payItems.BudgetSourceCode,
                                    BudgetItemCode     = payItems.BudgetItemCode,
                                    AccountingObjectId = null,
                                    MergerFundId       = null
                                };
                                bool flag = false;
                                for (int i = 0; i < cashEntity.CashDetails.Count; i++)
                                {
                                    if (cashEntity.CashDetails[i].CorrespondingAccountNumber == cashDetailEntity.CorrespondingAccountNumber &&
                                        cashEntity.CashDetails[i].AccountNumber == cashDetailEntity.AccountNumber &&
                                        cashEntity.CashDetails[i].BudgetItemCode == cashDetailEntity.BudgetItemCode &&
                                        cashEntity.CashDetails[i].BudgetSourceCode == cashDetailEntity.BudgetSourceCode)
                                    {
                                        cashEntity.CashDetails[i].AmountOc       = cashEntity.CashDetails[i].AmountOc + cashDetailEntity.AmountOc;
                                        cashEntity.CashDetails[i].AmountExchange = cashEntity.CashDetails[i].AmountExchange + cashDetailEntity.AmountExchange;
                                        flag = true;
                                        //   break;
                                    }
                                }

                                if (flag == false)
                                {
                                    cashEntity.CashDetails.Add(cashDetailEntity);
                                }

                                //Tính lại TotalAmountOc - TotalAmountExchange
                                cashEntity.TotalAmount         = cashEntity.TotalAmount + cashDetailEntity.AmountOc;
                                cashEntity.TotalAmountExchange = cashEntity.TotalAmountExchange + cashDetailEntity.AmountExchange;
                                //Get Bank Acount
                                cashEntity.AccountNumber = payItems.CreditAccountCode;
                            }
                            //Nợ
                            if (payItems.CreditAccountCode.Substring(0, 3).Contains("112"))
                            {
                                var depositDetailEntity = new DepositDetailEntity()
                                {
                                    RefDetailId   = mapper.RefTypeId,
                                    RefId         = 0,
                                    Description   = payItems.PayItemName + " tháng " + mapper.RefDate.Month + "/" + mapper.RefDate.Year,
                                    AccountNumber = payItems.DebitAccountCode,
                                    CorrespondingAccountNumber = payItems.CreditAccountCode,
                                    AmountOc           = employeePayItemEntity.Amount,
                                    AmountExchange     = employeePayItemEntity.Amount / mapper.ExchangeRate,
                                    VoucherTypeId      = 1,
                                    BudgetSourceCode   = payItems.BudgetSourceCode,
                                    AccountingObjectId = null,
                                    BudgetItemCode     = payItems.BudgetItemCode,
                                    //    DepartmentId = mapper.DepartmentId,
                                    MergerFundId = null
                                };
                                bool flag = false;
                                for (int i = 0; i < depositEntity.DepositDetails.Count; i++)
                                {
                                    if (depositEntity.DepositDetails[i].CorrespondingAccountNumber == depositDetailEntity.CorrespondingAccountNumber &&
                                        depositEntity.DepositDetails[i].BudgetItemCode == depositDetailEntity.BudgetItemCode &&
                                        depositEntity.DepositDetails[i].BudgetSourceCode == depositDetailEntity.BudgetSourceCode)
                                    {
                                        depositEntity.DepositDetails[i].AmountOc       = depositEntity.DepositDetails[i].AmountOc + depositDetailEntity.AmountOc;
                                        depositEntity.DepositDetails[i].AmountExchange = depositEntity.DepositDetails[i].AmountExchange + depositDetailEntity.AmountExchange;
                                        flag = true;
                                        //  break;
                                    }
                                }

                                if (flag == false)
                                {
                                    depositEntity.DepositDetails.Add(depositDetailEntity);
                                }
                                //Tính lại TotalAmountOc - TotalAmountExchange
                                depositEntity.TotalAmountOc       = depositEntity.TotalAmountOc + depositDetailEntity.AmountOc;
                                depositEntity.TotalAmountExchange = depositEntity.TotalAmountExchange +
                                                                    depositDetailEntity.AmountExchange;
                                //Get bank Acount
                                depositEntity.BankAccountCode = payItems.CreditAccountCode;
                            }
                        }
                    }
                    var cashRequest = new CashRequest();
                    var oCashFacade = new CashFacade();
                    cashRequest.Action = PersistType.Delete;
                    var cashForDelete = CashDao.GetCashByRefdateAndReftype(cashEntity);
                    if (cashForDelete != null)
                    {
                        cashRequest.RefId     = cashForDelete.RefId;
                        cashRequest.RefTypeId = cashForDelete.RefTypeId;
                        //    cashRequest.CashEntity = cashEntity;
                        oCashFacade.SetCashes(cashRequest);
                    }

                    var depositRequest = new DepositRequest();
                    var oDepositFacade = new DepositFacade();
                    depositRequest.Action = PersistType.Delete;
                    var depositForDelete = DepositDao.GetDepositByRefdateAndReftype(depositEntity);
                    if (depositForDelete != null)
                    {
                        depositRequest.RefId   = depositForDelete.RefId;
                        depositRequest.RefType = depositForDelete.RefTypeId;
                        //    depositRequest.Deposit = depositEntity;
                        oDepositFacade.SetDeposits(depositRequest);
                    }
                }
            }
            catch (Exception ex)
            {
                response.Acknowledge = AcknowledgeType.Failure;
                response.Message     = ex.Message;
                return(response);
            }
            response.Acknowledge = response.Message != null ? AcknowledgeType.Failure : AcknowledgeType.Success;
            return(response);
        }