コード例 #1
0
        public integrationservice_PortClient Integrationservice_PortClientService()
        {
            BasicHttpBinding basicHttpBinding = new BasicHttpBinding();

            basicHttpBinding.Security.Mode = BasicHttpSecurityMode.TransportCredentialOnly;
            basicHttpBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Ntlm;
            basicHttpBinding.MaxReceivedMessageSize = int.MaxValue;

            Config config = ConfigJSON.Read();

            NetworkCredential credential = new NetworkCredential
            {
                UserName = config.Default_Config.Username,
                Password = config.Default_Config.Password,
                Domain   = config.Integration_Setup.Domain
            };

            EndpointAddress endpoint = new EndpointAddress(
                config.URL + config.Default_Config.Integration_Services.Where(x => x.Integration_Type == "Integration_Service").FirstOrDefault().Service_Name);

            var client = new integrationservice_PortClient(basicHttpBinding, endpoint);

            client.ClientCredentials.Windows.ClientCredential          = credential;
            client.ClientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;

            return(client);
        }
コード例 #2
0
        public List <companies> GetCompaniesList()
        {
            List <companies> companiesCardList = new List <companies>();

            try
            {
                Config mainConfig = ConfigJSON.Read();
                config.Default_Config.Username     = mainConfig.Default_Config.Username;
                config.Default_Config.Password     = mainConfig.Default_Config.Password;
                config.Default_Config.Type         = mainConfig.Default_Config.Type;
                config.Default_Config.Company_Name = mainConfig.Default_Config.Company_Name;

                companies_Filter[] filters = new companies_Filter[0];
                companiesCardList = Companies_PortClientService()
                                    .ReadMultipleAsync(filters, "", 0)
                                    .GetAwaiter()
                                    .GetResult()
                                    .ReadMultiple_Result1
                                    .ToList();
            }
            catch (Exception ex)
            {
                TempData["Notify"] = JsonConvert.SerializeObject(new Notify {
                    title = "Exception Error", text = ex.Message, type = "error"
                });
            }
            return(companiesCardList);
        }
コード例 #3
0
        public IActionResult Submit()
        {
            Config config = ConfigJSON.Read();

            ViewBag.IsForRemit = config.Default_Config.IsForRemit;
            return(View());
        }
コード例 #4
0
        public bool DeleteSalesOrder()
        {
            Config config = ConfigJSON.Read();
            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.GET);

            request.AddHeader("Content-Type", "application/json");

            IRestResponse <SyncModel <NavSalesInvoice> > response = client.Execute <SyncModel <NavSalesInvoice> >(request);


            if (response.StatusCode == HttpStatusCode.OK)
            {
                foreach (var sOrder in response.Data.value)
                {
                    //delete first if already exist
                    string urlDelete     = url + "(" + sOrder.id + ")";
                    var    clientDelete  = NAV.NAVClient(urlDelete, config);
                    var    requestDelete = new RestRequest(Method.DELETE);
                    requestDelete.AddHeader("Content-Type", "application/json");
                    IRestResponse responseDelete = clientDelete.Execute(requestDelete);
                }
                return(true);
            }
            else
            {
                return(false);
            }
        }
コード例 #5
0
        public IActionResult GetClientComputerName(string ip)
        {
            try
            {
                Config config  = ConfigJSON.Read();
                string url     = "http://" + ip + ":" + config.ClientPort + "/POSClient/GetComputerName";
                var    client  = new RestSharp.RestClient(url);
                var    request = new RestSharp.RestRequest(RestSharp.Method.GET);

                request.AddHeader("Access-Control-Allow-Origin", "*");

                RestSharp.IRestResponse response = client.Execute(request);
                string pcName     = response.Content.Replace("\"", "");
                int    terminalId = 0;
                //check if terminal is assigned
                TerminalMapping terminalMapping = _context.TerminalMapping.FirstOrDefault(x => x.PCName == pcName);
                Terminal        terminal        = new Terminal();
                if (terminalMapping != null)
                {
                    terminal = _context.Terminal.FirstOrDefault(x => x.Id == terminalMapping.TerminalId);
                }

                return(Ok(new { pcName = pcName, terminalId = terminalMapping.TerminalId.ToString(), terminalName = terminal?.Name }));
            }
            catch (Exception ex)
            {
                return(StatusCode(500));
            }
        }
コード例 #6
0
        public IActionResult SchedulerSetup()
        {
            ViewData["Scheduler"] = ConfigJSON.Read();
            IList <CustomerViewModel> customer;

            _cache.TryGetValue("Customers", out customer);
            if (customer != null)
            {
                ViewData["IsCustomerCache"]    = true;
                ViewData["CustomerCacheCount"] = customer.Count();
            }
            else
            {
                ViewData["IsCustomerCache"] = false;
            }

            IList <ItemViewModel> item;

            _cache.TryGetValue("ItemViewModel", out item);
            if (item != null)
            {
                ViewData["IsItemCache"]    = true;
                ViewData["ItemCacheCount"] = item.Count();
            }
            else
            {
                ViewData["IsItemCache"] = false;
            }


            return(View());
        }
コード例 #7
0
        public IActionResult SchedulerSetup([FromBody] SchedulerDuration data)
        {
            Config config = ConfigJSON.Read();

            config.SchedulerDuration = data;
            ConfigJSON.Write(config);
            return(Ok());
        }
コード例 #8
0
        public IActionResult BrowserClose()
        {
            Config config = ConfigJSON.Read();

            config.LoggedInUsers.Remove(User.Identity.Name);
            ConfigJSON.Write(config);
            return(Ok());
        }
コード例 #9
0
        public IActionResult APISetup([FromBody] Config data)
        {
            Config config = ConfigJSON.Read();

            data.SchedulerDuration = config.SchedulerDuration;
            data.ClientPort        = config.ClientPort;
            data.Environment       = config.Environment;
            ConfigJSON.Write(data);
            return(Ok());
        }
コード例 #10
0
 public IActionResult Index([FromBody] Setting setting)
 {
     if (ModelState.IsValid)
     {
         Config config = ConfigJSON.Read();
         config.Environment  = setting.Environment;
         config.NavCompanyId = setting.CompanyId;
         ConfigJSON.Write(config);
     }
     return(RedirectToAction("Index"));
 }
コード例 #11
0
        public void PostUnSyncInvoie(Store store)
        {
            Config config        = ConfigJSON.Read();
            var    unSyncInvoice = _context.SalesInvoice.Where(x => x.IsNavPosted == false);
            //update isnavsync to false then restart scheduling job
            bool flag = UpdateIsNavSyncStatus(unSyncInvoice);

            if (flag == false)
            {
                return;
            }

            PostSalesInvoice(store);
        }
コード例 #12
0
        public void setContext()
        {
            Config config = ConfigJSON.Read();

            if (!string.IsNullOrEmpty(config.Environment))
            {
                var con = Configuration.GetConnectionString(config.Environment + "Connection");
                if (con != _context.Database.GetDbConnection().ConnectionString)
                {
                    var options = new DbContextOptionsBuilder <EntityCore>();
                    options.UseSqlServer(con);
                    _context = new EntityCore(options.Options);
                }
            }
        }
コード例 #13
0
        public async Task <IActionResult> LogOff()
        {
            Config config = ConfigJSON.Read();

            config.LoggedInUsers.Remove(User.Identity.Name);
            ConfigJSON.Write(config);
            await _signInManager.SignOutAsync();

            // _logger.LogInformation(4, "User logged out.");
            Response.Cookies.Append(User.Identity.Name, "", new CookieOptions()
            {
                Expires = DateTime.Now.AddDays(-1)
            });

            return(RedirectToAction("Login", "Account"));
        }
コード例 #14
0
        public IActionResult NAVTestConnection()
        {
            Config  config = ConfigJSON.Read();
            NavSync sync   = new NavSync(_context, _mapper, _userManager, _roleManager, _cache, Configuration);
            var     result = sync.TestNavConnection();

            if (result is string && result != "Success")
            {
                return(StatusCode(500, result));
            }
            if (result.Count() > 0)
            {
                return(Ok(result));
            }
            else
            {
                return(StatusCode(500, result));
            }
        }
コード例 #15
0
        public IActionResult UpdateIntegrationSetup()
        {
            try
            {
                integrationsetup_Filter[] filter = new integrationsetup_Filter[0];
                integrationsetup          result = Integrationsetup_PortClientService()
                                                   .ReadMultipleAsync(filter, "", 0)
                                                   .GetAwaiter()
                                                   .GetResult()
                                                   .ReadMultiple_Result1
                                                   .FirstOrDefault();

                Config config = ConfigJSON.Read();
                config.Integration_Setup = new Integration_Setup
                {
                    Base_URL         = result.Base_URL.Remove(result.Base_URL.Length - 1) + ':' + result.Port,
                    Service_Instance = result.Service_Instance,
                    Domain           = result.Domain.Remove(result.Domain.Length - 1),
                    Integration_Name = "WS"
                };

                config.URL = config.Integration_Setup.Base_URL
                             + '/'
                             + config.Integration_Setup.Service_Instance
                             + '/'
                             + config.Integration_Setup.Integration_Name
                             + '/'
                             + config.Default_Config.Company_Name
                             + '/'
                             + config.Default_Config.Type
                             + '/';

                ConfigJSON.Write(config);
                return(StatusCode(Convert.ToInt32(HttpStatusCode.OK), result));
            }
            catch (Exception ex)
            {
                return(StatusCode(Convert.ToInt32(HttpStatusCode.InternalServerError), ex.Message));
            }
        }
コード例 #16
0
        public IActionResult UpdateIntegrationServices()
        {
            try
            {
                integrationservice_Filter[] filter = new integrationservice_Filter[0];
                var oldResult = Integrationservice_PortClientService()
                                .ReadMultipleAsync(filter, "", 0)
                                .GetAwaiter()
                                .GetResult();

                var newResult = oldResult.ReadMultiple_Result1;
                var result    = newResult.ToList();

                Config config = ConfigJSON.Read();

                List <Integration_Service> integration_Services = new List <Integration_Service>();
                foreach (var item in result)
                {
                    integration_Services.Add(
                        new Integration_Service
                    {
                        Integration_Type = item.Integration_Type.ToString(),
                        Service_Name     = item.Service_Name,
                        Type             = item.Type.ToString(),
                        Company_Name     = item.Company_Name
                    });
                }

                config.Integration_Services = integration_Services.ToArray();
                ConfigJSON.Write(config);

                return(StatusCode(Convert.ToInt32(HttpStatusCode.OK), result));
            }
            catch (Exception ex)
            {
                return(StatusCode(Convert.ToInt32(HttpStatusCode.InternalServerError), ex.Message));
            }
        }
コード例 #17
0
        public IActionResult UpdateDefaultSetup(ConfigSetup obj)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    Config config = ConfigJSON.Read();

                    config.Default_Config.Username            = obj.Username;
                    config.Default_Config.Password            = obj.Password;
                    config.Default_Config.Company_Name        = obj.CompanyName;
                    config.Default_Config.Type                = obj.Type;
                    config.Integration_Setup.Base_URL         = obj.BaseURL;
                    config.Integration_Setup.Service_Instance = obj.ServiceInstance;
                    config.Integration_Setup.Domain           = obj.Domain;

                    config.URL = obj.BaseURL
                                 + '/'
                                 + obj.ServiceInstance
                                 + '/'
                                 + config.Integration_Setup.Integration_Name
                                 + '/'
                                 + obj.CompanyName
                                 + '/'
                                 + obj.Type
                                 + '/';

                    ConfigJSON.Write(config);
                    return(StatusCode(Convert.ToInt32(HttpStatusCode.OK), config));
                }
                return(StatusCode(Convert.ToInt32(HttpStatusCode.BadRequest), ModelState));
            }
            catch (Exception ex)
            {
                return(StatusCode(Convert.ToInt32(HttpStatusCode.InternalServerError), ex.Message));
            }
        }
コード例 #18
0
        public bool PostBill(BillViewModel model)
        {
            try
            {
                //Thread.Sleep(100000);
                Config config = ConfigJSON.Read();

                var client  = new RestClient(config.IRDBaseUrl);
                var request = new RestRequest(config.IRDBillUrl, Method.POST);

                request.AddHeader("Content-Type", "application/json");

                //post data
                //authentication
                model.username        = config.IRDUserName;
                model.password        = config.IRDPassword;
                request.RequestFormat = DataFormat.Json;
                var jsonModel = JsonConvert.SerializeObject(model);
                request.AddJsonBody(model);

                IRestResponse response = client.Execute(request);

                if (response.StatusCode == HttpStatusCode.OK)
                {
                    return(true);
                }
                else
                {
                    return(false);
                }
            }
            catch (Exception ex)
            {
                return(false);
            }
        }
        public IActionResult RejectRequest(string travelOrderNo)
        {
            PostedTravelOrderViewModel vmObj = new PostedTravelOrderViewModel();

            try
            {
                postedtravelordercard          obj    = new postedtravelordercard();
                postedtravelordercard_Filter[] filter =
                {
                    new postedtravelordercard_Filter
                    {
                        Field    = postedtravelordercard_Fields.Travel_Order_No,
                        Criteria = travelOrderNo
                    }
                };

                obj = Postedtravelordercard_PortClientService()
                      .ReadMultipleAsync(filter, "", 1)
                      .GetAwaiter()
                      .GetResult()
                      .ReadMultiple_Result1
                      .FirstOrDefault();

                vmObj = _mapper.Map <PostedTravelOrderViewModel>(obj);
            }
            catch (Exception ex)
            {
                TempData["Notify"] = JsonConvert.SerializeObject(new Notify {
                    title = "Exception Error", text = ex.Message, type = "error"
                });
            }
            Config config = ConfigJSON.Read();

            ViewBag.IsForRemit = config.Default_Config.IsForRemit;
            return(View(vmObj));
        }
コード例 #20
0
        public void UpdateCacheItemViewModel()
        {
            _cache.Set("IsItemCacheInProcess", true);
            //update cache
            Config config = ConfigJSON.Read();
            //split data to 1lakh and save to cache
            int      count = 100000, skip = 0, errorCount = 0;
            DateTime startDate = DateTime.Now;

            //_context.ChangeTracker.AutoDetectChangesEnabled = false;
            for (; ;)
            {
                try
                {
                    IList <ItemViewModel> itemsTotal = new List <ItemViewModel>();
                    _context.Database.SetCommandTimeout(TimeSpan.FromHours(1));
                    //IList<ItemViewModel> itemsTemp = _context.ItemViewModel.FromSql("SPItemViewModel @p0, @p1", count, skip).ToList();
                    IList <ItemViewModel> itemsTemp = _context.ItemViewModel.Skip(skip).Take(count).ToList();
                    if (itemsTemp.Count() > 0)
                    {
                        _cache.TryGetValue("ItemViewModel", out itemsTotal);
                        if (itemsTotal == null)
                        {
                            itemsTotal = new List <ItemViewModel>();
                        }
                        itemsTotal = itemsTotal.Concat(itemsTemp).DistinctBy(x => new {
                            x.Bar_Code, x.Code, x.Discount, x.DiscountEndDate, x.DiscountEndTime, x.DiscountItemType, x.DiscountLocation, x.DiscountMinimumQuantity,
                            x.DiscountSalesGroupCode, x.DiscountStartDate, x.DiscountStartTime, x.DiscountType, x.Name, x.Rate, x.RateEndDate, x.RateMinimumQuantity,
                            x.RateStartDate, x.SalesCode, x.SalesType
                        }).ToList();
                        _cache.Set("ItemViewModel", itemsTotal);
                    }
                    else
                    {
                        double totalTimeTake = (DateTime.Now - startDate).TotalMinutes;
                        config.Environment = "Total Time take " + totalTimeTake + " Mins";
                        ConfigJSON.Write(config);
                        _cache.Set("IsItemCacheInProcess", false);
                        break;
                    }
                    config.Environment = itemsTotal.Count() + " item cached";
                    // itemsTotal = itemsTotal.Concat(itemsTemp).ToList();
                    skip = skip + count;
                    // config.Environment = itemsTotal.Count() + " item cached";
                    ConfigJSON.Write(config);
                }
                catch (Exception ex)
                {
                    if (ex.Message == "Invalid object name 'ItemViewModel'.")
                    {
                        _cache.Set("IsItemCacheInProcess", true);
                        break;
                    }
                    if (errorCount > 5)
                    {
                        break;
                    }
                    errorCount += 1;
                }
            }
        }
コード例 #21
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));
        }
コード例 #22
0
        public bool PostSalesInvoicePaymentMode(string invoiceNumber, string invoiceId)
        {
            Config config = ConfigJSON.Read();
            NavIntegrationService services = _context.NavIntegrationService.FirstOrDefault(x => x.IntegrationType == "SalesInvoicePost");
            NavIntegrationService serviceforSalesInvoiceItem = _context.NavIntegrationService.FirstOrDefault(x => x.IntegrationType == "SalesPaymentModes");
            string url = config.NavApiBaseUrl + "/" + config.NavPath + $"/companies({config.NavCompanyId})/{services.ServiceName}";

            var invoiceBill = _context.SalesInvoiceBill.Where(x => x.Invoice_Number == invoiceNumber);
            //var itemList = _context.SalesInvoiceItems.Where(x=> all)
            int lineNo = 0;

            foreach (var i in invoiceBill)
            {
                //if credit then no need to call api
                if (i.Trans_Mode == "Credit")
                {
                    return(false);
                }
                lineNo += 1;
                NavSalesPaymentMode mode = new NavSalesPaymentMode()
                {
                    lineno       = lineNo * 10000,
                    amount       = i.Amount,
                    paymenttype  = i.Trans_Mode,// == "CreditNote" ? "" : i.Trans_Mode, //for creditNote payment type should be blank
                    locationcode = config.Location,
                    documentno   = i.Invoice_Number
                };
                var newUrl = url + $"({invoiceId})/{serviceforSalesInvoiceItem.ServiceName}";

                var client  = NAV.NAVClient(newUrl, config);
                var request = new RestRequest(Method.POST);

                request.AddHeader("Content-Type", "application/json");


                request.RequestFormat = DataFormat.Json;
                var temp = JsonConvert.SerializeObject(mode);
                request.AddJsonBody(JsonConvert.SerializeObject(mode));

                IRestResponse response = client.Execute(request);

                if (response.StatusCode == HttpStatusCode.Created || response.Content.Contains("already exists"))
                {
                    //update sync status
                    i.IsNavSync             = true;
                    i.NavSyncDate           = DateTime.Now;
                    _context.Entry(i).State = Microsoft.EntityFrameworkCore.EntityState.Modified;
                    //_context.SaveChanges();
                }
                else
                {
                    string errorMessage = "Error Invoice Bill, Invoice= " + i.Invoice_Number.ToString() + " Message= " + response.Content + "  " + DateTime.Now.ToString() + Environment.NewLine;
                    WriteToFile(Path.GetFullPath("logs/"), "NAVSyncLog.log", errorMessage);
                    //_logger.LogError("Error Invoice Bill, Invoice= " + i.Invoice_Number.ToString() + " Message= " + response.Content + "  " + DateTime.Now.ToString());
                }
            }
            _context.SaveChanges();


            return(true);
        }
コード例 #23
0
        public bool PostCreditNoteItem(string invoiceNumber)
        {
            Config config = ConfigJSON.Read();
            NavIntegrationService services = _context.NavIntegrationService.FirstOrDefault(x => x.IntegrationType == "CreditNotePost");
            NavIntegrationService serviceforSalesInvoiceItem = _context.NavIntegrationService.FirstOrDefault(x => x.IntegrationType == "CreditNotePostItem");
            string url = config.NavApiBaseUrl + "/" + config.NavPath + $"/companies({config.NavCompanyId})/{services.ServiceName}";


            var items = _context.CreditNoteItem.Where(x => x.Credit_Note_Number == invoiceNumber);

            foreach (var item in items)
            {
                NavCreditItems navSalesItem = new NavCreditItems()
                {
                    // itemId = item.it,
                    itemId = item.ItemId,
                    //itemno = item.ItemCode,
                    unitPrice       = item.RateExcludeVat,
                    quantity        = item.Quantity.Value,
                    discountPercent = item.DiscountPercent
                };


                var newUrl = url + $"({items.FirstOrDefault().Credit_Note_Id.ToString()})/{serviceforSalesInvoiceItem.ServiceName}";

                var client  = NAV.NAVClient(newUrl, config);
                var request = new RestRequest(Method.POST);

                request.AddHeader("Content-Type", "application/json");


                request.RequestFormat = DataFormat.Json;
                var temp = JsonConvert.SerializeObject(navSalesItem);
                request.AddJsonBody(JsonConvert.SerializeObject(navSalesItem));

                IRestResponse response = client.Execute(request);

                if (response.StatusCode == HttpStatusCode.Created || response.Content.Contains("already exists"))
                {
                    //update sync status
                    item.IsNavSync             = true;
                    item.NavSyncDate           = DateTime.Now;
                    _context.Entry(item).State = Microsoft.EntityFrameworkCore.EntityState.Modified;
                    _context.SaveChanges();
                }
                else
                {
                    string errorMessage = "Error Credit Note Item, Credit Note= " + items.FirstOrDefault().Credit_Note_Number.ToString() + " Message= " + response.Content + "  " + DateTime.Now.ToString() + Environment.NewLine;
                    WriteToFile(Path.GetFullPath("logs/"), "NAVSyncLog.log", errorMessage);
                    //_logger.LogError("Error Credit Note Item, Credit Note= " + items.FirstOrDefault().Credit_Note_Number.ToString() + " Message= " + response.Content + "  " + DateTime.Now.ToString());
                }
            }
            if (items.Where(x => x.IsNavSync == false).Count() == 0)
            {
                PostCreditInvoiceCompletedSignalToNav(config, items.FirstOrDefault().Credit_Note_Id.Value, items.FirstOrDefault().Credit_Note_Number);
            }



            return(true);
        }
コード例 #24
0
        public async Task <IActionResult> Login(LoginViewModel model, string returnUrl = null)
        {
            ViewData["ReturnUrl"] = null;
            //_logger.LogInformation("access login page");
            if (ModelState.IsValid)
            {
                if (model.ClientDate.ToShortDateString() != DateTime.Now.ToShortDateString())
                {
                    ModelState.AddModelError(string.Empty, "Date Not Up-to-Date !!");
                    return(View(model));
                }
                //first try to login with username
                IdentityUser user = await _userManager.FindByNameAsync(model.Email);

                var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, lockoutOnFailure : false);

                if (!result.Succeeded && !result.RequiresTwoFactor && !result.IsLockedOut)
                {
                    //now try to login with email
                    user = await _userManager.FindByEmailAsync(model.Email);

                    if (user != null)
                    {
                        result = await _signInManager.PasswordSignInAsync(user, model.Password, model.RememberMe, lockoutOnFailure : false);
                    }
                }
                if (result.Succeeded)
                {
                    // HttpContext.User = await _signInManager.CreateUserPrincipalAsync(user);
                    //first check username already loggedin
                    Config config = ConfigJSON.Read();
                    Store  store  = _context.Store.FirstOrDefault();
                    if (!User.Identity.IsAuthenticated && config.LoggedInUsers.Contains(user.UserName))
                    {
                        //ModelState.AddModelError(string.Empty, "You're currently logged in to another system !!");
                        //await _signInManager.SignOutAsync();
                        //return View(model);
                    }
                    else
                    {
                        config.LoggedInUsers.Remove(user.UserName);
                        config.LoggedInUsers.Add(user.UserName);
                        ConfigJSON.Write(config);
                    }
                    //get user role
                    var role           = _context.UserViewModel.FirstOrDefault(x => x.UserName == user.UserName);
                    var rolePermission = _context.RoleWisePermission.FirstOrDefault(x => x.RoleId == role.RoleId || x.RoleId == role.Role);


                    //save to session
                    HttpContext.Session.SetString("Role", JsonConvert.SerializeObject(role));
                    HttpContext.Session.SetString("TotalMenu", JsonConvert.SerializeObject(_context.Menu));
                    HttpContext.Session.SetString("Menus", JsonConvert.SerializeObject(_context.RoleWiseMenuPermission.Where(x => x.RoleId == role.Role).Include(x => x.Menu)));
                    HttpContext.Session.SetString("Store", JsonConvert.SerializeObject(store));
                    HttpContext.Session.SetString("RolePermission", JsonConvert.SerializeObject(rolePermission));
                    if (model.TerminalId != 0)
                    {
                        HttpContext.Session.SetString("TerminalId", model.TerminalId.ToString());
                        HttpContext.Session.SetString("Terminal", model.TerminalName);
                        //await _userManager.AddClaimAsync(user, new Claim("Terminal", model.TerminalId.ToString()));
                        //await _userManager.AddClaimAsync(user, new Claim("TerminalName", model.TerminalName.ToString()));
                    }
                    else
                    {
                        //check if user required terminal

                        //var roleName = User.FindFirstValue(ClaimTypes.Role);
                        //var role = _roleManager.FindByNameAsync(roleName);

                        bool requireTerminalToLogin = rolePermission == null ? false : rolePermission.Require_Terminal_To_Login;
                        if (requireTerminalToLogin)
                        {
                            ModelState.AddModelError(string.Empty, "You can only login from Terminals");
                            await _signInManager.SignOutAsync();

                            return(View(model));
                        }
                        else
                        {
                            //select default terminal
                            var terminal = _context.Terminal.FirstOrDefault();
                            if (terminal != null)
                            {
                                HttpContext.Session.SetString("TerminalId", terminal.Id.ToString());
                                HttpContext.Session.SetString("Terminal", terminal.Name.ToString());
                                //await _userManager.AddClaimAsync(user, new Claim("Terminal", terminal.Id.ToString()));
                                //await _userManager.AddClaimAsync(user, new Claim("TerminalName", terminal.Name.ToString()));
                            }
                        }
                    }
                    config.Environment = "successfully login";
                    ConfigJSON.Write(config);
                    if (!string.IsNullOrEmpty(returnUrl) && returnUrl != "/")
                    {
                        return(RedirectToLocal(returnUrl));
                    }
                    else
                    {
                        if (store.INITIAL == "WHS")
                        {
                            return(RedirectToAction("CrLanding", "SalesInvoice", new { Mode = "tax" }));
                        }
                        else
                        {
                            return(RedirectToAction("Landing", "SalesInvoice"));
                        }
                        //return RedirectToAction("CrLanding", "SalesInvoice", new { Mode = "tax" });
                    }
                }
                if (result.RequiresTwoFactor)
                {
                    return(RedirectToAction(nameof(SendCode), new { ReturnUrl = returnUrl, RememberMe = model.RememberMe }));
                }
                if (result.IsLockedOut)
                {
                    _logger.LogWarning(2, "User account locked out.");
                    return(View("Lockout"));
                }
                else
                {
                    ModelState.AddModelError(string.Empty, "Invalid login attempt.");
                    return(View(model));
                }
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
コード例 #25
0
 ////////********** scheduling jobs
 ///[HttpGet]
 public IActionResult APISetup()
 {
     ViewData["API"] = ConfigJSON.Read();
     return(View());
 }
コード例 #26
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;
                    }
                }
            }
        }
コード例 #27
0
        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));
            }
        }
コード例 #28
0
        public void PostCustomer()
        {
            Config config = ConfigJSON.Read();

            if (!config.StopCustomerPosting)
            {
                NavIntegrationService services = _context.NavIntegrationService.FirstOrDefault(x => x.IntegrationType == "Customer");
                string url    = config.NavApiBaseUrl + "/" + config.NavPath + $"/companies({config.NavCompanyId})/{services.ServiceName}";
                var    client = NAV.NAVClient(url, config);


                List <Customer> customers    = _context.Customer.Where(x => x.Is_Member == true && x.IsNavSync == false).ToList();
                var             navCustomers = _mapper.Map <List <NavCustomerPOST> >(customers);


                foreach (var cus in navCustomers)
                {
                    var settings = new JsonSerializerSettings();
                    //settings.ContractResolver = new CamelCasePropertyNamesContractResolver();
                    settings.NullValueHandling = NullValueHandling.Ignore;
                    //you can add multiple settings and then use it
                    var obj = JsonConvert.SerializeObject(cus, Formatting.Indented, settings);

                    var request = new RestRequest(Method.POST);
                    request.RequestFormat = DataFormat.Json;
                    request.AddHeader("Content-Type", "application/json");
                    request.AddJsonBody(obj);
                    IRestResponse <SyncModel <NavCustomer> > response = client.Execute <SyncModel <NavCustomer> >(request);
                    if (response.StatusCode == HttpStatusCode.Created)
                    {
                        var updatedCustomer = customers.FirstOrDefault(x => x.Membership_Number == cus.number);
                        updatedCustomer.IsNavSync   = true;
                        updatedCustomer.NavSyncDate = DateTime.Now;


                        ////update update number
                        //var data = JsonConvert.DeserializeObject<NavCustomer>(response.Content);
                        //if (data != null)
                        //{
                        //    services.LastUpdateNumber = data.Update_No;
                        //    services.LastSyncDate = DateTime.Now;
                        //}
                        _context.SaveChanges();
                        // _logger.LogInformation("Post Customer " + cus.number + " to NAV Successfully   " + DateTime.Now.ToString());
                    }
                    else
                    {
                        if (response.Content.Contains("already exist"))
                        {
                            // update update number
                            var updatedCustomer = customers.FirstOrDefault(x => x.Membership_Number == cus.number);
                            updatedCustomer.IsNavSync   = true;
                            updatedCustomer.NavSyncDate = DateTime.Now;

                            _context.SaveChanges();
                            // _logger.LogInformation("Customer already exist No=" + cus.number + " " + DateTime.Now.ToString());
                            continue;
                        }
                        else
                        {
                            string errorMessage = "Error Customer:: Customer No.= " + cus.number + " Message= " + response.Content + "  " + DateTime.Now.ToString() + Environment.NewLine;
                            WriteToFile(Path.GetFullPath("logs/"), "NAVSyncLog.log", errorMessage);
                            // _logger.LogError("Error Customer:: Customer No.= " + cus.number + " Message= " + response.Content + "  " + DateTime.Now.ToString());
                        }
                    }
                }
                if (_context.Customer.Where(x => x.Is_Member == true && x.IsNavSync == false).Any())
                {
                    BackgroundJob.Schedule(() => PostCustomer(), TimeSpan.FromMinutes(10));
                }

                //  request.AddJsonBody(navCustomers);

                ////IRestResponse response = client.Execute(request);
                //IRestResponse<SyncModel<NavCustomer>> response = client.Execute<SyncModel<NavCustomer>>(request);

                //if (response.StatusCode == HttpStatusCode.OK)
                //{
                //    List<Customer> navCustomer = _mapper.Map<List<Customer>>(response.Data.value);
                //    List<int?> memberIds = navCustomer.Select(x => x.Member_Id).ToList();
                //    var updatedCustomer = customers.Where(x => memberIds.Contains(x.Member_Id)).ToList();
                //    updatedCustomer.ForEach(x => { x.IsNavSync = true; x.NavSyncDate = DateTime.Now; });

                //    _context.SaveChanges();
                //    return true;
                //}
                //else
                //    return false;
            }
        }
コード例 #29
0
        public IActionResult Submit(TravelOrderViewModel vmObj)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    var obj = _mapper.Map <travelordercard>(vmObj);

                    TravelOrderCard.Create createObj = new TravelOrderCard.Create
                    {
                        travelordercard = obj
                    };

                    createObj.travelordercard.Employee_Name          = null;
                    createObj.travelordercard.Employee_No            = User.Identity.GetEmployeeNo();
                    createObj.travelordercard.Travel_TypeSpecified   = true;
                    createObj.travelordercard.Expenses_OnlySpecified = true;

                    Config config = ConfigJSON.Read();
                    if (config.Default_Config.IsForRemit)
                    {
                        createObj.travelordercard.Fooding_Allowance_OnlySpecified = true;
                        createObj.travelordercard.Lodging_Allowance_OnlySpecified = true;
                    }
                    else
                    {
                        createObj.travelordercard.Travel_Allowance_OnlySpecified = true;
                    }

                    createObj.travelordercard.Daily_Allowance_OnlySpecified   = true;
                    createObj.travelordercard.Depature_Date_ADSpecified       = true;
                    createObj.travelordercard.Arrival_Date_ADSpecified        = true;
                    createObj.travelordercard.Reason_for_TravelSpecified      = true;
                    createObj.travelordercard.Mode_Of_TransportationSpecified = true;
                    createObj.travelordercard.Approved_TypeSpecified          = true;
                    createObj.travelordercard.Exchange_RateSpecified          = true;
                    createObj.travelordercard.Travel_StatusSpecified          = true;

                    createObj.travelordercard.Claimed_Local_TransportationSpecified = true;
                    createObj.travelordercard.Claimed_FuelSpecified           = true;
                    createObj.travelordercard.Claimed_Other_ExpensesSpecified = true;

                    var result = Travelordercard_PortClientService()
                                 .CreateAsync(createObj)
                                 .GetAwaiter()
                                 .GetResult()
                                 .travelordercard;

                    if (result != null)
                    {
                        var postResult = Hrmgt_PortClientService()
                                         .PosttravelorderwebAsync(result.Travel_Order_No)
                                         .GetAwaiter()
                                         .GetResult()
                                         .return_value;

                        if (postResult == 200)
                        {
                            TempData["Notify"] = JsonConvert.SerializeObject(new Notify {
                                title = "Leave Request", text = "Travel order posted successfully.", type = "success"
                            });
                            return(RedirectToAction(nameof(Index)));
                        }
                        else
                        {
                            TempData["Notify"] = JsonConvert.SerializeObject(new Notify {
                                title = "Error", text = "Travel order created but submitting failed.", type = "error"
                            });
                        }
                    }
                    else
                    {
                        TempData["Notify"] = JsonConvert.SerializeObject(new Notify {
                            title = "Error", text = "Creating travel order failed. Try again.", type = "error"
                        });
                    }
                }
                else
                {
                    TempData["Notify"] = JsonConvert.SerializeObject(new Notify {
                        title = "Validation Error", text = "Insert proper values for each fields.", type = "error"
                    });
                }
            }
            catch (Exception ex)
            {
                TempData["Notify"] = JsonConvert.SerializeObject(new Notify {
                    title = "Exception Error", text = ex.Message, type = "error"
                });
            }
            return(View(vmObj));
        }
コード例 #30
0
        public bool PostCreditNote(Store store)
        {
            Config config = ConfigJSON.Read();

            if (config.StopCreditNotePosting)
            {
                return(true);
            }
            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);
            }

            NavIntegrationService services = _context.NavIntegrationService.FirstOrDefault(x => x.IntegrationType == "CreditNotePost");
            var unSyncInvoice = _context.CreditNote.Where(x => x.IsNavSync == false).OrderBy(x => x.Trans_Date_Ad);

            foreach (var credit in unSyncInvoice)
            {
                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");

                NavCreditMemo creditNote = new NavCreditMemo()
                {
                    id                     = credit.Id.ToString(),
                    number                 = credit.Credit_Note_Number,
                    postingno              = credit.Credit_Note_Number,
                    creditMemoDate         = credit.Trans_Date_Ad.Value.ToString("yyyy-MM-dd"),
                    customerNumber         = credit.MemberId,
                    customerName           = credit.Customer_Name,
                    vatregistrationnumber  = credit.Customer_Vat,
                    locationcode           = store.INITIAL,
                    accountabilitycenter   = store.INITIAL,
                    assigneduserid         = credit.Created_By,
                    externalDocumentNumber = credit.Reference_Number,
                    amountrounded          = credit.IsRoundup,
                    returnremarks          = credit.Credit_Note
                };
                request.RequestFormat = DataFormat.Json;
                var temp = JsonConvert.SerializeObject(creditNote);
                request.AddJsonBody(temp);

                IRestResponse response = client.Execute(request);

                if (response.StatusCode == HttpStatusCode.Created)
                {
                    //update sync status
                    CreditNote sInvoice = _context.CreditNote.FirstOrDefault(x => x.Credit_Note_Number == creditNote.number);
                    sInvoice.IsNavSync             = true;
                    sInvoice.NavSyncDate           = DateTime.Now;
                    _context.Entry(sInvoice).State = Microsoft.EntityFrameworkCore.EntityState.Modified;


                    _context.SaveChanges();
                    // _logger.LogInformation("Post Credit Note " + creditNote.number + " to NAV Successfully   " + DateTime.Now.ToString());
                    PostCreditNoteItem(sInvoice.Credit_Note_Number);
                    return(true);
                }
                else
                {
                    string errorMessage = "Error Credit Note:: Credit Note= " + creditNote.number + " Message= " + response.Content + "  " + DateTime.Now.ToString() + Environment.NewLine;
                    WriteToFile(Path.GetFullPath("logs/"), "NAVSyncLog.log", errorMessage);
                    // _logger.LogError("Error Credit Note:: Credit Note= " + creditNote.number + " Message= " + response.Content + "  " + DateTime.Now.ToString());
                    //update values
                    //CreditNote sInvoice = _context.CreditNote.FirstOrDefault(x => x.Credit_Note_Number == creditNote.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);
                }
            }
            return(true);
        }