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
+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' });
}