feat: 完成多日读取支持

This commit is contained in:
2026-08-16 17:28:53 +08:00
parent f209d93733
commit c35c985eb0
22 changed files with 1263 additions and 246 deletions
@@ -27,14 +27,14 @@ export interface BatchImportPddGoodsAdFeeResult {
}>;
}
/** 插件统一模型 → 后端 batch-import 入参 */
/** 插件统一模型 → 后端 batch-import 入参(日期取自每条 item) */
export function toBatchImportRequest(
batch: AdvertisingCostBatch,
): BatchImportPddGoodsAdFeeRequest {
return {
items: batch.items.map((item) => ({
channelShopId: batch.channelShopId,
feeDate: batch.feeDate,
feeDate: item.feeDate,
goodsId: item.goodsId,
feeAmount: item.feeAmount,
})),
@@ -0,0 +1,433 @@
<script setup lang="ts">
import { computed, onMounted, onUnmounted, ref } from 'vue';
import { batchImportPddGoodsAdFee } from '@/api/open/pddGoodsAdFee';
import { listPddChannelShops, type PddChannelShop } from '@/api/open/pddShop';
import { resolveAdapter } from '@/platform/core/PlatformDetector';
import { matchChannelShopByMallName } from '@/platform/pdd/matchShop';
import { EXTENSION_NAME } from '@/shared/constants';
import { toUserMessage } from '@/shared/errors';
import { listFeeDates, mergeAdvertisingItems } from '@/shared/mergeItems';
import { getSettings, saveSettings } from '@/storage/settings';
import type { AdvertisingCostBatch, PageContext } from '@/types/advertisingCost';
const emit = defineEmits<{
close: [];
minimize: [];
}>();
const shops = ref<PddChannelShop[]>([]);
const channelShopId = ref<number | undefined>(undefined);
const channelShopName = ref('');
const pageMallName = ref('');
const shopsLoading = ref(false);
const pageContext = ref<PageContext | null>(null);
const batch = ref<AdvertisingCostBatch | null>(null);
const statusText = ref('等待读取');
const errorText = ref('');
const syncResultText = ref('');
const busy = ref(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 };
let dragging = false;
let readTimer: ReturnType<typeof setTimeout> | null = null;
let urlPollTimer: ReturnType<typeof setInterval> | null = null;
let lastHref = typeof location !== 'undefined' ? location.href : '';
const totalFee = computed(() =>
(batch.value?.items ?? []).reduce((sum, item) => sum + Number(item.feeAmount || 0), 0),
);
const itemCount = computed(() => batch.value?.items.length ?? 0);
const accumulatedDates = computed(() => listFeeDates(batch.value?.items ?? []));
const dateCount = computed(() => accumulatedDates.value.length);
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 ?? ''}`;
if (mode === 'range') return '范围(本页不追加)';
return '未知';
});
const accumulatedLabel = computed(() => {
if (!dateCount.value) return '尚未累计';
return `${dateCount.value} 天 · ${itemCount.value} 条`;
});
async function refreshContext() {
try {
pageContext.value = await resolveAdapter(location.href).getPageContext();
pageMallName.value = pageContext.value.mallName ?? '';
} catch {
pageContext.value = null;
pageMallName.value = '';
}
}
async function loadLocalSettings() {
const settings = await getSettings();
channelShopId.value = settings.channelShopId;
channelShopName.value = settings.channelShopName ?? '';
}
async function persistShop() {
await saveSettings({
channelShopId: channelShopId.value,
channelShopName: channelShopName.value,
});
}
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;
}
}
/** 用页面店铺名自动匹配 BI 渠道店 */
async function autoMatchShopFromPage(): Promise<boolean> {
await refreshContext();
const mallName = pageMallName.value.trim();
if (!mallName) return false;
try {
const matched = await matchChannelShopByMallName(mallName);
if (!matched) {
statusText.value = `未匹配到店铺「${mallName}」,请手动选择或拉取列表`;
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];
}
await persistShop();
statusText.value = `已按页面店铺匹配:${channelShopName.value}`;
return true;
} catch (error) {
errorText.value = toUserMessage(error);
statusText.value = '店铺自动匹配失败';
return 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;
}
channelShopId.value = value;
const hit = shops.value.find((s) => s.id === value);
channelShopName.value = hit?.mallName ?? '';
void persistShop();
scheduleAutoRead();
}
async function handleRead(fromAuto = false) {
busy.value = true;
errorText.value = '';
syncResultText.value = '';
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 渠道店铺(页面店铺名可自动匹配)');
}
}
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 addedOrUpdated = parsed.items.length;
batch.value = {
platform: parsed.platform,
channelShopId: channelShopId.value,
items: mergedItems,
source: 'browser-extension',
importedAt: new Date().toISOString(),
};
await refreshContext();
const tag = parsed.platform === 'mock' ? 'Mock' : '页面';
statusText.value = incomingDate
? `已合并 ${incomingDate}(${addedOrUpdated} 条,${tag})· 累计 ${dateCount.value} 天`
: `已读取(${tag})`;
} catch (error) {
// 读取失败不清空已累计数据
statusText.value = '读取失败';
errorText.value = toUserMessage(error);
} finally {
busy.value = false;
}
}
function clearAccumulated() {
batch.value = null;
syncResultText.value = '';
errorText.value = '';
statusText.value = '已清空累计数据';
}
function scheduleAutoRead(delayMs = 450) {
if (readTimer) clearTimeout(readTimer);
readTimer = setTimeout(() => {
void handleRead(true);
}, delayMs);
}
async function onPageUrlChanged() {
await refreshContext();
if (pageContext.value?.dateMode === 'single') {
errorText.value = '';
// 等报表表格随 URL 刷新后再读
scheduleAutoRead(1200);
return;
}
if (pageContext.value?.dateMode === 'range') {
statusText.value = '范围视图不追加;已累计数据仍保留';
}
}
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 {
const payload: AdvertisingCostBatch = {
...batch.value,
channelShopId: channelShopId.value,
};
const result = await batchImportPddGoodsAdFee(payload);
statusText.value = '同步完成';
syncResultText.value =
`成功 ${result.successCount}/${result.totalCount}` +
(result.failureCount ? `,失败 ${result.failureCount}` : '');
} catch (error) {
statusText.value = '同步失败';
errorText.value = toUserMessage(error);
} finally {
busy.value = false;
}
}
function onHeaderPointerDown(event: PointerEvent) {
if ((event.target as HTMLElement).closest('button')) return;
dragging = true;
dragOffset = {
x: event.clientX - position.value.left,
y: event.clientY - position.value.top,
};
(event.currentTarget as HTMLElement).setPointerCapture(event.pointerId);
}
function onHeaderPointerMove(event: PointerEvent) {
if (!dragging) return;
const maxLeft = window.innerWidth - 80;
const maxTop = window.innerHeight - 80;
position.value = {
left: Math.min(maxLeft, Math.max(8, event.clientX - dragOffset.x)),
top: Math.min(maxTop, Math.max(8, event.clientY - dragOffset.y)),
};
}
function onHeaderPointerUp(event: PointerEvent) {
dragging = false;
try {
(event.currentTarget as HTMLElement).releasePointerCapture(event.pointerId);
} catch {
// ignore
}
}
onMounted(async () => {
await loadLocalSettings();
await refreshContext();
const matched = await autoMatchShopFromPage();
if (pageContext.value?.dateMode === 'range') {
statusText.value = '范围视图不追加;请切到单日逐日读取并累计';
errorText.value = pageContext.value.message ?? '';
} else if (matched || channelShopId.value != null) {
scheduleAutoRead();
}
lastHref = location.href;
urlPollTimer = setInterval(() => {
if (location.href === lastHref) return;
lastHref = location.href;
void onPageUrlChanged();
}, 800);
});
onUnmounted(() => {
if (readTimer) clearTimeout(readTimer);
if (urlPollTimer) clearInterval(urlPollTimer);
});
</script>
<template>
<div
ref="panelRef"
class="ecbi-panel"
:style="{ top: `${position.top}px`, left: `${position.left}px` }"
>
<header
class="ecbi-header"
@pointerdown="onHeaderPointerDown"
@pointermove="onHeaderPointerMove"
@pointerup="onHeaderPointerUp"
@pointercancel="onHeaderPointerUp"
>
<div>
<h1>{{ EXTENSION_NAME }}</h1>
<p>页内悬浮 · 单日累计多日</p>
</div>
<div class="ecbi-header-actions">
<button class="ecbi-icon-btn" type="button" title="收起" @click="emit('minimize')">
–
</button>
<button class="ecbi-icon-btn" type="button" title="关闭" @click="emit('close')">
×
</button>
</div>
</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>
<span>{{ dateModeLabel }}</span>
</div>
<div class="ecbi-row">
<span class="ecbi-label">已累计</span>
<span>{{ accumulatedLabel }}</span>
</div>
<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"
>
清空
</button>
<button
class="ecbi-btn ecbi-btn-primary"
type="button"
:disabled="busy || !batch?.items?.length"
@click="handleSync"
>
同步到 BI
</button>
</div>
<section class="ecbi-card">
<h2>数据预览</h2>
<div class="ecbi-row">
<span class="ecbi-label">推广费用</span>
<span class="ecbi-fee">¥{{ totalFee.toFixed(2) }}</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">
{{ accumulatedDates.join('、') || '—' }}
</span>
</div>
<div class="ecbi-row">
<span class="ecbi-label">条数</span>
<span>{{ itemCount }}</span>
</div>
<ul v-if="batch?.items?.length" class="ecbi-list">
<li v-for="item in batch.items" :key="`${item.feeDate}-${item.goodsId}`">
<span>{{ item.feeDate }} · {{ item.goodsId }}</span>
<span>¥{{ Number(item.feeAmount).toFixed(2) }}</span>
</li>
</ul>
</section>
<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>
@@ -0,0 +1,121 @@
import { createApp, type App } from 'vue';
import FloatingPanel from './FloatingPanel.vue';
import styles from './styles.css?inline';
const HOST_ID = 'ecbi-float-host';
const LAUNCHER_ID = 'ecbi-float-launcher';
let app: App<Element> | null = null;
let visible = false;
let minimized = false;
function ensureHost(): HTMLElement {
let host = document.getElementById(HOST_ID);
if (!host) {
host = document.createElement('div');
host.id = HOST_ID;
document.documentElement.appendChild(host);
}
return host;
}
function ensureShadow(host: HTMLElement): ShadowRoot {
return host.shadowRoot ?? host.attachShadow({ mode: 'open' });
}
function removeLauncher() {
document.getElementById(LAUNCHER_ID)?.remove();
}
function showLauncher() {
removeLauncher();
const btn = document.createElement('button');
btn.id = LAUNCHER_ID;
btn.type = 'button';
btn.textContent = 'ECBI';
btn.title = '展开 ECBI 悬浮面板';
Object.assign(btn.style, {
position: 'fixed',
right: '16px',
bottom: '16px',
zIndex: '2147483646',
border: '0',
borderRadius: '999px',
padding: '10px 14px',
background: '#0f172a',
color: '#fff',
fontSize: '12px',
fontWeight: '600',
cursor: 'pointer',
boxShadow: '0 8px 20px rgb(15 23 42 / 0.25)',
} as CSSStyleDeclaration);
btn.addEventListener('click', () => {
minimized = false;
setFloatingVisible(true);
});
document.documentElement.appendChild(btn);
}
function unmountApp() {
if (app) {
app.unmount();
app = null;
}
const host = document.getElementById(HOST_ID);
if (host?.shadowRoot) {
host.shadowRoot.innerHTML = '';
}
}
function mountApp() {
const host = ensureHost();
const shadow = ensureShadow(host);
shadow.innerHTML = '';
const styleEl = document.createElement('style');
styleEl.textContent = styles;
shadow.appendChild(styleEl);
const mountEl = document.createElement('div');
shadow.appendChild(mountEl);
app = createApp(FloatingPanel, {
onClose: () => setFloatingVisible(false),
onMinimize: () => {
minimized = true;
unmountApp();
showLauncher();
visible = true;
},
});
app.mount(mountEl);
}
export function isFloatingVisible(): boolean {
return visible;
}
export function setFloatingVisible(next: boolean): boolean {
if (!next) {
visible = false;
minimized = false;
unmountApp();
removeLauncher();
return false;
}
visible = true;
removeLauncher();
if (minimized) {
minimized = false;
}
if (!app) {
mountApp();
}
return true;
}
export function toggleFloatingPanel(): boolean {
return setFloatingVisible(!visible || minimized);
}
@@ -0,0 +1,222 @@
#ecbi-float-host {
all: initial;
}
.ecbi-panel {
position: fixed;
z-index: 2147483646;
width: 360px;
max-height: min(560px, calc(100vh - 24px));
overflow: hidden;
display: flex;
flex-direction: column;
border-radius: 12px;
border: 1px solid #e2e8f0;
background: #ffffff;
color: #0f172a;
box-shadow:
0 10px 15px -3px rgb(15 23 42 / 0.12),
0 4px 6px -4px rgb(15 23 42 / 0.08);
font-family:
ui-sans-serif,
system-ui,
-apple-system,
'Segoe UI',
Roboto,
'Helvetica Neue',
Arial,
'Noto Sans',
sans-serif;
font-size: 13px;
line-height: 1.4;
}
.ecbi-header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
padding: 10px 12px;
background: #0f172a;
color: #f8fafc;
cursor: move;
user-select: none;
}
.ecbi-header h1 {
margin: 0;
font-size: 13px;
font-weight: 600;
}
.ecbi-header p {
margin: 2px 0 0;
font-size: 11px;
opacity: 0.75;
}
.ecbi-header-actions {
display: flex;
gap: 4px;
}
.ecbi-icon-btn {
border: 0;
background: transparent;
color: #e2e8f0;
width: 24px;
height: 24px;
border-radius: 6px;
cursor: pointer;
}
.ecbi-icon-btn:hover {
background: rgb(255 255 255 / 0.12);
}
.ecbi-body {
padding: 12px;
overflow: auto;
display: flex;
flex-direction: column;
gap: 10px;
}
.ecbi-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
}
.ecbi-label {
color: #64748b;
flex-shrink: 0;
}
.ecbi-input,
.ecbi-select {
width: 100%;
border: 1px solid #e2e8f0;
border-radius: 8px;
padding: 6px 8px;
font-size: 13px;
outline: none;
background: #fff;
color: #0f172a;
box-sizing: border-box;
}
.ecbi-input:focus,
.ecbi-select:focus {
border-color: #94a3b8;
}
.ecbi-field {
display: flex;
flex-direction: column;
gap: 4px;
}
.ecbi-actions {
display: flex;
gap: 8px;
}
.ecbi-btn {
flex: 1;
border-radius: 8px;
border: 1px solid #cbd5e1;
background: #fff;
padding: 8px 10px;
font-size: 13px;
font-weight: 500;
cursor: pointer;
}
.ecbi-btn:disabled {
opacity: 0.5;
cursor: not-allowed;
}
.ecbi-btn-primary {
border-color: #059669;
background: #059669;
color: #fff;
}
.ecbi-btn-primary:hover:not(:disabled) {
background: #047857;
}
.ecbi-btn-ghost:hover:not(:disabled) {
background: #f8fafc;
}
.ecbi-card {
border: 1px solid #e2e8f0;
border-radius: 8px;
padding: 10px;
background: #f8fafc;
}
.ecbi-card h2 {
margin: 0 0 8px;
font-size: 11px;
font-weight: 600;
letter-spacing: 0.04em;
text-transform: uppercase;
color: #64748b;
}
.ecbi-fee {
font-weight: 700;
color: #e11d48;
}
.ecbi-list {
margin: 8px 0 0;
padding: 0;
list-style: none;
max-height: 120px;
overflow: auto;
}
.ecbi-list li {
display: flex;
justify-content: space-between;
gap: 8px;
font-size: 12px;
color: #475569;
padding: 2px 0;
}
.ecbi-muted {
color: #94a3b8;
font-size: 12px;
}
.ecbi-error {
color: #e11d48;
font-size: 12px;
margin: 0;
}
.ecbi-ok {
color: #047857;
font-size: 12px;
margin: 0;
}
.ecbi-link {
border: 0;
background: transparent;
color: #0369a1;
font-size: 12px;
cursor: pointer;
padding: 0;
}
.ecbi-link:hover {
text-decoration: underline;
}
+18 -2
View File
@@ -7,6 +7,12 @@ import {
} from '@/shared/messages';
import type { AdvertisingCostBatch } from '@/types/advertisingCost';
import {
isFloatingVisible,
setFloatingVisible,
toggleFloatingPanel,
} from './floating/mount';
async function handleMessage(message: ExtensionMessage): Promise<ExtensionResponse> {
const adapter = resolveAdapter(location.href);
@@ -18,14 +24,24 @@ async function handleMessage(message: ExtensionMessage): Promise<ExtensionRespon
return { ok: true, data };
}
case 'PARSE_ADVERTISING_COST': {
const parsed = await adapter.parseAdvertisingCost(message.payload.feeDate);
// channelShopId 由 Popup 选择后填入
const parsed = await adapter.parseAdvertisingCost();
const data: AdvertisingCostBatch = {
...parsed,
channelShopId: 0,
};
return { ok: true, data };
}
case 'TOGGLE_FLOATING_PANEL': {
const visible = toggleFloatingPanel();
return { ok: true, data: { visible } };
}
case 'SET_FLOATING_PANEL': {
const visible = setFloatingVisible(message.payload.visible);
return { ok: true, data: { visible } };
}
case 'GET_FLOATING_PANEL_STATE': {
return { ok: true, data: { visible: isFloatingVisible() } };
}
default:
return {
ok: false,
+5
View File
@@ -5,3 +5,8 @@ declare module '*.vue' {
const component: DefineComponent<object, object, unknown>;
export default component;
}
declare module '*.css?inline' {
const css: string;
export default css;
}
@@ -8,5 +8,6 @@ export interface PlatformAdapter {
readonly platform: PlatformType;
canHandle(url: string): boolean;
getPageContext(): Promise<PageContext>;
parseAdvertisingCost(feeDate: string): Promise<Omit<AdvertisingCostBatch, 'channelShopId'>>;
/** 从当前页解析推广费;每条 item 自带 feeDate */
parseAdvertisingCost(): Promise<Omit<AdvertisingCostBatch, 'channelShopId'>>;
}
@@ -2,8 +2,9 @@ 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 MockPlatformAdapter()];
const adapters: PlatformAdapter[] = [new PddPlatformAdapter(), new MockPlatformAdapter()];
export function detectPlatform(url: string): PlatformType {
const adapter = adapters.find((item) => item.canHandle(url));
@@ -15,8 +16,8 @@ export function resolveAdapter(url: string): PlatformAdapter {
if (matched) {
return matched;
}
// 第一阶段:未识别平台时回退 Mock,保证链路可跑通
return adapters[0]!;
// 非拼多多推广页时回退 Mock,便于本地联调
return adapters.find((item) => item.platform === 'mock') ?? adapters[0]!;
}
export function listAdapters(): PlatformAdapter[] {
@@ -2,13 +2,13 @@ import type { PlatformAdapter } from '@/platform/core/PlatformAdapter';
import type { AdvertisingCostBatch, PageContext } from '@/types/advertisingCost';
/**
* 第一阶段 Mock Adapter:不读真实 DOM,返回固定样例数据。
* 第一阶段 Mock Adapter:不读真实 DOM,返回带日期的样例。
* 真实页面解析等接入平台后再实现。
*/
export class MockPlatformAdapter implements PlatformAdapter {
readonly platform = 'mock' as const;
canHandle(_url: string): boolean {
// 未接入真实平台前,任意页面均可由 Mock 处理
return true;
}
@@ -22,19 +22,14 @@ export class MockPlatformAdapter implements PlatformAdapter {
};
}
async parseAdvertisingCost(
feeDate: string,
): Promise<Omit<AdvertisingCostBatch, 'channelShopId'>> {
const items = [
{ goodsId: 'mock-goods-1001', feeAmount: 128.5 },
{ goodsId: 'mock-goods-1002', feeAmount: 56.0 },
{ goodsId: 'mock-goods-1003', feeAmount: 1050.06 },
];
async parseAdvertisingCost(): Promise<Omit<AdvertisingCostBatch, 'channelShopId'>> {
return {
platform: 'mock',
feeDate,
items,
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,71 @@
import type { PlatformAdapter } from '@/platform/core/PlatformAdapter';
import type { AdvertisingCostBatch, PageContext } from '@/types/advertisingCost';
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(): 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 ?? '未能识别单日报表日期');
}
const items = parsePromotionItems(dateInfo.feeDate);
if (items.length === 0) {
throw new Error('未解析到商品推广费,请确认表格已加载且包含「总花费」列');
}
return {
platform: 'pdd',
items,
source: 'browser-extension',
importedAt: new Date().toISOString(),
};
}
}
@@ -0,0 +1,26 @@
import type { PddChannelShop } from '@/api/open/pddShop';
import { listPddChannelShops } from '@/api/open/pddShop';
/**
* 用页面店铺名通过 Open 店铺分页接口匹配 BI channelShop。
* 优先精确匹配 mallName,其次仅当筛选结果唯一时采用。
*/
export async function matchChannelShopByMallName(
mallName: string,
): Promise<PddChannelShop | null> {
const name = mallName.trim();
if (!name) return null;
const result = await listPddChannelShops({
page: 1,
pageSize: 50,
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;
}
@@ -0,0 +1,157 @@
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;
}
/** 优先 URL beginDate/endDate,其次主 RangePicker 两个 input */
export function readReportDate(doc: Document = document, href = location.href): PddReportDateInfo {
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
}
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;
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 { mode: 'unknown', message: '未能识别报表日期,请确认已打开商品推广总览且选择了日期' };
}
/**
* 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);
if (feeAmount == null) continue;
seen.add(goodsId);
items.push({
feeDate,
goodsId,
feeAmount,
metadata: {
goodsName: row
.querySelector('[class*="OverviewTable_goodsName"]')
?.getAttribute('title')
?.replace(/^商品名:/, ''),
},
});
}
return items;
}
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,18 @@
/** 拼多多推广报表 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',
} 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})/;
+83 -184
View File
@@ -1,45 +1,24 @@
<script setup lang="ts">
import { computed, onMounted, ref } from 'vue';
import { onMounted, ref } from 'vue';
import { batchImportPddGoodsAdFee } from '@/api/open/pddGoodsAdFee';
import { listPddChannelShops, type PddChannelShop } from '@/api/open/pddShop';
import { EXTENSION_NAME } from '@/shared/constants';
import { EXTENSION_NAME, OPEN_SCOPES } from '@/shared/constants';
import { toUserMessage } from '@/shared/errors';
import { getSettings, saveSettings } from '@/storage/settings';
import type { AdvertisingCostBatch, PageContext } from '@/types/advertisingCost';
import { fetchPageContext, parseAdvertisingCostFromPage } from './messaging';
import { getFloatingPanelState, openFloatingPanel, toggleFloatingPanel } from './messaging';
const settingsOpen = ref(false);
const apiBaseUrl = ref('');
const apiKey = ref('');
const feeDate = ref(new Date().toISOString().slice(0, 10));
const shops = ref<PddChannelShop[]>([]);
const channelShopId = ref<number | undefined>(undefined);
const channelShopName = ref('');
const shops = ref<PddChannelShop[]>([]);
const shopsLoading = ref(false);
const pageContext = ref<PageContext | null>(null);
const batch = ref<AdvertisingCostBatch | null>(null);
const statusText = ref('等待读取');
const panelVisible = ref(false);
const statusText = ref('');
const errorText = ref('');
const syncResultText = ref('');
const busy = ref(false);
const totalFee = computed(() =>
(batch.value?.items ?? []).reduce((sum, item) => sum + Number(item.feeAmount || 0), 0),
);
const itemCount = computed(() => batch.value?.items.length ?? 0);
const selectedShopLabel = computed(() => {
if (channelShopId.value == null) return '未选择';
return channelShopName.value
? `${channelShopName.value} (#${channelShopId.value})`
: `#${channelShopId.value}`;
});
async function loadLocalSettings() {
const settings = await getSettings();
apiBaseUrl.value = settings.apiBaseUrl;
@@ -49,22 +28,16 @@ async function loadLocalSettings() {
}
async function persistSettings() {
await saveSettings({
apiBaseUrl: apiBaseUrl.value.trim(),
apiKey: apiKey.value.trim(),
channelShopId: channelShopId.value,
channelShopName: channelShopName.value,
});
settingsOpen.value = false;
statusText.value = '配置已保存';
}
async function refreshPageContext() {
errorText.value = '';
try {
pageContext.value = await fetchPageContext();
await saveSettings({
apiBaseUrl: apiBaseUrl.value.trim(),
apiKey: apiKey.value.trim(),
channelShopId: channelShopId.value,
channelShopName: channelShopName.value,
});
statusText.value = '配置已保存';
} catch (error) {
pageContext.value = null;
errorText.value = toUserMessage(error);
}
}
@@ -73,14 +46,12 @@ async function loadShops() {
shopsLoading.value = true;
errorText.value = '';
try {
await persistSettingsQuiet();
await persistSettings();
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 ?? '';
}
if (hit) channelShopName.value = hit.mallName ?? '';
}
} catch (error) {
errorText.value = toUserMessage(error);
@@ -89,15 +60,6 @@ async function loadShops() {
}
}
async function persistSettingsQuiet() {
await saveSettings({
apiBaseUrl: apiBaseUrl.value.trim(),
apiKey: apiKey.value.trim(),
channelShopId: channelShopId.value,
channelShopName: channelShopName.value,
});
}
function onShopChange(event: Event) {
const value = Number((event.target as HTMLSelectElement).value);
if (!Number.isFinite(value) || value <= 0) {
@@ -108,62 +70,41 @@ function onShopChange(event: Event) {
channelShopId.value = value;
const hit = shops.value.find((s) => s.id === value);
channelShopName.value = hit?.mallName ?? '';
void persistSettingsQuiet();
}
async function handleRead() {
async function refreshPanelState() {
try {
const state = await getFloatingPanelState();
panelVisible.value = state.visible;
} catch {
panelVisible.value = false;
}
}
async function handleOpenPanel() {
busy.value = true;
errorText.value = '';
syncResultText.value = '';
statusText.value = '正在读取…';
statusText.value = '';
try {
if (channelShopId.value == null) {
throw new Error('请先选择 BI 渠道店铺(channelShopId)');
}
const parsed = await parseAdvertisingCostFromPage(feeDate.value);
batch.value = {
...parsed,
channelShopId: channelShopId.value,
feeDate: feeDate.value,
};
pageContext.value = await fetchPageContext();
statusText.value = '已读取(Mock)';
await persistSettings();
const state = await openFloatingPanel();
panelVisible.value = state.visible;
statusText.value = '已打开页内悬浮层';
} catch (error) {
batch.value = null;
statusText.value = '读取失败';
errorText.value = toUserMessage(error);
} finally {
busy.value = false;
}
}
async function handleSync() {
if (!batch.value) {
errorText.value = '请先读取数据';
return;
}
if (channelShopId.value == null) {
errorText.value = '请先选择 BI 渠道店铺';
return;
}
async function handleTogglePanel() {
busy.value = true;
errorText.value = '';
syncResultText.value = '';
statusText.value = '正在同步…';
try {
await persistSettingsQuiet();
const payload: AdvertisingCostBatch = {
...batch.value,
channelShopId: channelShopId.value,
feeDate: feeDate.value,
};
const result = await batchImportPddGoodsAdFee(payload);
statusText.value = '同步完成';
syncResultText.value = `成功 ${result.successCount}/${result.totalCount}` +
(result.failureCount ? `,失败 ${result.failureCount}` : '');
const state = await toggleFloatingPanel();
panelVisible.value = state.visible;
statusText.value = state.visible ? '悬浮层已显示' : '悬浮层已关闭';
} catch (error) {
statusText.value = '同步失败';
errorText.value = toUserMessage(error);
} finally {
busy.value = false;
@@ -172,32 +113,23 @@ async function handleSync() {
onMounted(async () => {
await loadLocalSettings();
await refreshPageContext();
await refreshPanelState();
});
</script>
<template>
<div class="flex min-h-[480px] w-[380px] flex-col gap-3 p-4">
<header class="flex items-start justify-between gap-2">
<div>
<h1 class="text-base font-semibold tracking-tight">{{ EXTENSION_NAME }}</h1>
<p class="mt-0.5 text-xs text-slate-500">主动同步 · Open API · 第一阶段 Mock</p>
</div>
<button
class="rounded-md border border-slate-200 bg-white px-2 py-1 text-xs text-slate-700 hover:bg-slate-50"
type="button"
@click="settingsOpen = !settingsOpen"
>
{{ settingsOpen ? '收起配置' : '配置' }}
</button>
<div class="flex w-[360px] flex-col gap-3 p-4">
<header>
<h1 class="text-base font-semibold tracking-tight">{{ EXTENSION_NAME }}</h1>
<p class="mt-0.5 text-xs text-slate-500">
Popup 负责配置与开关;业务操作在页内悬浮层完成。
</p>
</header>
<section
v-if="settingsOpen"
class="space-y-2 rounded-lg border border-slate-200 bg-white p-3"
>
<section class="space-y-2 rounded-lg border border-slate-200 bg-white p-3">
<h2 class="text-xs font-semibold uppercase tracking-wide text-slate-500">Open API 配置</h2>
<label class="block text-xs text-slate-600">
Open API Base URL
Base URL
<input
v-model="apiBaseUrl"
class="mt-1 w-full rounded-md border border-slate-200 px-2 py-1.5 text-sm outline-none focus:border-slate-400"
@@ -205,7 +137,7 @@ onMounted(async () => {
/>
</label>
<label class="block text-xs text-slate-600">
Open API Key
API Key
<input
v-model="apiKey"
type="password"
@@ -213,37 +145,13 @@ onMounted(async () => {
placeholder="sk_live_..."
/>
</label>
<button
class="w-full rounded-md bg-slate-900 px-3 py-1.5 text-sm text-white hover:bg-slate-800"
type="button"
@click="persistSettings"
>
保存配置
</button>
</section>
<p class="text-[11px] leading-relaxed text-slate-400">
需要 scope:{{ OPEN_SCOPES.pddShopRead }}、{{ OPEN_SCOPES.pddGoodsAdFeeImport }}
</p>
<section class="space-y-2 rounded-lg border border-slate-200 bg-white p-3 text-sm">
<div class="flex justify-between gap-2">
<span class="text-slate-500">当前平台</span>
<span class="font-medium">{{ pageContext?.platform ?? '未识别' }}</span>
</div>
<div class="flex justify-between gap-2">
<span class="text-slate-500">当前页面</span>
<span class="max-w-[220px] truncate text-right text-xs" :title="pageContext?.url">
{{ pageContext?.title || pageContext?.url || '—' }}
</span>
</div>
<label class="flex items-center justify-between gap-2">
<span class="text-slate-500">同步日期</span>
<input
v-model="feeDate"
type="date"
class="rounded-md border border-slate-200 px-2 py-1 text-sm"
/>
</label>
<div class="space-y-1">
<div class="flex items-center justify-between gap-2">
<span class="text-slate-500">BI 渠道店铺</span>
<div class="flex items-center justify-between">
<span class="text-xs text-slate-600">默认渠道店铺</span>
<button
class="text-xs text-sky-700 hover:underline"
type="button"
@@ -258,60 +166,51 @@ onMounted(async () => {
:value="channelShopId ?? ''"
@change="onShopChange"
>
<option value="">请选择 channelShopId</option>
<option value="">可选,打开悬浮层后仍可改</option>
<option v-for="shop in shops" :key="shop.id" :value="shop.id">
{{ shop.mallName || '未命名' }} (#{{ shop.id }}
<template v-if="shop.mallId != null"> / mall {{ shop.mallId }}</template>)
{{ shop.mallName || '未命名' }} (#{{ shop.id }})
</option>
</select>
<p class="text-xs text-slate-400">当前:{{ selectedShopLabel }}</p>
</div>
<div class="flex justify-between gap-2">
<span class="text-slate-500">数据状态</span>
<span class="font-medium">{{ statusText }}</span>
</div>
</section>
<div class="flex gap-2">
<button
class="flex-1 rounded-md border border-slate-300 bg-white px-3 py-2 text-sm font-medium hover:bg-slate-50 disabled:opacity-50"
class="w-full rounded-md bg-slate-900 px-3 py-1.5 text-sm text-white hover:bg-slate-800"
type="button"
:disabled="busy"
@click="handleRead"
@click="persistSettings"
>
读取数据
保存配置
</button>
<button
class="flex-1 rounded-md bg-emerald-600 px-3 py-2 text-sm font-medium text-white hover:bg-emerald-500 disabled:opacity-50"
type="button"
:disabled="busy || !batch"
@click="handleSync"
>
同步到 BI
</button>
</div>
<section class="rounded-lg border border-slate-200 bg-white p-3 text-sm">
<h2 class="mb-2 text-xs font-semibold uppercase tracking-wide text-slate-500">
数据预览
</h2>
<div class="flex justify-between">
<span class="text-slate-500">推广费用</span>
<span class="font-semibold text-rose-600">¥{{ totalFee.toFixed(2) }}</span>
</div>
<div class="mt-1 flex justify-between">
<span class="text-slate-500">数据条数</span>
<span class="font-medium">{{ itemCount }}</span>
</div>
<ul v-if="batch?.items?.length" class="mt-2 max-h-28 space-y-1 overflow-auto text-xs text-slate-600">
<li v-for="item in batch.items" :key="item.goodsId" class="flex justify-between gap-2">
<span class="truncate">{{ item.goodsId }}</span>
<span>¥{{ Number(item.feeAmount).toFixed(2) }}</span>
</li>
</ul>
</section>
<p v-if="syncResultText" class="text-xs text-emerald-700">{{ syncResultText }}</p>
<section class="space-y-2 rounded-lg border border-slate-200 bg-white p-3">
<h2 class="text-xs font-semibold uppercase tracking-wide text-slate-500">页内悬浮层</h2>
<p class="text-xs text-slate-500">
当前状态:
<span class="font-medium text-slate-800">{{ panelVisible ? '已打开' : '未打开' }}</span>
</p>
<div class="flex gap-2">
<button
class="flex-1 rounded-md bg-emerald-600 px-3 py-2 text-sm font-medium text-white hover:bg-emerald-500 disabled:opacity-50"
type="button"
:disabled="busy"
@click="handleOpenPanel"
>
打开悬浮层
</button>
<button
class="flex-1 rounded-md border border-slate-300 bg-white px-3 py-2 text-sm font-medium hover:bg-slate-50 disabled:opacity-50"
type="button"
:disabled="busy"
@click="handleTogglePanel"
>
开关切换
</button>
</div>
<p class="text-[11px] text-slate-400">若提示无法连接页面脚本,请先刷新目标网页。</p>
</section>
<p v-if="statusText" class="text-xs text-emerald-700">{{ statusText }}</p>
<p v-if="errorText" class="text-xs text-rose-600">{{ errorText }}</p>
</div>
</template>
+13 -12
View File
@@ -1,6 +1,5 @@
import type { ExtensionMessage, ExtensionResponse } from '@/shared/messages';
import { ExtensionError } from '@/shared/errors';
import type { AdvertisingCostBatch, PageContext } from '@/types/advertisingCost';
async function getActiveTabId(): Promise<number> {
const tabs = await chrome.tabs.query({ active: true, currentWindow: true });
@@ -19,7 +18,7 @@ async function sendToActiveTab<T>(message: ExtensionMessage): Promise<T> {
} catch {
throw new ExtensionError(
'PAGE_NOT_READY',
'无法连接页面脚本。请刷新目标页面后重试(需已注入 Content Script)。',
'无法连接页面脚本。请刷新目标页面后再打开悬浮层。',
);
}
@@ -35,15 +34,17 @@ async function sendToActiveTab<T>(message: ExtensionMessage): Promise<T> {
return response.data as T;
}
export async function fetchPageContext(): Promise<PageContext> {
return sendToActiveTab<PageContext>({ type: 'GET_PAGE_CONTEXT' });
}
export async function parseAdvertisingCostFromPage(
feeDate: string,
): Promise<AdvertisingCostBatch> {
return sendToActiveTab<AdvertisingCostBatch>({
type: 'PARSE_ADVERTISING_COST',
payload: { feeDate },
export async function openFloatingPanel(): Promise<{ visible: boolean }> {
return sendToActiveTab<{ visible: boolean }>({
type: 'SET_FLOATING_PANEL',
payload: { visible: true },
});
}
export async function toggleFloatingPanel(): Promise<{ visible: boolean }> {
return sendToActiveTab<{ visible: boolean }>({ type: 'TOGGLE_FLOATING_PANEL' });
}
export async function getFloatingPanelState(): Promise<{ visible: boolean }> {
return sendToActiveTab<{ visible: boolean }>({ type: 'GET_FLOATING_PANEL_STATE' });
}
@@ -0,0 +1,30 @@
import type { AdvertisingCostItem } from '@/types/advertisingCost';
function itemKey(item: AdvertisingCostItem): string {
return `${item.feeDate}::${item.goodsId}`;
}
/**
* 合并多次单日读取:按 (feeDate, goodsId) upsert。
* 换日再读保留已有日期;同日再读覆盖该日同商品。
*/
export function mergeAdvertisingItems(
previous: AdvertisingCostItem[],
incoming: AdvertisingCostItem[],
): AdvertisingCostItem[] {
const map = new Map<string, AdvertisingCostItem>();
for (const item of previous) {
map.set(itemKey(item), item);
}
for (const item of incoming) {
map.set(itemKey(item), item);
}
return Array.from(map.values()).sort((a, b) => {
const byDate = a.feeDate.localeCompare(b.feeDate);
return byDate !== 0 ? byDate : a.goodsId.localeCompare(b.goodsId);
});
}
export function listFeeDates(items: AdvertisingCostItem[]): string[] {
return [...new Set(items.map((item) => item.feeDate))].sort();
}
+15 -6
View File
@@ -2,21 +2,30 @@ import type { AdvertisingCostBatch, PageContext } from '@/types/advertisingCost'
export type ExtensionMessage =
| { type: 'GET_PAGE_CONTEXT' }
| { type: 'PARSE_ADVERTISING_COST'; payload: { feeDate: string } }
| { type: 'PARSE_ADVERTISING_COST' }
| { type: 'TOGGLE_FLOATING_PANEL' }
| { type: 'SET_FLOATING_PANEL'; payload: { visible: boolean } }
| { type: 'GET_FLOATING_PANEL_STATE' }
| { type: 'PING' };
export type ExtensionResponse =
| { ok: true; data: PageContext }
| { ok: true; data: AdvertisingCostBatch }
| { ok: true; data: { pong: true } }
| { ok: true; data: { visible: boolean } }
| { ok: false; code: string; message: string };
const MESSAGE_TYPES = new Set([
'GET_PAGE_CONTEXT',
'PARSE_ADVERTISING_COST',
'TOGGLE_FLOATING_PANEL',
'SET_FLOATING_PANEL',
'GET_FLOATING_PANEL_STATE',
'PING',
]);
export function isExtensionMessage(value: unknown): value is ExtensionMessage {
if (!value || typeof value !== 'object') return false;
const type = (value as { type?: unknown }).type;
return (
type === 'GET_PAGE_CONTEXT' ||
type === 'PARSE_ADVERTISING_COST' ||
type === 'PING'
);
return typeof type === 'string' && MESSAGE_TYPES.has(type);
}
+10 -2
View File
@@ -2,7 +2,10 @@
export type PlatformType = 'pdd' | 'taobao' | 'jd' | 'mock' | 'unknown';
/** 单条推广费:日期来自页面数据本身,不由用户手选 */
export interface AdvertisingCostItem {
/** 统计日期 YYYY-MM-DD(每条各自一份) */
feeDate: string;
goodsId: string;
feeAmount: number;
metadata?: Record<string, unknown>;
@@ -11,12 +14,11 @@ export interface AdvertisingCostItem {
/**
* 一次读取/同步批次。
* channelShopId = BI channel_pdd_shop.id(不是 mallId)
* feeDate = Popup 所选日期 YYYY-MM-DD
* 日期在 items[].feeDate,由 Adapter 从页面解析
*/
export interface AdvertisingCostBatch {
platform: PlatformType;
channelShopId: number;
feeDate: string;
items: AdvertisingCostItem[];
source: 'browser-extension';
importedAt: string;
@@ -28,4 +30,10 @@ export interface PageContext {
platform: PlatformType;
ready: boolean;
message?: string;
/** 页面展示的店铺名(用于匹配 BI channelShop) */
mallName?: string;
/** 单日模式下的统计日期 YYYY-MM-DD */
feeDate?: string;
/** single=可同步;range=范围报表不记录 */
dateMode?: 'single' | 'range' | 'unknown';
}