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