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
@@ -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,