예제 #1
0
        public int ProcessBillingResult(string batchNo, string fileName)
        {
            List <BillingRejectionViewModel> rejections = ReadBillingResultFile(fileName).ToList();

            foreach (BillingRejectionViewModel rejection in rejections)
            {
                InvoiceHeader invoice = context.InvoiceHeaders.SingleOrDefault(ih => ih.InvoiceNo == rejection.InvoiceNo && !ih.VoidDate.HasValue);
                if (invoice != null)
                {
                    var payments = invoice.PaymentHeaders.Where(ph => !ph.VoidDate.HasValue);
                    foreach (var payment in payments)
                    {
                        payment.VoidDate   = DateTime.Today;
                        payment.VoidReason = "AUTO PAY DECLINED: " + rejection.DeclineCode;
                    }

                    var status = new CustomerStatusHistory();
                    status.Customer         = invoice.Customer;
                    status.Date             = DateTime.Today;
                    status.CustomerStatusID = 4; // billing problem
                    status.Notes            = "AUTO PAY DECLINED OF INVOICE " + invoice.InvoiceNo + ", REJECTION CODE: " + rejection.DeclineCode;
                    status.StartDate        = DateTime.Today;
                    EntityHelper.SetAuditFieldForInsert(status, principal.Identity.Name);
                }
            }

            BillingHeader billing = context.BillingHeaders.SingleOrDefault(b => b.BatchNo == batchNo);

            if (billing != null)
            {
                billing.ResultProcessDate = DateTime.Now;
                foreach (var detail in billing.BillingDetails)
                {
                    var rejection =
                        rejections.SingleOrDefault(reject => reject.InvoiceNo == detail.InvoiceHeader.InvoiceNo);
                    if (rejection != null)
                    {
                        detail.BillingResult = rejection.DeclineCode;
                    }
                }
            }

            context.SaveChanges();

            return(rejections.Count);

            //foreach (var billingDetail in billing.BillingDetails)
            //{
            //    InvoiceHeader invoice = billingDetail.InvoiceHeader;
            //    if (invoice != null)
            //    {
            //        PaymentHeader payment = invoice.PaymentHeaders.SingleOrDefault(ph => !ph.VoidDate.HasValue);
            //        if (payment != null)
            //        {
            //            payment.VoidDate = DateTime.Today;
            //            payment.VoidReason = "AUTO PAY DECLINED: " + rejection.DeclineCode;
            //        }
            //    }
            //}
        }
        public void AddStatusHistory(CustomerStatus customerStatus, Customer customer, DateTime startDate, DateTime?endDate)
        {
            var csh = new CustomerStatusHistory();

            csh.CustomerStatusID = customerStatus.ID;
            csh.CustomerID       = customer.ID;
            csh.StartDate        = startDate;
            csh.EndDate          = endDate;
            EntityHelper.SetAuditFieldForInsert(csh, HttpContext.Current.User.Identity.Name);
            ctx.CustomerStatusHistories.InsertOnSubmit(csh);
            ctx.SubmitChanges();
        }
예제 #3
0
        public void AddStatusHistory(CustomerStatus customerStatus, Customer customer, DateTime startDate, DateTime?endDate)
        {
            var csh = new CustomerStatusHistory();

            csh.CustomerStatusID = customerStatus.ID;
            csh.CustomerID       = customer.ID;
            csh.StartDate        = startDate;
            csh.EndDate          = endDate;
            EntityHelper.SetAuditFieldForInsert(csh, principal.Identity.Name);
            context.Add(csh);
            context.SaveChanges();
        }
예제 #4
0
        public int ProcessBillingUnpaidInvoice(string fileName)
        {
            // accepted
            List <BillingAcceptedViewModel> acceptedInvoices = ReadBillingUnpaidAcceptedFile(fileName).ToList();

            foreach (BillingAcceptedViewModel acceptedInvoice in acceptedInvoices)
            {
                InvoiceHeader invoice = context.InvoiceHeaders.SingleOrDefault(ih => ih.InvoiceNo == acceptedInvoice.InvoiceNo);
                if (invoice != null)
                {
                    Customer cust = invoice.Customer;

                    var payments = invoice.PaymentHeaders.Where(ph => !ph.VoidDate.HasValue);
                    foreach (var payment in payments)
                    {
                        payment.VoidDate = DateTime.Today;
                        //payment.VoidReason = "AUTO PAY DECLINED: " + acceptedInvoice.DeclineCode;
                    }

                    string paymentNo = autoNumberProvider.Generate(invoice.BranchID, "PM", DateTime.Today.Month, DateTime.Today.Year);

                    var h = new PaymentHeader();
                    h.Date      = DateTime.Today;
                    h.InvoiceID = invoice.ID;
                    h.PaymentNo = paymentNo;
                    h.VoidDate  = null;
                    EntityHelper.SetAuditFieldForInsert(h, principal.Identity.Name);

                    var d = new PaymentDetail();
                    d.CreditCardTypeID = cust.CreditCardTypeID;
                    d.PaymentTypeID    = 4; // credit  card
                    d.Amount           = invoice.InvoiceDetails.Sum(inv => (inv.Quantity * inv.UnitPrice) - (inv.Discount / 100 * (inv.Quantity * inv.UnitPrice)));
                    d.ApprovalCode     = acceptedInvoice.VerificationCode;
                    h.PaymentDetails.Add(d);
                    context.Add(h);

                    autoNumberProvider.Increment("PM", invoice.BranchID, DateTime.Today.Year);

                    var status = new CustomerStatusHistory();
                    status.Customer         = invoice.Customer;
                    status.Date             = DateTime.Today;
                    status.CustomerStatusID = 1; // OK
                    status.Notes            = "AUTO PAY ACCEPTED FOR INVOICE " + invoice.InvoiceNo;
                    status.StartDate        = DateTime.Today;
                    EntityHelper.SetAuditFieldForInsert(status, principal.Identity.Name);
                }
            }

            context.SaveChanges();

            return(acceptedInvoices.Count);
        }
예제 #5
0
    private void GetCustomerInfo(string customerCode)
    {
        Customer cust = customerProvider.Get(customerCode);

        if (cust != null)
        {
            CustomerStatusHistory customerStatusHistory = customerStatusProvider.GetLatestStatus(customerCode);

            lblBarcode.Text = cust.Barcode;
            lblName.Text    = String.Format("{0} {1}", cust.FirstName, cust.LastName);
//            lblStatus.Text = customerStatusHistory == null ? "OK" : customerStatusHistory.CustomerStatus.Description;
            lblDateOfBirth.Text = cust.DateOfBirth.HasValue ? cust.DateOfBirth.Value.ToString("dddd, dd MMMM yyyy") : String.Empty;
        }
    }
예제 #6
0
 public static CustomerRelationsModel CreateChangeStatus(CustomerStatusHistory customerStatusHistory)
 {
     return(new CustomerRelationsModel
     {
         User = customerStatusHistory.Username == "se" ? "System" : customerStatusHistory.Username,
         Action = "Change Status",
         Comment = string.Format("description:{0}, previous status:{1}, current status:{2}{3}{4}{5}",
                                 customerStatusHistory.Description,
                                 customerStatusHistory.PreviousStatus.Name,
                                 customerStatusHistory.NewStatus.Name,
                                 string.IsNullOrEmpty(customerStatusHistory.Feedback) ? "" : ", feedback:" + customerStatusHistory.Feedback,
                                 customerStatusHistory.Amount.HasValue ? ", amount:" + customerStatusHistory.Amount.Value : "",
                                 customerStatusHistory.ApplyForJudgmentDate.HasValue ? ", apply for judgment date: " + customerStatusHistory.ApplyForJudgmentDate.Value.ToString("dd/MM/yyyy") : ""),
         DateTime = customerStatusHistory.Timestamp,
         Status = customerStatusHistory.NewStatus.Name
     });
 }
예제 #7
0
        }         // FillFreezeIntervals

        private void FillCustomerStatuses()
        {
            CustomerStatusHistory = new CustomerStatusHistory(null, this.m_oDateEnd, this.m_oDB);

            foreach (KeyValuePair <int, List <CustomerStatusChange> > pair in CustomerStatusHistory.FullData.Data)
            {
                int nCustomerID = pair.Key;

                foreach (CustomerStatusChange csc in pair.Value)
                {
                    try {
                        bool bAlreadyHas = this.m_oBadPeriods.ContainsKey(nCustomerID);
                        bool bLastKnown  = !bAlreadyHas || this.m_oBadPeriods[nCustomerID].IsLastKnownGood;
                        bool bIsOldGood  = !BadPeriods.IsBad(csc.OldStatus);
                        bool bIsNewGood  = !BadPeriods.IsBad(csc.NewStatus);

                        if (bLastKnown != bIsOldGood)
                        {
                            Warn(
                                "Last known status is '{0}' while previous status is '{1}' for customer {2} on {3}.",
                                (bLastKnown ? "good" : "bad"),
                                (bIsOldGood ? "good" : "bad"),
                                nCustomerID,
                                csc.ChangeDate.ToString("MMM dd yyyy", CultureInfo.InvariantCulture)
                                );
                        }                         // if

                        if (bLastKnown != bIsNewGood)
                        {
                            if (bAlreadyHas)
                            {
                                this.m_oBadPeriods[nCustomerID].Add(csc.ChangeDate, !bIsNewGood);
                            }
                            else
                            {
                                this.m_oBadPeriods[nCustomerID] = new BadPeriods(csc.ChangeDate);
                            }
                        }                         // if
                    } catch (Exception e) {
                        Alert(e, "Failed to process customer status history entry.");
                    } // try
                }     // for each status change
            }         // for each customer
        }             // FillCustomerStatuses
예제 #8
0
        public void Approve(int id)
        {
            ChangeStatusDocument doc = context.ChangeStatusDocuments.Single(d => d.ID == id);
            Employee             emp = context.Employees.SingleOrDefault(e => e.ID == doc.EmployeeID);

            if (emp != null && doc != null)
            {
                doc.ApprovedDate         = DateTime.Now;
                doc.ApprovedByEmployeeID = emp.ID;
                EntityHelper.SetAuditFieldForUpdate(doc, principal.Identity.Name);

                CustomerStatusHistory csh = new CustomerStatusHistory();
                csh.StartDate            = doc.StartDate;
                csh.EndDate              = doc.EndDate;
                csh.Notes                = doc.Notes;
                csh.CustomerID           = doc.CustomerID;
                csh.Date                 = DateTime.Today;
                csh.ChangeStatusDocument = doc;
                EntityHelper.SetAuditFieldForInsert(csh, principal.Identity.Name);

                if (doc.DocumentType.ChangeCustomerStatusIDTo.HasValue)
                {
                    csh.CustomerStatusID = doc.DocumentType.ChangeCustomerStatusIDTo.Value;
                }

                //if (doc.DocumentType.IsLastState)
                //{
                //    foreach (Contract activeContract in doc.Customer.Contracts.Where(con => con.Status == ContractStatus.PAID))
                //        activeContract.Status = ContractStatus.CLOSED;
                //}

                context.Add(csh);

                context.SaveChanges();
            }
        }
예제 #9
0
        public CustomerCheckInViewModel DoCheckInByContract(int branchID, string contractNo, string userName)
        {
            var      messages               = new List <string>();
            var      model                  = new CustomerCheckInViewModel();
            var      checkInConfiguration   = new CheckInConfiguration();
            Contract contract               = context.Contracts.FirstOrDefault(con => con.ContractNo == contractNo);
            var      customerStatusProvider = new CustomerStatusProvider(context, principal);

            if (contract != null)
            {
                var customer = contract.Customer;
                var package  = contract.PackageHeader;

                model.CustomerBarcode = customer.Barcode;
                model.CustomerName    = String.Format("{0} {1}", customer.FirstName, customer.LastName);
                model.PackageName     = package.Name;
                model.ContractNo      = contractNo;
                model.ExpiredDate     = contract.ExpiredDate.ToString("dddd, dd MMMM yyyy");
                model.MemberSince     = customer.CreatedWhen.ToString("dddd, dd MMMM yyyy");
                model.Photo           = customer.Photo;
                model.IsPhotoExist    = !String.IsNullOrEmpty(model.Photo);
                model.Age             = customer.DateOfBirth.GetValueOrDefault().ToAgeString();

                if (contract.ExpiredDate <= DateTime.Today)
                {
                    messages.Add("CONTRACT IS EXPIRED");
                }

                if (contract.ActiveDate.HasValue)
                {
                    messages.Add(String.Format("Contract has been activated since {0}",
                                               contract.ActiveDate.Value.ToString("dddd, dd MMMM yyyy")));
                }
                else
                {
                    messages.Add("CONTRACT IS NOT ACTIVE");
                }

                CustomerStatusHistory customerStatusHistory = customerStatusProvider.GetLatestStatus(customer.Barcode);
                model.CustomerStatus = customerStatusHistory == null
                    ? "OK"
                    : customerStatusHistory.CustomerStatus.Description;
                if (checkInConfiguration.BirthdayAlert)
                {
                    bool isBirthDay = customer.DateOfBirth.GetValueOrDefault().Month == DateTime.Today.Month &&
                                      customer.DateOfBirth.GetValueOrDefault().Day == DateTime.Today.Day;
                    if (isBirthDay)
                    {
                        messages.Add("HAPPY BIRTHDAY");
                    }
                }
                model.Messages = messages;

                /* Save checkin history */
                var checkinlog = new CheckInLog();
                checkinlog.BranchID   = branchID;
                checkinlog.CustomerID = customer.ID;

                checkinlog.CustomerStatusID = customerStatusHistory == null ? 1 : customerStatusHistory.CustomerStatusID;
                checkinlog.Employee         = context.Employees.SingleOrDefault(emp => emp.UserName == userName);
                checkinlog.CheckInWhen      = DateTime.Now;
                checkinlog.Messages         = String.Join("|", messages.ToArray());
                checkinlog.Allowed          = model.AllowCheckIn;
                checkinlog.ContractID       = contract.ID;
                context.Add(checkinlog);
                context.SaveChanges();
            }
            else
            {
                model.AllowCheckIn = false;
                messages.Add("INVALID CONTRACT NUMBER");
                model.Messages = messages;
            }

            return(model);
        }
예제 #10
0
        public CustomerCheckInViewModel DoCheckIn(int branchID, string customerBarcode, string userName, string path)
        {
            var checkInConfiguration = new CheckInConfiguration();

            var messages  = new List <string>();
            var viewModel = new CustomerCheckInViewModel();

            viewModel.PickUpPersons = new List <string>();
            viewModel.PickUpPhotos  = new List <string>();

            var customerStatusProvider = new CustomerStatusProvider(context, principal);

            Customer customer = context.Customers.SingleOrDefault(cust => cust.Barcode == customerBarcode);

            if (customer != null)
            {
                viewModel.CustomerBarcode = customerBarcode.ToUpper();
                viewModel.CustomerName    = String.Format("{0} {1}", customer.FirstName.Trim().ToUpper(), customer.LastName.Trim().ToUpper());
                viewModel.When            = DateTime.Now;
                viewModel.Photo           = customer.Photo;
                viewModel.Age             = customer.DateOfBirth.GetValueOrDefault().ToAgeString();
                viewModel.IsPhotoExist    = File.Exists(path + customer.Photo);
                viewModel.AllowCheckIn    = true;

                foreach (var person in customer.People.Where(p => p.Connection == 'P'))
                {
                    viewModel.PickUpPersons.Add(person.Name);
                    viewModel.PickUpPhotos.Add(person.Photo);
                }

                /* Get Messages */

                var contractProvider = new ContractProvider(context, principal);
                var activeContract   = contractProvider.GetActiveContracts(customerBarcode).FirstOrDefault(contract => contract.EffectiveDate <= DateTime.Today);
                if (activeContract != null)
                {
                    if (!activeContract.PackageHeader.OpenEnd)
                    {
                        if (activeContract.ExpiredDate < DateTime.Today)
                        {
                            messages.Add("CONTRACT " + activeContract.ContractNo + " EXPIRED");
                        }
                        else if (activeContract.ExpiredDate.Subtract(DateTime.Today) <= TimeSpan.FromDays(30))
                        {
                            messages.Add("CONTRACT " + activeContract.ContractNo + " EXPIRING");
                        }
                    }
                    viewModel.PackageName = activeContract.PackageHeader.Name;
                }
                else
                {
                    messages.Add("UNAPPROVED CONTRACT");
                }

                if (checkInConfiguration.ContractNotActiveAlert)
                {
                    var inactiveContracts = customer.Contracts.Where(contract => !contract.ActiveDate.HasValue && !contract.VoidDate.HasValue && contract.EffectiveDate <= DateTime.Today).ToList();
                    if (inactiveContracts.Any())
                    {
                        messages.Add("CONTRACT NOT ACTIVE: " + String.Join(", ", inactiveContracts.Select(contract => contract.ContractNo).ToArray()));
                    }
                }

                if (checkInConfiguration.ContractNotPaid)
                {
                    var unpaidContracts = customer.Contracts.Where(contract => !contract.PurchaseDate.HasValue && !contract.VoidDate.HasValue && contract.EffectiveDate <= DateTime.Today).ToList();
                    if (unpaidContracts.Any())
                    {
                        messages.Add("CONTRACT NOT PAID: " + String.Join(", ", unpaidContracts.Select(contract => contract.ContractNo).ToArray()));
                    }
                }

                if (checkInConfiguration.BirthdayAlert)
                {
                    bool isBirthDay = customer.DateOfBirth.GetValueOrDefault().Month == DateTime.Today.Month &&
                                      customer.DateOfBirth.GetValueOrDefault().Day == DateTime.Today.Day;
                    if (isBirthDay)
                    {
                        messages.Add("HAPPY BIRTHDAY");
                    }
                }

                if (customer.BillingType.ID > BillingTypeConstants.MANUAL_PAYMENT)
                {
                    // alert for credit card is valid only for non-manual payment
                    if (DateTime.Today >= customer.ExpiredDate.GetValueOrDefault() && checkInConfiguration.CreditCardExpired)
                    {
                        messages.Add("CREDIT CARD IS EXPIRED");
                    }
                    else
                    {
                        if (checkInConfiguration.CreditCardExpiringAlert)
                        {
                            bool isCreditCardExpiring = customer.ExpiredDate.GetValueOrDefault().Subtract(DateTime.Today) <= TimeSpan.FromDays(30);
                            if (isCreditCardExpiring)
                            {
                                messages.Add("CREDIT CARD IS EXPIRING");
                            }
                        }
                    }
                }

                CustomerStatusHistory customerStatusHistory = customerStatusProvider.GetLatestStatus(customerBarcode);
                viewModel.CustomerStatus = customerStatusHistory == null ? "OK" : customerStatusHistory.CustomerStatus.Description;
                string color = customerStatusProvider.GetStatusColor(viewModel.CustomerStatus);
                viewModel.CustomerStatusColor           = color.Split('|')[0];
                viewModel.CustomerStatusBackgroundColor = color.Split('|')[1];

                messages.AddRange(customer.CustomerNotes.Where(note => note.Priority == 1).Select(note => note.Notes));

                viewModel.Messages = messages;


                /* Save checkin history */
                var checkinlog = new CheckInLog();
                checkinlog.BranchID   = branchID;
                checkinlog.CustomerID = customer.ID;

                checkinlog.CustomerStatusID = customerStatusHistory == null ? 1 : customerStatusHistory.CustomerStatusID;
                checkinlog.Employee         = context.Employees.SingleOrDefault(emp => emp.UserName == userName);
                checkinlog.CheckInWhen      = viewModel.When.Value;
                checkinlog.Messages         = String.Join("|", messages.ToArray());
                checkinlog.Allowed          = viewModel.AllowCheckIn;
                context.Add(checkinlog);
                context.SaveChanges();
            }
            else
            {
                viewModel.AllowCheckIn = false;
                messages.Add("INVALID CUSTOMER BARCODE");
                viewModel.Messages = messages;
            }

            return(viewModel);
        }
예제 #11
0
        private void LoadData(int customerID)
        {
            Customer cust = CustomerService.Get(customerID);

            txtBarcode.ReadOnly          = true;
            txtFirstName.Text            = cust.FirstName;
            txtLastName.Text             = cust.LastName;
            txtBarcode.Text              = cust.Barcode;
            txtAddress.Text              = cust.Address;
            ddlBillingType.SelectedValue = cust.BillingTypeID.ToString();
            txtCardNo.Text         = cust.CardNo;
            txtCardHolderName.Text = cust.CardHolderName;
            txtCardHolderID.Text   = cust.CardHolderID;
            if (cust.BankID.HasValue)
            {
                ddlBank.SelectedValue = cust.BankID.ToString();
            }

            if (cust.ExpiredDate.HasValue)
            {
                calExpiredDate.SelectedDate = cust.ExpiredDate.Value;
            }
            calDate.SelectedDate = cust.DateOfBirth.HasValue ? cust.DateOfBirth.Value : DateTime.Today;
            txtEmail.Text        = cust.Email;
            txtPhone.Text        = cust.HomePhone;
            txtCellPhone.Text    = cust.CellPhone1;
            txtCellPhone2.Text   = cust.CellPhone2;
            txtWorkPhone.Text    = cust.WorkPhone;
            txtZipCode.Text      = cust.ZipCode;
            txtIDCardNo.Text     = cust.IDCardNo;
            if (cust.OccupationID.HasValue)
            {
                ddlOccupation.SelectedValue = Convert.ToString(cust.OccupationID);
            }
            else
            {
                ddlOccupation.SelectedIndex = 0;
            }
            txtMailingAddress.Text = cust.MailingAddress;
            txtMailingZipCode.Text = cust.MailingZipCode;
            txtPartner.Text        = cust.Customer1 == null ? String.Empty : cust.Customer1.Barcode;
            if (cust.CreditCardTypeID.HasValue)
            {
                ddlCreditCardType.SelectedValue = cust.CreditCardTypeID.ToString();
            }
            if (cust.AreaID.HasValue)
            {
                ddlArea.SelectedValue = cust.AreaID.ToString();
            }
            else
            {
                ddlArea.SelectedIndex = 0;
            }
            lblHomeBranch.Text = cust.Branch.Name;
            ViewState["Photo"] = cust.Photo;


            RefreshActiveContracts(cust.Barcode);

            CustomerStatusHistory customerStatus = CustomerStatusService.GetLatestStatus(cust.Barcode);

            lblStatus.Text      = customerStatus == null ? "OK" : customerStatus.CustomerStatus.Description;
            lblStatusNotes.Text = customerStatus == null ? String.Empty : customerStatus.Notes;

            if (!String.IsNullOrEmpty(cust.Photo))
            {
                FileInfo file = new FileInfo(cust.Photo);
                imgPhoto.ImageUrl = ConfigurationManager.AppSettings[ApplicationSettingKeys.FolderPhotoCustomers] + @"\" + file.Name.Substring(0, file.Name.IndexOf(".")) + file.Extension + ".ashx?w=200";
            }
            else
            {
                imgPhoto.ImageUrl = ConfigurationManager.AppSettings[ApplicationSettingKeys.FolderPhotoCustomers] + @"\default.png";
            }
            chkDeletePhoto.Checked = false;

            hypParent.Attributes["onclick"]            = String.Format("window.open('MasterParents.aspx?CustomerCode={0}', 'Parent', 'width=800,height=500,location=no,resizable=yes')", txtBarcode.Text);
            hypViewStatusHistory.Attributes["onclick"] = String.Format("window.open('ViewCustomerStatusHistory.aspx?CustomerCode={0}', 'Parent', 'width=1100,height=500,location=no,resizable=yes')", txtBarcode.Text);

            gvwParents.DataBind();

            txtCardHolderID.ReadOnly = txtCardHolderName.ReadOnly = txtCardNo.ReadOnly = Convert.ToInt32(ddlBillingType.SelectedValue) == 3;
            calExpiredDate.Enabled   = ddlBank.Enabled = ddlCreditCardType.Enabled = !txtCardNo.ReadOnly;

            txtBarcode.Focus();
        }
예제 #12
0
        public JsonResult Save(LoanOptions options)
        {
            if (options.ManualCaisFlag == "T")
            {
                options.ManualCaisFlag = "Calculated value";
            }

            this._loanOptionsRepository.SaveOrUpdate(options);
            Customer customer = this._loanRepository.Get(options.LoanId).Customer;

            NL_SaveLoanOptions(customer, options);

            if (options.CaisAccountStatus == "8")
            {
                int minDectForDefault = CurrentValues.Instance.MinDectForDefault;

                Loan triggeringLoan = null;

                // Update loan options
                foreach (Loan loan in customer.Loans)
                {
                    if (loan.Id == options.LoanId)
                    {
                        triggeringLoan = loan;
                        continue;
                    }

                    if (loan.Status == LoanStatus.PaidOff || loan.Balance < minDectForDefault)
                    {
                        continue;
                    }

                    LoanOptions currentOptions = this._loanOptionsRepository.GetByLoanId(loan.Id) ?? new LoanOptions
                    {
                        LoanId                  = loan.Id,
                        AutoPayment             = true,
                        ReductionFee            = true,
                        LatePaymentNotification = true,
                        EmailSendingAllowed     = false,
                        MailSendingAllowed      = false,
                        SmsSendingAllowed       = false,
                        ManualCaisFlag          = "Calculated value",
                        AutoLateFees            = true
                    };

                    currentOptions.CaisAccountStatus = "8";
                    this._loanOptionsRepository.SaveOrUpdate(currentOptions);
                    NL_SaveLoanOptions(customer, options);
                }


                // Update customer status
                CustomerStatuses prevStatus = customer.CollectionStatus;
                customer.CollectionStatus      = this.customerStatusesRepository.Get((int)CollectionStatusNames.Default);
                customer.CollectionDescription = string.Format("Triggered via loan options:{0}", triggeringLoan != null ? triggeringLoan.RefNumber : "unknown");

                // Update status history table
                var newEntry = new CustomerStatusHistory
                {
                    Username       = User.Identity.Name,
                    Timestamp      = DateTime.UtcNow,
                    CustomerId     = customer.Id,
                    PreviousStatus = prevStatus,
                    NewStatus      = customer.CollectionStatus,
                };
                this.customerStatusHistoryRepository.SaveOrUpdate(newEntry);
            }

            return(Json(new { }));
        }
        public JsonResult Save(int customerId, CollectionStatusModel collectionStatus)
        {
            var customer   = this.customerRepository.Get(customerId);
            var prevStatus = customer.CollectionStatus;

            if (prevStatus.Id == collectionStatus.CurrentStatus)
            {
                return(Json(new { }));
            }

            customer.CollectionStatus      = this.customerStatusesRepository.Get(collectionStatus.CurrentStatus);
            customer.CollectionDescription = collectionStatus.CollectionDescription;
            List <int> addFreeseLoans = new List <int>();

            new Transactional(() => {
                this.customerRepository.SaveOrUpdate(customer);

                if (customer.CollectionStatus.IsDefault)
                {
                    // Update loan options
                    foreach (Loan loan in customer.Loans.Where(l => l.Status != LoanStatus.PaidOff && l.Balance >= CurrentValues.Instance.MinDectForDefault))
                    {
                        LoanOptions options = this.loanOptionsRepository.GetByLoanId(loan.Id) ?? new LoanOptions {
                            LoanId                  = loan.Id,
                            AutoPayment             = true,
                            ReductionFee            = true,
                            LatePaymentNotification = true,
                            EmailSendingAllowed     = false,
                            MailSendingAllowed      = false,
                            SmsSendingAllowed       = false,
                            ManualCaisFlag          = "Calculated value",
                        };
                        options.CaisAccountStatus = "8";
                        this.loanOptionsRepository.SaveOrUpdate(options);
                        NL_SaveLoanOptions(customer, options);
                    }
                }

                DateTime now = DateTime.UtcNow;
                if (!customer.CollectionStatus.IsEnabled)
                {
                    // Update loan options add freeze interest
                    foreach (Loan loan in customer.Loans.Where(l => l.Status != LoanStatus.PaidOff && l.Balance >= CurrentValues.Instance.MinDectForDefault))
                    {
                        LoanOptions options  = this.loanOptionsRepository.GetByLoanId(loan.Id) ?? LoanOptions.GetDefault(loan.Id);
                        options.AutoLateFees = false;
                        options.AutoPayment  = false;
                        this.loanOptionsRepository.SaveOrUpdate(options);
                        NL_SaveLoanOptions(customer, options);

                        loan.InterestFreeze.Add(new LoanInterestFreeze {
                            Loan             = loan,
                            StartDate        = now.Date,
                            EndDate          = (DateTime?)null,
                            InterestRate     = 0,
                            ActivationDate   = now,
                            DeactivationDate = null
                        });

                        this.loanRepository.SaveOrUpdate(loan);

                        addFreeseLoans.Add(loan.Id);
                    }

                    //collection and external status is ok
                }
                else if (!prevStatus.IsEnabled && customer.CollectionStatus.IsEnabled && customer.ExternalCollectionStatus == null)
                {
                    // Update loan options add remove freeze interest
                    foreach (Loan loan in customer.Loans.Where(l => l.Status != LoanStatus.PaidOff && l.Balance >= CurrentValues.Instance.MinDectForDefault))
                    {
                        LoanOptions options  = this.loanOptionsRepository.GetByLoanId(loan.Id) ?? LoanOptions.GetDefault(loan.Id);
                        options.AutoLateFees = true;
                        options.AutoPayment  = true;
                        this.loanOptionsRepository.SaveOrUpdate(options);
                        NL_SaveLoanOptions(customer, options);

                        if (loan.InterestFreeze.Any(f => f.EndDate == null && f.DeactivationDate == null))
                        {
                            foreach (var interestFreeze in loan.InterestFreeze.Where(f => f.EndDate == null && f.DeactivationDate == null))
                            {
                                interestFreeze.DeactivationDate = now;
                                DeactivateLoanInterestFreeze(interestFreeze, customerId, loan.Id);
                            }
                            this.loanRepository.SaveOrUpdate(loan);
                        }
                    }
                }

                this.session.Flush();

                DateTime applyForJudgmentDate;
                bool hasApplyForJudgmentDate = DateTime.TryParseExact(collectionStatus.ApplyForJudgmentDate, "dd/MM/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal, out applyForJudgmentDate);

                var newEntry = new CustomerStatusHistory {
                    Username             = User.Identity.Name,
                    Timestamp            = DateTime.UtcNow,
                    CustomerId           = customerId,
                    PreviousStatus       = prevStatus,
                    NewStatus            = customer.CollectionStatus,
                    Description          = collectionStatus.CollectionDescription,
                    Amount               = collectionStatus.Amount,
                    ApplyForJudgmentDate = hasApplyForJudgmentDate ? applyForJudgmentDate : (DateTime?)null,
                    Feedback             = collectionStatus.Feedback,
                    Type = collectionStatus.Type
                };

                this.customerStatusHistoryRepository.SaveOrUpdate(newEntry);
            }).Execute();

            log.Debug("AaddFreeseLoans {0}", addFreeseLoans);

            foreach (int loanID in addFreeseLoans)
            {
                var loan = this.loanRepository.Get(loanID);
                SaveLoanInterestFreeze(loan.InterestFreeze.Last(), customerId, loan.Id);
            }

            if (customer.CollectionStatus.Name == "Disabled" && (collectionStatus.Unsubscribe || collectionStatus.ChangeEmail))
            {
                this.serviceClient.Instance.UserDisable(this.context.UserId, customer.Id, customer.Name, collectionStatus.Unsubscribe, collectionStatus.ChangeEmail);
            }

            this.serviceClient.Instance.SalesForceAddUpdateLeadAccount(this.context.UserId, customer.Name, customerId, false, false);
            return(Json(new { }));
        }