public IActionResult IndexPost()
        {
            List <BuyProductViewModel> lstCartItems = HttpContext.Session.Get <List <BuyProductViewModel> >("ssShoppingCart");
            double Total = 0.0;

            Clients    client    = ShoppingCartVM.client;
            SaleOrders saleOrder = new SaleOrders()
            {
                Description = ShoppingCartVM.Description,
                OrderDate   = DateTime.Now
            };

            // Xử lí thông tin người mua & tạo đơn hàng
            if (_db.clients.Where(m => m.Name == client.Name).Count() == 0)
            {
                _db.clients.Add(client);
                _db.SaveChanges();
                saleOrder.ClientId = _db.clients
                                     .OrderByDescending(x => x.Id)
                                     .Take(1)
                                     .Select(x => x.Id)
                                     .FirstOrDefault();
                _db.saleOrders.Add(saleOrder);
                _db.SaveChanges();
            }
            else
            {
                saleOrder.ClientId = _db.clients.Where(m => m.Name == client.Name).Select(x => x.Id).FirstOrDefault();
                _db.saleOrders.Add(saleOrder);
                _db.SaveChanges();
            }

            // Xử lí các sp người đó mua
            int saleOrderId = _db.saleOrders
                              .OrderByDescending(x => x.Id)
                              .Take(1)
                              .Select(x => x.Id)
                              .FirstOrDefault();

            foreach (BuyProductViewModel product in lstCartItems)
            {
                Products prod = new Products();
                prod        = _db.products.Where(m => m.Id == product.productId).FirstOrDefault();
                Total      += prod.DefaultSellingPrice;
                prod.Stock -= product.amount;
                SaleOrderDetails saleOrderDetail = new SaleOrderDetails()
                {
                    SaleOrderId     = saleOrderId,
                    ExportProductId = prod.Id,
                    Description     = "Xuất hàng theo hóa đơn của khách hàng " + client.Id,
                    Quantity        = product.amount,
                    Total           = prod.DefaultSellingPrice * product.amount
                };
                _db.saleOrderDetails.Add(saleOrderDetail);
                _db.SaveChanges();
            }

            // Cập nhật giá trị đơn hàng
            saleOrder.Total = (float)Total;
            _db.SaveChanges();

            lstCartItems = new List <BuyProductViewModel>();
            HttpContext.Session.Set("ssShoppingCart", lstCartItems);

            return(RedirectToAction("SaleOrderConfirmation", "ShoppingCart", new { id = saleOrderId }));
        }
예제 #2
0
        public void SaveOrder(Sale.ShoppingCart shoppingCart, string apiCodes, DateTime saveTime)
        {
            try
            {
                //SaleOrders SaleDetail SaleDetailsTotal
                var        saleOrders = shoppingCart.GetSaleStatistics();//销售清单
                SaleOrders _saleOrder = new SaleOrders()
                {
                    StoreId           = shoppingCart.MachineInformation.StoreId,    //门店id
                    MachineSN         = shoppingCart.MachineInformation.MachineSn,  //pos机号
                    PaySN             = shoppingCart.OrderSN,                       //订单流水号
                    CustomOrderSn     = shoppingCart.CustomOrderSN,                 //订单流水号
                    TotalAmount       = saleOrders.Receivable,                      //优惠后金额
                    PreferentialPrice = saleOrders.Preferential,                    //优惠金额
                    ApiCode           = apiCodes,                                   //支付方式  TODO:
                    CreateUID         = shoppingCart.MachineInformation.CashierUid, //收银员工号
                    CreateDT          = saveTime,
                    CompanyId         = CompanyId,
                    ProductCount      = saleOrders.Num,
                    Type          = 0,
                    State         = 0,
                    MemberId      = shoppingCart.MemberId,
                    ActivityId    = shoppingCart.ActivityId,
                    Salesman      = shoppingCart.SaleMan,
                    Receive       = shoppingCart.WipeZeroAfter,
                    IsTest        = IsSalesclerkTest,
                    InInventory   = 0,
                    IsProcess     = false,
                    OrderDiscount = shoppingCart.OrderDiscount
                };
                SaleOrdersService.CurrentRepository.Add(_saleOrder, false);

                var saleOrdersDetails = shoppingCart.GetOrdeList();//订单信息
                foreach (var item in saleOrdersDetails)
                {
                    SaleDetail _saleDetail = new SaleDetail()
                    {
                        PaySN           = _saleOrder.PaySN,
                        ProductCode     = item.ProductCode,
                        AveragePrice    = item.AveragePrice,//均价
                        CompanyId       = CompanyId,
                        Total           = item.Details.Total,
                        Barcode         = item.MainBarcode,         //商品条码
                        PurchaseNumber  = item.SaleNumber,          //销售数量
                        BuyPrice        = item.Details.BuyPrice,    //系统进价
                        SysPrice        = item.Details.SystemPrice, //系统售价
                        ActualPrice     = item.MarketingPrice,      //销售价
                        Title           = item.Details.Title,
                        ScanBarcode     = item.CurrentString,
                        SalesClassifyId = (int)item.Details.SaleStatus,//销售分类id
                    };
                    SaleDetailService.CurrentRepository.Add(_saleDetail, false);
                }
                SaleOrdersService.CurrentRepository.Update(_saleOrder);
                var orderEvent = new OrderCompletedEvent()
                {
                    MemberId           = shoppingCart.MemberId,
                    CompanyId          = CompanyId,
                    MachineSn          = MachineSN,
                    StoreId            = StoreId,
                    OrderAmount        = saleOrders.Receivable,
                    OrderProductCount  = saleOrders.Num,
                    SourceRecordId     = shoppingCart.OrderSN,
                    OrderReceiveAmount = shoppingCart.WipeZeroAfter,
                    OperatorUid        = shoppingCart.MachineInformation.CashierUid,
                    OrderDetails       = shoppingCart.GetOrdeList().Select(o =>
                                                                           new OrderDetail()
                    {
                        AveragePrice    = o.AveragePrice,
                        ActualPrice     = o.MarketingPrice,
                        Barcode         = o.MainBarcode,
                        PurchaseNumber  = o.SaleNumber,
                        BuyPrice        = o.Details.BuyPrice,
                        ProductCode     = o.ProductCode,
                        SalesClassifyId = (int)o.Details.SaleStatus,
                        ScanBarcode     = o.CurrentString,
                        SysPrice        = o.Details.SystemPrice,
                        Title           = o.Details.Title,
                        Total           = o.Details.Total,
                        Category        = o.Details.Category,
                        Size            = o.Details.Size
                    })
                };
                RedisManager.Publish <OrderCompletedEvent>("OrderCompleted", orderEvent);
            }
            catch (Exception ex)
            {
                throw;
            }
        }
예제 #3
0
        public DateTime ChangeOrRefund(Sale.AfterSale.OrderChangeRefundSale changeList, int reason, MachineInformation machineInformation, string newPaySn, decimal amount, decimal receive, string uid, string apiCodes, DateTime saveTime, string saleman, string oldOrderSn)
        {
            //to do save change
            //orders
            var oldOrder = (from a in SaleOrdersService.CurrentRepository.Entities.Where(o => o.StoreId == machineInformation.StoreId && o.CompanyId == machineInformation.CompanyId && o.CustomOrderSn == oldOrderSn)
                            join b in SaleDetailService.CurrentRepository.Entities
                            on a.PaySN equals b.PaySN
                            select new
            {
                a,
                b
            }).ToList();

            try
            {
                SaleOrders _saleOrder = new SaleOrders()
                {
                    PaySN             = changeList.PaySn,
                    CustomOrderSn     = changeList.CustomOrderSn,
                    MachineSN         = machineInformation.MachineSn,
                    StoreId           = machineInformation.StoreId,
                    TotalAmount       = amount,
                    Receive           = receive,
                    PreferentialPrice = 0,
                    ApiCode           = apiCodes,
                    CreateUID         = machineInformation.CashierUid,
                    CreateDT          = saveTime,
                    ReturnDT          = saveTime,
                    CompanyId         = machineInformation.CompanyId,
                    ProductCount      = changeList.RecordCount,
                    Type        = (short)changeList.Mode,
                    State       = 0,
                    MemberId    = null,
                    IsTest      = IsSalesclerkTest,
                    InInventory = 0,
                    IsProcess   = false,
                    Reason      = reason,
                    Salesman    = saleman,                //退换货原导购员  来自客户端
                    ReFundOrderCustomOrderSn = oldOrderSn //退换货原单号 来自客户端
                };
                SaleOrdersService.CurrentRepository.Add(_saleOrder, false);
                foreach (var item in changeList.ChangingList)
                {
                    var buyPrice = 0m;
                    if (oldOrder != null)
                    {
                        foreach (var itm in oldOrder)
                        {
                            if ((short)changeList.Mode == 2)
                            {
                                if (itm.b.Barcode == item.CurrentBarcode.MainBarcode)
                                {
                                    buyPrice = itm.b.BuyPrice;
                                }
                            }
                            else
                            {
                                if (itm.b.PurchaseNumber > 0)
                                {
                                    buyPrice = item.BuyPrice;
                                }
                                else
                                {
                                    if (itm.b.Barcode == item.CurrentBarcode.MainBarcode)
                                    {
                                        buyPrice = itm.b.BuyPrice;
                                    }
                                }
                            }
                        }
                    }
                    SaleDetail _saleDetail = new SaleDetail()
                    {
                        PaySN           = changeList.PaySn,
                        ScanBarcode     = item.CurrentBarcode.CurrentString,
                        ProductCode     = item.CurrentBarcode.ProductCode,
                        AveragePrice    = item.ChangePrice,//均价
                        CompanyId       = machineInformation.CompanyId,
                        Total           = item.ChangePrice * item.ChangeNumber,
                        Barcode         = item.CurrentBarcode.MainBarcode,
                        PurchaseNumber  = item.ChangeNumber,
                        BuyPrice        = buyPrice,//进价
                        SysPrice        = item.SysPrice,
                        ActualPrice     = item.ChangePrice,
                        SalesClassifyId = (int)item.SaleStatus,
                        Title           = item.CurrentBarcode.Details.Title
                    };
                    SaleDetailService.CurrentRepository.Add(_saleDetail, false);
                }
                SaleOrdersService.CurrentRepository.Update(_saleOrder);
            }
            catch (Exception ex)
            {
                throw;
            }

            return(saveTime);
        }
예제 #4
0
        /// <summary>
        /// 后台退货
        /// </summary>
        /// <param name="reason">换货理由(字典值)</param>
        /// <param name="retprice">顾客补价</param>
        /// <param name="returnDetailsStr">换货明细JSON字符串</param>
        /// <param name="payno">销售单流水号</param>
        /// <returns>OpResult</returns>
        public static OpResult SaveTui(int reason, decimal?retprice, string returnDetailsStr, string payno, bool returnAll = false)
        {
            var op   = OpResult.Fail();
            var olds = returnDetailsStr.ToObject <List <TuiHuan> >();

            if (!olds.Any())
            {
                op.Message = "退货商品信息不能为空";
            }
            else
            {
                if (!payno.IsNullOrEmpty() && returnAll)
                {
                    var obj = BaseService <SaleOrders> .Find(o => o.CompanyId == CommonService.CompanyId && o.PaySN == payno);

                    if (obj == null)
                    {
                        op.Message = "输入流水号不存在!";
                    }
                    else
                    {
                        obj.State          = 1;
                        obj.IsProcess      = false;
                        obj.Receive        = -(Math.Abs(obj.Receive));
                        obj.Reason         = reason;
                        obj.ReturnDT       = DateTime.Now;
                        obj.ReturnOrderUID = CurrentUser.UID;
                        op = BaseService <SaleOrders> .Update(obj);
                    }
                }
                else
                {
                    payno = CommonRules.PaySN;
                    var saleObj = new SaleOrders()
                    {
                        ApiCode           = "11",
                        MachineSN         = "-1",
                        CreateDT          = DateTime.Now,
                        CreateUID         = Sys.CurrentUser.UID,
                        PaySN             = payno,
                        TotalAmount       = retprice.GetValueOrDefault(),
                        Receive           = retprice.GetValueOrDefault(),
                        PreferentialPrice = 0,
                        StoreId           = Sys.CurrentUser.StoreId,
                        Type      = 2,
                        Reason    = reason,
                        CompanyId = CommonService.CompanyId,
                        Memo      = "后台退货新单"
                    };
                    var newSaleDetails = new List <SaleDetail>();
                    olds.Each(o =>
                    {
                        newSaleDetails.Add(new SaleDetail()
                        {
                            ActualPrice     = o.SysPrice,
                            SysPrice        = o.SysPrice,
                            Total           = o.Total,
                            BuyPrice        = 0,
                            Barcode         = o.OldBarcode,
                            ScanBarcode     = o.Barcode,
                            Title           = o.Title,
                            ProductCode     = o.ProductCode,
                            PaySN           = saleObj.PaySN,
                            PurchaseNumber  = o.Number,
                            SalesClassifyId = 0,
                            CompanyId       = saleObj.CompanyId,
                            Memo            = ""
                        });
                    });
                    BaseService <SaleOrders> .Add(saleObj, false);

                    op = BaseService <SaleDetail> .AddRange(newSaleDetails);
                }
                if (op.Successed)
                {
                    dal.UpdateTuiHuanStock();
                }
            }
            return(op);
        }
예제 #5
0
 public OperateResult SureImport()
 {
     try
     {
         var dt = _cacheService.GetObject <DataTable>(CacheKey);
         if (dt == null || dt.Rows.Count <= 0)
         {
             return(OperateResult.Fail("预览已过期,请重新选择导入!"));
         }
         var saleOrders = new List <SaleOrders>();
         var salelist   = dt.AsEnumerable().GroupBy(o => new { ApiOrderSN = o["ApiOrderSN"].ToString() }).ToList();
         var dates      = dt.AsEnumerable().GroupBy(o => o.GetValue("SaleDate").ToType <DateTime>().ToString("yyyy-MM-dd")).Select(o => o.Key).ToArray();
         var saleSvc    = AutofacBootstapper.CurrentContainer.Resolve <ISaleOrderRepository>();
         var dicts      = saleSvc.GetMaxNumByDate(dates);
         var companyId  = SysUserService.CurrentUser.CompanyId;
         foreach (var sl in salelist)
         {
             var sn       = sl.Key.ApiOrderSN;
             var datetime = sl.Max(o => Convert.ToDateTime(o["SaleDate"]));
             var pre      = "00" + datetime.ToString("yyyyMMdd");
             if (dicts.ContainsKey(pre))
             {
                 dicts[pre] += 1;
             }
             else
             {
                 dicts[pre] = 1;
             }
             var sale = new SaleOrders();
             sale.CustomOrderSn = pre + dicts[pre].ToString("0000");
             sale.MachineSN     = "00";
             sale.CompanyId     = companyId;
             sale.CreateDT      = datetime;
             sale.PaySN         = Guid.NewGuid().ToString("n");
             sale.CreateUID     = sl.Max(o => o.GetValue("CreateUID2").ToString());
             sale.Salesman      = sl.Max(o => o.GetValue("Salesman2").ToString());
             sale.StoreId       = sl.Max(o => o.GetValue("StoreId").ToString());
             sale.Receive       = sl.Max(o => o.GetValue("Receive").ToType <decimal>());
             sale.TotalAmount   = sl.Max(o => o.GetValue("TotalAmount").ToType <decimal>());
             sale.Type          = sl.Max(o => o.GetValue("Type").ToType <short>());
             sale.OrderDiscount = sl.Max(o => o.GetValue("OrderDiscount").ToType <decimal>());
             if (sl.Max(o => o.GetValue("InInventory").ToType <short>()) == 0)
             {
                 sale.InInventory = 1;
                 sale.IsProcess   = true;
             }
             sale.SaleDetails         = new List <SaleDetail>();
             sale.ConsumptionPayments = new List <ConsumptionPayment>();
             sale.WipeZeros           = new List <WipeZero>();
             var ApiCode_11 = sl.Max(o => o.GetValue("ApiCode_11").ToString());
             var ApiCode_12 = sl.Max(o => o.GetValue("ApiCode_12").ToString());
             var ApiCode_20 = sl.Max(o => o.GetValue("ApiCode_20").ToString());
             var ApiCode_21 = sl.Max(o => o.GetValue("ApiCode_21").ToString());
             var ApiCode_19 = sl.Max(o => o.GetValue("ApiCode_19").ToString());
             var ApiCode_15 = sl.Max(o => o.GetValue("ApiCode_15").ToString());
             var WipeZero   = sl.Max(o => o.GetValue("WipeZero").ToString());
             if (!(ApiCode_11.IsNullOrEmpty() || ApiCode_11 == "0"))
             {
                 var payment = new ConsumptionPayment()
                 {
                     ApiOrderSN = sn,
                     CompanyId  = sale.CompanyId,
                     PaySN      = sale.PaySN,
                     State      = 1
                 };
                 payment.ApiCode  = 11;
                 payment.Change   = sl.Max(o => o.GetValue("Change").ToType <decimal>());
                 payment.Received = ApiCode_11.ToType <decimal>();
                 payment.Amount   = payment.Received - payment.Change;
                 sale.ConsumptionPayments.Add(payment);
             }
             if (!(ApiCode_12.IsNullOrEmpty() || ApiCode_12 == "0"))
             {
                 var payment = new ConsumptionPayment()
                 {
                     Amount     = ApiCode_12.ToType <decimal>(),
                     ApiOrderSN = sn,
                     CompanyId  = sale.CompanyId,
                     PaySN      = sale.PaySN,
                     State      = 1
                 };
                 payment.ApiCode  = 12;
                 payment.Received = payment.Amount;
                 sale.ConsumptionPayments.Add(payment);
             }
             if (!(ApiCode_20.IsNullOrEmpty() || ApiCode_20 == "0"))
             {
                 var payment = new ConsumptionPayment()
                 {
                     Amount     = ApiCode_20.ToType <decimal>(),
                     ApiOrderSN = sn,
                     CompanyId  = sale.CompanyId,
                     PaySN      = sale.PaySN,
                     State      = 1
                 };
                 payment.ApiCode  = 20;
                 payment.Received = payment.Amount;
                 sale.ConsumptionPayments.Add(payment);
             }
             if (!(ApiCode_21.IsNullOrEmpty() || ApiCode_21 == "0"))
             {
                 var payment = new ConsumptionPayment()
                 {
                     Amount     = ApiCode_21.ToType <decimal>(),
                     ApiOrderSN = sn,
                     CompanyId  = sale.CompanyId,
                     PaySN      = sale.PaySN,
                     State      = 1
                 };
                 payment.ApiCode  = 21;
                 payment.Received = payment.Amount;
                 sale.ConsumptionPayments.Add(payment);
             }
             if (!(ApiCode_19.IsNullOrEmpty() || ApiCode_19 == "0"))
             {
                 var payment = new ConsumptionPayment()
                 {
                     Amount     = ApiCode_19.ToType <decimal>(),
                     ApiOrderSN = sn,
                     CompanyId  = sale.CompanyId,
                     PaySN      = sale.PaySN,
                     State      = 1
                 };
                 payment.ApiCode  = 19;
                 payment.Received = payment.Amount;
                 sale.ConsumptionPayments.Add(payment);
             }
             if (!(ApiCode_15.IsNullOrEmpty() || ApiCode_15 == "0"))
             {
                 var payment = new ConsumptionPayment()
                 {
                     Amount     = ApiCode_15.ToType <decimal>(),
                     ApiOrderSN = sn,
                     CompanyId  = sale.CompanyId,
                     PaySN      = sale.PaySN,
                     State      = 1
                 };
                 payment.ApiCode  = 15;
                 payment.Received = payment.Amount;
                 sale.ConsumptionPayments.Add(payment);
             }
             if (sale.ConsumptionPayments.Count <= 0)
             {
                 var payment = new ConsumptionPayment()
                 {
                     ApiOrderSN = sn,
                     CompanyId  = sale.CompanyId,
                     PaySN      = sale.PaySN,
                     State      = 1
                 };
                 payment.ApiCode  = 11;
                 payment.Received = 0;
                 payment.Amount   = 0;
                 payment.Change   = 0;
                 sale.ConsumptionPayments.Add(payment);
             }
             if (!(WipeZero.IsNullOrEmpty()))
             {
                 sale.WipeZeros.Add(new WipeZero()
                 {
                     CompanyId = sale.CompanyId,
                     PaySN     = sale.PaySN,
                     Number    = WipeZero.ToType <decimal>()
                 });
             }
             foreach (DataRow dr in dt.Select("ApiOrderSN='" + sn + "'"))
             {
                 var detail = new SaleDetail()
                 {
                     ActualPrice     = dr.GetValue("ActualPrice").ToType <decimal>(),
                     Barcode         = dr.GetValue("Barcode").ToString(),
                     BuyPrice        = dr.GetValue("BuyPrice").ToType <decimal>(),
                     CompanyId       = sale.CompanyId,
                     PaySN           = sale.PaySN,
                     ProductCode     = dr.GetValue("ProductCode").ToString(),
                     PurchaseNumber  = dr.GetValue("PurchaseNumber").ToType <decimal>(),
                     SalesClassifyId = dr.GetValue("SalesClassifyId2").ToType <int>(),
                     ScanBarcode     = dr.GetValue("Barcode").ToString(),
                     SysPrice        = dr.GetValue("SysPrice").ToType <decimal>(),
                     Title           = dr.GetValue("Title").ToString(),
                 };
                 sale.ProductCount += dr["ValuationType"].ToString() == "2" ? 1 : detail.PurchaseNumber;
                 var subt = dr.GetValue("SubTotal");
                 detail.Total        = subt is DBNull ? detail.PurchaseNumber * detail.ActualPrice : subt.ToType <decimal>();
                 detail.AveragePrice = detail.Total / detail.PurchaseNumber;
                 sale.SaleDetails.Add(detail);
             }
             sale.ApiCode = string.Join(",", sale.ConsumptionPayments.Select(o => o.ApiCode));
             //var total = sale.SaleDetails.Sum(o => o.Total);
             //var rate =total==0?0: sale.Receive / total;
             //sale.SaleDetails.Each(o => o.AveragePrice = o.ActualPrice * rate);
             saleOrders.Add(sale);
         }
         OperateResult op = saleSvc.AddOrUpdate(saleOrders.ToArray());
         if (op.Successed)
         {
             _cacheService.RemoveObject <DataTable>(CacheKey);
             var user = SysUserService.CurrentUser;
             LoggerFactory.CreateWithSave <SysLog>(new SysLog(user.CompanyId, user.UserID).Analysis("销售数据导入", null, LogType.其他, LogModule.其他));
             //var stores = string.Join(",", saleOrders.Select(o => o.StoreId).Distinct());
             //Pharos.Infrastructure.Data.Redis.RedisManager.Publish("SyncDatabase", new Pharos.ObjectModels.DTOs.DatabaseChanged() { CompanyId = Sys.SysCommonRules.CompanyId, StoreId = stores, Target = "SalePackage" });
         }
         return(op);
     }
     catch (Exception ex)
     {
         var user = SysUserService.CurrentUser;
         LoggerFactory.CreateWithSave <SysLog>(new SysLog(user.CompanyId, user.UserID).WriteError(ex, LogModule.其他));
         return(OperateResult.Fail());
     }
 }
        public void SaveOrder(Sale.ShoppingCart shoppingCart, string apiCodes, DateTime saveTime)
        {
            try
            {
                //SaleOrders SaleDetail SaleDetailsTotal
                var saleOrders = shoppingCart.GetSaleStatistics();//销售清单
                var version    = new byte[8] {
                    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01
                };
                SaleOrders _saleOrder = new SaleOrders()
                {
                    StoreId           = shoppingCart.MachineInformation.StoreId,    //门店id
                    MachineSN         = shoppingCart.MachineInformation.MachineSn,  //pos机号
                    PaySN             = shoppingCart.OrderSN,                       //订单流水号
                    CustomOrderSn     = shoppingCart.CustomOrderSN,                 //订单流水号
                    TotalAmount       = saleOrders.Receivable,                      //优惠后金额
                    PreferentialPrice = saleOrders.Preferential,                    //优惠金额
                    ApiCode           = apiCodes,                                   //支付方式  TODO:
                    CreateUID         = shoppingCart.MachineInformation.CashierUid, //收银员工号
                    CreateDT          = saveTime,
                    CompanyId         = CompanyId,
                    ProductCount      = saleOrders.Num,
                    Type            = 0,
                    State           = 0,
                    MemberId        = shoppingCart.MemberId,
                    ActivityId      = shoppingCart.ActivityId,
                    Salesman        = shoppingCart.SaleMan,
                    Receive         = shoppingCart.WipeZeroAfter,
                    IsTest          = IsSalesclerkTest,
                    InInventory     = 0,
                    IsProcess       = false,
                    OrderDiscount   = shoppingCart.OrderDiscount,
                    SyncItemId      = Guid.NewGuid(),
                    SyncItemVersion = version
                };
                SaleOrdersService.CurrentRepository.Add(_saleOrder, false);

                var saleOrdersDetails = shoppingCart.GetOrdeList();//订单信息
                foreach (var item in saleOrdersDetails)
                {
                    SaleDetail _saleDetail = new SaleDetail()
                    {
                        PaySN           = _saleOrder.PaySN,
                        ProductCode     = item.ProductCode,
                        AveragePrice    = item.AveragePrice,//均价
                        CompanyId       = CompanyId,
                        Total           = item.Details.Total,
                        Barcode         = item.MainBarcode,         //商品条码
                        PurchaseNumber  = item.SaleNumber,          //销售数量
                        BuyPrice        = item.Details.BuyPrice,    //系统进价
                        SysPrice        = item.Details.SystemPrice, //系统售价
                        ActualPrice     = item.MarketingPrice,      //销售价
                        Title           = item.Details.Title,
                        ScanBarcode     = item.CurrentString,
                        SalesClassifyId = (int)item.Details.SaleStatus,//销售分类id
                        SyncItemId      = Guid.NewGuid(),
                        SyncItemVersion = version
                    };
                    SaleDetailService.CurrentRepository.Add(_saleDetail, false);
                }
                SaleOrdersService.CurrentRepository.Update(_saleOrder);
                //  RedisManager.Publish("SyncDatabase", "SalePackage");
                StoreManager.PubEvent("SyncDatabase", "SalePackage");
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        public DateTime ChangeOrRefund(Sale.AfterSale.OrderChangeRefundSale changeList, int reason, MachineInformation machineInformation, string newPaySn, decimal amount, decimal receive, string uid, string apiCodes, DateTime saveTime, string saleman, string oldOrderSn)
        {
            try
            {
                var oldOrder = (from a in SaleOrdersService.CurrentRepository.Entities.Where(o => o.StoreId == machineInformation.StoreId && o.CompanyId == machineInformation.CompanyId && o.CustomOrderSn == oldOrderSn)
                                join b in SaleDetailService.CurrentRepository.Entities
                                on a.PaySN equals b.PaySN
                                select new
                {
                    a,
                    b
                });

                var version = new byte[8] {
                    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01
                };

                SaleOrders _saleOrder = new SaleOrders()
                {
                    PaySN             = changeList.PaySn,
                    CustomOrderSn     = changeList.CustomOrderSn,
                    MachineSN         = machineInformation.MachineSn,
                    StoreId           = machineInformation.StoreId,
                    TotalAmount       = amount,
                    Receive           = receive,
                    PreferentialPrice = 0,
                    ApiCode           = apiCodes,
                    CreateUID         = machineInformation.CashierUid,
                    CreateDT          = saveTime,
                    ReturnDT          = saveTime,
                    CompanyId         = machineInformation.CompanyId,
                    ProductCount      = changeList.RecordCount,
                    Type                     = (short)changeList.Mode,
                    State                    = 0,
                    MemberId                 = null,
                    IsTest                   = IsSalesclerkTest,
                    InInventory              = 0,
                    IsProcess                = false,
                    Reason                   = reason,
                    SyncItemId               = Guid.NewGuid(),
                    SyncItemVersion          = version,
                    Salesman                 = saleman,
                    ReFundOrderCustomOrderSn = oldOrderSn
                };
                SaleOrdersService.CurrentRepository.Add(_saleOrder, false);
                foreach (var item in changeList.ChangingList)
                {
                    var buyPrice = 0m;
                    if (oldOrder != null)
                    {
                        foreach (var itm in oldOrder)
                        {
                            if ((short)changeList.Mode == 2)
                            {
                                if (itm.b.Barcode == item.CurrentBarcode.MainBarcode)
                                {
                                    buyPrice = itm.b.BuyPrice;
                                }
                            }
                            else
                            {
                                if (itm.b.PurchaseNumber > 0)
                                {
                                    var isWeight = false;
                                    if (itm.b.Barcode.Length == 13 && itm.b.ScanBarcode.Substring(0, 2) == "27")
                                    {
                                        isWeight = true;
                                    }
                                    var productInfo = GetProductInfoByBarcode(itm.b.ScanBarcode, isWeight);
                                    if (productInfo != null)
                                    {
                                        buyPrice = productInfo.BuyPrice;
                                    }
                                }
                                else
                                {
                                    if (itm.b.Barcode == item.CurrentBarcode.MainBarcode)
                                    {
                                        buyPrice = itm.b.BuyPrice;
                                    }
                                }
                            }
                        }
                    }
                    SaleDetail _saleDetail = new SaleDetail()
                    {
                        PaySN           = changeList.PaySn,
                        ScanBarcode     = item.CurrentBarcode.CurrentString,
                        ProductCode     = item.CurrentBarcode.ProductCode,
                        AveragePrice    = item.ChangePrice,//均价
                        CompanyId       = machineInformation.CompanyId,
                        Total           = item.ChangePrice * item.ChangeNumber,
                        Barcode         = item.CurrentBarcode.MainBarcode,
                        PurchaseNumber  = item.ChangeNumber,
                        BuyPrice        = buyPrice,//进价
                        SysPrice        = item.SysPrice,
                        ActualPrice     = item.ChangePrice,
                        SalesClassifyId = (int)item.SaleStatus,
                        Title           = item.CurrentBarcode.Details.Title,
                        SyncItemId      = Guid.NewGuid(),
                        SyncItemVersion = version
                    };
                    SaleDetailService.CurrentRepository.Add(_saleDetail, false);
                }
                SaleOrdersService.CurrentRepository.Update(_saleOrder);
                //RedisManager.Publish("SyncDatabase", "SalePackage");
                StoreManager.PubEvent("SyncDatabase", "SalePackage");
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return(saveTime);
        }
        public DateTime RefundAll(int reason, string customOrderSn, decimal amount, string uid, string apiCodes, string newOrderSn, string newCustomOrderSn, DateTime createdt)
        {
            var order   = SaleOrdersService.CurrentRepository.Entities.FirstOrDefault(o => o.CompanyId == CompanyId && o.CustomOrderSn == customOrderSn && o.StoreId == StoreId && o.State == 0);
            var version = new byte[8] {
                0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01
            };
            var newOrder = new SaleOrders()
            {
                StoreId                  = order.StoreId,           //门店id
                MachineSN                = order.MachineSN,         //pos机号
                PaySN                    = newOrderSn,              //订单流水号
                CustomOrderSn            = newCustomOrderSn,        //订单流水号
                ReFundOrderCustomOrderSn = order.CustomOrderSn,     //原订单流水号
                TotalAmount              = -order.TotalAmount,      //优惠后金额
                PreferentialPrice        = order.PreferentialPrice, //优惠金额
                ApiCode                  = apiCodes,                //支付方式  TODO:
                CreateUID                = uid,                     //收银员工号
                ReturnOrderUID           = uid,
                ReturnDT                 = createdt,
                CreateDT                 = createdt,
                CompanyId                = order.CompanyId,
                ProductCount             = -order.ProductCount,
                Reason                   = reason,
                Type            = 3,
                State           = 1,
                MemberId        = order.MemberId,
                ActivityId      = order.ActivityId,
                Salesman        = order.Salesman,
                Receive         = -order.Receive,
                IsTest          = IsSalesclerkTest,
                InInventory     = 0,
                IsProcess       = false,
                OrderDiscount   = order.OrderDiscount,
                SyncItemId      = Guid.NewGuid(),
                SyncItemVersion = version
            };
            var saleOrdersDetails = SaleDetailService.FindList(o => o.PaySN == order.PaySN).ToList();

            foreach (var item in saleOrdersDetails)
            {
                SaleDetail _saleDetail = new SaleDetail()
                {
                    PaySN           = newOrderSn,
                    ProductCode     = item.ProductCode,
                    AveragePrice    = item.AveragePrice,//均价
                    CompanyId       = CompanyId,
                    Total           = -item.Total,
                    Barcode         = item.Barcode,         //商品条码
                    PurchaseNumber  = -item.PurchaseNumber, //销售数量
                    BuyPrice        = item.BuyPrice,        //系统进价
                    SysPrice        = item.SysPrice,        //系统售价
                    ActualPrice     = item.ActualPrice,     //销售价
                    Title           = item.Title,
                    ScanBarcode     = item.ScanBarcode,
                    SalesClassifyId = item.SalesClassifyId,//销售分类id
                    SyncItemId      = Guid.NewGuid(),
                    SyncItemVersion = version
                };
                SaleDetailService.CurrentRepository.Add(_saleDetail, false);
            }
            SaleOrdersService.CurrentRepository.Add(newOrder);
            //RedisManager.Publish("SyncDatabase", "SalePackage");
            StoreManager.PubEvent("SyncDatabase", "SalePackage");
            return(createdt);
        }