public ActionResult ImportCsOrder(string path)
        {
            path = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + path.Replace("..", "");
            var fileArr  = path.Split(new[] { "/" }, StringSplitOptions.RemoveEmptyEntries);
            var fileName = fileArr[fileArr.Length - 1];
            IList <CsOrderView.CsOrderImport> orders;

            try
            {
                orders = NpoiHelper.ReadExcel(path.Replace("/" + fileName, ""), fileName).ToList <CsOrderView.CsOrderImport>();
            }
            catch (Exception ex)
            {
                LogHelper.Log(ex.ToJson(), "execl文件读取失败");
                return(Json(new ResModel
                {
                    ResStatus = ResStatue.No,
                    Data = "execl 文件读取失败,请确认文件数据正确, 请检查日志描述"
                }));
            }
            if (!orders.Any())
            {
                return(Json(new ResModel
                {
                    ResStatus = ResStatue.No,
                    Data = "当前Excel中没有数据,请确认文件是否包含规定完整的数据"
                }));
            }
            var users        = _csUsersBll.GetModelList($" AND (UserName IN ('{string.Join("','", orders.Select(x => x.收货人))}') OR UserPhone IN ('{string.Join("','", orders.Select(x => x.收货人电话))}'))");
            var products     = _csProductsBll.GetModelList("");
            var parts        = _csPartsBll.GetModelList("");
            var data         = new List <CsOrderView.CsOrderAndDetail>();
            var item         = new CsOrderView.CsOrderAndDetail();
            var lastType     = ExcelRow.Other;   // 记录上一行状态
            var endEmpty     = new List <int>(); // 记录尾部空行
            var overEndEmpty = false;            // 尾部空行是否结束

            for (var i = orders.Count - 1; i >= 0; i--)
            {
                var type = ExcelRowType(orders[i]);
                if (type == ExcelRow.Empty &&
                    !overEndEmpty)
                {
                    endEmpty.Add(i);
                }
                else
                {
                    overEndEmpty = true;
                }
                if (type == ExcelRow.Empty &&
                    lastType == ExcelRow.Empty &&
                    overEndEmpty)
                {
                    return(Json(new ResModel
                    {
                        ResStatus = ResStatue.No,
                        Data = "当前Excel中,两个订单信息中间,存在连续多空行.请仔细确认数据, 数据一旦上传将无法撤回"
                    }));
                }
                lastType = type;
            }

            // 将尾部空行删除只保留一个
            endEmpty.ForEach(x => orders.RemoveAt(x));
            orders.Add(new CsOrderView.CsOrderImport());

            foreach (var order in orders)
            {
                var type = ExcelRowType(order);
                if (type == ExcelRow.Other)
                {
                    return(Json(new ResModel
                    {
                        ResStatus = ResStatue.No,
                        Data = "当前Excel中不满足格式的单元格,请仔细确认数据, 数据一旦上传将无法撤回"
                    }));
                }
                if (type == ExcelRow.Empty)
                {
                    data.Add(item);
                    item = new CsOrderView.CsOrderAndDetail();
                    continue;
                }
                var product = products.FirstOrDefault(x => x.ProductNumber == order.商品编码);
                var part    = parts.FirstOrDefault(x => x.PartNumber == order.商品编码);
                var pId     = 0;            // 商品Id
                var cType   = ChoseType.螃蟹; // 蟹或配件
                if (product == null && part == null)
                {
                    return(Json(new ResModel
                    {
                        ResStatus = ResStatue.No,
                        Data = $"商品编码:{order.商品编码},不存在与数据库中,请仔细确认数据"
                    }));
                }
                if (product != null)
                {
                    pId   = product.ProductId;
                    cType = ChoseType.螃蟹;
                }
                if (part != null)
                {
                    pId   = part.PartId;
                    cType = ChoseType.配件;
                }
                if (type == ExcelRow.Order)
                {
                    var user = users.FirstOrDefault(x => x.UserPhone == order.收货人电话 && x.UserName == order.收货人);
                    int userId;
                    if (user == null)
                    {
                        user = new CsUsers
                        {
                            UserSex     = "先生",
                            UserName    = order.收货人,
                            UserPhone   = order.收货人电话,
                            OpenId      = "",
                            Remarks     = "",
                            TotalWight  = 0,
                            UserBalance = 0,
                            UserState   = 1
                        };
                        userId = _csUsersBll.Add(user);
                    }
                    else
                    {
                        userId = user.UserId;
                    }
                    Thread.Sleep(5);
                    item.CsOrder = new CsOrder
                    {
                        RowStatus      = RowStatus.效.GetHashCode(),
                        DeleteDescribe = "",
                        OrderState     = OrderState.已发货.GetHashCode(),
                        UserId         = userId,
                        ActualMoney    = order.实收金额.ToDecimal(),
                        OrderDelivery  = order.货运单号,
                        SendAddress    = $"{order.发货人}${order.发货人电话}",
                        OrderAddress   = $"${order.收货人}" + $"({user.UserSex})$${order.收货人电话}${order.收货地址})",
                        DeleteDate     = "1900-1-1".ToDate(),
                        DiscountMoney  = order.总金额.ToDecimal() - order.实收金额.ToDecimal(),
                        OrderDate      = DateTime.Now,
                        OrderNumber    = DateTime.Now.ToString(OrderNumberFormat),
                        TotalMoney     = order.总金额.ToDecimal()
                    };
                    item.CsOrderDetails.Add(new CsOrderDetail
                    {
                        ProductId     = pId,
                        ProductNumber = order.数量.ToInt(),
                        ChoseType     = cType.GetHashCode(),
                        TotalPrice    = order.单价.ToDecimal() * order.数量.ToInt(),
                        UnitPrice     = order.单价.ToDecimal()
                    });
                }
                if (type == ExcelRow.Detail)
                {
                    item.CsOrderDetails.Add(new CsOrderDetail
                    {
                        ProductId     = pId,
                        ProductNumber = order.数量.ToInt(),
                        ChoseType     = cType.GetHashCode(),
                        TotalPrice    = order.单价.ToDecimal() * order.数量.ToInt(),
                        UnitPrice     = order.单价.ToDecimal()
                    });
                }
            }
            var count       = 0;
            var countDetail = 0;

            foreach (var d in data)
            {
                if (d.CsOrder.RowStatus == RowStatus.无效.GetHashCode())
                {
                    return(Json(new ResModel
                    {
                        ResStatus = ResStatue.No,
                        Data = "存在无效订单,请检查表格总的数据是否满足要求"
                    }));
                }
                var orderId = _csOrderBll.Add(d.CsOrder);
                foreach (var detail in d.CsOrderDetails)
                {
                    detail.OrderId = orderId;
                    _csOrderDetailBll.Add(detail);
                    countDetail++;
                }
                count++;
            }

            return(Json(new ResModel
            {
                ResStatus = ResStatue.Yes,
                Data = $"导入{count}条订单记录,以及共计{countDetail}条商品记录"
            }));
        }
        /// <summary>
        /// 批量更新已发货
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public ActionResult BatchDis(string path)
        {
            path = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + path.Replace("..", "");
            var fileArr  = path.Split(new[] { "/" }, StringSplitOptions.RemoveEmptyEntries);
            var fileName = fileArr[fileArr.Length - 1];
            IEnumerable <CsOrderView.CsOrderBatchDis> orders;

            try
            {
                orders = NpoiHelper.ReadExcel(path.Replace("/" + fileName, ""), fileName)
                         .ToList <CsOrderView.CsOrderBatchDis>()
                         .Where(x => !x.订单编号.IsNullOrEmpty() && !x.运单号.IsNullOrEmpty());
            }
            catch (Exception ex)
            {
                LogHelper.Log(ex.ToJson(), "execl文件读取失败");
                return(Json(new ResModel
                {
                    ResStatus = ResStatue.No,
                    Data = "execl 文件读取失败,请确认文件数据正确, 请检查日志描述"
                }));
            }

            if (!orders.Any())
            {
                return(Json(new ResModel
                {
                    ResStatus = ResStatue.No,
                    Data = "当前Excel中没有数据,请确认文件是否包含规定完整的数据"
                }));
            }
            if (orders.Any(x => x.订单编号.IsNullOrEmpty() || x.运单号.IsNullOrEmpty()))
            {
                return(Json(new ResModel
                {
                    ResStatus = ResStatue.No,
                    Data = "当前Excel中存在空数据,请确认数据的完整性, 数据一旦上传将无法撤回"
                }));
            }
            var distinct = orders.Distinct(x => x.订单编号);

            if (distinct.Count() != orders.Count())
            {
                return(Json(new
                {
                    code = ResStatue.Warn.GetHashCode(),
                    data = "存在重复的订单编号,请依据给出的数据检查, 数据一旦上传将无法撤回",
                    orderIds = orders.Except(distinct).Select(x => x.订单编号)
                }));
            }
            var data = _csOrderBll.GetModelList($" AND OrderNumber IN ('{string.Join("','", orders.Select(x => x.订单编号))}')");

            if (data.Count != orders.Count())
            {
                return(Json(new
                {
                    code = ResStatue.Warn.GetHashCode(),
                    data = "存在有误的订单编号,请依据给出的数据检查, 数据一旦上传将无法撤回",
                    orderIds = orders.Select(x => x.订单编号.Trim()).Except(data.Select(x => x.OrderNumber))
                }));
            }
            var count = 0;

            foreach (var order in orders)
            {
                var sh = new SqlHelper <CsOrder>();
                sh.AddUpdate("OrderState", OrderState.已发货.GetHashCode());
                sh.AddUpdate("OrderDelivery", order.运单号);
                sh.AddWhere($" AND OrderNumber = '{order.订单编号}'");
                count += sh.Update();
            }
            return(Json(new ResModel
            {
                ResStatus = ResStatue.Yes,
                Data = $"更新成功, 共计更新{count}条数据."
            }));
        }
Exemple #3
0
        /// <summary>
        /// 上传主函数
        /// </summary>
        public void Upload()
        {
            DataTable dt = new DataTable();

            dt.Columns.Add("result");
            dt.Columns.Add("message");

            if (context.Request.Files.Count == 0)
            {
                dt.Rows.Add(new object[] { "False", "文件过大或提交的信息有误!" });
            }
            else
            {

                string strFileName = Path.GetFileName(context.Request.Files[0].FileName);
                string strFileNameSelfDef = "";

                if (context.Request["fileName"] != null && context.Request["fileName"].ToString() != "")
                {
                    strFileNameSelfDef = context.Request["fileName"].ToString();
                }
                string strExtension = Path.GetExtension(context.Request.Files[0].FileName).ToLower();

                if (strFileNameSelfDef == "")
                {
                    strFileName = strFileName.Substring(0, strFileName.Length - strExtension.Length) + "-" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + strExtension;

                }
                else
                {
                    strFileName = strFileNameSelfDef + strExtension;
                }

                string strFilePath = context.Request["filepath"];
                if (string.IsNullOrEmpty(strFilePath))
                {
                    dt.Rows.Add(new object[] { "False", "filepath不能为空" });
                }
                else
                {

                    int fileSize = 1024 * 1024 * 20; //20M
                    HttpPostedFile postedFile = context.Request.Files[0];
                    if (postedFile.ContentLength > fileSize)
                    {
                        dt.Rows.Add(new object[] { "False", "最大只能上传20M文件" });
                    }
                    else
                    {

                        strFilePath = "/" + strFilePath + "/" + strFileName;
                        string strLocation = context.Server.MapPath("upload") + strFilePath;
                        context.Request.Files[0].SaveAs(strLocation);

                        if (GetFileType(strFileName) == FileType.Excel)
                        {
                            //读取EXCEL信息
                            NpoiHelper excel = new NpoiHelper();
                            m_dsExcelData = excel.ReadExcel(strLocation);

                        }
                        else if (GetFileType(strFileName) == FileType.Pic)
                        {
                            if (context.Request["filepath"] == "HZY_mat")
                            {
                                CreateThumbnail(strLocation, 200, 200);
                            }
                            dt.Rows.Add(new object[] { "True", "/upload" + strFilePath + "" });
                            dt.Rows.Add(new object[] { "文件大小", postedFile.ContentLength });
                        }
                        else
                        {
                            dt.Rows.Add(new object[] { "False", "文件类型不认识!" });

                        }

                    }
                }
            }

            if (context.Request["WSID"] == null)
            {
                string strJSON = HZY.COM.Common.JsonHelper.CreateJsonParameters(dt);
                context.Response.Write(strJSON);
            }
        }