From 655f71abfdf49fade17afb1906186b4f88afa41d Mon Sep 17 00:00:00 2001 From: Jack <46790855@qq.com> Date: Sat, 16 Aug 2025 17:36:06 +0800 Subject: [PATCH] =?UTF-8?q?=E8=B4=AD=E7=89=A9=E8=BD=A6=EF=BC=8C=E7=9B=B4?= =?UTF-8?q?=E6=8E=A5=E4=B8=8B=E5=8D=95=20=E6=89=93=E5=8C=85=E8=B4=B9=20fix?= =?UTF-8?q?=20bug?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../mall/account/RedisKeyManage/RedisKey.java | 6 - .../impl/AccountUserBindGeTuiServiceImpl.java | 42 +- .../service/impl/SFExpressApiServiceImpl.java | 178 +- .../impl/ShopStoreBaseServiceImpl.java | 15 +- .../user/service/ShopUserCartService.java | 4 +- .../service/impl/ShopUserCartServiceImpl.java | 1659 +++++++++-------- 6 files changed, 1034 insertions(+), 870 deletions(-) delete mode 100644 mall-account/src/main/java/com/suisung/mall/account/RedisKeyManage/RedisKey.java diff --git a/mall-account/src/main/java/com/suisung/mall/account/RedisKeyManage/RedisKey.java b/mall-account/src/main/java/com/suisung/mall/account/RedisKeyManage/RedisKey.java deleted file mode 100644 index 6edf2b41..00000000 --- a/mall-account/src/main/java/com/suisung/mall/account/RedisKeyManage/RedisKey.java +++ /dev/null @@ -1,6 +0,0 @@ -package com.suisung.mall.account.RedisKeyManage; - -public class RedisKey { - - public static final String SINGLEPUSHTOKE="singlePush:toke"; -} diff --git a/mall-account/src/main/java/com/suisung/mall/account/service/impl/AccountUserBindGeTuiServiceImpl.java b/mall-account/src/main/java/com/suisung/mall/account/service/impl/AccountUserBindGeTuiServiceImpl.java index 9a43e778..e6d39b68 100644 --- a/mall-account/src/main/java/com/suisung/mall/account/service/impl/AccountUserBindGeTuiServiceImpl.java +++ b/mall-account/src/main/java/com/suisung/mall/account/service/impl/AccountUserBindGeTuiServiceImpl.java @@ -1,5 +1,7 @@ package com.suisung.mall.account.service.impl; +import cn.hutool.core.date.DateField; +import cn.hutool.core.date.DateUtil; import cn.hutool.core.util.ObjectUtil; import cn.hutool.core.util.StrUtil; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; @@ -51,16 +53,22 @@ public class AccountUserBindGeTuiServiceImpl extends BaseServiceImpl().eq("user_id", userId).eq("status", CommonConstant.Enable)); } + + /** + * 清理一年没有登录的账号推送绑定关系列表 + * 异步执行以避免阻塞主线程 + */ + private void clearAccountUserBindGeTui() { + // 使用新线程异步执行清理任务 + new Thread(() -> { + try { + // 计算一年前的时间 + Date oneYearAgo = DateUtil.offset(new Date(), DateField.YEAR, -1); + + // 删除一年未更新的记录 + boolean result = remove(new QueryWrapper().lt("updated_at", oneYearAgo)); + + if (result) { + log.info("成功清理 {} 条一年未登录的个推绑定记录", result); + } + } catch (Exception e) { + // 捕获并记录异常,避免影响主线程 + log.error("异步清理一年未登录的个推绑定记录时发生异常: {}", e.getMessage(), e); + } + }, "ClearGeTuiBindThread").start(); + } } diff --git a/mall-shop/src/main/java/com/suisung/mall/shop/sfexpress/service/impl/SFExpressApiServiceImpl.java b/mall-shop/src/main/java/com/suisung/mall/shop/sfexpress/service/impl/SFExpressApiServiceImpl.java index e0906ce8..929c4330 100644 --- a/mall-shop/src/main/java/com/suisung/mall/shop/sfexpress/service/impl/SFExpressApiServiceImpl.java +++ b/mall-shop/src/main/java/com/suisung/mall/shop/sfexpress/service/impl/SFExpressApiServiceImpl.java @@ -52,9 +52,10 @@ import java.util.Map; @Service public class SFExpressApiServiceImpl implements SFExpressApiService { - - private final static String sfExpressApiDomain = "https://openic.sf-express.com/open/api/external/"; private static final Logger logger = LoggerFactory.getLogger(SFExpressApiServiceImpl.class); + + private static final String sfExpressApiDomain = "https://openic.sf-express.com/open/api/external/"; + @Value("${sf-express.appid}") private String appId; @Value("${sf-express.appkey}") @@ -112,93 +113,100 @@ public class SFExpressApiServiceImpl implements SFExpressApiService { String longitude, String latitude) { logger.info("开始创建顺丰同城店铺, storeId: {}", storeId); - // 1. 验证必要参数 - if (CheckUtil.isEmpty(storeId) || StringUtils.isAnyBlank(shopName, shopAddress, contactName, contactPhone)) { - return Pair.of(false, "顺丰同城店铺,缺少必要参数!"); - } - - // 2. 获取或初始化商家配送信息 - ShopStoreSameCityTransportBase transportBase = shopStoreSameCityTransportBaseService - .getShopStoreSameCityTransportBaseById(Long.valueOf(storeId)); - - if (transportBase == null) { - // 如果没有商家配送运费设置,则初始化 - Pair initResult = shopStoreSameCityTransportBaseService.initDefaultSameCityTransport(storeId); - if (!initResult.getFirst()) { - logger.error("初始化商家配送运费设置失败!"); - return initResult; + try { + // 1. 验证必要参数 + if (CheckUtil.isEmpty(storeId) || StringUtils.isAnyBlank(shopName, shopAddress, contactName, contactPhone)) { + return Pair.of(false, "创建顺丰店铺,缺少必要参数!"); } - transportBase = shopStoreSameCityTransportBaseService.getShopStoreSameCityTransportBaseById(Long.valueOf(storeId)); - } - // 3. 如果已存在顺丰店铺ID,验证其有效性 - if (CheckUtil.isNotEmpty(transportBase.getShop_id())) { - ThirdApiRes shopInfo = getSfShopInfo(transportBase.getShop_id()); - if (shopInfo != null && shopInfo.getError_code().equals(0)) { - logger.info("已成功创建顺丰同城店铺!"); - return Pair.of(true, transportBase.getShop_id()); + // 2. 获取或初始化商家配送信息 + ShopStoreSameCityTransportBase transportBase = shopStoreSameCityTransportBaseService + .getShopStoreSameCityTransportBaseById(Long.valueOf(storeId)); + + if (transportBase == null) { + // 如果没有商家配送运费设置,则初始化 + Pair initResult = shopStoreSameCityTransportBaseService.initDefaultSameCityTransport(storeId); + if (!initResult.getFirst()) { + logger.error("初始化商家配送运费设置失败!"); + return initResult; + } + transportBase = shopStoreSameCityTransportBaseService.getShopStoreSameCityTransportBaseById(Long.valueOf(storeId)); } + + // 3. 如果已存在顺丰店铺ID,验证其有效性 + if (CheckUtil.isNotEmpty(transportBase.getShop_id())) { + logger.debug("如果存在店铺Id,从顺丰同城平台查询店铺ID,开始验证其有效性!"); + ThirdApiRes shopInfo = getSfShopInfo(transportBase.getShop_id()); + if (shopInfo != null && shopInfo.getError_code().equals(0)) { + logger.info("已成功创建顺丰同城店铺!"); + return Pair.of(true, transportBase.getShop_id()); + } + } + + // 4. 构建请求参数 + Map params = buildCommonParams(); + params.put("supplier_id", supplierId); // 店铺所属商家id + params.put("out_shop_id", storeId); // 外部店铺ID + params.put("shop_name", shopName); // 店铺名称 + params.put("city_name", cityName); // 城市名称 + + // RMK 1:快餐 2:药品 3:百货 4:脏衣服收 5:干净衣服派 6:生鲜 8:高端饮品 9:现场勘验 10:快递 12:文件 13:蛋糕 14:鲜花 15:数码 16:服装 17: + //汽配 18:珠宝 20:披萨 21:中餐 22:水产 27:专人直送 32:中端饮品 33:便利店 34:面包糕点 35:火锅 36:证照 40:烧烤小龙虾 41:外部落地配 47:烟酒 + //行 48:成人用品 99:其他 + // 经营类型: 快餐,百货,生鲜,高端饮品,蛋糕,鲜花,数码,服装,披萨,水产,中端饮品,便利店,面包糕点,烟酒,其他 + params.put("shop_product_types", "1,3,6,8,13,14,15,16,20,22,32,33,34,47,99"); + params.put("shop_type", 1); // 店铺类型: 1-普通型 2-平台型 + params.put("shop_address", shopAddress); // 店铺地址 + params.put("longitude", longitude); // 经度 + params.put("latitude", latitude); // 纬度 + params.put("shop_contact_name", contactName); // 联系人姓名 + params.put("shop_contact_phone", contactPhone); // 联系电话 + + // 5. 发送请求到顺丰接口 + String paramJSON = JsonUtil.toJSONString(params); + String sendUrl = buildUrl("createShop", paramJSON); + String responseStr = HttpUtil.post(sendUrl, paramJSON); + + if (StrUtil.isBlank(responseStr)) { + logger.error("创建顺丰店铺异常,无返回值!"); + return Pair.of(false, "创建顺丰店铺异常,无返回值!"); + } + + ThirdApiRes apiRes = JSONUtil.toBean(responseStr, ThirdApiRes.class); + if (apiRes == null) { + logger.error("创建顺丰店铺异常,返回值有误!!"); + return Pair.of(false, "创建顺丰店铺异常,返回值有误!"); + } + + // 6. 检查接口调用结果 + if (!apiRes.getError_code().equals(0) || apiRes.getResult() == null) { + String errMsg = apiRes.getError_code().equals(0) ? "创建顺丰店铺失败!" : "创建顺丰店铺失败: " + apiRes.getError_msg(); + logger.error("创建顺丰店铺失败: {}", errMsg); + return Pair.of(false, errMsg); + } + + // 7. 提取顺丰店铺ID并更新数据库 + JSONObject result = (JSONObject) apiRes.getResult(); + String sfShopId = result.getStr("shop_id"); + transportBase.setShop_id(sfShopId); + transportBase.setShop_state(CommonConstant.Enable);// 顺丰同城快递商品特惠 + transportBase.setDelivery_brand(CommonConstant.DELIVERY_BRAND_SF); + + Pair updateResult = shopStoreSameCityTransportBaseService + .saveOrUpdateShopStoreSameCityTransportBase(transportBase); + + if (updateResult.getFirst() <= 0) { + logger.error("更新店铺信息失败"); + return Pair.of(false, "更新店铺信息失败"); + } + + logger.info("成功创建顺丰店铺,店铺ID: {}", sfShopId); + return Pair.of(true, sfShopId); + + } catch (Exception e) { + logger.error("创建顺丰同城店铺时发生异常: ", e); + return Pair.of(false, "创建顺丰同城店铺时发生异常: " + e.getMessage()); } - - // 4. 构建请求参数 - Map params = buildCommonParams(); - params.put("supplier_id", supplierId); // 店铺所属商家id - params.put("out_shop_id", storeId); // 外部店铺ID - params.put("shop_name", shopName); // 店铺名称 - params.put("city_name", cityName); // 城市名称 - - // RMK 1:快餐 2:药品 3:百货 4:脏衣服收 5:干净衣服派 6:生鲜 8:高端饮品 9:现场勘验 10:快递 12:文件 13:蛋糕 14:鲜花 15:数码 16:服装 17: - //汽配 18:珠宝 20:披萨 21:中餐 22:水产 27:专人直送 32:中端饮品 33:便利店 34:面包糕点 35:火锅 36:证照 40:烧烤小龙虾 41:外部落地配 47:烟酒 - //行 48:成人用品 99:其他 - // 经营类型: 快餐,百货,生鲜,高端饮品,蛋糕,鲜花,数码,服装,披萨,水产,中端饮品,便利店,面包糕点,烟酒,其他 - params.put("shop_product_types", "1,3,6,8,13,14,15,16,20,22,32,33,34,47,99"); - params.put("shop_type", 1); // 店铺类型: 1-普通型 2-平台型 - params.put("shop_address", shopAddress); // 店铺地址 - params.put("longitude", longitude); // 经度 - params.put("latitude", latitude); // 纬度 - params.put("shop_contact_name", contactName); // 联系人姓名 - params.put("shop_contact_phone", contactPhone); // 联系电话 - - // 5. 发送请求到顺丰接口 - String paramJSON = JsonUtil.toJSONString(params); - String sendUrl = buildUrl("createShop", paramJSON); - String responseStr = HttpUtil.post(sendUrl, paramJSON); - - if (StrUtil.isBlank(responseStr)) { - logger.error("创建顺丰店铺异常,无返回值!"); - return Pair.of(false, "创建顺丰店铺异常,无返回值!"); - } - - ThirdApiRes apiRes = JSONUtil.toBean(responseStr, ThirdApiRes.class); - if (apiRes == null) { - logger.error("创建顺丰店铺异常,返回值有误!!"); - return Pair.of(false, "创建顺丰店铺异常,返回值有误!"); - } - - // 6. 检查接口调用结果 - if (!apiRes.getError_code().equals(0) || apiRes.getResult() == null) { - String errMsg = apiRes.getError_code().equals(0) ? "创建顺丰店铺失败!" : "创建顺丰店铺失败: " + apiRes.getError_msg(); - logger.error("创建顺丰店铺失败: {}", errMsg); - return Pair.of(false, errMsg); - } - - // 7. 提取顺丰店铺ID并更新数据库 - JSONObject result = (JSONObject) apiRes.getResult(); - String sfShopId = result.getStr("shop_id"); - transportBase.setShop_id(sfShopId); - transportBase.setShop_state(CommonConstant.Enable);// 顺丰同城快递商品特惠 - transportBase.setDelivery_brand(CommonConstant.DELIVERY_BRAND_SF); - - Pair updateResult = shopStoreSameCityTransportBaseService - .saveOrUpdateShopStoreSameCityTransportBase(transportBase); - - if (updateResult.getFirst() <= 0) { - logger.error("更新店铺信息失败"); - return Pair.of(false, "更新店铺信息失败"); - } - - logger.info("成功创建顺丰店铺,店铺ID: {}", sfShopId); - return Pair.of(true, sfShopId); } /** diff --git a/mall-shop/src/main/java/com/suisung/mall/shop/store/service/impl/ShopStoreBaseServiceImpl.java b/mall-shop/src/main/java/com/suisung/mall/shop/store/service/impl/ShopStoreBaseServiceImpl.java index 58ce5055..564be207 100644 --- a/mall-shop/src/main/java/com/suisung/mall/shop/store/service/impl/ShopStoreBaseServiceImpl.java +++ b/mall-shop/src/main/java/com/suisung/mall/shop/store/service/impl/ShopStoreBaseServiceImpl.java @@ -62,6 +62,7 @@ import com.suisung.mall.shop.plantform.service.ShopPlantformSubsiteService; import com.suisung.mall.shop.product.mapper.ShopProductIndexMapper; import com.suisung.mall.shop.product.service.ShopProductBaseService; import com.suisung.mall.shop.product.service.ShopProductIndexService; +import com.suisung.mall.shop.sfexpress.service.SFExpressApiService; import com.suisung.mall.shop.store.mapper.ShopStoreBaseMapper; import com.suisung.mall.shop.store.service.*; import com.suisung.mall.shop.user.service.ShopUserFavoritesStoreService; @@ -107,6 +108,7 @@ public class ShopStoreBaseServiceImpl extends BaseServiceImpl StoreFilterOptData; + @Autowired private ShopPlantformSubsiteService shopPlantformSubsiteService; @Autowired @@ -184,6 +186,10 @@ public class ShopStoreBaseServiceImpl extends BaseServiceImpl= 2 ? areaNames[1] : shopStoreBase.getStore_area().replace("/", ""); + sfExpressApiService.createSfExpressShop(storeId, shopStoreBase.getStore_name(), cityName, shopStoreBase.getStore_address(), shopMchEntry.getContact_name(), contact_mobile, shopStoreBase.getStore_longitude(), shopStoreBase.getStore_longitude()); return Pair.of(storeId, "新增成功"); } catch (Exception e) { diff --git a/mall-shop/src/main/java/com/suisung/mall/shop/user/service/ShopUserCartService.java b/mall-shop/src/main/java/com/suisung/mall/shop/user/service/ShopUserCartService.java index 1cc2febd..ca7a7e7f 100644 --- a/mall-shop/src/main/java/com/suisung/mall/shop/user/service/ShopUserCartService.java +++ b/mall-shop/src/main/java/com/suisung/mall/shop/user/service/ShopUserCartService.java @@ -126,9 +126,9 @@ public interface ShopUserCartService extends IBaseService { * 5、根据选择,计算订单信息,将上一步权限验证并将结果计入数据中, 店铺商品总价 = 加价购商品总价 + 购物车非活动商品总价(按照限时折扣和团购价计算) * 6、 * - * @param cart_rows 购物车数据 + * @param cartItems 购物车数据 */ - Map formatCartRows(List cart_rows, Map activity_rows, ProductVo productVo, FixOrderVo fixOrderVo); + Map formatCartRows(List cartItems, Map activityData, ProductVo productVo, FixOrderVo fixOrderVo); /** * 尝试去操作:配送区域判断及运费, 并修正最终数据 diff --git a/mall-shop/src/main/java/com/suisung/mall/shop/user/service/impl/ShopUserCartServiceImpl.java b/mall-shop/src/main/java/com/suisung/mall/shop/user/service/impl/ShopUserCartServiceImpl.java index d447fa9e..60abdc46 100644 --- a/mall-shop/src/main/java/com/suisung/mall/shop/user/service/impl/ShopUserCartServiceImpl.java +++ b/mall-shop/src/main/java/com/suisung/mall/shop/user/service/impl/ShopUserCartServiceImpl.java @@ -14,6 +14,7 @@ import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.suisung.mall.common.api.CommonResult; import com.suisung.mall.common.api.ResultCode; import com.suisung.mall.common.api.StateCode; +import com.suisung.mall.common.constant.CommonConstant; import com.suisung.mall.common.domain.UserDto; import com.suisung.mall.common.exception.ApiException; import com.suisung.mall.common.exception.ApiUserException; @@ -533,208 +534,219 @@ public class ShopUserCartServiceImpl extends BaseServiceImpl cartQueryWrapper = new QueryWrapper<>(); - cartQueryWrapper.eq("user_id", user_id) - //.eq("chain_id", chain_id) TODO update 2024-12-23 蓝驰要求 - .eq("cart_select", 1); + cartQueryWrapper.eq("user_id", currentUserId) + .eq("cart_select", CommonConstant.Enable); + //.eq("chain_id", chain_id) TODO update 2024-12-23 蓝驰要求 - Integer checked_store = getParameter("checked_store", Integer.class); - if (checked_store != null && checked_store != 0) { - cartQueryWrapper.eq("store_id", checked_store); + Integer checkedStoreId = getParameter("checked_store", Integer.class); + if (checkedStoreId != null && checkedStoreId != 0) { + cartQueryWrapper.eq("store_id", checkedStoreId); } - // 从购物车里获取商品信息, 加入购物车时已经计算了运费、优惠、打包费等信息 - data = getLists(cartQueryWrapper, 1, 500); + // 从购物车里获取商品信息, 加入购物车时已经计算了优惠金额等信息 + checkoutResult = getLists(cartQueryWrapper); + } else { // 直接点击购买,数据检测 - if (StrUtil.isNotBlank(cart_id)) { - List item_info_row = StrUtil.split(cart_id, ","); + if (StrUtil.isNotBlank(cartId)) { + List itemInfoList = StrUtil.split(cartId, ","); - List cart_rows = new ArrayList(); - for (String item : item_info_row) { + // 购物车行项目列表 + List directPurchaseItems = new ArrayList(); + for (String itemInfo : itemInfoList) { - Map cart_row = new HashMap(); - cart_rows.add(cart_row); + Map cartItem = new HashMap(); + directPurchaseItems.add(cartItem); - int[] item_row = StrUtil.splitToInt(item, "|"); - if (item_row[1] <= 0) { + int[] itemData = StrUtil.splitToInt(itemInfo, "|"); + if (itemData[1] <= 0) { throw new ApiException(I18nUtil._("至少选购1个商品!")); } // 购买的商品记录 - ShopProductItem product_item_row = shopProductItemService.get(item_row[0]); - Long _product_id = product_item_row.getProduct_id(); - ShopProductBase product_row = shopProductBaseService.get(_product_id); - if (product_id == null) product_id = _product_id; + ShopProductItem productItem = shopProductItemService.get(itemData[0]); + Long productId = productItem.getProduct_id(); + ShopProductBase productBase = shopProductBaseService.get(productId); + if (mainProductId == null) mainProductId = productId; // 直接判断库存 - /* - //如果是礼包活动,直接判断礼包的库存 - if(!activity_id.equals(0)) + /* + //如果是礼包活动,直接判断礼包的库存 + if(!activity_id.equals(0)) + { + Map activity_rule = (Map) activity_rows.get("activity_rule"); + if (activity_rule.get("giftbag_quantity") < quantity) { - Map activity_rule = (Map) activity_rows.get("activity_rule"); - if (activity_rule.get("giftbag_quantity") < quantity) - { - throw new Exception(__("该礼包库存不足!")); - } + throw new Exception(__("该礼包库存不足!")); } - */ + } + */ - Integer item_quantity = product_item_row.getItem_quantity(); + Integer itemQuantity = productItem.getItem_quantity(); // 商品冻结库存 - Integer item_quantity_frozen = product_item_row.getItem_quantity_frozen(); - if (item_quantity < item_row[1] && CheckUtil.isEmpty(if_virtual)) { + Integer frozenItemQuantity = productItem.getItem_quantity_frozen(); + if (itemQuantity < itemData[1] && CheckUtil.isEmpty(isVirtualProduct)) { throw new ApiException(I18nUtil._("该商品库存不足!")); } - Integer product_inventory_warning = accountBaseConfigService.getConfig("product_inventory_warning", 5); + Integer lowInventoryWarningThreshold = accountBaseConfigService.getConfig("product_inventory_warning", 5); // 商品库存数量小于5个,通知卖家 - if ((item_quantity - item_quantity_frozen) < product_inventory_warning) { + if ((itemQuantity - frozenItemQuantity) < lowInventoryWarningThreshold) { // todo 发送消息 - String message_id = "commodity-inventory-notice"; - Map args = new HashMap(); - args.put("store_name", product_row.getStore_name()); - args.put("chain_name", product_row.getStore_name()); - args.put("product_id", product_item_row.getProduct_id()); - args.put("item_id", product_item_row.getItem_id()); - args.put("product_item_name", product_item_row.getItem_name() != null ? product_item_row.getItem_name().split(",") : product_row.getProduct_name()); - args.put("item_quantity", product_item_row.getItem_quantity()); + String inventoryWarningMessageId = "commodity-inventory-notice"; + Map inventoryWarningArgs = new HashMap(); + inventoryWarningArgs.put("store_name", productBase.getStore_name()); + inventoryWarningArgs.put("chain_name", productBase.getStore_name()); + inventoryWarningArgs.put("product_id", productItem.getProduct_id()); + inventoryWarningArgs.put("item_id", productItem.getItem_id()); + inventoryWarningArgs.put("product_item_name", productItem.getItem_name() != null ? productItem.getItem_name().split(",") : productBase.getProduct_name()); + inventoryWarningArgs.put("item_quantity", productItem.getItem_quantity()); - messageService.sendNoticeMsg(0, product_row.getStore_id(), message_id, args); - /* - message_id = "commodity-inventory-notice"; - args = array( - "store_name" => product_row["store_name"], - "chain_name" => product_row["store_name"], - "product_id" => product_item_row["product_id"], - "item_id" => product_item_row["item_id"], - "product_item_name" => product_item_row["item_name"] ? implode(",", product_item_row["item_name"]) : product_row["product_name"], - "item_quantity" => product_item_row["item_quantity"], - ); + messageService.sendNoticeMsg(0, productBase.getStore_id(), inventoryWarningMessageId, inventoryWarningArgs); + /* + message_id = "commodity-inventory-notice"; + args = array( + "store_name" => product_row["store_name"], + "chain_name" => product_row["store_name"], + "product_id" => product_item_row["product_id"], + "item_id" => product_item_row["item_id"], + "product_item_name" => product_item_row["item_name"] ? implode(",", product_item_row["item_name"]) : product_row["product_name"], + "item_quantity" => product_item_row["item_quantity"], + ); - Message_TemplateModel::getInstance()->sendNoticeMsg(0, product_row["store_id"], message_id, args); - */ + Message_TemplateModel::getInstance()->sendNoticeMsg(0, product_row["store_id"], message_id, args); + */ } - // 传入chain_id - if (if_chain) { - cart_row.put("chain_id", chain_id); + // 传入chain_id, isChainOrder 是否门店自提 + if (isChainOrder) { + cartItem.put("chain_id", chainId); } - cart_row.put("user_id", user_id); - cart_row.put("store_id", product_row.getStore_id()); - cart_row.put("item_id", item_row[0]); - cart_row.put("product_id", product_row.getProduct_id()); - cart_row.put("cart_quantity", item_row[1]); - cart_row.put("cart_type", 1); - cart_row.put("activity_id", activity_id); - cart_row.put("single_activity", ifSingleActivity()); - cart_row.put("cart_select", 1); - cart_row.put("cart_ttl", 100000); - cart_row.put("cart_time", new Date().getTime()); - cart_row.put("cart_file", cart_file); - cart_row.put("pfgb_id", pfgb_id); + cartItem.put("user_id", currentUserId); + cartItem.put("store_id", productBase.getStore_id()); + cartItem.put("item_id", itemData[0]); + cartItem.put("product_id", productBase.getProduct_id()); + cartItem.put("cart_quantity", itemData[1]); + cartItem.put("cart_type", 1); + cartItem.put("activity_id", activityId); + cartItem.put("single_activity", ifSingleActivity()); + cartItem.put("cart_select", 1); + cartItem.put("cart_ttl", 100000); + cartItem.put("cart_time", new Date().getTime()); + cartItem.put("cart_file", cartFile); + cartItem.put("pfgb_id", pfgbId); + } // 重要:生成订单数据,结算checkout预览及生成订单(关键函数) - data = formatCartRows(cart_rows, activity_rows, null, null); + checkoutResult = formatCartRows(directPurchaseItems, activityData, null, null); } } - data.put("if_virtual", false); + // 是否为虚拟商品 + checkoutResult.put("if_virtual", false); // 判断是否为虚拟商品, 虚拟商品不经过购物车 - List items = (List) data.get("items"); - if (CollUtil.isNotEmpty(items)) { - Map item = items.get(0); - List _items = (List) item.get("items"); - Map _item = _items.get(0); + List storeOrders = (List) checkoutResult.get("items"); + if (CollUtil.isNotEmpty(storeOrders)) { + // 店铺订单信息 + Map storeOrder = storeOrders.get(0); + // 订单的商品列表 + List orderProducts = (List) storeOrder.get("items"); + Map firstProduct = orderProducts.get(0); - Boolean is_virtual = Convert.toBool(_item.get("is_virtual"), false); - if (_items.size() == 1 && is_virtual && product_id != null) { - data.put("if_virtual", true); + // 是否为虚拟商品 + Boolean isVirtual = Convert.toBool(firstProduct.get("is_virtual"), false); + if (orderProducts.size() == 1 && isVirtual && mainProductId != null) { + checkoutResult.put("if_virtual", true); // 修正虚拟数据 - ShopProductValidPeriod validPeriod = shopProductValidPeriodService.get(product_id); - Map virtvual_row = Convert.toMap(String.class, Object.class, validPeriod); + ShopProductValidPeriod validPeriod = shopProductValidPeriodService.get(mainProductId); + Map virtualProductData = Convert.toMap(String.class, Object.class, validPeriod); - if (ObjectUtil.isNotEmpty(virtvual_row)) { - _item.putAll(virtvual_row); + if (ObjectUtil.isNotEmpty(virtualProductData)) { + firstProduct.putAll(virtualProductData); } // 判断是否需要上门服务,上门需要地址 // 判断是否教育课程类 // getEduOrderInfo() - Integer kind_id = (Integer) _item.get("kind_id"); - if (ObjectUtil.equal(kind_id, StateCode.PRODUCT_KIND_EDU)) { - Map orderDetail = shopOrderBaseService.getEduOrderDetail(user_id, product_id); - if (CollUtil.isNotEmpty(orderDetail)) { + Integer productKindId = (Integer) firstProduct.get("kind_id"); + if (ObjectUtil.equal(productKindId, StateCode.PRODUCT_KIND_EDU)) { + Map eduOrderDetail = shopOrderBaseService.getEduOrderDetail(currentUserId, mainProductId); + if (CollUtil.isNotEmpty(eduOrderDetail)) { // 判断订单状态(教育订单只能购买一份) // 订单状态(LIST):2011-待订单审核;2013-待财务审核;2020-待配货/待出库审核;2030-待发货;2040-已发货/待收货确认;2060-已完成/已签收;2070-已取消/已作废; - Integer order_state_id = (Integer) orderDetail.get("order_state_id"); - if (ObjectUtil.equal(order_state_id, StateCode.ORDER_STATE_FINISH) && StrUtil.isNotEmpty(Convert.toStr(orderDetail.get("order_item_payment_amount")))) { - throw new ApiException(String.format(I18nUtil._("课程不能重复购买!order_id【%s】"), orderDetail.get("order_id"))); + Integer orderStateId = (Integer) eduOrderDetail.get("order_state_id"); + if (ObjectUtil.equal(orderStateId, StateCode.ORDER_STATE_FINISH) && StrUtil.isNotEmpty(Convert.toStr(eduOrderDetail.get("order_item_payment_amount")))) { + throw new ApiException(String.format(I18nUtil._("课程不能重复购买!order_id【%s】"), eduOrderDetail.get("order_id"))); } - if (ObjectUtil.equal(order_state_id, StateCode.ORDER_STATE_WAIT_PAY)) { - data.put("order_id", orderDetail.get("order_id")); - Map trade = (Map) orderDetail.get("trade"); - data.put("trade_payment_amount", trade.get("trade_payment_amount")); + if (ObjectUtil.equal(orderStateId, StateCode.ORDER_STATE_WAIT_PAY)) { + checkoutResult.put("order_id", eduOrderDetail.get("order_id")); + Map tradeInfo = (Map) eduOrderDetail.get("trade"); + checkoutResult.put("trade_payment_amount", tradeInfo.get("trade_payment_amount")); } } } @@ -743,102 +755,106 @@ public class ShopUserCartServiceImpl extends BaseServiceImpl address_row = new ArrayList(); - Map delivery_address_row = new HashMap(); + List userDeliveryAddresses = new ArrayList(); + Map selectedDeliveryAddress = new HashMap(); - if (CheckUtil.isNotEmpty(ud_id)) { - ShopUserDeliveryAddress user_address_row = deliveryAddressService.get(ud_id); - if (user_address_row != null && ObjectUtil.equal(user_address_row.getUser_id(), user_id)) { - address_row.add(Convert.toMap(String.class, Object.class, user_address_row)); + if (CheckUtil.isNotEmpty(deliveryAddressId)) { + ShopUserDeliveryAddress userDeliveryAddress = deliveryAddressService.get(deliveryAddressId); + if (userDeliveryAddress != null && ObjectUtil.equal(userDeliveryAddress.getUser_id(), currentUserId)) { + userDeliveryAddresses.add(Convert.toMap(String.class, Object.class, userDeliveryAddress)); } } - if (CollUtil.isEmpty(address_row)) { + if (CollUtil.isEmpty(userDeliveryAddresses)) { QueryWrapper addressQueryWrapper = new QueryWrapper<>(); - addressQueryWrapper.eq("user_id", user_id).orderByDesc("ud_is_default"); + addressQueryWrapper.eq("user_id", currentUserId).orderByDesc("ud_is_default"); List addressList = deliveryAddressService.find(addressQueryWrapper); if (CollUtil.isNotEmpty(addressList)) { - address_row = Convert.toList(Map.class, addressList); + userDeliveryAddresses = Convert.toList(Map.class, addressList); } } // 选中一个收货人的收货地址 - deliveryAddressService.fixAddressData(address_row); - if (CollUtil.isNotEmpty(address_row)) { - Optional defaultOpl = address_row.stream().filter(s -> Convert.toBool(s.get("ud_is_default"), false)).findFirst(); - if (defaultOpl.isPresent()) { - delivery_address_row = defaultOpl.get(); + deliveryAddressService.fixAddressData(userDeliveryAddresses); + if (CollUtil.isNotEmpty(userDeliveryAddresses)) { + Optional defaultAddressOption = userDeliveryAddresses.stream().filter(s -> Convert.toBool(s.get("ud_is_default"), false)).findFirst(); + if (defaultAddressOption.isPresent()) { + selectedDeliveryAddress = defaultAddressOption.get(); } else { - delivery_address_row = address_row.get(0); + selectedDeliveryAddress = userDeliveryAddresses.get(0); } } - data.put("address_row", address_row); // 用户所有的收货地址 - data.put("delivery_address_row", delivery_address_row); //用户选择的收货地址 + checkoutResult.put("address_row", userDeliveryAddresses); // 用户所有的收货地址 + checkoutResult.put("delivery_address_row", selectedDeliveryAddress); //用户选择的收货地址 // 城市id - Integer district_id = Convert.toInt(delivery_address_row.get("ud_city_id")); - if (CollUtil.isNotEmpty(delivery_address_row) && CheckUtil.isNotEmpty(district_id)) { + Integer districtId = Convert.toInt(selectedDeliveryAddress.get("ud_city_id")); + if (CollUtil.isNotEmpty(selectedDeliveryAddress) && CheckUtil.isNotEmpty(districtId)) { // 计算邮费情况 - if (Convert.toBool(is_delivery)) { - data.put("delivery_type_id", delivery_type_id); + if (Convert.toBool(isDeliveryRequired)) { + checkoutResult.put("delivery_type_id", deliveryTypeId); + // 重要:配送运费校验和计算(涉及的东西比较多) // calTransportFreight(data, district_id); // logger.debug("checkout 计算配送费时的配送方式:{}",delivery_type_id); // 订单地址和金额不在配送范围,抛出异常提示 - tryCalTransportFreight(data, district_id, true); - data.put("has_stock", data.get("can_delivery")); // 是否有货 + tryCalTransportFreight(checkoutResult, districtId, true); + + checkoutResult.put("has_stock", checkoutResult.get("can_delivery")); // 是否有货 } else { - data.put("can_delivery", true); // 是否可以派送 - data.put("has_stock", true); // 是否有货 + checkoutResult.put("can_delivery", true); // 是否可以派送 + checkoutResult.put("has_stock", true); // 是否有货 } // 是否有货 - boolean has_stock = (boolean) data.get("has_stock"); - data.put("show_oos", !has_stock); //无库存 + boolean hasStock = (boolean) checkoutResult.get("has_stock"); + + // 是否显示缺货状态 + checkoutResult.put("show_oos", !hasStock); } // todo validPeriod // 配送时间 - data.put("time_not_timer", StateCode.DELIVERY_TIME_NOT_TIMER); - data.put("time_hour", StateCode.DELIVERY_TIME_HOUR); - data.put("time_minute", StateCode.DELIVERY_TIME_MINUTE); + checkoutResult.put("time_not_timer", StateCode.DELIVERY_TIME_NOT_TIMER); + checkoutResult.put("time_hour", StateCode.DELIVERY_TIME_HOUR); + checkoutResult.put("time_minute", StateCode.DELIVERY_TIME_MINUTE); //提货券 - calUnUsedRedemption(data, user_id); + calUnUsedRedemption(checkoutResult, currentUserId); // 代金券 - calUnUsedVoucher(data, user_id); + calUnUsedVoucher(checkoutResult, currentUserId); - boolean isComplete = deliveryAddressService.addressIsComplete(null, delivery_address_row); - data.put("need_edit", isComplete ? 0 : 1); + boolean isAddressComplete = deliveryAddressService.addressIsComplete(null, selectedDeliveryAddress); + checkoutResult.put("need_edit", isAddressComplete ? 0 : 1); - // 发票 - data.put("inv_info", new HashMap()); + // 发票信息 + checkoutResult.put("inv_info", new HashMap()); - // 自提 - data.put("if_chain", if_chain); + // 是否要自提 + checkoutResult.put("if_chain", isChainOrder); // 付款方式 - Map address_api = new HashMap(); - data.put("address_api", address_api); + Map paymentApiConfig = new HashMap(); + checkoutResult.put("address_api", paymentApiConfig); // 判断是否有线下支付方式 - PayPaymentChannel offline_pay_row = payService.getPayChannel(1409); - if (offline_pay_row != null) { - Integer payment_channel_enable = offline_pay_row.getPayment_channel_enable(); - if (payment_channel_enable != null && payment_channel_enable == 1) { - address_api.put("allow_offpay", 1); + PayPaymentChannel offlinePaymentChannel = payService.getPayChannel(1409); + if (offlinePaymentChannel != null) { + Integer paymentChannelStatus = offlinePaymentChannel.getPayment_channel_enable(); + if (paymentChannelStatus != null && paymentChannelStatus == 1) { + paymentApiConfig.put("allow_offpay", 1); } else { - address_api.put("allow_offpay", 0); + paymentApiConfig.put("allow_offpay", 0); } } else { - address_api.put("allow_offpay", 0); + paymentApiConfig.put("allow_offpay", 0); } // todo diy, 判断是否上传素材 - return data; + return checkoutResult; } @Override @@ -1193,7 +1209,7 @@ public class ShopUserCartServiceImpl extends BaseServiceImpl queryWrapper, Integer page, Integer rows) { Page userCartPage = lists(queryWrapper, page, rows); List cart_rows = userCartPage.getRecords(); - int total_quantity = cart_rows.stream().mapToInt(ShopUserCart::getCart_quantity).sum(); + return processCartData(cart_rows); + } + + /** + * 读取所有购物车列表(不分页) + * + * @param queryWrapper 查询条件 + * @return + */ + @Transactional + public Map getLists(QueryWrapper queryWrapper) { + List cart_rows = find(queryWrapper); + return processCartData(cart_rows); + } + + /** + * 处理购物车数据的公共方法 + * + * @param cartRows 购物车记录列表 + * @return 处理后的购物车数据 + */ + private Map processCartData(List cartRows) { + // 计算购物车商品总数量 + int totalQuantity = cartRows.stream().mapToInt(ShopUserCart::getCart_quantity).sum(); // 判断商品是否存在 // todo 删除商品没有删除后遗症 - List item_id_row = cart_rows.stream().map(ShopUserCart::getItem_id).distinct().collect(Collectors.toList()); + // 提取所有商品ID + List itemIds = cartRows.stream().map(ShopUserCart::getItem_id).distinct().collect(Collectors.toList()); - List item_rowss = shopProductItemService.gets(item_id_row); - List product_id_row = item_rowss.stream().map(s -> Convert.toLong(s.get("product_id"))).distinct().collect(Collectors.toList()); - List product_rows = shopProductBaseService.gets(product_id_row); - List product_info_rows = Convert.toList(Map.class, shopProductInfoService.gets(product_id_row)); - List shopProductIndex = shopProductIndexService.gets(product_id_row); - List product_index_rows = Convert.toList(Map.class, shopProductIndex); + // 获取商品相关信息 + List itemRows = shopProductItemService.gets(itemIds); + List productIds = itemRows.stream().map(s -> Convert.toLong(s.get("product_id"))).distinct().collect(Collectors.toList()); + List productRows = shopProductBaseService.gets(productIds); + List productInfoRows = Convert.toList(Map.class, shopProductInfoService.gets(productIds)); + List shopProductIndexes = shopProductIndexService.gets(productIds); + List productIndexRows = Convert.toList(Map.class, shopProductIndexes); - List image_row = new ArrayList<>(); - if (CollUtil.isNotEmpty(product_id_row)) { + // 获取商品图片信息 + List productImages = new ArrayList<>(); + if (CollUtil.isNotEmpty(productIds)) { QueryWrapper imageQueryWrapper = new QueryWrapper<>(); - imageQueryWrapper.in("product_id", product_id_row); - image_row = shopProductImageService.find(imageQueryWrapper); + imageQueryWrapper.in("product_id", productIds); + productImages = shopProductImageService.find(imageQueryWrapper); } + // 构建商品信息VO对象 ProductVo productVo = new ProductVo(); - productVo.setItem(item_rowss); - productVo.setBase(product_rows); - productVo.setInfo(product_info_rows); - productVo.setIndex(product_index_rows); - productVo.setImage(image_row); + productVo.setItem(itemRows); + productVo.setBase(productRows); + productVo.setInfo(productInfoRows); + productVo.setIndex(productIndexRows); + productVo.setImage(productImages); - List item_rows = shopProductItemService.getItemFromCategory(productVo); + // 获取分类后的商品信息 + List categorizedItemRows = shopProductItemService.getItemFromCategory(productVo); - Iterator iterator = cart_rows.iterator(); - while (iterator.hasNext()) { - ShopUserCart cart_row = iterator.next(); - Integer cart_id = cart_row.getCart_id(); - Long item_id = Convert.toLong(cart_row.getItem_id()); + // 遍历购物车记录,处理无效商品和状态 + Iterator cartIterator = cartRows.iterator(); + while (cartIterator.hasNext()) { + ShopUserCart cartRecord = cartIterator.next(); + Integer cartId = cartRecord.getCart_id(); + Long itemId = Convert.toLong(cartRecord.getItem_id()); - Optional itemOpl = item_rows.stream().filter(s -> ObjectUtil.equal(item_id, Convert.toLong(s.get("item_id")))).findFirst(); - Map item = itemOpl.orElseGet(HashMap::new); - Integer item_enable = Convert.toInt(item.get("item_enable")); - Integer item_quantity = Convert.toInt(item.get("item_quantity")); - //如果商品库存为空,同样删除购物车数据 - if (item_enable == null || ObjectUtil.notEqual(item_enable, StateCode.PRODUCT_STATE_NORMAL) || item_quantity.intValue() <= 0) { + // 查找对应的商品信息 + Optional itemOptional = categorizedItemRows.stream().filter(s -> ObjectUtil.equal(itemId, Convert.toLong(s.get("item_id")))).findFirst(); + Map itemInfo = itemOptional.orElseGet(HashMap::new); + Integer itemEnableStatus = Convert.toInt(itemInfo.get("item_enable")); + Integer itemQuantity = Convert.toInt(itemInfo.get("item_quantity")); + + // 如果商品库存为空或已下架,删除购物车数据 + if (itemEnableStatus == null || ObjectUtil.notEqual(itemEnableStatus, StateCode.PRODUCT_STATE_NORMAL) || itemQuantity.intValue() <= 0) { // 删除购物车数据 - remove(cart_id); - iterator.remove(); + remove(cartId); + cartIterator.remove(); } - //强制设置未选中 - Optional shopProductBaseOpl = product_rows.stream().filter(s -> ObjectUtil.equal(Convert.toLong(s.get("product_id")), cart_row.getProduct_id())).findFirst(); - if (shopProductBaseOpl.isPresent() && (Convert.toInt(shopProductBaseOpl.get().get("product_state_id")) == StateCode.PRODUCT_STATE_NORMAL) && (Convert.toInt(shopProductBaseOpl.get().get("product_verify_id")) == StateCode.PRODUCT_VERIFY_PASSED)) { - + // 强制设置未选中状态 + Optional productBaseOptional = productRows.stream().filter(s -> ObjectUtil.equal(Convert.toLong(s.get("product_id")), cartRecord.getProduct_id())).findFirst(); + if (productBaseOptional.isPresent() && + (Convert.toInt(productBaseOptional.get().get("product_state_id")) == StateCode.PRODUCT_STATE_NORMAL) && + (Convert.toInt(productBaseOptional.get().get("product_verify_id")) == StateCode.PRODUCT_VERIFY_PASSED)) { + // 商品状态正常,无需处理 } else { - //设置未选中状态 - cart_row.setCart_select(0); - saveOrUpdate(cart_row); + // 设置未选中状态 + cartRecord.setCart_select(0); + saveOrUpdate(cartRecord); } } - List _cart_rows = Convert.toList(Map.class, cart_rows); - Map data = formatCartRows(_cart_rows, new HashMap(), productVo, null); - data.put("total_quantity", total_quantity); + // 格式化购物车数据 + List formattedCartRows = Convert.toList(Map.class, cartRows); + Map processedData = formatCartRows(formattedCartRows, new HashMap(), productVo, null); + processedData.put("total_quantity", totalQuantity); - return data; + return processedData; } + /** * 生成订单数据,结算checkout预览及生成订单 *

@@ -1278,298 +1329,319 @@ public class ShopUserCartServiceImpl extends BaseServiceImpl + * 方法功能分析 + * formatCartRows 方法的主要作用是: + * 格式化购物车数据:将传入的购物车数据按照店铺进行分组整理 + * 计算价格信息:包括商品原价、折扣金额、最终应付金额等 + * 处理活动优惠:如满减、多件折、组合套餐等各类促销活动 + * 计算运费相关信息:打包费、配送方式等 + * 生成预览数据:为订单结算页面提供展示所需的数据结构 + * 无数据持久化操作 + * 通过代码分析可以确认: + * 方法中没有调用任何数据库插入操作 + * 没有使用 save()、insert()、update() 等持久化方法 + * 所有操作都是在内存中对数据进行处理和计算 + * 最终返回的是一个 Map 对象,仅包含格式化后的数据 + *

+ * 方法定位 + * 从方法注释和实现可以看出,这是一个纯数据处理方法,专门用于生成订单结算预览数据,为后续真正的订单创建提供数据支持。真正的订单数据插入应该在其他专门的订单服务方法中完成。 */ @Override - public Map formatCartRows(List cart_rows, Map activity_rows, ProductVo productVo, FixOrderVo fixOrderVo) { - Map data_rows = new HashMap<>(); + public Map formatCartRows(List cartItems, Map activityData, ProductVo productVo, FixOrderVo fixOrderVo) { + // 方法返回结果对象 + Map checkoutResult = new HashMap<>(); // 判断是否为单一活动。 - boolean single_item = cart_rows.size() == 1; - boolean single_activity = false; + boolean isSingleCartItem = cartItems.size() == 1; + boolean isSingleActivity = false; + + Integer deliveryTypeId = null; // 配送方式(ENUM):5-自提;10-快递;16-同城配送; - List allowTransportIds = new ArrayList() {{ + List allowedTransportTypeIds = new ArrayList() {{ add(StateCode.DELIVERY_TYPE_SELF_PICK_UP); add(StateCode.DELIVERY_TYPE_EXP); add(StateCode.DELIVERY_TYPE_SAME_CITY); }}; //允许的配送方式 // 关键金额数据,对方竟然没有备注清楚!!! - BigDecimal orderSelProductAmount = BigDecimal.ZERO; //商品订单原价 - BigDecimal orderSelFreightAmount = BigDecimal.ZERO;//选中商品运费金额(仅运费) - BigDecimal orderSelMoneyAmount = BigDecimal.ZERO;//选中商品最终应付金额 - BigDecimal orderDiscountAmount = BigDecimal.ZERO;//商品订单折扣优惠金额 - BigDecimal orderSelPointsAmount = BigDecimal.ZERO;//商品订单积分抵扣金额 - BigDecimal orderSelSpAmount = BigDecimal.ZERO;//可能是:商品订单促销金额 - BigDecimal orderRebateAmount = BigDecimal.ZERO;//可能是:商品订单返利金额 - BigDecimal packingFee = BigDecimal.ZERO; // 商家打包费 + BigDecimal totalOriginalAmount = BigDecimal.ZERO; //商品订单原价 + BigDecimal totalFreightAmount = BigDecimal.ZERO; //选中商品运费金额(仅运费) + BigDecimal totalPaymentAmount = BigDecimal.ZERO; //选中商品最终应付金额 + BigDecimal totalDiscountAmount = BigDecimal.ZERO; //商品订单折扣优惠金额 + BigDecimal totalPointsAmount = BigDecimal.ZERO; //商品订单积分抵扣金额 + BigDecimal totalPromotionAmount = BigDecimal.ZERO; //可能是:商品订单促销金额 + BigDecimal totalRebateAmount = BigDecimal.ZERO; //可能是:商品订单返利金额 + BigDecimal totalPackingFee = BigDecimal.ZERO; // 总计打包费 - data_rows.put("orderSelMoneyAmount", 10.00f); // 这是什么金额?最低支付金额吗? - data_rows.put("items", new ArrayList()); + checkoutResult.put("orderSelMoneyAmount", 10.00f); // 这是什么金额?最低支付金额吗? + checkoutResult.put("items", new ArrayList()); // 获取所有店铺信息 - List store_id_row = cart_rows.stream().map(s -> Convert.toInt(s.get("store_id"))).distinct().collect(Collectors.toList()); - List store_rows = shopStoreBaseService.gets(store_id_row); + List storeIds = cartItems.stream().map(s -> Convert.toInt(s.get("store_id"))).distinct().collect(Collectors.toList()); + List storeInfoList = shopStoreBaseService.gets(storeIds); // 店铺购物券 - List item_id_row = cart_rows.stream().map(s -> Convert.toLong(s.get("item_id"))).distinct().collect(Collectors.toList()); - List chain_id_row = cart_rows.stream().map(s -> Convert.toInt(Convert.toInt(s.get("chain_id")))).distinct().collect(Collectors.toList()); - if (chain_id_row.size() == 1 && chain_id_row.get(0) == null) chain_id_row.remove(0); + List productItemIds = cartItems.stream().map(s -> Convert.toLong(s.get("item_id"))).distinct().collect(Collectors.toList()); + List chainIds = cartItems.stream().map(s -> Convert.toInt(Convert.toInt(s.get("chain_id")))).distinct().collect(Collectors.toList()); + if (chainIds.size() == 1 && chainIds.get(0) == null) chainIds.remove(0); + // 获取所有商品信息 - List item_rows; + List productItemList; if (productVo != null) { - item_rows = shopProductItemService.getItemFromCategory(productVo); + productItemList = shopProductItemService.getItemFromCategory(productVo); } else { - item_rows = shopProductItemService.getItem(item_id_row); + productItemList = shopProductItemService.getItem(productItemIds); } - List chain_item_rows = new ArrayList<>(); - Map chain_row = null; - Map activity_info = new HashMap(); + // 门店商品信息列表 + List chainProductItemList = new ArrayList<>(); + // 门店信息 + Map chainInfo = null; + // 活动信息 + Map activityInfo = new HashMap(); - - if (CollUtil.isNotEmpty(chain_id_row)) { + if (CollUtil.isNotEmpty(chainIds)) { // 得到有该商品的门店 - Integer chain_id = chain_id_row.get(0); - ShopChainBase shopChainBase = shopChainBaseService.get(chain_id); - chain_row = Convert.toMap(String.class, Object.class, shopChainBase); -// List chain_rows = Convert.toList(Map.class, chain_row); + Integer chainId = chainIds.get(0); + ShopChainBase shopChainBase = shopChainBaseService.get(chainId); + chainInfo = Convert.toMap(String.class, Object.class, shopChainBase); // 获取该商品在chain_id下的 QueryWrapper itemQueryWrapper = new QueryWrapper<>(); - itemQueryWrapper.eq("chain_id", chain_id).in("item_id", item_id_row); + itemQueryWrapper.eq("chain_id", chainId).in("item_id", productItemIds); List shopChainItems = shopChainItemService.find(itemQueryWrapper); - chain_item_rows = Convert.toList(Map.class, shopChainItems); + chainProductItemList = Convert.toList(Map.class, shopChainItems); } - Map store_items_rows = new HashMap(); - data_rows.put("cart_select", 1); + // 按店铺分组的购物车商品数据 + Map> storeGroupedCartItems = new HashMap(); + checkoutResult.put("cart_select", 1); - if (CollUtil.isNotEmpty(cart_rows) && CollUtil.isNotEmpty(item_rows) && CollUtil.isNotEmpty(store_rows)) { + if (CollUtil.isNotEmpty(cartItems) && CollUtil.isNotEmpty(productItemList) && CollUtil.isNotEmpty(storeInfoList)) { // 格式化数据 店铺数据分组,商品仓库分组 - for (Map row : cart_rows) { - Map chain_item_row = new HashMap<>(); - // 修正门店产品 - Integer chain_id = Convert.toInt(row.get("chain_id")); - Long item_id = Convert.toLong(row.get("item_id")); - if (CheckUtil.isNotEmpty(chain_id) && CheckUtil.isNotEmpty(item_id)) { - for (Map chain_i_row : chain_item_rows) { - Integer chainId = Convert.toInt(chain_i_row.get("chain_id")); - Long itemId = Convert.toLong(chain_i_row.get("item_id")); + for (Map cartItem : cartItems) { - if (ObjectUtil.equal(chain_id, chainId) && ObjectUtil.equal(item_id, itemId)) { - chain_item_row = chain_i_row; + // 获取配送方式 + if (deliveryTypeId == null) { + deliveryTypeId = Convert.toInt(cartItem.get("delivery_type_id")); + } + // 门店商品信息 + Map chainProductItem = new HashMap<>(); + // 修正门店产品 + Integer chainId = Convert.toInt(cartItem.get("chain_id")); + Long itemId = Convert.toLong(cartItem.get("item_id")); + if (CheckUtil.isNotEmpty(chainId) && CheckUtil.isNotEmpty(itemId)) { + for (Map chainItem : chainProductItemList) { + Integer chainItemId = Convert.toInt(chainItem.get("chain_id")); + Long chainProductId = Convert.toLong(chainItem.get("item_id")); + + if (ObjectUtil.equal(chainId, chainItemId) && ObjectUtil.equal(itemId, chainProductId)) { + chainProductItem = chainItem; break; } } } - Optional itemOpl = item_rows.stream().filter(s -> ObjectUtil.equal(item_id, Convert.toLong(s.get("item_id")))).findFirst(); - Map item = itemOpl.orElseGet(HashMap::new); - Map item_row_map = new HashMap<>(); - item_row_map.putAll(item); - item_row_map.putAll(row); - + Optional itemOptional = productItemList.stream().filter(s -> ObjectUtil.equal(itemId, Convert.toLong(s.get("item_id")))).findFirst(); + Map productItem = itemOptional.orElseGet(HashMap::new); + // 商品信息合并购物车信息 + Map mergedItem = new HashMap<>(); + mergedItem.putAll(productItem); + mergedItem.putAll(cartItem); //允许发的快递类型id:普通快递,同城配送,上门自取。取交集 - allowTransportIds = (List) CollUtil.intersection(allowTransportIds, Convert.toList(Integer.class, item.get("product_transport_id"))); + allowedTransportTypeIds = (List) CollUtil.intersection(allowedTransportTypeIds, Convert.toList(Integer.class, productItem.get("product_transport_id"))); - Map stand_item_row = fixCartItemRow(item_row_map, chain_item_row); + Map standardCartItem = fixCartItemRow(mergedItem, chainProductItem); //单一活动判断,处理单一活动数据。 single_activity 和下面店铺处理费单一活动处理逻辑相反 - //activity_data = do_action("store_activity_item_data", store_id_row, "Activity"); - //获取店铺的活动信息 - 根据店铺检索数据,暂时没有,目前店铺活动需要绑定商品 - //活动数据,修正购物车内容 - //store_rows = apply_filters("activity_cart_info", store_rows, activity_data); - - single_activity = Convert.toBool(stand_item_row.get("single_activity"), false); + isSingleActivity = Convert.toBool(standardCartItem.get("single_activity"), false); // todo 处理 单个活动商品购买时 - if (single_activity && single_item) { - stand_item_row = shopStoreActivityBaseService.delSingleActivity(stand_item_row); + if (isSingleActivity && isSingleCartItem) { + standardCartItem = shopStoreActivityBaseService.delSingleActivity(standardCartItem); } - if (ObjectUtil.isNull(stand_item_row.get("activitys"))) { - stand_item_row.put("activitys", new HashMap()); + if (ObjectUtil.isNull(standardCartItem.get("activitys"))) { + standardCartItem.put("activitys", new HashMap()); } // 根据店铺分组数据 - Integer store_id = Convert.toInt(row.get("store_id")); - List stand_item_row_list = (List) ObjectUtil.defaultIfNull(store_items_rows.get(store_id), new ArrayList()); - if (CollUtil.isEmpty(stand_item_row_list)) store_items_rows.put(store_id, stand_item_row_list); - stand_item_row_list.add(stand_item_row); + Integer storeId = Convert.toInt(cartItem.get("store_id")); + List standardCartItemList = ObjectUtil.defaultIfNull(storeGroupedCartItems.get(storeId), new ArrayList()); + if (CollUtil.isEmpty(standardCartItemList)) storeGroupedCartItems.put(storeId, standardCartItemList); + standardCartItemList.add(standardCartItem); } // 根据店铺分组数据 - List storeIds = store_rows.stream().map(e -> Convert.toInt(e.get("store_id"))).collect(Collectors.toList()); - List storeConfigs = shopStoreConfigService.gets(storeIds); + List storeIdList = storeInfoList.stream().map(e -> Convert.toInt(e.get("store_id"))).collect(Collectors.toList()); + List storeConfigs = shopStoreConfigService.gets(storeIdList); - for (Map store_row : store_rows) { + for (Map storeInfo : storeInfoList) { // 店铺Id - Integer store_id = Convert.toInt(store_row.get("store_id")); - List stand_item_row_list = (List) ObjectUtil.defaultIfNull(store_items_rows.get(store_id), new ArrayList()); - store_row.put("items", stand_item_row_list); - List cart_select_row = stand_item_row_list.stream().map(s -> Convert.toInt(s.get("cart_select"))).collect(Collectors.toList()); + Integer storeId = Convert.toInt(storeInfo.get("store_id")); + List standardCartItemList = (List) ObjectUtil.defaultIfNull(storeGroupedCartItems.get(storeId), new ArrayList()); + storeInfo.put("items", standardCartItemList); + List cartSelectList = standardCartItemList.stream().map(s -> Convert.toInt(s.get("cart_select"))).collect(Collectors.toList()); - if (cart_select_row.contains(0)) { - store_row.put("cart_select", 0); - data_rows.put("cart_select", 0); + if (cartSelectList.contains(0)) { + storeInfo.put("cart_select", 0); + checkoutResult.put("cart_select", 0); } else { - store_row.put("cart_select", 1); + storeInfo.put("cart_select", 1); } - store_row.put("uuid", "1486449179.7034:58996a1babba44.74970832"); - int num = stand_item_row_list.stream().mapToInt(s -> Convert.toInt(s.get("num"), 0)).sum(); - store_row.put("totalWithoutGift", num); - store_row.put("totalSelGoods", store_row.get("totalWithoutGift")); - store_row.put("hasTv", true); - store_row.put("shipmentDesc", ""); - store_row.put("max_push_days", 21); - store_row.put("store_rebate", 0); + storeInfo.put("uuid", "1486449179.7034:58996a1babba44.74970832"); + int num = standardCartItemList.stream().mapToInt(s -> Convert.toInt(s.get("num"), 0)).sum(); + storeInfo.put("totalWithoutGift", num); + storeInfo.put("totalSelGoods", storeInfo.get("totalWithoutGift")); + storeInfo.put("hasTv", true); + storeInfo.put("shipmentDesc", ""); + storeInfo.put("max_push_days", 21); + storeInfo.put("store_rebate", 0); // 封装读取活动信息 - Map activitys = new HashMap(); - activitys.put("gift", new ArrayList()); - activitys.put("reduction", new ArrayList()); - activitys.put("multple", new ArrayList()); - activitys.put("coupons", new HashMap<>()); - activitys.put("postFree", new HashMap<>()); + Map storeActivities = new HashMap(); + storeActivities.put("gift", new ArrayList()); + storeActivities.put("reduction", new ArrayList()); + storeActivities.put("multple", new ArrayList()); + storeActivities.put("coupons", new HashMap<>()); + storeActivities.put("postFree", new HashMap<>()); // 封装读取活动信息 - store_row.put("activitys", activitys); + storeInfo.put("activitys", storeActivities); //促销,活动商品通过SKU商品,存入SPU管理数据方便? //如果加价购只属于一个商品,则商品内部显示,参见items pulse_bargains,这个基于配件方式,配件属于某商品专用,可在添加商品时候指定完成, 在数据库实现上, 采用促销活动实现。 //促销活动信息,加价购针对整个店铺或者多个商品,和具体商品无关 - store_row.put("bargains", new ArrayList()); // 促销商品选项 - store_row.put("bargainDiv", new ArrayList()); // 活动促销商品选择列表信息 + storeInfo.put("bargains", new ArrayList()); // 促销商品选项 + storeInfo.put("bargainDiv", new ArrayList()); // 活动促销商品选择列表信息 - store_row.put("giftsDiv", new ArrayList()); + storeInfo.put("giftsDiv", new ArrayList()); //单品活动优惠总额 - store_row.put("pulseActivityDiscountMoney", BigDecimal.ZERO); + storeInfo.put("pulseActivityDiscountMoney", BigDecimal.ZERO); // 只显示和叠加多商品的,携带在但商品的活动优惠直接显示在商品后面 - Map discount_items = new HashMap<>(); - discount_items.put("giftbag", 0); - discount_items.put("reduction_again", 0); - discount_items.put("reduction", 0); - discount_items.put("multple", 0); - discount_items.put("limited_discount", 0); - discount_items.put("one_piece_discount", 0);//单件折 + Map discountItems = new HashMap<>(); + discountItems.put("giftbag", 0); + discountItems.put("reduction_again", 0); + discountItems.put("reduction", 0); + discountItems.put("multple", 0); + discountItems.put("limited_discount", 0); + discountItems.put("one_piece_discount", 0);//单件折 - store_row.put("discount_items", discount_items); + storeInfo.put("discount_items", discountItems); - Map pulse_discount_items = new HashMap<>(); - pulse_discount_items.put("pulse_reduction", BigDecimal.ZERO); - pulse_discount_items.put("pulse_multple", BigDecimal.ZERO); + Map pulseDiscountItems = new HashMap<>(); + pulseDiscountItems.put("pulse_reduction", BigDecimal.ZERO); + pulseDiscountItems.put("pulse_multple", BigDecimal.ZERO); - store_row.put("pulse_discount_items", pulse_discount_items); - store_row.put("discount_detail_rows", new ArrayList<>()); + storeInfo.put("pulse_discount_items", pulseDiscountItems); + storeInfo.put("discount_detail_rows", new ArrayList<>()); //discount_detail_rows 格式例子 [["type" => "reduction_again", "type_id" => 1140, "item_ids" => [1,2], "amount" => "100", "discount" => "33.3", "old_amount" => "133.3"]]; //店铺全局活动优惠总额 - 不包含单品活动的 - store_row.put("activityDiscountMoney", BigDecimal.ZERO); - store_row.put("productMoney", BigDecimal.valueOf(28971.9)); - store_row.put("orderMoney", BigDecimal.valueOf(28971.9f)); - store_row.put("productMoneySelGoods", BigDecimal.valueOf(28971.9f)); + storeInfo.put("activityDiscountMoney", BigDecimal.ZERO); + storeInfo.put("productMoney", BigDecimal.valueOf(28971.9)); + storeInfo.put("orderMoney", BigDecimal.valueOf(28971.9f)); + storeInfo.put("productMoneySelGoods", BigDecimal.valueOf(28971.9f)); - int subtotal = stand_item_row_list.stream().mapToInt(s -> Convert.toInt(s.get("subtotal"), 0)).sum(); - store_row.put("order_money_select_items", subtotal); - int item_rebate_subtotal = stand_item_row_list.stream().mapToInt(s -> Convert.toInt(s.get("item_rebate_subtotal"), 0)).sum(); - store_row.put("store_rebate", item_rebate_subtotal); - store_row.put("postFree", true); // 是否免运费 - store_row.put("freight", ""); // 节省运费 - store_row.put("postFreeBalance", 0); // 还需 postFreeBalance 元即可免邮费 + int subtotal = standardCartItemList.stream().mapToInt(s -> Convert.toInt(s.get("subtotal"), 0)).sum(); + storeInfo.put("order_money_select_items", subtotal); + int itemRebateSubtotal = standardCartItemList.stream().mapToInt(s -> Convert.toInt(s.get("item_rebate_subtotal"), 0)).sum(); + storeInfo.put("store_rebate", itemRebateSubtotal); + storeInfo.put("postFree", true); // 是否免运费 + storeInfo.put("freight", ""); // 节省运费 + storeInfo.put("postFreeBalance", 0); // 还需 postFreeBalance 元即可免邮费 - store_row.put("coudan_items", new ArrayList()); // 立即凑单 postFreeBalance > 0 + storeInfo.put("coudan_items", new ArrayList()); // 立即凑单 postFreeBalance > 0 // 判断商家是否开票 for (ShopStoreConfig storeConfig : storeConfigs) { - if (storeConfig.getStore_id().equals(store_id)) { - store_row.put("sc_is_enabled_invoice", storeConfig.getSc_is_enabled_invoice()); + if (storeConfig.getStore_id().equals(storeId)) { + storeInfo.put("sc_is_enabled_invoice", storeConfig.getSc_is_enabled_invoice()); } } // 判断店铺商品显示勾选状态 如果有一个商品为正常状态则显示可勾选 - JSONArray items = JSONUtil.parseArray(store_row.get("items")); - store_row.put("store_checkable", items.stream() + JSONArray items = JSONUtil.parseArray(storeInfo.get("items")); + storeInfo.put("store_checkable", items.stream() .anyMatch(item -> Convert.toInt(JSONUtil.parseObj(item).get("product_state_id")) .equals(StateCode.PRODUCT_STATE_NORMAL))); } - Map activity_data = shopStoreActivityBaseService.getStoreActivityItmeData(store_id_row, null); - activity_info = (Map) activity_data.get("activity_info"); + Map storeActivityData = shopStoreActivityBaseService.getStoreActivityItmeData(storeIds, null); + activityInfo = (Map) storeActivityData.get("activity_info"); // 根据店铺读取活动 - if (!single_item || !single_activity) { + if (!isSingleCartItem || !isSingleActivity) { // todo //获取店铺的活动信息 - 根据店铺检索数据,暂时没有,目前店铺活动需要绑定商品 //活动数据,修正购物车内容 - store_rows = shopStoreActivityBaseService.getCartInfo(store_rows, activity_data, productVo); + storeInfoList = shopStoreActivityBaseService.getCartInfo(storeInfoList, storeActivityData, productVo); // 阶梯价 } } // todo 活动可能影响,重新计算价格 - if (CollUtil.isNotEmpty(cart_rows) && CollUtil.isNotEmpty(item_rows) && CollUtil.isNotEmpty(store_rows)) { + if (CollUtil.isNotEmpty(cartItems) && CollUtil.isNotEmpty(productItemList) && CollUtil.isNotEmpty(storeInfoList)) { // 平台等级 - Map user_info_row = new HashMap(); - Integer user_level_id = null; + Map userInfo = new HashMap(); + Integer userLevelId = null; //优惠信息-折上折用 //discount_deatil = array(); - Boolean user_level_rate_enable = accountBaseConfigService.getConfig("user_level_rate_enable", false); + Boolean userLevelRateEnable = accountBaseConfigService.getConfig("user_level_rate_enable", false); - Set user_ids = new HashSet(); - Set store_ids = new HashSet(); - Set transport_type_ids = new HashSet(); - List itemss = store_rows.stream().map(e -> e.get("items")).collect(Collectors.toList()); - JSONArray jsonArray = JSONUtil.parseArray(itemss); - if (!jsonArray.isEmpty()) { - for (Object o : jsonArray) { - JSONArray jsonArr = JSONUtil.parseArray(o); - for (Object object : jsonArr) { - JSONObject jsonObject = JSONUtil.parseObj(object); - Integer userId = Convert.toInt(jsonObject.get("user_id")); - Integer storeId = Convert.toInt(jsonObject.get("store_id")); - Integer transportTypeId = Convert.toInt(jsonObject.get("transport_type_id")); - user_ids.add(userId); - store_ids.add(storeId); - transport_type_ids.add(transportTypeId); + Set userIds = new HashSet<>(); + Set storeIdSet = new HashSet<>(); + Set transportTypeIds = new HashSet<>(); + + for (Map storeInfo : storeInfoList) { + List storeProductItems = (List) storeInfo.get("items"); + if (CollUtil.isNotEmpty(storeProductItems)) { + Integer storeId = Convert.toInt(storeInfo.get("store_id")); + storeIdSet.add(storeId); + + for (Map productItem : storeProductItems) { + userIds.add(Convert.toInt(productItem.get("user_id"))); + transportTypeIds.add(Convert.toInt(productItem.get("transport_type_id"))); } } } List userInfoList = new ArrayList<>(); - if (CollUtil.isNotEmpty(user_ids)) { - userInfoList = accountService.getUserInfoList(Convert.toList(Integer.class, user_ids)); + if (CollUtil.isNotEmpty(userIds)) { + userInfoList = accountService.getUserInfoList(Convert.toList(Integer.class, userIds)); } List invoicingCustomerBases = new ArrayList<>(); - if (CollUtil.isNotEmpty(store_ids) && CollUtil.isNotEmpty(user_ids)) { + if (CollUtil.isNotEmpty(storeIdSet) && CollUtil.isNotEmpty(userIds)) { QueryWrapper customerBaseQueryWrapper = new QueryWrapper<>(); - customerBaseQueryWrapper.in("store_id", store_ids).in("user_id", user_ids); + customerBaseQueryWrapper.in("store_id", storeIdSet).in("user_id", userIds); invoicingCustomerBases = invoicingCustomerBaseService.find(customerBaseQueryWrapper); - } - List transportTypes = shopStoreTransportTypeService.gets(transport_type_ids); + List transportTypes = shopStoreTransportTypeService.gets(transportTypeIds); - for (Map store_row : store_rows) { - Map activitys = (Map) ObjectUtil.defaultIfNull(store_row.get("activitys"), new HashMap()); - Map discount_items = (Map) store_row.get("discount_items"); - List discount_detail_rows = (List) ObjectUtil.defaultIfNull(store_row.get("discount_detail_rows"), new ArrayList()); + for (Map storeInfo : storeInfoList) { + Map storeActivities = (Map) ObjectUtil.defaultIfNull(storeInfo.get("activitys"), new HashMap()); + Map discountItems = (Map) storeInfo.get("discount_items"); + List discountDetailRows = (List) ObjectUtil.defaultIfNull(storeInfo.get("discount_detail_rows"), new ArrayList()); // 平台等级则不启用平台等级折扣 - List items = (List) store_row.get("items"); + List storeProductItems = (List) storeInfo.get("items"); - if (user_level_id == null && user_level_rate_enable) { - if (CollUtil.isEmpty(user_info_row)) { - if (items.size() > 0) { - Map item = items.get(0); - Integer user_id = Convert.toInt(item.get("user_id")); - for (AccountUserInfo userInfo : userInfoList) { - if (userInfo.getUser_id().equals(user_id)) { - user_level_id = userInfo.getUser_level_id(); + if (userLevelId == null && userLevelRateEnable) { + if (CollUtil.isEmpty(userInfo)) { + if (storeProductItems.size() > 0) { + Map item = storeProductItems.get(0); + Integer userId = Convert.toInt(item.get("user_id")); + for (AccountUserInfo userInfoItem : userInfoList) { + if (userInfoItem.getUser_id().equals(userId)) { + userLevelId = userInfoItem.getUser_level_id(); } } } @@ -1577,213 +1649,219 @@ public class ShopUserCartServiceImpl extends BaseServiceImpl type.getTransport_type_id().equals(transportTypeId)) + .findFirst() + .orElse(null); + + if (transportTypeData != null) { + Integer transportTypePricingMethod = transportTypeData.getTransport_type_pricing_method(); + BigDecimal currentQuantity = (BigDecimal) ObjectUtil.defaultIfNull( + transportTypeQuantities.get(transportTypeId), BigDecimal.ZERO); + + if (transportTypePricingMethod == 2) { + // 按重量计算运费 + BigDecimal itemWeight = Convert.toBigDecimal(productItemInStore.get("item_weight")); + BigDecimal weightSum = NumberUtil.add(currentQuantity, + NumberUtil.mul(cartQuantity, itemWeight)); + transportTypeQuantities.put(transportTypeId, weightSum); + } else { + // 按数量计算运费 + BigDecimal quantitySum = NumberUtil.add(currentQuantity, BigDecimal.valueOf(cartQuantity)); + transportTypeQuantities.put(transportTypeId, quantitySum); } } } - Boolean pfgb_id = Convert.toBool(cart_rows.get(0).get("pfgb_id")); - if (pfgb_id != null && pfgb_id) { + Boolean isPfgb = Convert.toBool(cartItems.get(0).get("pfgb_id")); + if (isPfgb != null && isPfgb) { // 修正团购批发价 - fixPriceGroupPolicyWholesale(item_row); + fixPriceGroupPolicyWholesale(productItemInStore); } else { // 修正批发价 - fixPricePolicyWholesale(item_row); + fixPricePolicyWholesale(productItemInStore); } // 修正价格策略影响 - fixPricePolicy(item_row, customer_level_id, user_level_id); - store_row.put("policy_discountrate", item_row.get("policy_discountrate")); + fixPricePolicy(productItemInStore, customerLevelId, userLevelId); + storeInfo.put("policy_discountrate", productItemInStore.get("policy_discountrate")); - store_total = NumberUtil.add(Convert.toBigDecimal(item_row.get("subtotal")), store_total); - store_origin_total = store_origin_total.add(item_unit_price.multiply(Convert.toBigDecimal(cart_quantity))); - store_points_total = NumberUtil.add(Convert.toBigDecimal(item_row.get("points_subtotal")), store_points_total); - store_sp_total = NumberUtil.add(Convert.toBigDecimal(item_row.get("sp_subtotal")), store_sp_total); - store_old_amount = NumberUtil.add(store_old_amount, Convert.toBigDecimal(item_row.get("old_amount"))); + storeTotalAmount = NumberUtil.add(Convert.toBigDecimal(productItemInStore.get("subtotal")), storeTotalAmount); + + storeOriginalAmount = storeOriginalAmount.add(itemUnitPrice.multiply(Convert.toBigDecimal(cartQuantity))); + storePointsAmount = NumberUtil.add(Convert.toBigDecimal(productItemInStore.get("points_subtotal")), storePointsAmount); + storePromotionAmount = NumberUtil.add(Convert.toBigDecimal(productItemInStore.get("sp_subtotal")), storePromotionAmount); + storeOldAmount = NumberUtil.add(storeOldAmount, Convert.toBigDecimal(productItemInStore.get("old_amount"))); //限时折扣 //店铺优惠总额 - Map pulse_discount = (Map) item_row.get("pulse_discount"); - if (CollUtil.isNotEmpty(pulse_discount)) { - store_row.put("pulseActivityDiscountMoney", Convert.toBigDecimal(store_row.get("pulseActivityDiscountMoney")).add(Convert.toBigDecimal(item_row.get("activity_discount_amount")))); + Map pulseDiscount = (Map) productItemInStore.get("pulse_discount"); + if (CollUtil.isNotEmpty(pulseDiscount)) { + storeInfo.put("pulseActivityDiscountMoney", Convert.toBigDecimal(storeInfo.get("pulseActivityDiscountMoney")).add(Convert.toBigDecimal(productItemInStore.get("activity_discount_amount")))); - BigDecimal activity_discount_amount = Convert.toBigDecimal(item_row.get("activity_discount_amount")); - BigDecimal limited_discount_tmp = Convert.toBigDecimal(discount_items.get("limited_discount")); - discount_items.put("limited_discount", limited_discount_tmp.add(activity_discount_amount)); + BigDecimal activityDiscountAmount = Convert.toBigDecimal(productItemInStore.get("activity_discount_amount")); + BigDecimal limitedDiscountTmp = Convert.toBigDecimal(discountItems.get("limited_discount")); + discountItems.put("limited_discount", limitedDiscountTmp.add(activityDiscountAmount)); } //单件折 pulse_discount_rate - Map pulse_discount_rate = (Map) item_row.get("pulse_discount_rate"); - if (CollUtil.isNotEmpty(pulse_discount_rate)) { - store_row.put("pulseActivityDiscountMoney", Convert.toBigDecimal(store_row.get("pulseActivityDiscountMoney")).add(Convert.toBigDecimal(item_row.get("activity_discount_amount")))); + Map pulseDiscountRate = (Map) productItemInStore.get("pulse_discount_rate"); + if (CollUtil.isNotEmpty(pulseDiscountRate)) { + storeInfo.put("pulseActivityDiscountMoney", Convert.toBigDecimal(storeInfo.get("pulseActivityDiscountMoney")).add(Convert.toBigDecimal(productItemInStore.get("activity_discount_amount")))); - BigDecimal activity_discount_amount = Convert.toBigDecimal(item_row.get("activity_discount_amount")); - BigDecimal limited_discount_tmp = Convert.toBigDecimal(discount_items.get("one_piece_discount")); - discount_items.put("one_piece_discount", limited_discount_tmp.add(activity_discount_amount)); + BigDecimal activityDiscountAmount = Convert.toBigDecimal(productItemInStore.get("activity_discount_amount")); + BigDecimal limitedDiscountTmp = Convert.toBigDecimal(discountItems.get("one_piece_discount")); + discountItems.put("one_piece_discount", limitedDiscountTmp.add(activityDiscountAmount)); } // 礼品 - List pulse_gift_carts = (List) item_row.get("pulse_gift_cart"); - if (CollUtil.isNotEmpty(pulse_gift_carts)) { + List pulseGiftCarts = (List) productItemInStore.get("pulse_gift_cart"); + if (CollUtil.isNotEmpty(pulseGiftCarts)) { - List pulse_gift_cart_list = new ArrayList(); - for (Map pulse_gift_cart : pulse_gift_carts) { - Long cart_item_id = Convert.toLong(pulse_gift_cart.get("item_id")); - ids.add(cart_item_id); + List pulseGiftCartList = new ArrayList(); + for (Map pulseGiftCart : pulseGiftCarts) { + Long cartItemId = Convert.toLong(pulseGiftCart.get("item_id")); + selectedIds.add(cartItemId); - Integer cart_transport_type_id = Convert.toInt(pulse_gift_cart.get("transport_type_id")); - BigDecimal sum = Convert.toBigDecimal(tt_ids.get(cart_transport_type_id)); - Integer cart_cart_quantity = Convert.toInt(pulse_gift_cart.get("cart_quantity")); + Integer cartTransportTypeId = Convert.toInt(pulseGiftCart.get("transport_type_id")); + BigDecimal sum = Convert.toBigDecimal(transportTypeQuantities.get(cartTransportTypeId)); + Integer cartCartQuantity = Convert.toInt(pulseGiftCart.get("cart_quantity")); - tt_ids.put(transport_type_id, NumberUtil.add(sum, cart_cart_quantity)); + transportTypeQuantities.put(transportTypeId, NumberUtil.add(sum, cartCartQuantity)); // 修正价格策略影响 - fixPricePolicy(pulse_gift_cart, customer_level_id, user_level_id); - BigDecimal cart_item_sale_price = Convert.toBigDecimal(pulse_gift_cart.get("item_sale_price")); - BigDecimal cart_item_unit_points = Convert.toBigDecimal(pulse_gift_cart.get("item_unit_points")); - BigDecimal cart_item_unit_sp = Convert.toBigDecimal(pulse_gift_cart.get("item_unit_sp")); + fixPricePolicy(pulseGiftCart, customerLevelId, userLevelId); + BigDecimal cartItemSalePrice = Convert.toBigDecimal(pulseGiftCart.get("item_sale_price")); + BigDecimal cartItemUnitPoints = Convert.toBigDecimal(pulseGiftCart.get("item_unit_points")); + BigDecimal cartItemUnitSp = Convert.toBigDecimal(pulseGiftCart.get("item_unit_sp")); - pulse_gift_cart.put("subtotal", NumberUtil.mul(cart_item_sale_price, cart_cart_quantity)); - pulse_gift_cart.put("points_subtotal", NumberUtil.mul(cart_item_unit_points, cart_cart_quantity)); - pulse_gift_cart.put("sp_subtotal", NumberUtil.mul(cart_item_unit_sp, cart_cart_quantity)); - pulse_gift_cart_list.add(pulse_gift_cart); + pulseGiftCart.put("subtotal", NumberUtil.mul(cartItemSalePrice, cartCartQuantity)); + pulseGiftCart.put("points_subtotal", NumberUtil.mul(cartItemUnitPoints, cartCartQuantity)); + pulseGiftCart.put("sp_subtotal", NumberUtil.mul(cartItemUnitSp, cartCartQuantity)); + pulseGiftCartList.add(pulseGiftCart); } - item_row.put("pulse_gift_cart", pulse_gift_cart_list); + productItemInStore.put("pulse_gift_cart", pulseGiftCartList); } - // 活动满减 - List pulse_reductions = (List) item_row.get("pulse_reduction"); - Integer activity_id = null; - for (Map pulse_reduction : pulse_reductions) { - activity_id = (Integer) pulse_reduction.get("activity_id"); + List pulseReductions = (List) productItemInStore.get("pulse_reduction"); + Integer activityId = null; + for (Map pulseReduction : pulseReductions) { + activityId = (Integer) pulseReduction.get("activity_id"); } //当前店铺活动信息 //List activity_row_list = (List) ObjectUtil.defaultIfNull(activity_info.get(store_id), new ArrayList<>()); - if (CollUtil.isNotEmpty(pulse_reductions)) { - item_row.put("show_typename", shopBaseStateCodeService.getText(StateCode.ACTIVITY_TYPE_REDUCTION, null)); + if (CollUtil.isNotEmpty(pulseReductions)) { + productItemInStore.put("show_typename", shopBaseStateCodeService.getText(StateCode.ACTIVITY_TYPE_REDUCTION, null)); //重置防止累加 - Map pulse_discount_items = (Map) store_row.get("pulse_discount_items"); - pulse_discount_items.put("pulse_reduction", BigDecimal.ZERO); + Map pulseDiscountItemsMap = (Map) storeInfo.get("pulse_discount_items"); + pulseDiscountItemsMap.put("pulse_reduction", BigDecimal.ZERO); - for (Map pulse_reduction : pulse_reductions) { - /* - //活动等级判断 - Integer c_activity_id = (Integer) pulse_reduction.get("activity_id"); - Optional defaultOpl = activity_row_list.stream().filter(s -> ObjectUtil.equal(c_activity_id, Convert.toInt(s.get("activity_id")))).findFirst(); - if (defaultOpl.isPresent()) { - Map activity_row = defaultOpl.get(); - } else { - } */ + for (Map pulseReduction : pulseReductions) { + /* + //活动等级判断 + Integer c_activity_id = (Integer) pulse_reduction.get("activity_id"); + Optional defaultOpl = activity_row_list.stream().filter(s -> ObjectUtil.equal(c_activity_id, Convert.toInt(s.get("activity_id")))).findFirst(); + if (defaultOpl.isPresent()) { + Map activity_row = defaultOpl.get(); + } else { + } */ - BigDecimal activityDiscountMoney = Convert.toBigDecimal(store_row.get("activityDiscountMoney")); - BigDecimal reduceMoney = Convert.toBigDecimal(pulse_reduction.get("reduceMoney")); - BigDecimal subtotal = Convert.toBigDecimal(item_row.get("subtotal")); + BigDecimal activityDiscountMoney = Convert.toBigDecimal(storeInfo.get("activityDiscountMoney")); + BigDecimal reduceMoney = Convert.toBigDecimal(pulseReduction.get("reduceMoney")); + BigDecimal subtotalValue = Convert.toBigDecimal(productItemInStore.get("subtotal")); - store_row.put("activityDiscountMoney", NumberUtil.add(activityDiscountMoney, reduceMoney)); - item_row.put("subtotal", NumberUtil.sub(subtotal, reduceMoney)); + storeInfo.put("activityDiscountMoney", NumberUtil.add(activityDiscountMoney, reduceMoney)); + productItemInStore.put("subtotal", NumberUtil.sub(subtotalValue, reduceMoney)); - BigDecimal pulse_reduction_tmp = Convert.toBigDecimal(pulse_discount_items.get("pulse_reduction")); - pulse_discount_items.put("pulse_reduction", NumberUtil.add(pulse_reduction_tmp, reduceMoney)); + BigDecimal pulseReductionTmp = Convert.toBigDecimal(pulseDiscountItemsMap.get("pulse_reduction")); + pulseDiscountItemsMap.put("pulse_reduction", NumberUtil.add(pulseReductionTmp, reduceMoney)); } } //多件折 //店铺活动汇总 - List act_multple = (List) ObjectUtil.defaultIfNull(activitys.get("multple"), new ArrayList()); - List pulse_multples = (List) item_row.get("pulse_multple"); + List actMultple = (List) ObjectUtil.defaultIfNull(storeActivities.get("multple"), new ArrayList()); + List pulseMultples = (List) productItemInStore.get("pulse_multple"); - - for (Map pulse_multple : pulse_multples) { - activity_id = (Integer) pulse_multple.get("activity_id"); + for (Map pulseMultple : pulseMultples) { + activityId = (Integer) pulseMultple.get("activity_id"); } - if (CollUtil.isNotEmpty(pulse_multples)) { + if (CollUtil.isNotEmpty(pulseMultples)) { - item_row.put("show_typename", shopBaseStateCodeService.getText(StateCode.ACTIVITY_TYPE_MULTIPLE_FOLD, null)); + productItemInStore.put("show_typename", shopBaseStateCodeService.getText(StateCode.ACTIVITY_TYPE_MULTIPLE_FOLD, null)); //start 计算商品折扣值 - for (Map pulse_multple : pulse_multples) { + for (Map pulseMultple : pulseMultples) { //计算此活动商品数量 - Integer tmp_activity_id = (Integer) pulse_multple.get("activity_id"); + Integer tmpActivityId = (Integer) pulseMultple.get("activity_id"); + BigDecimal itemMultipleQuantity = storeProductItems.stream().filter(s -> { + Boolean cartSelectTmp = Convert.toBool(s.get("cart_select")); + Boolean isOnSaleTmp = Convert.toBool(s.get("is_on_sale")); - BigDecimal item_multple_quantity = items.stream().filter(s -> { - Boolean cart_select_tmp = Convert.toBool(s.get("cart_select")); - Boolean is_on_sale_tmp = Convert.toBool(s.get("is_on_sale")); - - if (cart_select_tmp && is_on_sale_tmp) { - List tmp_pulse_multples = (List) s.get("pulse_multple"); - if (CollUtil.isNotEmpty(tmp_pulse_multples)) { - Integer act_id = (Integer) tmp_pulse_multples.get(0).get("activity_id"); - return act_id.equals(tmp_activity_id); + if (cartSelectTmp && isOnSaleTmp) { + List tmpPulseMultples = (List) s.get("pulse_multple"); + if (CollUtil.isNotEmpty(tmpPulseMultples)) { + Integer actId = (Integer) tmpPulseMultples.get(0).get("activity_id"); + return actId.equals(tmpActivityId); } } @@ -1792,25 +1870,24 @@ public class ShopUserCartServiceImpl extends BaseServiceImpl rule_row = (List) activity_rule_map.get("rule"); + Map activityRuleMap = (Map) pulseMultple.get("activity_rule"); + List ruleRow = (List) activityRuleMap.get("rule"); //循环规则,取一个满减最大值。 - if (rule_row.size() > 0) { - BigDecimal max_multple_quantity = BigDecimal.ZERO; //多件折数量 - BigDecimal max_multple_rate = BigDecimal.ZERO; //多件折数量 - Boolean give_enable = false; //是否有达成额度 + if (ruleRow.size() > 0) { + BigDecimal maxMultipleQuantity = BigDecimal.ZERO; //多件折数量 + BigDecimal maxMultipleRate = BigDecimal.ZERO; //多件折数量 + Boolean giveEnable = false; //是否有达成额度 - for (Map item : rule_row) { + for (Map itemRule : ruleRow) { //参与的商品数量满足 - BigDecimal tmp_max_num = Convert.toBigDecimal(item.get("total")); - BigDecimal tmp_rate = Convert.toBigDecimal(item.get("max_num")); + BigDecimal tmpMaxNum = Convert.toBigDecimal(itemRule.get("total")); + BigDecimal tmpRate = Convert.toBigDecimal(itemRule.get("max_num")); - if (item_multple_quantity.compareTo(tmp_max_num) >= 0) { - if (tmp_max_num.compareTo(max_multple_quantity) > 0) { - max_multple_quantity = tmp_max_num; - max_multple_rate = tmp_rate; + if (itemMultipleQuantity.compareTo(tmpMaxNum) >= 0) { + if (tmpMaxNum.compareTo(maxMultipleQuantity) > 0) { + maxMultipleQuantity = tmpMaxNum; + maxMultipleRate = tmpRate; } else { } } else { @@ -1818,59 +1895,58 @@ public class ShopUserCartServiceImpl extends BaseServiceImpl 0; + giveEnable = maxMultipleQuantity.compareTo(BigDecimal.ZERO) > 0; - pulse_multple.put("give_enable", give_enable); + pulseMultple.put("give_enable", giveEnable); } } //end 计算商品折扣值 - Map pulse_discount_items = (Map) store_row.get("pulse_discount_items"); + Map pulseDiscountItemsMap = (Map) storeInfo.get("pulse_discount_items"); - for (Map pulse_multple : pulse_multples) { - boolean give_enable = (boolean) pulse_multple.get("give_enable"); - if (give_enable) { - BigDecimal max_multple_rate = Convert.toBigDecimal(pulse_multple.get("max_multple_rate")); - BigDecimal max_multple_rate_num = NumberUtil.div(max_multple_rate, 100); - BigDecimal max_multple_discount_num = BigDecimal.ONE.subtract(max_multple_rate_num); - BigDecimal discount_sale_money = item_sale_price.multiply(max_multple_discount_num); - BigDecimal reduceMoney = discount_sale_money.multiply(Convert.toBigDecimal(cart_quantity)); - item_sale_price = item_sale_price.multiply(max_multple_rate_num); - BigDecimal subtotal = Convert.toBigDecimal(item_row.get("subtotal")); - - BigDecimal item_discount_amount_old = Convert.toBigDecimal(item_row.get("item_discount_amount")); + for (Map pulseMultple : pulseMultples) { + boolean giveEnable = (boolean) pulseMultple.get("give_enable"); + if (giveEnable) { + BigDecimal maxMultipleRate = Convert.toBigDecimal(pulseMultple.get("max_multple_rate")); + BigDecimal maxMultipleRateNum = NumberUtil.div(maxMultipleRate, 100); + BigDecimal maxMultipleDiscountNum = BigDecimal.ONE.subtract(maxMultipleRateNum); + BigDecimal discountSaleMoney = itemSalePrice.multiply(maxMultipleDiscountNum); + BigDecimal reduceMoney = discountSaleMoney.multiply(Convert.toBigDecimal(cartQuantity)); + itemSalePrice = itemSalePrice.multiply(maxMultipleRateNum); + BigDecimal subtotalValue = Convert.toBigDecimal(productItemInStore.get("subtotal")); + BigDecimal itemDiscountAmountOld = Convert.toBigDecimal(productItemInStore.get("item_discount_amount")); //item_row.put("show_typename", shopBaseStateCodeService.getText(StateCode.ACTIVITY_TYPE_MULTIPLE_FOLD, null)); - item_row.put("item_sale_price", item_sale_price); - item_row.put("discount_sale_money", discount_sale_money); - item_row.put("item_discount_amount", NumberUtil.add(item_discount_amount_old, reduceMoney)); - item_row.put("subtotal", NumberUtil.sub(subtotal, reduceMoney)); + productItemInStore.put("item_sale_price", itemSalePrice); + productItemInStore.put("discount_sale_money", discountSaleMoney); + productItemInStore.put("item_discount_amount", NumberUtil.add(itemDiscountAmountOld, reduceMoney)); + productItemInStore.put("subtotal", NumberUtil.sub(subtotalValue, reduceMoney)); - store_total = store_total.subtract(reduceMoney); + storeTotalAmount = storeTotalAmount.subtract(reduceMoney); - pulse_multple.put("multple", reduceMoney); + pulseMultple.put("multple", reduceMoney); //店铺汇总 - Integer tmp_activity_id = (Integer) pulse_multple.get("activity_id"); - for (Map multple_row : act_multple) { - Integer act_id = (Integer) multple_row.get("activity_id"); - if (act_id.equals(tmp_activity_id)) { + Integer tmpActivityId = (Integer) pulseMultple.get("activity_id"); + for (Map multpleRow : actMultple) { + Integer actId = (Integer) multpleRow.get("activity_id"); + if (actId.equals(tmpActivityId)) { // - BigDecimal pulse_multple_tmp = Convert.toBigDecimal(pulse_discount_items.get("pulse_multple")); - pulse_discount_items.put("pulse_multple", NumberUtil.add(pulse_multple_tmp, reduceMoney)); + BigDecimal pulseMultpleTmp = Convert.toBigDecimal(pulseDiscountItemsMap.get("pulse_multple")); + pulseDiscountItemsMap.put("pulse_multple", NumberUtil.add(pulseMultpleTmp, reduceMoney)); - multple_row.put("reduceMoney", NumberUtil.add(reduceMoney, Convert.toBigDecimal(multple_row.get("reduceMoney"), BigDecimal.ZERO))); - multple_row.put("activity_quantity", pulse_multple.get("activity_quantity")); - multple_row.put("max_multple_quantity", pulse_multple.get("max_multple_quantity")); //购买生效数量 - multple_row.put("max_multple_rate", max_multple_rate); //折扣比率 - multple_row.put("give_enable", give_enable); + multpleRow.put("reduceMoney", NumberUtil.add(reduceMoney, Convert.toBigDecimal(multpleRow.get("reduceMoney"), BigDecimal.ZERO))); + multpleRow.put("activity_quantity", pulseMultple.get("activity_quantity")); + multpleRow.put("max_multple_quantity", pulseMultple.get("max_multple_quantity")); //购买生效数量 + multpleRow.put("max_multple_rate", maxMultipleRate); //折扣比率 + multpleRow.put("give_enable", giveEnable); - store_row.put("pulseActivityDiscountMoney", NumberUtil.add(Convert.toBigDecimal(store_row.get("pulseActivityDiscountMoney")), reduceMoney)); + storeInfo.put("pulseActivityDiscountMoney", NumberUtil.add(Convert.toBigDecimal(storeInfo.get("pulseActivityDiscountMoney")), reduceMoney)); } } } @@ -1879,53 +1955,53 @@ public class ShopUserCartServiceImpl extends BaseServiceImpl pulse_bargains_cart_list = (List) item_row.get("pulse_bargains_cart"); - List pulse_bargains_carts = new ArrayList(); - if (CollUtil.isNotEmpty(pulse_bargains_cart_list)) { - item_row.put("show_typename", shopBaseStateCodeService.getText(StateCode.ACTIVITY_TYPE_BARGAIN, null)); + List pulseBargainsCartList = (List) productItemInStore.get("pulse_bargains_cart"); + List pulseBargainsCarts = new ArrayList(); + if (CollUtil.isNotEmpty(pulseBargainsCartList)) { + productItemInStore.put("show_typename", shopBaseStateCodeService.getText(StateCode.ACTIVITY_TYPE_BARGAIN, null)); - for (Map pulse_bargains_cart : pulse_bargains_cart_list) { + for (Map pulseBargainsCart : pulseBargainsCartList) { - BigDecimal cart_item_sale_price = Convert.toBigDecimal(pulse_bargains_cart.get("item_sale_price")); - BigDecimal cart_item_unit_points = Convert.toBigDecimal(pulse_bargains_cart.get("item_unit_points")); - BigDecimal cart_item_unit_sp = Convert.toBigDecimal(pulse_bargains_cart.get("item_unit_sp")); - Integer cart_cart_quantity = Convert.toInt(pulse_bargains_cart.get("cart_quantity")); + BigDecimal cartItemSalePrice = Convert.toBigDecimal(pulseBargainsCart.get("item_sale_price")); + BigDecimal cartItemUnitPoints = Convert.toBigDecimal(pulseBargainsCart.get("item_unit_points")); + BigDecimal cartItemUnitSp = Convert.toBigDecimal(pulseBargainsCart.get("item_unit_sp")); + Integer cartCartQuantity = Convert.toInt(pulseBargainsCart.get("cart_quantity")); - if (cart_select && is_on_sale) { - Boolean pulse_cart_select = Convert.toBool(pulse_bargains_cart.get("cart_select")); - Boolean pulse_is_on_sale = Convert.toBool(pulse_bargains_cart.get("is_on_sale")); - if (pulse_cart_select && pulse_is_on_sale) { - pulse_bargains_cart.put("subtotal", NumberUtil.mul(cart_item_sale_price, cart_cart_quantity)); - pulse_bargains_cart.put("points_subtotal", NumberUtil.mul(cart_item_unit_points, cart_cart_quantity)); - pulse_bargains_cart.put("sp_subtotal", NumberUtil.mul(cart_item_unit_sp, cart_cart_quantity)); + if (cartSelect && isOnSale) { + Boolean pulseCartSelect = Convert.toBool(pulseBargainsCart.get("cart_select")); + Boolean pulseIsOnSale = Convert.toBool(pulseBargainsCart.get("is_on_sale")); + if (pulseCartSelect && pulseIsOnSale) { + pulseBargainsCart.put("subtotal", NumberUtil.mul(cartItemSalePrice, cartCartQuantity)); + pulseBargainsCart.put("points_subtotal", NumberUtil.mul(cartItemUnitPoints, cartCartQuantity)); + pulseBargainsCart.put("sp_subtotal", NumberUtil.mul(cartItemUnitSp, cartCartQuantity)); } else { - pulse_bargains_cart.put("subtotal", BigDecimal.ZERO); - pulse_bargains_cart.put("points_subtotal", BigDecimal.ZERO); - pulse_bargains_cart.put("sp_subtotal", BigDecimal.ZERO); + pulseBargainsCart.put("subtotal", BigDecimal.ZERO); + pulseBargainsCart.put("points_subtotal", BigDecimal.ZERO); + pulseBargainsCart.put("sp_subtotal", BigDecimal.ZERO); } - Long item_id = Convert.toLong(pulse_bargains_cart.get("item_id")); - ids.add(item_id); + Long itemId = Convert.toLong(pulseBargainsCart.get("item_id")); + selectedIds.add(itemId); - Integer transport_type_id = Convert.toInt(pulse_bargains_cart.get("transport_type_id")); - BigDecimal sum = Convert.toBigDecimal(tt_ids.get(transport_type_id)); - tt_ids.put(transport_type_id, NumberUtil.add(cart_cart_quantity, sum)); + Integer transportTypeId = Convert.toInt(pulseBargainsCart.get("transport_type_id")); + BigDecimal sum = Convert.toBigDecimal(transportTypeQuantities.get(transportTypeId)); + transportTypeQuantities.put(transportTypeId, NumberUtil.add(cartCartQuantity, sum)); // 修正价格策略影响 - fixPricePolicy(pulse_bargains_cart, customer_level_id, user_level_id); + fixPricePolicy(pulseBargainsCart, customerLevelId, userLevelId); //pulse_bargains_carts.add(pulse_bargains_cart); - BigDecimal subtotal = Convert.toBigDecimal(pulse_bargains_cart.get("subtotal")); - store_total = NumberUtil.add(subtotal, store_total); + BigDecimal subtotalValue = Convert.toBigDecimal(pulseBargainsCart.get("subtotal")); + storeTotalAmount = NumberUtil.add(subtotalValue, storeTotalAmount); - BigDecimal points_subtotal = Convert.toBigDecimal(pulse_bargains_cart.get("points_subtotal")); - store_points_total = NumberUtil.add(points_subtotal, store_points_total); + BigDecimal pointsSubtotal = Convert.toBigDecimal(pulseBargainsCart.get("points_subtotal")); + storePointsAmount = NumberUtil.add(pointsSubtotal, storePointsAmount); - BigDecimal sp_subtotal = Convert.toBigDecimal(pulse_bargains_cart.get("sp_subtotal")); - store_sp_total = NumberUtil.add(sp_subtotal, store_sp_total); + BigDecimal spSubtotal = Convert.toBigDecimal(pulseBargainsCart.get("sp_subtotal")); + storePromotionAmount = NumberUtil.add(spSubtotal, storePromotionAmount); //pulse_bargains_carts.add(pulse_bargains_cart); - store_origin_total = NumberUtil.add(store_origin_total, subtotal); + storeOriginalAmount = NumberUtil.add(storeOriginalAmount, subtotalValue); } } @@ -1934,100 +2010,98 @@ public class ShopUserCartServiceImpl extends BaseServiceImpl reduction = (List) ObjectUtil.defaultIfNull(activitys.get("reduction"), new ArrayList()); + List reductionList = (List) ObjectUtil.defaultIfNull(storeActivities.get("reduction"), new ArrayList()); - for (Map reduction_row : reduction) { - BigDecimal activityDiscountMoney = Convert.toBigDecimal(store_row.get("activityDiscountMoney")); - BigDecimal reduceMoney = Convert.toBigDecimal(reduction_row.get("reduceMoney")); - store_row.put("activityDiscountMoney", NumberUtil.add(activityDiscountMoney, reduceMoney)); + for (Map reductionRow : reductionList) { + BigDecimal activityDiscountMoney = Convert.toBigDecimal(storeInfo.get("activityDiscountMoney")); + BigDecimal reduceMoney = Convert.toBigDecimal(reductionRow.get("reduceMoney")); + storeInfo.put("activityDiscountMoney", NumberUtil.add(activityDiscountMoney, reduceMoney)); //分到组后一个商品上 - /*Map item_row = items.get(items.size() - 1); - BigDecimal subtotal = Convert.toBigDecimal(item_row.get("subtotal")); + /*Map item_row = items.get(items.size() - 1); + BigDecimal subtotal = Convert.toBigDecimal(item_row.get("subtotal")); - item_row.put("subtotal", NumberUtil.sub(subtotal, reduceMoney));*/ + item_row.put("subtotal", NumberUtil.sub(subtotal, reduceMoney));*/ //循环判断商品,修正商品subtotal - List item_ids = Convert.toList(Long.class, reduction_row.get("item_ids")); - for (Map item_row : items) { - if (item_ids.contains(Convert.toLong(item_row.get("item_id")))) { - BigDecimal subtotal = Convert.toBigDecimal(item_row.get("subtotal")); - BigDecimal reduce_money = Convert.toBigDecimal(item_row.get("reduceMoney")); - item_row.put("subtotal", NumberUtil.sub(subtotal, reduce_money)); + List reductionItemIds = Convert.toList(Long.class, reductionRow.get("item_ids")); + for (Map productItemInStore : storeProductItems) { + if (reductionItemIds.contains(Convert.toLong(productItemInStore.get("item_id")))) { + BigDecimal subtotalValue = Convert.toBigDecimal(productItemInStore.get("subtotal")); + BigDecimal reduceMoneyValue = Convert.toBigDecimal(productItemInStore.get("reduceMoney")); + productItemInStore.put("subtotal", NumberUtil.sub(subtotalValue, reduceMoneyValue)); } } } - - /*if(activity_row["activity_type_id"] == StateCode.ACTIVITY_TYPE_GIFTBAG && activity_row && activity_row["store_id"] && activity_row["store_id"] == store_row["store_id"]) - { - store_row["activitys"]["giftbag"] = activity_row; - }*/ + /*if(activity_row["activity_type_id"] == StateCode.ACTIVITY_TYPE_GIFTBAG && activity_row && activity_row["store_id"] && activity_row["store_id"] == store_row["store_id"]) + { + store_row["activitys"]["giftbag"] = activity_row; + }*/ //多件折 - List multple = (List) ObjectUtil.defaultIfNull(activitys.get("multple"), new ArrayList()); - BigDecimal multple_tmp = Convert.toBigDecimal(discount_items.get("multple")); + List multipleList = (List) ObjectUtil.defaultIfNull(storeActivities.get("multple"), new ArrayList()); + BigDecimal multipleTmp = Convert.toBigDecimal(discountItems.get("multple")); - for (Map multple_row : multple) { - multple_tmp = NumberUtil.add(multple_tmp, Convert.toBigDecimal(multple_row.get("reduceMoney"))); + for (Map multipleRow : multipleList) { + multipleTmp = NumberUtil.add(multipleTmp, Convert.toBigDecimal(multipleRow.get("reduceMoney"))); } - discount_items.put("multple", multple_tmp); + discountItems.put("multple", multipleTmp); //store_row.put("activityDiscountMoney", NumberUtil.add(Convert.toBigDecimal(store_row.get("activityDiscountMoney")), multple_tmp)); // 组合套餐 - List giftbags = (List) ObjectUtil.defaultIfNull(activitys.get("giftbag"), new ArrayList()); + List giftbags = (List) ObjectUtil.defaultIfNull(storeActivities.get("giftbag"), new ArrayList()); if (CollUtil.isNotEmpty(giftbags)) { //套餐总优惠 - BigDecimal giftbag_tmp = Convert.toBigDecimal(discount_items.get("giftbag")); + BigDecimal giftbagTmp = Convert.toBigDecimal(discountItems.get("giftbag")); - for (Map multple_row : giftbags) { - giftbag_tmp = NumberUtil.add(giftbag_tmp, Convert.toInt(multple_row.get("reduceMoney"))); - List item_ids = (List) multple_row.get("item_ids"); + for (Map multipleRow : giftbags) { + giftbagTmp = NumberUtil.add(giftbagTmp, Convert.toInt(multipleRow.get("reduceMoney"))); + List itemIdsList = (List) multipleRow.get("item_ids"); //循环判断商品,修正商品subtotal - for (Map item_row : items) { - if (item_ids.contains(Convert.toLong(item_row.get("item_id")))) { - BigDecimal subtotal = Convert.toBigDecimal(item_row.get("subtotal")); - BigDecimal reduceMoney = Convert.toBigDecimal(item_row.get("reduceMoney")); - BigDecimal giftbag_tc_num = Convert.toBigDecimal(item_row.get("giftbag_tc_num")); - - item_row.put("subtotal", NumberUtil.sub(subtotal, reduceMoney)); + for (Map productItemInStore : storeProductItems) { + if (itemIdsList.contains(Convert.toLong(productItemInStore.get("item_id")))) { + BigDecimal subtotalValue = Convert.toBigDecimal(productItemInStore.get("subtotal")); + BigDecimal reduceMoneyValue = Convert.toBigDecimal(productItemInStore.get("reduceMoney")); + BigDecimal giftbagTcNum = Convert.toBigDecimal(productItemInStore.get("giftbag_tc_num")); + productItemInStore.put("subtotal", NumberUtil.sub(subtotalValue, reduceMoneyValue)); //item_row.put("item_discount_amount", Convert.toBigDecimal(item_row.get("giftbag_discount_price"))); //item_row.put("discount_sale_money", reduceMoney); - store_total = store_total.subtract(reduceMoney); + storeTotalAmount = storeTotalAmount.subtract(reduceMoneyValue); } } } - discount_items.put("giftbag", giftbag_tmp); - store_row.put("pulseActivityDiscountMoney", NumberUtil.add(Convert.toBigDecimal(store_row.get("pulseActivityDiscountMoney")), giftbag_tmp)); + discountItems.put("giftbag", giftbagTmp); + storeInfo.put("pulseActivityDiscountMoney", NumberUtil.add(Convert.toBigDecimal(storeInfo.get("pulseActivityDiscountMoney")), giftbagTmp)); } // 有满足折上折活动的 - List reduction_again = (List) ObjectUtil.defaultIfNull(activitys.get("reduction_again"), new ArrayList()); + List reductionAgainList = (List) ObjectUtil.defaultIfNull(storeActivities.get("reduction_again"), new ArrayList()); - if (CollUtil.isNotEmpty(reduction_again)) { + if (CollUtil.isNotEmpty(reductionAgainList)) { //计算参与活动商品付款总额,根据不同活动计算。 - Iterator it = reduction_again.iterator(); + Iterator it = reductionAgainList.iterator(); while (it.hasNext()) { - Map reduction_again_row = it.next(); + Map reductionAgainRow = it.next(); //计算此活动商品实付总额 - Integer tmp_activity_id = (Integer) reduction_again_row.get("activity_id"); - BigDecimal item_reduction_again_amount = items.stream().filter(s -> { - Boolean cart_select_tmp = Convert.toBool(s.get("cart_select")); - Boolean is_on_sale_tmp = Convert.toBool(s.get("is_on_sale")); + Integer tmpActivityId = (Integer) reductionAgainRow.get("activity_id"); + BigDecimal itemReductionAgainAmount = storeProductItems.stream().filter(s -> { + Boolean cartSelectTmp = Convert.toBool(s.get("cart_select")); + Boolean isOnSaleTmp = Convert.toBool(s.get("is_on_sale")); - if (cart_select_tmp && is_on_sale_tmp) { - List tmp_reduction_again = (List) s.get("pulse_reduction_again"); - if (CollUtil.isNotEmpty(tmp_reduction_again)) { - Integer act_id = (Integer) tmp_reduction_again.get(0).get("activity_id"); + if (cartSelectTmp && isOnSaleTmp) { + List tmpReductionAgain = (List) s.get("pulse_reduction_again"); + if (CollUtil.isNotEmpty(tmpReductionAgain)) { + Integer actId = (Integer) tmpReductionAgain.get(0).get("activity_id"); - return act_id.equals(tmp_activity_id); + return actId.equals(tmpActivityId); } } @@ -2036,21 +2110,20 @@ public class ShopUserCartServiceImpl extends BaseServiceImpl rule_row = (List) activity_rule_map.get("rule"); + Map activityRuleMap = (Map) reductionAgainRow.get("activity_rule"); + List ruleRow = (List) activityRuleMap.get("rule"); //循环规则,取一个满减最大值。 - if (rule_row.size() > 0) { - BigDecimal max_reduction_again = BigDecimal.ZERO; //折上折额度 - Boolean give_enable = false; //是否有达成额度 + if (ruleRow.size() > 0) { + BigDecimal maxReductionAgain = BigDecimal.ZERO; //折上折额度 + Boolean giveEnable = false; //是否有达成额度 - for (Map item : rule_row) { + for (Map itemRule : ruleRow) { //参与的商品额度满足 - if (item_reduction_again_amount.compareTo(Convert.toBigDecimal(item.get("total"))) >= 0) { - BigDecimal tmp_max_num = Convert.toBigDecimal(item.get("max_num")); - if (tmp_max_num.compareTo(max_reduction_again) > 0) { - max_reduction_again = tmp_max_num; + if (itemReductionAgainAmount.compareTo(Convert.toBigDecimal(itemRule.get("total"))) >= 0) { + BigDecimal tmpMaxNum = Convert.toBigDecimal(itemRule.get("max_num")); + if (tmpMaxNum.compareTo(maxReductionAgain) > 0) { + maxReductionAgain = tmpMaxNum; } else { } } else { @@ -2058,40 +2131,38 @@ public class ShopUserCartServiceImpl extends BaseServiceImpl 0) { - give_enable = true; - reduction_again_row.put("give_enable", give_enable); + if (maxReductionAgain.compareTo(BigDecimal.ZERO) > 0) { + giveEnable = true; + reductionAgainRow.put("give_enable", giveEnable); //预览折上折额度 - discount_items.put("reduction_again", max_reduction_again); - + discountItems.put("reduction_again", maxReductionAgain); //默认应该为全局订单折扣 //store_row.put("activityDiscountMoney", NumberUtil.add(Convert.toBigDecimal(store_row.get("activityDiscountMoney")), max_reduction_again)); //折上折单纯处理优惠显示 - 采用单品折扣显示 - store_row.put("pulseActivityDiscountMoney", NumberUtil.add(Convert.toBigDecimal(store_row.get("pulseActivityDiscountMoney")), max_reduction_again)); + storeInfo.put("pulseActivityDiscountMoney", NumberUtil.add(Convert.toBigDecimal(storeInfo.get("pulseActivityDiscountMoney")), maxReductionAgain)); //采用单品折扣显示, 这修正订单数据 - store_total = store_total.subtract(max_reduction_again); + storeTotalAmount = storeTotalAmount.subtract(maxReductionAgain); + Map activityItemInfo = new HashMap<>(); - Map activity_item_info = new HashMap<>(); + activityItemInfo.put("item_ids", reductionAgainRow.get("item_ids")); + activityItemInfo.put("type_id", reductionAgainRow.get("activity_type_id")); + activityItemInfo.put("type", "reduction_again"); + activityItemInfo.put("old_amount", itemReductionAgainAmount); + activityItemInfo.put("amount", itemReductionAgainAmount.subtract(maxReductionAgain)); + activityItemInfo.put("discount", maxReductionAgain); - activity_item_info.put("item_ids", reduction_again_row.get("item_ids")); - activity_item_info.put("type_id", reduction_again_row.get("activity_type_id")); - activity_item_info.put("type", "reduction_again"); - activity_item_info.put("old_amount", item_reduction_again_amount); - activity_item_info.put("amount", item_reduction_again_amount.subtract(max_reduction_again)); - activity_item_info.put("discount", max_reduction_again); - - discount_detail_rows.add(activity_item_info); + discountDetailRows.add(activityItemInfo); } else { - give_enable = false; - reduction_again_row.put("give_enable", give_enable); + giveEnable = false; + reductionAgainRow.put("give_enable", giveEnable); //不删除,可以做提示 //it.remove(); @@ -2104,29 +2175,29 @@ public class ShopUserCartServiceImpl extends BaseServiceImpl manhui = (List) ObjectUtil.defaultIfNull(activitys.get("manhui"), new ArrayList()); - if (CollUtil.isNotEmpty(manhui)) { + List manhuiList = (List) ObjectUtil.defaultIfNull(storeActivities.get("manhui"), new ArrayList()); + if (CollUtil.isNotEmpty(manhuiList)) { //计算参与活动商品付款总额,根据不同活动计算。 //单品参与活动 - Map act_item_amount = new HashMap<>(); + Map actItemAmount = new HashMap<>(); - Iterator it = manhui.iterator(); + Iterator it = manhuiList.iterator(); while (it.hasNext()) { - Map manhui_row = it.next(); + Map manhuiRow = it.next(); //计算此活动商品实付总额 - Integer tmp_activity_id = (Integer) manhui_row.get("activity_id"); - BigDecimal item_manfan_amount = items.stream().filter(s -> { - Boolean cart_select_tmp = Convert.toBool(s.get("cart_select")); - Boolean is_on_sale_tmp = Convert.toBool(s.get("is_on_sale")); + Integer tmpActivityId = (Integer) manhuiRow.get("activity_id"); + BigDecimal itemManfanAmount = storeProductItems.stream().filter(s -> { + Boolean cartSelectTmp = Convert.toBool(s.get("cart_select")); + Boolean isOnSaleTmp = Convert.toBool(s.get("is_on_sale")); - if (cart_select_tmp && is_on_sale_tmp) { - List tmp_manhui = (List) s.get("pulse_manhui"); - if (CollUtil.isNotEmpty(tmp_manhui)) { - Integer act_id = (Integer) tmp_manhui.get(0).get("activity_id"); + if (cartSelectTmp && isOnSaleTmp) { + List tmpManhui = (List) s.get("pulse_manhui"); + if (CollUtil.isNotEmpty(tmpManhui)) { + Integer actId = (Integer) tmpManhui.get(0).get("activity_id"); - return act_id.equals(tmp_activity_id); + return actId.equals(tmpActivityId); } } @@ -2135,45 +2206,44 @@ public class ShopUserCartServiceImpl extends BaseServiceImpl ruleRow = (List) activityRuleMap.get("rule"); - Map activity_rule_map = (Map) manhui_row.get("activity_rule"); - List rule_row = (List) activity_rule_map.get("rule"); + if (ruleRow.size() > 0) { + Boolean giveEnable = false; //是否有达成额度 + Boolean removeFlag = true; - if (rule_row.size() > 0) { - Boolean give_enable = false; //是否有达成额度 - Boolean remove_flag = true; - - for (Map item : rule_row) { + for (Map itemRule : ruleRow) { //添加满返优惠券信息 max_num为获取优惠券活动编号give_id //不满足条件的商品活动移除 //if (NumberUtil.sub(store_total, Convert.toBigDecimal(store_row.get("activityDiscountMoney")), Convert.toBigDecimal(store_row.get("pulseActivityDiscountMoney"))).compareTo(Convert.toBigDecimal(item.get("total"))) >= 0) { //参与的商品额度满足 - if (item_manfan_amount.compareTo(Convert.toBigDecimal(item.get("total"))) >= 0) { + if (itemManfanAmount.compareTo(Convert.toBigDecimal(itemRule.get("total"))) >= 0) { //todo 此处判断移入活动数据初始化中 - if (CheckUtil.isNotEmpty(Convert.toInt(item.get("max_num")))) { - ShopStoreActivityBase tmp = shopStoreActivityBaseService.get(Convert.toInt(item.get("max_num"))); + if (CheckUtil.isNotEmpty(Convert.toInt(itemRule.get("max_num")))) { + ShopStoreActivityBase tmp = shopStoreActivityBaseService.get(Convert.toInt(itemRule.get("max_num"))); if (tmp != null) { - com.alibaba.fastjson.JSONObject activity_rule = com.alibaba.fastjson.JSONObject.parseObject(tmp.getActivity_rule()); + com.alibaba.fastjson.JSONObject activityRule = com.alibaba.fastjson.JSONObject.parseObject(tmp.getActivity_rule()); //不复用活动结构,无give_id==优惠券编号, 则不满足条件。 - manhui_row.put("give_id", tmp.getActivity_id()); - manhui_row.put("give_name", tmp.getActivity_name()); - manhui_row.put("give_image", activity_rule.get("voucher_image")); - manhui_row.put("give_row", activity_rule); - manhui_row.put("give_enable", true); + manhuiRow.put("give_id", tmp.getActivity_id()); + manhuiRow.put("give_name", tmp.getActivity_name()); + manhuiRow.put("give_image", activityRule.get("voucher_image")); + manhuiRow.put("give_row", activityRule); + manhuiRow.put("give_enable", true); - give_enable = true; - remove_flag = false; + giveEnable = true; + removeFlag = false; } else { //异常数据,删除活动 -- 多个商品,其中包含错误,会导致此活动无效 - remove_flag = true; + removeFlag = true; break; } } else { //异常数据,删除活动 -- 多个商品,其中包含错误,会导致此活动无效 - remove_flag = true; + removeFlag = true; break; } } else { @@ -2181,7 +2251,7 @@ public class ShopUserCartServiceImpl extends BaseServiceImpl Convert.toBigDecimal(s.get("policy_discount_amount"), BigDecimal.ZERO)).reduce(BigDecimal::add).get(); - store_row.put("policy_discount_amount", policy_discount_amount); + BigDecimal policyDiscountAmount = storeProductItems.stream().map(s -> Convert.toBigDecimal(s.get("policy_discount_amount"), BigDecimal.ZERO)).reduce(BigDecimal::add).get(); + storeInfo.put("policy_discount_amount", policyDiscountAmount); //单品活动累加优惠总额 - BigDecimal pulseActivityDiscountMoney = Convert.toBigDecimal(store_row.get("pulseActivityDiscountMoney")); + BigDecimal pulseActivityDiscountMoney = Convert.toBigDecimal(storeInfo.get("pulseActivityDiscountMoney")); //店铺订单活动总额度 = 店铺全局优惠 + 单品优惠 - BigDecimal order_activity_discount_amount = NumberUtil.add(activityDiscountMoney, pulseActivityDiscountMoney); + BigDecimal orderActivityDiscountAmount = NumberUtil.add(activityDiscountMoney, pulseActivityDiscountMoney); //店铺订单总优惠额度 = 店铺全局优惠 + 单品优惠 + (会员等级)价格策略折扣 - BigDecimal order_discount_amount = NumberUtil.add(order_activity_discount_amount, policy_discount_amount); + BigDecimal orderDiscountAmount = NumberUtil.add(orderActivityDiscountAmount, policyDiscountAmount); - store_row.put("productMoney", 0); - store_row.put("orderMoney", 0); - store_row.put("productMoneySelGoods", NumberUtil.sub(store_total, activityDiscountMoney)); - store_row.put("productMoneyOriginGoods", store_origin_total); - store_row.put("productPointsSel", store_points_total); - store_row.put("productSpSel", store_sp_total); - store_row.put("order_money_select_items", NumberUtil.sub(store_total, activityDiscountMoney)); + boolean isVirtualOrder = false; + if (CollUtil.isNotEmpty(cartItems)) { + Map firstItem = cartItems.get(0); + Boolean isVirtual = Convert.toBool(firstItem.get("is_virtual"), false); + isVirtualOrder = cartItems.size() == 1 && isVirtual; + } - // 店铺订单打包费 - // store_row.put("packing_fee", packingFee); + // 店铺的打包费 + logger.info("开始确认店铺打包费"); + BigDecimal packingFee = getStorePackingFee(storeId, isVirtualOrder, Convert.toInt(storeInfo.get("delivery_type_id"))); // 商家打包费 + storeInfo.put("packing_fee", packingFee); + + storeInfo.put("productMoney", 0); + storeInfo.put("orderMoney", 0); + storeInfo.put("productMoneySelGoods", NumberUtil.sub(storeTotalAmount, activityDiscountMoney)); + storeInfo.put("productMoneyOriginGoods", storeOriginalAmount); + storeInfo.put("productPointsSel", storePointsAmount); + storeInfo.put("productSpSel", storePromotionAmount); + + // 店铺订单金额 = 商品金额 + 打包费 + BigDecimal orderMoneySelectItems = NumberUtil.add(NumberUtil.sub(storeTotalAmount, activityDiscountMoney), packingFee); + storeInfo.put("order_money_select_items", orderMoneySelectItems); //BigDecimal item_discount_amount_sum = items.stream().map(s -> Convert.toBigDecimal(s.get("item_discount_amount"), BigDecimal.ZERO)).reduce(BigDecimal::add).get(); //item_discount_amount 数据实时放入 activityDiscountMoney, pulseActivityDiscountMoney 中。 不重叠放入。二选一。 //店铺订单活动总额度 = 店铺全局优惠 + 单品优惠 - store_row.put("order_activity_discount_amount", order_activity_discount_amount); + storeInfo.put("order_activity_discount_amount", orderActivityDiscountAmount); // 店铺订单总优惠额度 = 店铺全局优惠 + 单品优惠 + (会员等级)价格策略折扣 - store_row.put("order_discount_amount", order_discount_amount); - store_row.put("postFree", true); // 是否免运费 - store_row.put("freight", 0); // 运费金额 - store_row.put("postFreeBalance", 0); // 还需postFreeBalance元即可免邮费 - store_row.put("activity_discount_amount", order_activity_discount_amount); - + storeInfo.put("order_discount_amount", orderDiscountAmount); + storeInfo.put("postFree", true); // 是否免运费 + storeInfo.put("freight", 0); // 运费金额 + storeInfo.put("postFreeBalance", 0); // 还需postFreeBalance元即可免邮费 + storeInfo.put("activity_discount_amount", orderActivityDiscountAmount); // 关键订单金额数据 - orderSelProductAmount = orderSelProductAmount.add(store_origin_total); - orderSelFreightAmount = orderSelFreightAmount.add(Convert.toBigDecimal(store_row.get("freight"))); // 重要:订单运费金额 - orderSelMoneyAmount = orderSelMoneyAmount.add(Convert.toBigDecimal(store_row.get("order_money_select_items")));// 重要:订单折后金额(订单金额-折扣金额) - orderDiscountAmount = orderDiscountAmount.add(Convert.toBigDecimal(store_row.get("order_discount_amount"))); // 重要:订单折扣金额 - orderSelPointsAmount = orderSelPointsAmount.add(store_points_total); - orderSelSpAmount = orderSelSpAmount.add(store_sp_total); - orderRebateAmount = orderRebateAmount.add(Convert.toBigDecimal(store_row.get("store_rebate"))); + totalOriginalAmount = totalOriginalAmount.add(storeOriginalAmount); + totalFreightAmount = totalFreightAmount.add(Convert.toBigDecimal(storeInfo.get("freight"))); // 重要:订单运费金额 + totalPaymentAmount = totalPaymentAmount.add(Convert.toBigDecimal(storeInfo.get("order_money_select_items")));// 重要:订单折后金额(订单金额-折扣金额),不包括运费 + totalDiscountAmount = totalDiscountAmount.add(Convert.toBigDecimal(storeInfo.get("order_discount_amount"))); // 重要:订单折扣金额 + totalPointsAmount = totalPointsAmount.add(storePointsAmount); + totalPromotionAmount = totalPromotionAmount.add(storePromotionAmount); + totalRebateAmount = totalRebateAmount.add(Convert.toBigDecimal(storeInfo.get("store_rebate"))); + + // 多个店铺总计打包费 + totalPackingFee = totalPackingFee.add(packingFee); } } - // 计算运费,根据配送地址计算。独立封装方法。 - data_rows.put("transportIds", allowTransportIds); - data_rows.put("orderSelProductAmount", orderSelProductAmount); - data_rows.put("orderSelFreightAmount", orderSelFreightAmount); - data_rows.put("orderSelMoneyAmount", orderSelMoneyAmount); - data_rows.put("orderDiscountAmount", orderDiscountAmount); - data_rows.put("orderSelPointsAmount", orderSelPointsAmount); - data_rows.put("orderSelSpAmount", orderSelSpAmount); - data_rows.put("order_rebate_amount", orderRebateAmount); + checkoutResult.put("transportIds", allowedTransportTypeIds); + checkoutResult.put("orderSelProductAmount", totalOriginalAmount); + checkoutResult.put("orderSelFreightAmount", totalFreightAmount); + checkoutResult.put("orderSelMoneyAmount", totalPaymentAmount); + checkoutResult.put("orderDiscountAmount", totalDiscountAmount); + checkoutResult.put("orderSelPointsAmount", totalPointsAmount); + checkoutResult.put("orderSelSpAmount", totalPromotionAmount); + checkoutResult.put("order_rebate_amount", totalRebateAmount); - if (CollUtil.isNotEmpty(store_rows)) { - data_rows.put("items", store_rows); + // 多个店铺总计打包费 + checkoutResult.put("totalPackingFee", totalPackingFee); + + if (CollUtil.isNotEmpty(storeInfoList)) { + checkoutResult.put("items", storeInfoList); } else { - data_rows.put("items", new ArrayList<>()); + checkoutResult.put("items", new ArrayList<>()); } // 可自提的门店信息 - List chain_info = CollUtil.isNotEmpty(chain_id_row) && ObjectUtil.isNotNull(chain_row) ? Convert.toList(chain_row) : new ArrayList<>(); - data_rows.put("chain_info", chain_info); + List chainInfoList = CollUtil.isNotEmpty(chainIds) && ObjectUtil.isNotNull(chainInfo) ? Convert.toList(chainInfo) : new ArrayList<>(); + checkoutResult.put("chain_info", chainInfoList); //计算免单金额 //data_rows = this->calFreeFreight(data_rows); @@ -2271,7 +2357,7 @@ public class ShopUserCartServiceImpl extends BaseServiceImplcalFreeFreight(data_rows, district_id); - return data_rows; + return checkoutResult; } /** @@ -3008,4 +3094,37 @@ public class ShopUserCartServiceImpl extends BaseServiceImpl