feat: 优化拼多多浮窗

This commit is contained in:
2026-08-16 22:30:05 +08:00
parent c2ad4477fb
commit 12a5f4039f
14 changed files with 991 additions and 185 deletions
+2 -2
View File
@@ -29,9 +29,9 @@ async function main() {
{
id: 'pdd-ad-fee',
name: '拼多多商品推广费同步',
version: '0.2.0',
version: '0.3.9',
description:
'从推广总览读取单日总花费并同步到 BI(MAIN world 远程脚本,更新后端静态资源即可热更新)',
'从推广总览读取推广费并同步到 BI(浮窗滚动条统一 thin)',
matchUrlPatterns: [
'*://yingxiao.pinduoduo.com/*',
'https://yingxiao.pinduoduo.com/',
@@ -2,10 +2,14 @@
import { computed, onMounted, onUnmounted, ref } from 'vue';
import { batchImportPddGoodsAdFee } from '@/api/open/pddGoodsAdFee';
import { listPddChannelShops, type PddChannelShop } from '@/api/open/pddShop';
import DateHeatmap from './DateHeatmap.vue';
import { resolveAdapter } from '@/platform/core/PlatformDetector';
import { matchChannelShopByMallName } from '@/platform/pdd/matchShop';
import {
MAX_AUTO_COLLECT_DAYS,
listDatesInclusive,
runAutoCollectByDates,
} from '@/platform/pdd/autoCollectDates';
import { matchChannelShopByMallName, shopAuthorizeHint } from '@/platform/pdd/matchShop';
import { EXTENSION_NAME } from '@/shared/constants';
import { toUserMessage } from '@/shared/errors';
import { listFeeDates, mergeAdvertisingItems } from '@/shared/mergeItems';
@@ -17,11 +21,11 @@ const emit = defineEmits<{
minimize: [];
}>();
const shops = ref<PddChannelShop[]>([]);
const channelShopId = ref<number | undefined>(undefined);
const channelShopName = ref('');
const pageMallName = ref('');
const shopsLoading = ref(false);
const shopMatching = ref(false);
const shopMatched = ref(false);
const pageContext = ref<PageContext | null>(null);
const batch = ref<AdvertisingCostBatch | null>(null);
@@ -31,6 +35,14 @@ const errorText = ref('');
const syncResultText = ref('');
const busy = ref(false);
const autoStartDate = ref('');
const autoEndDate = ref('');
const autoSkipRead = ref(true);
const autoRunning = ref(false);
let autoAbort: AbortController | null = null;
/** 自动切日期期间禁止 URL 轮询触发二次读取 */
let suppressUrlAutoRead = false;
const panelRef = ref<HTMLElement | null>(null);
const position = ref({ top: 72, left: Math.max(24, window.innerWidth - 400) });
let dragOffset = { x: 0, y: 0 };
@@ -39,6 +51,29 @@ let readTimer: ReturnType<typeof setTimeout> | null = null;
let urlPollTimer: ReturnType<typeof setInterval> | null = null;
let lastHref = typeof location !== 'undefined' ? location.href : '';
function todayIso(): string {
const now = new Date();
const y = now.getFullYear();
const m = String(now.getMonth() + 1).padStart(2, '0');
const d = String(now.getDate()).padStart(2, '0');
return `${y}-${m}-${d}`;
}
function shiftIso(iso: string, deltaDays: number): string {
const dt = new Date(`${iso}T00:00:00`);
dt.setDate(dt.getDate() + deltaDays);
const y = dt.getFullYear();
const m = String(dt.getMonth() + 1).padStart(2, '0');
const d = String(dt.getDate()).padStart(2, '0');
return `${y}-${m}-${d}`;
}
function initAutoDateRange(preferredEnd?: string) {
const end = preferredEnd && /^\d{4}-\d{2}-\d{2}$/.test(preferredEnd) ? preferredEnd : todayIso();
autoEndDate.value = end;
autoStartDate.value = shiftIso(end, -(Math.min(6, MAX_AUTO_COLLECT_DAYS - 1)));
}
const totalFee = computed(() =>
(batch.value?.items ?? []).reduce((sum, item) => sum + Number(item.feeAmount || 0), 0),
);
@@ -52,12 +87,6 @@ const previewItems = computed(() => {
const previewFee = computed(() =>
previewItems.value.reduce((sum, item) => sum + Number(item.feeAmount || 0), 0),
);
const selectedShopLabel = computed(() => {
if (channelShopId.value == null) return '未选择渠道店';
return channelShopName.value
? `${channelShopName.value} (#${channelShopId.value})`
: `#${channelShopId.value}`;
});
const dateModeLabel = computed(() => {
const mode = pageContext.value?.dateMode;
if (mode === 'single') return `单日 ${pageContext.value?.feeDate ?? ''}`;
@@ -72,6 +101,27 @@ const previewLabel = computed(() => {
if (!filterDate.value) return '全部已读';
return filterDate.value;
});
const autoDaySpanLabel = computed(() => {
try {
if (!autoStartDate.value || !autoEndDate.value) return `最多 ${MAX_AUTO_COLLECT_DAYS} 天`;
const n = listDatesInclusive(autoStartDate.value, autoEndDate.value).length;
return `${n} 天(上限 ${MAX_AUTO_COLLECT_DAYS})`;
} catch (error) {
return error instanceof Error ? error.message : '日期无效';
}
});
const shopStatusLabel = computed(() => {
if (shopMatching.value) return '匹配中';
if (shopMatched.value && channelShopId.value != null) return '已授权';
if (pageMallName.value.trim()) return '未授权,请到 BI 系统授权同名店铺';
return '未识别店铺';
});
const headerShopLine = computed(() => {
const name = pageMallName.value.trim() || '未识别店铺';
return `${name} · ${shopStatusLabel.value}`;
});
function onHeatSelect(date: string | undefined) {
filterDate.value = date;
@@ -91,6 +141,11 @@ async function loadLocalSettings() {
const settings = await getSettings();
channelShopId.value = settings.channelShopId;
channelShopName.value = settings.channelShopName ?? '';
// 缓存仅作提示;真正读写前会按页面店名再精确校验
shopMatched.value =
channelShopId.value != null &&
Boolean(channelShopName.value) &&
channelShopName.value.trim() === (pageMallName.value || channelShopName.value).trim();
}
async function persistShop() {
@@ -100,111 +155,117 @@ async function persistShop() {
});
}
async function loadShops() {
shopsLoading.value = true;
errorText.value = '';
try {
const result = await listPddChannelShops({ page: 1, pageSize: 100 });
shops.value = result.records ?? [];
if (channelShopId.value != null) {
const hit = shops.value.find((s) => s.id === channelShopId.value);
if (hit) channelShopName.value = hit.mallName ?? '';
}
} catch (error) {
errorText.value = toUserMessage(error);
} finally {
shopsLoading.value = false;
}
async function clearMatchedShop() {
channelShopId.value = undefined;
channelShopName.value = '';
shopMatched.value = false;
await persistShop();
}
/** 用页面店铺名自动匹配 BI 渠道店 */
async function autoMatchShopFromPage(): Promise<boolean> {
/** 仅按页面店铺名完全匹配;失败时提示去系统授权 */
async function matchShopFromPage(options: { quiet?: boolean } = {}): Promise<boolean> {
await refreshContext();
const mallName = pageMallName.value.trim();
if (!mallName) return false;
if (!mallName) {
await clearMatchedShop();
if (!options.quiet) {
errorText.value = '未识别到页面店铺名,请确认已打开推广总览';
statusText.value = '无法匹配店铺';
}
return false;
}
// 已与当前页店名精确对应则复用
if (
channelShopId.value != null &&
channelShopName.value.trim() === mallName
) {
shopMatched.value = true;
return true;
}
shopMatching.value = true;
if (!options.quiet) errorText.value = '';
try {
const matched = await matchChannelShopByMallName(mallName);
if (!matched) {
statusText.value = `未匹配到店铺「${mallName}」,请手动选择或拉取列表`;
await clearMatchedShop();
const hint = shopAuthorizeHint(mallName);
errorText.value = hint;
statusText.value = '店铺未授权';
return false;
}
channelShopId.value = matched.id;
channelShopName.value = matched.mallName ?? mallName;
if (!shops.value.some((s) => s.id === matched.id)) {
shops.value = [matched, ...shops.value];
}
shopMatched.value = true;
await persistShop();
statusText.value = `已按页面店铺匹配:${channelShopName.value}`;
statusText.value = `已匹配授权店铺:${channelShopName.value}`;
return true;
} catch (error) {
await clearMatchedShop();
errorText.value = toUserMessage(error);
statusText.value = '店铺自动匹配失败';
statusText.value = '店铺匹配失败';
return false;
} finally {
shopMatching.value = false;
}
}
function onShopChange(event: Event) {
const value = Number((event.target as HTMLSelectElement).value);
if (!Number.isFinite(value) || value <= 0) {
channelShopId.value = undefined;
channelShopName.value = '';
void persistShop();
return;
async function ensureChannelShop(): Promise<void> {
const ok = await matchShopFromPage();
if (!ok || channelShopId.value == null) {
const mallName = pageMallName.value.trim();
throw new Error(
mallName ? shopAuthorizeHint(mallName) : '未识别到页面店铺名,请确认已打开推广总览',
);
}
channelShopId.value = value;
const hit = shops.value.find((s) => s.id === value);
channelShopName.value = hit?.mallName ?? '';
void persistShop();
scheduleAutoRead();
}
async function handleRead(fromAuto = false) {
async function handleRead(fromAuto = false, allowEmpty = false) {
busy.value = true;
errorText.value = '';
syncResultText.value = '';
statusText.value = fromAuto ? '自动读取中…' : '正在读取…';
statusText.value = fromAuto ? '自动读取中…' : '正在读取…';
try {
await refreshContext();
if (pageContext.value?.dateMode === 'range') {
// 范围视图不追加,但保留已累计的多日数据
statusText.value = '范围视图不追加;已累计数据仍保留';
errorText.value = pageContext.value.message ?? '请切回单日后再读取';
return;
}
if (channelShopId.value == null) {
const matched = await autoMatchShopFromPage();
if (!matched || channelShopId.value == null) {
throw new Error('请先选择 BI 渠道店铺(页面店铺名可自动匹配)');
}
}
await ensureChannelShop();
statusText.value = '检查分页(每页 100)…';
const adapter = resolveAdapter(location.href);
const parsed = await adapter.parseAdvertisingCost();
const mergedItems = mergeAdvertisingItems(batch.value?.items ?? [], parsed.items);
const incomingDate = parsed.items[0]?.feeDate;
const parsed = await adapter.parseAdvertisingCost({ allowEmpty });
const incomingDate = parsed.items[0]?.feeDate ?? pageContext.value?.feeDate;
const addedOrUpdated = parsed.items.length;
batch.value = {
platform: parsed.platform,
channelShopId: channelShopId.value,
items: mergedItems,
source: 'browser-extension',
importedAt: new Date().toISOString(),
};
if (incomingDate) {
filterDate.value = incomingDate;
if (parsed.items.length > 0) {
batch.value = {
platform: parsed.platform,
channelShopId: channelShopId.value!,
items: mergeAdvertisingItems(batch.value?.items ?? [], parsed.items),
source: 'browser-extension',
importedAt: new Date().toISOString(),
};
if (incomingDate) filterDate.value = incomingDate;
}
await refreshContext();
const tag = parsed.platform === 'mock' ? 'Mock' : '页面';
if (addedOrUpdated === 0) {
statusText.value = incomingDate
? `${incomingDate} 无推广费数据(已跳过)· 累计 ${dateCount.value} 天`
: '当日无推广费数据';
return;
}
statusText.value = incomingDate
? `已合并 ${incomingDate}(${addedOrUpdated} 条,${tag})· 累计 ${dateCount.value} 天`
: `已读取(${tag})`;
} catch (error) {
// 读取失败不清空已累计数据
statusText.value = '读取失败';
errorText.value = toUserMessage(error);
} finally {
@@ -221,17 +282,23 @@ function clearAccumulated() {
}
function scheduleAutoRead(delayMs = 450) {
if (suppressUrlAutoRead || autoRunning.value) return;
if (readTimer) clearTimeout(readTimer);
readTimer = setTimeout(() => {
void handleRead(true);
void handleRead(true).catch(() => {
// 错误已写入 errorText
});
}, delayMs);
}
async function onPageUrlChanged() {
if (suppressUrlAutoRead || autoRunning.value) {
await refreshContext();
return;
}
await refreshContext();
if (pageContext.value?.dateMode === 'single') {
errorText.value = '';
// 等报表表格随 URL 刷新后再读
scheduleAutoRead(1200);
return;
}
@@ -240,23 +307,91 @@ async function onPageUrlChanged() {
}
}
async function handleAutoCollect() {
if (autoRunning.value) return;
errorText.value = '';
syncResultText.value = '';
try {
listDatesInclusive(autoStartDate.value, autoEndDate.value);
} catch (error) {
errorText.value = toUserMessage(error);
return;
}
autoAbort = new AbortController();
autoRunning.value = true;
suppressUrlAutoRead = true;
busy.value = true;
if (readTimer) {
clearTimeout(readTimer);
readTimer = null;
}
try {
await ensureChannelShop();
await runAutoCollectByDates({
startDate: autoStartDate.value,
endDate: autoEndDate.value,
skipDates: autoSkipRead.value ? listFeeDates(batch.value?.items ?? []) : [],
signal: autoAbort.signal,
onProgress: (p) => {
statusText.value = p.message;
},
readDay: async () => {
await refreshContext();
await ensureChannelShop();
const adapter = resolveAdapter(location.href);
const parsed = await adapter.parseAdvertisingCost({ allowEmpty: true });
const incomingDate = parsed.items[0]?.feeDate ?? pageContext.value?.feeDate;
if (parsed.items.length > 0) {
batch.value = {
platform: parsed.platform,
channelShopId: channelShopId.value!,
items: mergeAdvertisingItems(batch.value?.items ?? [], parsed.items),
source: 'browser-extension',
importedAt: new Date().toISOString(),
};
if (incomingDate) filterDate.value = incomingDate;
}
await refreshContext();
lastHref = location.href;
},
});
statusText.value = `自动读取完成 · 累计 ${dateCount.value} 天 ${itemCount.value} 条`;
} catch (error) {
if (error instanceof DOMException && error.name === 'AbortError') {
statusText.value = `已停止自动读取 · 累计 ${dateCount.value} 天`;
} else {
statusText.value = '自动读取中断';
errorText.value = toUserMessage(error);
}
} finally {
autoRunning.value = false;
suppressUrlAutoRead = false;
busy.value = false;
autoAbort = null;
lastHref = location.href;
}
}
function stopAutoCollect() {
autoAbort?.abort();
}
async function handleSync() {
if (!batch.value) {
errorText.value = '请先读取数据';
return;
}
if (channelShopId.value == null) {
errorText.value = '请先选择 BI 渠道店铺';
return;
}
busy.value = true;
errorText.value = '';
syncResultText.value = '';
statusText.value = '正在同步…';
try {
await ensureChannelShop();
const payload: AdvertisingCostBatch = {
...batch.value,
channelShopId: channelShopId.value,
channelShopId: channelShopId.value!,
};
const result = await batchImportPddGoodsAdFee(payload);
statusText.value = '同步完成';
@@ -303,12 +438,16 @@ function onHeaderPointerUp(event: PointerEvent) {
onMounted(async () => {
await loadLocalSettings();
await refreshContext();
const matched = await autoMatchShopFromPage();
initAutoDateRange(pageContext.value?.feeDate);
const matched = await matchShopFromPage({ quiet: true });
if (pageContext.value?.dateMode === 'range') {
statusText.value = '范围视图不追加;请切到单日逐日读取并累计';
errorText.value = pageContext.value.message ?? '';
} else if (matched || channelShopId.value != null) {
} else if (matched) {
scheduleAutoRead();
} else if (pageMallName.value.trim()) {
errorText.value = shopAuthorizeHint(pageMallName.value);
statusText.value = '店铺未授权';
}
lastHref = location.href;
@@ -320,6 +459,7 @@ onMounted(async () => {
});
onUnmounted(() => {
autoAbort?.abort();
if (readTimer) clearTimeout(readTimer);
if (urlPollTimer) clearInterval(urlPollTimer);
});
@@ -338,11 +478,30 @@ onUnmounted(() => {
@pointerup="onHeaderPointerUp"
@pointercancel="onHeaderPointerUp"
>
<div>
<div class="ecbi-header-main">
<h1>{{ EXTENSION_NAME }}</h1>
<p>页内悬浮 · 单日累计多日</p>
<p
class="ecbi-header-sub"
:class="{
'ecbi-header-sub-warn': !shopMatched && Boolean(pageMallName.trim()) && !shopMatching,
}"
:title="headerShopLine"
>
{{ headerShopLine }}
</p>
<p class="ecbi-header-stats">{{ accumulatedLabel }}</p>
</div>
<div class="ecbi-header-actions">
<button
class="ecbi-header-link"
type="button"
title="按页面店名重新精确匹配"
:disabled="shopMatching || busy || autoRunning"
@pointerdown.stop
@click="matchShopFromPage()"
>
{{ shopMatching ? '…' : '匹配' }}
</button>
<button class="ecbi-icon-btn" type="button" title="收起" @click="emit('minimize')">
–
</button>
@@ -353,26 +512,14 @@ onUnmounted(() => {
</header>
<div class="ecbi-body">
<div class="ecbi-row">
<span class="ecbi-label">平台</span>
<span>{{ pageContext?.platform ?? '未识别' }}</span>
</div>
<div class="ecbi-row">
<span class="ecbi-label">页面店铺</span>
<span class="ecbi-muted" style="max-width: 220px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap">
{{ pageMallName || '—' }}
</span>
</div>
<div class="ecbi-row">
<span class="ecbi-label">当前视图</span>
<div class="ecbi-meta">
<span>{{ dateModeLabel }}</span>
</div>
<div class="ecbi-row">
<span class="ecbi-label">已累计</span>
<span>{{ accumulatedLabel }}</span>
<span class="ecbi-meta-sep">·</span>
<span class="ecbi-fee">¥{{ totalFee.toFixed(2) }}</span>
<span class="ecbi-muted">/ {{ itemCount }} 条</span>
</div>
<section class="ecbi-card">
<section class="ecbi-card ecbi-card-tight">
<DateHeatmap
:items="batch?.items ?? []"
:page-date="pageContext?.feeDate"
@@ -380,84 +527,102 @@ onUnmounted(() => {
@select="onHeatSelect"
/>
<div v-if="filterDate" class="ecbi-heat-filter">
<span class="ecbi-muted">筛选:{{ filterDate }}</span>
<button class="ecbi-link" type="button" @click="filterDate = undefined">显示全部</button>
<span class="ecbi-muted">筛选 {{ filterDate }} · ¥{{ previewFee.toFixed(2) }}</span>
<button class="ecbi-link" type="button" @click="filterDate = undefined">全部</button>
</div>
</section>
<div class="ecbi-field">
<div class="ecbi-row">
<span class="ecbi-label">BI 渠道店铺</span>
<button
class="ecbi-link"
type="button"
:disabled="shopsLoading || busy"
@click="autoMatchShopFromPage"
>
按页面匹配
</button>
<button class="ecbi-link" type="button" :disabled="shopsLoading || busy" @click="loadShops">
{{ shopsLoading ? '加载中…' : '拉取列表' }}
</button>
</div>
<select class="ecbi-select" :value="channelShopId ?? ''" @change="onShopChange">
<option value="">请选择 channelShopId</option>
<option v-for="shop in shops" :key="shop.id" :value="shop.id">
{{ shop.mallName || '未命名' }} (#{{ shop.id }})
</option>
</select>
<span class="ecbi-muted">{{ selectedShopLabel }}</span>
</div>
<div class="ecbi-row">
<span class="ecbi-label">状态</span>
<span>{{ statusText }}</span>
</div>
<div class="ecbi-actions">
<button class="ecbi-btn ecbi-btn-ghost" type="button" :disabled="busy" @click="handleRead(false)">
读取并合并
</button>
<button
class="ecbi-btn ecbi-btn-ghost"
type="button"
:disabled="busy || !batch?.items?.length"
@click="clearAccumulated"
:disabled="busy || autoRunning"
@click="handleRead(false)"
>
清空
读当日
</button>
<button
class="ecbi-btn ecbi-btn-primary"
type="button"
:disabled="busy || !batch?.items?.length"
:disabled="busy || autoRunning || !batch?.items?.length"
@click="handleSync"
>
同步到 BI
传入系统
</button>
</div>
<section class="ecbi-card">
<h2>数据预览 · {{ previewLabel }}</h2>
<div class="ecbi-row">
<span class="ecbi-label">{{ filterDate ? '当日费用' : '累计费用' }}</span>
<span class="ecbi-fee">¥{{ (filterDate ? previewFee : totalFee).toFixed(2) }}</span>
<details class="ecbi-fold">
<summary>自动逐日 · {{ autoDaySpanLabel }}</summary>
<div class="ecbi-fold-body">
<div class="ecbi-date-row">
<label class="ecbi-date-field">
<span class="ecbi-muted">开始</span>
<input
v-model="autoStartDate"
class="ecbi-date-input"
type="date"
:disabled="autoRunning"
/>
</label>
<label class="ecbi-date-field">
<span class="ecbi-muted">结束</span>
<input
v-model="autoEndDate"
class="ecbi-date-input"
type="date"
:disabled="autoRunning"
/>
</label>
</div>
<div class="ecbi-row" style="margin-top: 8px">
<label class="ecbi-check">
<input v-model="autoSkipRead" type="checkbox" :disabled="autoRunning" />
跳过已读
</label>
</div>
<div class="ecbi-actions" style="margin-top: 10px">
<button
v-if="!autoRunning"
class="ecbi-btn ecbi-btn-ghost"
type="button"
:disabled="busy"
@click="handleAutoCollect"
>
开始
</button>
<button v-else class="ecbi-btn ecbi-btn-ghost" type="button" @click="stopAutoCollect">
停止
</button>
<button
class="ecbi-btn ecbi-btn-ghost"
type="button"
:disabled="busy || autoRunning || !batch?.items?.length"
@click="clearAccumulated"
>
清空累计
</button>
</div>
</div>
<div class="ecbi-row">
<span class="ecbi-label">条数</span>
<span>{{ previewItems.length }}{{ filterDate ? ` / ${itemCount}` : '' }}</span>
</div>
<ul v-if="previewItems.length" class="ecbi-list">
<li v-for="item in previewItems" :key="`${item.feeDate}-${item.goodsId}`">
<span>{{ item.feeDate }} · {{ item.goodsId }}</span>
<span>¥{{ Number(item.feeAmount).toFixed(2) }}</span>
</li>
</ul>
<p v-else class="ecbi-muted" style="margin: 8px 0 0">暂无数据,请在单日视图读取</p>
</section>
</details>
<details class="ecbi-fold">
<summary>明细 · {{ previewLabel }}({{ previewItems.length }})</summary>
<div class="ecbi-fold-body">
<ul v-if="previewItems.length" class="ecbi-list">
<li v-for="item in previewItems" :key="`${item.feeDate}-${item.goodsId}`">
<span>{{ item.feeDate }} · {{ item.goodsId }}</span>
<span>¥{{ Number(item.feeAmount).toFixed(2) }}</span>
</li>
</ul>
<p v-else class="ecbi-muted" style="margin: 0">暂无数据</p>
</div>
</details>
<p class="ecbi-status" :class="{ 'ecbi-status-busy': busy || autoRunning }">
{{ statusText }}
</p>
<p v-if="syncResultText" class="ecbi-ok">{{ syncResultText }}</p>
<p v-if="errorText" class="ecbi-error">{{ errorText }}</p>
<p class="ecbi-muted">日历点亮表示已读取;虚线框为当前页日期。同步提交全部已累计条目(不受筛选影响)。</p>
</div>
</div>
</template>
@@ -49,6 +49,35 @@
line-height: 1.5714;
}
/* 面板内所有滚动条统一细条 */
.ecbi-panel,
.ecbi-panel * {
scrollbar-width: thin;
scrollbar-color: rgb(0 0 0 / 0.28) transparent;
}
.ecbi-panel::-webkit-scrollbar,
.ecbi-panel *::-webkit-scrollbar {
width: 6px;
height: 6px;
}
.ecbi-panel::-webkit-scrollbar-thumb,
.ecbi-panel *::-webkit-scrollbar-thumb {
background: rgb(0 0 0 / 0.28);
border-radius: 3px;
}
.ecbi-panel::-webkit-scrollbar-thumb:hover,
.ecbi-panel *::-webkit-scrollbar-thumb:hover {
background: rgb(0 0 0 / 0.4);
}
.ecbi-panel::-webkit-scrollbar-track,
.ecbi-panel *::-webkit-scrollbar-track {
background: transparent;
}
.ecbi-header {
display: flex;
align-items: center;
@@ -74,6 +103,53 @@
opacity: 0.85;
}
.ecbi-header-main {
min-width: 0;
flex: 1;
}
.ecbi-header-sub {
max-width: 100%;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.ecbi-header-stats {
margin: 2px 0 0;
font-size: 12px;
opacity: 0.8;
max-width: 100%;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.ecbi-header-sub-warn {
color: #ffe58f;
opacity: 1;
}
.ecbi-header-link {
border: 0;
background: rgb(255 255 255 / 0.16);
color: #fff;
height: 28px;
padding: 0 8px;
border-radius: var(--ecbi-radius-sm);
font-size: 12px;
cursor: pointer;
}
.ecbi-header-link:hover:not(:disabled) {
background: rgb(255 255 255 / 0.28);
}
.ecbi-header-link:disabled {
opacity: 0.5;
cursor: not-allowed;
}
.ecbi-header-actions {
display: flex;
gap: 4px;
@@ -94,11 +170,78 @@
}
.ecbi-body {
padding: 14px;
padding: 12px 14px 14px;
overflow: auto;
display: flex;
flex-direction: column;
gap: 12px;
gap: 10px;
}
.ecbi-meta {
display: flex;
align-items: baseline;
flex-wrap: wrap;
gap: 4px 6px;
font-size: 13px;
}
.ecbi-meta-sep {
color: var(--ecbi-text-tertiary);
}
.ecbi-row-links {
display: inline-flex;
gap: 10px;
}
.ecbi-card-tight {
padding: 10px;
}
.ecbi-fold {
border: 1px solid var(--ecbi-border-secondary);
border-radius: var(--ecbi-radius);
background: var(--ecbi-bg);
padding: 0 10px;
}
.ecbi-fold > summary {
cursor: pointer;
list-style: none;
padding: 8px 0;
font-size: 12px;
color: var(--ecbi-text-secondary);
user-select: none;
}
.ecbi-fold > summary::-webkit-details-marker {
display: none;
}
.ecbi-fold > summary::before {
content: '▸';
display: inline-block;
margin-right: 6px;
transition: transform 0.15s;
}
.ecbi-fold[open] > summary::before {
transform: rotate(90deg);
}
.ecbi-fold-body {
padding: 0 0 10px;
}
.ecbi-status {
margin: 0;
font-size: 12px;
color: var(--ecbi-text-secondary);
line-height: 1.4;
}
.ecbi-status-busy {
color: var(--ecbi-primary);
}
.ecbi-row {
@@ -403,3 +546,58 @@ button.ecbi-heat-cell:disabled {
gap: 8px;
margin-top: 2px;
}
.ecbi-date-row {
display: flex;
flex-direction: column;
gap: 8px;
align-items: stretch;
}
.ecbi-date-field {
display: flex;
flex-direction: column;
gap: 4px;
width: 100%;
min-width: 0;
}
.ecbi-date-input {
box-sizing: border-box;
width: 100%;
max-width: 100%;
min-width: 0;
height: 32px;
padding: 4px 8px;
border: 1px solid var(--ecbi-border);
border-radius: var(--ecbi-radius-sm);
background: var(--ecbi-bg);
color: var(--ecbi-text);
font-size: 13px;
outline: none;
}
.ecbi-date-input:focus {
border-color: var(--ecbi-primary);
box-shadow: 0 0 0 2px rgb(22 119 255 / 0.1);
}
.ecbi-date-input:disabled {
background: var(--ecbi-fill);
color: var(--ecbi-text-secondary);
cursor: not-allowed;
}
.ecbi-check {
display: inline-flex;
align-items: center;
gap: 6px;
font-size: 12px;
color: var(--ecbi-text);
cursor: pointer;
user-select: none;
}
.ecbi-check input {
margin: 0;
}
@@ -6,7 +6,7 @@ import { installMainWorldAdapters } from '@/features/runtime/mainWorldAdapters';
import { setFloatingVisible } from '@/content/floating/mount';
const FEATURE_ID = 'pdd-ad-fee';
const FEATURE_VERSION = '0.2.0';
const FEATURE_VERSION = '0.3.9';
export interface RemoteFeatureExport {
id: string;
@@ -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'));
}
@@ -1,18 +1,18 @@
{
"schemaVersion": 1,
"updatedAt": "2026-08-16T12:53:27.630Z",
"updatedAt": "2026-08-16T14:27:38.290Z",
"features": [
{
"id": "pdd-ad-fee",
"name": "拼多多商品推广费同步",
"version": "0.2.0",
"description": "从推广总览读取单日总花费并同步到 BI(MAIN world 远程脚本,更新后端静态资源即可热更新)",
"version": "0.3.9",
"description": "从推广总览读取推广费并同步到 BI(浮窗滚动条统一 thin)",
"matchUrlPatterns": [
"*://yingxiao.pinduoduo.com/*",
"https://yingxiao.pinduoduo.com/"
],
"entry": "pdd-ad-fee.js",
"sha256": "da5e94dde412aff60347b39e73a321be517b55ba5e801f44432070fdce439c4b",
"sha256": "0ee120f49b6ecbb5c2ed433b087cb2543fad68319183d21c016eb8696e8b417b",
"executionWorld": "main"
}
]
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long