public IActionResult VerifySettlement([FromBody] SettlementPostViewModel data) { if (ModelState.IsValid) { IList <Settlement> settlement = _context.Settlement.Where(x => x.SessionId == data.Settlement.SessionId).ToList(); var store = JsonConvert.DeserializeObject <Store>(HttpContext.Session.GetString("Store")); using (var trans = _context.Database.BeginTransaction()) { try { foreach (var item in settlement) { if (item.PaymentMode == "Cash") { item.AdjustmentAmount = data.AdjustmentCashAmount; item.ShortExcessAmount = data.ShortExcessCashAmount; } else if (item.PaymentMode == "Credit") { item.AdjustmentAmount = data.AdjustmentCreditAmount; item.ShortExcessAmount = data.ShortExcessCreditAmount; } else if (item.PaymentMode == "CreditNote") { item.AdjustmentAmount = data.AdjustmentCreditNoteAmount; item.ShortExcessAmount = data.ShortExcessCreditNoteAmount; } else if (item.PaymentMode == "Card") { item.AdjustmentAmount = data.AdjustmentCardAmount; item.ShortExcessAmount = data.ShortExcessCardAmount; } item.VerifiedBy = User.Identity.Name; item.VerifiedDate = DateTime.Now; item.Status = "Verified"; _context.Entry(item).State = EntityState.Modified; } _context.SaveChanges(); trans.Commit(); var settlementData = _context.SettlementViewModel.Where(x => x.SessionId == settlement.FirstOrDefault().SessionId).ToList(); return(Ok(new { SettlementData = settlementData, Store = store })); } catch (Exception ex) { trans.Rollback(); } }; } return(StatusCode(400)); }
public async Task <IActionResult> Create(Denomination denomination) { if (ModelState.IsValid) { if (denomination.Date.ToShortDateString() != System.DateTime.Now.ToShortDateString()) { return(StatusCode(400, "Date not Up-to-Date !!")); } //check if Session present denomination.User_Id = User.Identity.Name; IList <Settlement> settlementData = _context.Settlement.Where(x => x.UserId == denomination.User_Id).ToList(); if (settlementData == null || settlementData.Count == 0) { ModelState.AddModelError(string.Empty, "Sorry, No Transaction Found In Your Name !!"); } else if (!settlementData.Any(x => x.Status == "Open")) { if (settlementData.Any(x => x.Status == "Closed")) { ModelState.AddModelError(string.Empty, "Already Saved, Cannot Save Twice !!"); } else { ModelState.AddModelError(string.Empty, "Sorry, No Transaction Found In Your Name !!"); } } else { denomination.TotalCash = denomination.Total;//CalcTotalCash(denomination); _context.Add(denomination); await _context.SaveChangesAsync(); var newSettlementData = settlementData.Where(x => x.Status == "Open"); foreach (var item in newSettlementData) { item.Status = "Closed"; item.DenominationId = denomination.Id; _context.Entry(item).State = EntityState.Modified; } await _context.SaveChangesAsync(); TempData["StatusMessage"] = "Saved Successfully"; return(RedirectToAction(nameof(Edit), new { id = denomination.Id })); } } ViewData["Terminal_Id"] = new SelectList(_context.Terminal, "Id", "Name", denomination.Terminal_Id); return(View(denomination)); }
public IActionResult UpdatePrintCount(string invoiceNumber) { var printCount = _context.InvoicePrint.FirstOrDefault(x => x.InvoiceNumber == invoiceNumber); if (printCount != null) { printCount.PrintCount += 1; printCount.PrintedBy = User.Identity.Name; printCount.PrintedDate = DateTime.Now; _context.Entry(printCount).State = Microsoft.EntityFrameworkCore.EntityState.Modified; _context.SaveChanges(); } return(Ok()); }
public async Task <IActionResult> Index([FromBody] CreditNote creditNote) { if (ModelState.IsValid) { try { Store store = JsonConvert.DeserializeObject <Store>(HttpContext.Session.GetString("Store"));; creditNote.Id = Guid.NewGuid(); creditNote.Credit_Note_Id = _context.CreditNote.Select(x => x.Credit_Note_Id).DefaultIfEmpty(0).Max() + 1; creditNote.Credit_Note_Number = "CN-" + creditNote.Credit_Note_Id.ToString("0000") + "-" + store.INITIAL + '-' + store.FISCAL_YEAR; creditNote.Trans_Time = DateTime.Now.TimeOfDay; creditNote.Division = "Divisioin"; creditNote.Terminal = HttpContext.Session.GetString("Terminal"); creditNote.Created_Date = DateTime.Now; creditNote.Created_By = User.Identity.Name; creditNote.isRedeem = creditNote.isRedeem; if (creditNote.isRedeem == true) { creditNote.Remarks = "Claimed"; } _context.Add(creditNote); foreach (var item in creditNote.CreditNoteItems) { item.Credit_Note_Id = creditNote.Id; item.Credit_Note_Number = creditNote.Credit_Note_Number; _context.CreditNoteItem.Add(item); } //save to print table InvoicePrint print = new InvoicePrint() { InvoiceNumber = creditNote.Credit_Note_Number, Type = "CreditNote", FirstPrintedDate = DateTime.Now, FirstPrintedBy = User.Identity.Name, PrintCount = 1 }; _context.InvoicePrint.Add(print); await _context.SaveChangesAsync(); //now update invoice remarks also SalesInvoice invoice = _context.SalesInvoice.FirstOrDefault(x => x.Invoice_Number == creditNote.Reference_Number.Trim()); invoice.Remarks = "Return"; _context.Entry(invoice).State = EntityState.Modified; InvoiceMaterializedView invoiceMaterializedViewOld = _context.InvoiceMaterializedView.FirstOrDefault(x => x.BillNo == creditNote.Reference_Number.Trim()); invoiceMaterializedViewOld.IsBillActive = false; _context.Entry(invoiceMaterializedViewOld).State = EntityState.Modified; InvoiceMaterializedView view = new InvoiceMaterializedView() { BillNo = creditNote.Credit_Note_Number, DocumentType = "Credit Memo", FiscalYear = store.FISCAL_YEAR, LocationCode = store.INITIAL, BillDate = creditNote.Trans_Date_Ad.Value, PostingTime = creditNote.Trans_Time.Value, CustomerCode = creditNote.Customer_Id, CustomerName = creditNote.Customer_Name, Vatno = creditNote.Customer_Vat, Amount = creditNote.Total_Gross_Amount.Value, Discount = creditNote.Total_Discount.Value, TaxableAmount = creditNote.TaxableAmount, NonTaxableAmount = creditNote.NonTaxableAmount, TaxAmount = creditNote.Total_Vat == null ? 0 : creditNote.Total_Vat.Value, TotalAmount = creditNote.Total_Net_Amount.Value, IsBillActive = true, IsBillPrinted = false, PrintedTime = DateTime.Now, PrintedBy = "", EnteredBy = creditNote.Created_By, SyncStatus = "Not Started", SyncedDate = DateTime.Now, SyncedTime = DateTime.Now.TimeOfDay, SyncWithIrd = false, IsRealTime = false }; InvoiceMaterializedView invoiceMaterializedView = _context.InvoiceMaterializedView.FirstOrDefault(x => x.BillNo == creditNote.Reference_Number.Trim()); invoiceMaterializedView.IsBillActive = false; _context.Entry(invoiceMaterializedView).State = EntityState.Modified; NavCreditMemo navCreditMemo = new NavCreditMemo() { id = creditNote.Id.ToString(), number = creditNote.Credit_Note_Number, postingno = creditNote.Credit_Note_Number, creditMemoDate = creditNote.Trans_Date_Ad.Value.ToString("yyyy-MM-dd"), customerNumber = creditNote.MemberId, customerName = creditNote.Customer_Name, vatregistrationnumber = creditNote.Customer_Vat, locationcode = store.INITIAL, accountabilitycenter = store.INITIAL, assigneduserid = creditNote.Created_By, externalDocumentNumber = creditNote.Reference_Number, amountrounded = creditNote.IsRoundup, returnremarks = creditNote.Credit_Note }; _context.InvoiceMaterializedView.Add(view); _context.SaveChanges(); //post to ird //background task BackgroundJob.Enqueue(() => SendDataToIRD(creditNote, store)); //Send data to NAV Config config = ConfigJSON.Read(); if (!config.StopCreditNotePosting) { NavPostData navPostData = new NavPostData(_context, _mapper); BackgroundJob.Enqueue(() => navPostData.PostCreditNote(navCreditMemo)); } //for api return TempData["StatusMessage"] = "Credit Note Added Successfully"; return(Ok(new { redirectUrl = "/CreditNote", Message = "Credit Note Added Successfully", InvoiceData = creditNote, StoreData = store })); } catch (Exception ex) { if (ex.Message.Contains("UniqueCreditNoteNumber") || ex.InnerException.Message.Contains("UniqueCreditNoteNumber")) { return(await Index(creditNote)); } } } return(View(creditNote)); }
public IActionResult Billing([FromBody] SalesInvoiceBillingViewModel model) { try { //check if billing is not available if (model == null || model.bill.Count() == 0) { return(NotFound()); } //Check from salesInvoiceTmp table SalesInvoiceTmp salesInvoiceTmp = _context.SalesInvoiceTmp.FirstOrDefault(x => x.Id == model.salesInvoiceId); if (salesInvoiceTmp == null) { return(NotFound()); } using (var trans = _context.Database.BeginTransaction()) { SalesInvoice salesInvoice = new SalesInvoice(); try { //get store info Store store = JsonConvert.DeserializeObject <Store>(HttpContext.Session.GetString("Store")); //convert to sales invoice and save //if (_context.ChangeTracker.HasChanges(.Any(x => x.Id == model.salesInvoiceId)) // salesInvoice = _context.SalesInvoice.FirstOrDefault(x => x.Id == model.salesInvoiceId); //else salesInvoice = _mapper.Map <SalesInvoice>(salesInvoiceTmp); salesInvoice.Id = Guid.NewGuid(); salesInvoice.Total_Bill_Discount = model.billDiscount; salesInvoice.Total_Payable_Amount = model.totalPayable; salesInvoice.Total_Net_Amount_Roundup = model.totalNetAmountRoundUp; salesInvoice.Tender_Amount = model.tenderAmount; salesInvoice.Change_Amount = model.changeAmount; salesInvoice.Invoice_Id = _context.SalesInvoice.Where(x => x.Trans_Type == salesInvoice.Trans_Type).Select(x => x.Invoice_Id).DefaultIfEmpty(0).Max() + 1; salesInvoice.Invoice_Number = SalesInvoiceNumberFormat(store, salesInvoice.Invoice_Id, salesInvoice.Trans_Type); _context.SalesInvoice.Add(salesInvoice); //get invoice items temp convert to sales invoice item and save them IList <SalesInvoiceItemsTmp> itemtmp = _context.SalesInvoiceItemsTmp.Where(x => x.Invoice_Id == salesInvoiceTmp.Id).ToList(); foreach (var item in itemtmp) { item.Invoice = null; SalesInvoiceItems salesItem = _mapper.Map <SalesInvoiceItems>(item); salesItem.Id = 0; salesItem.Invoice_Id = salesInvoice.Id; salesItem.Invoice_Number = salesInvoice.Invoice_Number; _context.SalesInvoiceItems.Add(salesItem); } _context.SaveChanges(); //check session Settlement oldSettlement = _context.Settlement.FirstOrDefault(x => x.UserId == salesInvoice.Created_By && x.Status == "Open"); string sessionId = oldSettlement != null ? oldSettlement.SessionId : Guid.NewGuid().ToString(); string crNumber = salesInvoice.Invoice_Number; //save bill amount information foreach (var item in model.bill) { item.Invoice_Id = salesInvoice.Id; item.Invoice_Number = salesInvoice.Invoice_Number; item.Invoice_Type = salesInvoice.Trans_Type; item.Terminal = HttpContext.Session.GetString("Terminal"); if (item.Trans_Mode == "Cash") { item.Amount = item.Amount - salesInvoice.Change_Amount; } item.IsNavSync = false; _context.SalesInvoiceBill.Add(item); //if credit note amount is used then update credit note table if (item.Trans_Mode == "Credit Note") { CreditNote creditNote = _context.CreditNote.FirstOrDefault(x => x.Credit_Note_Number == item.Account); crNumber = item.Account; if (creditNote != null) { creditNote.Created_By = User.Identity.Name; creditNote.Created_Date = DateTime.Now; creditNote.Remarks = "Claimed"; _context.Entry(creditNote).State = EntityState.Modified; } } //save to settlement table decimal totalAmount = 0; if (item.Trans_Mode == "Cash") { totalAmount = item.Amount; } else { totalAmount = item.Amount; } Settlement settlement = new Settlement() { SessionId = sessionId, TransactionDate = DateTime.Now, PaymentMode = item.Trans_Mode, Amount = item.Amount, Status = "Open", VerifiedBy = "", VerifiedDate = DateTime.Now, TransactionNumber = salesInvoice.Invoice_Number, Remarks = "", TerminalId = Convert.ToInt32(HttpContext.Session.GetString("TerminalId")), UserId = salesInvoice.Created_By }; _context.Settlement.Add(settlement); } //save to print table InvoicePrint print = new InvoicePrint() { InvoiceNumber = salesInvoice.Invoice_Number, Type = salesInvoice.Trans_Type, FirstPrintedDate = DateTime.Now, FirstPrintedBy = User.Identity.Name, PrintCount = 1 }; _context.InvoicePrint.Add(print); _context.SaveChanges(); //if everything seems good, then delete salesInvoiceTmp _context.Remove(salesInvoiceTmp); //total amount excludevat decimal totalRateExcludeVat = 0; foreach (var i in salesInvoice.SalesInvoiceItems) { totalRateExcludeVat += i.RateExcludeVat * i.Quantity.Value; } // salesInvoice.SalesInvoiceItems.Select(x => x.RateExcludeVat).Sum(); //save to invoiceMaterialview InvoiceMaterializedView view = new InvoiceMaterializedView() { BillNo = salesInvoice.Invoice_Number, DocumentType = salesInvoice.Trans_Type + " Invoice", FiscalYear = store.FISCAL_YEAR, LocationCode = store.INITIAL, BillDate = salesInvoice.Trans_Date_Ad.Value, PostingTime = salesInvoice.Trans_Time.Value, CustomerCode = salesInvoice.Customer_Id, CustomerName = salesInvoice.Customer_Name, Vatno = salesInvoice.Customer_Vat, Amount = totalRateExcludeVat, Discount = salesInvoice.TOTAL_DISCOUNT_EXC_VAT, TaxableAmount = salesInvoice.TaxableAmount, NonTaxableAmount = salesInvoice.NonTaxableAmount, TaxAmount = salesInvoice.Total_Vat.Value, TotalAmount = salesInvoice.Total_Net_Amount.Value, IsBillActive = true, IsBillPrinted = true, PrintedBy = User.Identity.Name, PrintedTime = DateTime.Now, EnteredBy = salesInvoice.Created_By, SyncStatus = "Not Started", SyncedDate = DateTime.Now, SyncedTime = DateTime.Now.TimeOfDay, SyncWithIrd = false, IsRealTime = false }; NavSalesInvoice navSalesInvoice = new NavSalesInvoice() { id = salesInvoice.Id.ToString(), number = salesInvoice.Invoice_Number, postingno = salesInvoice.Invoice_Number, shippingno = salesInvoice.Invoice_Number, orderDate = salesInvoice.Trans_Date_Ad.Value.ToString("yyyy-MM-dd"), customerNumber = salesInvoice.MemberId, customerName = salesInvoice.Customer_Name, vatregistrationnumber = salesInvoice.Customer_Vat, locationcode = store.INITIAL, accountabilitycenter = store.INITIAL, assigneduserid = salesInvoice.Created_By, externalDocumentNumber = crNumber, amountrounded = salesInvoice.Total_Net_Amount != salesInvoice.Total_Payable_Amount }; _context.InvoiceMaterializedView.Add(view); _context.SaveChanges(); trans.Commit(); //*********** background task Config config = ConfigJSON.Read(); //Send data to IRD if (!config.StopPostingIRD) { BackgroundJob.Enqueue(() => SendDataToIRD(salesInvoice, store)); } //Send data to NAV if (!config.StopInvoicePosting) { NavPostData navPostData = new NavPostData(_context, _mapper); BackgroundJob.Enqueue(() => navPostData.PostSalesInvoice(navSalesInvoice)); } //TempData["StatusMessage"] = "Bill Payment Successfull !!"; return(Ok(new { StatusMessage = "Bill Payment Successfull !!", InvoiceData = salesInvoice, StoreData = store, BillData = model.bill })); } catch (Exception ex) { trans.Rollback(); if (ex.Message.Contains("UniqueInvoiceNumber") || ex.InnerException.Message.Contains("UniqueInvoiceNumber")) { _context.Entry(salesInvoice).State = EntityState.Detached; return(Billing(model)); } else { return(BadRequest(ex.Message)); } } }; } catch (Exception ex) { return(BadRequest(ex.Message)); } }
public IActionResult CreateMembership([FromBody] Customer customer) { if (ModelState.IsValid) { try { customer.Code = Guid.NewGuid().ToString(); customer.Is_Member = true; customer.Member_Id = _context.Customer.Where(x => x.Is_Member == true && x.Member_Id != null).Select(x => x.Member_Id).DefaultIfEmpty(0).Max() + 1; Store store = JsonConvert.DeserializeObject <Store>(HttpContext.Session.GetString("Store")); customer.Membership_Number = store.INITIAL + "-" + Convert.ToInt32(customer.Member_Id).ToString("000000"); //check number series already Customer isCustomerExist = _context.Customer.FirstOrDefault(x => x.Membership_Number == customer.Membership_Number); if (isCustomerExist != null) { if (isCustomerExist.Member_Id != customer.Member_Id) { isCustomerExist.Member_Id = customer.Member_Id; _context.Entry(isCustomerExist).State = EntityState.Modified; _context.SaveChanges(); } return(CreateMembership(customer)); } customer.Created_By = User.Identity.Name; customer.Registration_Date = DateTime.Now; customer.CustomerDiscGroup = "RSP"; customer.CustomerPriceGroup = "RSP"; customer.MembershipDiscGroup = "CATEGORY D"; _context.Add(customer); _context.SaveChanges(); //update cache IList <CustomerViewModel> customers; if (!_cache.TryGetValue("Customers", out customers)) { // Key not in cache, so get data. customers = _context.Customer .Select(x => new CustomerViewModel { Address = x.Address, Barcode = x.Barcode, Code = x.Code, CustomerDiscGroup = x.CustomerDiscGroup, CustomerPriceGroup = x.CustomerPriceGroup, Is_Member = x.Is_Member, Is_Sale_Refused = x.Is_Sale_Refused, MembershipDiscGroup = x.MembershipDiscGroup, Membership_Number = x.Membership_Number, Membership_Number_Old = x.Membership_Number_Old, Member_Id = x.Member_Id, Mobile1 = x.Mobile1, Name = x.Name, Type = x.Type, Vat = x.Vat }).ToList(); } customers.Add(new CustomerViewModel() { Address = customer.Address, Barcode = customer.Barcode, Code = customer.Code, CustomerDiscGroup = customer.CustomerDiscGroup, CustomerPriceGroup = customer.CustomerPriceGroup, Is_Member = customer.Is_Member, Is_Sale_Refused = customer.Is_Sale_Refused, MembershipDiscGroup = customer.MembershipDiscGroup, Membership_Number = customer.Membership_Number, Membership_Number_Old = customer.Membership_Number_Old, Member_Id = customer.Member_Id, Mobile1 = customer.Mobile1, Name = customer.Name, Type = customer.Type, Vat = customer.Vat }); _cache.Set("Customer", customers); NavPostData navPost = new NavPostData(_context, _mapper); BackgroundJob.Enqueue(() => navPost.PostCustomer()); return(Ok(new { StatusMessage = "Membership Created Successfully !!", Membership = customer })); } catch (Exception ex) { if (ex.Message.Contains("'UniqueMobileNumber") || ex.InnerException.Message.Contains("UniqueMobileNumber")) { return(StatusCode(409, new { StatusMessage = "Mobile Number Already Register !!" })); } else if (ex.Message.Contains("idx_unique_member_id") || ex.InnerException.Message.Contains("idx_unique_member_id") && ex.Message.Contains("duplicate") || ex.InnerException.Message.Contains("duplicate")) { return(CreateMembership(customer)); } else { return(StatusCode(500, new { StatusMessage = ex.Message })); } //TempData["StatusMessage"] = "Customer Created Successfully !!"; } } return(StatusCode(400, new { StatusMessage = "Not Valid" })); }
public bool PostSalesInvoice(NavSalesInvoice invoice) { Config config = ConfigJSON.Read(); var currentTime = DateTime.Now.TimeOfDay; if ((config.OfficeHourStart != null && currentTime.CompareTo(Convert.ToDateTime(config.OfficeHourStart).TimeOfDay) == 1) && (config.OfficeHourEnd != null && currentTime.CompareTo(Convert.ToDateTime(config.OfficeHourEnd).TimeOfDay) == -1)) { return(true); } if (config.StopInvoicePosting == false) { NavIntegrationService services = _context.NavIntegrationService.FirstOrDefault(x => x.IntegrationType == "SalesInvoicePost"); string url = config.NavApiBaseUrl + "/" + config.NavPath + $"/companies({config.NavCompanyId})/{services.ServiceName}"; var client = NAV.NAVClient(url, config); var request = new RestRequest(Method.POST); request.AddHeader("Content-Type", "application/json"); request.RequestFormat = DataFormat.Json; var temp = JsonConvert.SerializeObject(invoice); request.AddJsonBody(temp); IRestResponse <SyncModel <NavSalesInvoice> > response = client.Execute <SyncModel <NavSalesInvoice> >(request); if (response.StatusCode == HttpStatusCode.Created || response.StatusCode == HttpStatusCode.OK || response.Content.Contains("already exists")) { //update sync status SalesInvoice sInvoice = _context.SalesInvoice.FirstOrDefault(x => x.Invoice_Number == invoice.number); sInvoice.IsNavSync = true; sInvoice.NavSyncDate = DateTime.Now; _context.Entry(sInvoice).State = Microsoft.EntityFrameworkCore.EntityState.Modified; _context.SaveChanges(); PostSalesInvoicePaymentMode(invoice.number, invoice.id); PostSalesInvoiceItem(invoice.number, invoice.id, sInvoice.Trans_Type); return(true); } else { string errorMessage = "Error Invoice:: Invoice Number= " + invoice.number + " Message= " + response.Content + " " + DateTime.Now.ToString() + Environment.NewLine; WriteToFile(Path.GetFullPath("logs/"), "NAVSyncLog.log", errorMessage); // _logger.LogError("Error Invoice:: Invoice Number= " + invoice.number + " Message= " + response.Content + " " + DateTime.Now.ToString()); //update values //SalesInvoice sInvoice = _context.SalesInvoice.FirstOrDefault(x => x.Invoice_Number == invoice.number); //if (sInvoice.SyncErrorCount < 3) //{ // sInvoice.SyncErrorCount = sInvoice.SyncErrorCount + 1; // _context.Entry(sInvoice).State = Microsoft.EntityFrameworkCore.EntityState.Modified; // _context.SaveChanges(); // //run scheduler after 1 minute // // BackgroundJob.Schedule(() => PostSalesInvoice(invoice), TimeSpan.FromMinutes(sInvoice.SyncErrorCount * 5)); //} return(false); } } else { return(true); } }