Пример #1
0
        private void addMovement(Movement toSave, AccountingMovement acctMov)
        {
            int?nullReference = null;

            //subaccount_type  1 -> Client, 2 -> Banking Account, 3 -> Employee, 4 -> Lender, 5 -> OtherDetail, 6 -> Shareholder
            Movements_Accounts movementAccountToSave = new Movements_Accounts();

            if (toSave.Id != 0)
            {
                movementAccountToSave = manager.My_db.Movements_Accounts.FirstOrDefault(x => x.Id == toSave.Id);

                if (movementAccountToSave == null)
                {
                    throw new Exception("Attempt to edit non existing movement account.");
                }
            }

            movementAccountToSave.AccountingMovement             = acctMov;
            movementAccountToSave.FK_Movements_Accounts_Funds    = manager.Selected;
            movementAccountToSave.FK_Movements_Accounts_Accounts = toSave.Account;

            if (toSave.Subaccount != -1)
            {
                movementAccountToSave.FK_Movements_Accounts_Subaccounts = toSave.Subaccount;
            }
            else
            {
                movementAccountToSave.FK_Movements_Accounts_Subaccounts = nullReference;
            }

            /*WARNING en la tabla Movements_Accounts los campos subaccount y subaccount_type se refieren a detail y detail_type respectivamente*/
            movementAccountToSave.subaccount_type = toSave.Detail_type;

            if (toSave.Detail != -1)
            {
                movementAccountToSave.subaccount = toSave.Detail;
            }
            else
            {
                movementAccountToSave.subaccount = nullReference;
            }

            movementAccountToSave.debit  = Math.Round(toSave.Debit, 2);
            movementAccountToSave.credit = Math.Round(toSave.Credit, 2);

            Account    _account    = manager.My_db.Accounts.FirstOrDefault(x => x.Id == toSave.Account);
            Subaccount _subAccount = manager.My_db.Subaccounts.FirstOrDefault(x => x.Id == toSave.Subaccount);

            if (toSave.Id == 0)
            {
                manager.My_db.Movements_Accounts.Add(movementAccountToSave);
            }
        }
Пример #2
0
        private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            String reference = dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString();

            AccountingMovement accMov = manager.My_db.AccountingMovements.FirstOrDefault(x => x.reference == reference && x.FK_AccountingMovements_Funds == manager.Selected);

            if (accMov != null)
            {
                GeneralLedgerForm ledger = new GeneralLedgerForm();
                ledger.FormInEditAccountingMovement = true;
                ledger.IdOfAccountingMovementToEdit = accMov.Id;
                ledger.StartPosition = FormStartPosition.CenterScreen;
                ledger.ShowDialog();

                loadData();
            }
        }
Пример #3
0
        private AccountingMovement generateAccountingMovement(Loan loan)
        {
            AccountingMovement _accountingMovement = new AccountingMovement();

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

            if (account470 != null)
            {
                Currency   currency   = manager.My_db.Currencies.FirstOrDefault(x => x.Id == loan.currency_id && x.FK_Currencies_Funds == manager.Selected);
                Subaccount subacct470 = manager.My_db.Subaccounts.FirstOrDefault(x => x.FK_Subaccounts_Accounts == account470.Id && x.name == "Principal Loan");

                if (currency != null && subacct470 != null)
                {
                    _accountingMovement.FK_AccountingMovements_Funds = manager.Selected;
                    _accountingMovement.description = "Loan";
                    _accountingMovement.date        = loan.start;
                    _accountingMovement.reference   = _accountingMovement.contract = KeyDefinitions.NextAccountMovementReference(loan.start.Year);
                    _accountingMovement.FK_AccountingMovements_Currencies = loan.currency_id;
                    _accountingMovement.original_reference = "";

                    manager.My_db.AccountingMovements.Add(_accountingMovement);

                    Movements_Accounts _maccount470 = new Movements_Accounts();

                    _maccount470.AccountingMovement                = _accountingMovement;
                    _maccount470.FK_Movements_Accounts_Funds       = manager.Selected;
                    _maccount470.FK_Movements_Accounts_Accounts    = account470.Id;
                    _maccount470.FK_Movements_Accounts_Subaccounts = subacct470.Id;
                    _maccount470.subaccount      = loan.lender_id;
                    _maccount470.subaccount_type = 4;
                    _maccount470.debit           = 0;
                    _maccount470.credit          = Math.Round(loan.amount, 2);

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

                return(_accountingMovement);
            }

            return(null);
        }
Пример #4
0
        private void cmdDeleteMovement_Click(object sender, EventArgs e)
        {
            try
            {
                if (movementCanBeDeleted())
                {
                    if (MessageBox.Show("This operation can not be undone. Do you wish to proceed?", "Warning", MessageBoxButtons.OKCancel) == DialogResult.OK)
                    {
                        AccountingMovement toAccountingMovementDelete = manager.My_db.AccountingMovements.FirstOrDefault(x => x.Id == IdOfAccountingMovementToEdit);

                        if (toAccountingMovementDelete != null)
                        {
                            List <Movements_Accounts> movementsToDelete = manager.My_db.Movements_Accounts.Where(x => x.FK_Movements_Accounts_AccountingMovements == IdOfAccountingMovementToEdit).ToList();

                            foreach (Movements_Accounts movToDelete in movementsToDelete)
                            {
                                manager.My_db.Movements_Accounts.Remove(movToDelete);
                            }

                            manager.My_db.AccountingMovements.Remove(toAccountingMovementDelete);

                            manager.My_db.SaveChanges();

                            this.Close();
                        }
                    }
                }
                else
                {
                    ErrorMessage.showErrorMessage(new Exception("This accounting movement can not be deleted."));
                }
            }
            catch (Exception _ex)
            {
                ErrorMessage.showErrorMessage(_ex);
            }
        }
Пример #5
0
        private void button3_Click(object sender, EventArgs e)
        {
            AccountingMovement _movement = new AccountingMovement();
            _movement.FK_AccountingMovements_Funds = manager.Selected;
            _movement.description = textBox4.Text;
            _movement.date = Convert.ToDateTime(dateTimePicker1.Text);
            _movement.reference = textBox5.Text;
            _movement.FK_AccountingMovements_Currencies = Convert.ToInt32(comboBox6.SelectedValue);
            manager.My_db.AccountingMovements.Add(_movement);
            manager.My_db.SaveChanges();
            textBox4.Clear();
            textBox5.Text = MyNewReference();
            listView1.Items.Clear();
            textBox1.Text = 0.ToString();
            textBox2.Text = 0.ToString();
            total_credit = 0;
            total_debit = 0;

            foreach (Movement my_movement in movements) {
                
                //subaccount_type  0 -> Client, 1 -> Banking Account, 2 -> Employee, 3 -> Lender
                Movements_Accounts _maccount = new Movements_Accounts();

                _maccount.FK_Movements_Accounts_AccountingMovements = _movement.Id;
                _maccount.FK_Movements_Accounts_Funds = manager.Selected;
                _maccount.FK_Movements_Accounts_Subaccounts = my_movement.Subaccount;
                _maccount.subaccount_type = my_movement.Detalle_type;
                _maccount.subaccount = my_movement.Detalle;
                _maccount.debit = my_movement.Debit;
                _maccount.credit = my_movement.Credit;
                manager.My_db.Movements_Accounts.Add(_maccount);
                manager.My_db.SaveChanges();

            }

        }
        private void generateInterest(bool forAll)
        {
            bool   errorsDetected = false;
            string errorMessages  = "";

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

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

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

            if (account128 != null && account901 != 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 <ProfitShareToAccrue> _profitShareToAccrueList = new List <ProfitShareToAccrue>();

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

                                if (int.TryParse(_item.Text, out disbursementId))
                                {
                                    ProfitShareToAccrue toAcrue = manager.My_db.ProfitShareToAccrues.FirstOrDefault(x => x.Id == disbursementId);

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

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

                                    if (toAcrue.profit_share == 0)
                                    {
                                        errorsDetected = true;
                                        errorMessages += "\rNumber " + toAcrue.number + ": profit share = 0.";
                                    }
                                }
                            }
                        }
                        else
                        {
                            foreach (ListViewItem _item in lvDisbursements.Items)
                            {
                                int disbursementId = 0;

                                if (int.TryParse(_item.Text, out disbursementId))
                                {
                                    ProfitShareToAccrue toAcrue = manager.My_db.ProfitShareToAccrues.FirstOrDefault(x => x.Id == disbursementId);

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

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

                                    if (toAcrue.profit_share == 0)
                                    {
                                        errorsDetected = true;
                                        errorMessages += "\rNumber " + toAcrue.number + ": profit share = 0.";
                                    }
                                }
                            }
                        }

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

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

                            bool interestCreated = false;

                            decimal _totalInterest = 0;

                            bool someDataMissed = false;

                            foreach (ProfitShareToAccrue _profitShareToAccrue in _profitShareToAccrueList)
                            {
                                Currency   currency   = manager.My_db.Currencies.FirstOrDefault(x => x.Id == _profitShareToAccrue.currency_id && x.FK_Currencies_Funds == manager.Selected);
                                Subaccount subacct128 = manager.My_db.Subaccounts.FirstOrDefault(x => x.FK_Subaccounts_Accounts == account128.Id && x.name == "INV " + currency.symbol);
                                Investment investment = manager.My_db.Investments.FirstOrDefault(x => x.Id == _profitShareToAccrue.investment_id);

                                if (currency != null && subacct128 != null && investment != null)
                                {
                                    DisbursementGeneratedInterestDetail interestDetail = manager.My_db.DisbursementGeneratedInterestDetails.FirstOrDefault(x => x.disbursement_id == _profitShareToAccrue.Id && x.generated_interest_date.Year == _date.Year && x.generated_interest_date.Month == _date.Month);

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

                                        if (fromDate == null)
                                        {
                                            fromDate = _profitShareToAccrue.pay_date;
                                        }

                                        bool canContinueGeneratingInterest = true;

                                        decimal _interest = 0;

                                        int totalFinancingDays = (_profitShareToAccrue.collection_date.Date - _profitShareToAccrue.pay_date.Value.Date).Days;

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

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

                                        if (totalFinancingDays > 0 && financingDays > 0)
                                        {
                                            decimal profitSharePerDay = _profitShareToAccrue.profit_share / totalFinancingDays;
                                            _interest = Math.Round(financingDays * profitSharePerDay, 2);
                                        }

                                        canContinueGeneratingInterest = toDate < _profitShareToAccrue.collection_date;

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

                                            if (!canContinueGeneratingInterest)
                                            {
                                                decimal generatedInterest = manager.My_db.DisbursementGeneratedInterestDetails.Where(x => x.disbursement_id == _profitShareToAccrue.Id).Sum(x => x.generated_interest);

                                                Disbursement disb = manager.My_db.Disbursements.FirstOrDefault(x => x.Id == _profitShareToAccrue.Id);

                                                if (disb != null)
                                                {
                                                    decimal difference = disb.profit_share - generatedInterest - _interest;

                                                    if ((double)Math.Abs(difference) > 0.01)
                                                    {
                                                        ErrorMessage.showErrorMessage(new Exception("Referece " + disb.number + " has wrong interest accrued. Please, contact with tech support."));
                                                    }

                                                    _interest = disb.profit_share - generatedInterest;

                                                    disb.can_generate_interest = false;
                                                }
                                            }

                                            _totalInterest += _interest;

                                            DisbursementGeneratedInterestDetail _detail = new DisbursementGeneratedInterestDetail();

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

                                            manager.My_db.DisbursementGeneratedInterestDetails.Add(_detail);

                                            AccountingMovement _accountingMovement = new AccountingMovement();

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

                                            manager.My_db.AccountingMovements.Add(_accountingMovement);

                                            _detail.AccountingMovement = _accountingMovement;

                                            Movements_Accounts _maccount128 = new Movements_Accounts();

                                            _maccount128.AccountingMovement             = _accountingMovement;
                                            _maccount128.FK_Movements_Accounts_Funds    = manager.Selected;
                                            _maccount128.FK_Movements_Accounts_Accounts = account128.Id;
                                            if (subacct128 != null)
                                            {
                                                _maccount128.FK_Movements_Accounts_Subaccounts = subacct128.Id;
                                            }
                                            _maccount128.subaccount      = _profitShareToAccrue.client_id;
                                            _maccount128.subaccount_type = 1;
                                            _maccount128.debit           = Math.Round(_interest, 2);
                                            _maccount128.credit          = 0;

                                            manager.My_db.Movements_Accounts.Add(_maccount128);

                                            Movements_Accounts _maccount901 = new Movements_Accounts();

                                            _maccount901.AccountingMovement             = _accountingMovement;
                                            _maccount901.FK_Movements_Accounts_Funds    = manager.Selected;
                                            _maccount901.FK_Movements_Accounts_Accounts = account901.Id;

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

                                            manager.My_db.Movements_Accounts.Add(_maccount901);
                                        }
                                    }
                                    else
                                    {
                                        Console.WriteLine("Attempt to duplicate disbursement 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)
                            {
                                DisbursementGeneratedInterestForm disbursement_generated_interest_form = new DisbursementGeneratedInterestForm();
                                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 128 or 901 were found."));
            }
        }
Пример #7
0
        private void addLoan()
        {
            try
            {
                if (manager.My_db.ClosedPeriods.FirstOrDefault(x => x.year == dtpFrom.Value.Year && x.fund_id == manager.Selected) == null)
                {
                    int lenderId   = Convert.ToInt32(cbLender.SelectedValue);
                    int currencyId = Convert.ToInt32(cbCurrency.SelectedValue);

                    if (!fEditMode)
                    {
                        Loan _validation = manager.My_db.Loans.FirstOrDefault(x => x.reference == txtReference.Text && x.fund_id == manager.Selected);

                        if (_validation != null)
                        {
                            MessageBox.Show("Duplicated reference.");
                            return;
                        }

                        Loan _loan = new Loan();
                        _loan.fund_id               = manager.Selected;
                        _loan.lender_id             = lenderId;
                        _loan.reference             = txtReference.Text;
                        _loan.interest              = Math.Round(decimal.Parse(txtInterest.Text), 2);
                        _loan.amount                = Math.Round(decimal.Parse(txtAmount.Text), 2);
                        _loan.start                 = dtpFrom.Value;
                        _loan.end                   = dtpTo.Value;
                        _loan.currency_id           = currencyId;
                        _loan.renegotiated          = false;
                        _loan.interest_base         = rb360.Checked ? 360 : 365;
                        _loan.paid                  = 0;
                        _loan.can_generate_interest = 1;

                        AccountingMovement acctMov = generateAccountingMovement(_loan);

                        if (acctMov != null)
                        {
                            _loan.AccountingMovement = acctMov;

                            manager.My_db.Loans.Add(_loan);

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

                            if (!gledger.OperationCompleted)
                            {
                                throw new Exception("Ledger window has been closed. The operation has been rolled back.");
                            }
                        }
                    }
                    //else
                    //{
                    //    //TODO: no esta claro como proceder en la modificacion pues hay mov de cuentas involucrados
                    //    int _id = int.Parse(dataGridView1.SelectedRows[0].Cells[0].Value.ToString());

                    //    Loan _validation = manager.My_db.Loans.FirstOrDefault(x => x.Id != _id && x.reference == txtReference.Text && x.fund_id == manager.Selected);

                    //    if (_validation != null)
                    //    {
                    //        MessageBox.Show("Duplicated reference.");
                    //        return;
                    //    }

                    //    Loan _selected = manager.My_db.Loans.FirstOrDefault(x => x.Id == _id);

                    //    if (_selected != null)
                    //    {
                    //        _selected.fund_id = manager.Selected;
                    //        _selected.lender_id = lenderId;
                    //        _selected.reference = txtReference.Text;
                    //        _selected.interest = Math.Round(decimal.Parse(txtInterest.Text), 2);
                    //        _selected.amount = Math.Round(decimal.Parse(txtAmount.Text), 2);
                    //        _selected.start = dtpFrom.Value;
                    //        _selected.end = dtpTo.Value;
                    //        _selected.currency_id = currencyId;
                    //        _selected.interest_base = rb360.Checked ? 360 : 365;

                    //        manager.My_db.SaveChanges();
                    //    }
                    //}

                    loadLoansData();

                    cmdCancel_Click(null, null);
                }
                else
                {
                    ErrorMessage.showErrorMessage(new Exception("No movement allowed in closed period."));
                }
            }
            catch (Exception _ex)
            {
                ErrorMessage.showErrorMessage(_ex, false);
            }
        }
Пример #8
0
        private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                if (manager.My_db.ClosedPeriods.FirstOrDefault(x => x.year == dtpIssuingDate.Value.Year && x.fund_id == manager.Selected) == null)
                {
                    BondsTFF bond = new BondsTFF();
                    bond.number                    = txtNumber.Text;
                    bond.issued                    = Convert.ToDateTime(dtpIssuingDate.Text);
                    bond.expired                   = Convert.ToDateTime(dtpExpirationDate.Text);
                    bond.FK_Bonds_Funds            = manager.Selected;
                    bond.price                     = Math.Round(Convert.ToDecimal(txtPrice.Text), 2);
                    bond.pieces                    = (float)Convert.ToDecimal(txtBondPieces.Text);
                    bond.interest_on_bond          = Convert.ToInt32(txtBondInterest.Text);
                    bond.interest_tff_contribution = Convert.ToInt32(txtTFFInterest.Text);

                    bond.active = 1;

                    manager.My_db.BondsTFFs.Add(bond);
                    manager.My_db.SaveChanges();

                    foreach (InvestorForBond _investor in investors)
                    {
                        BondsTFFInvestor bond_investor = new BondsTFFInvestor();
                        bond_investor.FK_BondsInvestors_Bonds     = bond.Id;
                        bond_investor.FK_BondsInvestors_Investors = _investor.Id;
                        bond_investor.quantity = _investor.Pieces;
                        manager.My_db.BondsTFFInvestors.Add(bond_investor);
                        manager.My_db.SaveChanges();
                    }

                    Resource _resource = manager.My_db.Resources.FirstOrDefault(x => x.Name == KeyDefinitions.BONDTFF_CONSECUTIVE_KEY && x.FundId == manager.Selected);

                    fBondConsecutive++;

                    _resource.Value = fBondConsecutive.ToString();

                    manager.My_db.SaveChanges();



                    //TODO: Crear un movimiento contable con un debito a 100 y un credito a 510 por el monto del bono

                    //Obtener nuevo numero de referencia
                    //Crear AccountingMovement
                    //Crear Movements_Accounts con un debito a 100
                    //Crear Movements_Accounts con un credito a 510

                    Account    _CashAtBank    = manager.My_db.Accounts.FirstOrDefault(x => x.number == "100" && x.FK_Accounts_Funds == manager.Selected);
                    Account    _Bonds         = manager.My_db.Accounts.FirstOrDefault(x => x.number == "510" && x.FK_Accounts_Funds == manager.Selected);
                    Subaccount _CashAtBankEUR = manager.My_db.Subaccounts.FirstOrDefault(x => x.name == "Cash at Bank EUR");
                    Subaccount _BondI         = manager.My_db.Subaccounts.FirstOrDefault(x => x.name == "Bond I");

                    if (_CashAtBank != null &&
                        _Bonds != null &&
                        _CashAtBankEUR != null &&
                        _BondI != null)
                    {
                        AccountingMovement _movement = new AccountingMovement();
                        _movement.FK_AccountingMovements_Funds = manager.Selected;
                        //TODO: Poner description correcta cuando la manden
                        _movement.description = "";
                        _movement.date        = bond.issued;
                        _movement.reference   = KeyDefinitions.NextAccountMovementReference(dtpIssuingDate.Value.Year);
                        _movement.FK_AccountingMovements_Currencies = manager.My_db.Currencies.FirstOrDefault().Id;
                        //TODO: Poner ORIG cuando la manden
                        _movement.original_reference = "";
                        manager.My_db.AccountingMovements.Add(_movement);
                        manager.My_db.SaveChanges();

                        Movements_Accounts _movAcctCashAtBank = new Movements_Accounts();
                        Movements_Accounts _movAcctBond       = new Movements_Accounts();

                        _movAcctCashAtBank.FK_Movements_Accounts_AccountingMovements = _movement.Id;
                        _movAcctCashAtBank.FK_Movements_Accounts_Funds       = manager.Selected;
                        _movAcctCashAtBank.FK_Movements_Accounts_Accounts    = _CashAtBank.Id;
                        _movAcctCashAtBank.FK_Movements_Accounts_Subaccounts = _CashAtBankEUR.Id;
                        //TODO: Poner subaccount type correcto cuando lo manden
                        //_movAcctCashAtBank.subaccount_type = my_movement.Detail_type;
                        //TODO: Poner subaccount type correcto cuando lo manden
                        //_movAcctCashAtBank.subaccount = my_movement.Detail;

                        _movAcctCashAtBank.debit  = Math.Round((decimal)bond.pieces * bond.price, 2);
                        _movAcctCashAtBank.credit = 0;

                        manager.My_db.Movements_Accounts.Add(_movAcctCashAtBank);

                        _movAcctBond.FK_Movements_Accounts_AccountingMovements = _movement.Id;
                        _movAcctBond.FK_Movements_Accounts_Funds       = manager.Selected;
                        _movAcctBond.FK_Movements_Accounts_Accounts    = _Bonds.Id;
                        _movAcctBond.FK_Movements_Accounts_Subaccounts = _BondI.Id;
                        //TODO: Poner subaccount type correcto cuando lo manden
                        //_movAcctBond.subaccount_type = my_movement.Detail_type;
                        //TODO: Poner subaccount type correcto cuando lo manden
                        //_movAcctBond.subaccount = my_movement.Detail;

                        _movAcctBond.debit  = 0;
                        _movAcctBond.credit = Math.Round((decimal)bond.pieces * bond.price, 2);

                        manager.My_db.Movements_Accounts.Add(_movAcctBond);

                        manager.My_db.SaveChanges();

                        investors.Clear();
                        check_pieces           = 0;
                        txtNumber.Text         = "Bond " + Conversions.toRomanNumeral(fBondConsecutive);
                        txtPrice.Text          = "0";
                        txtBondInterest.Text   = "10";
                        txtTFFInterest.Text    = "1";
                        txtInvestorPieces.Text = "0";
                        txtBondPieces.Text     = "0";
                        listView1.Items.Clear();
                        txtPrice.ReadOnly      = false;
                        txtBondPieces.ReadOnly = false;
                    }
                }
                else
                {
                    ErrorMessage.showErrorMessage(new Exception("No movement allowed in closed period."));
                }
            }
            catch (Exception _ex)
            {
                ErrorMessage.showErrorMessage(_ex);
            }
        }
Пример #9
0
        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);
            }
        }
Пример #10
0
        private void generateInterest(bool forAll)
        {
            bool   errorsDetected = false;
            string errorMessages  = "";

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

            Account account840 = manager.My_db.Accounts.FirstOrDefault(x => x.number == "840" && x.FK_Accounts_Funds == manager.Selected);
            Account account540 = manager.My_db.Accounts.FirstOrDefault(x => x.number == "540" && x.FK_Accounts_Funds == manager.Selected);

            if (account840 != null && account540 != null)
            {
                Subaccount subacct840 = manager.My_db.Subaccounts.FirstOrDefault(x => x.FK_Subaccounts_Accounts == account840.Id && x.name == "Interest on Bonds");
                Subaccount subacct540 = manager.My_db.Subaccounts.FirstOrDefault(x => x.FK_Subaccounts_Accounts == account540.Id && x.name == "Interest Bond");

                if (subacct840 != null && subacct540 != 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 <BondsTFAM> _bondsToGenerateInterest = new List <BondsTFAM>();

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

                                    if (int.TryParse(_item.Text, out bondId))
                                    {
                                        BondsTFAM toGenerate = manager.My_db.BondsTFAMs.FirstOrDefault(x => x.Id == bondId);

                                        if (toGenerate != null)
                                        {
                                            _bondsToGenerateInterest.Add(toGenerate);
                                        }

                                        if (toGenerate.expired <= toGenerate.issued)
                                        {
                                            errorsDetected = true;
                                            errorMessages += "\rBond " + toGenerate.number + ": expire <= issued date.";
                                        }

                                        if (toGenerate.amount == 0)
                                        {
                                            errorsDetected = true;
                                            errorMessages += "\rBond " + toGenerate.number + ": amount = 0.";
                                        }
                                    }
                                }
                            }
                            else
                            {
                                foreach (ListViewItem _item in lvData.Items)
                                {
                                    int bondId = 0;

                                    if (int.TryParse(_item.Text, out bondId))
                                    {
                                        BondsTFAM toGenerate = manager.My_db.BondsTFAMs.FirstOrDefault(x => x.Id == bondId);

                                        if (toGenerate != null)
                                        {
                                            _bondsToGenerateInterest.Add(toGenerate);
                                        }

                                        if (toGenerate.expired <= toGenerate.issued)
                                        {
                                            errorsDetected = true;
                                            errorMessages += "\rBond " + toGenerate.number + ": expire <= issued date.";
                                        }

                                        if (toGenerate.amount == 0)
                                        {
                                            errorsDetected = true;
                                            errorMessages += "\rBond " + toGenerate.number + ": amount = 0.";
                                        }
                                    }
                                }
                            }

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

                            if (_bondsToGenerateInterest.Count > 0)
                            {
                                BondsTFAMGeneratedInterest _interest = new BondsTFAMGeneratedInterest();
                                _interest.GeneratedDate = DateTime.Now;

                                bool interestCreated = false;

                                foreach (BondsTFAM _bondToGenerate in _bondsToGenerateInterest)
                                {
                                    BondsTFAMGeneratedInterestDetail existingInterest = manager.My_db.BondsTFAMGeneratedInterestDetails.FirstOrDefault(x => x.bond_id == _bondToGenerate.Id && x.generated_interest_date.Year == _date.Year && x.generated_interest_date.Month == _date.Month);

                                    if (existingInterest == null)
                                    {
                                        DateTime?fromDate = getLastGeneratedInterestDateFor(_bondToGenerate.Id);

                                        if (fromDate == null)
                                        {
                                            fromDate = _bondToGenerate.issued;
                                        }

                                        bool canContinueGeneratingInterest = true;

                                        decimal _interestOnBond = 0;
                                        decimal _interestOnTFF  = 0;

                                        DateTime toDate = dtpDate.Value <= _bondToGenerate.expired ? dtpDate.Value : _bondToGenerate.expired;

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

                                        if (days > 0)
                                        {
                                            _interestOnBond = Math.Round(_bondToGenerate.amount * (decimal)_bondToGenerate.interest_on_bond * days / 360 / 100, 2);
                                            _interestOnTFF  = Math.Round(_bondToGenerate.amount * (decimal)_bondToGenerate.interest_tff_contribution * days / 360 / 100, 2);
                                        }

                                        canContinueGeneratingInterest = toDate < _bondToGenerate.expired;

                                        if (_interestOnBond > 0 && _interestOnTFF > 0)
                                        {
                                            if (!interestCreated)
                                            {
                                                manager.My_db.BondsTFAMGeneratedInterests.Add(_interest);
                                                interestCreated = true;
                                            }

                                            BondsTFAMGeneratedInterestDetail _interestDetail = new BondsTFAMGeneratedInterestDetail();
                                            _interestDetail.BondsTFAMGeneratedInterest = _interest;

                                            _interestDetail.bond_id = _bondToGenerate.Id;
                                            _interestDetail.generated_bond_interest = Math.Round(_interestOnBond, 2);
                                            _interestDetail.generated_tff_interest  = Math.Round(_interestOnTFF, 2);
                                            _interestDetail.generated_interest_date = toDate;

                                            manager.My_db.BondsTFAMGeneratedInterestDetails.Add(_interestDetail);

                                            AccountingMovement _accountingMovement = new AccountingMovement();

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

                                            manager.My_db.AccountingMovements.Add(_accountingMovement);

                                            _interestDetail.AccountingMovement = _accountingMovement;

                                            Movements_Accounts _maccount840 = new Movements_Accounts();

                                            _maccount840.AccountingMovement             = _accountingMovement;
                                            _maccount840.FK_Movements_Accounts_Funds    = manager.Selected;
                                            _maccount840.FK_Movements_Accounts_Accounts = account840.Id;
                                            if (subacct840 != null)
                                            {
                                                _maccount840.FK_Movements_Accounts_Subaccounts = subacct840.Id;
                                            }
                                            _maccount840.subaccount_type = 9;
                                            _maccount840.subaccount      = _bondToGenerate.Id;
                                            _maccount840.debit           = Math.Round(_interestOnBond + _interestOnTFF, 2);
                                            _maccount840.credit          = 0;

                                            manager.My_db.Movements_Accounts.Add(_maccount840);

                                            Movements_Accounts _maccount540 = new Movements_Accounts();

                                            _maccount540.AccountingMovement             = _accountingMovement;
                                            _maccount540.FK_Movements_Accounts_Funds    = manager.Selected;
                                            _maccount540.FK_Movements_Accounts_Accounts = account540.Id;
                                            if (subacct540 != null)
                                            {
                                                _maccount540.FK_Movements_Accounts_Subaccounts = subacct540.Id;
                                            }
                                            _maccount540.subaccount_type = 9;
                                            _maccount540.subaccount      = _bondToGenerate.Id;
                                            _maccount540.debit           = 0;
                                            _maccount540.credit          = Math.Round(_interestOnBond + _interestOnTFF, 2);

                                            manager.My_db.Movements_Accounts.Add(_maccount540);
                                        }
                                    }
                                    else
                                    {
                                        Console.WriteLine("Attempt to duplicate bond interest generation.");
                                    }
                                }

                                manager.My_db.SaveChanges();

                                BondGeneratedInterestForm generated_interest_form = new BondGeneratedInterestForm();
                                generated_interest_form.generated_interest_id = _interest.Id;
                                generated_interest_form.Show();
                            }
                            else
                            {
                                MessageBox.Show("No bonds found for interest generation.");
                            }
                        }
                        else
                        {
                            ErrorMessage.showErrorMessage(new Exception("No movement allowed in closed period."));
                        }
                    }
                    catch (Exception _ex)
                    {
                        ErrorMessage.showErrorMessage(_ex);
                    }
                }
                else
                {
                    ErrorMessage.showErrorMessage(new Exception("No subaccount for 840 or 540 were found."));
                }

                cmdGenerateInterest.Enabled    = true;
                cmdGenerateAllInterest.Enabled = true;
            }
            else
            {
                ErrorMessage.showErrorMessage(new Exception("No account 840 or 540 were found."));
            }
        }
Пример #11
0
        private void GeneralLedgerForm_Load(object sender, EventArgs e)
        {
            try
            {
                this.currenciesTableAdapter.FillByFund(this.fundsDBDataSet.Currencies, manager.Selected);
                this.accountsTableAdapter.FillByFund(this.fundsDBDataSet.Accounts, manager.Selected);
                cbAccount.SelectedItem      = null;
                cbAccount.SelectedText      = "Select account";
                cbSubaccount.SelectedIndex  = -1;
                cbOtherDetail.SelectedItem  = null;
                cbOtherDetail.SelectedIndex = -1;
                textBox3.Text = KeyDefinitions.NextAccountMovementReference(dateTimePicker1.Value.Year);

                fFloatingAccounts = manager.My_db.Accounts.Where(x => x.FK_Accounts_Funds == manager.Selected).ToList();

                txtContract.Text = "";

                OnAccountChanged(null, null);



                if (FormInEditAccountingMovement && IdOfAccountingMovementToEdit > 0)
                {
                    listView1.MultiSelect = false;

                    button2.Enabled = true;
                    button2.Text    = "Save Movement";

                    AccountingMovementToEdit = manager.My_db.AccountingMovements.FirstOrDefault(x => x.Id == IdOfAccountingMovementToEdit);

                    if (AccountingMovementToEdit != null)
                    {
                        for (int i = 0; i < comboBox4.Items.Count; i++)
                        {
                            FundsManager.FundsDBDataSet.CurrenciesRow row = (FundsManager.FundsDBDataSet.CurrenciesRow)((System.Data.DataRowView)comboBox4.Items[i]).Row;

                            if (row.Id == AccountingMovementToEdit.FK_AccountingMovements_Currencies)
                            {
                                comboBox4.SelectedIndex = i;
                                break;
                            }
                        }

                        dateTimePicker1.Value = AccountingMovementToEdit.date;

                        textBox3.Text = AccountingMovementToEdit.reference;

                        textBox4.Text = AccountingMovementToEdit.description;

                        textBox5.Text = AccountingMovementToEdit.original_reference;

                        txtContract.Text = AccountingMovementToEdit.contract != null ? AccountingMovementToEdit.contract : "";

                        List <Movements_Accounts> movementsAccount = manager.My_db.Movements_Accounts.Where(x => x.FK_Movements_Accounts_AccountingMovements == IdOfAccountingMovementToEdit).ToList();

                        foreach (Movements_Accounts _mov in movementsAccount)
                        {
                            movements.Add(new Movement(_mov));
                        }

                        loadMovementsInListView();

                        checkForContractVisibility();
                    }

                    if (movementCanBeDeleted())
                    {
                        cmdDeleteMovement.Visible = true;
                    }
                }

                if (FromExternalOperation && ExternalAccountMovemet != null)
                {
                    AvoidAccountBalanceValidation = true;

                    textBox3.Text = ExternalAccountMovemet.reference;

                    textBox5.Text = ExternalAccountMovemet.original_reference;

                    dateTimePicker1.Value = ExternalAccountMovemet.date;

                    textBox4.Text = ExternalAccountMovemet.description;

                    for (int i = 0; i < comboBox4.Items.Count; i++)
                    {
                        int currency_id = ((FundsManager.FundsDBDataSet.CurrenciesRow)((System.Data.DataRowView)comboBox4.Items[i]).Row).Id;

                        if (currency_id == ExternalAccountMovemet.FK_AccountingMovements_Currencies)
                        {
                            comboBox4.SelectedIndex = i;
                            break;
                        }
                    }

                    textBox3.Enabled  = false;
                    textBox5.Enabled  = false;
                    comboBox4.Enabled = false;

                    textBox1.Text = String.Format("{0:0.00}", ExternalDebit);
                    textBox2.Text = String.Format("{0:0.00}", ExternalCredit);
                }
            }
            catch (Exception _ex)
            {
                Console.WriteLine("Error in GeneralLedgerForm.GeneralLedgerForm_Load: " + _ex.Message);
            }
        }
Пример #12
0
        private void makeMovement()
        {
            if (listView1.Items.Count >= 0)
            {
                try
                {
                    DateTime date = Convert.ToDateTime(dateTimePicker1.Text);
                    if (manager.My_db.ClosedPeriods.FirstOrDefault(x => x.year == date.Year && x.fund_id == manager.Selected) == null)
                    {
                        if (!FormInEditAccountingMovement)
                        {
                            AccountingMovement newAccountingMovement = new AccountingMovement();

                            if (!FromExternalOperation)
                            {
                                newAccountingMovement.FK_AccountingMovements_Funds = manager.Selected;
                                newAccountingMovement.reference          = textBox3.Text;
                                newAccountingMovement.original_reference = textBox5.Text;
                            }
                            else
                            {
                                newAccountingMovement = ExternalAccountMovemet;
                            }

                            newAccountingMovement.description = textBox4.Text;
                            newAccountingMovement.date        = Convert.ToDateTime(dateTimePicker1.Text);
                            newAccountingMovement.FK_AccountingMovements_Currencies = Convert.ToInt32(comboBox4.SelectedValue);

                            if (txtContract.Visible)
                            {
                                newAccountingMovement.contract = txtContract.Text;
                            }

                            if (!FromExternalOperation)
                            {
                                manager.My_db.AccountingMovements.Add(newAccountingMovement);
                            }

                            textBox3.Text = KeyDefinitions.NextAccountMovementReference(dateTimePicker1.Value.Year);
                            textBox4.Clear();
                            textBox5.Clear();
                            txtContract.Clear();
                            listView1.Items.Clear();
                            textBox1.Text = 0.ToString();
                            textBox2.Text = 0.ToString();
                            total_credit  = 0;
                            total_debit   = 0;

                            foreach (Movement newMovementAccount in movements)
                            {
                                addMovement(newMovementAccount, newAccountingMovement);
                            }

                            manager.My_db.SaveChanges();

                            movements.Clear();
                            movementsToDelete.Clear();

                            checkForContractVisibility();

                            button2.Enabled = false;

                            if (FromExternalOperation)
                            {
                                OperationCompleted = true;
                                this.Close();
                            }
                        }
                        else
                        {
                            AccountingMovementToEdit.FK_AccountingMovements_Funds = manager.Selected;
                            AccountingMovementToEdit.description = textBox4.Text;
                            AccountingMovementToEdit.date        = Convert.ToDateTime(dateTimePicker1.Text);
                            AccountingMovementToEdit.reference   = textBox3.Text;
                            AccountingMovementToEdit.FK_AccountingMovements_Currencies = Convert.ToInt32(comboBox4.SelectedValue);
                            AccountingMovementToEdit.original_reference = textBox5.Text;

                            if (txtContract.Visible)
                            {
                                AccountingMovementToEdit.contract = txtContract.Text;
                            }

                            textBox3.Text = KeyDefinitions.NextAccountMovementReference(dateTimePicker1.Value.Year);
                            textBox4.Clear();
                            textBox5.Clear();
                            txtContract.Clear();
                            listView1.Items.Clear();
                            textBox1.Text = 0.ToString();
                            textBox2.Text = 0.ToString();
                            total_credit  = 0;
                            total_debit   = 0;

                            foreach (Movement movementToSave in movements)
                            {
                                addMovement(movementToSave, AccountingMovementToEdit);
                            }

                            foreach (Movement toDelete in movementsToDelete)
                            {
                                if (toDelete.Id > 0)
                                {
                                    manager.DeleteMovementAccount(toDelete.Id);
                                }
                            }

                            manager.My_db.SaveChanges();

                            movements.Clear();
                            movementsToDelete.Clear();

                            OperationCompleted = true;
                            this.Close();
                        }

                        OperationCompleted = true;
                    }
                    else
                    {
                        ErrorMessage.showErrorMessage(new Exception("No movement allowed in closed period."));
                    }
                }
                catch (Exception _ex)
                {
                    ErrorMessage.showErrorMessage(_ex);

                    OperationCompleted = false;
                }

                cmdDeleteMovement.Visible = false;
            }
            else
            {
                ErrorMessage.showErrorMessage(new Exception("Sorry, yo must add a movement account first."));
            }
        }
Пример #13
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);
            }
        }
Пример #14
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);
            }
        }
Пример #15
0
        private void cmdBook_Click(object sender, EventArgs e)
        {
            try
            {
                if (manager.My_db.ClosedPeriods.FirstOrDefault(x => x.year == dtpBookingDate.Value.Year && x.fund_id == manager.Selected) == null)
                {
                    decimal totalAmount      = bookings.Sum(x => x.amount);
                    decimal totalProfitShare = bookings.Sum(x => x.profit_share);

                    AccountingMovement _accountingMovement = new AccountingMovement();
                    DisbursementBook   _book = new DisbursementBook();

                    Currency   currency   = manager.My_db.Currencies.FirstOrDefault(x => x.Id == currencyId && x.FK_Currencies_Funds == manager.Selected);
                    Account    account125 = manager.My_db.Accounts.FirstOrDefault(x => x.number == "125" && x.FK_Accounts_Funds == manager.Selected);
                    Subaccount subacct125 = manager.My_db.Subaccounts.FirstOrDefault(x => x.FK_Subaccounts_Accounts == account125.Id && x.name == "INV " + currency.symbol);
                    Account    account128 = manager.My_db.Accounts.FirstOrDefault(x => x.number == "128" && x.FK_Accounts_Funds == manager.Selected);
                    Subaccount subacct128 = manager.My_db.Subaccounts.FirstOrDefault(x => x.FK_Subaccounts_Accounts == account128.Id && x.name == "INV " + currency.symbol);

                    if (account125 == null || account128 == null || subacct125 == null || subacct128 == null)
                    {
                        //TODO: Error
                        return;
                    }

                    _accountingMovement.FK_AccountingMovements_Funds = manager.Selected;
                    _accountingMovement.description = "";
                    _accountingMovement.date        = dtpBookingDate.Value.Date;
                    _accountingMovement.reference   = KeyDefinitions.NextAccountMovementReference(dtpBookingDate.Value.Year);
                    _accountingMovement.FK_AccountingMovements_Currencies = currencyId;
                    _accountingMovement.original_reference = investment.contract;
                    _accountingMovement.contract           = investment.contract;

                    manager.My_db.AccountingMovements.Add(_accountingMovement);

                    _book.date = DateTime.Now.Date;

                    _book.AccountingMovement = _accountingMovement;
                    manager.My_db.DisbursementBooks.Add(_book);

                    Movements_Accounts _maccount125_total = new Movements_Accounts();

                    _maccount125_total.AccountingMovement             = _accountingMovement;
                    _maccount125_total.FK_Movements_Accounts_Funds    = manager.Selected;
                    _maccount125_total.FK_Movements_Accounts_Accounts = account125.Id;
                    if (subacct125 != null)
                    {
                        _maccount125_total.FK_Movements_Accounts_Subaccounts = subacct125.Id;
                    }
                    _maccount125_total.subaccount      = clientId;
                    _maccount125_total.subaccount_type = 1;
                    _maccount125_total.credit          = totalAmount;
                    _maccount125_total.debit           = 0;

                    manager.My_db.Movements_Accounts.Add(_maccount125_total);

                    Movements_Accounts _maccount128_total = new Movements_Accounts();

                    _maccount128_total.AccountingMovement             = _accountingMovement;
                    _maccount128_total.FK_Movements_Accounts_Funds    = manager.Selected;
                    _maccount128_total.FK_Movements_Accounts_Accounts = account128.Id;
                    if (subacct128 != null)
                    {
                        _maccount128_total.FK_Movements_Accounts_Subaccounts = subacct128.Id;
                    }
                    _maccount128_total.subaccount      = clientId;
                    _maccount128_total.subaccount_type = 1;
                    _maccount128_total.credit          = totalProfitShare;
                    _maccount128_total.debit           = 0;

                    manager.My_db.Movements_Accounts.Add(_maccount128_total);

                    _book.Movements_Accounts  = _maccount125_total;
                    _book.Movements_Accounts1 = _maccount128_total;

                    int plus = 1;

                    foreach (Disbursement _booking in bookings)
                    {
                        _booking.book_id = _book.Id;

                        Movements_Accounts _maccount125 = new Movements_Accounts();

                        _maccount125.AccountingMovement             = _accountingMovement;
                        _maccount125.FK_Movements_Accounts_Funds    = manager.Selected;
                        _maccount125.FK_Movements_Accounts_Accounts = account125.Id;
                        if (subacct125 != null)
                        {
                            _maccount125.FK_Movements_Accounts_Subaccounts = subacct125.Id;
                        }
                        _maccount125.subaccount      = clientId;
                        _maccount125.subaccount_type = 1;
                        _maccount125.credit          = 0;
                        _maccount125.debit           = Math.Round(_booking.amount, 2);

                        manager.My_db.Movements_Accounts.Add(_maccount125);

                        Movements_Accounts _maccount128 = new Movements_Accounts();

                        _maccount128.AccountingMovement             = _accountingMovement;
                        _maccount128.FK_Movements_Accounts_Funds    = manager.Selected;
                        _maccount128.FK_Movements_Accounts_Accounts = account128.Id;
                        if (subacct128 != null)
                        {
                            _maccount128.FK_Movements_Accounts_Subaccounts = subacct128.Id;
                        }
                        _maccount128.subaccount      = clientId;
                        _maccount128.subaccount_type = 1;
                        _maccount128.credit          = 0;
                        _maccount128.debit           = Math.Round(_booking.profit_share, 2);

                        manager.My_db.Movements_Accounts.Add(_maccount128);

                        _booking.Movements_Accounts  = _maccount125;
                        _booking.Movements_Accounts1 = _maccount128;

                        int?groupId = manager.My_db.Disbursements.Max(x => x.group_id);

                        if (!groupId.HasValue)
                        {
                            groupId = 1;
                        }

                        groupId += plus;

                        plus++;

                        _booking.group_id = groupId;

                        manager.My_db.Disbursements.Add(_booking);
                    }

                    int groupParentId = 0;

                    if (disbursementForAddendumGroup.Count == 1)
                    {
                        groupParentId = disbursementForAddendumGroup.ElementAt(0).group_id.Value;
                    }
                    else
                    {
                        int?maxGroupId = manager.My_db.Disbursements.Max(x => x.group_id);

                        if (!maxGroupId.HasValue)
                        {
                            maxGroupId = 1;
                        }

                        groupParentId = maxGroupId.Value + bookings.Count + 1;
                    }

                    foreach (Disbursement item in disbursementForAddendumGroup)
                    {
                        item.has_bookings = true;
                        item.group_id     = groupParentId;
                    }

                    foreach (Disbursement item in bookings)
                    {
                        item.DisbursementBook = _book;
                        item.group_parent_id  = groupParentId;
                    }

                    manager.My_db.SaveChanges();

                    txtAmount.Text             = "0";
                    txtNumber.Text             = "";
                    txtProfitShare.Text        = String.Format("{0:0.00}", 0);
                    lblTotalToBeCollected.Text = String.Format("{0:0.00}", 0);
                    lbISelectedItems.Items.Clear();
                    lvBooking.Items.Clear();

                    bookings.Clear();

                    cmdCancel_Click(null, null);

                    this.Close();
                }
                else
                {
                    ErrorMessage.showErrorMessage(new Exception("No movement allowed in closed period."));
                }
            }
            catch (Exception _ex)
            {
                ErrorMessage.showErrorMessage(_ex);
            }
        }
Пример #16
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."));
            }
        }
        private void cmdCollect_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 <decimal> amounts              = new List <decimal>();
                    List <decimal> profitShares         = new List <decimal>();
                    List <decimal> delayInterests       = new List <decimal>();
                    List <decimal> overdues             = new List <decimal>();
                    List <decimal> collectPrincipal     = new List <decimal>();
                    List <decimal> collectProfitShare   = new List <decimal>();
                    List <decimal> collectDelayInterest = new List <decimal>();
                    List <decimal> collectOverdues      = new List <decimal>();
                    List <bool>    isBookings           = new List <bool>();

                    String errors = "";

                    foreach (DataGridViewRow row in dataGridView1.Rows)
                    {
                        string  rowId         = row.Cells[IdIndex].Value.ToString();
                        string  number        = row.Cells[NumberIndex].Value.ToString();
                        decimal amount        = decimal.Parse(row.Cells[AmountIndex].Value.ToString());
                        decimal profitShare   = decimal.Parse(row.Cells[ProfitShareIndex].Value.ToString());
                        decimal delayInterest = decimal.Parse(row.Cells[DelayInterestIndex].Value.ToString());
                        decimal overdue       = decimal.Parse(row.Cells[OverdueIndex].Value.ToString());
                        string  amountToBeCollectedPrincipalStr     = row.Cells[CollectToPrincipalIndex].Value != null ? row.Cells[CollectToPrincipalIndex].Value.ToString() : "0";
                        string  amountToBeCollectedProfitShareStr   = row.Cells[CollectToProfitShareIndex].Value != null ? row.Cells[CollectToProfitShareIndex].Value.ToString() : "0";
                        string  amountToBeCollectedDelayInterestStr = row.Cells[CollectToDelayInterestIndex].Value != null ? row.Cells[CollectToDelayInterestIndex].Value.ToString() : "0";
                        string  amountToBeCollectedOverdueStr       = row.Cells[CollectToOverdueIndex].Value != null ? row.Cells[CollectToOverdueIndex].Value.ToString() : "0";
                        bool    isBooking = row.Cells[IsBookingIndex].Value != null?bool.Parse(row.Cells[IsBookingIndex].Value.ToString()) : false;

                        if (amountToBeCollectedPrincipalStr != "0" ||
                            amountToBeCollectedProfitShareStr != "0" ||
                            amountToBeCollectedDelayInterestStr != "0" ||
                            amountToBeCollectedOverdueStr != "0")
                        {
                            decimal amountToBeCollectedPrincipal     = 0;
                            decimal amountToBeCollectedProfitShare   = 0;
                            decimal amountToBeCollectedDelayInterest = 0;
                            decimal amountToBeCollectedOverdue       = 0;

                            if (decimal.TryParse(amountToBeCollectedPrincipalStr, out amountToBeCollectedPrincipal) &&
                                decimal.TryParse(amountToBeCollectedProfitShareStr, out amountToBeCollectedProfitShare) &&
                                decimal.TryParse(amountToBeCollectedDelayInterestStr, out amountToBeCollectedDelayInterest) &&
                                decimal.TryParse(amountToBeCollectedOverdueStr, out amountToBeCollectedOverdue))
                            {
                                if (amount - amountToBeCollectedPrincipal >= 0 &&
                                    profitShare - amountToBeCollectedProfitShare >= 0 &&
                                    delayInterest - amountToBeCollectedDelayInterest >= 0 &&
                                    overdue - amountToBeCollectedOverdue >= 0)
                                {
                                    rowIds.Add(rowId);
                                    amounts.Add(amount);
                                    profitShares.Add(profitShare);
                                    delayInterests.Add(delayInterest);
                                    overdues.Add(overdue);
                                    collectPrincipal.Add(amountToBeCollectedPrincipal);
                                    collectProfitShare.Add(amountToBeCollectedProfitShare);
                                    collectDelayInterest.Add(amountToBeCollectedDelayInterest);
                                    collectOverdues.Add(amountToBeCollectedOverdue);
                                    isBookings.Add(isBooking);
                                }
                                else
                                {
                                    errors += "\r\tDisbursement " + number + " has too much collection value.";
                                }
                            }
                            else
                            {
                                errors += "\r  Disbursement " + number + " has wrong collection value.";
                            }
                        }
                    }

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

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

                        if (rowIds.Count > 0)
                        {
                            DisbursementCollection collection = new DisbursementCollection();
                            collection.collection_date = dtpDate.Value;
                            collection.investment_id   = cbContract.SelectedValue != null?int.Parse(cbContract.SelectedValue.ToString()) : 0;

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

                            if (collection.investment_id > 0)
                            {
                                if (account125 != null && account128 != null && account130 != null)
                                {
                                    manager.My_db.DisbursementCollections.Add(collection);

                                    AccountingMovement accountingMovement = new AccountingMovement();

                                    accountingMovement.FK_AccountingMovements_Funds = manager.Selected;
                                    accountingMovement.description        = "Disbursement Collection";
                                    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 amount                     = amounts[i];
                                        decimal profitShare                = profitShares[i];
                                        decimal delayInterest              = delayInterests[i];
                                        decimal overdue                    = overdues[i];
                                        decimal toBeCollectedPrincipal     = collectPrincipal[i];
                                        decimal toBeCollectedProfitShare   = collectProfitShare[i];
                                        decimal toBeCollectedDelayInterest = collectDelayInterest[i];
                                        decimal toBeCollectedOverdue       = collectOverdues[i];
                                        bool    isBooking                  = isBookings[i];

                                        int disbursementId = int.Parse(rowId);

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

                                        if (disbursement != null)
                                        {
                                            int currencyId = disbursement.currency_id;

                                            Currency   currency   = manager.My_db.Currencies.FirstOrDefault(x => x.Id == currencyId && x.FK_Currencies_Funds == manager.Selected);
                                            Subaccount subacct125 = manager.My_db.Subaccounts.FirstOrDefault(x => x.FK_Subaccounts_Accounts == account125.Id && x.name == "INV " + currency.symbol);
                                            Subaccount subacct128 = manager.My_db.Subaccounts.FirstOrDefault(x => x.FK_Subaccounts_Accounts == account128.Id && x.name == "INV " + currency.symbol);
                                            Subaccount subacct130 = manager.My_db.Subaccounts.FirstOrDefault(x => x.FK_Subaccounts_Accounts == account130.Id && x.name == "INV " + currency.symbol);

                                            if (currency != null)
                                            {
                                                if (subacct125 != null && subacct128 != null && subacct130 != null)
                                                {
                                                    if (accountingMovement.FK_AccountingMovements_Currencies == 0)
                                                    {
                                                        accountingMovement.FK_AccountingMovements_Currencies = currency.Id;

                                                        manager.My_db.AccountingMovements.Add(accountingMovement);

                                                        collection.AccountingMovement = accountingMovement;
                                                    }

                                                    DisbursementCollectionsDetail disbursementCollectionDetail = new DisbursementCollectionsDetail();

                                                    disbursementCollectionDetail.DisbursementCollection       = collection;
                                                    disbursementCollectionDetail.disbursement_id              = disbursementId;
                                                    disbursementCollectionDetail.amount_to_be_collected       = amount + profitShare + delayInterest + overdue;
                                                    disbursementCollectionDetail.amount_collected             = Math.Round(toBeCollectedPrincipal + toBeCollectedProfitShare + toBeCollectedDelayInterest + toBeCollectedOverdue, 2);
                                                    disbursementCollectionDetail.principal_to_be_collected    = amount;
                                                    disbursementCollectionDetail.principal_collected          = Math.Round(toBeCollectedPrincipal, 2);
                                                    disbursementCollectionDetail.profit_share_to_be_collected = profitShare;
                                                    disbursementCollectionDetail.profit_share_collected       = Math.Round(toBeCollectedProfitShare, 2);
                                                    disbursementCollectionDetail.delay_interest_be_collected  = delayInterest;
                                                    disbursementCollectionDetail.delay_interest_collected     = Math.Round(toBeCollectedDelayInterest, 2);
                                                    disbursementCollectionDetail.overdue_to_be_collected      = overdue;
                                                    disbursementCollectionDetail.overdue_collected            = Math.Round(toBeCollectedOverdue, 2);

                                                    if (amount - toBeCollectedPrincipal <= 0 &&
                                                        profitShare - toBeCollectedProfitShare <= 0 &&
                                                        delayInterest - toBeCollectedDelayInterest <= 0 &&
                                                        overdue - toBeCollectedOverdue <= 0 &&
                                                        !disbursement.can_generate_interest)
                                                    {
                                                        setCollected(disbursement);
                                                    }

                                                    manager.My_db.DisbursementCollectionsDetails.Add(disbursementCollectionDetail);

                                                    if (toBeCollectedPrincipal > 0)
                                                    {
                                                        Movements_Accounts _maccount125 = new Movements_Accounts();

                                                        _maccount125.AccountingMovement             = accountingMovement;
                                                        _maccount125.FK_Movements_Accounts_Funds    = manager.Selected;
                                                        _maccount125.FK_Movements_Accounts_Accounts = account125.Id;
                                                        if (subacct125 != null)
                                                        {
                                                            _maccount125.FK_Movements_Accounts_Subaccounts = subacct125.Id;
                                                        }
                                                        _maccount125.subaccount      = disbursement.client_id;
                                                        _maccount125.subaccount_type = 1;
                                                        _maccount125.debit           = 0;
                                                        _maccount125.credit          = Math.Round(toBeCollectedPrincipal, 2);

                                                        manager.My_db.Movements_Accounts.Add(_maccount125);

                                                        disbursementCollectionDetail.Movements_Accounts = _maccount125;
                                                    }

                                                    if (toBeCollectedProfitShare > 0)
                                                    {
                                                        Movements_Accounts _maccount128 = new Movements_Accounts();

                                                        _maccount128.AccountingMovement             = accountingMovement;
                                                        _maccount128.FK_Movements_Accounts_Funds    = manager.Selected;
                                                        _maccount128.FK_Movements_Accounts_Accounts = account128.Id;
                                                        if (subacct128 != null)
                                                        {
                                                            _maccount128.FK_Movements_Accounts_Subaccounts = subacct128.Id;
                                                        }
                                                        _maccount128.subaccount      = disbursement.client_id;
                                                        _maccount128.subaccount_type = 1;
                                                        _maccount128.debit           = 0;
                                                        _maccount128.credit          = Math.Round(toBeCollectedProfitShare, 2);

                                                        manager.My_db.Movements_Accounts.Add(_maccount128);

                                                        disbursementCollectionDetail.Movements_Accounts1 = _maccount128;
                                                    }

                                                    if (toBeCollectedDelayInterest > 0 | toBeCollectedOverdue > 0)
                                                    {
                                                        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           = 0;
                                                        _maccount130.credit          = Math.Round(toBeCollectedDelayInterest + toBeCollectedOverdue, 2);

                                                        manager.My_db.Movements_Accounts.Add(_maccount130);

                                                        disbursementCollectionDetail.Movements_Accounts2 = _maccount130;
                                                    }

                                                    totalPaid += toBeCollectedPrincipal + toBeCollectedProfitShare + toBeCollectedDelayInterest + toBeCollectedOverdue;

                                                    showGL = true;
                                                }
                                                else
                                                {
                                                    msg += "\rSome sub account is missing. No collection has been generated for disbursement with Id=\"" + disbursementId + "\".";
                                                }
                                            }
                                            else
                                            {
                                                msg += "\rCurrency is missing. No collection has been generated for disbursement with Id=\"" + disbursementId + "\".";
                                            }
                                        }
                                        else
                                        {
                                            msg += "\rDisbursement with Id=\"" + disbursementId.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.ExternalDebit          = 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("Account 125, 128 or 130 is missing."));
                                }
                            }
                            else
                            {
                                ErrorMessage.showErrorMessage(new Exception("No investment found for this contract."));
                            }
                        }
                        else
                        {
                            ErrorMessage.showErrorMessage(new Exception("No disbursement found."));
                        }
                    }

                    updateDisbursementList();
                }
                else
                {
                    ErrorMessage.showErrorMessage(new Exception("No movement allowed in closed period."));
                }
            }
            catch (Exception _ex)
            {
                ErrorMessage.showErrorMessage(_ex, false);
            }
        }
Пример #18
0
        private void generateInterest(bool forAll)
        {
            bool   errorsDetected = false;
            string errorMessages  = "";

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

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

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

            if (account840 != null && account470 != 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 <Loans_View> _loansToAccrue = new List <Loans_View>();

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

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

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

                                    if (toAcrue.end_date <= toAcrue.start_date)
                                    {
                                        errorsDetected = true;
                                        errorMessages += "\rReference " + toAcrue.reference + ": end <= start date.";
                                    }

                                    if (toAcrue.interest == 0)
                                    {
                                        errorsDetected = true;
                                        errorMessages += "\rReference " + toAcrue.reference + ": interest = 0.";
                                    }
                                }
                            }
                        }
                        else
                        {
                            foreach (ListViewItem _item in lvData.Items)
                            {
                                int loanId = 0;

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

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

                                    if (toAcrue.end_date <= toAcrue.start_date)
                                    {
                                        errorsDetected = true;
                                        errorMessages += "\rReference " + toAcrue.reference + ": end <= start date.";
                                    }

                                    if (toAcrue.interest == 0)
                                    {
                                        errorsDetected = true;
                                        errorMessages += "\rReference " + toAcrue.reference + ": interest = 0.";
                                    }
                                }
                            }
                        }

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

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

                            bool interestCreated = false;

                            decimal _totalInterest = 0;

                            bool someDataMissed = false;

                            foreach (Loans_View _loanToAccrue in _loansToAccrue)
                            {
                                Subaccount subacct840 = manager.My_db.Subaccounts.FirstOrDefault(x => x.FK_Subaccounts_Accounts == account840.Id && x.name == "Interest on loan");
                                Subaccount subacct470 = manager.My_db.Subaccounts.FirstOrDefault(x => x.FK_Subaccounts_Accounts == account470.Id && x.name == "Interest Loan");

                                if (subacct840 != null && subacct470 != null)
                                {
                                    LoanGeneratedInterestDetail interestDetail = manager.My_db.LoanGeneratedInterestDetails.FirstOrDefault(x => x.loan_id == _loanToAccrue.Id && x.generated_interest_date.Year == _date.Year && x.generated_interest_date.Month == _date.Month);

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

                                        if (fromDate == null)
                                        {
                                            fromDate = _loanToAccrue.start_date;
                                        }

                                        bool canContinueGeneratingInterest = true;

                                        decimal _interest = 0;

                                        DateTime toDate = dtpDate.Value <= _loanToAccrue.end_date ? dtpDate.Value : _loanToAccrue.end_date;

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

                                        if (days > 0)
                                        {
                                            _interest = Math.Round(_loanToAccrue.amount * _loanToAccrue.interest * days / _loanToAccrue.interest_base / 100, 2);
                                        }

                                        canContinueGeneratingInterest = toDate < _loanToAccrue.end_date;

                                        if (!canContinueGeneratingInterest)
                                        {
                                            Loan loan = manager.My_db.Loans.FirstOrDefault(x => x.Id == _loanToAccrue.Id);
                                            loan.can_generate_interest = 0;
                                        }

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

                                            _totalInterest += _interest;

                                            LoanGeneratedInterestDetail _detail = new LoanGeneratedInterestDetail();

                                            _detail.LoanGeneratedInterest = _generatedInterest;
                                            _detail.loan_id                 = _loanToAccrue.Id;
                                            _detail.generated_interest      = Math.Round(_interest, 2);
                                            _detail.generated_interest_date = toDate;

                                            manager.My_db.LoanGeneratedInterestDetails.Add(_detail);

                                            AccountingMovement _accountingMovement = new AccountingMovement();

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

                                            manager.My_db.AccountingMovements.Add(_accountingMovement);

                                            _detail.AccountingMovement = _accountingMovement;

                                            Movements_Accounts _maccount840 = new Movements_Accounts();

                                            _maccount840.AccountingMovement             = _accountingMovement;
                                            _maccount840.FK_Movements_Accounts_Funds    = manager.Selected;
                                            _maccount840.FK_Movements_Accounts_Accounts = account840.Id;
                                            if (subacct840 != null)
                                            {
                                                _maccount840.FK_Movements_Accounts_Subaccounts = subacct840.Id;
                                            }
                                            _maccount840.subaccount_type = 4;
                                            _maccount840.subaccount      = _loanToAccrue.lender_id;
                                            _maccount840.debit           = Math.Round(_interest, 2);
                                            _maccount840.credit          = 0;

                                            manager.My_db.Movements_Accounts.Add(_maccount840);

                                            Movements_Accounts _maccount470 = new Movements_Accounts();

                                            _maccount470.AccountingMovement             = _accountingMovement;
                                            _maccount470.FK_Movements_Accounts_Funds    = manager.Selected;
                                            _maccount470.FK_Movements_Accounts_Accounts = account470.Id;
                                            if (subacct470 != null)
                                            {
                                                _maccount470.FK_Movements_Accounts_Subaccounts = subacct470.Id;
                                            }
                                            _maccount470.subaccount_type = 4;
                                            _maccount470.subaccount      = _loanToAccrue.lender_id;
                                            _maccount470.debit           = 0;
                                            _maccount470.credit          = Math.Round(_interest, 2);

                                            manager.My_db.Movements_Accounts.Add(_maccount470);
                                        }
                                    }
                                    else
                                    {
                                        Console.WriteLine("Attempt to duplicate loan 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)
                            {
                                LoanGeneratedInterestForm generated_interest_form = new LoanGeneratedInterestForm();
                                generated_interest_form.generated_interest_id = _generatedInterest.Id;
                                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 840 or 470 were found."));
            }
        }
Пример #19
0
        private void cmdPay_Click(object sender, EventArgs e)
        {
            decimal totalPaid = 0;

            int investmentId = 0;

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

            AccountingMovement _accountingMovement = new AccountingMovement();

            try
            {
                if (manager.My_db.ClosedPeriods.FirstOrDefault(x => x.year == dtpPayDate.Value.Year && x.fund_id == manager.Selected) == null)
                {
                    if (account125 != null)
                    {
                        if (cbContract.SelectedValue != null &&
                            int.TryParse(cbContract.SelectedValue.ToString(), out investmentId))
                        {
                            if (lvDisbursements.SelectedItems.Count > 0)
                            {
                                DisbursementPayment dPayment = new DisbursementPayment();
                                dPayment.investment_id = investmentId;
                                dPayment.payment_date  = Convert.ToDateTime(dtpPayDate.Text);

                                manager.My_db.DisbursementPayments.Add(dPayment);

                                foreach (ListViewItem _item in lvDisbursements.SelectedItems)
                                {
                                    int disbursementId = 0;

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

                                        if (toPay != null)
                                        {
                                            toPay.pay_date = dPayment.payment_date;
                                            toPay.can_generate_interest = true;

                                            dPayment.Disbursements.Add(toPay);

                                            if (_accountingMovement.Id == 0)
                                            {
                                                _accountingMovement.FK_AccountingMovements_Funds = manager.Selected;
                                                _accountingMovement.description = "";
                                                _accountingMovement.date        = dPayment.payment_date;
                                                _accountingMovement.reference   = KeyDefinitions.NextAccountMovementReference(dtpPayDate.Value.Year);
                                                _accountingMovement.FK_AccountingMovements_Currencies = toPay.currency_id;
                                                _accountingMovement.original_reference = cbContract.SelectedIndex > 0 ? cbContract.Text : "";
                                                _accountingMovement.contract           = cbContract.SelectedText;

                                                manager.My_db.AccountingMovements.Add(_accountingMovement);

                                                dPayment.AccountingMovement = _accountingMovement;
                                            }

                                            Currency   currency   = manager.My_db.Currencies.FirstOrDefault(x => x.Id == toPay.currency_id && x.FK_Currencies_Funds == manager.Selected);
                                            Subaccount subacct125 = manager.My_db.Subaccounts.FirstOrDefault(x => x.FK_Subaccounts_Accounts == account125.Id && x.name == "INV " + currency.symbol);

                                            Movements_Accounts _maccount125 = new Movements_Accounts();

                                            _maccount125.AccountingMovement             = _accountingMovement;
                                            _maccount125.FK_Movements_Accounts_Funds    = manager.Selected;
                                            _maccount125.FK_Movements_Accounts_Accounts = account125.Id;
                                            if (subacct125 != null)
                                            {
                                                _maccount125.FK_Movements_Accounts_Subaccounts = subacct125.Id;
                                            }
                                            _maccount125.subaccount      = toPay.client_id;
                                            _maccount125.subaccount_type = 1;
                                            _maccount125.debit           = Math.Round(toPay.amount, 2);
                                            _maccount125.credit          = 0;

                                            totalPaid += toPay.amount;

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

                                lvDisbursements.SelectedIndices.Clear();

                                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.");
                                }

                                DisbursementPaymentForm disbursement_payments = new DisbursementPaymentForm();
                                disbursement_payments.paymentId = dPayment.id;
                                disbursement_payments.Show();
                            }
                            else
                            {
                                ErrorMessage.showErrorMessage(new Exception("No disbursement to pay was selected."));
                            }
                        }
                        else
                        {
                            ErrorMessage.showErrorMessage(new Exception("No contract selected."));
                        }
                    }
                    else
                    {
                        ErrorMessage.showErrorMessage(new Exception("Account 125 not found."));
                    }
                }
                else
                {
                    ErrorMessage.showErrorMessage(new Exception("No movement allowed in closed period."));
                }
            }
            catch (Exception _ex)
            {
                Console.WriteLine("Error in DisbursementsForm.cmdPay_Click: " + _ex.Message);
                ErrorMessage.showErrorMessage(_ex, false);
            }

            loadDisbursements();
        }
Пример #20
0
        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);
            }
        }