Exemplo n.º 1
0
        private Disbursement getBookingFromGUI()
        {
            try
            {
                Disbursement _booking = new Disbursement();

                _booking.fund_id              = manager.Selected;
                _booking.investment_id        = investment.Id;
                _booking.contract             = investment.contract;
                _booking.is_booking           = true;
                _booking.client_id            = clientId;
                _booking.currency_id          = currencyId;
                _booking.exchange_rate        = 1;
                _booking.underlying_debtor_id = underlayingDebtor;
                _booking.bank_risk_id         = bankRiskId;
                _booking.sector_id            = sectorId;
                _booking.pay_date             = payDate;
                _booking.shipment_id          = shipmentId;

                if (fEditMode && lvBooking.SelectedIndices.Count > 0)
                {
                    _booking              = bookings[lvBooking.SelectedIndices[0]];
                    fAmountRemaining     += _booking.amount;
                    fProfitShareRemainig += _booking.profit_share;
                }

                decimal amountToDecrease      = Convert.ToDecimal(txtAmount.Text);
                decimal profitShareToDecrease = Convert.ToDecimal(txtProfitShare.Text);
                decimal delayInterest         = Convert.ToDecimal(txtDelayInterest.Text);

                _booking.amount          = Math.Round(amountToDecrease, 2);
                _booking.profit_share    = Math.Round(profitShareToDecrease, 2);
                _booking.date            = Convert.ToDateTime(dtpStartingDate.Text);
                _booking.collection_date = Convert.ToDateTime(dtpCollectionDate.Text);
                _booking.number          = txtNumber.Text;
                _booking.delay_interest  = Math.Round(delayInterest, 2);

                fAmountRemaining     -= amountToDecrease;
                fProfitShareRemainig -= profitShareToDecrease;

                _booking.collected             = false;
                _booking.can_generate_interest = true;

                _booking.has_bookings = false;

                return(_booking);
            }
            catch (Exception)
            {
                return(null);
            }
        }
Exemplo n.º 2
0
        private void checkEnablingAddBookingButton()
        {
            try
            {
                decimal _selectedAmount          = decimal.Parse(txtAmount.Text);
                decimal _selectedProfitShare     = decimal.Parse(txtProfitShare.Text);
                decimal _selectedDelayedInterest = decimal.Parse(txtDelayInterest.Text);

                if (!fEditMode)
                {
                    cmdAddBooking.Enabled = txtNumber.Text.Trim() != "" &&
                                            _selectedAmount >= 0 &&
                                            _selectedProfitShare >= 0 &&
                                            _selectedDelayedInterest >= 0 &&
                                            (_selectedAmount > 0 || _selectedProfitShare > 0 || _selectedDelayedInterest > 0);
                }
                else
                {
                    Disbursement toModify = bookings[lvBooking.SelectedIndices[0]];

                    decimal _amount          = 0;
                    decimal _profitShare     = 0;
                    decimal _delayedInterest = 0;

                    foreach (Disbursement booking in bookings)
                    {
                        _amount          += booking.amount;
                        _profitShare     += booking.profit_share;
                        _delayedInterest += booking.delay_interest ?? 0;
                    }

                    _amount          -= toModify.amount - _selectedAmount;
                    _profitShare     -= toModify.profit_share - _selectedProfitShare;
                    _delayedInterest -= (toModify.delay_interest ?? 0) - _selectedDelayedInterest;

                    cmdAddBooking.Enabled = txtNumber.Text.Trim() != "" &&
                                            _selectedAmount >= 0 &&
                                            _selectedProfitShare >= 0 &&
                                            _delayedInterest >= 0 &&
                                            (_selectedAmount > 0 || _selectedProfitShare > 0 || _selectedDelayedInterest > 0) &&
                                            fAmountRemaining - _amount >= 0 &&
                                            fProfitShareRemainig - _profitShare >= 0
                    ;
                }
            }
            catch (Exception _ex)
            {
                Console.WriteLine("Error in AddendumsForm.checkEnablingAddDisbursementButton: " + _ex.Message);
                cmdAddBooking.Enabled = false;
            }
        }
Exemplo n.º 3
0
        private void lvBooking_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                if (lvBooking.SelectedIndices.Count > 0)
                {
                    if (lvBooking.SelectedIndices[0] == lvBooking.Items.Count - 1)
                    {
                        lvBooking.SelectedIndices.Clear();
                    }
                    else
                    {
                        Disbursement selected = bookings[lvBooking.SelectedIndices[0]];
                    }
                }

                if (lvBooking.SelectedIndices.Count > 0)
                {
                    fEditMode = true;
                    cmdDeleteBooking.Enabled = true;
                    cmdAddBooking.Enabled    = false;
                    cmdCancel.Visible        = true;

                    Disbursement selected = bookings[lvBooking.SelectedIndices[0]];

                    txtAmount.Text = String.Format("{0:0.00}", selected.amount);

                    txtProfitShare.Text   = String.Format("{0:0.00}", selected.profit_share);
                    txtDelayInterest.Text = String.Format("{0:0.00}", selected.delay_interest);
                    txtNumber.Text        = selected.number;

                    calculate_total_collection();

                    dtpStartingDate.Value   = selected.date;
                    dtpCollectionDate.Value = selected.collection_date;
                }
                else
                {
                    fEditMode = false;
                    cmdDeleteBooking.Enabled = false;
                    cmdCancel.Visible        = false;
                }

                checkEnablingAddBookingButton();
            }
            catch (Exception _ex)
            {
                Console.WriteLine("Error in AddendumsForm.lvBooking_SelectedIndexChanged: " + _ex.Message);
            }
        }
Exemplo n.º 4
0
        private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                checkEnablingAddDisbursementButton();

                if (!cmdAddDisbursement.Enabled)
                {
                    return;
                }

                float exchangeRate = 0;

                if (float.TryParse(txtExchangeRate.Text, out exchangeRate) && exchangeRate > 0)
                {
                    if (!duplicatedDisbursementNumber())
                    {
                        Disbursement toAdd = getDisbursementFromGUI();

                        if (fEditMode)
                        {
                            disbursements.RemoveAt(lvDisbursements.SelectedIndices[0]);
                        }

                        addDisbursement(toAdd);

                        loadDisbursements();

                        cmdCancel_Click(null, null);

                        checkEnablingAddInvestmentButton();
                    }
                    else
                    {
                        MessageBox.Show("Duplicated disbursement number.");
                    }
                }
                else
                {
                    MessageBox.Show("Error in exchage rate data.");
                }
            }
            catch (Exception _ex)
            {
                Console.WriteLine("Error in InvestmentsForm.button2_Click: " + _ex.Message);
            }
        }
Exemplo n.º 5
0
        private void cmdAddBooking_Click(object sender, EventArgs e)
        {
            try
            {
                checkEnablingAddBookingButton();

                if (!cmdAddBooking.Enabled)
                {
                    return;
                }

                if (!duplicatedBookingNumber())
                {
                    Disbursement toAdd = getBookingFromGUI();

                    if (fEditMode)
                    {
                        bookings.RemoveAt(lvBooking.SelectedIndices[0]);
                    }

                    addBooking(toAdd);

                    loadBookings();

                    cmdCancel_Click(null, null);

                    checkEnablingBookButton();
                }
                else
                {
                    MessageBox.Show("Duplicated disbursement number.");
                }
            }
            catch (Exception _ex)
            {
                Console.WriteLine("Error in AddendumsForm.cmdAddBooking_Click: " + _ex.Message);
            }

            checkEnablingAddBookingButton();

            calculate_total_collection();
        }
Exemplo n.º 6
0
        private void cmdDeleteBooking_Click(object sender, EventArgs e)
        {
            try
            {
                if (lvBooking.SelectedIndices.Count > 0)
                {
                    Disbursement booking = bookings[lvBooking.SelectedIndices[0]];
                    fAmountRemaining     += booking.amount;
                    fProfitShareRemainig += booking.profit_share;
                    bookings.RemoveAt(lvBooking.SelectedIndices[0]);
                }

                loadBookings();

                checkEnablingBookButton();

                cmdCancel_Click(null, null);
            }
            catch (Exception _ex)
            {
                Console.WriteLine("Error in AddendumsForm.cmdDeleteBooking_Click: " + _ex.Message);
            }
        }
Exemplo n.º 7
0
        private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                if (e.RowIndex >= 0 && e.RowIndex < dataGridView1.RowCount)
                {
                    int disbursementId = 0;

                    if (int.TryParse(dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString(), out disbursementId))
                    {
                        Disbursement disbToEdit = manager.My_db.Disbursements.FirstOrDefault(x => x.Id == disbursementId);

                        if (disbToEdit != null)
                        {
                            Investment invToEdit = disbToEdit.Investment;

                            if (invToEdit != null)
                            {
                                InvestmentsForm invForm = new InvestmentsForm();

                                invForm.EditingExistingInvestment = true;
                                invForm.InvestmenToEdit           = invToEdit;
                                invForm.StartPosition             = FormStartPosition.CenterScreen;

                                invForm.ShowDialog();

                                loadInvestments();
                            }
                        }
                    }
                }
            }
            catch (Exception _ex)
            {
                ErrorMessage.showErrorMessage(_ex);
            }
        }
Exemplo n.º 8
0
        private void addBooking(Disbursement toAdd)
        {
            if (toAdd != null)
            {
                int _index = -1;

                for (int i = 0; i < bookings.Count; i++)
                {
                    Disbursement _item = bookings[i];

                    if (_item.date > toAdd.date)
                    {
                        bookings.Insert(i, toAdd);
                        _index = i;
                        break;
                    }
                }

                if (_index == -1)
                {
                    bookings.Add(toAdd);
                }
            }
        }
Exemplo n.º 9
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();
        }
        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);
            }
        }
        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."));
            }
        }
Exemplo n.º 12
0
        private Disbursement getDisbursementFromGUI()
        {
            try
            {
                Disbursement _disbursement = new Disbursement();

                _disbursement.has_bookings   = false;
                _disbursement.is_booking     = false;
                _disbursement.delay_interest = 0;


                float exchangeRate = 0;

                if (float.TryParse(txtExchangeRate.Text, out exchangeRate) && exchangeRate > 0)
                {
                    if (fEditMode && lvDisbursements.SelectedIndices.Count > 0)
                    {
                        _disbursement = disbursements[lvDisbursements.SelectedIndices[0]];
                    }

                    _disbursement.fund_id = manager.Selected;

                    int?bankId = null;

                    if (cbBank.SelectedValue.ToString() != "0")
                    {
                        bankId = Convert.ToInt32(cbBank.SelectedValue);
                    }

                    int?underDebtorId = null;

                    if (cbUnderlyingDebtor.SelectedValue.ToString() != "0")
                    {
                        underDebtorId = Convert.ToInt32(cbUnderlyingDebtor.SelectedValue);
                    }

                    int?shipmentId = null;

                    if (cbShipment.SelectedValue.ToString() != "0")
                    {
                        shipmentId = Convert.ToInt32(cbShipment.SelectedValue);
                    }

                    _disbursement.exchange_rate = exchangeRate;
                    _disbursement.amount        = Math.Round(Convert.ToDecimal(txtAmount.Text) / (decimal)exchangeRate, 2);
                    _disbursement.profit_share  = Math.Round(Convert.ToDecimal(txtProfitShare.Text) / (decimal)exchangeRate, 2);
                    _disbursement.currency_id   = Convert.ToInt32(cbCurrency.SelectedValue);

                    _disbursement.bank_risk_id = bankId;

                    _disbursement.client_id = Convert.ToInt32(cbClient.SelectedValue);

                    _disbursement.underlying_debtor_id = underDebtorId;

                    _disbursement.date                  = Convert.ToDateTime(dtpDisbursementDate.Text);
                    _disbursement.collection_date       = Convert.ToDateTime(dtpCollectionDate.Text);
                    _disbursement.sector_id             = Convert.ToInt32(cbSector.SelectedValue);
                    _disbursement.number                = txtNumber.Text;
                    _disbursement.can_generate_interest = false;

                    _disbursement.TextClient           = cbClient.Text;
                    _disbursement.TextUnderlyingDebtor = cbUnderlyingDebtor.Text;

                    _disbursement.Euro_collection = _disbursement.amount + _disbursement.profit_share;

                    _disbursement.shipment_id = shipmentId;

                    _disbursement.ItemsIds.Clear();

                    foreach (int _itemId in fItemIds)
                    {
                        _disbursement.AddItemId(_itemId);
                    }

                    _disbursement.collected = false;

                    return(_disbursement);
                }
                else
                {
                    return(null);
                }
            }
            catch (Exception)
            {
                return(null);
            }
        }
Exemplo n.º 13
0
        private void lvDisbursements_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                if (lvDisbursements.SelectedIndices.Count > 0)
                {
                    if (lvDisbursements.SelectedIndices[0] == lvDisbursements.Items.Count - 1)
                    {
                        lvDisbursements.SelectedIndices.Clear();
                    }
                    else
                    {
                        Disbursement selected = disbursements[lvDisbursements.SelectedIndices[0]];

                        if (selected.pay_date.HasValue)
                        {
                            lvDisbursements.SelectedIndices.Clear();
                            MessageBox.Show("This disbursement has been already paid.");
                        }
                    }
                }

                if (lvDisbursements.SelectedIndices.Count > 0)
                {
                    fEditMode = true;
                    cmdDeleteDisbursement.Enabled = true;
                    cmdAddDisbursement.Enabled    = true;
                    cmdAddDisbursement.Text       = "Save Disbursement";
                    cmdCancel.Visible             = true;

                    Disbursement selected = disbursements[lvDisbursements.SelectedIndices[0]];

                    txtAmount.Text = String.Format("{0:0.00}", selected.amount * (decimal)selected.exchange_rate);

                    if (selected.currency_id > 0)
                    {
                        for (int i = 0; i < cbCurrency.Items.Count; i++)
                        {
                            cbCurrency.SelectedIndex = i;

                            if (cbCurrency.SelectedValue.ToString() == selected.currency_id.ToString())
                            {
                                break;
                            }
                        }
                    }

                    txtExchangeRate.Text       = String.Format("{0:0.0000000}", selected.exchange_rate);
                    txtProfitShare.Text        = String.Format("{0:0.00}", selected.profit_share);
                    txtNumber.Text             = selected.number;
                    txtTotalToBeCollected.Text = String.Format("{0:0.00}", selected.Euro_collection);

                    if (selected.client_id > 0)
                    {
                        for (int i = 0; i < cbClient.Items.Count; i++)
                        {
                            cbClient.SelectedIndex = i;

                            if (cbClient.SelectedValue.ToString() == selected.client_id.ToString())
                            {
                                break;
                            }
                        }
                    }

                    if (selected.underlying_debtor_id > 0)
                    {
                        for (int i = 0; i < cbUnderlyingDebtor.Items.Count; i++)
                        {
                            cbUnderlyingDebtor.SelectedIndex = i;

                            if (cbUnderlyingDebtor.SelectedValue.ToString() == selected.underlying_debtor_id.ToString())
                            {
                                break;
                            }
                        }
                    }

                    if (selected.bank_risk_id > 0)
                    {
                        for (int i = 0; i < cbBank.Items.Count; i++)
                        {
                            cbBank.SelectedIndex = i;

                            if (cbBank.SelectedValue.ToString() == selected.bank_risk_id.ToString())
                            {
                                break;
                            }
                        }
                    }

                    if (selected.shipment_id > 0)
                    {
                        Shipment shipment = manager.My_db.Shipments.FirstOrDefault(x => x.Id == selected.shipment_id);

                        if (shipment != null)
                        {
                            letter_of_credits letter = manager.My_db.letter_of_credits.FirstOrDefault(x => x.Id == shipment.LetterOfCreditId);

                            if (letter != null)
                            {
                                this.letter_of_creditsTableAdapter.FillByBank(this.fundsDBDataSet.letter_of_credits, manager.Selected, int.Parse(cbBank.SelectedValue.ToString()));

                                for (int i = 0; i < cbLetterOfCredit.Items.Count; i++)
                                {
                                    cbLetterOfCredit.SelectedIndex = i;

                                    if (cbLetterOfCredit.SelectedValue.ToString() == letter.Id.ToString())
                                    {
                                        this.shipmentsTableAdapter.FillByLetterWithEmpty(this.fundsDBDataSet.Shipments, int.Parse(cbLetterOfCredit.SelectedValue.ToString()));

                                        for (int j = 0; j < cbShipment.Items.Count; j++)
                                        {
                                            cbShipment.SelectedIndex = j;

                                            if (cbShipment.SelectedValue.ToString() == shipment.Id.ToString())
                                            {
                                                break;
                                            }
                                        }

                                        break;
                                    }
                                }
                            }
                        }
                    }

                    if (selected.sector_id > 0)
                    {
                        for (int i = 0; i < cbSector.Items.Count; i++)
                        {
                            cbSector.SelectedIndex = i;

                            if (cbSector.SelectedValue.ToString() == selected.sector_id.ToString())
                            {
                                break;
                            }
                        }
                    }

                    fItemIds.Clear();
                    lbISelectedItems.Items.Clear();
                    lbISelectedItems.Text = "";

                    foreach (int itemId in selected.ItemsIds)
                    {
                        fItemIds.Add(itemId);

                        for (int i = 0; i < cbItems.Items.Count; i++)
                        {
                            cbItems.SelectedIndex = i;

                            if (cbItems.SelectedValue.ToString() == itemId.ToString())
                            {
                                string name = ((FundsManager.FundsDBDataSet.ItemsRow)((System.Data.DataRowView)cbItems.Items[i]).Row).name;
                                lbISelectedItems.Items.Add(name);
                            }
                        }
                    }

                    dtpCollectionDate.Value = selected.collection_date;

                    dtpDisbursementDate.Value = selected.date;
                }
                else
                {
                    fEditMode = false;
                    cmdDeleteDisbursement.Enabled = false;
                    cmdAddDisbursement.Text       = "Add Disbursement";
                    cmdCancel.Visible             = false;
                }
            }
            catch (Exception _ex)
            {
                Console.WriteLine("Error in InvestmentsForm.lvDisbursements_SelectedIndexChanged: " + _ex.Message);
            }
        }
Exemplo n.º 14
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."));
            }
        }
Exemplo n.º 15
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);
            }
        }