protected void grdBill_ItemCommand(object source, Telerik.Web.UI.GridCommandEventArgs e)
    {
        if (e.CommandName == "RowClick" && e.Item is GridDataItem)
        {
            Context.Items["BillId"] = e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["BillId"];
            Response.Redirect("Bill.aspx");
        }
        else if (e.CommandName == "Delete" && e.Item.ItemType != GridItemType.GroupFooter)
        {
            var financialManager = new FinancialManager(this);
            if (e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["BillId"] != null)
            {
                var bill = financialManager.GetBill(Convert.ToInt32(e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["BillId"]), Company.CompanyId);

                if (bill.ExpenditureAuthorizations.Any())
                {
                    ClientScript.RegisterClientScriptBlock(this.GetType(), "", "alert('O registro não pode ser apagado pois há outros registros de autorização de despesas associados!')", true);
                    return;
                }

                financialManager.DeleteBill(Convert.ToInt32(e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["BillId"]), Company.CompanyId);

            }
            grdBill.DataBind();
            if (grdBill.Items.Count == 0)
                grdBill.ShowFooter = false;
        }
    }
    protected void grdInvoices_ItemCommand(object source, Telerik.Web.UI.GridCommandEventArgs e)
    {
        if (e.CommandName == "RowClick" && e.Item is GridDataItem)
        {
            Context.Items["InvoiceId"] = e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["InvoiceId"];
            Server.Transfer("Invoice.aspx");
        }
        else if (e.CommandName == "Delete" && e.Item.ItemType != GridItemType.GroupFooter)
        {
            var financialManager = new FinancialManager(this);
            try
            {
                if (e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["InvoiceId"] != null)
                    financialManager.DeleteInvoice(Convert.ToInt32(e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["InvoiceId"]), Company.CompanyId);
                grdInvoices.DataBind();
            }
            catch (System.Data.SqlClient.SqlException err)
            {
                DataManager.Rollback();
                if (err.ErrorCode.Equals(Convert.ToInt32("0x80131904", 16)))
                    ShowError(Resources.Exception.DeletingRegisterWithForeignKey);
                e.Canceled = true;

            }

            if (grdInvoices.Items.Count == 0)
                Response.Redirect("Invoices.aspx");

        }
    }
        /// <summary>
        /// Save the entity
        /// </summary>
        /// <param name="entity"></param>
        public void Save(Company company, Statement statement)
        {
            //
            // Create invoice for the related customer
            //
            statement.StatementTotal = statement.StatementItems.Sum(x => x.Value);
            var list = new List<Parcel>();
            list.Add(new Parcel()
            {
                DueDate = statement.PeriodEnd.AddDays(15),
                Amount = statement.StatementTotal
            });

            var financialManager = new FinancialManager(this);
            var invoice = ConvertStatementToInvoice(company, statement);
            financialManager.Insert(invoice, list);

            //
            // Update data
            //
            statement.Invoice = invoice;
            company.NextStatementDueDate = company.NextStatementDueDate.AddMonths(1);

            //
            // Save statement
            //
            if (statement.StatementId > 0)
            {
                var original = GetStatement(statement.StatementId);
                original.CopyPropertiesFrom(statement);
            }
            else
                DbContext.Statements.InsertOnSubmit(statement);


            DbContext.SubmitChanges();
        }
        /// <summary>
        /// this method calculates the amounts of bill and invoices
        /// </summary>
        /// <param name="companyId"></param>
        /// <param name="beginDate"></param>
        /// <param name="endDate"></param>
        /// <param name="accountId"></param>
        /// <returns></returns>
        private Decimal GetAccountAmountByPeriod(Int32 companyId, DateTime? beginDate, DateTime? endDate,
                                                 Int32 accountId)
        {
            var financialManager = new FinancialManager(this);

            return Decimal.Subtract(
                financialManager.GetRegisteredInvoiceAmountByPeriod(companyId, beginDate, endDate, accountId),
                financialManager.GetRegisteredBillAmountByPeriod(companyId, beginDate, endDate, accountId));
        }
        /// <summary>
        /// This method non authorizes the especified expenditures
        /// </summary>
        /// <param name="expenditureAuthorizationIds"></param>
        public void NonAuthorizeExpenditures(List<Int32> expenditureAuthorizationIds)
        {
            var financialManager = new FinancialManager(this);
            var billId = 0;

            foreach (var expenditureAuthorizationId in expenditureAuthorizationIds)
            {
                var expenditureAuthorization = GetExpenditureAuthorization(expenditureAuthorizationId);

                if (expenditureAuthorization.BillId.HasValue)
                {
                    billId = expenditureAuthorization.BillId.Value;
                    expenditureAuthorization.BillId = null;

                    financialManager.DeleteBill(billId, expenditureAuthorization.CompanyId);
                }
                SetAuthorizationStatusInExpenditure(expenditureAuthorization, true);
            }
        }
        /// <summary>
        /// This method authorizes specified expenditures generating a bill related        
        /// </summary>
        /// <param name="companyId"></param>
        /// <param name="expenditureAuthorizationIds"></param>
        public void AuthorizeExpenditures(Int32 companyId, List<Int32> expenditureAuthorizationIds)
        {
            var financialManager = new FinancialManager(this);

            //
            // Creating Parcel
            //

            var parcel = new Parcel();

            decimal parcelAmount = 0;
            parcel.CompanyId = companyId;
            parcel.Description = "1/1";

            var predictableDate = DateTime.Now.AddMonths(1);
            parcel.DueDate = new DateTime(predictableDate.Year, predictableDate.Month, 5);

            //
            // Creating Bill
            //

            var bill = new Bill();

            bill.CompanyId = companyId;
            bill.Description = "Despesas de funcionários";

            var listParcels = new List<Parcel>();
            listParcels.Add(parcel);
            financialManager.Insert(bill, listParcels);

            foreach (var expenditureAuthorizationId in expenditureAuthorizationIds)
            {
                var expenditureAuthorization = GetExpenditureAuthorization(expenditureAuthorizationId);
                expenditureAuthorization.BillId = bill.BillId;

                SetAuthorizationStatusInExpenditure(expenditureAuthorization, false);
                parcelAmount += expenditureAuthorization.Amount;
            }

            parcel.Amount = parcelAmount;

            DbContext.SubmitChanges();
        }
    protected void btnAdd_Click(object sender, EventArgs e)
    {
        if (ucCurrFieldBalance.Text == "0,00")
        {
            litErrorMessage.Visible = true;
            litErrorMessage.Text = "<font color='red'> Saldo a ser ajustado não pode ser zero! </font>";
            return;
        }


        var invoice = new Invoice();
        var parcel = new Parcel();
        var financialManager = new FinancialManager(this);

        invoice.CompanyId = Company.CompanyId;
        invoice.EntryDate = DateTime.Now;

        parcel.EffectedDate = SqlDateTime.MinValue.Value;
        parcel.DueDate = SqlDateTime.MinValue.Value;
        parcel.OperationDate = SqlDateTime.MinValue.Value;

        invoice.Description = "(Conta a receber através de acerto de saldo)";

        parcel.Amount = ucCurrFieldBalance.CurrencyValue.Value;
        parcel.EffectedAmount = parcel.Amount;

        var parcels = new List<Parcel>();
        parcels.Add(parcel);

        financialManager.Insert(invoice, parcels);

        ClientScript.RegisterClientScriptBlock(this.GetType(), "", "alert('Operação realizada com sucesso!')", true);
        ucCurrFieldBalance.CurrencyValue = null;
        litErrorMessage.Visible = false;
        CalculateBalance();
    }
    protected void btnExport_Click(object sender, EventArgs e)
    {
        if (rbtExportAutomaticDebit.Checked)
        {
            AccountManager accountManager = new AccountManager(this);
            List<Parcel> lstParcels = new ParcelsManager(this).GetInvoiceParcelsByPeriodInAcount(Company.CompanyId, DateTime.Now.Sql2005MinValue(), DateTime.Now, null).ToList();
            Response.Clear();
            Response.ContentType = "text/rtf";
            string headerValue = "attachment;filename=Débito.rtf";
            Response.AddHeader("content-disposition", headerValue);
            Response.ContentEncoding = System.Text.Encoding.Default;
            // Response.Write(accountManager.GenerateAutomaticDebitFile(Company, accountManager.GetAccount(Convert.ToInt32(cboAccount.SelectedValue), Company.CompanyId), lstParcels, 1));
            Response.End();
        }
        else
        {
            try
            {
                var financialManager = new FinancialManager(this);
                Response.Clear();
                financialManager.GerarArquivoRemessa(Company.CompanyId, Convert.ToInt32(cboAccount.SelectedValue), DateTime.MinValue.Sql2005MinValue(), DateTime.MaxValue, Response.OutputStream);
                Response.ContentType = "text/txt";
                string headerValue = "attachment;filename=" + "Arquivo.txt";
                Response.AddHeader("content-disposition", headerValue);
                // Response.Write(Response.OutputStream);
                Response.End();
            }
            catch (Exception ex)
            {

                ShowError(Resources.Exception.InvalidBank);
            }

        }

    }
    /// <summary>
    /// this region contains all functions
    /// </summary>
    #region functions
    /// <summary>
    /// this function show the Invoice
    /// </summary>
    protected void showInvoice(Int32 invoiceId)
    {
        financialManager = new FinancialManager(this);
        Invoice invoice = financialManager.GetInvoice(Company.CompanyId, invoiceId);
        Contract contract;

        txtSource.Text = invoice.Description;

        if (invoice.AccountingPlanId != null)
            cboAccountPlan.SelectedValue = invoice.AccountingPlanId.ToString();
        if (invoice.CostCenterId != null)
            cboCostCenter.SelectedValue = invoice.CostCenterId.Value.ToString();
        SelCustomer.ShowCustomer(invoice.Customer);
        Sale sale = invoice.Sales.FirstOrDefault();
        if (sale != null)
        {
            lblSale.Visible = true;
            lnkSale.Text = sale.SaleId.ToString();
            lnkSale.NavigateUrl = "../POS/SaleViewer.aspx?SaleId=" + sale.SaleId;

            if (sale.ReceiptId.HasValue)
            {
                lblReceipt.Visible = true;
                lnkReceipt.Text = sale.Receipt.ReceiptNumber.ToString();
                lnkReceipt.NavigateUrl = "../Accounting/Receipt.aspx?ReceiptId=" + Convert.ToString(sale.ReceiptId);
            }
            pnlInvoiceSource.Visible = true;
        }

        contract = invoice.Contracts.FirstOrDefault();
        if (contract != null)
        {
            lblContract.Visible = true;
            lnkContract.Text = String.IsNullOrEmpty(contract.ContractNumber) ? Convert.ToString(contract.ContractId) : contract.ContractNumber;
            lnkContract.NavigateUrl = "Contract.aspx?ContractId=" + Convert.ToString(contract.ContractId);
            pnlInvoiceSource.Visible = true;
        }

        pnlInvoiceSource.Visible = true;
        ucParcels.DataSource = invoice.Parcels.ToList();
    }
    private void ExportInvoiceDocument(Invoice invoice, Int32 parcelId, string fileName, Int32 documentTemplateId)
    {
        var financialManager = new FinancialManager(this);

        //
        // Clean buffers of response to not send headers of ASPX pages
        // 
        Response.Clear();
        Response.ContentType = "text/doc";
        //
        // Sets the header that tells to browser to download not show in the screen
        // 
        Response.AddHeader("content-disposition", "attachment;filename=" + fileName + ".rtf");
        //
        // Indicate that file format will be the same model
        // 
        Response.ContentEncoding = System.Text.Encoding.Default;

        //
        // Apply the changes from model, changing []'s for the content
        // 
        Response.Write(financialManager.ApplyInvoiceTemplate(invoice, parcelId, documentTemplateId));

        //
        // Cut the page process to not merge the model content to the page HTML
        // 
        Response.End();
    }
    private Invoice SaveInvoice()
    {
        financialManager = new FinancialManager(this);
        Invoice original_invoice = new Invoice();
        Invoice invoice = new Invoice();

        if (Page.ViewState["InvoiceId"] != null)
        {
            original_invoice = financialManager.GetInvoice(Company.CompanyId, Convert.ToInt32(Page.ViewState["InvoiceId"]));
            invoice.CopyPropertiesFrom(original_invoice);
        }

        invoice.Description = txtSource.Text;
        invoice.CompanyId = Company.CompanyId;
        invoice.CostCenterId = Convert.ToInt32(cboCostCenter.SelectedValue);

        if (Page.ViewState["CustomerId"] != null)
            invoice.CustomerId = Convert.ToInt32(Page.ViewState["CustomerId"]);

        //accountPlan
        if (!String.IsNullOrEmpty(cboAccountPlan.SelectedValue))
            invoice.AccountingPlanId = Convert.ToInt32(cboAccountPlan.SelectedValue);

        if (Page.ViewState["InvoiceId"] != null)
        {
            invoice.ModifiedByUser = User.Identity.UserName;
            financialManager.Update(original_invoice, invoice, ucParcels.DataSource);
        }
        else
        {
            invoice.CreatedByUser = User.Identity.UserName;
            financialManager.Insert(invoice, ucParcels.DataSource);
        }


        if (Page.ViewState["InvoiceId"] != null)
            return original_invoice;
        else
            return invoice;
    }
        /// <summary>
        /// This method cancels a sale and return the products to inventory
        /// </summary>
        /// <param name="saleId"></param>
        /// <param name="matrixId"></param>
        public void CancelSale(int saleId, int matrixId, Int32 userId)
        {
            var inventoryManager = new InventoryManager(this);
            var receiptManager = new ReceiptManager(this);
            var financialManager = new FinancialManager(this);
            var parcelManager = new ParcelsManager(this);

            Sale sale = GetSale(matrixId, saleId);
            sale.IsCanceled = true;

            if (sale.ReceiptId != null)
            {
                Receipt receipt = receiptManager.GetReceipt((int)sale.ReceiptId, sale.CompanyId);
                sale.ReceiptId = null;
                receiptManager.DeleteReceipt(receipt);
                receipt.IsCanceled = true;
            }

            sale.InvoiceId = null;

            //
            // return the products to inventory
            //
            foreach (SaleItem saleItem in sale.SaleItems)
            {
                if (saleItem.ProductId != null)
                {
                    Inventory inventory = inventoryManager.GetProductInventory(saleItem.CompanyId,
                                                                               (int)saleItem.ProductId,
                                                                               (int)sale.DepositId);
                    if (inventory != null)
                        inventoryManager.StockDeposit(inventory, null, userId);
                }
            }

            //
            // Delete the invoice of sale
            //
            if (sale.InvoiceId.HasValue)
                financialManager.DeleteInvoice((int)sale.InvoiceId, sale.CompanyId);

            DbContext.SubmitChanges();
        }
        /// <summary>
        /// this method save the invoice created by Sale
        /// </summary>
        /// <param name="sale"></param>
        private void SaveSaleInvoice(Sale sale, Invoice invoice, List<Parcel> lstParcels)
        {
            //
            // Save Invoice
            //
            var financialManager = new FinancialManager(this);
            sale.InvoiceId = financialManager.InsertRetrievingId(invoice);
            DbContext.SubmitChanges();


            //
            // Save Parcels
            //
            var parcelsManager = new ParcelsManager(this);
            var accountManager = new AccountManager(this);

            var firstParcel = lstParcels.FirstOrDefault();
            var condition = accountManager.GetFinancierConditionByParcelCount(firstParcel.CompanyId, firstParcel.FinancierOperationId.Value, lstParcels.Count());

            foreach (Parcel parcel in lstParcels)
            {
                parcel.InvoiceId = invoice.InvoiceId;
                parcelsManager.Insert(parcel, condition);
            }


        }
    private void SaveBill(object sender)
    {
        var bill = new Bill();

        bill.CopyPropertiesFrom(OriginalBill);

        bill.CompanyId = Company.CompanyId;
        // Numero da Nota fiscal do fornecedor
        bill.DocumentNumber = txtDocumentNumber.Text;
       
        bill.Description = txtDescription.Text;
        bill.CostCenterId = Convert.ToInt32(cboCostCenter.SelectedValue);
        bill.EntryDate = DateTime.Now;



        //supplier
        if (Page.ViewState["SupplierId"] != null)
            bill.SupplierId = Convert.ToInt32(Page.ViewState["SupplierId"]);
        else
            bill.SupplierId = null;

        //accountPlan
        if (!String.IsNullOrEmpty(cboAccountPlan.SelectedValue))
            bill.AccountingPlanId = Convert.ToInt32(cboAccountPlan.SelectedValue);

        //documentType
        if (rbtGuia.Checked)
            bill.DocumentType = (Int32)DocumentType.Guia;
        else if (rbtReceipt.Checked)
            bill.DocumentType = (Int32)DocumentType.receipt;
        else if (rbtOthers.Checked)
            bill.DocumentType = (Int32)DocumentType.others;

        var billManager = new FinancialManager(this);

        //bill.Parcels = ucParcels.DataSource;

        if (Page.ViewState["BillId"] != null)
        {
            bill.ModifiedByUser = User.Identity.UserName;
            billManager.Update(OriginalBill, bill, ucParcels.DataSource);
        }
        else
        {
            bill.CreatedByUser = User.Identity.UserName;
            billManager.Insert(bill, ucParcels.DataSource);
            Context.Items["PostBack"] = Context.Items["BillId"] = bill.BillId;
        }
        ucParcels.Clear();

        if ((sender as Button).ID == "btnNew")
            Response.Redirect("Bill.aspx");
        else
            Response.Redirect("Bills.aspx");
    }