refacor: 重构目录架构

This commit is contained in:
2026-09-16 22:43:21 +08:00
parent b37cdb0d54
commit 2754ed1e45
2762 changed files with 0 additions and 1529 deletions
@@ -0,0 +1,15 @@
import type {
AdvertisingCostBatch,
PageContext,
PlatformType,
} from '@/types/advertisingCost';
export interface PlatformAdapter {
readonly platform: PlatformType;
canHandle(url: string): boolean;
getPageContext(): Promise<PageContext>;
/** 从当前页解析推广费;每条 item 自带 feeDate */
parseAdvertisingCost(
options?: { allowEmpty?: boolean },
): Promise<Omit<AdvertisingCostBatch, 'channelShopId'>>;
}
@@ -0,0 +1,25 @@
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 PddPlatformAdapter(), new MockPlatformAdapter()];
export function detectPlatform(url: string): PlatformType {
const adapter = adapters.find((item) => item.canHandle(url));
return adapter?.platform ?? 'unknown';
}
export function resolveAdapter(url: string): PlatformAdapter {
const matched = adapters.find((item) => item.canHandle(url));
if (matched) {
return matched;
}
// 非拼多多推广页时回退 Mock,便于本地联调
return adapters.find((item) => item.platform === 'mock') ?? adapters[0]!;
}
export function listAdapters(): PlatformAdapter[] {
return [...adapters];
}
@@ -0,0 +1,2 @@
export type { PlatformAdapter } from './PlatformAdapter';
export { detectPlatform, listAdapters, resolveAdapter } from './PlatformDetector';
@@ -0,0 +1,37 @@
import type { PlatformAdapter } from '@/platform/core/PlatformAdapter';
import type { AdvertisingCostBatch, PageContext } from '@/types/advertisingCost';
/**
* 第一阶段 Mock Adapter:不读真实 DOM,返回带日期的样例。
* 真实页面解析等接入平台后再实现。
*/
export class MockPlatformAdapter implements PlatformAdapter {
readonly platform = 'mock' as const;
canHandle(_url: string): boolean {
return true;
}
async getPageContext(): Promise<PageContext> {
return {
url: typeof location !== 'undefined' ? location.href : '',
title: typeof document !== 'undefined' ? document.title : '',
platform: 'mock',
ready: true,
message: '当前为 Mock Adapter(未解析真实平台页面)',
};
}
async parseAdvertisingCost(): Promise<Omit<AdvertisingCostBatch, 'channelShopId'>> {
return {
platform: 'mock',
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,77 @@
import type { PlatformAdapter } from '@/platform/core/PlatformAdapter';
import type { AdvertisingCostBatch, PageContext } from '@/types/advertisingCost';
import { ensurePageSize100 } from './ensurePageSize';
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(
options: { allowEmpty?: boolean } = {},
): 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 ?? '未能识别单日报表日期');
}
// 读取前把「每页」自动切到 100,减少分页漏读
await ensurePageSize100();
const items = parsePromotionItems(dateInfo.feeDate);
if (items.length === 0 && !options.allowEmpty) {
throw new Error('未解析到商品推广费,请确认表格已加载且包含「总花费」列');
}
return {
platform: 'pdd',
items,
source: 'browser-extension',
importedAt: new Date().toISOString(),
};
}
}
@@ -0,0 +1,117 @@
import { normalizePddDate } from './parseReport';
import { humanPauseMs, sleep } from './domInteract';
import { switchToSingleDay } from './switchReportDate';
/** 单次自动逐日最多天数(含起止) */
export const MAX_AUTO_COLLECT_DAYS = 31;
export function listDatesInclusive(startIso: string, endIso: string): string[] {
const start = normalizePddDate(startIso) ?? startIso;
const end = normalizePddDate(endIso) ?? endIso;
if (!/^\d{4}-\d{2}-\d{2}$/.test(start) || !/^\d{4}-\d{2}-\d{2}$/.test(end)) {
throw new Error('起止日期格式无效');
}
if (start > end) {
throw new Error('开始日期不能晚于结束日期');
}
const dates: string[] = [];
const cursor = new Date(`${start}T00:00:00`);
const endDate = new Date(`${end}T00:00:00`);
while (cursor <= endDate) {
const y = cursor.getFullYear();
const m = String(cursor.getMonth() + 1).padStart(2, '0');
const d = String(cursor.getDate()).padStart(2, '0');
dates.push(`${y}-${m}-${d}`);
if (dates.length > MAX_AUTO_COLLECT_DAYS) {
throw new Error(`单次最多 ${MAX_AUTO_COLLECT_DAYS} 天,请缩小范围`);
}
cursor.setDate(cursor.getDate() + 1);
}
return dates;
}
export interface AutoCollectProgress {
index: number;
total: number;
date: string;
phase: 'switch' | 'read' | 'pause' | 'done' | 'skip';
message: string;
}
export interface AutoCollectOptions {
startDate: string;
endDate: string;
/** 已累计过的日期,默认跳过 */
skipDates?: Set<string> | string[];
signal?: AbortSignal;
onProgress?: (p: AutoCollectProgress) => void;
/** 切到该日后执行读取;返回是否成功(无数据也可 true) */
readDay: (date: string) => Promise<void>;
}
/**
* 按日拟人切换并读取。日间有随机停顿,避免过快连点。
*/
export async function runAutoCollectByDates(options: AutoCollectOptions): Promise<void> {
const dates = listDatesInclusive(options.startDate, options.endDate);
const skip = new Set(
[...(options.skipDates ?? [])].map((d) => normalizePddDate(d) ?? d),
);
for (let i = 0; i < dates.length; i++) {
if (options.signal?.aborted) {
throw new DOMException('已取消自动读取', 'AbortError');
}
const date = dates[i]!;
if (skip.has(date)) {
options.onProgress?.({
index: i + 1,
total: dates.length,
date,
phase: 'skip',
message: `跳过已读 ${date}(${i + 1}/${dates.length})`,
});
continue;
}
options.onProgress?.({
index: i + 1,
total: dates.length,
date,
phase: 'switch',
message: `切换日期 ${date}(${i + 1}/${dates.length})…`,
});
await switchToSingleDay(date, { signal: options.signal });
options.onProgress?.({
index: i + 1,
total: dates.length,
date,
phase: 'read',
message: `读取 ${date}(${i + 1}/${dates.length})…`,
});
await options.readDay(date);
if (i < dates.length - 1) {
const pause = humanPauseMs('betweenDays');
options.onProgress?.({
index: i + 1,
total: dates.length,
date,
phase: 'pause',
message: `已读 ${date},停顿 ${(pause / 1000).toFixed(1)}s 后继续…`,
});
await sleep(pause);
}
}
options.onProgress?.({
index: dates.length,
total: dates.length,
date: dates[dates.length - 1] ?? '',
phase: 'done',
message: `自动读取完成(${dates.length} 天)`,
});
}
@@ -0,0 +1,41 @@
/** 轻量 DOM 拟人点击(供分页、切日期等复用) */
export function sleep(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}
/** 均匀随机整数 [min, max] */
export function randomInt(min: number, max: number): number {
const lo = Math.ceil(min);
const hi = Math.floor(max);
return Math.floor(Math.random() * (hi - lo + 1)) + lo;
}
export function dispatchMouse(el: HTMLElement, type: string): void {
el.dispatchEvent(
new MouseEvent(type, {
bubbles: true,
cancelable: true,
view: window,
buttons: 1,
}),
);
}
/** Ant Design 控件开合依赖 mousedown,单用 click() 常无效 */
export function pointerClick(el: HTMLElement): void {
el.scrollIntoView({ block: 'center', inline: 'nearest' });
dispatchMouse(el, 'pointerdown');
dispatchMouse(el, 'mousedown');
dispatchMouse(el, 'pointerup');
dispatchMouse(el, 'mouseup');
dispatchMouse(el, 'click');
}
/** 操作间隔:略留余量等 UI/拉数,不再刻意拖慢 */
export function humanPauseMs(kind: 'betweenDays' | 'afterUi' | 'afterNav' = 'betweenDays'): number {
if (kind === 'afterUi') return randomInt(80, 180);
if (kind === 'afterNav') return randomInt(400, 800);
// 日与日之间:约 0.6s~1.2s
return randomInt(600, 1200);
}
@@ -0,0 +1,212 @@
import { PDD_SELECTORS } from './selectors';
const TARGET_PAGE_SIZE = 100;
function sleep(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}
function dispatchMouse(el: HTMLElement, type: string): void {
el.dispatchEvent(
new MouseEvent(type, {
bubbles: true,
cancelable: true,
view: window,
buttons: 1,
}),
);
}
/** Ant Design Select 开合依赖 mousedown,单用 click() 首次常打不开 */
function pointerClick(el: HTMLElement): void {
dispatchMouse(el, 'pointerdown');
dispatchMouse(el, 'mousedown');
dispatchMouse(el, 'pointerup');
dispatchMouse(el, 'mouseup');
dispatchMouse(el, 'click');
}
function findPageSizeSelect(doc: Document = document): HTMLElement | null {
const wrap =
doc.querySelector(PDD_SELECTORS.overviewTable) ??
doc.querySelector(PDD_SELECTORS.paginationWrap) ??
doc;
const perPage = wrap.querySelector(PDD_SELECTORS.perPageText);
const li = perPage?.closest('li') ?? wrap.querySelector('.anq-pagination-total-text');
const select =
(li?.querySelector(PDD_SELECTORS.pageSizeSelect) as HTMLElement | null) ??
(wrap.querySelector(
`${PDD_SELECTORS.paginationWrap} ${PDD_SELECTORS.pageSizeSelect}`,
) as HTMLElement | null);
return select;
}
function readCurrentPageSize(select: Element): number | undefined {
const item = select.querySelector(PDD_SELECTORS.pageSizeValue);
const raw = (item?.getAttribute('title') || item?.textContent || '').trim();
const value = Number(raw.replace(/[^\d]/g, ''));
return Number.isFinite(value) && value > 0 ? value : undefined;
}
function getCombobox(select: Element): HTMLInputElement | null {
return select.querySelector('input[role="combobox"], .anq-select-selection-search-input');
}
function isSelectOpen(select: Element): boolean {
return getCombobox(select)?.getAttribute('aria-expanded') === 'true';
}
/** 仅认「当前可见」的下拉,避免点到手动操作后残留的 hidden dropdown */
function findVisibleDropdown(doc: Document = document): HTMLElement | null {
const dropdowns = Array.from(doc.querySelectorAll('.anq-select-dropdown'));
for (const el of dropdowns) {
if (el.classList.contains('anq-select-dropdown-hidden')) continue;
const style = window.getComputedStyle(el);
if (style.display === 'none' || style.visibility === 'hidden') continue;
if (style.pointerEvents === 'none') continue;
return el as HTMLElement;
}
return null;
}
function isTargetOption(el: Element, target: number): boolean {
const title = (el.getAttribute('title') || '').trim();
const text = (el.textContent || '').replace(/\s+/g, ' ').trim();
if (title === String(target)) return true;
if (text === String(target)) return true;
if (text === `${target}条` || text === `${target} 条`) return true;
return false;
}
function findOptionIn(root: ParentNode, target: number): HTMLElement | null {
const candidates = root.querySelectorAll(
[
'.anq-select-item-option',
'[class*="select-item-option"]',
'[role="option"]',
].join(','),
);
for (const el of candidates) {
if (el.classList.contains('anq-select-item-option-disabled')) continue;
if (isTargetOption(el, target)) return el as HTMLElement;
}
return null;
}
async function waitForVisibleOption(
target: number,
timeoutMs: number,
doc: Document,
): Promise<HTMLElement | null> {
const started = Date.now();
while (Date.now() - started < timeoutMs) {
const dropdown = findVisibleDropdown(doc);
if (dropdown) {
const option = findOptionIn(dropdown, target);
if (option) return option;
}
await sleep(80);
}
return null;
}
async function waitUntilPageSize(
select: Element,
target: number,
timeoutMs = 4000,
): Promise<boolean> {
const started = Date.now();
while (Date.now() - started < timeoutMs) {
if (readCurrentPageSize(select) === target) return true;
await sleep(100);
}
return readCurrentPageSize(select) === target;
}
async function openPageSizeSelect(select: HTMLElement, doc: Document): Promise<boolean> {
const trigger =
(select.querySelector('.anq-select-selector') as HTMLElement | null) ?? select;
const input = getCombobox(select);
trigger.scrollIntoView({ block: 'center', inline: 'nearest' });
await sleep(50);
input?.focus({ preventScroll: true });
// 已打开则先关掉,保证重新挂载可见下拉(避免点到残留 hidden 节点)
if (isSelectOpen(select) || findVisibleDropdown(doc)) {
doc.body.dispatchEvent(
new KeyboardEvent('keydown', { key: 'Escape', bubbles: true, cancelable: true }),
);
await sleep(120);
}
pointerClick(trigger);
const started = Date.now();
while (Date.now() - started < 1500) {
if (isSelectOpen(select) && findVisibleDropdown(doc)) return true;
await sleep(80);
}
// 再试一次:部分 antd 版本首次 mousedown 被挡
pointerClick(trigger);
const retryStart = Date.now();
while (Date.now() - retryStart < 1500) {
if (isSelectOpen(select) && findVisibleDropdown(doc)) return true;
await sleep(80);
}
return Boolean(isSelectOpen(select) && findVisibleDropdown(doc));
}
/**
* 将推广商品表分页「每页」自动切到 100(若已是 100 则跳过)。
*
* 注意:首次进入页面时下拉选项不在 DOM;手动切换过后,antd 常把
* `.anq-select-dropdown-hidden` 残留在 body。若只搜全局 option,
* 会点到不可见节点「看似成功」或首次完全失败。因此必须:
* 1) 用 mousedown 序列真正打开 Select
* 2) 只点击「可见」dropdown 内的 100
*/
export async function ensurePageSize100(doc: Document = document): Promise<{
changed: boolean;
pageSize?: number;
}> {
const select = findPageSizeSelect(doc);
if (!select) {
return { changed: false };
}
const current = readCurrentPageSize(select);
if (current === TARGET_PAGE_SIZE) {
return { changed: false, pageSize: current };
}
const opened = await openPageSizeSelect(select, doc);
if (!opened) {
doc.body.dispatchEvent(
new KeyboardEvent('keydown', { key: 'Escape', bubbles: true, cancelable: true }),
);
throw new Error(
`未能打开每页条数下拉(当前 ${current ?? '未知'})。请先滚动到表格底部分页区后重试`,
);
}
const option = await waitForVisibleOption(TARGET_PAGE_SIZE, 2500, doc);
if (!option) {
doc.body.dispatchEvent(
new KeyboardEvent('keydown', { key: 'Escape', bubbles: true, cancelable: true }),
);
throw new Error(
`下拉已打开但未找到 ${TARGET_PAGE_SIZE} 选项,请确认分页支持该页大小`,
);
}
pointerClick(option);
const ok = await waitUntilPageSize(select, TARGET_PAGE_SIZE);
if (!ok) {
throw new Error(`切换每页 ${TARGET_PAGE_SIZE} 未生效,请手动切换后重试`);
}
await sleep(900);
return { changed: true, pageSize: TARGET_PAGE_SIZE };
}
@@ -0,0 +1,19 @@
import type { PddChannelShop } from '@/api/open/pddShop';
import { matchPddChannelShopByMallName } from '@/api/open/pddShop';
/**
* 用页面店铺名匹配 BI channelShop:后端按 mallName trim 后精确匹配。
*/
export async function matchChannelShopByMallName(
mallName: string,
): Promise<PddChannelShop | null> {
const name = mallName.trim();
if (!name) return null;
const shop = await matchPddChannelShopByMallName(name);
return shop ?? null;
}
export function shopAuthorizeHint(mallName: string): string {
const name = mallName.trim() || '当前店铺';
return `未在系统中找到与「${name}」完全同名的授权店铺,请先到 BI 系统完成该店铺授权后再试`;
}
@@ -0,0 +1,165 @@
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;
}
/** 优先主 RangePicker 显示值(页面真实选中),URL 仅作回退。
* 勿只信 URL:history.pushState 改地址栏不会驱动 React 重拉数据。 */
export function readReportDate(doc: Document = document, href = location.href): PddReportDateInfo {
const fromPicker = readDateFromMainPicker(doc);
if (fromPicker) return fromPicker;
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
}
return { mode: 'unknown', message: '未能识别报表日期,请确认已打开商品推广总览且选择了日期' };
}
/** 读取 DateArea 主日期选择器(跳过对比日期) */
export function readDateFromMainPicker(doc: Document = document): PddReportDateInfo | null {
const pickers = Array.from(doc.querySelectorAll(PDD_SELECTORS.rangePicker));
for (const picker of pickers) {
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 null;
}
/**
* 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);
// 总花费为 0 / 空 不记录
if (feeAmount == null || feeAmount <= 0) continue;
seen.add(goodsId);
items.push({
feeDate,
goodsId,
feeAmount,
metadata: {
goodsName: row
.querySelector('[class*="OverviewTable_goodsName"]')
?.getAttribute('title')
?.replace(/^商品名:/, ''),
},
});
}
return items.sort((a, b) => Number(b.feeAmount) - Number(a.feeAmount));
}
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,23 @@
/** 拼多多推广报表 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',
/** 分页「每页」 */
paginationWrap: '[class*="OverviewTable_paginationWrap"], .anq-pagination-wrapper',
perPageText: '.anq-perpage-text',
pageSizeSelect: '.anq-select',
pageSizeValue: '.anq-select-selection-item',
} 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})/;
@@ -0,0 +1,272 @@
import { normalizePddDate, readDateFromMainPicker, readReportDate } from './parseReport';
import { PDD_SELECTORS } from './selectors';
import { humanPauseMs, pointerClick, sleep } from './domInteract';
const MAX_WAIT_MS = 15_000;
function throwIfAborted(signal?: AbortSignal): void {
if (signal?.aborted) {
throw new DOMException('已取消自动切换日期', 'AbortError');
}
}
function findMainRangePicker(doc: Document = document): HTMLElement | null {
const pickers = Array.from(doc.querySelectorAll(PDD_SELECTORS.rangePicker));
for (const picker of pickers) {
if (picker.closest('[class*="CompareDate"]')) continue;
if (picker.closest('[class*="DateArea"]')) return picker as HTMLElement;
}
for (const picker of pickers) {
if (picker.closest('[class*="CompareDate"]')) continue;
return picker as HTMLElement;
}
return null;
}
function findVisiblePickerDropdown(doc: Document = document): HTMLElement | null {
const dropdowns = Array.from(
doc.querySelectorAll('.anq-picker-dropdown, [class*="picker-dropdown"]'),
);
for (const el of dropdowns) {
if (el.classList.contains('anq-picker-dropdown-hidden')) continue;
const style = window.getComputedStyle(el);
if (style.display === 'none' || style.visibility === 'hidden') continue;
if (style.pointerEvents === 'none') continue;
// 排除完全不可见
const rect = el.getBoundingClientRect();
if (rect.width < 2 || rect.height < 2) continue;
return el as HTMLElement;
}
return null;
}
function closePicker(doc: Document = document): void {
doc.body.dispatchEvent(
new KeyboardEvent('keydown', { key: 'Escape', bubbles: true, cancelable: true }),
);
}
async function openRangePicker(doc: Document, signal?: AbortSignal): Promise<HTMLElement> {
const picker = findMainRangePicker(doc);
if (!picker) throw new Error('未找到日期范围选择器');
// 先关掉残留面板,避免点到 hidden 节点
if (findVisiblePickerDropdown(doc)) {
closePicker(doc);
await sleep(180);
}
const triggers: HTMLElement[] = [];
const startInput = picker.querySelector(
'.anq-picker-input input, .anq-picker-input-active input',
) as HTMLElement | null;
const anyInput = picker.querySelector('input') as HTMLElement | null;
const suffix = picker.querySelector('.anq-picker-suffix') as HTMLElement | null;
if (startInput) triggers.push(startInput);
if (anyInput && anyInput !== startInput) triggers.push(anyInput);
if (suffix) triggers.push(suffix);
triggers.push(picker);
for (const trigger of triggers) {
throwIfAborted(signal);
pointerClick(trigger);
// 部分环境还吃原生 click
try {
trigger.click();
} catch {
// ignore
}
await sleep(humanPauseMs('afterUi'));
const started = Date.now();
while (Date.now() - started < 1800) {
throwIfAborted(signal);
const dropdown = findVisiblePickerDropdown(doc);
if (dropdown) return dropdown;
await sleep(80);
}
}
throw new Error('未能打开日期面板,请手动点开日期选择器后再试自动读取');
}
function titleCandidates(isoDate: string): string[] {
const [y, m, d] = isoDate.split('-');
if (!y || !m || !d) return [isoDate];
return [
isoDate,
`${y}/${m}/${d}`,
`${y}/${Number(m)}/${Number(d)}`,
`${y}-${Number(m)}-${Number(d)}`,
];
}
function findDateCell(dropdown: HTMLElement, isoDate: string): HTMLElement | null {
for (const title of titleCandidates(isoDate)) {
const cells = Array.from(
dropdown.querySelectorAll(`.anq-picker-cell[title="${title}"], td[title="${title}"]`),
) as HTMLElement[];
const preferred =
cells.find(
(el) =>
el.classList.contains('anq-picker-cell-in-view') &&
!el.classList.contains('anq-picker-cell-disabled'),
) ??
cells.find((el) => !el.classList.contains('anq-picker-cell-disabled')) ??
null;
if (preferred) {
return (
(preferred.querySelector('.anq-picker-cell-inner') as HTMLElement | null) ?? preferred
);
}
}
return null;
}
function parseHeaderYearMonth(dropdown: HTMLElement): { y: number; m: number } | null {
const headers = Array.from(
dropdown.querySelectorAll('.anq-picker-header-view, [class*="picker-header-view"]'),
);
// Range 常左右两个月面板,取第一个可见头
for (const header of headers) {
const text = (header.textContent || '').replace(/\s+/g, '');
let m = text.match(/(\d{4})\s*年\s*(\d{1,2})\s*月/);
if (m) return { y: Number(m[1]), m: Number(m[2]) };
m = text.match(/(\d{4})[/.-](\d{1,2})/);
if (m) return { y: Number(m[1]), m: Number(m[2]) };
}
return null;
}
async function navigateToMonth(
dropdown: HTMLElement,
isoDate: string,
signal?: AbortSignal,
): Promise<void> {
const [ys, ms] = isoDate.split('-');
const targetY = Number(ys);
const targetM = Number(ms);
if (!targetY || !targetM) throw new Error(`非法日期:${isoDate}`);
for (let i = 0; i < 36; i++) {
throwIfAborted(signal);
if (findDateCell(dropdown, isoDate)) return;
const current = parseHeaderYearMonth(dropdown);
if (!current) break;
const curIdx = current.y * 12 + current.m;
const tgtIdx = targetY * 12 + targetM;
if (curIdx === tgtIdx) {
// 头已对齐但仍找不到 cell — 可能 title 格式不同
break;
}
const wantNext = curIdx < tgtIdx;
const buttons = Array.from(
dropdown.querySelectorAll(
wantNext
? '.anq-picker-header-next-btn'
: '.anq-picker-header-prev-btn',
),
) as HTMLElement[];
// 双月面板时点左侧(第一个)的 prev/next
const btn = buttons[0];
if (!btn) break;
pointerClick(btn);
await sleep(humanPauseMs('afterUi'));
}
if (!findDateCell(dropdown, isoDate)) {
throw new Error(`日期面板中找不到 ${isoDate},请确认未超出可选范围`);
}
}
/** 以选择器输入值为准,确认已切到目标单日(不认仅改 URL) */
async function waitUntilPickerSingleDay(
isoDate: string,
signal?: AbortSignal,
): Promise<void> {
const started = Date.now();
while (Date.now() - started < MAX_WAIT_MS) {
throwIfAborted(signal);
const picker = readDateFromMainPicker();
if (picker?.mode === 'single' && picker.feeDate === isoDate) return;
await sleep(200);
}
const picker = readDateFromMainPicker();
const fallback = readReportDate();
throw new Error(
`切换到 ${isoDate} 超时(选择器:${picker?.mode ?? '无'} ${picker?.feeDate ?? picker?.beginDate ?? '?'};页面:${fallback.feeDate ?? '?'})`,
);
}
async function clickCellTwiceForSingleDay(
dropdown: HTMLElement,
isoDate: string,
doc: Document,
signal?: AbortSignal,
): Promise<void> {
const cell = findDateCell(dropdown, isoDate);
if (!cell) throw new Error(`未找到日期单元格 ${isoDate}`);
// RangePicker:起、止各点同一天
pointerClick(cell);
try {
cell.click();
} catch {
// ignore
}
await sleep(humanPauseMs('afterUi'));
throwIfAborted(signal);
const dropdown2 = findVisiblePickerDropdown(doc);
if (dropdown2) {
const cell2 = findDateCell(dropdown2, isoDate);
if (cell2) {
pointerClick(cell2);
try {
cell2.click();
} catch {
// ignore
}
await sleep(humanPauseMs('afterUi'));
}
}
}
/**
* 将推广总览切到指定单日。
* 只通过 DateArea RangePicker 拟人点击;禁止 pushState 假切换。
*/
export async function switchToSingleDay(
isoDate: string,
options: { signal?: AbortSignal; doc?: Document } = {},
): Promise<void> {
const date = normalizePddDate(isoDate) ?? isoDate;
if (!/^\d{4}-\d{2}-\d{2}$/.test(date)) {
throw new Error(`日期格式无效:${isoDate}`);
}
const { signal, doc = document } = options;
throwIfAborted(signal);
const current = readDateFromMainPicker(doc) ?? readReportDate(doc);
if (current.mode === 'single' && current.feeDate === date) {
return;
}
const dropdown = await openRangePicker(doc, signal);
await navigateToMonth(dropdown, date, signal);
await clickCellTwiceForSingleDay(dropdown, date, doc, signal);
// 若面板仍开着,再 Esc(有的版本选完自动关)
if (findVisiblePickerDropdown(doc)) {
closePicker(doc);
await sleep(200);
}
await waitUntilPickerSingleDay(date, signal);
// 等报表按新日期拉数
await sleep(humanPauseMs('afterNav'));
}