feat: 增加自动选最大页码功能

This commit is contained in:
2026-08-16 18:00:26 +08:00
parent 3c0dfc2f77
commit 8a8e36602f
9 changed files with 393 additions and 102 deletions
@@ -1,6 +1,7 @@
import type { PlatformAdapter } from '@/platform/core/PlatformAdapter';
import type { AdvertisingCostBatch, PageContext } from '@/types/advertisingCost';
import { ensurePageSize100 } from './ensurePageSize';
import {
isPddPromotionOverviewUrl,
parsePromotionItems,
@@ -56,6 +57,9 @@ export class PddPlatformAdapter implements PlatformAdapter {
throw new Error(dateInfo.message ?? '未能识别单日报表日期');
}
// 读取前把「每页」自动切到 100,减少分页漏读
await ensurePageSize100();
const items = parsePromotionItems(dateInfo.feeDate);
if (items.length === 0) {
throw new Error('未解析到商品推广费,请确认表格已加载且包含「总花费」列');
@@ -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 };
}
@@ -9,6 +9,11 @@ export const PDD_SELECTORS = {
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;
/** 推广费列名:取「总花费(元)」 */