예제 #1
0
        /// <summary>
        /// Generate All Invoices to a contract
        /// </summary>
        /// <param name="contract"></param>
        /// <returns></returns>
        //private void GenerateLoanFromContract(Contract contract, int qtdParcels)
        //{
        //    AccountManager accountManager = new AccountManager(this);


        //    //contract.FinancierOperation = accountManager.GetFinancierOperation(contract.CompanyId, Convert.ToInt32(contract.FinancierOperationId));

        //    contract.FinancierCondition = accountManager.GetFinancierConditionByParcelCount(contract.CompanyId, Convert.ToInt32(contract.FinancierOperationId), qtdParcels) ?? new FinancierCondition();


        //    if (contract.FinancierOperation.Brokerage.HasValue && contract.FinancierOperation.Brokerage.Value)
        //    {
        //        GenerateBrokerCommission(contract);
        //        GenerateRepresententBrokerComission(contract);
        //    }
        //    else
        //    {
        //        GenerateMonthlyInvoicesFromLoan(contract);
        //        GenerateBillToCustomerFromLoan(contract);
        //    }
        //}

        #region Calculate Commission

        //private void GenerateBrokerCommission(Contract contract)
        //{
        //    InvoicesManager manager = new InvoicesManager(this);


        //    Invoice invoice = new Invoice();
        //    invoice.CompanyId = contract.CompanyId;
        //    invoice.CustomerId = contract.CustomerId;
        //    invoice.EntryDate = contract.FirstParcelDueDate.Value.AddDays(contract.FinancierOperation.ReceiveDay).NextUtilDay();
        //    //invoice.Creditor = !String.IsNullOrEmpty(contract.ContractNumber) ? contract.ContractNumber : contract.ContractId.ToString();
        //    invoice.Description = "Comissão Contrato N. " + contract.ContractNumber;
        //    //invoice.InvoiceValue = Decimal.Zero;

        //    if (contract.InvoiceId.HasValue)
        //    {
        //        Invoice original_invoice = manager.GetInvoice(contract.CompanyId, contract.InvoiceId.Value);
        //        new ParcelsManager(this).DeleteAllNextInvoiceParcels(invoice, DateTime.Now);
        //        manager.Update(original_invoice, invoice);
        //    }
        //    else
        //    {
        //        //manager.Insert(invoice, null);
        //        manager.InsertRetrievingId(invoice);
        //        contract.InvoiceId = invoice.InvoiceId;
        //    }
        //    GenerateBrokerCommissionParcel(contract, invoice);


        //    DbContext.SubmitChanges();
        //}

        //private Parcel GenerateBrokerCommissionParcel(Contract contract, Invoice invoice)
        //{
        //    if (contract.FinancierOperation == null)
        //        return null;

        //    Parcel parcel = new Parcel();
        //    parcel.FinancierOperationId = contract.FinancierOperationId;
        //    parcel.CompanyId = contract.CompanyId;
        //    parcel.Description = "1/1";
        //    parcel.DueDate = contract.FirstParcelDueDate.Value.AddDays(contract.FinancierOperation.ReceiveDay).NextUtilDay(); ;

        //    parcel.Amount = CalculateNetWorth(contract) * contract.FinancierCondition.PercentCompany / 100m;

        //    if (contract.Insurance.HasValue) //seguro
        //        parcel.Amount += contract.Insurance.Value * Convert.ToDecimal(contract.FinancierOperation.InsurancePercent) / 100m;

        //    if (contract.MoneyReserves.HasValue) //pecúlio
        //        parcel.Amount += contract.MoneyReserves.Value * Convert.ToDecimal(contract.FinancierOperation.PeculiumPercent) / 100m;

        //    if (contract.MonthlyFee.HasValue)// mensalidade
        //        parcel.Amount += (contract.MonthlyFee.Value * contract.FinancierCondition.ParcelCount) * Convert.ToDecimal(contract.FinancierOperation.MonthlyFeePercent) / 100m;

        //    //invoice.InvoiceValue += parcel.Amount;
        //    parcel.InvoiceId = invoice.InvoiceId;
        //    new InvoicesManager(this).Insert(parcel, contract.FinancierCondition);

        //    return parcel;
        //}

        //private void GenerateRepresententBrokerComission(Contract contract)
        //{
        //    if (contract.RepresentantId.HasValue)
        //    {
        //        BillManager billManager = new BillManager(this);

        //        Bill bill = new Bill();
        //        bill.CompanyId = contract.CompanyId;
        //        bill.DocumentType = (Int32)DocumentType.others;
        //        bill.EntryDate = contract.FirstParcelDueDate.Value.AddDays(contract.FinancierOperation.ReceiveDay).NextUtilDay();

        //        //if (contract.RepresentantId.HasValue)
        //        //{
        //        //   // bill.Creditor = (contract.Representant.Profile != null ? contract.Representant.Profile.AbreviatedName : contract.Representant.LegalEntityProfile.CompanyName);
        //        //    bill.Description = "Comissão »" + bill.Creditor;
        //        //}


        //        billManager.Insert(bill, null);

        //        GenerateRepresententBrokerComissionParcel(contract, bill);

        //        DbContext.SubmitChanges();
        //    }
        //}

        //private Parcel GenerateRepresententBrokerComissionParcel(Contract contract, Bill bill)
        //{
        //    if (contract.FinancierOperation == null)
        //        return null;

        //    Parcel parcel = new Parcel();
        //    parcel.FinancierOperationId = contract.FinancierOperationId;
        //    parcel.CompanyId = contract.CompanyId;
        //    parcel.Description = "1/1";
        //    parcel.DueDate = contract.FirstParcelDueDate.Value.AddDays(contract.FinancierOperation.ReceiveDay).NextUtilDay(); ;

        //    parcel.Amount = CalculateNetWorth(contract) * contract.FinancierCondition.PercentRepresentant / 100m;

        //    if (contract.Insurance.HasValue) //seguro
        //        parcel.Amount += contract.Insurance.Value * Convert.ToDecimal(contract.FinancierOperation.InsurancePercentPerRepresentant) / 100m;

        //    if (contract.MoneyReserves.HasValue) //pecúlio
        //        parcel.Amount += contract.MoneyReserves.Value * Convert.ToDecimal(contract.FinancierOperation.PeculiumPercentPerRepresentant) / 100m;

        //    if (contract.MonthlyFee.HasValue)// mensalidade
        //        parcel.Amount += (contract.MonthlyFee.Value * contract.FinancierCondition.ParcelCount) * Convert.ToDecimal(contract.FinancierOperation.MonthlyFeePercentPerRepresentant) / 100m;

        //    //bill.BillValue += parcel.Amount;
        //    parcel.BillId = bill.BillId;
        //    new BillManager(this).Insert(parcel, contract.FinancierCondition);
        //    return parcel;
        //}

        #endregion

        private void GenerateBillToCustomerFromLoan(Contract contract)
        {
            var billManager     = new FinancialManager(this);
            var parcelsManager  = new ParcelsManager(this);
            var customerManager = new CustomerManager(this);

            var bill = new Bill();

            bill.CompanyId    = contract.CompanyId;
            bill.DocumentType = (Int32)DocumentType.others;

            Customer customer = customerManager.GetCustomer(contract.CustomerId, contract.CompanyId);

            //bill.Creditor = customer.Profile != null ? customer.Profile.Name : customer.LegalEntityProfile.CompanyName;
            //bill.Description = "Empréstimo p/ " + bill.Creditor;

            //bill.BillValue = contract.ContractValue.Value - CalculateOtherDebits(contract);
            billManager.Insert(bill, null);

            //
            var parcel = new Parcel();

            parcel.FinancierOperationId = contract.FinancierOperationId;
            parcel.CompanyId            = contract.CompanyId;
            parcel.BillId = bill.BillId;

            parcel.Description = "1/1";
            parcel.DueDate     = contract.BeginDate.NextUtilDay();
            //parcel.Amount = bill.BillValue.Value;
            parcelsManager.Insert(parcel, null);
        }
예제 #2
0
    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();
    }
예제 #3
0
    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;
            }
        }
    }
예제 #4
0
        //private void GenerateMonthlyInvoicesFromLoan(Contract entity)
        //{
        //    InvoicesManager manager = new InvoicesManager(this);
        //    Invoice invoice = new Invoice();
        //    Invoice original_invoice = new Invoice();

        //    if (entity.InvoiceId.HasValue)
        //        original_invoice = manager.GetInvoice(entity.CompanyId, Convert.ToInt32(entity.InvoiceId));

        //    invoice.CopyPropertiesFrom(original_invoice);

        //    invoice.CompanyId = entity.CompanyId;
        //    invoice.CustomerId = entity.CustomerId;
        //    invoice.Description = !String.IsNullOrEmpty(entity.ContractNumber) ? entity.ContractNumber : entity.ContractId.ToString();
        //    invoice.InvoiceValue = decimal.Zero;

        //    if (or/ger.InsertRetrievingId(invoice);
        //    else
        //        manager.Update(original_invoice, invoice);

        //    entity.InvoiceId = invoice.InvoiceId;
        //    invoice.InvoiceValue += GenerateMonthlyInvoiceParcelFromLoan(entity);

        //    DbContext.SubmitChanges();

        //}

        /// <summary>
        /// this method generates MonthlyInvoice's parcels
        /// </summary>
        /// <param name="entity">Current Contract</param>
        /// <param name="qtdParcels">Number of parcels</param>
        /// <returns>returns the sum of invoice's parcels</returns>
        private Decimal GenerateMonthlyInvoiceParcelFromLoan(Contract entity)
        {
            DateTime dueDate      = Convert.ToDateTime(entity.FirstParcelDueDate);
            Decimal  parcelAmount = decimal.Zero;
            Parcel   parcel;
            var      invoicesManager = new FinancialManager(this);

            for (int i = 1; i <= entity.FinancierCondition.ParcelCount; i++)
            {
                if ((entity.Periodicity.Value == 30
                         ? entity.BeginDate.AddMonths(1)
                         : entity.BeginDate.AddDays(entity.Periodicity.Value)) > DateTime.Now.Date)
                {
                    parcel = CreateMonthlyInvoiceParcelFromLoan(entity,
                                                                (i / entity.FinancierCondition.ParcelCount).ToString(),
                                                                dueDate);
                    parcelAmount += parcel.Amount;
                    invoicesManager.Insert(parcel, entity.FinancierCondition);
                }

                //If days contains 30, Add a Month
                if (entity.Periodicity.Value == 30)
                {
                    dueDate = dueDate.AddMonths(1);
                }
                else
                {
                    dueDate = dueDate.AddDays(entity.Periodicity.Value);
                }
            }
            DbContext.SubmitChanges();

            return(parcelAmount);
        }
예제 #5
0
    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");
            }
        }
    }
예제 #6
0
 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);
         }
     }
 }
예제 #7
0
    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);
        }
    }
예제 #8
0
    /// <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();
    }
        public void DoWork()
        {
            using (var companyManager = new CompanyManager(null))
            using (var financialManager = new FinancialManager(null))
            {
                // Para cada empresa verifica se tem parcela em atraso
                foreach (var company in companyManager.GetAllCompanies())
                {

                    // Se tiver parcela em atraso bloqueia a empresa

                    // Se náo tiver verifica se é o dia da próxima fatura
                    if (company.NextStatementDueDate.Date.Equals(DateTime.Now.Date))
                        companyManager.GenerateStatement(company);                  
                }
            }
        }
예제 #10
0
        public void DoWork()
        {
            using (var companyManager = new CompanyManager(null))
                using (var financialManager = new FinancialManager(null))
                {
                    // Para cada empresa verifica se tem parcela em atraso
                    foreach (var company in companyManager.GetAllCompanies())
                    {
                        // Se tiver parcela em atraso bloqueia a empresa

                        // Se náo tiver verifica se é o dia da próxima fatura
                        if (company.NextStatementDueDate.Date.Equals(DateTime.Now.Date))
                        {
                            companyManager.GenerateStatement(company);
                        }
                    }
                }
        }
            static void Main(string[] args)
            {
                PurchaseRequest requestDao   = new PurchaseRequest(8000.0, "单刀5把");
                PurchaseRequest requestHuaJi = new PurchaseRequest(10000.0, "10把方天画戟");
                PurchaseRequest requestJian  = new PurchaseRequest(80000.0, "5把金丝龙鳞闪电劈");

                Approver manager   = new Manager("黄飞鸿");
                Approver financial = new FinancialManager("黄麒英");
                Approver ceo       = new CEO("十三姨");

                // 设置职责链
                manager.NextApprover   = financial;
                financial.NextApprover = ceo;

                // 处理请求
                manager.ProcessRequest(requestDao);
                manager.ProcessRequest(requestHuaJi);
                manager.ProcessRequest(requestJian);

                Console.ReadLine();
            }
예제 #12
0
    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();
    }
예제 #13
0
    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");
        }
    }
예제 #14
0
        /// <summary>
        /// this method save the receipt and its items
        /// </summary>
        /// <param name="original_entity">this parameter is used in update operation</param>
        /// <param name="entity">this parameter always is used</param>
        /// <param name="lstReceiptItem">this parameter contai the list of ReceiptItems</param>
        public void SaveReceipt(Receipt original_entity, Receipt entity, List <ReceiptItem> lstReceiptItem,
                                List <Int32> lstServiceOrder, List <Int32> lstSale)
        {
            //Managers
            var accountManager   = new AccountManager(this);
            var parcelsManager   = new ParcelsManager(this);
            var financialManager = new FinancialManager(this);
            var invoice          = new Invoice();
            var bill             = new Bill();

            entity.ModifiedDate = DateTime.Now;
            if (original_entity.ReceiptId == 0)
            {
                //insert the Receipt
                //if (ExistReceiptNumber(entity.CompanyId, Convert.ToInt32(entity.ReceiptNumber)))
                //    throw new InvalidOperationException();

                DbContext.Receipts.InsertOnSubmit(entity);
            }
            else
            {
                //update
                original_entity.CopyPropertiesFrom(entity);

                //delete all receiptItens
                DeleteReceiptItemsByReceipt(entity.ReceiptId, entity.CompanyId);
            }

            DbContext.SubmitChanges();

            foreach (ReceiptItem item in lstReceiptItem)
            {
                item.ReceiptId = entity.ReceiptId;
                item.CompanyId = entity.CompanyId;
                InsertReceiptItem(item);
            }
            ////insert the ReceiptItems
            //for (int i = 0; i < lstReceiptItem.Count; i++)
            //{
            //    lstReceiptItem[i].ReceiptId = entity.ReceiptId;
            //    InsertReceiptItem(lstReceiptItem[i]);
            //}

            if (entity.SupplierId.HasValue)
            {
                bill.CompanyId      = entity.CompanyId;
                bill.EntryDate      = DateTime.Now;
                bill.SupplierId     = entity.SupplierId;
                bill.DocumentNumber = Convert.ToString(entity.ReceiptNumber);
                //if (entity.ReceiptValue.HasValue)
                //    bill.BillValue = entity.ReceiptValue.Value;
                financialManager.Insert(bill, null);
            }
            else
            {
                SetReceiptIdInSale(entity.CompanyId, lstSale, entity.ReceiptId);
                SetReceiptIdInServiceOrder(entity.CompanyId, lstServiceOrder, entity.ReceiptId);
            }

            DbContext.SubmitChanges();

            if (bill.BillId != 0)
            {
                //insert the parcel
                var parcel = new Parcel();
                parcel.PaymentMethodId = PaymentMethod.Cash;
                parcel.CompanyId       = entity.CompanyId;
                parcel.DueDate         = DateTime.Now;
                //parcel.Amount = bill.BillValue.Value;
                parcel.BillId = bill.BillId;

                parcelsManager.Insert(parcel,
                                      accountManager.GetFinancierConditionByParcelCount(entity.CompanyId,
                                                                                        PaymentMethod.Cash, 1));
            }

            DbContext.SubmitChanges();
        }