Esempio n. 1
0
        public async Task BrowseProducts_Valid_OK()
        {
            for (int i = 0; i < 30; i++)
            {
                var productRecord = new ProductRecord
                {
                    ProductCode = $"P{i}",
                    ProductName = $"Product {i}",
                    ListPrice   = 100 + i,
                };

                _productRecords.Add(productRecord);

                Fixture.Db.Add(productRecord);
            }

            var browseRequest = new BrowseProductsRequest
            {
                Page = 3,
                Size = 5,
            };

            var browseResponse = await Fixture.Api.Products.BrowseProductsAsync(browseRequest);

            Assert.Equal(HttpStatusCode.OK, browseResponse.StatusCode);

            var browseResponseContent = browseResponse.Data;

            Assert.Equal(browseRequest.Size, browseResponseContent.Count);

            var skip = browseRequest.Page * browseRequest.Size;
            var take = browseRequest.Size;

            var expected = _productRecords.Skip(skip).Take(take).ToList();

            for (int i = 0; i < expected.Count; i++)
            {
                var expectedRecord = expected[i];
                var actualRecord   = browseResponseContent.Records[i];
                Assert.Equal(expectedRecord.Id, actualRecord.Id);
                Assert.Equal(expectedRecord.ProductCode, actualRecord.Code);
                Assert.Equal(expectedRecord.ProductName, actualRecord.Description);
                Assert.Equal(expectedRecord.ListPrice, actualRecord.UnitPrice);
            }
        }
Esempio n. 2
0
        static void Main(string[] args)
        {
            if (args.Length != 1)
            {
                Console.WriteLine("Path argument required, for example:  PrestoParser.exe ./input-sample.txt");
                return;
            }

            LinearParser prestoParse = new LinearParser(args[0], new FixedWidthFormat());

            try
            {
                // parse the passed in data file
                List <ProductRecord> records = prestoParse.Parse();

                int goodCount = 0;

                // simple json exporter
                using (StreamWriter writer = new StreamWriter("./output.json", false))
                {
                    writer.WriteLine("{ \"Record\" : [");

                    ProductRecord lastRecord = records.Last();
                    foreach (ProductRecord r in records)
                    {
                        writer.WriteLine(r.OutputJSON() + ((r != lastRecord) ? ", " : ""));

                        goodCount += r.IsGood() ? 1 : 0;
                    }

                    writer.WriteLine("] }");
                }

                // output good/bad record status to console
                Console.WriteLine("Records Parsed: " + records.Count + ", Bad Records: " + (records.Count - goodCount));
            }
            catch (ParserException exception)
            {
                Console.WriteLine("Parsing Failed with error: ");
                Console.Write(exception.Message);
            }

            Console.WriteLine("Press enter to continue");
            Console.ReadLine();
        }
Esempio n. 3
0
        private void FillProductViewModelWithColours(ProductViewModel viewModel, ProductRecord product)
        {
            viewModel.ProductColours = _productColourRepository.Table
                                       .Where(c => c.ProdColorCulture == cultureUsed)
                                       .OrderBy(c => c.Name)
                                       .Select(c => new ProductColourItemViewModel
            {
                Id       = c.Id,
                Name     = c.Name,
                HexValue = c.Value
            })
                                       .ToList();

            if (product == null)
            {
                return;
            }

            var selectedProductColourIds = _linkProductColorRepository.Table
                                           .Where(it => it.ProductRecord == product)
                                           .Select(it => it.ProductColorRecord.Id)
                                           .ToList();

            viewModel.ProductColours.ToList().ForEach(c =>
            {
                if (selectedProductColourIds.Contains(c.Id))
                {
                    c.Selected = true;
                }
            });

            viewModel.SelectedProductColours = _linkProductColorRepository.Table
                                               .Where(it => it.ProductRecord == product)
                                               .Fetch(it => it.ProductColorRecord)
                                               .Select(it => new ProductColourItemViewModel
            {
                Id = it.Id,
                ProductColourId = it.ProductColorRecord.Id,
                Name            = it.ProductColorRecord.Name,
                HexValue        = it.ProductColorRecord.Value,
                //BaseCost = it.ProductRecord.BaseCost
            })
                                               .ToList();
        }
Esempio n. 4
0
        private void FillProductViewModelWithSizes(ProductViewModel viewModel, ProductRecord product)
        {
            viewModel.ProductSizes = _productSizeRepository.Table
                                     .Where(s => s.ProdSizeCulture == cultureUsed)
                                     .Fetch(s => s.SizeCodeRecord)
                                     .Select(s => new ProductSizeItemViewModel
            {
                Id           = s.Id,
                LengthCm     = s.LengthCm,
                WidthCm      = s.WidthCm,
                SleeveCm     = s.SleeveCm,
                LengthInch   = s.LengthInch,
                WidthInch    = s.WidthInch,
                SleeveInch   = s.SleeveInch,
                SizeCodeId   = s.SizeCodeRecord.Id,
                SizeCodeName = s.SizeCodeRecord.Name,
                Remark       = s.Remarks
            })
                                     .ToList();

            if (product == null)
            {
                return;
            }

            var selectedProductSizeIds = _linkProductSizeRepository.Table
                                         .Where(it => it.ProductRecord == product)
                                         //.Select(it => it.ProductSizeRecord.Id)
                                         .ToList();

            viewModel.ProductSizes.ToList().ForEach(s =>
            {
                if (selectedProductSizeIds.Exists(c => c.ProductSizeRecord.Id == s.Id))
                {
                    s.Selected = true;
                    s.CostSize = selectedProductSizeIds.Where(c => c.ProductSizeRecord.Id == s.Id).First().SizeCost;
                }
            });

            //var selectedProductSizeCost = _linkProductSizeRepository.Table
            //    .Where(it => it.ProductRecord == product)
            //    .Select(it => it.ProductSizId)
            //    .ToList();
        }
        //商城給予魚骨、兌換購買等功能
        public bool AddBearByAssets(ProductRecord ar)
        {
            Assets assDb   = db.Assets.Where(p => p.UserId == ar.UserID && p.unitSn == ar.unitSn).FirstOrDefault();
            double fAssets = (assDb == null ? 0 : assDb.assets);

            if (assDb == null)
            {
                assDb = new Assets
                {
                    UserId = ar.UserID,
                    unitSn = (int)ar.unitSn,
                    assets = fAssets + (int)ar.assets
                };
                db.Assets.Add(assDb);
            }
            else
            {
                assDb.assets += (int)ar.assets;
            }
            try
            {
                db.SaveChanges();
            }
            catch (Exception ex)
            {
                throw;
            }

            ProductRecord assr = new ProductRecord
            {
                UserID    = ar.UserID,
                unitSn    = ar.unitSn,
                assets    = ar.assets,
                inpdate   = DateTime.Now,
                type      = ar.type,
                ProductId = ar.ProductId
            };

            db.ProductRecord.Add(assr);
            db.SaveChanges();


            return(true);
        }
Esempio n. 6
0
        protected override async void Run(Session session, C2G_QueryUserProductRecord message, Action <G2C_QueryUserProductRecord> reply)
        {
            G2C_QueryUserProductRecord response          = new G2C_QueryUserProductRecord();
            UserProductRecord          UserProductRecord = null;

            try
            {
                DBProxyComponent dBProxyComponent = Game.Scene.GetComponent <DBProxyComponent>();

                var acounts = await dBProxyComponent.Query <UserProductRecord>("{ '_AccountID': " + message.AccountID + "}");

                if (acounts.Count > 0)
                {
                    for (int i = 0; i < acounts.Count; i++)
                    {
                        UserProductRecord = acounts[i] as UserProductRecord;

                        ProductRecord record = new ProductRecord();
                        record.AccountID     = UserProductRecord._AccountID;
                        record.InfoID        = UserProductRecord._InfoID;
                        record.ProductID     = UserProductRecord._ProductID;
                        record.Level         = UserProductRecord._Level;
                        record.StartDate     = UserProductRecord._StartDate;
                        record.EndDate       = UserProductRecord._EndDate;
                        record.RightCodeList = RepeatedFieldAndListChangeTool.ListToRepeatedField(UserProductRecord._RightCodeList);
                        record.BuyType       = UserProductRecord._BuyType;
                        record.Price         = UserProductRecord._Price;
                        response.Userlist.Add(record);
                    }
                }

                await dBProxyComponent.Save(UserProductRecord);

                await dBProxyComponent.SaveLog(UserProductRecord);

                reply(response);
            }
            catch (Exception e)
            {
                response.Message = "数据库异常";
                ReplyError(response, e, reply);
            }
        }
Esempio n. 7
0
        public async Task BrowseProducts_ValidRequest_ReturnsResponse()
        {
            for (int i = 0; i < 30; i++)
            {
                var productRecord = new ProductRecord
                {
                    ProductCode = $"P{i.ToString("0000")}",
                    ProductName = $"Product {i.ToString("0000")}",
                    ListPrice   = 100 + i,
                };

                _productRecords.Add(productRecord);

                Fixture.Db.Add(productRecord);
            }

            var browseRequest = new BrowseProductsRequest
            {
                Page = 3,
                Size = 5,
            };

            var browseResponse = await Fixture.Products.BrowseProductsAsync(browseRequest);

            Assert.Equal(_productRecords.Count, browseResponse.TotalRecords);

            var skip = (browseRequest.Page - 1) * browseRequest.Size;
            var take = browseRequest.Size;

            var expected = _productRecords.Skip(skip).Take(take).ToList();

            for (int i = 0; i < expected.Count; i++)
            {
                var expectedRecord = expected[i];
                var actualRecord   = browseResponse.Records[i];
                Assert.Equal(expectedRecord.Id, actualRecord.Id);
                Assert.Equal(expectedRecord.ProductCode, actualRecord.Code);
                Assert.Equal(expectedRecord.ProductName, actualRecord.Description);
                Assert.Equal(expectedRecord.ListPrice, actualRecord.UnitPrice);
                Assert.Equal(expectedRecord.IsListed, actualRecord.IsListed);
            }
        }
Esempio n. 8
0
        public async Task <IActionResult> PutProduct(string code, ProductRecord product)
        {
            if (product == null)
            {
                return(BadRequest("Product is null"));
            }

            if (code != product.Code)
            {
                return(BadRequest());
            }

            var result = await productService.UpdateAsync(code, product);

            if (result.NotFound)
            {
                return(NotFound(result.ErrorMessage));
            }

            return(NoContent());
        }
Esempio n. 9
0
        public ActionResult Save(int?id)
        {
            var obj = new ProductRecord()
            {
                Source = 1
            };

            if (id.HasValue)
            {
                obj = ProductService.GetOne(id);
            }
            ViewBag.subunits = ListToSelect(DictionaryService.GetSubUnitCategories().Select(o => new SelectListItem()
            {
                Value = o.DicSN.ToString(), Text = o.Title
            }), emptyTitle: "");
            ViewBag.brands = ListToSelect(BrandService.GetList().Select(o => new SelectListItem()
            {
                Value = o.BrandSN.ToString(), Text = o.Title
            }), emptyTitle: "");
            return(View(obj.IsNullThrow()));
        }
Esempio n. 10
0
        public async Task <UpdateResult> UpdateAsync(string code, ProductRecord productIn)
        {
            if (!ProductExists(code))
            {
                return(new UpdateResult()
                {
                    NotFound = true, ErrorMessage = $"Product with code {productIn.Code} doesn't exist."
                });
            }

            Product productToUpdate = await this.dbContext.Products.FindAsync(code);

            productToUpdate.Cost                = productIn.Cost;
            productToUpdate.Description         = productIn.Description;
            productToUpdate.Price               = productToUpdate.Price;
            productToUpdate.QuantityPerUnitPack = productToUpdate.QuantityPerUnitPack;
            productToUpdate.Review              = productToUpdate.Review;
            productToUpdate.Weight              = productToUpdate.Weight;

            this.dbContext.Entry(productToUpdate).State = Microsoft.EntityFrameworkCore.EntityState.Modified;

            this.dbContext.Products.Update(productToUpdate);

            try
            {
                await this.dbContext.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException dce)
            {
                return(new UpdateResult()
                {
                    Success = false, ErrorMessage = dce.Message
                });
            }

            return(new UpdateResult()
            {
                Success = true
            });
        }
        IProductRecord Parse(RawSampleProductFormat raw)
        {
            var result = new ProductRecord();

            result.ProductID          = int.Parse(raw.ProductId);
            result.ProductDescription = raw.ProductDescription.Trim();

            result.RegularCalculatorPrice = CalculatorPrice(raw.RegularSingularPrice,
                                                            raw.RegularSplitPrice, raw.RegularForX);
            result.RegularDisplayPrice = FormatCurrencyForDisplay(result.RegularCalculatorPrice);

            result.PromotionalCalculatorPrice = CalculatorPrice(raw.PromotionalSingularPrice,
                                                                raw.PromotionalSplitPrice, raw.PromotionalForX);
            result.PromotionalDisplayPrice = result.PromotionalCalculatorPrice == 0 ?
                                             "N/A" :  FormatCurrencyForDisplay(result.PromotionalCalculatorPrice);

            result.TaxRate     = CheckFlag(raw.Flags, 5) ? 7.775m : 0;
            result.Measure     = CheckFlag(raw.Flags, 3) ? UnitOfMeasure.Pound : UnitOfMeasure.Each;
            result.ProductSize = raw.ProductSize.Trim();

            return(result);
        }
Esempio n. 12
0
        /// <summary>
        /// 扣除 拆分子产品 库存
        /// </summary>
        /// <param name="childProduct">拆分子产品条码,实际库存变动的产品</param>
        /// <param name="purchaseNumber">库存变动数量</param>
        /// <param name="storeId">门店Id</param>
        /// <param name="paySn">订单流水号</param>
        /// <param name="saleBarcode">销售条码</param>
        /// <param name="mode">库存变化来源操作的模式(1、销售量消减;2、父商品拆分;3、组合商品消减;4、整单退出库存回撤,5、拆分子商品入库,6、退货库存回撤,7、修改订单库存回撤,8、修改订单新增商品消减)</param>
        /// <param name="isSave">是否保存到数据库。默认:false</param>
        private static void SubtractSplitChildStock(ProductRecord childProduct, decimal purchaseNumber, string storeId, string paySn, string saleBarcode, int mode, bool isSave = false)
        {
            try
            {
                var thisChildInventory = BaseService <Inventory> .CurrentRepository.QueryEntity.FirstOrDefault(o => o.CompanyId == CommonService.CompanyId && o.Barcode == childProduct.Barcode && o.StoreId == storeId);

                if (thisChildInventory != null)
                {     //存在库存
                    if (purchaseNumber <= thisChildInventory.StockNumber)
                    { //足够扣,视作单品来扣
                        SubtractSingleProductStock(purchaseNumber, thisChildInventory.Barcode, storeId, paySn, saleBarcode, mode);
                    }
                    else
                    {   //不足够扣
                        var subtractParentNum = Math.Ceiling((purchaseNumber - thisChildInventory.StockNumber) / (childProduct.SaleNum ?? 1m));
                        //扣除父产品库存
                        SubtractSplitParentStock(subtractParentNum, childProduct.OldBarcode, storeId, paySn, saleBarcode);
                        //最多递归一次,故此次作为事务一部分而不SaveChanges
                        SubtractSplitChildStock(childProduct, purchaseNumber, storeId, paySn, saleBarcode, mode);
                    }
                }
                else
                {   //不存在库存(不应该有此情况,售卖前应先入了库,但此处考虑后台操作产品未必有库存)
                    var subtractParentNum = Math.Ceiling((purchaseNumber - thisChildInventory.StockNumber) / (childProduct.SaleNum ?? 1m));
                    //扣除父产品库存
                    SubtractSplitParentStock(subtractParentNum, childProduct.OldBarcode, storeId, paySn, saleBarcode);
                    //最多递归一次,故此次作为事务一部分而不SaveChanges
                    SubtractSplitChildStock(childProduct, purchaseNumber, storeId, paySn, saleBarcode, mode);
                }
                if (isSave)
                {
                    BaseService <Inventory> .CurrentRepository.Update(new Inventory());
                }
            }
            catch (Exception ex)
            {
                Log.WriteError("扣除拆分子产品库存操作失败!", ex);
            }
        }
Esempio n. 13
0
        /// <summary>
        /// 称重条码解析
        /// </summary>
        /// <param name="barcode">条码</param>
        /// <param name="isNotFoundThrowException">当未找到商品时,是否抛出异常</param>
        /// <returns>商品列表</returns>
        public IEnumerable <ProductRecord> WeightBarcodeAnalysis(string barcode, bool isNotFoundThrowException = false)
        {
            IEnumerable <ProductRecord>             products = new ProductRecord[0];
            IPosElectronicBalanceSettingsRepository posElectronicBalanceSettingsRepository = new PosElectronicBalanceSettingsRepository();
            var electronicBalanceSetting = posElectronicBalanceSettingsRepository.Get(true);

            if (electronicBalanceSetting.Enable && electronicBalanceSetting.MaybeWeightProduct(barcode))//处理称重商品
            {
                var productBarcode = string.Empty;
                var productCode    = string.Empty;

                IPosSystemSettingsRepository systemSettingsRepository = new PosSystemSettingsRepository();
                var settings = systemSettingsRepository.Get();
                IProductRepository productRepository = null;
                if (settings.EnableRemoteService)
                {
                    productRepository = new ProductOnlineRepository();
                }
                else
                {
                    productRepository = new ProductOfflineRepository();
                }

                if (electronicBalanceSetting.IsProductCode(barcode, out productCode))
                {
                    var product = productRepository.FindProductByProductCode(productCode);
                    products = new ProductRecord[] { product };
                }
                else if (electronicBalanceSetting.IsProductBarcode(barcode, out productBarcode))
                {
                    products = productRepository.FindProductByBarcode(productBarcode);
                }
            }
            if (isNotFoundThrowException && (products == null || products.Count() == 0))
            {
                throw new NotFoundProductException(string.Format("未能找到指定条码【{0}】的商品!", barcode));
            }
            return(products);
        }
        public void AddItem_WithNewItem_AddNewItemToBasket()
        {
            // Arrange
            var basketId = "some-basketId";
            var itemId   = "some-itemId";

            var product = new ProductRecord
            {
                Id    = itemId,
                Price = 1.11m
            };

            this._storageServiceMock.Setup(x => x.Get <BasketModel>(basketId)).Returns((BasketModel)null);
            this._storageServiceMock.Setup(x => x.Put(basketId, It.IsAny <BasketModel>()));
            this._productRepositoryMock.Setup(x => x.Get(itemId)).Returns(product);

            // Act
            this._subject.AddItem(basketId, itemId);

            // Assert
            this._storageServiceMock.Verify(x => x.Put(basketId, It.Is <BasketModel>(y => y.Items[0].ItemId == itemId)),
                                            Times.Once);
        }
Esempio n. 15
0
        /// <summary>
        /// 普通商品条码解析
        /// </summary>
        /// <param name="barcode">条码</param>
        /// <param name="isNotFoundThrowException">当未找到商品时,是否抛出异常</param>
        /// <returns>商品列表</returns>
        public IEnumerable <ProductRecord> BarcodeAnalysis(string barcode, bool isNotFoundThrowException = false)
        {
            IEnumerable <ProductRecord> products = new ProductRecord[0];

            IPosSystemSettingsRepository systemSettingsRepository = new PosSystemSettingsRepository();
            var settings = systemSettingsRepository.Get();
            IProductRepository productRepository = null;

            if (settings.EnableRemoteService)
            {
                productRepository = new ProductOnlineRepository();
            }
            else
            {
                productRepository = new ProductOfflineRepository();
            }

            products = productRepository.FindProductByBarcode(barcode);
            if (isNotFoundThrowException && (products == null || products.Count() == 0))
            {
                throw new NotFoundProductException(string.Format("未能找到指定条码【{0}】的商品!", barcode));
            }
            return(products);
        }
Esempio n. 16
0
        public override void Modify(ProductRecord record)
        {
            DbCommand command    = this.Provider.GetStoredProcedure("spInsertUpdateProduct");;
            bool      useV6Logic = true;

            if (record.SyProduct == 10)
            {
                command    = this.Provider.GetStoredProcedure("spConsensusLearningProductModify");
                useV6Logic = false;
            }
            else
            {
                this.MapParameterIn(command, "@PA_USER_LOGIN_ID", "dev");
                this.MapErrorParams(command);
            }

            this.MapParametersIn(command, record, useV6Logic);
            this.Execute(command);
            if (record.SyProduct != 10)
            {
                this.CheckErrorParams(command);
            }
            this.MapParametersOut(command, record);
        }
Esempio n. 17
0
        public ActionResult Save(ProductRecord obj)
        {
            var re = ProductService.SaveOrUpdate(obj);

            return(new OpActionResult(re));
        }
Esempio n. 18
0
        public JsonResult Action(FormCollection formCollection)
        {
            JsonResult json = new JsonResult();

            try
            {
                ProductActionViewModel model = GetProductActionViewModelFromForm(formCollection);

                if (model.ProductID > 0)
                {
                    var product = ProductsService.Instance.GetProductByID(model.ProductID);

                    if (product == null)
                    {
                        throw new Exception("Dashboard.Products.Action.Validation.ProductNotFound".LocalizedString());
                    }

                    product.ID         = model.ProductID;
                    product.CategoryID = model.CategoryID;
                    product.Price      = model.Price;

                    product.Discount   = model.Discount;
                    product.Cost       = model.Cost;
                    product.SKU        = model.SKU;
                    product.Barcode    = model.Barcode;
                    product.Tags       = model.Tags;
                    product.Supplier   = model.Supplier;
                    product.isFeatured = model.isFeatured;
                    product.ModifiedOn = DateTime.Now;

                    if (!string.IsNullOrEmpty(model.ProductPictures))
                    {
                        var pictureIDs = model.ProductPictures
                                         .Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
                                         .Select(ID => int.Parse(ID)).ToList();

                        if (pictureIDs.Count > 0)
                        {
                            var newPictures = new List <ProductPicture>();

                            newPictures.AddRange(pictureIDs.Select(x => new ProductPicture()
                            {
                                ProductID = product.ID, PictureID = x
                            }).ToList());

                            if (!ProductsService.Instance.UpdateProductPictures(product.ID, newPictures))
                            {
                                throw new Exception("Dashboard.Products.Action.Validation.UnableToUpdateProductPictures".LocalizedString());
                            }

                            product.ThumbnailPictureID = model.ThumbnailPicture != 0 ? model.ThumbnailPicture : pictureIDs.First();
                        }
                    }

                    if (!ProductsService.Instance.UpdateProduct(product))
                    {
                        throw new Exception("Dashboard.Products.Action.Validation.UnableToUpdateProduct".LocalizedString());
                    }

                    var currentLanguageRecord = product.ProductRecords.FirstOrDefault(x => x.LanguageID == AppDataHelper.CurrentLanguage.ID);

                    var isNewRecord = false;

                    if (currentLanguageRecord == null)
                    {
                        currentLanguageRecord = new ProductRecord();
                        isNewRecord           = true;
                    }

                    currentLanguageRecord.ProductID   = product.ID;
                    currentLanguageRecord.LanguageID  = AppDataHelper.CurrentLanguage.ID;
                    currentLanguageRecord.Name        = model.Name;
                    currentLanguageRecord.Summary     = model.Summary;
                    currentLanguageRecord.Description = model.Description;

                    currentLanguageRecord.ModifiedOn = DateTime.Now;

                    if (model.ProductSpecifications != null && model.ProductSpecifications.Count > 0)
                    {
                        var newProductSpecification = new List <ProductSpecification>();

                        newProductSpecification.AddRange(model.ProductSpecifications.Select(x => new ProductSpecification()
                        {
                            ProductRecordID = currentLanguageRecord.ID, Title = x.Title, Value = x.Value
                        }));

                        if (isNewRecord)
                        {
                            currentLanguageRecord.ProductSpecifications = newProductSpecification;
                        }
                        else
                        {
                            ProductsService.Instance.UpdateProductSpecifications(product.ID, newProductSpecification);
                        }
                    }

                    var result = false;
                    if (isNewRecord)
                    {
                        result = ProductsService.Instance.SaveProductRecord(currentLanguageRecord);
                    }
                    else
                    {
                        result = ProductsService.Instance.UpdateProductRecord(currentLanguageRecord);
                    }

                    if (!result)
                    {
                        throw new Exception("Dashboard.Products.Action.Validation.UnableToUpdateProductRecord".LocalizedString());
                    }
                }
                else
                {
                    Product product = new Product
                    {
                        CategoryID = model.CategoryID,
                        Price      = model.Price,

                        Discount = model.Discount,
                        Cost     = model.Cost,
                        SKU      = model.SKU,
                        Barcode  = model.Barcode,
                        Tags     = model.Tags,
                        Supplier = model.Supplier,


                        isFeatured = model.isFeatured,
                        ModifiedOn = DateTime.Now
                    };

                    if (!string.IsNullOrEmpty(model.ProductPictures))
                    {
                        var pictureIDs = model.ProductPictures
                                         .Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
                                         .Select(ID => int.Parse(ID)).ToList();

                        if (pictureIDs.Count > 0)
                        {
                            product.ProductPictures = new List <ProductPicture>();
                            product.ProductPictures.AddRange(pictureIDs.Select(x => new ProductPicture()
                            {
                                ProductID = product.ID, PictureID = x
                            }).ToList());

                            product.ThumbnailPictureID = model.ThumbnailPicture != 0 ? model.ThumbnailPicture : pictureIDs.First();
                        }
                    }

                    if (!ProductsService.Instance.SaveProduct(product))
                    {
                        throw new Exception("Dashboard.Products.Action.Validation.UnableToCreateProduct".LocalizedString());
                    }

                    var currentLanguageRecord = new ProductRecord
                    {
                        ProductID   = product.ID,
                        LanguageID  = AppDataHelper.CurrentLanguage.ID,
                        Name        = model.Name,
                        Summary     = model.Summary,
                        Description = model.Description,

                        ModifiedOn = DateTime.Now
                    };

                    if (model.ProductSpecifications != null)
                    {
                        currentLanguageRecord.ProductSpecifications = new List <ProductSpecification>();
                        currentLanguageRecord.ProductSpecifications.AddRange(model.ProductSpecifications.Select(x => new ProductSpecification()
                        {
                            ProductRecordID = product.ID, Title = x.Title, Value = x.Value
                        }));
                    }

                    var result = ProductsService.Instance.SaveProductRecord(currentLanguageRecord);

                    if (!result)
                    {
                        throw new Exception("Dashboard.Products.Action.Validation.UnableToCreateProductRecord".LocalizedString());
                    }
                }

                json.Data = new { Success = true };
            }
            catch (Exception ex)
            {
                json.Data = new { Success = false, Message = ex.Message };
            }

            return(json);
        }
Esempio n. 19
0
 /// <summary>
 ///     Initialises a new <see cref="LocalProductMembershipModel" /> instance.
 /// </summary>
 /// <param name="provider">
 ///     The business provider to which the business model is bound.
 /// </param>
 /// <param name="record">
 ///     The data record which is encapsulated by the business model.
 /// </param>
 internal LocalProductMembershipModel(LocalProvider provider, ProductRecord record) : base(provider, record)
 {
 }
Esempio n. 20
0
 private string PromotionalToString(ProductRecord productRecord) => productRecord.IsPromotional() ? $" | {productRecord.PromotionalDisplayPrice()} | {productRecord.PromotionalCalculatorPrice()}" : " | |";
Esempio n. 21
0
 private string RegularToString(ProductRecord productRecord) => productRecord.IsRegular() ? $" | {productRecord.RegularDisplayPrice()} | {productRecord.RegularCalculatorPrice()}" : " | |";
Esempio n. 22
0
 // A passagem do record é por referência, semelhante a classe.
 static void UpdateProduct(ProductRecord product) => product.Name = "item";
Esempio n. 23
0
        public ActionResult Save(ProductRecord obj)
        {
            var re = ProductService.SaveOrUpdate(obj);

            return(Content(re.ToJson()));
        }
Esempio n. 24
0
 public dynamic AddOrUpdate(ProductRecord obj)
 {
     throw new NotImplementedException();
 }
Esempio n. 25
0
 public async Task <int> UpdateAsync(int productId, ProductRecord product)
 {
     return(await _productRepository.UpdateAsync(productId, product.ProductName, product.SupplierID, product.CategoryID,
                                                 product.QuantityPerUnit, product.UnitPrice, product.UnitsInStock, product.UnitsOnOrder, product.ReorderLevel, product.Discontinued));
 }
 public async Task <int> Put(int id, [FromBody] ProductRecord record)
 {
     return(await _productService.UpdateAsync(id, record));
 }
Esempio n. 27
0
 public void Create(ProductRecord item)
 {
     throw new NotImplementedException();
 }
Esempio n. 28
0
 public void CreateWithSaveChanges(ProductRecord item)
 {
     throw new NotImplementedException();
 }
 public async Task <int> Post([FromBody] ProductRecord record)
 {
     return(await _productService.AddNewAsync(record));
 }
Esempio n. 30
0
        private ProductImageSavingResult SaveProductBackImage(HttpPostedFileBase imageFile, ProductRecord product)
        {
            if (imageFile == null)
            {
                return(null);
            }

            if (!IsImagePng(imageFile))
            {
                _orchardServices.Notifier.Error(
                    T("Back Image file should be *.png.",
                      ProductImageWidth,
                      ProductImageHeight));

                return(null);
            }

            using (var image = Image.FromStream(imageFile.InputStream, true, true))
            {
                if (image.Width != ProductImageWidth || image.Height != ProductImageHeight)
                {
                    _orchardServices.Notifier.Error(
                        T("Back Image should be {0}x{1}.",
                          ProductImageWidth,
                          ProductImageHeight));

                    return(null);
                }

                var imageFileName     = string.Format(ProductImageBackFileNameTemplate, product.Id);
                var imagePhysicalPath = Path.Combine(Server.MapPath(ProductImagesRelativePath), imageFileName);

                image.Save(imagePhysicalPath, ImageFormat.Png);

                return(new ProductImageSavingResult
                {
                    Width = image.Width,
                    Height = image.Height
                });
            }
        }