public JsonResult Index(int id)
        {
            var customer = this.customerRepository.Get(id);

            var collectionStatus = customer.CollectionStatus;

            var loans          = customer.Loans.Select(l => LoanModel.FromLoan(l, new LoanRepaymentScheduleCalculator(l, null, CurrentValues.Instance.AmountToChargeFrom))).ToList();
            var loansNonClosed = loans.Where(l => l.DateClosed == null).ToList();

            var data = new CollectionStatusModel {
                CurrentStatus         = collectionStatus.Id,
                CollectionDescription = customer.CollectionDescription,
                Items = loansNonClosed.Select(loan => new CollectionStatusItem {
                    LoanId        = loan.Id,
                    LoanRefNumber = loan.RefNumber
                }).ToList()
            };

            return(Json(data, JsonRequestBehavior.AllowGet));
        }
        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 { }));
        }