mirror of
https://gitee.com/qqtt-ah/ecom-dmb.git
synced 2026-11-24 21:09:19 +08:00
feat: 优化拼多多浮窗
This commit is contained in:
@@ -9,5 +9,7 @@ export interface PlatformAdapter {
|
||||
canHandle(url: string): boolean;
|
||||
getPageContext(): Promise<PageContext>;
|
||||
/** 从当前页解析推广费;每条 item 自带 feeDate */
|
||||
parseAdvertisingCost(): Promise<Omit<AdvertisingCostBatch, 'channelShopId'>>;
|
||||
parseAdvertisingCost(
|
||||
options?: { allowEmpty?: boolean },
|
||||
): Promise<Omit<AdvertisingCostBatch, 'channelShopId'>>;
|
||||
}
|
||||
|
||||
@@ -48,7 +48,9 @@ export class PddPlatformAdapter implements PlatformAdapter {
|
||||
};
|
||||
}
|
||||
|
||||
async parseAdvertisingCost(): Promise<Omit<AdvertisingCostBatch, 'channelShopId'>> {
|
||||
async parseAdvertisingCost(
|
||||
options: { allowEmpty?: boolean } = {},
|
||||
): Promise<Omit<AdvertisingCostBatch, 'channelShopId'>> {
|
||||
const dateInfo = readReportDate();
|
||||
if (dateInfo.mode === 'range') {
|
||||
throw new Error(dateInfo.message ?? '范围报表不记录,请切换为单日查看');
|
||||
@@ -61,7 +63,7 @@ export class PddPlatformAdapter implements PlatformAdapter {
|
||||
await ensurePageSize100();
|
||||
|
||||
const items = parsePromotionItems(dateInfo.feeDate);
|
||||
if (items.length === 0) {
|
||||
if (items.length === 0 && !options.allowEmpty) {
|
||||
throw new Error('未解析到商品推广费,请确认表格已加载且包含「总花费」列');
|
||||
}
|
||||
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
@@ -2,8 +2,8 @@ import type { PddChannelShop } from '@/api/open/pddShop';
|
||||
import { listPddChannelShops } from '@/api/open/pddShop';
|
||||
|
||||
/**
|
||||
* 用页面店铺名通过 Open 店铺分页接口匹配 BI channelShop。
|
||||
* 优先精确匹配 mallName,其次仅当筛选结果唯一时采用。
|
||||
* 用页面店铺名匹配 BI channelShop:仅接受 mallName 完全一致。
|
||||
* 接口 filters 可能是模糊搜,结果里再做精确过滤。
|
||||
*/
|
||||
export async function matchChannelShopByMallName(
|
||||
mallName: string,
|
||||
@@ -17,10 +17,11 @@ export async function matchChannelShopByMallName(
|
||||
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;
|
||||
return exact ?? null;
|
||||
}
|
||||
|
||||
export function shopAuthorizeHint(mallName: string): string {
|
||||
const name = mallName.trim() || '当前店铺';
|
||||
return `未在系统中找到与「${name}」完全同名的授权店铺,请先到 BI 系统完成该店铺授权后再试`;
|
||||
}
|
||||
|
||||
@@ -40,8 +40,12 @@ export function readMallName(doc: Document = document): string | undefined {
|
||||
return text || undefined;
|
||||
}
|
||||
|
||||
/** 优先 URL beginDate/endDate,其次主 RangePicker 两个 input */
|
||||
/** 优先主 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);
|
||||
@@ -61,9 +65,13 @@ export function readReportDate(doc: Document = document, href = location.href):
|
||||
// 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) {
|
||||
// 跳过对比日期区(CompareDate 内嵌 picker)
|
||||
if (picker.closest('[class*="CompareDate"]')) continue;
|
||||
const inputs = Array.from(picker.querySelectorAll('input')).slice(0, 2);
|
||||
if (inputs.length < 2) continue;
|
||||
@@ -80,8 +88,7 @@ export function readReportDate(doc: Document = document, href = location.href):
|
||||
message: `当前为范围报表(${begin} ~ ${end}),仅单日查看时才记录`,
|
||||
};
|
||||
}
|
||||
|
||||
return { mode: 'unknown', message: '未能识别报表日期,请确认已打开商品推广总览且选择了日期' };
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -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'));
|
||||
}
|
||||
Reference in New Issue
Block a user