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
+64
View File
@@ -0,0 +1,64 @@
import { ExtensionError } from '@/shared/errors';
import { getSettings } from '@/storage/settings';
export interface ApiResponseBody<T> {
code: number;
message: string;
data: T;
}
export async function openApiRequest<T>(
path: string,
init: RequestInit = {},
): Promise<T> {
const settings = await getSettings();
if (!settings.apiBaseUrl) {
throw new ExtensionError('CONFIG_MISSING', '请先配置 BI Open API Base URL');
}
if (!settings.apiKey) {
throw new ExtensionError('CONFIG_MISSING', '请先配置 BI Open API Key');
}
const url = `${settings.apiBaseUrl}${path.startsWith('/') ? path : `/${path}`}`;
const headers = new Headers(init.headers);
headers.set('Content-Type', 'application/json');
headers.set('X-Api-Key', settings.apiKey);
let response: Response;
try {
response = await fetch(url, {
...init,
headers,
});
} catch {
throw new ExtensionError('NETWORK_ERROR', '网络异常,无法连接 BI Open API');
}
if (response.status === 401) {
throw new ExtensionError('AUTH_FAILED', 'API Key 无效、过期或 IP 不在白名单');
}
let body: ApiResponseBody<T>;
try {
body = (await response.json()) as ApiResponseBody<T>;
} catch {
throw new ExtensionError('API_REQUEST_FAILED', `请求失败(HTTP ${response.status})`);
}
if (!response.ok) {
throw new ExtensionError(
'API_REQUEST_FAILED',
body.message || `请求失败(HTTP ${response.status})`,
);
}
// 后端业务码:0 / 200 视为成功(兼容)
if (body.code !== 0 && body.code !== 200) {
throw new ExtensionError(
'API_BUSINESS_ERROR',
body.message || `业务错误(code=${body.code})`,
);
}
return body.data;
}
@@ -0,0 +1,55 @@
import type { AdvertisingCostBatch } from '@/types/advertisingCost';
import { openApiRequest } from '@/api/client';
import { OPEN_API_PATHS } from '@/shared/constants';
export interface BatchImportPddGoodsAdFeeItem {
channelShopId: number;
feeDate: string;
goodsId: string;
feeAmount: number;
}
export interface BatchImportPddGoodsAdFeeRequest {
items: BatchImportPddGoodsAdFeeItem[];
}
export interface BatchImportPddGoodsAdFeeResult {
totalCount: number;
successCount: number;
failureCount: number;
successIds?: number[];
failureRecords?: Array<{
rowNumber?: number;
channelShopId?: number;
goodsId?: string;
failureReason?: string;
}>;
}
/** 插件统一模型 → 后端 batch-import 入参 */
export function toBatchImportRequest(
batch: AdvertisingCostBatch,
): BatchImportPddGoodsAdFeeRequest {
return {
items: batch.items.map((item) => ({
channelShopId: batch.channelShopId,
feeDate: batch.feeDate,
goodsId: item.goodsId,
feeAmount: item.feeAmount,
})),
};
}
export async function batchImportPddGoodsAdFee(
batch: AdvertisingCostBatch,
): Promise<BatchImportPddGoodsAdFeeResult> {
const body = toBatchImportRequest(batch);
return openApiRequest<BatchImportPddGoodsAdFeeResult>(
OPEN_API_PATHS.pddGoodsAdFeeBatchImport,
{
method: 'POST',
body: JSON.stringify(body),
},
);
}
+35
View File
@@ -0,0 +1,35 @@
import { openApiRequest } from '@/api/client';
import { OPEN_API_PATHS } from '@/shared/constants';
export interface PageQueryDTO<TFilters> {
page: number;
pageSize: number;
filters?: TFilters;
}
export interface PageResultVO<T> {
records: T[];
total: number;
page?: number;
pageSize?: number;
}
export interface PddChannelShop {
id: number;
mallId?: number;
mallName?: string;
logo?: string;
}
export interface PddShopFilters {
mallName?: string;
}
export async function listPddChannelShops(
query: PageQueryDTO<PddShopFilters> = { page: 1, pageSize: 50 },
): Promise<PageResultVO<PddChannelShop>> {
return openApiRequest<PageResultVO<PddChannelShop>>(OPEN_API_PATHS.pddShopList, {
method: 'POST',
body: JSON.stringify(query),
});
}
+6
View File
@@ -0,0 +1,6 @@
export type {
BatchImportPddGoodsAdFeeItem,
BatchImportPddGoodsAdFeeRequest,
BatchImportPddGoodsAdFeeResult,
} from './open/pddGoodsAdFee';
export type { PddChannelShop, PageQueryDTO, PageResultVO } from './open/pddShop';
+15
View File
@@ -0,0 +1,15 @@
/**
* Background Service Worker:生命周期与消息转发占位。
* 第一阶段业务请求由 Popup 直接发起;Content 由 Manifest 注入。
*/
chrome.runtime.onInstalled.addListener(() => {
console.info('[ecbi-extension] installed');
});
chrome.runtime.onMessage.addListener((message, _sender, sendResponse) => {
if (message?.type === 'BACKGROUND_PING') {
sendResponse({ ok: true, data: { pong: true } });
return true;
}
return false;
});
+59
View File
@@ -0,0 +1,59 @@
import { resolveAdapter } from '@/platform/core/PlatformDetector';
import { ExtensionError } from '@/shared/errors';
import {
isExtensionMessage,
type ExtensionMessage,
type ExtensionResponse,
} from '@/shared/messages';
import type { AdvertisingCostBatch } from '@/types/advertisingCost';
async function handleMessage(message: ExtensionMessage): Promise<ExtensionResponse> {
const adapter = resolveAdapter(location.href);
switch (message.type) {
case 'PING':
return { ok: true, data: { pong: true } };
case 'GET_PAGE_CONTEXT': {
const data = await adapter.getPageContext();
return { ok: true, data };
}
case 'PARSE_ADVERTISING_COST': {
const parsed = await adapter.parseAdvertisingCost(message.payload.feeDate);
// channelShopId 由 Popup 选择后填入
const data: AdvertisingCostBatch = {
...parsed,
channelShopId: 0,
};
return { ok: true, data };
}
default:
return {
ok: false,
code: 'UNKNOWN',
message: '未知消息类型',
};
}
}
chrome.runtime.onMessage.addListener((message, _sender, sendResponse) => {
if (!isExtensionMessage(message)) {
return false;
}
void handleMessage(message)
.then((result) => sendResponse(result))
.catch((error: unknown) => {
const err =
error instanceof ExtensionError
? error
: new ExtensionError('UNKNOWN', 'Content Script 处理失败');
const response: ExtensionResponse = {
ok: false,
code: err.code,
message: err.message,
};
sendResponse(response);
});
return true;
});
+7
View File
@@ -0,0 +1,7 @@
/// <reference types="vite/client" />
declare module '*.vue' {
import type { DefineComponent } from 'vue';
const component: DefineComponent<object, object, unknown>;
export default component;
}
@@ -0,0 +1,12 @@
import type {
AdvertisingCostBatch,
PageContext,
PlatformType,
} from '@/types/advertisingCost';
export interface PlatformAdapter {
readonly platform: PlatformType;
canHandle(url: string): boolean;
getPageContext(): Promise<PageContext>;
parseAdvertisingCost(feeDate: string): Promise<Omit<AdvertisingCostBatch, 'channelShopId'>>;
}
@@ -0,0 +1,24 @@
import type { PlatformType } from '@/types/advertisingCost';
import type { PlatformAdapter } from './PlatformAdapter';
import { MockPlatformAdapter } from '../mock/MockPlatformAdapter';
const adapters: PlatformAdapter[] = [new MockPlatformAdapter()];
export function detectPlatform(url: string): PlatformType {
const adapter = adapters.find((item) => item.canHandle(url));
return adapter?.platform ?? 'unknown';
}
export function resolveAdapter(url: string): PlatformAdapter {
const matched = adapters.find((item) => item.canHandle(url));
if (matched) {
return matched;
}
// 第一阶段:未识别平台时回退 Mock,保证链路可跑通
return adapters[0]!;
}
export function listAdapters(): PlatformAdapter[] {
return [...adapters];
}
@@ -0,0 +1,2 @@
export type { PlatformAdapter } from './PlatformAdapter';
export { detectPlatform, listAdapters, resolveAdapter } from './PlatformDetector';
@@ -0,0 +1,42 @@
import type { PlatformAdapter } from '@/platform/core/PlatformAdapter';
import type { AdvertisingCostBatch, PageContext } from '@/types/advertisingCost';
/**
* 第一阶段 Mock Adapter:不读真实 DOM,返回固定样例数据。
*/
export class MockPlatformAdapter implements PlatformAdapter {
readonly platform = 'mock' as const;
canHandle(_url: string): boolean {
// 未接入真实平台前,任意页面均可由 Mock 处理
return true;
}
async getPageContext(): Promise<PageContext> {
return {
url: typeof location !== 'undefined' ? location.href : '',
title: typeof document !== 'undefined' ? document.title : '',
platform: 'mock',
ready: true,
message: '当前为 Mock Adapter(未解析真实平台页面)',
};
}
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 },
];
return {
platform: 'mock',
feeDate,
items,
source: 'browser-extension',
importedAt: new Date().toISOString(),
};
}
}
+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;
}
+11
View File
@@ -0,0 +1,11 @@
export const EXTENSION_NAME = 'ECBI 数据同步';
export const OPEN_API_PATHS = {
pddShopList: '/open/v1/channel/pdd/shop/list',
pddGoodsAdFeeBatchImport: '/open/v1/channel/pdd/goods/adfee/batch-import',
} as const;
export const OPEN_SCOPES = {
pddShopRead: 'open:scope:pdd_shop:read',
pddGoodsAdFeeImport: 'open:scope:pdd_goods_ad_fee:import',
} as const;
+32
View File
@@ -0,0 +1,32 @@
export type ExtensionErrorCode =
| 'PLATFORM_NOT_SUPPORTED'
| 'PAGE_NOT_READY'
| 'DATA_PARSE_FAILED'
| 'INVALID_DATA'
| 'AUTH_FAILED'
| 'API_REQUEST_FAILED'
| 'API_BUSINESS_ERROR'
| 'NETWORK_ERROR'
| 'CONFIG_MISSING'
| 'NO_ACTIVE_TAB'
| 'UNKNOWN';
export class ExtensionError extends Error {
readonly code: ExtensionErrorCode;
constructor(code: ExtensionErrorCode, message: string) {
super(message);
this.name = 'ExtensionError';
this.code = code;
}
}
export function toUserMessage(error: unknown): string {
if (error instanceof ExtensionError) {
return error.message;
}
if (error instanceof Error && error.message) {
return error.message;
}
return '发生未知错误,请稍后重试';
}
+22
View File
@@ -0,0 +1,22 @@
import type { AdvertisingCostBatch, PageContext } from '@/types/advertisingCost';
export type ExtensionMessage =
| { type: 'GET_PAGE_CONTEXT' }
| { type: 'PARSE_ADVERTISING_COST'; payload: { feeDate: string } }
| { type: 'PING' };
export type ExtensionResponse =
| { ok: true; data: PageContext }
| { ok: true; data: AdvertisingCostBatch }
| { ok: true; data: { pong: true } }
| { ok: false; code: string; message: string };
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'
);
}
+40
View File
@@ -0,0 +1,40 @@
export interface ExtensionSettings {
/** 例:https://host/api (不要末尾斜杠) */
apiBaseUrl: string;
/** Open API Key(非 JWT) */
apiKey: string;
/** 记住的渠道店铺 */
channelShopId?: number;
channelShopName?: string;
}
const STORAGE_KEY = 'ecbi.extension.settings';
const DEFAULT_SETTINGS: ExtensionSettings = {
apiBaseUrl: '',
apiKey: '',
};
export async function getSettings(): Promise<ExtensionSettings> {
const result = await chrome.storage.local.get(STORAGE_KEY);
const raw = result[STORAGE_KEY] as Partial<ExtensionSettings> | undefined;
return {
...DEFAULT_SETTINGS,
...raw,
apiBaseUrl: (raw?.apiBaseUrl ?? '').replace(/\/+$/, ''),
apiKey: raw?.apiKey ?? '',
};
}
export async function saveSettings(
patch: Partial<ExtensionSettings>,
): Promise<ExtensionSettings> {
const current = await getSettings();
const next: ExtensionSettings = {
...current,
...patch,
apiBaseUrl: (patch.apiBaseUrl ?? current.apiBaseUrl).replace(/\/+$/, ''),
};
await chrome.storage.local.set({ [STORAGE_KEY]: next });
return next;
}
+1
View File
@@ -0,0 +1 @@
export type { ExtensionSettings } from './settings';
@@ -0,0 +1,31 @@
/** 插件侧统一广告费模型(平台无关) */
export type PlatformType = 'pdd' | 'taobao' | 'jd' | 'mock' | 'unknown';
export interface AdvertisingCostItem {
goodsId: string;
feeAmount: number;
metadata?: Record<string, unknown>;
}
/**
* 一次读取/同步批次。
* channelShopId = BI channel_pdd_shop.id(不是 mallId)
* feeDate = Popup 所选日期 YYYY-MM-DD
*/
export interface AdvertisingCostBatch {
platform: PlatformType;
channelShopId: number;
feeDate: string;
items: AdvertisingCostItem[];
source: 'browser-extension';
importedAt: string;
}
export interface PageContext {
url: string;
title: string;
platform: PlatformType;
ready: boolean;
message?: string;
}