mirror of
https://gitee.com/qqtt-ah/ecom-dmb.git
synced 2026-11-23 23:19:19 +08:00
273 lines
8.3 KiB
TypeScript
273 lines
8.3 KiB
TypeScript
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'));
|
||
}
|