Esempio n. 1
0
        public ProductDto SaveProduct(ProductDto model)
        {
            try
            {
                // ensure the EIS SKU is upper cased
                model.EisSKU.ToUpper();
                var product = Mapper.Map <ProductDto, product>(model);
                product.CreatedBy = model.ModifiedBy;
                product.Created   = DateTime.UtcNow;

                _context.products.Add(product);
                _context.SaveChanges();

                return(Mapper.Map <product, ProductDto>(product));
            }
            catch (DbEntityValidationException ex)
            {
                var errorMsg = EisHelper.ParseDbEntityValidationException(ex);
                _logger.LogError(LogEntryType.ProductService, errorMsg, ex.StackTrace);
                return(model);
            }
            catch (Exception ex)
            {
                _logger.LogError(LogEntryType.ProductService, EisHelper.GetExceptionMessage(ex), ex.StackTrace);
                return(model);
            }
        }
        public MessageTemplateDto UpdateMessageTemplate(MessageTemplateDto model)
        {
            try
            {
                var oldMessageTemplate     = _context.messagetemplates.FirstOrDefault(x => x.Id == model.Id);
                var updatedMessageTemplate = Mapper.Map <messagetemplate>(model);
                updatedMessageTemplate.Modified = DateTime.Now;

                _context.Entry(oldMessageTemplate).CurrentValues.SetValues(updatedMessageTemplate);
                _context.SaveChanges();

                return(model);
            }
            catch (DbEntityValidationException ex)
            {
                var errorMsg = EisHelper.ParseDbEntityValidationException(ex);
                _logger.LogError(LogEntryType.VendorProductService, errorMsg, ex.StackTrace);
                throw ex;
            }
            catch (Exception ex)
            {
                _logger.LogError(LogEntryType.VendorProductService, EisHelper.GetExceptionMessage(ex), ex.StackTrace);
                throw ex;
            }
        }
Esempio n. 3
0
        public SavedSearchFilterDto CreateSavedSearchFilter(SavedSearchFilterDto model)
        {
            try
            {
                var savedsearchfilter = Mapper.Map <savedsearchfilter>(model);
                savedsearchfilter.Created   = DateTime.UtcNow;
                savedsearchfilter.CreatedBy = model.CreatedBy;


                _context.savedsearchfilters.Add(savedsearchfilter);
                _context.SaveChanges();
                model.Id = savedsearchfilter.Id;

                return(model);
            }
            catch (DbEntityValidationException ex)
            {
                var errorMsg = EisHelper.ParseDbEntityValidationException(ex);
                _logger.LogError(LogEntryType.VendorService, errorMsg, ex.StackTrace);
                throw ex;
            }
            catch (Exception ex)
            {
                _logger.LogError(LogEntryType.VendorService, EisHelper.GetExceptionMessage(ex), ex.StackTrace);
                throw ex;
            }
        }
Esempio n. 4
0
        private void updateProductsDetail(List <ProductAmazon> amazonProducts)
        {
            try
            {
                // iterate and update the EIS product info with data from marketplace
                foreach (var amazonProduct in amazonProducts)
                {
                    _repository.UpdateEisProduct(amazonProduct, _systemJob.SubmittedBy);
                    _repository.DoUpdateOrInsertAmazon(amazonProduct, _systemJob.SubmittedBy);

                    // parsed and save its images
                    if (amazonProduct.Images != null || amazonProduct.Images.Any())
                    {
                        _repository.UpdateProductImages(amazonProduct.Images.Select(x => x.Url).ToList(),
                                                        amazonProduct.EisSKU);
                    }
                }
            }
            catch (DbEntityValidationException ex)
            {
                var errorMsg = EisHelper.ParseDbEntityValidationException(ex);
                _logger.LogError(LogEntryType.AmazonGetInfoWorker, errorMsg, ex.StackTrace);

                _jobRepository.UpdateSystemJobStatus(_systemJob.Id, JobStatus.Failed);
            }
            catch (Exception ex)
            {
                _logger.LogError(LogEntryType.AmazonGetInfoWorker,
                                 string.Format("Error in updating products. <br/> Error message: {0}", ex.InnerException != null ? ex.InnerException.Message : ex.Message),
                                 ex.StackTrace);

                _jobRepository.UpdateSystemJobStatus(_systemJob.Id, JobStatus.Failed);
            }
        }
Esempio n. 5
0
        public CustomerNotesDto UpdateCustomerNotes(CustomerNotesDto model)
        {
            try
            {
                var oldCustomerNotes = _context.customersnotes.FirstOrDefault(x => x.CustomerNotesId == model.CustomerNotesId);

                var updatedCustomerNotes = Mapper.Map <customersnote>(model);
                updatedCustomerNotes.Modified   = DateTime.Now;
                updatedCustomerNotes.ModifiedBy = model.ModifiedBy;
                updatedCustomerNotes.Created    = oldCustomerNotes.Created;
                updatedCustomerNotes.CreatedBy  = oldCustomerNotes.CreatedBy;
                updatedCustomerNotes.CustomerId = model.NotesCustomerId;


                _context.Entry(oldCustomerNotes).CurrentValues.SetValues(updatedCustomerNotes);
                _context.SaveChanges();

                return(model);
            }
            catch (DbEntityValidationException ex)
            {
                var errorMsg = EisHelper.ParseDbEntityValidationException(ex);
                _logger.LogError(LogEntryType.CustomerService, errorMsg, ex.StackTrace);
                throw ex;
            }
            catch (Exception ex)
            {
                _logger.LogError(LogEntryType.CustomerService, EisHelper.GetExceptionMessage(ex), ex.StackTrace);
                throw ex;
            }
        }
Esempio n. 6
0
        public bool CreateCompany(CompanyDto model)
        {
            try
            {
                var company = Mapper.Map <CompanyDto, company>(model);
                company.Created    = DateTime.UtcNow;
                company.CreatedBy  = model.ModifiedBy;
                company.ModifiedBy = null;

                _context.companies.Add(company);
                _context.SaveChanges();
                model.Id = company.Id;

                return(true);
            }
            catch (DbEntityValidationException ex)
            {
                var errorMsg = EisHelper.ParseDbEntityValidationException(ex);
                _logger.LogError(LogEntryType.VendorService, errorMsg, ex.StackTrace);
                return(false);
            }
            catch (Exception ex)
            {
                _logger.LogError(LogEntryType.VendorProductService, EisHelper.GetExceptionMessage(ex), ex.StackTrace);
                return(false);
            }
        }
Esempio n. 7
0
        public VendorDto CreateVendor(VendorDto model)
        {
            try
            {
                var vendor = Mapper.Map<VendorDto, vendor>(model);
                vendor.CreatedBy = model.ModifiedBy;
                vendor.Created = DateTime.UtcNow;

                _context.vendors.Add(vendor);
                _context.SaveChanges();

                // update all of its vendor products if it is configured as always in stock
                if (vendor.IsAlwaysInStock)
                    upateVendorProductsQuantity(vendor.Id, vendor.AlwaysQuantity ?? 0);

                return Mapper.Map<vendor, VendorDto>(vendor);
            }
            catch (DbEntityValidationException ex)
            {
                var errorMsg = EisHelper.ParseDbEntityValidationException(ex);
                _logger.LogError(LogEntryType.VendorService, errorMsg, ex.StackTrace);
                return model;
            }
            catch (Exception ex)
            {
                _logger.LogError(LogEntryType.VendorProductService, EisHelper.GetExceptionMessage(ex), ex.StackTrace);
                return model;
            }
        }
        public SystemEmailDto CreateSystemEmail(SystemEmailDto model)
        {
            try
            {
                var systemEmail = Mapper.Map <systememail>(model);
                systemEmail.Created    = DateTime.UtcNow;
                systemEmail.CreatedBy  = model.ModifiedBy;
                systemEmail.ModifiedBy = null;

                _context.systememails.Add(systemEmail);
                _context.SaveChanges();
                model.Id = systemEmail.Id;

                return(model);
            }
            catch (DbEntityValidationException ex)
            {
                var errorMsg = EisHelper.ParseDbEntityValidationException(ex);
                _logger.LogError(LogEntryType.VendorService, errorMsg, ex.StackTrace);
                throw ex;
            }
            catch (Exception ex)
            {
                _logger.LogError(LogEntryType.VendorService, EisHelper.GetExceptionMessage(ex), ex.StackTrace);
                throw ex;
            }
        }
        public SystemEmailDto UpdateSystemEmail(SystemEmailDto model)
        {
            try
            {
                var oldSystemEmail     = _context.systememails.FirstOrDefault(x => x.Id == model.Id);
                var updatedSystemEmail = Mapper.Map <systememail>(model);
                updatedSystemEmail.Modified   = DateTime.Now;
                updatedSystemEmail.ModifiedBy = model.ModifiedBy;
                updatedSystemEmail.Created    = oldSystemEmail.Created;
                updatedSystemEmail.CreatedBy  = oldSystemEmail.CreatedBy;



                _context.Entry(oldSystemEmail).CurrentValues.SetValues(updatedSystemEmail);
                _context.SaveChanges();

                return(model);
            }
            catch (DbEntityValidationException ex)
            {
                var errorMsg = EisHelper.ParseDbEntityValidationException(ex);
                _logger.LogError(LogEntryType.VendorProductService, errorMsg, ex.StackTrace);
                throw ex;
            }
            catch (Exception ex)
            {
                _logger.LogError(LogEntryType.VendorProductService, EisHelper.GetExceptionMessage(ex), ex.StackTrace);
                throw ex;
            }
        }
Esempio n. 10
0
        public bool CreateVendorProduct(VendorProductDto model)
        {
            try
            {
                // get its vendor's info and if it's always on stock, use it alwaysQuantity
                var vendor = _context.vendors.FirstOrDefault(x => x.Id == model.VendorId);
                if (vendor.IsAlwaysInStock)
                {
                    model.Quantity = vendor.AlwaysQuantity ?? 0;
                }

                var product = Mapper.Map <vendorproduct>(model);
                product.Created   = DateTime.UtcNow;
                product.CreatedBy = model.ModifiedBy;

                _context.vendorproducts.Add(product);
                _context.SaveChanges();

                // generated id
                model.EisSupplierSKU = product.EisSupplierSKU;

                return(true);
            }
            catch (DbEntityValidationException ex)
            {
                var errorMsg = EisHelper.ParseDbEntityValidationException(ex);
                _logger.LogError(LogEntryType.VendorProductService, errorMsg, ex.StackTrace);
                return(false);
            }
            catch (Exception ex)
            {
                _logger.LogError(LogEntryType.VendorProductService, EisHelper.GetExceptionMessage(ex), ex.StackTrace);
                return(false);
            }
        }
Esempio n. 11
0
        public SavedSearchFilterDto UpdateSavedSearchFilter(SavedSearchFilterDto model)
        {
            try
            {
                var oldSavedFilterSearch     = _context.savedsearchfilters.FirstOrDefault(x => x.Id == model.Id);
                var updatedSavedFilterSearch = Mapper.Map <savedsearchfilter>(model);

                updatedSavedFilterSearch.Created   = DateTime.Now;
                updatedSavedFilterSearch.CreatedBy = model.CreatedBy;

                _context.Entry(oldSavedFilterSearch).CurrentValues.SetValues(updatedSavedFilterSearch);
                _context.SaveChanges();

                return(model);
            }
            catch (DbEntityValidationException ex)
            {
                var errorMsg = EisHelper.ParseDbEntityValidationException(ex);
                _logger.LogError(LogEntryType.VendorProductService, errorMsg, ex.StackTrace);
                throw ex;
            }
            catch (Exception ex)
            {
                _logger.LogError(LogEntryType.VendorProductService, EisHelper.GetExceptionMessage(ex), ex.StackTrace);
                throw ex;
            }
        }
Esempio n. 12
0
        public ProductAmazonDto UpdateProductAmazon(string eisSku, ProductAmazonDto model)
        {
            var oldProduct = _context.productamazons.Find(eisSku);

            try
            {
                // ensure the EIS SKU is upper cased
                model.EisSKU.ToUpper();
                _context.Entry(oldProduct).CurrentValues.SetValues(model);
                oldProduct.Modified   = DateTime.UtcNow;
                oldProduct.ModifiedBy = model.ModifiedBy;

                _context.SaveChanges();
            }
            catch (DbEntityValidationException ex)
            {
                var errorMsg = EisHelper.ParseDbEntityValidationException(ex);
                _logger.LogError(LogEntryType.ProductService, errorMsg, ex.StackTrace);
                throw ex;
            }
            catch (Exception ex)
            {
                _logger.LogError(LogEntryType.ProductService, EisHelper.GetExceptionMessage(ex), ex.StackTrace);
                throw ex;
            }

            return(model);
        }
Esempio n. 13
0
        public ProductAmazonDto SaveProductAmazon(ProductAmazonDto model)
        {
            var product = Mapper.Map <ProductAmazonDto, productamazon>(model);

            try
            {
                product.Modified   = DateTime.UtcNow;
                product.ModifiedBy = model.ModifiedBy;

                _context.productamazons.Add(product);
                _context.SaveChanges();
            }
            catch (DbEntityValidationException ex)
            {
                var errorMsg = EisHelper.ParseDbEntityValidationException(ex);
                _logger.LogError(LogEntryType.ProductService, errorMsg, ex.StackTrace);
                throw ex;
            }
            catch (Exception ex)
            {
                _logger.LogError(LogEntryType.ProductService, EisHelper.GetExceptionMessage(ex), ex.StackTrace);
                throw ex;
            }

            return(model);
        }
Esempio n. 14
0
        public CustomerNotesDto CreateCustomerNotes(CustomerNotesDto model)
        {
            try
            {
                var customerNotes = Mapper.Map <customersnote>(model);
                customerNotes.Created    = DateTime.UtcNow;
                customerNotes.CreatedBy  = model.ModifiedBy;
                customerNotes.ModifiedBy = null;
                customerNotes.CustomerId = model.NotesCustomerId;

                _context.customersnotes.Add(customerNotes);
                _context.SaveChanges();
                model.CustomerNotesId = customerNotes.CustomerNotesId;

                return(model);
            }
            catch (DbEntityValidationException ex)
            {
                var errorMsg = EisHelper.ParseDbEntityValidationException(ex);
                _logger.LogError(LogEntryType.CustomerService, errorMsg, ex.StackTrace);
                throw ex;
            }
            catch (Exception ex)
            {
                _logger.LogError(LogEntryType.CustomerService, EisHelper.GetExceptionMessage(ex), ex.StackTrace);
                throw ex;
            }
        }
Esempio n. 15
0
        public int SaveMarketplaceOrders(List <MarketplaceOrder> orderResults)
        {
            try
            {
                var results = new List <OrderProductResult>();

                // iterate and convert the order results into order domain object
                foreach (var orderResult in orderResults)
                {
                    // let's check first if this marketplace order already exist to the db
                    var existingOrder = _context.orders.FirstOrDefault(x => x.OrderId == orderResult.OrderId);
                    if (existingOrder != null)
                    {
                        continue;
                    }

                    // map the order result into order domain and set the its EIS order Id
                    var order = Mapper.Map <order>(orderResult);
                    order.EisOrderId = GetNextEisOrderId();
                    _context.orders.Add(order);

                    foreach (var orderItem in orderResult.OrderItems)
                    {
                        // create also the order update history for orderitems
                        _context.orderupdatehistories.Add(new orderupdatehistory
                        {
                            OrderItemId  = orderItem.OrderItemId,
                            QtyOrdered   = orderItem.QtyOrdered,
                            OrderStatus  = orderResult.OrderStatus,
                            PurchaseDate = orderResult.PurchaseDate,
                            ResultDate   = DateTime.UtcNow
                        });

                        // create order products and update the product inventory
                        var result = ManageOrderVendorProduct(orderItem);
                        results.Add(result);
                    }

                    // let's save the changes 1by1 so we can get its EIS OrderID
                    _context.SaveChanges();
                }

                // notify Admin if there are insufficient products for the orders
                EvaluateForInsufficientVendorProducts(results);
            }
            catch (DbEntityValidationException ex)
            {
                var errorMsg = EisHelper.ParseDbEntityValidationException(ex);
                _logger.LogError(LogEntryType.OrderService, errorMsg, ex.StackTrace);
                return(0);
            }
            catch (Exception ex)
            {
                _logger.LogError(LogEntryType.OrderService, EisHelper.GetExceptionMessage(ex), ex.StackTrace);
                return(0);
            }

            return(orderResults.Count);
        }
Esempio n. 16
0
        public CustomerAddressDto UpdateCustomerAddress(CustomerAddressDto model)
        {
            try
            {
                var customerAddressesList = _context.customersaddresses.Where(x => x.CustomerId == model.AddressCustomerId).ToList();

                if (customerAddressesList.Count == 0 || !customerAddressesList.Any(x => x.IsPrimary == true))
                {
                    model.IsPrimary = true;
                }
                else if (model.IsPrimary)
                {
                    foreach (var address in customerAddressesList)
                    {
                        address.IsPrimary = false;

                        _context.Entry(address).State = System.Data.Entity.EntityState.Modified;
                        _context.SaveChanges();
                    }
                }

                var oldCustomerAddress = _context.customersaddresses.FirstOrDefault(x => x.CustomerAddressID == model.CustomerAddressID);

                var updatedCustomerAddress = Mapper.Map <customersaddress>(model);
                updatedCustomerAddress.Modified   = DateTime.Now;
                updatedCustomerAddress.ModifiedBy = model.ModifiedBy;
                updatedCustomerAddress.Created    = oldCustomerAddress.Created;
                updatedCustomerAddress.CreatedBy  = oldCustomerAddress.CreatedBy;

                updatedCustomerAddress.CustomerId   = model.AddressCustomerId;
                updatedCustomerAddress.EmailAddress = model.customerEmailAddress;
                updatedCustomerAddress.Country      = Convert.ToInt32(model.SelectedCountryId);


                _context.Entry(oldCustomerAddress).CurrentValues.SetValues(updatedCustomerAddress);
                _context.SaveChanges();

                return(model);
            }
            catch (DbEntityValidationException ex)
            {
                var errorMsg = EisHelper.ParseDbEntityValidationException(ex);
                _logger.LogError(LogEntryType.CustomerService, errorMsg, ex.StackTrace);
                throw ex;
            }
            catch (Exception ex)
            {
                _logger.LogError(LogEntryType.CustomerService, EisHelper.GetExceptionMessage(ex), ex.StackTrace);
                throw ex;
            }
        }
Esempio n. 17
0
        public void UpdateProductImages(List <MediaContent> imageUrls, string eisSku)
        {
            try
            {
                // get the Amazon images
                var amazonImages = _context.productimages
                                   .Where(x => x.EisSKU == eisSku && x.ImageType != "CUSTOM")
                                   .ToList();
                foreach (var image in amazonImages)
                {
                    // delete first the image file from the directory
                    _imageHelper.RemoveProductImage(eisSku, image.FileName);

                    // then the image record from the database
                    _context.productimages.Remove(image);
                }

                // let's save the changes first for the deleted images
                _context.SaveChanges();


                foreach (var media in imageUrls)
                {
                    // download the image from net and save it to the file system
                    var fileName = _imageHelper.SaveProductImage(eisSku, media.Url);
                    if (string.IsNullOrEmpty(fileName))
                    {
                        continue;
                    }

                    // add the database to the database
                    addProductImage(fileName, eisSku, 99, "Amazon Large Image", media.Type);
                }

                // save the images
                _context.SaveChanges();
            }
            catch (DbEntityValidationException ex)
            {
                var errorMsg = EisHelper.ParseDbEntityValidationException(ex);
                _logger.LogError(LogEntryType.ProductService, errorMsg, ex.StackTrace);
            }
            catch (Exception ex)
            {
                _logger.LogError(LogEntryType.ProductService, EisHelper.GetExceptionMessage(ex), ex.StackTrace);
            }
        }
Esempio n. 18
0
        public CustomerDto CreateCustomer(CustomerDto model)
        {
            try
            {
                model.CompanyId   = int.Parse(model.SelectedCompanyId);
                model.AccountType = int.Parse(model.SelectedAccountType);
                model.AmountType  = int.Parse(model.SelectedAmountType);

                if (!string.IsNullOrEmpty(model.SelectedCostPlusBasedWholeSalePriceType))
                {
                    model.CostPlusBasedWholeSalePriceType = int.Parse(model.SelectedCostPlusBasedWholeSalePriceType);
                }


                if (!string.IsNullOrEmpty(model.strCustomerNumber))
                {
                    model.CustomerNumber = int.Parse(model.strCustomerNumber);
                }
                else
                {
                    model.CustomerNumber = getMaxCustomerNumber() + 1;
                }

                var customer = Mapper.Map <customer>(model);
                customer.Created    = DateTime.UtcNow;
                customer.CreatedBy  = model.ModifiedBy;
                customer.ModifiedBy = null;

                _context.customers.Add(customer);
                _context.SaveChanges();
                model.CustomerId = customer.CustomerId;

                return(model);
            }
            catch (DbEntityValidationException ex)
            {
                var errorMsg = EisHelper.ParseDbEntityValidationException(ex);
                _logger.LogError(LogEntryType.CustomerService, errorMsg, ex.StackTrace);
                throw ex;
            }
            catch (Exception ex)
            {
                _logger.LogError(LogEntryType.CustomerService, EisHelper.GetExceptionMessage(ex), ex.StackTrace);
                throw ex;
            }
        }
 public void DeleteTemplate(int id)
 {
     try
     {
         var templateToDelete = _context.reporttemplates.FirstOrDefault(x => x.Id == id);
         _context.reporttemplates.Remove(templateToDelete);
         _context.SaveChanges();
     }
     catch (DbEntityValidationException ex)
     {
         var errorMsg = EisHelper.ParseDbEntityValidationException(ex);
         _logger.LogError(LogEntryType.ProductService, errorMsg, ex.StackTrace);
     }
     catch (Exception ex)
     {
         _logger.LogError(LogEntryType.ProductService, EisHelper.GetExceptionMessage(ex), ex.StackTrace);
     }
 }
Esempio n. 20
0
        public CustomerDto UpdateCustomer(CustomerDto model)
        {
            try
            {
                model.CompanyId   = int.Parse(model.SelectedCompanyId);
                model.AccountType = int.Parse(model.SelectedAccountType);
                model.AmountType  = int.Parse(model.SelectedAmountType);

                if (!string.IsNullOrEmpty(model.SelectedCostPlusBasedWholeSalePriceType))
                {
                    model.CostPlusBasedWholeSalePriceType = int.Parse(model.SelectedCostPlusBasedWholeSalePriceType);
                }

                var oldCustomer = _context.customers.FirstOrDefault(x => x.CustomerId == model.CustomerId);
                model.CustomerNumber = oldCustomer.CustomerNumber;

                var updatedCustomer = Mapper.Map <customer>(model);
                updatedCustomer.Modified   = DateTime.Now;
                updatedCustomer.ModifiedBy = model.ModifiedBy;
                updatedCustomer.Created    = oldCustomer.Created;
                updatedCustomer.CreatedBy  = oldCustomer.CreatedBy;



                _context.Entry(oldCustomer).CurrentValues.SetValues(updatedCustomer);
                _context.SaveChanges();

                return(model);
            }
            catch (DbEntityValidationException ex)
            {
                var errorMsg = EisHelper.ParseDbEntityValidationException(ex);
                _logger.LogError(LogEntryType.CustomerService, errorMsg, ex.StackTrace);
                throw ex;
            }
            catch (Exception ex)
            {
                _logger.LogError(LogEntryType.CustomerService, EisHelper.GetExceptionMessage(ex), ex.StackTrace);
                throw ex;
            }
        }
Esempio n. 21
0
        public bool SaveProductBigCommerce(ProductBigCommerceDto model)
        {
            var product = Mapper.Map <productbigcommerce>(model);

            try {
                product.Created   = DateTime.UtcNow;
                product.CreatedBy = model.ModifiedBy;

                _context.productbigcommerces.Add(product);
                _context.SaveChanges();

                return(true);
            } catch (DbEntityValidationException ex) {
                var errorMsg = EisHelper.ParseDbEntityValidationException(ex);
                _logger.LogError(LogEntryType.ProductService, errorMsg, ex.StackTrace);
                throw ex;
            } catch (Exception ex) {
                _logger.LogError(LogEntryType.ProductService, EisHelper.GetExceptionMessage(ex), ex.StackTrace);
                throw ex;
            }
        }
Esempio n. 22
0
        public bool CreateScheduledTask(CustomerScheduledTaskDto taskModel)
        {
            try
            {
                // unbox the correct object type for the credential
                var task = Mapper.Map <customerscheduledtask>(taskModel);
                task.StartTime = taskModel.StartTimeDate.TimeOfDay;
                task.CreatedBy = taskModel.ModifiedBy;
                task.Created   = DateTime.UtcNow;

                _context.customerscheduledtasks.Add(task);
                _context.SaveChanges();
                taskModel.Id = task.Id;
            }
            catch (DbEntityValidationException ex)
            {
                var errorMsg = EisHelper.ParseDbEntityValidationException(ex);
                return(false);
            }

            return(true);
        }
Esempio n. 23
0
        public bool UpdateVendorProduct(string eisSupplierSKU, VendorProductDto model)
        {
            try
            {
                var existingProduct = _context.vendorproducts
                                      .FirstOrDefault(x => x.EisSupplierSKU == eisSupplierSKU);
                if (existingProduct == null)
                {
                    return(false);
                }

                // get its vendor's info and if it's always on stock, use it alwaysQuantity
                var vendor = existingProduct.vendor;
                if (vendor.IsAlwaysInStock)
                {
                    model.Quantity = vendor.AlwaysQuantity ?? 0;
                }

                // reflect the changes from model
                Mapper.Map(model, existingProduct);
                existingProduct.ModifiedBy = model.ModifiedBy;
                existingProduct.Modified   = DateTime.UtcNow;
                _context.SaveChanges();

                return(true);
            }
            catch (DbEntityValidationException ex)
            {
                var errorMsg = EisHelper.ParseDbEntityValidationException(ex);
                _logger.LogError(LogEntryType.VendorProductService, errorMsg, ex.StackTrace);
                return(false);
            }
            catch (Exception ex)
            {
                _logger.LogError(LogEntryType.VendorProductService, EisHelper.GetExceptionMessage(ex), ex.StackTrace);
                return(false);
            }
        }
        public ReportTemplateViewModel SaveTemplate(ReportTemplateViewModel model)
        {
            try
            {
                var reportTemplate = Mapper.Map <ReportTemplateViewModel, reporttemplate>(model);

                _context.reporttemplates.Add(reportTemplate);
                _context.SaveChanges();

                return(Mapper.Map <reporttemplate, ReportTemplateViewModel>(reportTemplate));
            }
            catch (DbEntityValidationException ex)
            {
                var errorMsg = EisHelper.ParseDbEntityValidationException(ex);
                _logger.LogError(LogEntryType.ProductService, errorMsg, ex.StackTrace);
                return(model);
            }
            catch (Exception ex)
            {
                _logger.LogError(LogEntryType.ProductService, EisHelper.GetExceptionMessage(ex), ex.StackTrace);
                return(model);
            }
        }
Esempio n. 25
0
        public int DoUpdateVendorInventoryProduct(VendorProduct model, int vendorId, string submittedBy)
        {
            try
            {
                // NEED TO CREATE NEW DB CONTEXT SINCE THIS METHOD IS SHARED TO CONSOLE SERVICES
                using (var context = new EisInventoryContext())
                {
                    // get the existing vendor product
                    var product = context.vendorproducts.FirstOrDefault(x => x.EisSupplierSKU == model.EisSupplierSKU && x.VendorId == vendorId);
                    if (product == null)
                    {
                        return(0);
                    }

                    product.Quantity = model.Quantity;

                    product.Modified   = DateTime.UtcNow;
                    product.ModifiedBy = submittedBy;
                    context.SaveChanges();
                }
                return(1);
            }
            catch (DbEntityValidationException ex)
            {
                var errorMsg = EisHelper.ParseDbEntityValidationException(ex);
                _logger.LogError(LogEntryType.VendorProductFileUploadWorker, errorMsg, ex.StackTrace);
                return(0);
            }
            catch (Exception ex)
            {
                _logger.LogError(LogEntryType.VendorProductFileUploadWorker,
                                 string.Format("Error in updating vendor product details -> SupplierSKU: {0} VendorId: {1}. <br/>Error message: {2}",
                                               model.SupplierSKU, model.VendorId, EisHelper.GetExceptionMessage(ex)),
                                 ex.StackTrace);
                return(0);
            }
        }
        public MessageTemplateDto CreateMessageTemplate(MessageTemplateDto model)
        {
            try
            {
                var result = Mapper.Map <messagetemplate>(model);
                result.Created = DateTime.Now;

                _context.messagetemplates.Add(result);
                _context.SaveChanges();

                return(Mapper.Map <MessageTemplateDto>(result));
            }
            catch (DbEntityValidationException ex)
            {
                var errorMsg = EisHelper.ParseDbEntityValidationException(ex);
                _logger.LogError(LogEntryType.VendorProductService, errorMsg, ex.StackTrace);
                throw ex;
            }
            catch (Exception ex)
            {
                _logger.LogError(LogEntryType.VendorProductService, EisHelper.GetExceptionMessage(ex), ex.StackTrace);
                throw ex;
            }
        }
        protected override void bw_DoWork(object sender, DoWorkEventArgs e)
        {
            if (_isWorkerExecuted)
            {
                return;
            }

            // set the flag the this bw_DoWork has already called
            _isWorkerExecuted = true;
            var totalProcessed = 0;
            var affectedRows   = 0;

            // parsed the vendor product data from the file
            var vendorProducts = new List <VendorProduct>();
            var message        = CsvFileDataParser.ParseVendorInventoryFile(_systemJob.Parameters, vendorProducts, _systemJob.HasHeader);

            try
            {
                if (vendorProducts.Count == 0)
                {
                    Console.WriteLine("0 records to update vendor inventory products");
                    _jobRepository.UpdateSystemJobStatus(_systemJob.Id, JobStatus.Completed);
                    return;
                }
                int selectedVendorId = Convert.ToInt32(supportiveParameters["selectedVendor"]);
                if (Convert.ToBoolean(supportiveParameters["inventoryZero"]))
                {
                    var vendorProductsList = _service.GetProductsByVendorId(selectedVendorId).Take(5).ToList();

                    var totalItems = vendorProductsList.Count;
                    setTotalItemsProcessed(totalItems);
                    _logger.LogInfo(LogEntryType.VendorProductFileUploadWorker, string.Format("Uploading {0} vendor inventory products initiated by {1}", totalItems, _systemJob.SubmittedBy));


                    var vendorProductsNotInList = vendorProductsList.Where(x => !vendorProducts.Any(y => y.VendorId == selectedVendorId && y.EisSupplierSKU == x.EisSupplierSKU)).
                                                  Select(x => new VendorProduct
                    {
                        Category       = x.Category,
                        Description    = x.Description,
                        EisSupplierSKU = x.EisSupplierSKU,
                        Quantity       = 0,
                        VendorId       = x.VendorId
                    }).ToList();


                    foreach (var vendorProduct in vendorProducts)
                    {
                        totalProcessed++;
                        var percentage = (((double)totalProcessed) / totalItems) * 100.00;

                        affectedRows += _service.DoUpdateVendorInventoryProduct(vendorProduct, selectedVendorId, _systemJob.SubmittedBy);

                        _bw.ReportProgress(affectedRows);
                        Console.WriteLine(string.Format("{1:#0.00}% Updating vendor products EisSupplierSKU: {0}", vendorProduct.EisSupplierSKU, percentage));
                    }

                    foreach (var vendorProduct in vendorProductsNotInList)
                    {
                        totalProcessed++;
                        var percentage = (((double)totalProcessed) / totalItems) * 100.00;

                        affectedRows += _service.DoUpdateVendorInventoryProduct(vendorProduct, selectedVendorId, _systemJob.SubmittedBy);

                        _bw.ReportProgress(affectedRows);
                        Console.WriteLine(string.Format("{1:#0.00}% Updating vendor products EisSupplierSKU: {0}", vendorProduct.EisSupplierSKU, percentage));
                    }
                }
                else
                {
                    var totalItems = vendorProducts.Count;
                    setTotalItemsProcessed(totalItems);
                    _logger.LogInfo(LogEntryType.VendorProductFileUploadWorker, string.Format("Uploading {0} vendor inventory products initiated by {1}", totalItems, _systemJob.SubmittedBy));

                    foreach (var vendorProduct in vendorProducts)
                    {
                        totalProcessed++;
                        var percentage = (((double)totalProcessed) / totalItems) * 100.00;

                        affectedRows += _service.DoUpdateVendorInventoryProduct(vendorProduct, selectedVendorId, _systemJob.SubmittedBy);

                        _bw.ReportProgress(affectedRows);
                        Console.WriteLine(string.Format("{1:#0.00}% Updating vendor inventory products EisSupplierSKU: {0}", vendorProduct.EisSupplierSKU, percentage));
                    }
                }
            }
            catch (DbEntityValidationException ex)
            {
                _hasError = true;
                _logger.LogError(LogEntryType.VendorProductFileUploadWorker, EisHelper.ParseDbEntityValidationException(ex), ex.StackTrace);
                _jobRepository.UpdateSystemJobStatus(_systemJob.Id, JobStatus.Failed);
            }
            catch (Exception ex)
            {
                _hasError = true;
                _logger.LogError(LogEntryType.VendorProductFileUploadWorker,
                                 string.Format("Error in uploading vendor inventory products. <br/> Error message: {0}", EisHelper.GetExceptionMessage(ex)),
                                 ex.StackTrace);
                _jobRepository.UpdateSystemJobStatus(_systemJob.Id, JobStatus.Failed);
            }

            _logger.LogInfo(LogEntryType.VendorProductFileUploadWorker, string.Format("{0} vendor inventory products have been successfully uploaded by {1}", totalProcessed, _systemJob.SubmittedBy));
        }
        protected override void bw_DoWork(object sender, DoWorkEventArgs e)
        {
            if (_isWorkerExecuted)
            {
                return;
            }

            // set the flag the this bw_DoWork has already called
            _isWorkerExecuted = true;

            var eisProducts        = new List <Product>();
            var amazonProducts     = new List <ProductAmazon>();
            var eBayProducts       = new List <ProducteBayDto>();
            var bigCommerceProucts = new List <ProductBigCommerceDto>();
            var repository         = new ProductRepository(_logger);
            var affectedProducts   = 0;
            var isCreateNew        = _systemJob.IsAddNewItem;

            // get the Product and/or Amazon details from the file path
            var message = CsvFileDataParser.ParseProductFile(_systemJob.Parameters,
                                                             eisProducts,
                                                             amazonProducts,
                                                             eBayProducts,
                                                             bigCommerceProucts,
                                                             _systemJob.HasHeader);
            var defaultCompany = repository.GetDefaultCompany();
            var totalProducts  = eisProducts.Count;

            setTotalItemsProcessed(totalProducts);
            _logger.LogInfo(LogEntryType.ProductFileUploadWorker, string.Format("Uploading {0} products initiated by {1}", totalProducts, _systemJob.SubmittedBy));

            try
            {
                var retValue = 0;
                foreach (var eisProduct in eisProducts)
                {
                    // get the product EIS SKU
                    var eisSKU = eisProduct.EisSKU;
                    if (!isCreateNew && string.IsNullOrEmpty(eisSKU))
                    {
                        continue;
                    }

                    // update the EIS Product details if there's any
                    if (eisProduct.HasAnyChanges)
                    {
                        var isUpdate = true;
                        if (string.IsNullOrEmpty(eisSKU) && isCreateNew)
                        {
                            eisSKU   = repository.GetNextEisSKUForCompany(eisProduct.CompanyId);
                            isUpdate = false;
                        }

                        eisProduct.EisSKU = eisSKU;
                        retValue          = repository.DoUpadateOrInsertProduct(eisProduct, isUpdate, _systemJob.SubmittedBy);
                    }

                    // then update the Amazon product details, if there's any
                    var amazonModel = amazonProducts.FirstOrDefault(x => x.EisSKU == eisProduct.EisSKU);
                    if (amazonModel != null && amazonModel.HasAnyChanges)
                    {
                        // set the EIS SKU for the product Amzon
                        amazonModel.EisSKU = eisSKU;
                        retValue           = repository.DoUpdateOrInsertAmazon(amazonModel, _systemJob.SubmittedBy);
                    }

                    // update eBay product details, if there's any
                    var eBayModel = eBayProducts.FirstOrDefault(x => x.EisSKU == eisProduct.EisSKU);
                    if (eBayModel != null && eBayModel.HasAnyChanged)
                    {
                        // set the EIS SKU for the product eBay
                        eBayModel.EisSKU = eisSKU;
                        retValue         = repository.DoUpadateOrInserteBay(eBayModel, _systemJob.SubmittedBy);
                    }

                    // lastly, update the bigCommerce details, if there's any changed
                    var bigCommerce = bigCommerceProucts.FirstOrDefault(x => x.EisSKU == eisProduct.EisSKU);
                    if (bigCommerce != null && bigCommerce.HasAnyChanged)
                    {
                        // set the EIS SKU for this model
                        bigCommerce.EisSKU = eisSKU;
                        retValue           = repository.DoUpdateOrInsertBigCommerce(bigCommerce, _systemJob.SubmittedBy);
                    }

                    affectedProducts += retValue;
                    _bw.ReportProgress(affectedProducts);
                    var percentage = (((double)affectedProducts) / totalProducts) * 100.00;
                    Console.WriteLine(string.Format("{1:#0.00}% Updating EIS/Amazon Product EisSKU: {0}", eisProduct.EisSKU, percentage));
                }

                // close the repo db connection
                repository.CloseDbConnection();
            }
            catch (DbEntityValidationException ex)
            {
                _hasError = true;
                _logger.LogError(LogEntryType.ProductFileUploadWorker, EisHelper.ParseDbEntityValidationException(ex), ex.StackTrace);
                _jobRepository.UpdateSystemJobStatus(_systemJob.Id, JobStatus.Failed);
            }
            catch (Exception ex)
            {
                _hasError = true;
                _logger.LogError(LogEntryType.ProductFileUploadWorker,
                                 string.Format("Error in uploading products. <br/> Error message: {0}", EisHelper.GetExceptionMessage(ex)),
                                 ex.StackTrace);
                _jobRepository.UpdateSystemJobStatus(_systemJob.Id, JobStatus.Failed);
            }

            _logger.LogInfo(LogEntryType.ProductFileUploadWorker, string.Format("{0} products have been successfully uploaded by {1}", affectedProducts, _systemJob.SubmittedBy));
        }
Esempio n. 29
0
        public int DoUpadateOrInsertVendorProduct(VendorProduct model, bool isToUpdate, string submittedBy)
        {
            try
            {
                // NEED TO CREATE NEW DB CONTEXT SINCE THIS METHOD IS SHARED TO CONSOLE SERVICES
                using (var context = new EisInventoryContext())
                {
                    if (isToUpdate)
                    {
                        // get the existing vendor product
                        var product = context.vendorproducts.FirstOrDefault(x => x.EisSupplierSKU == model.EisSupplierSKU);
                        if (product == null)
                        {
                            return(0);
                        }

                        // set the new quantity for this vendor product
                        if (model.IsQuantitySet)
                        {
                            // get the number of order items which are Unshipped/Pending for this item
                            var pendingQtyOrders = context.orderproducts.Where(x => x.EisSupplierSKU == model.EisSupplierSKU)
                                                   .Join(context.orderitems,
                                                         op => op.OrderItemId,
                                                         oi => oi.OrderItemId,
                                                         (op, oi) => new { OrderProduct = op, OrderItem = oi })
                                                   .Join(context.orders.Where(x => x.OrderStatus == OrderStatus.Unshipped || x.OrderStatus == OrderStatus.Pending),
                                                         ooi => ooi.OrderItem.OrderId,
                                                         o => o.OrderId,
                                                         (ooi, o) => new { ooi.OrderProduct })
                                                   .Select(x => x.OrderProduct)
                                                   .DefaultIfEmpty <orderproduct>()
                                                   .Sum(x => (x == null ? 0 : x.Quantity));

                            // deduct the availability for this item with its pending orders
                            product.Quantity = model.Quantity - pendingQtyOrders;
                        }

                        if (model.Name != null)
                        {
                            product.Name = model.Name;
                        }
                        if (model.Description != null)
                        {
                            product.Description = model.Description;
                        }
                        if (model.IsSupplierPriceSet)
                        {
                            product.SupplierPrice = model.SupplierPrice;
                        }
                        if (model.IsMinPackSet)
                        {
                            product.MinPack = model.MinPack;
                        }
                        if (model.UPC != null)
                        {
                            product.UPC = model.UPC;
                        }
                        if (model.Category != null)
                        {
                            product.Category = model.Category;
                        }
                        if (model.Weight != null)
                        {
                            product.Weight = model.Weight;
                        }
                        if (model.WeightUnit != null)
                        {
                            product.WeightUnit = model.WeightUnit;
                        }
                        if (model.Shipping != null)
                        {
                            product.Shipping = model.Shipping;
                        }
                        if (model.VendorMOQ != null)
                        {
                            product.VendorMOQ = model.VendorMOQ;
                        }
                        if (model.VendorMOQType != null)
                        {
                            product.VendorMOQType = model.VendorMOQType;
                        }
                        if (model.IsAutoLinkToEisSKUSet)
                        {
                            product.IsAutoLinkToEisSKU = model.IsAutoLinkToEisSKU;
                        }

                        product.Modified   = DateTime.UtcNow;
                        product.ModifiedBy = submittedBy;
                        context.SaveChanges();

                        // let's set some properties; assuming that only EisSupplierSKU is supplied
                        // these data will be used when creating new EisSKU
                        model.Name             = product.Name;
                        model.Description      = product.Description;
                        model.ShortDescription = product.ShortDescription;
                        model.Category         = product.Category;
                        model.UPC         = product.UPC;
                        model.SubmittedBy = submittedBy;
                    }
                    else
                    {
                        var product = new vendorproduct();
                        CopyObject.CopyFields(model, product);
                        product.Created   = DateTime.UtcNow;
                        product.CreatedBy = submittedBy;

                        // add it to the context and save
                        context.vendorproducts.Add(product);
                        context.SaveChanges();
                    }
                    UpdateVendorProductImages(model.Images, model.EisSupplierSKU);
                }
                return(1);
            }
            catch (DbEntityValidationException ex)
            {
                var errorMsg = EisHelper.ParseDbEntityValidationException(ex);
                _logger.LogError(LogEntryType.VendorProductFileUploadWorker, errorMsg, ex.StackTrace);
                return(0);
            }
            catch (Exception ex)
            {
                _logger.LogError(LogEntryType.VendorProductFileUploadWorker,
                                 string.Format("Error in updating vendor product details -> SupplierSKU: {0} VendorId: {1}. <br/>Error message: {2}",
                                               model.SupplierSKU, model.VendorId, EisHelper.GetExceptionMessage(ex)),
                                 ex.StackTrace);
                return(0);
            }
        }
Esempio n. 30
0
        protected override void bw_DoWork(object sender, DoWorkEventArgs e)
        {
            if (_isWorkerExecuted)
            {
                return;
            }

            // set the flag the this bw_DoWork has already called
            _isWorkerExecuted = true;
            var totalProcessed = 0;
            var affectedRows   = 0;

            // parsed the vendor product data from the file
            var vendorProducts = new List <VendorProduct>();
            var message        = CsvFileDataParser.ParseVendorProductFile(_systemJob.Parameters, vendorProducts, _systemJob.HasHeader);

            // get the total items and update the system job status
            var totalItems = vendorProducts.Count;

            setTotalItemsProcessed(totalItems);
            _logger.LogInfo(LogEntryType.VendorProductFileUploadWorker, string.Format("Uploading {0} products initiated by {1}", totalItems, _systemJob.SubmittedBy));

            try
            {
                // iterate and do insert or update vendor product data
                foreach (var vendorProduct in vendorProducts)
                {
                    totalProcessed++;
                    var percentage = (((double)totalProcessed) / totalItems) * 100.00;

                    // get first the vendor product SKU
                    var eisSupplierSKU = _service.GetVendorProductSKU(vendorProduct);
                    vendorProduct.EisSupplierSKU = eisSupplierSKU;

                    // continue if it is not to create new item and its eisSupplierSKU is NULL
                    if (!_systemJob.IsAddNewItem && string.IsNullOrEmpty(eisSupplierSKU))
                    {
                        Console.WriteLine(string.Format("{1:#0.00}% No vendor product updated!", vendorProduct.EisSupplierSKU, percentage));
                        continue;
                    }

                    var isToUpdate = true;
                    if (string.IsNullOrEmpty(eisSupplierSKU))
                    {
                        // get the start SKU code for this vendor
                        var startSkuCode = _service.GetVendorStartSku(vendorProduct.VendorId);
                        vendorProduct.EisSupplierSKU = string.Format("{0}{1}", startSkuCode, vendorProduct.SupplierSKU.Trim());
                        isToUpdate = false;
                    }

                    // do insert or update vendor product
                    affectedRows += _service.DoUpadateOrInsertVendorProduct(vendorProduct, isToUpdate, _systemJob.SubmittedBy);
                    var uploadResultType = UploadResultType.NoChanges;
                    var newEisSKU        = string.Empty;

                    // the IsAutoLinkToEisSKU field from the vendor product is the highest precedendens over on the HasPostAction_2 and HasPostAction_1
                    if (vendorProduct.IsAutoLinkToEisSKUSet)
                    {
                        if (vendorProduct.IsAutoLinkToEisSKU)
                        {
                            // update the current link of this vendor product
                            uploadResultType = _service.UpdateEisProductLinks(vendorProduct.EisSupplierSKU, vendorProduct.UPC, vendorProduct.MinPack);
                        }
                        else
                        {
                            // delete the existing product links if there's any
                            _service.DeleteOldVendorProductLinks(vendorProduct.EisSupplierSKU, new List <string>());
                            uploadResultType = UploadResultType.DeletedLink;
                        }
                    }
                    else
                    {
                        // check first if we want to auto-link and create new EIS product if it doesn't exist
                        if (_systemJob.HasPostAction_2 && !string.IsNullOrEmpty(vendorProduct.UPC))
                        {
                            newEisSKU        = _service.AddLinkAndCreateEisProductIfNoMatchWithUPC(vendorProduct);
                            uploadResultType = string.IsNullOrEmpty(newEisSKU) ? UploadResultType.UpdatedItem : UploadResultType.NewItemCreated;
                        }

                        // check if there's a need to auto-link this vendor product with EIS product
                        if (_systemJob.HasPostAction_1 && !_systemJob.HasPostAction_2 && !string.IsNullOrEmpty(vendorProduct.UPC))
                        {
                            uploadResultType = _service.UpdateEisProductLinks(vendorProduct.EisSupplierSKU, vendorProduct.UPC, vendorProduct.MinPack);
                        }
                    }

                    // add the EisSupplierSKU for the upload result tracking
                    addUploadFileResult(vendorProduct.EisSupplierSKU, newEisSKU, uploadResultType);

                    _bw.ReportProgress(affectedRows);
                    Console.WriteLine(string.Format("{1:#0.00}% Updating vendor products EisSupplierSKU: {0}", vendorProduct.EisSupplierSKU, percentage));
                }
            }
            catch (DbEntityValidationException ex)
            {
                _hasError = true;
                _logger.LogError(LogEntryType.VendorProductFileUploadWorker, EisHelper.ParseDbEntityValidationException(ex), ex.StackTrace);
                _jobRepository.UpdateSystemJobStatus(_systemJob.Id, JobStatus.Failed);
            }
            catch (Exception ex)
            {
                _hasError = true;
                _logger.LogError(LogEntryType.VendorProductFileUploadWorker,
                                 string.Format("Error in uploading vendor products. <br/> Error message: {0}", EisHelper.GetExceptionMessage(ex)),
                                 ex.StackTrace);
                _jobRepository.UpdateSystemJobStatus(_systemJob.Id, JobStatus.Failed);
            }

            _logger.LogInfo(LogEntryType.VendorProductFileUploadWorker, string.Format("{0} vendor products have been successfully uploaded by {1}", totalProcessed, _systemJob.SubmittedBy));
        }