feat: 新增浏览器插件

This commit is contained in:
2026-08-16 16:45:24 +08:00
parent 2f32d955eb
commit f209d93733
38 changed files with 4727 additions and 0 deletions
+317
View File
@@ -0,0 +1,317 @@
<script setup lang="ts">
import { computed, 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 { toUserMessage } from '@/shared/errors';
import { getSettings, saveSettings } from '@/storage/settings';
import type { AdvertisingCostBatch, PageContext } from '@/types/advertisingCost';
import { fetchPageContext, parseAdvertisingCostFromPage } 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 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 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;
apiKey.value = settings.apiKey;
channelShopId.value = settings.channelShopId;
channelShopName.value = settings.channelShopName ?? '';
}
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();
} catch (error) {
pageContext.value = null;
errorText.value = toUserMessage(error);
}
}
async function loadShops() {
shopsLoading.value = true;
errorText.value = '';
try {
await persistSettingsQuiet();
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 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) {
channelShopId.value = undefined;
channelShopName.value = '';
return;
}
channelShopId.value = value;
const hit = shops.value.find((s) => s.id === value);
channelShopName.value = hit?.mallName ?? '';
void persistSettingsQuiet();
}
async function handleRead() {
busy.value = true;
errorText.value = '';
syncResultText.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)';
} 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;
}
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}` : '');
} catch (error) {
statusText.value = '同步失败';
errorText.value = toUserMessage(error);
} finally {
busy.value = false;
}
}
onMounted(async () => {
await loadLocalSettings();
await refreshPageContext();
});
</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>
</header>
<section
v-if="settingsOpen"
class="space-y-2 rounded-lg border border-slate-200 bg-white p-3"
>
<label class="block text-xs text-slate-600">
Open API 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"
placeholder="https://host/api"
/>
</label>
<label class="block text-xs text-slate-600">
Open API Key
<input
v-model="apiKey"
type="password"
class="mt-1 w-full rounded-md border border-slate-200 px-2 py-1.5 text-sm outline-none focus:border-slate-400"
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>
<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>
<button
class="text-xs text-sky-700 hover:underline"
type="button"
:disabled="shopsLoading || busy"
@click="loadShops"
>
{{ shopsLoading ? '加载中…' : '拉取列表' }}
</button>
</div>
<select
class="w-full rounded-md border border-slate-200 px-2 py-1.5 text-sm"
:value="channelShopId ?? ''"
@change="onShopChange"
>
<option value="">请选择 channelShopId</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>)
</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"
type="button"
:disabled="busy"
@click="handleRead"
>
读取数据
</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>
<p v-if="errorText" class="text-xs text-rose-600">{{ errorText }}</p>
</div>
</template>
+12
View File
@@ -0,0 +1,12 @@
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>ECBI 数据同步</title>
</head>
<body class="bg-slate-50 text-slate-900">
<div id="app"></div>
<script type="module" src="./main.ts"></script>
</body>
</html>
+6
View File
@@ -0,0 +1,6 @@
import { createApp } from 'vue';
import App from './App.vue';
import './styles.css';
createApp(App).mount('#app');
+49
View File
@@ -0,0 +1,49 @@
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 });
const tabId = tabs[0]?.id;
if (tabId == null) {
throw new ExtensionError('NO_ACTIVE_TAB', '未找到当前标签页');
}
return tabId;
}
async function sendToActiveTab<T>(message: ExtensionMessage): Promise<T> {
const tabId = await getActiveTabId();
let response: ExtensionResponse | undefined;
try {
response = (await chrome.tabs.sendMessage(tabId, message)) as ExtensionResponse;
} catch {
throw new ExtensionError(
'PAGE_NOT_READY',
'无法连接页面脚本。请刷新目标页面后重试(需已注入 Content Script)。',
);
}
if (!response) {
throw new ExtensionError('PAGE_NOT_READY', '页面无响应');
}
if (!response.ok) {
throw new ExtensionError(
(response.code as never) || 'UNKNOWN',
response.message || '页面处理失败',
);
}
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 },
});
}
+10
View File
@@ -0,0 +1,10 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
html,
body {
margin: 0;
min-width: 360px;
min-height: 480px;
}