Example #1
0
        //yxk 2015-9-
        /// <summary>
        /// 查询数据
        /// </summary>
        /// <returns></returns>
        public async Task <ActionResult> List()
        {
            GridRequest request = new GridRequest(Request);
            Expression <Func <Purchase, bool> > predicate = FilterHelper.GetExpression <Purchase>(request.FilterGroup);
            var availableStorageIds = CacheAccess.GetManagedStorage(_storageContract, _administratorContract).Select(i => i.Id).ToList();
            var data = await Task.Run(() =>
            {
                var count = 0;

                var list = (from m in _purchaseContract.Purchases.Where(c => !c.IsDeleted && c.IsEnabled)
                            .Where(c => availableStorageIds.Contains(c.ReceiverStorageId.Value) || availableStorageIds.Contains(c.StorageId.Value))
                            .Where <Purchase, int>(predicate, request.PageCondition, out count)
                            select new
                {
                    ParentId = "",
                    m.PurchaseNumber,
                    FactoryName = m.StoreCartId.HasValue && m.OriginFlag == StoreCardOriginFlag.工厂 ? m.StoreCart.Factory.FactoryName:"",
                    StorageOut = _storageContract.Storages.Where(c => c.Id == m.StorageId).FirstOrDefault().StorageName,
                    // m.StorageId,
                    ReceiverStore = _storeContract.Stores.Where(c => c.Id == m.ReceiverId).FirstOrDefault().StoreName,
                    ReceiverStoreId = _storeContract.Stores.Where(c => c.Id == m.ReceiverId).FirstOrDefault().Id,
                    // m.ReceiverId,
                    ReceiverStorage = _storageContract.Storages.Where(c => c.Id == m.ReceiverStorageId).FirstOrDefault().StorageName,
                    m.PurchaseStatus,
                    m.Notes,
                    ProductNum = "",
                    m.Id,
                    m.IsDeleted,
                    m.IsEnabled,
                    m.Sequence,
                    m.UpdatedTime,
                    m.CreatedTime,
                    m.Operator.Member.MemberName,
                    Quantity = -1,
                    OrderBlankNumber = m.Orderblanks.Where(x => x.IsEnabled && !x.IsDeleted).OrderByDescending(s => s.CreatedTime).FirstOrDefault().OrderBlankNumber ?? "",
                    StyleCount = m.PurchaseItems.Where(w => !w.IsNewAdded).Select(s => s.Product.BigProdNum).Distinct().Count(),
                    StyleCountReal = m.PurchaseItems.Select(s => s.Product.BigProdNum).Distinct().Count(),
                    StyleCountRealed = m.PurchaseItems.Where(w => w.PurchaseItemProducts.Any()).Select(s => s.Product.BigProdNum).Distinct().Count(),
                    PieceCount = m.PurchaseItems.Where(w => !w.IsNewAdded).Sum(s => s.Quantity),
                    PieceCountReal = m.PurchaseItems.Sum(s => s.Quantity),
                    PieceCountRealed = m.PurchaseItems.SelectMany(s => s.PurchaseItemProducts).Count(),
                    //OriginFlag = m.StoreCart != null ? (m.StoreCart.OriginFlag + "") : "未知"
                    OriginFlag = m.OriginFlag + "",
                }).ToList();
                return(new GridData <object>(list, count, request.RequestInfo));
            });

            return(Json(data, JsonRequestBehavior.AllowGet));
        }
        //da= [{ProduId:22,StorCou:120,StoreId:12,StorageId:2},{ProduId:22,StorCou:120,StoreId:12,StorageId:2}]
        //yxk
        public JsonResult AddInventory(string[] prCodes, int storageId, string notes, string recordOrderNumber, DateTime?CreatedTime)
        {
            if (!CreatedTime.HasValue)
            {
                CreatedTime = DateTime.Now;
            }
            OperationResult  optresul = new OperationResult(OperationResultType.Error, "入库失败");
            List <Inventory> inves    = new List <Inventory>();

            if (prCodes == null)
            {
                prCodes = new string[0];
            }
            string key = "ScanValid";
            var    productsModeList = Session[key] as List <Product_Model>;
            int    err = 0;

            if (productsModeList == null || productsModeList.Count == 0)
            {
                optresul.Message = "在服务器中未查到相关的入库操作,可能是操作超时";
            }
            else
            {
                var instorageCode = prCodes.Any() ? productsModeList.Where(c => prCodes.Contains(c.ProductBarcode)).Select(c => c.ProductBarcode).ToList()
                                                  : productsModeList.Select(c => c.ProductBarcode).Distinct().ToList();
                //检查是否有已经入库的条码
                if (_inventoryContract.Inventorys.Any(i => instorageCode.Contains(i.ProductBarcode)))
                {
                    return(Json(OperationResult.Error("检测到有已经入过库的流水号")));
                }
                int adminid = (int)AuthorityHelper.OperatorId;

                var storage = CacheAccess.GetManagedStorage(_storageContract, _administratorContract).FirstOrDefault(f => f.Id == storageId);

                if (storage.IsNull())
                {
                    optresul.Message = "当前用户无权限操作该仓库,ID:" + storageId;
                }
                else
                {
                    var barcodesFromDb = _productBarcodeDetailContract.productBarcodeDetails
                                         .Where(c => instorageCode.Contains(c.ProductNumber + c.OnlyFlag))
                                         .ToList();
                    var distinceBarcodes = new List <ProductBarcodeDetail>();
                    foreach (var code in barcodesFromDb)
                    {
                        if (distinceBarcodes.Any(i => i.ProductNumber == code.ProductNumber && i.OnlyFlag == code.OnlyFlag))
                        {
                            continue;
                        }
                        else
                        {
                            distinceBarcodes.Add(code);
                        }
                    }
                    var productNumbersFromBarcode = distinceBarcodes.Select(c => c.ProductNumber).ToList();
                    var products = _productContract.Products.Where(c => productNumbersFromBarcode.Contains(c.ProductNumber))
                                   .Select(c => new
                    {
                        c.ProductNumber,
                        c.Id,
                        c.ProductOriginNumber.TagPrice,
                        c.ProductOriginNumber.WholesalePrice,
                        c.ProductOriginNumber.PurchasePrice
                    })
                                   .ToList();
                    var           productNumbersFromProduct = products.Select(c => c.ProductNumber).ToList();
                    var           errproduct = distinceBarcodes.Where(c => !productNumbersFromProduct.Contains(c.ProductNumber));
                    List <string> errbarcode = new List <string>();
                    if (errproduct.Any())
                    {
                        //与该商品相关的商品档案不存在
                        //写日志 待完善

                        errbarcode = errproduct.Select(c => c.ProductNumber + c.OnlyFlag).ToList();
                        //inves = new List<Inventory>(); //清空需要入库的数据
                        var errst = "";
                        if (errbarcode.Count > 4)
                        {
                            errst = string.Join(",", errbarcode.Take(4).ToArray());
                        }
                        else
                        {
                            errst = string.Join(",", errbarcode);
                        }
                        _logContract.Insert(new LogDto()
                        {
                            Description = string.Join(",", errbarcode) + "未查找到商品档案",
                        });
                        optresul.Message = "部分商品未查找到商品档案:" + errst + "……,详情请查看日志";
                    }
                    else
                    {
                        inves = distinceBarcodes.Select(c => new Inventory()
                        {
                            ProductNumber  = c.ProductNumber,
                            OnlyFlag       = c.OnlyFlag,
                            ProductLogFlag = Guid.NewGuid().ToString().Replace("-", ""),
                            ProductBarcode = c.ProductNumber + c.OnlyFlag,
                            StoreId        = storage.StoreId,
                            StorageId      = storageId,
                            ProductId      = products.FirstOrDefault(g => g.ProductNumber == c.ProductNumber).Id,
                            Description    = notes,
                        }).ToList();
                    }
                    if (inves.Any())
                    {
                        // 计算本次入库总吊牌价
                        float totalTagPrice = 0;
                        foreach (var inventory in inves)
                        {
                            totalTagPrice += products.First(p => p.Id == inventory.ProductId).TagPrice;
                        }
                        // 根据生成的库存信息,插入入库记录
                        var record = new InventoryRecord()
                        {
                            Quantity          = inves.Count,
                            OperatorId        = adminid,
                            StorageId         = storageId,
                            StoreId           = storage.StoreId,
                            TagPrice          = totalTagPrice,
                            RecordOrderNumber = recordOrderNumber,
                            CreatedTime       = CreatedTime.Value
                        };

                        using (var tran = _inventoryContract.GetTransaction())
                        {
                            var res = _inventoryRecordContract.Insert(record);
                            if (res.ResultType != OperationResultType.Success)
                            {
                                tran.Rollback();
                                return(Json(OperationResult.Error("库存记录插入失败")));
                            }

                            // 将库存信息与入库记录进行关联
                            inves.Each(i => i.InventoryRecordId = record.Id);
                            // 保存库存信息
                            optresul = _inventoryContract.BulkInsert(inves);
                            if (optresul.ResultType != OperationResultType.Success)
                            {
                                tran.Rollback();
                                return(Json(OperationResult.Error("保存库存信息失败")));
                            }
                            List <ProductTrack> listpt = new List <ProductTrack>();
                            foreach (var item in inves)
                            {
                                #region 商品追踪
                                ProductTrack pt = new ProductTrack();
                                pt.ProductNumber  = item.ProductNumber;
                                pt.ProductBarcode = item.ProductNumber + item.OnlyFlag;
                                pt.Describe       = String.Format(ProductOptDescTemplate.ON_PRODUCT_INVENTORY, storage.StorageName);

                                listpt.Add(pt);
                                #endregion
                            }
                            var resPT = _productTrackContract.BulkInsert(listpt);
                            if (resPT.ResultType != OperationResultType.Success)
                            {
                                tran.Rollback();
                                return(Json(OperationResult.Error("商品追踪插入失败")));
                            }
                            List <string> proCodes = inves.Select(c => c.ProductBarcode).ToList();
                            var           details  = _productBarcodeDetailContract.productBarcodeDetails.Where(c => proCodes.Contains(c.ProductNumber + c.OnlyFlag));
                            details.Each(c => c.Status = 1);

                            var resPBD = _productBarcodeDetailContract.BulkUpdate(details);
                            if (resPBD.ResultType != OperationResultType.Success)
                            {
                                tran.Rollback();
                                return(Json(OperationResult.Error("商品条码信息更新失败")));
                            }
                            productsModeList.RemoveAll(c => proCodes.Contains(c.ProductBarcode));
                            SessionAccess.Set(key, productsModeList);

                            tran.Commit();
                        }
                    }
                }
            }
            return(Json(optresul, JsonRequestBehavior.AllowGet));
        }