mirror of
https://gitee.com/qqtt-ah/ecom-dmb.git
synced 2026-11-23 23:19:19 +08:00
refactor: 重构拼多多渠道同步任务和数据只关联渠道店铺
This commit is contained in:
@@ -118,7 +118,7 @@ FE 打开店铺增量开关
|
||||
→ doIncremental:按页 upsert channel_pdd_*
|
||||
→ 每同步完一页 → publish OrderConvertMessage(
|
||||
mode=INC, orders=[{channelOrderId}, ...]) → order.convert.pdd.inc
|
||||
→ Convert:同店独占(与 FULL 互斥);按渠道主键查镜像;内部单用 platform_code + source_order_id 定位
|
||||
→ Convert:同店独占(与 FULL 互斥);按渠道主键查镜像;内部单用 uk(company, shop, platform_order_no) 定位
|
||||
· 内部无此单 → 新增并算贡献差发 BI inc
|
||||
· 内部已有:channel.pdd_updated_at 不晚于 ec_order.platform_updated_at → 跳过
|
||||
· 渠道更新时间更新 → 覆盖转换;对比转换前后贡献,算出各聚合字段加减量
|
||||
@@ -349,7 +349,6 @@ RoutingKey:
|
||||
|----------|------|
|
||||
| `platform_order_no` | `channel_pdd_order.order_sn` |
|
||||
| `source` | 固定 `sync` |
|
||||
| `source_order_id` | `channel_pdd_order.id` |
|
||||
| `platform_code` | `pdd` |
|
||||
| `shop_id` / `company_id` | 上下文 |
|
||||
| 金额 / 邮费 / 优惠 | 与渠道镜像同构字段 |
|
||||
@@ -371,7 +370,7 @@ RoutingKey:
|
||||
| mode | 行为 |
|
||||
|------|------|
|
||||
| `FULL_DAY` | 开事务批量转换:消息带 `orders`(含空)只按 id 加载;`orders==null` 的旧消息才按店+成交日查。仅渠道新于内部的单写入;批内预加载 SKU/成本 → 写 `platform_updated_at` → 发 `bi.stat.full`(含成交日,即使当日零变更) |
|
||||
| `INC` | 逐单按 `channelOrderId` 查渠道镜像;内部用 `platform_code + source_order_id` 定位:无单则新增;有单则仅当 `channel.pdd_updated_at` **严格晚于** `ec_order.platform_updated_at` 时覆盖转换;用转换前后贡献差算出 delta,按受影响 `statDate` 各发一条 `bi.stat.inc`;`internalOrderUpdateTime` = 转换后 `ec_order.update_time` |
|
||||
| `INC` | 逐单按 `channelOrderId` 查渠道镜像;内部用 `uk(company_id, shop_id, platform_order_no)` 定位:无单则新增;有单则仅当 `channel.pdd_updated_at` **严格晚于** `ec_order.platform_updated_at` 时覆盖转换;用转换前后贡献差算出 delta,按受影响 `statDate` 各发一条 `bi.stat.inc`;`internalOrderUpdateTime` = 转换后 `ec_order.update_time` |
|
||||
|
||||
部分失败:FULL_DAY 不发 full 消息,转换消息进重试/DLQ;INC 仅对实际转换成功的订单发 inc 消息。
|
||||
|
||||
@@ -657,7 +656,7 @@ ecom:
|
||||
| 转换队列 | 全量日 / 增量**分两个队列**;同店 FULL/INC 互斥,FULL 可按天并行 |
|
||||
| BI 队列 | 全量 / 增量**分两个队列** |
|
||||
| 全量计算 | MySQL consistent snapshot + 按日重算覆盖写 Mongo,写入 `dbSnapshotTime`;锁 `bi:stat:lock:{company}:{shop}:{statDate}` |
|
||||
| 增量转换 | 消息带渠道主键;内部用 `platform_code + source_order_id` 定位;对比 `ec_order.platform_updated_at` vs 渠道 `pdd_updated_at`;跳过或转换并产出 delta |
|
||||
| 增量转换 | 消息带渠道主键;内部用 `uk(company, shop, platform_order_no)` 定位;对比 `ec_order.platform_updated_at` vs 渠道 `pdd_updated_at`;跳过或转换并产出 delta |
|
||||
| 增量计算 | 转换侧算 delta 并带 `internalOrderUpdateTime`;BI:`internalOrderUpdateTime <= dbSnapshotTime` 跳过,否则 `$inc`;**同日**全量进行中且更新更晚则延后;不同日可并行 |
|
||||
| 增量写 Mongo | `$inc` 累加,不抬高 `dbSnapshotTime` |
|
||||
| 投递转换 | 全量按天 / 增量按页 publish(消息带渠道镜像主键);Listener 仅 repair |
|
||||
|
||||
@@ -17,31 +17,32 @@
|
||||
-- order_tag_list 等嵌套结构写入 raw_response
|
||||
-- 3. 幂等键 uk(company_id, order_sn)
|
||||
-- 4. 主表仅存脱敏收件信息(*_mask);明文地址/电话不落独立列(完整报文在 raw_response)
|
||||
-- 5. 同步策略详见 channel_pdd_order_sync_design.md
|
||||
-- 5. 渠道侧 shop_id 一律为 channel_pdd_shop.id(不挂 ec_shop);授权经 pdd 店的 pdd_auth_id 解析,不落订单/游标表
|
||||
-- 6. 同步策略详见 channel_pdd_order_sync_design.md
|
||||
-- 限流(官方 FAQ):商家限流=单店铺;接口总限流=全平台所有店铺/所有 ISV
|
||||
-- 例:pdd.order.list.get 商家 10000次/60秒,接口总 17500次/10秒
|
||||
-- 6. SDK 未内置限流;出站前按「店铺 + API」经 PddPopRateLimiter,触限阻塞/退避,不推进游标
|
||||
-- 7. 同步控制面(已废弃 channel_pdd_order_sync_cursor):
|
||||
-- 7. SDK 未内置限流;出站前按「店铺 + API」经 PddPopRateLimiter,触限阻塞/退避,不推进游标
|
||||
-- 8. 同步控制面(已废弃 channel_pdd_order_sync_cursor):
|
||||
-- · 增量开关:ec_shop.order_inc_sync_enabled
|
||||
-- · 增量运行态(游标/出错暂停):channel_pdd_order_inc_sync(每店一行)
|
||||
-- · 增量运行态(游标/出错暂停):channel_pdd_order_inc_sync(每渠道店一行)
|
||||
-- · 全量任务进度:channel_pdd_order_full_sync_task
|
||||
-- ========================================
|
||||
|
||||
DROP TABLE IF EXISTS `channel_pdd_order_item`;
|
||||
DROP TABLE IF EXISTS `channel_pdd_order`;
|
||||
DROP TABLE IF EXISTS `channel_pdd_order_full_sync_task_day`;
|
||||
DROP TABLE IF EXISTS `channel_pdd_order_full_sync_task`;
|
||||
DROP TABLE IF EXISTS `channel_pdd_order_inc_sync`;
|
||||
DROP TABLE IF EXISTS `channel_pdd_order_sync_cursor`;
|
||||
|
||||
-- ========================================
|
||||
-- 拼多多订单增量同步状态表(每店一行;开关在 ec_shop)
|
||||
-- 拼多多订单增量同步状态表(每渠道店一行;开关在 ec_shop)
|
||||
-- status: 0停用 1正常 2出错暂停(Job 跳过 status=2,直至人工恢复)
|
||||
-- ========================================
|
||||
CREATE TABLE `channel_pdd_order_inc_sync` (
|
||||
`id` bigint UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '主键ID',
|
||||
`company_id` bigint UNSIGNED NOT NULL COMMENT '公司ID',
|
||||
`shop_id` bigint UNSIGNED NOT NULL COMMENT '内部店铺ID(ec_shop.id)',
|
||||
`pdd_auth_id` bigint UNSIGNED NULL DEFAULT NULL COMMENT '拼多多授权ID(channel_pdd_auth.id)',
|
||||
`shop_id` bigint UNSIGNED NOT NULL COMMENT '渠道店铺ID(channel_pdd_shop.id)',
|
||||
`last_cursor_at` datetime NULL DEFAULT NULL COMMENT '已成功同步到的更新时间游标',
|
||||
`overlap_seconds` int NOT NULL DEFAULT 120 COMMENT '窗口重叠秒数(防边界漏单,默认 120)',
|
||||
`status` tinyint NOT NULL DEFAULT 1 COMMENT '状态:0停用 1正常 2出错暂停',
|
||||
@@ -54,8 +55,7 @@ CREATE TABLE `channel_pdd_order_inc_sync` (
|
||||
INDEX `idx_channel_pdd_order_inc_sync_company`(`company_id` ASC) USING BTREE,
|
||||
INDEX `idx_channel_pdd_order_inc_sync_status`(`status` ASC) USING BTREE,
|
||||
CONSTRAINT `fk_channel_pdd_order_inc_sync_company` FOREIGN KEY (`company_id`) REFERENCES `org_company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
|
||||
CONSTRAINT `fk_channel_pdd_order_inc_sync_shop` FOREIGN KEY (`shop_id`) REFERENCES `ec_shop` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
|
||||
CONSTRAINT `fk_channel_pdd_order_inc_sync_auth` FOREIGN KEY (`pdd_auth_id`) REFERENCES `channel_pdd_auth` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
|
||||
CONSTRAINT `fk_channel_pdd_order_inc_sync_shop` FOREIGN KEY (`shop_id`) REFERENCES `channel_pdd_shop` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
|
||||
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = '拼多多-订单增量同步状态表' ROW_FORMAT = Dynamic;
|
||||
|
||||
-- ========================================
|
||||
@@ -65,7 +65,7 @@ CREATE TABLE `channel_pdd_order_inc_sync` (
|
||||
CREATE TABLE `channel_pdd_order_full_sync_task` (
|
||||
`id` bigint UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '主键ID',
|
||||
`company_id` bigint UNSIGNED NOT NULL COMMENT '公司ID',
|
||||
`shop_id` bigint UNSIGNED NOT NULL COMMENT '内部店铺ID(ec_shop.id)',
|
||||
`shop_id` bigint UNSIGNED NOT NULL COMMENT '渠道店铺ID(channel_pdd_shop.id)',
|
||||
`platform_code` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL DEFAULT 'pdd' COMMENT '平台编码',
|
||||
`date_from` date NOT NULL COMMENT '成交日起(含)',
|
||||
`date_to` date NOT NULL COMMENT '成交日止(含)',
|
||||
@@ -81,7 +81,7 @@ CREATE TABLE `channel_pdd_order_full_sync_task` (
|
||||
PRIMARY KEY (`id`) USING BTREE,
|
||||
INDEX `idx_channel_pdd_order_full_sync_task_shop_status`(`company_id` ASC, `shop_id` ASC, `status` ASC) USING BTREE,
|
||||
CONSTRAINT `fk_channel_pdd_order_full_sync_task_company` FOREIGN KEY (`company_id`) REFERENCES `org_company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
|
||||
CONSTRAINT `fk_channel_pdd_order_full_sync_task_shop` FOREIGN KEY (`shop_id`) REFERENCES `ec_shop` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
|
||||
CONSTRAINT `fk_channel_pdd_order_full_sync_task_shop` FOREIGN KEY (`shop_id`) REFERENCES `channel_pdd_shop` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
|
||||
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = '拼多多-订单全量同步任务表' ROW_FORMAT = Dynamic;
|
||||
|
||||
-- ========================================
|
||||
@@ -92,7 +92,7 @@ CREATE TABLE `channel_pdd_order_full_sync_task_day` (
|
||||
`id` bigint UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '主键ID',
|
||||
`task_id` bigint UNSIGNED NOT NULL COMMENT '父任务ID',
|
||||
`company_id` bigint UNSIGNED NOT NULL COMMENT '公司ID',
|
||||
`shop_id` bigint UNSIGNED NOT NULL COMMENT '内部店铺ID(ec_shop.id)',
|
||||
`shop_id` bigint UNSIGNED NOT NULL COMMENT '渠道店铺ID(channel_pdd_shop.id)',
|
||||
`day` date NOT NULL COMMENT '成交日',
|
||||
`status` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL DEFAULT 'PENDING' COMMENT 'PENDING/RUNNING/SUCCESS/FAILED',
|
||||
`last_error` varchar(512) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '失败信息',
|
||||
@@ -112,8 +112,7 @@ CREATE TABLE `channel_pdd_order_full_sync_task_day` (
|
||||
CREATE TABLE `channel_pdd_order` (
|
||||
`id` bigint UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '主键ID',
|
||||
`company_id` bigint UNSIGNED NOT NULL COMMENT '公司ID',
|
||||
`shop_id` bigint UNSIGNED NOT NULL COMMENT '店铺ID(ec_shop.id)',
|
||||
`pdd_auth_id` bigint UNSIGNED NULL DEFAULT NULL COMMENT '拼多多授权ID(channel_pdd_auth.id)',
|
||||
`shop_id` bigint UNSIGNED NOT NULL COMMENT '渠道店铺ID(channel_pdd_shop.id)',
|
||||
`order_sn` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '拼多多订单号',
|
||||
`order_status` int NOT NULL COMMENT '订单状态(order_status 1:待发货,2:已发货待签收,3:已签收)',
|
||||
`refund_status` int NULL DEFAULT NULL COMMENT '退款状态(refund_status 1:无售后或售后关闭,2:售后处理中,3:退款中,4: 退款成功)',
|
||||
@@ -153,19 +152,14 @@ CREATE TABLE `channel_pdd_order` (
|
||||
`update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||
PRIMARY KEY (`id`) USING BTREE,
|
||||
UNIQUE INDEX `uk_channel_pdd_order_company_sn`(`company_id` ASC, `order_sn` ASC) USING BTREE COMMENT '幂等键:同一公司订单号唯一;精确查单号',
|
||||
-- 列表默认:WHERE company_id [= shop_id] ORDER BY confirm_time DESC, id DESC
|
||||
INDEX `idx_channel_pdd_order_company_confirm`(`company_id` ASC, `confirm_time` ASC, `id` ASC) USING BTREE COMMENT '公司维度按成交时间分页',
|
||||
INDEX `idx_channel_pdd_order_company_shop_confirm`(`company_id` ASC, `shop_id` ASC, `confirm_time` ASC, `id` ASC) USING BTREE COMMENT '店铺维度按成交时间分页',
|
||||
-- 按下单时间筛选
|
||||
INDEX `idx_channel_pdd_order_company_created`(`company_id` ASC, `created_time` ASC, `id` ASC) USING BTREE COMMENT '公司+下单时间',
|
||||
INDEX `idx_channel_pdd_order_company_shop_created`(`company_id` ASC, `shop_id` ASC, `created_time` ASC, `id` ASC) USING BTREE COMMENT '店铺+下单时间',
|
||||
-- 按支付时间筛选
|
||||
INDEX `idx_channel_pdd_order_company_pay`(`company_id` ASC, `pay_time` ASC, `id` ASC) USING BTREE COMMENT '公司+支付时间',
|
||||
INDEX `idx_channel_pdd_order_pdd_updated`(`shop_id` ASC, `pdd_updated_at` ASC) USING BTREE COMMENT '按店+平台更新时间排查/增量',
|
||||
INDEX `idx_channel_pdd_order_auth`(`pdd_auth_id` ASC) USING BTREE,
|
||||
CONSTRAINT `fk_channel_pdd_order_company` FOREIGN KEY (`company_id`) REFERENCES `org_company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
|
||||
CONSTRAINT `fk_channel_pdd_order_shop` FOREIGN KEY (`shop_id`) REFERENCES `ec_shop` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
|
||||
CONSTRAINT `fk_channel_pdd_order_auth` FOREIGN KEY (`pdd_auth_id`) REFERENCES `channel_pdd_auth` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
|
||||
CONSTRAINT `fk_channel_pdd_order_shop` FOREIGN KEY (`shop_id`) REFERENCES `channel_pdd_shop` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
|
||||
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = '拼多多-订单主表' ROW_FORMAT = Dynamic;
|
||||
|
||||
-- ========================================
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
-- 设计原则:
|
||||
-- 1. 主表一单一行;明细一行一 SKU;与具体平台表解耦,不写平台专属 FK
|
||||
-- 2. 幂等:uk(company_id, shop_id, platform_order_no)(店内平台单号唯一)
|
||||
-- 3. 追溯:source + source_order_id(镜像表主键);用 shop.platform_code 判定读哪张镜像表
|
||||
-- 3. 追溯:source(import/sync/manual);镜像回查用 platform_code + platform_order_no(渠道表 uk)
|
||||
-- 4. 明细优先绑 ec_product_sku;成本快照落明细,不随历史成本表回写
|
||||
-- 5. 平台差异字段不进主表;扩展信息留在各平台镜像 raw,转换时归一化
|
||||
-- 6. status / platform_code 均为软约定枚举(代码字典),不建状态表/平台表
|
||||
@@ -24,7 +24,6 @@ CREATE TABLE `ec_order` (
|
||||
`status` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '内部订单状态码:PENDING_SHIPMENT/SHIPPED/COMPLETED/CANCELLED/REFUNDING/REFUNDED/UNKNOWN',
|
||||
`platform_order_no` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '平台订单号',
|
||||
`source` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL DEFAULT 'import' COMMENT '来源:import-导入 sync-平台镜像转换 manual-手工',
|
||||
`source_order_id` bigint UNSIGNED NULL DEFAULT NULL COMMENT '来源平台镜像订单主键(如 channel_pdd_order.id;无跨表 FK,结合 platform 解析)',
|
||||
`pay_amount` decimal(12, 2) NOT NULL DEFAULT 0.00 COMMENT '买家实付金额(订单合计)',
|
||||
`received_amount` decimal(12, 2) NOT NULL DEFAULT 0.00 COMMENT '商家实收金额(=实付-服务费+平台优惠)',
|
||||
`service_fee` decimal(12, 2) NOT NULL DEFAULT 0.00 COMMENT '平台服务费(多平台归一;PDD 来自 service_fee_detail 汇总)',
|
||||
@@ -66,8 +65,7 @@ CREATE TABLE `ec_order` (
|
||||
INDEX `idx_ec_order_pay_time`(`pay_time` ASC) USING BTREE,
|
||||
INDEX `idx_ec_order_confirm_time`(`confirm_time` ASC) USING BTREE,
|
||||
INDEX `idx_ec_order_import_task`(`import_task_id` ASC) USING BTREE,
|
||||
INDEX `idx_ec_order_source`(`source` ASC, `source_order_id` ASC) USING BTREE,
|
||||
INDEX `idx_ec_order_company_platform_source`(`company_id` ASC, `platform_code` ASC, `source_order_id` ASC) USING BTREE COMMENT '转换按来源镜像定位',
|
||||
INDEX `idx_ec_order_source`(`source` ASC) USING BTREE,
|
||||
INDEX `idx_ec_order_confirm`(`confirm` ASC) USING BTREE,
|
||||
CONSTRAINT `fk_ec_order_company` FOREIGN KEY (`company_id`) REFERENCES `org_company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
|
||||
CONSTRAINT `fk_ec_order_shop` FOREIGN KEY (`shop_id`) REFERENCES `ec_shop` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
-- 开发阶段:渠道订单 shop_id 改为 channel_pdd_shop.id,去掉 pdd_auth_id
|
||||
-- 不兼容旧 ec_shop.id:相关表清空后改结构
|
||||
-- 外键/索引名以 information_schema 为准动态删除(避免库内命名与设计脚本不一致)
|
||||
|
||||
SET FOREIGN_KEY_CHECKS = 0;
|
||||
TRUNCATE TABLE `channel_pdd_order_item`;
|
||||
TRUNCATE TABLE `channel_pdd_order`;
|
||||
TRUNCATE TABLE `channel_pdd_order_full_sync_task_day`;
|
||||
TRUNCATE TABLE `channel_pdd_order_full_sync_task`;
|
||||
TRUNCATE TABLE `channel_pdd_order_inc_sync`;
|
||||
SET FOREIGN_KEY_CHECKS = 1;
|
||||
|
||||
DROP PROCEDURE IF EXISTS `tmp_drop_fk_on_col`;
|
||||
DROP PROCEDURE IF EXISTS `tmp_drop_idx_if_exists`;
|
||||
|
||||
DELIMITER $$
|
||||
|
||||
CREATE PROCEDURE `tmp_drop_fk_on_col`(
|
||||
IN p_table VARCHAR(64),
|
||||
IN p_column VARCHAR(64)
|
||||
)
|
||||
BEGIN
|
||||
DECLARE done INT DEFAULT 0;
|
||||
DECLARE v_fk VARCHAR(64);
|
||||
DECLARE cur CURSOR FOR
|
||||
SELECT DISTINCT CONSTRAINT_NAME
|
||||
FROM information_schema.KEY_COLUMN_USAGE
|
||||
WHERE TABLE_SCHEMA = DATABASE()
|
||||
AND TABLE_NAME = p_table
|
||||
AND COLUMN_NAME = p_column
|
||||
AND REFERENCED_TABLE_NAME IS NOT NULL;
|
||||
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;
|
||||
|
||||
OPEN cur;
|
||||
read_loop: LOOP
|
||||
FETCH cur INTO v_fk;
|
||||
IF done = 1 THEN
|
||||
LEAVE read_loop;
|
||||
END IF;
|
||||
SET @sql = CONCAT('ALTER TABLE `', p_table, '` DROP FOREIGN KEY `', v_fk, '`');
|
||||
PREPARE stmt FROM @sql;
|
||||
EXECUTE stmt;
|
||||
DEALLOCATE PREPARE stmt;
|
||||
END LOOP;
|
||||
CLOSE cur;
|
||||
END$$
|
||||
|
||||
CREATE PROCEDURE `tmp_drop_idx_if_exists`(
|
||||
IN p_table VARCHAR(64),
|
||||
IN p_index VARCHAR(64)
|
||||
)
|
||||
BEGIN
|
||||
IF EXISTS (
|
||||
SELECT 1 FROM information_schema.STATISTICS
|
||||
WHERE TABLE_SCHEMA = DATABASE()
|
||||
AND TABLE_NAME = p_table
|
||||
AND INDEX_NAME = p_index
|
||||
) THEN
|
||||
SET @sql = CONCAT('ALTER TABLE `', p_table, '` DROP INDEX `', p_index, '`');
|
||||
PREPARE stmt FROM @sql;
|
||||
EXECUTE stmt;
|
||||
DEALLOCATE PREPARE stmt;
|
||||
END IF;
|
||||
END$$
|
||||
|
||||
DELIMITER ;
|
||||
|
||||
-- ---------- channel_pdd_order ----------
|
||||
CALL `tmp_drop_fk_on_col`('channel_pdd_order', 'shop_id');
|
||||
CALL `tmp_drop_fk_on_col`('channel_pdd_order', 'pdd_auth_id');
|
||||
CALL `tmp_drop_idx_if_exists`('channel_pdd_order', 'idx_channel_pdd_order_auth');
|
||||
|
||||
ALTER TABLE `channel_pdd_order`
|
||||
DROP COLUMN `pdd_auth_id`;
|
||||
|
||||
ALTER TABLE `channel_pdd_order`
|
||||
MODIFY COLUMN `shop_id` bigint UNSIGNED NOT NULL COMMENT '渠道店铺ID(channel_pdd_shop.id)',
|
||||
ADD CONSTRAINT `fk_channel_pdd_order_shop`
|
||||
FOREIGN KEY (`shop_id`) REFERENCES `channel_pdd_shop` (`id`)
|
||||
ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- ---------- channel_pdd_order_inc_sync ----------
|
||||
CALL `tmp_drop_fk_on_col`('channel_pdd_order_inc_sync', 'shop_id');
|
||||
CALL `tmp_drop_fk_on_col`('channel_pdd_order_inc_sync', 'pdd_auth_id');
|
||||
|
||||
ALTER TABLE `channel_pdd_order_inc_sync`
|
||||
DROP COLUMN `pdd_auth_id`;
|
||||
|
||||
ALTER TABLE `channel_pdd_order_inc_sync`
|
||||
MODIFY COLUMN `shop_id` bigint UNSIGNED NOT NULL COMMENT '渠道店铺ID(channel_pdd_shop.id)',
|
||||
ADD CONSTRAINT `fk_channel_pdd_order_inc_sync_shop`
|
||||
FOREIGN KEY (`shop_id`) REFERENCES `channel_pdd_shop` (`id`)
|
||||
ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- ---------- channel_pdd_order_full_sync_task ----------
|
||||
CALL `tmp_drop_fk_on_col`('channel_pdd_order_full_sync_task', 'shop_id');
|
||||
|
||||
ALTER TABLE `channel_pdd_order_full_sync_task`
|
||||
MODIFY COLUMN `shop_id` bigint UNSIGNED NOT NULL COMMENT '渠道店铺ID(channel_pdd_shop.id)',
|
||||
ADD CONSTRAINT `fk_channel_pdd_order_full_sync_task_shop`
|
||||
FOREIGN KEY (`shop_id`) REFERENCES `channel_pdd_shop` (`id`)
|
||||
ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
ALTER TABLE `channel_pdd_order_full_sync_task_day`
|
||||
MODIFY COLUMN `shop_id` bigint UNSIGNED NOT NULL COMMENT '渠道店铺ID(channel_pdd_shop.id)';
|
||||
|
||||
DROP PROCEDURE IF EXISTS `tmp_drop_fk_on_col`;
|
||||
DROP PROCEDURE IF EXISTS `tmp_drop_idx_if_exists`;
|
||||
@@ -0,0 +1,66 @@
|
||||
-- 去掉 ec_order.source_order_id:转换/回查统一用平台单号(uk_ec_order_shop_platform_no / 渠道 uk)
|
||||
|
||||
DROP PROCEDURE IF EXISTS `tmp_drop_idx_if_exists`;
|
||||
DROP PROCEDURE IF EXISTS `tmp_drop_col_if_exists`;
|
||||
|
||||
DELIMITER $$
|
||||
|
||||
CREATE PROCEDURE `tmp_drop_idx_if_exists`(
|
||||
IN p_table VARCHAR(64),
|
||||
IN p_index VARCHAR(64)
|
||||
)
|
||||
BEGIN
|
||||
IF EXISTS (
|
||||
SELECT 1 FROM information_schema.STATISTICS
|
||||
WHERE TABLE_SCHEMA = DATABASE()
|
||||
AND TABLE_NAME = p_table
|
||||
AND INDEX_NAME = p_index
|
||||
) THEN
|
||||
SET @sql = CONCAT('ALTER TABLE `', p_table, '` DROP INDEX `', p_index, '`');
|
||||
PREPARE stmt FROM @sql;
|
||||
EXECUTE stmt;
|
||||
DEALLOCATE PREPARE stmt;
|
||||
END IF;
|
||||
END$$
|
||||
|
||||
CREATE PROCEDURE `tmp_drop_col_if_exists`(
|
||||
IN p_table VARCHAR(64),
|
||||
IN p_column VARCHAR(64)
|
||||
)
|
||||
BEGIN
|
||||
IF EXISTS (
|
||||
SELECT 1 FROM information_schema.COLUMNS
|
||||
WHERE TABLE_SCHEMA = DATABASE()
|
||||
AND TABLE_NAME = p_table
|
||||
AND COLUMN_NAME = p_column
|
||||
) THEN
|
||||
SET @sql = CONCAT('ALTER TABLE `', p_table, '` DROP COLUMN `', p_column, '`');
|
||||
PREPARE stmt FROM @sql;
|
||||
EXECUTE stmt;
|
||||
DEALLOCATE PREPARE stmt;
|
||||
END IF;
|
||||
END$$
|
||||
|
||||
DELIMITER ;
|
||||
|
||||
CALL `tmp_drop_idx_if_exists`('ec_order', 'idx_ec_order_company_platform_source');
|
||||
CALL `tmp_drop_idx_if_exists`('ec_order', 'idx_ec_order_source');
|
||||
|
||||
-- 重建仅按 source 的轻量索引
|
||||
SET @has_source_idx := (
|
||||
SELECT COUNT(1) FROM information_schema.STATISTICS
|
||||
WHERE TABLE_SCHEMA = DATABASE()
|
||||
AND TABLE_NAME = 'ec_order'
|
||||
AND INDEX_NAME = 'idx_ec_order_source'
|
||||
);
|
||||
SET @sql := IF(@has_source_idx = 0,
|
||||
'ALTER TABLE `ec_order` ADD INDEX `idx_ec_order_source`(`source`)',
|
||||
'SELECT 1');
|
||||
PREPARE stmt FROM @sql;
|
||||
EXECUTE stmt;
|
||||
DEALLOCATE PREPARE stmt;
|
||||
|
||||
CALL `tmp_drop_col_if_exists`('ec_order', 'source_order_id');
|
||||
|
||||
DROP PROCEDURE IF EXISTS `tmp_drop_idx_if_exists`;
|
||||
DROP PROCEDURE IF EXISTS `tmp_drop_col_if_exists`;
|
||||
+1
-1
@@ -7,7 +7,7 @@ import lombok.NoArgsConstructor;
|
||||
|
||||
/**
|
||||
* 渠道订单引用:镜像表主键。
|
||||
* 转换侧按 id 查渠道镜像;内部单用 platform_code + source_order_id 定位。
|
||||
* 转换侧按 id 查渠道镜像;内部单按平台单号幂等键定位。
|
||||
*/
|
||||
@Data
|
||||
@Builder
|
||||
|
||||
+38
-20
@@ -36,6 +36,9 @@ import top.xyquan.ecomdmbbackend.modules.ec.product.model.po.ProductSkuCostPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.model.po.ProductSkuPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.service.ProductSkuCostService;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.service.ProductSkuService;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.shop.mapper.ShopMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.shop.model.po.ShopPO;
|
||||
import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.time.LocalDate;
|
||||
@@ -70,6 +73,7 @@ public class PddOrderConvertService {
|
||||
private final PlatformTransactionManager transactionManager;
|
||||
private final OrderStatContributionCalculator contributionCalculator;
|
||||
private final OrderStatusStatResolver orderStatusStatResolver;
|
||||
private final ShopMapper shopMapper;
|
||||
|
||||
public void convert(OrderConvertMessage message) {
|
||||
if (message.getMode() == OrderConvertMode.FULL_DAY) {
|
||||
@@ -80,9 +84,10 @@ public class PddOrderConvertService {
|
||||
// 必须等转换事务提交后再投递 BI / 自动建品,否则消费者可能读到未提交快照
|
||||
ConvertBatchResult result = tt.execute(status -> convertFullDay(message));
|
||||
if (result != null) {
|
||||
Long internalShopId = requireInternalShopId(message.getCompanyId(), message.getShopId());
|
||||
for (LocalDate d : result.biDates()) {
|
||||
biCalcPublisher.publishFull(
|
||||
message.getCompanyId(), message.getShopId(), d, message.getSyncBatchId());
|
||||
message.getCompanyId(), internalShopId, d, message.getSyncBatchId());
|
||||
}
|
||||
publishAutoCreate(message.getCompanyId(), message.getShopId(), result.pendingGoodsIds());
|
||||
}
|
||||
@@ -113,7 +118,7 @@ public class PddOrderConvertService {
|
||||
}
|
||||
SkuBindContext bindCtx = preloadSkuBind(message.getCompanyId(), channelOrders);
|
||||
for (PddOrderPO channel : channelOrders) {
|
||||
OrderPO existing = findInternalBySource(channel);
|
||||
OrderPO existing = findInternalOrder(channel);
|
||||
if (existing != null && !isChannelNewer(channel, existing)) {
|
||||
continue;
|
||||
}
|
||||
@@ -131,7 +136,7 @@ public class PddOrderConvertService {
|
||||
|
||||
/**
|
||||
* 增量:消息带渠道镜像主键列表;按 id 查渠道单。
|
||||
* 内部单用 platform_code + source_order_id 定位:无则新增;有则仅当渠道更新时间更新时覆盖,并产出 BI delta。
|
||||
* 内部单按 uk(company, shop, platform_order_no) 定位;仅当渠道更新时间更新时覆盖并产出 BI delta。
|
||||
* @return 未绑定需异步建品的 goodsId
|
||||
*/
|
||||
private Set<Long> convertInc(OrderConvertMessage message) {
|
||||
@@ -159,7 +164,7 @@ public class PddOrderConvertService {
|
||||
SkuBindContext bindCtx = preloadSkuBind(message.getCompanyId(), channels);
|
||||
|
||||
for (PddOrderPO channel : channels) {
|
||||
OrderPO oldOrder = findInternalBySource(channel);
|
||||
OrderPO oldOrder = findInternalOrder(channel);
|
||||
if (oldOrder != null && !isChannelNewer(channel, oldOrder)) {
|
||||
log.info("跳过 INC 转换(内部已是最新) channelOrderId={} platformUpdatedAt={}",
|
||||
channel.getId(), oldOrder.getPlatformUpdatedAt());
|
||||
@@ -191,11 +196,16 @@ public class PddOrderConvertService {
|
||||
return bindCtx.pendingGoodsIds();
|
||||
}
|
||||
|
||||
private OrderPO findInternalBySource(PddOrderPO channel) {
|
||||
/** 定位内部单:uk(company_id, shop_id, platform_order_no)。 */
|
||||
private OrderPO findInternalOrder(PddOrderPO channel) {
|
||||
if (!StringUtils.hasText(channel.getOrderSn())) {
|
||||
return null;
|
||||
}
|
||||
Long internalShopId = requireInternalShopId(channel.getCompanyId(), channel.getShopId());
|
||||
return orderMapper.selectOne(new LambdaQueryWrapper<OrderPO>()
|
||||
.eq(OrderPO::getCompanyId, channel.getCompanyId())
|
||||
.eq(OrderPO::getPlatformCode, PlatformCode.PDD.getCode())
|
||||
.eq(OrderPO::getSourceOrderId, channel.getId())
|
||||
.eq(OrderPO::getShopId, internalShopId)
|
||||
.eq(OrderPO::getPlatformOrderNo, channel.getOrderSn())
|
||||
.last("LIMIT 1"));
|
||||
}
|
||||
|
||||
@@ -230,7 +240,9 @@ public class PddOrderConvertService {
|
||||
skuByDate.getOrDefault(date, Map.of()).values());
|
||||
skus.removeIf(s -> s.getMetrics() == null || s.getMetrics().isAllZero());
|
||||
biCalcPublisher.publishIncDelta(
|
||||
message.getCompanyId(), message.getShopId(), date, internalOrderUpdateTime,
|
||||
message.getCompanyId(),
|
||||
requireInternalShopId(message.getCompanyId(), message.getShopId()),
|
||||
date, internalOrderUpdateTime,
|
||||
orderId, channelOrderId, shopDelta, products, skus);
|
||||
}
|
||||
}
|
||||
@@ -324,25 +336,16 @@ public class PddOrderConvertService {
|
||||
}
|
||||
|
||||
private OrderPO upsertInternalOrder(PddOrderPO channel, LocalDateTime mappedAt, SkuBindContext bindCtx) {
|
||||
OrderPO existing = findInternalBySource(channel);
|
||||
if (existing == null) {
|
||||
// 兼容:早期仅按平台单号落库、尚未写 source_order_id 的行
|
||||
existing = orderMapper.selectOne(new LambdaQueryWrapper<OrderPO>()
|
||||
.eq(OrderPO::getCompanyId, channel.getCompanyId())
|
||||
.eq(OrderPO::getShopId, channel.getShopId())
|
||||
.eq(OrderPO::getPlatformOrderNo, channel.getOrderSn())
|
||||
.last("LIMIT 1"));
|
||||
}
|
||||
|
||||
Long internalShopId = requireInternalShopId(channel.getCompanyId(), channel.getShopId());
|
||||
OrderPO existing = findInternalOrder(channel);
|
||||
OrderPO order = existing != null ? existing : new OrderPO();
|
||||
order.setCompanyId(channel.getCompanyId());
|
||||
order.setShopId(channel.getShopId());
|
||||
order.setShopId(internalShopId);
|
||||
order.setPlatformCode(PlatformCode.PDD.getCode());
|
||||
OrderStatus status = PddOrderStatusMapper.map(channel.getOrderStatus(), channel.getRefundStatus());
|
||||
order.setStatus(status.getCode());
|
||||
order.setPlatformOrderNo(channel.getOrderSn());
|
||||
order.setSource("sync");
|
||||
order.setSourceOrderId(channel.getId());
|
||||
order.setPayAmount(nz(channel.getPayAmount()));
|
||||
order.setGoodsAmount(channel.getGoodsAmount());
|
||||
order.setDiscountAmount(channel.getDiscountAmount());
|
||||
@@ -483,6 +486,21 @@ public class PddOrderConvertService {
|
||||
return new SkuBindContext(itemsByOrderId, skuByCode, costs, new HashSet<>());
|
||||
}
|
||||
|
||||
private Long requireInternalShopId(Long companyId, Long channelShopId) {
|
||||
if (channelShopId == null) {
|
||||
throw new BusinessException("渠道店铺 ID 不能为空");
|
||||
}
|
||||
ShopPO shop = shopMapper.selectOne(new LambdaQueryWrapper<ShopPO>()
|
||||
.eq(ShopPO::getCompanyId, companyId)
|
||||
.eq(ShopPO::getPlatformCode, PlatformCode.PDD.getCode())
|
||||
.eq(ShopPO::getExternalShopId, channelShopId)
|
||||
.last("LIMIT 1"));
|
||||
if (shop == null) {
|
||||
throw new BusinessException("未找到绑定该拼多多店的内部店铺,无法写入经营订单");
|
||||
}
|
||||
return shop.getId();
|
||||
}
|
||||
|
||||
private record ConvertBatchResult(Set<LocalDate> biDates, Set<Long> pendingGoodsIds) {
|
||||
}
|
||||
|
||||
|
||||
+2
-1
@@ -63,7 +63,8 @@ public class PddProductAutoCreateService {
|
||||
|| message.getShopId() == null || message.getGoodsId() == null) {
|
||||
return;
|
||||
}
|
||||
PddOrderSyncShopContext ctx = contextResolver.resolve(message.getCompanyId(), message.getShopId());
|
||||
PddOrderSyncShopContext ctx = contextResolver.resolveByChannelShopId(
|
||||
message.getCompanyId(), message.getShopId());
|
||||
if (ctx.getPddShop() == null || ctx.getPddShop().getId() == null) {
|
||||
log.warn("自动建品:缺少渠道店铺,跳过 companyId={} goodsId={}",
|
||||
message.getCompanyId(), message.getGoodsId());
|
||||
|
||||
-2
@@ -14,8 +14,6 @@ public class CreatePddOrderDTO {
|
||||
@NotNull(message = "店铺ID不能为空")
|
||||
private Long shopId;
|
||||
|
||||
private Long pddAuthId;
|
||||
|
||||
@NotBlank(message = "拼多多订单号不能为空")
|
||||
private String orderSn;
|
||||
|
||||
|
||||
+2
@@ -4,9 +4,11 @@ import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/** 拼多多渠道订单列表筛选;shopId 为 channel_pdd_shop.id。 */
|
||||
@Data
|
||||
public class PddOrderFilterDTO {
|
||||
|
||||
/** 渠道店铺 ID(channel_pdd_shop.id) */
|
||||
private Long shopId;
|
||||
|
||||
private String orderSn;
|
||||
|
||||
-2
@@ -14,8 +14,6 @@ public class UpdatePddOrderDTO {
|
||||
@NotNull(message = "店铺ID不能为空")
|
||||
private Long shopId;
|
||||
|
||||
private Long pddAuthId;
|
||||
|
||||
@NotBlank(message = "拼多多订单号不能为空")
|
||||
private String orderSn;
|
||||
|
||||
|
||||
-3
@@ -19,9 +19,6 @@ public class PddOrderPO {
|
||||
@TableField("shop_id")
|
||||
private Long shopId;
|
||||
|
||||
@TableField("pdd_auth_id")
|
||||
private Long pddAuthId;
|
||||
|
||||
@TableField("order_sn")
|
||||
private String orderSn;
|
||||
|
||||
|
||||
+7
-1
@@ -6,6 +6,10 @@ import java.math.BigDecimal;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 拼多多渠道订单返回体。
|
||||
* shopId 为 channel_pdd_shop.id;shopName 为展示用 mall_name。
|
||||
*/
|
||||
@Data
|
||||
public class PddOrderVO {
|
||||
|
||||
@@ -13,9 +17,11 @@ public class PddOrderVO {
|
||||
|
||||
private Long companyId;
|
||||
|
||||
/** 渠道店铺 ID(channel_pdd_shop.id) */
|
||||
private Long shopId;
|
||||
|
||||
private Long pddAuthId;
|
||||
/** 渠道店铺名称(channel_pdd_shop.mall_name) */
|
||||
private String shopName;
|
||||
|
||||
private String orderSn;
|
||||
|
||||
|
||||
+53
-4
@@ -21,20 +21,32 @@ import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.model.po.PddOrderPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.model.vo.PddOrderItemVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.model.vo.PddOrderVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.service.PddOrderService;
|
||||
import top.xyquan.ecomdmbbackend.modules.channel.pdd.shop.mapper.PddShopMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.channel.pdd.shop.model.po.PddShopPO;
|
||||
import top.xyquan.ecomdmbbackend.utils.CurrentUserContext;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
import java.util.function.Function;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/** 拼多多渠道订单 CRUD;列表/详情补全渠道店铺展示名。 */
|
||||
@Service
|
||||
public class PddOrderServiceImpl extends ServiceImpl<PddOrderMapper, PddOrderPO> implements PddOrderService {
|
||||
|
||||
private final PddOrderItemMapper pddOrderItemMapper;
|
||||
private final PddShopMapper pddShopMapper;
|
||||
private final CurrentUserContext currentUserContext;
|
||||
|
||||
public PddOrderServiceImpl(PddOrderItemMapper pddOrderItemMapper, CurrentUserContext currentUserContext) {
|
||||
public PddOrderServiceImpl(PddOrderItemMapper pddOrderItemMapper,
|
||||
PddShopMapper pddShopMapper,
|
||||
CurrentUserContext currentUserContext) {
|
||||
this.pddOrderItemMapper = pddOrderItemMapper;
|
||||
this.pddShopMapper = pddShopMapper;
|
||||
this.currentUserContext = currentUserContext;
|
||||
}
|
||||
|
||||
@@ -62,7 +74,7 @@ public class PddOrderServiceImpl extends ServiceImpl<PddOrderMapper, PddOrderPO>
|
||||
items.forEach(pddOrderItemMapper::insert);
|
||||
}
|
||||
|
||||
return convertToVO(order);
|
||||
return toVoWithShop(order);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -100,7 +112,7 @@ public class PddOrderServiceImpl extends ServiceImpl<PddOrderMapper, PddOrderPO>
|
||||
items.forEach(pddOrderItemMapper::insert);
|
||||
}
|
||||
|
||||
return convertToVO(order);
|
||||
return toVoWithShop(order);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -169,6 +181,7 @@ public class PddOrderServiceImpl extends ServiceImpl<PddOrderMapper, PddOrderPO>
|
||||
List<PddOrderVO> voList = result.getRecords().stream()
|
||||
.map(this::convertToVO)
|
||||
.collect(Collectors.toList());
|
||||
fillShopNames(voList);
|
||||
|
||||
return PageResultVO.create(voList, result.getTotal(),
|
||||
(int) pageQueryDTO.getPage(), (int) pageQueryDTO.getPageSize());
|
||||
@@ -180,7 +193,43 @@ public class PddOrderServiceImpl extends ServiceImpl<PddOrderMapper, PddOrderPO>
|
||||
if (order == null) {
|
||||
throw new BusinessException("订单不存在");
|
||||
}
|
||||
return convertToVO(order);
|
||||
return toVoWithShop(order);
|
||||
}
|
||||
|
||||
private PddOrderVO toVoWithShop(PddOrderPO order) {
|
||||
PddOrderVO vo = convertToVO(order);
|
||||
fillShopNames(Collections.singletonList(vo));
|
||||
return vo;
|
||||
}
|
||||
|
||||
/** 按渠道店铺 ID 批量补全 shopName,避免列表 N+1。 */
|
||||
private void fillShopNames(List<PddOrderVO> vos) {
|
||||
if (vos == null || vos.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
Set<Long> shopIds = new HashSet<>();
|
||||
for (PddOrderVO vo : vos) {
|
||||
if (vo.getShopId() != null) {
|
||||
shopIds.add(vo.getShopId());
|
||||
}
|
||||
}
|
||||
if (shopIds.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
Map<Long, PddShopPO> shopMap = pddShopMapper.selectList(
|
||||
new LambdaQueryWrapper<PddShopPO>().in(PddShopPO::getId, shopIds))
|
||||
.stream()
|
||||
.filter(Objects::nonNull)
|
||||
.collect(Collectors.toMap(PddShopPO::getId, Function.identity(), (a, b) -> a));
|
||||
for (PddOrderVO vo : vos) {
|
||||
if (vo.getShopId() == null) {
|
||||
continue;
|
||||
}
|
||||
PddShopPO shop = shopMap.get(vo.getShopId());
|
||||
if (shop != null) {
|
||||
vo.setShopName(shop.getMallName());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private PddOrderItemPO convertToItemPO(CreatePddOrderItemDTO dto, Long orderId, Long companyId, String orderSn) {
|
||||
|
||||
+4
-4
@@ -46,14 +46,14 @@ public class PddOrderIncrementalSyncJob {
|
||||
if (!done.add(shop.getId())) {
|
||||
continue;
|
||||
}
|
||||
if (fullSyncTaskService.isIncrementalPaused(shop.getId())) {
|
||||
log.debug("跳过出错暂停的增量店铺 shopId={}", shop.getId());
|
||||
if (fullSyncTaskService.isIncrementalPaused(shop.getExternalShopId())) {
|
||||
log.debug("跳过出错暂停的增量店铺 channelShopId={}", shop.getExternalShopId());
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
syncPublisher.publishInc(shop.getCompanyId(), shop.getId());
|
||||
syncPublisher.publishInc(shop.getCompanyId(), shop.getExternalShopId());
|
||||
} catch (Exception e) {
|
||||
log.warn("投递增量同步失败 shopId={}: {}", shop.getId(), e.getMessage());
|
||||
log.warn("投递增量同步失败 channelShopId={}: {}", shop.getExternalShopId(), e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+5
@@ -8,6 +8,8 @@ import top.xyquan.ecomdmbbackend.modules.ec.shop.model.po.ShopPO;
|
||||
|
||||
/**
|
||||
* 一次同步所需的店铺/授权上下文。
|
||||
* shopId = channel_pdd_shop.id(写入渠道表与本模块 MQ);
|
||||
* internalShopId = ec_shop.id(增量开关、ec_order、BI)。
|
||||
*/
|
||||
@Data
|
||||
@Builder
|
||||
@@ -17,7 +19,10 @@ public class PddOrderSyncShopContext {
|
||||
private PddShopPO pddShop;
|
||||
private PddAuthPO auth;
|
||||
private Long companyId;
|
||||
/** 渠道店铺 ID(channel_pdd_shop.id) */
|
||||
private Long shopId;
|
||||
/** 内部店铺 ID(ec_shop.id) */
|
||||
private Long internalShopId;
|
||||
private Long mallId;
|
||||
private String accessToken;
|
||||
}
|
||||
|
||||
-3
@@ -25,9 +25,6 @@ public class PddOrderIncSyncPO {
|
||||
@TableField("shop_id")
|
||||
private Long shopId;
|
||||
|
||||
@TableField("pdd_auth_id")
|
||||
private Long pddAuthId;
|
||||
|
||||
@TableField("last_cursor_at")
|
||||
private LocalDateTime lastCursorAt;
|
||||
|
||||
|
||||
+14
-2
@@ -1,9 +1,12 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.service;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Component;
|
||||
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.model.po.PddOrderFullSyncTaskPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.model.vo.PddOrderFullSyncTaskVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.shop.mapper.ShopMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.shop.model.po.ShopPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.notify.sse.RealtimeSseEvents;
|
||||
import top.xyquan.ecomdmbbackend.modules.notify.sse.RealtimeSseService;
|
||||
|
||||
@@ -17,6 +20,7 @@ import java.util.Map;
|
||||
public class PddOrderFullSyncProgressPublisher {
|
||||
|
||||
private final RealtimeSseService realtimeSseService;
|
||||
private final ShopMapper shopMapper;
|
||||
|
||||
public void publish(PddOrderFullSyncTaskPO task) {
|
||||
if (task == null || task.getCompanyId() == null) {
|
||||
@@ -37,10 +41,18 @@ public class PddOrderFullSyncProgressPublisher {
|
||||
}
|
||||
}
|
||||
|
||||
private static PddOrderFullSyncTaskVO toVo(PddOrderFullSyncTaskPO task) {
|
||||
private PddOrderFullSyncTaskVO toVo(PddOrderFullSyncTaskPO task) {
|
||||
Long apiShopId = task.getShopId();
|
||||
ShopPO shop = shopMapper.selectOne(new LambdaQueryWrapper<ShopPO>()
|
||||
.eq(ShopPO::getCompanyId, task.getCompanyId())
|
||||
.eq(ShopPO::getExternalShopId, task.getShopId())
|
||||
.last("LIMIT 1"));
|
||||
if (shop != null) {
|
||||
apiShopId = shop.getId();
|
||||
}
|
||||
return PddOrderFullSyncTaskVO.builder()
|
||||
.id(task.getId())
|
||||
.shopId(task.getShopId())
|
||||
.shopId(apiShopId)
|
||||
.dateFrom(task.getDateFrom())
|
||||
.dateTo(task.getDateTo())
|
||||
.currentDate(task.getCurrentDate())
|
||||
|
||||
+45
-21
@@ -81,7 +81,7 @@ public class PddOrderFullSyncTaskService {
|
||||
PddOrderSyncShopContext ctx = contextResolver.resolveForCurrentCompany(dto.getShopId());
|
||||
|
||||
PddOrderFullSyncTaskPO active = taskMapper.selectOne(new LambdaQueryWrapper<PddOrderFullSyncTaskPO>()
|
||||
.eq(PddOrderFullSyncTaskPO::getShopId, dto.getShopId())
|
||||
.eq(PddOrderFullSyncTaskPO::getShopId, ctx.getShopId())
|
||||
.in(PddOrderFullSyncTaskPO::getStatus,
|
||||
PddOrderFullSyncTaskPO.STATUS_PENDING, PddOrderFullSyncTaskPO.STATUS_RUNNING)
|
||||
.orderByDesc(PddOrderFullSyncTaskPO::getId)
|
||||
@@ -107,7 +107,7 @@ public class PddOrderFullSyncTaskService {
|
||||
Long taskId = task.getId();
|
||||
scheduleAfterCommit(taskId);
|
||||
progressPublisher.publish(task);
|
||||
return toVo(task);
|
||||
return toVo(task, ctx.getInternalShopId());
|
||||
}
|
||||
|
||||
private void insertDayRows(PddOrderFullSyncTaskPO task) {
|
||||
@@ -172,19 +172,21 @@ public class PddOrderFullSyncTaskService {
|
||||
.eq(PddOrderFullSyncTaskPO::getShopId, ctx.getShopId())
|
||||
.orderByDesc(PddOrderFullSyncTaskPO::getId)
|
||||
.last("LIMIT " + lim));
|
||||
return tasks.stream().map(PddOrderFullSyncTaskService::toVo).collect(Collectors.toList());
|
||||
return tasks.stream()
|
||||
.map(t -> toVo(t, ctx.getInternalShopId()))
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
public PddOrderFullSyncTaskVO getTask(Long taskId) {
|
||||
PddOrderFullSyncTaskPO task = requireOwnedTask(taskId);
|
||||
return toVo(task);
|
||||
return toVo(task, resolveApiShopId(task));
|
||||
}
|
||||
|
||||
/** 进行中优先,否则该店最近一次全量任务。 */
|
||||
public PddOrderFullSyncTaskVO latestTask(Long shopId) {
|
||||
PddOrderSyncShopContext ctx = contextResolver.resolveForCurrentCompany(shopId);
|
||||
PddOrderFullSyncTaskPO task = findLatestTask(ctx.getCompanyId(), ctx.getShopId());
|
||||
return task == null ? null : toVo(task);
|
||||
return task == null ? null : toVo(task, ctx.getInternalShopId());
|
||||
}
|
||||
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
@@ -203,7 +205,7 @@ public class PddOrderFullSyncTaskService {
|
||||
task.setLastError(null);
|
||||
taskMapper.updateById(task);
|
||||
progressPublisher.publish(task);
|
||||
return toVo(task);
|
||||
return toVo(task, resolveApiShopId(task));
|
||||
}
|
||||
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
@@ -243,7 +245,7 @@ public class PddOrderFullSyncTaskService {
|
||||
|
||||
scheduleAfterCommit(task.getId());
|
||||
progressPublisher.publish(task);
|
||||
return toVo(task);
|
||||
return toVo(task, resolveApiShopId(task));
|
||||
}
|
||||
|
||||
public List<PddOrderSyncShopStatusVO> batchStatus(List<Long> shopIds) {
|
||||
@@ -266,8 +268,13 @@ public class PddOrderFullSyncTaskService {
|
||||
Map<Long, ShopPO> shopMap = shops.stream()
|
||||
.collect(Collectors.toMap(ShopPO::getId, s -> s, (a, b) -> a));
|
||||
|
||||
Map<Long, PddOrderFullSyncTaskPO> latestByShop = loadLatestTasksByShop(companyId, owned);
|
||||
Map<Long, PddOrderIncSyncPO> incByShop = loadIncStatesByShop(owned);
|
||||
Map<Long, Long> ecToChannel = shops.stream()
|
||||
.filter(s -> s.getExternalShopId() != null)
|
||||
.collect(Collectors.toMap(ShopPO::getId, ShopPO::getExternalShopId, (a, b) -> a));
|
||||
Set<Long> channelIds = new HashSet<>(ecToChannel.values());
|
||||
|
||||
Map<Long, PddOrderFullSyncTaskPO> latestByChannel = loadLatestTasksByShop(companyId, channelIds);
|
||||
Map<Long, PddOrderIncSyncPO> incByChannel = loadIncStatesByShop(channelIds);
|
||||
|
||||
List<PddOrderSyncShopStatusVO> result = new ArrayList<>();
|
||||
for (Long shopId : distinctIds) {
|
||||
@@ -275,12 +282,13 @@ public class PddOrderFullSyncTaskService {
|
||||
continue;
|
||||
}
|
||||
ShopPO shop = shopMap.get(shopId);
|
||||
PddOrderFullSyncTaskPO full = latestByShop.get(shopId);
|
||||
PddOrderIncSyncPO inc = incByShop.get(shopId);
|
||||
Long channelId = ecToChannel.get(shopId);
|
||||
PddOrderFullSyncTaskPO full = channelId == null ? null : latestByChannel.get(channelId);
|
||||
PddOrderIncSyncPO inc = channelId == null ? null : incByChannel.get(channelId);
|
||||
boolean enabled = shop != null && Integer.valueOf(1).equals(shop.getOrderIncSyncEnabled());
|
||||
result.add(PddOrderSyncShopStatusVO.builder()
|
||||
.shopId(shopId)
|
||||
.fullTask(full == null ? null : toVo(full))
|
||||
.fullTask(full == null ? null : toVo(full, shopId))
|
||||
.incremental(toIncVo(shopId, enabled, inc))
|
||||
.build());
|
||||
}
|
||||
@@ -290,7 +298,7 @@ public class PddOrderFullSyncTaskService {
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public PddOrderIncrementalStatusVO toggleIncremental(PddOrderIncrementalToggleDTO dto) {
|
||||
PddOrderSyncShopContext ctx = contextResolver.resolveForCurrentCompany(dto.getShopId());
|
||||
ShopPO shop = shopMapper.selectById(ctx.getShopId());
|
||||
ShopPO shop = shopMapper.selectById(ctx.getInternalShopId());
|
||||
if (shop == null) {
|
||||
throw new BusinessException("店铺不存在");
|
||||
}
|
||||
@@ -304,15 +312,15 @@ public class PddOrderFullSyncTaskService {
|
||||
state.setLastError(null);
|
||||
incSyncMapper.updateById(state);
|
||||
}
|
||||
return incrementalStatus(ctx.getShopId());
|
||||
return incrementalStatus(ctx.getInternalShopId());
|
||||
}
|
||||
|
||||
public PddOrderIncrementalStatusVO incrementalStatus(Long shopId) {
|
||||
PddOrderSyncShopContext ctx = contextResolver.resolveForCurrentCompany(shopId);
|
||||
ShopPO shop = shopMapper.selectById(ctx.getShopId());
|
||||
ShopPO shop = shopMapper.selectById(ctx.getInternalShopId());
|
||||
PddOrderIncSyncPO state = findIncState(ctx.getShopId());
|
||||
boolean enabled = shop != null && Integer.valueOf(1).equals(shop.getOrderIncSyncEnabled());
|
||||
return toIncVo(shopId, enabled, state);
|
||||
return toIncVo(ctx.getInternalShopId(), enabled, state);
|
||||
}
|
||||
|
||||
public boolean isIncrementalEnabled(Long shopId) {
|
||||
@@ -320,8 +328,9 @@ public class PddOrderFullSyncTaskService {
|
||||
return shop != null && Integer.valueOf(1).equals(shop.getOrderIncSyncEnabled());
|
||||
}
|
||||
|
||||
public boolean isIncrementalPaused(Long shopId) {
|
||||
PddOrderIncSyncPO state = findIncState(shopId);
|
||||
/** @param channelShopId channel_pdd_shop.id */
|
||||
public boolean isIncrementalPaused(Long channelShopId) {
|
||||
PddOrderIncSyncPO state = findIncState(channelShopId);
|
||||
return state != null && Integer.valueOf(PddOrderIncSyncPO.STATUS_PAUSED).equals(state.getStatus());
|
||||
}
|
||||
|
||||
@@ -330,7 +339,7 @@ public class PddOrderFullSyncTaskService {
|
||||
if (task == null) {
|
||||
throw new BusinessException("全量同步任务不存在");
|
||||
}
|
||||
PddOrderSyncShopContext ctx = contextResolver.resolveForCurrentCompany(task.getShopId());
|
||||
PddOrderSyncShopContext ctx = contextResolver.resolveByChannelShopId(task.getCompanyId(), task.getShopId());
|
||||
if (!ctx.getCompanyId().equals(task.getCompanyId())) {
|
||||
throw new BusinessException("无权操作该任务");
|
||||
}
|
||||
@@ -411,7 +420,6 @@ public class PddOrderFullSyncTaskService {
|
||||
PddOrderIncSyncPO state = new PddOrderIncSyncPO();
|
||||
state.setCompanyId(ctx.getCompanyId());
|
||||
state.setShopId(ctx.getShopId());
|
||||
state.setPddAuthId(ctx.getAuth().getId());
|
||||
state.setOverlapSeconds(syncProperties.getOverlapSeconds());
|
||||
state.setStatus(PddOrderIncSyncPO.STATUS_OK);
|
||||
incSyncMapper.insert(state);
|
||||
@@ -448,10 +456,26 @@ public class PddOrderFullSyncTaskService {
|
||||
return HEALTH_OK;
|
||||
}
|
||||
|
||||
private Long resolveApiShopId(PddOrderFullSyncTaskPO task) {
|
||||
if (task == null || task.getShopId() == null) {
|
||||
return null;
|
||||
}
|
||||
ShopPO shop = shopMapper.selectOne(new LambdaQueryWrapper<ShopPO>()
|
||||
.eq(ShopPO::getCompanyId, task.getCompanyId())
|
||||
.eq(ShopPO::getExternalShopId, task.getShopId())
|
||||
.last("LIMIT 1"));
|
||||
return shop != null ? shop.getId() : task.getShopId();
|
||||
}
|
||||
|
||||
private static PddOrderFullSyncTaskVO toVo(PddOrderFullSyncTaskPO task) {
|
||||
return toVo(task, task.getShopId());
|
||||
}
|
||||
|
||||
/** @param apiShopId 对前端暴露的店铺 ID(内部 ec_shop.id) */
|
||||
private static PddOrderFullSyncTaskVO toVo(PddOrderFullSyncTaskPO task, Long apiShopId) {
|
||||
return PddOrderFullSyncTaskVO.builder()
|
||||
.id(task.getId())
|
||||
.shopId(task.getShopId())
|
||||
.shopId(apiShopId)
|
||||
.dateFrom(task.getDateFrom())
|
||||
.dateTo(task.getDateTo())
|
||||
.currentDate(task.getCurrentDate())
|
||||
|
||||
+37
-23
@@ -29,13 +29,35 @@ public class PddOrderSyncAuthFailureHandler {
|
||||
private final PddShopMapper pddShopMapper;
|
||||
private final PddOrderIncSyncMapper incSyncMapper;
|
||||
|
||||
/**
|
||||
* @param internalShopId 内部店 ec_shop.id(可空)
|
||||
* @param channelShopId 渠道店 channel_pdd_shop.id(可空;与 internal 至少其一)
|
||||
*/
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public void handle(Long companyId, Long shopId, Long authId, String error) {
|
||||
public void handle(Long companyId, Long internalShopId, Long channelShopId, Long authId, String error) {
|
||||
String msg = truncate(error, 900);
|
||||
log.warn("拼多多同步授权失效处置 companyId={} shopId={} authId={} err={}",
|
||||
companyId, shopId, authId, msg);
|
||||
log.warn("拼多多同步授权失效处置 companyId={} internalShopId={} channelShopId={} authId={} err={}",
|
||||
companyId, internalShopId, channelShopId, authId, msg);
|
||||
|
||||
Long resolvedAuthId = authId != null ? authId : resolveAuthId(companyId, shopId);
|
||||
Long resolvedInternal = internalShopId;
|
||||
Long resolvedChannel = channelShopId;
|
||||
if (resolvedInternal != null && resolvedChannel == null) {
|
||||
ShopPO shop = shopMapper.selectById(resolvedInternal);
|
||||
if (shop != null) {
|
||||
resolvedChannel = shop.getExternalShopId();
|
||||
}
|
||||
}
|
||||
if (resolvedChannel != null && resolvedInternal == null) {
|
||||
ShopPO shop = shopMapper.selectOne(new LambdaQueryWrapper<ShopPO>()
|
||||
.eq(companyId != null, ShopPO::getCompanyId, companyId)
|
||||
.eq(ShopPO::getExternalShopId, resolvedChannel)
|
||||
.last("LIMIT 1"));
|
||||
if (shop != null) {
|
||||
resolvedInternal = shop.getId();
|
||||
}
|
||||
}
|
||||
|
||||
Long resolvedAuthId = authId != null ? authId : resolveAuthId(companyId, resolvedChannel);
|
||||
if (resolvedAuthId != null) {
|
||||
pddAuthMapper.update(null, new LambdaUpdateWrapper<PddAuthPO>()
|
||||
.eq(PddAuthPO::getId, resolvedAuthId)
|
||||
@@ -43,27 +65,25 @@ public class PddOrderSyncAuthFailureHandler {
|
||||
.set(PddAuthPO::getStatus, 0));
|
||||
}
|
||||
|
||||
if (shopId != null) {
|
||||
if (resolvedInternal != null) {
|
||||
shopMapper.update(null, new LambdaUpdateWrapper<ShopPO>()
|
||||
.eq(ShopPO::getId, shopId)
|
||||
.eq(ShopPO::getId, resolvedInternal)
|
||||
.eq(companyId != null, ShopPO::getCompanyId, companyId)
|
||||
.set(ShopPO::getOrderIncSyncEnabled, 0));
|
||||
}
|
||||
|
||||
if (resolvedChannel != null && companyId != null) {
|
||||
PddOrderIncSyncPO state = incSyncMapper.selectOne(new LambdaQueryWrapper<PddOrderIncSyncPO>()
|
||||
.eq(PddOrderIncSyncPO::getShopId, shopId)
|
||||
.eq(PddOrderIncSyncPO::getShopId, resolvedChannel)
|
||||
.last("LIMIT 1"));
|
||||
if (state != null) {
|
||||
state.setStatus(PddOrderIncSyncPO.STATUS_PAUSED);
|
||||
state.setLastError(msg != null ? msg : "拼多多授权失效,请重新授权");
|
||||
if (resolvedAuthId != null) {
|
||||
state.setPddAuthId(resolvedAuthId);
|
||||
}
|
||||
incSyncMapper.updateById(state);
|
||||
} else if (companyId != null) {
|
||||
} else {
|
||||
PddOrderIncSyncPO neu = new PddOrderIncSyncPO();
|
||||
neu.setCompanyId(companyId);
|
||||
neu.setShopId(shopId);
|
||||
neu.setPddAuthId(resolvedAuthId);
|
||||
neu.setShopId(resolvedChannel);
|
||||
neu.setStatus(PddOrderIncSyncPO.STATUS_PAUSED);
|
||||
neu.setLastError(msg != null ? msg : "拼多多授权失效,请重新授权");
|
||||
incSyncMapper.insert(neu);
|
||||
@@ -71,19 +91,13 @@ public class PddOrderSyncAuthFailureHandler {
|
||||
}
|
||||
}
|
||||
|
||||
private Long resolveAuthId(Long companyId, Long shopId) {
|
||||
if (shopId == null) {
|
||||
return null;
|
||||
}
|
||||
ShopPO shop = shopMapper.selectById(shopId);
|
||||
if (shop == null || shop.getExternalShopId() == null) {
|
||||
return null;
|
||||
}
|
||||
if (companyId != null && !companyId.equals(shop.getCompanyId())) {
|
||||
private Long resolveAuthId(Long companyId, Long channelShopId) {
|
||||
if (channelShopId == null) {
|
||||
return null;
|
||||
}
|
||||
PddShopPO pddShop = pddShopMapper.selectOne(new LambdaQueryWrapper<PddShopPO>()
|
||||
.eq(PddShopPO::getId, shop.getExternalShopId())
|
||||
.eq(PddShopPO::getId, channelShopId)
|
||||
.eq(companyId != null, PddShopPO::getCompanyId, companyId)
|
||||
.last("LIMIT 1"));
|
||||
return pddShop != null ? pddShop.getPddAuthId() : null;
|
||||
}
|
||||
|
||||
+34
-9
@@ -14,6 +14,11 @@ import top.xyquan.ecomdmbbackend.modules.ec.shop.mapper.ShopMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.shop.model.po.ShopPO;
|
||||
import top.xyquan.ecomdmbbackend.utils.CurrentUserContext;
|
||||
|
||||
/**
|
||||
* 解析同步上下文。
|
||||
* API 入参:内部店 {@code ec_shop.id};
|
||||
* MQ / 渠道表:渠道店 {@code channel_pdd_shop.id}。
|
||||
*/
|
||||
@Service
|
||||
public class PddOrderSyncContextResolver {
|
||||
|
||||
@@ -32,16 +37,17 @@ public class PddOrderSyncContextResolver {
|
||||
this.authTokenService = authTokenService;
|
||||
}
|
||||
|
||||
public PddOrderSyncShopContext resolveForCurrentCompany(Long shopId) {
|
||||
Long companyId = currentUserContext.getCurrentCompanyId();
|
||||
return resolve(companyId, shopId);
|
||||
/** 当前公司 + 内部店铺 ID(API) */
|
||||
public PddOrderSyncShopContext resolveForCurrentCompany(Long internalShopId) {
|
||||
return resolveByInternalShopId(currentUserContext.getCurrentCompanyId(), internalShopId);
|
||||
}
|
||||
|
||||
public PddOrderSyncShopContext resolve(Long companyId, Long shopId) {
|
||||
if (shopId == null) {
|
||||
/** 按内部店铺 ID 解析(ec_shop.id) */
|
||||
public PddOrderSyncShopContext resolveByInternalShopId(Long companyId, Long internalShopId) {
|
||||
if (internalShopId == null) {
|
||||
throw new BusinessException("店铺 ID 不能为空");
|
||||
}
|
||||
ShopPO shop = shopMapper.selectById(shopId);
|
||||
ShopPO shop = shopMapper.selectById(internalShopId);
|
||||
if (shop == null || !companyId.equals(shop.getCompanyId())) {
|
||||
throw new BusinessException("内部店铺不存在或不属于当前公司");
|
||||
}
|
||||
@@ -51,15 +57,33 @@ public class PddOrderSyncContextResolver {
|
||||
if (shop.getExternalShopId() == null) {
|
||||
throw new PddAuthFailureException("店铺尚未绑定拼多多外部店,请先完成授权");
|
||||
}
|
||||
return buildContext(companyId, shop, shop.getExternalShopId());
|
||||
}
|
||||
|
||||
/** 按渠道店铺 ID 解析(channel_pdd_shop.id;MQ / 任务表) */
|
||||
public PddOrderSyncShopContext resolveByChannelShopId(Long companyId, Long channelShopId) {
|
||||
if (channelShopId == null) {
|
||||
throw new BusinessException("渠道店铺 ID 不能为空");
|
||||
}
|
||||
ShopPO shop = shopMapper.selectOne(new LambdaQueryWrapper<ShopPO>()
|
||||
.eq(ShopPO::getCompanyId, companyId)
|
||||
.eq(ShopPO::getPlatformCode, PlatformCode.PDD.getCode())
|
||||
.eq(ShopPO::getExternalShopId, channelShopId)
|
||||
.last("LIMIT 1"));
|
||||
if (shop == null) {
|
||||
throw new BusinessException("未找到绑定该拼多多店的内部店铺");
|
||||
}
|
||||
return buildContext(companyId, shop, channelShopId);
|
||||
}
|
||||
|
||||
private PddOrderSyncShopContext buildContext(Long companyId, ShopPO shop, Long channelShopId) {
|
||||
PddShopPO pddShop = pddShopMapper.selectOne(new LambdaQueryWrapper<PddShopPO>()
|
||||
.eq(PddShopPO::getId, shop.getExternalShopId())
|
||||
.eq(PddShopPO::getId, channelShopId)
|
||||
.eq(PddShopPO::getCompanyId, companyId)
|
||||
.last("LIMIT 1"));
|
||||
if (pddShop == null || pddShop.getPddAuthId() == null) {
|
||||
throw new PddAuthFailureException("未找到拼多多店铺授权绑定,请重新授权");
|
||||
}
|
||||
// access 将过期则自动 refresh;真正失效看 refresh_token
|
||||
PddAuthPO auth = authTokenService.ensureUsableById(pddShop.getPddAuthId());
|
||||
|
||||
return PddOrderSyncShopContext.builder()
|
||||
@@ -67,7 +91,8 @@ public class PddOrderSyncContextResolver {
|
||||
.pddShop(pddShop)
|
||||
.auth(auth)
|
||||
.companyId(companyId)
|
||||
.shopId(shopId)
|
||||
.shopId(pddShop.getId())
|
||||
.internalShopId(shop.getId())
|
||||
.mallId(pddShop.getMallId())
|
||||
.accessToken(auth.getAccessToken())
|
||||
.build();
|
||||
|
||||
+30
-17
@@ -107,7 +107,7 @@ public class PddOrderSyncService {
|
||||
}
|
||||
return PddOrderSyncResultVO.builder()
|
||||
.mode("bootstrap")
|
||||
.shopId(ctx.getShopId())
|
||||
.shopId(ctx.getInternalShopId())
|
||||
.fetchedCount(fetched)
|
||||
.upsertedCount(upserted)
|
||||
.skippedCount(Math.max(fetched - upserted, 0))
|
||||
@@ -120,18 +120,19 @@ public class PddOrderSyncService {
|
||||
try {
|
||||
ctx = contextResolver.resolveForCurrentCompany(shopId);
|
||||
} catch (PddAuthFailureException e) {
|
||||
onAuthFailure(null, shopId, null, e);
|
||||
onAuthFailureInternal(null, shopId, null, e);
|
||||
throw e;
|
||||
}
|
||||
return withIncLock(ctx.getShopId(), () -> doIncremental(ctx));
|
||||
}
|
||||
|
||||
public PddOrderSyncResultVO syncIncrementalInternal(Long companyId, Long shopId) {
|
||||
/** MQ 消费:shopId = channel_pdd_shop.id */
|
||||
public PddOrderSyncResultVO syncIncrementalInternal(Long companyId, Long channelShopId) {
|
||||
PddOrderSyncShopContext ctx;
|
||||
try {
|
||||
ctx = contextResolver.resolve(companyId, shopId);
|
||||
ctx = contextResolver.resolveByChannelShopId(companyId, channelShopId);
|
||||
} catch (PddAuthFailureException e) {
|
||||
onAuthFailure(companyId, shopId, null, e);
|
||||
onAuthFailureChannel(companyId, channelShopId, null, e);
|
||||
throw e;
|
||||
}
|
||||
return withIncLock(ctx.getShopId(), () -> doIncremental(ctx));
|
||||
@@ -175,7 +176,7 @@ public class PddOrderSyncService {
|
||||
notifyListeners(ctx, upsertedIds, "repair");
|
||||
return PddOrderSyncResultVO.builder()
|
||||
.mode("repair")
|
||||
.shopId(ctx.getShopId())
|
||||
.shopId(ctx.getInternalShopId())
|
||||
.fetchedCount(fetched)
|
||||
.upsertedCount(upserted)
|
||||
.skippedCount(skipped)
|
||||
@@ -190,12 +191,13 @@ public class PddOrderSyncService {
|
||||
.isNotNull(ShopPO::getExternalShopId));
|
||||
}
|
||||
|
||||
public PddOrderSyncResultVO syncByConfirmDateForTask(Long companyId, Long shopId, LocalDate day, Long taskId) {
|
||||
/** MQ / 全量任务:shopId = channel_pdd_shop.id */
|
||||
public PddOrderSyncResultVO syncByConfirmDateForTask(Long companyId, Long channelShopId, LocalDate day, Long taskId) {
|
||||
PddOrderSyncShopContext ctx;
|
||||
try {
|
||||
ctx = contextResolver.resolve(companyId, shopId);
|
||||
ctx = contextResolver.resolveByChannelShopId(companyId, channelShopId);
|
||||
} catch (PddAuthFailureException e) {
|
||||
onAuthFailure(companyId, shopId, null, e);
|
||||
onAuthFailureChannel(companyId, channelShopId, null, e);
|
||||
throw e;
|
||||
}
|
||||
return withFullDayLock(ctx.getShopId(), day,
|
||||
@@ -272,7 +274,7 @@ public class PddOrderSyncService {
|
||||
}
|
||||
return PddOrderSyncResultVO.builder()
|
||||
.mode(mode)
|
||||
.shopId(ctx.getShopId())
|
||||
.shopId(ctx.getInternalShopId())
|
||||
.fetchedCount(fetched)
|
||||
.upsertedCount(upserted)
|
||||
.skippedCount(Math.max(fetched - upserted, 0))
|
||||
@@ -377,7 +379,7 @@ public class PddOrderSyncService {
|
||||
|
||||
return PddOrderSyncResultVO.builder()
|
||||
.mode("incremental")
|
||||
.shopId(ctx.getShopId())
|
||||
.shopId(ctx.getInternalShopId())
|
||||
.fetchedCount(fetched)
|
||||
.upsertedCount(upserted)
|
||||
.skippedCount(Math.max(fetched - upserted, 0))
|
||||
@@ -395,7 +397,6 @@ public class PddOrderSyncService {
|
||||
PddOrderIncSyncPO state = new PddOrderIncSyncPO();
|
||||
state.setCompanyId(ctx.getCompanyId());
|
||||
state.setShopId(ctx.getShopId());
|
||||
state.setPddAuthId(ctx.getAuth().getId());
|
||||
state.setOverlapSeconds(syncProperties.getOverlapSeconds());
|
||||
state.setStatus(PddOrderIncSyncPO.STATUS_OK);
|
||||
incSyncMapper.insert(state);
|
||||
@@ -408,7 +409,6 @@ public class PddOrderSyncService {
|
||||
state.setStatus(PddOrderIncSyncPO.STATUS_OK);
|
||||
state.setLastError(null);
|
||||
state.setLastSuccessTime(LocalDateTime.now(ZONE));
|
||||
state.setPddAuthId(ctx.getAuth().getId());
|
||||
state.setOverlapSeconds(syncProperties.getOverlapSeconds());
|
||||
incSyncMapper.updateById(state);
|
||||
}
|
||||
@@ -426,14 +426,27 @@ public class PddOrderSyncService {
|
||||
|
||||
private void onAuthFailure(PddOrderSyncShopContext ctx, PddAuthFailureException e) {
|
||||
Long authId = ctx.getAuth() != null ? ctx.getAuth().getId() : null;
|
||||
onAuthFailure(ctx.getCompanyId(), ctx.getShopId(), authId, e);
|
||||
try {
|
||||
authFailureHandler.handle(
|
||||
ctx.getCompanyId(), ctx.getInternalShopId(), ctx.getShopId(), authId, e.getMessage());
|
||||
} catch (Exception ex) {
|
||||
log.warn("授权失效处置失败 channelShopId={}: {}", ctx.getShopId(), ex.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private void onAuthFailure(Long companyId, Long shopId, Long authId, PddAuthFailureException e) {
|
||||
private void onAuthFailureInternal(Long companyId, Long internalShopId, Long authId, PddAuthFailureException e) {
|
||||
try {
|
||||
authFailureHandler.handle(companyId, shopId, authId, e.getMessage());
|
||||
authFailureHandler.handle(companyId, internalShopId, null, authId, e.getMessage());
|
||||
} catch (Exception ex) {
|
||||
log.warn("授权失效处置失败 shopId={}: {}", shopId, ex.getMessage());
|
||||
log.warn("授权失效处置失败 internalShopId={}: {}", internalShopId, ex.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private void onAuthFailureChannel(Long companyId, Long channelShopId, Long authId, PddAuthFailureException e) {
|
||||
try {
|
||||
authFailureHandler.handle(companyId, null, channelShopId, authId, e.getMessage());
|
||||
} catch (Exception ex) {
|
||||
log.warn("授权失效处置失败 channelShopId={}: {}", channelShopId, ex.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
-1
@@ -77,7 +77,6 @@ public class PddOrderUpsertService {
|
||||
PddOrderPO order = existing != null ? existing : new PddOrderPO();
|
||||
order.setCompanyId(ctx.getCompanyId());
|
||||
order.setShopId(ctx.getShopId());
|
||||
order.setPddAuthId(ctx.getAuth().getId());
|
||||
order.setOrderSn(snapshot.getOrderSn());
|
||||
order.setOrderStatus(snapshot.getOrderStatus() != null ? snapshot.getOrderStatus() : 0);
|
||||
order.setRefundStatus(snapshot.getRefundStatus());
|
||||
|
||||
-3
@@ -36,9 +36,6 @@ public class OrderPO {
|
||||
@TableField("source")
|
||||
private String source;
|
||||
|
||||
@TableField("source_order_id")
|
||||
private Long sourceOrderId;
|
||||
|
||||
@TableField("pay_amount")
|
||||
private BigDecimal payAmount;
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
*/
|
||||
export namespace PddOrderDTO {
|
||||
export interface Filters {
|
||||
/** 渠道店铺 ID(channel_pdd_shop.id) */
|
||||
shopId?: number;
|
||||
orderSn?: string;
|
||||
orderStatus?: number;
|
||||
|
||||
@@ -20,8 +20,10 @@ export namespace PddOrderVO {
|
||||
export interface Info {
|
||||
id: number;
|
||||
companyId: number;
|
||||
/** 渠道店铺 ID(channel_pdd_shop.id) */
|
||||
shopId: number;
|
||||
pddAuthId?: number;
|
||||
/** 渠道店铺名称(mall_name) */
|
||||
shopName?: string;
|
||||
orderSn: string;
|
||||
orderStatus?: number;
|
||||
refundStatus?: number;
|
||||
|
||||
+4
-1
@@ -96,6 +96,9 @@ async function open(id: number, shopLabel?: string) {
|
||||
detail.value = null;
|
||||
try {
|
||||
detail.value = await getPddOrderDetailApi(id);
|
||||
if (detail.value?.shopName) {
|
||||
shopName.value = detail.value.shopName;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
message.error('加载订单详情失败');
|
||||
@@ -126,7 +129,7 @@ defineExpose({ open, close });
|
||||
{{ detail.orderSn }}
|
||||
</DescriptionsItem>
|
||||
<DescriptionsItem label="店铺">
|
||||
{{ shopName || `店铺#${detail.shopId}` }}
|
||||
{{ detail.shopName || shopName || `店铺#${detail.shopId}` }}
|
||||
</DescriptionsItem>
|
||||
<DescriptionsItem label="运单号">
|
||||
{{ detail.trackingNumber || '-' }}
|
||||
|
||||
@@ -2,16 +2,14 @@
|
||||
import type { VxeGridProps } from '#/adapter/vxe-table';
|
||||
import type { PddOrderDTO, PddOrderVO } from '#/api/channel/pdd/order';
|
||||
import type { PddShopVO } from '#/api/channel/pdd/shop';
|
||||
import type { ShopDTO, ShopVO } from '#/api/ec/shop/types';
|
||||
import type { PageQueryDTO } from '#/types/common';
|
||||
|
||||
import { computed, onMounted, ref, watch } from 'vue';
|
||||
import { computed, ref, watch } from 'vue';
|
||||
|
||||
import { Button, Card, Image, Space, Tag, Tooltip, message } from 'ant-design-vue';
|
||||
|
||||
import { useVbenVxeGrid } from '#/adapter/vxe-table';
|
||||
import { getPddOrderPageApi } from '#/api/channel/pdd/order';
|
||||
import { getShopPageApi } from '#/api/ec/shop';
|
||||
import PddShopColPage from '#/views/channel/pdd/components/PddShopColPage.vue';
|
||||
|
||||
import dayjs from 'dayjs';
|
||||
@@ -20,8 +18,6 @@ import PddOrderDetailDrawer from './components/PddOrderDetailDrawer.vue';
|
||||
|
||||
defineOptions({ name: 'PddOrderManagement' });
|
||||
|
||||
const PLATFORM_CODE_PDD = 'pdd';
|
||||
|
||||
const ORDER_STATUS_MAP: Record<number, { color: string; text: string }> = {
|
||||
1: { text: '待发货', color: 'orange' },
|
||||
2: { text: '已发货待签收', color: 'blue' },
|
||||
@@ -37,11 +33,8 @@ const REFUND_STATUS_MAP: Record<number, { color: string; text: string }> = {
|
||||
|
||||
const loading = ref(false);
|
||||
const detailDrawerRef = ref<InstanceType<typeof PddOrderDetailDrawer>>();
|
||||
/** 左侧选中的拼多多渠道店铺 ID */
|
||||
/** 左侧选中的拼多多渠道店铺 ID(与订单 shopId 一致) */
|
||||
const selectedPddShopId = ref<number | undefined>(undefined);
|
||||
/** 渠道店铺 ID → 内部店铺 ID(订单表 shop_id 为 ec_shop.id) */
|
||||
const ecShopIdByPddShopId = ref<Record<number, number>>({});
|
||||
const shopNameById = ref<Record<number, string>>({});
|
||||
|
||||
const DEFAULT_LIST_DAYS = 7;
|
||||
|
||||
@@ -97,34 +90,6 @@ function goodsSpecTooltip(row: PddOrderVO.Info) {
|
||||
return text || undefined;
|
||||
}
|
||||
|
||||
async function loadShopMappings() {
|
||||
try {
|
||||
const data = await getShopPageApi({
|
||||
page: 1,
|
||||
pageSize: 500,
|
||||
filters: {} as ShopDTO.Filters,
|
||||
});
|
||||
const list = (data.records ?? []).filter(
|
||||
(s: ShopVO.Info) =>
|
||||
s.platformCode === PLATFORM_CODE_PDD ||
|
||||
!!s.pddShop ||
|
||||
!!s.externalShopId,
|
||||
);
|
||||
const ecMap: Record<number, number> = {};
|
||||
const nameMap: Record<number, string> = {};
|
||||
for (const s of list) {
|
||||
nameMap[s.id] = s.name;
|
||||
if (s.externalShopId != null) {
|
||||
ecMap[s.externalShopId] = s.id;
|
||||
}
|
||||
}
|
||||
ecShopIdByPddShopId.value = ecMap;
|
||||
shopNameById.value = nameMap;
|
||||
} catch {
|
||||
message.error('获取店铺映射失败');
|
||||
}
|
||||
}
|
||||
|
||||
function onShopSelect(shop: PddShopVO.Info | null) {
|
||||
if (!shop) {
|
||||
selectedPddShopId.value = undefined;
|
||||
@@ -132,13 +97,7 @@ function onShopSelect(shop: PddShopVO.Info | null) {
|
||||
return;
|
||||
}
|
||||
selectedPddShopId.value = shop.id;
|
||||
const ecShopId = ecShopIdByPddShopId.value[shop.id];
|
||||
if (ecShopId == null) {
|
||||
message.warning('该拼多多店铺尚未绑定内部店铺,暂无订单数据');
|
||||
searchForm.value.shopId = -1;
|
||||
return;
|
||||
}
|
||||
searchForm.value.shopId = ecShopId;
|
||||
searchForm.value.shopId = shop.id;
|
||||
}
|
||||
|
||||
const gridOptions: VxeGridProps<PddOrderVO.Info> = {
|
||||
@@ -374,12 +333,8 @@ watch(selectedPddShopId, () => {
|
||||
});
|
||||
|
||||
function openDetail(row: PddOrderVO.Info) {
|
||||
detailDrawerRef.value?.open(row.id, shopNameById.value[row.shopId]);
|
||||
detailDrawerRef.value?.open(row.id, row.shopName);
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
await loadShopMappings();
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -406,7 +361,7 @@ onMounted(async () => {
|
||||
>
|
||||
<Grid class="pdd-order-grid h-full min-h-0" :loading="loading">
|
||||
<template #shopName="{ row }">
|
||||
{{ shopNameById[row.shopId] || `店铺#${row.shopId}` }}
|
||||
{{ row.shopName || `店铺#${row.shopId}` }}
|
||||
</template>
|
||||
|
||||
<template #goods="{ row }">
|
||||
|
||||
Reference in New Issue
Block a user