Beispiel #1
0
        private void generateInterest(bool forAll)
        {
            bool   errorsDetected = false;
            string errorMessages  = "";

            cmdGenerateInterest.Enabled    = false;
            cmdGenerateAllInterest.Enabled = false;

            Account account130 = manager.My_db.Accounts.FirstOrDefault(x => x.number == "130" && x.FK_Accounts_Funds == manager.Selected);

            Account account902 = manager.My_db.Accounts.FirstOrDefault(x => x.number == "902" && x.FK_Accounts_Funds == manager.Selected);

            if (account130 != null && account902 != null)
            {
                try
                {
                    if (manager.My_db.ClosedPeriods.FirstOrDefault(x => x.year == dtpDate.Value.Year && x.fund_id == manager.Selected) == null)
                    {
                        DateTime _date = Convert.ToDateTime(dtpDate.Text);

                        List <Disbursement> _delayedInterestToAccrueList = new List <Disbursement>();

                        if (!forAll)
                        {
                            foreach (ListViewItem _item in lvBookings.SelectedItems)
                            {
                                int bookingId = 0;

                                if (int.TryParse(_item.Text, out bookingId))
                                {
                                    Disbursement toAcrue = manager.My_db.Disbursements.FirstOrDefault(x => x.Id == bookingId);

                                    if (toAcrue != null)
                                    {
                                        _delayedInterestToAccrueList.Add(toAcrue);
                                    }

                                    if (toAcrue.collection_date <= toAcrue.date)
                                    {
                                        errorsDetected = true;
                                        errorMessages += "\rNumber " + toAcrue.number + ": collection <= stating date.";
                                    }

                                    if (toAcrue.delay_interest == 0)
                                    {
                                        errorsDetected = true;
                                        errorMessages += "\rNumber " + toAcrue.number + ": delay interest = 0.";
                                    }
                                }
                            }
                        }
                        else
                        {
                            foreach (ListViewItem _item in lvBookings.Items)
                            {
                                int bookingId = 0;

                                if (int.TryParse(_item.Text, out bookingId))
                                {
                                    Disbursement toAcrue = manager.My_db.Disbursements.FirstOrDefault(x => x.Id == bookingId);

                                    if (toAcrue != null)
                                    {
                                        _delayedInterestToAccrueList.Add(toAcrue);
                                    }

                                    if (toAcrue.collection_date <= toAcrue.date)
                                    {
                                        errorsDetected = true;
                                        errorMessages += "\rNumber " + toAcrue.number + ": collection <= starting date.";
                                    }

                                    if (toAcrue.delay_interest == 0)
                                    {
                                        errorsDetected = true;
                                        errorMessages += "\rNumber " + toAcrue.number + ": delay interest = 0.";
                                    }
                                }
                            }
                        }

                        if (errorsDetected)
                        {
                            if (MessageBox.Show("Do you want continue?\r\rThese bookings will be ignored in interest generation." + errorMessages, "Warning", MessageBoxButtons.OKCancel) != DialogResult.OK)
                            {
                                cmdGenerateInterest.Enabled    = true;
                                cmdGenerateAllInterest.Enabled = true;
                                return;
                            }
                        }

                        if (_delayedInterestToAccrueList.Count > 0)
                        {
                            BookingGeneratedInterest _generatedInterest = new BookingGeneratedInterest();
                            _generatedInterest.GeneratedDate = Convert.ToDateTime(dtpDate.Text);

                            bool interestCreated = false;

                            decimal _totalInterest = 0;

                            bool someDataMissed = false;

                            foreach (Disbursement _delayedInterestToAccrue in _delayedInterestToAccrueList)
                            {
                                Currency   currency   = manager.My_db.Currencies.FirstOrDefault(x => x.Id == _delayedInterestToAccrue.currency_id && x.FK_Currencies_Funds == manager.Selected);
                                Subaccount subacct130 = manager.My_db.Subaccounts.FirstOrDefault(x => x.FK_Subaccounts_Accounts == account130.Id && x.name == "INV " + currency.symbol);

                                if (currency != null && subacct130 != null)
                                {
                                    BookingGeneratedInterestDetail interestDetail = manager.My_db.BookingGeneratedInterestDetails.FirstOrDefault(x => x.disbursement_id == _delayedInterestToAccrue.Id && x.generated_interest_date.Year == _date.Year && x.generated_interest_date.Month == _date.Month);

                                    if (interestDetail == null)
                                    {
                                        DateTime?fromDate = getLastGeneratedInterestDateFor(_delayedInterestToAccrue.Id);

                                        if (fromDate == null)
                                        {
                                            fromDate = _delayedInterestToAccrue.date;
                                        }

                                        bool canContinueGeneratingInterest = true;

                                        decimal _interest = 0;

                                        int totalFinancingDays = (_delayedInterestToAccrue.collection_date.Date - _delayedInterestToAccrue.date.Date).Days;

                                        DateTime toDate = dtpDate.Value <= _delayedInterestToAccrue.collection_date ? dtpDate.Value : _delayedInterestToAccrue.collection_date;

                                        int financingDays = (toDate.Date - fromDate.Value.Date).Days;

                                        if (totalFinancingDays > 0 && financingDays > 0)
                                        {
                                            decimal delayInterestPerDay = _delayedInterestToAccrue.delay_interest.Value / totalFinancingDays;
                                            _interest = Math.Round(financingDays * delayInterestPerDay, 2);
                                        }

                                        canContinueGeneratingInterest = toDate < _delayedInterestToAccrue.collection_date;

                                        if (_interest > 0)
                                        {
                                            if (!interestCreated)
                                            {
                                                manager.My_db.BookingGeneratedInterests.Add(_generatedInterest);
                                                interestCreated = true;
                                            }

                                            if (!canContinueGeneratingInterest)
                                            {
                                                Disbursement disbBooking = manager.My_db.Disbursements.FirstOrDefault(x => x.Id == _delayedInterestToAccrue.Id);

                                                if (disbBooking != null)
                                                {
                                                    disbBooking.can_generate_interest = false;
                                                }
                                            }

                                            _totalInterest += _interest;

                                            BookingGeneratedInterestDetail _detail = new BookingGeneratedInterestDetail();

                                            _detail.BookingGeneratedInterest = _generatedInterest;
                                            _detail.generated_interest       = Math.Round(_interest, 2);
                                            _detail.generated_interest_date  = toDate;
                                            _detail.disbursement_id          = _delayedInterestToAccrue.Id;

                                            manager.My_db.BookingGeneratedInterestDetails.Add(_detail);

                                            AccountingMovement _accountingMovement = new AccountingMovement();

                                            _accountingMovement.FK_AccountingMovements_Funds = manager.Selected;
                                            _accountingMovement.description = "";
                                            _accountingMovement.date        = dtpDate.Value;
                                            _accountingMovement.reference   = KeyDefinitions.NextAccountMovementReference(dtpDate.Value.Year);
                                            _accountingMovement.FK_AccountingMovements_Currencies = _delayedInterestToAccrue.currency_id;
                                            _accountingMovement.original_reference = _delayedInterestToAccrue.contract;
                                            _accountingMovement.contract           = _delayedInterestToAccrue.contract;

                                            manager.My_db.AccountingMovements.Add(_accountingMovement);

                                            _detail.AccountingMovement = _accountingMovement;

                                            Movements_Accounts _maccount130 = new Movements_Accounts();

                                            _maccount130.AccountingMovement             = _accountingMovement;
                                            _maccount130.FK_Movements_Accounts_Funds    = manager.Selected;
                                            _maccount130.FK_Movements_Accounts_Accounts = account130.Id;
                                            if (subacct130 != null)
                                            {
                                                _maccount130.FK_Movements_Accounts_Subaccounts = subacct130.Id;
                                            }
                                            _maccount130.subaccount      = _delayedInterestToAccrue.client_id;
                                            _maccount130.subaccount_type = 1;
                                            _maccount130.debit           = Math.Round(_interest, 2);
                                            _maccount130.credit          = 0;

                                            manager.My_db.Movements_Accounts.Add(_maccount130);

                                            Movements_Accounts _maccount902 = new Movements_Accounts();

                                            _maccount902.AccountingMovement             = _accountingMovement;
                                            _maccount902.FK_Movements_Accounts_Funds    = manager.Selected;
                                            _maccount902.FK_Movements_Accounts_Accounts = account902.Id;

                                            _maccount902.subaccount      = _delayedInterestToAccrue.client_id;
                                            _maccount902.subaccount_type = 1;
                                            _maccount902.debit           = 0;
                                            _maccount902.credit          = Math.Round(_interest, 2);

                                            manager.My_db.Movements_Accounts.Add(_maccount902);
                                        }
                                    }
                                    else
                                    {
                                        Console.WriteLine("Attempt to duplicate booking interest generation.");
                                    }
                                }
                                else
                                {
                                    someDataMissed = true;
                                }
                            }

                            manager.My_db.SaveChanges();

                            if (someDataMissed)
                            {
                                ErrorMessage.showErrorMessage(new Exception("Some interests has not been generated dued missing related data. \rPlease, contact with your system administrator in order to find and fix missed data."));
                            }

                            if (interestCreated)
                            {
                                BookingGeneratedInterestForm disbursement_generated_interest_form = new BookingGeneratedInterestForm();
                                disbursement_generated_interest_form.generated_interest_id = _generatedInterest.Id;
                                disbursement_generated_interest_form.Show();
                            }
                            else
                            {
                                MessageBox.Show("No actions performed.");
                            }
                        }
                        else
                        {
                            MessageBox.Show("No disbursement found for interest generation.");
                        }
                    }
                    else
                    {
                        ErrorMessage.showErrorMessage(new Exception("No movement allowed in closed period."));
                    }
                }
                catch (Exception _ex)
                {
                    ErrorMessage.showErrorMessage(_ex);
                }

                cmdGenerateInterest.Enabled    = true;
                cmdGenerateAllInterest.Enabled = true;
            }
            else
            {
                ErrorMessage.showErrorMessage(new Exception("No account 130 or 902 were found."));
            }
        }
Beispiel #2
0
        private void generate(bool forAll)
        {
            try
            {
                decimal monthly_rate = 0;

                if (decimal.TryParse(txtMonthlyRate.Text.Trim(), out monthly_rate) && monthly_rate > 0)
                {
                    if ((forAll && dataGridView1.Rows.Count > 0) || (!forAll && dataGridView1.SelectedRows.Count > 0))
                    {
                        Account account130 = manager.My_db.Accounts.FirstOrDefault(x => x.number == "130" && x.FK_Accounts_Funds == manager.Selected);
                        Account account902 = manager.My_db.Accounts.FirstOrDefault(x => x.number == "902" && x.FK_Accounts_Funds == manager.Selected);

                        if (account130 != null && account902 != null)
                        {
                            List <DisbursementOverdueDetail> details = new List <DisbursementOverdueDetail>();

                            if (forAll)
                            {
                                foreach (DataGridViewRow row in dataGridView1.Rows)
                                {
                                    details.AddRange(readFromRow(row, monthly_rate));
                                }
                            }
                            else
                            {
                                foreach (DataGridViewRow row in dataGridView1.SelectedRows)
                                {
                                    details.AddRange(readFromRow(row, monthly_rate));
                                }
                            }

                            if (details.Count > 0)
                            {
                                DisbursementOverdue overdue = new DisbursementOverdue();
                                overdue.OverdueDate = dtpDate.Value.Date;

                                manager.My_db.DisbursementOverdues.Add(overdue);

                                foreach (DisbursementOverdueDetail detail in details)
                                {
                                    detail.DisbursementOverdue = overdue;

                                    Disbursement disbursement = manager.My_db.Disbursements.FirstOrDefault(x => x.Id == detail.disbursement_id);

                                    if (disbursement != null)
                                    {
                                        Currency   currency   = manager.My_db.Currencies.FirstOrDefault(x => x.Id == disbursement.currency_id && x.FK_Currencies_Funds == manager.Selected);
                                        Subaccount subacct130 = manager.My_db.Subaccounts.FirstOrDefault(x => x.FK_Subaccounts_Accounts == account130.Id && x.name == "INV " + currency.symbol);

                                        AccountingMovement accountingMovement = new AccountingMovement();
                                        accountingMovement.FK_AccountingMovements_Funds = manager.Selected;
                                        accountingMovement.description = "Overdue";
                                        accountingMovement.date        = dtpDate.Value.Date;
                                        accountingMovement.reference   = KeyDefinitions.NextAccountMovementReference(dtpDate.Value.Year);
                                        accountingMovement.FK_AccountingMovements_Currencies = disbursement.currency_id;
                                        accountingMovement.original_reference = "";
                                        accountingMovement.contract           = disbursement.Investment.contract;

                                        manager.My_db.AccountingMovements.Add(accountingMovement);

                                        detail.AccountingMovement = accountingMovement;

                                        Movements_Accounts _maccount130 = new Movements_Accounts();

                                        _maccount130.AccountingMovement             = accountingMovement;
                                        _maccount130.FK_Movements_Accounts_Funds    = manager.Selected;
                                        _maccount130.FK_Movements_Accounts_Accounts = account130.Id;
                                        if (subacct130 != null)
                                        {
                                            _maccount130.FK_Movements_Accounts_Subaccounts = subacct130.Id;
                                        }
                                        _maccount130.subaccount      = disbursement.client_id;
                                        _maccount130.subaccount_type = 1;
                                        _maccount130.debit           = Math.Round(detail.generated_overdue, 2);
                                        _maccount130.credit          = 0;

                                        manager.My_db.Movements_Accounts.Add(_maccount130);

                                        Movements_Accounts _maccount902 = new Movements_Accounts();

                                        _maccount902.AccountingMovement             = accountingMovement;
                                        _maccount902.FK_Movements_Accounts_Funds    = manager.Selected;
                                        _maccount902.FK_Movements_Accounts_Accounts = account902.Id;

                                        _maccount902.subaccount      = disbursement.client_id;
                                        _maccount902.subaccount_type = 1;
                                        _maccount902.debit           = 0;
                                        _maccount902.credit          = Math.Round(detail.generated_overdue, 2);

                                        manager.My_db.Movements_Accounts.Add(_maccount902);

                                        detail.AccountingMovement = accountingMovement;

                                        manager.My_db.DisbursementOverdueDetails.Add(detail);
                                    }
                                    else
                                    {
                                        //TODO: Originary disbursement doesn't exists.
                                    }
                                }

                                manager.My_db.SaveChanges();

                                OverduesReportForm disbursement_overdues_form = new OverduesReportForm();
                                disbursement_overdues_form.generated_overdue_id = overdue.Id;
                                disbursement_overdues_form.Show();
                            }
                            else
                            {
                                //TODO: error. No hay details que generar
                            }
                        }
                        else
                        {
                            //TODO: error some account is missing
                        }
                    }
                    else
                    {
                        MessageBox.Show("No selected data.");
                    }
                }
                else
                {
                    MessageBox.Show("Monthly rate must be greather than zero.");
                }
            }
            catch (Exception _ex)
            {
                Console.WriteLine("Error in DisbursementToBeOverdueForm.generate: " + _ex.Message);
            }
        }
        private void cmdActivate_Click(object sender, EventArgs e)
        {
            try
            {
                if (manager.My_db.ClosedPeriods.FirstOrDefault(x => x.year == dtpActivationDate.Value.Year && x.fund_id == manager.Selected) == null)
                {
                    if (cbBond.SelectedItem != null)
                    {
                        int bondId = int.Parse(cbBond.SelectedValue.ToString());

                        BondsTFAM bond = manager.My_db.BondsTFAMs.FirstOrDefault(x => x.Id == bondId);

                        if (bond != null)
                        {
                            Account account540 = manager.My_db.Accounts.FirstOrDefault(x => x.number == "540" && x.FK_Accounts_Funds == manager.Selected);

                            if (account540 != null)
                            {
                                AccountingMovement _accountingMovement = new AccountingMovement();

                                _accountingMovement.FK_AccountingMovements_Funds = manager.Selected;
                                _accountingMovement.description = bond.number + " Activation";
                                _accountingMovement.date        = dtpActivationDate.Value;
                                _accountingMovement.reference   = KeyDefinitions.NextAccountMovementReference(dtpActivationDate.Value.Year);
                                _accountingMovement.FK_AccountingMovements_Currencies = bond.currency_id;
                                _accountingMovement.original_reference = "";
                                _accountingMovement.contract           = "";

                                manager.My_db.AccountingMovements.Add(_accountingMovement);

                                bond.AccountingMovement    = _accountingMovement;
                                bond.active                = 1;
                                bond.can_generate_interest = 1;

                                Subaccount subacct = manager.My_db.Subaccounts.FirstOrDefault(x => x.FK_Subaccounts_Accounts == account540.Id && x.name == "Principal Bonds");

                                Movements_Accounts _maccount = new Movements_Accounts();

                                _maccount.AccountingMovement             = _accountingMovement;
                                _maccount.FK_Movements_Accounts_Funds    = manager.Selected;
                                _maccount.FK_Movements_Accounts_Accounts = account540.Id;
                                if (subacct != null)
                                {
                                    _maccount.FK_Movements_Accounts_Subaccounts = subacct.Id;
                                }
                                _maccount.subaccount      = bond.Id;
                                _maccount.subaccount_type = 9;
                                _maccount.debit           = 0;
                                _maccount.credit          = Math.Round(bond.amount, 2);

                                manager.My_db.Movements_Accounts.Add(_maccount);

                                GeneralLedgerForm gledger = new GeneralLedgerForm();
                                gledger.StartPosition          = FormStartPosition.CenterScreen;
                                gledger.FromExternalOperation  = true;
                                gledger.ExternalAccountMovemet = _accountingMovement;
                                gledger.ExternalDebit          = bond.amount;
                                gledger.ShowDialog();

                                if (!gledger.OperationCompleted)
                                {
                                    throw new Exception("Ledger window has been closed. The operation has been rolled back.");
                                }
                            }
                            else
                            {
                                ErrorMessage.showErrorMessage(new Exception("Account 540 not found."));
                            }
                        }
                    }

                    this.bondsTFAMTableAdapter.FillByActivation(this.fundsDBDataSet.BondsTFAM, manager.Selected);
                }
                else
                {
                    ErrorMessage.showErrorMessage(new Exception("No movement allowed in closed period."));
                }
            }
            catch (Exception _ex)
            {
                Console.WriteLine("Error in BondsTFAMActivation.cmdActivate_Click: " + _ex.Message);
                ErrorMessage.showErrorMessage(_ex, false);
            }
        }
Beispiel #4
0
        private void cmdClose_Click(object sender, EventArgs e)
        {
            try
            {
                if (MessageBox.Show("Do you want close selected period?", "Warning", MessageBoxButtons.OKCancel) == DialogResult.OK)
                {
                    AccountingMovement _accountingMovement = new AccountingMovement();

                    Account account999 = manager.My_db.Accounts.FirstOrDefault(x => x.number == "999" && x.FK_Accounts_Funds == manager.Selected);

                    if (account999 != null)
                    {
                        _accountingMovement.FK_AccountingMovements_Funds = manager.Selected;
                        _accountingMovement.description = "Period Closure";
                        _accountingMovement.date        = new DateTime(selectedYear, 12, 31, 23, 59, 59);
                        _accountingMovement.reference   = _accountingMovement.contract = KeyDefinitions.NextAccountMovementReference(selectedYear);
                        _accountingMovement.FK_AccountingMovements_Currencies = 1;
                        _accountingMovement.original_reference = "";

                        manager.My_db.AccountingMovements.Add(_accountingMovement);

                        foreach (KeyValuePair <string, decimal> item in accountBalances)
                        {
                            string[] strKeys = item.Key.Split('_');

                            int accountId    = int.Parse(strKeys[0]);
                            int?subaccountId = null;
                            int?detailType   = null;
                            int?detailId     = null;

                            if (strKeys[1] != "x")
                            {
                                subaccountId = int.Parse(strKeys[1]);
                            }

                            if (strKeys[2] != "x")
                            {
                                detailType = int.Parse(strKeys[2]);
                            }

                            if (strKeys[3] != "x")
                            {
                                detailId = int.Parse(strKeys[3]);
                            }

                            Account acct = manager.My_db.Accounts.FirstOrDefault(x => x.Id == accountId);

                            Movements_Accounts movement = new Movements_Accounts();

                            movement.AccountingMovement                = _accountingMovement;
                            movement.FK_Movements_Accounts_Funds       = manager.Selected;
                            movement.FK_Movements_Accounts_Accounts    = accountId;
                            movement.FK_Movements_Accounts_Subaccounts = subaccountId;
                            movement.subaccount_type = detailType;
                            movement.subaccount      = detailId;
                            movement.debit           = acct.type == 3 ? Math.Round(item.Value, 2) : 0;
                            movement.credit          = acct.type == 4 ? Math.Round(item.Value, 2) : 0;

                            manager.My_db.Movements_Accounts.Add(movement);
                        }

                        Movements_Accounts _maccount999 = new Movements_Accounts();

                        _maccount999.AccountingMovement             = _accountingMovement;
                        _maccount999.FK_Movements_Accounts_Funds    = manager.Selected;
                        _maccount999.FK_Movements_Accounts_Accounts = account999.Id;
                        _maccount999.debit  = Math.Round(debitAdjustment, 2);
                        _maccount999.credit = Math.Round(creditAdjustment, 2);

                        manager.My_db.Movements_Accounts.Add(_maccount999);

                        txtYear.Text             = "";
                        lblCredit.Text           = "";
                        lblDebit.Text            = "";
                        lblCreditAdjustment.Text = "";
                        lblDebitAdjustment.Text  = "";
                        cmdClose.Enabled         = false;

                        ClosedPeriod closure = new ClosedPeriod();
                        closure.year               = selectedYear;
                        closure.closing_date       = DateTime.Now;
                        closure.AccountingMovement = _accountingMovement;
                        closure.fund_id            = manager.Selected;

                        manager.My_db.ClosedPeriods.Add(closure);

                        manager.My_db.SaveChanges();

                        MessageBox.Show("Period has been closed.");
                    }
                    else
                    {
                        ErrorMessage.showErrorMessage(new Exception("Missing account 999."));
                    }
                }
            }
            catch (Exception _ex)
            {
                ErrorMessage.showErrorMessage(_ex);
            }
        }
        private void cmdRepay_Click(object sender, EventArgs e)
        {
            try
            {
                if (manager.My_db.ClosedPeriods.FirstOrDefault(x => x.year == dtpDate.Value.Year && x.fund_id == manager.Selected) == null)
                {
                    List <string>  rowIds               = new List <string>();
                    List <string>  references           = new List <string>();
                    List <decimal> principals           = new List <decimal>();
                    List <decimal> interestAccrueds     = new List <decimal>();
                    List <decimal> principalCollections = new List <decimal>();
                    List <decimal> interestCollections  = new List <decimal>();

                    String errors = "";

                    foreach (DataGridViewRow row in dataGridView1.Rows)
                    {
                        string  rowId                     = row.Cells[idIndex].Value.ToString();
                        string  reference                 = row.Cells[referenceIndex].Value.ToString();
                        decimal principal                 = decimal.Parse(row.Cells[principalIndex].Value.ToString());
                        decimal interestAccrued           = decimal.Parse(row.Cells[interestAccruedIndex].Value.ToString());
                        string  principalToBeCollectedStr = row.Cells[principalCollectionIndex].Value != null ? row.Cells[principalCollectionIndex].Value.ToString() : "0";
                        string  interestToBeCollectedStr  = row.Cells[interestCollectionIndex].Value != null ? row.Cells[interestCollectionIndex].Value.ToString() : "0";

                        decimal principalToBeCollected = 0;
                        decimal interestToBeCollected  = 0;

                        if (principalToBeCollectedStr != "0" || interestToBeCollectedStr != "0")
                        {
                            if (decimal.TryParse(principalToBeCollectedStr, out principalToBeCollected) &&
                                decimal.TryParse(interestToBeCollectedStr, out interestToBeCollected))
                            {
                                if (principal - principalToBeCollected >= 0 && interestAccrued - interestToBeCollected >= 0)
                                {
                                    rowIds.Add(rowId);
                                    references.Add(reference);
                                    principals.Add(principal);
                                    interestAccrueds.Add(interestAccrued);
                                    principalCollections.Add(principalToBeCollected);
                                    interestCollections.Add(interestToBeCollected);
                                }
                                else
                                {
                                    errors += "\rLoan " + reference + " has too much repayment value.";
                                }
                            }
                            else
                            {
                                errors += "\r  Loan " + reference + " has wrong repayment value.";
                            }
                        }
                    }

                    if (errors != "")
                    {
                        string msg = "Please, fix these errors:" + errors;

                        ErrorMessage.showErrorMessage(new Exception(msg));
                        return;
                    }
                    else
                    {
                        string msg = "";

                        if (rowIds.Count > 0)
                        {
                            Loan_Repayments loanRepayment = new Loan_Repayments();
                            loanRepayment.repayment_date = dtpDate.Value;

                            Account account470 = manager.My_db.Accounts.FirstOrDefault(x => x.number == "470" && x.FK_Accounts_Funds == manager.Selected);

                            if (account470 != null)
                            {
                                Subaccount subAcct01 = manager.My_db.Subaccounts.FirstOrDefault(x => x.FK_Subaccounts_Accounts == account470.Id && x.number == "01");
                                Subaccount subAcct02 = manager.My_db.Subaccounts.FirstOrDefault(x => x.FK_Subaccounts_Accounts == account470.Id && x.number == "02");

                                if (subAcct01 != null && subAcct02 != null)
                                {
                                    manager.My_db.Loan_Repayments.Add(loanRepayment);

                                    AccountingMovement accountingMovement = new AccountingMovement();

                                    accountingMovement.FK_AccountingMovements_Funds = manager.Selected;
                                    accountingMovement.description        = "Loan Repayment";
                                    accountingMovement.date               = dtpDate.Value;
                                    accountingMovement.reference          = KeyDefinitions.NextAccountMovementReference(dtpDate.Value.Year);
                                    accountingMovement.original_reference = cbContract.SelectedIndex > 0 ? cbContract.Text : "";
                                    accountingMovement.contract           = cbContract.Text;
                                    accountingMovement.FK_AccountingMovements_Currencies = 0;

                                    bool    showGL    = false;
                                    decimal totalPaid = 0;

                                    for (int i = 0; i < rowIds.Count; i++)
                                    {
                                        string  rowId                  = rowIds[i];
                                        decimal principal              = principals[i];
                                        decimal interestAccrued        = interestAccrueds[i];
                                        decimal principalToBeCollected = principalCollections[i];
                                        decimal interestToBeCollected  = interestCollections[i];

                                        int loandId = int.Parse(rowId);

                                        Loan loan = manager.My_db.Loans.FirstOrDefault(x => x.Id == loandId);

                                        if (loan != null)
                                        {
                                            Currency currency = manager.My_db.Currencies.FirstOrDefault(x => x.Id == loan.currency_id && x.FK_Currencies_Funds == manager.Selected);

                                            if (currency != null)
                                            {
                                                if (accountingMovement.FK_AccountingMovements_Currencies == 0)
                                                {
                                                    accountingMovement.FK_AccountingMovements_Currencies = currency.Id;

                                                    manager.My_db.AccountingMovements.Add(accountingMovement);

                                                    loanRepayment.AccountingMovement = accountingMovement;
                                                }

                                                LoanRepaymentDetail repaymentDetail = new LoanRepaymentDetail();

                                                repaymentDetail.Loan_Repayments  = loanRepayment;
                                                repaymentDetail.loan_id          = loandId;
                                                repaymentDetail.principal_repaid = Math.Round(principalToBeCollected, 2);
                                                repaymentDetail.interest_repaid  = Math.Round(interestToBeCollected, 2);

                                                if (principal - principalToBeCollected <= 0)
                                                {
                                                    loan.can_generate_interest = 0;
                                                }

                                                if (loan.can_generate_interest == 0 && principal - principalToBeCollected <= 0 && interestAccrued - interestToBeCollected <= 0)
                                                {
                                                    loan.can_generate_interest = 0;
                                                    loan.paid = 1;
                                                }

                                                manager.My_db.LoanRepaymentDetails.Add(repaymentDetail);

                                                if (principalToBeCollected > 0)
                                                {
                                                    Movements_Accounts _maccount01 = new Movements_Accounts();

                                                    _maccount01.AccountingMovement             = accountingMovement;
                                                    _maccount01.FK_Movements_Accounts_Funds    = manager.Selected;
                                                    _maccount01.FK_Movements_Accounts_Accounts = account470.Id;
                                                    if (subAcct01 != null)
                                                    {
                                                        _maccount01.FK_Movements_Accounts_Subaccounts = subAcct01.Id;
                                                    }
                                                    _maccount01.subaccount      = loan.lender_id;
                                                    _maccount01.subaccount_type = 4;
                                                    _maccount01.debit           = Math.Round(principalToBeCollected, 2);
                                                    _maccount01.credit          = 0;

                                                    manager.My_db.Movements_Accounts.Add(_maccount01);

                                                    repaymentDetail.Movements_Accounts = _maccount01;
                                                }

                                                if (interestToBeCollected > 0)
                                                {
                                                    Movements_Accounts _maccount02 = new Movements_Accounts();

                                                    _maccount02.AccountingMovement             = accountingMovement;
                                                    _maccount02.FK_Movements_Accounts_Funds    = manager.Selected;
                                                    _maccount02.FK_Movements_Accounts_Accounts = account470.Id;
                                                    if (subAcct02 != null)
                                                    {
                                                        _maccount02.FK_Movements_Accounts_Subaccounts = subAcct02.Id;
                                                    }
                                                    _maccount02.subaccount      = loan.lender_id;
                                                    _maccount02.subaccount_type = 4;
                                                    _maccount02.debit           = Math.Round(interestToBeCollected, 2);
                                                    _maccount02.credit          = 0;

                                                    manager.My_db.Movements_Accounts.Add(_maccount02);

                                                    repaymentDetail.Movements_Accounts1 = _maccount02;
                                                }

                                                totalPaid += principalToBeCollected + interestToBeCollected;

                                                showGL = true;
                                            }
                                            else
                                            {
                                                msg += "\rCurrency is missing. No repayment has been generated for loan with Id=\"" + loandId + "\".";
                                            }
                                        }
                                        else
                                        {
                                            msg += "\rLoan with Id=\"" + loandId.ToString() + "\" not found.";
                                        }
                                    }

                                    if (msg != "")
                                    {
                                        MessageBox.Show("Warning:\r\r" + msg);
                                    }

                                    if (showGL)
                                    {
                                        GeneralLedgerForm gledger = new GeneralLedgerForm();
                                        gledger.StartPosition          = FormStartPosition.CenterScreen;
                                        gledger.FromExternalOperation  = true;
                                        gledger.ExternalAccountMovemet = accountingMovement;
                                        gledger.ExternalCredit         = totalPaid;
                                        gledger.ShowDialog();

                                        if (!gledger.OperationCompleted)
                                        {
                                            throw new Exception("Ledger window has been closed. The operation has been rolled back.");
                                        }
                                    }
                                }
                                else
                                {
                                    ErrorMessage.showErrorMessage(new Exception("Sub Account 01 or 02 are missing."));
                                }
                            }
                            else
                            {
                                ErrorMessage.showErrorMessage(new Exception("Account 470 is missing."));
                            }
                        }
                        else
                        {
                            ErrorMessage.showErrorMessage(new Exception("No loan found."));
                        }
                    }

                    cbContract_SelectedIndexChanged(null, null);
                }
                else
                {
                    ErrorMessage.showErrorMessage(new Exception("No movement allowed in closed period."));
                }
            }
            catch (Exception _ex)
            {
                ErrorMessage.showErrorMessage(_ex, false);
            }
        }