Esempio n. 1
0
        public IActionResult RoleWisePermission([FromBody] RoleWisePermissionCommon permission)
        {
            if (!ModelState.IsValid)
            {
                return(StatusCode(400));
            }
            try
            {
                //first delete
                RoleWisePermission oldPermission = _context.RoleWisePermission.FirstOrDefault(x => x.RoleId == permission.roleWiseUserPermission.RoleId);
                if (oldPermission != null)
                {
                    _context.RoleWisePermission.Remove(oldPermission);
                }
                List <RoleWiseMenuPermission> oldMenuPermission = _context.RoleWiseMenuPermission.Where(x => x.RoleId == permission.roleWiseMenuPermissions.FirstOrDefault().RoleId).ToList();
                if (oldMenuPermission != null)
                {
                    _context.RoleWiseMenuPermission.RemoveRange(oldMenuPermission);
                }

                //then add
                _context.RoleWisePermission.Add(permission.roleWiseUserPermission);
                _context.RoleWiseMenuPermission.AddRange(permission.roleWiseMenuPermissions);

                //finally save all changes
                _context.SaveChanges();
                TempData["StatusMessage"] = "Saved Successfully !!";
                return(Ok(permission.roleWiseUserPermission.RoleId));
            }
            catch
            {
                ModelState.AddModelError("Error", "Error occour, try again later !!");
                return(StatusCode(500));
            }
        }
        public IActionResult TerminalMapping([FromBody] TerminalMapping terminalMapping)
        {
            if (ModelState.IsValid)
            {
                //first remove if mapped to terminal
                IEnumerable <TerminalMapping> oldMapping = _context.TerminalMapping.Where(x => x.IPAddress == terminalMapping.IPAddress);
                _context.TerminalMapping.RemoveRange(oldMapping);
                _context.SaveChanges();

                terminalMapping.AssignedBy   = User.Identity.Name;;
                terminalMapping.AssignedDate = DateTime.Now;
                _context.TerminalMapping.Add(terminalMapping);
                _context.SaveChanges();
                return(Ok());
            }
            return(StatusCode(400));
        }
Esempio n. 3
0
        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 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());
        }
Esempio n. 5
0
        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));
        }
Esempio n. 6
0
        public async Task <IActionResult> Index([FromBody] SalesInvoiceAndCustomerViewModel model)
        {
            SalesInvoiceTmp salesInvoiceTmp = model.SalesInvoice;
            Customer        customer        = model.Customer;

            if (ModelState.IsValid)
            {
                if (model.SalesInvoice.Trans_Date_Ad.Value.ToShortDateString() != DateTime.Now.ToShortDateString())
                {
                    return(StatusCode(400, "Date is not Up-to-Date !!"));
                }
                try
                {
                    //if that salesinvoice already exist, than track first
                    SalesInvoiceTmp oldData = new SalesInvoiceTmp();
                    bool            isExistOldSalesInvoice = false;
                    if (salesInvoiceTmp.Id != null)
                    {
                        oldData = await _context.SalesInvoiceTmp.FirstOrDefaultAsync(x => x.Id == salesInvoiceTmp.Id);

                        if (oldData != null)
                        {
                            isExistOldSalesInvoice = true;
                        }
                    }

                    //add membership
                    if (!string.IsNullOrEmpty(customer.Name) && !string.IsNullOrEmpty(customer.Mobile1) && customer.Is_Member == true)
                    {
                        Customer member = AddCustomer(customer);
                        //_context.SaveChanges();
                        salesInvoiceTmp.Customer_Id = member.Code;
                        salesInvoiceTmp.MemberId    = member.Membership_Number;
                    }


                    //now processed to new save invoice
                    salesInvoiceTmp.Id           = Guid.NewGuid();
                    salesInvoiceTmp.Trans_Time   = DateTime.Now.TimeOfDay;
                    salesInvoiceTmp.Division     = "Divisioin";
                    salesInvoiceTmp.Terminal     = HttpContext.Session.GetString("Terminal");
                    salesInvoiceTmp.Created_Date = DateTime.Now;
                    salesInvoiceTmp.Created_By   = User.Identity.Name;



                    _context.Add(salesInvoiceTmp);

                    foreach (var item in salesInvoiceTmp.SalesInvoiceItems)
                    {
                        item.Invoice_Id     = salesInvoiceTmp.Id;
                        item.Invoice_Number = salesInvoiceTmp.Invoice_Number;
                        _context.SalesInvoiceItemsTmp.Add(item);
                    }



                    await _context.SaveChangesAsync();

                    //if everything goes right then delete old sales invoice in background
                    if (isExistOldSalesInvoice)
                    {
                        _context.SalesInvoiceTmp.Remove(oldData);
                        _context.SaveChanges();
                    }



                    //for serverside return
                    //if (salesInvoiceTmp.Trans_Type == "Hold")
                    //    return RedirectToAction("Index");
                    //else
                    //    return RedirectToAction("Billing", new { id = salesInvoiceTmp.Id });
                    //for api return
                    if (salesInvoiceTmp.Trans_Type == "Save")
                    {
                        return(Ok(new { redirectUrl = "" }));
                    }
                    if (salesInvoiceTmp.Trans_Type == "Hold" || salesInvoiceTmp.Trans_Type == "Save")
                    {
                        return(Ok(new { redirectUrl = "/SalesInvoice/Landing" }));
                    }
                    else if (salesInvoiceTmp.Trans_Type == "Tax")
                    {
                        return(Ok(new { RedirectUrl = "/SalesInvoice/Billing/" + salesInvoiceTmp.Id + "?M=" + salesInvoiceTmp.MemberId + "&Mode=tax" }));
                    }
                    else
                    {
                        return(Ok(new { RedirectUrl = "/SalesInvoice/Billing/" + salesInvoiceTmp.Id + "?M=" + salesInvoiceTmp.MemberId }));
                    }
                }
                catch (Exception ex)
                {
                    return(StatusCode(500, ex.InnerException));
                }
            }
            return(View(salesInvoiceTmp));
        }
Esempio n. 7
0
        public void UpdateCacheItemViewModel()
        {
            bool IsItemCacheInProcess = false;

            _cache.TryGetValue("IsItemCacheInProcess", out IsItemCacheInProcess);

            if (!IsItemCacheInProcess)
            {
                _cache.Set("IsItemCacheInProcess", true);
                //update cache
                Config config = ConfigJSON.Read();
                //split data to 1lakh and save to cache
                int      count = 1000, skip = 0, errorCount = 0;
                DateTime startDate = DateTime.Now;
                //_context.ChangeTracker.AutoDetectChangesEnabled = false;
                for (; ;)
                {
                    try
                    {
                        IList <ItemViewModel> itemsTotal = new List <ItemViewModel>();
                        _cache.TryGetValue("ItemViewModel", out itemsTotal);
                        if (itemsTotal == null)
                        {
                            _cache.Set("IsItemCacheInProcess", false);
                            break;
                        }

                        _context.Database.SetCommandTimeout(TimeSpan.FromHours(1));
                        var listOfItemsChanged    = _context.ItemUpdateTrigger.Skip(skip).Take(count).ToList();
                        var listOfItemsCodeToLoad = listOfItemsChanged.Where(x => x.ACTIONS != "Delete")
                                                    .Select(x => x.ITEMCODE).Distinct().ToList();

                        var listOfItemsChangedCode = listOfItemsChanged.Select(x => x.ITEMCODE).Distinct().ToList();
                        foreach (var i in listOfItemsChangedCode)
                        {
                            var listOfItemsToDelete = itemsTotal.Where(x => x.Code == i).ToList();
                            foreach (var j in listOfItemsToDelete)
                            {
                                itemsTotal.Remove(j);
                            }
                        }

                        string listOfItemsCodeString    = string.Join(",", listOfItemsCodeToLoad);
                        IList <ItemViewModel> itemsTemp = _context.ItemViewModel.FromSql("SPItemViewModel {0}", listOfItemsCodeString).ToList();
                        if (itemsTemp.Count() > 0)
                        {
                            itemsTotal = itemsTotal.Concat(itemsTemp).ToList();
                            _cache.Set("ItemViewModel", itemsTotal);

                            //now remove trigger from database
                            _context.RemoveRange(listOfItemsChanged);
                            _context.SaveChanges();

                            double totalTimeTake = (DateTime.Now - startDate).TotalMinutes;
                            config.Environment = "Total Time take " + totalTimeTake + " Mins";
                            ConfigJSON.Write(config);
                            _cache.Set("IsItemCacheInProcess", false);
                            break;
                        }
                        else
                        {
                            _cache.Set("IsItemCacheInProcess", false);
                            break;
                        }
                    }
                    catch (Exception ex)
                    {
                        if (errorCount > 5)
                        {
                            _cache.Set("IsItemCacheInProcess", false);
                            break;
                        }
                        errorCount += 1;
                    }
                }
            }
        }
Esempio n. 8
0
        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);
            }
        }