mirror of
https://gitee.com/qqtt-ah/ecom-dmb.git
synced 2026-11-24 03:19:18 +08:00
feat: 完成多日读取支持
This commit is contained in:
@@ -8,5 +8,6 @@ export interface PlatformAdapter {
|
||||
readonly platform: PlatformType;
|
||||
canHandle(url: string): boolean;
|
||||
getPageContext(): Promise<PageContext>;
|
||||
parseAdvertisingCost(feeDate: string): Promise<Omit<AdvertisingCostBatch, 'channelShopId'>>;
|
||||
/** 从当前页解析推广费;每条 item 自带 feeDate */
|
||||
parseAdvertisingCost(): Promise<Omit<AdvertisingCostBatch, 'channelShopId'>>;
|
||||
}
|
||||
|
||||
@@ -2,8 +2,9 @@ import type { PlatformType } from '@/types/advertisingCost';
|
||||
|
||||
import type { PlatformAdapter } from './PlatformAdapter';
|
||||
import { MockPlatformAdapter } from '../mock/MockPlatformAdapter';
|
||||
import { PddPlatformAdapter } from '../pdd/PddPlatformAdapter';
|
||||
|
||||
const adapters: PlatformAdapter[] = [new MockPlatformAdapter()];
|
||||
const adapters: PlatformAdapter[] = [new PddPlatformAdapter(), new MockPlatformAdapter()];
|
||||
|
||||
export function detectPlatform(url: string): PlatformType {
|
||||
const adapter = adapters.find((item) => item.canHandle(url));
|
||||
@@ -15,8 +16,8 @@ export function resolveAdapter(url: string): PlatformAdapter {
|
||||
if (matched) {
|
||||
return matched;
|
||||
}
|
||||
// 第一阶段:未识别平台时回退 Mock,保证链路可跑通
|
||||
return adapters[0]!;
|
||||
// 非拼多多推广页时回退 Mock,便于本地联调
|
||||
return adapters.find((item) => item.platform === 'mock') ?? adapters[0]!;
|
||||
}
|
||||
|
||||
export function listAdapters(): PlatformAdapter[] {
|
||||
|
||||
@@ -2,13 +2,13 @@ import type { PlatformAdapter } from '@/platform/core/PlatformAdapter';
|
||||
import type { AdvertisingCostBatch, PageContext } from '@/types/advertisingCost';
|
||||
|
||||
/**
|
||||
* 第一阶段 Mock Adapter:不读真实 DOM,返回固定样例数据。
|
||||
* 第一阶段 Mock Adapter:不读真实 DOM,返回带日期的样例。
|
||||
* 真实页面解析等接入平台后再实现。
|
||||
*/
|
||||
export class MockPlatformAdapter implements PlatformAdapter {
|
||||
readonly platform = 'mock' as const;
|
||||
|
||||
canHandle(_url: string): boolean {
|
||||
// 未接入真实平台前,任意页面均可由 Mock 处理
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -22,19 +22,14 @@ export class MockPlatformAdapter implements PlatformAdapter {
|
||||
};
|
||||
}
|
||||
|
||||
async parseAdvertisingCost(
|
||||
feeDate: string,
|
||||
): Promise<Omit<AdvertisingCostBatch, 'channelShopId'>> {
|
||||
const items = [
|
||||
{ goodsId: 'mock-goods-1001', feeAmount: 128.5 },
|
||||
{ goodsId: 'mock-goods-1002', feeAmount: 56.0 },
|
||||
{ goodsId: 'mock-goods-1003', feeAmount: 1050.06 },
|
||||
];
|
||||
|
||||
async parseAdvertisingCost(): Promise<Omit<AdvertisingCostBatch, 'channelShopId'>> {
|
||||
return {
|
||||
platform: 'mock',
|
||||
feeDate,
|
||||
items,
|
||||
items: [
|
||||
{ feeDate: '2026-08-14', goodsId: 'mock-goods-1001', feeAmount: 128.5 },
|
||||
{ feeDate: '2026-08-15', goodsId: 'mock-goods-1002', feeAmount: 56.0 },
|
||||
{ feeDate: '2026-08-16', goodsId: 'mock-goods-1003', feeAmount: 1050.06 },
|
||||
],
|
||||
source: 'browser-extension',
|
||||
importedAt: new Date().toISOString(),
|
||||
};
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
import type { PlatformAdapter } from '@/platform/core/PlatformAdapter';
|
||||
import type { AdvertisingCostBatch, PageContext } from '@/types/advertisingCost';
|
||||
|
||||
import {
|
||||
isPddPromotionOverviewUrl,
|
||||
parsePromotionItems,
|
||||
readMallName,
|
||||
readReportDate,
|
||||
} from './parseReport';
|
||||
|
||||
/**
|
||||
* 拼多多推广平台 · 商品推广总览报表
|
||||
* https://yingxiao.pinduoduo.com/goods/report/promotion/overView
|
||||
*/
|
||||
export class PddPlatformAdapter implements PlatformAdapter {
|
||||
readonly platform = 'pdd' as const;
|
||||
|
||||
canHandle(url: string): boolean {
|
||||
return isPddPromotionOverviewUrl(url);
|
||||
}
|
||||
|
||||
async getPageContext(): Promise<PageContext> {
|
||||
const mallName = readMallName();
|
||||
const dateInfo = readReportDate();
|
||||
const ready = Boolean(mallName) && dateInfo.mode !== 'unknown';
|
||||
|
||||
let message: string | undefined;
|
||||
if (!mallName) {
|
||||
message = '未识别到店铺名称';
|
||||
} else if (dateInfo.mode === 'range') {
|
||||
message = dateInfo.message;
|
||||
} else if (dateInfo.mode === 'unknown') {
|
||||
message = dateInfo.message;
|
||||
} else {
|
||||
message = `店铺「${mallName}」· 单日 ${dateInfo.feeDate}`;
|
||||
}
|
||||
|
||||
return {
|
||||
url: location.href,
|
||||
title: document.title,
|
||||
platform: 'pdd',
|
||||
ready,
|
||||
message,
|
||||
mallName,
|
||||
feeDate: dateInfo.feeDate,
|
||||
dateMode: dateInfo.mode,
|
||||
};
|
||||
}
|
||||
|
||||
async parseAdvertisingCost(): Promise<Omit<AdvertisingCostBatch, 'channelShopId'>> {
|
||||
const dateInfo = readReportDate();
|
||||
if (dateInfo.mode === 'range') {
|
||||
throw new Error(dateInfo.message ?? '范围报表不记录,请切换为单日查看');
|
||||
}
|
||||
if (dateInfo.mode !== 'single' || !dateInfo.feeDate) {
|
||||
throw new Error(dateInfo.message ?? '未能识别单日报表日期');
|
||||
}
|
||||
|
||||
const items = parsePromotionItems(dateInfo.feeDate);
|
||||
if (items.length === 0) {
|
||||
throw new Error('未解析到商品推广费,请确认表格已加载且包含「总花费」列');
|
||||
}
|
||||
|
||||
return {
|
||||
platform: 'pdd',
|
||||
items,
|
||||
source: 'browser-extension',
|
||||
importedAt: new Date().toISOString(),
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import type { PddChannelShop } from '@/api/open/pddShop';
|
||||
import { listPddChannelShops } from '@/api/open/pddShop';
|
||||
|
||||
/**
|
||||
* 用页面店铺名通过 Open 店铺分页接口匹配 BI channelShop。
|
||||
* 优先精确匹配 mallName,其次仅当筛选结果唯一时采用。
|
||||
*/
|
||||
export async function matchChannelShopByMallName(
|
||||
mallName: string,
|
||||
): Promise<PddChannelShop | null> {
|
||||
const name = mallName.trim();
|
||||
if (!name) return null;
|
||||
|
||||
const result = await listPddChannelShops({
|
||||
page: 1,
|
||||
pageSize: 50,
|
||||
filters: { mallName: name },
|
||||
});
|
||||
const records = result.records ?? [];
|
||||
if (records.length === 0) return null;
|
||||
|
||||
const exact = records.find((shop) => (shop.mallName ?? '').trim() === name);
|
||||
if (exact) return exact;
|
||||
if (records.length === 1) return records[0]!;
|
||||
return null;
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
import type { AdvertisingCostItem } from '@/types/advertisingCost';
|
||||
|
||||
import {
|
||||
DATE_VALUE_RE,
|
||||
FEE_COLUMN_LABEL,
|
||||
GOODS_ID_RE,
|
||||
PDD_SELECTORS,
|
||||
} from './selectors';
|
||||
|
||||
export type PddDateMode = 'single' | 'range' | 'unknown';
|
||||
|
||||
export interface PddReportDateInfo {
|
||||
mode: PddDateMode;
|
||||
feeDate?: string;
|
||||
beginDate?: string;
|
||||
endDate?: string;
|
||||
message?: string;
|
||||
}
|
||||
|
||||
export function normalizePddDate(raw: string | null | undefined): string | undefined {
|
||||
if (!raw) return undefined;
|
||||
const cleaned = raw.trim().replace(/(.*?)|\(.*?\)/g, '').trim();
|
||||
const match = cleaned.match(DATE_VALUE_RE);
|
||||
if (!match) return undefined;
|
||||
const [, y, m, d] = match;
|
||||
return `${y}-${m!.padStart(2, '0')}-${d!.padStart(2, '0')}`;
|
||||
}
|
||||
|
||||
export function parseAmount(raw: string | null | undefined): number | undefined {
|
||||
if (raw == null) return undefined;
|
||||
const text = raw.replace(/[,\s¥¥]/g, '').trim();
|
||||
if (!text || text === '-' || text === '--') return undefined;
|
||||
const value = Number(text);
|
||||
return Number.isFinite(value) ? value : undefined;
|
||||
}
|
||||
|
||||
export function readMallName(doc: Document = document): string | undefined {
|
||||
const el = doc.querySelector(PDD_SELECTORS.mallName);
|
||||
const text = el?.textContent?.trim();
|
||||
return text || undefined;
|
||||
}
|
||||
|
||||
/** 优先 URL beginDate/endDate,其次主 RangePicker 两个 input */
|
||||
export function readReportDate(doc: Document = document, href = location.href): PddReportDateInfo {
|
||||
try {
|
||||
const url = new URL(href);
|
||||
const begin = normalizePddDate(url.searchParams.get('beginDate') ?? undefined);
|
||||
const end = normalizePddDate(url.searchParams.get('endDate') ?? undefined);
|
||||
if (begin && end) {
|
||||
if (begin === end) {
|
||||
return { mode: 'single', feeDate: begin, beginDate: begin, endDate: end };
|
||||
}
|
||||
return {
|
||||
mode: 'range',
|
||||
beginDate: begin,
|
||||
endDate: end,
|
||||
message: `当前为范围报表(${begin} ~ ${end}),仅单日查看时才记录`,
|
||||
};
|
||||
}
|
||||
} catch {
|
||||
// ignore invalid href
|
||||
}
|
||||
|
||||
const pickers = Array.from(doc.querySelectorAll(PDD_SELECTORS.rangePicker));
|
||||
for (const picker of pickers) {
|
||||
// 跳过对比日期区(CompareDate 内嵌 picker)
|
||||
if (picker.closest('[class*="CompareDate"]')) continue;
|
||||
const inputs = Array.from(picker.querySelectorAll('input')).slice(0, 2);
|
||||
if (inputs.length < 2) continue;
|
||||
const begin = normalizePddDate(inputs[0]?.value);
|
||||
const end = normalizePddDate(inputs[1]?.value);
|
||||
if (!begin || !end) continue;
|
||||
if (begin === end) {
|
||||
return { mode: 'single', feeDate: begin, beginDate: begin, endDate: end };
|
||||
}
|
||||
return {
|
||||
mode: 'range',
|
||||
beginDate: begin,
|
||||
endDate: end,
|
||||
message: `当前为范围报表(${begin} ~ ${end}),仅单日查看时才记录`,
|
||||
};
|
||||
}
|
||||
|
||||
return { mode: 'unknown', message: '未能识别报表日期,请确认已打开商品推广总览且选择了日期' };
|
||||
}
|
||||
|
||||
/**
|
||||
* antd 横向滚动表会拆成「sticky 表头 table」+「表体 table」:
|
||||
* 表头有「总花费」、无商品行;表体有商品行、无 thead。
|
||||
* 因此列索引从表头取,行数据从含 goodsId 的 tr 取。
|
||||
*/
|
||||
function findFeeColumnIndex(root: ParentNode): number {
|
||||
const headers = Array.from(root.querySelectorAll(PDD_SELECTORS.tableHeaderCell));
|
||||
return headers.findIndex((th) => (th.textContent ?? '').includes(FEE_COLUMN_LABEL));
|
||||
}
|
||||
|
||||
export function parsePromotionItems(
|
||||
feeDate: string,
|
||||
doc: Document = document,
|
||||
): AdvertisingCostItem[] {
|
||||
const wrap = doc.querySelector(PDD_SELECTORS.overviewTable) ?? doc;
|
||||
|
||||
const feeCol = findFeeColumnIndex(wrap);
|
||||
if (feeCol < 0) {
|
||||
throw new Error(`未找到「${FEE_COLUMN_LABEL}」列,请检查报表列配置是否包含总花费`);
|
||||
}
|
||||
|
||||
const goodsNodes = Array.from(wrap.querySelectorAll(PDD_SELECTORS.goodsId));
|
||||
if (goodsNodes.length === 0) {
|
||||
throw new Error('未找到商品 ID,请确认推广商品表格已加载完成');
|
||||
}
|
||||
|
||||
const items: AdvertisingCostItem[] = [];
|
||||
const seen = new Set<string>();
|
||||
|
||||
for (const goodsEl of goodsNodes) {
|
||||
const goodsText = goodsEl.textContent?.trim() ?? '';
|
||||
const goodsMatch = goodsText.match(GOODS_ID_RE);
|
||||
if (!goodsMatch) continue;
|
||||
|
||||
const goodsId = goodsMatch[1]!;
|
||||
if (seen.has(goodsId)) continue;
|
||||
|
||||
const row = goodsEl.closest('tr');
|
||||
if (!row) continue;
|
||||
|
||||
const cells = Array.from(row.querySelectorAll(':scope > td'));
|
||||
const feeCell = cells[feeCol];
|
||||
const feeAmount = parseAmount(feeCell?.textContent);
|
||||
if (feeAmount == null) continue;
|
||||
|
||||
seen.add(goodsId);
|
||||
items.push({
|
||||
feeDate,
|
||||
goodsId,
|
||||
feeAmount,
|
||||
metadata: {
|
||||
goodsName: row
|
||||
.querySelector('[class*="OverviewTable_goodsName"]')
|
||||
?.getAttribute('title')
|
||||
?.replace(/^商品名:/, ''),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return items;
|
||||
}
|
||||
|
||||
export function isPddPromotionOverviewUrl(url: string): boolean {
|
||||
try {
|
||||
const u = new URL(url);
|
||||
if (!u.hostname.includes('yingxiao.pinduoduo.com')) return false;
|
||||
return u.pathname.includes('/report/promotion/overView') || u.pathname.includes('/goods/report/promotion');
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
/** 拼多多推广报表 DOM 选择器(CSS Modules hash 会变,用前缀匹配) */
|
||||
|
||||
export const PDD_SELECTORS = {
|
||||
mallName: '[class*="AccountNew_mallName"], [class*="AccountNew_titleName"]',
|
||||
overviewTable: '[class*="OverviewTable_wrap"]',
|
||||
goodsId: '[class*="OverviewTable_goodsId"]',
|
||||
/** 主日期范围选择器(不含对比日期) */
|
||||
rangePicker: '.anq-picker-range',
|
||||
rangePickerInput: '.anq-picker-range .anq-picker-input input',
|
||||
/** 表头可能在 sticky 独立 table 里,需在整个 OverviewTable_wrap 内查找 */
|
||||
tableHeaderCell: 'thead th',
|
||||
} as const;
|
||||
|
||||
/** 推广费列名:取「总花费(元)」 */
|
||||
export const FEE_COLUMN_LABEL = '总花费';
|
||||
|
||||
export const GOODS_ID_RE = /商品\s*ID\s*[::]\s*(\d+)/i;
|
||||
export const DATE_VALUE_RE = /^(\d{4})[/-](\d{1,2})[/-](\d{1,2})/;
|
||||
Reference in New Issue
Block a user