public FindResult<ProductListItem> GetAllProductListItems(ProductFilterOption filterOption)
        {
            FindResult<ProductListItem> result = new FindResult<ProductListItem>() { Success = false };

            try
            {

                using (InnoventoryDBContext dbContext = new InnoventoryDBContext())
                {
                    List<ProductListItem> productListItems = (from pr in dbContext.ProductSet.ToList()
                                                              join catSubCatMap in dbContext.CategorySubCategoryMapSet.ToList()
                                                              on pr.CategorySubCategoryMapId equals catSubCatMap.CategorySubCategoryMapId
                                                              join category in dbContext.CategorySet.ToList()
                                                              on catSubCatMap.CategoryId equals category.CategoryId
                                                              join subCategory in dbContext.SubCategorySet
                                                              on catSubCatMap.SubCategoryId equals subCategory.SubCategoryId
                                                              select new ProductListItem
                                                              {
                                                                  CategoryId = category.CategoryId,
                                                                  CategoryName = category.CategoryName,
                                                                  Description = pr.Description,
                                                                  ImageId = pr.ImageId,
                                                                  ItemType = pr.ItemType,
                                                                  ProductName = pr.ProductName,
                                                                  SubCategoryId = subCategory.SubCategoryId,
                                                                  SubCategoryName = subCategory.SubCategoryName,
                                                                  ProductId = pr.ProductId

                                                              }).ToList();

                    if (!string.IsNullOrEmpty(filterOption.SearchString) && filterOption.SearchString.Trim() != string.Empty)
                    {
                        productListItems = productListItems.Where(x => x.ProductName.Contains(filterOption.SearchString)).ToList();

                    }

                    if (filterOption.CategoryId != Guid.Empty)
                    {
                        productListItems = productListItems.Where(x => x.CategoryId == filterOption.CategoryId).ToList();
                    }

                    if (filterOption.SubCategoryId != Guid.Empty)
                    {
                        productListItems = productListItems.Where(x => x.SubCategoryId == filterOption.SubCategoryId).ToList();
                    }

                    result.Entities = productListItems.OrderBy(x => x.ProductName).ToList();
                }

                result.Success = true;

            }
            catch (Exception ex)
            {
                result.Success = false;
                throw;
            }

            return result;
        }
        public FindResult<SubCategoryViewModel> GetAllSubcategoriesByCategory(Guid id)
        {
            FindResult<SubCategoryViewModel> entityResult = new FindResult<SubCategoryViewModel>() { Success = false };

            List<SubCategoryViewModel> subCategories = new List<SubCategoryViewModel>();

            using (InnoventoryDBContext dbContext = new InnoventoryDBContext())
            {
                var query = from c in dbContext.CategorySet
                            join csbmap in dbContext.CategorySubCategoryMapSet
                            on c.CategoryId equals csbmap.CategoryId
                            join sb in dbContext.SubCategorySet
                            on csbmap.SubCategoryId equals sb.SubCategoryId
                            where c.CategoryId == id
                            select sb;

                foreach (var item in query)
                {
                    subCategories.Add(ObjectMapper.PropertyMap(item, new SubCategoryViewModel()));
                }

                entityResult.Entities = subCategories;
                entityResult.Success = true;
            }

            return entityResult;
        }
        public FindResult<ProductAttributeViewModel> Find(Func<ProductAttributeViewModel, bool> predicate)
        {
            FindResult<ProductAttributeViewModel> productFindResult = null;

            using (InnoventoryDBContext dbContext = new InnoventoryDBContext())
            {

                productFindResult = productAttributeRepository.FindBy(dbContext, predicate);

                if (!productFindResult.Success)
                {
                    return productFindResult;

                }

                return SetFindResult(productFindResult, dbContext);
            }
        }
        public List<CategoryViewModel> GetCategories(InnoventoryDBContext dbContext, Guid guid)
        {
            List<CategoryViewModel> retResult = new List<CategoryViewModel>();

            var query = from category in dbContext.CategorySet.ToList()
                        join map in dbContext.CategorySubCategoryMapSet.ToList()
                        on category.CategoryId equals map.CategoryId
                        join sc in dbContext.SubCategorySet.ToList()
                        on map.SubCategoryId equals sc.SubCategoryId
                        where (sc.SubCategoryId == guid)
                        select category;

            foreach (var item in query)
            {
                CategoryViewModel cvm = new CategoryViewModel();

                ObjectMapper.PropertyMap(item, cvm);

                retResult.Add(cvm);
            }

            return retResult;
        }
        public GetEntityResult<ViewModels.SalesOrderViewModel> GetSalesOrder(Guid salesOrderId)
        {
            GetEntityResult<SalesOrderViewModel> salesOrderResult = new GetEntityResult<SalesOrderViewModel>
            {
                Success = false,

            };

            using (InnoventoryDBContext dbContext = new InnoventoryDBContext())
            {

                salesOrderResult = salesOrderRepository.FindById(dbContext, salesOrderId);

                if (!salesOrderResult.Success || salesOrderResult.Entity == null)
                {
                    return salesOrderResult;
                }

                SalesOrderViewModel salesOrder = salesOrderResult.Entity;

                salesOrderResult.Entity.SaleOrderItems = new List<SalesOrderItemViewModel>();

                FindResult<SalesOrderItemViewModel> salesOrderItemsResult = salesOrderItemRepository.FindBy(dbContext, x => x.SalesOrderId == salesOrder.SalesOrderId);

                if (!salesOrderItemsResult.Success || salesOrderItemsResult.Entities.Count == 0)
                {
                    return salesOrderResult;
                }

                salesOrderResult.Entity.SaleOrderItems = salesOrderItemsResult.Entities;

                salesOrderResult.Success = true;
            }

            return salesOrderResult;
        }
        public GetEntityResult<PurchaseOrderViewModel> GetPurchaseOrder(Guid purchaseOrderId)
        {
            GetEntityResult<PurchaseOrderViewModel> purchaseOrderResult = new GetEntityResult<PurchaseOrderViewModel>
            {
                Success = false,

            };

            using (InnoventoryDBContext dbContext = new InnoventoryDBContext())
            {

                purchaseOrderResult = purchaseOrderRepository.FindById(dbContext, purchaseOrderId);

                if (!purchaseOrderResult.Success || purchaseOrderResult.Entity == null)
                {
                    return purchaseOrderResult;
                }

                PurchaseOrderViewModel purchaseOrder = purchaseOrderResult.Entity;

                purchaseOrderResult.Entity.PurchaseOrderItems = new List<PurchaseOrderItemViewModel>();

                FindResult<PurchaseOrderItemViewModel> purchaseOrderItemsResult = purchaseOrderItemRepository.FindBy(dbContext, x => x.PurchaseOrderId == purchaseOrder.PurchaseOrderId);

                if (!purchaseOrderItemsResult.Success || purchaseOrderItemsResult.Entities.Count == 0)
                {
                    return purchaseOrderResult;
                }

                purchaseOrderResult.Entity.PurchaseOrderItems = purchaseOrderItemsResult.Entities;

                purchaseOrderResult.Success = true;
            }

            return purchaseOrderResult;
        }
        public ExternalOrderShippedResult SetExternalOrderShipped(ApiOrderShipmentRequest orderShipmentRequest)
        {
            ExternalOrderShippedResult shippedResult = new ExternalOrderShippedResult();

            shippedResult = new ExternalOrderClient().SetOrdersShipped(orderShipmentRequest);

            try
            {
                if (shippedResult != null && shippedResult.ShippingResults.Count > 0)
                {
                    using (InnoventoryDBContext dbContext = new InnoventoryDBContext())
                    {
                        DbSet<ExternalOrder> externalOrderSet = dbContext.ExternalOrderSet;

                        foreach (ShippingResult shippingResult in shippedResult.ShippingResults)
                        {

                            ExternalOrder shippedOrder = externalOrderSet.Where(x => x.StoreOrderHeaderId == shippingResult.ExternalOrderHeaderId).FirstOrDefault();

                            if (shippedOrder != null)
                            {

                                if (shippingResult.Success)
                                {
                                    try
                                    {
                                        shippedOrder.ShippedDate = shippingResult.ShippedDate.Value;
                                        shippedOrder.OrderStatus = (int)StoreOrderStatusEnum.Shipped;

                                        shippedOrder.StoreOrderStatus = StoreOrderStatusEnum.Shipped.ToString();

                                        externalOrderSet.Attach(shippedOrder);

                                        dbContext.Entry(shippedOrder).State = EntityState.Modified;

                                        dbContext.SaveChanges();
                                    }
                                    catch(DbEntityValidationException dbEx)
                                    {
                                        string errorMessage = string.Join("; ", dbEx.EntityValidationErrors);
                                        shippedResult.ErrorMessage = shippedResult.ErrorMessage + "; " + errorMessage;
                                    }
                                }

                            }

                        }

                    }

                    shippedResult.Success = true;
                }
            }

            catch (Exception ex)
            {

                shippedResult.ErrorMessage = shippedResult.ErrorMessage + "; " +ex.Message;
                shippedResult.Success = false;
            }

            return shippedResult;
        }
        public EntityOperationResultBase SaveExternalOrder(List<ExternalOrder> orders)
        {
            EntityOperationResultBase updateResult = new EntityOperationResultBase() { Success = false };
            try
            {
                using (InnoventoryDBContext dbContext = new InnoventoryDBContext())
                {
                    DbSet<ExternalOrder> externalOrderSet = dbContext.ExternalOrderSet;

                    foreach (var order in orders)
                    {

                        ExternalOrder existingOrder = externalOrderSet.Where(x => x.StoreProviderOrderId == order.StoreProviderOrderId).FirstOrDefault();

                        if (existingOrder == null)
                        {
                            order.OrderStatus = (int)StoreOrderStatusEnum.Unshipped;
                            order.StoreOrderHeaderId = Guid.NewGuid();
                            order.ShippedDate = null;
                            order.JsonShippingAddress = JsonConvert.SerializeObject(order.ShippingAddress);
                            dbContext.ExternalOrderSet.Add(order);

                            foreach (var lineItem in order.ExternalOrderLineItems)
                            {
                                lineItem.ExternalOrderLineItemId = Guid.NewGuid();
                                lineItem.StoreOrderId = order.StoreOrderHeaderId;
                                dbContext.ExternalOrderLineItemSet.Add(lineItem);

                            }

                            dbContext.SaveChanges();
                        }
                    }

                    updateResult.Success = true;
                }
            }
            catch (DbEntityValidationException dbEx)
            {
                var errorMessages = dbEx.EntityValidationErrors
                        .SelectMany(x => x.ValidationErrors)
                        .Select(x => x.ErrorMessage);

                // Join the list to a single string.
                var fullErrorMessage = string.Join("; ", errorMessages);

                // Combine the original exception message with the new one.
                var exceptionMessage = string.Concat(" The validation errors are: ", fullErrorMessage);
                updateResult.Success = false;
                updateResult.ErrorMessage = exceptionMessage;
            }
            catch (Exception ex)
            {
                string ErrorMessage = string.Format("An error {0} occurred while saving changes to database",
                                   ex.Message);
                updateResult.Success = false;
                updateResult.ErrorMessage = ErrorMessage;
            }

            return updateResult;
        }
        public List<ProductVariantAttributeValueViewModel> GetProductVariantAttributeValueVMS(InnoventoryDBContext dbContext, Guid productVariantId)
        {
            var ProductVariantAttributeValues = (from pv in dbContext.ProductVariantAttributeValueSet
                                                 join avl in dbContext.AttributeValueListSet on pv.AttributeValueListId equals avl.AttributeValueListId
                                                 join subcatAttrMap in dbContext.SubCategoryAttributeMapSet
                                                 on avl.SubCategoryAttributeMapID equals subcatAttrMap.SubCategoryAttributeMapId
                                                 join productAttributs in dbContext.ProductAttributeSet
                                                 on subcatAttrMap.ProductAttributeId equals productAttributs.ProductAttributeId
                                                 where pv.ProductVariantId == productVariantId
                                                 select new ProductVariantAttributeValueViewModel
                                                 {
                                                     ProductVariantId = pv.ProductVariantId,
                                                     AttributeValueListId = avl.AttributeValueListId,
                                                     ProductAttributeName = productAttributs.AttributeName,
                                                     ProductAttributeValue = avl.AttributeValue
                                                 }).ToList();

            return ProductVariantAttributeValues;
        }
        private bool AddUpdateCategorySubCategoryMapRepo(SubCategoryViewModel viewModel)
        {
            using (InnoventoryDBContext dbContext = new InnoventoryDBContext())
            {
                using (DbContextTransaction transaction = dbContext.Database.BeginTransaction())
                {

                    DbSet<SubCategory> subCategorySet = dbContext.SubCategorySet;
                    SubCategory subCategory = new SubCategory();
                    ObjectMapper.PropertyMap(viewModel, subCategory);

                    FindResult<CategoryViewModel> categoryResult = categoryRepository.GetAll(dbContext);

                    FindResult<CategorySubCategoryMapViewModel> mapResult = categorySubCategoryMapRepo.FindBy(x => x.SubCategoryId == viewModel.SubCategoryId);

                    List<CategorySubCategoryMapViewModel> existingMappings = new List<CategorySubCategoryMapViewModel>();

                    existingMappings = mapResult.Entities;

                    List<Guid> deletionList = new List<Guid>();

                    List<Guid> newAdded = new List<Guid>();

                    foreach (var emapvm in existingMappings)
                    {
                        if (!viewModel.CategoryIds.Contains(emapvm.CategoryId))
                        {
                            deletionList.Add(emapvm.CategorySubCategoryMapId);
                        }
                    }

                    if (viewModel.CategoryIds != null && viewModel.CategoryIds.Count > 0)
                    {

                        foreach (var cId in viewModel.CategoryIds)
                        {
                            CategorySubCategoryMapViewModel existingMap = existingMappings.FirstOrDefault(x => x.SubCategoryId == viewModel.SubCategoryId && x.CategoryId == cId);

                            if (existingMap == null)
                            {
                                newAdded.Add(cId);
                            }
                        }

                    }

                    if (deletionList.Count > 0)
                    {
                        foreach (Guid mapid in deletionList)
                        {
                            categorySubCategoryMapRepo.Delete(mapid);
                        }
                    }

                    if (newAdded.Count > 0)
                    {
                        foreach (Guid categoryId in newAdded)
                        {
                            CategorySubCategoryMapViewModel catSubCatMapVM = new CategorySubCategoryMapViewModel
                            {

                                CategorySubCategoryMapId = Guid.Empty,
                                CategoryId = categoryId,
                                SubCategoryId = viewModel.SubCategoryId,

                            };

                            categorySubCategoryMapRepo.Update(dbContext, catSubCatMapVM);
                        }
                    }

                    subCategorySet.Attach(subCategory);

                    dbContext.Entry<SubCategory>(subCategory).State = EntityState.Modified;

                    dbContext.SaveChanges();

                    transaction.Commit();
                }
            }

            return true;
        }
        public ExternalOrderViewModelResult GetExternalOrders(OrderSearchOptions orderSearchOptions)
        {
            ExternalOrderViewModelResult result = new ExternalOrderViewModelResult()
            {
                Success = false,
                ExternalOrderViewModels = new List<ExternalOrderViewModel>(),
            };

            DateTime fromDate = orderSearchOptions.FromDate;
            DateTime toDate = orderSearchOptions.ToDate;

            DbSet<ExternalOrder> externalOrderSet = new InnoventoryDBContext().ExternalOrderSet;

            DateTime from = Utility.ConvertToGMT(fromDate);

            DateTime to = Utility.ConvertToGMT(toDate);

            int storeType = (int)orderSearchOptions.StoreProvider;

            var dbExternalOrders = externalOrderSet.Where(x => x.OrderDate >= from && x.OrderDate <= to && x.StoreProviderId == storeType).OrderByDescending(y => y.OrderDate).ToList();

            if (dbExternalOrders.Count > 0)
            {
                foreach (var order in dbExternalOrders)
                {
                    ExternalOrderViewModel vm = new ExternalOrderViewModel(order);

                    result.ExternalOrderViewModels.Add(vm);
                }
            }
            else
            {
                result.ErrorMessage = "No unshipped orders found...";
            }

            return result;
        }
        private bool IsAttributeNameDuplicate(ProductAttributeViewModel productAttribute)
        {
            using (InnoventoryDBContext dbContext = new InnoventoryDBContext())
            {

                FindResult<ProductAttributeViewModel> findResult = productAttributeRepository.FindBy(dbContext, x => x.AttributeName == productAttribute.AttributeName);

                if (findResult.Success && findResult.Entities.Count > 0)
                {

                    if (findResult.Entities.FirstOrDefault().ProductAttributeId != productAttribute.ProductAttributeId)
                    {
                        return true;
                    }

                }

            }

            return false;
        }
        public UpdateResult<ProductAttributeViewModel> UpdateProductAttribute(ProductAttributeViewModel productAttribute)
        {
            UpdateResult<ProductAttributeViewModel> updateResult = new UpdateResult<ProductAttributeViewModel>();

            updateResult.Entity = productAttribute;

            List<AttributeSubCategorySelection> selectedSubCategories = productAttribute.SubCategorySelections.Where(x => x.IsSelected).ToList();

            if (selectedSubCategories.Count == 0)
            {
                updateResult.Success = false;
                updateResult.ErrorMessage = "Please select at least one Sub Category";

                return updateResult;
            }

            if (string.IsNullOrEmpty(productAttribute.AttributeName))
            {
                updateResult.ErrorMessage = "Please enter a valid attribute name";
                return updateResult;
            }

            if (IsAttributeNameDuplicate(productAttribute))
            {
                updateResult.ErrorMessage = "Attribute Name already exist";

                return updateResult;
            }

            using (InnoventoryDBContext dbContext = new InnoventoryDBContext())
            {
                using (DbContextTransaction trans = dbContext.Database.BeginTransaction())
                {

                    if (productAttribute.ProductAttributeId != Guid.Empty)
                    {

                        FindResult<SubCategoryAttributeMapViewModel> subCategoryAttributeMapVMResult = subCategoryAttributeMapRepository.FindBy(x => x.ProductAttributeId == productAttribute.ProductAttributeId);

                        List<Guid> existingSubCategoryIds = subCategoryAttributeMapVMResult.Entities.Select(x => x.SubCategoryId).ToList();

                        if (!subCategoryAttributeMapVMResult.Success)
                        {
                            updateResult.ErrorMessage = updateResult.ErrorMessage = string.Format("Can not retrieve existing mappings");
                            return updateResult;
                        }

                        if (subCategoryAttributeMapVMResult.Entities.Count > 0)
                        {
                            foreach (var item in subCategoryAttributeMapVMResult.Entities)
                            {
                                AttributeSubCategorySelection existingSelection = productAttribute.SubCategorySelections
                                        .FirstOrDefault(x => x.SubCategory.SubCategoryId == item.SubCategoryId && x.IsSelected == true);

                                if (existingSelection == null)
                                {
                                    EntityOperationResultBase deleteResult = subCategoryAttributeMapRepository.Delete(dbContext, item.SubCategoryAttributeMapId);

                                    if (deleteResult.Success == false)
                                    {
                                        updateResult.ErrorMessage = updateResult.ErrorMessage = string.Format("Mapping {0} Can not be deleted. Error: {1}", item.SubCategoryAttributeMapId, deleteResult.ErrorMessage);
                                    }
                                }
                            }
                        }

                        foreach (AttributeSubCategorySelection subCategorySelection in selectedSubCategories)
                        {

                            if (!existingSubCategoryIds.Contains(subCategorySelection.SubCategory.SubCategoryId))
                            {

                                SubCategoryAttributeMapViewModel newMapping = new SubCategoryAttributeMapViewModel
                                {
                                    ProductAttributeId = productAttribute.ProductAttributeId,
                                    SubCategoryId = subCategorySelection.SubCategory.SubCategoryId
                                };

                                UpdateResult<SubCategoryAttributeMapViewModel> updMappingResult = subCategoryAttributeMapRepository.Update(dbContext, newMapping);

                                if (!updMappingResult.Success)
                                {
                                    updateResult.Success = false;
                                    updateResult.ErrorMessage = updateResult.ErrorMessage = string.Format("Mapping with {0} Can not be saved", subCategorySelection.SubCategory.SubCategoryName); ;
                                    return updateResult;
                                }

                            }

                        }

                        updateResult = productAttributeRepository.Update(productAttribute);

                    }
                    else
                    {

                        updateResult = productAttributeRepository.Update(productAttribute);

                        if (!updateResult.Success)
                        {
                            return updateResult;
                        }

                        ProductAttributeViewModel updatedModel = updateResult.Entity;

                        foreach (var subCatSelection in selectedSubCategories)
                        {

                            SubCategoryAttributeMapViewModel newMapping = new SubCategoryAttributeMapViewModel
                            {
                                SubCategoryId = subCatSelection.SubCategory.SubCategoryId,
                                ProductAttributeId = updatedModel.ProductAttributeId
                            };

                            UpdateResult<SubCategoryAttributeMapViewModel> newMappingUpdateResult = subCategoryAttributeMapRepository.Update(newMapping);

                            if (!newMappingUpdateResult.Success)
                            {
                                trans.Rollback();
                                updateResult.Success = false;
                                updateResult.ErrorMessage = string.Format("Mapping with {0} Can not be saved", subCatSelection.SubCategory.SubCategoryName);
                                return updateResult;
                            }

                        }

                    }

                    trans.Commit();
                }

                if (updateResult.Success)
                {
                    updateResult.SuccessMessage = "Product Attribute saved successfully";
                }
                //if(findre)

            }

            return updateResult;
        }
        //[Import]
        //private ICategorySubCategoryMapRepository categorySubCategoryMapRepo;
        public FindResult<ProductAttributeViewModel> GetProductAttributes()
        {
            FindResult<ProductAttributeViewModel> findResult = new FindResult<ProductAttributeViewModel>();

            using (InnoventoryDBContext dbContext = new InnoventoryDBContext())
            {
                findResult = productAttributeRepository.GetAll(dbContext);

                if (!findResult.Success)
                {
                    return findResult;
                }

                return SetFindResult(findResult, dbContext);
            }
        }
        public FindResult<CategorySubCategoryAttributeValuesViewModel> GetAllCategorySubCategoryAttributesValueList(Guid categorySubCategoryMapId)
        {
            FindResult<CategorySubCategoryAttributeValuesViewModel> result = new FindResult<CategorySubCategoryAttributeValuesViewModel>();

            using (InnoventoryDBContext dbContext = new InnoventoryDBContext())
            {
                var categorySubCategoryMapResult = dbContext.CategorySubCategoryMapSet.Where(x=>x.CategorySubCategoryMapId == categorySubCategoryMapId).FirstOrDefault();

                Guid categoryId = Guid.Empty;
                Guid subCategoryId = Guid.Empty;

                if(categorySubCategoryMapResult == null)
                {
                    result.Success = false;

                    return result;
                }

                categoryId = categorySubCategoryMapResult.CategoryId;

                subCategoryId = categorySubCategoryMapResult.SubCategoryId;

                var prodAttributes = (from pa in dbContext.ProductAttributeSet
                                     join sca in dbContext.SubCategoryAttributeMapSet
                                     on pa.ProductAttributeId equals sca.ProductAttributeId
                                     where sca.SubCategoryId == subCategoryId
                                     select new CategorySubCategoryAttributeValuesViewModel
                                     {
                                         AttributeName = pa.AttributeName,
                                         ProductAttributeId = pa.ProductAttributeId,
                                          CategorySubCategoryMapId = sca.SubCategoryAttributeMapId,

                                     }).ToList();

                List<AttributeValueList> attributeValueLists = dbContext.AttributeValueListSet.ToList();

                foreach (var pa in prodAttributes)
                {
                    var attributeValueList = (from attvl in attributeValueLists
                                             where attvl.SubCategoryAttributeMapID == pa.CategorySubCategoryMapId
                                             && attvl.CategoryId == categoryId
                                             select new AttributeValueItem
                                             {
                                                 AttributeValue = attvl.AttributeValue,
                                                 AttributeValueListId = attvl.AttributeValueListId
                                             }).ToList();

                    pa.AttributeValues = attributeValueList;
                }

                result.Entities = prodAttributes;

                result.Success = true;

            }

            return result;
        }
Example #16
0
        public FindResult<ProductVariantListItem> GetAllProductVariantListItems(Guid productId)
        {
            FindResult<ProductVariantListItem> result = new FindResult<ProductVariantListItem> { Success = false };

            using (InnoventoryDBContext dbContext = new InnoventoryDBContext())
            {

                var productVariants = (from prv in dbContext.ProductVariantSet
                                       where prv.ProductId == productId
                                       select new ProductVariantListItem
                                       {
                                           ProductVariantId = prv.ProductVariantId,
                                           AvailableQuantity = prv.AvailableQuantity,
                                           BasePrice = prv.BasePrice,
                                           ShelfPrice = prv.ShelfPrice,
                                           SKUCode = prv.SKUCode,
                                       }).ToList();

                foreach (ProductVariantListItem pvm in productVariants)
                {

                    var productVariantAttributeValues = GetProductVariantAttributeValueVMS(dbContext, pvm.ProductVariantId);

                    if (productVariantAttributeValues.Count > 0)
                    {
                        StringBuilder sb = new StringBuilder();

                        foreach (var item in productVariantAttributeValues)
                        {
                            sb.AppendFormat("{0}: {1}; ", item.ProductAttributeName, item.ProductAttributeValue);
                            sb.Append(" ");
                        }

                        string formattedAttributeValues = sb.ToString().Trim();

                        if (formattedAttributeValues.EndsWith(";"))
                        {
                            formattedAttributeValues = formattedAttributeValues.Substring(0, formattedAttributeValues.Length - 1);
                        }

                        pvm.AttributeValuesString = formattedAttributeValues;
                    }

                }

                result.Entities = productVariants;
            }

            result.Success = true;

            return result;
        }
Example #17
0
        public UpdateResult<ProductViewModel> SaveProduct(ProductViewModel productViewModel)
        {
            UpdateResult<ProductViewModel> result = new UpdateResult<ProductViewModel>() { Success = false };

            Guid categoryId = productViewModel.CategorySubCategoryMap.CategoryId;
            Guid subCategoryId = productViewModel.CategorySubCategoryMap.SubCategoryId;

            using (InnoventoryDBContext dbContext = new InnoventoryDBContext())
            {
                try
                {

                    UpdateResult<ProductViewModel> updateResult = productRepository.Update(dbContext, productViewModel);

                    if (!updateResult.Success)
                    {
                        return updateResult;
                    }

                    foreach (ProductVariantViewModel prvm in productViewModel.ProductVariants)
                    {

                        prvm.ProductId = updateResult.Entity.ProductId;

                        ProductVariant pv = dbContext.ProductVariantSet.Where(x => x.ProductVariantId == prvm.ProductVariantId).FirstOrDefault();

                        if (pv == null)
                        {
                            prvm.ProductVariantId = Guid.Empty;
                        }

                        UpdateResult<ProductVariantViewModel> pvUpdateResult = productVariantRepository.Update(prvm);

                        if (!pvUpdateResult.Success)
                        {
                            result.Success = false;
                            result.ErrorMessage = pvUpdateResult.ErrorMessage;
                            return result;
                        }

                        List<ProductVariantAttributeValue> productVariantAttributeValueMaps = dbContext.ProductVariantAttributeValueSet
                                            .Where(x => x.ProductVariantId == prvm.ProductVariantId).ToList();

                        List<Guid> attributeSelectValueIds = new List<Guid>();

                        foreach (var item in prvm.ProductVariantAttributeValues)
                        {
                            if (item.ProductAttributeId != Guid.Empty)
                            {

                                if ((!item.AttributeValueListId.HasValue
                                     || item.AttributeValueListId.Value == Guid.Empty)
                                     && !string.IsNullOrEmpty(item.ProductAttributeValue))
                                {
                                    SubCategoryAttributeMap scAttrMap = dbContext.SubCategoryAttributeMapSet
                                        .Where(x => x.ProductAttributeId == item.ProductAttributeId && x.SubCategoryId == subCategoryId).FirstOrDefault();

                                    AttributeValueList avl = new AttributeValueList()
                                    {

                                        AttributeValueListId = Guid.NewGuid(),
                                        AttributeValue = item.ProductAttributeValue,
                                        CategoryId = categoryId,
                                        SubCategoryAttributeMapID = scAttrMap.SubCategoryAttributeMapId,
                                    };

                                    dbContext.AttributeValueListSet.Add(avl);

                                    item.AttributeValueListId = avl.AttributeValueListId;

                                    ProductVariantAttributeValue newPVAttrValue = new ProductVariantAttributeValue()
                                    {
                                        ProductVariantId = prvm.ProductVariantId,
                                        AttributeValueListId = item.AttributeValueListId.Value,
                                    };

                                    dbContext.ProductVariantAttributeValueSet.Add(newPVAttrValue);
                                    dbContext.SaveChanges();

                                }
                                else if (item.AttributeValueListId.HasValue && item.AttributeValueListId != Guid.Empty && !string.IsNullOrEmpty(item.ProductAttributeValue))
                                {
                                    ProductVariantAttributeValue pvAttrValue = productVariantAttributeValueMaps
                                                        .Where(x => x.AttributeValueListId == item.AttributeValueListId.Value)
                                                        .FirstOrDefault();

                                    if (pvAttrValue != null)
                                    {
                                        productVariantAttributeValueMaps.Remove(pvAttrValue);
                                    }
                                    else
                                    {
                                        ProductVariantAttributeValue newPVAttrValue = new ProductVariantAttributeValue()
                                        {
                                            ProductVariantId = prvm.ProductVariantId,
                                            AttributeValueListId = item.AttributeValueListId.Value,
                                        };

                                        dbContext.ProductVariantAttributeValueSet.Add(newPVAttrValue);
                                        dbContext.SaveChanges();

                                    }
                                }
                            }

                        }

                        if (productVariantAttributeValueMaps != null && productVariantAttributeValueMaps.Count > 0)
                        {
                            foreach (var pvavm in productVariantAttributeValueMaps)
                            {
                                dbContext.ProductVariantAttributeValueSet.Remove(pvavm);

                            }

                            dbContext.SaveChanges();
                        }
                    }

                    result.Success = true;
                }
                catch (Exception ex)
                {
                    result.Success = false;
                    result.ErrorMessage = ex.Message;
                }
            }

            return result;
        }
        public UpdateResult<ExternalActivity> UpdateExternalActivityDetails(ExternalActivityViewModel externalActivity)
        {
            UpdateResult<ExternalActivity> updateResult = new UpdateResult<ExternalActivity>() { Success = false };

            using (InnoventoryDBContext dbContext = new InnoventoryDBContext())
            {
                DbSet<ExternalActivity> externalActivitySet = dbContext.ExternalActivitySet;

                ExternalActivity existingActivity = externalActivitySet.Where(x => x.StoreProviderType == (int)externalActivity.StoreProviderType
                                                                && x.ExternalActivityType == (int)externalActivity.ExternalActivityType).FirstOrDefault();

                if (existingActivity != null)
                {
                    Guid existingId = existingActivity.ActivityId;

                    existingActivity.ActivityStatus = (int)ExternalActivityStatus.Completed;
                    existingActivity.ExternalActivityType = (int)externalActivity.ExternalActivityType;
                    existingActivity.LastPerformedOn = externalActivity.LastPerformedOn;
                    existingActivity.StoreProviderType = (int)externalActivity.StoreProviderType;
                    externalActivity.UnshippedOrdersCount = externalActivity.UnshippedOrdersCount;

                    externalActivitySet.Attach(existingActivity);

                    dbContext.Entry(existingActivity).State = EntityState.Modified;

                }
                else
                {

                    existingActivity = existingActivity = new ExternalActivity()
                    {
                        ActivityId = Guid.NewGuid(),
                        ActivityStatus = (int)externalActivity.ActivityStatus,
                        ExternalActivityType = (int)externalActivity.ExternalActivityType,
                        LastPerformedOn = externalActivity.LastPerformedOn,
                        StoreProviderType = (int)externalActivity.StoreProviderType,
                    };

                    externalActivitySet.Add(existingActivity);
                }

                dbContext.SaveChanges();
                updateResult.Entity = existingActivity;

            }

            return updateResult;
        }
        public UpdateResult<ExternalOrderViewModel> UpdateExternalOrderShipped(ExternalOrderViewModel order)
        {
            UpdateResult<ExternalOrderViewModel> updateResult = new UpdateResult<ExternalOrderViewModel>();

            using (InnoventoryDBContext dbContext = new InnoventoryDBContext())
            {

                DbSet<ExternalOrder> externalOrderSet = dbContext.ExternalOrderSet;

                ExternalOrder existingOrder = externalOrderSet.Where(x => x.StoreProviderOrderId == order.StoreProviderOrderId).FirstOrDefault();

                if (existingOrder != null)
                {
                    existingOrder.OrderStatus = (int)StoreOrderStatusEnum.Shipped;
                }

            }

            return updateResult;
        }
        private FindResult<ProductAttributeViewModel> SetFindResult(FindResult<ProductAttributeViewModel> findResult, InnoventoryDBContext dbContext)
        {
            //findResult.Success = false;

            FindResult<SubCategoryViewModel> subCategoryResult = subCategoryRepository.GetAll(dbContext);

            FindResult<ProductAttributeViewModel> retResult = new FindResult<ProductAttributeViewModel>();

            retResult.Entities = new List<ProductAttributeViewModel>();

            if (findResult.Success && findResult.Entities.Count > 0)
            {
                foreach (var entity in findResult.Entities)
                {
                    Guid productAttributeId = entity.ProductAttributeId;

                    FindResult<SubCategoryAttributeMapViewModel> subCategoryAttributeMapResult = subCategoryAttributeMapRepository.FindBy(x => x.ProductAttributeId == productAttributeId);

                    List<AttributeSubCategorySelection> subCategorySelections = new List<AttributeSubCategorySelection>();

                    subCategoryResult.Entities.ForEach(x => subCategorySelections.Add(new AttributeSubCategorySelection
                    {
                        SubCategory = x,
                        IsSelected = false,
                    }));

                    subCategorySelections.ForEach(x => x.IsSelected = false);

                    entity.SubCategorySelections = new List<AttributeSubCategorySelection>();

                    entity.SubCategorySelections = subCategorySelections;
                    entity.SubCategoryNames = string.Empty;

                    AttributeSubCategorySelection selection = new AttributeSubCategorySelection();

                    if (subCategoryAttributeMapResult.Success && subCategoryAttributeMapResult.Entities.Count > 0)
                    {
                        foreach (SubCategoryAttributeMapViewModel map in subCategoryAttributeMapResult.Entities)
                        {
                            AttributeSubCategorySelection selectedSubCategory = entity.SubCategorySelections
                                .FirstOrDefault(x => x.SubCategory.SubCategoryId == map.SubCategoryId);

                            selectedSubCategory.IsSelected = true;

                            entity.SubCategoryNames += selectedSubCategory.SubCategory.SubCategoryName + ", ";
                        }
                    }

                    if (entity.SubCategoryNames.Contains(","))
                    {
                        entity.SubCategoryNames = entity.SubCategoryNames.Trim().Substring(0, entity.SubCategoryNames.Trim().Length - 1);
                    }

                    retResult.Entities.Add(entity);
                }

                retResult.Success = true;

            }

            return retResult;
        }
        private void AddCategorySubCategoryMap(InnoventoryDBContext dbContext, SubCategoryViewModel viewModel)
        {
            if (viewModel.CategoryIds != null && viewModel.CategoryIds.Count > 0)
            {
                foreach (Guid categoryId in viewModel.CategoryIds)
                {
                    CategorySubCategoryMapViewModel mapViewModel = new CategorySubCategoryMapViewModel
                    {
                        CategorySubCategoryMapId = Guid.Empty,
                        CategoryId = categoryId,
                        SubCategoryId = viewModel.SubCategoryId,
                    };

                    categorySubCategoryMapRepo.Update(dbContext, mapViewModel);
                }
            }
        }
        private List<CategorySelectionViewModel> GetCategorySelections(Guid subCategoryId)
        {
            List<CategorySelectionViewModel> categorySelections = new List<CategorySelectionViewModel>();

            using (InnoventoryDBContext dbContext = new InnoventoryDBContext())
            {

                List<CategoryViewModel> selectedCategories = GetCategories(dbContext, subCategoryId);

                List<Guid> selectedCategoryIds = selectedCategories.Select(x => x.CategoryId).ToList();

                FindResult<CategoryViewModel> categoryResult = categoryRepository.GetAll();
                List<CategoryViewModel> allCategories = new List<CategoryViewModel>();

                if (categoryResult != null && categoryResult.Success)
                {
                    allCategories = categoryResult.Entities;
                }

                foreach (var category in allCategories)
                {
                    CategorySelectionViewModel selectionViewModel = new CategorySelectionViewModel();

                    selectionViewModel.CategoryVM = category;

                    if (selectedCategoryIds.Contains(category.CategoryId))
                    {
                        selectionViewModel.IsSelected = true;
                    }

                    categorySelections.Add(selectionViewModel);
                }

            }

            return categorySelections;
        }
        private UpdateResult<SubCategoryViewModel> CreateNewSubcategory(SubCategoryViewModel subCategoryViewModel)
        {
            UpdateResult<SubCategoryViewModel> updateResult = new UpdateResult<SubCategoryViewModel>();

            using (InnoventoryDBContext dbContext = new InnoventoryDBContext())
            {

                updateResult = subCategoryRepository.Update(subCategoryViewModel);

                if (updateResult.Success)
                {
                    AddCategorySubCategoryMap(dbContext, subCategoryViewModel);
                }

                updateResult.Success = true;
                updateResult.ErrorMessage = string.Empty;
            }

            return updateResult;
        }
Example #24
0
        public GetEntityResult<ProductViewModel> GetProduct(Guid productId)
        {
            GetEntityResult<ProductViewModel> entityResult = new GetEntityResult<ProductViewModel>();

            using (InnoventoryDBContext dbContext = new InnoventoryDBContext())
            {

                GetEntityResult<ProductViewModel> productResult = productRepository.FindById(dbContext, productId);

                if (!productResult.Success)
                {
                    return productResult;
                }

                var product = productResult.Entity;

                var categorySubCategoryMap = from cscmap in dbContext.CategorySubCategoryMapSet
                                             join c in dbContext.CategorySet on cscmap.CategoryId equals c.CategoryId
                                             join sc in dbContext.SubCategorySet
                                             on cscmap.SubCategoryId equals sc.SubCategoryId
                                             where (cscmap.CategorySubCategoryMapId == product.CategorySubCategoryMapId)
                                             select new CategorySubCategoryMapViewModel
                                             {
                                                 Category = new CategoryViewModel
                                                 {
                                                     CategoryId = c.CategoryId,
                                                     CategoryName = c.CategoryName,
                                                     Description = c.Description,
                                                 },
                                                 CategoryId = c.CategoryId,
                                                 CategorySubCategoryMapId = product.CategorySubCategoryMapId,
                                                 SubCategory = new SubCategoryViewModel
                                                 {
                                                     Description = sc.Description,
                                                     SubCategoryId = sc.SubCategoryId,
                                                     SubCategoryName = sc.SubCategoryName,
                                                 },
                                                 SubCategoryId = sc.SubCategoryId
                                             };

                product.CategorySubCategoryMap = categorySubCategoryMap.FirstOrDefault();

                //if (categorySubCategoryMap != null)
                //{
                //    var category = dbContext.CategorySet.Where(x => x.CategoryId == categorySubCategoryMap.CategoryId).FirstOrDefault();

                //    if (category != null)
                //    {
                //        product.CategoryId = category.CategoryId;
                //        product.CategoryName = category.CategoryName;
                //    }

                //    var subCategory = dbContext.SubCategorySet.Where(x => x.SubCategoryId == categorySubCategoryMap.SubCategoryId).FirstOrDefault();

                //    if (subCategory != null)
                //    {
                //        product.SubCategoryId = subCategory.SubCategoryId;
                //        product.SubCategoryName = subCategory.SubCategoryName;
                //    }

                //}

                FindResult<ProductVariantViewModel> findProductVriantResult = productVariantRepository.FindBy(dbContext, x => x.ProductId == productId);

                if (!findProductVriantResult.Success)
                {
                    entityResult.Success = false;
                    entityResult.ErrorMessage = findProductVriantResult.ErrorMessage;
                    return entityResult;
                }

                List<ProductVariantViewModel> productVariants = findProductVriantResult.Entities;

                product.ProductVariants = productVariants;

                long categoryAttributeCount = 0;

                FindResult<SubCategoryAttributeMapViewModel> subCatAttribMapResult = subCategoryAttributeMapRepository
                                .FindBy(dbContext, x => x.SubCategoryId == product.CategorySubCategoryMap.SubCategoryId);

                if (subCatAttribMapResult.Success && subCatAttribMapResult.Count > 0)
                {

                    categoryAttributeCount = subCatAttribMapResult.Count;

                }
                if (product.ProductVariants != null && product.ProductVariants.Count > 0)
                {
                    foreach (ProductVariantViewModel pvm in product.ProductVariants)
                    {

                        pvm.ProductVariantAttributeValues = (from pv in dbContext.ProductVariantAttributeValueSet
                                                             join avl in dbContext.AttributeValueListSet on pv.AttributeValueListId equals avl.AttributeValueListId
                                                             join subcatAttrMap in dbContext.SubCategoryAttributeMapSet
                                                             on avl.SubCategoryAttributeMapID equals subcatAttrMap.SubCategoryAttributeMapId
                                                             join productAttributs in dbContext.ProductAttributeSet
                                                             on subcatAttrMap.ProductAttributeId equals productAttributs.ProductAttributeId
                                                             where pv.ProductVariantId == pvm.ProductVariantId
                                                             select new ProductVariantAttributeValueViewModel
                                                             {
                                                                 ProductVariantId = pv.ProductVariantId,
                                                                 AttributeValueListId = avl.AttributeValueListId,
                                                                 ProductAttributeName = productAttributs.AttributeName,
                                                                 ProductAttributeValue = avl.AttributeValue,
                                                                 ProductAttributeId = productAttributs.ProductAttributeId,
                                                             }).ToList();

                    }
                }

                FindResult<ProductVariantListItem> pvResult = GetAllProductVariantListItems(product.ProductId);

                if (pvResult.Success)
                {
                    product.ProductVariantListItems = pvResult.Entities;
                }

                entityResult.Entity = product;

                entityResult.Success = true;
            }

            return entityResult;
        }
        public GetEntityResult<ProductAttributeViewModel> FindById(Guid id)
        {
            GetEntityResult<ProductAttributeViewModel> getEntityResult = null;

            using (InnoventoryDBContext dbContext = new InnoventoryDBContext())
            {

                getEntityResult = productAttributeRepository.FindById(dbContext, id);

                if (!getEntityResult.Success)
                {
                    return getEntityResult;
                }

                FindResult<ProductAttributeViewModel> findResult = new FindResult<ProductAttributeViewModel>();

                findResult.Entities.Add(getEntityResult.Entity);

                findResult = SetFindResult(findResult, dbContext);

                getEntityResult.Success = true;

                getEntityResult.Entity = findResult.Entities.FirstOrDefault();
            }

            return getEntityResult;
        }
        public ExternalOrderViewModelResult GetExternalOrdersByProvider(int providerId)
        {
            ExternalOrderViewModelResult result = new ExternalOrderViewModelResult()
            {
                Success = false,
                ExternalOrderViewModels = new List<ExternalOrderViewModel>(),
            };

            using (InnoventoryDBContext dbContext = new InnoventoryDBContext())
            {
                DbSet<ExternalOrder> externalOrderSet = dbContext.ExternalOrderSet;

                DbSet<ExternalOrderLineItem> orderItemSet = dbContext.ExternalOrderLineItemSet;

                var dbExternalOrders = externalOrderSet.Where(x => x.StoreProviderId == providerId && x.OrderStatus == (int)StoreOrderStatusEnum.Unshipped).OrderByDescending(y => y.OrderDate).ToList();

                if (dbExternalOrders.Count > 0)
                {
                    int serialNo = 0;
                    foreach (var order in dbExternalOrders)
                    {
                        serialNo += 1;

                        List<ExternalOrderLineItem> orderItems = orderItemSet.Where(x => x.StoreOrderId == order.StoreOrderHeaderId).ToList();

                        order.ExternalOrderLineItems = orderItems;

                        ExternalOrderViewModel vm = new ExternalOrderViewModel(order);

                        vm.SerialNo = serialNo;

                        result.ExternalOrderViewModels.Add(vm);
                    }

                    result.Success = true;
                }
                else
                {
                    result.ErrorMessage = "No unshipped orders found...";
                }
            }

            return result;
        }
        public FindResult<PurchaseOrderViewModel> SearchPurchaseOrders(PurchaseOrderSearchOptions searchOptions)
        {
            FindResult<PurchaseOrderViewModel> purchaseOrderResult = new FindResult<PurchaseOrderViewModel>
            {
                Entities = new List<PurchaseOrderViewModel>(),
                Success = false,

            };

            using (InnoventoryDBContext dbContext = new InnoventoryDBContext())
            {
                purchaseOrderResult = purchaseOrderRepository.GetAll();

                if (!purchaseOrderResult.Success || purchaseOrderResult.Entities == null || purchaseOrderResult.Entities.Count == 0)
                {
                    return purchaseOrderResult;
                }

                List<PurchaseOrderViewModel> purchaseOrders = purchaseOrderResult.Entities;

                if (searchOptions.FromDate.HasValue)
                {

                    DateTime tDate = searchOptions.FromDate.Value;

                    purchaseOrders = purchaseOrders.Where(x => x.PurchaseOrderDate >= searchOptions.FromDate.Value).ToList();
                }

                if (searchOptions.ToDate.HasValue)
                {

                    purchaseOrders = purchaseOrders.Where(x => x.PurchaseOrderDate <= searchOptions.ToDate.Value).ToList();
                }

                if (!string.IsNullOrEmpty(searchOptions.InvoiceReferenceNumber))
                {
                    purchaseOrders = purchaseOrders.Where(x => x.SupplierReference.Contains(searchOptions.InvoiceReferenceNumber)).ToList();
                }

                purchaseOrders = purchaseOrders.OrderByDescending(x => x.PurchaseOrderDate).ToList();

                foreach (PurchaseOrderViewModel item in purchaseOrders)
                {

                    Supplier supplier = dbContext.SupplierSet.Where(x => x.SupplierId == item.SupplierId).FirstOrDefault();

                    SupplierViewModel cvm = ObjectMapper.PropertyMap(supplier, new SupplierViewModel());

                    item.Supplier = cvm;

                    //FindResult<PurchaseOrderItemViewModel> soItemResult = purchaseOrderItemRepository.FindBy(dbContext, x => x.PurchaseOrderId == item.PurchaseOrderId);

                    List<PurchaseOrderItemViewModel> poItemVMs = (from poitem in dbContext.PurchaseOrderItemSet
                                                                  join pv in dbContext.ProductVariantSet on poitem.ProductVariantId equals pv.ProductVariantId
                                                                  join prod in dbContext.ProductSet on pv.ProductId equals prod.ProductId
                                                                  where (poitem.PurchaseOrderId == item.PurchaseOrderId)
                                                                  select new PurchaseOrderItemViewModel
                                                                  {
                                                                      Price = poitem.Price,
                                                                      Quantity = poitem.Quantity,
                                                                      PurchaseOrderId = poitem.PurchaseOrderId,
                                                                      ProductVariantId = poitem.ProductVariantId,
                                                                      PurchaseOrderItemId = poitem.PurchaseOrderItemId,
                                                                      ProductName = prod.ProductName,
                                                                      SKUCode = pv.SKUCode,

                                                                  }).ToList();

                    if (poItemVMs != null)
                    {

                        foreach (var poItem in poItemVMs)
                        {
                            poItem.AttributeValueString = productVariantRepository.GetProductVariantAttributeValueString(poItem.ProductVariantId);
                        }

                        item.PurchaseOrderItems = poItemVMs;
                        item.InvoiceAmount = poItemVMs.Sum(x => (x.Amount));
                    }

                }

                if (searchOptions.SupplierId.HasValue)
                {
                    purchaseOrders = purchaseOrders.Where(x => x.Supplier.SupplierId == searchOptions.SupplierId).ToList();

                }

                purchaseOrderResult.Entities = purchaseOrders;
            }

            return purchaseOrderResult;
        }
        public GetEntityResult<ExternalActivityViewModel> GetLastExternalActivityDetails(ExternalActivityTypeEnum activityType, StoreProviderTypeEnum storeProvider)
        {
            GetEntityResult<ExternalActivityViewModel> externalActivityResult = new GetEntityResult<ExternalActivityViewModel>() { Success = false };

            using (InnoventoryDBContext dbContext = new InnoventoryDBContext())
            {
                DbSet<ExternalActivity> externalActivitySet = dbContext.ExternalActivitySet;

                List<ExternalActivity> externalActivities = externalActivitySet.Where(x => x.ExternalActivityType == (int)activityType
                                                    && x.StoreProviderType == (int)storeProvider).ToList();

                if (externalActivities.Count == 0)
                {
                    externalActivityResult.Entity = null;

                    externalActivityResult.Success = true;

                    externalActivityResult.SuccessMessage = "No activity found...";
                }

                else
                {
                    externalActivities = externalActivities.OrderByDescending(x => x.LastPerformedOn).ToList();

                    ExternalActivity activity = externalActivities.FirstOrDefault();

                    ExternalActivityViewModel activityViewModel = new ExternalActivityViewModel()
                    {
                        ActivityStatus = (ExternalActivityStatus)activity.ActivityStatus,
                        ExternalActivityType = (ExternalActivityTypeEnum)activity.ExternalActivityType,
                        LastPerformedOn = activity.LastPerformedOn,
                        StoreProviderType = (StoreProviderTypeEnum)activity.StoreProviderType,

                    };

                    int unshippedCount = dbContext.ExternalOrderSet.Where(x => x.StoreOrderStatus == StoreOrderStatusEnum.Unshipped.ToString()
                                                                        && x.StoreProviderId == (int)storeProvider).Count();

                    activityViewModel.UnshippedOrdersCount = unshippedCount;

                    externalActivityResult.Entity = activityViewModel;

                    externalActivityResult.Success = true;

                }
            }

            return externalActivityResult;
        }
        public UpdateResult<PurchaseOrderViewModel> SavePurchaseOrder(PurchaseOrderViewModel purchaseOrder)
        {
            UpdateResult<PurchaseOrderViewModel> updateResult = new UpdateResult<PurchaseOrderViewModel>();

            bool isNewOrder = purchaseOrder.PurchaseOrderId == Guid.Empty ? true : false;

            using (InnoventoryDBContext dbContext = new InnoventoryDBContext())
            {

                using (DbContextTransaction tran = dbContext.Database.BeginTransaction())
                {

                    try
                    {
                        updateResult = purchaseOrderRepository.Update(dbContext, purchaseOrder);

                        if (!updateResult.Success || updateResult.Entity == null)
                        {
                            return updateResult;
                        }

                        Dictionary<Guid, PurchaseOrderItemViewModel> existingPurchaseOrderItems = new Dictionary<Guid, PurchaseOrderItemViewModel>();

                        List<Guid> soItemIds = new List<Guid>();

                        if (!isNewOrder)
                        {
                            FindResult<PurchaseOrderItemViewModel> existingSOItemsResult = purchaseOrderItemRepository.FindBy(dbContext, x => x.PurchaseOrderId == purchaseOrder.PurchaseOrderId);

                            if (existingSOItemsResult.Success)
                            {
                                existingPurchaseOrderItems = existingSOItemsResult.Entities.ToDictionary(x => x.PurchaseOrderItemId, y => y);

                                soItemIds = existingPurchaseOrderItems.Keys.ToList();
                            }

                        }

                        purchaseOrder.PurchaseOrderId = updateResult.Entity.PurchaseOrderId;

                        foreach (PurchaseOrderItemViewModel sItem in purchaseOrder.PurchaseOrderItems)
                        {

                            sItem.PurchaseOrderId = purchaseOrder.PurchaseOrderId;

                            decimal quantityToUpdate = sItem.Quantity;

                            if (!soItemIds.Contains(sItem.PurchaseOrderItemId))
                            {

                                sItem.PurchaseOrderItemId = Guid.Empty;

                            }
                            else
                            {

                                quantityToUpdate -= existingPurchaseOrderItems[sItem.PurchaseOrderItemId].Quantity;
                                existingPurchaseOrderItems.Remove(sItem.PurchaseOrderItemId);

                            }

                            UpdateResult<PurchaseOrderItemViewModel> soItemUpdResult = purchaseOrderItemRepository.Update(dbContext, sItem);

                            if (soItemUpdResult.Success)
                            {
                                sItem.PurchaseOrderItemId = soItemUpdResult.Entity.PurchaseOrderId;

                                ProductVariant pv = dbContext.ProductVariantSet.Where(x => x.ProductVariantId == sItem.ProductVariantId).FirstOrDefault();

                                if (pv != null)
                                {
                                    pv.TransactionQuantity += sItem.Quantity;
                                    pv.LastPurchasePrice = sItem.Price;

                                    dbContext.ProductVariantSet.Attach(pv);
                                    dbContext.Entry(pv).State = EntityState.Modified;
                                    dbContext.SaveChanges();
                                }

                            }

                        }//For Each sItem in purchaseOrder.PurchaseOrderItems

                        foreach (Guid key in existingPurchaseOrderItems.Keys)
                        {
                            purchaseOrderItemRepository.Delete(dbContext, key);

                            PurchaseOrderItemViewModel pvItem = existingPurchaseOrderItems[key];

                            ProductVariant pv = dbContext.ProductVariantSet.Where(x => x.ProductVariantId == pvItem.ProductVariantId).FirstOrDefault();

                            if(pv != null)
                            {
                                pv.TransactionQuantity -= pvItem.Quantity;

                                dbContext.ProductVariantSet.Attach(pv);
                                dbContext.Entry(pv).State = EntityState.Modified;
                                dbContext.SaveChanges();
                            }

                        }

                        tran.Commit();
                        updateResult.Success = true;

                    }//Try
                    catch (Exception ex)
                    {
                        tran.Rollback();
                        updateResult.Success = false;
                        updateResult.ErrorMessage = ex.Message;

                    }

                }//Using Transaction

            }// Using DBContext

            return updateResult;
        }
        public FindResult<SalesOrderViewModel> SearchSalesOrders(SalesOrderSearchOptions searchOptions)
        {
            FindResult<SalesOrderViewModel> salesOrderResult = new FindResult<SalesOrderViewModel>
            {
                Entities = new List<SalesOrderViewModel>(),
                Success = false,

            };

            using (InnoventoryDBContext dbContext = new InnoventoryDBContext())
            {
                salesOrderResult = salesOrderRepository.GetAll();

                if (!salesOrderResult.Success || salesOrderResult.Entities == null || salesOrderResult.Entities.Count == 0)
                {
                    return salesOrderResult;
                }

                List<SalesOrderViewModel> salesOrders = salesOrderResult.Entities;

                if (searchOptions.FromDate.HasValue)
                {
                    Calendar calendar = System.Threading.Thread.CurrentThread.CurrentUICulture.Calendar;

                    DateTime tDate = searchOptions.FromDate.Value;

                    DateTime fromDate = new DateTime(tDate.Year, tDate.Month, tDate.Day, calendar);

                    salesOrders = salesOrders.Where(x => x.SaleOrderDate >= searchOptions.FromDate.Value).ToList();
                }

                if (searchOptions.ToDate.HasValue)
                {
                    salesOrders = salesOrders.Where(x => x.SaleOrderDate <= searchOptions.ToDate.Value).ToList();
                }

                if (!string.IsNullOrEmpty(searchOptions.InvoiceReferenceNumber))
                {
                    salesOrders = salesOrders.Where(x => x.ReferenceNo.Contains(searchOptions.InvoiceReferenceNumber)).ToList();
                }

                salesOrders = salesOrders.OrderByDescending(x => x.SaleOrderDate).ToList();

                foreach (SalesOrderViewModel item in salesOrders)
                {

                    Customer customer = dbContext.CustomerSet.Where(x => x.CustomerId == item.CustomerId).FirstOrDefault();

                    CustomerViewModel cvm = ObjectMapper.PropertyMap(customer, new CustomerViewModel());

                    item.Customer = cvm;

                    //FindResult<SalesOrderItemViewModel> soItemResult = salesOrderItemRepository.FindBy(dbContext, x => x.SalesOrderId == item.SalesOrderId);

                    List<SalesOrderItemViewModel> soItemVMs = (from soitem in dbContext.SalesOrderItemSet
                                                               join pv in dbContext.ProductVariantSet on soitem.ProductVariantId equals pv.ProductVariantId
                                                               join prod in dbContext.ProductSet on pv.ProductId equals prod.ProductId
                                                               where (soitem.SalesOrderId == item.SalesOrderId)
                                                               select new SalesOrderItemViewModel
                                                               {
                                                                   Price = soitem.Price,
                                                                   Quantity = soitem.Quantity,
                                                                   SalesOrderId = soitem.SalesOrderId,
                                                                   ProductVariantId = soitem.ProductVariantId,
                                                                   SalesOrderItemId = soitem.SalesOrderItemId,
                                                                   ProductName = prod.ProductName,
                                                                   SKUCode = pv.SKUCode,

                                                               }).ToList();
                    if (soItemVMs != null)
                    {

                        foreach (var soItemVM in soItemVMs)
                        {
                            soItemVM.AttributeValueString = productVariantRepository.GetProductVariantAttributeValueString(soItemVM.ProductVariantId);
                        }

                        item.SaleOrderItems = soItemVMs;
                        item.InvoiceAmount = soItemVMs.Sum(x => (x.Amount));
                    }
                    else
                    {
                        item.SaleOrderItems = new List<SalesOrderItemViewModel>();

                        item.InvoiceAmount = 0;
                    }

                }

                if (searchOptions.CustomerId.HasValue)
                {
                    var lst = salesOrders.Where(x => x.Customer.CustomerId == searchOptions.CustomerId.Value);

                    if (lst != null)
                    {
                        salesOrders = lst.ToList();
                    }

                }

                salesOrderResult.Entities = salesOrders;
            }

            return salesOrderResult;
        }