Esempio n. 1
0
        public async Task BuildAsync()
        {
            using var uow = _unitOfWorkManager.Begin();

            var productDetail1 = await _productDetailRepository.InsertAsync(
                new ProductDetail(ProductsTestData.ProductDetails1Id, null, ProductsTestData.Store1Id,
                                  "Product details for store 1"), true);

            var productDetail2 = await _productDetailRepository.InsertAsync(
                new ProductDetail(ProductsTestData.ProductDetails2Id, null, ProductsTestData.Store1Id,
                                  "Product details for store 1"), true);

            var product = new Product(ProductsTestData.Product1Id, null, ProductsTestData.Store1Id, "Default",
                                      productDetail1.Id, "Cake", "Cake", InventoryStrategy.NoNeed, null, true, false, false, null, null, 0);

            var attribute1 = new ProductAttribute(ProductsTestData.Product1Attribute1Id, "Size", null, 1);
            var attribute2 = new ProductAttribute(ProductsTestData.Product1Attribute2Id, "Color", null, 2);

            attribute1.ProductAttributeOptions.AddRange(new[]
            {
                new ProductAttributeOption(ProductsTestData.Product1Attribute1Option4Id, "XL", null, 4),
                new ProductAttributeOption(ProductsTestData.Product1Attribute1Option2Id, "M", null, 2),
                new ProductAttributeOption(ProductsTestData.Product1Attribute1Option1Id, "S", null, 1),
                new ProductAttributeOption(ProductsTestData.Product1Attribute1Option3Id, "L", null, 3),
            });

            attribute2.ProductAttributeOptions.AddRange(new[]
            {
                new ProductAttributeOption(ProductsTestData.Product1Attribute2Option2Id, "Green", null, 2),
                new ProductAttributeOption(ProductsTestData.Product1Attribute2Option1Id, "Red", null, 1),
            });

            product.ProductAttributes.Add(attribute2);
            product.ProductAttributes.Add(attribute1);

            await _productManager.CreateAsync(product);

            var productSku1 = new ProductSku(ProductsTestData.Product1Sku1Id,
                                             await _attributeOptionIdsSerializer.SerializeAsync(new[]
                                                                                                { ProductsTestData.Product1Attribute1Option1Id, ProductsTestData.Product1Attribute2Option1Id }),
                                             null, "USD", null, 1m, 1, 10, null, null, null);

            var productSku2 = new ProductSku(ProductsTestData.Product1Sku2Id,
                                             await _attributeOptionIdsSerializer.SerializeAsync(new[]
                                                                                                { ProductsTestData.Product1Attribute1Option2Id, ProductsTestData.Product1Attribute2Option1Id }),
                                             null, "USD", null, 2m, 1, 10, null, null, null);

            var productSku3 = new ProductSku(ProductsTestData.Product1Sku3Id,
                                             await _attributeOptionIdsSerializer.SerializeAsync(new[]
                                                                                                { ProductsTestData.Product1Attribute1Option3Id, ProductsTestData.Product1Attribute2Option2Id }),
                                             null, "USD", null, 3m, 1, 10, null, null, null);

            await _productManager.CreateSkuAsync(product, productSku1);

            await _productManager.CreateSkuAsync(product, productSku2);

            await _productManager.CreateSkuAsync(product, productSku3);

            await uow.CompleteAsync();
        }
        public IEnumerable <ProductSku> GetProductSku(int?ProductSkuID)
        {
            List <ProductSku> productSkus = new List <ProductSku>();

            if (ProductSkuID == null)
            {
                command = new SqlCommand("SELECT * FROM [ViewProductsSKU]", connection);
            }
            else
            {
                command = new SqlCommand("SELECT * FROM [ViewProductsSKU] WHERE ProductID = '" + ProductSkuID + "'", connection);
            }

            connection.Open();

            using (var reader = command.ExecuteReader())
            {
                while (reader.Read())
                {
                    ProductSku productSku = new ProductSku((int)Convert.ToInt64(reader["ProductID"]),
                                                           (long)reader["ProductSKU"]);
                    productSkus.Add(productSku);
                }
            }

            connection.Close();

            return(productSkus);
        }
Esempio n. 3
0
        public async Task <IActionResult> UpdateAsync(ProductSkuUpdate productSkuUpdate)
        {
            var productSku = new ProductSku();

            _mapper.Map(productSkuUpdate, productSku);
            await _productSkuService.UpdateAsync(productSku);

            return(Accepted());
        }
Esempio n. 4
0
        public async Task <IActionResult> InsertAsync(ProductSkuInsert productSkuInsert)
        {
            var productSku = new ProductSku();

            _mapper.Map(productSkuInsert, productSku);
            await _productSkuService.InsertAsync(productSku);

            return(StatusCode((int)HttpStatusCode.Created));
        }
Esempio n. 5
0
 public WXSoldProductDetailToDb(ProductSku sku)
     : base(sqlMetas)
 {
     SetSqlInt32(0, sku.num_iid);
     SetSqlString(1, sku.sku_id);
     SetSqlString(2, sku.outer_sku_id);
     SetSqlInt32(3, sku.quantity);
     SetSqlDecimal(4, sku.price);
     SetSqlString(5, sku.sku_properties_name);
 }
Esempio n. 6
0
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "application/json";
            string          orderId   = context.Request["order_id"];
            WXMallOrderInfo orderInfo = bllMall.GetOrderInfo(orderId);

            if (orderInfo == null)
            {
                resp.errcode = 1;
                resp.errmsg  = "订单号不存在";
                context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(resp));
                return;
            }
            if (orderInfo.OrderType != 1)
            {
                resp.errcode = 1;
                resp.errmsg  = "不是礼品订单";
                context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(resp));
                return;
            }
            if (orderInfo.PaymentStatus == 0)
            {
                resp.errcode = 1;
                resp.errmsg  = "礼品订单未付款";
                context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(resp));
                return;
            }
            if (!string.IsNullOrEmpty(orderInfo.ParentOrderId))
            {
                //resp.errcode =1;
                //resp.errmsg = "不是父订单";
                //context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(resp));
                //return;
                orderInfo = bllMall.GetOrderInfo(orderInfo.ParentOrderId);
            }

            WXMallOrderDetailsInfo orderDetail = bllMall.GetOrderDetail(orderInfo.OrderID).First();
            WXMallProductInfo      productInfo = bllMall.GetProduct(orderDetail.PID);
            ProductSku             skuInfo     = bllMall.GetProductSku((int)orderDetail.SkuId);

            context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(new
            {
                errcode         = 0,
                errmsg          = "ok",
                order_id        = orderInfo.OrderID,
                product_name    = productInfo.PName,
                product_img_url = bllMall.GetImgUrl(productInfo.RecommendImg),
                product_count   = orderDetail.TotalCount,
                //product_properties = bllMall.GetProductProperties(skuInfo.SkuId),
                product_properties = "",
                is_get_gift        = IsGetGift(orderInfo.OrderID),
                receiver_list      = GetReceiverList(orderInfo.OrderID),
                send_user_info     = GiftOrderUserInfo(orderInfo.OrderUserID)
            }));
        }
Esempio n. 7
0
        public void Delete_IfZeroParameter_Return_InsertValidNumber()
        {
            //Arrange
            var productSku = new ProductSku();

            //Act
            var ex = Assert.ThrowsAsync <Exception>(() => _productSkuService.DeleteAsync(0));

            //Assert
            Assert.That(ex.Message, Is.EqualTo("Please insert Valid Number!"));
        }
Esempio n. 8
0
        public void Insert_Return_ProductSkuMustBeEntered()
        {
            //Arrange
            var productSku = new ProductSku();

            //Act
            var ex = Assert.ThrowsAsync <ArgumentNullException>(() => _productSkuService.InsertAsync(productSku));

            //Assert
            Assert.That(ex.Message, Is.EqualTo("ProductSku must be entered!"));
        }
Esempio n. 9
0
 public ActionResult Edit([Bind(Include = "ID,ProductID,Size,UnitPrice,Active")] ProductSku productSku)
 {
     if (ModelState.IsValid)
     {
         db.Entry(productSku).State = EntityState.Modified;
         db.SaveChanges();
         return(RedirectToAction("Index"));
     }
     ViewBag.ProductID = new SelectList(db.Products, "ID", "Name", productSku.ProductID);
     return(View(productSku));
 }
Esempio n. 10
0
 private MemberDiscountActivityItem GetDefaultSku(ProductSku productSku)
 {
     return(new MemberDiscountActivityItem
     {
         ProductSkuId = productSku.Id,
         Name = productSku.PropertyValueDesc,
         Bn = productSku.Bn,
         Price = productSku.Price,
         GradeItems = productSku.GradePriceList.MapTo <List <ProductSkuGradeItem> >()
     });
 }
Esempio n. 11
0
        public async Task InsertAsync(ProductSku productSku)
        {
            if (productSku == null)
            {
                throw new ArgumentNullException("ProductSku must be entered!");
            }

            if (string.IsNullOrWhiteSpace(productSku.Title))
            {
                throw new Exception("Title is required!");
            }

            await _productSkuRepository.InsertAsync(productSku);
        }
Esempio n. 12
0
        public async Task <IActionResult> PostProductSku([FromBody] ProductskuEditDto dto)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            //Product p = _context.Products.Find(dto.ProductID);
            var productSku = ProductSku.Create(dto.ProductID, dto.Name, dto.Description, dto.Code, dto.Vendable,
                                               dto.CommodityName, dto.ListPrice, dto.QuantityRate, dto.PreSellQuantity, dto.PreSellAuxiliaryQuantity);

            _context.ProductSkus.Add(productSku);
            await _context.SaveChangesAsync();

            return(this.AlpsActionOk());
        }
Esempio n. 13
0
        // GET: ProductSkus/Edit/5
        public ActionResult Edit(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            ProductSku productSku = db.ProductSkus.Find(id);

            if (productSku == null)
            {
                return(HttpNotFound());
            }
            ViewBag.ProductID = new SelectList(db.Products, "ID", "Name", productSku.ProductID);
            return(View(productSku));
        }
Esempio n. 14
0
 private bool checkEx(bool isAdded, int timeSetMethod, ProductSku sku)
 {
     if (isAdded)
     {
         return(false);
     }
     if (timeSetMethod != 1 && timeSetMethod != 2)
     {
         return(false);
     }
     if (timeSetMethod == 1)
     {
         return(!string.IsNullOrWhiteSpace(sku.PropValueIdEx1) && DateTime.Parse(sku.PropValueIdEx1) > DateTime.Now);
     }
     return(true);
 }
Esempio n. 15
0
        public void Insert_Return_TitleIsRequired()
        {
            //Arrange
            var productSku = new ProductSku()
            {
                Quantity  = 10,
                Price     = 1000,
                ProductId = 1
            };

            //Act
            var ex = Assert.ThrowsAsync <Exception>(() => _productSkuService.InsertAsync(productSku));

            //Assert
            Assert.That(ex.Message, Is.EqualTo("Title is required!"));
        }
Esempio n. 16
0
        ///// <summary>
        ///// 生成外部订单号
        ///// </summary>
        ///// <returns></returns>
        //private string CreateOutOrderId(string orderId)
        //{

        //    if (orderId.Length > 10)
        //    {
        //        orderId = orderId.Substring(0, 10);
        //    }
        //    return string.Format("{0}_{1}", DateTime.Now.ToString("yyyyMMddhhmmss"), orderId.PadLeft(10, '0'));

        //}

        ///// <summary>
        ///// 生成签名
        ///// </summary>
        ///// <param name="appId"></param>
        ///// <param name="timeStamp"></param>
        ///// <param name="appkey"></param>
        ///// <returns></returns>
        //public string CreateSign(string appId, string timeStamp, string appkey)
        //{
        //    string sign = ZentCloud.Common.SHA1.SHA1_Encrypt(string.Format("appid={0}&appkey={1}&timestamp={2}", appId, appkey, timeStamp)).ToUpper();
        //    return sign;

        //}


        protected void Button1_Click(object sender, EventArgs e)
        {
            BLLMall bllMall = new BLLMall();

            /// <summary>
            /// Efast
            /// </summary>
            Open.EfastSDK.Client efastClient = new Open.EfastSDK.Client();
            ProductSku           skuInfo     = bllMall.Get <ProductSku>(string.Format("SkuSN='{0}'", txtOrderId.Text));

            if (skuInfo == null)
            {
                txtOrderId.Text = string.Format("条码不存在");
                return;
            }
            var eFastSku = efastClient.GetSkuStock(9, skuInfo.OutBarCode);

            if (eFastSku != null)
            {
                if (eFastSku.sl != skuInfo.Stock)
                {
                    skuInfo.Stock = eFastSku.sl;

                    if (ZentCloud.ZCBLLEngine.BLLBase.ExecuteSql(string.Format("update ZCJ_ProductSku set Stock={0} where SkuId={1}", skuInfo.Stock, skuInfo.SkuId)) >= 0)
                    {
                        txtOrderId.Text = string.Format("同步成功,条码:{0}库存:{1}", skuInfo.OutBarCode, skuInfo.Stock);
                    }
                }
                else
                {
                    txtOrderId.Text = string.Format("库存一致,跳过 条码:{0}库存:{1}", skuInfo.OutBarCode, skuInfo.Stock);
                }
            }
            else
            {
                txtOrderId.Text = "未查到";
            }
        }
Esempio n. 17
0
        public ActionResult Checkout(ShoppingCartCheckoutViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(JsonValidationError());
            }

            // Get cart contents
            ShoppingCart cart = GetOrCreateCart();

            if (!cart.ShoppingCartItems.Any())
            {
                return(JsonError("Your shopping cart is empty!"));
            }

            // Check quantity
            foreach (ShoppingCartItem cartItem in cart.ShoppingCartItems)
            {
                Product product = db.Products.Find(cartItem.ProductId);
                int?    qty     = null;
                if (cartItem.ProductSkuId.HasValue && cartItem.ProductSku.Quantity.HasValue)
                {
                    qty = cartItem.ProductSku.Quantity.Value;
                }
                if (qty == null && product.Quantity.HasValue)
                {
                    qty = product.Quantity.Value;
                }
                if (qty.HasValue && qty < cartItem.Quantity)
                {
                    return(JsonError(string.Format("The requested quantity for \"{0}\" is not available", product.Name)));
                }
            }

            // Get current user (or create a new one)
            User user = null;

            if (User.Identity.IsAuthenticated)
            {
                user = customerService.Find(currentUser.User.Id);
            }
            if (user == null)
            {
                var userModel = new CustomerViewModel
                {
                    FirstName   = model.BillingAddress.FirstName,
                    LastName    = model.BillingAddress.LastName,
                    Company     = model.BillingAddress.Company,
                    PhoneNumber = model.BillingAddress.Phone,
                    Email       = model.Email
                };
                try
                {
                    user = customerService.AddOrUpdate(userModel);
                }
                catch (ArgumentException err)
                {
                    return(JsonError(err.Message));
                }

                customerService.LoginUser(HttpContext, user);
            }

            // Get addresses
            var billingAddress = Mapper.Map <Address>(model.BillingAddress);

            billingAddress.Type = AddressType.Billing;

            var shippingAddress = Mapper.Map <Address>(model.SameShippingAddress
                ? model.BillingAddress
                : model.ShippingAddress);

            shippingAddress.Type = AddressType.Shipping;

            var defaultBillingAddress = customerService.GetAddress(user.Id, AddressType.Billing);

            if (defaultBillingAddress == null)
            {
                // Add default billing address
                defaultBillingAddress           = Mapper.Map <Address>(model.BillingAddress);
                defaultBillingAddress.Type      = AddressType.Billing;
                defaultBillingAddress.IsPrimary = true;
                user.Addresses.Add(defaultBillingAddress);
            }

            var defaultShippingAddress = customerService.GetAddress(user.Id, AddressType.Shipping);

            if (defaultShippingAddress == null)
            {
                // Add default shipping address
                defaultShippingAddress = Mapper.Map <Address>(model.SameShippingAddress
                    ? model.BillingAddress
                    : model.ShippingAddress);
                defaultShippingAddress.Type      = AddressType.Shipping;
                defaultShippingAddress.IsPrimary = true;
                user.Addresses.Add(defaultShippingAddress);
            }

            db.SaveChanges();

            // Create order
            var order = new Order
            {
                UserId          = user.Id,
                BillingAddress  = billingAddress,
                ShippingAddress = shippingAddress,
                DatePlaced      = DateTime.Now,
                DateUpdated     = DateTime.Now,
                IPAddress       = Request.UserHostAddress,
                UserComments    = model.UserComments,
                Status          = OrderStatus.AwaitingPayment
            };

            db.Orders.Add(order);

            TaxZone taxZone = taxZoneService.Find(billingAddress.CountryCode, billingAddress.RegionId);

            foreach (ShoppingCartItem cartItem in cart.ShoppingCartItems)
            {
                Product    product    = db.Products.Find(cartItem.ProductId);
                ProductSku productSku = cartItem.ProductSku;

                if (productSku != null && productSku.Quantity.HasValue)
                {
                    productSkuService.RemoveQuantity(productSku.Id, cartItem.Quantity);
                }
                else if (product.Quantity.HasValue)
                {
                    productService.RemoveQuantity(product.Id, cartItem.Quantity);
                }

                decimal price = product.SalePrice ?? product.Price;
                if (cartItem.ProductSkuId.HasValue && cartItem.ProductSku.Price.HasValue)
                {
                    price = cartItem.ProductSku.Price.Value;
                }

                var cartItemOptions  = JsonConvert.DeserializeObject <ShoppingCartItemOptionViewModel[]>(cartItem.Options);
                var orderItemOptions = Mapper.Map <OrderItemOption[]>(cartItemOptions);

                var orderItem = new OrderItem
                {
                    Order        = order,
                    ProductId    = product.Id,
                    ProductSkuId = cartItem.ProductSkuId,
                    Quantity     = cartItem.Quantity,
                    Options      = JsonConvert.SerializeObject(orderItemOptions),
                    ItemPrice    = price
                };

                db.OrderItems.Add(orderItem);

                order.Subtotal += cartItem.Quantity * price;

                if (taxZone != null)
                {
                    order.TaxAmount += taxRateService.CalculateTax(taxZone.Id, product.TaxClassId, price * cartItem.Quantity);
                }
            }

            ShippingMethod shippingMethod = db.ShippingMethods.Find(model.ShippingMethodId);

            order.ShippingAmount = shippingService.CalculateShipping(shippingMethod,
                                                                     cart.ShoppingCartItems.Sum(i => i.Quantity),
                                                                     cart.ShoppingCartItems.Sum(i => i.Quantity * i.Product.Weight),
                                                                     order.Subtotal, shippingAddress).GetValueOrDefault();

            order.Total = order.Subtotal + order.ShippingAmount;
            if (!settings.Get <bool>(SettingField.TaxIncludedInPrices))
            {
                order.Total += order.TaxAmount;
            }

            db.SaveChanges();

            return(JsonSuccess(new { orderId = order.Id, paymentMethodId = model.PaymentMethodId }));
        }
Esempio n. 18
0
        /// <summary>
        /// 根据重量生成配送方式(集合)
        /// </summary>
        /// <param name="orderProducts"></param>
        /// <param name="ShippingAddressID"></param>
        /// <returns></returns>
        public Dictionary <long, string> GenerateDeliveryModes(List <JsonOrderProduct> orderProducts, long ShippingAddressID)
        {
            using (ISession s = SessionFactory.Instance.CreateSession())
            {
                //用户收货地址
                ShoppingAddress shippingAddress = s.Get <ShoppingAddress>(ShippingAddressID);
                if (shippingAddress == null)
                {
                    throw new Exception("不存在该用户收货地址");
                }

                int weight = 0;

                foreach (JsonOrderProduct jop in orderProducts)
                {
                    ProductSku sku = s.Get <ProductSku>("where dbo.fn_check_specset(specset,@0) = 1 and product_id = @1", (jop.specset ?? ""), jop.product_id);
                    weight += sku.weight * jop.qty;
                }

                //配送方式实体类
                List <DeliveryMode> modes = s.List <DeliveryMode>("", "");

                //配送方式以及运费集合
                Dictionary <long, string> deliveryMode = new Dictionary <long, string>();
                decimal price = 0, first_price = 0, add_price = 0;

                foreach (DeliveryMode m in modes)
                {
                    //获取当前配送方式运费模板
                    FreightTemplate fTemplate = s.Get <FreightTemplate>(m.freight_template_id);

                    if (fTemplate != null)
                    {
                        //默认首重价格
                        first_price = fTemplate.default_first_price;
                        //默认续重价格
                        add_price = fTemplate.default_add_price;

                        //特殊地区按特殊地区价格算
                        FreightRegion fRegion = s.Get <FreightRegion>("where region_name like '%'+@0+'%' and freight_template_id = @1 ", shippingAddress.province, fTemplate.id);
                        if (fRegion != null)
                        {
                            if (weight < fRegion.first_weight)
                            {
                                price = fRegion.first_price;
                            }
                            else
                            {
                                decimal t = (((weight - fRegion.first_weight) / fRegion.add_weight) + ((weight - fRegion.first_weight) % fRegion.add_weight) == 0 ? 0 : 1) * fRegion.add_price;
                                price = weight <= fRegion.first_weight ? fRegion.first_price : t + fRegion.first_price;
                            }
                        }
                        else
                        {
                            if (weight < fTemplate.first_weight)
                            {
                                price = fTemplate.default_first_price;
                            }
                            else
                            {
                                decimal tmp = (((weight - fTemplate.first_weight) / fTemplate.add_weight) + ((weight - fTemplate.first_weight) % fTemplate.add_weight) == 0 ? 0 : 1) * add_price;
                                price = weight <= fTemplate.first_weight ? first_price : Math.Ceiling((decimal)(weight - fTemplate.first_weight) / (decimal)fTemplate.add_weight) * add_price + first_price;
                            }
                        }

                        deliveryMode.Add(m.id, string.Format("{0}: {1}", m.name, price.ToString("f2")));
                    }
                }
                return(deliveryMode);
            }
        }
Esempio n. 19
0
        /// <summary>
        /// 根据重量生成配送方式(最小运费)
        /// </summary>
        /// <param name="orderProducts"></param>
        /// <param name="shippingAddressID"></param>
        /// <returns></returns>
        public string GetDeliveryModeFreight(List <JsonOrderProduct> orderProducts, long shippingAddressID)
        {
            using (ISession s = SessionFactory.Instance.CreateSession())
            {
                //用户收货地址
                ShoppingAddress shippingAddress = s.Get <ShoppingAddress>(shippingAddressID);
                if (shippingAddress == null)
                {
                    throw new Exception("不存在该用户收货地址");
                }

                decimal price = 0, first_price = 0, add_price = 0;
                decimal pricetmp = 0;
                long    defaultModeID = 0, modeID = 0, weight = 0;

                foreach (JsonOrderProduct jop in orderProducts)
                {
                    Product pdt = s.Get <Product>(jop.product_id);
                    //排除包邮商品
                    if (pdt != null && !pdt.is_postage)
                    {
                        ProductSku sku = s.Get <ProductSku>("where dbo.fn_check_specset(specset,@0) = 1 and product_id = @1", jop.specset ?? "", jop.product_id);
                        weight += sku.weight * jop.qty;
                    }
                }

                //配送方式实体类
                List <DeliveryMode> modes = s.List <DeliveryMode>("", "");

                foreach (DeliveryMode m in modes)
                {
                    //记录当前配送方式ID
                    modeID = m.id;

                    //获取当前配送方式运费模板
                    FreightTemplate fTemplate = s.Get <FreightTemplate>(m.freight_template_id);

                    if (fTemplate != null)
                    {
                        //默认首重价格
                        first_price = fTemplate.default_first_price;
                        //默认续重价格
                        add_price = fTemplate.default_add_price;

                        //获取特殊区域
                        FreightRegion fRegion = s.Get <FreightRegion>("where region_name like '%'+@0+'%' and freight_template_id = @1 ", shippingAddress.province, fTemplate.id);
                        if (fRegion != null)
                        {
                            if (weight < fRegion.first_weight)
                            {
                                pricetmp = fRegion.first_price;
                            }
                            else
                            {
                                decimal t = (((weight - fRegion.first_weight) / fRegion.add_weight) + ((weight - fRegion.first_weight) % fRegion.add_weight) == 0 ? 0 : 1) * fRegion.add_price;
                                pricetmp = weight <= fRegion.first_weight ? fRegion.first_price : t + fRegion.first_price;
                            }
                        }

                        if (weight < fTemplate.first_weight)
                        {
                            price = fTemplate.default_first_price;
                        }
                        else
                        {
                            decimal tmp = (((weight - fTemplate.first_weight) / fTemplate.add_weight) + ((weight - fTemplate.first_weight) % fTemplate.add_weight) == 0 ? 0 : 1) * add_price;
                            price = weight <= fTemplate.first_weight ? first_price : Math.Ceiling((decimal)(weight - fTemplate.first_weight) / (decimal)fTemplate.add_weight) * add_price + first_price;
                        }

                        //最小价格
                        if (price < pricetmp)
                        {
                            pricetmp      = price;
                            defaultModeID = m.id;
                        }
                    }
                }

                defaultModeID = defaultModeID == 0 ? modeID : defaultModeID;
                price         = price < pricetmp ? price : pricetmp == 0 ? price : pricetmp;

                return(defaultModeID + "#" + (int)price);
            }
        }
Esempio n. 20
0
        /// <summary>
        /// 根据重量生成配送方式
        /// 默认配送方式
        /// </summary>
        /// <param name="orderProducts"></param>
        /// <param name="shippingAddressID"></param>
        /// <returns></returns>
        public StateCode GetDefaultFreight(List <JsonOrderProduct> orderProducts, long shippingAddressID, out string result)
        {
            result = "";
            using (ISession s = SessionFactory.Instance.CreateSession())
            {
                //用户收货地址
                ShoppingAddress shippingAddress = s.Get <ShoppingAddress>(shippingAddressID);
                if (shippingAddress == null)
                {
                    return(StateCode.State_252);
                }

                //配送方式实体类
                DeliveryMode mode = s.Get <DeliveryMode>("where is_default = @0", true);
                if (mode == null)
                {
                    return(StateCode.State_251);
                }

                decimal price = 0, first_price = 0, add_price = 0;
                long    weight = 0;

                foreach (JsonOrderProduct jop in orderProducts)
                {
                    Product pdt = s.Get <Product>(new string[] { "id", "is_postage" }, "where id = @0", jop.product_id);
                    //排除包邮商品
                    if (pdt != null && !pdt.is_postage)
                    {
                        ProductSku sku = s.Get <ProductSku>("where dbo.fn_check_specset(specset,@0) = 1 and product_id = @1", jop.specset ?? "", jop.product_id);
                        weight += sku.weight * jop.qty;
                    }
                }

                //获取当前配送方式运费模板
                FreightTemplate fTemplate = s.Get <FreightTemplate>(mode.freight_template_id);

                if (fTemplate != null && weight > 0)
                {
                    //默认首重价格
                    first_price = fTemplate.default_first_price;
                    //默认续重价格
                    add_price = fTemplate.default_add_price;

                    //特殊地区按特殊地区价格算
                    FreightRegion fRegion = s.Get <FreightRegion>("where region_name like '%'+@0+'%' and freight_template_id = @1 ", shippingAddress.province, fTemplate.id);
                    if (fRegion != null)
                    {
                        if (weight < fRegion.first_weight)
                        {
                            price = fRegion.first_price;
                        }
                        else
                        {
                            decimal t = (((weight - fRegion.first_weight) / fRegion.add_weight) + (((weight - fRegion.first_weight) % fRegion.add_weight) == 0 ? 0 : 1)) * fRegion.add_price;
                            price = weight <= fRegion.first_weight ? fRegion.first_price : t + fRegion.first_price;
                        }
                    }
                    else
                    {
                        if (weight < fTemplate.first_weight)
                        {
                            price = fTemplate.default_first_price;
                        }
                        else
                        {
                            decimal tmp = (((weight - fTemplate.first_weight) / fTemplate.add_weight) + (((weight - fTemplate.first_weight) % fTemplate.add_weight) == 0 ? 0 : 1)) * add_price;
                            price = weight <= fTemplate.first_weight ? first_price : Math.Ceiling((decimal)(weight - fTemplate.first_weight) / (decimal)fTemplate.add_weight) * add_price + first_price;
                        }
                    }
                }

                result = mode.id + "#" + price;

                return(StateCode.State_200);
            }
        }
Esempio n. 21
0
            void CommonMgrSeed(AlpsContext context)
            {
                #region 初始化管理员
                AlpsRole role = AlpsRole.Create("Admin", "管理员");
                context.AlpsRoles.Add(role);
                AlpsUser user = AlpsUser.Create("a", "a", "李", "123456", "223344");

                user.AddRole(role);
                role = AlpsRole.Create("User", "用户");
                context.AlpsRoles.Add(role);
                user.AddRole(role);
                context.AlpsUsers.Add(user);

                user = AlpsUser.Create("b", "b", "张三", "112233", "789789");
                user.AddRole(role);
                context.AlpsUsers.Add(user);

                role = AlpsRole.Create("Cashier", "出纳");
                context.AlpsRoles.Add(role);
                user = AlpsUser.Create("cw", "cw", "财务", "11", "22");
                user.AddRole(role);
                context.AlpsUsers.Add(user);



                #endregion
                #region 初始化地址

                context.Countries.Add(Country.Create("菲律宾"));
                Country country = Country.Create("中国");
                context.Countries.Add(country);
                context.Provinces.Add(Province.Create("浙江省", country.ID));
                context.Provinces.Add(Province.Create("广东省", country.ID));
                context.Provinces.Add(Province.Create("江西省", country.ID));
                context.Provinces.Add(Province.Create("湖南省", country.ID));
                Province province = Province.Create("福建省", country.ID);
                context.Provinces.Add(province);
                context.Cities.Add(City.Create("泉州市", province.ID));
                context.Cities.Add(City.Create("莆田市", province.ID));
                context.Cities.Add(City.Create("宁德市", province.ID));
                City city = City.Create("福州市", province.ID);
                context.Cities.Add(city);
                context.Counties.Add(County.Create("福清市", city.ID));
                context.Counties.Add(County.Create("闽候县", city.ID));
                context.Counties.Add(County.Create("鼓楼区", city.ID));
                County county = County.Create("长乐区", city.ID);
                context.Counties.Add(county);

                context.SaveChanges();

                #endregion

                #region 初始化部门
                Department d = Department.Create("供销科");
                context.Departments.Add(d);
                d = Department.Create("轧钢车间");
                productDepartmentID = d.ID;
                context.Departments.Add(d);
                d = Department.Create("焊管车间");
                context.Departments.Add(d);
                d = Department.Create("采购部");
                context.Departments.Add(d);
                context.SaveChanges();
                departmentID = d.ID;
                #endregion

                #region 初始化客户
                Address  address = Address.Create(county, "青口钢材市场");
                Customer c       = Customer.Create("江水金", address);
                context.Customers.Add(c);
                address = Address.Create(county, "青口钢材市场");
                c       = Customer.Create("陈依寿", address);
                context.Customers.Add(c);
                address = Address.Create(county, "青口钢材市场");
                c       = Customer.Create("林光江", address);
                context.Customers.Add(c);
                context.SaveChanges();
                customerID = c.ID;
                #endregion

                #region 初始化供应商

                SupplierClass sc = SupplierClass.Create("配件供应商");
                context.SupplierClasses.Add(sc);
                sc = SupplierClass.Create("煤碳供应商");
                context.SupplierClasses.Add(sc);
                SupplierClass gpsc = SupplierClass.Create("坯料供应商");
                context.SupplierClasses.Add(gpsc);

                address = Address.Create(county, "漳州");
                Supplier s = Supplier.Create("三宝", gpsc.ID, address);
                context.Suppliers.Add(s);
                address = Address.Create(county, "罗源");
                s       = Supplier.Create("亿鑫", gpsc.ID, address);
                context.Suppliers.Add(s);
                address = Address.Create(county, "松下镇");
                s       = Supplier.Create("大东海", gpsc.ID, address);
                context.Suppliers.Add(s);
                address = Address.Create(county, "吴航镇");
                s       = Supplier.Create("锦强", sc.ID, address);
                context.Suppliers.Add(s);
                context.SaveChanges();
                supplierID = s.ID;
                #endregion

                #region 初始化交易账户

                TradeAccount ta = TradeAccount.Create("宏建", TradeAccountType.SupplierAndCustomer, "13900000000", "");
                context.TradeAccounts.Add(ta);
                ta = TradeAccount.Create("富鑫", TradeAccountType.SupplierAndCustomer, "13900000001", "");
                context.TradeAccounts.Add(ta);
                ta = TradeAccount.Create("江水金", TradeAccountType.Customer, "13900000003", "");
                context.TradeAccounts.Add(ta);
                ta = TradeAccount.Create("陈依寿", TradeAccountType.Customer, "13900000005", "");
                context.TradeAccounts.Add(ta);
                ta = TradeAccount.Create("永盛金属", TradeAccountType.Customer, "13900000006", "");
                context.TradeAccounts.Add(ta);
                ta = TradeAccount.Create("永盛钢贸", TradeAccountType.Customer, "13900000006", "");
                context.TradeAccounts.Add(ta);
                context.SaveChanges();
                #endregion

                #region 初始化单位
                Unit unit = Unit.Create("吨", 1, false, 1000);
                context.Units.Add(unit);
                unitID = unit.ID;
                context.Units.Add(Unit.Create("公斤", 1, true));
                context.Units.Add(Unit.Create("件", 2, true));
                context.SaveChanges();
                #endregion

                #region 初始化仓位
                context.Positions.Add(new Position()
                {
                    Name = "新建616", Number = "616", Warehouse = "新建仓库"
                });
                Position position = new Position()
                {
                    Name = "小槽315", Number = "315", Warehouse = "小槽仓库"
                };
                context.Positions.Add(position);


                positionID = position.ID;
                position   = new Position()
                {
                    Name = "坯场-1", Number = "901", Warehouse = "坯场"
                };
                context.Positions.Add(position);
                position = new Position()
                {
                    Name = "坯场-2", Number = "902", Warehouse = "坯场"
                };
                context.Positions.Add(position);
                context.SaveChanges();
                #endregion

                #region 初始化类别

                Catagory nCatagory = Catagory.Create("钢材");
                nCatagory.AddChildCatagory(Catagory.Create("槽钢")
                                           .AddChildCatagory(Catagory.Create("5#")).AddChildCatagory(Catagory.Create("6.3#")).
                                           AddChildCatagory(Catagory.Create("8#")).AddChildCatagory(Catagory.Create("10#"))
                                           .AddChildCatagory(Catagory.Create("12#")).AddChildCatagory(Catagory.Create("14#"))
                                           .AddChildCatagory(Catagory.Create("16#")).AddChildCatagory(Catagory.Create("18#"))
                                           .AddChildCatagory(Catagory.Create("20#")))
                .AddChildCatagory(Catagory.Create("角钢")
                                  .AddChildCatagory(Catagory.Create("3#")).AddChildCatagory(Catagory.Create("4#"))
                                  .AddChildCatagory(Catagory.Create("5#")).AddChildCatagory(Catagory.Create("6#")))
                .AddChildCatagory(Catagory.Create("工字钢")
                                  .AddChildCatagory(Catagory.Create("10#")).AddChildCatagory(Catagory.Create("12#"))
                                  .AddChildCatagory(Catagory.Create("14#")).AddChildCatagory(Catagory.Create("16#"))
                                  .AddChildCatagory(Catagory.Create("18#")).AddChildCatagory(Catagory.Create("20a#")));
                context.Catagories.Add(nCatagory);
                nCatagory = Catagory.Create("坯料").AddChildCatagory(Catagory.Create("连铸坯"));
                context.Catagories.Add(nCatagory);
                nCatagory = Catagory.Create("镀锌板管")
                            .AddChildCatagory(Catagory.Create("方管").AddChildCatagory(Catagory.Create("16方")).AddChildCatagory(Catagory.Create("20方")).AddChildCatagory(Catagory.Create("32方")))
                            .AddChildCatagory(Catagory.Create("矩形管").AddChildCatagory(Catagory.Create("20*40")).AddChildCatagory(Catagory.Create("30*50")).AddChildCatagory(Catagory.Create("40*60")))
                            .AddChildCatagory(Catagory.Create("圆管").AddChildCatagory(Catagory.Create("2寸")).AddChildCatagory(Catagory.Create("3寸")).AddChildCatagory(Catagory.Create("4寸")));
                context.Catagories.Add(nCatagory);
                nCatagory = Catagory.Create("轧辊");
                context.Catagories.Add(nCatagory);
                context.SaveChanges();
                #endregion

                #region 初始化产品
                Product  product            = null;
                Catagory associatedCatagory = context.Catagories.FirstOrDefault(p => p.Name == "5#");
                for (int i = 13; i < 30; i = i + 2)
                {
                    product = Product.Create(associatedCatagory.Name + i.ToString() + "-" + (i + 1).ToString() + "Kg",
                                             associatedCatagory.Name + i.ToString() + "-" + (i + 1).ToString() + "Kg", "系统创建", PricingMethod.PricingByWeight, 2000, unitID);
                    product.SetCatagory(associatedCatagory);
                    context.Products.Add(product);
                }
                associatedCatagory = context.Catagories.FirstOrDefault(p => p.Name == "6.3#");
                for (int i = 15; i < 38; i = i + 2)
                {
                    product = Product.Create(associatedCatagory.Name + i.ToString() + "-" + (i + 1).ToString() + "Kg",
                                             associatedCatagory.Name + i.ToString() + "-" + (i + 1).ToString() + "Kg", "系统创建", PricingMethod.PricingByWeight, 2000, unitID);
                    product.SetCatagory(associatedCatagory);
                    context.Products.Add(product);
                }
                associatedCatagory = context.Catagories.FirstOrDefault(p => p.Name == "8#");
                for (int i = 17; i < 48; i = i + 2)
                {
                    product = Product.Create(associatedCatagory.Name + i.ToString() + "-" + (i + 1).ToString() + "Kg",
                                             associatedCatagory.Name + i.ToString() + "-" + (i + 1).ToString() + "Kg", "系统创建", PricingMethod.PricingByWeight, 2000, unitID);
                    product.SetCatagory(associatedCatagory);
                    context.Products.Add(product);
                }
                foreach (Catagory childCatagory in context.Catagories.FirstOrDefault(p => p.Name == "工字钢").Children)
                {
                    product = Product.Create(childCatagory.Name + "下偏3-5%", childCatagory.Name + "下偏3-5%", "系统创建", PricingMethod.PricingByWeight, 2000, unitID);
                    product.SetCatagory(childCatagory);
                    context.Products.Add(product);
                    product = Product.Create(childCatagory.Name + "下偏8-10%", childCatagory.Name + "下偏8-10%", "系统创建", PricingMethod.PricingByWeight, 2000, unitID);
                    product.SetCatagory(childCatagory);
                    context.Products.Add(product);
                    product = Product.Create(childCatagory.Name + "下偏18-20%", childCatagory.Name + "下偏18-20%", "系统创建", PricingMethod.PricingByWeight, 2000, unitID);
                    product.SetCatagory(childCatagory);
                    context.Products.Add(product);
                }

                associatedCatagory = context.Catagories.FirstOrDefault(p => p.Name == "连铸坯");
                product            = Product.Create("150*150", "150*150连铸坯", "系统创建", PricingMethod.PricingByWeight, 2000, unitID);
                product.SetCatagory(associatedCatagory);
                context.Products.Add(product);
                product = Product.Create("120*120", "120*120连铸坯", "系统创建", PricingMethod.PricingByWeight, 2000, unitID);
                product.SetCatagory(associatedCatagory);
                context.Products.Add(product);
                context.SaveChanges();

                #endregion

                #region 初始化SKU
                ProductSku sku = null;
                foreach (Product p in context.Products.Where(p => p.Catagory.Name == "5#"))
                {
                    //sku = ProductSku.Create(p, "6米*144条", "系统初始化");
                    sku = ProductSku.Create(p.ID, p.Name + " " + "6米*144条", "系统初始化", "", true, "", 3800, 2.3m, 0, 0);
                    context.ProductSkus.Add(sku);
                }
                gcSkuID = sku.ID;
                foreach (Product p in context.Products.Where(p => p.Catagory.Name == "6.3#"))
                {
                    sku = ProductSku.Create(p.ID, p.Name + " " + "6米*96条", "系统初始化", "", true, "", 3800, 2.3m, 0, 0);
                    //sku = ProductSku.Create(p, "6米*96条", "系统初始化");
                    context.ProductSkus.Add(sku);
                }
                foreach (Product p in context.Products.Where(p => p.Catagory.Name == "8#"))
                {
                    sku = ProductSku.Create(p.ID, p.Name + " " + "6米*84条", "系统初始化", "", true, "", 3800, 3.6m, 0, 0);
                    //sku = ProductSku.Create(p, "6米*84条", "系统初始化");
                    context.ProductSkus.Add(sku);
                    sku = ProductSku.Create(p.ID, p.Name + " " + "6米*64条", "系统初始化", "", true, "", 3800, 3.6m, 0, 0);
                    //sku = ProductSku.Create(p, "9米*64条", "系统初始化");
                    context.ProductSkus.Add(sku);
                }
                // foreach (Product p in context.Products.Where(p => p.Catagory.Name == "连铸坯"))
                // {
                //     sku = ProductSku.Create(p.ID, p.Name + " " + "6米", "系统初始化", "", false);
                //     //sku = ProductSku.Create(p, "6米", "系统初始化");
                //     context.ProductSkus.Add(sku);
                //     sku = ProductSku.Create(p.ID, p.Name + " " + "12米", "系统初始化", "", false);
                //     //sku = ProductSku.Create(p, "12米", "系统初始化");
                //     context.ProductSkus.Add(sku);
                // }
                var gp     = context.Products.FirstOrDefault(p => p.Name == "150*150");
                var newSku = ProductSku.Create(gp.ID, "亿鑫150*150*12M", "", "9001", false);
                context.ProductSkus.Add(newSku);
                gpSkuID = newSku.ID;
                newSku  = ProductSku.Create(gp.ID, "大东海150*150*12M", "", "9002", false);
                context.ProductSkus.Add(newSku);
                newSku = ProductSku.Create(gp.ID, "春兴150*150*12M", "", "9003", false);
                context.ProductSkus.Add(newSku);
                newSku = ProductSku.Create(gp.ID, "东华150*150*12M", "", "9003", false);
                context.ProductSkus.Add(newSku);

                context.SaveChanges();

                #endregion
            }
Esempio n. 22
0
        public void ProcessRequest(HttpContext context)
        {
            string     data       = context.Request["data"];
            decimal    productFee = 0;    //商品总价格
            OrderModel orderRequestModel; //订单模型

            try
            {
                orderRequestModel = ZentCloud.Common.JSONHelper.JsonToModel <OrderModel>(data);
            }
            catch (Exception ex)
            {
                apiResp.code = 1;
                apiResp.msg  = "JSON格式错误,请检查.错误信息:" + ex.Message;
                context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                return;
            }
            #region 检查是否可以下单
            if (string.IsNullOrEmpty(orderRequestModel.select_time_type))
            {
                apiResp.code = 1;
                apiResp.msg  = "请选择一种时间预约方式";
                context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                return;
            }
            int totalHours = 0;                            //预约小时数
            if (orderRequestModel.select_time_type == "0") //直接选择开始时间结束时间方式
            {
                if (string.IsNullOrEmpty(orderRequestModel.start_time) || string.IsNullOrEmpty(orderRequestModel.stop_time))
                {
                    apiResp.code = 1;
                    apiResp.msg  = "请选择开始时间与结束时间";
                    context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                    return;
                }
                if (DateTime.Parse(orderRequestModel.start_time) <= DateTime.Now)
                {
                    apiResp.code = 1;
                    apiResp.msg  = "开始时间需要晚于当前时间";
                    context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                    return;
                }
                if (DateTime.Parse(orderRequestModel.stop_time) <= DateTime.Parse(orderRequestModel.start_time))
                {
                    apiResp.code = 1;
                    apiResp.msg  = "结束时间需要晚于开始时间";
                    context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                    return;
                }

                totalHours = (int)(DateTime.Parse(orderRequestModel.stop_time) - DateTime.Parse(orderRequestModel.start_time)).TotalHours;
            }
            else if (orderRequestModel.select_time_type == "1")//选择某一天的多个时间段的方式
            {
                if (string.IsNullOrEmpty(orderRequestModel.date) || string.IsNullOrEmpty(orderRequestModel.date_time_ranges))
                {
                    apiResp.code = 1;
                    apiResp.msg  = "请选择预约时间段";
                    context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                    return;
                }
                if (DateTime.Parse(orderRequestModel.date) <= DateTime.Now)
                {
                    apiResp.code = 1;
                    apiResp.msg  = "开始时间需要晚于当前时间";
                    context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                    return;
                }
                totalHours = orderRequestModel.date_time_ranges.Split(';').Count();
            }


            if (!Check(orderRequestModel))
            {
                apiResp.code = 1;
                apiResp.msg  = "您所选的时间段已经被占用,请选择别的时间段";
                context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                return;
            }
            #endregion



            WXMallOrderInfo orderInfo = new WXMallOrderInfo();//订单表
            orderInfo.OrderID        = bllMall.GetGUID(BLLJIMP.TransacType.AddMallOrder);
            orderInfo.Consignee      = orderRequestModel.receiver_name;
            orderInfo.InsertDate     = DateTime.Now;
            orderInfo.OrderUserID    = CurrentUserInfo.UserID;
            orderInfo.Phone          = orderRequestModel.receiver_phone;
            orderInfo.WebsiteOwner   = bllMall.WebsiteOwner;
            orderInfo.Transport_Fee  = 0;
            orderInfo.OrderMemo      = orderRequestModel.buyer_memo;
            orderInfo.MyCouponCardId = orderRequestModel.cardcoupon_id.ToString();
            orderInfo.UseScore       = orderRequestModel.use_score;
            orderInfo.Status         = "待付款";
            orderInfo.OrderType      = 3;
            orderInfo.Ex3            = orderRequestModel.select_time_type;
            orderInfo.Ex4            = orderRequestModel.start_time;
            orderInfo.Ex5            = orderRequestModel.stop_time;
            orderInfo.Ex6            = orderRequestModel.date;
            orderInfo.Ex7            = orderRequestModel.date_time_ranges;
            orderInfo.LastUpdateTime = DateTime.Now;
            if (!string.IsNullOrEmpty(orderRequestModel.sale_id))//分销ID
            {
                long saleId = 0;
                if (long.TryParse(orderRequestModel.sale_id, out saleId))
                {
                    orderInfo.SellerId = saleId;
                }
            }
            if (orderRequestModel.pay_type == "WEIXIN")//微信支付
            {
                orderInfo.PaymentType = 2;
            }
            else if (orderRequestModel.pay_type == "ALIPAY")//支付宝支付
            {
                orderInfo.PaymentType = 1;
            }

            #region 格式检查
            if (string.IsNullOrEmpty(orderInfo.Consignee))
            {
                apiResp.code = 1;
                apiResp.msg  = "收货人姓名不能为空";
                context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                return;
            }
            if (string.IsNullOrEmpty(orderRequestModel.receiver_phone))
            {
                apiResp.code = 1;
                apiResp.msg  = "联系手机号不能为空";
                context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                return;
            }


            if (orderRequestModel.skus == null)
            {
                apiResp.code = 1;
                apiResp.msg  = "skus 参数不能为空";
                context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                return;
            }

            //相关检查
            #endregion

            #region 商品检查 订单详情生成
            ///订单详情
            List <WXMallOrderDetailsInfo> detailList = new List <WXMallOrderDetailsInfo>();//订单详情
            #region 购买的商品
            List <WXMallProductInfo> productList = new List <WXMallProductInfo>();
            foreach (var sku in orderRequestModel.skus)
            {
                ProductSku        productSku  = bllMall.GetProductSku(sku.sku_id);
                WXMallProductInfo productInfo = bllMall.GetProduct(productSku.ProductId.ToString());
                productList.Add(productInfo);
            }
            productList = productList.Distinct().ToList();
            #endregion
            #region 检查优惠券是否可用
            if (orderRequestModel.cardcoupon_id > 0)
            {
                var mycardCoupon = bllCardCoupon.GetMyCardCoupon(orderRequestModel.cardcoupon_id, CurrentUserInfo.UserID);
                if (mycardCoupon == null)
                {
                    apiResp.code = 1;
                    apiResp.msg  = "无效的优惠券";
                    context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp)); return;
                }
                var cardCoupon = bllCardCoupon.GetCardCoupon(mycardCoupon.CardId);
                if (cardCoupon == null)
                {
                    apiResp.code = 1;
                    apiResp.msg  = "无效的优惠券";
                    context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp)); return;
                }
                #region 需要购买指定商品
                if ((!string.IsNullOrEmpty(cardCoupon.Ex2)) && (cardCoupon.Ex2 != "0"))
                {
                    if (productList.Count(p => p.PID == cardCoupon.Ex2) == 0)
                    {
                        var productInfo = bllMall.GetProduct(cardCoupon.Ex2);
                        apiResp.code = 1;
                        apiResp.msg  = string.Format("此优惠券需要购买{0}时才可以使用", productInfo.PName);
                        context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp)); return;
                    }
                }


                #endregion

                #region 需要购买指定标签商品
                if (!string.IsNullOrEmpty(cardCoupon.Ex8))
                {
                    if (productList.Where(p => p.Tags == "" || p.Tags == null).Count() == productList.Count)//全部商品都没有标签
                    {
                        apiResp.code = 1;
                        apiResp.msg  = string.Format("使用此优惠券需要购买标签为{0}的商品", cardCoupon.Ex8);
                        context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp)); return;
                    }
                    bool checkResult = false;
                    foreach (var product in productList)
                    {
                        if (!string.IsNullOrEmpty(product.Tags))
                        {
                            foreach (string tag in product.Tags.Split(','))
                            {
                                if (cardCoupon.Ex8.Contains(tag))
                                {
                                    checkResult = true;
                                    break;
                                }
                            }
                        }
                    }
                    if (!checkResult)
                    {
                        apiResp.code = 1;
                        apiResp.msg  = string.Format("使用此优惠券需要购买标签为{0}的商品", cardCoupon.Ex8);
                        context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp)); return;
                    }
                }
                #endregion
            }
            #endregion

            foreach (var sku in orderRequestModel.skus)
            {
                //先检查库存
                ProductSku productSku = bllMall.GetProductSku(sku.sku_id);
                if (productSku == null)
                {
                    apiResp.code = 1;
                    apiResp.msg  = "SKU不存在";
                    context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp)); return;
                }
                WXMallProductInfo productInfo = bllMall.GetProduct(productSku.ProductId.ToString());
                if (productInfo.IsOnSale == "0")
                {
                    apiResp.code = 1;
                    apiResp.msg  = string.Format("{0}已下架", productInfo.PName);
                    context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                    return;
                }

                WXMallOrderDetailsInfo detailModel = new WXMallOrderDetailsInfo();
                detailModel.OrderID     = orderInfo.OrderID;
                detailModel.PID         = productInfo.PID;
                detailModel.TotalCount  = sku.count;
                detailModel.OrderPrice  = bllMall.GetSkuPrice(productSku) * totalHours;
                detailModel.ProductName = productInfo.PName;
                detailModel.SkuId       = productSku.SkuId;
                detailList.Add(detailModel);
            }
            #endregion
            productFee = detailList.Sum(p => p.OrderPrice * p.TotalCount).Value;   //商品费用
            orderInfo.Transport_Fee = 0;
            orderInfo.Product_Fee   = productFee;
            orderInfo.TotalAmount   = orderInfo.Product_Fee + orderInfo.Transport_Fee;
            #region 优惠券计算
            decimal discountAmount   = 0;//优惠金额
            bool    canUseCardCoupon = false;
            string  msg = "";
            if (orderRequestModel.cardcoupon_id > 0)//有优惠券
            {
                discountAmount = bllMall.CalcDiscountAmount(orderRequestModel.cardcoupon_id.ToString(), data, CurrentUserInfo.UserID, out canUseCardCoupon, out msg);
                if (!canUseCardCoupon)
                {
                    apiResp.code = 1;
                    apiResp.msg  = msg;
                    context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp)); return;
                }
                if (discountAmount > productFee)
                {
                    apiResp.code = 1;
                    apiResp.msg  = "优惠券可优惠金额超过了订单总金额";
                    context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp)); return;
                }
                orderInfo.CardcouponDisAmount = discountAmount;
            }
            #endregion

            #region 积分计算
            decimal scoreExchangeAmount = 0;///积分抵扣的金额
            //积分计算
            if (orderRequestModel.use_score > 0)
            {
                if (CurrentUserInfo.TotalScore < orderRequestModel.use_score)
                {
                    apiResp.code = 1;
                    apiResp.msg  = "积分不足";
                    context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp)); return;
                }
                ScoreConfig scoreConfig = bllScore.GetScoreConfig();
                scoreExchangeAmount = Math.Round(orderRequestModel.use_score / (scoreConfig.ExchangeScore / scoreConfig.ExchangeAmount), 2);
            }



            //积分计算
            #endregion

            #region 合计计算

            orderInfo.TotalAmount  -= discountAmount;        //优惠券优惠金额
            orderInfo.TotalAmount  -= scoreExchangeAmount;   //积分优惠金额
            orderInfo.PayableAmount = orderInfo.TotalAmount; //应付金额
            if ((productFee - discountAmount - scoreExchangeAmount) < orderInfo.TotalAmount)
            {
                apiResp.code = 1;
                apiResp.msg  = "积分兑换金额不能大于订单总金额,请减少积分兑换";
                context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                return;
            }
            #endregion
            if (orderInfo.TotalAmount < 0)
            {
                apiResp.code = 1;
                apiResp.msg  = "付款金额不能小于0";
                context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                return;
            }
            if (orderInfo.TotalAmount == 0)
            {
                orderInfo.PaymentStatus = 1;
                orderInfo.PayTime       = DateTime.Now;
                orderInfo.Status        = "待发货";
            }
            ZentCloud.ZCBLLEngine.BLLTransaction tran = new ZCBLLEngine.BLLTransaction();
            try
            {
                if (!this.bllMall.Add(orderInfo, tran))
                {
                    tran.Rollback();
                    apiResp.code = 1;
                    apiResp.msg  = "提交失败";
                    context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp)); return;
                }

                #region 更新优惠券使用状态
                //优惠券
                if (orderRequestModel.cardcoupon_id > 0 && (canUseCardCoupon == true))//有优惠券且已经成功使用
                {
                    MyCardCoupons myCardCoupon = bllCardCoupon.GetMyCardCoupon(orderRequestModel.cardcoupon_id, CurrentUserInfo.UserID);
                    myCardCoupon.UseDate = DateTime.Now;
                    myCardCoupon.Status  = 1;
                    if (!bllCardCoupon.Update(myCardCoupon, tran))
                    {
                        tran.Rollback();
                        apiResp.code = 1;
                        apiResp.msg  = "更新优惠券状态失败";
                        context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp)); return;
                    }
                }
                //优惠券
                #endregion

                #region 积分抵扣
                //积分扣除
                if (orderRequestModel.use_score > 0)
                {
                    CurrentUserInfo.TotalScore -= orderRequestModel.use_score;
                    if (bllMall.Update(CurrentUserInfo, string.Format(" TotalScore-={0}", orderRequestModel.use_score), string.Format(" AutoID={0}", CurrentUserInfo.AutoID)) < 0)
                    {
                        tran.Rollback();
                        apiResp.code = 1;
                        apiResp.msg  = "更新用户积分失败";
                        context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp)); return;
                    }
                    //积分记录
                    UserScoreDetailsInfo scoreRecord = new UserScoreDetailsInfo();
                    scoreRecord.AddTime   = DateTime.Now;
                    scoreRecord.Score     = -orderRequestModel.use_score;
                    scoreRecord.ScoreType = "OrderSubmit";
                    scoreRecord.UserID    = CurrentUserInfo.UserID;
                    scoreRecord.AddNote   = "预约使用积分";
                    if (!bllMall.Add(scoreRecord))
                    {
                        tran.Rollback();
                        apiResp.code = 1;
                        apiResp.msg  = "插入积分记录失败";
                        context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                        return;
                    }
                    //积分记录
                }

                //积分扣除
                #endregion

                #region 插入订单详情页
                foreach (var item in detailList)
                {
                    ProductSku        productSku  = bllMall.GetProductSku((int)(item.SkuId));
                    WXMallProductInfo productInfo = bllMall.GetProduct(productSku.ProductId.ToString());
                    if (!this.bllMall.Add(item, tran))
                    {
                        tran.Rollback();
                        apiResp.code = 1;
                        apiResp.msg  = "提交失败";
                        context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp)); return;
                    }
                }
                #endregion

                tran.Commit();//提交订单事务
            }
            catch (Exception ex)
            {
                //回滚事物
                tran.Rollback();
                apiResp.code = 1;
                apiResp.msg  = "提交订单失败,内部错误";
                context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                return;
            }
            apiResp.status = true;
            apiResp.msg    = "ok";
            apiResp.result = new
            {
                order_id = orderInfo.OrderID
            };
            context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
        }
Esempio n. 23
0
File: Get.ashx.cs Progetto: uvbs/mmp
        public void ProcessRequest(HttpContext context)
        {
            string orderId = context.Request["order_id"];

            if (string.IsNullOrEmpty(orderId))
            {
                apiResp.code = (int)APIErrCode.OperateFail;
                apiResp.msg  = "order_id 必传";
                context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                return;
            }
            WXMallOrderInfo orderInfo = bllMall.GetOrderInfo(orderId);

            if (orderInfo == null)
            {
                apiResp.code = (int)APIErrCode.OperateFail;
                apiResp.msg  = "订单号不存在";
                context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                return;
            }
            if (orderInfo.OrderType != 2)
            {
                apiResp.code = (int)APIErrCode.OperateFail;
                apiResp.msg  = "不是拼团订单";
                context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                return;
            }
            if (!string.IsNullOrEmpty(orderInfo.GroupBuyParentOrderId))
            {
                orderInfo = bllMall.GetOrderInfo(orderInfo.GroupBuyParentOrderId);
            }
            if (orderInfo.PaymentStatus == 0)
            {
                apiResp.code = (int)APIErrCode.OperateFail;
                apiResp.msg  = "团长订单未付款";
                context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                return;
            }
            WXMallOrderDetailsInfo orderDetail = bllMall.GetOrderDetail(orderInfo.OrderID).First();
            WXMallProductInfo      productInfo = bllMall.GetProduct(orderDetail.PID);
            ProductSku             skuInfo     = bllMall.GetProductSku((int)orderDetail.SkuId);
            decimal kk = Math.Round((decimal)productInfo.Price * (decimal)(orderInfo.MemberDiscount / 10), 2);

            apiResp.result =
                new
            {
                order_id           = orderInfo.OrderID,
                product_id         = productInfo.PID,
                product_name       = productInfo.PName,
                summary            = productInfo.Summary,
                priduct_price      = productInfo.Price,
                product_price      = productInfo.Price,
                product_img_url    = bllMall.GetImgUrl(productInfo.RecommendImg),
                product_properties = bllMall.GetProductProperties(skuInfo.SkuId),
                product_desc       = productInfo.PDescription,
                is_join            = IsJoin(orderInfo),
                people_list        = GetPeopleList(orderInfo),
                head_discount      = orderInfo.HeadDiscount,
                head_price         = Math.Round((decimal)productInfo.Price * (decimal)(orderInfo.HeadDiscount / 10), 2),
                member_discount    = orderInfo.MemberDiscount,
                member_price       = Math.Round((decimal)productInfo.Price * (decimal)(orderInfo.MemberDiscount / 10), 2),
                people_count       = orderInfo.PeopleCount,
                pay_people_count   = GetPayPeopleCount(orderInfo),
                expire_day         = orderInfo.ExpireDay,
                is_head            = IsHead(orderInfo),
                group_buy_status   = GetGroupBuyStatus(orderInfo),
                end_time           = bllMall.GetTimeStamp(((DateTime)orderInfo.PayTime).AddDays(orderInfo.ExpireDay)),
                pay_order_id       = GetNeedPayOrderId(orderInfo),
                score           = productInfo.Score,
                is_cashpay_only = productInfo.IsCashPayOnly,
                is_no_express   = productInfo.IsNoExpress,
                sku_id          = skuInfo.SkuId,
                ex10            = orderInfo.Ex10
            };
            apiResp.status = true;
            apiResp.msg    = "ok";
            context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
        }
Esempio n. 24
0
        /// <summary>
        /// 抓取单个商品
        /// </summary>
        /// <param name="searchRst"></param>
        /// <returns></returns>
        bool getProduct(SearchProductResult searchRst)
        {
            if (searchRst == null)
            {
                return(false);
            }

            #region//TODO 抓取商品数据
            var detailsHtml = WebClientHelper.GetContent(searchRst.Link, detailsOption.Encoding);

            if (string.IsNullOrWhiteSpace(detailsHtml))
            {
                return(false);
            }

            //商品装载数据
            ProductSetupResult setup = null;
            Regex setupRegex         = new Regex(detailsOption.SetupRegex.Pattern, RegexOptions.IgnoreCase);
            Match setupMatch         = setupRegex.Match(detailsHtml);
            if (setupMatch != null)
            {
                string setupData = setupMatch.Groups[detailsOption.SetupRegex.GroupName].Value;
                setup = JsonConvert.DeserializeObject <ProductSetupResult>(setupData);
            }

            if (setup == null || setup.ItemDO == null)
            {
                return(false);
            }

            //定义商品ID
            long productId = Tools.NewId();

            //图片
            Dictionary <string, string> proImgDic = new Dictionary <string, string>();//key为“商品ID_v序号”组成,value为采集的图片地址
            Regex imagesRegex = new Regex(detailsOption.ImagesDataRegex.Pattern, RegexOptions.IgnoreCase);
            Match imagesMatch = imagesRegex.Match(detailsHtml);
            if (imagesMatch != null)
            {
                string imagesData = imagesMatch.Groups[detailsOption.ImagesDataRegex.GroupName].Value;

                Regex singleImgRegex = new Regex(detailsOption.SingleImageRegex.Pattern, RegexOptions.IgnoreCase);

                MatchCollection singleImgMatches = singleImgRegex.Matches(imagesData);

                Regex removeRegex = new Regex(detailsOption.ImageSrcRemoveRegex.Pattern, RegexOptions.IgnoreCase);

                int proIdx = 0;
                foreach (Match m in singleImgMatches)
                {
                    string src = m.Groups[detailsOption.SingleImageRegex.GroupName].Value.GetFullLink();

                    //移除缩略图标识,保留原图地址
                    src = removeRegex.Replace(src, "");

                    proImgDic.Add($"{setup.ItemDO.ItemId}_v{++proIdx}", src);
                }
            }

            //商品描述
            string desc      = null;
            var    descHtml  = WebClientHelper.GetContent(setup.Api.DescUrl, detailsOption.Encoding);
            Regex  descRegex = new Regex(detailsOption.DescRegex.Pattern, RegexOptions.IgnoreCase);
            Match  descMatch = descRegex.Match(descHtml);
            if (descMatch != null)
            {
                desc = descMatch.Groups[detailsOption.DescRegex.GroupName].Value;
            }

            //描述中的图片
            Dictionary <string, string> descImgDic = new Dictionary <string, string>();//key为“商品ID_d序号”组成,value为采集的图片地址
            Regex           descImgRegex           = new Regex(detailsOption.DescImageRegex.Pattern, RegexOptions.IgnoreCase);
            MatchCollection descImgMatches         = descImgRegex.Matches(desc);
            int             descIdx = 0;
            foreach (Match m in descImgMatches)
            {
                string src = m.Groups[detailsOption.DescImageRegex.GroupName].Value;

                //当前图片标识
                string currentImgTag = $"{setup.ItemDO.ItemId}_d{++descIdx}";

                //将详情描述中的当前图片地址用标识符替换以占位,待上传后用新地址替换
                desc = desc.Replace(src, currentImgTag);

                descImgDic.Add(currentImgTag, src.GetFullLink());
            }
            #endregion

            //下载商品展示图
            proImgDic = WebClientHelper.DownloadFile(proImgDic, uploadOption.VisitAddress, uploadOption.SaveDirectory);

            //下载商品描述图
            descImgDic = WebClientHelper.DownloadFile(descImgDic, uploadOption.VisitAddress, uploadOption.SaveDirectory);

            //将描述中的图更换为上传后的地址
            foreach (var img in descImgDic)
            {
                //将描述中的标识符替换为上传后的图片地址
                desc = desc.Replace(img.Key, img.Value);
            }

            #region // 解析成产品库数据

            string title = setup.ItemDO.Title;

            if (detailsOption.ReplaceItems.Any())
            {
                foreach (var rep in detailsOption.ReplaceItems)
                {
                    title = title.Replace(rep.SourceText, rep.ReplaceTo);
                    desc  = desc.Replace(rep.SourceText, rep.ReplaceTo);
                }
            }

            //商品
            Product product = new Product
            {
                BrandID         = long.Parse(setup.ItemDO.BrandId),
                CategoryID      = searchRst.CategoryId,
                CreateTime      = DateTime.Now,
                Intro           = desc,
                IsDelete        = false,
                mainPic         = proImgDic.Values.FirstOrDefault(),
                Path            = searchRst.Link,
                Pics            = string.Join(",", proImgDic.Values),
                ProductID       = productId,
                Properties      = string.Empty,
                Source          = collectorType,
                Title           = title,
                UpdateTime      = DateTime.Now,
                Weight          = float.Parse(setup.ItemDO.Weight),
                SourceProductID = long.Parse(setup.ItemDO.ItemId)
            };

            //SKU
            ProductSku sku = new ProductSku
            {
                CreateTime = product.CreateTime,
                IsDelete   = false,
                Name       = product.Title,
                ProductID  = product.ProductID,
                SalePrice  = decimal.Parse(setup.Detail.DefaultItemPrice),
                SkuID      = Tools.NewId(),
                UpdateTime = product.UpdateTime,
                Weight     = product.Weight
            };

            #endregion

            #region // 保存到数据库

            using (var db = new DataContext())
            {
                db.Product.Add(product);
                db.ProductSku.Add(sku);

                return(db.SaveChanges() > 0);
            }

            #endregion
        }
Esempio n. 25
0
        /// <summary>
        /// 加入购物车
        /// </summary>
        /// <param name="user_id"></param>
        /// <param name="product_id"></param>
        /// <param name="specset"></param>
        /// <param name="qty"></param>
        /// <returns></returns>
        public StateCode Join(long user_id, long product_id, string specset, int qty)
        {
            using (ISession s = SessionFactory.Instance.CreateSession())
            {
                try
                {
                    //商品SKU
                    ProductSku sku = s.Get <ProductSku>("where product_id = @0 and dbo.fn_check_specset(specset,@1) = 1 ", product_id, specset ?? "");

                    //商品已删除
                    Product product = s.Get <Product>("where id = @0 ", sku.product_id);
                    if (product == null)
                    {
                        return(StateCode.State_501);
                    }

                    //商品已下架
                    if (!((bool)product.is_shelves && !(bool)product.is_delete && (DateTime.Now > product.shelves_sdate && DateTime.Now < product.shelves_edate)))
                    {
                        return(StateCode.State_505);
                    }

                    s.StartTransaction();

                    //购买数量大于0
                    if (qty > 0 || qty == -1)
                    {
                        //规格详细信息
                        StringBuilder sb = new StringBuilder();

                        //是否开启规格
                        if (product.is_open_spec)
                        {
                            string[] arr = StringHelper.StringToArray(sku.specset);
                            foreach (string i in arr)
                            {
                                int specname_id  = 0;
                                int specvalue_id = 0;
                                if (i.IndexOf("_") != -1)
                                {
                                    int.TryParse(i.Split('_')[0], out specname_id);
                                    int.TryParse(i.Split('_')[1], out specvalue_id);

                                    SpecName  specname  = s.Get <SpecName>("where id = @0 ", specname_id);
                                    SpecValue specvalue = s.Get <SpecValue>("where id = @0 ", specvalue_id);

                                    if (specname != null && specvalue != null)
                                    {
                                        if (sb.Length == 0)
                                        {
                                            sb.Append(string.Format("{0}:{1}", specname.name, specvalue.val));
                                        }
                                        else
                                        {
                                            sb.Append(string.Format(",{0}:{1}", specname.name, specvalue.val));
                                        }
                                    }
                                    else
                                    {
                                        throw new Exception("商品规格信息异常");
                                    }
                                }
                            }
                        }

                        string img_url = "";
                        Img    img     = s.Get <Img>(" where biz_type = @0 and biz_id = @1 and is_main = @2", ImgType.Product_Cover, sku.product_id, true);
                        if (img != null)
                        {
                            if (img.is_webimg)
                            {
                                img_url = img.webimg_url;
                            }
                            else
                            {
                                img.visit_path = img.visit_path.Replace("/Image/", "/Thm_Image/");
                                img_url        = img.domain_name + img.visit_path + img.file_name + img.extend_name;
                            }
                        }

                        //当前购物车信息
                        ShoppingCart shoppingcart = s.Get <ShoppingCart>("where user_id = @0 and dbo.fn_check_specset(specset,@1) = 1 and product_id = @2", user_id, sku.specset, product_id);

                        if (shoppingcart != null)
                        {
                            shoppingcart.product_img_url = img_url;
                            shoppingcart.count          += qty;
                            shoppingcart.market_price    = product.market_price;
                            shoppingcart.product_price   = sku.sale_price;
                            shoppingcart.product_name    = product.name;
                            shoppingcart.weight          = sku.weight;
                            shoppingcart.updated_date    = DateTime.Now;
                            s.Update <ShoppingCart>(shoppingcart);
                        }
                        else
                        {
                            shoppingcart = new ShoppingCart()
                            {
                                user_id         = user_id,
                                product_id      = sku.product_id,
                                market_price    = product.market_price,
                                product_price   = sku.sale_price,
                                product_name    = product.name,
                                product_en_name = product.en_name,
                                weight          = sku.weight,
                                specset         = sku.specset,
                                spec_msg        = sb.ToString(),
                                product_img_url = img_url,
                                count           = qty,
                                created_date    = DateTime.Now,
                                updated_date    = DateTime.Now
                            };
                            s.Insert <ShoppingCart>(shoppingcart);
                        }
                    }

                    s.Commit();
                    return(StateCode.State_200);
                }
                catch (Exception ex)
                {
                    s.RollBack();
                    return(StateCode.State_500);
                }
            }
        }
Esempio n. 26
0
        public void ProcessRequest(HttpContext context)
        {
            WebsiteInfo websiteInfo = bllMall.GetWebsiteInfoModelFromDataBase();

            Open.HongWareSDK.Client     hongWareClient        = new Open.HongWareSDK.Client(websiteInfo.WebsiteOwner);
            Open.HongWareSDK.MemberInfo hongWeiWareMemberInfo = null;
            if (websiteInfo.IsUnionHongware == 1)
            {
                hongWeiWareMemberInfo = hongWareClient.GetMemberInfo(CurrentUserInfo.WXOpenId);
                if (hongWeiWareMemberInfo.member == null)
                {
                    apiResp.code = (int)APIErrCode.OperateFail;
                    apiResp.msg  = "您尚未绑定宏巍账号,请先绑定";
                    context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                    return;
                }
            }
            string data = context.Request["data"];

            if (string.IsNullOrEmpty(data))
            {
                apiResp.code = (int)APIErrCode.OperateFail;
                apiResp.msg  = "data 参数必传";
                context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                return;
            }
            decimal    productFee = 0;    //商品总价格 不包含邮费
            OrderModel orderRequestModel; //订单模型

            try
            {
                orderRequestModel = ZentCloud.Common.JSONHelper.JsonToModel <OrderModel>(data);
            }
            catch (Exception ex)
            {
                apiResp.code = (int)APIErrCode.OperateFail;
                apiResp.msg  = "JSON格式错误,请检查。错误信息:" + ex.Message;
                context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                return;
            }
            if (string.IsNullOrEmpty(orderRequestModel.order_id))
            {
                apiResp.code = (int)APIErrCode.OperateFail;
                apiResp.msg  = "order_id 必传";
                context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                return;
            }



            WXMallOrderInfo parentOrderInfo = bllMall.GetOrderInfo(orderRequestModel.order_id);//父订单

            if (parentOrderInfo == null)
            {
                apiResp.code = (int)APIErrCode.OperateFail;
                apiResp.msg  = "订单不存在";
                context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                return;
            }
            if (parentOrderInfo.OrderUserID == CurrentUserInfo.UserID)
            {
                apiResp.code = (int)APIErrCode.OperateFail;
                apiResp.msg  = "团长不可以参加";
                context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                return;
            }
            if (parentOrderInfo.OrderType != 2)
            {
                apiResp.code = (int)APIErrCode.OperateFail;
                apiResp.msg  = "不是拼团订单";
                context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                return;
            }
            if (!string.IsNullOrEmpty(parentOrderInfo.GroupBuyParentOrderId))
            {
                apiResp.code = (int)APIErrCode.OperateFail;
                apiResp.msg  = "订单无效";
                context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                return;
            }
            if (parentOrderInfo.PaymentStatus == 0)
            {
                apiResp.code = (int)APIErrCode.OperateFail;
                apiResp.msg  = "团长订单未付款";
                context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                return;
            }
            if (bllMall.GetCount <WXMallOrderInfo>(string.Format("PaymentStatus=1 And GroupBuyParentOrderId='{0}' Or OrderId='{0}'", parentOrderInfo.OrderID)) >= parentOrderInfo.PeopleCount)
            {
                apiResp.code = (int)APIErrCode.OperateFail;
                apiResp.msg  = "团购人数已满";
                context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                return;
            }
            if (bllMall.GetCount <WXMallOrderInfo>(string.Format("GroupBuyParentOrderId='{0}' And OrderUserId='{1}' And PaymentStatus=0", parentOrderInfo.OrderID, CurrentUserInfo.UserID)) > 0)
            {
                apiResp.code = (int)APIErrCode.OperateFail;
                apiResp.msg  = "您还有未支付的订单,请先支付";
                context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                return;
            }
            if (DateTime.Now >= (((DateTime)parentOrderInfo.PayTime).AddDays(parentOrderInfo.ExpireDay)))
            {
                parentOrderInfo.GroupBuyStatus = "2";
                bllMall.Update(parentOrderInfo);
                apiResp.code = (int)APIErrCode.OperateFail;
                apiResp.msg  = "拼团已过期";
                context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                return;
            }

            #region 分销关系建立
            if (websiteInfo.DistributionRelationBuildMallOrder == 1)
            {
                UserInfo orderUserInfo = bllUser.GetUserInfo(parentOrderInfo.OrderUserID, parentOrderInfo.WebsiteOwner);
                if (bllUser.IsDistributionMember(orderUserInfo))
                {
                    if (string.IsNullOrEmpty(CurrentUserInfo.DistributionOwner))
                    {
                        var setUserDistributionOwnerResult = bllDis.SetUserDistributionOwner(CurrentUserInfo.UserID, orderUserInfo.UserID, CurrentUserInfo.WebsiteOwner);
                        if (setUserDistributionOwnerResult)
                        {
                            CurrentUserInfo.DistributionOwner = orderUserInfo.UserID;
                            CurrentUserInfo.Channel           = orderUserInfo.Channel;
                        }
                    }
                }
            }
            #endregion


            WXMallOrderInfo orderInfo = new WXMallOrderInfo();//订单表
            orderInfo.Address       = orderRequestModel.receiver_address;
            orderInfo.Consignee     = orderRequestModel.receiver_name;
            orderInfo.InsertDate    = DateTime.Now;
            orderInfo.OrderUserID   = CurrentUserInfo.UserID;
            orderInfo.Phone         = orderRequestModel.receiver_phone;
            orderInfo.WebsiteOwner  = bllMall.WebsiteOwner;
            orderInfo.Transport_Fee = 0;
            orderInfo.OrderID       = bllMall.GetGUID(BLLJIMP.TransacType.AddMallOrder);
            if (bllMall.WebsiteOwner != "mixblu")
            {
                orderInfo.OutOrderId = orderInfo.OrderID;
            }
            orderInfo.OrderMemo            = orderRequestModel.buyer_memo;
            orderInfo.ReceiverProvince     = orderRequestModel.receiver_province;
            orderInfo.ReceiverProvinceCode = orderRequestModel.receiver_province_code.ToString();
            orderInfo.ReceiverCity         = orderRequestModel.receiver_city;
            orderInfo.ReceiverCityCode     = orderRequestModel.receiver_city_code.ToString();
            orderInfo.ReceiverDist         = orderRequestModel.receiver_dist;
            orderInfo.ReceiverDistCode     = orderRequestModel.receiver_dist_code.ToString();
            orderInfo.ZipCode               = orderRequestModel.receiver_zip;
            orderInfo.Status                = "待付款";
            orderInfo.OrderType             = 2;
            orderInfo.GroupBuyParentOrderId = parentOrderInfo.OrderID;
            orderInfo.MyCouponCardId        = orderRequestModel.cardcoupon_id.ToString();
            orderInfo.UseScore              = orderRequestModel.use_score;
            orderInfo.UseAmount             = orderRequestModel.use_amount;
            orderInfo.LastUpdateTime        = DateTime.Now;

            if (orderRequestModel.pay_type == "WEIXIN")//微信支付
            {
                orderInfo.PaymentType = 2;
            }
            else if (orderRequestModel.pay_type == "ALIPAY")//支付宝支付
            {
                orderInfo.PaymentType = 1;
            }

            #region 格式检查

            if (string.IsNullOrEmpty(orderInfo.Consignee))
            {
                apiResp.code = (int)APIErrCode.OperateFail;
                apiResp.msg  = "收货人姓名不能为空";
                context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                return;
            }
            if (string.IsNullOrEmpty(orderInfo.Phone))
            {
                apiResp.code = (int)APIErrCode.OperateFail;
                apiResp.msg  = "收货人联系电话不能为空";
                context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                return;
            }
            if (string.IsNullOrEmpty(orderInfo.ReceiverProvince))
            {
                apiResp.code = (int)APIErrCode.OperateFail;
                apiResp.msg  = "省份名称不能为空";
                context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                return;
            }
            if (string.IsNullOrEmpty(orderInfo.ReceiverProvinceCode))
            {
                apiResp.code = (int)APIErrCode.OperateFail;
                apiResp.msg  = "省份代码不能为空";
                context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                return;
            }
            if (string.IsNullOrEmpty(orderInfo.ReceiverCity))
            {
                apiResp.code = (int)APIErrCode.OperateFail;
                apiResp.msg  = "城市名称不能为空";
                context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                return;
            }
            if (string.IsNullOrEmpty(orderInfo.ReceiverCityCode))
            {
                apiResp.code = (int)APIErrCode.OperateFail;
                apiResp.msg  = "城市代码不能为空";
                context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                return;
            }
            if (string.IsNullOrEmpty(orderInfo.ReceiverDist))
            {
                apiResp.code = (int)APIErrCode.OperateFail;
                apiResp.msg  = "城市区域名称不能为空";
                context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                return;
            }
            if (string.IsNullOrEmpty(orderInfo.ReceiverCityCode))
            {
                apiResp.code = (int)APIErrCode.OperateFail;
                apiResp.msg  = "城市区域代码不能为空";
                context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                return;
            }
            if (string.IsNullOrEmpty(orderInfo.Address))
            {
                apiResp.code = (int)APIErrCode.OperateFail;
                apiResp.msg  = "收货地址不能为空";
                context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                return;
            }



            //相关检查
            #endregion


            #region 商品检查 订单详情生成


            var     needUseScore = 0; //必须使用的积分
            decimal needUseCash  = 0; //必须使用的现金

            var parentOrderDetailList = bllMall.GetOrderDetailsList(parentOrderInfo.OrderID);

            //先检查库存
            ProductSku productSku = bllMall.GetProductSku((int)parentOrderDetailList[0].SkuId);
            if (productSku == null)
            {
                apiResp.code = (int)APIErrCode.OperateFail;
                apiResp.msg  = "SKU不存在";
                context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                return;
            }

            WXMallProductInfo productInfo    = bllMall.GetProduct(productSku.ProductId.ToString());
            string            cardCouponType = "";//优惠券类型

            #region 检查优惠券是否可用
            if (orderRequestModel.cardcoupon_id > 0)
            {
                var mycardCoupon = bllCardCoupon.GetMyCardCoupon(orderRequestModel.cardcoupon_id, CurrentUserInfo.UserID);
                if (mycardCoupon == null)
                {
                    apiResp.code = (int)APIErrCode.OperateFail;
                    apiResp.msg  = "无效的优惠券";
                    context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                    return;
                }
                var cardCoupon = bllCardCoupon.GetCardCoupon(mycardCoupon.CardId);
                if (cardCoupon == null)
                {
                    apiResp.code = (int)APIErrCode.OperateFail;
                    apiResp.msg  = "无效的优惠券";
                    context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                    return;
                }
                cardCouponType = cardCoupon.CardCouponType;
                #region 需要购买指定商品
                if ((!string.IsNullOrEmpty(cardCoupon.Ex2)) && (cardCoupon.Ex2 != "0"))
                {
                    if (productInfo.PID != cardCoupon.Ex2)
                    {
                        var productInfoCard = bllMall.GetProduct(cardCoupon.Ex2);
                        apiResp.code = (int)APIErrCode.OperateFail;
                        apiResp.msg  = string.Format("此优惠券需要购买{0}时才可以使用", productInfoCard.PName);
                        context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                        return;
                    }
                }
                #endregion

                #region 需要购买指定标签商品
                if (!string.IsNullOrEmpty(cardCoupon.Ex8))
                {
                    if (string.IsNullOrEmpty(productInfo.Tags))//全部商品都没有标签
                    {
                        apiResp.code = (int)APIErrCode.OperateFail;
                        apiResp.msg  = string.Format("使用此优惠券需要购买标签为{0}的商品", cardCoupon.Ex8);
                        context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                        return;
                    }
                    bool checkResult = true;

                    if (!string.IsNullOrEmpty(productInfo.Tags))
                    {
                        bool tempResult = false;
                        foreach (string tag in productInfo.Tags.Split(','))
                        {
                            if (cardCoupon.Ex8.Contains(tag))
                            {
                                tempResult = true;
                                break;
                            }
                        }
                        if (!tempResult)
                        {
                            checkResult = false;
                        }
                    }
                    else//商品不包含标签
                    {
                        checkResult = false;
                    }
                    if (!checkResult)
                    {
                        apiResp.code = (int)APIErrCode.OperateFail;
                        apiResp.msg  = string.Format("使用此优惠券需要购买标签为{0}的商品", cardCoupon.Ex8);
                        context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                        return;
                    }
                }
                #endregion
            }
            #endregion


            if (productInfo.IsOnSale == "0")
            {
                apiResp.code = (int)APIErrCode.OperateFail;
                apiResp.msg  = string.Format("{0}已下架", productInfo.PName);
                context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                return;
            }
            if (productSku.Stock < 1)
            {
                apiResp.code = (int)APIErrCode.OperateFail;
                apiResp.msg  = string.Format("{0}{1}库存余量为{2},库存不足", productInfo.PName, bllMall.GetProductShowProperties(productSku.SkuId), productSku.Stock);
                context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                return;
            }

            if (productInfo.Score > 0)//必须使用的积分
            {
                needUseScore = productInfo.Score;
            }
            if (productInfo.IsCashPayOnly == 1)                                                                            //必须使用的现金
            {
                needUseCash = Math.Round((decimal)(productSku.Price * (decimal)(parentOrderInfo.MemberDiscount / 10)), 2); //四舍五入
            }

            WXMallOrderDetailsInfo detailModel = new WXMallOrderDetailsInfo();
            detailModel.OrderID     = orderInfo.OrderID;
            detailModel.PID         = productInfo.PID;
            detailModel.TotalCount  = 1;
            detailModel.OrderPrice  = Math.Round((decimal)(productSku.Price * (decimal)(parentOrderInfo.MemberDiscount / 10)), 2);//四舍五入
            detailModel.ProductName = productInfo.PName;
            detailModel.SkuId       = productSku.SkuId;
            detailModel.SkuShowProp = bllMall.GetProductShowProperties(productSku.SkuId);
            detailModel.IsComplete  = 1;//拼团的只要下单就算销量


            #endregion
            #region 纯积分购买
            if (needUseScore > 0)
            {
                if ((CurrentUserInfo.TotalScore < needUseScore) || (orderRequestModel.use_score < needUseScore))
                {
                    apiResp.code = (int)APIErrCode.OperateFail;
                    apiResp.msg  = string.Format("您需要使用{0}积分来兑换, 可用积分不足", needUseScore);
                    context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                    return;
                }
            }
            #endregion



            productFee = (decimal)detailModel.OrderPrice;
            //物流费用
            #region 运费计算

            List <SkuModel> skus = new List <SkuModel>();
            skus.Add(new SkuModel
            {
                sku_id = productSku.SkuId,
                count  = 1
            });
            FreightModel freightModel = new FreightModel();
            freightModel.receiver_province_code = orderRequestModel.receiver_province_code;
            freightModel.receiver_city_code     = orderRequestModel.receiver_city_code;
            freightModel.receiver_dist_code     = orderRequestModel.receiver_dist_code;
            freightModel.skus = skus;
            decimal freight    = 0;//运费
            string  freightMsg = "";
            if (!bllMall.CalcFreight(freightModel, out freight, out freightMsg))
            {
                apiResp.code = (int)APIErrCode.OperateFail;
                apiResp.msg  = freightMsg;
                context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp)); return;
            }
            orderInfo.Transport_Fee = freight;
            #endregion

            #region 优惠券计算

            decimal discountAmount   = 0;//优惠金额
            bool    canUseCardCoupon = false;
            string  msg = "";
            if (orderRequestModel.cardcoupon_id > 0)//有优惠券
            {
                discountAmount = bllMall.CalcDiscountAmount(orderRequestModel.cardcoupon_id.ToString(), data, CurrentUserInfo.UserID, out canUseCardCoupon, out msg);
                if (!canUseCardCoupon)
                {
                    apiResp.code = (int)APIErrCode.OperateFail;
                    apiResp.msg  = msg;
                    context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                    return;
                }
                if (cardCouponType == "MallCardCoupon_FreeFreight")//免邮券
                {
                    orderInfo.Transport_Fee = 0;
                }
            }
            //优惠券计算
            #endregion


            #region 积分计算
            decimal scoreExchangeAmount = 0;///积分抵扣的金额
            //积分计算
            if (orderRequestModel.use_score > 0)
            {
                #region 使用宏巍积分
                if (websiteInfo.IsUnionHongware == 1)
                {
                    CurrentUserInfo.TotalScore = hongWeiWareMemberInfo.member.point;
                }
                #endregion
                orderInfo.UseScore = orderRequestModel.use_score;
                if (CurrentUserInfo.TotalScore < orderRequestModel.use_score)
                {
                    apiResp.code = (int)APIErrCode.OperateFail;
                    apiResp.msg  = "积分不足";
                    context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp)); return;
                }

                ScoreConfig scoreConfig = bllScore.GetScoreConfig();
                if (scoreConfig != null && scoreConfig.ExchangeAmount > 0)
                {
                    scoreExchangeAmount = Math.Round(orderRequestModel.use_score / (scoreConfig.ExchangeScore / scoreConfig.ExchangeAmount), 2);
                }
                //scoreExchangeAmount = Math.Round(orderRequestModel.use_score / (scoreConfig.ExchangeScore / scoreConfig.ExchangeAmount), 2);
            }



            //积分计算
            #endregion

            #region 使用账户余额
            if (orderRequestModel.use_amount > 0)
            {
                if (!bllMall.IsEnableAccountAmountPay())
                {
                    apiResp.msg = "尚未启用余额支付功能";
                    context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                    return;
                }
                #region 使用宏巍余额
                if (websiteInfo.IsUnionHongware == 1)
                {
                    CurrentUserInfo.AccountAmount = (decimal)hongWeiWareMemberInfo.member.balance;
                }
                #endregion
                if (CurrentUserInfo.AccountAmount < orderRequestModel.use_amount)
                {
                    apiResp.code = (int)APIErrCode.OperateFail;
                    apiResp.msg  = "您的账户余额不足";
                    context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                    return;
                }
            }
            #endregion

            //合计计算
            orderInfo.Product_Fee   = productFee;
            orderInfo.TotalAmount   = orderInfo.Product_Fee + orderInfo.Transport_Fee;
            orderInfo.TotalAmount  -= discountAmount;                  //优惠券优惠金额
            orderInfo.TotalAmount  -= scoreExchangeAmount;             //积分优惠金额
            orderInfo.TotalAmount  -= orderRequestModel.use_amount;    //余额
            orderInfo.PayableAmount = orderInfo.TotalAmount - freight; //应付金额

            orderInfo.HeadDiscount          = parentOrderInfo.HeadDiscount;
            orderInfo.MemberDiscount        = parentOrderInfo.MemberDiscount;
            orderInfo.PeopleCount           = parentOrderInfo.PeopleCount;
            orderInfo.ExpireDay             = parentOrderInfo.ExpireDay;
            orderInfo.GroupBuyParentOrderId = parentOrderInfo.OrderID;

            orderInfo.ScoreExchangAmount  = scoreExchangeAmount; //优惠券抵扣金额
            orderInfo.CardcouponDisAmount = discountAmount;      //卡券抵扣金额

            if (orderInfo.TotalAmount <= 0)
            {
                orderInfo.TotalAmount   = 0;
                orderInfo.PaymentStatus = 1;
                orderInfo.PayTime       = DateTime.Now;
                orderInfo.Status        = "待发货";
            }
            if (orderInfo.TotalAmount < needUseCash)
            {
                apiResp.code = (int)APIErrCode.OperateFail;
                apiResp.msg  = string.Format("最少需要支付{0}元" + needUseCash);
                context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                return;
            }
            ZentCloud.ZCBLLEngine.BLLTransaction tran = new ZCBLLEngine.BLLTransaction();
            try
            {
                if (!this.bllMall.Add(orderInfo, tran))
                {
                    tran.Rollback();
                    apiResp.code = (int)APIErrCode.OperateFail;
                    apiResp.msg  = "提交失败";
                    context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                    return;
                }

                #region 更新优惠券使用状态
                //优惠券
                if (orderRequestModel.cardcoupon_id > 0 && (canUseCardCoupon == true))//有优惠券且已经成功使用
                {
                    MyCardCoupons myCardCoupon = bllCardCoupon.GetMyCardCoupon(orderRequestModel.cardcoupon_id, CurrentUserInfo.UserID);
                    myCardCoupon.UseDate = DateTime.Now;
                    myCardCoupon.Status  = 1;
                    if (!bllCardCoupon.Update(myCardCoupon, tran))
                    {
                        tran.Rollback();
                        apiResp.code = (int)APIErrCode.OperateFail;
                        apiResp.msg  = "更新优惠券状态失败";
                        context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                        return;
                    }
                }
                //优惠券
                #endregion

                #region 积分抵扣
                //积分扣除
                if (orderRequestModel.use_score > 0)
                {
                    CurrentUserInfo.TotalScore -= orderRequestModel.use_score;
                    if (bllMall.Update(CurrentUserInfo, string.Format(" TotalScore-={0}", orderRequestModel.use_score), string.Format(" AutoID={0}", CurrentUserInfo.AutoID), tran) < 0)
                    {
                        tran.Rollback();
                        apiResp.code = (int)APIErrCode.OperateFail;
                        apiResp.msg  = "更新用户积分失败";
                        context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                        return;
                    }

                    //积分记录
                    UserScoreDetailsInfo scoreRecord = new UserScoreDetailsInfo();
                    scoreRecord.AddTime      = DateTime.Now;
                    scoreRecord.Score        = -orderRequestModel.use_score;
                    scoreRecord.TotalScore   = CurrentUserInfo.TotalScore;
                    scoreRecord.ScoreType    = "OrderSubmit";
                    scoreRecord.UserID       = CurrentUserInfo.UserID;
                    scoreRecord.AddNote      = "微商城-参加团购使用积分";
                    scoreRecord.WebSiteOwner = CurrentUserInfo.WebsiteOwner;
                    if (!bllMall.Add(scoreRecord, tran))
                    {
                        tran.Rollback();
                        apiResp.code = (int)APIErrCode.OperateFail;
                        apiResp.msg  = "插入积分记录失败";
                        context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                        return;
                    }
                    #region 更新宏巍积分
                    if (websiteInfo.IsUnionHongware == 1)
                    {
                        if (!hongWareClient.UpdateMemberScore(hongWeiWareMemberInfo.member.mobile, CurrentUserInfo.WXOpenId, -orderRequestModel.use_score))
                        {
                            tran.Rollback();
                            apiResp.code = (int)APIErrCode.OperateFail;
                            apiResp.msg  = "更新宏巍积分失败";
                            context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                            return;
                        }
                    }
                    #endregion
                }

                //积分扣除
                #endregion

                #region 余额抵扣

                if (orderRequestModel.use_amount > 0 && bllMall.IsEnableAccountAmountPay())
                {
                    CurrentUserInfo.AccountAmount -= orderRequestModel.use_amount;
                    if (bllMall.Update(CurrentUserInfo, string.Format(" AccountAmount={0}", CurrentUserInfo.AccountAmount), string.Format(" AutoID={0}", CurrentUserInfo.AutoID)) < 0)
                    {
                        tran.Rollback();
                        apiResp.code = (int)APIErrCode.OperateFail;
                        apiResp.msg  = "更新用户余额失败";
                        context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                        return;
                    }


                    UserScoreDetailsInfo scoreRecord = new UserScoreDetailsInfo();
                    scoreRecord.AddTime      = DateTime.Now;
                    scoreRecord.Score        = -(double)orderRequestModel.use_amount;
                    scoreRecord.TotalScore   = (double)CurrentUserInfo.AccountAmount;
                    scoreRecord.UserID       = CurrentUserInfo.UserID;
                    scoreRecord.AddNote      = "拼团-参团使用余额";
                    scoreRecord.RelationID   = orderInfo.OrderID;
                    scoreRecord.WebSiteOwner = bllUser.WebsiteOwner;
                    scoreRecord.ScoreType    = "AccountAmount";
                    if (!bllMall.Add(scoreRecord))
                    {
                        tran.Rollback();
                        apiResp.code = (int)APIErrCode.OperateFail;
                        apiResp.msg  = "插入余额记录失败";
                        context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                        return;
                    }

                    UserCreditAcountDetails record = new UserCreditAcountDetails();
                    record.WebsiteOwner = bllUser.WebsiteOwner;
                    record.Operator     = CurrentUserInfo.UserID;
                    record.UserID       = CurrentUserInfo.UserID;
                    record.CreditAcount = -orderRequestModel.use_amount;
                    record.SysType      = "AccountAmount";
                    record.AddTime      = DateTime.Now;
                    record.AddNote      = "账户余额变动-" + orderRequestModel.use_amount;
                    if (!bllMall.Add(record))
                    {
                        tran.Rollback();
                        apiResp.code = (int)APIErrCode.OperateFail;
                        apiResp.msg  = "插入余额记录失败";
                        context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                        return;
                    }
                    #region 更新宏巍余额
                    if (websiteInfo.IsUnionHongware == 1)
                    {
                        if (!hongWareClient.UpdateMemberBlance(hongWeiWareMemberInfo.member.mobile, CurrentUserInfo.WXOpenId, -(float)orderRequestModel.use_amount))
                        {
                            tran.Rollback();
                            apiResp.code = (int)APIErrCode.OperateFail;
                            apiResp.msg  = "更新宏巍余额失败";
                            context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(resp));
                            return;
                        }
                    }
                    #endregion
                }


                #endregion

                #region 插入订单详情表及更新库存

                if (!this.bllMall.Add(detailModel, tran))
                {
                    tran.Rollback();
                    apiResp.code = (int)APIErrCode.OperateFail;
                    apiResp.msg  = "提交失败";
                    context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                    return;
                }
                //更新 SKU库存
                System.Text.StringBuilder sbUpdateStock = new StringBuilder();//更新库存sql
                sbUpdateStock.AppendFormat(" Update ZCJ_ProductSku Set Stock-={0} ", 1);
                sbUpdateStock.AppendFormat(" Where SkuId={0} And Stock>0 ", productSku.SkuId);
                if (ZentCloud.ZCBLLEngine.BLLBase.ExecuteSql(sbUpdateStock.ToString(), tran) <= 0)
                {
                    tran.Rollback();
                    apiResp.code = (int)APIErrCode.OperateFail;
                    apiResp.msg  = "提交订单失败,库存不足";
                    context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                    return;
                }

                #endregion

                tran.Commit();//提交订单事务
                #region 宏巍通知
                if (websiteInfo.IsUnionHongware == 1)
                {
                    hongWareClient.OrderNotice(CurrentUserInfo.WXOpenId, orderInfo.OrderID);
                }
                #endregion
                try
                {
                    //团购完成取消其它未付款订单
                    if (parentOrderInfo.Ex10 == "1")
                    {
                        if (bllMall.GetCount <WXMallOrderInfo>(string.Format("PaymentStatus=1 And  (GroupBuyParentOrderId='{0}')", parentOrderInfo.OrderID)) >= parentOrderInfo.PeopleCount)
                        {
                            bllMall.Update(new WXMallOrderInfo(), string.Format("Status='已取消'"), string.Format("  GroupBuyParentOrderId='{0}' And PaymentStatus=0", parentOrderInfo.OrderID));
                            parentOrderInfo.GroupBuyStatus = "1";
                            bllMall.Update(parentOrderInfo);
                        }
                    }
                    else
                    {
                        if (bllMall.GetCount <WXMallOrderInfo>(string.Format("PaymentStatus=1 And  (GroupBuyParentOrderId='{0}' Or OrderId='{0}')", parentOrderInfo.OrderID)) >= parentOrderInfo.PeopleCount)
                        {
                            bllMall.Update(new WXMallOrderInfo(), string.Format("Status='已取消'"), string.Format("  GroupBuyParentOrderId='{0}' And PaymentStatus=0", parentOrderInfo.OrderID));
                            parentOrderInfo.GroupBuyStatus = "1";
                            bllMall.Update(parentOrderInfo);
                        }
                    }

                    #region 微信模板消息
                    string title = "订单已成功提交";
                    if (orderInfo.TotalAmount > 0)
                    {
                        title += ",请尽快付款";
                    }
                    bllWeiXin.SendTemplateMessageNotifyComm(CurrentUserInfo, title, string.Format("订单号:{0}\\n订单金额:{1}元\\n收货人:{2}\\n电话:{3}", orderInfo.OrderID, orderInfo.TotalAmount, orderInfo.Consignee, orderInfo.Phone));
                    #endregion
                }
                catch
                {
                }
            }
            catch (Exception ex)
            {
                //回滚事物
                tran.Rollback();
                apiResp.code = (int)APIErrCode.OperateFail;
                apiResp.msg  = "提交订单失败";
                context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                return;
            }
            apiResp.status = true;
            apiResp.msg    = "ok";
            apiResp.result = new
            {
                order_id = orderInfo.OrderID
            };
            context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
        }
Esempio n. 27
0
 public async Task UpdateAsync(ProductSku productSku)
 {
     productSku.UpdatedDate = DateTime.Now;
     await _productSkuRepository.UpdateAsync(productSku);
 }
Esempio n. 28
0
        public void ProcessRequest(HttpContext context)
        {
            Add.ProductModel productRequestModel = new Add.ProductModel();//订单模型
            try
            {
                productRequestModel = bllMall.ConvertRequestToModel <Add.ProductModel>(productRequestModel);
            }
            catch (Exception ex)
            {
                apiResp.msg  = "提交格式错误";
                apiResp.code = (int)APIErrCode.OperateFail;
                bllMall.ContextResponse(context, apiResp);
                return;
            }
            //数据检查
            if (string.IsNullOrEmpty(productRequestModel.product_title))
            {
                apiResp.msg  = "商品名称必填";
                apiResp.code = (int)APIErrCode.OperateFail;
                bllMall.ContextResponse(context, apiResp);
                return;
            }
            //if (productRequestModel.price == 0)
            //{
            //    apiResp.msg = "商品价格必填";
            //    apiResp.code = (int)APIErrCode.OperateFail;
            //    bllMall.ContextResponse(context, apiResp);
            //    return;
            //}
            //if (string.IsNullOrWhiteSpace(productRequestModel.show_imgs) && !productRequestModel.article_category_type.Contains("Added"))
            //{
            //    apiResp.msg = "请上传商品图片";
            //    apiResp.code = (int)APIErrCode.OperateFail;
            //    bllMall.ContextResponse(context, apiResp);
            //    return;
            //}
            WXMallProductInfo productInfo = bllMall.GetByKey <WXMallProductInfo>("PID", productRequestModel.product_id, true);

            if (productInfo == null)
            {
                apiResp.msg  = "数据未找到";
                apiResp.code = (int)APIErrCode.IsNotFound;
                bllMall.ContextResponse(context, apiResp);
                return;
            }
            productInfo.PName        = productRequestModel.product_title;
            productInfo.PDescription = productRequestModel.product_desc;
            productInfo.Price        = productRequestModel.price;
            productInfo.CategoryId   = productRequestModel.category_id;
            productInfo.IsOnSale     = productRequestModel.is_onsale.ToString();
            productInfo.Stock        = productRequestModel.totalcount;//(容纳人数)
            productInfo.Sort         = productRequestModel.sort;
            //productInfo.UserID = currentUserInfo.UserID;
            productInfo.PreviousPrice     = productRequestModel.price;
            productInfo.Summary           = productRequestModel.product_summary;
            productInfo.LastUpdate        = DateTime.Now;
            productInfo.RelationProductId = productRequestModel.relation_product_id;
            productInfo.AccessLevel       = productRequestModel.access_Level;
            productInfo.Unit = productRequestModel.unit;
            if (!string.IsNullOrWhiteSpace(productRequestModel.show_imgs))
            {
                productInfo.ShowImage = productRequestModel.show_imgs;
                List <string> imgs = productRequestModel.show_imgs.Split(',').Where(p => !string.IsNullOrWhiteSpace(p)).ToList();
                productInfo.RecommendImg = imgs[0];
                int max = imgs.Count > 5 ? 5 : imgs.Count;
                for (int i = 0; i < max; i++)
                {
                    if (i == 0)
                    {
                        productInfo.ShowImage1 = imgs[0];
                    }
                    else if (i == 1)
                    {
                        productInfo.ShowImage2 = imgs[1];
                    }
                    else if (i == 2)
                    {
                        productInfo.ShowImage3 = imgs[2];
                    }
                    else if (i == 3)
                    {
                        productInfo.ShowImage4 = imgs[3];
                    }
                    else if (i == 4)
                    {
                        productInfo.ShowImage5 = imgs[4];
                    }
                }
            }

            string dSkuIds = "";
            //默认第一条sku
            ProductSku productSku = bllMall.GetProductSku(productRequestModel.product_id);

            if (productSku == null)
            {
                //增加系统默认sku
                productSku                     = new ProductSku();//
                productSku.InsertDate          = DateTime.Now;
                productSku.Stock               = 1;
                productSku.WebSiteOwner        = bllMall.WebsiteOwner;
                productSku.ArticleCategoryType = productInfo.ArticleCategoryType;
            }
            List <ProductSku> addSkuList    = new List <ProductSku>();
            List <ProductSku> updateSkuList = new List <ProductSku>();

            if (productRequestModel.time_set_method == 0)
            {
                productSku.Price = productInfo.Price;
                updateSkuList.Add(productSku);

                List <ProductSku> dSkuList = bllMall.GetColList <ProductSku>(int.MaxValue, 1, string.Format("ProductId={0} AND SkuId!={1} ", productInfo.PID, productSku.SkuId), "SkuId");
                if (dSkuList.Count > 0)
                {
                    dSkuIds = ZentCloud.Common.MyStringHelper.ListToStr(dSkuList.Select(p => p.SkuId).ToList(), "", ",");
                }
            }
            else if (productRequestModel.time_set_method == 1 || productRequestModel.time_set_method == 2)
            {
                List <Add.timeModel> skuModelList = JSONHelper.JsonToModel <List <Add.timeModel> >(productRequestModel.time_data);
                string pSkuIds = ZentCloud.Common.MyStringHelper.ListToStr(skuModelList.Select(p => p.sku_id).ToList(), "", ",");
                if (string.IsNullOrWhiteSpace(pSkuIds))
                {
                    pSkuIds = "0";
                }
                List <ProductSku> dSkuList = bllMall.GetColList <ProductSku>(int.MaxValue, 1, string.Format("ProductId={0} AND SkuId Not In ({1}) ", productInfo.PID, pSkuIds), "SkuId");
                if (dSkuList.Count > 0)
                {
                    dSkuIds = ZentCloud.Common.MyStringHelper.ListToStr(dSkuList.Select(p => p.SkuId).ToList(), "", ",");
                }
                foreach (Add.timeModel item in skuModelList)
                {
                    ProductSku nSku = (ProductSku)productSku.Clone();
                    if (item.sku_id != 0)
                    {
                        nSku = bllMall.GetByKey <ProductSku>("SkuId", item.sku_id.ToString());
                    }
                    nSku.PropValueIdEx1 = item.ex1;
                    nSku.PropValueIdEx2 = item.ex2;
                    nSku.PropValueIdEx3 = item.ex3;
                    nSku.Price          = item.price;
                    if (item.sku_id != 0)
                    {
                        updateSkuList.Add(nSku);
                    }
                    else
                    {
                        addSkuList.Add(nSku);
                    }
                }
            }

            BLLTransaction tran   = new BLLTransaction();
            bool           result = bllMall.Update(productInfo, tran);

            if (!result)
            {
                tran.Rollback();
                apiResp.msg  = "更新失败";
                apiResp.code = (int)APIErrCode.OperateFail;
                bllMall.ContextResponse(context, apiResp);
                return;
            }
            if (!string.IsNullOrWhiteSpace(dSkuIds))
            {
                result = bllMall.DeleteMultByKey <ProductSku>("SkuId", dSkuIds, tran) >= 0;
                if (!result)
                {
                    tran.Rollback();
                    apiResp.msg  = "删除旧时间段失败";
                    apiResp.code = (int)APIErrCode.OperateFail;
                    bllMall.ContextResponse(context, apiResp);
                    return;
                }
            }
            foreach (ProductSku item in updateSkuList)
            {
                result = bllMall.Update(item, tran);
                if (!result)
                {
                    tran.Rollback();
                    apiResp.msg  = "修改Sku失败";
                    apiResp.code = (int)APIErrCode.OperateFail;
                    bllMall.ContextResponse(context, apiResp);
                    return;
                }
            }
            int productId = int.Parse(productInfo.PID);

            foreach (ProductSku item in addSkuList)
            {
                item.ProductId = productId;
                item.SkuId     = int.Parse(bllMall.GetGUID(BLLJIMP.TransacType.AddProductSku));
                result         = bllMall.Add(item, tran);
                if (!result)
                {
                    tran.Rollback();
                    apiResp.msg  = "新增Sku失败";
                    apiResp.code = (int)APIErrCode.OperateFail;
                    bllMall.ContextResponse(context, apiResp);
                    return;
                }
            }
            tran.Commit();
            apiResp.status = true;
            apiResp.msg    = "更新完成";
            apiResp.code   = (int)APIErrCode.IsSuccess;
            bllMall.ContextResponse(context, apiResp);
        }
Esempio n. 29
0
        public void ProcessRequest(HttpContext context)
        {
            string     data = context.Request["data"];
            OrderModel orderRequestModel;//订单模型

            try
            {
                orderRequestModel = JSONHelper.JsonToModel <OrderModel>(data);
            }
            catch (Exception ex)
            {
                apiResp.msg  = "提交格式错误";
                apiResp.code = (int)APIErrCode.OperateFail;
                bllMall.ContextResponse(context, apiResp);
                return;
            }

            WXMallProductInfo productInfo = bllMall.GetProduct(orderRequestModel.product_id.ToString());

            if (productInfo == null)
            {
                apiResp.msg  = "记录没有找到";
                apiResp.code = (int)APIErrCode.IsNotFound;
                bllMall.ContextResponse(context, apiResp);
                return;
            }
            WXMallOrderInfo orderInfo = new WXMallOrderInfo();//订单表

            orderInfo.ArticleCategoryType = productInfo.ArticleCategoryType;
            orderInfo.InsertDate          = DateTime.Now;
            orderInfo.OrderUserID         = CurrentUserInfo.UserID;
            orderInfo.WebsiteOwner        = bllMall.WebsiteOwner;
            orderInfo.OrderMemo           = orderRequestModel.buyer_memo;
            orderInfo.UseAmount           = orderRequestModel.use_amount;
            if (orderRequestModel.receiver_id == 0)
            {
                orderInfo.Consignee = CurrentUserInfo.TrueName;
                orderInfo.Phone     = CurrentUserInfo.Phone;
            }
            else
            {
                WXConsigneeAddress nUserAddress = bllMall.GetByKey <WXConsigneeAddress>("AutoID", orderRequestModel.receiver_id.ToString());
                orderInfo.Consignee            = nUserAddress.ConsigneeName;
                orderInfo.Phone                = nUserAddress.Phone;
                orderInfo.Address              = nUserAddress.Address;
                orderInfo.ZipCode              = nUserAddress.ZipCode;
                orderInfo.ReceiverProvince     = nUserAddress.Province;
                orderInfo.ReceiverProvinceCode = nUserAddress.ProvinceCode;
                orderInfo.ReceiverCity         = nUserAddress.City;
                orderInfo.ReceiverCityCode     = nUserAddress.CityCode;
                orderInfo.ReceiverDist         = nUserAddress.Dist;
                orderInfo.ReceiverDistCode     = nUserAddress.DistCode;
            }

            orderInfo.Transport_Fee = 0;
            orderInfo.Status        = "待付款";
            if (orderRequestModel.pay_type == "WEIXIN")//微信支付
            {
                orderInfo.PaymentType = 2;
            }
            else if (orderRequestModel.pay_type == "ALIPAY")//支付宝支付
            {
                orderInfo.PaymentType = 1;
            }
            if (orderRequestModel.skus == null || orderRequestModel.skus.Count == 0)
            {
                apiResp.msg  = "Skus不能为空";
                apiResp.code = (int)APIErrCode.OperateFail;
                bllMall.ContextResponse(context, apiResp);
                return;
            }

            #region 商品检查 订单详情生成
            //订单详情
            List <WXMallOrderDetailsInfo> detailList      = new List <WXMallOrderDetailsInfo>(); //主商品订单明细
            List <WXMallOrderDetailsInfo> detailAddedList = new List <WXMallOrderDetailsInfo>(); //增值服务订单明细
            orderRequestModel.skus = orderRequestModel.skus.Distinct().ToList();
            #region 购买的商品
            foreach (var sku in orderRequestModel.skus)
            {
                ProductSku             productSku  = bllMall.GetProductSku(sku.sku_id);
                WXMallOrderDetailsInfo detailModel = new WXMallOrderDetailsInfo();
                detailModel.TotalCount          = sku.count;
                detailModel.OrderPrice          = bllMall.GetSkuPrice(productSku);
                detailModel.SkuId               = productSku.SkuId;
                detailModel.ArticleCategoryType = productSku.ArticleCategoryType;
                if (productSku.ArticleCategoryType.Contains("Added"))
                {
                    WXMallProductInfo rproductInfo = bllMall.GetProduct(productSku.ProductId.ToString());
                    detailModel.PID         = rproductInfo.PID;
                    detailModel.ProductName = rproductInfo.PName;
                    detailModel.Unit        = rproductInfo.Unit;
                    detailAddedList.Add(detailModel);
                }
                else
                {
                    detailModel.PID         = productInfo.PID;
                    detailModel.ProductName = productInfo.PName;
                    detailModel.StartDate   = sku.start_date;
                    detailModel.EndDate     = sku.end_date;
                    detailModel.Unit        = productInfo.Unit;
                    detailList.Add(detailModel);
                }
            }
            #endregion
            if (detailList.Count == 0)
            {
                apiResp.msg  = "请选择预约时间";
                apiResp.code = (int)APIErrCode.OperateFail;
                bllMall.ContextResponse(context, apiResp);
                return;
            }
            //已有订单详情
            List <WXMallOrderDetailsInfo> oDetailList = bllMall.GetOrderDetailsList(null, productInfo.PID, productInfo.ArticleCategoryType, detailList.Min(p => p.StartDate), detailList.Max(p => p.EndDate));
            List <string> hasOrderID_List             = new List <string>();
            string        hasOrderIDs = "";
            int           maxCount    = productInfo.Stock;
            foreach (var item in detailList)
            {
                List <WXMallOrderDetailsInfo> hasOrderDetailList = oDetailList.Where(p => !((item.StartDate >= p.EndDate && item.EndDate > p.EndDate) || (item.StartDate < p.StartDate && item.EndDate <= p.StartDate))).ToList();
                if (hasOrderDetailList.Count >= maxCount)
                {
                    hasOrderID_List.AddRange(hasOrderDetailList.Select(p => p.OrderID).Distinct());
                }
            }
            if (hasOrderID_List.Count > 0)
            {
                hasOrderID_List = hasOrderID_List.Distinct().ToList();
                hasOrderIDs     = MyStringHelper.ListToStr(hasOrderID_List, "'", ",");
                int tempCount = 0;
                List <WXMallOrderInfo> tempList = bllMall.GetOrderList(0, 1, "", out tempCount, "预约成功", null, null, null,
                                                                       null, null, null, null, null, null, null, orderInfo.ArticleCategoryType, hasOrderIDs);
                if (tempCount >= maxCount)
                {
                    apiResp.msg  = "所选时间已有成功的预约";
                    apiResp.code = (int)APIErrCode.OperateFail;
                    bllMall.ContextResponse(context, apiResp);
                    return;
                }
            }
            //增值服务合并到主订单明细列表
            detailList.AddRange(detailAddedList);
            //合计计算
            orderInfo.Product_Fee = detailList.Sum(p => p.OrderPrice * p.TotalCount).Value;

            #region 积分计算

            decimal scoreExchangeAmount = 0;//积分抵扣的金额
            //积分计算
            if (orderRequestModel.use_score > 0 && orderInfo.Product_Fee > 0)
            {
                orderInfo.UseScore = orderRequestModel.use_score;
                if (CurrentUserInfo.TotalScore < orderRequestModel.use_score)
                {
                    apiResp.msg  = "积分不足";
                    apiResp.code = (int)APIErrCode.OperateFail;
                    bllMall.ContextResponse(context, apiResp);
                    return;
                }
                ScoreConfig scoreConfig = bllScore.GetScoreConfig();
                scoreExchangeAmount = Math.Round(orderRequestModel.use_score / (scoreConfig.ExchangeScore / scoreConfig.ExchangeAmount), 2);
            }
            //积分计算
            #endregion

            #region 使用账户余额
            if (orderRequestModel.use_amount > 0)
            {
                if (!bllMall.IsEnableAccountAmountPay())
                {
                    apiResp.msg  = "未开启余额支付";
                    apiResp.code = (int)APIErrCode.OperateFail;
                    bllMall.ContextResponse(context, apiResp);
                    return;
                }
                if (CurrentUserInfo.AccountAmount < orderRequestModel.use_amount)
                {
                    apiResp.msg  = "您的账户余额不足";
                    apiResp.code = (int)APIErrCode.OperateFail;
                    bllMall.ContextResponse(context, apiResp);
                    return;
                }
            }
            #endregion

            orderInfo.TotalAmount   = orderInfo.Product_Fee + orderInfo.Transport_Fee;
            orderInfo.TotalAmount  -= scoreExchangeAmount;                             //积分优惠金额
            orderInfo.TotalAmount  -= orderRequestModel.use_amount;                    //余额抵扣金额
            orderInfo.PayableAmount = orderInfo.TotalAmount - orderInfo.Transport_Fee; //应付金额
            if ((orderInfo.Product_Fee + orderInfo.Transport_Fee - scoreExchangeAmount) < orderInfo.TotalAmount)
            {
                apiResp.msg  = "积分兑换金额不能大于订单总金额,请减少积分兑换";
                apiResp.code = (int)APIErrCode.OperateFail;
                bllMall.ContextResponse(context, apiResp);
                return;
            }

            if (orderInfo.TotalAmount < 0)
            {
                orderInfo.TotalAmount = 0;
            }
            if (orderInfo.TotalAmount == 0 && orderInfo.UseScore == 0)
            {
                orderInfo.Status = "待审核";
            }
            else if (orderInfo.TotalAmount == 0 && (orderInfo.UseAmount > 0 || orderInfo.UseScore > 0))
            {
                orderInfo.PaymentStatus = 1;
                orderInfo.PayTime       = DateTime.Now;
                orderInfo.Status        = "预约成功";
            }

            #endregion

            //生成订单ID
            orderInfo.OrderID = bllMall.GetGUID(BLLJIMP.TransacType.AddMallOrder);
            BLLTransaction tran = new BLLTransaction();
            if (!this.bllMall.Add(orderInfo, tran))
            {
                tran.Rollback();
                apiResp.msg  = "提交失败";
                apiResp.code = (int)APIErrCode.OperateFail;
                bllMall.ContextResponse(context, apiResp);
                return;
            }
            foreach (var item in detailList)
            {
                item.OrderID = orderInfo.OrderID;
                if (!this.bllMall.Add(item, tran))
                {
                    tran.Rollback();
                    apiResp.msg  = "提交失败";
                    apiResp.code = (int)APIErrCode.OperateFail;
                    bllMall.ContextResponse(context, apiResp);
                    return;
                }
            }

            #region 积分抵扣
            //积分扣除
            if (orderRequestModel.use_score > 0)
            {
                CurrentUserInfo.TotalScore -= orderRequestModel.use_score;
                if (bllMall.Update(CurrentUserInfo,
                                   string.Format(" TotalScore-={0}", orderRequestModel.use_score),
                                   string.Format(" AutoID={0}", CurrentUserInfo.AutoID)
                                   , tran) < 0)
                {
                    tran.Rollback();
                    apiResp.msg  = "更新用户积分失败";
                    apiResp.code = (int)APIErrCode.OperateFail;
                    bllMall.ContextResponse(context, apiResp);
                    return;
                }

                //积分记录
                UserScoreDetailsInfo scoreRecord = new UserScoreDetailsInfo();
                scoreRecord.AddTime      = DateTime.Now;
                scoreRecord.Score        = -orderRequestModel.use_score;
                scoreRecord.TotalScore   = CurrentUserInfo.TotalScore;
                scoreRecord.ScoreType    = "OrderSubmit";
                scoreRecord.UserID       = CurrentUserInfo.UserID;
                scoreRecord.AddNote      = "预约-下单使用积分";
                scoreRecord.RelationID   = orderInfo.OrderID;
                scoreRecord.WebSiteOwner = CurrentUserInfo.WebsiteOwner;
                if (!bllMall.Add(scoreRecord))
                {
                    tran.Rollback();
                    apiResp.msg  = "插入积分记录失败";
                    apiResp.code = (int)APIErrCode.OperateFail;
                    bllMall.ContextResponse(context, apiResp);
                    return;
                }
            }
            //积分扣除
            #endregion

            #region 余额抵扣

            if (orderRequestModel.use_amount > 0 && bllMall.IsEnableAccountAmountPay())
            {
                CurrentUserInfo.AccountAmount -= orderRequestModel.use_amount;
                if (bllMall.Update(CurrentUserInfo, string.Format(" AccountAmount={0}", CurrentUserInfo.AccountAmount), string.Format(" AutoID={0}", CurrentUserInfo.AutoID)) < 0)
                {
                    tran.Rollback();
                    apiResp.msg  = "更新用户余额失败";
                    apiResp.code = (int)APIErrCode.OperateFail;
                    bllMall.ContextResponse(context, apiResp);
                    return;
                }


                UserScoreDetailsInfo scoreRecord = new UserScoreDetailsInfo();
                scoreRecord.AddTime      = DateTime.Now;
                scoreRecord.Score        = -(double)orderRequestModel.use_amount;
                scoreRecord.TotalScore   = (double)CurrentUserInfo.AccountAmount;
                scoreRecord.UserID       = CurrentUserInfo.UserID;
                scoreRecord.AddNote      = "账户余额变动-下单使用余额";
                scoreRecord.RelationID   = orderInfo.OrderID;
                scoreRecord.WebSiteOwner = bllMall.WebsiteOwner;
                scoreRecord.ScoreType    = "AccountAmount";
                if (!bllMall.Add(scoreRecord))
                {
                    tran.Rollback();
                    apiResp.code = (int)APIErrCode.OperateFail;
                    apiResp.msg  = "插入余额记录失败";
                    context.Response.Write(ZentCloud.Common.JSONHelper.ObjectToJson(apiResp));
                    return;
                }

                UserCreditAcountDetails record = new UserCreditAcountDetails();
                record.WebsiteOwner = bllMall.WebsiteOwner;
                record.Operator     = CurrentUserInfo.UserID;
                record.UserID       = CurrentUserInfo.UserID;
                record.CreditAcount = -orderRequestModel.use_amount;
                record.SysType      = "AccountAmount";
                record.AddTime      = DateTime.Now;
                record.AddNote      = "账户余额变动-" + orderRequestModel.use_amount;
                if (!bllMall.Add(record))
                {
                    tran.Rollback();

                    apiResp.msg  = "插入余额记录失败";
                    apiResp.code = (int)APIErrCode.OperateFail;
                    bllMall.ContextResponse(context, apiResp);
                    return;
                }
            }


            #endregion
            tran.Commit();//提交订单事务

            if (orderInfo.Status == "预约成功")
            {
                int tempCount = 0;
                if (string.IsNullOrWhiteSpace(hasOrderIDs))
                {
                    hasOrderIDs = "'0'";
                }
                List <WXMallOrderInfo> tempList = bllMall.GetOrderList(0, 1, "", out tempCount, "预约成功", null, null, null,
                                                                       null, null, null, null, null, null, null, orderInfo.ArticleCategoryType, hasOrderIDs);
                tempCount = tempCount + 1; //加上当前订单的数量
                if (tempCount >= maxCount)
                {
                    tempList = bllMall.GetColOrderListInStatus("'待付款','待审核'", hasOrderIDs, "OrderID,OrderUserID,UseScore", bllMall.WebsiteOwner);
                    if (tempList.Count > 0)
                    {
                        string stopOrderIds = MyStringHelper.ListToStr(tempList.Select(p => p.OrderID).ToList(), "'", ",");
                        tempList = tempList.Where(p => p.UseScore > 0).ToList();
                        foreach (var item in tempList)
                        {
                            UserInfo orderUserInfo = bllUser.GetUserInfo(orderInfo.OrderUserID, bllMall.WebsiteOwner);//下单用户信息
                            if (orderUserInfo == null)
                            {
                                continue;
                            }
                            orderUserInfo.TotalScore += item.UseScore;
                            if (bllMall.Update(orderUserInfo, string.Format(" TotalScore+={0}", item.UseScore),
                                               string.Format(" UserID='{0}'", item.OrderUserID)) > 0)
                            {
                                UserScoreDetailsInfo scoreRecord = new UserScoreDetailsInfo();
                                scoreRecord.AddTime      = DateTime.Now;
                                scoreRecord.Score        = item.UseScore;
                                scoreRecord.TotalScore   = orderUserInfo.TotalScore;
                                scoreRecord.ScoreType    = "OrderCancel";
                                scoreRecord.UserID       = item.OrderUserID;
                                scoreRecord.RelationID   = item.OrderID;
                                scoreRecord.AddNote      = "预约-订单失败返还积分";
                                scoreRecord.WebSiteOwner = item.WebsiteOwner;
                                bllMall.Add(scoreRecord);
                            }
                        }
                        bllMall.Update(new WXMallOrderInfo(),
                                       string.Format("Status='{0}'", "预约失败"),
                                       string.Format("OrderID In ({0}) and WebsiteOwner='{1}'", stopOrderIds, bllMall.WebsiteOwner));
                    }
                }
            }


            //预约通知
            bllWeiXin.SendTemplateMessageNotifyComm(CurrentUserInfo, orderInfo.Status, string.Format("预约:{2}\\n订单号:{0}\\n订单金额:{1}元", orderInfo.OrderID, orderInfo.TotalAmount, productInfo.PName));

            apiResp.result = new
            {
                order_id = orderInfo.OrderID
            };
            apiResp.msg    = "提交完成";
            apiResp.code   = (int)APIErrCode.IsSuccess;
            apiResp.status = true;
            bllMall.ContextResponse(context, apiResp);
        }
Esempio n. 30
0
        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="userID"></param>
        /// <param name="product"></param>
        /// <param name="pdtAttrVals"></param>
        /// <param name="pdtExtAttrVals"></param>
        /// <param name="skus"></param>
        /// <param name="specCustoms"></param>
        /// <param name="imglist"></param>
        /// <param name="ratios"></param>
        /// <param name="mainimg"></param>
        /// <returns></returns>
        public StateCode Save(long userID, Product product, List <PdtAttrVal> pdtAttrVals, List <PdtExtAttrVal> pdtExtAttrVals, List <ProductSku> skus, List <SpecCustom> specCustoms,
                              List <Img> imglist, string mainimg)
        {
            product.catg_path     = ServiceIoc.Get <ProductCatgService>().GetParentPath(product.catg_id);
            product.catg_pathname = ServiceIoc.Get <ProductCatgService>().GetParentPathName(product.catg_id);

            product.gcatg_path     = ServiceIoc.Get <GuideProductCatgService>().GetParentPath(product.gcatg_id);
            product.gcatg_pathname = ServiceIoc.Get <GuideProductCatgService>().GetParentPathName(product.gcatg_id);

            //分类路径
            using (ISession s = SessionFactory.Instance.CreateSession())
            {
                try
                {
                    s.StartTransaction();

                    //是否是最后分类
                    if (product.gcatg_id != 0 && s.Exist <GuideProductCatg>("where parent_id = @0 ", product.gcatg_id) > 0)
                    {
                        return(StateCode.State_201);
                    }

                    #region 商品基本信息
                    if (product.id != 0)
                    {
                        //product.is_shelves = new_product.is_shelves;
                        product.updated_user_id = userID;
                        product.updated_date    = DateTime.Now;
                        s.Update <Product>(product);
                    }
                    else
                    {
                        product.created_user_id = userID;
                        product.created_date    = DateTime.Now;
                        s.Insert <Product>(product);
                    }
                    #endregion

                    #region 处理商品图片

                    if (imglist != null && imglist.Count > 0)
                    {
                        //去除重复图片
                        s.ExcuteUpdate("update tb_img set biz_id = 0 where biz_type = @0 and biz_id = @1 and is_webimg = @2", ImgType.Product_Cover, product.id, false);
                        foreach (Img image in imglist)
                        {
                            if (!string.IsNullOrEmpty(image.file_name))
                            {
                                Img img = s.Get <Img>("where file_name = @0 and biz_type = @1 ", image.file_name, ImgType.Product_Cover);
                                if (img != null)
                                {
                                    //显示顺序
                                    img.order_index = image.order_index;
                                    //业务ID
                                    img.biz_id = product.id;
                                    s.Update <Img>(img);
                                }
                            }
                        }

                        //重置主图
                        s.ExcuteUpdate("update tb_img set is_main = @0 where biz_id = @1 and biz_type = @2 ", false, product.id, ImgType.Product_Cover);

                        //如果没设置主图,则设置第一个为默认主图
                        if (string.IsNullOrEmpty(mainimg))
                        {
                            mainimg = imglist[0].file_name;
                        }

                        //filename情况
                        if (mainimg.Length < 30)
                        {
                            s.ExcuteUpdate("update tb_img set is_main = @0 where id = @1 and biz_type = @2", true, long.Parse(mainimg), ImgType.Product_Cover);
                        }
                        else
                        {
                            s.ExcuteUpdate("update tb_img set is_main = @0 where file_name = @1 and biz_type = @2 ", true, mainimg, ImgType.Product_Cover);
                        }
                    }

                    #endregion

                    #region 商品基本属性值
                    if (pdtAttrVals == null)
                    {
                        //删除商品基本属性值
                        s.ExcuteUpdate("delete tb_pdt_attrval where product_id = @0 ", product.id);
                    }
                    else
                    {
                        List <PdtAttrVal> tmp_baseAttrValues = new List <PdtAttrVal>();

                        //数据库原有数据
                        List <PdtAttrVal> old_baseAttrValues = s.List <PdtAttrVal>("where product_id = @0", product.id);

                        foreach (PdtAttrVal ptbav in pdtAttrVals)
                        {
                            ptbav.product_id = product.id;
                            int exist_AttrName = s.Exist <AttrName>("where id = @0", ptbav.attrname_id);

                            //是否存商品类型基础扩展属性名
                            if (exist_AttrName > 0)
                            {
                                if (ptbav.id != 0)
                                {
                                    ptbav.val = ptbav.val ?? "";
                                    s.Update <PdtAttrVal>(ptbav);
                                    tmp_baseAttrValues.Add(ptbav);
                                }
                                else
                                {
                                    //确保 pdt_attributename_id 数据唯一
                                    int exist_pdtval = s.Exist <PdtAttrVal>("where product_id = @0 and attrname_id = @1 ", product.id, ptbav.attrname_id);
                                    if (exist_pdtval == 0)
                                    {
                                        s.Insert <PdtAttrVal>(ptbav);
                                    }
                                }
                            }
                        }

                        //筛选出删除的基础属性值
                        foreach (PdtAttrVal p in old_baseAttrValues)
                        {
                            bool exists = true;
                            foreach (PdtAttrVal o_p in tmp_baseAttrValues)
                            {
                                if (p.id == o_p.id)
                                {
                                    exists = false;
                                    break;
                                }
                            }
                            if (exists)
                            {
                                //删除商品基本属性值
                                s.ExcuteUpdate("delete tb_pdt_attrval where id = @0 ", p.id);
                            }
                        }
                    }
                    #endregion

                    #region 商品扩展属性值

                    //清空扩展属性值
                    s.ExcuteUpdate("delete tb_pdt_extattrval where product_id = @0 ", product.id);
                    if (pdtExtAttrVals != null)
                    {
                        foreach (PdtExtAttrVal pta in pdtExtAttrVals)
                        {
                            pta.product_id = product.id;
                            s.Insert <PdtExtAttrVal>(pta);
                        }
                    }

                    #endregion

                    #region 商品自定义规格信息

                    List <SpecCustom> old_ssc = s.List <SpecCustom>("where product_id = @0 ", product.id);
                    s.ExcuteUpdate("delete tb_pdt_spec_custom where product_id = @0 ", product.id);

                    if (specCustoms != null)
                    {
                        foreach (SpecCustom ssc in specCustoms)
                        {
                            ssc.custom_value = ssc.custom_value == null ? "" : ssc.custom_value;
                            ssc.product_id   = product.id;
                            s.Insert <SpecCustom>(ssc);
                        }
                    }

                    #endregion

                    #region 商品SKU

                    //当前商品规格详细
                    List <ProductSku> oldSkus = s.List <ProductSku>("where product_id = @0 ", product.id);

                    //开启规格
                    if (product.is_open_spec)
                    {
                        //当前合法的规格详细信息
                        List <ProductSku> currentSkus = new List <ProductSku>();

                        //当前商品规格名称集合
                        List <SpecName> specNames = s.List <SpecName>("where product_type_id = @0", product.product_type_id);

                        //当前商品规格名称集合
                        List <SpecValue> specValues = s.List <SpecValue>("where product_type_id = @0", product.product_type_id);

                        //商品规格信息
                        if (skus == null || skus.Count == 0)
                        {
                            throw new Exception("商品规格信息异常");
                        }

                        //遍历sku集合
                        foreach (ProductSku s_sku in skus)
                        {
                            //标示是否是合法sku数据
                            bool ispass = true;

                            //检测规格数据是否存在
                            string[] arr = StringHelper.StringToArray(s_sku.specset);
                            foreach (string i in arr)
                            {
                                int specname_id  = 0;
                                int specvalue_id = 0;
                                if (i.IndexOf("_") != -1)
                                {
                                    int.TryParse(i.Split('_')[0], out specname_id);
                                    int.TryParse(i.Split('_')[1], out specvalue_id);
                                    //验证规格名称和规格值
                                    if (!specNames.Exists(sn => sn.id == specname_id) || !specValues.Exists(sv => sv.id == specvalue_id))
                                    {
                                        ispass = false;
                                        break;
                                    }
                                }
                            }

                            if (ispass)
                            {
                                //是否在原有的集合存在
                                ProductSku ssku = oldSkus.Where(osku => osku.specset.Equals(s_sku.specset)).SingleOrDefault();
                                if (ssku != null)
                                {
                                    s_sku.id         = ssku.id;
                                    s_sku.product_id = product.id;
                                    s.Update <ProductSku>(s_sku);
                                    currentSkus.Add(s_sku);
                                }
                                else
                                {
                                    s_sku.product_id = product.id;
                                    s.Insert <ProductSku>(s_sku);
                                }

                                //商品规格集合数据
                                foreach (string i in arr)
                                {
                                    int specname_id  = 0;
                                    int specvalue_id = 0;
                                    if (i.IndexOf("_") != -1)
                                    {
                                        int.TryParse(i.Split('_')[0], out specname_id);
                                        int.TryParse(i.Split('_')[1], out specvalue_id);

                                        SpecSet specset = new SpecSet();
                                        specset.specname_id  = specname_id;
                                        specset.specvalue_id = specvalue_id;
                                        specset.product_id   = product.id;
                                        specset.pdt_sku_id   = s_sku.id;
                                        s.Insert <SpecSet>(specset);
                                    }
                                }
                            }
                        }

                        //筛选出删除的商品规格
                        foreach (ProductSku o_sku in oldSkus)
                        {
                            bool exists = true;
                            foreach (ProductSku cpsd in currentSkus)
                            {
                                if (cpsd.id == o_sku.id)
                                {
                                    exists = false;
                                    break;
                                }
                            }
                            if (exists)
                            {
                                //删除sku
                                s.ExcuteUpdate("delete tb_pdt_sku where id = @0 and product_id = @1", o_sku.id, product.id);
                                //删除商品规格集合
                                s.ExcuteUpdate("delete tb_pdt_specset where pdt_sku_id = @0 and product_id = @1", o_sku.id, product.id);
                            }
                        }
                    }
                    else
                    {
                        //SKUs
                        if (skus == null || skus.Count != 1)
                        {
                            throw new Exception("商品扩展属性数据异常");
                        }

                        //判断开启规格之前的信息
                        if (oldSkus.Count > 1)
                        {
                            foreach (ProductSku sku in oldSkus)
                            {
                                //删除商品 自定义规格值
                                s.ExcuteUpdate("delete tb_pdt_specset where pdt_sku_id = @0 and product_id = @1 ", sku.id, product.id);
                            }
                            //删除商品 SKU 集合
                            s.ExcuteUpdate("delete tb_pdt_sku where and product_id = @0", product.id);
                        }

                        ProductSku c_sku = s.Get <ProductSku>(" where product_id = @0", product.id);
                        if (c_sku != null)
                        {
                            c_sku.specset = "";
                            //成本价
                            c_sku.cost_price = skus[0].cost_price;
                            //供货价
                            c_sku.sale_price = skus[0].sale_price;
                            //市场价
                            c_sku.market_price = skus[0].market_price;
                            //商品货号
                            c_sku.serial_no = product.no;
                            //库存
                            c_sku.stock = skus[0].stock;
                            //重量
                            c_sku.weight = skus[0].weight;
                            //预警库存
                            c_sku.warning_stock = skus[0].warning_stock;

                            s.Update <ProductSku>(c_sku);
                        }
                        else
                        {
                            c_sku         = new ProductSku();
                            c_sku.specset = "";
                            //商品ID
                            c_sku.product_id = product.id;
                            //供货价
                            c_sku.cost_price = skus[0].cost_price;
                            //市场价
                            c_sku.market_price = skus[0].market_price;
                            //商品货号
                            c_sku.serial_no = product.no;
                            //库存
                            c_sku.stock = skus[0].stock;
                            //重量
                            c_sku.weight = skus[0].weight;
                            //预警库存
                            c_sku.warning_stock = skus[0].warning_stock;

                            s.Insert <ProductSku>(c_sku);
                        }
                    }

                    #endregion


                    s.Commit();
                    return(StateCode.State_200);
                }
                catch (Exception ex)
                {
                    s.RollBack();
                    return(StateCode.State_500);
                }
            }
        }