public static void SaveCashPayDocument(Invoice Inv)
 {
     var db = new StoreDBEntities();
     long accountid = 0;
     try
     {
         accountid = db.Accounts.AsEnumerable().First(x => x.DistributorID == Inv.TarafID).Id;
     }
     catch (InvalidOperationException)
     {
         Account newAcc = new Account
         {
             Name = Inv.Distributor.Name,
             Description = " ",
             CustomerID = 0,
             DistributorID = Inv.TarafID,
             BankAccountID = 0
         };
         db.Accounts.AddObject(newAcc);
         db.SaveChanges();
         accountid = db.Accounts.OrderByDescending(x => x.Id).First().Id;
         //db.AcceptAllChanges();
         //db = new StoreDBEntities();
     }
     Document newDocDebt = new Document
     {
         AccountID = accountid,
         Description = "پرداخت نقد فاکتور " + Inv.InvoiceID,
         Value = Inv.TotalPrice + Inv.Expenses - Inv.Discount,
         Date = Inv.Date,
         SetDate = Utilities.getCurrentPersianDate(),
         Debt_Credit = true,
         InvoiceID = Inv.InvoiceID
     };
     db.Documents.AddObject(newDocDebt);
     db.SaveChanges();
 }
        private void btnInvoiceSubmit_Click(object sender, System.EventArgs e)
        {
            if (this.submitted && FarsiMessage.Show("این فاکتور قبلاً ثبت شده است. آیا واقعا تمایل دارید آن را دوباره ثبت کنید؟", "ثبت تکراری", FarsiMessageBoxButtons.YesNo, FarsiMessageBoxIcons.Question) == DialogResult.No)
            {
                return;
            }
            this.ComputeTotal();
            if (this.lstInvoice.Items.Count == 0)
            {
                this.errorProvider.SetError(this.lstInvoice, "لیست خرید خالی است");
                return;
            }
            if (this.cmbDistributor.Text == "")
            {
                this.errorProvider.SetError(this.cmbDistributor, "نام طرف حساب وارد نشده است");
                return;
            }
            this.ComputeTotal();
            if (FarsiMessage.Show(string.Concat(new string[]
			{
				"آیا مایل هستید فاکتور خرید به مبلغ ",
				(total - discount).ToString("0,0"),
				" به نام ",
				this.cmbDistributor.Text,
				" ثبت شود؟"
			}), "تایید ثبت", FarsiMessageBoxButtons.YesNo, FarsiMessageBoxIcons.Question) == DialogResult.Yes)
            {
                long invoiceID;
                if (!this.edit)
                {
                    Invoice newInv = new Invoice()
                    {
                        Sale = false,
                        TarafID = (long)this.cmbDistributor.SelectedValue,
                        Date = this.bestDate,
                        Paid = this.chkPaidInvoice.Checked,
                        TotalPrice = this.total,
                        Discount = this.discount,
                        Expenses = this.expenses,
                        Description = txtDescription.Text
                    };
                    db.Invoices.AddObject(newInv);
                    db.SaveChanges();
                    invoiceID = newInv.InvoiceID;
                }
                else
                {
                    List<InvoiceItem> list = editInvoice.InvoiceItems.ToList<InvoiceItem>();
                    for (int i = 0; i < list.Count; i++)
                    {
                        long invItemID = list[i].ID;
                        this.db.InvoiceItems.DeleteObject(this.db.InvoiceItems.First((InvoiceItem x) => x.ID == invItemID));
                        long itemID = list[i].ItemID;
                        Item item = this.db.Items.First((Item x) => x.ItemID == itemID);
                        item.Available -= list[i].Count;
                        this.db.Items.ApplyCurrentValues(item);
                    }
                    this.db.SaveChanges();
                    invoiceID = this.editInvoice.InvoiceID;
                    Invoice invoice = this.db.Invoices.First((Invoice x) => x.InvoiceID == invoiceID);
                    invoice.TarafID = (long)this.cmbDistributor.SelectedValue;
                    invoice.Discount = this.discount;
                    invoice.Expenses = this.expenses;
                    invoice.Description = txtDescription.Text;
                    invoice.TotalPrice = this.total;
                    invoice.Date = this.bestDate;
                    invoice.Paid = this.chkPaidInvoice.Checked;
                    db.Invoices.ApplyCurrentValues(invoice);
                    this.db.SaveChanges();
                    this.edit = false;
                }
                for (int i = 0; i < this.lstInvoice.Items.Count; i++)
                {
                    try
                    {
                        object obj = this.invoiceItemTableAdapter.InsertReturnID(
                            invoiceID,
                            long.Parse(this.lstInvoice.Items[i].SubItems[1].Text),
                            int.Parse(this.lstInvoice.Items[i].SubItems[4].Text),
                            int.Parse(this.lstInvoice.Items[i].SubItems[3].Text));
                        this.lstInvoice.Items[i].SubItems[0].Text = obj.ToString();
                        StoreDBDataSet.ItemDataTable dataByItemID = this.itemTableAdapter.GetDataByItemID(long.Parse(this.lstInvoice.Items[i].SubItems[1].Text));
                        this.itemTableAdapter.UpdateQuery(
                            dataByItemID[0].ItemID,
                            dataByItemID[0].Name,
                            dataByItemID[0].Available + int.Parse(this.lstInvoice.Items[i].SubItems[3].Text), int.Parse(this.lstInvoice.Items[i].SubItems[6].Text), dataByItemID[0].ItemID);
                    }
                    catch (System.Exception)
                    {
                        FarsiMessage.Show("حین ثبت کالای شماره " + this.lstInvoice.Items[i].SubItems[1].Text + " در این فاکتور مشکلی به وجود آمده است. مابقی اقلام این فاکتور ثبت خواهند شد.\nبرای تصحیح فاکتور میتوانید به بخش مدیریت فاکتورها مراجعه کنید", "خطا", FarsiMessageBoxButtons.OK, FarsiMessageBoxIcons.Error);
                    }
                }
                SaveInvoiceDocument(db.Invoices.FirstOrDefault(x=>x.InvoiceID == invoiceID));
                if (chkPaidInvoice.Checked && rdbtnPaidCash.Checked)
                    SaveCashPayDocument(db.Invoices.FirstOrDefault(x => x.InvoiceID == invoiceID));

                if (chkPaidInvoice.Checked && rdbtnPaidCheque.Checked)
                {
                    new ChequeAddForm((long)this.cmbDistributor.SelectedValue, invoiceID, this.total - this.discount).ShowDialog();
                }
                FarsiMessage.Show("فاکتور شماره " + invoiceID + " به نام " + cmbDistributor.SelectedText + "ثبت شد");
                total = 0;
                discount = 0;
                txtTotal.Text = "0";
                txtPureTotal.Text = "0";
                numDiscount.Value = 0;
                this.submitted = true;
                this.lstInvoice.Items.Clear();
                this.numDiscount.ResetText();
                this.txtTotal.Clear();
                this.txtItemNameID.Focus();
                this.txtItemNameID.SelectAll();
            }
        }
 public static void SaveInvoiceDocument(Invoice Inv)
 {
     var db = new StoreDBEntities();
     if (Inv.Sale && (Inv.TarafID < 0 || Inv.Paid))
         return;
     long accountid = 0;
     try
     {
         accountid = db.Accounts.AsEnumerable().First(x => x.DistributorID == Inv.TarafID).Id;
     }
     catch (InvalidOperationException)
     {
         Account newAcc = new Account
         {
             Name = Inv.Distributor.Name,
             Description = " ",
             CustomerID = Inv.Sale ? Inv.TarafID : 0,
             DistributorID = Inv.Sale ? 0 : Inv.TarafID,
             BankAccountID = 0
         };
         db.Accounts.AddObject(newAcc);
         db.SaveChanges();
         accountid = db.Accounts.OrderByDescending(x => x.Id).First().Id;
         //db.AcceptAllChanges();
         //db = new StoreDBEntities();
     }
     Document newDocCred = new Document
     {
         AccountID = accountid,
         Description = "فاکتور "+ (Inv.Sale ? "ف" : "خ") +" شماره " + Inv.InvoiceID,
         Value = Inv.TotalPrice + Inv.Expenses - Inv.Discount,
         Date = Inv.Date,
         SetDate = Utilities.getCurrentPersianDate(),
         Debt_Credit = Inv.Sale ? true : false,
         InvoiceID = Inv.InvoiceID
     };
     db.Documents.AddObject(newDocCred);
     db.SaveChanges();
 }
        public InvoiceBuyForm(Invoice edtInv)
            : this()
        {
            List<InvoiceItem> list = edtInv.InvoiceItems.ToList<InvoiceItem>();
            for (int i = 0; i < list.Count; i++)
            {
                this.lstInvoice.Items.Add(new ListViewItem(new string[]
				{
					"-",
					list[i].ItemID.ToString(),
					list[i].Item.Name,
					list[i].Count.ToString(),
					list[i].Price.ToString(),
					(list[i].Price * list[i].Count).ToString(),
					list[i].Item.SellPrice.ToString()
				}));
            }
            this.Font = MainForm.FORM_FONT;
            this.editInvoice = edtInv;
            this.edit = true;
            if (FarsiMessage.Show("با تغییر محتوای فاکتور تمامی اقلام فاکتور ابتدا حذف شده و سپس ذخیره می شوند", "تغییر", FarsiMessageBoxButtons.OKCancel) == System.Windows.Forms.DialogResult.Cancel)
                this.Close();
            this.cmbDistributor.SelectedIndex = this.cmbDistributor.FindString(this.editInvoice.Distributor.Name);
            this.chkPaidInvoice.Checked = edtInv.Paid;
            this.abrDateInvoiceDate.SelectedDate = (Utilities.getMiladiFromPersian(edtInv.Date));
            this.numDiscount.Value = edtInv.Discount;
            this.numExpenses.Value = edtInv.Expenses;
            this.txtDescription.Text = edtInv.Description;
            this.ComputeTotal();
        }
        private void btnCreateInvoice_Click(object sender, System.EventArgs e)
        {
            if (this.total == 0L)
            {
                FarsiMessage.Show("مجموع فاکتور صفر است", "", FarsiMessageBoxButtons.OK, FarsiMessageBoxIcons.Stop);
                return;
            }
            string selectedDateString = this.abrInvoiceDate.SelectedDateString;
            if (this.edit)
            {
                List<InvoiceItem> list = editInv.InvoiceItems.ToList<InvoiceItem>();
                for (int i = 0; i < list.Count; i++)
                {
                    long invItemId = list[i].ID;
                    this.db.InvoiceItems.DeleteObject(this.db.InvoiceItems.First((InvoiceItem x) => x.ID == invItemId));
                    long itemID = list[i].ItemID;
                    Item item = this.db.Items.First((Item x) => x.ItemID == itemID);
                    item.Available += list[i].Count;
                    
                }
                this.GenInvoiceID = this.editInv.InvoiceID;
                Invoice invoice = this.db.Invoices.First((Invoice x) => x.InvoiceID == this.GenInvoiceID);
                invoice.TarafID = (long)this.cmbCustomers.SelectedValue;
                invoice.Paid = (this.cmbCustomers.SelectedIndex <= 0 || !this.chkUnPaidInvoice.Checked);
                invoice.Discount = this.discount;
                invoice.TotalPrice = this.total;
                invoice.Expenses = this.expenses;
                invoice.Description = "";
                invoice.Date = this.abrInvoiceDate.SelectedDateString;
                this.db.Invoices.ApplyCurrentValues(invoice);
                this.db.SaveChanges();
                this.edit = false;
            }
            else
            {
                Invoice newInv = new Invoice()
                {
                    Sale = true,
                    TarafID = (long)this.cmbCustomers.SelectedValue,
                    Date = selectedDateString,
                    Paid = this.cmbCustomers.SelectedIndex == 0 || !this.chkUnPaidInvoice.Checked,
                    TotalPrice = this.total,
                    Discount = this.discount,
                    Expenses = this.expenses,
                    Description = ""
                };
                db.Invoices.AddObject(newInv);
                db.SaveChanges();
                GenInvoiceID = newInv.InvoiceID;
                
                long accountid = 0;
                if (cmbCustomers.SelectedIndex > 0)
                {
                    try
                    {
                        accountid = db.Accounts.First(x => x.CustomerID == (long)cmbCustomers.SelectedValue).Id;
                    }
                    catch (InvalidOperationException)
                    {
                        Account newAcc = new Account
                        {
                            Name = cmbCustomers.Text,
                            Description = " ",
                            DistributorID = 0,
                            CustomerID = (long)cmbCustomers.SelectedValue,
                            BankAccountID = 0
                        };
                        db.Accounts.AddObject(newAcc);
                        db.SaveChanges();
                        accountid = db.Accounts.OrderByDescending(x => x.Id).First().Id;
                    }
                    try
                    {
                        Document docEdit = db.Documents.First(x => x.InvoiceID == GenInvoiceID && x.Debt_Credit == true);
                        docEdit.Value = total - discount;
                        db.Documents.ApplyCurrentValues(docEdit);
                    }
                    catch
                    {
                        Document newDocDebt = new Document
                        {
                            AccountID = accountid,
                            Description = "فاکتور ف " + GenInvoiceID,
                            Value = total - discount,
                            Date = abrInvoiceDate.SelectedDateString,
                            SetDate = Utilities.getCurrentPersianDate(),
                            Debt_Credit = true,
                            InvoiceID = GenInvoiceID
                        };
                        db.Documents.AddObject(newDocDebt);
                    }
                    try
                    {
                        Document docPayEdit = db.Documents.First(x => x.InvoiceID == GenInvoiceID && x.Debt_Credit == false);
                        if (!this.chkUnPaidInvoice.Checked)
                        {
                            docPayEdit.Value = total - discount;
                            db.Documents.ApplyCurrentValues(docPayEdit);
                        }
                        else
                            db.Documents.DeleteObject(docPayEdit);
                    }
                    catch
                    {
                        if (!this.chkUnPaidInvoice.Checked)
                        {
                            Document newDocPay = new Document
                            {
                                AccountID = accountid,
                                Description = "پرداخت فاکتور فروش " + GenInvoiceID,
                                Value = total - discount,
                                Date = abrInvoiceDate.SelectedDateString,
                                SetDate = Utilities.getCurrentPersianDate(),
                                Debt_Credit = false,
                                InvoiceID = GenInvoiceID
                            };
                            db.Documents.AddObject(newDocPay);
                        }
                    }
                    db.SaveChanges();
                }
                ClearTempItems();
                timestamp = Utilities.getCurrentTimeStamp();
                lblTimestamp.Text = timestamp.ToString();
            }
            this.daily = this.dailyTransactionTableAdapter.GetData().ToList<StoreDBDataSet.DailyTransactionRow>().FirstOrDefault((StoreDBDataSet.DailyTransactionRow x) => x.Description == "اضافه دریافت فاکتور " + GenInvoiceID);
            if(daily != null)
                this.dailyTransactionTableAdapter.DeleteByID(this.daily.ID);
//            if (numExpenses.Value>0)
//                this.dailyTransactionTableAdapter.Insert(selectedDateString, this.expenses, false, "اضافه دریافت فاکتور " + this.GenInvoiceID);
//            else if (this.discount > 0L)
//                this.dailyTransactionTableAdapter.Insert(selectedDateString, this.discount, true, "تخفیف فاکتور " + this.GenInvoiceID);
            for (int i = 0; i < this.lstTotal.Items.Count; i++)
            {
                long num2 = long.Parse(this.lstTotal.Items[i].SubItems[0].Text);
                this.invoiceItemTableAdapter.Insert(this.GenInvoiceID, num2, int.Parse(this.lstTotal.Items[i].SubItems[2].Text.Replace(",", "")), int.Parse(this.lstTotal.Items[i].SubItems[3].Text));
                //this.itemTableAdapter.GetDataByItemID(num2);
                this.itemTableAdapter.UpdateAvailable(int.Parse(this.lstTotal.Items[i].SubItems[3].Text), num2);
            }
            if (this.cmbCustomers.SelectedIndex > 0)
            {
                StoreDBDataSet.CustomerRow customerRow = this.customerTableAdapter.GetData().First((StoreDBDataSet.CustomerRow x) => x.ID == (long)this.cmbCustomers.SelectedValue);
                this.customerTableAdapter.UpdateByID(customerRow.Name, this.chkUnPaidInvoice.Checked ? (customerRow.Debt + this.total + this.expenses - this.discount) : customerRow.Debt, customerRow.LastPayment, selectedDateString, customerRow.ID);
                
            }
            if (this.chkReportOutput.Checked)
            {
                var rep = stiReport1.SaveToString();
                this.invoiceItemTableAdapter.FillByInvoiceID(this.storeDBDataSet.InvoiceItem, this.GenInvoiceID);
                this.itemTableAdapter.Fill(this.storeDBDataSet.Item);
                this.invoiceTableAdapter.Fill(this.storeDBDataSet.Invoice);
                this.customerTableAdapter.Fill(this.storeDBDataSet.Customer);
                this.stiReport1.RegData(this.storeDBDataSet);
                this.stiReport1.Show(false);
                stiReport1.LoadFromString(rep);
            }
            //this.FillTable(this.itemTableAdapter.GetData());
            db = new StoreDBEntities();
            this.lstTotal.Items.Clear();
            this.lblTotalPrice.Text = "";
            this.ComputeTotal(false);
            this.numDiscount.Value = 0m;
            this.numExpenses.Value = 0m;
            this.cmbCustomers.SelectedIndex = 0;
            this.chkUnPaidInvoice.Checked = false;
            this.txtItemNameID.Clear();
            this.txtItemNameID.Focus();
        }
        public InvoiceSaleForm(Invoice ei)
            : this()
        {
            this.Font = MainForm.FORM_FONT;
            this.editInv = ei;
            this.edit = true;
            List<InvoiceItem> list = ei.InvoiceItems.ToList<InvoiceItem>();
            for (int i = 0; i < list.Count; i++)
            {
                this.lstTotal.Items.Add(new ListViewItem(new string[]
				{
					list[i].ItemID.ToString(),
					list[i].Item.Name,
					list[i].Price.ToString(),
					list[i].Count.ToString(),
					(list[i].Count * list[i].Price).ToString()
				}));
                //long invItemId = list[i].ID;
                //this.db.InvoiceItems.DeleteObject(this.db.InvoiceItems.First((InvoiceItem x) => x.ID == invItemId));
                //long itemID = list[i].ItemID;
                //Item item = this.db.Items.First((Item x) => x.ItemID == itemID);
                //item.Available += list[i].Count;
                //this.db.Items.ApplyCurrentValues(item);
            }
            this.chkUnPaidInvoice.Checked = !ei.Paid;
            this.cmbCustomers.SelectedIndex = this.cmbCustomers.FindString(ei.Customer.Name);
            this.abrInvoiceDate.SelectedDate = (Utilities.getMiladiFromPersian(ei.Date));
            this.discount = ei.Discount;
            this.total = ei.TotalPrice;
            this.expenses = ei.Expenses;
            if (discount > 0)
                this.numDiscount.Value = ei.Discount;
            else
                this.numExpenses.Value = ei.Expenses;
            this.lblTotalPrice.Text = ei.TotalPrice.ToString("0,0");
            
            this.db.SaveChanges();
            FarsiMessage.Show("با تغییر محتوای فاکتور تمامی اقلام فاکتور ابتدا حذف شده \r\nو سپس با صدور فاکتور جدید دوباره ذخیره می شوند");
        }
 /// <summary>
 /// Deprecated Method for adding a new object to the Invoices EntitySet. Consider using the .Add method of the associated ObjectSet&lt;T&gt; property instead.
 /// </summary>
 public void AddToInvoices(Invoice invoice)
 {
     base.AddObject("Invoices", invoice);
 }
 /// <summary>
 /// Create a new Invoice object.
 /// </summary>
 /// <param name="invoiceID">Initial value of the InvoiceID property.</param>
 /// <param name="tarafID">Initial value of the TarafID property.</param>
 /// <param name="date">Initial value of the Date property.</param>
 /// <param name="sale">Initial value of the Sale property.</param>
 /// <param name="totalPrice">Initial value of the TotalPrice property.</param>
 /// <param name="paid">Initial value of the Paid property.</param>
 /// <param name="discount">Initial value of the Discount property.</param>
 /// <param name="expenses">Initial value of the Expenses property.</param>
 public static Invoice CreateInvoice(global::System.Int64 invoiceID, global::System.Int64 tarafID, global::System.String date, global::System.Boolean sale, global::System.Int64 totalPrice, global::System.Boolean paid, global::System.Int64 discount, global::System.Int64 expenses)
 {
     Invoice invoice = new Invoice();
     invoice.InvoiceID = invoiceID;
     invoice.TarafID = tarafID;
     invoice.Date = date;
     invoice.Sale = sale;
     invoice.TotalPrice = totalPrice;
     invoice.Paid = paid;
     invoice.Discount = discount;
     invoice.Expenses = expenses;
     return invoice;
 }