public void CreateInvoice(InvoiceModel invoice) { }
public ActionResult Printinv(int id) { var datainv = new InvoiceModel(); try { var cmd = _context.Database.Connection.CreateCommand(); cmd.Parameters.Clear(); cmd.CommandType = CommandType.Text; cmd.CommandText = @"select * from invoice iv where iv.id=@id"; cmd.Parameters.Add(new SqlParameter("@id", SqlDbType.Int) { Value = id }); try { cmd.Connection.Open(); var result = cmd.ExecuteReader(); while (result.Read()) { datainv.id = (int)result["id"]; datainv.InvoiceNo = result["InvoiceNo"].ToString(); datainv.InvoiceDate = result["InvoiceDate"].ToString() == "" ? (DateTime?)null : (DateTime?)result["InvoiceDate"]; datainv.PeriodeBln = result["PeriodeBln"].ToString(); datainv.PeriodeThn = result["PeriodeThn"].ToString(); datainv.Deskripsi = result["Deskripsi"].ToString(); datainv.Status = result["Status"].ToString(); datainv.Filename = result["Filename"].ToString(); datainv.Qty = (int)result["Qty"]; datainv.GrandTotal = (Decimal)result["GrandTotal"]; datainv.CreateDate = (DateTime)result["CreateDate"]; datainv.UpdateDate = result["UpdateDate"].ToString() == "" ? (DateTime?)null : (DateTime?)result["UpdateDate"]; } if (datainv == null || datainv.id == 0) { throw new Exception("Data Invoice tidak ditemukan"); } } catch (Exception ex) { TempData["pesanJudul"] = "Error!"; TempData["pesanType"] = "alert-danger"; TempData["pesanText"] = ex.Message; } finally { cmd.Dispose(); cmd.Connection.Close(); } if (!(datainv.Qty > 0) && (datainv.GrandTotal > 0)) { throw new Exception("Nilai tagihan nol"); } var tmstamp = new DateTimeOffset(DateTime.UtcNow).ToUnixTimeSeconds().ToString(); var invfile = String.Concat("INV", datainv.PeriodeThn.Trim(), datainv.PeriodeBln.Trim(), tmstamp.Trim(), ".pdf"); if (datainv.Filename == "" || datainv.InvoiceDate == null) { datainv.Filename = invfile; try { CreatePdfInvoice(datainv); // update tgl Invoice datainv.InvoiceDate = UpdateInvoicePrint(id, datainv.Filename); } catch (Exception ex) { TempData["pesanJudul"] = "Error!"; TempData["pesanType"] = "alert-danger"; TempData["pesanText"] = ex.Message; return(RedirectToAction("Index")); } } string pathTemp = ConfigurationManager.AppSettings["FileInvoice"]; string Fileinvpdf = pathTemp + datainv.Filename; if (!System.IO.File.Exists(Fileinvpdf)) { TempData["pesanJudul"] = "Error!"; TempData["pesanType"] = "alert-danger"; TempData["pesanText"] = "File template invoice tidak ditemukan " + Fileinvpdf; return(RedirectToAction("Index")); } Response.Headers.Add("content-disposition", "attachment; filename=" + datainv.Filename); return(File(new FileStream(Fileinvpdf, FileMode.Open), "application/octet-stream")); } catch (Exception ex) { TempData["pesanJudul"] = "Error!"; TempData["pesanType"] = "alert-danger"; TempData["pesanText"] = ex.Message; //throw new Exception(ex.Message); return(RedirectToAction("Index")); } }
public async Task <InvoiceStatus> GetStatusOnlyAsync(string invoiceId) { InvoiceModel invoice = await _payInvoiceClient.GetInvoiceAsync(invoiceId); return(invoice.Status); }
public IActionResult ReciveAddInvoice(InvoiceModel value) { //add model to db. return(Json(value)); }
public override InvoiceModel CalculateTotalDue(InvoiceModel invoice, string memberId, string locale, string countryCode, bool isReset) { CalculateDiscountedAmount(invoice); CalculateTotalDue(invoice); return(invoice); }
public ActionResult PaymentReturn() { try { string eventCode = Request["event"]; string dataId = Request["data[id]"]; string dataStatus = Request["data[status]"]; string dataAccountId = Request["data[account_id]"]; string dataSubscriptionId = Request["data[subscription_id]"]; var requestMessage = new StringBuilder(); requestMessage.Append("Plugin.Payments.Iugu:"); requestMessage.AppendFormat("eventCode: {0} ", eventCode); requestMessage.AppendFormat("dataId: {0} ", dataId); requestMessage.AppendFormat("dataStatus: {0} ", dataStatus); requestMessage.AppendFormat("dataAccountId: {0} ", dataAccountId); requestMessage.AppendFormat("dataSubscriptionId: {0} ", dataSubscriptionId); _logger.Information(requestMessage.ToString()); string codigoPedido = string.Empty; if (string.IsNullOrEmpty(eventCode)) { _logger.Error("Plugin.Payments.Iugu: eventCode não encontrado"); return(new HttpStatusCodeResult(HttpStatusCode.OK)); } InvoiceModel invoice = null; using (var apiInvoice = new Invoice()) { invoice = apiInvoice.GetAsync(dataId, _iuguPaymentSettings.CustomApiToken).ConfigureAwait(false).GetAwaiter().GetResult(); foreach (var variable in invoice.custom_variables) { if (variable.name == IuguHelper.CODIGO_PEDIDO) { codigoPedido = variable.value; } } } if (string.IsNullOrEmpty(codigoPedido)) { _logger.Error("Plugin.Payments.Iugu: Pedido não encontrado na fatura IUGU"); return(new HttpStatusCodeResult(HttpStatusCode.InternalServerError)); } Order order = null; if (codigoPedido.Length == 36) { order = _orderService.GetOrderByGuid(new Guid(codigoPedido)); } else { order = _orderService.GetOrderById(int.Parse(codigoPedido)); } if (order == null) { _logger.Information("Plugin.Payments.Iugu: Pedido não encontrado. Pedido: " + codigoPedido); return(new HttpStatusCodeResult(HttpStatusCode.InternalServerError)); } if (dataStatus == "paid" && _orderProcessingService.CanMarkOrderAsPaid(order)) { order.AuthorizationTransactionId = dataId; _orderService.UpdateOrder(order); _orderProcessingService.MarkOrderAsPaid(order); _orderNoteService.AddOrderNote("Pagamento aprovado.", true, order); if (_iuguPaymentSettings.AdicionarNotaExcluir) { _orderNoteService.AddOrderNote("Aguardando Impressão - Excluir esse comentário ao imprimir ", false, order); } if (_iuguPaymentSettings.AdicionarNotaPrazoFabricaoEnvio) { _orderNoteService.AddOrderNote(_orderNoteService.GetOrdeNoteRecievedPayment(order, _iuguPaymentSettings.NomePluginAmigavelMensagemConfirmacao), true, order, true); } } } catch (Exception ex) { string erro = string.Format("Plugin.Payments.Iugu: Erro IUGU - {0}", ex.Message.ToString()); _logger.Error(erro, ex); return(new HttpStatusCodeResult(HttpStatusCode.InternalServerError)); } return(new HttpStatusCodeResult(HttpStatusCode.OK)); }
public IHttpActionResult PostInvoice([FromBody] InvoiceViewModel invoiceViewModel) { InvoiceTable Table = new InvoiceTable(); using (DBEntities context = new DBEntities()) { using (DbContextTransaction transaction = context.Database.BeginTransaction(System.Data.IsolationLevel.ReadCommitted)) { try { Table.Invoice_ID = invoiceViewModel.Invoice_ID; Table.CompanyId = invoiceViewModel.CompanyId; Table.UserId = invoiceViewModel.UserId; Table.ContactId = invoiceViewModel.ContactId; Table.RefNumber = invoiceViewModel.RefNumber; Table.InvoiceDate = invoiceViewModel.InvoiceDate; Table.InvoiceDueDate = invoiceViewModel.InvoiceDueDate; Table.SubTotal = invoiceViewModel.SubTotal; Table.DiscountAmount = invoiceViewModel.DiscountAmount; Table.TotalAmount = invoiceViewModel.TotalAmount; Table.CustomerNote = invoiceViewModel.CustomerNote; Table.TotalVat21 = invoiceViewModel.TotalVat21; Table.TotalVat6 = invoiceViewModel.TotalVat6; Table.Type = StatusEnum.Goods.ToString(); Table.Status = "accepted"; Table.InvoiceDescription = invoiceViewModel.InvoiceDescription; if (Table.TotalVat6 != null) { double vat61 = Math.Round((double)Table.TotalVat6, 2, MidpointRounding.AwayFromZero); Table.TotalVat6 = vat61; } if (Table.TotalVat21 != null) { double vat21 = Math.Round((double)Table.TotalVat21, 2, MidpointRounding.AwayFromZero); Table.TotalVat21 = vat21; } Table = context.InvoiceTables.Add(Table); context.SaveChanges(); if (invoiceViewModel.InvoiceDetailsTable != null) { foreach (InvoiceDetailsTable InvoiceDetailsList in invoiceViewModel.InvoiceDetailsTable) { InvoiceDetailsTable InvoiceDetails = new InvoiceDetailsTable(); InvoiceDetails.ItemId = Convert.ToInt32(InvoiceDetailsList.ItemId); InvoiceDetails.InvoiceId = Table.InvoiceID; InvoiceDetails.Description = InvoiceDetailsList.Description; InvoiceDetails.Quantity = InvoiceDetailsList.Quantity; InvoiceDetails.Rate = Convert.ToDouble(InvoiceDetailsList.Rate); InvoiceDetails.Total = Convert.ToDouble(InvoiceDetailsList.Total); InvoiceDetails.ServiceDate = InvoiceDetailsList.ServiceDate; InvoiceDetails.RowSubTotal = InvoiceDetailsList.RowSubTotal; InvoiceDetails.Vat = Convert.ToDouble(InvoiceDetailsList.Vat); InvoiceDetails.Type = InvoiceDetailsList.Type; if (InvoiceDetails.InvoiceDetailId == 0) { InvoiceDetails = context.InvoiceDetailsTables.Add(InvoiceDetails); context.SaveChanges(); } } } AccountTransictionTable Account = new AccountTransictionTable(); Account.TransictionDate = DateTime.Now; Account.TransictionNumber = base64Guid; Account.TransictionType = "Invoice"; Account.TransictionRefrenceId = Table.InvoiceID.ToString(); Account.CreationTime = DateTime.Now.TimeOfDay; Account.AddedBy = 1; Account.FK_CompanyId = invoiceViewModel.CompanyId; Account.FKPaymentTerm = 1; //Cash Account Transaction int CashtAccountId = AccountIdByName("Cash on hand", (int)invoiceViewModel.CompanyId); if (CashtAccountId != 0) { Account.Dr = invoiceViewModel.TotalAmount; Account.Cr = 0.00; Account.FK_AccountID = CashtAccountId; context.AccountTransictionTables.Add(Account); context.SaveChanges(); } // Sale Account Transaction int SaleAccount = AccountIdByName("Seles", (int)invoiceViewModel.CompanyId); if (SaleAccount != 0) { Account.Cr = invoiceViewModel.SubTotal; Account.Dr = 0.00; Account.FK_AccountID = SaleAccount; context.AccountTransictionTables.Add(Account); context.SaveChanges(); } // vat Out Put Trnsaction int VatAccountId = AccountIdByName("VAT Payable", (int)invoiceViewModel.CompanyId); if (VatAccountId != 0) { Account.Cr = invoiceViewModel.TotalVat6 + invoiceViewModel.TotalVat21; Account.Dr = 0.00; Account.FK_AccountID = VatAccountId; context.AccountTransictionTables.Add(Account); int Id = context.SaveChanges(); } InvoiceModel inc = new InvoiceModel(); inc.InvoiceID = Table.InvoiceID; transaction.Commit(); return(Ok(inc)); } catch (Exception) { transaction.Rollback(); return(BadRequest()); } } } }
private void CalculateTaxAmount(InvoiceModel invoice, string memberId, string countryCode, Address address, string warehouseCode, string shippingMethodId) { if (invoice.InvoicePrice.TaxPercentage > 0) { invoice.InvoicePrice.CalcTaxAmount = decimal.Round( ((invoice.InvoicePrice.SubTotal - invoice.InvoicePrice.CalcDiscountAmount) * (invoice.InvoicePrice.TaxPercentage / 100)), 2); invoice.InvoicePrice.DisplayCalculatedTax = invoice.InvoicePrice.CalcTaxAmount.FormatPrice(); } else if (invoice.InvoicePrice.TaxAmount > 0) { invoice.InvoicePrice.CalcTaxAmount = invoice.InvoicePrice.TaxAmount; invoice.InvoicePrice.DisplayCalculatedTax = invoice.InvoicePrice.CalcTaxAmount.FormatPrice(); } else if (invoice.InvoicePrice.TaxAmount == 0 && invoice.InvoicePrice.TaxPercentage == 0 && (invoice.IsCustomerTaxEdited && !invoice.ResetCustomerTaxValue)) { invoice.InvoicePrice.CalcTaxAmount = invoice.InvoicePrice.TaxAmount; invoice.InvoicePrice.DisplayCalculatedTax = invoice.InvoicePrice.CalcTaxAmount.FormatPrice(); } else { var customerOrder = ConvertToCustomerOrder(invoice, memberId, countryCode, address, warehouseCode, shippingMethodId); var productTax = 0M; var freightTax = 0M; var customerOrderItems = new OrderItems(); foreach (CustomerOrderItem_V01 item in customerOrder.OrderItems) { customerOrderItems.Add(item); } if (customerOrderItems.Any()) { customerOrder.OrderItems = null; customerOrder.OrderItems = customerOrderItems; var response = CallDwsPricing(customerOrder); if (null != response && response.Status == ServiceProvider.OrderSvc.ServiceResponseStatusType.Success) { var responseV01 = response as GetTaxDataForDwsFromVertexResponse_V01; if (responseV01 == null) { LoggerHelper.Error( string.Format( "CalculateDistributorPrice - InvoicePriceProvider: An error occured while invoking CalculateDistributorPrice" )); } else { productTax += responseV01.ProductTaxData.AsParallel().Sum(x => x.Value); freightTax += responseV01.FreightTaxData.AsParallel().Sum(x => x.Value); } } else { LoggerHelper.Error( string.Format( "CalculateDistributorPrice - InvoicePriceProvider: An error occured while invoking CalculateDistributorPrice {0}", memberId)); } } invoice.InvoicePrice.CalcTaxAmount = productTax + freightTax; invoice.InvoicePrice.TaxAmount = invoice.InvoicePrice.CalcTaxAmount; invoice.InvoicePrice.DisplayCalculatedTax = invoice.InvoicePrice.CalcTaxAmount.FormatPrice(); } }
public List <HistoryModel> GetStockNumberHistory(InvoiceModel invoice) { var history = InvoiceRepository.GetInvoiceHistory(invoice.StockNumber); return(Mapper.Map <IList <Data.Graph.StockNumberHistory>, List <HistoryModel> >(history)); }
public GetInvoiceQueryResult(InvoiceModel invoiceModel) { InvoiceModel = invoiceModel; }
// GET: Invoice/Edit/By ID public ActionResult Edit(long id) { var errorViewModel = new ErrorViewModel(); try { var model = _InvoiceService.BMSUnit.InvoiceRepository.GetByID(id); Session["InvoiceId"] = model.Id; var customerList = SelectListItemExtension.PopulateDropdownList(_InvoiceService.BMSUnit.CustomerRepository.GetAll().ToList <tblCustomer>(), "Id", "CustomerName").ToList(); var organizationList = SelectListItemExtension.PopulateDropdownList(_InvoiceService.BMSUnit.OrganizationRepository.GetAll().ToList <tblOrganization>(), "Id", "Organization").ToList(); var currencyList = SelectListItemExtension.PopulateDropdownList(_InvoiceService.BMSUnit.CurrencyRepository.GetAll().ToList <tblCurrency>(), "Id", "CurrencyName").ToList(); var priceTermList = SelectListItemExtension.PopulateDropdownList(_InvoiceService.BMSUnit.PriceTermRepository.GetAll().ToList <tblPriceTerm>(), "Id", "PriceTermName").ToList(); var commTypeList = SelectListItemExtension.PopulateDropdownList(_InvoiceService.BMSUnit.CommCalculationTypeRepository.GetAll().ToList <tblCommCalculationType>(), "Id", "CommissionCalculationTerm").ToList(); var shipmentCountryList = SelectListItemExtension.PopulateDropdownList(_InvoiceService.BMSUnit.CountryRepository.GetAll().ToList <tblCountry>(), "Id", "CountryName").ToList(); var portOfDischargeList = SelectListItemExtension.PopulateDropdownList(_InvoiceService.BMSUnit.PortRepository.GetAll().ToList <tblPort>(), "Id", "PortName").ToList(); var invoiceTypeList = Common.PopulateInvoiceTypeDDList(); if (model != null) { InvoiceModel viewModel = new InvoiceModel { Id = model.Id, InvoiceNo = model.InvoiceNo, InvoiceDate = model.InvoiceDate, ddlInvoiceType = invoiceTypeList, InvoiceType = model.InvoiceType, //InvoiceType = _InvoiceService.BMSUnit.Inv.GetByID(model.OrganizationId).Name, InvoicePeriod = model.InvoicePeriod, ddlOrganization = organizationList, OrganizationId = Convert.ToInt64(model.OrganizationId), //Organization = _InvoiceService.BMSUnit.OrganizationRepository.GetByID(model.OrganizationId).Organization, ddlCustomer = customerList, CustomerId = model.CustomerId, CustomerName = _InvoiceService.BMSUnit.CustomerRepository.GetByID(model.CustomerId).CustomerName, CustomerAddress = _InvoiceService.BMSUnit.CustomerRepository.GetByID(model.CustomerId).Address, Phone = _InvoiceService.BMSUnit.CustomerRepository.GetByID(model.CustomerId).Phone, Email = _InvoiceService.BMSUnit.CustomerRepository.GetByID(model.CustomerId).Email, TIN = _InvoiceService.BMSUnit.CustomerRepository.GetByID(model.CustomerId).TIN, BIN = _InvoiceService.BMSUnit.CustomerRepository.GetByID(model.CustomerId).BIN, ddlPriceTerm = priceTermList, PriceTermId = Convert.ToInt64(model.PriceTermId), ddlCurrency = currencyList, CurrencyId = Convert.ToInt64(model.CurrencyId), ddlShipmentCountry = shipmentCountryList, ShipmentFromCountryId = Convert.ToInt64(model.ShipmentFromCountryId), ddlPortOfDischarge = portOfDischargeList, PortOfDischargeId = Convert.ToInt64(model.PortOfDischargeId), LCNo = model.LCNo, LCDate = model.LCDate, // LDS=model.LDS, LDE = model.LDE, ShipmentDate = model.ShipmentDate, ArrivalDate = model.ArrivalDate, CommercialInvoiceNo = model.CommercialInvoiceNo, CommercialInvoiceDate = model.CommercialInvoiceDate, BoLNo = model.BoLNo, ddlCommissionTerm = commTypeList, CommCalcTermId = Convert.ToInt64(model.CommCalcTermId), Total = model.Total, OtherCharges = model.OtherCharges, CommissionPer = model.CommissionPercent, Commission = model.Commission, NET = model.NET //,IsActive = Convert.ToBoolean(model.IsActive) }; return(PartialView("_Edit", viewModel)); } else { errorViewModel.ErrorMessage = CommonMessage.ErrorOccurred; return(PartialView("_ErrorPopUp", errorViewModel)); } } catch (Exception ex) { errorViewModel.ErrorMessage = CommonExceptionMessage.GetExceptionMessage(ex); return(PartialView("_ErrorPopUp", errorViewModel)); } }
public ActionResult Create(InvoiceModel viewModel) { var strMessage = string.Empty; try { if (ModelState.IsValid) { #region Current User var userName = HttpContext.User.Identity.Name; viewModel.IUser = userName; viewModel.IDate = DateTime.Now; viewModel.EDate = DateTime.Now; #endregion #region Releated Data viewModel.InvoiceNo = "123"; //viewModel.testVal1 = _InvoiceService.Get_New_InvoiceId().FirstOrDefault().testVal1; viewModel.InvoicePeriod = 201609; viewModel.InvoiceType = "C"; viewModel.Remarks = "Remarks Field Has not found"; var PSavedGRlist = _InvoiceService.GenerateCustomInvoiceId().ToList(); viewModel.InvoiceNo = PSavedGRlist.FirstOrDefault().InvoiceId; #endregion List <InvoiceDetailModel> list = new List <InvoiceDetailModel>(); if (Session["lstInvoiceDetails"] != null) { list = (List <InvoiceDetailModel>)Session["lstInvoiceDetails"]; } var entity = viewModel.ToEntity(); _InvoiceService.BMSUnit.InvoiceRepository.Add(entity); _InvoiceService.BMSUnit.InvoiceRepository.SaveChanges(); Session["InvoiceMasterId"] = entity.Id; #region Save Invoice Detail if (list != null && list.Count > 0) { //foreach (InvoiceDetailViewModel detail in list) foreach (InvoiceDetailModel detail in list) { detail.InvoiceId = Convert.ToInt32(entity.Id); var detailEntity = detail.ToEntity(); _InvoiceService.BMSUnit.InvoiceDetailsRepository.Add(detailEntity); _InvoiceService.BMSUnit.InvoiceDetailsRepository.SaveChanges(); } } Session["lstInvoiceDetails"] = null; #endregion return(Content(Boolean.TrueString)); } strMessage = Common.GetModelStateErrorMessage(ModelState); } catch (Exception ex) { strMessage = CommonExceptionMessage.GetExceptionMessage(ex, CommonAction.Save); } return(Content(strMessage)); }
public InvoiceModel Save(InvoiceModel invoice) { throw new NotSupportedException(); }
public void Delete(InvoiceModel invoice) { throw new NotSupportedException(); }
// POST: api/Invoice public void Post([FromBody] InvoiceModel invoice) { invoiceData.AddInvoice(invoice); }
private static void CalculateTotalEarnBase(InvoiceModel invoice) { invoice.InvoicePrice.TotalEarnBase = invoice.InvoiceLines.AsParallel().Sum(s => s.TotalEarnBase); }
public void ProcessFile(InvoiceModel model) { if (model == null) { throw new InvalidOperationException("Invalid model"); } var now = DateTime.Now; if (!(model.Date.Year == now.Year && model.Date.Month == now.Month)) { throw new Exception("Lze naskladnit pouze v aktuálním měsíci"); } var supplier = m_supplierRepository.GetSupplier(model.SupplierName ?? string.Empty).Ensure($"Neexistující dodavatel \"{model.SupplierName}\""); var currency = m_currencyRepository.GetCurrency(model.Currency).Ensure($"Neexistující symbol měny \"{model.Currency}\""); if (string.IsNullOrWhiteSpace(model.InvoiceNumber)) { throw new InvalidOperationException("Chybí číslo faktury"); } var validItems = model.Items.Where(i => !string.IsNullOrWhiteSpace(i.MaterialName)).ToList(); if (!validItems.Any()) { throw new InvalidOperationException("Žádné položky"); } var noPriced = validItems.FirstOrDefault(i => i.Price < 0.0001m || i.Quantity < 0.0001m); if (noPriced != null) { throw new InvalidOperationException($"Položka \"{noPriced.MaterialName}\" nemá cenu nebo mnozstvi"); } decimal priceFactor = model.TotalPrice / validItems.Sum(i => i.Price); var itemsWithCorrectedPrices = new List <Tuple <InvoiceItem, decimal> >(validItems.Count); foreach (var item in validItems) { itemsWithCorrectedPrices.Add(new Tuple <InvoiceItem, decimal>(item, item.Price * priceFactor)); } using (var tx = m_database.OpenTransaction()) { var existingBatches = m_batchRepository.GetBatchesByInvoiceNumber(model.InvoiceNumber, supplier.Id).ToList(); foreach (var itemWithCorrectedPrice in itemsWithCorrectedPrices) { var invoiceItem = itemWithCorrectedPrice.Item1; var material = m_materialRepository.GetMaterialByName(invoiceItem.MaterialName) .Ensure($"Neznámý materiál \"{invoiceItem.MaterialName}\""); var unit = m_unitRepository.GetUnitBySymbol(invoiceItem.Unit) .Ensure($"Neznámá jednotka \"{invoiceItem.Unit}"); if (invoiceItem.Id > 0) { throw new NotSupportedException($"Toto jeste neni podporovano :("); //var existing = existingBatches.FirstOrDefault(b => b.Id == invoiceItem.Id); //if (existing == null) //{ // throw new InvalidOperationException($"Soubor obsahuje polozku s id={invoiceItem.Id}. Toto ID sarze ale nebylo v databazi nalezeno"); //} //existingBatches.Remove(existing); //m_batchRepository.UpdateBatch(invoiceItem.Id, b => //{ // b.BatchNumber = invoiceItem.BatchNumber; // b.Created = receiveDate; // b.InvoiceNr = model.InvoiceNumber; // b.InvoiceVarSymbol = model.VarSymbol; // b.Price = itemWithCorrectedPrice.Item2; // b. //}); } var batchNumber = invoiceItem.BatchNumber?.Trim(); if (string.IsNullOrWhiteSpace(batchNumber)) { var materialInfo = m_materialFacade.GetMaterialInfo(invoiceItem.MaterialName); if (materialInfo == null) { throw new InvalidOperationException($"Neznamy material {invoiceItem.MaterialName}"); } if (!materialInfo.AutomaticBatches) { throw new InvalidOperationException($"Pro materiál \"{invoiceItem.MaterialName}\" musí být uvedeno čslo šarže"); } batchNumber = materialInfo.AutoBatchNr; } m_batchRepository.SaveBottomLevelMaterialBatch(0, material.Adaptee, invoiceItem.Quantity, unit, batchNumber, model.Date, itemWithCorrectedPrice.Item2, model.InvoiceNumber, supplier.Name, currency.Symbol, model.VarSymbol); } tx.Commit(); } }
private static void CalculateSubtotal(InvoiceModel invoice) { invoice.InvoicePrice.SubTotal = invoice.InvoiceLines.AsParallel().Sum(s => s.TotalRetailPrice); invoice.InvoicePrice.DisplaySubtotal = invoice.InvoicePrice.SubTotal.FormatPrice(); }
private static void CalculateTotalYourPrice(InvoiceModel invoice) { invoice.InvoicePrice.TotalYourPrice = invoice.InvoiceLines.AsParallel().Sum(x => x.YourPrice); invoice.InvoicePrice.DisplayTotalYourPrice = invoice.InvoicePrice.TotalYourPrice.FormatPrice(); }
public void SaveInvoice(InvoiceModel invoiceModel) { this._invoicesProvider.SaveInvoice(invoiceModel); }
public override InvoiceModel CalculateBasicPrice(InvoiceModel invoice, string memberId, string locale, string countryCode, bool isReset) { var distributorOrderingProfile = GetDistributorOrderingProfile(memberId, countryCode); if (null == invoice.InvoicePrice) { invoice.InvoicePrice = new InvoicePriceModel(); } var currencySymbol = HLConfigManager.Configurations.CheckoutConfiguration.CurrencySymbol; invoice.InvoicePrice.DisplayCurrencySymbol = currencySymbol; foreach (var invoiceLine in invoice.InvoiceLines) { CalculateInvoiceLineTotal(invoiceLine, currencySymbol); } CalculateSubtotal(invoice); CalculateTotalEarnBase(invoice); var memberDiscount = invoice.InvoicePrice.MemberStaticDiscount > 0 ? invoice.InvoicePrice.MemberStaticDiscount : distributorOrderingProfile.StaticDiscount; CalculateTotalVolumePoints(invoice); if (invoice.Type == "Distributor" && invoice.InvoicePrice.DiscountPercentage == 0) { invoice.InvoicePrice.DiscountPercentage = 25; } if (isReset) { invoice.InvoicePrice.TaxPercentage = 0; invoice.InvoicePrice.CalcTaxAmount = 0; invoice.InvoicePrice.TaxAmount = invoice.InvoicePrice.CalcTaxAmount; invoice.InvoicePrice.DisplayCalculatedTax = invoice.InvoicePrice.CalcTaxAmount.FormatPrice(); invoice.InvoicePrice.TotalDue = invoice.InvoicePrice.SubTotal; invoice.InvoicePrice.DisplayTotalDue = invoice.InvoicePrice.TotalDue.FormatPrice(); invoice.InvoicePrice.DiscountPercentage = invoice.Type == "Distributor" ? 25 : 0; invoice.InvoicePrice.DiscountAmount = 0; invoice.InvoicePrice.CalcDiscountAmount = 0; invoice.InvoicePrice.DisplayDiscountedAmount = string.Format("-{0}", invoice.InvoicePrice.CalcDiscountAmount.FormatPrice()); invoice.InvoicePrice.ShippingPercentage = 0; invoice.InvoicePrice.ShippingAmount = 0; invoice.InvoicePrice.DisplayShipping = invoice.InvoicePrice.ShippingAmount.FormatPrice(); invoice.InvoicePrice.MemberFreight = 0; invoice.InvoicePrice.DisplayMemberFreight = invoice.InvoicePrice.MemberFreight.FormatPrice(); invoice.InvoicePrice.MemberTax = 0; invoice.InvoicePrice.DisplayMemberTax = invoice.InvoicePrice.MemberTax.FormatPrice(); invoice.InvoicePrice.MemberTotal = 0; invoice.InvoicePrice.DisplayMemberTotal = invoice.InvoicePrice.MemberTotal.FormatPrice(); invoice.InvoicePrice.Profit = 0; invoice.InvoicePrice.DisplayProfit = invoice.InvoicePrice.Profit.FormatPrice(); invoice.InvoicePrice.ProfitPercentage = 0; } return(invoice); }
/// <summary> /// Get payment details from Invoice, PaymentRequest and Order /// </summary> /// <param name="invoiceId">Invoice Id</param> /// <param name="force">Will force to create new order if the actual order is expired but can be considered // as actual till extended due date</param> /// <returns></returns> public async Task <PaymentDetails> GetPaymentDetailsAsync(string invoiceId, bool force) { InvoiceModel invoice = await _payInvoiceClient.GetInvoiceAsync(invoiceId); if (invoice.DueDate <= DateTime.UtcNow || invoice.Status == InvoiceStatus.Removed) { return(null); } Task <MerchantModel> merchantTask = _payMerchantClient.Api.GetByIdAsync(invoice.MerchantId); Task <MarkupResponse> markupForMerchantTask = _payInternalClient.ResolveMarkupByMerchantAsync(invoice.MerchantId, $"{invoice.PaymentAssetId}{invoice.SettlementAssetId}"); // now it is important to wait order checkout before making GetPaymentRequest // as WalletAddress will be only after that Task <OrderModel> orderTask = _payInternalClient.ChechoutOrderAsync(new ChechoutRequestModel { MerchantId = invoice.MerchantId, PaymentRequestId = invoice.PaymentRequestId, Force = force }); try { await Task.WhenAll(merchantTask, markupForMerchantTask, orderTask); } catch (Exception ex) { _log.ErrorWithDetails(ex, invoice.Sanitize()); throw; } OrderModel order = orderTask.Result; MerchantModel merchant = merchantTask.Result; MarkupResponse markupForMerchant = markupForMerchantTask.Result; PaymentRequestModel paymentRequest = await _payInternalClient.GetPaymentRequestAsync(invoice.MerchantId, invoice.PaymentRequestId); Asset settlementAsset = await _lykkeAssetsResolver.TryGetAssetAsync(invoice.SettlementAssetId); Asset paymentAsset = await _lykkeAssetsResolver.TryGetAssetAsync(invoice.PaymentAssetId); int totalSeconds = 0; int remainingSeconds = 0; int extendedTotalSeconds = 0; int extendedRemainingSeconds = 0; if (invoice.Status == InvoiceStatus.Unpaid) { totalSeconds = (int)(order.DueDate - order.CreatedDate).TotalSeconds; remainingSeconds = (int)(order.DueDate - DateTime.UtcNow).TotalSeconds; if (remainingSeconds > totalSeconds) { remainingSeconds = totalSeconds; } extendedTotalSeconds = (int)(order.ExtendedDueDate - order.DueDate).TotalSeconds; extendedRemainingSeconds = (int)(order.ExtendedDueDate - DateTime.UtcNow).TotalSeconds; if (extendedRemainingSeconds > extendedTotalSeconds) { extendedRemainingSeconds = extendedTotalSeconds; } } return(new PaymentDetails { Id = invoice.Id, Number = invoice.Number, Status = invoice.Status, Merchant = merchant, PaymentAmount = order.PaymentAmount, SettlementAmount = invoice.Amount, PaymentAssetId = invoice.PaymentAssetId, PaymentAsset = paymentAsset, SettlementAssetId = invoice.SettlementAssetId, SettlementAsset = settlementAsset, ExchangeRate = order.ExchangeRate, DeltaSpread = markupForMerchant.DeltaSpread > 0, Pips = markupForMerchant.Pips + paymentRequest.MarkupPips, Percents = markupForMerchant.DeltaSpread + markupForMerchant.Percent + paymentRequest.MarkupPercent, Fee = markupForMerchant.FixedFee + paymentRequest.MarkupFixedFee, DueDate = invoice.DueDate, Note = invoice.Note, WalletAddress = paymentRequest.WalletAddress, PaymentRequestId = invoice.PaymentRequestId, TotalSeconds = totalSeconds, RemainingSeconds = remainingSeconds, ExtendedTotalSeconds = extendedTotalSeconds, ExtendedRemainingSeconds = extendedRemainingSeconds, PaidAmount = paymentRequest.PaidAmount, PaidDate = paymentRequest.PaidDate }); }
private static void CalculateTotalVolumePoints(InvoiceModel invoice) { invoice.InvoicePrice.TotalVolumePoints = invoice.InvoiceLines.AsParallel().Sum(x => x.TotalVolumePoint); }
private static async Task <InvoiceModel> GetInvoiceElements(IDbConnection connection, InvoiceModel invoice) { var invoiceItems = connection.Query <InvoiceItems>(getInvoiceItemsSql, new { @InvoiceId = invoice.Id }).ToList(); invoice.InvoiceItemses = invoiceItems; var customer = Customer.GetCustomer(invoice.CustomerId); invoice.Customer = customer; var employee = Employee.GetEmployee(invoice.EmployeeId); invoice.Employee = employee; foreach (var item in invoiceItems) { var i = Item.GetItem(item.ItemId); item.Item = i; } return(invoice); }
private static void CalculateTotalMemberTax(InvoiceModel invoice) { invoice.InvoicePrice.MemberTotal = invoice.InvoicePrice.TotalYourPrice + invoice.InvoicePrice.MemberTax + invoice.InvoicePrice.MemberFreight; invoice.InvoicePrice.DisplayMemberTotal = invoice.InvoicePrice.MemberTotal.FormatPrice(); }
private SearchResult <List <InvoiceModel> > Z9EAR_ODBC(int DocEntry, List <InvoiceView> list) { var result = new SearchResult <List <InvoiceModel> >(); var connstring = GetOdbcConnectionString(); using (OdbcConnection connection = new OdbcConnection(connstring)) //创建connection连接对象 { connection.Open(); //打开链接 var sql = "SELECT * FROM \"BS_SBO_1970_AR\".\"CBIC_AR\""; if (DocEntry > 0) { sql = sql + " where \"CBIC_AR\".\"DocEntry\"=" + DocEntry; } using (OdbcCommand command = new OdbcCommand(sql)) //command 对象 { command.Connection = connection; OdbcDataReader reader = command.ExecuteReader(); while (reader.Read()) { list.Add(new InvoiceView() { DocEntry = reader["DocEntry"] == null ? -1 : reader["DocEntry"].ToInt(), DocNum = reader["DocNum"] == null ? -1 : reader["DocNum"].ToInt(), TaxDate = reader["TaxDate"] == null ? DateTime.MinValue : reader["TaxDate"].ToDateTime(), U_ARS = reader["U_ARS"] == null ? "" : reader["U_ARS"].ToString(), U_ART = reader["U_ART"] == null ? "" : reader["U_ART"].ToString(), CardCode = reader["CardCode"] == null ? "" : reader["CardCode"].ToString(), CardName = reader["CardName"] == null ? "" : reader["CardName"].ToString(), GTSRegNum = reader["GTSRegNum"] == null ? "" : reader["GTSRegNum"].ToString(), GTSBilAddr = reader["GTSBilAddr"] == null ? "" : reader["GTSBilAddr"].ToString(), Phone1 = reader["Phone1"] == null ? "" : reader["Phone1"].ToString(), U_CV_BankName = reader["U_CV_BankName"] == null ? "" : reader["U_CV_BankName"].ToString(), GTSBankAct = reader["GTSBankAct"] == null ? "" : reader["GTSBankAct"].ToString(), LineNum = reader["LineNum"] == null ? -1 : reader["LineNum"].ToInt(), ItemCode = reader["ItemCode"] == null ? "" : reader["ItemCode"].ToString(), Quantity = reader["Quantity"] == null ? -1 : reader["Quantity"].ToDecimal(), unitMsr = reader["unitMsr"] == null ? "" : reader["unitMsr"].ToString(), VatPrcnt = reader["VatPrcnt"] == null ? -1 : reader["VatPrcnt"].ToDecimal(), GTotalSC = reader["GTotalSC"] == null ? -1 : reader["GTotalSC"].ToDecimal(), }); } reader.Close(); } } var invoiceList = list.GroupBy(x => new { x.DocEntry, x.DocNum, x.TaxDate, x.U_ARS, x.U_ART, x.U_ARC, x.CardCode, x.CardName, x.GTSRegNum, x.GTSBilAddr, x.Phone1, x.U_CV_BankName, x.GTSBankAct }) .Select(x => new { DocEntry = x.Key.DocEntry, DocNum = x.Key.DocNum, TaxDate = x.Key.TaxDate, U_ARS = x.Key.U_ARS, U_ART = x.Key.U_ART, U_ARC = x.Key.U_ARC, CardCode = x.Key.CardCode, CardName = x.Key.CardName, GTSRegNum = x.Key.GTSRegNum, GTSBilAddr = x.Key.GTSBilAddr, Phone1 = x.Key.Phone1, U_CV_BankName = x.Key.U_CV_BankName, GTSBankAct = x.Key.GTSBankAct }).ToList(); var invoice = new List <InvoiceModel>(); invoiceList.ForEach(x => { var data = new InvoiceModel() { DocEntry = x.DocEntry, DocNum = x.DocNum, TaxDate = x.TaxDate, U_ARS = x.U_ARS, U_ART = x.U_ART, U_ARC = x.U_ARC, CardCode = x.CardCode, CardName = x.CardName, GTSRegNum = x.GTSRegNum, GTSBilAddr = x.GTSBilAddr, Phone1 = x.Phone1, U_CV_BankName = x.U_CV_BankName, GTSBankAct = x.GTSBankAct, Contact = x.GTSBilAddr + x.Phone1, BankAccount = x.U_CV_BankName + x.GTSBankAct, DetailList = new List <Detail>() }; invoice.Add(data); var temp = list.Where(q => q.DocEntry == x.DocEntry).ToList(); temp.ForEach(q => { data.DetailList.Add(new Detail() { GTotalSC = q.GTotalSC, ItemCode = q.ItemCode, LineNum = q.LineNum, Quantity = q.Quantity, unitMsr = q.unitMsr, VatPrcnt = q.VatPrcnt }); }); }); logger.Info("返回结果行数:" + invoice.Count); result.Code = "Y"; result.Msg = "成功"; result.TotalCount = invoice.Count; result.Body = invoice; return(result); }
private static void CalculateMemberFreight(InvoiceModel invoice, Dictionary <string, decimal> frieghtTaxData) { invoice.InvoicePrice.MemberFreight = frieghtTaxData.AsParallel().Sum(x => x.Value); invoice.InvoicePrice.DisplayMemberFreight = invoice.InvoicePrice.MemberFreight.FormatPrice(); }
//private void CreatePdfInvoice2(InvoiceModel datainv) //{ // using (WordprocessingDocument doc = WordprocessingDocument.Open(@"D:\DocTemplate\INVOICE ISOMEDIK (002).docx", true)) // { // var body = doc.MainDocumentPart.Document.Body; // var paras = body.Elements<Paragraph>(); // foreach (var para in paras) // { // foreach (var run in para.Elements<Run>()) // { // foreach (var text in run.Elements<Text>()) // { // if (text.Text.Contains("text-to-replace")) text.Text = text.Text.Replace("text-to-replace", "replaced-text"); // } // } // } // } //} private void CreatePdfInvoice(InvoiceModel datainv) { string pathTemp = ConfigurationManager.AppSettings["FileInvoice"]; string pathDoc = ConfigurationManager.AppSettings["TemplateInvoice"]; if (!Directory.Exists(pathTemp)) { throw new Exception("Directori " + pathTemp + " tidak ditemukan "); } if (!System.IO.File.Exists(pathDoc)) { throw new Exception("File template invoice tidak ditemukan " + pathDoc); } var matchCase = true; var matchWholeWord = true; var matchWildcards = false; var matchSoundsLike = false; var matchAllWordForms = false; var forward = true; var wrap = 1; var format = false; var replace = 2; // Parameter di MS Word var InvoiceNo = "{NOINVOICE}"; var TglInvoice = "{TGLinvoice}"; var deskripsi = "{deskripsi}"; var qty = "{qty}"; var Total = "{total}"; var grandTotal = "{grandtotal}"; Application app = new word.Application(); app.Visible = false; Document doc = app.Documents.Open(pathDoc); try { app.Selection.Find.Execute(InvoiceNo, matchCase, matchWholeWord, matchWildcards, matchSoundsLike, matchAllWordForms, forward, wrap, format, datainv.InvoiceNo, replace); app.Selection.Find.Execute(TglInvoice, matchCase, matchWholeWord, matchWildcards, matchSoundsLike, matchAllWordForms, forward, wrap, format, (datainv.InvoiceDate ?? DateTime.Now).ToString("dd MMM yyyy"), replace); app.Selection.Find.Execute(deskripsi, matchCase, matchWholeWord, matchWildcards, matchSoundsLike, matchAllWordForms, forward, wrap, format, datainv.Deskripsi, replace); app.Selection.Find.Execute(qty, matchCase, matchWholeWord, matchWildcards, matchSoundsLike, matchAllWordForms, forward, wrap, format, datainv.Qty.ToString("#,##0"), replace); app.Selection.Find.Execute(Total, matchCase, matchWholeWord, matchWildcards, matchSoundsLike, matchAllWordForms, forward, wrap, format, datainv.GrandTotal.ToString("#,##0"), replace); app.Selection.Find.Execute(grandTotal, matchCase, matchWholeWord, matchWildcards, matchSoundsLike, matchAllWordForms, forward, wrap, format, datainv.GrandTotal.ToString("#,##0"), replace); doc.SaveAs2(pathTemp + datainv.Filename, word.WdSaveFormat.wdFormatPDF); } catch (Exception ex) { //ViewBag.pesanJudul = "Error!"; //ViewBag.pesanType = "alert-danger"; //ViewBag.pesanText = ex.Message; throw new Exception(ex.Message); } finally { doc.Close(word.WdSaveOptions.wdDoNotSaveChanges); app.Quit(); } }
private static void CalculateMemberTax(InvoiceModel invoice, Dictionary <string, decimal> productTaxData) { invoice.InvoicePrice.MemberTax = productTaxData.AsParallel().Sum(x => x.Value); invoice.InvoicePrice.DisplayMemberTax = invoice.InvoicePrice.MemberTax.FormatPrice(); }
public async Task <ResponseStructure> TestCheckout(HttpRequest httpRequest, HttpResponse httpResponse, int type = 1, bool RequestedPOS = false) { try { var authorize = Barayand.Common.Services.TokenService.AuthorizeUser(httpRequest); if (authorize < 1) { return(ResponseModel.Error("کاربر وارد نشده است")); } UserModel userModel = await _userrepository.GetById(authorize); if (userModel == null) { return(ResponseModel.Error("کاربر یافت نشد")); } FullPropertyBasketModel BasketModel = new FullPropertyBasketModel(); string cookie; string InvoiceID = null; if (httpRequest.Cookies.TryGetValue("Cart", out cookie)) { if (cookie != null) { var basketInfo = Barayand.Common.Services.CryptoJsService.DecryptStringAES(cookie); BasketModel = JsonConvert.DeserializeObject <FullPropertyBasketModel>(basketInfo); if (BasketModel.CartItems.Count() > 0) { BasketViewModel basketView = await GetBasketItems(httpRequest); InvoiceModel Invoice = new InvoiceModel(); Invoice.I_BoxWrapperId = BasketModel.GiftBoxWrapperId; Invoice.I_CopponDiscount = (BasketModel.Coppon.Count() > 0) ? BasketModel.Coppon.Sum(x => x.CP_Discount) : 0; Invoice.I_CopponId = (BasketModel.Coppon.Count() > 0) ? BasketModel.Coppon.FirstOrDefault().CP_Id : 0; Invoice.I_DeliveryDate = BasketModel.RecipientInfo.DeliveryDate; Invoice.I_PaymentDate = DateTime.Now; Invoice.I_PaymentInfo = "Test payment"; Invoice.I_PaymentType = type; Invoice.I_RecipientInfo = JsonConvert.SerializeObject(BasketModel.RecipientInfo); Invoice.I_RequestedPOS = RequestedPOS; Invoice.I_Status = 2; Invoice.I_TotalProductAmount = basketView.Products.Sum(x => x.Total); Invoice.I_TotalAmount = basketView.Total; Invoice.I_UserId = userModel.U_Id; Invoice.I_Id = UtilesService.RandomDigit(12); var insertInvoiceResult = await _invoicerepository.Insert(Invoice); if (insertInvoiceResult.Status == false) { return(insertInvoiceResult); } int AvailAbleCounts = 0; foreach (var item in BasketModel.CartItems) { OrderModel order = new OrderModel(); if (item.ProductType == 1) { var combine = await _productcombinerepo.GetById(item.ProductCombineId); if (combine != null && combine.X_AvailableCount >= item.Quantity) { AvailAbleCounts++; order.O_ColorId = combine.X_ColorId; order.O_ProductId = combine.X_ProductId; order.O_WarrantyId = combine.X_WarrantyId; order.O_ReciptId = Invoice.I_Id; order.O_Quantity = item.Quantity; order.O_ProductType = 1; order.O_Price = combine.PriceModel.Price; order.O_Discount = combine.PriceModel.HasDiscount ? combine.PriceModel.Discount : 0; order.O_DiscountType = 1; order.O_GiftId = item.GiftProductCombineId; await _orderrepository.Insert(order); } } else { var pmanual = await _productmanualrepo.GetById(item.ProductCombineId); if (pmanual != null) { AvailAbleCounts++; order.O_ProductId = pmanual.M_ProductId; order.O_ReciptId = Invoice.I_Id; order.O_Quantity = item.Quantity; order.O_ProductType = 2; order.O_Price = pmanual.M_Price; await _orderrepository.Insert(order); } } } InvoiceID = Invoice.I_Id; if (AvailAbleCounts < 1) { await _invoicerepository.Delete(InvoiceID); await FreeUpCart(httpRequest, httpResponse); return(ResponseModel.Error("تمامی کالاهای موجود در سبد خرید شما ناموجود میباشند")); } } } } await FreeUpCart(httpRequest, httpResponse); return(ResponseModel.Success("سفارش شما با موفقیت ثبت گردید", data: InvoiceID)); } catch (Exception ex) { return(ResponseModel.ServerInternalError(data: ex)); } }
public InvoiceModel Put(string id, InvoiceModel model) { var retorno = PutAsync<InvoiceModel>(id, model).Result; return retorno; }