diff --git a/src/main/java/cn/van/business/util/JDUtil.java b/src/main/java/cn/van/business/util/JDUtil.java index 77e7400..c6fc7d6 100644 --- a/src/main/java/cn/van/business/util/JDUtil.java +++ b/src/main/java/cn/van/business/util/JDUtil.java @@ -6,7 +6,6 @@ import cn.van.business.model.jd.ProductOrder; import cn.van.business.repository.OrderRowRepository; import cn.van.business.repository.ProductOrderRepository; import com.alibaba.fastjson2.JSON; -import com.alibaba.fastjson2.JSONObject; import com.fasterxml.jackson.databind.ObjectMapper; import com.jd.open.api.sdk.DefaultJdClient; import com.jd.open.api.sdk.JdClient; @@ -56,6 +55,7 @@ import static cn.van.business.util.WXUtil.super_admins; */ @Component public class JDUtil { + static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); /** * 密钥配置 */ @@ -66,18 +66,12 @@ public class JDUtil { // 导购的 private static final String LPF_APP_KEY_DG = "faf410cb9587dc80dc7b31e321d7d322"; private static final String LPF_SECRET_KEY_DG = "a4fb15d7bedd4316b97b4e96e4effc1c"; - private static final String LL_APP_KEY_DG = "9c2011409f0fc906b73432dd3687599d"; private static final String LL_SECRET_KEY_DG = "3ceddff403e544a8a2eacc727cf05dab"; - - private static final String SERVER_URL = "https://api.jd.com/routerjson"; //accessToken private static final String ACCESS_TOKEN = ""; - private static final Logger logger = LoggerFactory.getLogger(JDUtil.class); - - static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); private static final String INTERACTION_STATE_PREFIX = "interaction_state:"; private static final long TIMEOUT_MINUTES = 1; private final StringRedisTemplate redisTemplate; @@ -522,14 +516,21 @@ public class JDUtil { * 接口描述:通过商品链接、领券链接、活动链接获取普通推广链接或优惠券二合一推广链接 * jd.union.open.promotion.bysubunionid.get */ - String transfer(String url) throws Exception { + String transfer(String url) { JdClient client = new DefaultJdClient(SERVER_URL, ACCESS_TOKEN, LPF_APP_KEY_DG, LPF_SECRET_KEY_DG); UnionOpenPromotionBysubunionidGetRequest request = new UnionOpenPromotionBysubunionidGetRequest(); PromotionCodeReq promotionCodeReq = new PromotionCodeReq(); + promotionCodeReq.setMaterialId(url); + promotionCodeReq.setSceneId(1); request.setPromotionCodeReq(promotionCodeReq); request.setVersion("1.0"); - UnionOpenPromotionBysubunionidGetResponse response = client.execute(request); + UnionOpenPromotionBysubunionidGetResponse response = null; + try { + response = client.execute(request); + } catch (Exception e) { + throw new RuntimeException(e); + } /** * { @@ -597,68 +598,104 @@ public class JDUtil { // return response; //} - public void handleUserInteraction(String fromWxid, String message) { - String key = INTERACTION_STATE_PREFIX + fromWxid; - String stateJson = redisTemplate.opsForValue().get(key); - UserInteractionState state; - if (stateJson == null) { - state = new UserInteractionState(); - logger.debug("New interaction state created for user: {}", fromWxid); - } else { - try { - state = objectMapper.readValue(stateJson, UserInteractionState.class); - // 检查是否超时 - LocalDateTime now = LocalDateTime.now(); - LocalDateTime lastInteractionTime = LocalDateTime.parse(state.getLastInteractionTime(), DATE_TIME_FORMATTER); - if (ChronoUnit.MINUTES.between(lastInteractionTime, now) > TIMEOUT_MINUTES) { - redisTemplate.delete(key); - logger.debug("Deleted timeout state for user: {}", fromWxid); - state = new UserInteractionState(); - } - } catch (Exception e) { - logger.error("Error parsing interaction state: {}", e.getMessage()); +private void handleUserInteraction(String fromWxid, String message) { + String key = INTERACTION_STATE_PREFIX + fromWxid; + String stateJson = redisTemplate.opsForValue().get(key); + UserInteractionState state; + + if (stateJson == null) { + state = new UserInteractionState(); + logger.debug("New interaction state created for user: {}", fromWxid); + } else { + try { + state = objectMapper.readValue(stateJson, UserInteractionState.class); + // 检查是否超时 + LocalDateTime now = LocalDateTime.now(); + LocalDateTime lastInteractionTime = LocalDateTime.parse(state.getLastInteractionTime(), DATE_TIME_FORMATTER); + if (ChronoUnit.MINUTES.between(lastInteractionTime, now) > TIMEOUT_MINUTES) { + redisTemplate.delete(key); + logger.debug("Deleted timeout state for user: {}", fromWxid); state = new UserInteractionState(); } - } - state.updateLastInteractionTime(); - - switch (state.getCurrentState()) { - case INIT: - if ("礼金".equals(message)) { - state.setCurrentState(GIFT_MONEY_FLOW); - state.setCurrentStep(STEP_PRODUCT_LINK); - wxUtil.sendTextMessage(fromWxid, "请输入商品链接:", 1, fromWxid); - logger.info("进入礼金开通流程 - 商品链接步骤"); - } - if ("登记".equals(message)) { - // 开始登记新的订单 - state.setCurrentState(DISINFECTANT_CABINET); - state.setCurrentField("orderId"); - wxUtil.sendTextMessage(fromWxid, "请输入订单号:", 1, fromWxid); - logger.debug("User {} entered DISINFECTANT_CABINET state", fromWxid); - } - break; - case GIFT_MONEY_FLOW: - handleGiftMoneyFlow(fromWxid, message, state); - break; - case PRODUCT_ORDER_REGISTRATION: - handleProductOrderRegistration(fromWxid, message, state); - break; - default: - wxUtil.sendTextMessage(fromWxid, "无效的状态,请重新开始对话", 1, fromWxid); - state.setCurrentState(INIT); - logger.debug("User {} reset to INIT state due to invalid state", fromWxid); - break; - } - - try { - redisTemplate.opsForValue().set(key, objectMapper.writeValueAsString(state), TIMEOUT_MINUTES, TimeUnit.MINUTES); - logger.debug("Saved interaction state for user {}: {}", fromWxid, state); } catch (Exception e) { - logger.error("Error saving interaction state: {}", e.getMessage()); + logger.error("Error parsing interaction state: {}", e.getMessage()); + state = new UserInteractionState(); } } + state.updateLastInteractionTime(); + + switch (state.getCurrentState()) { + case INIT: + if ("转链".equals(message)) { + state.setCurrentState(UserInteractionState.ProcessState.PRODUCT_PROMOTION); + state.setCurrentField("content"); + wxUtil.sendTextMessage(fromWxid, "请输入推广文案(包含商品链接):", 1, fromWxid); + logger.info("进入转链流程 - 文案输入步骤"); + } else if ("礼金".equals(message)) { + state.setCurrentState(GIFT_MONEY_FLOW); + state.setCurrentStep(STEP_PRODUCT_LINK); + wxUtil.sendTextMessage(fromWxid, "请输入商品链接:", 1, fromWxid); + logger.info("进入礼金开通流程 - 商品链接步骤"); + } else if ("登记".equals(message)) { + state.setCurrentState(DISINFECTANT_CABINET); + state.setCurrentField("orderId"); + wxUtil.sendTextMessage(fromWxid, "请输入订单号:", 1, fromWxid); + logger.debug("User {} entered DISINFECTANT_CABINET state", fromWxid); + } + break; + + case PRODUCT_PROMOTION: + if ("content".equals(state.getCurrentField())) { + // 第一次输入文案 + state.getCollectedFields().put("content", message); + state.setCurrentField("option"); + wxUtil.sendTextMessage(fromWxid, "请选择操作:\n回复 1 - 需要图片和 SKU 名称\n回复 2 - 仅进行转链", 1, fromWxid); + logger.info("转链流程 - 等待用户选择操作"); + } else if ("option".equals(state.getCurrentField())) { + // 第二次选择操作 + if ("1".equals(message)) { + // 需要图片和 SKU 名称 + String content = state.getCollectedFields().get("content"); + String result = generatePromotionContent(content, true); + wxUtil.sendTextMessage(fromWxid, "处理结果:\n" + result, 1, fromWxid); + state.reset(); + } else if ("2".equals(message)) { + // 仅进行转链 + String content = state.getCollectedFields().get("content"); + String result = generatePromotionContent(content, false); + wxUtil.sendTextMessage(fromWxid, "处理结果:\n" + result, 1, fromWxid); + state.reset(); + } else { + wxUtil.sendTextMessage(fromWxid, "无效的选择,请重新输入:\n回复 1 - 需要图片和 SKU 名称\n回复 2 - 仅进行转链", 1, fromWxid); + } + } + break; + + case GIFT_MONEY_FLOW: + handleGiftMoneyFlow(fromWxid, message, state); + break; + + case PRODUCT_ORDER_REGISTRATION: + handleProductOrderRegistration(fromWxid, message, state); + break; + + default: + wxUtil.sendTextMessage(fromWxid, "无效的状态,请重新开始对话", 1, fromWxid); + state.setCurrentState(INIT); + logger.debug("User {} reset to INIT state due to invalid state", fromWxid); + break; + } + + try { + redisTemplate.opsForValue().set(key, objectMapper.writeValueAsString(state), TIMEOUT_MINUTES, TimeUnit.MINUTES); + logger.debug("Saved interaction state for user {}: {}", fromWxid, state); + } catch (Exception e) { + logger.error("Error saving interaction state: {}", e.getMessage()); + } +} + + // 新增礼金流程处理方法 private void handleGiftMoneyFlow(String fromWxid, String message, UserInteractionState state) { if (state.getCurrentStep() == null) { @@ -762,324 +799,347 @@ public class JDUtil { state.reset(); } } -/** - * 生成转链和文案的方法 - * - * @param message 文案内容,包含商品链接 - * @return 处理后的文案,附带商品信息 - */ -public String generatePromotionContent(String message,Boolean needImagesAndSkuName) { - // 提取文案中的所有 u.jd.com 链接 - List urls = extractUJDUrls(message); - if (urls.isEmpty()) { - return "文案中未找到有效的商品链接,请检查格式是否正确。\n" + message; - } - - // 存储解析后的商品信息 - StringBuilder enrichedContent = new StringBuilder(); - enrichedContent.append("✨ 商品推广文案:\n\n").append(message).append("\n\n"); /** - * { - * "jd_union_open_goods_query_responce": { - * "code": "0", - * "queryResult": { - * "code": 200, - * "data": [ - * { - * "brandCode": "16407", - * "brandName": "松下(Panasonic)", - * "categoryInfo": { - * "cid1": 737, - * "cid1Name": "家用电器", - * "cid2": 794, - * "cid2Name": "大 家 电", - * "cid3": 880, - * "cid3Name": "洗衣机" - * }, - * "comments": 10000, - * "commissionInfo": { - * "commission": 599.95, - * "commissionShare": 5, - * "couponCommission": 592.95, - * "endTime": 1743609599000, - * "isLock": 1, - * "plusCommissionShare": 5, - * "startTime": 1742486400000 - * }, - * "couponInfo": { - * "couponList": [ - * { - * "bindType": 1, - * "couponStatus": 0, - * "couponStyle": 0, - * "discount": 100, - * "getEndTime": 1746028799000, - * "getStartTime": 1743436800000, - * "isBest": 1, - * "isInputCoupon": 1, - * "link": "https://coupon.m.jd.com/coupons/show.action?linkKey=AAROH_xIpeffAs_-naABEFoeVJzBK6Q6mfry4nz4ylRYHXsp_NnipDSrReNwGZGTxXhj94SGi9SkzR_7xaWEXLpO2boqow", - * "platformType": 0, - * "quota": 5000, - * "useEndTime": 1746028799000, - * "useStartTime": 1743436800000 - * }, - * { - * "bindType": 1, - * "couponStatus": 0, - * "couponStyle": 0, - * "discount": 50, - * "getEndTime": 1746028799000, - * "getStartTime": 1743436800000, - * "hotValue": 0, - * "isBest": 0, - * "isInputCoupon": 0, - * "link": "https://coupon.m.jd.com/coupons/show.action?linkKey=AAROH_xIpeffAs_-naABEFoervD9YaNNXlsj6OBbZoWSFI1sZXw31PSjK04AH6tFP_Iu0YJlePWBT6sZfNvp14W0QK2K6A", - * "platformType": 0, - * "quota": 5000, - * "useEndTime": 1746028799000, - * "useStartTime": 1743436800000 - * }, - * { - * "bindType": 1, - * "couponStatus": 0, - * "couponStyle": 0, - * "discount": 40, - * "getEndTime": 1746028799000, - * "getStartTime": 1743436800000, - * "hotValue": 0, - * "isBest": 0, - * "isInputCoupon": 0, - * "link": "https://coupon.m.jd.com/coupons/show.action?linkKey=AAROH_xIpeffAs_-naABEFoeqQdmhZbv1TiAn0QqI5gnT4g_zAgV5887llN8j6TatV-zpDfReipMr-hKkwQasE9NNUV2uQ", - * "platformType": 0, - * "quota": 500, - * "useEndTime": 1746028799000, - * "useStartTime": 1743436800000 - * }, - * { - * "bindType": 1, - * "couponStatus": 0, - * "couponStyle": 0, - * "discount": 20, - * "getEndTime": 1746028799000, - * "getStartTime": 1743436800000, - * "hotValue": 0, - * "isBest": 0, - * "isInputCoupon": 0, - * "link": "https://coupon.m.jd.com/coupons/show.action?linkKey=AAROH_xIpeffAs_-naABEFoepukjRCuLpbwceODRbBw5HpNLRTVe5Olp99d34Izdo0s9lDtTIdyYZ-uJRCEXnc5N3OZ5LA", - * "platformType": 0, - * "quota": 2000, - * "useEndTime": 1746028799000, - * "useStartTime": 1743436800000 - * }, - * { - * "bindType": 1, - * "couponStatus": 0, - * "couponStyle": 0, - * "discount": 10, - * "getEndTime": 1746028799000, - * "getStartTime": 1743436800000, - * "hotValue": 0, - * "isBest": 0, - * "isInputCoupon": 0, - * "link": "https://coupon.m.jd.com/coupons/show.action?linkKey=AAROH_xIpeffAs_-naABEFoeKIIbuvk-VsfJj_m1o3PRHqRaEBIbXHwooEMMt3z44T3cNQTkQsS8TjGnEeIz1obKp_t_mQ", - * "platformType": 0, - * "quota": 1000, - * "useEndTime": 1746028799000, - * "useStartTime": 1743436800000 - * } - * ] - * }, - * "deliveryType": 1, - * "eliteType": [], - * "forbidTypes": [ - * 0 - * ], - * "goodCommentsShare": 99, - * "imageInfo": { - * "imageList": [ - * { - * "url": "https://img14.360buyimg.com/pop/jfs/t1/273873/17/14072/113544/67ebd215Feef3f56b/fc5156bf59a25ba3.jpg" - * }, - * { - * "url": "https://img14.360buyimg.com/pop/jfs/t1/273802/16/14273/84419/67ebd224F72dbcc8d/8ffe6f99aeeeb8fd.jpg" - * }, - * { - * "url": "https://img14.360buyimg.com/pop/jfs/t1/278931/40/12819/81341/67ea0227F41ffc604/ab1c6727e5d4f224.jpg" - * }, - * { - * "url": "https://img14.360buyimg.com/pop/jfs/t1/276989/12/13440/79310/67ea0226F68c2ed40/8acdeda05aa3596b.jpg" - * }, - * { - * "url": "https://img14.360buyimg.com/pop/jfs/t1/284503/25/12384/59498/67ea0225F8be60c83/b29ea34abc64346e.jpg" - * }, - * { - * "url": "https://img14.360buyimg.com/pop/jfs/t1/284667/29/12481/56118/67ea0225F97d9c729/f4c81d77064957bd.jpg" - * }, - * { - * "url": "https://img14.360buyimg.com/pop/jfs/t1/270959/35/13852/50552/67ea0224F911b8f00/248f9a7751549db7.jpg" - * }, - * { - * "url": "https://img14.360buyimg.com/pop/jfs/t1/274981/3/13326/48019/67ea0224Fe64bca69/b062218fc8db9b29.jpg" - * }, - * { - * "url": "https://img14.360buyimg.com/pop/jfs/t1/283691/1/12478/82267/67ea0223Fd4ecb0f5/2c32de327d8aa440.jpg" - * }, - * { - * "url": "https://img14.360buyimg.com/pop/jfs/t1/281457/31/12476/94335/67ea0222Fde76593a/cdddcd59b0b20c9a.jpg" - * } - * ] - * }, - * "inOrderComm30Days": 633170.8, - * "inOrderCount30Days": 3000, - * "inOrderCount30DaysSku": 100, - * "isHot": 1, - * "isJdSale": 1, - * "isOversea": 0, - * "itemId": "BsrqLq5CfIziE7BSl3ItPp8q_3DFaNVYJqfkRRLc7HR", - * "jxFlags": [], - * "materialUrl": "jingfen.jd.com/detail/BsrqLq5CfIziE7BSl3ItPp8q_3DFaNVYJqfkRRLc7HR.html", - * "oriItemId": "BMrqLq5CfIz9X04KC3ItPp8q_3DFaNVYJqfkRRLc7HR", - * "owner": "g", - * "pinGouInfo": {}, - * "pingGouInfo": {}, - * "priceInfo": { - * "lowestCouponPrice": 11899, - * "lowestPrice": 11999, - * "lowestPriceType": 1, - * "price": 11999 - * }, - * "purchasePriceInfo": { - * "basisPriceType": 1, - * "code": 200, - * "couponList": [ - * { - * "bindType": 1, - * "couponStatus": 0, - * "couponStyle": 0, - * "discount": 100, - * "isBest": 0, - * "link": "https://coupon.m.jd.com/coupons/show.action?linkKey=AAROH_xIpeffAs_-naABEFoeVJzBK6Q6mfry4nz4ylRYHXsp_NnipDSrReNwGZGTxXhj94SGi9SkzR_7xaWEXLpO2boqow", - * "platformType": 0, - * "quota": 5000 - * }, - * { - * "bindType": 1, - * "couponStatus": 0, - * "couponStyle": 0, - * "discount": 40, - * "isBest": 0, - * "link": "https://coupon.m.jd.com/coupons/show.action?linkKey=AAROH_xIpeffAs_-naABEFoeqQdmhZbv1TiAn0QqI5gnT4g_zAgV5887llN8j6TatV-zpDfReipMr-hKkwQasE9NNUV2uQ", - * "platformType": 0, - * "quota": 500 - * } - * ], - * "message": "success", - * "purchaseNum": 1, - * "purchasePrice": 11859, - * "thresholdPrice": 11999 - * }, - * "shopInfo": { - * "shopId": 1000001741, - * "shopLabel": "0", - * "shopLevel": 4.9, - * "shopName": "松下洗衣机京东自营旗舰店" - * }, - * "skuName": "松下(Panasonic)白月光4.0Ultra 洗烘套装 10kg滚筒洗衣机+变频热泵烘干机 除毛升级2.0 水氧SPA护理 8532N+8532NR", - * "skuTagList": [ - * { - * "index": 1, - * "name": "自营", - * "type": 11 - * }, - * { - * "index": 1, - * "name": "plus", - * "type": 6 - * }, - * { - * "index": 3, - * "name": "7天无理由退货", - * "type": 12 - * } - * ], - * "spuid": 100137629936, - * "videoInfo": {} - * } - * ], - * "message": "success", - * "requestId": "o_0b721560_m8yp5pqj_88394507", - * "totalCount": 1 - * } - * } - * } + * 生成转链和文案的方法 * - * */ - //"materialUrl": "jingfen.jd.com/detail/BsrqLq5CfIziE7BSl3ItPp8q_3DFaNVYJqfkRRLc7HR.html", - //"oriItemId": "BMrqLq5CfIz9X04KC3ItPp8q_3DFaNVYJqfkRRLc7HR", - //"owner": "g", - //"shopInfo": { - // "shopId": 1000001741, - // "shopLabel": "0", - // "shopLevel": 4.9, - // "shopName": "松下洗衣机京东自营旗舰店" - //}, - //"skuName": "松下(Panasonic)白月光4.0Ultra 洗烘套装 10kg滚筒洗衣机+变频热泵烘干机 除毛升级2.0 水氧SPA护理 8532N+8532NR", - //"spuid": 100137629936, - ArrayList> resultList = new ArrayList<>(); - for (String url : urls) { - try { - // 查询商品信息 - GoodsQueryResult productInfo = queryProductInfoByUJDUrl(url); - if (productInfo == null || productInfo.getCode() != 200) { - enrichedContent.append("⚠️ 商品链接查询失败:").append(url).append("\n"); - continue; - } - long totalCount = productInfo.getTotalCount(); - HashMap itemMap = new HashMap<>(); - itemMap.put("url", url); - - if (totalCount == 0) { - itemMap.put("type", "coupon"); - } - else { - itemMap.put("type", "goods"); - itemMap.put("data", JSONObject.toJSONString(productInfo.getData())); - } - resultList.add(itemMap); - - } catch (Exception e) { - logger.error("处理商品链接时发生异常:{}", url, e); - enrichedContent.append("❌ 处理商品链接时发生异常:").append(url).append("\n"); + * @param message 文案内容,包含商品链接 + * @return 处理后的文案,附带商品信息 + */ + public String generatePromotionContent(String message, Boolean needImagesAndSkuName) { + // 提取文案中的所有 u.jd.com 链接 + List urls = extractUJDUrls(message); + if (urls.isEmpty()) { + return "文案中未找到有效的商品链接,请检查格式是否正确。\n" + message; } + + + /** + * { + * "jd_union_open_goods_query_responce": { + * "code": "0", + * "queryResult": { + * "code": 200, + * "data": [ + * { + * "brandCode": "16407", + * "brandName": "松下(Panasonic)", + * "categoryInfo": { + * "cid1": 737, + * "cid1Name": "家用电器", + * "cid2": 794, + * "cid2Name": "大 家 电", + * "cid3": 880, + * "cid3Name": "洗衣机" + * }, + * "comments": 10000, + * "commissionInfo": { + * "commission": 599.95, + * "commissionShare": 5, + * "couponCommission": 592.95, + * "endTime": 1743609599000, + * "isLock": 1, + * "plusCommissionShare": 5, + * "startTime": 1742486400000 + * }, + * "couponInfo": { + * "couponList": [ + * { + * "bindType": 1, + * "couponStatus": 0, + * "couponStyle": 0, + * "discount": 100, + * "getEndTime": 1746028799000, + * "getStartTime": 1743436800000, + * "isBest": 1, + * "isInputCoupon": 1, + * "link": "https://coupon.m.jd.com/coupons/show.action?linkKey=AAROH_xIpeffAs_-naABEFoeVJzBK6Q6mfry4nz4ylRYHXsp_NnipDSrReNwGZGTxXhj94SGi9SkzR_7xaWEXLpO2boqow", + * "platformType": 0, + * "quota": 5000, + * "useEndTime": 1746028799000, + * "useStartTime": 1743436800000 + * }, + * { + * "bindType": 1, + * "couponStatus": 0, + * "couponStyle": 0, + * "discount": 50, + * "getEndTime": 1746028799000, + * "getStartTime": 1743436800000, + * "hotValue": 0, + * "isBest": 0, + * "isInputCoupon": 0, + * "link": "https://coupon.m.jd.com/coupons/show.action?linkKey=AAROH_xIpeffAs_-naABEFoervD9YaNNXlsj6OBbZoWSFI1sZXw31PSjK04AH6tFP_Iu0YJlePWBT6sZfNvp14W0QK2K6A", + * "platformType": 0, + * "quota": 5000, + * "useEndTime": 1746028799000, + * "useStartTime": 1743436800000 + * }, + * { + * "bindType": 1, + * "couponStatus": 0, + * "couponStyle": 0, + * "discount": 40, + * "getEndTime": 1746028799000, + * "getStartTime": 1743436800000, + * "hotValue": 0, + * "isBest": 0, + * "isInputCoupon": 0, + * "link": "https://coupon.m.jd.com/coupons/show.action?linkKey=AAROH_xIpeffAs_-naABEFoeqQdmhZbv1TiAn0QqI5gnT4g_zAgV5887llN8j6TatV-zpDfReipMr-hKkwQasE9NNUV2uQ", + * "platformType": 0, + * "quota": 500, + * "useEndTime": 1746028799000, + * "useStartTime": 1743436800000 + * }, + * { + * "bindType": 1, + * "couponStatus": 0, + * "couponStyle": 0, + * "discount": 20, + * "getEndTime": 1746028799000, + * "getStartTime": 1743436800000, + * "hotValue": 0, + * "isBest": 0, + * "isInputCoupon": 0, + * "link": "https://coupon.m.jd.com/coupons/show.action?linkKey=AAROH_xIpeffAs_-naABEFoepukjRCuLpbwceODRbBw5HpNLRTVe5Olp99d34Izdo0s9lDtTIdyYZ-uJRCEXnc5N3OZ5LA", + * "platformType": 0, + * "quota": 2000, + * "useEndTime": 1746028799000, + * "useStartTime": 1743436800000 + * }, + * { + * "bindType": 1, + * "couponStatus": 0, + * "couponStyle": 0, + * "discount": 10, + * "getEndTime": 1746028799000, + * "getStartTime": 1743436800000, + * "hotValue": 0, + * "isBest": 0, + * "isInputCoupon": 0, + * "link": "https://coupon.m.jd.com/coupons/show.action?linkKey=AAROH_xIpeffAs_-naABEFoeKIIbuvk-VsfJj_m1o3PRHqRaEBIbXHwooEMMt3z44T3cNQTkQsS8TjGnEeIz1obKp_t_mQ", + * "platformType": 0, + * "quota": 1000, + * "useEndTime": 1746028799000, + * "useStartTime": 1743436800000 + * } + * ] + * }, + * "deliveryType": 1, + * "eliteType": [], + * "forbidTypes": [ + * 0 + * ], + * "goodCommentsShare": 99, + * "imageInfo": { + * "imageList": [ + * { + * "url": "https://img14.360buyimg.com/pop/jfs/t1/273873/17/14072/113544/67ebd215Feef3f56b/fc5156bf59a25ba3.jpg" + * }, + * { + * "url": "https://img14.360buyimg.com/pop/jfs/t1/273802/16/14273/84419/67ebd224F72dbcc8d/8ffe6f99aeeeb8fd.jpg" + * }, + * { + * "url": "https://img14.360buyimg.com/pop/jfs/t1/278931/40/12819/81341/67ea0227F41ffc604/ab1c6727e5d4f224.jpg" + * }, + * { + * "url": "https://img14.360buyimg.com/pop/jfs/t1/276989/12/13440/79310/67ea0226F68c2ed40/8acdeda05aa3596b.jpg" + * }, + * { + * "url": "https://img14.360buyimg.com/pop/jfs/t1/284503/25/12384/59498/67ea0225F8be60c83/b29ea34abc64346e.jpg" + * }, + * { + * "url": "https://img14.360buyimg.com/pop/jfs/t1/284667/29/12481/56118/67ea0225F97d9c729/f4c81d77064957bd.jpg" + * }, + * { + * "url": "https://img14.360buyimg.com/pop/jfs/t1/270959/35/13852/50552/67ea0224F911b8f00/248f9a7751549db7.jpg" + * }, + * { + * "url": "https://img14.360buyimg.com/pop/jfs/t1/274981/3/13326/48019/67ea0224Fe64bca69/b062218fc8db9b29.jpg" + * }, + * { + * "url": "https://img14.360buyimg.com/pop/jfs/t1/283691/1/12478/82267/67ea0223Fd4ecb0f5/2c32de327d8aa440.jpg" + * }, + * { + * "url": "https://img14.360buyimg.com/pop/jfs/t1/281457/31/12476/94335/67ea0222Fde76593a/cdddcd59b0b20c9a.jpg" + * } + * ] + * }, + * "inOrderComm30Days": 633170.8, + * "inOrderCount30Days": 3000, + * "inOrderCount30DaysSku": 100, + * "isHot": 1, + * "isJdSale": 1, + * "isOversea": 0, + * "itemId": "BsrqLq5CfIziE7BSl3ItPp8q_3DFaNVYJqfkRRLc7HR", + * "jxFlags": [], + * "materialUrl": "jingfen.jd.com/detail/BsrqLq5CfIziE7BSl3ItPp8q_3DFaNVYJqfkRRLc7HR.html", + * "oriItemId": "BMrqLq5CfIz9X04KC3ItPp8q_3DFaNVYJqfkRRLc7HR", + * "owner": "g", + * "pinGouInfo": {}, + * "pingGouInfo": {}, + * "priceInfo": { + * "lowestCouponPrice": 11899, + * "lowestPrice": 11999, + * "lowestPriceType": 1, + * "price": 11999 + * }, + * "purchasePriceInfo": { + * "basisPriceType": 1, + * "code": 200, + * "couponList": [ + * { + * "bindType": 1, + * "couponStatus": 0, + * "couponStyle": 0, + * "discount": 100, + * "isBest": 0, + * "link": "https://coupon.m.jd.com/coupons/show.action?linkKey=AAROH_xIpeffAs_-naABEFoeVJzBK6Q6mfry4nz4ylRYHXsp_NnipDSrReNwGZGTxXhj94SGi9SkzR_7xaWEXLpO2boqow", + * "platformType": 0, + * "quota": 5000 + * }, + * { + * "bindType": 1, + * "couponStatus": 0, + * "couponStyle": 0, + * "discount": 40, + * "isBest": 0, + * "link": "https://coupon.m.jd.com/coupons/show.action?linkKey=AAROH_xIpeffAs_-naABEFoeqQdmhZbv1TiAn0QqI5gnT4g_zAgV5887llN8j6TatV-zpDfReipMr-hKkwQasE9NNUV2uQ", + * "platformType": 0, + * "quota": 500 + * } + * ], + * "message": "success", + * "purchaseNum": 1, + * "purchasePrice": 11859, + * "thresholdPrice": 11999 + * }, + * "shopInfo": { + * "shopId": 1000001741, + * "shopLabel": "0", + * "shopLevel": 4.9, + * "shopName": "松下洗衣机京东自营旗舰店" + * }, + * "skuName": "松下(Panasonic)白月光4.0Ultra 洗烘套装 10kg滚筒洗衣机+变频热泵烘干机 除毛升级2.0 水氧SPA护理 8532N+8532NR", + * "skuTagList": [ + * { + * "index": 1, + * "name": "自营", + * "type": 11 + * }, + * { + * "index": 1, + * "name": "plus", + * "type": 6 + * }, + * { + * "index": 3, + * "name": "7天无理由退货", + * "type": 12 + * } + * ], + * "spuid": 100137629936, + * "videoInfo": {} + * } + * ], + * "message": "success", + * "requestId": "o_0b721560_m8yp5pqj_88394507", + * "totalCount": 1 + * } + * } + * } + * + * */ + + // 如果需要图片和SKU名称,则代表要把图片下载发过去,还有对应的skuName + StringBuilder enrichedContent = new StringBuilder(); + ArrayList> resultList = new ArrayList<>(); + for (String url : urls) { + try { + // 查询商品信息 + GoodsQueryResult productInfo = queryProductInfoByUJDUrl(url); + if (productInfo == null || productInfo.getCode() != 200) { + enrichedContent.append("商品链接查询失败:").append(url).append("\n"); + continue; + } + long totalCount = productInfo.getTotalCount(); + HashMap itemMap = new HashMap<>(); + itemMap.put("url", url); + + if (totalCount == 0) { + itemMap.put("type", "coupon"); + } else { + itemMap.put("type", "goods"); + //itemMap.put("data", JSONObject.toJSONString(productInfo.getData())); + + //"materialUrl": "jingfen.jd.com/detail/BsrqLq5CfIziE7BSl3ItPp8q_3DFaNVYJqfkRRLc7HR.html", + //"oriItemId": "BMrqLq5CfIz9X04KC3ItPp8q_3DFaNVYJqfkRRLc7HR", + //"owner": "g", + //"shopInfo": { + // "shopId": 1000001741, + // "shopLabel": "0", + // "shopLevel": 4.9, + // "shopName": "松下洗衣机京东自营旗舰店" + //}, + //"skuName": "松下(Panasonic)白月光4.0Ultra 洗烘套装 10kg滚筒洗衣机+变频热泵烘干机 除毛升级2.0 水氧SPA护理 8532N+8532NR", + //"spuid": 100137629936, + itemMap.put("materialUrl", productInfo.getData()[0].getMaterialUrl()); + itemMap.put("oriItemId", productInfo.getData()[0].getOriItemId()); + itemMap.put("owner", productInfo.getData()[0].getOwner()); + itemMap.put("shopId", String.valueOf(productInfo.getData()[0].getShopInfo().getShopId())); + itemMap.put("shopName", productInfo.getData()[0].getShopInfo().getShopName()); + itemMap.put("skuName", productInfo.getData()[0].getSkuName()); + itemMap.put("spuid", String.valueOf(productInfo.getData()[0].getSpuid())); + } + resultList.add(itemMap); + + } catch (Exception e) { + logger.error("处理商品链接时发生异常:{}", url, e); + enrichedContent.append("❌ 处理商品链接时发生异常:").append(url).append("\n"); + } + } + if (resultList.isEmpty()){ + enrichedContent.append("❌ 处理商品链接时发生异常:").append("\n"); + return enrichedContent.toString(); + } + if(!needImagesAndSkuName){ + // 完成转链后替换链接为u.jd.com链接,文案不修改就返回 + for (HashMap stringStringHashMap : resultList) { + String url = stringStringHashMap.get("url"); + String transferUrl = transfer(url); + stringStringHashMap.put("transferUrl", transferUrl); + message = message.replace(url, transferUrl); + } + } + + //enrichedContent.append("商品推广文案:\n\n").append(message).append("\n\n"); + + + return enrichedContent.toString(); } - return enrichedContent.toString(); -} + /** + * 提取文案中的所有 u.jd.com 链接 + * + * @param message 文案内容 + * @return 包含所有 u.jd.com 链接的列表 + */ + private List extractUJDUrls(String message) { + List urls = new ArrayList<>(); + Pattern pattern = Pattern.compile("https://u\\.jd\\.com/[^\\s]+"); + Matcher matcher = pattern.matcher(message); -/** - * 提取文案中的所有 u.jd.com 链接 - * - * @param message 文案内容 - * @return 包含所有 u.jd.com 链接的列表 - */ -private List extractUJDUrls(String message) { - List urls = new ArrayList<>(); - Pattern pattern = Pattern.compile("https://u\\.jd\\.com/[^\\s]+"); - Matcher matcher = pattern.matcher(message); + while (matcher.find()) { + urls.add(matcher.group()); + } - while (matcher.find()) { - urls.add(matcher.group()); + return urls; } - return urls; -} - /** * 通过这个可以将u.jd.*** 查询到对应的商品信息 和 商品图片,甚至可以查询到是不是自营的商品 - * - * */ + */ public UnionOpenGoodsQueryResponse getUnionOpenGoodsQueryRequest(String uJDUrl) throws Exception { JdClient client = new DefaultJdClient(SERVER_URL, ACCESS_TOKEN, LPF_APP_KEY_WZ, LPF_APP_KEY_WZ); @@ -1153,64 +1213,64 @@ private List extractUJDUrls(String message) { // 新增礼金创建方法 -public String createGiftCoupon(String skuId, double amount, int quantity, String owner) throws Exception { - logger.debug("准备创建礼金:SKU={}, 金额={}元,数量={}, Owner={}", skuId, amount, quantity, owner); + public String createGiftCoupon(String skuId, double amount, int quantity, String owner) throws Exception { + logger.debug("准备创建礼金:SKU={}, 金额={}元,数量={}, Owner={}", skuId, amount, quantity, owner); - // 参数校验 - if (skuId == null || amount <= 0 || quantity <= 0) { - logger.error("礼金创建失败:参数错误,SKU={}, 金额={}元,数量={}", skuId, amount, quantity); + // 参数校验 + if (skuId == null || amount <= 0 || quantity <= 0) { + logger.error("礼金创建失败:参数错误,SKU={}, 金额={}元,数量={}", skuId, amount, quantity); + return null; + } + + // 设置默认值 + owner = (owner != null) ? owner : "自营"; + + JdClient client = new DefaultJdClient(SERVER_URL, ACCESS_TOKEN, LPF_APP_KEY_WZ, LPF_APP_KEY_WZ); + + UnionOpenCouponGiftGetRequest request = new UnionOpenCouponGiftGetRequest(); + CreateGiftCouponReq couponReq = new CreateGiftCouponReq(); + couponReq.setSkuMaterialId(skuId); // 使用SKU或链接 + couponReq.setDiscount(amount); + couponReq.setAmount(quantity); + + // 自营的只能设置一天,pop的只能设置7天,默认为自营 + String startTime; + String endTime; + if ("pop".equals(owner)) { + startTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH")); + endTime = LocalDateTime.now().plusDays(6).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH")); + } else { + startTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH")); + endTime = LocalDateTime.now().plusDays(1).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH")); + } + + couponReq.setReceiveStartTime(startTime); + couponReq.setReceiveEndTime(endTime); + couponReq.setEffectiveDays(7); + couponReq.setIsSpu(1); + couponReq.setExpireType(1); + couponReq.setShare(-1); + couponReq.setCouponTitle(skuId); + couponReq.setContentMatch(1); + + request.setCouponReq(couponReq); + request.setVersion("1.0"); + + logger.debug("请求参数:{}", JSON.toJSONString(request)); + + UnionOpenCouponGiftGetResponse response = client.execute(request); + logger.debug("API响应:{}", JSON.toJSONString(response)); + + if ("200".equals(response.getCode())) { + String giftKey = response.getGetResult().getData().getGiftCouponKey(); + logger.debug("礼金创建成功:批次ID={}, 返回数据:{}", giftKey, response.getGetResult().getData()); + return giftKey; + } else { + logger.error("礼金创建失败:错误码={}, 错误信息={}", response.getCode(), response.getMsg()); + } return null; } - // 设置默认值 - owner = (owner != null) ? owner : "自营"; - - JdClient client = new DefaultJdClient(SERVER_URL, ACCESS_TOKEN, LPF_APP_KEY_WZ, LPF_APP_KEY_WZ); - - UnionOpenCouponGiftGetRequest request = new UnionOpenCouponGiftGetRequest(); - CreateGiftCouponReq couponReq = new CreateGiftCouponReq(); - couponReq.setSkuMaterialId(skuId); // 使用SKU或链接 - couponReq.setDiscount(amount); - couponReq.setAmount(quantity); - - // 自营的只能设置一天,pop的只能设置7天,默认为自营 - String startTime; - String endTime; - if ("pop".equals(owner)) { - startTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH")); - endTime = LocalDateTime.now().plusDays(6).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH")); - } else { - startTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH")); - endTime = LocalDateTime.now().plusDays(1).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH")); - } - - couponReq.setReceiveStartTime(startTime); - couponReq.setReceiveEndTime(endTime); - couponReq.setEffectiveDays(7); - couponReq.setIsSpu(1); - couponReq.setExpireType(1); - couponReq.setShare(-1); - couponReq.setCouponTitle(skuId); - couponReq.setContentMatch(1); - - request.setCouponReq(couponReq); - request.setVersion("1.0"); - - logger.debug("请求参数:{}", JSON.toJSONString(request)); - - UnionOpenCouponGiftGetResponse response = client.execute(request); - logger.debug("API响应:{}", JSON.toJSONString(response)); - - if ("200".equals(response.getCode())) { - String giftKey = response.getGetResult().getData().getGiftCouponKey(); - logger.debug("礼金创建成功:批次ID={}, 返回数据:{}", giftKey, response.getGetResult().getData()); - return giftKey; - } else { - logger.error("礼金创建失败:错误码={}, 错误信息={}", response.getCode(), response.getMsg()); - } - return null; -} - // 修改activateGiftMoney方法调用真实接口 private boolean activateGiftMoney(String skuId, double amount, int quantity, String owner) { @@ -1378,18 +1438,18 @@ public String createGiftCoupon(String skuId, double amount, int quantity, String this.lastInteractionTime = LocalDateTime.now().format(DATE_TIME_FORMATTER); } - public void reset() { - this.currentState = INIT; - this.collectedFields.clear(); - this.currentStep = STEP_PRODUCT_LINK; // 明确重置步骤 - this.currentProductOrderStep = null; - updateLastInteractionTime(); - } + public void reset() { + this.currentState = INIT; + this.collectedFields.clear(); + this.currentStep = STEP_PRODUCT_LINK; // 明确重置步骤 + this.currentProductOrderStep = null; + updateLastInteractionTime(); + } // 推荐使用枚举管理状态 public enum ProcessState { - INIT, GIFT_MONEY_FLOW, DISINFECTANT_CABINET, PRODUCT_ORDER_REGISTRATION + INIT, GIFT_MONEY_FLOW, DISINFECTANT_CABINET, PRODUCT_ORDER_REGISTRATION,PRODUCT_PROMOTION } public enum GiftMoneyStep {