refactor: 重构推广费导入链

This commit is contained in:
2026-08-19 14:52:13 +08:00
parent 5c104446b2
commit 650774ba22
56 changed files with 1932 additions and 561 deletions
+52 -11
View File
@@ -14,19 +14,26 @@ export interface BatchImportPddGoodsAdFeeRequest {
items: BatchImportPddGoodsAdFeeItem[];
}
export interface BatchImportPddGoodsAdFeeResult {
/** 导入任务摘要(创建立即返回 pending,需轮询至终态) */
export interface PddGoodsAdFeeImportTask {
id: number;
companyId?: number;
channelShopId: number;
status: 'pending' | 'processing' | 'success' | 'partial' | 'failed' | string;
totalCount: number;
successCount: number;
failureCount: number;
successIds?: number[];
failureRecords?: Array<{
rowNumber?: number;
channelShopId?: number;
goodsId?: string;
failureReason?: string;
}>;
failCount: number;
authExpired?: number;
message?: string | null;
startedAt?: string | null;
finishedAt?: string | null;
createTime?: string;
}
const TERMINAL_STATUS = new Set(['success', 'partial', 'failed']);
const POLL_INTERVAL_MS = 2500;
const POLL_TIMEOUT_MS = 30 * 60 * 1000;
/** 插件统一模型 → 后端 batch-import 入参(日期取自每条 item;金额须大于 0) */
export function toBatchImportRequest(
batch: AdvertisingCostBatch,
@@ -43,18 +50,52 @@ export function toBatchImportRequest(
};
}
export async function getPddGoodsAdFeeImportTask(
taskId: number,
): Promise<PddGoodsAdFeeImportTask> {
return openApiRequest<PddGoodsAdFeeImportTask>(
`${OPEN_API_PATHS.pddGoodsAdFeeImportTask}/${taskId}`,
);
}
export async function waitForPddGoodsAdFeeImportTask(
taskId: number,
onProgress?: (task: PddGoodsAdFeeImportTask) => void,
): Promise<PddGoodsAdFeeImportTask> {
const deadline = Date.now() + POLL_TIMEOUT_MS;
while (Date.now() < deadline) {
const task = await getPddGoodsAdFeeImportTask(taskId);
onProgress?.(task);
if (TERMINAL_STATUS.has(task.status)) {
return task;
}
await sleep(POLL_INTERVAL_MS);
}
throw new Error('导入超时,请稍后在后台查看任务进度');
}
/** 提交导入任务并等到处理结束 */
export async function batchImportPddGoodsAdFee(
batch: AdvertisingCostBatch,
): Promise<BatchImportPddGoodsAdFeeResult> {
onProgress?: (task: PddGoodsAdFeeImportTask) => void,
): Promise<PddGoodsAdFeeImportTask> {
const body = toBatchImportRequest(batch);
if (!body.items.length) {
throw new Error('没有可传入的记录(推广费须大于 0)');
}
return openApiRequest<BatchImportPddGoodsAdFeeResult>(
const created = await openApiRequest<PddGoodsAdFeeImportTask>(
OPEN_API_PATHS.pddGoodsAdFeeBatchImport,
{
method: 'POST',
body: JSON.stringify(body),
},
);
onProgress?.(created);
return waitForPddGoodsAdFeeImportTask(created.id, onProgress);
}
function sleep(ms: number): Promise<void> {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}
+1 -1
View File
@@ -1,6 +1,6 @@
export type {
BatchImportPddGoodsAdFeeItem,
BatchImportPddGoodsAdFeeRequest,
BatchImportPddGoodsAdFeeResult,
PddGoodsAdFeeImportTask,
} from './open/pddGoodsAdFee';
export type { PddChannelShop, PageQueryDTO, PageResultVO } from './open/pddShop';
@@ -393,11 +393,20 @@ async function handleSync() {
...batch.value,
channelShopId: channelShopId.value!,
};
const result = await batchImportPddGoodsAdFee(payload);
statusText.value = '同步完成';
const result = await batchImportPddGoodsAdFee(payload, (task) => {
const done = (task.successCount ?? 0) + (task.failCount ?? 0);
statusText.value = `正在导入… ${done}/${task.totalCount ?? 0}`;
});
const failed = result.status === 'failed';
const partial = result.status === 'partial';
statusText.value = failed ? '同步失败' : partial ? '部分成功' : '同步完成';
const authHint = result.authExpired
? ',授权已失效请重新授权后再导失败商品'
: '';
syncResultText.value =
`成功 ${result.successCount}/${result.totalCount}` +
(result.failureCount ? `,失败 ${result.failureCount}` : '');
(result.failCount ? `,失败 ${result.failCount}` : '') +
authHint;
} catch (error) {
statusText.value = '同步失败';
errorText.value = toUserMessage(error);
@@ -3,6 +3,7 @@ export const EXTENSION_NAME = 'ECBI 数据同步';
export const OPEN_API_PATHS = {
pddShopList: '/open/v1/channel/pdd/shop/list',
pddGoodsAdFeeBatchImport: '/open/v1/channel/pdd/goods/adfee/batch-import',
pddGoodsAdFeeImportTask: '/open/v1/channel/pdd/goods/adfee/import-task',
extensionFeatureList: '/open/v1/extension/features',
extensionFeatureScript: '/open/v1/extension/features',
} as const;
@@ -385,7 +385,7 @@ CREATE TABLE ec_order_stat_refresh_queue (
### 4.6 推广费 / 刷单(不改)
继续读 `ec_ad_fee`、`ec_fake_orders_fee`。数据量远小于订单,区间 SUM 走现有索引 **毫秒级**。
继续读 `ec_product_ad_fee`、`ec_fake_orders_fee`。数据量远小于订单,区间 SUM 走现有索引 **毫秒级**。
### 4.7 容量估算(单公司,日 10 万单,50 店,5000 SKU,20000 规格)
@@ -1,32 +1,85 @@
-- ========================================
-- 拼多多商品广告费/推广费(按日)数据库设计
-- 拼多多商品广告费/推广费
--
-- 设计原则:
-- 1. 与 ec_ad_fee(内部经营广告费)分离,本表存渠道侧按日统计原始/同步数据
-- 2. 广告费维度跟随 channel_pdd_goods(SPU),用 goods_id(+ channel_shop_id)关联商品
-- 3. 统计粒度为「渠道店铺商品 × 自然日」一条;同日重复同步按唯一键覆盖/幂等写入
-- 4. 金额单位:元(decimal),与 ec_ad_fee.fee_amount 一致;后续若接口以分为单位需入库前换算
-- 5. channel_shop_id = channel_pdd_shop.id(非 ec_shop.id);mall_id 为拼多多侧店铺号
-- 1. 与 ec_product_ad_fee(内部商品广告费)分离:本域先落渠道日表,导入完成后再转换
-- 2. 日表只挂 channel_pdd_goods:店铺 / mall_id / 平台 goods_id 从商品主表带出,不重复存
-- 3. 统计粒度「渠道商品 × 自然日」一条;同日重复导入按唯一键覆盖
-- 4. 浏览器扩展 / OpenAPI 只创建导入任务并入队;明细在子表,不进 JSON 大字段
-- 5. 金额单位:元(decimal),与 ec_product_ad_fee.fee_amount 一致
-- ========================================
DROP TABLE IF EXISTS `channel_pdd_goods_ad_fee_daily`;
DROP TABLE IF EXISTS `channel_pdd_goods_ad_fee_import_item`;
DROP TABLE IF EXISTS `channel_pdd_goods_ad_fee_import_task`;
-- ----------------------------
-- 导入任务(OpenAPI 创建后入 RabbitMQ,worker 异步处理)
-- ----------------------------
CREATE TABLE `channel_pdd_goods_ad_fee_import_task` (
`id` bigint UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '任务ID',
`company_id` bigint UNSIGNED NOT NULL COMMENT '公司ID',
`channel_shop_id` bigint UNSIGNED NOT NULL COMMENT '渠道店铺ID(channel_pdd_shop.id)',
`status` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL DEFAULT 'pending' COMMENT 'pending / processing / success / partial / failed',
`total_count` int UNSIGNED NOT NULL DEFAULT 0 COMMENT '明细条数',
`success_count` int UNSIGNED NOT NULL DEFAULT 0 COMMENT '成功条数',
`fail_count` int UNSIGNED NOT NULL DEFAULT 0 COMMENT '失败条数',
`auth_expired` tinyint NOT NULL DEFAULT 0 COMMENT '处理中遇到授权失效 0否 1是(插件可据此提示重新授权)',
`message` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '摘要/失败原因',
`started_at` datetime NULL DEFAULT NULL COMMENT '开始处理时间',
`finished_at` datetime NULL DEFAULT NULL COMMENT '结束时间',
`create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
`create_by` bigint UNSIGNED NULL DEFAULT NULL COMMENT '创建人ID(Open Key 操作者)',
PRIMARY KEY (`id`) USING BTREE,
INDEX `idx_pdd_ad_fee_import_task_company`(`company_id` ASC, `create_time` DESC) USING BTREE,
INDEX `idx_pdd_ad_fee_import_task_shop`(`channel_shop_id` ASC, `create_time` DESC) USING BTREE,
INDEX `idx_pdd_ad_fee_import_task_status`(`status` ASC) USING BTREE,
CONSTRAINT `fk_pdd_ad_fee_import_task_company` FOREIGN KEY (`company_id`) REFERENCES `org_company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `fk_pdd_ad_fee_import_task_shop` FOREIGN KEY (`channel_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;
-- ----------------------------
-- 导入明细(插件提交的原始行;处理成功后才写日表)
-- fail_code: AUTH_EXPIRED / GOODS_FETCH_FAILED / BIND_FAILED / INVALID / OTHER
-- ----------------------------
CREATE TABLE `channel_pdd_goods_ad_fee_import_item` (
`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(冗余)',
`goods_id` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '拼多多商品ID(导入入参)',
`fee_date` date NOT NULL COMMENT '统计日期',
`fee_amount` decimal(12, 2) NOT NULL COMMENT '当日广告费金额(元)',
`goods_row_id` bigint UNSIGNED NULL DEFAULT NULL COMMENT '解析成功后的 channel_pdd_goods.id',
`status` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL DEFAULT 'pending' COMMENT 'pending / success / failed',
`fail_code` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '失败分类,见文件头注释',
`fail_reason` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '失败说明',
`create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
PRIMARY KEY (`id`) USING BTREE,
INDEX `idx_pdd_ad_fee_import_item_task`(`task_id` ASC, `status` ASC) USING BTREE,
INDEX `idx_pdd_ad_fee_import_item_goods`(`task_id` ASC, `goods_id` ASC) USING BTREE,
CONSTRAINT `fk_pdd_ad_fee_import_item_task` FOREIGN KEY (`task_id`) REFERENCES `channel_pdd_goods_ad_fee_import_task` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `fk_pdd_ad_fee_import_item_company` FOREIGN KEY (`company_id`) REFERENCES `org_company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = '拼多多-商品广告费导入明细' ROW_FORMAT = Dynamic;
-- ----------------------------
-- 渠道日表(转换源;店铺/mall/goods_id 经 goods_row_id 关联主表)
-- ----------------------------
CREATE TABLE `channel_pdd_goods_ad_fee_daily` (
`id` bigint UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '主键ID',
`company_id` bigint UNSIGNED NOT NULL COMMENT '公司ID',
`channel_shop_id` bigint UNSIGNED NOT NULL COMMENT '渠道店铺ID(channel_pdd_shop.id,非 ec_shop.id)',
`mall_id` bigint UNSIGNED NOT NULL COMMENT '拼多多店铺ID(mall_id)',
`goods_id` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '拼多多商品ID(goods_id,对应 channel_pdd_goods.goods_id)',
`goods_row_id` bigint UNSIGNED NOT NULL COMMENT '渠道商品ID(channel_pdd_goods.id)',
`fee_date` date NOT NULL COMMENT '广告费统计日期(自然日)',
`fee_amount` decimal(12, 2) NOT NULL DEFAULT 0.00 COMMENT '当日广告费金额(元)',
`raw_response` json NULL COMMENT '原始报文/扩展指标 JSON(点击、曝光等可先落于此)',
`last_sync_time` datetime NOT NULL COMMENT '最近一次同步时间',
`last_sync_time` datetime NOT NULL COMMENT '最近一次写入时间',
`create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '入库时间',
`update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
PRIMARY KEY (`id`) USING BTREE,
UNIQUE INDEX `uk_channel_pdd_goods_ad_fee_daily`(`channel_shop_id` ASC, `goods_id` ASC, `fee_date` ASC) USING BTREE,
UNIQUE INDEX `uk_channel_pdd_goods_ad_fee_daily`(`goods_row_id` ASC, `fee_date` ASC) USING BTREE,
INDEX `idx_channel_pdd_goods_ad_fee_company_date`(`company_id` ASC, `fee_date` ASC) USING BTREE,
INDEX `idx_channel_pdd_goods_ad_fee_goods_date`(`goods_id` ASC, `fee_date` ASC) USING BTREE,
INDEX `idx_channel_pdd_goods_ad_fee_sync`(`last_sync_time` ASC) USING BTREE,
CONSTRAINT `fk_channel_pdd_goods_ad_fee_company` FOREIGN KEY (`company_id`) REFERENCES `org_company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `fk_channel_pdd_goods_ad_fee_channel_shop` FOREIGN KEY (`channel_shop_id`) REFERENCES `channel_pdd_shop` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
CONSTRAINT `fk_channel_pdd_goods_ad_fee_goods` FOREIGN KEY (`goods_row_id`) REFERENCES `channel_pdd_goods` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = '拼多多-商品广告费按日统计表' ROW_FORMAT = Dynamic;
@@ -1,17 +1,17 @@
-- ========================================
-- 电商-广告推广费域设计
-- ec_ad_fee
-- 电商-商品广告推广费域设计
-- ec_product_ad_fee
-- ========================================
-- ----------------------------
-- 广告推广费记录表
-- 商品广告推广费记录表(商品 × 自然日唯一)
-- ----------------------------
DROP TABLE IF EXISTS `ec_ad_fee`;
CREATE TABLE `ec_ad_fee` (
DROP TABLE IF EXISTS `ec_product_ad_fee`;
CREATE TABLE `ec_product_ad_fee` (
`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',
`product_id` bigint UNSIGNED NULL DEFAULT NULL COMMENT '商品ID(与 fee_date 联合唯一;为空时不参与唯一约束)',
`product_id` bigint UNSIGNED NOT NULL COMMENT '商品ID(与 fee_date 联合唯一)',
`campaign_name` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '推广活动名称',
`fee_amount` decimal(10, 2) NOT NULL DEFAULT 0.00 COMMENT '推广费金额',
`fee_date` date NOT NULL COMMENT '推广费发生日期',
@@ -21,15 +21,15 @@ CREATE TABLE `ec_ad_fee` (
`create_by` bigint UNSIGNED NULL DEFAULT NULL COMMENT '创建人ID',
`update_by` bigint UNSIGNED NULL DEFAULT NULL COMMENT '更新人ID',
PRIMARY KEY (`id`) USING BTREE,
UNIQUE INDEX `uk_ec_ad_fee_product_date`(`product_id` ASC, `fee_date` ASC) USING BTREE,
UNIQUE INDEX `uk_ec_product_ad_fee_product_date`(`product_id` ASC, `fee_date` ASC) USING BTREE,
INDEX `idx_company_id`(`company_id` ASC) USING BTREE,
INDEX `idx_shop_id`(`shop_id` ASC) USING BTREE,
INDEX `idx_fee_date`(`fee_date` ASC) USING BTREE,
INDEX `fk_ec_ad_fee_creator`(`create_by` ASC) USING BTREE,
INDEX `fk_ec_ad_fee_updater`(`update_by` ASC) USING BTREE,
CONSTRAINT `fk_ec_ad_fee_company` FOREIGN KEY (`company_id`) REFERENCES `org_company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `fk_ec_ad_fee_creator` FOREIGN KEY (`create_by`) REFERENCES `sys_user` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `fk_ec_ad_fee_shop` FOREIGN KEY (`shop_id`) REFERENCES `ec_shop` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `fk_ec_ad_fee_product` FOREIGN KEY (`product_id`) REFERENCES `ec_product` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `fk_ec_ad_fee_updater` FOREIGN KEY (`update_by`) REFERENCES `sys_user` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = '电商-广告推广费记录表' ;
INDEX `fk_ec_product_ad_fee_creator`(`create_by` ASC) USING BTREE,
INDEX `fk_ec_product_ad_fee_updater`(`update_by` ASC) USING BTREE,
CONSTRAINT `fk_ec_product_ad_fee_company` FOREIGN KEY (`company_id`) REFERENCES `org_company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `fk_ec_product_ad_fee_creator` FOREIGN KEY (`create_by`) REFERENCES `sys_user` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `fk_ec_product_ad_fee_shop` FOREIGN KEY (`shop_id`) REFERENCES `ec_shop` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `fk_ec_product_ad_fee_product` FOREIGN KEY (`product_id`) REFERENCES `ec_product` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `fk_ec_product_ad_fee_updater` FOREIGN KEY (`update_by`) REFERENCES `sys_user` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = '电商-商品广告推广费记录表' ;
@@ -0,0 +1,83 @@
-- 拼多多商品广告费:日表改为挂 channel_pdd_goods;新增导入任务/明细表
-- ----------------------------
-- 1) 导入任务
-- ----------------------------
CREATE TABLE IF NOT EXISTS `channel_pdd_goods_ad_fee_import_task` (
`id` bigint UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '任务ID',
`company_id` bigint UNSIGNED NOT NULL COMMENT '公司ID',
`channel_shop_id` bigint UNSIGNED NOT NULL COMMENT '渠道店铺ID(channel_pdd_shop.id)',
`status` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL DEFAULT 'pending' COMMENT 'pending / processing / success / partial / failed',
`total_count` int UNSIGNED NOT NULL DEFAULT 0 COMMENT '明细条数',
`success_count` int UNSIGNED NOT NULL DEFAULT 0 COMMENT '成功条数',
`fail_count` int UNSIGNED NOT NULL DEFAULT 0 COMMENT '失败条数',
`auth_expired` tinyint NOT NULL DEFAULT 0 COMMENT '处理中遇到授权失效 0否 1是',
`message` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '摘要/失败原因',
`started_at` datetime NULL DEFAULT NULL COMMENT '开始处理时间',
`finished_at` datetime NULL DEFAULT NULL COMMENT '结束时间',
`create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
`create_by` bigint UNSIGNED NULL DEFAULT NULL COMMENT '创建人ID',
PRIMARY KEY (`id`) USING BTREE,
INDEX `idx_pdd_ad_fee_import_task_company`(`company_id` ASC, `create_time` DESC) USING BTREE,
INDEX `idx_pdd_ad_fee_import_task_shop`(`channel_shop_id` ASC, `create_time` DESC) USING BTREE,
INDEX `idx_pdd_ad_fee_import_task_status`(`status` ASC) USING BTREE,
CONSTRAINT `fk_pdd_ad_fee_import_task_company` FOREIGN KEY (`company_id`) REFERENCES `org_company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `fk_pdd_ad_fee_import_task_shop` FOREIGN KEY (`channel_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;
CREATE TABLE IF NOT EXISTS `channel_pdd_goods_ad_fee_import_item` (
`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(冗余)',
`goods_id` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '拼多多商品ID(导入入参)',
`fee_date` date NOT NULL COMMENT '统计日期',
`fee_amount` decimal(12, 2) NOT NULL COMMENT '当日广告费金额(元)',
`goods_row_id` bigint UNSIGNED NULL DEFAULT NULL COMMENT '解析成功后的 channel_pdd_goods.id',
`status` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL DEFAULT 'pending' COMMENT 'pending / success / failed',
`fail_code` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT 'AUTH_EXPIRED / GOODS_FETCH_FAILED / BIND_FAILED / INVALID / OTHER',
`fail_reason` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '失败说明',
`create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
PRIMARY KEY (`id`) USING BTREE,
INDEX `idx_pdd_ad_fee_import_item_task`(`task_id` ASC, `status` ASC) USING BTREE,
INDEX `idx_pdd_ad_fee_import_item_goods`(`task_id` ASC, `goods_id` ASC) USING BTREE,
CONSTRAINT `fk_pdd_ad_fee_import_item_task` FOREIGN KEY (`task_id`) REFERENCES `channel_pdd_goods_ad_fee_import_task` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `fk_pdd_ad_fee_import_item_company` FOREIGN KEY (`company_id`) REFERENCES `org_company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = '拼多多-商品广告费导入明细' ROW_FORMAT = Dynamic;
-- ----------------------------
-- 2) 日表:增加 goods_row_id 并回填
-- ----------------------------
ALTER TABLE `channel_pdd_goods_ad_fee_daily`
ADD COLUMN `goods_row_id` bigint UNSIGNED NULL COMMENT '渠道商品ID(channel_pdd_goods.id)' AFTER `company_id`;
UPDATE `channel_pdd_goods_ad_fee_daily` d
INNER JOIN `channel_pdd_goods` g
ON g.`shop_id` = d.`channel_shop_id`
AND g.`goods_id` = d.`goods_id`
AND g.`company_id` = d.`company_id`
SET d.`goods_row_id` = g.`id`
WHERE d.`goods_row_id` IS NULL;
-- 无法关联渠道商品的历史行无法满足新外键,删除
DELETE FROM `channel_pdd_goods_ad_fee_daily` WHERE `goods_row_id` IS NULL;
ALTER TABLE `channel_pdd_goods_ad_fee_daily`
DROP FOREIGN KEY `fk_channel_pdd_goods_ad_fee_channel_shop`;
ALTER TABLE `channel_pdd_goods_ad_fee_daily`
DROP INDEX `uk_channel_pdd_goods_ad_fee_daily`,
DROP INDEX `idx_channel_pdd_goods_ad_fee_goods_date`;
ALTER TABLE `channel_pdd_goods_ad_fee_daily`
DROP COLUMN `channel_shop_id`,
DROP COLUMN `mall_id`,
DROP COLUMN `goods_id`;
ALTER TABLE `channel_pdd_goods_ad_fee_daily`
MODIFY COLUMN `goods_row_id` bigint UNSIGNED NOT NULL COMMENT '渠道商品ID(channel_pdd_goods.id)';
ALTER TABLE `channel_pdd_goods_ad_fee_daily`
ADD UNIQUE INDEX `uk_channel_pdd_goods_ad_fee_daily`(`goods_row_id` ASC, `fee_date` ASC) USING BTREE,
ADD CONSTRAINT `fk_channel_pdd_goods_ad_fee_goods` FOREIGN KEY (`goods_row_id`) REFERENCES `channel_pdd_goods` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;
@@ -0,0 +1,27 @@
-- ec_ad_fee → ec_product_ad_fee;product_id 改为非空(表已清空,不做数据迁移)
RENAME TABLE `ec_ad_fee` TO `ec_product_ad_fee`;
ALTER TABLE `ec_product_ad_fee`
DROP FOREIGN KEY `fk_ec_ad_fee_company`,
DROP FOREIGN KEY `fk_ec_ad_fee_creator`,
DROP FOREIGN KEY `fk_ec_ad_fee_shop`,
DROP FOREIGN KEY `fk_ec_ad_fee_product`,
DROP FOREIGN KEY `fk_ec_ad_fee_updater`;
ALTER TABLE `ec_product_ad_fee`
DROP INDEX `uk_ec_ad_fee_product_date`,
DROP INDEX `fk_ec_ad_fee_creator`,
DROP INDEX `fk_ec_ad_fee_updater`;
ALTER TABLE `ec_product_ad_fee`
MODIFY COLUMN `product_id` bigint UNSIGNED NOT NULL COMMENT '商品ID(与 fee_date 联合唯一)',
ADD UNIQUE INDEX `uk_ec_product_ad_fee_product_date`(`product_id` ASC, `fee_date` ASC) USING BTREE,
ADD INDEX `fk_ec_product_ad_fee_creator`(`create_by` ASC) USING BTREE,
ADD INDEX `fk_ec_product_ad_fee_updater`(`update_by` ASC) USING BTREE,
ADD CONSTRAINT `fk_ec_product_ad_fee_company` FOREIGN KEY (`company_id`) REFERENCES `org_company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
ADD CONSTRAINT `fk_ec_product_ad_fee_creator` FOREIGN KEY (`create_by`) REFERENCES `sys_user` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
ADD CONSTRAINT `fk_ec_product_ad_fee_shop` FOREIGN KEY (`shop_id`) REFERENCES `ec_shop` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
ADD CONSTRAINT `fk_ec_product_ad_fee_product` FOREIGN KEY (`product_id`) REFERENCES `ec_product` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
ADD CONSTRAINT `fk_ec_product_ad_fee_updater` FOREIGN KEY (`update_by`) REFERENCES `sys_user` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
COMMENT = '电商-商品广告推广费记录表';
@@ -0,0 +1,23 @@
package top.xyquan.ecomdmbbackend.modules.channel.pdd.adfee.config;
/**
* 拼多多商品广告费导入/转换 MQ 常量。
*/
public final class PddAdFeeMqConstants {
public static final String EXCHANGE = "ecom.order.topic";
public static final String RK_IMPORT = "pdd.adfee.import";
public static final String QUEUE_IMPORT = "pdd.adfee.import";
public static final String QUEUE_IMPORT_DLQ = "pdd.adfee.import.dlq";
public static final String RK_CONVERT = "pdd.adfee.convert";
public static final String QUEUE_CONVERT = "pdd.adfee.convert";
public static final String QUEUE_CONVERT_DLQ = "pdd.adfee.convert.dlq";
public static final int BUSY_MAX_RETRY = 20;
public static final long BUSY_DELAY_MS = 15_000L;
private PddAdFeeMqConstants() {
}
}
@@ -0,0 +1,56 @@
package top.xyquan.ecomdmbbackend.modules.channel.pdd.adfee.config;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.QueueBuilder;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* 拼多多商品广告费导入/转换队列,复用订单 TopicExchange。
*/
@Configuration
public class PddAdFeeRabbitConfig {
@Bean
public Queue pddAdFeeImportQueue() {
return QueueBuilder.durable(PddAdFeeMqConstants.QUEUE_IMPORT)
.withArgument("x-dead-letter-exchange", "")
.withArgument("x-dead-letter-routing-key", PddAdFeeMqConstants.QUEUE_IMPORT_DLQ)
.build();
}
@Bean
public Queue pddAdFeeImportDlq() {
return QueueBuilder.durable(PddAdFeeMqConstants.QUEUE_IMPORT_DLQ).build();
}
@Bean
public Binding pddAdFeeImportBinding(Queue pddAdFeeImportQueue, TopicExchange orderTopicExchange) {
return BindingBuilder.bind(pddAdFeeImportQueue)
.to(orderTopicExchange)
.with(PddAdFeeMqConstants.RK_IMPORT);
}
@Bean
public Queue pddAdFeeConvertQueue() {
return QueueBuilder.durable(PddAdFeeMqConstants.QUEUE_CONVERT)
.withArgument("x-dead-letter-exchange", "")
.withArgument("x-dead-letter-routing-key", PddAdFeeMqConstants.QUEUE_CONVERT_DLQ)
.build();
}
@Bean
public Queue pddAdFeeConvertDlq() {
return QueueBuilder.durable(PddAdFeeMqConstants.QUEUE_CONVERT_DLQ).build();
}
@Bean
public Binding pddAdFeeConvertBinding(Queue pddAdFeeConvertQueue, TopicExchange orderTopicExchange) {
return BindingBuilder.bind(pddAdFeeConvertQueue)
.to(orderTopicExchange)
.with(PddAdFeeMqConstants.RK_CONVERT);
}
}
@@ -2,19 +2,27 @@ package top.xyquan.ecomdmbbackend.modules.channel.pdd.adfee.controller;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import top.xyquan.ecomdmbbackend.common.annotation.RequirePermission;
import top.xyquan.ecomdmbbackend.common.model.dto.PageQueryDTO;
import top.xyquan.ecomdmbbackend.common.model.vo.PageResultVO;
import top.xyquan.ecomdmbbackend.common.response.ApiResponse;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.adfee.model.dto.BatchImportPddGoodsAdFeeDTO;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.adfee.model.dto.CreatePddGoodsAdFeeDTO;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.adfee.model.dto.PddGoodsAdFeeFilterDTO;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.adfee.model.dto.UpdatePddGoodsAdFeeDTO;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.adfee.model.vo.BatchImportPddGoodsAdFeeResultVO;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.adfee.model.vo.PddGoodsAdFeeVO;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.adfee.service.PddGoodsAdFeeService;
/**
* 控制台:拼多多商品广告费日表。
*/
@RestController
@RequestMapping("/api/channel/pdd/goods/adfee")
@RequiredArgsConstructor
@@ -31,7 +39,7 @@ public class PddGoodsAdFeeController {
@PutMapping("/update/{id}")
@RequirePermission(value = "biz:pdd:ad-fee:manage", description = "更新拼多多商品广告费", allowSuper = true)
public ApiResponse<PddGoodsAdFeeVO> update(
@PathVariable Long id,
@PathVariable Long id,
@Valid @RequestBody UpdatePddGoodsAdFeeDTO dto) {
return ApiResponse.success("更新成功", pddGoodsAdFeeService.update(id, dto));
}
@@ -55,11 +63,4 @@ public class PddGoodsAdFeeController {
@Valid @RequestBody PageQueryDTO<PddGoodsAdFeeFilterDTO> pageQueryDTO) {
return ApiResponse.success("获取成功", pddGoodsAdFeeService.getPage(pageQueryDTO));
}
@PostMapping("/batch-import")
@RequirePermission(value = "biz:pdd:ad-fee:manage", description = "批量导入拼多多商品广告费", allowSuper = true)
public ApiResponse<BatchImportPddGoodsAdFeeResultVO> batchImport(
@Valid @RequestBody BatchImportPddGoodsAdFeeDTO dto) {
return ApiResponse.success("批量导入完成", pddGoodsAdFeeService.batchImport(dto));
}
}
@@ -0,0 +1,65 @@
package top.xyquan.ecomdmbbackend.modules.channel.pdd.adfee.convert.consumer;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
import top.xyquan.ecomdmbbackend.common.mq.DelayedMqRepublisher;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.adfee.config.PddAdFeeMqConstants;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.adfee.convert.messaging.PddAdFeeConvertMessage;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.adfee.convert.service.PddGoodsAdFeeConvertService;
import java.time.OffsetDateTime;
import java.time.ZoneId;
/**
* 广告费转换消费:按任务成功行或单条日表写入 ec_product_ad_fee。
*/
@Slf4j
@Component
@RequiredArgsConstructor
public class PddAdFeeConvertConsumer {
private static final ZoneId ZONE = ZoneId.of("Asia/Shanghai");
private final PddGoodsAdFeeConvertService convertService;
private final DelayedMqRepublisher delayedMqRepublisher;
@RabbitListener(queues = PddAdFeeMqConstants.QUEUE_CONVERT, concurrency = "1-2")
public void onMessage(PddAdFeeConvertMessage message) {
if (message == null || (message.getTaskId() == null && message.getDailyId() == null)) {
log.warn("广告费转换消息非法: {}", message);
return;
}
log.info("收到广告费转换 taskId={} dailyId={} messageId={}",
message.getTaskId(), message.getDailyId(), message.getMessageId());
try {
if (message.getDailyId() != null) {
convertService.convertByChannelAdFeeId(message.getDailyId());
} else {
convertService.convertByTaskId(message.getTaskId());
}
} catch (Exception e) {
log.error("广告费转换失败 taskId={} dailyId={}",
message.getTaskId(), message.getDailyId(), e);
delayAndRepublish(message, e.getMessage());
}
}
private void delayAndRepublish(PddAdFeeConvertMessage message, String reason) {
int retry = message.getRetryCount() == null ? 0 : message.getRetryCount();
if (retry >= PddAdFeeMqConstants.BUSY_MAX_RETRY) {
throw new IllegalStateException("广告费转换重试超限 taskId=" + message.getTaskId()
+ " dailyId=" + message.getDailyId() + " reason=" + reason);
}
message.setRetryCount(retry + 1);
message.setOccurredAt(OffsetDateTime.now(ZONE));
delayedMqRepublisher.republish(
PddAdFeeMqConstants.EXCHANGE,
PddAdFeeMqConstants.RK_CONVERT,
message,
PddAdFeeMqConstants.BUSY_DELAY_MS);
log.info("广告费转换已延迟重投 taskId={} dailyId={} retry={}",
message.getTaskId(), message.getDailyId(), message.getRetryCount());
}
}
@@ -0,0 +1,25 @@
package top.xyquan.ecomdmbbackend.modules.channel.pdd.adfee.convert.messaging;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.time.OffsetDateTime;
/**
* 广告费转换消息:taskId 转整任务成功行,dailyId 转单条日表。
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class PddAdFeeConvertMessage {
private String messageId;
private Long companyId;
private Long taskId;
private Long dailyId;
private OffsetDateTime occurredAt;
private Integer retryCount;
}
@@ -0,0 +1,62 @@
package top.xyquan.ecomdmbbackend.modules.channel.pdd.adfee.convert.messaging;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.support.TransactionSynchronization;
import org.springframework.transaction.support.TransactionSynchronizationManager;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.adfee.config.PddAdFeeMqConstants;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.util.UUID;
/**
* 广告费转换入队;事务提交后再发送。
*/
@Slf4j
@Component
@RequiredArgsConstructor
public class PddAdFeeConvertPublisher {
private static final ZoneId ZONE = ZoneId.of("Asia/Shanghai");
private final RabbitTemplate rabbitTemplate;
public void publishTaskAfterCommit(Long companyId, Long taskId) {
publishAfterCommit(companyId, taskId, null);
}
public void publishDailyAfterCommit(Long companyId, Long dailyId) {
publishAfterCommit(companyId, null, dailyId);
}
private void publishAfterCommit(Long companyId, Long taskId, Long dailyId) {
Runnable send = () -> publish(companyId, taskId, dailyId);
if (!TransactionSynchronizationManager.isSynchronizationActive()) {
send.run();
return;
}
TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
@Override
public void afterCommit() {
send.run();
}
});
}
public void publish(Long companyId, Long taskId, Long dailyId) {
PddAdFeeConvertMessage msg = PddAdFeeConvertMessage.builder()
.messageId(UUID.randomUUID().toString())
.companyId(companyId)
.taskId(taskId)
.dailyId(dailyId)
.occurredAt(OffsetDateTime.now(ZONE))
.retryCount(0)
.build();
rabbitTemplate.convertAndSend(
PddAdFeeMqConstants.EXCHANGE, PddAdFeeMqConstants.RK_CONVERT, msg);
log.info("已投递广告费转换 companyId={} taskId={} dailyId={}", companyId, taskId, dailyId);
}
}
@@ -1,46 +0,0 @@
package top.xyquan.ecomdmbbackend.modules.channel.pdd.adfee.convert.messaging;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.adfee.convert.service.PddGoodsAdFeeConvertService;
import java.util.List;
/**
* 渠道广告费 → 内部广告费 异步投递入口(事务提交后调用)。
*/
@Slf4j
@Component
@RequiredArgsConstructor
public class PddGoodsAdFeeConvertAsyncInvoker {
private final PddGoodsAdFeeConvertService convertService;
@Async
public void convertAsync(Long channelAdFeeId) {
if (channelAdFeeId == null) {
return;
}
try {
convertService.convertByChannelAdFeeId(channelAdFeeId);
} catch (Exception e) {
log.error("异步转换拼多多广告费失败 channelAdFeeId={}", channelAdFeeId, e);
}
}
@Async
public void convertBatchAsync(List<Long> channelAdFeeIds) {
if (channelAdFeeIds == null || channelAdFeeIds.isEmpty()) {
return;
}
for (Long id : channelAdFeeIds) {
try {
convertService.convertByChannelAdFeeId(id);
} catch (Exception e) {
log.error("异步转换拼多多广告费失败 channelAdFeeId={}", id, e);
}
}
}
}
@@ -1,23 +1,18 @@
package top.xyquan.ecomdmbbackend.modules.channel.pdd.adfee.convert.service;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.util.StringUtils;
import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.adfee.importtask.mapper.PddGoodsAdFeeImportItemMapper;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.adfee.importtask.model.po.PddGoodsAdFeeImportItemPO;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.adfee.mapper.PddGoodsAdFeeDailyMapper;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.adfee.model.po.PddGoodsAdFeeDailyPO;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.auth.model.po.PddAuthPO;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.auth.service.PddAuthTokenService;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.goods.mapper.PddGoodsMapper;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.goods.model.po.PddGoodsPO;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.goods.service.PddGoodsService;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.convert.service.PddProductAutoCreateService;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.pop.goods.PddGoodsPopApiClient;
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.modules.ec.platform.model.enums.PlatformCode;
import top.xyquan.ecomdmbbackend.modules.ec.shop.adfee.mapper.AdFeeMapper;
import top.xyquan.ecomdmbbackend.modules.ec.shop.adfee.model.po.AdFeePO;
@@ -25,32 +20,67 @@ import top.xyquan.ecomdmbbackend.modules.ec.shop.mapper.ShopMapper;
import top.xyquan.ecomdmbbackend.modules.ec.shop.model.po.ShopPO;
import java.math.BigDecimal;
import java.util.List;
import java.util.Objects;
/**
* 拼多多渠道商品广告费 → 内部 ec_ad_fee 转换。
* <p>
* goods_id → channel_pdd_goods → product_id;渠道商品缺失时拉详情自动建品并落库绑定。
* 渠道日表 → 内部 ec_product_ad_fee。
* 依赖导入/ensure 已写入的渠道商品绑定;转换只读 product_id,不再拉 POP、不再验内部商品存在性。
*/
@Slf4j
@Service
@RequiredArgsConstructor
public class PddGoodsAdFeeConvertService {
private static final String CAMPAIGN_NAME = "拼多多商品推广";
private final PddGoodsAdFeeDailyMapper channelAdFeeMapper;
private final PddGoodsAdFeeImportItemMapper importItemMapper;
private final PddGoodsMapper pddGoodsMapper;
private final PddShopMapper pddShopMapper;
private final PddAuthTokenService authTokenService;
private final PddGoodsPopApiClient goodsPopApiClient;
private final PddProductAutoCreateService productAutoCreateService;
private final PddGoodsService pddGoodsService;
private final ShopMapper shopMapper;
private final AdFeeMapper adFeeMapper;
private final TransactionTemplate transactionTemplate;
public PddGoodsAdFeeConvertService(PddGoodsAdFeeDailyMapper channelAdFeeMapper,
PddGoodsAdFeeImportItemMapper importItemMapper,
PddGoodsMapper pddGoodsMapper,
ShopMapper shopMapper,
AdFeeMapper adFeeMapper,
PlatformTransactionManager transactionManager) {
this.channelAdFeeMapper = channelAdFeeMapper;
this.importItemMapper = importItemMapper;
this.pddGoodsMapper = pddGoodsMapper;
this.shopMapper = shopMapper;
this.adFeeMapper = adFeeMapper;
this.transactionTemplate = new TransactionTemplate(transactionManager);
}
/**
* 转换任务中全部成功明细对应的日表行。
*/
public void convertByTaskId(Long taskId) {
if (taskId == null) {
return;
}
List<PddGoodsAdFeeImportItemPO> items = importItemMapper.selectList(
new LambdaQueryWrapper<PddGoodsAdFeeImportItemPO>()
.eq(PddGoodsAdFeeImportItemPO::getTaskId, taskId)
.eq(PddGoodsAdFeeImportItemPO::getStatus, PddGoodsAdFeeImportItemPO.STATUS_SUCCESS)
.isNotNull(PddGoodsAdFeeImportItemPO::getGoodsRowId));
for (PddGoodsAdFeeImportItemPO item : items) {
PddGoodsAdFeeDailyPO daily = channelAdFeeMapper.selectOne(
new LambdaQueryWrapper<PddGoodsAdFeeDailyPO>()
.eq(PddGoodsAdFeeDailyPO::getGoodsRowId, item.getGoodsRowId())
.eq(PddGoodsAdFeeDailyPO::getFeeDate, item.getFeeDate())
.last("LIMIT 1"));
if (daily == null) {
continue;
}
transactionTemplate.executeWithoutResult(status -> convertDaily(daily));
}
}
@Transactional(rollbackFor = Exception.class)
public void convertByChannelAdFeeId(Long channelAdFeeId) throws Exception {
public void convertByChannelAdFeeId(Long channelAdFeeId) {
if (channelAdFeeId == null) {
return;
}
@@ -59,76 +89,34 @@ public class PddGoodsAdFeeConvertService {
log.warn("渠道广告费不存在,跳过转换 id={}", channelAdFeeId);
return;
}
convertDaily(channelFee);
}
private void convertDaily(PddGoodsAdFeeDailyPO channelFee) {
if (channelFee.getFeeAmount() == null
|| channelFee.getFeeAmount().compareTo(BigDecimal.ZERO) <= 0) {
log.warn("渠道广告费金额无效,跳过转换 id={} amount={}",
channelAdFeeId, channelFee.getFeeAmount());
channelFee.getId(), channelFee.getFeeAmount());
return;
}
Long productId = resolveProductId(
channelFee.getCompanyId(),
channelFee.getChannelShopId(),
channelFee.getGoodsId());
if (productId == null) {
throw new BusinessException("无法解析内部商品 productId,goods_id=" + channelFee.getGoodsId());
if (channelFee.getGoodsRowId() == null) {
log.warn("渠道广告费缺少 goods_row_id,跳过转换 id={}", channelFee.getId());
return;
}
Long internalShopId = resolveInternalShopId(
channelFee.getCompanyId(), channelFee.getChannelShopId());
// 成功写入日表前 ensure 已绑定;此处仅防御脏数据,跳过不拖垮整批
PddGoodsPO goods = pddGoodsMapper.selectById(channelFee.getGoodsRowId());
if (goods == null || goods.getProductId() == null) {
log.warn("渠道商品未绑定内部商品,跳过转换 dailyId={} goodsRowId={}",
channelFee.getId(), channelFee.getGoodsRowId());
return;
}
Long internalShopId = resolveInternalShopId(channelFee.getCompanyId(), goods.getShopId());
if (internalShopId == null) {
throw new BusinessException("未找到绑定该渠道店的内部店铺 channelShopId="
+ channelFee.getChannelShopId());
log.warn("未找到绑定该渠道店的内部店铺,跳过转换 dailyId={} channelShopId={}",
channelFee.getId(), goods.getShopId());
return;
}
upsertInternalAdFee(channelFee, productId, internalShopId);
}
/**
* 查找渠道商品绑定的内部商品;不存在则拉详情自动建品并 upsert channel_pdd_goods。
*/
private Long resolveProductId(Long companyId, Long channelShopId, String goodsId) throws Exception {
if (companyId == null || channelShopId == null || !StringUtils.hasText(goodsId)) {
return null;
}
String gid = goodsId.trim();
PddGoodsPO goods = pddGoodsMapper.selectOne(new LambdaQueryWrapper<PddGoodsPO>()
.eq(PddGoodsPO::getCompanyId, companyId)
.eq(PddGoodsPO::getShopId, channelShopId)
.eq(PddGoodsPO::getGoodsId, gid)
.last("LIMIT 1"));
if (goods != null && goods.getProductId() != null) {
return goods.getProductId();
}
PddShopPO pddShop = pddShopMapper.selectById(channelShopId);
if (pddShop == null || !Objects.equals(pddShop.getCompanyId(), companyId)) {
throw new BusinessException("渠道店铺不存在 channelShopId=" + channelShopId);
}
if (pddShop.getPddAuthId() == null) {
throw new BusinessException("渠道店铺未授权,无法拉取商品 channelShopId=" + channelShopId);
}
long goodsIdLong;
try {
goodsIdLong = Long.parseLong(gid);
} catch (NumberFormatException e) {
throw new BusinessException("非法 goods_id=" + gid);
}
PddAuthPO auth = authTokenService.ensureUsableById(pddShop.getPddAuthId());
PddGoodsPopApiClient.GoodsDetail detail = goodsPopApiClient.fetchGoodsInformation(
pddShop.getMallId(), auth.getAccessToken(), goodsIdLong);
Long productId = productAutoCreateService.ensureInternalProduct(companyId, detail);
if (productId == null) {
log.warn("自动建内部商品失败 companyId={} goodsId={}", companyId, gid);
return null;
}
pddGoodsService.upsertFromGoodsDetail(
companyId, channelShopId, pddShop.getMallId(), productId, detail);
log.info("广告费转换:已自动拉取并绑定渠道商品 channelShopId={} goodsId={} productId={}",
channelShopId, gid, productId);
return productId;
upsertInternalAdFee(channelFee, goods, goods.getProductId(), internalShopId);
}
private Long resolveInternalShopId(Long companyId, Long channelShopId) {
@@ -141,6 +129,7 @@ public class PddGoodsAdFeeConvertService {
}
private void upsertInternalAdFee(PddGoodsAdFeeDailyPO channelFee,
PddGoodsPO goods,
Long productId,
Long internalShopId) {
AdFeePO existing = adFeeMapper.selectOne(new LambdaQueryWrapper<AdFeePO>()
@@ -148,6 +137,7 @@ public class PddGoodsAdFeeConvertService {
.eq(AdFeePO::getFeeDate, channelFee.getFeeDate())
.last("LIMIT 1"));
String goodsId = goods.getGoodsId();
if (existing == null) {
AdFeePO po = new AdFeePO();
po.setCompanyId(channelFee.getCompanyId());
@@ -157,7 +147,7 @@ public class PddGoodsAdFeeConvertService {
po.setFeeAmount(channelFee.getFeeAmount());
po.setFeeDate(channelFee.getFeeDate());
po.setRemark("channel_pdd_goods_ad_fee_daily#" + channelFee.getId()
+ " goods_id=" + channelFee.getGoodsId());
+ " goods_id=" + goodsId);
adFeeMapper.insert(po);
log.info("已转换新增内部广告费 productId={} feeDate={} amount={} channelId={}",
productId, channelFee.getFeeDate(), channelFee.getFeeAmount(), channelFee.getId());
@@ -1,55 +0,0 @@
package top.xyquan.ecomdmbbackend.modules.channel.pdd.adfee.convert.support;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.transaction.support.TransactionSynchronization;
import org.springframework.transaction.support.TransactionSynchronizationManager;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.adfee.convert.messaging.PddGoodsAdFeeConvertAsyncInvoker;
import java.util.ArrayList;
import java.util.List;
/**
* 事务提交后再异步触发渠道广告费转换,避免读到未提交数据。
*/
@Component
@RequiredArgsConstructor
public class PddGoodsAdFeeConvertScheduler {
private final PddGoodsAdFeeConvertAsyncInvoker asyncInvoker;
public void scheduleAfterCommit(Long channelAdFeeId) {
if (channelAdFeeId == null) {
return;
}
Runnable task = () -> asyncInvoker.convertAsync(channelAdFeeId);
if (!TransactionSynchronizationManager.isSynchronizationActive()) {
task.run();
return;
}
TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
@Override
public void afterCommit() {
task.run();
}
});
}
public void scheduleBatchAfterCommit(List<Long> channelAdFeeIds) {
if (channelAdFeeIds == null || channelAdFeeIds.isEmpty()) {
return;
}
List<Long> ids = new ArrayList<>(channelAdFeeIds);
Runnable task = () -> asyncInvoker.convertBatchAsync(ids);
if (!TransactionSynchronizationManager.isSynchronizationActive()) {
task.run();
return;
}
TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
@Override
public void afterCommit() {
task.run();
}
});
}
}
@@ -0,0 +1,62 @@
package top.xyquan.ecomdmbbackend.modules.channel.pdd.adfee.importtask.consumer;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
import top.xyquan.ecomdmbbackend.common.mq.DelayedMqRepublisher;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.adfee.config.PddAdFeeMqConstants;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.adfee.importtask.messaging.PddAdFeeImportMessage;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.adfee.importtask.service.PddGoodsAdFeeImportProcessor;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.pop.PddPopRateLimitedException;
import java.time.OffsetDateTime;
import java.time.ZoneId;
/**
* 广告费导入任务消费;限流时延迟重投,不把授权失效当成订单同步故障。
*/
@Slf4j
@Component
@RequiredArgsConstructor
public class PddAdFeeImportConsumer {
private static final ZoneId ZONE = ZoneId.of("Asia/Shanghai");
private final PddGoodsAdFeeImportProcessor importProcessor;
private final DelayedMqRepublisher delayedMqRepublisher;
@RabbitListener(queues = PddAdFeeMqConstants.QUEUE_IMPORT, concurrency = "1")
public void onMessage(PddAdFeeImportMessage message) {
if (message == null || message.getTaskId() == null) {
log.warn("广告费导入消息非法: {}", message);
return;
}
log.info("收到广告费导入任务 taskId={} messageId={}", message.getTaskId(), message.getMessageId());
try {
importProcessor.process(message.getTaskId());
} catch (PddPopRateLimitedException e) {
delayAndRepublish(message, e.getMessage());
} catch (Exception e) {
log.error("广告费导入任务失败 taskId={}", message.getTaskId(), e);
delayAndRepublish(message, e.getMessage());
}
}
private void delayAndRepublish(PddAdFeeImportMessage message, String reason) {
int retry = message.getRetryCount() == null ? 0 : message.getRetryCount();
if (retry >= PddAdFeeMqConstants.BUSY_MAX_RETRY) {
throw new IllegalStateException("广告费导入重试超限 taskId=" + message.getTaskId()
+ " reason=" + reason);
}
message.setRetryCount(retry + 1);
message.setOccurredAt(OffsetDateTime.now(ZONE));
delayedMqRepublisher.republish(
PddAdFeeMqConstants.EXCHANGE,
PddAdFeeMqConstants.RK_IMPORT,
message,
PddAdFeeMqConstants.BUSY_DELAY_MS);
log.info("广告费导入已延迟重投 taskId={} retry={} reason={}",
message.getTaskId(), message.getRetryCount(), reason);
}
}
@@ -0,0 +1,49 @@
package top.xyquan.ecomdmbbackend.modules.channel.pdd.adfee.importtask.controller;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import top.xyquan.ecomdmbbackend.common.annotation.RequirePermission;
import top.xyquan.ecomdmbbackend.common.model.dto.PageQueryDTO;
import top.xyquan.ecomdmbbackend.common.model.vo.PageResultVO;
import top.xyquan.ecomdmbbackend.common.response.ApiResponse;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.adfee.importtask.model.dto.PddGoodsAdFeeImportTaskFilterDTO;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.adfee.importtask.model.vo.PddGoodsAdFeeImportTaskVO;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.adfee.importtask.service.PddGoodsAdFeeImportService;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.adfee.model.dto.BatchImportPddGoodsAdFeeDTO;
/**
* 控制台:拼多多商品广告费导入任务。
*/
@RestController
@RequestMapping("/api/channel/pdd/goods/adfee/import-task")
@RequiredArgsConstructor
public class PddGoodsAdFeeImportController {
private final PddGoodsAdFeeImportService importService;
@PostMapping("/create")
@RequirePermission(value = "biz:pdd:ad-fee:manage", description = "创建拼多多商品广告费导入任务", allowSuper = true)
public ApiResponse<PddGoodsAdFeeImportTaskVO> create(
@Valid @RequestBody BatchImportPddGoodsAdFeeDTO dto) {
return ApiResponse.success("已创建导入任务", importService.createAndEnqueue(dto));
}
@GetMapping("/detail/{id}")
@RequirePermission(value = "biz:pdd:ad-fee:read", description = "查询拼多多商品广告费导入任务", allowSuper = true)
public ApiResponse<PddGoodsAdFeeImportTaskVO> detail(@PathVariable Long id) {
return ApiResponse.success("获取成功", importService.getDetail(id));
}
@PostMapping("/list")
@RequirePermission(value = "biz:pdd:ad-fee:read", description = "查询拼多多商品广告费导入任务列表", allowSuper = true)
public ApiResponse<PageResultVO<PddGoodsAdFeeImportTaskVO>> list(
@Valid @RequestBody PageQueryDTO<PddGoodsAdFeeImportTaskFilterDTO> pageQueryDTO) {
return ApiResponse.success("获取成功", importService.getPage(pageQueryDTO));
}
}
@@ -0,0 +1,12 @@
package top.xyquan.ecomdmbbackend.modules.channel.pdd.adfee.importtask.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.adfee.importtask.model.po.PddGoodsAdFeeImportItemPO;
/**
* 拼多多商品广告费导入明细 Mapper。
*/
@Mapper
public interface PddGoodsAdFeeImportItemMapper extends BaseMapper<PddGoodsAdFeeImportItemPO> {
}
@@ -0,0 +1,12 @@
package top.xyquan.ecomdmbbackend.modules.channel.pdd.adfee.importtask.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.adfee.importtask.model.po.PddGoodsAdFeeImportTaskPO;
/**
* 拼多多商品广告费导入任务 Mapper。
*/
@Mapper
public interface PddGoodsAdFeeImportTaskMapper extends BaseMapper<PddGoodsAdFeeImportTaskPO> {
}
@@ -0,0 +1,24 @@
package top.xyquan.ecomdmbbackend.modules.channel.pdd.adfee.importtask.messaging;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.time.OffsetDateTime;
/**
* 广告费导入任务消息。
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class PddAdFeeImportMessage {
private String messageId;
private Long companyId;
private Long taskId;
private OffsetDateTime occurredAt;
private Integer retryCount;
}
@@ -0,0 +1,53 @@
package top.xyquan.ecomdmbbackend.modules.channel.pdd.adfee.importtask.messaging;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.support.TransactionSynchronization;
import org.springframework.transaction.support.TransactionSynchronizationManager;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.adfee.config.PddAdFeeMqConstants;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.util.UUID;
/**
* 广告费导入任务入队;事务提交后再发送。
*/
@Slf4j
@Component
@RequiredArgsConstructor
public class PddAdFeeImportPublisher {
private static final ZoneId ZONE = ZoneId.of("Asia/Shanghai");
private final RabbitTemplate rabbitTemplate;
public void publishAfterCommit(Long companyId, Long taskId) {
Runnable send = () -> publish(companyId, taskId);
if (!TransactionSynchronizationManager.isSynchronizationActive()) {
send.run();
return;
}
TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
@Override
public void afterCommit() {
send.run();
}
});
}
public void publish(Long companyId, Long taskId) {
PddAdFeeImportMessage msg = PddAdFeeImportMessage.builder()
.messageId(UUID.randomUUID().toString())
.companyId(companyId)
.taskId(taskId)
.occurredAt(OffsetDateTime.now(ZONE))
.retryCount(0)
.build();
rabbitTemplate.convertAndSend(
PddAdFeeMqConstants.EXCHANGE, PddAdFeeMqConstants.RK_IMPORT, msg);
log.info("已投递广告费导入任务 companyId={} taskId={}", companyId, taskId);
}
}
@@ -0,0 +1,14 @@
package top.xyquan.ecomdmbbackend.modules.channel.pdd.adfee.importtask.model.dto;
import lombok.Data;
/**
* 导入任务列表过滤。
*/
@Data
public class PddGoodsAdFeeImportTaskFilterDTO {
private Long channelShopId;
private String status;
}
@@ -0,0 +1,66 @@
package top.xyquan.ecomdmbbackend.modules.channel.pdd.adfee.importtask.model.po;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
/**
* 拼多多商品广告费导入明细。
*/
@Data
@TableName("channel_pdd_goods_ad_fee_import_item")
public class PddGoodsAdFeeImportItemPO {
public static final String STATUS_PENDING = "pending";
public static final String STATUS_SUCCESS = "success";
public static final String STATUS_FAILED = "failed";
public static final String FAIL_AUTH_EXPIRED = "AUTH_EXPIRED";
public static final String FAIL_GOODS_FETCH = "GOODS_FETCH_FAILED";
public static final String FAIL_BIND = "BIND_FAILED";
public static final String FAIL_INVALID = "INVALID";
public static final String FAIL_OTHER = "OTHER";
@TableId(value = "id", type = IdType.AUTO)
private Long id;
@TableField("task_id")
private Long taskId;
@TableField("company_id")
private Long companyId;
@TableField("goods_id")
private String goodsId;
@TableField("fee_date")
private LocalDate feeDate;
@TableField("fee_amount")
private BigDecimal feeAmount;
@TableField("goods_row_id")
private Long goodsRowId;
@TableField("status")
private String status;
@TableField("fail_code")
private String failCode;
@TableField("fail_reason")
private String failReason;
@TableField(value = "create_time", fill = FieldFill.INSERT)
private LocalDateTime createTime;
@TableField(value = "update_time", fill = FieldFill.INSERT_UPDATE)
private LocalDateTime updateTime;
}
@@ -0,0 +1,66 @@
package top.xyquan.ecomdmbbackend.modules.channel.pdd.adfee.importtask.model.po;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import java.time.LocalDateTime;
/**
* 拼多多商品广告费导入任务。
*/
@Data
@TableName("channel_pdd_goods_ad_fee_import_task")
public class PddGoodsAdFeeImportTaskPO {
public static final String STATUS_PENDING = "pending";
public static final String STATUS_PROCESSING = "processing";
public static final String STATUS_SUCCESS = "success";
public static final String STATUS_PARTIAL = "partial";
public static final String STATUS_FAILED = "failed";
@TableId(value = "id", type = IdType.AUTO)
private Long id;
@TableField("company_id")
private Long companyId;
@TableField("channel_shop_id")
private Long channelShopId;
@TableField("status")
private String status;
@TableField("total_count")
private Integer totalCount;
@TableField("success_count")
private Integer successCount;
@TableField("fail_count")
private Integer failCount;
@TableField("auth_expired")
private Integer authExpired;
@TableField("message")
private String message;
@TableField("started_at")
private LocalDateTime startedAt;
@TableField("finished_at")
private LocalDateTime finishedAt;
@TableField(value = "create_time", fill = FieldFill.INSERT)
private LocalDateTime createTime;
@TableField(value = "update_time", fill = FieldFill.INSERT_UPDATE)
private LocalDateTime updateTime;
@TableField("create_by")
private Long createBy;
}
@@ -0,0 +1,25 @@
package top.xyquan.ecomdmbbackend.modules.channel.pdd.adfee.importtask.model.vo;
import lombok.Data;
import java.time.LocalDateTime;
/**
* 导入任务摘要(列表/创建回包)。
*/
@Data
public class PddGoodsAdFeeImportTaskVO {
private Long id;
private Long companyId;
private Long channelShopId;
private String status;
private Integer totalCount;
private Integer successCount;
private Integer failCount;
private Integer authExpired;
private String message;
private LocalDateTime startedAt;
private LocalDateTime finishedAt;
private LocalDateTime createTime;
}
@@ -0,0 +1,376 @@
package top.xyquan.ecomdmbbackend.modules.channel.pdd.adfee.importtask.service;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.util.StringUtils;
import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.adfee.convert.messaging.PddAdFeeConvertPublisher;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.adfee.importtask.mapper.PddGoodsAdFeeImportItemMapper;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.adfee.importtask.mapper.PddGoodsAdFeeImportTaskMapper;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.adfee.importtask.model.po.PddGoodsAdFeeImportItemPO;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.adfee.importtask.model.po.PddGoodsAdFeeImportTaskPO;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.adfee.mapper.PddGoodsAdFeeDailyMapper;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.adfee.model.po.PddGoodsAdFeeDailyPO;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.goods.ensure.PddGoodsEnsureService;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.goods.mapper.PddGoodsMapper;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.goods.model.po.PddGoodsPO;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.pop.PddAuthFailureException;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.pop.PddPopRateLimitedException;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* 导入任务 worker:已绑定商品直接写日表;缺失的拉 POP 再写;授权失效不影响已有商品。
*/
@Slf4j
@Service
public class PddGoodsAdFeeImportProcessor {
private static final int MSG_MAX = 500;
private final PddGoodsAdFeeImportTaskMapper taskMapper;
private final PddGoodsAdFeeImportItemMapper itemMapper;
private final PddGoodsAdFeeDailyMapper dailyMapper;
private final PddGoodsMapper pddGoodsMapper;
private final PddGoodsEnsureService goodsEnsureService;
private final PddAdFeeConvertPublisher convertPublisher;
private final TransactionTemplate transactionTemplate;
public PddGoodsAdFeeImportProcessor(PddGoodsAdFeeImportTaskMapper taskMapper,
PddGoodsAdFeeImportItemMapper itemMapper,
PddGoodsAdFeeDailyMapper dailyMapper,
PddGoodsMapper pddGoodsMapper,
PddGoodsEnsureService goodsEnsureService,
PddAdFeeConvertPublisher convertPublisher,
PlatformTransactionManager transactionManager) {
this.taskMapper = taskMapper;
this.itemMapper = itemMapper;
this.dailyMapper = dailyMapper;
this.pddGoodsMapper = pddGoodsMapper;
this.goodsEnsureService = goodsEnsureService;
this.convertPublisher = convertPublisher;
this.transactionTemplate = new TransactionTemplate(transactionManager);
}
public void process(Long taskId) throws Exception {
if (taskId == null) {
return;
}
PddGoodsAdFeeImportTaskPO task = taskMapper.selectById(taskId);
if (task == null) {
log.warn("广告费导入任务不存在 taskId={}", taskId);
return;
}
if (isTerminal(task.getStatus())) {
log.info("广告费导入任务已结束,跳过 taskId={} status={}", taskId, task.getStatus());
return;
}
markProcessing(task);
List<PddGoodsAdFeeImportItemPO> pending = itemMapper.selectList(
new LambdaQueryWrapper<PddGoodsAdFeeImportItemPO>()
.eq(PddGoodsAdFeeImportItemPO::getTaskId, taskId)
.eq(PddGoodsAdFeeImportItemPO::getStatus, PddGoodsAdFeeImportItemPO.STATUS_PENDING)
.orderByAsc(PddGoodsAdFeeImportItemPO::getId));
if (pending.isEmpty()) {
finalizeTask(task);
return;
}
Set<String> goodsIds = new LinkedHashSet<>();
for (PddGoodsAdFeeImportItemPO item : pending) {
if (StringUtils.hasText(item.getGoodsId())) {
goodsIds.add(item.getGoodsId().trim());
}
}
Map<String, GoodsResolve> resolved = new LinkedHashMap<>();
for (String goodsId : goodsIds) {
PddGoodsPO bound = findBound(task.getCompanyId(), task.getChannelShopId(), goodsId);
if (bound != null) {
resolved.put(goodsId, GoodsResolve.ok(bound));
}
}
boolean authExpired = Integer.valueOf(1).equals(task.getAuthExpired());
String authMessage = authExpired ? "拼多多授权已失效" : null;
for (String goodsId : goodsIds) {
if (resolved.containsKey(goodsId)) {
continue;
}
if (authExpired) {
resolved.put(goodsId, GoodsResolve.fail(
PddGoodsAdFeeImportItemPO.FAIL_AUTH_EXPIRED, authMessage));
continue;
}
try {
PddGoodsPO goods = goodsEnsureService.ensureBound(
task.getCompanyId(), task.getChannelShopId(), goodsId);
resolved.put(goodsId, GoodsResolve.ok(goods));
} catch (PddPopRateLimitedException e) {
throw e;
} catch (PddAuthFailureException e) {
authExpired = true;
authMessage = clip(e.getMessage(), MSG_MAX);
resolved.put(goodsId, GoodsResolve.fail(
PddGoodsAdFeeImportItemPO.FAIL_AUTH_EXPIRED, authMessage));
log.warn("广告费导入遇授权失效 taskId={} goodsId={}: {}",
taskId, goodsId, e.getMessage());
} catch (BusinessException e) {
resolved.put(goodsId, GoodsResolve.fail(mapFailCode(e), e.getMessage()));
} catch (Exception e) {
log.warn("广告费导入拉取商品失败 taskId={} goodsId={}", taskId, goodsId, e);
resolved.put(goodsId, GoodsResolve.fail(
PddGoodsAdFeeImportItemPO.FAIL_OTHER,
e.getMessage() != null ? e.getMessage() : "拉取商品失败"));
}
}
Map<String, List<PddGoodsAdFeeImportItemPO>> byGoods = new LinkedHashMap<>();
List<PddGoodsAdFeeImportItemPO> invalid = new ArrayList<>();
for (PddGoodsAdFeeImportItemPO item : pending) {
if (!StringUtils.hasText(item.getGoodsId()) || item.getFeeDate() == null
|| item.getFeeAmount() == null
|| item.getFeeAmount().compareTo(BigDecimal.ZERO) <= 0) {
invalid.add(item);
continue;
}
byGoods.computeIfAbsent(item.getGoodsId().trim(), k -> new ArrayList<>()).add(item);
}
int successDelta = 0;
int failDelta = 0;
failDelta += markFailed(invalid, PddGoodsAdFeeImportItemPO.FAIL_INVALID, "明细字段无效");
for (Map.Entry<String, List<PddGoodsAdFeeImportItemPO>> entry : byGoods.entrySet()) {
GoodsResolve resolve = resolved.get(entry.getKey());
if (resolve == null) {
failDelta += markFailed(entry.getValue(),
PddGoodsAdFeeImportItemPO.FAIL_OTHER, "未解析到渠道商品");
continue;
}
if (!resolve.ok()) {
failDelta += markFailed(entry.getValue(), resolve.failCode(), resolve.failReason());
continue;
}
successDelta += persistSuccess(entry.getValue(), resolve.goods());
}
final boolean expiredFlag = authExpired;
final String expiredMsg = authMessage;
final int successAdd = successDelta;
final int failAdd = failDelta;
transactionTemplate.executeWithoutResult(status -> {
PddGoodsAdFeeImportTaskPO latest = taskMapper.selectById(taskId);
if (latest == null) {
return;
}
int success = nvl(latest.getSuccessCount()) + successAdd;
int fail = nvl(latest.getFailCount()) + failAdd;
latest.setSuccessCount(success);
latest.setFailCount(fail);
if (expiredFlag) {
latest.setAuthExpired(1);
if (!StringUtils.hasText(latest.getMessage())) {
latest.setMessage(expiredMsg);
}
}
taskMapper.updateById(latest);
});
PddGoodsAdFeeImportTaskPO after = taskMapper.selectById(taskId);
finalizeTask(after);
}
private void markProcessing(PddGoodsAdFeeImportTaskPO task) {
transactionTemplate.executeWithoutResult(status -> {
if (PddGoodsAdFeeImportTaskPO.STATUS_PENDING.equals(task.getStatus())) {
taskMapper.update(null, new LambdaUpdateWrapper<PddGoodsAdFeeImportTaskPO>()
.eq(PddGoodsAdFeeImportTaskPO::getId, task.getId())
.eq(PddGoodsAdFeeImportTaskPO::getStatus, PddGoodsAdFeeImportTaskPO.STATUS_PENDING)
.set(PddGoodsAdFeeImportTaskPO::getStatus, PddGoodsAdFeeImportTaskPO.STATUS_PROCESSING)
.set(PddGoodsAdFeeImportTaskPO::getStartedAt, LocalDateTime.now()));
task.setStatus(PddGoodsAdFeeImportTaskPO.STATUS_PROCESSING);
} else if (!PddGoodsAdFeeImportTaskPO.STATUS_PROCESSING.equals(task.getStatus())) {
taskMapper.update(null, new LambdaUpdateWrapper<PddGoodsAdFeeImportTaskPO>()
.eq(PddGoodsAdFeeImportTaskPO::getId, task.getId())
.set(PddGoodsAdFeeImportTaskPO::getStatus, PddGoodsAdFeeImportTaskPO.STATUS_PROCESSING));
task.setStatus(PddGoodsAdFeeImportTaskPO.STATUS_PROCESSING);
}
});
}
private int persistSuccess(List<PddGoodsAdFeeImportItemPO> items, PddGoodsPO goods) {
Integer written = transactionTemplate.execute(status -> {
int n = 0;
for (PddGoodsAdFeeImportItemPO item : items) {
upsertDaily(item.getCompanyId(), goods.getId(), item.getFeeDate(), item.getFeeAmount());
item.setGoodsRowId(goods.getId());
item.setStatus(PddGoodsAdFeeImportItemPO.STATUS_SUCCESS);
item.setFailCode(null);
item.setFailReason(null);
itemMapper.updateById(item);
n++;
}
return n;
});
return written != null ? written : 0;
}
private int markFailed(List<PddGoodsAdFeeImportItemPO> items, String failCode, String failReason) {
if (items == null || items.isEmpty()) {
return 0;
}
String reason = clip(failReason, MSG_MAX);
transactionTemplate.executeWithoutResult(status -> {
for (PddGoodsAdFeeImportItemPO item : items) {
item.setStatus(PddGoodsAdFeeImportItemPO.STATUS_FAILED);
item.setFailCode(failCode);
item.setFailReason(reason);
itemMapper.updateById(item);
}
});
return items.size();
}
private void upsertDaily(Long companyId, Long goodsRowId,
java.time.LocalDate feeDate, BigDecimal feeAmount) {
PddGoodsAdFeeDailyPO existing = dailyMapper.selectOne(new LambdaQueryWrapper<PddGoodsAdFeeDailyPO>()
.eq(PddGoodsAdFeeDailyPO::getGoodsRowId, goodsRowId)
.eq(PddGoodsAdFeeDailyPO::getFeeDate, feeDate)
.last("LIMIT 1"));
LocalDateTime now = LocalDateTime.now();
if (existing != null) {
existing.setFeeAmount(feeAmount);
existing.setLastSyncTime(now);
dailyMapper.updateById(existing);
return;
}
PddGoodsAdFeeDailyPO po = new PddGoodsAdFeeDailyPO();
po.setCompanyId(companyId);
po.setGoodsRowId(goodsRowId);
po.setFeeDate(feeDate);
po.setFeeAmount(feeAmount);
po.setLastSyncTime(now);
dailyMapper.insert(po);
}
private void finalizeTask(PddGoodsAdFeeImportTaskPO task) {
if (task == null) {
return;
}
Long pending = itemMapper.selectCount(new LambdaQueryWrapper<PddGoodsAdFeeImportItemPO>()
.eq(PddGoodsAdFeeImportItemPO::getTaskId, task.getId())
.eq(PddGoodsAdFeeImportItemPO::getStatus, PddGoodsAdFeeImportItemPO.STATUS_PENDING));
if (pending != null && pending > 0) {
return;
}
int success = countItems(task.getId(), PddGoodsAdFeeImportItemPO.STATUS_SUCCESS);
int fail = countItems(task.getId(), PddGoodsAdFeeImportItemPO.STATUS_FAILED);
String status;
if (fail == 0) {
status = PddGoodsAdFeeImportTaskPO.STATUS_SUCCESS;
} else if (success == 0) {
status = PddGoodsAdFeeImportTaskPO.STATUS_FAILED;
} else {
status = PddGoodsAdFeeImportTaskPO.STATUS_PARTIAL;
}
String message = task.getMessage();
if (Integer.valueOf(1).equals(task.getAuthExpired()) && !StringUtils.hasText(message)) {
message = "授权失效,已绑定商品已写入,未入库商品需重新授权后再导";
}
final String finalStatus = status;
final String finalMessage = clip(message, MSG_MAX);
final int finalSuccess = success;
final int finalFail = fail;
if (success > 0) {
convertPublisher.publish(task.getCompanyId(), task.getId(), null);
}
transactionTemplate.executeWithoutResult(tx -> {
taskMapper.update(null, new LambdaUpdateWrapper<PddGoodsAdFeeImportTaskPO>()
.eq(PddGoodsAdFeeImportTaskPO::getId, task.getId())
.set(PddGoodsAdFeeImportTaskPO::getStatus, finalStatus)
.set(PddGoodsAdFeeImportTaskPO::getSuccessCount, finalSuccess)
.set(PddGoodsAdFeeImportTaskPO::getFailCount, finalFail)
.set(PddGoodsAdFeeImportTaskPO::getMessage, finalMessage)
.set(PddGoodsAdFeeImportTaskPO::getFinishedAt, LocalDateTime.now()));
});
log.info("广告费导入任务结束 taskId={} status={} success={} fail={} authExpired={}",
task.getId(), status, success, fail, task.getAuthExpired());
}
private PddGoodsPO findBound(Long companyId, Long channelShopId, String goodsId) {
PddGoodsPO goods = pddGoodsMapper.selectOne(new LambdaQueryWrapper<PddGoodsPO>()
.eq(PddGoodsPO::getCompanyId, companyId)
.eq(PddGoodsPO::getShopId, channelShopId)
.eq(PddGoodsPO::getGoodsId, goodsId)
.last("LIMIT 1"));
if (goods == null || goods.getProductId() == null) {
return null;
}
return goods;
}
private static String mapFailCode(BusinessException e) {
String msg = e.getMessage() != null ? e.getMessage() : "";
if (msg.contains("非法 goods_id")) {
return PddGoodsAdFeeImportItemPO.FAIL_INVALID;
}
if (msg.contains("拉取") || msg.contains("详情为空")) {
return PddGoodsAdFeeImportItemPO.FAIL_GOODS_FETCH;
}
if (msg.contains("无法关联") || msg.contains("落库失败") || msg.contains("自动创建")) {
return PddGoodsAdFeeImportItemPO.FAIL_BIND;
}
return PddGoodsAdFeeImportItemPO.FAIL_OTHER;
}
private int countItems(Long taskId, String status) {
Long n = itemMapper.selectCount(new LambdaQueryWrapper<PddGoodsAdFeeImportItemPO>()
.eq(PddGoodsAdFeeImportItemPO::getTaskId, taskId)
.eq(PddGoodsAdFeeImportItemPO::getStatus, status));
return n == null ? 0 : n.intValue();
}
private static boolean isTerminal(String status) {
return PddGoodsAdFeeImportTaskPO.STATUS_SUCCESS.equals(status)
|| PddGoodsAdFeeImportTaskPO.STATUS_PARTIAL.equals(status)
|| PddGoodsAdFeeImportTaskPO.STATUS_FAILED.equals(status);
}
private static int nvl(Integer v) {
return v == null ? 0 : v;
}
private static String clip(String s, int max) {
if (s == null) {
return null;
}
return s.length() <= max ? s : s.substring(0, max);
}
private record GoodsResolve(PddGoodsPO goods, String failCode, String failReason) {
static GoodsResolve ok(PddGoodsPO goods) {
return new GoodsResolve(goods, null, null);
}
static GoodsResolve fail(String failCode, String failReason) {
return new GoodsResolve(null, failCode, failReason);
}
boolean ok() {
return goods != null && goods.getId() != null;
}
}
}
@@ -0,0 +1,19 @@
package top.xyquan.ecomdmbbackend.modules.channel.pdd.adfee.importtask.service;
import top.xyquan.ecomdmbbackend.common.model.dto.PageQueryDTO;
import top.xyquan.ecomdmbbackend.common.model.vo.PageResultVO;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.adfee.importtask.model.dto.PddGoodsAdFeeImportTaskFilterDTO;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.adfee.importtask.model.vo.PddGoodsAdFeeImportTaskVO;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.adfee.model.dto.BatchImportPddGoodsAdFeeDTO;
/**
* 拼多多商品广告费导入任务:只建任务/明细并入队,不写日表。
*/
public interface PddGoodsAdFeeImportService {
PddGoodsAdFeeImportTaskVO createAndEnqueue(BatchImportPddGoodsAdFeeDTO dto);
PddGoodsAdFeeImportTaskVO getDetail(Long id);
PageResultVO<PddGoodsAdFeeImportTaskVO> getPage(PageQueryDTO<PddGoodsAdFeeImportTaskFilterDTO> pageQueryDTO);
}
@@ -0,0 +1,146 @@
package top.xyquan.ecomdmbbackend.modules.channel.pdd.adfee.importtask.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
import top.xyquan.ecomdmbbackend.common.model.dto.PageQueryDTO;
import top.xyquan.ecomdmbbackend.common.model.vo.PageResultVO;
import top.xyquan.ecomdmbbackend.common.utils.BeanCopyUtils;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.adfee.importtask.mapper.PddGoodsAdFeeImportItemMapper;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.adfee.importtask.mapper.PddGoodsAdFeeImportTaskMapper;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.adfee.importtask.messaging.PddAdFeeImportPublisher;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.adfee.importtask.model.dto.PddGoodsAdFeeImportTaskFilterDTO;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.adfee.importtask.model.po.PddGoodsAdFeeImportItemPO;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.adfee.importtask.model.po.PddGoodsAdFeeImportTaskPO;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.adfee.importtask.model.vo.PddGoodsAdFeeImportTaskVO;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.adfee.importtask.service.PddGoodsAdFeeImportService;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.adfee.model.dto.BatchImportPddGoodsAdFeeDTO;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.adfee.model.dto.BatchImportPddGoodsAdFeeItemDTO;
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.List;
import java.util.Objects;
/**
* 创建导入任务并入队;查询仅当前公司。
*/
@Service
@RequiredArgsConstructor
public class PddGoodsAdFeeImportServiceImpl implements PddGoodsAdFeeImportService {
public static final int MAX_ITEMS = 20_000;
private final PddGoodsAdFeeImportTaskMapper taskMapper;
private final PddGoodsAdFeeImportItemMapper itemMapper;
private final PddShopMapper pddShopMapper;
private final PddAdFeeImportPublisher importPublisher;
private final CurrentUserContext currentUserContext;
@Override
@Transactional(rollbackFor = Exception.class)
public PddGoodsAdFeeImportTaskVO createAndEnqueue(BatchImportPddGoodsAdFeeDTO dto) {
Long companyId = currentUserContext.getCurrentCompanyId();
List<BatchImportPddGoodsAdFeeItemDTO> items = dto.getItems();
if (items.size() > MAX_ITEMS) {
throw new BusinessException("单次最多导入 " + MAX_ITEMS + " 条");
}
Long channelShopId = resolveChannelShopId(items);
requireOwnedShop(channelShopId, companyId);
PddGoodsAdFeeImportTaskPO task = new PddGoodsAdFeeImportTaskPO();
task.setCompanyId(companyId);
task.setChannelShopId(channelShopId);
task.setStatus(PddGoodsAdFeeImportTaskPO.STATUS_PENDING);
task.setTotalCount(items.size());
task.setSuccessCount(0);
task.setFailCount(0);
task.setAuthExpired(0);
task.setCreateBy(currentUserContext.getCurrentUserId());
taskMapper.insert(task);
for (BatchImportPddGoodsAdFeeItemDTO item : items) {
PddGoodsAdFeeImportItemPO row = new PddGoodsAdFeeImportItemPO();
row.setTaskId(task.getId());
row.setCompanyId(companyId);
row.setGoodsId(item.getGoodsId().trim());
row.setFeeDate(item.getFeeDate());
row.setFeeAmount(item.getFeeAmount());
row.setStatus(PddGoodsAdFeeImportItemPO.STATUS_PENDING);
itemMapper.insert(row);
}
importPublisher.publishAfterCommit(companyId, task.getId());
return toVo(task);
}
@Override
public PddGoodsAdFeeImportTaskVO getDetail(Long id) {
Long companyId = currentUserContext.getCurrentCompanyId();
PddGoodsAdFeeImportTaskPO task = taskMapper.selectById(id);
if (task == null || !Objects.equals(task.getCompanyId(), companyId)) {
throw new BusinessException("导入任务不存在或无权访问");
}
return toVo(task);
}
@Override
public PageResultVO<PddGoodsAdFeeImportTaskVO> getPage(
PageQueryDTO<PddGoodsAdFeeImportTaskFilterDTO> pageQueryDTO) {
Long companyId = currentUserContext.getCurrentCompanyId();
PddGoodsAdFeeImportTaskFilterDTO filters =
pageQueryDTO.getFilters() != null ? pageQueryDTO.getFilters() : new PddGoodsAdFeeImportTaskFilterDTO();
LambdaQueryWrapper<PddGoodsAdFeeImportTaskPO> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(PddGoodsAdFeeImportTaskPO::getCompanyId, companyId);
if (filters.getChannelShopId() != null) {
wrapper.eq(PddGoodsAdFeeImportTaskPO::getChannelShopId, filters.getChannelShopId());
}
if (StringUtils.hasText(filters.getStatus())) {
wrapper.eq(PddGoodsAdFeeImportTaskPO::getStatus, filters.getStatus().trim());
}
wrapper.orderByDesc(PddGoodsAdFeeImportTaskPO::getCreateTime)
.orderByDesc(PddGoodsAdFeeImportTaskPO::getId);
Page<PddGoodsAdFeeImportTaskPO> page = new Page<>(pageQueryDTO.getPage(), pageQueryDTO.getPageSize());
IPage<PddGoodsAdFeeImportTaskPO> result = taskMapper.selectPage(page, wrapper);
List<PddGoodsAdFeeImportTaskVO> records = result.getRecords().stream().map(this::toVo).toList();
return PageResultVO.create(records, result.getTotal(),
(int) pageQueryDTO.getPage(), (int) pageQueryDTO.getPageSize());
}
private Long resolveChannelShopId(List<BatchImportPddGoodsAdFeeItemDTO> items) {
Long shopId = null;
for (BatchImportPddGoodsAdFeeItemDTO item : items) {
if (item.getChannelShopId() == null) {
throw new BusinessException("渠道店铺ID不能为空");
}
if (shopId == null) {
shopId = item.getChannelShopId();
} else if (!shopId.equals(item.getChannelShopId())) {
throw new BusinessException("同一导入任务只能包含一个渠道店铺");
}
}
return shopId;
}
private PddShopPO requireOwnedShop(Long channelShopId, Long companyId) {
PddShopPO shop = pddShopMapper.selectById(channelShopId);
if (shop == null || !Objects.equals(shop.getCompanyId(), companyId)) {
throw new BusinessException("渠道店铺不存在或无权访问");
}
return shop;
}
private PddGoodsAdFeeImportTaskVO toVo(PddGoodsAdFeeImportTaskPO po) {
PddGoodsAdFeeImportTaskVO vo = new PddGoodsAdFeeImportTaskVO();
BeanCopyUtils.copyProperties(po, vo);
return vo;
}
}
@@ -4,6 +4,9 @@ import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.adfee.model.po.PddGoodsAdFeeDailyPO;
/**
* 拼多多商品广告费日表 Mapper。
*/
@Mapper
public interface PddGoodsAdFeeDailyMapper extends BaseMapper<PddGoodsAdFeeDailyPO> {
}
@@ -2,14 +2,19 @@ package top.xyquan.ecomdmbbackend.modules.channel.pdd.adfee.model.dto;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.Size;
import lombok.Data;
import java.util.List;
/**
* 拼多多商品广告费批量导入入参;同一任务仅允许一个渠道店铺。
*/
@Data
public class BatchImportPddGoodsAdFeeDTO {
@NotEmpty(message = "广告费记录不能为空")
@Size(max = 20000, message = "单次最多导入 20000 条")
@Valid
private List<BatchImportPddGoodsAdFeeItemDTO> items;
}
@@ -8,6 +8,9 @@ import lombok.Data;
import java.math.BigDecimal;
import java.time.LocalDate;
/**
* 导入明细行;同一任务的 channelShopId 必须相同。
*/
@Data
public class BatchImportPddGoodsAdFeeItemDTO {
@@ -11,6 +11,9 @@ import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
/**
* 拼多多商品广告费日表,只挂 channel_pdd_goods。
*/
@Data
@TableName("channel_pdd_goods_ad_fee_daily")
public class PddGoodsAdFeeDailyPO {
@@ -21,15 +24,8 @@ public class PddGoodsAdFeeDailyPO {
@TableField("company_id")
private Long companyId;
/** 渠道店铺ID(channel_pdd_shop.id) */
@TableField("channel_shop_id")
private Long channelShopId;
@TableField("mall_id")
private Long mallId;
@TableField("goods_id")
private String goodsId;
@TableField("goods_row_id")
private Long goodsRowId;
@TableField("fee_date")
private LocalDate feeDate;
@@ -1,23 +0,0 @@
package top.xyquan.ecomdmbbackend.modules.channel.pdd.adfee.model.vo;
import lombok.Data;
import java.util.List;
@Data
public class BatchImportPddGoodsAdFeeResultVO {
private Integer totalCount;
private Integer successCount;
private Integer failureCount;
private List<Long> successIds;
private List<ImportFailureRecord> failureRecords;
@Data
public static class ImportFailureRecord {
private Integer rowNumber;
private Long channelShopId;
private String goodsId;
private String failureReason;
}
}
@@ -6,11 +6,15 @@ import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
/**
* 拼多多渠道商品广告费日表展示;店铺/商品字段从 channel_pdd_goods 带出。
*/
@Data
public class PddGoodsAdFeeVO {
private Long id;
private Long companyId;
private Long goodsRowId;
private Long channelShopId;
private String channelShopName;
private Long mallId;
@@ -2,13 +2,14 @@ package top.xyquan.ecomdmbbackend.modules.channel.pdd.adfee.service;
import top.xyquan.ecomdmbbackend.common.model.dto.PageQueryDTO;
import top.xyquan.ecomdmbbackend.common.model.vo.PageResultVO;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.adfee.model.dto.BatchImportPddGoodsAdFeeDTO;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.adfee.model.dto.CreatePddGoodsAdFeeDTO;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.adfee.model.dto.PddGoodsAdFeeFilterDTO;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.adfee.model.dto.UpdatePddGoodsAdFeeDTO;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.adfee.model.vo.BatchImportPddGoodsAdFeeResultVO;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.adfee.model.vo.PddGoodsAdFeeVO;
/**
* 拼多多渠道商品广告费日表维护。
*/
public interface PddGoodsAdFeeService {
PddGoodsAdFeeVO create(CreatePddGoodsAdFeeDTO dto);
@@ -20,10 +21,4 @@ public interface PddGoodsAdFeeService {
PddGoodsAdFeeVO getDetail(Long id);
PageResultVO<PddGoodsAdFeeVO> getPage(PageQueryDTO<PddGoodsAdFeeFilterDTO> pageQueryDTO);
/**
* 按 channelShopId + goods_id + fee_date 批量写入;
* 金额有变化才更新;新增/变更后异步转换为内部广告费(缺渠道商品时自动拉取绑定)。
*/
BatchImportPddGoodsAdFeeResultVO batchImport(BatchImportPddGoodsAdFeeDTO dto);
}
@@ -10,18 +10,15 @@ import org.springframework.util.StringUtils;
import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
import top.xyquan.ecomdmbbackend.common.model.dto.PageQueryDTO;
import top.xyquan.ecomdmbbackend.common.model.vo.PageResultVO;
import top.xyquan.ecomdmbbackend.common.utils.BeanCopyUtils;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.adfee.convert.support.PddGoodsAdFeeConvertScheduler;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.adfee.convert.messaging.PddAdFeeConvertPublisher;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.adfee.mapper.PddGoodsAdFeeDailyMapper;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.adfee.model.dto.BatchImportPddGoodsAdFeeDTO;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.adfee.model.dto.BatchImportPddGoodsAdFeeItemDTO;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.adfee.model.dto.CreatePddGoodsAdFeeDTO;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.adfee.model.dto.PddGoodsAdFeeFilterDTO;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.adfee.model.dto.UpdatePddGoodsAdFeeDTO;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.adfee.model.po.PddGoodsAdFeeDailyPO;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.adfee.model.vo.BatchImportPddGoodsAdFeeResultVO;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.adfee.model.vo.PddGoodsAdFeeVO;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.adfee.service.PddGoodsAdFeeService;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.goods.ensure.PddGoodsEnsureService;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.goods.mapper.PddGoodsMapper;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.goods.model.po.PddGoodsPO;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.shop.mapper.PddShopMapper;
@@ -29,8 +26,8 @@ import top.xyquan.ecomdmbbackend.modules.channel.pdd.shop.model.po.PddShopPO;
import top.xyquan.ecomdmbbackend.utils.CurrentUserContext;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
@@ -39,6 +36,9 @@ import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
/**
* 渠道广告费日表 CRUD;写入前确保渠道商品已绑定,提交后投递转换。
*/
@Service
@RequiredArgsConstructor
public class PddGoodsAdFeeServiceImpl implements PddGoodsAdFeeService {
@@ -46,28 +46,27 @@ public class PddGoodsAdFeeServiceImpl implements PddGoodsAdFeeService {
private final PddGoodsAdFeeDailyMapper adFeeMapper;
private final PddShopMapper pddShopMapper;
private final PddGoodsMapper pddGoodsMapper;
private final PddGoodsEnsureService goodsEnsureService;
private final PddAdFeeConvertPublisher convertPublisher;
private final CurrentUserContext currentUserContext;
private final PddGoodsAdFeeConvertScheduler convertScheduler;
@Override
@Transactional(rollbackFor = Exception.class)
public PddGoodsAdFeeVO create(CreatePddGoodsAdFeeDTO dto) {
Long companyId = currentUserContext.getCurrentCompanyId();
PddShopPO shop = requireOwnedShop(dto.getChannelShopId(), companyId);
assertGoodsInShop(companyId, shop.getId(), dto.getGoodsId());
assertUnique(shop.getId(), dto.getGoodsId(), dto.getFeeDate(), null);
requireOwnedShop(dto.getChannelShopId(), companyId);
assertFeeAmount(dto.getFeeAmount());
PddGoodsPO goods = ensureGoods(companyId, dto.getChannelShopId(), dto.getGoodsId());
assertUnique(goods.getId(), dto.getFeeDate(), null);
PddGoodsAdFeeDailyPO po = new PddGoodsAdFeeDailyPO();
po.setCompanyId(companyId);
po.setChannelShopId(shop.getId());
po.setMallId(shop.getMallId());
po.setGoodsId(dto.getGoodsId().trim());
po.setGoodsRowId(goods.getId());
po.setFeeDate(dto.getFeeDate());
po.setFeeAmount(dto.getFeeAmount());
po.setLastSyncTime(LocalDateTime.now());
adFeeMapper.insert(po);
convertScheduler.scheduleAfterCommit(po.getId());
convertPublisher.publishDailyAfterCommit(companyId, po.getId());
return toVo(po);
}
@@ -76,30 +75,25 @@ public class PddGoodsAdFeeServiceImpl implements PddGoodsAdFeeService {
public PddGoodsAdFeeVO update(Long id, UpdatePddGoodsAdFeeDTO dto) {
Long companyId = currentUserContext.getCurrentCompanyId();
PddGoodsAdFeeDailyPO existing = requireOwnedRecord(id, companyId);
PddShopPO shop = requireOwnedShop(dto.getChannelShopId(), companyId);
assertGoodsInShop(companyId, shop.getId(), dto.getGoodsId());
assertUnique(shop.getId(), dto.getGoodsId(), dto.getFeeDate(), id);
requireOwnedShop(dto.getChannelShopId(), companyId);
assertFeeAmount(dto.getFeeAmount());
PddGoodsPO goods = ensureGoods(companyId, dto.getChannelShopId(), dto.getGoodsId());
assertUnique(goods.getId(), dto.getFeeDate(), id);
String goodsId = dto.getGoodsId().trim();
boolean changed = !Objects.equals(existing.getChannelShopId(), shop.getId())
|| !Objects.equals(existing.getGoodsId(), goodsId)
boolean changed = !Objects.equals(existing.getGoodsRowId(), goods.getId())
|| !Objects.equals(existing.getFeeDate(), dto.getFeeDate())
|| existing.getFeeAmount() == null
|| existing.getFeeAmount().compareTo(dto.getFeeAmount()) != 0;
if (!changed) {
return toVo(existing);
}
existing.setChannelShopId(shop.getId());
existing.setMallId(shop.getMallId());
existing.setGoodsId(goodsId);
existing.setGoodsRowId(goods.getId());
existing.setFeeDate(dto.getFeeDate());
existing.setFeeAmount(dto.getFeeAmount());
existing.setLastSyncTime(LocalDateTime.now());
adFeeMapper.updateById(existing);
convertScheduler.scheduleAfterCommit(existing.getId());
convertPublisher.publishDailyAfterCommit(companyId, existing.getId());
return toVo(existing);
}
@@ -125,11 +119,13 @@ public class PddGoodsAdFeeServiceImpl implements PddGoodsAdFeeService {
LambdaQueryWrapper<PddGoodsAdFeeDailyPO> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(PddGoodsAdFeeDailyPO::getCompanyId, companyId);
if (filters.getChannelShopId() != null) {
wrapper.eq(PddGoodsAdFeeDailyPO::getChannelShopId, filters.getChannelShopId());
}
if (StringUtils.hasText(filters.getGoodsId())) {
wrapper.eq(PddGoodsAdFeeDailyPO::getGoodsId, filters.getGoodsId().trim());
if (filters.getChannelShopId() != null || StringUtils.hasText(filters.getGoodsId())) {
List<Long> goodsRowIds = lookupGoodsRowIds(companyId, filters.getChannelShopId(), filters.getGoodsId());
if (goodsRowIds.isEmpty()) {
return PageResultVO.create(List.of(), 0L,
(int) pageQueryDTO.getPage(), (int) pageQueryDTO.getPageSize());
}
wrapper.in(PddGoodsAdFeeDailyPO::getGoodsRowId, goodsRowIds);
}
if (filters.getFeeDateStart() != null) {
wrapper.ge(PddGoodsAdFeeDailyPO::getFeeDate, filters.getFeeDateStart());
@@ -147,95 +143,27 @@ public class PddGoodsAdFeeServiceImpl implements PddGoodsAdFeeService {
(int) pageQueryDTO.getPage(), (int) pageQueryDTO.getPageSize());
}
@Override
@Transactional(rollbackFor = Exception.class)
public BatchImportPddGoodsAdFeeResultVO batchImport(BatchImportPddGoodsAdFeeDTO dto) {
Long companyId = currentUserContext.getCurrentCompanyId();
List<BatchImportPddGoodsAdFeeItemDTO> items = dto.getItems();
BatchImportPddGoodsAdFeeResultVO result = new BatchImportPddGoodsAdFeeResultVO();
result.setTotalCount(items.size());
result.setSuccessIds(new ArrayList<>());
result.setFailureRecords(new ArrayList<>());
List<Long> changedIds = new ArrayList<>();
int success = 0;
for (int i = 0; i < items.size(); i++) {
BatchImportPddGoodsAdFeeItemDTO item = items.get(i);
int rowNumber = i + 1;
try {
UpsertOutcome outcome = upsertByChannelShopAndGoods(companyId, item);
result.getSuccessIds().add(outcome.id());
success++;
if (outcome.changed()) {
changedIds.add(outcome.id());
}
} catch (Exception e) {
BatchImportPddGoodsAdFeeResultVO.ImportFailureRecord failure =
new BatchImportPddGoodsAdFeeResultVO.ImportFailureRecord();
failure.setRowNumber(rowNumber);
failure.setChannelShopId(item.getChannelShopId());
failure.setGoodsId(item.getGoodsId());
failure.setFailureReason(e.getMessage() != null ? e.getMessage() : "导入失败");
result.getFailureRecords().add(failure);
}
private List<Long> lookupGoodsRowIds(Long companyId, Long channelShopId, String goodsId) {
LambdaQueryWrapper<PddGoodsPO> gw = new LambdaQueryWrapper<>();
gw.eq(PddGoodsPO::getCompanyId, companyId);
if (channelShopId != null) {
gw.eq(PddGoodsPO::getShopId, channelShopId);
}
result.setSuccessCount(success);
result.setFailureCount(items.size() - success);
convertScheduler.scheduleBatchAfterCommit(changedIds);
return result;
if (StringUtils.hasText(goodsId)) {
gw.eq(PddGoodsPO::getGoodsId, goodsId.trim());
}
gw.select(PddGoodsPO::getId);
return pddGoodsMapper.selectList(gw).stream().map(PddGoodsPO::getId).toList();
}
/**
* 按 channelShopId + goods_id + fee_date upsert;金额无变化则不写库。
* 不强制渠道商品已存在(转换层会自动拉取并绑定)。
*/
private UpsertOutcome upsertByChannelShopAndGoods(Long companyId, BatchImportPddGoodsAdFeeItemDTO item) {
if (item.getChannelShopId() == null) {
throw new BusinessException("渠道店铺ID不能为空");
private PddGoodsPO ensureGoods(Long companyId, Long channelShopId, String goodsId) {
try {
return goodsEnsureService.ensureBound(companyId, channelShopId, goodsId);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
throw new BusinessException("拉取渠道商品失败: " + e.getMessage());
}
if (item.getFeeAmount() == null || item.getFeeAmount().compareTo(BigDecimal.ZERO) <= 0) {
throw new BusinessException("广告费金额须大于0");
}
if (!StringUtils.hasText(item.getGoodsId())) {
throw new BusinessException("商品ID不能为空");
}
if (item.getFeeDate() == null) {
throw new BusinessException("统计日期不能为空");
}
PddShopPO shop = requireOwnedShop(item.getChannelShopId(), companyId);
String goodsId = item.getGoodsId().trim();
PddGoodsAdFeeDailyPO existing = adFeeMapper.selectOne(new LambdaQueryWrapper<PddGoodsAdFeeDailyPO>()
.eq(PddGoodsAdFeeDailyPO::getChannelShopId, shop.getId())
.eq(PddGoodsAdFeeDailyPO::getGoodsId, goodsId)
.eq(PddGoodsAdFeeDailyPO::getFeeDate, item.getFeeDate())
.last("LIMIT 1"));
LocalDateTime now = LocalDateTime.now();
if (existing != null) {
if (existing.getFeeAmount() != null
&& existing.getFeeAmount().compareTo(item.getFeeAmount()) == 0) {
return new UpsertOutcome(existing.getId(), false);
}
existing.setFeeAmount(item.getFeeAmount());
existing.setMallId(shop.getMallId());
existing.setLastSyncTime(now);
adFeeMapper.updateById(existing);
return new UpsertOutcome(existing.getId(), true);
}
PddGoodsAdFeeDailyPO po = new PddGoodsAdFeeDailyPO();
po.setCompanyId(companyId);
po.setChannelShopId(shop.getId());
po.setMallId(shop.getMallId());
po.setGoodsId(goodsId);
po.setFeeDate(item.getFeeDate());
po.setFeeAmount(item.getFeeAmount());
po.setLastSyncTime(now);
adFeeMapper.insert(po);
return new UpsertOutcome(po.getId(), true);
}
private PddShopPO requireOwnedShop(Long channelShopId, Long companyId) {
@@ -254,20 +182,9 @@ public class PddGoodsAdFeeServiceImpl implements PddGoodsAdFeeService {
return po;
}
private void assertGoodsInShop(Long companyId, Long channelShopId, String goodsId) {
Long count = pddGoodsMapper.selectCount(new LambdaQueryWrapper<PddGoodsPO>()
.eq(PddGoodsPO::getCompanyId, companyId)
.eq(PddGoodsPO::getShopId, channelShopId)
.eq(PddGoodsPO::getGoodsId, goodsId.trim()));
if (count == null || count == 0) {
throw new BusinessException("该渠道店铺下不存在商品 goods_id=" + goodsId);
}
}
private void assertUnique(Long channelShopId, String goodsId, java.time.LocalDate feeDate, Long excludeId) {
private void assertUnique(Long goodsRowId, LocalDate feeDate, Long excludeId) {
LambdaQueryWrapper<PddGoodsAdFeeDailyPO> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(PddGoodsAdFeeDailyPO::getChannelShopId, channelShopId)
.eq(PddGoodsAdFeeDailyPO::getGoodsId, goodsId.trim())
wrapper.eq(PddGoodsAdFeeDailyPO::getGoodsRowId, goodsRowId)
.eq(PddGoodsAdFeeDailyPO::getFeeDate, feeDate);
if (excludeId != null) {
wrapper.ne(PddGoodsAdFeeDailyPO::getId, excludeId);
@@ -287,49 +204,55 @@ public class PddGoodsAdFeeServiceImpl implements PddGoodsAdFeeService {
if (records == null || records.isEmpty()) {
return List.of();
}
Set<Long> shopIds = new HashSet<>();
Set<String> goodsIds = new HashSet<>();
Set<Long> goodsRowIds = new HashSet<>();
for (PddGoodsAdFeeDailyPO po : records) {
shopIds.add(po.getChannelShopId());
goodsIds.add(po.getGoodsId());
if (po.getGoodsRowId() != null) {
goodsRowIds.add(po.getGoodsRowId());
}
}
Map<Long, PddGoodsPO> goodsMap = new HashMap<>();
if (!goodsRowIds.isEmpty()) {
for (PddGoodsPO goods : pddGoodsMapper.selectByIds(goodsRowIds)) {
goodsMap.put(goods.getId(), goods);
}
}
Set<Long> shopIds = goodsMap.values().stream()
.map(PddGoodsPO::getShopId)
.filter(Objects::nonNull)
.collect(Collectors.toSet());
Map<Long, String> shopNameMap = new HashMap<>();
if (!shopIds.isEmpty()) {
List<PddShopPO> shops = pddShopMapper.selectByIds(shopIds);
for (PddShopPO shop : shops) {
for (PddShopPO shop : pddShopMapper.selectByIds(shopIds)) {
shopNameMap.put(shop.getId(), shop.getMallName());
}
}
Map<String, String> goodsNameMap = new HashMap<>();
if (!goodsIds.isEmpty()) {
List<PddGoodsPO> goodsList = pddGoodsMapper.selectList(new LambdaQueryWrapper<PddGoodsPO>()
.eq(PddGoodsPO::getCompanyId, currentUserContext.getCurrentCompanyId())
.in(PddGoodsPO::getGoodsId, goodsIds));
for (PddGoodsPO goods : goodsList) {
goodsNameMap.putIfAbsent(goods.getGoodsId(), goods.getGoodsName());
}
}
return records.stream().map(po -> {
PddGoodsAdFeeVO vo = toVoPlain(po);
vo.setChannelShopName(shopNameMap.get(po.getChannelShopId()));
vo.setGoodsName(goodsNameMap.get(po.getGoodsId()));
return vo;
}).collect(Collectors.toList());
return records.stream().map(po -> toVoPlain(po, goodsMap.get(po.getGoodsRowId()), shopNameMap))
.collect(Collectors.toList());
}
private PddGoodsAdFeeVO toVo(PddGoodsAdFeeDailyPO po) {
return enrich(List.of(po)).get(0);
}
private PddGoodsAdFeeVO toVoPlain(PddGoodsAdFeeDailyPO po) {
private PddGoodsAdFeeVO toVoPlain(PddGoodsAdFeeDailyPO po,
PddGoodsPO goods,
Map<Long, String> shopNameMap) {
PddGoodsAdFeeVO vo = new PddGoodsAdFeeVO();
BeanCopyUtils.copyProperties(po, vo);
vo.setId(po.getId());
vo.setCompanyId(po.getCompanyId());
vo.setGoodsRowId(po.getGoodsRowId());
vo.setFeeDate(po.getFeeDate());
vo.setFeeAmount(po.getFeeAmount());
vo.setLastSyncTime(po.getLastSyncTime());
vo.setCreateTime(po.getCreateTime());
vo.setUpdateTime(po.getUpdateTime());
if (goods != null) {
vo.setChannelShopId(goods.getShopId());
vo.setMallId(goods.getMallId());
vo.setGoodsId(goods.getGoodsId());
vo.setGoodsName(goods.getGoodsName());
vo.setChannelShopName(shopNameMap.get(goods.getShopId()));
}
return vo;
}
private record UpsertOutcome(Long id, boolean changed) {
}
}
@@ -0,0 +1,19 @@
package top.xyquan.ecomdmbbackend.modules.channel.pdd.goods.ensure;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.goods.model.po.PddGoodsPO;
/**
* 确保渠道商品已入库并绑定内部商品。已存在则直接返回,缺失时拉 POP 详情再建绑。
*/
public interface PddGoodsEnsureService {
/**
* 按渠道店 + goods_id 返回已绑定内部品的渠道商品。
* <p>
* 绑定:扫 SKU 的 outer_id → 内部 sku_code,取首个命中的 product_id,
* 再把内部缺失的 SKU 补到该商品下;一个都没命中则自动建新品。
*
* @param channelShopId channel_pdd_shop.id
*/
PddGoodsPO ensureBound(Long companyId, Long channelShopId, String goodsId) throws Exception;
}
@@ -0,0 +1,143 @@
package top.xyquan.ecomdmbbackend.modules.channel.pdd.goods.ensure;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.auth.model.po.PddAuthPO;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.auth.service.PddAuthTokenService;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.goods.mapper.PddGoodsMapper;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.goods.model.po.PddGoodsPO;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.goods.service.PddGoodsService;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.convert.service.PddProductAutoCreateService;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.pop.PddAuthFailureException;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.pop.goods.PddGoodsPopApiClient;
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.modules.ec.product.mapper.ProductSkuMapper;
import top.xyquan.ecomdmbbackend.modules.ec.product.model.po.ProductSkuPO;
import java.util.List;
import java.util.Objects;
/**
* 渠道商品确保入库:查库 → 拉详情 → 首个 outer_id 定品 → 缺 SKU 补齐 → 否则自动建品。
*/
@Slf4j
@Service
public class PddGoodsEnsureServiceImpl implements PddGoodsEnsureService {
private final PddGoodsMapper pddGoodsMapper;
private final PddShopMapper pddShopMapper;
private final PddAuthTokenService authTokenService;
private final PddGoodsPopApiClient goodsPopApiClient;
private final ProductSkuMapper productSkuMapper;
private final PddProductAutoCreateService productAutoCreateService;
private final PddGoodsService pddGoodsService;
public PddGoodsEnsureServiceImpl(PddGoodsMapper pddGoodsMapper,
PddShopMapper pddShopMapper,
PddAuthTokenService authTokenService,
PddGoodsPopApiClient goodsPopApiClient,
ProductSkuMapper productSkuMapper,
PddProductAutoCreateService productAutoCreateService,
@Lazy PddGoodsService pddGoodsService) {
this.pddGoodsMapper = pddGoodsMapper;
this.pddShopMapper = pddShopMapper;
this.authTokenService = authTokenService;
this.goodsPopApiClient = goodsPopApiClient;
this.productSkuMapper = productSkuMapper;
this.productAutoCreateService = productAutoCreateService;
this.pddGoodsService = pddGoodsService;
}
@Override
@Transactional(rollbackFor = Exception.class)
public PddGoodsPO ensureBound(Long companyId, Long channelShopId, String goodsId) throws Exception {
if (companyId == null || channelShopId == null || !StringUtils.hasText(goodsId)) {
throw new BusinessException("渠道商品定位参数不完整");
}
String gid = goodsId.trim();
PddGoodsPO existing = find(companyId, channelShopId, gid);
if (existing != null && existing.getProductId() != null) {
return existing;
}
PddShopPO pddShop = pddShopMapper.selectById(channelShopId);
if (pddShop == null || !Objects.equals(pddShop.getCompanyId(), companyId)) {
throw new BusinessException("渠道店铺不存在 channelShopId=" + channelShopId);
}
if (pddShop.getPddAuthId() == null) {
throw new PddAuthFailureException("渠道店铺未授权,无法拉取商品");
}
long goodsIdLong;
try {
goodsIdLong = Long.parseLong(gid);
} catch (NumberFormatException e) {
throw new BusinessException("非法 goods_id=" + gid);
}
PddAuthPO auth = authTokenService.ensureUsableById(pddShop.getPddAuthId());
PddGoodsPopApiClient.GoodsDetail detail = goodsPopApiClient.fetchGoodsInformation(
pddShop.getMallId(), auth.getAccessToken(), goodsIdLong);
if (detail == null || detail.goodsId() == null) {
throw new BusinessException("拉取拼多多商品详情为空 goods_id=" + gid);
}
Long productId = resolveProductIdByOuterIds(companyId, detail.skuList());
if (productId != null) {
// 已有内部品:只补缺失 SKU,不挪动已挂在其他商品下的 SKU
productAutoCreateService.ensureMissingSkus(companyId, productId, detail);
} else {
productId = productAutoCreateService.ensureInternalProduct(companyId, detail);
}
if (productId == null) {
throw new BusinessException("无法关联或自动创建内部商品 goods_id=" + gid);
}
pddGoodsService.upsertFromGoodsDetail(
companyId, channelShopId, pddShop.getMallId(), productId, detail);
PddGoodsPO saved = find(companyId, channelShopId, gid);
if (saved == null || saved.getProductId() == null) {
throw new BusinessException("渠道商品落库失败 goods_id=" + gid);
}
log.info("已确保渠道商品绑定 channelShopId={} goodsId={} productId={}",
channelShopId, gid, saved.getProductId());
return saved;
}
private PddGoodsPO find(Long companyId, Long channelShopId, String goodsId) {
return pddGoodsMapper.selectOne(new LambdaQueryWrapper<PddGoodsPO>()
.eq(PddGoodsPO::getCompanyId, companyId)
.eq(PddGoodsPO::getShopId, channelShopId)
.eq(PddGoodsPO::getGoodsId, goodsId)
.last("LIMIT 1"));
}
/**
* 按 outer_id → 内部 sku_code 扫描,取第一个命中的 product_id。
* 多个 SKU 落在不同内部商品时仍取首个,不改动其余内部商品。
*/
private Long resolveProductIdByOuterIds(Long companyId, List<PddGoodsPopApiClient.SkuDetail> skus) {
if (skus == null || skus.isEmpty()) {
return null;
}
for (PddGoodsPopApiClient.SkuDetail sku : skus) {
if (sku == null || !StringUtils.hasText(sku.outerId())) {
continue;
}
ProductSkuPO internal = productSkuMapper.selectOne(new LambdaQueryWrapper<ProductSkuPO>()
.eq(ProductSkuPO::getCompanyId, companyId)
.eq(ProductSkuPO::getSkuCode, sku.outerId().trim())
.last("LIMIT 1"));
if (internal != null && internal.getProductId() != null) {
return internal.getProductId();
}
}
return null;
}
}
@@ -26,8 +26,8 @@ import top.xyquan.ecomdmbbackend.modules.channel.pdd.goods.model.po.PddGoodsSkuP
import top.xyquan.ecomdmbbackend.modules.channel.pdd.goods.model.vo.PddGoodsSkuVO;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.goods.model.vo.PddGoodsSyncResultVO;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.goods.model.vo.PddGoodsVO;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.goods.ensure.PddGoodsEnsureService;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.goods.service.PddGoodsService;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.convert.service.PddProductAutoCreateService;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.pop.goods.PddGoodsPopApiClient;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.shop.mapper.PddShopMapper;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.shop.model.po.PddShopPO;
@@ -62,7 +62,7 @@ public class PddGoodsServiceImpl extends ServiceImpl<PddGoodsMapper, PddGoodsPO>
private final PddGoodsPopApiClient goodsPopApiClient;
private final ProductSkuMapper productSkuMapper;
private final ProductMapper productMapper;
private final PddProductAutoCreateService productAutoCreateService;
private final PddGoodsEnsureService goodsEnsureService;
private final CurrentUserContext currentUserContext;
public PddGoodsServiceImpl(PddGoodsSkuMapper pddGoodsSkuMapper,
@@ -71,7 +71,7 @@ public class PddGoodsServiceImpl extends ServiceImpl<PddGoodsMapper, PddGoodsPO>
PddGoodsPopApiClient goodsPopApiClient,
ProductSkuMapper productSkuMapper,
ProductMapper productMapper,
@Lazy PddProductAutoCreateService productAutoCreateService,
@Lazy PddGoodsEnsureService goodsEnsureService,
CurrentUserContext currentUserContext) {
this.pddGoodsSkuMapper = pddGoodsSkuMapper;
this.pddShopMapper = pddShopMapper;
@@ -79,7 +79,7 @@ public class PddGoodsServiceImpl extends ServiceImpl<PddGoodsMapper, PddGoodsPO>
this.goodsPopApiClient = goodsPopApiClient;
this.productSkuMapper = productSkuMapper;
this.productMapper = productMapper;
this.productAutoCreateService = productAutoCreateService;
this.goodsEnsureService = goodsEnsureService;
this.currentUserContext = currentUserContext;
}
@@ -426,11 +426,11 @@ public class PddGoodsServiceImpl extends ServiceImpl<PddGoodsMapper, PddGoodsPO>
}
if (productId == null) {
try {
productId = productAutoCreateService.ensureInternalProductByFetching(
companyId, mallId, accessToken, item.goodsId());
PddGoodsPO bound = goodsEnsureService.ensureBound(companyId, pddShopId, goodsId);
productId = bound != null ? bound.getProductId() : null;
autoCreatedInternal = productId != null;
} catch (Exception e) {
log.warn("同步时自动建内部商品失败 shopId={} goodsId={}: {}",
log.warn("同步时确保渠道商品失败 shopId={} goodsId={}: {}",
pddShopId, goodsId, e.getMessage());
}
}
@@ -1,18 +1,19 @@
package top.xyquan.ecomdmbbackend.modules.channel.pdd.order.convert.service;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.goods.ensure.PddGoodsEnsureService;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.convert.messaging.PddProductAutoCreateMessage;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.mapper.PddOrderItemMapper;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.model.po.PddOrderItemPO;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.model.PddOrderSyncShopContext;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.service.PddOrderSyncContextResolver;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.goods.service.PddGoodsService;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.pop.goods.PddGoodsPopApiClient;
import top.xyquan.ecomdmbbackend.modules.ec.product.category.model.po.CategoryPO;
import top.xyquan.ecomdmbbackend.modules.ec.product.category.service.CategoryService;
@@ -28,17 +29,34 @@ import top.xyquan.ecomdmbbackend.modules.ec.product.service.ProductSkuService;
*/
@Slf4j
@Service
@RequiredArgsConstructor
public class PddProductAutoCreateService {
private final PddOrderSyncContextResolver contextResolver;
private final PddGoodsPopApiClient goodsPopApiClient;
private final PddGoodsService pddGoodsService;
private final PddOrderItemMapper pddOrderItemMapper;
private final CategoryService categoryService;
private final ProductService productService;
private final ProductSkuService productSkuService;
/** 与 {@link PddGoodsEnsureService} 互调,字段注入避免构造环。 */
@Autowired
@Lazy
private PddGoodsEnsureService goodsEnsureService;
public PddProductAutoCreateService(PddOrderSyncContextResolver contextResolver,
PddGoodsPopApiClient goodsPopApiClient,
PddOrderItemMapper pddOrderItemMapper,
CategoryService categoryService,
ProductService productService,
ProductSkuService productSkuService) {
this.contextResolver = contextResolver;
this.goodsPopApiClient = goodsPopApiClient;
this.pddOrderItemMapper = pddOrderItemMapper;
this.categoryService = categoryService;
this.productService = productService;
this.productSkuService = productSkuService;
}
@Transactional(rollbackFor = Exception.class)
public void createFromGoods(PddProductAutoCreateMessage message) throws Exception {
if (message == null || message.getCompanyId() == null
@@ -46,26 +64,17 @@ public class PddProductAutoCreateService {
return;
}
PddOrderSyncShopContext ctx = contextResolver.resolve(message.getCompanyId(), message.getShopId());
PddGoodsPopApiClient.GoodsDetail detail = goodsPopApiClient.fetchGoodsInformation(
ctx.getMallId(), ctx.getAccessToken(), message.getGoodsId());
Long productId = ensureInternalProduct(message.getCompanyId(), detail);
if (productId == null) {
return;
}
if (ctx.getPddShop() == null || ctx.getPddShop().getId() == null) {
log.warn("自动建品:缺少渠道店铺,跳过 channel_pdd_goods 落库 companyId={} goodsId={}",
log.warn("自动建品:缺少渠道店铺,跳过 companyId={} goodsId={}",
message.getCompanyId(), message.getGoodsId());
return;
}
pddGoodsService.upsertFromGoodsDetail(
goodsEnsureService.ensureBound(
message.getCompanyId(),
ctx.getPddShop().getId(),
ctx.getMallId(),
productId,
detail);
log.info("自动建品已绑定渠道商品 companyId={} pddShopId={} goodsId={} productId={}",
message.getCompanyId(), ctx.getPddShop().getId(), message.getGoodsId(), productId);
String.valueOf(message.getGoodsId()));
log.info("自动建品已绑定渠道商品 companyId={} pddShopId={} goodsId={}",
message.getCompanyId(), ctx.getPddShop().getId(), message.getGoodsId());
}
/**
@@ -109,11 +118,21 @@ public class PddProductAutoCreateService {
return null;
}
if (detail.skuList() == null || detail.skuList().isEmpty()) {
log.info("自动建品:商品无 SKU 列表 goodsId={} productId={}", detail.goodsId(), product.getId());
return product.getId();
}
ensureMissingSkus(companyId, product.getId(), detail);
return product.getId();
}
/**
* 在指定内部商品下补齐缺失 SKU。
* 公司内已存在的 sku_code(含挂在其他商品下的)一律跳过,不挪动、不改绑。
*/
@Transactional(rollbackFor = Exception.class)
public void ensureMissingSkus(Long companyId, Long productId, PddGoodsPopApiClient.GoodsDetail detail) {
if (companyId == null || productId == null || detail == null
|| detail.skuList() == null || detail.skuList().isEmpty()) {
return;
}
String imageUrl = resolveProductImageUrl(detail, companyId, detail.goodsId());
int created = 0;
int skipped = 0;
for (PddGoodsPopApiClient.SkuDetail skuDetail : detail.skuList()) {
@@ -130,16 +149,14 @@ public class PddProductAutoCreateService {
skipped++;
continue;
}
if (createSku(companyId, product.getId(), skuCode, skuDetail, imageUrl)) {
if (createSku(companyId, productId, skuCode, skuDetail, imageUrl)) {
created++;
} else {
skipped++;
}
}
log.info("自动建品完成 companyId={} goodsId={} productId={} categoryId={} createdSku={} skipped={} hasImage={}",
companyId, detail.goodsId(), product.getId(), categoryId, created, skipped,
StringUtils.hasText(imageUrl));
return product.getId();
log.info("补齐内部 SKU companyId={} productId={} goodsId={} created={} skipped={}",
companyId, productId, detail.goodsId(), created, skipped);
}
/**
@@ -170,10 +187,12 @@ public class PddProductAutoCreateService {
* 按叶子类目名判断是否已有内部类目;有则直接用。
* 无则:一级类目(goods_category) → parent_id=null;叶子(last_category) → 挂在一级下。
* 商品绑定叶子类目 id(仅有一级时绑一级)。
* <p>
* PDD 类目名可能带路径如「洗护清洁剂/卫生巾/纸/香薰」,只取第一个「/」前一段。
*/
private Long ensureCategoryId(Long companyId, String goodsCategory, String lastCategory) {
String leaf = StringUtils.hasText(lastCategory) ? lastCategory.trim() : null;
String level1 = StringUtils.hasText(goodsCategory) ? goodsCategory.trim() : null;
String leaf = normalizeCategoryName(lastCategory);
String level1 = normalizeCategoryName(goodsCategory);
if (leaf == null && level1 == null) {
return null;
}
@@ -193,6 +212,19 @@ public class PddProductAutoCreateService {
return ensureNamedCategory(companyId, null, level1);
}
/** 「A/B/C」→「A」;无「/」则原样。 */
private static String normalizeCategoryName(String raw) {
if (!StringUtils.hasText(raw)) {
return null;
}
String name = raw.trim();
int slash = name.indexOf('/');
if (slash >= 0) {
name = name.substring(0, slash).trim();
}
return StringUtils.hasText(name) ? name : null;
}
/** 按公司+名称查找或创建类目(公司内名称唯一)。 */
private Long ensureNamedCategory(Long companyId, Long parentId, String name) {
CategoryPO existing = categoryService.getByCompanyIdAndName(companyId, name);
@@ -216,6 +216,9 @@ public class PddGoodsPopApiClient {
}
public record SkuDetail(Long skuId, String spec, String outerId, String outerGoodsId, String skuImg) {
/**
* 内部 sku_code:优先商家编码 outer_id;无则回退 {@code PDD:{skuId}}。
*/
public String resolveSkuCode() {
if (StringUtils.hasText(outerId)) {
return outerId.trim();
@@ -19,8 +19,9 @@ public class CreateAdFeeDTO {
private Long shopId;
/**
* 商品ID(可选,关联到具体商品)
* 商品ID
*/
@NotNull(message = "商品ID不能为空")
private Long productId;
/**
@@ -25,8 +25,9 @@ public class UpdateAdFeeDTO {
private Long shopId;
/**
* 商品ID(可选,关联到具体商品)
* 商品ID
*/
@NotNull(message = "商品ID不能为空")
private Long productId;
/**
@@ -1,6 +1,10 @@
package top.xyquan.ecomdmbbackend.modules.ec.shop.adfee.model.po;
import com.baomidou.mybatisplus.annotation.*;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import lombok.EqualsAndHashCode;
@@ -9,82 +13,47 @@ import java.time.LocalDate;
import java.time.LocalDateTime;
/**
* 电商-广告费记录实体(表 ec_ad_fee)
* 电商-商品广告推广费(表 ec_product_ad_fee)。
*/
@Data
@EqualsAndHashCode(callSuper = false)
@TableName("ec_ad_fee")
@TableName("ec_product_ad_fee")
public class AdFeePO {
/**
* 广告费记录ID
*/
@TableId(value = "id", type = IdType.AUTO)
private Long id;
/**
* 公司ID
*/
@TableField("company_id")
private Long companyId;
/**
* 店铺ID
*/
@TableField("shop_id")
private Long shopId;
/**
* 商品ID(可选)
*/
/** 商品ID(必填,与 fee_date 联合唯一) */
@TableField("product_id")
private Long productId;
/**
* 广告活动名称
*/
@TableField("campaign_name")
private String campaignName;
/**
* 广告费金额
*/
@TableField("fee_amount")
private BigDecimal feeAmount;
/**
* 广告费发生日期
*/
@TableField("fee_date")
private LocalDate feeDate;
/**
* 备注
*/
@TableField("remark")
private String remark;
/**
* 创建时间
*/
@TableField(value = "create_time", fill = FieldFill.INSERT)
private LocalDateTime createTime;
/**
* 更新时间
*/
@TableField(value = "update_time", fill = FieldFill.INSERT_UPDATE)
private LocalDateTime updateTime;
/**
* 创建人ID
*/
@TableField("create_by")
private Long createBy;
/**
* 更新人ID
*/
@TableField("update_by")
private Long updateBy;
}
@@ -33,7 +33,7 @@ public class AdFeeVO {
private String shopName;
/**
* 商品ID(可选)
* 商品ID
*/
private Long productId;
@@ -28,7 +28,7 @@ import java.util.stream.Collectors;
/**
* 广告费导入处理器
* 负责解析 CSV/Excel 文件中的推广费数据,按字段映射提取 campaignName/feeAmount,
* 从文件列中直接读取 productId,按 product_id + fee_date 联合唯一 upsert 写入 ec_ad_fee。
* 从文件列中直接读取 productId,按 product_id + fee_date 联合唯一 upsert 写入 ec_product_ad_fee。
*/
@Service
public class AdFeeImportProcessor extends ServiceImpl<AdFeeMapper, AdFeePO> {
@@ -83,18 +83,14 @@ public class AdFeeImportProcessor extends ServiceImpl<AdFeeMapper, AdFeePO> {
* 同文件内相同 productId + feeDate 保留最后一行,避免撞唯一键。
*/
private List<AdFeePO> collapseByProductDate(List<AdFeePO> records) {
LinkedHashMap<String, AdFeePO> withProduct = new LinkedHashMap<>();
List<AdFeePO> withoutProduct = new ArrayList<>();
LinkedHashMap<String, AdFeePO> byKey = new LinkedHashMap<>();
for (AdFeePO po : records) {
if (po.getProductId() == null) {
withoutProduct.add(po);
if (po.getProductId() == null || po.getFeeDate() == null) {
continue;
}
withProduct.put(po.getProductId() + "|" + po.getFeeDate(), po);
byKey.put(po.getProductId() + "|" + po.getFeeDate(), po);
}
List<AdFeePO> result = new ArrayList<>(withProduct.values());
result.addAll(withoutProduct);
return result;
return new ArrayList<>(byKey.values());
}
private int upsertBatch(List<AdFeePO> batch) {
@@ -107,35 +103,35 @@ public class AdFeeImportProcessor extends ServiceImpl<AdFeeMapper, AdFeePO> {
.filter(Objects::nonNull)
.distinct()
.collect(Collectors.toList());
if (productIds.isEmpty() || feeDate == null) {
return 0;
}
Map<Long, AdFeePO> existingByProduct = new HashMap<>();
if (!productIds.isEmpty() && feeDate != null) {
List<AdFeePO> existing = list(new LambdaQueryWrapper<AdFeePO>()
.eq(AdFeePO::getFeeDate, feeDate)
.in(AdFeePO::getProductId, productIds));
for (AdFeePO po : existing) {
existingByProduct.put(po.getProductId(), po);
}
List<AdFeePO> existing = list(new LambdaQueryWrapper<AdFeePO>()
.eq(AdFeePO::getFeeDate, feeDate)
.in(AdFeePO::getProductId, productIds));
for (AdFeePO po : existing) {
existingByProduct.put(po.getProductId(), po);
}
List<AdFeePO> toInsert = new ArrayList<>();
List<AdFeePO> toUpdate = new ArrayList<>();
for (AdFeePO incoming : batch) {
if (incoming.getProductId() == null) {
continue;
}
AdFeePO found = existingByProduct.get(incoming.getProductId());
if (found == null) {
toInsert.add(incoming);
continue;
}
AdFeePO existing = existingByProduct.get(incoming.getProductId());
if (existing == null) {
toInsert.add(incoming);
continue;
}
existing.setShopId(incoming.getShopId());
existing.setCampaignName(incoming.getCampaignName());
existing.setFeeAmount(incoming.getFeeAmount());
existing.setRemark(incoming.getRemark());
existing.setUpdateBy(incoming.getUpdateBy());
toUpdate.add(existing);
found.setShopId(incoming.getShopId());
found.setCampaignName(incoming.getCampaignName());
found.setFeeAmount(incoming.getFeeAmount());
found.setRemark(incoming.getRemark());
found.setUpdateBy(incoming.getUpdateBy());
toUpdate.add(found);
}
if (!toInsert.isEmpty()) {
@@ -144,7 +140,7 @@ public class AdFeeImportProcessor extends ServiceImpl<AdFeeMapper, AdFeePO> {
if (!toUpdate.isEmpty()) {
updateBatchById(toUpdate);
}
return batch.size();
return toInsert.size() + toUpdate.size();
}
private ParseResult parseCsv(File file, Charset charset,
@@ -257,12 +253,16 @@ public class AdFeeImportProcessor extends ServiceImpl<AdFeeMapper, AdFeePO> {
}
BigDecimal feeAmount = new BigDecimal(normalizeFeeAmount(feeAmountStr));
Long productId = parseLong(cellGetter.apply("productId"));
if (productId == null) {
return RowBuildResult.invalid("商品ID不能为空", campaignName);
}
AdFeePO po = new AdFeePO();
po.setCompanyId(task.getCompanyId());
po.setShopId(task.getShopId());
po.setFeeDate(feeDate);
po.setProductId(parseLong(cellGetter.apply("productId")));
po.setProductId(productId);
po.setCampaignName(campaignName);
po.setFeeAmount(feeAmount);
po.setCreateBy(task.getCreateBy());
@@ -54,10 +54,12 @@ public class AdFeeServiceImpl implements AdFeeService {
@Override
@Transactional(rollbackFor = Exception.class)
public Long createAdFee(CreateAdFeeDTO dto) {
Long companyId = currentUserContext.getCurrentCompanyId();
requireOwnedProduct(dto.getProductId(), companyId);
assertProductDateUnique(dto.getProductId(), dto.getFeeDate(), null);
AdFeePO po = new AdFeePO();
BeanCopyUtils.copyProperties(dto, po);
po.setCompanyId(currentUserContext.getCurrentCompanyId());
po.setCompanyId(companyId);
po.setCreateBy(currentUserContext.getCurrentUserId());
po.setUpdateBy(currentUserContext.getCurrentUserId());
@@ -77,6 +79,7 @@ public class AdFeeServiceImpl implements AdFeeService {
if (existing == null || !existing.getCompanyId().equals(companyId)) {
throw new BusinessException("广告费记录不存在");
}
requireOwnedProduct(dto.getProductId(), companyId);
assertProductDateUnique(dto.getProductId(), dto.getFeeDate(), dto.getId());
AdFeePO po = new AdFeePO();
BeanCopyUtils.copyProperties(dto, po);
@@ -191,11 +194,24 @@ public class AdFeeServiceImpl implements AdFeeService {
}
/**
* 商品 + 推广日期联合唯一(product_id 为空时不校验)
* 校验商品属于当前公司。
*/
private void requireOwnedProduct(Long productId, Long companyId) {
if (productId == null) {
throw new BusinessException("商品ID不能为空");
}
ProductPO product = productService.getById(productId);
if (product == null || !companyId.equals(product.getCompanyId())) {
throw new BusinessException("商品不存在或无权访问");
}
}
/**
* 商品 + 推广日期联合唯一。
*/
private void assertProductDateUnique(Long productId, LocalDate feeDate, Long excludeId) {
if (productId == null || feeDate == null) {
return;
throw new BusinessException("商品ID与推广日期不能为空");
}
LambdaQueryWrapper<AdFeePO> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(AdFeePO::getProductId, productId)
@@ -2,28 +2,49 @@ package top.xyquan.ecomdmbbackend.modules.open.api.controller;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import top.xyquan.ecomdmbbackend.common.annotation.RequireOpenScope;
import top.xyquan.ecomdmbbackend.common.model.dto.PageQueryDTO;
import top.xyquan.ecomdmbbackend.common.model.vo.PageResultVO;
import top.xyquan.ecomdmbbackend.common.response.ApiResponse;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.adfee.importtask.model.dto.PddGoodsAdFeeImportTaskFilterDTO;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.adfee.importtask.model.vo.PddGoodsAdFeeImportTaskVO;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.adfee.importtask.service.PddGoodsAdFeeImportService;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.adfee.model.dto.BatchImportPddGoodsAdFeeDTO;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.adfee.model.vo.BatchImportPddGoodsAdFeeResultVO;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.adfee.service.PddGoodsAdFeeService;
import top.xyquan.ecomdmbbackend.modules.open.api.constants.OpenApiScopeConstants;
/**
* OpenAPI:浏览器扩展只创建导入任务并查询进度。
*/
@RestController
@RequestMapping("/api/open/v1/channel/pdd/goods/adfee")
@RequiredArgsConstructor
public class OpenPddGoodsAdFeeController {
private final PddGoodsAdFeeService pddGoodsAdFeeService;
private final PddGoodsAdFeeImportService importService;
@PostMapping("/batch-import")
@RequireOpenScope(value = OpenApiScopeConstants.PDD_GOODS_AD_FEE_IMPORT, description = "批量导入拼多多商品广告费")
public ApiResponse<BatchImportPddGoodsAdFeeResultVO> batchImport(
@RequireOpenScope(value = OpenApiScopeConstants.PDD_GOODS_AD_FEE_IMPORT, description = "创建拼多多商品广告费导入任务")
public ApiResponse<PddGoodsAdFeeImportTaskVO> batchImport(
@Valid @RequestBody BatchImportPddGoodsAdFeeDTO dto) {
return ApiResponse.success("批量导入完成", pddGoodsAdFeeService.batchImport(dto));
return ApiResponse.success("已创建导入任务", importService.createAndEnqueue(dto));
}
@GetMapping("/import-task/{id}")
@RequireOpenScope(value = OpenApiScopeConstants.PDD_GOODS_AD_FEE_IMPORT, description = "查询拼多多商品广告费导入任务")
public ApiResponse<PddGoodsAdFeeImportTaskVO> importTaskDetail(@PathVariable Long id) {
return ApiResponse.success("获取成功", importService.getDetail(id));
}
@PostMapping("/import-task/list")
@RequireOpenScope(value = OpenApiScopeConstants.PDD_GOODS_AD_FEE_IMPORT, description = "查询拼多多商品广告费导入任务列表")
public ApiResponse<PageResultVO<PddGoodsAdFeeImportTaskVO>> importTaskList(
@Valid @RequestBody PageQueryDTO<PddGoodsAdFeeImportTaskFilterDTO> pageQueryDTO) {
return ApiResponse.success("获取成功", importService.getPage(pageQueryDTO));
}
}
@@ -489,7 +489,7 @@ INSERT INTO `sys_menu` (`id`, `parent_id`, `super`, `name`, `title`, `path`, `co
SELECT 13002, (SELECT id FROM `sys_menu` WHERE `name` = '配置管理' LIMIT 1), 0, '商品类目', '商品类目', '/category', '/ecommerce/config/category-config/index', '', 'iconamoon:category-bold', 'menu', 1, 1, 0, 12
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_menu` WHERE `name` = '商品类目');
-- 推广费用类型菜单已下线(ec_ad_fee 重构后不再维护类型表)
-- 推广费用类型菜单已下线(ec_product_ad_fee 重构后不再维护类型表)
-- INSERT INTO `sys_menu` (`id`, `parent_id`, `super`, `name`, `title`, `path`, `component`, `redirect`, `icon`, `type`, `visible`, `status`, `keep_alive`, `order`)
-- SELECT 13003, (SELECT id FROM `sys_menu` WHERE `name` = '配置管理' LIMIT 1), 0, '推广费用类型', '推广费用类型', '/promotion-fee-type', '/ecommerce/config/promotion-fee-type-config/index', '', 'lucide:percent', 'menu', 1, 1, 0, 13
-- FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_menu` WHERE `name` = '推广费用类型');
@@ -28,6 +28,7 @@ export namespace PddGoodsAdFeeVO {
export interface Info {
id: number;
companyId?: number;
goodsRowId?: number;
channelShopId: number;
channelShopName?: string;
mallId?: number;
@@ -19,8 +19,8 @@ export namespace AdFeeDTO {
export interface Create {
/** 店铺ID */
shopId: number;
/** 商品ID(可选,关联到具体商品) */
productId?: number;
/** 商品ID */
productId: number;
/** 推广活动名称 */
campaignName?: string;
/** 广告费金额 */
@@ -37,8 +37,8 @@ export namespace AdFeeDTO {
id: number;
/** 店铺ID */
shopId: number;
/** 商品ID(可选,关联到具体商品) */
productId?: number;
/** 商品ID */
productId: number;
/** 推广活动名称 */
campaignName?: string;
/** 广告费金额 */
@@ -13,8 +13,8 @@ export namespace AdFeeVO {
shopId: number;
/** 店铺名称 */
shopName?: string;
/** 商品ID(可选) */
productId?: number;
/** 商品ID */
productId: number;
/** 商品名称 */
productName?: string;
/** 商品编码 */
@@ -87,6 +87,7 @@ const formData = ref<AdFeeFormState>({
const rules = {
shopId: [{ required: true, message: '请选择店铺', trigger: 'change' }],
productId: [{ required: true, message: '请选择商品', trigger: 'change' }],
feeAmount: [{ required: true, message: '请输入广告费金额', trigger: 'blur' }],
feeDate: [{ required: true, message: '请选择发生日期', trigger: 'change' }],
} as any;
@@ -248,12 +249,11 @@ onMounted(() => {
</Select>
</Form.Item>
<Form.Item label="商品(可选)" name="productId">
<Form.Item label="商品" name="productId">
<Select
v-model:value="formData.productId"
placeholder="请选择商品(可选)"
placeholder="请选择商品"
:loading="productListLoading"
allow-clear
show-search
:filter-option="productSelectFilterOption"
>