protected void btnAddInvoice_Click(object sender, EventArgs e) { InvoicingDataContext db = new InvoicingDataContext(); InvoiceDetail invoice = new InvoiceDetail(); invoice.invoice_number = this.txtInvoiceRef.Text; invoice.personal_details = this.ddlPersonalDetails.SelectedIndex + 1; invoice.client_details = this.ddlClient.SelectedIndex + 1; invoice.bank_details = this.ddlBank.SelectedIndex + 1; invoice.time_worked = Convert.ToInt32(this.txtTimeWorked.Text); invoice.rate = Convert.ToInt32(this.txtRate.Text); invoice.date_from = Convert.ToDateTime(this.txtDateFrom.Text); invoice.date_to = Convert.ToDateTime(this.txtDateTo.Text); db.InvoiceDetails.InsertOnSubmit(invoice); try { db.SubmitChanges(); } catch { Response.Write("Couldn't add invoice"); } finally { Response.Write("success"); } }
public void TestSetup() { dbConnStr = buildConnectionString(CustomerManagementTest.Properties.Settings.Default.TestDb, () => DateTimeOffset.UtcNow.ToString("yyyy-MM-dd_hh:mm:ssZ")); using (var db = new CustomerContext(dbConnStr)) { var invoicedetail = new InvoiceDetail { ItemUnits=10 }; db.Save(invoicedetail); db.SaveChanges(); invId = invoicedetail.Id; } }
public static void AddInvoiceDetail(InvoiceDetail id) { SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString); SqlCommand command; connection.Open(); try { command = connection.CreateCommand(); command.CommandText = "INSERT INTO UnileverInvoiceTrackingSystem.dbo.invoicedetails (invoiceno, invoiceterritory, invoiceregion, invoicedate, invoiceduedate, invoiceaging, netpayableamount, shortagecomments) VALUES (@IN,@IT,@IR,@ID,@IDD,@IA,@NPA,@SC);"; command.Parameters.AddWithValue("@IN", Convert.ToInt64(id.InvoiceNo)); command.Parameters.AddWithValue("@IT", id.InvoiceTerritory); command.Parameters.AddWithValue("@IR", Convert.ToString(id.InvoiceRegion)); command.Parameters.AddWithValue("@ID", Convert.ToDateTime(id.InvoiceDate)); command.Parameters.AddWithValue("@IDD", Convert.ToDateTime(id.InvoiceDueDate)); command.Parameters.AddWithValue("@IA", id.InvoiceAging); command.Parameters.AddWithValue("@NPA", Convert.ToDecimal(id.NPA)); command.Parameters.AddWithValue("@SC", id.SC); command.ExecuteNonQuery(); } catch (Exception) { throw; } finally { if (connection.State == ConnectionState.Open) { connection.Close(); } } }
public bool CreateInvoiceDetail(ExcelProxyInvoiceDetail invoicedetail, EntityReference product) { using (var orgContext = new OrganizationServiceContext(service)) { var newinvoiceeDetail = new InvoiceDetail() { ProductId = product, IsPriceOverridden = true, Quantity = Convert.ToInt32(invoicedetail.Count), PricePerUnit = new Money(Convert.ToDecimal(invoicedetail.Priceperunit)), //new_purchaseprice = new Money(Convert.ToDecimal(invoicedetail.Purchaseprice)), //new_amountpurchase = new Money(Convert.ToDecimal(invoicedetail.Amountpurchase)), //new_pricepurchaseusd = Convert.ToDouble(invoicedetail.Pricepurchaseusd), //InvoiceId = mainEntityId, //new_kursspeka = Convert.ToDouble(invoicedetail.Exchangerates), //new_viborkurs = new OptionSetValue(100000003), //new_totalpurchaseusd = Convert.ToDouble(invoicedetail.totalUSD), //UoMId = (from i in orgContext.CreateQuery<UoM>() // where i.Name == "Базовая единица" // //where i.Id == new Guid("28FD5C9C-22F7-419C-BBBC-720523DD3666") // select new EntityReference // { // Id = i.Id, // LogicalName = i.LogicalName, // Name = i.Name // }).FirstOrDefault() }; try { service.Create(newinvoiceeDetail); } catch (Exception ex) { throw new InvalidPluginExecutionException(ex.Message); } } return true; }
public static InvoiceDetail_Accommodation CreateNew_InvoiceDetail_Accommodation(InvoiceDetail parentInvoiceDetail, object servicePrice, object startDate, object bedId, object overridenroomClassId, object isSurchargeApplied, object isTaxApplied, object serviceDescription, object isServiceIncludedInInsurance, object insurancePercetnage) { if (bedId == null || parentInvoiceDetail == null) { return(null); } InvoiceDetail_Accommodation accommodation = DBCommon.CreateNewDBEntity <InvoiceDetail_Accommodation>(); if (parentInvoiceDetail.InvoiceDetail_Accommodation == null) { parentInvoiceDetail.InvoiceDetail_Accommodation = new List <InvoiceDetail_Accommodation>(); } parentInvoiceDetail.InvoiceDetail_Accommodation.Add(accommodation); if (Convert.ToBoolean(isServiceIncludedInInsurance) && insurancePercetnage != null) { accommodation.PatientShare = (1 - Convert.ToDouble(insurancePercetnage)) * Convert.ToDouble(servicePrice); accommodation.InsuranceShare = Convert.ToDouble(insurancePercetnage) * Convert.ToDouble(servicePrice); accommodation.IsInsuranceApplied = true; } else { accommodation.PatientShare = Convert.ToDouble(servicePrice); accommodation.InsuranceShare = 0; accommodation.IsInsuranceApplied = false; } InPatientRoomBed_cu roomBed = InPatientRoomBed_cu.ItemsList.Find(item => Convert.ToInt32(item.ID).Equals(Convert.ToInt32(bedId))); if (roomBed == null) { return(null); } InPatientRoom_cu room = InPatientRoom_cu.ItemsList.Find( item => Convert.ToInt32(item.ID).Equals(Convert.ToInt32(roomBed.InPatientRoom_CU_ID))); if (room == null) { return(null); } InPatientRoomClassification_cu roomClassification = InPatientRoomClassification_cu.ItemsList.Find( item => Convert.ToInt32(item.ID).Equals(Convert.ToInt32(room.InPatientRoomClassification_CU_ID))); if (roomClassification == null) { return(null); } accommodation.InPatientRoomBed_CU_ID = roomBed.ID; accommodation.InPatientRoom_CU_ID = room.ID; accommodation.InPatientRoomClassification_CU_ID = roomClassification.ID; accommodation.IsOnDuty = true; accommodation.IsSurchargeApplied = Convert.ToBoolean(isSurchargeApplied); accommodation.StartDate = Convert.ToDateTime(startDate); if (serviceDescription != null) { accommodation.Description = serviceDescription.ToString(); } return(accommodation); }
public async Task <EntityApiResponse <InvoiceDetail> > AddInvoiceAsync(InvoiceDetail invoiceDetail, string currentUserId) { if (invoiceDetail is null) { throw new ArgumentNullException(nameof(invoiceDetail)); } if (invoiceDetail.InvoiceItems is null || invoiceDetail.InvoiceItems.Count < 1) { return(new EntityApiResponse <InvoiceDetail>(error: "Invoice has no items")); } if (invoiceDetail.InvoiceItems.Any(item => item.Quantity < 1)) { return(new EntityApiResponse <InvoiceDetail>(error: "Invoice can't have an item with quantity zero")); } var org = await _orgRepository.GetByIdAsync(invoiceDetail.OrganizationId); if (org is null) { return(new EntityApiResponse <InvoiceDetail>(error: "Organization does not exist")); } Customer customer = null; var belongToCustomer = !(invoiceDetail.Customer is null); var paidWithPoints = invoiceDetail.PaidWithPoints > 0; if (belongToCustomer) { customer = await _customerRepository.GetByIdAsync(invoiceDetail.Customer.Id); if (customer is null) { return(new EntityApiResponse <InvoiceDetail>(error: "Customer does not exist")); } if (paidWithPoints && customer.Points < invoiceDetail.PaidWithPoints) { return(new EntityApiResponse <InvoiceDetail>(error: "Customer doesn't have enough points")); } if (paidWithPoints && !_settings.PointsValues.TryGetValue(invoiceDetail.PaidWithPoints, out var amount)) { return(new EntityApiResponse <InvoiceDetail>(error: $"{invoiceDetail.PaidWithPoints} points are not a standard exchangement")); } } // Check if the current user is in his specified session var now = DateTime.UtcNow; Session session = null; if (_settings.RestrictPaymentOnSession) { session = await _sessionRepository.Table .FirstOrDefaultAsync(s => now >= s.StartDate && now <= s.EndDate && s.UserId == currentUserId); if (session is null) { return(new EntityApiResponse <InvoiceDetail>(error: "Can't add invoice, current session belongs to another user")); } } var newInvoiceNumber = org.LastInvoiceNumber + 1; var invoicePoints = 0; var invoice = new Invoice { Number = newInvoiceNumber, Discount = invoiceDetail.Discount, OrganizationId = org.Id, CreatedById = currentUserId, ModifiedById = currentUserId, OriginalPrice = invoiceDetail.OriginalPrice, FinalPrice = invoiceDetail.FinalPrice, Note = invoiceDetail.Note?.Trim(), CustomerId = customer?.Id }; await _invoiceRepository.InsertAsync(invoice); foreach (var item in invoiceDetail.InvoiceItems) { var stock = await _stockRepository.GetByIdAsync(item.Stock?.Id); if (stock is null) { continue; } var newInvoiceItem = new InvoiceItem { Description = item.Description?.Trim(), Quantity = item.Quantity, Price = item.Price, FinalPrice = item.FinalPrice, Discount = item.Discount, CreatedById = currentUserId, ModifiedById = currentUserId, OrganizationId = org.Id, StockId = stock.Id, InvoiceId = invoice.Id }; await _invoiceItemRepository.InsertAsync(newInvoiceItem); stock.Quantity -= newInvoiceItem.Quantity; stock.LastModifiedDate = DateTime.UtcNow; stock.ModifiedById = currentUserId; await _stockRepository.UpdateAsync(stock); invoicePoints += stock.Points * newInvoiceItem.Quantity; } // Check points for updating customer's balance if (belongToCustomer) { customer.Points += invoicePoints; if (paidWithPoints) { customer.Points -= invoiceDetail.PaidWithPoints; } await _customerRepository.UpdateAsync(customer); } var payment = new CashierPayment { CashEntered = invoiceDetail.CashierPayment?.CashEntered ?? 0m, Change = invoiceDetail.CashierPayment?.Change ?? 0m, SessionId = session?.Id, OrganizationId = org.Id, InvoiceId = invoice.Id, CreatedById = currentUserId, ModifiedById = currentUserId }; await _paymentRepository.InsertAsync(payment); invoice.Points = invoicePoints; await _invoiceRepository.UpdateAsync(invoice); org.LastInvoiceNumber += 1; await _orgRepository.UpdateAsync(org); return(new EntityApiResponse <InvoiceDetail>(entity: new InvoiceDetail(invoice, payment))); }
public void AddToInvoiceDetails(InvoiceDetail invoiceDetail) { base.AddObject("InvoiceDetails", invoiceDetail); }
/// <summary> /// Gathers information from gridview footer /// </summary> /// <returns></returns> protected InvoiceDetail getInvoiceDetailLine() { decimal qty = 0; decimal rate = 0; decimal totalAmount = 0; string[] values = null; int serviceTypeID = 0; DateTime date = DateTime.MaxValue; InvoiceDetail invoiceDetailLine = new InvoiceDetail(); // service date WebDatePicker txtDate = gvInvoiceLines.FooterRow.FindControl("txtDate") as WebDatePicker; if (txtDate != null && !string.IsNullOrEmpty(txtDate.Text)) invoiceDetailLine.LineDate = Convert.ToDateTime(txtDate.Text); // service description DropDownList cbx = gvInvoiceLines.FooterRow.FindControl("cbxServiceDescription") as DropDownList; if (cbx != null) { values = cbx.SelectedValue.Split(new char[] { '|' }); if (values.Length >= 3) { int.TryParse(values[0], out serviceTypeID); invoiceDetailLine.ServiceTypeID = serviceTypeID; invoiceDetailLine.LineDescription = cbx.SelectedItem.Text.Trim(); } } // quantity WebNumericEditor txtQty = gvInvoiceLines.FooterRow.FindControl("txtQty") as WebNumericEditor; if (txtQty != null) { qty = txtQty.Value == null ? 0 : Convert.ToDecimal(txtQty.Value); invoiceDetailLine.Qty = qty; } // unit description //Label lblUnitDescription = gvInvoiceLines.FooterRow.FindControl("lblUnitDescription") as Label; //if (lblUnitDescription != null) // invoiceDetailLine.UnitDescription = lblUnitDescription.Text; // rate WebNumericEditor txtRate = gvInvoiceLines.FooterRow.FindControl("txtRate") as WebNumericEditor; if (txtRate != null) { rate = txtRate.Value == null ? 0 : Convert.ToDecimal(txtRate.Value); invoiceDetailLine.Rate = rate; } // total amount // quantity TextBox txtLineAmount = gvInvoiceLines.FooterRow.FindControl("txtLineAmount") as TextBox; decimal.TryParse(txtLineAmount.Text.Trim().Replace(",", ""), out totalAmount); invoiceDetailLine.LineAmount = totalAmount; invoiceDetailLine.Total = totalAmount; //if (invoiceDetailLine.UnitDescription != null && invoiceDetailLine.UnitDescription.ToLower() == "percentage") // totalAmount = (rate / 100 ) * qty; //else // totalAmount = rate * qty; // comments WebTextEditor txtComments = gvInvoiceLines.FooterRow.FindControl("txtComments") as WebTextEditor; if (txtComments != null) invoiceDetailLine.Comments = txtComments.Text.Trim(); // is billable CheckBox cbxBillable = gvInvoiceLines.FooterRow.FindControl("cbxBillable") as CheckBox; if (cbxBillable != null) invoiceDetailLine.isBillable = cbxBillable.Checked; return invoiceDetailLine; }
private void generateAutomaticInvoicePublicAdjuster(Client client) { Claim claim = null; int claimID = 0; int clientID = Core.SessionHelper.getClientId(); int days = 0; int invoiceID = 0; Invoice invoice = null; InvoiceDetail invoiceDetail = null; Leads lead = null; CRM.Data.Entities.LeadPolicy policy = null; int nextInvoiceNumber = 0; decimal totalAmount = 0; claimID = SessionHelper.getClaimID(); claim = ClaimsManager.Get(claimID); if (claim != null && claim.LeadPolicy != null && claim.LeadPolicy.Leads != null) { lead = claim.LeadPolicy.Leads; policy = claim.LeadPolicy; invoice = new Invoice(); days = client.InvoicePaymentTerms ?? 0; totalAmount = txtNetClaimPayable.ValueDecimal * (client.InvoiceContingencyFee ?? 0); // invoice invoice.InvoiceDate = DateTime.Now; invoice.DueDate = DateTime.Now.AddDays(days); invoice.BillToName = lead.insuredName; invoice.BillToAddress1 = lead.MailingAddress ?? ""; invoice.BillToAddress2 = lead.MailingAddress2 ?? ""; invoice.BillToAddress3 = string.Format("{0}, {1} {2}", lead.MailingCity ?? "", lead.MailingState, lead.MailingZip); invoice.ClaimID = claim.ClaimID; invoice.IsVoid = false; invoice.IsApprove = false; invoice.TotalAmount = totalAmount; invoice.InvoiceTypeID = claim.InvoiceTypeID;// Convert.ToInt32(ddlInvoiceType.SelectedValue);//NEW OC 11/6/14 // invoice detail invoiceDetail = new InvoiceDetail(); invoiceDetail.LineDate = DateTime.Now; invoiceDetail.LineDescription = "Contingency Fee"; invoiceDetail.Total = totalAmount; invoiceDetail.LineAmount = totalAmount; invoiceDetail.isBillable = true; invoiceDetail.Qty = txtNetClaimPayable.ValueDecimal; invoiceDetail.Rate = client.InvoiceContingencyFee * 100; try { using (TransactionScope scope = new TransactionScope()) { // assign next invoice number to new invoice nextInvoiceNumber = InvoiceManager.GetNextInvoiceNumber(client.ClientId); invoice.InvoiceNumber = nextInvoiceNumber; invoiceID = InvoiceManager.Save(invoice); invoiceDetail.InvoiceID = invoiceID; InvoiceDetailManager.Save(invoiceDetail); // update invoice ready flag claim.IsInvoiceReady = cbxInvoiceReady.Checked; claim.IsInvoiced = true; ClaimsManager.Save(claim); // 2014-05-02 apply rule using (SpecificExpenseTypePerCarrier ruleEngine = new SpecificExpenseTypePerCarrier()) { RuleException ruleException = ruleEngine.TestRule(clientID, invoice); if (ruleException != null) { ruleException.UserID = Core.SessionHelper.getUserId(); ruleEngine.AddException(ruleException); CheckSendMail(ruleException); } } // commit transaction scope.Complete(); lblMessage.Text = "Invoice has been generated successfully."; lblMessage.CssClass = "ok"; } } catch (Exception ex) { Core.EmailHelper.emailError(ex); lblMessage.Text = "Invoice was not generated."; lblMessage.CssClass = "error"; } } }
public List<InvoiceDetail> MapInvoiceDetails(List<UiItem> uiitems) { List<InvoiceDetail> details = new List<InvoiceDetail>(); foreach (var uiitem in uiitems) { var detail = new InvoiceDetail {ItemPricing=uiitem.Pricing, ItemUnits=uiitem.ItemUnits }; details.Add(detail); } return details; }
public ActionResult Update([DataSourceRequest] DataSourceRequest request, [Bind(Prefix = "models")] IEnumerable <StockInDetail> items, string so_hoa_don, DateTime ngay_hoa_don, string ma_phieu_header) { using (var dbConn = Helpers.OrmliteConnection.openConn()) { try { if (accessDetail.sua) { var isNhapKho = false; foreach (var item in items) { if (item.so_luong_nhap == 0) { continue; } var detail = dbConn.FirstOrDefault <StockInDetail>(s => s.id == item.id); if (item.so_luong == item.so_luong_da_nhap + item.so_luong_nhap) { detail.trang_thai = "NHAP_HOAN_TAT"; } else if (item.so_luong_da_nhap + item.so_luong_nhap == 0) { detail.trang_thai = "MOI"; } else { detail.trang_thai = "NHAP_MOT_PHAN"; } if (item.so_luong_nhap > 0) { isNhapKho = true; } detail.ngay_nhap = item.ngay_nhap; detail.so_luong_da_nhap = item.so_luong_da_nhap + item.so_luong_nhap; detail.ngay_cap_nhat = DateTime.Now; detail.nguoi_cap_nhat = currentUser.ma_nguoi_dung; dbConn.Update(detail); } if (isNhapKho) { var listDetail = dbConn.Select <StockInDetail>(p => p.ma_phieu_header == ma_phieu_header && p.trang_thai != "NHAP_HOAN_TAT"); if (listDetail.Count == 0) { var header = dbConn.Select <StockInHeader>(p => p.ma_phieu == ma_phieu_header).FirstOrDefault(); header.trang_thai = "NHAP_HOAN_TAT"; header.ngay_cap_nhat = DateTime.Now; dbConn.Update <StockInHeader>(header); } else { var listDetailnew = dbConn.Select <StockInDetail>(p => p.ma_phieu_header == ma_phieu_header && p.trang_thai == "NHAP_MOT_PHAN"); if (listDetail.Count > 0) { var header = dbConn.Select <StockInHeader>(p => p.ma_phieu == ma_phieu_header).FirstOrDefault(); header.trang_thai = "NHAP_MOT_PHAN"; header.ngay_cap_nhat = DateTime.Now; dbConn.Update <StockInHeader>(header); } } //Invoice var stockInheader = dbConn.FirstOrDefault <StockInHeader>(s => s.ma_phieu == ma_phieu_header); var stocIndetail = dbConn.Select <StockInDetail>(s => s.ma_phieu_header == stockInheader.ma_phieu); var lstStockIn = stocIndetail.GroupBy( p => p.ma_chi_nhanh, (key, g) => new { ma_chi_nhanh = key, Details = g.ToList() }); foreach (var stockin in lstStockIn) { InvoiceHeader invoiceHeader = new InvoiceHeader(); string ma_phieu = ""; var loai = "IV"; //var ma_don_vi = currentUser.ma_don_vi; var yyMMdd = DateTime.Now.ToString("yyMMdd"); var existLast = dbConn.SingleOrDefault <InvoiceHeader>("SELECT TOP 1 * FROM InvoiceHeader ORDER BY id DESC"); var nextNo = 0; var yearNow = int.Parse(DateTime.Now.Year.ToString().Substring(2, 2)); if (existLast != null) { nextNo = int.Parse(existLast.ma_phieu.Substring(8, existLast.ma_phieu.Length - 8)) + 1; var yearOld = int.Parse(existLast.ma_phieu.Substring(2, 2)); if (yearOld == yearNow) { ma_phieu = loai + yyMMdd + String.Format("{0:00000}", nextNo); } else { ma_phieu = loai + yyMMdd + "00001"; } } else { ma_phieu = loai + yyMMdd + "00001"; } invoiceHeader.ma_phieu = ma_phieu; invoiceHeader.ma_don_vi = stockin.ma_chi_nhanh; invoiceHeader.ma_phieu_nhap_kho = stockInheader.ma_phieu; invoiceHeader.ma_hoa_don = so_hoa_don; invoiceHeader.ngay_hoa_don = ngay_hoa_don; invoiceHeader.ngay_tao = DateTime.Now; invoiceHeader.nguoi_tao = currentUser.ma_nguoi_dung; invoiceHeader.ngay_cap_nhat = DateTime.Parse("1900-01-01"); invoiceHeader.nguoi_cap_nhat = ""; invoiceHeader.trang_thai = "MOI"; dbConn.Insert(invoiceHeader); foreach (var de in stockin.Details) { InvoiceDetail newdata = new InvoiceDetail(); newdata.ma_phieu_header = invoiceHeader.ma_phieu; newdata.ma_san_pham = de.ma_san_pham; newdata.so_luong = items.Where(p => p.id == de.id).FirstOrDefault().so_luong_nhap; newdata.don_gia_vat = de.don_gia_vat; newdata.don_gia = de.don_gia; newdata.thue_vat = de.thue_vat; newdata.don_vi_tinh = de.don_vi_tinh; newdata.chi_phi = items.Where(p => p.id == de.id).FirstOrDefault().so_luong_nhap *de.don_gia_vat; newdata.id_nhap_kho = de.id; newdata.ma_phieu_nhap_kho = de.ma_phieu_header; newdata.thong_so_ky_thuat = de.thong_so_ky_thuat; newdata.nguoi_tao = currentUser.ma_nguoi_dung; newdata.ngay_tao = DateTime.Now; newdata.ngay_cap_nhat = DateTime.Parse("1900-01-01"); newdata.nguoi_cap_nhat = ""; newdata.trang_thai = ""; dbConn.Insert <InvoiceDetail>(newdata); } } } } else { return(Json(new { success = false, error = "Bạn không có quyền sửa dữ liệu" })); } return(Json(new { success = true })); } catch (Exception ex) { return(Json(new { success = false, error = ex.Message })); } } }
protected override Result <InvoiceDetail> ProcessReturnDetail(long branchOfficeId, InvoiceDetail detail, IDataRepositoryFactory dataRepositoryFactory, Invoice invoice) { return(new Result <InvoiceDetail>(0, 0, "ok_msg", new List <InvoiceDetail>() { detail })); }
public JsonResult Create(InvoiceDetail model) { db.InvoiceDetails.Add(model); db.SaveChanges(); return(Json(new { success = true, id = model.Id }, JsonRequestBehavior.AllowGet)); }
public ActionResult Import(HttpPostedFileBase file) { DataSet ds = file.ToDataSet(); InvoiceDetail invoiceDetail; Invoice invoice; DataTable dt = ds.Tables[0]; dt.Columns.Add("State", typeof(string)); dt.Columns.Add("Description", typeof(string)); DateTime?PODate = null; string des = ""; string state = ""; int? Warranty = null; if (ds != null) { foreach (DataTable dt2 in ds.Tables) { foreach (DataRow r in dt.Rows) { if (r[0].ToString().Equals("")) { state = "Unsuccessful"; des = "Null PONo"; r[11] = state; r[12] = des; } else { var PoNo = r[0].ToString(); invoice = db.Invoices.SingleOrDefault(e => e.PONo.Equals(PoNo, StringComparison.OrdinalIgnoreCase)); if (invoice == null) { if (!r[1].ToString().Equals("")) { PODate = Convert.ToDateTime(r[1].ToString()); } invoice = new Invoice() { PONo = r[0].ToString(), PODate = PODate }; if (!r[2].ToString().Equals("")) { var supName = r[2].ToString(); var sup = db.Suppliers.SingleOrDefault(a => a.Name.Equals(supName, StringComparison.OrdinalIgnoreCase)); if (sup != null) { invoice.SupplierId = sup.Id; } else { string Code = AutoNumberHelper.GenerateNumber(ObjectType.Supplier, db);//code tự tăng Supplier supplier = new Supplier() { Code = Code, Name = r[2].ToString() }; invoice.Supplier = supplier; } } db.Invoices.Add(invoice); db.SaveChanges(); } //Add InvoiceDetail if (!r[4].ToString().Equals("")) { Warranty = Convert.ToInt32(r[4].ToString()); } invoiceDetail = new InvoiceDetail() { InvoiceId = invoice.Id, WarrantyPeriod = Warranty, Quantity = Convert.ToInt32(r[5].ToString()), UnitPrice = Convert.ToDecimal(r[7].ToString()), }; if (!r[3].ToString().Equals("")) { var proName = r[3].ToString(); var pro = db.Products.SingleOrDefault(a => a.Name.Equals(proName, StringComparison.OrdinalIgnoreCase)); if (pro != null) { invoiceDetail.ProductId = pro.Id; } else { string Code = AutoNumberHelper.GenerateNumber(ObjectType.Product, db);//code tự tăng Product product = new Product() { Code = Code, Name = r[3].ToString() }; invoiceDetail.Product = product; } } db.InvoiceDetails.Add(invoiceDetail); db.SaveChanges(); state = "Successful"; des = "Successful"; r[11] = state; r[12] = des; } } } } FileExcel(dt); return(RedirectToAction("Index", "Invoice")); }
void LoadFacturaDetalleEdit(InvoiceDetail detail) { txtProducto.Text = detail.productname; txtCantidad.Text = detail.quantity.ToString(); txtPrecioUnitario.Text = detail.unitprice.ToString(); }
public void TestUpdateInvoiceDetail() { List<UiItem> uiitems = new List<UiItem> { new UiItem {Item=items[0], Pricing=items[0].ItemPricings[0], ItemUnits=3}, new UiItem {Item=items[1], Pricing=items[1].ItemPricings[0], ItemUnits=4}, new UiItem {Item=items[2], Pricing=items[2].ItemPricings[0], ItemUnits=5}, }; var inv = cs.CreateInvoice(customer.Id, Invoice.Type.Invoice, uiitems, "Note", "Payment Note"); var upinv = new InvoiceDetail { ItemUnits = 25, ItemPricing = items[0].ItemPricings[1] }; cs.UpdateInvoiceDetail(inv.InvoiceDetails.First().Id, upinv); var updatedinvoice=cs.GetInvoiceDetail(inv.InvoiceDetails.First().Id); Assert.IsTrue(updatedinvoice.ItemUnits == 25 && updatedinvoice.ItemPricing.UnitPrice == 52M, "Did not update correctly"); }
private void saveInvoice() { int clientID = 0; int invoiceID = 0; int InvoiceLineID = 0; Invoice invoice = null; InvoiceDetail invoiceDetailLine = null; InvoiceDetail invoiceDetail = null; int nextInvoiceNumber = 0; int policyID = 0; decimal taxAmount = 0; // get invoice id invoiceID = Convert.ToInt32(ViewState["InvoiceID"].ToString()); clientID = Core.SessionHelper.getClientId(); // current policy being edited policyID = Session["policyID"] == null ? 0 : Convert.ToInt32(Session["policyID"]); //policy = LeadPolicyManager.GetByID(policyID); if (invoiceID == 0) { invoice = new Invoice(); // get id for current lead invoice.ClaimID = Core.SessionHelper.getClaimID(); invoice.IsVoid = false; // assign client //invoice.ClientID = clientID; // hide print button //btnPrint.Visible = false; } else { invoice = InvoiceManager.Get(invoiceID); // show print button //btnPrint.Visible = true; } //invoice.PolicyID = policy.PolicyType; invoice.InvoiceDate = Convert.ToDateTime(txtInvoiceDate.Text); invoice.DueDate = Convert.ToDateTime(txtDueDate.Text); invoice.BillToName = txtBillTo.Text.Trim(); invoice.BillToAddress1 = txtBillToAddress1.Text.Trim(); invoice.BillToAddress2 = txtBillToAddress2.Text.Trim(); invoice.BillToAddress3 = txtBillToAddress3.Text.Trim(); //invoice.AdjusterID = policy.AdjusterID; //invoice.AdjusterInvoiceNumber = txtReferenceNumber.Text.Trim(); try { using (TransactionScope scope = new TransactionScope()) { if (invoiceID == 0) { // assign next invoice number to new invoice nextInvoiceNumber = InvoiceManager.GetNextInvoiceNumber(clientID); invoice.InvoiceNumber = nextInvoiceNumber; } invoiceID = InvoiceManager.Save(invoice); // save newly generated invoice id ViewState["InvoiceID"] = invoiceID.ToString(); // check for add/edit invoice detail line InvoiceLineID = ViewState["InvoiceLineID"] == null ? 0 : Convert.ToInt32(ViewState["InvoiceLineID"]); if (InvoiceLineID > 0) invoiceDetail = InvoiceDetailManager.Get(InvoiceLineID); else invoiceDetail = new InvoiceDetail(); // get detail line from gridview footer if (invoiceDetail != null) { invoiceDetailLine = getInvoiceDetailLine(); if (invoiceDetailLine.LineDate != null && !string.IsNullOrEmpty(invoiceDetailLine.LineDescription) && invoiceDetailLine.Qty > 0 && invoiceDetailLine.Rate > 0) { // update fields invoiceDetail.InvoiceID = invoiceID; invoiceDetail.InvoiceLineID = InvoiceLineID; invoiceDetail.ServiceTypeID = invoiceDetailLine.ServiceTypeID; invoiceDetail.Comments = invoiceDetailLine.Comments; invoiceDetail.isBillable = invoiceDetailLine.isBillable; invoiceDetail.LineAmount = invoiceDetailLine.LineAmount; invoiceDetail.LineDate = invoiceDetailLine.LineDate; invoiceDetail.LineDescription = invoiceDetailLine.LineDescription; invoiceDetail.Qty = invoiceDetailLine.Qty; invoiceDetail.Rate = invoiceDetailLine.Rate; invoiceDetail.UnitDescription = invoiceDetailLine.UnitDescription; invoiceDetail.Total = invoiceDetailLine.Total; // save invoice detail InvoiceDetailManager.Save(invoiceDetail); // clear ViewState["InvoiceLineID"] = "0"; // update invoice total after adding invoice = InvoiceManager.Get(invoiceID); invoice.TotalAmount = invoice.InvoiceDetail.Where(x => x.isBillable == true).Sum(x => x.LineAmount); taxAmount = (invoice.TotalAmount ?? 0) * (invoice.TaxRate / 100); //invoice.TotalAmount = invoice.TotalAmount + taxAmount; InvoiceManager.Save(invoice); // update comment updateInvoiceComment(invoice, invoiceDetail); } } // 2014-05-02 apply rule using (SpecificExpenseTypePerCarrier ruleEngine = new SpecificExpenseTypePerCarrier()) { RuleException ruleException = ruleEngine.TestRule(clientID, invoice); if (ruleException != null) { ruleException.UserID = Core.SessionHelper.getUserId(); ruleEngine.AddException(ruleException); CheckSendMail(ruleException); } } // complete transaction scope.Complete(); } // refresh invoice detail lines bindInvoiceDetails(invoiceID); // refresh invoice number on UI txtInvoiceNumber.Text = (invoice.InvoiceNumber ?? 0).ToString(); clearFields(); showToolbarButtons(); lblMessage.Text = "Invoice save successfully."; lblMessage.CssClass = "ok"; } catch (Exception ex) { lblMessage.Text = "Error while saving invoice."; lblMessage.CssClass = "error"; Core.EmailHelper.emailError(ex); } }
public string Insert(InvoiceDetail entity) { return(this.repository.Insert(entity)); }
private List <InvoiceDetail> ProcessFile(string fileName) { List <InvoiceDetail> lstInvoice = new List <InvoiceDetail>(); var DA = new OleDbDataAdapter(); var DS = new DataSet(); var ext = Path.GetExtension(fileName); var strxlsProvider = string.Empty; short rowCount; if (ext.ToLower() == ".xls") { strxlsProvider = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileName + ";Extended Properties=Excel 8.0"; } else if (ext.ToLower() == ".xlsx") { strxlsProvider = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties=Excel 12.0;"; } var objXlsConnection = new OleDbConnection(strxlsProvider); try { objXlsConnection.Open(); if (objXlsConnection.State == ConnectionState.Closed) { return(null); } var objCmd = new OleDbCommand("Select * From [Sheet1$]", objXlsConnection); objCmd.CommandType = CommandType.Text; DA.SelectCommand = objCmd; DA.Fill(DS, "XLSData"); rowCount = Convert.ToInt16(DS.Tables[0].Rows.Count); var tableHeaderValue = DS.Tables[0].Columns[0].ColumnName; lstInvoice.Add(new InvoiceDetail { SerialNo = tableHeaderValue.Trim() }); foreach (DataRow row in DS.Tables[0].Rows) { var currentItem = new InvoiceDetail(); currentItem.SerialNo = row[0].ToString().Trim(); //row["Part #"].ToString(); //currentItem.SerialNo = row["Serial Number"].ToString(); lstInvoice.Add(currentItem); } return(lstInvoice); } catch (Exception ex) { ViewBag.Exception = ex.Message; throw ex; } finally { objXlsConnection.Close(); } }
static void Main(string[] args) { using (var ctx = new ASAEntitiesContext()) { //Sender sen = new Sender() //{ // Title = "mr", // ForName1 = "Sat", // ForName2 = "Ch", // SurName = "Gat", // Email = "*****@*****.**", // AddressLine1 = "awdas", // AddressLine2 = "asdasdsa", // AddressLine3 = "www", // Country = "UK", // Postcode = "E11", // Mobile = "01111", // SenderPassword = "******", // Telephone = "5131", // Type = SenderType.Individual, // HMRCUserId = "VATDEC180a01", // HMRCPassword = "******" //}; //ctx.Sender.Add(sen); //ctx.SaveChanges(); GovTalkMessage msg = new GovTalkMessage() { }; //SuccessResponseIRmarkReceipt ir = new SuccessResponseIRmarkReceipt //{ //}; //SuccessResponse resp = new SuccessResponse() //{ // //IRmarkReceipt = ir, // AcceptedTime = DateTime.Now, // AcceptedTimeSpecified = true, // ResponseData_IsEmpty = true, //}; //ctx.SucessResponse.Add(resp); ctx.SaveChanges(); Client clt = new Client() { Name = "London Borough Of Redbride", RegNo = "Reg123456789", VATNo = "VAT123456" }; ctx.Client.Add(clt); ctx.SaveChanges(); Business bu = new Business() { BusinessName = "TEST", BusinessId = 1, TradingName = "TEST", RegisteredDate = DateTime.Now, VATRegNo = "123456", SenderId = 1 }; BusinessAddress bud = new BusinessAddress() { Line1 = "test", Line2 = "test2", Line3 = "test3", Line4 = "test5", Postcode = "IG1", Country = "UK" }; bu.BusinessAddress = bud; //ctx.BusinessAddress.Add(bud); //ctx.Business.Add(bu); // ctx.SaveChanges(); PeriodData per = new PeriodData() { StartPeriod = DateTime.Now.AddMonths(-3), EndPeriod = DateTime.Now, PeriodrefId = "2017-04", Status = SubmissionStatus.Draft }; VAT100 vat = new VAT100() { }; //per.VAT100 = vat; bu.Periods.Add(per); Client cl = new Client() { //Id = 1, Name = "consoleC", RegNo = "123", VATNo = "1234567" }; ClientAddress cd = new ClientAddress() { Address1 = "First line of add", Address2 = "Second line of add", City = "Lonodn", ClientAddressId = 1, Country = "UK", PostCode = "SS1", }; PeriodData per1 = new PeriodData() { StartPeriod = DateTime.Now.AddMonths(-3), EndPeriod = DateTime.Now, PeriodrefId = "2017-07", Status = SubmissionStatus.Draft }; bu.Periods.Add(per1); //works above cl.ClientAddress = cd; //ctx.Client.Add(cl); //ctx.SaveChanges(); //ctx.SaveChanges(); //var cup = ctx.ClientAddress.FirstOrDefault(); //cup.Address1 = "New Update address"; //var c = ctx.Client.FirstOrDefault(); //c.ClientAddress = cup; //ctx.Client.Add(c); // ctx.Client.Add(cl); InvoiceDetail invd = new InvoiceDetail(); invd.No = "LBR-1"; invd.IssueDate = DateTime.Now; invd.DueDate = DateTime.Now.AddDays(7); invd.Note = "test"; invd.Ref = "nothing"; invd.Discount = "10%"; InvoiceItem item = new InvoiceItem(); var itemguid = Guid.Parse("00000000-0000-0000-0000-000000000000"); item.Id = itemguid; item.Description = "apple"; item.Quantity = "1"; item.Price = "1"; item.Total = "1"; item.SubTotal = "1"; item.VAT = "0"; item.VATRate = "0"; List <InvoiceItem> items = new List <InvoiceItem>(); items.Add(item); var myguid = Guid.Parse("3551A09E-DE21-A325-6DF4-40281A4FEBE0"); //var inv = ctx.Invoice.Where(i => i.InvoiceId == myguid) // .Include(d => d.InvoiceDetail) // .Include(it => it.InvoiceItems) // .FirstOrDefault(); //ctx.Entry(inv).CurrentValues.SetValues(inv); //foreach (var it in items) //{ // var existingChild = inv.InvoiceItems.Where(c => c.Id == it.Id).SingleOrDefault(); // if(existingChild!=null) // { // ctx.Entry(existingChild).CurrentValues.SetValues(it); // } // else // { // Console.WriteLine("add new item"); // inv.InvoiceItems.Add(item); // } //} //ctx.Entry(inv).State = EntityState.Modified; //Invoice myinvoice = new Invoice(); //myinvoice.ClientId = 3; //myinvoice.InvoiceDetail = invd; //myinvoice.InvoiceItems = items; //ctx.Invoice.Add(myinvoice); //ctx.SaveChanges(); // bu.Periods.Add(per1); // ctx.Business.Add(bu); //cl.ClientAddress = cd; //ctx.Client.Add(cl); //ctx.SaveChanges(); } }
protected void addInvoiceToClaimDiary(Invoice invoice, InvoiceDetail invoiceDetail) { ClaimComment comment = null; // retrieve comment by reference //comment = ClaimCommentManager.GetLeadCommentByReferenceId(invoiceDetail.InvoiceLineID); if (comment == null) comment = new ClaimComment(); comment.UserId = Core.SessionHelper.getUserId(); comment.CommentDate = DateTime.Now; comment.ClaimID = invoice.ClaimID; //comment.ReferenceID = invoiceDetail.InvoiceLineID; comment.IsActive = true; // active comment.CommentText = string.Format("<div>Invoice # {0} - {1:MM-dd-yyyy} for {2} Qty:{3:N2} Rate:{4:N2} Item Total:{5:N2}</div><div>{6}</div>", invoice.InvoiceNumber, invoiceDetail.LineDate, invoiceDetail.LineDescription ?? "", invoiceDetail.Qty ?? 0, invoiceDetail.Rate ?? 0, invoiceDetail.LineAmount ?? 0, invoiceDetail.Comments ?? "" ); ClaimCommentManager.Save(comment); }
/// <summary> /// Hàm cập nhật Hóa đơn chi tiết /// </summary> /// <param name="invoiceDetail">Hóa đơn chi tiết</param> /// <returns>Trạng thái cập nhật</returns> /// Người tạo: ntxuan (20/6/2019) public int UpdateInvoiceDetail(InvoiceDetail invoiceDetail) { return(invoiceDetailDL.UpdateInvoiceDetail(invoiceDetail)); }
protected InvoiceDetail getInvoiceDetailLine(GridViewRow row) { decimal rate = 0; decimal totalAmount = 0; int? serviceTypeID = 0; DateTime date = DateTime.MaxValue; InvoiceDetail invoiceDetailLine = null; CheckBox cbxInclude = row.FindControl("cbxInclude") as CheckBox; if (cbxInclude.Checked) { invoiceDetailLine = new InvoiceDetail(); // invoiceLineID invoiceDetailLine.InvoiceLineID = (int)gvTimeExpense.DataKeys[row.RowIndex].Values[0]; // service date Label lblLineDate = row.FindControl("lblLineDate") as Label; if (!string.IsNullOrEmpty(lblLineDate.Text)) invoiceDetailLine.LineDate = Convert.ToDateTime(lblLineDate.Text); // service description Label lblLineDescription = row.FindControl("lblLineDescription") as Label; // service type serviceTypeID = (int?)gvTimeExpense.DataKeys[row.RowIndex].Values[1]; invoiceDetailLine.ServiceTypeID = serviceTypeID; // expense type id invoiceDetailLine.ExpenseTypeID = (int?)gvTimeExpense.DataKeys[row.RowIndex].Values[2]; invoiceDetailLine.LineDescription = lblLineDescription.Text; // quantity Label lblQty = row.FindControl("lblQty") as Label; invoiceDetailLine.Qty = string.IsNullOrEmpty(lblQty.Text) ? 0 : Convert.ToDecimal(lblQty.Text); // rate Label lblRate = row.FindControl("lblRate") as Label; rate = string.IsNullOrEmpty(lblRate.Text) ? 0 : Convert.ToDecimal(lblRate.Text); invoiceDetailLine.Rate = rate; // total amount // quantity Label lblLineTotal = row.FindControl("lblLineTotal") as Label; decimal.TryParse(lblLineTotal.Text.Trim().Replace(",", "").Replace("$", ""), out totalAmount); invoiceDetailLine.LineAmount = totalAmount; // comments Label lblComments = row.FindControl("lblComments") as Label; invoiceDetailLine.Comments = lblComments.Text.Trim(); invoiceDetailLine.isBillable = true; } return invoiceDetailLine; }
private void insertDetailLine(int invoiceID, string serviceDescription, string activity, string activityDescription, decimal amount, decimal qty, decimal rate, DateTime? date = null, string comments = null) { InvoiceDetail invoiceDetail = null; // invoice detail invoiceDetail = new InvoiceDetail(); invoiceDetail.InvoiceID = invoiceID; invoiceDetail.LineDate = date == null ? DateTime.Now : date; invoiceDetail.LineDescription = serviceDescription; invoiceDetail.Activity = activity; invoiceDetail.Comments = comments; invoiceDetail.Total = amount; invoiceDetail.LineAmount = amount; invoiceDetail.isBillable = true; invoiceDetail.Qty = qty; invoiceDetail.Rate = rate; invoiceDetail.ActivityDescription = activityDescription; InvoiceDetailManager.Save(invoiceDetail); }
private void bindTimeExpenseForInvoice(int claimID) { List<InvoiceDetail> invoiceDetails = new List<InvoiceDetail>(); InvoiceDetail invoiceDetail = null; decimal serviceRate = 0; decimal servicePercentage = 0; decimal rate = 0; List<ClaimService> claimServices = null; List<ClaimExpense> claimExpenses = null; using (ClaimServiceManager repository = new ClaimServiceManager()) { claimServices = repository.GetAll(claimID); } using (ClaimExpenseManager repository = new ClaimExpenseManager()) { claimExpenses = repository.GetAll(claimID); } // add claim services to invoice if (claimServices != null) { foreach (ClaimService service in claimServices) { invoiceDetail = new InvoiceDetail(); invoiceDetail.LineDate = service.ServiceDate; invoiceDetail.ServiceTypeID = service.ServiceTypeID; invoiceDetail.LineDescription = service.InvoiceServiceType.ServiceDescription; invoiceDetail.Qty = service.ServiceQty; invoiceDetail.Comments = service.ServiceDescription; serviceRate = service.InvoiceServiceType.ServiceRate ?? 0; servicePercentage = service.InvoiceServiceType.ServicePercentage ?? 0; if (serviceRate > 0) { rate = serviceRate; } else { rate = servicePercentage / 100; } invoiceDetail.LineAmount = invoiceDetail.Qty * rate; invoiceDetail.Rate = rate; // add service to invoicedetail list invoiceDetails.Add(invoiceDetail); } } // add claim expenses to invoice if (claimExpenses != null) { foreach (ClaimExpense expense in claimExpenses) { invoiceDetail = new InvoiceDetail(); invoiceDetail.ExpenseTypeID = expense.ExpenseTypeID; invoiceDetail.LineDate = expense.ExpenseDate; invoiceDetail.LineDescription = expense.ExpenseDescription; invoiceDetail.Comments = expense.ExpenseDescription; invoiceDetail.LineAmount = expense.ExpenseAmount; invoiceDetail.Qty = 1; invoiceDetail.Rate = expense.ExpenseAmount; // add expense to invoicedetail list invoiceDetails.Add(invoiceDetail); } } // bind invoice detail lines gvTimeExpense.DataSource = invoiceDetails; gvTimeExpense.DataBind(); }
public static List<InvoiceView> GetInvoiceForReport(int invoiceID) { InvoiceView invoice = null; List<InvoiceView> invoices = new List<InvoiceView>(); Invoice claimInvoice = null; Client client = null; LeadPolicy policy = null; Leads lead = null; ZipCodeMaster zipCodeMaster = null; //ClaimService mActivity = null; claimInvoice = (from x in DbContextHelper.DbContext .Invoice .Include("InvoiceDetail") .Include("InvoiceDetail.InvoiceServiceType") .Include("InvoiceDetail.InvoiceServiceType.InvoiceServiceUnit") .Include("Claim") .Include("Claim.LeadPolicy.Leads.Client") .Include("Claim.LeadPolicy.Leads.Client.StateMaster") .Include("Claim.LeadPolicy.Leads.Client.CityMaster") .Include("Claim.LeadPolicy") .Include("Claim.LeadPolicy.LeadPolicyType") .Include("Claim.ClaimService") where x.InvoiceID == invoiceID select x ).FirstOrDefault<Invoice>(); if (claimInvoice != null) { invoice = new InvoiceView(); invoice.invoiceID = claimInvoice.InvoiceID; invoice.invoiceDate = (DateTime)claimInvoice.InvoiceDate; invoice.dueDate = claimInvoice.DueDate == null ? DateTime.Now : (DateTime)claimInvoice.DueDate; invoice.invoiceNumber = (int)(claimInvoice.InvoiceNumber ?? 0); invoice.billTo = claimInvoice.BillToName; invoice.billToAddress1 = claimInvoice.BillToAddress1; invoice.billToAddress2 = claimInvoice.BillToAddress2; invoice.billToAddress3 = claimInvoice.BillToAddress3; invoice.totalAmount = claimInvoice.TotalAmount ?? 0; //invoice.activity = claimInvoice.Claim.ClaimService NEW OC 9/30/14 //invoice.adjusterInvoiceNumber = claimInvoice.AdjusterInvoiceNumber; // get policy type associated with invoice //claimInvoice.Lead.LeadPolicies.FirstOrDefault(x => x.PolicyType == claimInvoice.PolicyTypeID); //mActivity = claimInvoice.Claim.ClaimService.FirstOrDefault(); //invoice.activity = mActivity.Activity; policy = claimInvoice.Claim.LeadPolicy; if (policy != null) { invoice.policyType = policy.LeadPolicyType == null ? "" : policy.LeadPolicyType.Description; invoice.policyNumber = policy.PolicyNumber; lead = policy.Leads; } invoice.claimNumber = claimInvoice.Claim.AdjusterClaimNumber; invoice.insurerFileNo = claimInvoice.Claim.InsurerClaimNumber; invoice.adjusterInvoiceNumber = claimInvoice.InvoiceNumber.ToString(); if (lead != null) { invoice.claimantName = lead.InsuredName;//policyHolderName; OC 9/30/14 invoice.claimantAddress1 = lead.LossAddress; invoice.claimantAddress2 = lead.LossAddress2; invoice.claimantAddress3 = string.Format("{0}, {1} {2}", lead.CityName ?? "", lead.StateName ?? "", lead.Zip ?? ""); client = lead.Client; } invoice.taxRate = claimInvoice.TaxRate; if (claimInvoice.Claim.LossDate != null) invoice.claimDate = (DateTime)claimInvoice.Claim.LossDate; invoice.invoiceLines = claimInvoice.InvoiceDetail.ToList(); // add sales tax if (invoice.taxRate > 0) { InvoiceDetail invoiceTaxLine = new InvoiceDetail(); invoiceTaxLine.InvoiceID = invoice.invoiceID; invoiceTaxLine.LineDescription = "Sales Tax"; //invoiceTaxLine.isBillable = true; invoiceTaxLine.LineAmount = invoice.totalAmount * (invoice.taxRate / 100); invoiceTaxLine.Activity = invoice.activity; invoice.invoiceLines.Add(invoiceTaxLine); } if (client != null) { client = lead.Client; invoice.clientName = client.BusinessName; invoice.clientAddress1 = client.StreetAddress1; invoice.clientAddress2 = client.StreetAddress2; string stateName = client.StateMaster != null ? client.StateMaster.StateCode : ""; string cityName = client.CityMaster != null ? client.CityMaster.CityName : ""; string zipCode = client.ZipCode ?? ""; // this is badly designed. if (!string.IsNullOrEmpty(zipCode)) { zipCodeMaster = ZipCode.Get(zipCode); if (zipCodeMaster != null) zipCode = zipCodeMaster.ZipCode; } invoice.clientAddress3 = cityName + ", " + stateName + " " + zipCode; invoice.clientPhone = client.PrimaryPhoneNo; invoice.clientFax = client.SecondaryPhoneNo; invoice.clientEmail = client.PrimaryEmailId; invoice.federalIDNo = client.FederalIDNo; invoice.logoPath = string.Format("{0}/ClientLogo/{1}.jpg", ConfigurationManager.AppSettings["appURL"].ToString(), client.ClientId); } else { invoice.logoPath = ConfigurationManager.AppSettings["appURL"].ToString() + "/images/claim_ruler_logo.jpg"; invoice.clientName = "Claim Ruler Demo"; invoice.clientAddress1 = "400 East Las Olas Blvd"; invoice.clientAddress2 = "Suite 404"; invoice.clientAddress3 = "Ft. Lauderdale, FL 33301"; invoice.clientPhone = "999-999-9999"; invoice.clientFax = "999-999-9999"; invoice.clientEmail = "*****@*****.**"; invoice.federalIDNo = "99999999"; } invoices.Add(invoice); } return invoices; }
private void saveInvoice() { int clientID = 0; int invoiceID = 0; int InvoiceLineID = 0; Invoice invoice = null; InvoiceDetail invoiceDetailLine = null; InvoiceDetail invoiceDetail = null; int nextInvoiceNumber = 0; decimal taxAmount = 0; clientID = Core.SessionHelper.getClientId(); invoiceID = ViewState["InvoiceID"] == null ? 0 : Convert.ToInt32(ViewState["InvoiceID"].ToString()); if (invoiceID == 0) { invoice = new Invoice(); // get id for current lead invoice.ClaimID = Core.SessionHelper.getClaimID(); invoice.IsVoid = false; } else { invoice = InvoiceManager.Get(invoiceID); } //invoice.PolicyID = policy.PolicyType; invoice.InvoiceDate = Convert.ToDateTime(txtInvoiceDate.Text); invoice.DueDate = Convert.ToDateTime(txtDueDate.Text); invoice.BillToName = txtBillTo.Text.Trim(); invoice.BillToAddress1 = txtBillToAddress1.Text.Trim(); invoice.BillToAddress2 = txtBillToAddress2.Text.Trim(); invoice.BillToAddress3 = txtBillToAddress3.Text.Trim(); try { using (TransactionScope scope = new TransactionScope()) { if (invoiceID == 0) { // assign next invoice number to new invoice nextInvoiceNumber = InvoiceManager.GetNextInvoiceNumber(clientID); invoice.InvoiceNumber = nextInvoiceNumber; } invoiceID = InvoiceManager.Save(invoice); // save newly generated invoice id ViewState["InvoiceID"] = invoiceID.ToString(); #region get detail line from gridview foreach (GridViewRow row in gvTimeExpense.Rows) { // get detail line from grid invoiceDetailLine = getInvoiceDetailLine(row); if (invoiceDetailLine != null) { if (invoiceDetailLine.InvoiceLineID > 0) invoiceDetail = InvoiceDetailManager.Get(InvoiceLineID); else invoiceDetail = new InvoiceDetail(); // update fields invoiceDetail.InvoiceID = invoiceID; invoiceDetail.ServiceTypeID = invoiceDetailLine.ServiceTypeID; invoiceDetail.ExpenseTypeID = invoiceDetailLine.ExpenseTypeID; invoiceDetail.Comments = invoiceDetailLine.Comments; invoiceDetail.isBillable = invoiceDetailLine.isBillable; invoiceDetail.LineAmount = invoiceDetailLine.LineAmount; invoiceDetail.LineDate = invoiceDetailLine.LineDate; invoiceDetail.LineDescription = invoiceDetailLine.LineDescription; invoiceDetail.Qty = invoiceDetailLine.Qty; invoiceDetail.Rate = invoiceDetailLine.Rate; invoiceDetail.UnitDescription = invoiceDetailLine.UnitDescription; invoiceDetail.Total = invoiceDetailLine.Total; // save invoice detail InvoiceDetailManager.Save(invoiceDetail); } } // foreach #endregion // update invoice total after adding invoice = InvoiceManager.Get(invoiceID); invoice.TotalAmount = invoice.InvoiceDetail.Where(x => x.isBillable == true).Sum(x => x.LineAmount); taxAmount = (invoice.TotalAmount ?? 0) * (invoice.TaxRate / 100); InvoiceManager.Save(invoice); // add invoice to claim diary comment addInvoiceToClaimDiary(invoice, invoiceDetail); // 2014-05-02 apply rule using (SpecificExpenseTypePerCarrier ruleEngine = new SpecificExpenseTypePerCarrier()) { RuleException ruleException = ruleEngine.TestRule(clientID, invoice); if (ruleException != null) { ruleException.UserID = Core.SessionHelper.getUserId(); ruleEngine.AddException(ruleException); CheckSendMail(ruleException); } } // complete transaction scope.Complete(); } // using // refresh invoice number on UI txtInvoiceNumber.Text = (invoice.InvoiceNumber ?? 0).ToString(); showToolbarButtons(); lblMessage.Text = "Invoice was generated successfully."; lblMessage.CssClass = "ok"; } catch (Exception ex) { lblMessage.Text = "Error while saving invoice."; lblMessage.CssClass = "error"; Core.EmailHelper.emailError(ex); } }
public void bindData(int invoiceID) { int claimID = 0; int clientID = 0; int leadID = 0; int policyID = 0; Claim claim = null; Invoice invoice = null; InvoiceDetail invoiceDetail = null; Leads lead = null; List<InvoiceDetail> invoiceDetails = null; // save invoice id ViewState["InvoiceID"] = invoiceID.ToString(); invoice = InvoiceManager.Get(invoiceID); if (invoice != null) { claimID = invoice.ClaimID; claim = ClaimsManager.Get(claimID); policyID = claim.PolicyID; leadID = claim.LeadPolicy.Leads.LeadId; lead = claim.LeadPolicy.Leads; clientID = (int)lead.ClientID; // get policy type if (claim.LeadPolicy != null && claim.LeadPolicy.LeadPolicyType != null) lblPolicyType.Text = claim.LeadPolicy.LeadPolicyType.Description; // get policy number if (claim.LeadPolicy != null) lblPolicyNumber.Text = claim.LeadPolicy.PolicyNumber; // get insurer claim number lblInsurerClaimNumber.Text = claim.InsurerClaimNumber; } else { // new invoice // get id for current lead claimID = Core.SessionHelper.getClaimID(); // get id for current lead leadID = Core.SessionHelper.getLeadId(); // get client id clientID = Core.SessionHelper.getClientId(); // get current policy policyID = Core.SessionHelper.getPolicyID(); // get lead/claim lead = LeadsManager.GetByLeadId(leadID); // get policy type lblPolicyType.Text = LeadPolicyManager.GetPolicyTypeDescription(policyID); // get policy number lblPolicyNumber.Text = LeadPolicyManager.GetPolicyNumber(policyID); // get insurer claim number lblInsurerClaimNumber.Text = ClaimsManager.getInsurerClaimNumber(claimID); } // get policy information if (lead != null) { lblClient.Text = string.Format("<b>{0} {1}<br/>{2}<br/>{3}<br/>{4}, {5} {6}</b>", lead.ClaimantFirstName ?? "", //0 lead.ClaimantLastName ?? "", //1 lead.LossAddress ?? "", //2 lead.LossAddress2 ?? "", //3 lead.CityName ?? "", //4 lead.StateName ?? "", //5 lead.Zip ?? "" //6 ); } if (invoiceID == 0) { // new invoice txtInvoiceDate.Text = DateTime.Now.ToShortDateString(); invoiceDetail = new InvoiceDetail(); invoiceDetail.LineDate = DateTime.Now; invoiceDetails = new List<InvoiceDetail>(); invoiceDetails.Add(invoiceDetail); gvInvoiceLines.DataSource = invoiceDetails; gvInvoiceLines.DataBind(); // hide empty row gvInvoiceLines.Rows[0].Visible = false; // hide print button //btnPrint.Visible = false; // hiden invoice number //pnlInvoiceNumber.Visible = false; } else { // edit invoice // show print button btnPrint.Visible = true; lbtnEmail.Visible = true; if (invoice != null && invoice.InvoiceDetail != null) { txtInvoiceDate.Text = string.Format("{0:MM/dd/yyyy}", invoice.InvoiceDate); txtDueDate.Text = string.Format("{0:MM/dd/yyyy}", invoice.DueDate); txtBillTo.Text = invoice.BillToName; txtBillToAddress1.Text = invoice.BillToAddress1; txtBillToAddress2.Text = invoice.BillToAddress2; txtBillToAddress3.Text = invoice.BillToAddress3; // reference txtReferenceNumber.Text = (invoice.InvoiceNumber ?? 0).ToString(); // show total txtTotalAmount.Text = string.Format("{0:N2}", invoice.TotalAmount); // sort line items by date gvInvoiceLines.DataSource = invoice.InvoiceDetail.OrderBy(x => x.LineDate); gvInvoiceLines.DataBind(); // show invoice numebr //pnlInvoiceNumber.Visible = true; txtInvoiceNumber.Text = string.Format("{0:N0}", invoice.InvoiceNumber ?? 0); } } bindInvoiceServices(); contractGrid.DataBind(); }
public void UpdateItem(InvoiceDetail invoiceDetailToModify) { this._mock.updateItem(invoiceDetailToModify); }
public static QueueManager CreateNewQueueManager(Invoice invoice, InvoiceDetail invoiceDetail) { Service_cu service; if (invoiceDetail.Service_CU_ID != null) { service = GetService(Convert.ToInt32(invoiceDetail.Service_CU_ID)); } else { return(null); } List <StationPointStage_cu> serviceType_StationPointStagesList = null; List <StationPointStage_cu> ServiceCategory_StationPointStagesList = null; List <StationPointStage_cu> service_StationPointStagesList = null; ServiceCategory_cu serviceCategory = GetServiceCategory(Convert.ToInt32(service.ServiceCategory_CU_ID)); ServiceCategory_StationPoint_cu serviceCategoryStation = null; if (serviceCategory != null) { serviceCategoryStation = GetServiceCategoryStationPoint(serviceCategory.ID); } if (serviceCategoryStation != null) { ServiceCategory_StationPointStagesList = GetStationPointStagesList(serviceCategoryStation.StationPoint_CU_ID, true); } DB_ServiceType serviceType = (DB_ServiceType)service.ServiceType_P_ID; ServiceType_StationPoint_cu serviceTypeStation = ServiceType_StationPoint_cu.ItemsList.Find( item => Convert.ToInt32(item.ServiceType_P_ID).Equals((int)serviceType)); if (serviceTypeStation != null) { serviceType_StationPointStagesList = GetStationPointStagesList(serviceTypeStation.StationPoint_CU_ID, true); } Service_StationPoint_cu serviceStation = GetServiceStationPoint(service.ID); if (serviceStation != null) { service_StationPointStagesList = GetStationPointStagesList(serviceStation.StationPoint_CU_ID, true); } if (serviceStation != null) { return(CreateNewQueueManager(invoice, invoiceDetail, serviceStation, service_StationPointStagesList)); } if (serviceCategoryStation != null) { return(CreateNewQueueManager(invoice, invoiceDetail, serviceCategoryStation, ServiceCategory_StationPointStagesList)); } if (serviceTypeStation != null) { return(CreateNewQueueManager(invoice, invoiceDetail, serviceTypeStation, serviceType_StationPointStagesList)); } return(null); }
public void AddInvoiceDetail(InvoiceDetail invoiceDetail) { context.InvoiceDetails.Add(invoiceDetail); context.SaveChanges(); }
public async Task <EntityApiResponse <InvoiceDetail> > UpdateInvoiceAsync(InvoiceDetail invoiceDetail, string currentUserId) { // Do the checks if (invoiceDetail is null) { throw new ArgumentNullException(nameof(invoiceDetail)); } if (invoiceDetail.InvoiceItems is null || invoiceDetail.InvoiceItems.Count < 1) { return(new EntityApiResponse <InvoiceDetail>(error: "Invoice has no items")); } if (invoiceDetail.InvoiceItems.Any(item => item.Quantity < 1)) { return(new EntityApiResponse <InvoiceDetail>(error: "Invoice can't have an item with quantity zero")); } var invoice = await _invoiceRepository.GetByIdAsync(invoiceDetail.Id); if (invoice is null) { return(new EntityApiResponse <InvoiceDetail>(error: "Invoice does not exist")); } // Customer which points to the newly updated customer // or the same customer before updating the invoice Customer customer = null; // Indicates if a customer has been selected with the new invoice details var belongsToCustomer = !(invoiceDetail.Customer is null); // Indicates if the invoice is paid/sub-paid by points var paidWithPoints = invoiceDetail.PaidWithPoints > 0; // Indicates if invoice before updated did belong to a customer var oldInvoiceBelongToCustomer = !string.IsNullOrEmpty(invoice.CustomerId); if (belongsToCustomer) { customer = await _customerRepository.GetByIdAsync(invoiceDetail.Customer?.Id); if (customer is null) { return(new EntityApiResponse <InvoiceDetail>(error: "Customer does not exist")); } if (paidWithPoints) { if (!_settings.PointsValues.TryGetValue(invoiceDetail.PaidWithPoints, out var amount)) { return(new EntityApiResponse <InvoiceDetail>(error: $"{invoiceDetail.PaidWithPoints} points are not a standard exchangement")); } if (oldInvoiceBelongToCustomer && customer.Id != invoice.CustomerId && customer.Points < invoiceDetail.PaidWithPoints) { return(new EntityApiResponse <InvoiceDetail>(error: "Customer doesn't have enough points")); } // Basically this check is for when the same customer just gets back and takes a new item // his old points that he paid with should be considered too else if (oldInvoiceBelongToCustomer && customer.Id == invoice.Id && customer.Points + invoice.PaidWithPoints < invoiceDetail.PaidWithPoints) { return(new EntityApiResponse <InvoiceDetail>(error: "Customer doesn't have enough points")); } } } // Check if the current user is in his specified session var now = DateTime.UtcNow; Session session = null; if (_settings.RestrictPaymentOnSession) { session = await _sessionRepository.Table .FirstOrDefaultAsync(s => now >= s.StartDate && now <= s.EndDate && s.UserId == currentUserId); if (session is null) { return(new EntityApiResponse <InvoiceDetail>(error: "Can't add invoice, current session belongs to another user")); } } // Get info needed about the old invoice items var invoiceNewPoints = 0; var invoiceOldPoints = invoice.Points; // Get the ones that should be deleted, add their quantities, delete them var oldItems = invoice.InvoiceItems.ToList(); var itemsToBeDeleted = oldItems .Where(i => !invoiceDetail.InvoiceItems.Any(itemDetail => itemDetail.Id == i.Id)); foreach (var item in itemsToBeDeleted) { var stock = await _stockRepository.GetByIdAsync(item.Stock?.Id); stock.Quantity += item.Quantity; stock.LastModifiedDate = DateTime.UtcNow; stock.ModifiedById = currentUserId; await _stockRepository.UpdateAsync(stock); } await _invoiceItemRepository.DeleteAsync(itemsToBeDeleted); // Go over new and updated items in the invoice details foreach (var invoiceItem in invoiceDetail.InvoiceItems) { var stock = await _stockRepository.GetByIdAsync(invoiceItem.Stock?.Id); if (stock is null) { continue; } InvoiceItem item = null; if (string.IsNullOrEmpty(item.Id)) { item = new InvoiceItem { Description = invoiceItem.Description?.Trim(), Discount = invoiceItem.Discount, Price = invoiceItem.Price, FinalPrice = invoiceItem.FinalPrice, Quantity = invoiceItem.Quantity, InvoiceId = invoice.Id, StockId = stock.Id, OrganizationId = invoice.OrganizationId, CreatedById = currentUserId, ModifiedById = currentUserId }; await _invoiceItemRepository.InsertAsync(item); stock.Quantity -= item.Quantity; } // Update the already existing ones else { item = oldItems.FirstOrDefault(i => i.Id == invoiceItem.Id); if (item is null) { continue; } stock.Quantity += item.Quantity - invoiceItem.Quantity; item.Quantity = invoiceItem.Quantity; item.Discount = invoice.Discount; item.Description = invoiceItem.Description?.Trim(); item.Price = invoiceItem.Price; item.FinalPrice = invoiceItem.FinalPrice; item.ModifiedById = currentUserId; item.LastModifiedDate = DateTime.UtcNow; await _invoiceItemRepository.UpdateAsync(item); } stock.LastModifiedDate = DateTime.UtcNow; stock.ModifiedById = currentUserId; await _stockRepository.UpdateAsync(stock); invoiceNewPoints += stock.Points * item.Quantity; } if (belongsToCustomer) { // if the current customer is different than the old customer if (oldInvoiceBelongToCustomer && customer.Id != invoice.CustomerId) { // Get the old customer var oldCustomer = await _customerRepository.GetByIdAsync(invoice.CustomerId); // Add to the old customer the old points that he paid with oldCustomer.Points += invoice.PaidWithPoints; // Remove from the old customer the old points that he got from the invoice oldCustomer.Points -= invoiceOldPoints; await _customerRepository.UpdateAsync(oldCustomer); customer.Points -= invoiceDetail.PaidWithPoints; } // Same customer else if (oldInvoiceBelongToCustomer && customer.Id == invoice.CustomerId) { // customer's points were initially 650k // bought stuff with $65 --> 60$ with points so take away 600k and $5 cash as payment // now he got back stuff and his current invoice is 20$ // he bought them with points (200k) soo he should now have 450k points and $5 returned to him // or he could buy stuff with $25.. $20 with points and $5 cash // so points added to him should be the difference between if (paidWithPoints) { customer.Points += invoice.PaidWithPoints - invoiceDetail.PaidWithPoints; } customer.Points -= invoiceOldPoints; } // There wasn't any customer selected when the invoice was added // but when the invoice was updated a customer has been added else if (!oldInvoiceBelongToCustomer && paidWithPoints) { customer.Points -= invoiceDetail.PaidWithPoints; } // Add the invoice points to the current customer anyways customer.Points += invoiceNewPoints; await _customerRepository.UpdateAsync(customer); } // Invoice did belong to a customer but customer was unselected else if (!belongsToCustomer && oldInvoiceBelongToCustomer) { customer.Points -= invoiceOldPoints; customer.Points += invoice.PaidWithPoints; await _customerRepository.UpdateAsync(customer); } // Update the related payment var payment = await _paymentRepository.Table .FirstOrDefaultAsync(p => p.InvoiceId == invoice.Id); payment.CashEntered = invoiceDetail.CashierPayment?.CashEntered ?? 0m; payment.Change = invoiceDetail.CashierPayment?.Change ?? 0m; payment.LastModifiedDate = DateTime.UtcNow; payment.ModifiedById = currentUserId; payment.SessionId = session?.Id; await _paymentRepository.UpdateAsync(payment); invoice.OriginalPrice = invoiceDetail.OriginalPrice; invoice.FinalPrice = invoiceDetail.FinalPrice; invoice.Discount = invoiceDetail.Discount; invoice.Note = invoiceDetail.Note?.Trim(); invoice.Points = invoiceNewPoints; invoice.PaidWithPoints = invoiceDetail.PaidWithPoints; invoice.ModifiedById = currentUserId; invoice.LastModifiedDate = DateTime.UtcNow; invoice.CustomerId = customer.Id; await _invoiceRepository.UpdateAsync(invoice); return(new EntityApiResponse <InvoiceDetail>(entity: new InvoiceDetail(invoice, payment))); }
public void RemoveInvoiceDetail(InvoiceDetail invoiceDetail) { context.InvoiceDetails.Remove(invoiceDetail); context.SaveChanges(); }
public static Result <Invoice> UpdateDetails(Invoice invoice, IDataRepositoryFactory dataRepositoryFactory) { var detailsRepo = dataRepositoryFactory.GetCustomDataRepositories <IInvoiceDetailRepository>(); var productUnitsRepo = dataRepositoryFactory.GetCustomDataRepositories <IUnitProductEquivalenceRepository>(); var oldDetails = detailsRepo.GetByInvoiceId(invoice.Id).ToList(); var newDetails = invoice.InvoiceDetails.Where(x => x.Id == 0).ToList(); var modifiedDetails = invoice.InvoiceDetails.Except(newDetails).ToList().Except(oldDetails).ToList(); var untouchedDetails = invoice.InvoiceDetails.Intersect(oldDetails).ToList(); oldDetails.ForEach(d => { bool existe = (modifiedDetails.Exists(x => x.ProductId == d.ProductId && d.ParentId == null) || untouchedDetails.Exists(x => x.ProductId == d.ProductId && d.ParentId == null)); if (!existe) { detailsRepo.Remove(d.Id); var result = InventoryHelper.AddInventory(d, invoice, dataRepositoryFactory); if (result.Status < 0) { throw new Exception(result.Message); } } }); Invoice newinvoice = new Invoice(invoice); newinvoice.InvoiceDetails = newDetails; AddDetails(newinvoice, dataRepositoryFactory); modifiedDetails.ForEach(d => { if (!d.Product.IsService) { var oldDetail = oldDetails.Where(x => x.Id == d.Id).FirstOrDefault(); decimal currentQuantity = (decimal)ProductsHelper.ConvertToProductPrincipalUnit( d.Quantity, d.UnitId.Value, d.Product.ProductUnits == null || d.Product.ProductUnits.Count == 0 ? productUnitsRepo.GetProductUnits(d.ProductId).ToList() : d.Product.ProductUnits ).Data.FirstOrDefault(); decimal oldQuantity = (decimal)ProductsHelper.ConvertToProductPrincipalUnit( oldDetail.Quantity, oldDetail.UnitId.Value, oldDetail.Product.ProductUnits == null || oldDetail.Product.ProductUnits.Count == 0 ? productUnitsRepo.GetProductUnits(oldDetail.ProductId).ToList() : oldDetail.Product.ProductUnits ).Data.FirstOrDefault(); decimal difference = currentQuantity - oldQuantity; if (difference > 0) { var warehouse = invoice.BranchOffice.Warehouses?.Where(y => y.Id == d.WarehouseId).FirstOrDefault(); if (warehouse == null) { throw new Exception("warehouseError_msg"); } InvoiceDetail nuevoDetalle = new InvoiceDetail() { Product = d.Product, ProductId = d.ProductId, Quantity = difference, UnitId = d.UnitId ?? null, Unit = d.Unit ?? null }; var result = InventoryHelper.UpdateInventory(nuevoDetalle, warehouse, invoice, dataRepositoryFactory); if (result.Status < 0) { throw new Exception(result.Message); } } else if (difference < 0) { InvoiceDetail detailToInsert = new InvoiceDetail(d); detailToInsert.Quantity = Math.Abs(difference); detailToInsert.Unit = d.Product.ProductUnits.Where(u => u.IsPrimary).FirstOrDefault().Unit; detailToInsert.UnitId = detailToInsert.Unit.Id; var result = InventoryHelper.AddInventory(detailToInsert, invoice, dataRepositoryFactory); if (result.Status < 0) { throw new Exception(result.Message); } } detailsRepo.Update(d); } else { detailsRepo.Update(d); } }); UpdateInvoiceTaxes(invoice, dataRepositoryFactory); return(new Result <Invoice>(0, 0, "ok_msg", new List <Invoice>() { invoice })); }
public void UpdateInvoiceDetail(InvoiceDetail invoiceDetail) { context.InvoiceDetails.Update(invoiceDetail); context.SaveChanges(); }
public string Update(InvoiceDetail entity) { return(this.repository.Update(entity)); }
private void bindTimeExpenseForInvoice(int claimID) { List <InvoiceDetail> invoiceDetails = new List <InvoiceDetail>(); InvoiceDetail invoiceDetail = null; decimal serviceRate = 0; decimal servicePercentage = 0; decimal rate = 0; List <ClaimService> claimServices = null; List <ClaimExpense> claimExpenses = null; using (ClaimServiceManager repository = new ClaimServiceManager()) { claimServices = repository.GetAll(claimID); } using (ClaimExpenseManager repository = new ClaimExpenseManager()) { claimExpenses = repository.GetAll(claimID); } // add claim services to invoice if (claimServices != null) { foreach (ClaimService service in claimServices) { invoiceDetail = new InvoiceDetail(); invoiceDetail.LineDate = service.ServiceDate; invoiceDetail.ServiceTypeID = service.ServiceTypeID; invoiceDetail.LineDescription = service.InvoiceServiceType.ServiceDescription; invoiceDetail.Qty = service.ServiceQty; invoiceDetail.Comments = service.ServiceDescription; serviceRate = service.InvoiceServiceType.ServiceRate ?? 0; servicePercentage = service.InvoiceServiceType.ServicePercentage ?? 0; if (serviceRate > 0) { rate = serviceRate; } else { rate = servicePercentage / 100; } invoiceDetail.LineAmount = invoiceDetail.Qty * rate; invoiceDetail.Rate = rate; // add service to invoicedetail list invoiceDetails.Add(invoiceDetail); } } // add claim expenses to invoice if (claimExpenses != null) { foreach (ClaimExpense expense in claimExpenses) { invoiceDetail = new InvoiceDetail(); invoiceDetail.ExpenseTypeID = expense.ExpenseTypeID; invoiceDetail.LineDate = expense.ExpenseDate; invoiceDetail.LineDescription = expense.ExpenseDescription; invoiceDetail.Comments = expense.ExpenseDescription; invoiceDetail.LineAmount = expense.ExpenseAmount; invoiceDetail.Qty = 1; invoiceDetail.Rate = expense.ExpenseAmount; // add expense to invoicedetail list invoiceDetails.Add(invoiceDetail); } } // bind invoice detail lines gvTimeExpense.DataSource = invoiceDetails; gvTimeExpense.DataBind(); }
public ActionResult Index(FormCollection formCollection) { try { var invoice = new invoice(); var invoiceData = new invoiceData(); var currency = _currencySvc.GetById(int.Parse(formCollection["CurrencyId"])); invoice.invoiceData = invoiceData; invoiceData.id = "data"; //Thuộc tính ID của thẻ <invoiceData ID="data"> var sss = Bkav.eHoadon.XML.eHoadon.Entity.Create.invoiceDataInvoiceType.Item01GTKT; //Thông tin chung về hóa đơn invoiceData.invoiceAppRecordId = getRandomNumber(999999); //ID của bản ghi được quản lý bởi phần mềm Lập hóa đơn của DN. invoiceData.invoiceType = sss; //Ký hiệu loại hóa đơn var releaseId = -1; if (int.TryParse(formCollection["ResleaseIdNo"], out releaseId)) { var release = _listReleaseInvoiceSvc.GetById(releaseId); invoiceData.templateCode = release.No; invoiceData.invoiceSeries = release.SerialInvoice; } else { invoiceData.templateCode = formCollection["ResleaseIdNo"]; //"01GTKT0/089"; //Ký hiệu mẫu hóa đơn invoiceData.invoiceSeries = formCollection["Serial"]; //"AC/14E"; } //"01GTKT0/089"; //Ký hiệu mẫu hóa đơn invoiceData.invoiceNumber = formCollection["InvoiceNumber"]; //createUid(20); //Số hóa đơn hiện tại có chiều dài 7 chữ số invoiceData.invoiceName = "Hóa đơn giá trị gia tăng"; //Tên loại hóa đơn invoiceData.invoiceIssuedDate = DateTime.Now; //Ngày xuất hóa đơn invoiceData.signedDate = DateTime.Now; //Ngày ký số lên hóa đơn, có thể lấy là ngày xuất hóa đơn invoiceData.submittedDate = DateTime.Now; //Ngày gửi hóa đơn lên CQT, tương đương với ngày đẩy vào thiết bị xác thực, có thể lấy là ngày xuất hóa đơn invoiceData.currencyCode = currency != null ? currency.CurrencyCode : ""; //Ký hiệu mã tiền tệ sử dụng: VND, USD,... //invoiceData.isAdjusted = 1; //Trạng thái hóa đơn: 1: hóa đơn thường, 5: hóa đơn điều chỉnh,.... trong file Doc mô tả chuẩn XML //Thông tin thanh toán hóa đơn var paymentInfo = new paymentInfo(); paymentInfo.paymentMethodName = formCollection["PaymentsType"]; //"Tiền mặt"; //Thông tin về phương thức thanh toán hóa đơn: Tiền mặt, Tiền mặt/Chuyển khoản, Chuyển khoản List <paymentInfo> payments = invoiceData.payments; payments.Add(paymentInfo); //Thông tin người bán (Seller) //invoiceData.sellerAppRecordId = createUid(20); //Tùy doanh nghiệp có thể dùng chung trường ID của bản ghi được quản lý bởi phần mềm Lập hóa đơn của DN. invoiceData.sellerLegalName = formCollection["CompanyNameAcc"]; //"CÔNG TY TNHH DỊCH VỤ TIN HỌC FPT (Demo)"; //Tên doanh nghiệp bán hàng hóa dịch vụ var random = new Random(); //String tin = allowTin[random.Next(allowTin.Length)]; //invoiceData.sellerTaxCode = tin; //Mã số thuến người bán invoiceData.sellerAddressLine = formCollection["AddressAcc"]; //"Tầng 6 Tòa nhà Thành Công, Dịch Vọng Hậu, Cầu Giấy, Hà Nội"; //Địa chỉ người bán invoiceData.sellerPhoneNumber = formCollection["PhoneAcc"]; //"0812345678"; //Số điện thoại người bán invoiceData.sellerFaxNumber = formCollection["PhoneAcc"]; //"0812345678"; //invoiceData.sellerContactPersonName = formCollection["sellerAddressLine"];// "Đỗ C"; //Tên người đại diện công ty đăng ký kinh doanh //invoiceData.sellerEmail = formCollection["sellerAddressLine"]; //"*****@*****.**"; //email đăng ký kinh doanh //invoiceData.sellerSignedPersonName = formCollection["sellerAddressLine"];// "Phạm A"; //Người bán hàng hoặc người thực hiện việc xuất hóa đơn //invoiceData.sellerSubmittedPersonName = formCollection["sellerAddressLine"]; //"Nguyễn B"; //Người thực hiện phê duyệt hoặc gửi hóa đơn đi xác thực //Thông tin người mua ( Buyer) invoiceData.buyerLegalName = formCollection["CompanyName"]; // "Công ty Thử Nghiệm"; //Tên doanh nghiệp bán hàng hóa dịch vụ invoiceData.buyerDisplayName = formCollection["CustomerName"]; //"Nguyễn Tiến X"; invoiceData.buyerTaxCode = formCollection["CompanyCode"]; //"0104128565"; //Mã số thuến người mua invoiceData.buyerAddressLine = formCollection["Address"]; //"15 Nguyễn Du - Hai Bà Trưng - Hà Nội"; //Địa chỉ người bán invoiceData.buyerPhoneNumber = "0812345678"; //Số điện thoại người mua invoiceData.buyerFaxNumber = "0812345678"; invoiceData.buyerEmail = formCollection["BuyerEmail"]; //"*****@*****.**"; //email đăng ký kinh doanh invoiceData.invoiceNote = formCollection["Comment"]; //Thông tin các mặt hàng invoiceData.items = new List <invoiceItem>(); //Thêm mặt hàng thứ nhất var invoiceItem = new invoiceItem(); //invoiceItemList[0].promotion uint i = 1; var data = formCollection.AllKeys.Count(); for (int j = 0; j < (data - 27) / 10; j++) { invoiceItem = new invoiceItem(); var vatCategoryPercentage = 0; int.TryParse(formCollection[string.Format("invoiceItemList[{0}].vatCategoryPercentage", j)], out vatCategoryPercentage); var itemTotalAmountWithoutVat = 0; int.TryParse(formCollection[string.Format("invoiceItemList[{0}].itemTotalAmountWithoutVat", j)], out itemTotalAmountWithoutVat); invoiceItem.lineNumber = i; //Dòng hóa đơn invoiceItem.itemCode = formCollection[string.Format("invoiceItemList[{0}].itemCode", j)]; //Mã hàng hóa invoiceItem.itemName = formCollection[string.Format("invoiceItemList[{0}].itemName", j)]; //Tên hàng hóa invoiceItem.unitName = formCollection[string.Format("invoiceItemList[{0}].unitCode", j)]; ; //Đơn vị tính try { invoiceItem.quantity = int.Parse(formCollection[string.Format("invoiceItemList[{0}].quantity", j)]); //Số lượng invoiceItem.unitPrice = int.Parse(formCollection[string.Format("invoiceItemList[{0}].unitPrice", j)]); } catch (Exception) { // Cho phép nhập thành tiền invoiceItem.quantity = 0; invoiceItem.unitPrice = 0; } //Đơn giá invoiceItem.vatPercentage = vatCategoryPercentage; //Thuế xuất của mặt hàng: -2: không kê khai thuế, -1: không chịu thuế, 0: 0%, 5:5%, 10:10%..... invoiceItem.itemTotalAmountWithoutVat = itemTotalAmountWithoutVat; //Tổng tiền chưa thuế của dòng hóa đơn: = số lượng * đơn giá invoiceData.items.Add(invoiceItem); i++; } invoiceData.invoiceTaxBreakdowns = new List <invoiceTaxBreakdownInfo>(); //Tạo thông tin cho mức thuế xuất 5% var invoiceTaxBreakdownInfo = new invoiceTaxBreakdownInfo(); var vatCatTaxAmt = 0; var vatCatTaxableAmt = 0; var vatPercentage = 0; int.TryParse(formCollection["invoiceTaxBreakdownList[0].vatCategoryPercentage"] + "", out vatPercentage); int.TryParse(formCollection["invoiceTaxBreakdownList[0].vatCatTaxAmt"], out vatCatTaxAmt); int.TryParse(formCollection["invoiceTaxBreakdownList[0].vatCatTaxableAmt"], out vatCatTaxableAmt); if (vatPercentage == 5) { //invoiceData.totalAmountWithoutVAT = vatCatTaxAmt; invoiceTaxBreakdownInfo.vatPercentage = 5; //Mức thuế invoiceTaxBreakdownInfo.vatTaxableAmount = vatCatTaxableAmt; //Tổng tiền trên hóa đơn chịu mức thuế xuất này invoiceTaxBreakdownInfo.vatTaxAmount = vatCatTaxAmt; //Tổng tiền thuế của mức thuế xuất này invoiceData.invoiceTaxBreakdowns.Add(invoiceTaxBreakdownInfo); } else if (vatPercentage == 10) { int.TryParse(formCollection["invoiceTaxBreakdownList[0].vatCatTaxAmt"], out vatCatTaxAmt); int.TryParse(formCollection["invoiceTaxBreakdownList[0].vatCatTaxableAmt"], out vatCatTaxableAmt); //invoiceData.totalAmountWithoutVAT = vatCatTaxAmt; invoiceTaxBreakdownInfo.vatPercentage = 10; //Mức thuế invoiceTaxBreakdownInfo.vatTaxableAmount = vatCatTaxableAmt; //Tổng tiền trên hóa đơn chịu mức thuế xuất này invoiceTaxBreakdownInfo.vatTaxAmount = vatCatTaxAmt; //Tổng tiền thuế của mức thuế xuất này invoiceData.invoiceTaxBreakdowns.Add(invoiceTaxBreakdownInfo); } if (formCollection.AllKeys.Contains("invoiceTaxBreakdownList[1].vatCategoryPercentage")) { var vatPercentage10 = 0; var vatCatTaxAmt1 = 0; var vatCatTaxableAmt1 = 0; int.TryParse(formCollection["invoiceTaxBreakdownList[1].vatCategoryPercentage"] + "", out vatPercentage10); int.TryParse(formCollection["invoiceTaxBreakdownList[1].vatCatTaxAmt"], out vatCatTaxAmt1); int.TryParse(formCollection["invoiceTaxBreakdownList[1].vatCatTaxableAmt"], out vatCatTaxableAmt1); if (vatPercentage10 == 5) { int.TryParse(formCollection["invoiceTaxBreakdownList[1].vatCatTaxAmt"], out vatCatTaxAmt); int.TryParse(formCollection["invoiceTaxBreakdownList[1].vatCatTaxableAmt"], out vatCatTaxableAmt); //invoiceData.totalAmountWithoutVAT = vatCatTaxAmt; invoiceTaxBreakdownInfo.vatPercentage = vatPercentage10; //Mức thuế invoiceTaxBreakdownInfo.vatTaxableAmount = vatCatTaxableAmt1; //Tổng tiền trên hóa đơn chịu mức thuế xuất này invoiceTaxBreakdownInfo.vatTaxAmount = vatCatTaxAmt1; //Tổng tiền thuế của mức thuế xuất này invoiceData.invoiceTaxBreakdowns.Add(invoiceTaxBreakdownInfo); } else if (vatPercentage10 == 10) { int.TryParse(formCollection["invoiceTaxBreakdownList[1].vatCatTaxAmt"], out vatCatTaxAmt1); int.TryParse(formCollection["invoiceTaxBreakdownList[1].vatCatTaxableAmt"], out vatCatTaxableAmt1); //invoiceData.totalAmountWithoutVAT = vatCatTaxAmt; invoiceTaxBreakdownInfo.vatPercentage = vatPercentage10; //Mức thuế invoiceTaxBreakdownInfo.vatTaxableAmount = vatCatTaxableAmt1; //Tổng tiền trên hóa đơn chịu mức thuế xuất này invoiceTaxBreakdownInfo.vatTaxAmount = vatCatTaxAmt1; //Tổng tiền thuế của mức thuế xuất này invoiceData.invoiceTaxBreakdowns.Add(invoiceTaxBreakdownInfo); } } //var vatCatTaxAmt = 0; //int.TryParse(formCollection["invoiceTaxBreakdownList[0].vatCatTaxAmt"], out vatCatTaxAmt); invoiceData.totalAmountWithoutVAT = vatCatTaxAmt; //Tổng tiền không chịu thuế trên toàn hóa đơn var amountForPaymentVnd = 0; int.TryParse(formCollection["amountForPaymentVnd"], out amountForPaymentVnd); invoiceData.totalVATAmount = amountForPaymentVnd; //Tổng tiền thuế trên toàn hóa đơn var totalAmountWithVat = 0; int.TryParse(formCollection["totalAmountWithVat"], out totalAmountWithVat); invoiceData.totalAmountWithVAT = totalAmountWithVat; //Tổng tiền đã bao gồm cả thuế trên toàn hóa đơn invoiceData.totalAmountWithVATInWords = formCollection["totalAmtWithVatInWords"]; //Tổng tiền đã bao gồm cả thuế trên toàn hóa đơn được viết bằng chữ invoice.invoiceData = invoiceData; string xmlInvoice = invoice.Serialize(Encoding.UTF8); var curentTranId = formCollection["tranId"]; if (!string.IsNullOrEmpty(curentTranId)) { //var tran = _transactionSvc.GetById(int.Parse(curentTranId)); //var invoiceFile = tran.InvoiceXML; //var currentInvoice = _invoiceSvc.GetById(tran.InvoiceID); } var fileName = Guid.NewGuid() + ".xml"; var pathFile = Path.Combine(Server.MapPath("~/Content/File"), fileName); XmlDocument doc = new XmlDocument(); doc.LoadXml(xmlInvoice); doc.Save(pathFile); //lưu vào bảng transaction/invoice/invoicedetail var invoices = new Entities.Invoice(); if (invoice.invoiceData.currencyCode != null) { var currencys = _currencySvc.GetByCode(invoice.invoiceData.currencyCode); if (currencys != null && currencys.Any()) { var cus = currencys.First(); invoices.CurrencyID = cus.Id; //invoices.Currency = cus.BankName; } } invoices.InvoiceNote = invoice.invoiceData.invoiceNote; if (formCollection[string.Format("CustomerId")] != null) { invoices.CustomerInvoiceID = int.Parse(formCollection[string.Format("CustomerId")]); } invoices.AccountId = User.GetAccountId(); invoices.InvoiceNumber = invoiceData.invoiceNumber; invoices.Serial = invoiceData.invoiceSeries; invoices.TotalAmountWithVAT = invoiceData.totalAmountWithVAT; invoices.TotalAmountWithoutVAT = invoiceData.totalAmountWithoutVAT; invoices.TotalVATAmount = invoiceData.totalAmountWithVAT; invoices.TemplateCode = formCollection["templateCode"]; var invoiceDetails = new List <InvoiceDetail>(); foreach (var item in invoiceData.items) { var invoiceDetail = new InvoiceDetail(); //invoiceDetail.AdjustmentVatAmount = ""; // invoiceDetail.TotalAmountWithoutVAT = invoiceData.totalAmountWithoutVAT; //invoiceDetail.TotalVATAmount = invoiceData.totalAmountWithVAT; //invoiceDetail.TemplateCode = formCollection["templateCode"]; invoiceDetails.Add(invoiceDetail); } var transaction = new Transaction(); transaction.InvoiceXML = fileName; transaction.TemplateCode = invoices.TemplateCode; transaction.InvoiceSeries = invoices.Serial; int tranId = _invoiceSvc.Create(invoices, transaction); if (releaseId > 0) { var invoiceNums = _invoiceNumberSvc.GetByReleaseIdAnduseStatus(releaseId, 0); if (invoiceNums != null && invoiceNums.FirstOrDefault() != null) { var invoiceNum = invoiceNums.FirstOrDefault(); invoiceNum.UseStatus = 1; invoiceNum.Status = 1; _invoiceNumberSvc.UpdateInvoiceNumbers(invoiceNum); } } return(Json(new ResultInvoice { Flag = true, Message = "Lưu dữ liệu thành công", TransactionId = tranId })); } catch (Exception ex) { return(Json(new ResultInvoice { Flag = true, Message = ex.Message, TransactionId = 0 })); } }
protected InvoiceDetail getInvoiceDetailLine(GridViewRow row) { decimal rate = 0; decimal totalAmount = 0; int? serviceTypeID = 0; DateTime date = DateTime.MaxValue; InvoiceDetail invoiceDetailLine = null; CheckBox cbxInclude = row.FindControl("cbxInclude") as CheckBox; if (cbxInclude.Checked) { invoiceDetailLine = new InvoiceDetail(); // invoiceLineID invoiceDetailLine.InvoiceLineID = (int)gvTimeExpense.DataKeys[row.RowIndex].Values[0]; // service date Label lblLineDate = row.FindControl("lblLineDate") as Label; if (!string.IsNullOrEmpty(lblLineDate.Text)) { invoiceDetailLine.LineDate = Convert.ToDateTime(lblLineDate.Text); } // service description Label lblLineDescription = row.FindControl("lblLineDescription") as Label; // service type serviceTypeID = (int?)gvTimeExpense.DataKeys[row.RowIndex].Values[1]; invoiceDetailLine.ServiceTypeID = serviceTypeID; // expense type id invoiceDetailLine.ExpenseTypeID = (int?)gvTimeExpense.DataKeys[row.RowIndex].Values[2]; invoiceDetailLine.LineDescription = lblLineDescription.Text; // quantity Label lblQty = row.FindControl("lblQty") as Label; invoiceDetailLine.Qty = string.IsNullOrEmpty(lblQty.Text) ? 0 : Convert.ToDecimal(lblQty.Text); // rate Label lblRate = row.FindControl("lblRate") as Label; rate = string.IsNullOrEmpty(lblRate.Text) ? 0 : Convert.ToDecimal(lblRate.Text); invoiceDetailLine.Rate = rate; // total amount // quantity Label lblLineTotal = row.FindControl("lblLineTotal") as Label; decimal.TryParse(lblLineTotal.Text.Trim().Replace(",", "").Replace("$", ""), out totalAmount); invoiceDetailLine.LineAmount = totalAmount; // comments Label lblComments = row.FindControl("lblComments") as Label; invoiceDetailLine.Comments = lblComments.Text.Trim(); invoiceDetailLine.isBillable = true; } return(invoiceDetailLine); }
/// <summary> /// Hàm thêm mới Hóa đơn chi tiết /// </summary> /// <param name="invoiceDetail">Hóa đơn chi tiết</param> /// <returns>Trạng thái thêm mới</returns> /// Người tạo: ntxuan (20/6/2019) public int CreateInvoiceDetail(InvoiceDetail invoiceDetail) { return(invoiceDetailDL.CreateInvoiceDetail(invoiceDetail)); }
private void saveInvoice() { int clientID = 0; int invoiceID = 0; int InvoiceLineID = 0; Invoice invoice = null; InvoiceDetail invoiceDetailLine = null; InvoiceDetail invoiceDetail = null; int nextInvoiceNumber = 0; decimal taxAmount = 0; clientID = Core.SessionHelper.getClientId(); invoiceID = ViewState["InvoiceID"] == null ? 0 : Convert.ToInt32(ViewState["InvoiceID"].ToString()); if (invoiceID == 0) { invoice = new Invoice(); // get id for current lead invoice.ClaimID = Core.SessionHelper.getClaimID(); invoice.IsVoid = false; } else { invoice = InvoiceManager.Get(invoiceID); } //invoice.PolicyID = policy.PolicyType; invoice.InvoiceDate = Convert.ToDateTime(txtInvoiceDate.Text); invoice.DueDate = Convert.ToDateTime(txtDueDate.Text); invoice.BillToName = txtBillTo.Text.Trim(); invoice.BillToAddress1 = txtBillToAddress1.Text.Trim(); invoice.BillToAddress2 = txtBillToAddress2.Text.Trim(); invoice.BillToAddress3 = txtBillToAddress3.Text.Trim(); try { using (TransactionScope scope = new TransactionScope()) { if (invoiceID == 0) { // assign next invoice number to new invoice nextInvoiceNumber = InvoiceManager.GetNextInvoiceNumber(clientID); invoice.InvoiceNumber = nextInvoiceNumber; } invoiceID = InvoiceManager.Save(invoice); // save newly generated invoice id ViewState["InvoiceID"] = invoiceID.ToString(); #region get detail line from gridview foreach (GridViewRow row in gvTimeExpense.Rows) { // get detail line from grid invoiceDetailLine = getInvoiceDetailLine(row); if (invoiceDetailLine != null) { if (invoiceDetailLine.InvoiceLineID > 0) { invoiceDetail = InvoiceDetailManager.Get(InvoiceLineID); } else { invoiceDetail = new InvoiceDetail(); } // update fields invoiceDetail.InvoiceID = invoiceID; invoiceDetail.ServiceTypeID = invoiceDetailLine.ServiceTypeID; invoiceDetail.ExpenseTypeID = invoiceDetailLine.ExpenseTypeID; invoiceDetail.Comments = invoiceDetailLine.Comments; invoiceDetail.isBillable = invoiceDetailLine.isBillable; invoiceDetail.LineAmount = invoiceDetailLine.LineAmount; invoiceDetail.LineDate = invoiceDetailLine.LineDate; invoiceDetail.LineDescription = invoiceDetailLine.LineDescription; invoiceDetail.Qty = invoiceDetailLine.Qty; invoiceDetail.Rate = invoiceDetailLine.Rate; invoiceDetail.UnitDescription = invoiceDetailLine.UnitDescription; invoiceDetail.Total = invoiceDetailLine.Total; // save invoice detail InvoiceDetailManager.Save(invoiceDetail); } } // foreach #endregion // update invoice total after adding invoice = InvoiceManager.Get(invoiceID); invoice.TotalAmount = invoice.InvoiceDetail.Where(x => x.isBillable == true).Sum(x => x.LineAmount); taxAmount = (invoice.TotalAmount ?? 0) * (invoice.TaxRate / 100); InvoiceManager.Save(invoice); // add invoice to claim diary comment addInvoiceToClaimDiary(invoice, invoiceDetail); // 2014-05-02 apply rule using (SpecificExpenseTypePerCarrier ruleEngine = new SpecificExpenseTypePerCarrier()) { RuleException ruleException = ruleEngine.TestRule(clientID, invoice); if (ruleException != null) { ruleException.UserID = Core.SessionHelper.getUserId(); ruleEngine.AddException(ruleException); CheckSendMail(ruleException); } } // complete transaction scope.Complete(); } // using // refresh invoice number on UI txtInvoiceNumber.Text = (invoice.InvoiceNumber ?? 0).ToString(); showToolbarButtons(); lblMessage.Text = "Invoice was generated successfully."; lblMessage.CssClass = "ok"; } catch (Exception ex) { lblMessage.Text = "Error while saving invoice."; lblMessage.CssClass = "error"; Core.EmailHelper.emailError(ex); } }
public void Notify(Toyota.Tsusho.CRM.API.MessageContracts.OrderNotifyRequestMessage request) { using (OrganizationServiceProxy proxy = CRMHelper.Connect()) { ServiceContext context = new ServiceContext(proxy); foreach (OrderItemDataContract item in request.Items) { bool add = false; Entity entity = null; Invoice record = (from a in context.InvoiceSet where a.new_saporderno == item.Invoice.new_saporderno select a).FirstOrDefault(); if (record == null) { add = true; record = new Invoice(); } //CustomerId Lookup Contact contact = (from c in context.ContactSet where c.new_customeraccountnumber == item.Invoice.CustomerId.Name select c).FirstOrDefault(); if (contact == null) throw new Exception(String.Format("No Contact could be retrieved for {0}", item.Invoice.CustomerId.Name)); //SalesOrder SalesOrder order = null; if (item.Invoice.SalesOrderId != null) { order = (from o in context.SalesOrderSet where o.new_DBMOrderNumber == item.Invoice.SalesOrderId.Name select o).FirstOrDefault(); } //SalesOffice Territory salesOffice = null; if (item.Invoice.new_salesoffice != null) { entity = (from s in context.CreateQuery("territory") where s["new_sapcode"] == item.Invoice.new_salesoffice.Name select s).FirstOrDefault(); if (entity != null) salesOffice = entity.ToEntity<Territory>(); } //Plant entity = (from p in context.CreateQuery("territory") where p["new_sapcode"] == item.Invoice.new_plant.Name select p).FirstOrDefault(); Territory plant = null; if(entity != null) plant = entity.ToEntity<Territory>(); //new_invoicetype new_invoicetype invoiceType = null; if(item.Invoice.new_invoicetype != null) { entity = (from it in context.CreateQuery("new_invoicetype") where it["new_typeidinvoice"] == item.Invoice.new_invoicetype.Name select it).FirstOrDefault(); if(entity != null) invoiceType = entity.ToEntity<new_invoicetype>(); } //Populate Order Fields record.new_saporderno = item.Invoice.new_saporderno; record.new_client = item.Invoice.new_client; if (contact != null) record.CustomerId = contact.ToEntityReference(); if (order != null) record.SalesOrderId = order.ToEntityReference(); record.new_precedingdocument = item.Invoice.new_precedingdocument; if (salesOffice != null) record.new_salesoffice = salesOffice.ToEntityReference(); if(plant != null) record.new_plant = plant.ToEntityReference(); record.new_customeradviser = item.Invoice.new_customeradviser; record.new_billingdate = item.Invoice.new_billingdate; record.new_licenseplatenumber = item.Invoice.new_licenseplatenumber; record.new_country = item.Invoice.new_country; record.new_counterreading = item.Invoice.new_counterreading; record.new_counterunit = item.Invoice.new_counterunit; record.new_orderstatus = item.Invoice.new_orderstatus; record.new_netvalue = item.Invoice.new_netvalue; record.new_vehicleguid = item.Invoice.new_vehicleguid; if (invoiceType != null) record.new_invoicetype = invoiceType.ToEntityReference(); if (add) context.AddObject(record); else context.UpdateObject(record); //Invoice Detail //We will nowdelete all line item s and readd them //if we do not do this we will get duplicate records. if (record.invoice_details != null) { foreach (InvoiceDetail detail in record.invoice_details) context.DeleteObject(detail); } foreach (InvoiceDetail lineItem in item.InvoiceDetails) { InvoiceDetail detail = new InvoiceDetail(); //new_material new_modelsalescode material = null; if(detail.new_material != null) { material = (from m in context.new_modelsalescodeSet where m.new_name == lineItem.new_material.Name select m).FirstOrDefault(); } //Plant Territory detailPlant = null; if (lineItem.new_plant != null) { entity = (from p in context.CreateQuery("territory") where p["new_sapcode"] == lineItem.new_plant.Name select p).FirstOrDefault(); if (entity != null) detailPlant = entity.ToEntity<Territory>(); } //Populate Invoice Detail detail.LineItemNumber = lineItem.LineItemNumber; detail.new_pricingreferencematerial = lineItem.new_pricingreferencematerial; detail.new_lvhierno = lineItem.new_lvhierno; if (material != null) detail.new_material = material.ToEntityReference(); detail.new_materialgroup = lineItem.new_materialgroup; detail.ProductDescription = lineItem.ProductDescription; detail.IsPriceOverridden = lineItem.IsPriceOverridden; detail.IsProductOverridden = lineItem.IsProductOverridden; detail.new_description1 = lineItem.new_description1; detail.new_itemcategory = lineItem.new_itemcategory; detail.new_deleteitem = lineItem.new_deleteitem; detail.Quantity = lineItem.Quantity; detail.new_targetqtyuom = lineItem.new_targetqtyuom; detail.new_baseunit = lineItem.new_baseunit; detail.new_targetqtyuom = lineItem.new_targetqtyuom; detail.new_division = lineItem.new_division; detail.PricePerUnit = lineItem.PricePerUnit; detail.new_salesunit = lineItem.new_salesunit; if (detailPlant != null) detail.new_plant = detailPlant.ToEntityReference(); detail.new_storagelocation = lineItem.new_storagelocation; context.AddRelatedObject(record, new Relationship("invoice_details"), detail); } } context.SaveChanges(); } }
public void SyncInvoiceFromQBO(string vendor) { var vendorInDb = _context.UpperVendors.SingleOrDefault(x => x.Name == vendor); var invoicesInDb = _context.Invoices .Include(x => x.UpperVendor) .Include(x => x.InvoiceDetails) .Where(x => x.UpperVendor.Name == vendor); var existedInvoiceList = new List <QBOInvoice>(); var newInvoiceList = new List <QBOInvoice>(); var invoiceQueryResult = QueryAllInvoices(_oauthInfo); var filteredInvoices = invoiceQueryResult.QueryResponse.Invoice.Where(x => x.CustomerRef.Name == vendor); //找出系统中之前同步过且存在的invoice(doc号相同) //找出新invoice(系统中没有的invoice) foreach (var i in filteredInvoices) { if (!invoicesInDb.Select(x => x.InvoiceNumber).Contains(i.DocNumber)) { newInvoiceList.Add(i); } else { existedInvoiceList.Add(i); } } //同步旧invoice foreach (var i in existedInvoiceList) { var invoiceInDb = invoicesInDb.SingleOrDefault(x => x.InvoiceNumber == i.DocNumber); invoiceInDb.InvoiceDate = i.TxnDate.ToString("yyyy-MM-dd"); invoiceInDb.DueDate = i.DueDate.ToString("yyyy-MM-dd"); invoiceInDb.ShipDate = i.ShipDate.ToString("yyyy-MM-dd"); invoiceInDb.CreatedDate = i.MetaData.CreateTime; invoiceInDb.UploadedDate = _syncDate; invoiceInDb.UploadedBy = _userName; //如果totalamt不一样或line数量不同,说明invoice内容改过了,需要删掉旧内容,重新同步新内容 if (i.TotalAmt != invoiceInDb.TotalDue || (i.Line.Count - 1) != invoiceInDb.InvoiceDetails.Count) { _context.InvoiceDetails.RemoveRange(invoiceInDb.InvoiceDetails); invoiceInDb.InvoiceDetails = null; i.Line.Remove(i.Line[i.Line.Count - 1]); for (var j = 0; j < i.Line.Count; j++) { var newLine = new InvoiceDetail { Activity = i.Line[j].SalesItemLineDetail == null ? "NA" : i.Line[j].SalesItemLineDetail.ItemRef.Name, ChargingType = i.Line[j].ItemAccountRef == null ? "NA" : i.Line[j].ItemAccountRef.Name, Unit = "NA", Quantity = i.Line[j].SalesItemLineDetail == null ? 0 : i.Line[j].SalesItemLineDetail.Qty, Rate = i.Line[j].SalesItemLineDetail == null ? 0 : i.Line[j].SalesItemLineDetail.UnitPrice, Amount = i.Line[j].Amount, Memo = i.Line[j].Description == null ? "NA" : i.Line[j].Description, Invoice = invoiceInDb }; _context.InvoiceDetails.Add(newLine); } } invoiceInDb.TotalDue = i.TotalAmt; } ////同步新invoice //if (newInvoiceList.Count == 0) //{ // throw new Exception("No more new invoices need to be synchronized."); //} foreach (var i in newInvoiceList) { var newInvoice = new Models.Invoice { InvoiceNumber = i.DocNumber, PurchaseOrder = "INSIDE", Container = "INSIDE", InvoiceDate = i.TxnDate.ToString("yyyy-MM-dd"), TotalDue = i.TotalAmt, DueDate = i.DueDate.ToString("yyyy-MM-dd"), Enclosed = "NA", ShipDate = i.ShipDate.ToString("yyyy-MM-dd"), ShipVia = "NA", CreatedDate = i.MetaData.CreateTime, CreatedBy = "FROM QBO", UploadedDate = _syncDate, UploadedBy = _userName, UpperVendor = vendorInDb, RequestId = "First sync at " + _syncDate.ToString("yyy--MM-dd") }; _context.Invoices.Add(newInvoice); i.Line.Remove(i.Line[i.Line.Count - 1]); for (var j = 0; j < i.Line.Count; j++) { var newLine = new InvoiceDetail { Activity = i.Line[j].SalesItemLineDetail == null ? "NA" : i.Line[j].SalesItemLineDetail.ItemRef.Name, ChargingType = i.Line[j].ItemAccountRef == null ? "NA" : i.Line[j].ItemAccountRef.Name, Unit = "NA", Quantity = i.Line[j].SalesItemLineDetail == null ? 0 : i.Line[j].SalesItemLineDetail.Qty, Rate = i.Line[j].SalesItemLineDetail == null ? 0 : i.Line[j].SalesItemLineDetail.UnitPrice, Amount = i.Line[j].Amount, Memo = i.Line[j].Description == null ? "NA" : i.Line[j].Description, Invoice = newInvoice }; _context.InvoiceDetails.Add(newLine); } } _context.SaveChanges(); }
private void insertDetailLine(int invoiceID, string serviceDescription, decimal qty, decimal rate, DateTime? date = null, string comments = null) { InvoiceDetail invoiceDetail = null; // invoice detail invoiceDetail = new InvoiceDetail(); invoiceDetail.InvoiceID = invoiceID; invoiceDetail.LineDate = date == null ? DateTime.Now : date; invoiceDetail.LineDescription = serviceDescription; invoiceDetail.Comments = comments; invoiceDetail.LineAmount = Convert.ToDecimal( Session["ExpAmount"]); // * qty invoiceDetail.Total = invoiceDetail.LineAmount; invoiceDetail.isBillable = true; invoiceDetail.Qty = qty; invoiceDetail.Rate = rate; InvoiceDetailManager.Save(invoiceDetail); }
public ActionResult Index(List <ShoppingCart> cart) { ApplicationUser user = System.Web.HttpContext.Current.GetOwinContext() .GetUserManager <ApplicationUserManager>() .FindById(System.Web.HttpContext.Current.User.Identity.GetUserId()); Invoice invoice = new Invoice(DateTime.Today, false, false, DateTime.Now.ToString(), user.Email, user.Surname, user.Firstname); APIConsumer <Models.Webshop.Invoice> .AddObject("invoice", invoice); Webshop.BL.EmailService service = new Webshop.BL.EmailService(); PdfDocument doc = new PdfDocument(); //Add a page PdfPage page = doc.Pages.Add(); //Create border color. PdfColor borderColor = new PdfColor(Color.FromArgb(255, 142, 170, 219)); PdfBrush lightBlueBrush = new PdfSolidBrush(new PdfColor(Color.FromArgb(255, 91, 126, 215))); PdfBrush darkBlueBrush = new PdfSolidBrush(new PdfColor(Color.FromArgb(255, 65, 104, 209))); PdfBrush whiteBrush = new PdfSolidBrush(new PdfColor(Color.FromArgb(255, 255, 255, 255))); PdfPen borderPen = new PdfPen(borderColor, 1f); //Create TrueType font. PdfTrueTypeFont headerFont = new PdfTrueTypeFont(new Font("Arial", 30, System.Drawing.FontStyle.Regular), true); PdfTrueTypeFont arialRegularFont = new PdfTrueTypeFont(new Font("Arial", 9, System.Drawing.FontStyle.Regular), true); PdfTrueTypeFont arialBoldFont = new PdfTrueTypeFont(new Font("Arial", 11, System.Drawing.FontStyle.Bold), true); const float margin = 30; const float lineSpace = 7; const float headerHeight = 90; //Add Ghrapics PdfGraphics graphics = page.Graphics; //Get the page width and height. float pageWidth = page.GetClientSize().Width; float pageHeight = page.GetClientSize().Height; //Draw page border graphics.DrawRectangle(borderPen, new RectangleF(0, 0, pageWidth, pageHeight)); //Fill the header with light Brush. graphics.DrawRectangle(lightBlueBrush, new RectangleF(0, 0, pageWidth, headerHeight)); RectangleF headerAmountBounds = new RectangleF(400, 0, pageWidth - 400, headerHeight); graphics.DrawString("Bestelbon", headerFont, whiteBrush, new PointF(margin, headerAmountBounds.Height / 3)); graphics.DrawRectangle(darkBlueBrush, headerAmountBounds); graphics.DrawString("Totaal te betalen", arialRegularFont, whiteBrush, headerAmountBounds, new PdfStringFormat(PdfTextAlignment.Center, PdfVerticalAlignment.Middle)); List <Invoice> invoices = APIConsumer <Invoice> .GetAPI("invoice").ToList(); PdfTextElement textElement = new PdfTextElement("Factuurnr.: " + invoices.Count, arialRegularFont); PdfLayoutResult layoutResult = textElement.Draw(page, new PointF(headerAmountBounds.X - margin, 120)); textElement.Text = "Datum : " + DateTime.Now.ToString("dd MMMM yyyy"); textElement.Draw(page, new PointF(layoutResult.Bounds.X, layoutResult.Bounds.Bottom + lineSpace)); textElement.Text = "Aan:"; layoutResult = textElement.Draw(page, new PointF(margin, 120)); textElement.Text = user.Firstname + " " + user.Surname; layoutResult = textElement.Draw(page, new PointF(margin, layoutResult.Bounds.Bottom + lineSpace)); textElement.Text = user.Address + " , Postcode: " + user.ZIPCode; layoutResult = textElement.Draw(page, new PointF(margin, layoutResult.Bounds.Bottom + lineSpace)); textElement.Text = user.PhoneNumber; layoutResult = textElement.Draw(page, new PointF(margin, layoutResult.Bounds.Bottom + lineSpace)); textElement.Text = user.Email; layoutResult = textElement.Draw(page, new PointF(margin, layoutResult.Bounds.Bottom + lineSpace)); PdfGrid grid = new PdfGrid(); DataTable dataTable = new DataTable(); ////Add columns to the DataTable dataTable.Columns.Add("Product"); dataTable.Columns.Add("Aantal"); dataTable.Columns.Add("Prijs"); ////Add rows to the DataTable cart = (List <ShoppingCart>)Session["cart"]; foreach (ShoppingCart item in (List <ShoppingCart>)Session["cart"]) { if (item.Course == null) { dataTable.Rows.Add(new object[] { item.Product.Name, item.Quantity, (item.Product.Price * item.Quantity) }); } else { dataTable.Rows.Add(new object[] { item.Course.Name, item.Quantity, (item.Course.Price * item.Quantity) }); } } grid.DataSource = dataTable; grid.Columns[1].Width = 150; grid.Style.Font = arialRegularFont; grid.Style.CellPadding.All = 5; grid.ApplyBuiltinStyle(PdfGridBuiltinStyle.ListTable4Accent5); layoutResult = grid.Draw(page, new PointF(0, layoutResult.Bounds.Bottom + 40)); textElement.Text = "Totaal: "; textElement.Font = arialBoldFont; layoutResult = textElement.Draw(page, new PointF(headerAmountBounds.X - 40, layoutResult.Bounds.Bottom + lineSpace)); float totalAmountCourses = (float)cart.Where(item => item.Course != null).Sum(item => item.Course.Price * item.Quantity); float totalAmountProducts = (float)cart.Where(item => item.Product != null).Sum(item => item.Product.Price * item.Quantity); float totalAmount = totalAmountProducts + totalAmountCourses; textElement.Text = "€" + totalAmount.ToString(); layoutResult = textElement.Draw(page, new PointF(layoutResult.Bounds.Right + 4, layoutResult.Bounds.Y)); graphics.DrawString("€" + totalAmount.ToString(), arialBoldFont, whiteBrush, new RectangleF(400, lineSpace, pageWidth - 400, headerHeight + 15), new PdfStringFormat(PdfTextAlignment.Center, PdfVerticalAlignment.Middle)); borderPen.DashStyle = PdfDashStyle.Custom; borderPen.DashPattern = new float[] { 3, 3 }; PdfLine line = new PdfLine(borderPen, new PointF(0, 0), new PointF(pageWidth, 0)); layoutResult = line.Draw(page, new PointF(0, pageHeight - 100)); textElement.Text = "dotNET academy Antwerpen"; textElement.Font = arialRegularFont; layoutResult = textElement.Draw(page, new PointF(margin, layoutResult.Bounds.Bottom + (lineSpace * 3))); textElement.Text = "Komiteitstraat 46-52 (de Koekenfabriek), 2170 Antwerpen"; layoutResult = textElement.Draw(page, new PointF(margin, layoutResult.Bounds.Bottom + lineSpace)); textElement.Text = "Vragen? \n tel: +32 16 35 93 78 \n email: [email protected]"; layoutResult = textElement.Draw(page, new PointF(margin, layoutResult.Bounds.Bottom + lineSpace)); //Save the document doc.Save(@"\Invoices\Bestelling.pdf"); //Close the document doc.Close(true); foreach (ShoppingCart item in cart) { if (item.Course == null) { InvoiceDetail detail = new InvoiceDetail(item.Quantity, 0, item.Product.Id); APIConsumer <Models.Webshop.InvoiceDetail> .AddObject("InvoiceDetail", detail); } else { InvoiceDetail detail = new InvoiceDetail(item.Quantity, item.Course.Id); APIConsumer <Models.Webshop.InvoiceDetail> .AddObject("InvoiceDetail", detail); } } string mail = user.Email; service.SendInvoice(mail, "Factuur", "Als bijlage uw bestelbon."); return(RedirectToAction("Success", "Purchase")); }
public InvoiceDetail CreateInvoiceDetail(long invoiceId, long itempricingId, int itemunits) { using (var db = Db()) { var invoice = db.Invoices.FirstOrDefault(i => i.Id == invoiceId); if (invoice == null) throw new ArgumentNullException("Invoice does not exist"); var itempricing = db.ItemPricings.FirstOrDefault(i => i.Id == itempricingId); if (itempricing == null) throw new ArgumentNullException("Item Pricing does not exist"); db.Attach(invoice); db.Attach(itempricing); var invoicedetail = new InvoiceDetail(); invoicedetail.ItemUnits = itemunits; invoicedetail.Invoice = invoice; invoicedetail.ItemPricing = itempricing; db.Save(invoicedetail); return invoicedetail; } }
public async Task <IActionResult> Save() { if (Request.HasFormContentType && Request.Form != null && Request.Form.Count() > 0) { if (HttpContext.Session.GetString("success") == null) { string url = ""; //paypal var payPalAPI = new PayPalAPI(configuration); var totala = Request.Form["total"][0]; double total2 = Int32.Parse(totala) / 23139 + Int32.Parse(totala) % 23139; url = await payPalAPI.getRedirectUrlToPayPal(total2, "USD"); HttpContext.Session.SetString("qrcode", url); return(Redirect("/Checkout")); //adddatabase var Address = Request.Form["Address"][0]; HttpContext.Session.SetString("Address", Address); var City = Request.Form["City"][0]; HttpContext.Session.SetString("City", City); var County = Request.Form["County"][0]; HttpContext.Session.SetString("County", County); var Postcode = Request.Form["Postcode"][0]; HttpContext.Session.SetString("Postcode", Postcode); var Odernote = Request.Form["Odernote"][0]; HttpContext.Session.SetString("Odernote", Odernote); var total = Request.Form["total"][0]; HttpContext.Session.SetString("total", total); var Id = Request.Form["Id"][0]; HttpContext.Session.SetString("Id", Id); var count = Request.Form["count"][0]; HttpContext.Session.SetString("count", count); return(Redirect(url)); } } if (HttpContext.Session.GetString("success") == "success") { //adddatabase var Address = HttpContext.Session.GetString("Address"); var City = HttpContext.Session.GetString("City"); var County = HttpContext.Session.GetString("County"); var Postcode = HttpContext.Session.GetString("Postcode"); var Odernote = HttpContext.Session.GetString("Odernote"); var total = HttpContext.Session.GetString("total"); var Id = HttpContext.Session.GetString("Id"); var count = HttpContext.Session.GetString("count"); Invoice invoice = new Invoice(); invoice.Customer_Id = Int32.Parse(Id); invoice.customer = _context.Customer.FirstOrDefault(s => s.Id == Int32.Parse(Id)); invoice.TotalMoney = total; invoice.Postcode = Postcode; invoice.amount = count; invoice.CustomerAddress = Address + "," + City + "," + County; invoice.CreateDay = DateTime.Now; invoice.Ordernote = Odernote; invoice.status = "Đang giao hàng"; _context.Invoice.Add(invoice); await _context.SaveChangesAsync(); //detail InvoiceDetail invoiceDetail = new InvoiceDetail(); var jsoncart = ""; var jsoncartcombo = ""; List <Item> cart = SessionHelper.GetObjectFromJson <List <Item> >(HttpContext.Session, "cart"); if (cart != null) { jsoncart = JsonConvert.SerializeObject(cart); invoiceDetail.Products = jsoncart; } List <ItemCombo> cartcombo = SessionCombo.GetObjectFromJsonCombo <List <ItemCombo> >(HttpContext.Session, "cartcombo"); if (cartcombo != null) { jsoncartcombo = JsonConvert.SerializeObject(cartcombo); invoiceDetail.Combos = jsoncartcombo; } var invoices = from s in _context.Invoice select s; invoices = invoices.OrderByDescending(s => s.Id); Invoice a = invoices.First(); invoiceDetail.Invoice_Id = a.Id; _context.InvoiceDetail.Add(invoiceDetail); await _context.SaveChangesAsync(); //amount if (cart != null) { foreach (var item in cart) { var products = from s in _context.Product select s; products = products.Where(s => s.Id == item.Product.Id); Product pro = products.FirstOrDefault(); pro.Amount = pro.Amount - item.Quantity; await _context.SaveChangesAsync(); Removecart(item.Product.Id); } } if (cartcombo != null) { foreach (var item in cartcombo) { var cartcombos = from s in _context.Combo select s; cartcombos = cartcombos.Where(s => s.Id == item.Combo.Id); Combo cobo = cartcombos.First(); var list = await _context.ComboProduct.Include("Products") .Where(s => s.Combo_Id == cobo.Id).ToListAsync(); foreach (var item1 in list) { item1.Products.Amount = item1.Products.Amount - item.Quantity; } await _context.SaveChangesAsync(); Removecombo(item.Combo.Id); } } } if (HttpContext.Session.GetString("success") == "cancel") { return(Redirect("/Checkout")); } return(Redirect("/Checkout")); }
public InvoiceDetail UpdateInvoiceDetail(long invoiceDetailId, InvoiceDetail invd) { using (var db = Db()) { var invoiceDetail = db.InvoiceDetails.FirstOrDefault(i => i.Id == invoiceDetailId); if (invoiceDetail == null) throw new ArgumentNullException("Invoice does not exist"); if (invd.ItemPricing == null) throw new ArgumentNullException("Item Pricing does not exist"); db.Attach(invoiceDetail); invoiceDetail.ItemUnits = invd.ItemUnits; invoiceDetail.ItemPricing = invd.ItemPricing; db.SaveChanges(); return invoiceDetail; } }
protected void InvoiceRecordButton_Click(object sender, EventArgs e) { DateTime duedate; duedate = Convert.ToDateTime(InvoiceDateTextBox.Text); duedate = duedate.AddDays(40); InvoiceDetail invoiceentry = new InvoiceDetail(); InvoicePayment invoicepayment = new InvoicePayment(); ShortageDetails shortagedetail = new ShortageDetails(); invoiceentry.InvoiceNo = Convert.ToInt64(InvoiceNoTextBox.Text); invoiceentry.InvoiceTerritory = getterritory(); invoiceentry.InvoiceRegion = InvoiceRegionDropDownList.SelectedValue; invoiceentry.InvoiceDate = Convert.ToDateTime(InvoiceDateTextBox.Text).Date; invoiceentry.InvoiceDueDate = duedate.Date; invoiceentry.InvoiceAging = Convert.ToInt32((DateTime.Now.Date - Convert.ToDateTime(InvoiceDateTextBox.Text).Date).TotalDays); invoiceentry.NPA = Convert.ToDecimal(NetAmountTextBox.Text); invoiceentry.SC = ShortageCommentsDropDownList.SelectedValue; InvoiceDetailHandler.AddInvoiceDetail(invoiceentry); invoicepayment.InvoiceNo = Convert.ToInt64(InvoiceNoTextBox.Text); invoicepayment.PaymentStatus = "Non-Paid"; invoicepayment.AmountReceived = Convert.ToDecimal("0.00"); invoicepayment.Balance = Convert.ToDecimal("0.00"); invoicepayment.PaymentRemarks = "Under Progress"; InvoicePaymentHandler.AddInvoicePayment(invoicepayment); shortagedetail.InvoiceNo = Convert.ToInt64(InvoiceNoTextBox.Text); shortagedetail.SD = ShortageDetailsTextBox.Text; ShortageDetailHandler.AddShortageDetail(shortagedetail); cleardata(); }
// generate invoices protected void btnGenerate_Click(object sender, EventArgs e) { Carrier carrier = null; CarrierInvoiceProfile profile = null; Invoice invoice = null; int carrierID = Convert.ToInt32(ddlCarrier.SelectedValue); decimal invoiceAmount = 0; int policyID = 0; int profileID = Convert.ToInt32(this.ddlInvoiceProfile.SelectedValue); if (carrierID == 0 || profileID == 0) return; try { profile = CarrierInvoiceProfileManager.Get(profileID); carrier = CarrierManager.Get(carrierID); } catch (Exception ex) { Core.EmailHelper.emailError(ex); showErrorMessage(); return; } try { using (TransactionScope scope = new TransactionScope()) { foreach (GridViewRow row in gvCarrierPolicy.Rows) { if (row.RowType == DataControlRowType.DataRow) { CheckBox cbxSelect = row.FindControl("cbxSelect") as CheckBox; if (cbxSelect.Checked) { invoice = new Invoice(); //invoice.ClientID = clientID; //invoice.CarrierID = carrierID; invoice.InvoiceDate = DateTime.Now; invoice.InvoiceTypeID = profile.InvoiceType; invoice.CarrierInvoiceProfileID = profileID; invoice.IsVoid = false; invoice.BillToAddress1 = carrier.AddressLine1; invoice.BillToAddress2 = carrier.AddressLine2; invoice.BillToAddress3 = string.Empty; invoice.BillToName = carrier.CarrierName; policyID = (int)gvCarrierPolicy.DataKeys[row.RowIndex].Values[0]; //invoice.PolicyID = policyID; //invoice.LeadId = (int)gvCarrierPolicy.DataKeys[row.RowIndex].Values[1]; //invoice.PolicyTypeID = (int)gvCarrierPolicy.DataKeys[row.RowIndex].Values[2]; Label lblInvoiceAmount = row.FindControl("lblInvoiceAmount") as Label; decimal.TryParse(lblInvoiceAmount.Text, out invoiceAmount); invoice.TotalAmount = invoiceAmount; invoice.InvoiceNumber = InvoiceManager.GetNextInvoiceNumber(clientID); int invoiceID = InvoiceManager.Save(invoice); InvoiceDetail invoiceDetail = new InvoiceDetail(); invoiceDetail.InvoiceID = invoiceID; invoiceDetail.isBillable = true; invoiceDetail.Qty = 1; invoiceDetail.Rate = invoiceAmount; invoiceDetail.LineAmount = invoiceAmount; invoiceDetail.LineDate = DateTime.Now; invoiceDetail.LineDescription = "As per contract"; InvoiceDetailManager.Save(invoiceDetail); // flag policy as invoiced CRM.Data.Entities.LeadPolicy policy = LeadPolicyManager.Get(policyID); if (policy != null) { policy.IsInvoiced = true; LeadPolicyManager.Save(policy); } } } } // foreach // complete transaction scope.Complete(); lblMessage.Text = "Invoice(s) have been generated."; lblMessage.CssClass = "ok"; } } catch (Exception ex) { Core.EmailHelper.emailError(ex); showErrorMessage(); } finally { // refresh those policies to be invoiced bindPoliciesReadyForInvoice(); } }
protected void btnGenerateInvoice_Click(object sender, EventArgs e) { if (IsValid) { DateTime currentTime = DateTime.UtcNow.AddHours(10); // Australian time string path = Server.MapPath("~/files/temp/" + DateTime.Now.ToString("MMddyy") + ".pdf"); User user = new DataModelEntities().Users.First(u => u.User_Code == UserKey); string lastBuyerID = string.Empty; int count = 1; foreach (RepeaterItem item in rptParcelItems.Items) { if (((CheckBox)item.FindControl("chkSelect")).Checked == true) { string isIncomplete = ((HtmlInputHidden)item.FindControl("hfIsIncomplete")).Value; if (isIncomplete.ToLower() == "true") { continue; } string itemID = ((HiddenField)item.FindControl("hfItemID")).Value; string transactionId = ((HiddenField)item.FindControl("hfTransactionID")).Value; string customLabel = ((Label)item.FindControl("lblCustomLabel")).Text; string itemName = ((Label)item.FindControl("lblItemName")).Text; string state = ((HiddenField)item.FindControl("hfState")).Value; string street = ((HtmlInputHidden)item.FindControl("hfStreet")).Value; string street2 = ((HtmlInputHidden)item.FindControl("hfStreet2")).Value; string street3 = ((HtmlInputHidden)item.FindControl("hfStreet3")).Value; string city = ((HtmlInputHidden)item.FindControl("hfCity")).Value; string postalCode = ((HtmlInputHidden)item.FindControl("hfPostalCode")).Value; string country = ((HiddenField)item.FindControl("hfCountry")).Value; string phone = ((HiddenField)item.FindControl("hfPhone")).Value; string shippingMethod = ((Label)item.FindControl("lblShippingMethod")).Text; string buyerName = ((Label)item.FindControl("lblBuyerName")).Text; string buyerId = ((Label)item.FindControl("lblBuyerID")).Text; string quantity = ((Label)item.FindControl("lblQuantity")).Text; string price = ((HiddenField)item.FindControl("hfPrice")).Value; string currency = ((HiddenField)item.FindControl("hfCurrency")).Value; string shippingCost = ((HiddenField)item.FindControl("hfShippingCost")).Value; string saleRecordId = ((HiddenField)item.FindControl("hfSaleRecordId")).Value; Invoice invoice = new Invoice(); Invoice sameInvoice = invoiceList.FirstOrDefault(i => i.BuyerId == buyerId); if (sameInvoice == null) { invoice.Invoice_Code = count.ToString(); invoice.From_Name = user.Company + " - " + user.Full_Name; invoice.From_Address = user.Address1; invoice.From_Address2 = user.Address2; invoice.From_Country = user.Country; invoice.To_Name = buyerName; invoice.To_Address = street2 + " " + street3; invoice.To_Address2 = city + ' ' + state + " - " + postalCode; invoice.To_Country = country; invoice.Currency = currency; invoice.Total_Price = Math.Round((decimal.Parse(price) * decimal.Parse(quantity)), 2); invoice.Invoice_Date = DateTime.Now.ToString("dd/MM/yyyy"); invoice.Invoice_Number = saleRecordId; invoice.Shipping_Cost = shippingCost == string.Empty ? 0 : Math.Round(decimal.Parse(shippingCost), 2); invoice.Grand_Total = Math.Round(invoice.Total_Price + invoice.Shipping_Cost, 2); invoice.Tax_Price = Math.Round(invoice.Grand_Total / 11, 2); // divide by 11 invoice.Shipping_Method = shippingMethod; invoice.From_Suburb = user.City; invoice.From_State = user.State; invoice.From_Postcode = user.Zip; invoice.From_Phone = user.Phone_Number; invoice.Company_Logo = string.IsNullOrEmpty(user.Company_Logo) ? null : GetFile(user.Company_Logo); invoice.ABN_Number = user.ABN_Number; invoice.BuyerId = buyerId; invoiceList.Add(invoice); } else { sameInvoice.Total_Price += Math.Round((decimal.Parse(price) * decimal.Parse(quantity)), 2); sameInvoice.Grand_Total = Math.Round(sameInvoice.Total_Price + sameInvoice.Shipping_Cost, 2); sameInvoice.Tax_Price = Math.Round(sameInvoice.Grand_Total / 11, 2); // 10 percent Tax } InvoiceDetail invoiceDetail = new InvoiceDetail(); invoiceDetail.Invoice_Code = count.ToString(); invoiceDetail.Item_Code = itemID; invoiceDetail.Quantity = quantity; invoiceDetail.Item_Name = itemName; invoiceDetail.Price = price; invoiceDetail.BuyerId = buyerId; invoiceDetailList.Add(invoiceDetail); count++; } } GeneratePDF(path); GenerateZip(path, "Ebay-Invoices"); } }
public static InvoiceDetail CreateInvoiceDetail(int ID, int invoiceDetail_Invoice, byte[] rowVersion) { InvoiceDetail invoiceDetail = new InvoiceDetail(); invoiceDetail.Id = ID; invoiceDetail.InvoiceDetail_Invoice = invoiceDetail_Invoice; invoiceDetail.RowVersion = rowVersion; return invoiceDetail; }
public void UpdateDetailById(InvoiceDetail detail) { this.GetById(detail.InvoiceId).UpdateDetailsById(detail); }
public void AddDetailOnlyOne(InvoiceDetail detail) { this.GetById(detail.InvoiceId).AddDetail(detail); }
//protected void bindBillTo(Lead lead) { // ListItem billToItem = null; // string itemValue = null; // string claimantName = null; // ddlBillTo.Items.Add(new ListItem("Select One", "0")); // if (lead != null && lead.LeadPolicies != null && lead.LeadPolicies.Count > 0) { // // add insurance company policy // foreach (LeadPolicy policy in lead.LeadPolicies) { // if (!string.IsNullOrEmpty(policy.InsuranceCompanyName)) { // itemValue = string.Format("{0}|{1}", policy.PolicyType, policy.CarrierID ?? 0); // billToItem = new ListItem(policy.InsuranceCompanyName, itemValue); // ddlBillTo.Items.Add(billToItem); // } // } // // add client mailing address as option // claimantName = string.Format("{0} {1}", lead.ClaimantFirstName ?? "", lead.ClaimantLastName ?? ""); // itemValue = string.Format("{0}|{1}|{2}|{3}|{4}|{5}", // 1, // homeowners // claimantName, // lead.MailingAddress ?? "", // lead.MailingCity ?? "", // lead.MailingState ?? "", // lead.MailingZip ?? "" // ); // ddlBillTo.Items.Add(new ListItem("Policyholder - Mailing Address", itemValue)); // // add client loss address as option // claimantName = string.Format("{0} {1}", lead.ClaimantFirstName ?? "", lead.ClaimantLastName ?? ""); // itemValue = string.Format("{0}|{1}|{2}|{3}|{4}|{5}", // 1, // homeowners // claimantName, // (lead.LossAddress ?? "") + (lead.LossAddress2 ?? ""), // lead.CityName ?? "", // lead.StateName ?? "", // lead.Zip ?? "" // ); // ddlBillTo.Items.Add(new ListItem("Policyholder - Loss Address", itemValue)); // } //} protected void bindData() { int claimID = 0; int clientID = 0; int invoiceID = 0; int leadID = 0; int policyID = 0; string dencryptedID = null; Invoice invoice = null; InvoiceDetail invoiceDetail = null; List<InvoiceDetail> invoiceDetails = null; // get id for current lead claimID = Core.SessionHelper.getClaimID(); // get id for current lead leadID = Core.SessionHelper.getLeadId(); // get client id clientID = Core.SessionHelper.getClientId(); // get current policy policyID = Core.SessionHelper.getPolicyID(); // check for new invoice or edit invoice if (Request.Params["q"] != null) { dencryptedID = Core.SecurityManager.DecryptQueryString(Request.Params["q"].ToString()); ViewState["InvoiceID"] = dencryptedID; } else { ViewState["InvoiceID"] = "0"; } int.TryParse(ViewState["InvoiceID"].ToString(), out invoiceID); // get lead/claim Leads lead = LeadsManager.GetByLeadId(leadID); // get policy type lblPolicyType.Text = LeadPolicyManager.GetPolicyTypeDescription(policyID); // get policy number lblPolicyNumber.Text = LeadPolicyManager.GetPolicyNumber(policyID); // get insurer claim number lblInsurerClaimNumber.Text = ClaimsManager.getInsurerClaimNumber(claimID); // get policy information if (lead != null) { lblClient.Text = string.Format("<b>{0} {1}<br/>{2}<br/>{3}<br/>{4}, {5} {6}</b>", lead.ClaimantFirstName ?? "", //0 lead.ClaimantLastName ?? "", //1 lead.LossAddress ?? "", //2 lead.LossAddress2 ?? "", //3 lead.CityName ?? "", //4 lead.StateName ?? "", //5 lead.Zip ?? "" //6 ); } if (invoiceID == 0) { // new invoice txtInvoiceDate.Text = DateTime.Now.ToShortDateString(); invoiceDetail = new InvoiceDetail(); invoiceDetail.LineDate = DateTime.Now; invoiceDetails = new List<InvoiceDetail>(); invoiceDetails.Add(invoiceDetail); gvInvoiceLines.DataSource = invoiceDetails; gvInvoiceLines.DataBind(); // hide empty row gvInvoiceLines.Rows[0].Visible = false; // hide print button //btnPrint.Visible = false; // hiden invoice number //pnlInvoiceNumber.Visible = false; } else { // edit invoice invoice = InvoiceManager.Get(invoiceID); // show print button //btnPrint.Visible = true; if (invoice != null && invoice.InvoiceDetail != null) { txtInvoiceDate.Text = string.Format("{0:MM/dd/yyyy}", invoice.InvoiceDate); txtDueDate.Text = string.Format("{0:MM/dd/yyyy}", invoice.DueDate); txtBillTo.Text = invoice.BillToName; txtBillToAddress1.Text = invoice.BillToAddress1; txtBillToAddress2.Text = invoice.BillToAddress2; txtBillToAddress3.Text = invoice.BillToAddress3; // reference txtReferenceNumber.Text = (invoice.InvoiceNumber ?? 0).ToString(); // show total txtTotalAmount.Text = string.Format("{0:N2}", invoice.TotalAmount); // sort line items by date gvInvoiceLines.DataSource = invoice.InvoiceDetail.OrderBy(x => x.LineDate); gvInvoiceLines.DataBind(); // show invoice numebr //pnlInvoiceNumber.Visible = true; txtInvoiceNumber.Text = string.Format("{0:N0}", invoice.InvoiceNumber ?? 0); } } bindInvoiceServices(); }
public void DeleteDetailById(InvoiceDetail detail) { this.GetById(detail.InvoiceId).DeleteDetailsById(detail.Id); }
public InvoiceDetail getInvoiceDetail(int CarrierInvoiceProfileID) { InvoiceDetail InvoiceDetailObj = new InvoiceDetail(); InvoiceDetailObj = (from x in claimRulerDBContext.InvoiceDetail from d in claimRulerDBContext.Invoice where d.CarrierInvoiceProfile.CarrierInvoiceProfileID == CarrierInvoiceProfileID && d.InvoiceID == x.InvoiceID select x).FirstOrDefault(); return InvoiceDetailObj; }