private void InitializeInvoices() { var date = DateTime.UtcNow.Date; DesignInvoice = new Invoice { DueDate = date, FixedScheduleOptionInt = (Int32)FixedScheduleOption.FirstOfMonth, Memo = "Cleaning Grease Trap", RelativeScheduleDays = 5, ScheduleModeInt = (Int32)ScheduleMode.FixedDate }; DesignInvoiceTwo = new Invoice { DueDate =date.AddDays(5), FixedScheduleOptionInt = (Int32)FixedScheduleOption.MiddleOfMonth, Memo = "Food Delivery", RelativeScheduleDays = 10, ScheduleModeInt = (Int32)ScheduleMode.Relative }; DesignInvoiceThree = new Invoice { DueDate = date.AddDays(40), FixedScheduleOptionInt = (Int32)FixedScheduleOption.LastOfMonth, Memo = "Deliver Freight", RelativeScheduleDays = 34, ScheduleModeInt = (Int32)ScheduleMode.FixedDate }; DesignInvoices = new List<Invoice> { DesignInvoice, DesignInvoiceTwo, DesignInvoiceThree }; }
internal CostEstimate GetCostEstimateFor(Carrier carrier, Invoice invoice, Dimensions dimensions, float[] parcelWeights) { int numParcels = parcelWeights.Length; CostEstimate estimate = new CostEstimate(); double weightTotal = 0.0f, sizeTotal = 0.0f; string new_temp_city = invoice.InvoiceCustomer.City; int parcelNumber = 1; //int numSizeWeights = txtBox_input_dimensions.Text == "" ? 0 : txtBox_input_dimensions.Text.Split('/').Length; // Split the weights and do separate checks for each foreach (float weight in parcelWeights) { if (weight > MAXIMUM_WEIGHT) { throw new PricingException($"Parcel weight is larger than {MAXIMUM_WEIGHT}KGs!"); } Parcel p = new Parcel(weight, parcelNumber, 0.0d, numParcels); p.Size = dimensions; API.InvoicesAPI.AddParcelToInvoice(invoice, p); float sizeWeight = p.getSizeWeight() * carrier.DimensionWeightRate; weightTotal += GetCostEstimate(carrier, p, invoice); sizeTotal += sizeWeight == 0 ? 0.0f : GetCostEstimateByWeight(sizeWeight, carrier, p, invoice); parcelNumber++; } return estimate; }
public int AddInvoice(Invoice invoice) { DbParameter parameter = null; parameter = Db.CreateParameter("InvoiceId", DbType.Int32, 8); parameter.Direction = ParameterDirection.Output; Db.ExecuteNonQuery("usp_Invoice_InsertInvoiceDetails", CommandType.StoredProcedure, new DbParameter[] { parameter, Db.CreateParameter("CompanyId", invoice.CompanyId), Db.CreateParameter("ClientId", invoice.ClientId), Db.CreateParameter("IssueDate", invoice.IssueDate), Db.CreateParameter("PurchaseOrderNo", invoice.PurchaseOrderNo), Db.CreateParameter("PaymentTermId", invoice.PaymentTermId), Db.CreateParameter("DueDate", invoice.DueDate), Db.CreateParameter("Discount", invoice.Discount), Db.CreateParameter("RoundOffTotal", invoice.RoundOffTotal), Db.CreateParameter("MarkInvoicePaid", invoice.MarkInvoicePaid), Db.CreateParameter("PaymentTypeId", invoice.PaymentTypeId), Db.CreateParameter("AmountPaid", invoice.AmountPaid), Db.CreateParameter("PaymentDate", invoice.PaymentDate), Db.CreateParameter("PaymentStatus", invoice.PaymentStatus), Db.CreateParameter("Notes", invoice.Notes), Db.CreateParameter("TotalAmount", invoice.TotalAmount), Db.CreateParameter("NotesForClient", invoice.NotesForClient), Db.CreateParameter("PrivateNotes", invoice.PrivateNotes), Db.CreateParameter("Status", invoice.Status) }); return (int)parameter.Value; }
protected void btnUpload_OnClick(object sender, EventArgs e) { InvoiceLogic il = new InvoiceLogic(); Invoice i1 = new Invoice(); i1.OrderID = Convert.ToInt32(Request.QueryString["ID"]); i1.InvoiceNo = TextBox2.Text; DateTime d1 = new DateTime(); if (!DateTime.TryParseExact(TextBox3.Text, "dd/MM/yyyy", null, System.Globalization.DateTimeStyles.None, out d1)) { i1.InvoiceDate = DateTime.Today; } else { i1.InvoiceDate = d1; } i1.GrandTotal = Convert.ToSingle(txtGTotal.Text); string path; string ticks = DateTime.Now.Ticks.ToString(); if (FileUpload1.HasFile) { FileUpload1.SaveAs(Server.MapPath("Images/" + ticks + FileUpload1.FileName)); path = "Images/" + ticks + FileUpload1.FileName; i1.InvoicePDF = path; } il.Insert(i1); Response.Redirect("ViewInvoice.aspx"); }
public void Add(Invoice invoice) { if (list.Exists(item => item == invoice)) return; list.Add(invoice); }
/// <summary> /// Use for update the Delivery Records /// </summary> /// <param name="deliveryId">Delivery Id sent from View Delivery Notes Page</param> protected void LoadByInvoiceID(int InvoiceId) { Invoice objInvoice = new Invoice(InvoiceId); txtInvoiceDate.Text = Conversion.ParseString(objInvoice.DateCreated.ToShortDateString()); //txtDeliveryEstimaDateTime.Text = Conversion.ParseString(objDelivery.DeliveryEstimateDates.ToShortDateString()); ////txtDeliveryID.Text = Conversion.ParseString(objDelivery.DeliveryID); //txtDeliveryName.Text = Conversion.ParseString(objDelivery.DeliveryName); //txtShipToidnumber.Text = Conversion.ParseString(objDelivery.OrganizationShipTo); //txtTransporterID.Text = Conversion.ParseString(objDelivery.OrganizationTransporter); //txtVehicleDetails.Text = Conversion.ParseString(objDelivery.VehicleDetails); //txtWeight.Text = objDelivery.Weight.ToString(); //if (objDelivery.TranspotationType == 1) // rdTransportor.SelectedValue = "1"; //else if (objDelivery.TranspotationType == 2) // rdTransportor.SelectedValue = "2"; //else if (objDelivery.TranspotationType == 3) // rdTransportor.SelectedValue = "3"; //hdLoadIDs.Value = objDelivery.LoadIds; //_LoadIds = objDelivery.LoadIds; //hidOrgID.Value = objDelivery.OrganizationShipToId.ToString(); //hdTranspoterID.Value = objDelivery.OrganizationTransporterId.ToString(); //LoadsInfo(1); //getLoads(objDelivery.LoadIds); //LoadTireInfoByLoadIds(objDelivery.LoadIds, 1); }
protected void Page_Init(object sender, EventArgs e) { ctx = new AriClinicContext("AriClinicContext"); // security control, it must be a user logged if (Session["User"] == null) Response.Redirect("Default.aspx"); else { user = CntAriCli.GetUser((Session["User"] as User).UserId, ctx); Process proc = (from p in ctx.Processes where p.Code == "rtickets" select p).FirstOrDefault<Process>(); per = CntAriCli.GetPermission(user.UserGroup, proc, ctx); } // cheks if is call from another form if (Request.QueryString["Report"] != null) report = Request.QueryString["Report"]; if (Request.QueryString["FDate"] != null) fDate = CntWeb.ParseUrlDate(Request.QueryString["FDate"]); if (Request.QueryString["TDate"] != null) tDate = CntWeb.ParseUrlDate(Request.QueryString["TDate"]); if (Request.QueryString["Diary"] != null) diary = CntAriCli.GetDiary(int.Parse(Request.QueryString["Diary"]),ctx); if (Request.QueryString["Visit"] != null) visit = CntAriCli.GetVisit(int.Parse(Request.QueryString["Visit"]), ctx); if (Request.QueryString["Treatment"] != null) treatment = CntAriCli.GetTreatment(int.Parse(Request.QueryString["Treatment"]), ctx); if (Request.QueryString["Invoice"] != null) invoice = CntAriCli.GetInvoice(int.Parse(Request.QueryString["Invoice"]), ctx); if (Request.QueryString["PrescriptionGlasses"] != null) prescriptionGlasses = CntAriCli.GetPrescriptionGlasses(int.Parse(Request.QueryString["PrescriptionGlasses"]), ctx); }
public MonthlyInvoice(Invoice.InvoiceType type, int year, int month, double amount) { this.Type = type; this.Year = year; this.Month = month; this.Amount = amount; }
public double CalculateFor(Invoice invoice) { var invoiceTotaler = new InvoiceTotaler(); var total = invoiceTotaler.CalculateFor(invoice); total = total * 1.05; return total; }
public ActionResult Index(AllowanceInvalidViewModel Model) { //1. 設定開立折讓作廢資訊 AllowanceInvalid invc = new AllowanceInvalid(); invc.MerchantID = Model.MerchantID; invc.InvoiceNo = Model.InvoiceNo; invc.AllowanceNo = Model.AllowanceNo; invc.Reason = Model.Reason; //2. 初始化發票Service物件 Invoice<AllowanceInvalid> inv = new Invoice<AllowanceInvalid>(); //3. 指定測試環境, 上線時請記得改Prod inv.Environment = EInvoice.Integration.Enumeration.EnvironmentEnum.Stage; //4. 設定歐付寶提供的 Key 和 IV inv.HashIV = "q9jcZX8Ib9LM8wYk"; inv.HashKey = "ejCk326UnaZWKisg"; //5. 執行API的回傳結果(JSON)字串 string json = inv.post(invc); //6. 解序列化,還原成物件使用 //AllowanceInvalidReturn obj = new AllowanceInvalidReturn(); //obj = JsonConvert.DeserializeObject<AllowanceInvalidReturn>(json); //obj.XXX; // ... ViewBag.message = json; return View(); }
public void Write_WithOneInvoiceAndTwoLineItems_GeneratesCorrectOutput() { // Arrange List<InvoiceLineItem> lineItems = new List<InvoiceLineItem>(); lineItems.Add(new InvoiceLineItem(100.00m, "Test item 1")); lineItems.Add(new InvoiceLineItem(123.45m, "Test item 2")); Invoice invoice = new Invoice( "WEE0001", new DateTime(2015, 1, 1), TransactionType.Invoice, "WEE741804H", lineItems); TransactionFile file = new TransactionFile("WEE", 0); file.AddInvoice(invoice); // Act string result = file.Write(); // Assert string expectedDate = DateTime.UtcNow.Date.ToString("dd-MMM-yyyy").ToUpperInvariant(); string expectedOutput = "\"H\",\"0000000\",\"WEE\",\"H\",\"I\",\"00000\",\"\",\"" + expectedDate + "\"" + Environment.NewLine + "\"D\",\"0000001\",\"WEE0001\",\"01-JAN-2015\",\"I\",\"WEE741804H\",\"\",\"GBP\",\"\",\"01-JAN-2015\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\"," + "\"10000\",\"\",\"H\",\"Test item 1\",\"W\",\"H\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"1\",\"Each\",\"10000\"" + Environment.NewLine + "\"D\",\"0000002\",\"WEE0001\",\"01-JAN-2015\",\"I\",\"WEE741804H\",\"\",\"GBP\",\"\",\"01-JAN-2015\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\"," + "\"12345\",\"\",\"H\",\"Test item 2\",\"W\",\"H\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"1\",\"Each\",\"12345\"" + Environment.NewLine + "\"T\",\"0000003\",\"0000004\",\"22345\",\"0\"" + Environment.NewLine; Assert.Equal(expectedOutput, result); }
public ActionResult Index(QueryInvoiceViewModel model) { //1. 設定開立發票資訊 QueryInvoice qinv = new QueryInvoice(); qinv.MerchantID = model.MerchantID; qinv.RelateNumber = model.RelateNumber; //2. 初始化發票Service物件 Invoice<QueryInvoice> inv = new Invoice<QueryInvoice>(); //3. 指定測試環境, 上線時請記得改Prod inv.Environment = EInvoice.Integration.Enumeration.EnvironmentEnum.Stage; //4. 設定歐付寶提供的 Key 和 IV inv.HashIV = "q9jcZX8Ib9LM8wYk"; inv.HashKey = "ejCk326UnaZWKisg"; //5. 執行API的回傳結果(JSON)字串 string json = inv.post(qinv); //6. 解序列化,還原成物件使用 //QueryInvoiceReturn obj = new QueryInvoiceReturn(); //obj = JsonConvert.DeserializeObject<QueryInvoiceReturn>(json); //obj.XXX; //obj.XXX; // ... ViewBag.message = json; return View(); }
internal float GetCostEstimateByWeight(float weight, Carrier carrier, Parcel parcel, Invoice invoice) { float estimate = 0; int intPostcode = 0; int.TryParse(invoice.InvoiceCustomer.Postcode, out intPostcode); BlauModel _dbcontext = BlauModel.GetContext(); DBCarrier _carrier = _dbcontext.Carrier.Where(x => x.carrierId == (int)carrier.CarrierId).FirstOrDefault(); if (_carrier != default(DBCarrier)) { /*PricingOption option = (from rate in _carrier.Rates where rate.Zones.Where(x => x.Postcode == invoice.InvoiceCustomer.Postcode).Count() > 0 && rate.MinWeight < weight && rate.MaxWeight >= weight select new PricingOption(rate.Rate, rate.ExtraRate, rate.MinWeight, rate.MaxWeight, rate.SecondRate, rate.SecondRateExtra) ).FirstOrDefault(); if (option != null) { if (parcel.ParcelNumber == 1) estimate = option.rate + option.extra_rate * weight; else estimate = option.second_parcel_rate + option.second_parcel_extra_rate * weight; }*/ } return estimate; }
public int Add(Invoice newInvoice) { this.invoices.Add(newInvoice); this.invoices.SaveChanges(); return newInvoice.Id; }
public InputDialog() { InitializeComponent(); _invoice = Invoice.GetUniqueInstance(); input.Text = _invoice.Number; }
protected void SetInvoiceInfo(Invoice invoice, bool initialSetting) { string invoiceViewURL = "/Invoice_ViewV2.aspx?invoice_id=" + invoice.InvoiceID; lblInvoiceID.Text = "<a href=\"" + invoiceViewURL + "\" onclick=\"open_new_tab('" + invoiceViewURL + "');return false;\">" + invoice.InvoiceID + "</a>"; lblInvoiceTotal.Text = "$" + invoice.Total.ToString(); lblInvoiceOwing.Text = "$" + invoice.TotalDue.ToString(); lblReceiptedTotal.Text = "$" + invoice.ReceiptsTotal.ToString() + (invoice.CreditNotesTotal == 0 ? "" : " ($" + invoice.CreditNotesTotal.ToString() + " Credit Noted)") + (invoice.RefundsTotal == 0 ? "" : " ($" + invoice.RefundsTotal.ToString() + " Refunds)"); hiddenInvoiceOwingTotalCents.Value = ((int)(invoice.TotalDue * 100)).ToString(); hiddenReceiptedAmountTotalCents.Value = ((int)(invoice.ReceiptsTotal * 100)).ToString(); Page.ClientScript.RegisterStartupScript(this.GetType(), "setamount", "<script language=javascript>if (!is_debugging) document.getElementById('amount').value = '" + invoice.TotalDue.ToString() + "';</script>"); lblDebtor.Text = invoice.GetDebtor(true); if (invoice.Booking != null) { lblBkDate.Text = invoice.Booking.DateStart.ToString("d MMM, yyyy"); lblBkOrgText.Text = invoice.Booking.Organisation.IsAgedCare ? "Facility" : "Clinic"; lblBkOrg.Text = invoice.Booking.Organisation.Name; } else { td_bk_date.Visible = false; td_bk_org.Visible = false; } result.InnerHtml = hiddenResponse.Value; merchantReceipt.InnerHtml = (hiddenMerchangeReceipt.Value.Length > 0) ? "<pre>" + hiddenMerchangeReceipt.Value + "</pre>" : string.Empty; customerReceipt.InnerHtml = (hiddenCustomerReceipt.Value.Length > 0) ? "<pre>" + hiddenCustomerReceipt.Value + "</pre>" : string.Empty; btnPrintMerchantReceipt.Style["display"] = hiddenMerchangeReceipt.Value.Length > 0 ? "" : "none"; btnPrintCustomerReceipt.Style["display"] = hiddenCustomerReceipt.Value.Length > 0 ? "" : "none"; }
public InvoiceViewModel CreateContractInvoice(InvoiceViewModel invoice, int contractId) { var newInvoice = new Invoice { Id = invoice.Id, From = invoice.From, To = invoice.To, MgSubs = invoice.MgSubs, Cps = invoice.Cps, CreatedOn = DateTime.Now, CorrespondencePayment = invoice.CorrespondencePayment, AdditionalInformation = invoice.AdditionalInformation, FixedMonthlyFee = invoice.FixedMonthlyFee, Vat = invoice.Vat, ClientContractId = contractId, Comments = invoice.Comments, IsPaid = false, IsVisible = invoice.IsVisible }; this.Data.Invoices.Add(newInvoice); this.Data.SaveChanges(); invoice.Id = newInvoice.Id; return invoice; }
public ActionResult Index(InvoiceDelayViewModel Model) { //1. 設定觸發或延遲開立發票資訊 InvoiceDelay invc = new InvoiceDelay(); invc.MerchantID = Model.MerchantID; invc.DelayFlag = Model.DelayFlag; invc.RelateNumber = Model.RelateNumber; invc.CustomerID = Model.CustomerID; invc.CustomerIdentifier = Model.CustomerIdentifier; invc.CustomerAddr = Model.CustomerAddr; invc.CustomerName = Model.CustomerName; invc.CustomerPhone = Model.CustomerPhone; invc.CustomerEmail = Model.CustomerEmail; invc.ClearanceMark = Model.ClearanceMark; invc.TaxType = Model.TaxType; invc.SalesAmount = Model.SalesAmount; invc.carruerType = Model.CarruerType; invc.CarruerNum = Model.CarruerNum; invc.Donation = Model.Donation; invc.LoveCode = Model.LoveCode; invc.Print = Model.Print; invc.Items.Add(new Item() { ItemName = Model.ItemName, ItemPrice = Model.ItemPrice, ItemCount = Model.ItemCount, ItemWord = Model.ItemWord, ItemAmount = Model.ItemAmount }); invc.InvoiceRemark = Model.InvoiceRemark; invc.DelayDay = Model.DelayDay; invc.ECBankID = Model.ECBankID; invc.Tsr = Model.Tsr; invc.PayType = Model.PayType; invc.NotifyURL = Model.NotifyURL; invc.invType = Model.InvType; //2. 初始化發票Service物件 Invoice<InvoiceDelay> inv = new Invoice<InvoiceDelay>(); //3. 指定測試環境, 上線時請記得改Prod inv.Environment = EInvoice.Integration.Enumeration.EnvironmentEnum.Stage; //4. 設定歐付寶提供的 Key 和 IV inv.HashIV = "q9jcZX8Ib9LM8wYk"; inv.HashKey = "ejCk326UnaZWKisg"; //5. 執行API的回傳結果(JSON)字串 string json = inv.post(invc); //6. 解序列化,還原成物件使用 //InvoiceDelayReturn obj = new InvoiceDelayReturn(); //obj = JsonConvert.DeserializeObject<QueryAllowanceReturn>(json); //obj.XXX; // ... ViewBag.message = json; return View(); }
protected void btnExecute_Click(object sender, EventArgs e) { //Define a workbook to store null value initially Workbook workbook = null; string path = MapPath("."); path = path.Substring(0, path.LastIndexOf("\\")); Invoice invoice = new Invoice(path); //Create the workbook based on a custom method of a class workbook = invoice.CreateInvoice(); if (ddlFileVersion.SelectedItem.Value == "XLS") { ////Save file and send to client browser using selected format workbook.Save(HttpContext.Current.Response, "Invoice.xls", ContentDisposition.Attachment, new XlsSaveOptions(SaveFormat.Excel97To2003)); } else { workbook.Save(HttpContext.Current.Response, "Invoice.xlsx", ContentDisposition.Attachment, new OoxmlSaveOptions(SaveFormat.Xlsx)); } //end response to avoid unneeded html HttpContext.Current.Response.End(); }
public OrderDocument(Order order, Invoice invoices, List<Receipt> receipts) { _Order = order; _Invoices = invoices; Receipts = receipts; CalcAmountPaid(); }
public ActionResult Index(InvoiceTriggerViewModel Model) { //1. 設定付款完成觸發或延遲開立發票資訊 InvoiceTrigger invt = new InvoiceTrigger(); invt.MerchantID = Model.MerchantID; invt.Tsr = Model.Tsr; invt.PayType = Model.PayType; //2. 初始化發票Service物件 Invoice<InvoiceTrigger> inv = new Invoice<InvoiceTrigger>(); //3. 指定測試環境, 上線時請記得改Prod inv.Environment = EInvoice.Integration.Enumeration.EnvironmentEnum.Stage; //4. 設定歐付寶提供的 Key 和 IV inv.HashIV = "q9jcZX8Ib9LM8wYk"; inv.HashKey = "ejCk326UnaZWKisg"; //5. 執行API的回傳結果(JSON)字串 string json = inv.post(invt); //6. 解序列化,還原成物件使用 //InvoiceTriggerReturn obj = new InvoiceTriggerReturn(); //obj = JsonConvert.DeserializeObject<InvoiceTriggerReturn>(json); //obj.XXX; // ... ViewBag.message = json; return View(); }
/// <summary> /// This function is responsible for populating the /// parameters required for generating a invoice. /// </summary> /// <param name="invoicedto"></param> /// <param name="timeActivity"></param> /// <returns></returns> private Invoice PopulateInvoiceParam(Invoicedto invoicedto, TimeActivity timeActivity) { Invoice invoice = new Invoice(); invoice.TxnDate = timeActivity.TxnDate; invoice.Line = new Line[] { new Line{AmountSpecified=true,Description=timeActivity.Description,Amount=25,DetailType=LineDetailTypeEnum.SalesItemLineDetail,DetailTypeSpecified=true,AnyIntuitObject = new SalesItemLineDetail{Qty=Convert.ToDecimal(3.5),TaxCodeRef=new ReferenceType{Value="NON"},ItemRef=new ReferenceType{Value=timeActivity.ItemRef.Value}}}, new Line{Amount=25,AmountSpecified=true,DetailType=LineDetailTypeEnum.SubTotalLineDetail,DetailTypeSpecified=true,AnyIntuitObject = new SubTotalLineDetail{}} }; invoice.TxnTaxDetail = new TxnTaxDetail { TotalTax = 0 }; invoice.CustomerRef = new ReferenceType { Value = timeActivity.CustomerRef.Value }; invoice.DueDate = DateTime.Now; invoice.TotalAmt = 25; invoice.ApplyTaxAfterDiscount = false; invoice.PrintStatus = PrintStatusEnum.NeedToPrint; invoice.PrintStatusSpecified = true; invoice.EmailStatus = EmailStatusEnum.NotSet; invoice.EmailStatusSpecified = true; invoice.Balance = 25; invoice.BalanceSpecified = true; invoice.Deposit = 0; invoice.DepositSpecified = true; invoice.AllowIPNPayment = false; invoice.AllowIPNPaymentSpecified = true; invoice.AllowOnlinePayment = false; invoice.AllowOnlinePaymentSpecified = true; invoice.AllowOnlineCreditCardPayment = false; invoice.AllowOnlineCreditCardPaymentSpecified = true; invoice.AllowOnlineACHPayment = false; invoice.AllowOnlineACHPaymentSpecified = true; return invoice; }
public async Task<IbisFileGeneratorResult<TransactionFile>> CreateAsync(ulong fileID, InvoiceRun invoiceRun) { TransactionFile transactionFile = new TransactionFile("WEE", fileID); var errors = new List<Exception>(); var groups = invoiceRun.MemberUploads.GroupBy(mu => mu.Scheme); foreach (var group in groups) { List<InvoiceLineItem> lineItems = new List<InvoiceLineItem>(); var lineItemErrors = new List<Exception>(); foreach (MemberUpload memberUpload in group) { DateTime submittedDate = memberUpload.SubmittedDate.Value; string description = string.Format("Charge for producer registration submission made on {0:dd MMM yyyy}.", submittedDate); try { InvoiceLineItem lineItem = new InvoiceLineItem( memberUpload.TotalCharges, description); lineItems.Add(lineItem); } catch (Exception ex) { lineItemErrors.Add(new SchemeFieldException(group.Key, ex)); } } errors.AddRange(lineItemErrors); string transactionReference = await transactionReferenceGenerator.GetNextTransactionReferenceAsync(); if (lineItemErrors.Count == 0) { try { Invoice invoice = new Invoice( group.Key.IbisCustomerReference, invoiceRun.IssuedDate, TransactionType.Invoice, transactionReference, lineItems); transactionFile.AddInvoice(invoice); } catch (Exception ex) { errors.Add(new SchemeFieldException(group.Key, ex)); } } } return new IbisFileGeneratorResult<TransactionFile>(errors.Count == 0 ? transactionFile : null, errors); }
public MailSend(Invoice invoice, Enums.MessageType type) { ID = 0; this.Invoice = invoice; MessageType = type; Status = Enums.MailStatus.WAITING; SaveJob(); }
public ActionResult List(DateTime date) { ViewBag.invoicedate = date; List<Invoice> invoices = new Invoice().GetAllByDate(date); ViewBag.invoices = invoices; return View(); }
public void should_send_to_collectio_when_past_due_and_notice_sent() { var invoice = new Invoice() {DateSent = DateTime.Now.AddDays(31), NoticeSent = true}; var spec = new InvoiceOverDueSpecification() .And(new InvoiceNoticeSentSpecification()) .IsSatisfiedBy(invoice); spec.ShouldBeTrue(); }
public void NeutralizeInvoice(ref Invoice Invoice, Transaction oldTransaction) { Invoice.TotalHasPaid -= oldTransaction.TotalPayment.AsDecimal(); if (Invoice.TotalHasPaid != Invoice.TotalPrice) { Invoice.PaymentStatus = (int)DbConstant.PaymentStatus.NotSettled; } }
// Prints the result private static void Print(Invoice i) { Console.WriteLine("Part Number:\t{0}", i.PartNumber); Console.WriteLine("Descritpion:\t{0}", i.Description); Console.WriteLine("Quantity:\t{0}", i.Quantity); Console.WriteLine("Price:\t\t{0}", i.Price); Console.WriteLine("Invoice amount:\t{0}\n", i.GetInvoiceAmount()); }
static void Main(string[] args) { //Task1 Address addressdefault = new Address(); Address address = new Address() { Apartment = 110 , City = "Kiev", Country = "Ukraine", House = 50 , Index = 58000, Street = "Hreshatik"}; Address addressChangedIndex = new Address(10000); addressdefault.DisplayAddress(); address.DisplayAddress(); Console.WriteLine(addressChangedIndex.ToString()); //Task 2 string str = ""; double number1 = 0; double number2 = 0; number1 = str.CheckDoubleDigits(); number2 = str.CheckDoubleDigits(); Rectangle rectangle = new Rectangle(number1, number2); Console.WriteLine(rectangle.ToString()); //Task 3 Book book = new Book("Programming","Troelsen","C#"); book.Show(); Console.ResetColor(); //Task 4 Point A = new Point(1, 2); Point B = new Point(2, 1); Point C = new Point(3, 2); Figure figure = new Figure(A, B, C); figure.Display(); //Task 5 User user = new User(login:"******", password: "******", name: "Jack", sername:"..."); user.Output(); //Task 6 Converter conv = new Converter(24.6081, 25.99,0.3274); conv.Sum = 10.11; conv.ChooseCurrency(); conv.ExchangeCurrency(); //Task 7 Employee employee = new Employee("User", "Relly"); employee.Display(); //Task 8 Invoice invoice = new Invoice(10000, "Customer" ,"Provider"); invoice.Article = "PC"; invoice.Quantity = 2; invoice.Display(); Console.ReadLine(); Console.ReadLine(); }
static void ShowStory01And03() { var listTaxes = _taxService.AllTaxesToInvoice(); Invoice invoice = new Invoice(1, 5001, listTaxes); Console.WriteLine("Total taxes:\n{0}", invoice.TotalAmountAllTaxes()); Console.WriteLine("Total sum taxes:\n{0}", invoice.TotalSumAmoutTaxes()); }
/// <summary> /// Performs a new payment request with the given invoice. /// </summary> /// <param name="onlinePayment"></param> /// <param name="invoice">The invoice that must be paid.</param> public static IPaymentRequestResult Request(this IOnlinePayment onlinePayment, Invoice invoice) => onlinePayment.RequestAsync(invoice) .GetAwaiter() .GetResult();
protected BaseState(Invoice invoice) => Invoice = invoice;
private static InvoiceFormattedData CreateDataAfterLinesUpdated(Invoice invoice, InvoiceFormattedData invoiceOldData) { var data = invoiceOldData; var cultureInfo = string.IsNullOrEmpty(invoice.Language) ? CultureInfo.CurrentCulture : CultureInfo.GetCultureInfo(invoice.Language); #region TableBodyRows, TableFooterRows, TableTotalRow data.TableBodyRows = new List <List <string> >(); var invoiceLines = invoice.GetInvoiceLines(); var invoiceTaxes = new Dictionary <int, decimal>(); decimal subtotal = 0; decimal discount = 0; decimal amount = 0; foreach (var line in invoiceLines) { var item = Global.DaoFactory.GetInvoiceItemDao().GetByID(line.InvoiceItemID); var tax1 = line.InvoiceTax1ID > 0 ? Global.DaoFactory.GetInvoiceTaxDao().GetByID(line.InvoiceTax1ID) : null; var tax2 = line.InvoiceTax2ID > 0 ? Global.DaoFactory.GetInvoiceTaxDao().GetByID(line.InvoiceTax2ID) : null; var subtotalValue = Math.Round(line.Quantity * line.Price, 2); var discountValue = Math.Round(subtotalValue * line.Discount / 100, 2); var rate = 0; if (tax1 != null) { rate += tax1.Rate; if (invoiceTaxes.ContainsKey(tax1.ID)) { invoiceTaxes[tax1.ID] = invoiceTaxes[tax1.ID] + Math.Round((subtotalValue - discountValue) * tax1.Rate / 100, 2); } else { invoiceTaxes.Add(tax1.ID, Math.Round((subtotalValue - discountValue) * tax1.Rate / 100, 2)); } } if (tax2 != null) { rate += tax2.Rate; if (invoiceTaxes.ContainsKey(tax2.ID)) { invoiceTaxes[tax2.ID] = invoiceTaxes[tax2.ID] + Math.Round((subtotalValue - discountValue) * tax2.Rate / 100, 2); } else { invoiceTaxes.Add(tax2.ID, Math.Round((subtotalValue - discountValue) * tax2.Rate / 100, 2)); } } decimal taxValue = Math.Round((subtotalValue - discountValue) * rate / 100, 2); decimal amountValue = Math.Round(subtotalValue - discountValue + taxValue, 2); subtotal += subtotalValue; discount += discountValue; amount += amountValue; data.TableBodyRows.Add(new List <string> { item.Title + (string.IsNullOrEmpty(line.Description) ? string.Empty : ": " + line.Description), line.Quantity.ToString(CultureInfo.InvariantCulture), line.Price.ToString(CultureInfo.InvariantCulture), line.Discount.ToString(CultureInfo.InvariantCulture), tax1 != null ? tax1.Name : string.Empty, tax2 != null ? tax2.Name : string.Empty, (subtotalValue - discountValue).ToString(CultureInfo.InvariantCulture) }); } data.TableFooterRows = new List <Tuple <string, string> >(); data.TableFooterRows.Add(new Tuple <string, string>(CRMInvoiceResource.ResourceManager.GetString("Subtotal", cultureInfo), (subtotal - discount).ToString(CultureInfo.InvariantCulture))); foreach (var invoiceTax in invoiceTaxes) { var iTax = Global.DaoFactory.GetInvoiceTaxDao().GetByID(invoiceTax.Key); data.TableFooterRows.Add(new Tuple <string, string>(string.Format("{0} ({1}%)", iTax.Name, iTax.Rate), invoiceTax.Value.ToString(CultureInfo.InvariantCulture))); } //data.TableFooterRows.Add(new Tuple<string, string>(CRMInvoiceResource.ResourceManager.GetString("Discount", cultureInfo), "-" + discount.ToString(CultureInfo.InvariantCulture))); data.TableTotalRow = new Tuple <string, string>(string.Format("{0} ({1})", CRMInvoiceResource.ResourceManager.GetString("Total", cultureInfo), invoice.Currency), amount.ToString(CultureInfo.InvariantCulture)); #endregion return(data); }
public ActionResult Create(Invoice invoice) { invoice = _iFInvoice.Create(invoice); return(RedirectToAction("Index")); //, new { id = invoice.InvoiceId } }
internal async Task <DataWrapper <InvoiceResponse> > CreateInvoiceCore(Invoice invoice, StoreData store, string serverUrl, double expiryMinutes = 15) { var derivationStrategies = store.GetDerivationStrategies(_NetworkProvider).ToList(); if (derivationStrategies.Count == 0) { throw new BitpayHttpException(400, "This store has not configured the derivation strategy"); } var entity = new InvoiceEntity { InvoiceTime = DateTimeOffset.UtcNow }; entity.SetDerivationStrategies(derivationStrategies); var storeBlob = store.GetStoreBlob(); Uri notificationUri = Uri.IsWellFormedUriString(invoice.NotificationURL, UriKind.Absolute) ? new Uri(invoice.NotificationURL, UriKind.Absolute) : null; if (notificationUri == null || (notificationUri.Scheme != "http" && notificationUri.Scheme != "https")) //TODO: Filer non routable addresses ? { notificationUri = null; } EmailAddressAttribute emailValidator = new EmailAddressAttribute(); entity.ExpirationTime = entity.InvoiceTime.AddMinutes(expiryMinutes); entity.MonitoringExpiration = entity.ExpirationTime + TimeSpan.FromMinutes(storeBlob.MonitoringExpiration); entity.OrderId = invoice.OrderId; entity.ServerUrl = serverUrl; entity.FullNotifications = invoice.FullNotifications || invoice.ExtendedNotifications; entity.ExtendedNotifications = invoice.ExtendedNotifications; entity.NotificationURL = notificationUri?.AbsoluteUri; entity.BuyerInformation = Map <Invoice, BuyerInformation>(invoice); //Another way of passing buyer info to support FillBuyerInfo(invoice.Buyer, entity.BuyerInformation); if (entity?.BuyerInformation?.BuyerEmail != null) { if (!EmailValidator.IsEmail(entity.BuyerInformation.BuyerEmail)) { throw new BitpayHttpException(400, "Invalid email"); } entity.RefundMail = entity.BuyerInformation.BuyerEmail; } entity.ProductInformation = Map <Invoice, ProductInformation>(invoice); entity.RedirectURL = invoice.RedirectURL ?? store.StoreWebsite; entity.Status = "new"; entity.SpeedPolicy = ParseSpeedPolicy(invoice.TransactionSpeed, store.SpeedPolicy); var queries = derivationStrategies .Select(derivationStrategy => { return(new { network = derivationStrategy.Network, getFeeRate = _FeeProviderFactory.CreateFeeProvider(derivationStrategy.Network).GetFeeRateAsync(), getRate = _RateProviders.GetRateProvider(derivationStrategy.Network).GetRateAsync(invoice.Currency), getAddress = _Wallet.ReserveAddressAsync(derivationStrategy) }); }); var cryptoDatas = new Dictionary <string, CryptoData>(); foreach (var q in queries) { CryptoData cryptoData = new CryptoData(); cryptoData.CryptoCode = q.network.CryptoCode; cryptoData.FeeRate = (await q.getFeeRate); cryptoData.TxFee = storeBlob.NetworkFeeDisabled ? Money.Zero : cryptoData.FeeRate.GetFee(100); // assume price for 100 bytes cryptoData.Rate = await q.getRate; cryptoData.DepositAddress = (await q.getAddress).ToString(); #pragma warning disable CS0618 if (q.network.IsBTC) { entity.TxFee = cryptoData.TxFee; entity.Rate = cryptoData.Rate; entity.DepositAddress = cryptoData.DepositAddress; } #pragma warning restore CS0618 cryptoDatas.Add(cryptoData.CryptoCode, cryptoData); } entity.SetCryptoData(cryptoDatas); entity.PosData = invoice.PosData; entity = await _InvoiceRepository.CreateInvoiceAsync(store.Id, entity, _NetworkProvider); _EventAggregator.Publish(new Events.InvoiceCreatedEvent(entity.Id)); var resp = entity.EntityToDTO(_NetworkProvider); return(new DataWrapper <InvoiceResponse>(resp) { Facade = "pos/invoice" }); }
public Task <bool> DeleteInvoiceAsync(Invoice invoice) { return(channel.DeleteInvoiceAsync(invoice)); }
private int SaveOrUpdateInvoice(Invoice invoice, DbManager db) { if (String.IsNullOrEmpty(invoice.Number) || invoice.IssueDate == DateTime.MinValue || invoice.ContactID <= 0 || invoice.DueDate == DateTime.MinValue || String.IsNullOrEmpty(invoice.Currency) || invoice.ExchangeRate <= 0 || String.IsNullOrEmpty(invoice.Terms)) { throw new ArgumentException(); } if (!IsExist(invoice.ID, db)) { if (IsExist(invoice.Number, db)) { throw new ArgumentException(); } invoice.ID = db.ExecuteScalar <int>( Insert("crm_invoice") .InColumnValue("id", 0) .InColumnValue("status", (int)invoice.Status) .InColumnValue("number", invoice.Number) .InColumnValue("issue_date", TenantUtil.DateTimeToUtc(invoice.IssueDate)) .InColumnValue("template_type", invoice.TemplateType) .InColumnValue("contact_id", invoice.ContactID) .InColumnValue("consignee_id", invoice.ConsigneeID) .InColumnValue("entity_type", (int)invoice.EntityType) .InColumnValue("entity_id", invoice.EntityID) .InColumnValue("due_date", TenantUtil.DateTimeToUtc(invoice.DueDate)) .InColumnValue("language", invoice.Language) .InColumnValue("currency", invoice.Currency) .InColumnValue("exchange_rate", invoice.ExchangeRate) .InColumnValue("purchase_order_number", invoice.PurchaseOrderNumber) .InColumnValue("terms", invoice.Terms) .InColumnValue("description", invoice.Description) .InColumnValue("json_data", null) .InColumnValue("file_id", 0) .InColumnValue("create_on", DateTime.UtcNow) .InColumnValue("create_by", SecurityContext.CurrentAccount.ID) .InColumnValue("last_modifed_on", DateTime.UtcNow) .InColumnValue("last_modifed_by", SecurityContext.CurrentAccount.ID) .Identity(1, 0, true)); } else { var oldInvoice = db.ExecuteList(GetInvoiceSqlQuery(Exp.Eq("id", invoice.ID), null)) .ConvertAll(ToInvoice) .FirstOrDefault(); CRMSecurity.DemandEdit(oldInvoice); if (oldInvoice.ContactID != invoice.ContactID) { oldInvoice.FileID = 0; } db.ExecuteNonQuery( Update("crm_invoice") .Set("status", (int)invoice.Status) .Set("issue_date", TenantUtil.DateTimeToUtc(invoice.IssueDate)) .Set("template_type", invoice.TemplateType) .Set("contact_id", invoice.ContactID) .Set("consignee_id", invoice.ConsigneeID) .Set("entity_type", (int)invoice.EntityType) .Set("entity_id", invoice.EntityID) .Set("due_date", TenantUtil.DateTimeToUtc(invoice.DueDate)) .Set("language", invoice.Language) .Set("currency", invoice.Currency) .Set("exchange_rate", invoice.ExchangeRate) .Set("purchase_order_number", invoice.PurchaseOrderNumber) .Set("terms", invoice.Terms) .Set("description", invoice.Description) .Set("json_data", null) .Set("file_id", oldInvoice.FileID) .Set("last_modifed_on", DateTime.UtcNow) .Set("last_modifed_by", SecurityContext.CurrentAccount.ID) .Where(Exp.Eq("id", invoice.ID))); } return(invoice.ID); }
public bool DeleteInvoice(Invoice invoice) { return(channel.DeleteInvoice(invoice)); }
/// <summary> /// Addtional operations to be performed when cloning an instance of <see cref="Invoice" /> to an instance of <see cref="PSInvoice" />. /// </summary> /// <param name="invoice">The invoice being cloned.</param> private void CloneAdditionalOperations(Invoice invoice) { InvoiceId = invoice.Id; }
public int CreateInvoice(Invoice invoice) { return(channel.CreateInvoice(invoice)); }
public override Task <RequestResult> RequestAsync(Invoice invoice) { return(Task.FromResult(Request(invoice))); }
public void UpdateInvoice(Invoice invoice) { _context.Entry(invoice).State = EntityState.Modified; }
public void UpdateInvoiceJsonData(Invoice invoice, int billingAddressID, int deliveryAddressID) { invoice.JsonData = JsonConvert.SerializeObject(InvoiceFormattedData.GetData(invoice, billingAddressID, deliveryAddressID)); Global.DaoFactory.GetInvoiceDao().UpdateInvoiceJsonData(invoice.ID, invoice.JsonData); }
public void EmailIsGenerated() { var emailer = new Mock <IEmailer>(); string to = null; string from = null; string subject = null; string body = null; emailer .Setup(x => x.Send(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>())) .Callback(delegate(string delegateTo, string delegateFrom, string delegateSubject, string delegateBody) { to = delegateTo; from = delegateFrom; subject = delegateSubject; body = delegateBody; }); var request = new GenerateInvoiceRequest(); request.InvoiceNumber = "ABC123"; request.PeriodFrom = new DateTime(2010, 10, 1); request.PeriodTo = new DateTime(2010, 10, 10); request.Customer = new Customer() { Id = Guid.NewGuid(), GivenName = "Tom", Bookings = new List <Booking>() { new Booking() { EndDate = new DateTime(2010, 10, 2), Total = 200m }, new Booking() { EndDate = new DateTime(2010, 10, 9), Total = 150m } }, User = new User() { Id = Guid.NewGuid(), Username = "******" } }; var invoice = Invoice.Generate(request, emailer.Object); Assert.AreEqual("*****@*****.**", to); Assert.AreEqual("*****@*****.**", from); Assert.AreEqual("Invoice for period 1 Oct 2010 to 10 Oct 2010", subject); var expectedBody = new StringBuilder(); expectedBody.AppendLine("Dear Tom,"); expectedBody.AppendLine(); expectedBody.AppendLine("Please pay the outstanding amount of £350.00"); expectedBody.AppendLine(); expectedBody.AppendLine("Regards,"); expectedBody.AppendLine("The Campervibe Team"); Assert.AreEqual(expectedBody.ToString(), body); }
public void DeleteInvoice(Invoice invoice) { _context.Invoices.Remove(invoice); }
//We can print everything without knowing the implementation public void Print(Invoice invoice) { //printing logic _printingSystem.Print(invoice); }
public void InsertInvoice(Invoice invoice) { _context.Invoices.Add(invoice); }
public void PrintWithLogo(Invoice invoice) { //PrintWithLogo logic _printingGeneric.PrintWithLogo(invoice); }
public ActionResult CreateCart(ShoppingCartDetails cartDetails, FormCollection col)//[Bind(Include = "Id,GoodId,Name,ShortDetail,LongDetail,Thumbail,WholesaleRate,Quantity,CoupenCode,CreatedDate,CreatedBy,EditedBy,EditedDate,Imag ) { if (Session["ACategory"] != null) { if (Session["ACategory"].ToString() == "Trading" && Session["ACategory"] != null) { if (ModelState.IsValid) { try { if (Convert.ToInt32(col["customerId"]) != 0) { int customerId = Convert.ToInt32(col["customerId"]); decimal Vat = Convert.ToDecimal(col["vatTotal"]); decimal Subtotal = Convert.ToDecimal(col["Total"]); decimal GrandTotal = Convert.ToDecimal(col["GrandTotal"]); decimal other = Convert.ToDecimal(col["Other"]); var objInvoiceGoods = new Invoice(); var objInvoice = new INVProduct(); objInvoiceGoods.CustomerId = customerId; objInvoiceGoods.Vat = Vat; objInvoiceGoods.Subtotal = Subtotal; objInvoiceGoods.GrandTotal = GrandTotal; objInvoiceGoods.Other = other; InvoiceGenerate invoice = db.InvoiceGenerates.FirstOrDefault(); if (invoice == null) { db.InvoiceGenerates.Add(new InvoiceGenerate { InvoiceId = 1 }); db.SaveChanges(); invoice = db.InvoiceGenerates.FirstOrDefault(); } else { invoice.InvoiceId = invoice.InvoiceId + 1; db.SaveChanges(); } string invoicet = invoice.InvoiceId.ToString(); objInvoiceGoods.InvoiceNo = invoice.InvoiceId.ToString(); db.Invoices.Add(objInvoiceGoods); db.SaveChanges(); try { foreach (var item in cartDetails.AddToCarts) { objInvoice.InvoiceId = invoicet; objInvoice.Rate = item.price; objInvoice.Quantity = item.Quantity; objInvoice.TradingGoodsId = item.ProductId; objInvoice.Total = item.Subtotal; var goods = db.TradingGoods.Where(t => t.Id == item.ProductId).FirstOrDefault(); goods.Quantity -= item.Quantity; db.INVProducts.Add(objInvoice); db.SaveChanges(); } var Sesson = Session["userEmail"].ToString(); db.Database.ExecuteSqlCommand("Delete From cart where SessonId ='" + Sesson + "'"); return(RedirectToAction("Index", "TradingCompletes")); } catch { return(RedirectToAction("ViewCart")); } } TempData["message"] = "Please select costumer"; return(RedirectToAction("ViewCart")); } catch { return(RedirectToAction("ViewCart")); } } return(RedirectToAction("ViewCart")); } } return(new HttpStatusCodeResult(HttpStatusCode.NotFound)); }
public void PrintAll(Invoice invoice) { //printAll logic _printAll.Print(invoice); _printAll.PrintWithLogo(invoice); }
public static InvoiceFormattedData GetData(Invoice invoice, int billingAddressID, int deliveryAddressID) { return(invoice.JsonData != null?ReadData(invoice.JsonData) : CreateData(invoice, billingAddressID, deliveryAddressID)); }
public async Task CreateInvoice(Invoice invoice) { await Container.CreateItemAsync(invoice, new PartitionKey(invoice.id)); }
private static InvoiceFormattedData CreateData(Invoice invoice, int billingAddressID, int deliveryAddressID) { var data = new InvoiceFormattedData(); var sb = new StringBuilder(); var list = new List <string>(); var cultureInfo = string.IsNullOrEmpty(invoice.Language) ? CultureInfo.CurrentCulture : CultureInfo.GetCultureInfo(invoice.Language); #region TemplateType data.TemplateType = (int)invoice.TemplateType; #endregion #region Seller, LogoBase64, LogoSrcFormat var invoiceSettings = Global.DaoFactory.GetInvoiceDao().GetSettings(); if (!string.IsNullOrEmpty(invoiceSettings.CompanyName)) { sb.Append(invoiceSettings.CompanyName); } if (!string.IsNullOrEmpty(invoiceSettings.CompanyAddress)) { var obj = JObject.Parse(invoiceSettings.CompanyAddress); var str = obj.Value <string>("country"); if (!string.IsNullOrEmpty(str)) { list.Add(str); } str = obj.Value <string>("state"); if (!string.IsNullOrEmpty(str)) { list.Add(str); } str = obj.Value <string>("city"); if (!string.IsNullOrEmpty(str)) { list.Add(str); } str = obj.Value <string>("street"); if (!string.IsNullOrEmpty(str)) { list.Add(str); } str = obj.Value <string>("zip"); if (!string.IsNullOrEmpty(str)) { list.Add(str); } if (list.Count > 0) { sb.AppendLine(); sb.Append(string.Join(", ", list)); } } data.Seller = new Tuple <string, string>(CRMInvoiceResource.ResourceManager.GetString("Seller", cultureInfo), sb.ToString()); if (invoiceSettings.CompanyLogoID != 0) { data.LogoBase64Id = invoiceSettings.CompanyLogoID; //data.LogoBase64 = OrganisationLogoManager.GetOrganisationLogoBase64(invoiceSettings.CompanyLogoID); data.LogoSrcFormat = OrganisationLogoManager.OrganisationLogoSrcFormat; } #endregion #region Number data.Number = new Tuple <string, string>(CRMInvoiceResource.ResourceManager.GetString("Invoice", cultureInfo), invoice.Number); #endregion #region Invoice data.Invoice = new List <Tuple <string, string> >(); data.Invoice.Add(new Tuple <string, string>(CRMInvoiceResource.ResourceManager.GetString("IssueDate", cultureInfo), invoice.IssueDate.ToShortDateString())); if (!string.IsNullOrEmpty(invoice.PurchaseOrderNumber)) { data.Invoice.Add(new Tuple <string, string>(CRMInvoiceResource.ResourceManager.GetString("PONumber", cultureInfo), invoice.PurchaseOrderNumber)); } data.Invoice.Add(new Tuple <string, string>(CRMInvoiceResource.ResourceManager.GetString("DueDate", cultureInfo), invoice.DueDate.ToShortDateString())); #endregion #region Customer var customer = Global.DaoFactory.GetContactDao().GetByID(invoice.ContactID); if (customer != null) { sb = new StringBuilder(); sb.Append(customer.GetTitle()); var billingAddress = billingAddressID != 0 ? Global.DaoFactory.GetContactInfoDao().GetByID(billingAddressID) : null; if (billingAddress != null && billingAddress.InfoType == ContactInfoType.Address && billingAddress.Category == (int)AddressCategory.Billing) { list = new List <string>(); var obj = JObject.Parse(billingAddress.Data); var str = obj.Value <string>("country"); if (!string.IsNullOrEmpty(str)) { list.Add(str); } str = obj.Value <string>("state"); if (!string.IsNullOrEmpty(str)) { list.Add(str); } str = obj.Value <string>("city"); if (!string.IsNullOrEmpty(str)) { list.Add(str); } str = obj.Value <string>("street"); if (!string.IsNullOrEmpty(str)) { list.Add(str); } str = obj.Value <string>("zip"); if (!string.IsNullOrEmpty(str)) { list.Add(str); } if (list.Count > 0) { sb.AppendLine(); sb.Append(string.Join(", ", list)); } } data.Customer = new Tuple <string, string>(CRMInvoiceResource.ResourceManager.GetString("BillTo", cultureInfo), sb.ToString()); } #endregion #region TableHeaderRow, TableBodyRows, TableFooterRows, TableTotalRow data.TableHeaderRow = new List <string> { CRMInvoiceResource.ResourceManager.GetString("ItemCol", cultureInfo), CRMInvoiceResource.ResourceManager.GetString("QuantityCol", cultureInfo), CRMInvoiceResource.ResourceManager.GetString("PriceCol", cultureInfo), CRMInvoiceResource.ResourceManager.GetString("DiscountCol", cultureInfo), CRMInvoiceResource.ResourceManager.GetString("TaxCol", cultureInfo), CRMInvoiceResource.ResourceManager.GetString("TaxCol", cultureInfo), CRMInvoiceResource.ResourceManager.GetString("AmountCol", cultureInfo) }; data.TableBodyRows = new List <List <string> >(); var invoiceLines = invoice.GetInvoiceLines(); var invoiceTaxes = new Dictionary <int, decimal>(); decimal subtotal = 0; decimal discount = 0; decimal amount = 0; foreach (var line in invoiceLines) { var item = Global.DaoFactory.GetInvoiceItemDao().GetByID(line.InvoiceItemID); var tax1 = line.InvoiceTax1ID > 0 ? Global.DaoFactory.GetInvoiceTaxDao().GetByID(line.InvoiceTax1ID) : null; var tax2 = line.InvoiceTax2ID > 0 ? Global.DaoFactory.GetInvoiceTaxDao().GetByID(line.InvoiceTax2ID) : null; var subtotalValue = Math.Round(line.Quantity * line.Price, 2); var discountValue = Math.Round(subtotalValue * line.Discount / 100, 2); var rate = 0; if (tax1 != null) { rate += tax1.Rate; if (invoiceTaxes.ContainsKey(tax1.ID)) { invoiceTaxes[tax1.ID] = invoiceTaxes[tax1.ID] + Math.Round((subtotalValue - discountValue) * tax1.Rate / 100, 2); } else { invoiceTaxes.Add(tax1.ID, Math.Round((subtotalValue - discountValue) * tax1.Rate / 100, 2)); } } if (tax2 != null) { rate += tax2.Rate; if (invoiceTaxes.ContainsKey(tax2.ID)) { invoiceTaxes[tax2.ID] = invoiceTaxes[tax2.ID] + Math.Round((subtotalValue - discountValue) * tax2.Rate / 100, 2); } else { invoiceTaxes.Add(tax2.ID, Math.Round((subtotalValue - discountValue) * tax2.Rate / 100, 2)); } } decimal taxValue = Math.Round((subtotalValue - discountValue) * rate / 100, 2); decimal amountValue = Math.Round(subtotalValue - discountValue + taxValue, 2); subtotal += subtotalValue; discount += discountValue; amount += amountValue; data.TableBodyRows.Add(new List <string> { item.Title + (string.IsNullOrEmpty(line.Description) ? string.Empty : ": " + line.Description), line.Quantity.ToString(CultureInfo.InvariantCulture), line.Price.ToString(CultureInfo.InvariantCulture), line.Discount.ToString(CultureInfo.InvariantCulture), tax1 != null ? tax1.Name : string.Empty, tax2 != null ? tax2.Name : string.Empty, (subtotalValue - discountValue).ToString(CultureInfo.InvariantCulture) }); } data.TableFooterRows = new List <Tuple <string, string> >(); data.TableFooterRows.Add(new Tuple <string, string>(CRMInvoiceResource.ResourceManager.GetString("Subtotal", cultureInfo), (subtotal - discount).ToString(CultureInfo.InvariantCulture))); foreach (var invoiceTax in invoiceTaxes) { var iTax = Global.DaoFactory.GetInvoiceTaxDao().GetByID(invoiceTax.Key); data.TableFooterRows.Add(new Tuple <string, string>(string.Format("{0} ({1}%)", iTax.Name, iTax.Rate), invoiceTax.Value.ToString(CultureInfo.InvariantCulture))); } //data.TableFooterRows.Add(new Tuple<string, string>(CRMInvoiceResource.ResourceManager.GetString("Discount", cultureInfo), "-" + discount.ToString(CultureInfo.InvariantCulture))); data.TableTotalRow = new Tuple <string, string>(string.Format("{0} ({1})", CRMInvoiceResource.ResourceManager.GetString("Total", cultureInfo), invoice.Currency), amount.ToString(CultureInfo.InvariantCulture)); #endregion #region Terms data.Terms = new Tuple <string, string>(CRMInvoiceResource.ResourceManager.GetString("Terms", cultureInfo), invoice.Terms); #endregion #region Notes if (!string.IsNullOrEmpty(invoice.Description)) { data.Notes = new Tuple <string, string>(CRMInvoiceResource.ResourceManager.GetString("ClientNotes", cultureInfo), invoice.Description); } #endregion #region Consignee var consignee = Global.DaoFactory.GetContactDao().GetByID(invoice.ConsigneeID); if (consignee != null) { sb = new StringBuilder(); sb.Append(consignee.GetTitle()); var deliveryAddress = deliveryAddressID != 0 ? Global.DaoFactory.GetContactInfoDao().GetByID(deliveryAddressID) : null; if (deliveryAddress != null && deliveryAddress.InfoType == ContactInfoType.Address && deliveryAddress.Category == (int)AddressCategory.Postal) { list = new List <string>(); var obj = JObject.Parse(deliveryAddress.Data); var str = obj.Value <string>("country"); if (!string.IsNullOrEmpty(str)) { list.Add(str); } str = obj.Value <string>("state"); if (!string.IsNullOrEmpty(str)) { list.Add(str); } str = obj.Value <string>("city"); if (!string.IsNullOrEmpty(str)) { list.Add(str); } str = obj.Value <string>("street"); if (!string.IsNullOrEmpty(str)) { list.Add(str); } str = obj.Value <string>("zip"); if (!string.IsNullOrEmpty(str)) { list.Add(str); } if (list.Count > 0) { sb.AppendLine(); sb.Append(string.Join(", ", list)); } } data.Consignee = new Tuple <string, string>(CRMInvoiceResource.ResourceManager.GetString("ShipTo", cultureInfo), sb.ToString()); } #endregion #region Addresses data.BillingAddressID = billingAddressID; data.DeliveryAddressID = deliveryAddressID; #endregion return(data); }
public IActionResult GetInvoicesByUserNetwork([FromForm] string guid, [FromForm] string sharedid, [FromForm] string username) { if (!Helper.IsCallerValid(guid, sharedid, _connstrWallet)) { ErrorObject ro = new ErrorObject(); ro.message = "Invalid"; ro.error = true; return(Json(ro)); } List <Invoice> ret = new List <Invoice>(); string errorMessage = ""; bool isError = false; //get addresses //select unspent outputs //sum and return NpgsqlConnection conn = new NpgsqlConnection(_connstrWallet); conn.Open(); try { string sql = "sp_getinvoicesbyusernetwork"; NpgsqlCommand cmd = new NpgsqlCommand(sql, conn); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add(new NpgsqlParameter("p_guid", guid)); cmd.Parameters.Add(new NpgsqlParameter("p_username", username)); NpgsqlDataReader reader = cmd.ExecuteReader(); int counter = 0; while (reader.Read()) { Invoice inv = new Invoice(); inv.InvoiceFrom = reader.GetString(0); inv.InvoiceId = reader.GetInt32(1); inv.InvoiceDate = reader.GetDateTime(2); inv.InvoiceStatus = reader.GetInt32(3); if (!reader.IsDBNull(4)) { inv.InvoicePaidDate = reader.GetDateTime(4); } if (!reader.IsDBNull(5)) { inv.TransactionId = reader.GetString(5); } inv.Packet = reader.GetString(6); ret.Add(inv); counter++; } } catch (Exception ex) { isError = true; errorMessage = "Database related Error"; } finally { conn.Close(); } if (isError) { ErrorObject ro = new ErrorObject(); ro.message = errorMessage; ro.error = true; return(Json(ro)); } else { return(Json(ret)); } }
public int CreateInvoice(Invoice Model) { string sql = $"insert into Invoice values ('{Model.Unit}','{Model.Tax}','{Model.Bank}','{Model.Bankurl}',{(Model.Duty == true ? 1 : 0)},'{Model.Rate}')"; return(conn.Execute(sql)); }
public async Task <Invoice> Put([FromBody] Invoice invoice) { return(await invoiceService.UpdateInvoice(invoice)); }
private void gridView1_RowClick(object sender, RowClickEventArgs e) { Invoice selectedRowInvoice = (sender as GridView).GetFocusedRow() as Invoice; switch (selectedRowInvoice) { case Invoice invoice when invoice.InvoiceStatus == InvoiceSeed.Emitted: { parent.ChangeEnableOption_bbMarkAsSentInvoice(true); parent.ChangeEnableOption_bbPayInvoice(true); parent.ChangeEnableOption_bbStornoInvoice(true); parent.ChangeEnableOption_bbCancelInvoice(true); parent.ChangeEnableOption_bbEditDataInvoice(true); parent.ChangeEnableOption_bbOpenClientInvoice(false); parent.ChangeEnableOption_bbAnnounceInvoice(false); break; } case Invoice invoice when invoice.InvoiceStatus == InvoiceSeed.Cancelled: { parent.ChangeEnableOption_bbEditDataInvoice(true); parent.ChangeEnableOption_bbMarkAsSentInvoice(true); parent.ChangeEnableOption_bbOpenClientInvoice(false); parent.ChangeEnableOption_bbAnnounceInvoice(false); parent.ChangeEnableOption_bbPayInvoice(false); parent.ChangeEnableOption_bbStornoInvoice(false); parent.ChangeEnableOption_bbCancelInvoice(false); break; } case Invoice invoice when invoice.InvoiceStatus == InvoiceSeed.Invoiced: { parent.ChangeEnableOption_bbEditDataInvoice(true); parent.ChangeEnableOption_bbOpenClientInvoice(false); parent.ChangeEnableOption_bbAnnounceInvoice(false); parent.ChangeEnableOption_bbMarkAsSentInvoice(false); parent.ChangeEnableOption_bbPayInvoice(false); parent.ChangeEnableOption_bbStornoInvoice(false); parent.ChangeEnableOption_bbCancelInvoice(false); break; } case Invoice invoice when invoice.InvoiceStatus == InvoiceSeed.Overdue: { parent.ChangeEnableOption_bbEditDataInvoice(true); parent.ChangeEnableOption_bbAnnounceInvoice(true); parent.ChangeEnableOption_bbPayInvoice(true); parent.ChangeEnableOption_bbOpenClientInvoice(false); parent.ChangeEnableOption_bbMarkAsSentInvoice(false); parent.ChangeEnableOption_bbStornoInvoice(false); parent.ChangeEnableOption_bbCancelInvoice(false); break; } case Invoice invoice when invoice.InvoiceStatus == InvoiceSeed.Sent: { parent.ChangeEnableOption_bbPayInvoice(true); parent.ChangeEnableOption_bbStornoInvoice(true); parent.ChangeEnableOption_bbCancelInvoice(true); parent.ChangeEnableOption_bbEditDataInvoice(true); parent.ChangeEnableOption_bbOpenClientInvoice(false); parent.ChangeEnableOption_bbAnnounceInvoice(false); parent.ChangeEnableOption_bbMarkAsSentInvoice(false); break; } } }
public async Task Post([FromBody] Invoice invoice) { await invoiceService.SaveInvoice(invoice); }
public Task <int> CreateInvoiceAsync(Invoice invoice) { return(channel.CreateInvoiceAsync(invoice)); }
/// <summary> /// Initializes a new instance of the <see cref="PSInvoice" /> class. /// </summary> /// <param name="invoice">The base invoice for this instance.</param> public PSInvoice(Invoice invoice) { this.CopyFrom(invoice, CloneAdditionalOperations); }