refacor: 重构目录架构

This commit is contained in:
2026-09-16 22:43:21 +08:00
parent b37cdb0d54
commit 2754ed1e45
2762 changed files with 0 additions and 1529 deletions
+86
View File
@@ -0,0 +1,86 @@
import { ExtensionError } from '@/shared/errors';
import { executeOpenApiFetch } from './openApiFetch';
export type { ApiResponseBody } from './openApiFetch';
export type OpenApiRequestFn = <T>(path: string, init?: RequestInit) => Promise<T>;
let openApiOverride: OpenApiRequestFn | null = null;
/** 功能包在 main world 安装桥接实现时调用 */
export function setOpenApiRequestOverride(fn: OpenApiRequestFn | null): void {
openApiOverride = fn;
}
type OpenApiBgPayload = {
path: string;
method?: string;
body?: string;
headers?: Record<string, string>;
};
type OpenApiBgResponse =
| { ok: true; data: unknown }
| { ok: false; code: string; message: string };
function canUseBackgroundProxy(): boolean {
return typeof chrome !== 'undefined' && Boolean(chrome.runtime?.id);
}
async function requestViaBackground<T>(
path: string,
init: RequestInit = {},
): Promise<T> {
const headers: Record<string, string> = {};
if (init.headers) {
new Headers(init.headers).forEach((value, key) => {
headers[key] = value;
});
}
const payload: OpenApiBgPayload = {
path,
method: init.method,
body: typeof init.body === 'string' ? init.body : undefined,
headers,
};
let response: OpenApiBgResponse | undefined;
try {
response = (await chrome.runtime.sendMessage({
type: 'OPEN_API_REQUEST',
payload,
})) as OpenApiBgResponse | undefined;
} catch {
throw new ExtensionError('NETWORK_ERROR', '无法连接扩展后台,请重载扩展后重试');
}
if (!response) {
throw new ExtensionError('NETWORK_ERROR', '扩展后台无响应');
}
if (!response.ok) {
throw new ExtensionError(
(response.code as ExtensionError['code']) || 'API_REQUEST_FAILED',
response.message || '请求失败',
);
}
return response.data as T;
}
/**
* Open API 统一入口。
* Content Script 在 HTTPS 第三方页内不能直连 HTTP 本地 API(混合内容/CORS),
* 默认经 Background 代发。
*/
export async function openApiRequest<T>(
path: string,
init: RequestInit = {},
): Promise<T> {
if (openApiOverride) {
return openApiOverride<T>(path, init);
}
if (canUseBackgroundProxy()) {
return requestViaBackground<T>(path, init);
}
return executeOpenApiFetch<T>(path, init);
}
@@ -0,0 +1,45 @@
import { openApiRequest } from '@/api/client';
import { OPEN_API_PATHS } from '@/shared/constants';
import type { ExtensionFeatureItem, ExtensionFeatureManifest } from '@/features/runtime/types';
export interface FeatureScriptPayload {
featureId: string;
version?: string;
sha256?: string;
content: string;
}
export async function fetchFeatureManifest(): Promise<ExtensionFeatureManifest> {
return openApiRequest<ExtensionFeatureManifest>(OPEN_API_PATHS.extensionFeatureList, {
method: 'GET',
});
}
export async function fetchFeatureScript(featureId: string): Promise<FeatureScriptPayload> {
return openApiRequest<FeatureScriptPayload>(
`${OPEN_API_PATHS.extensionFeatureScript}/${encodeURIComponent(featureId)}/script`,
{ method: 'GET' },
);
}
/** 下载远程脚本并可选校验 sha256(与静态 manifest 一致) */
export async function downloadAndVerifyFeature(
item: ExtensionFeatureItem,
): Promise<{ code: string; verified: boolean; remoteVersion?: string }> {
const payload = await fetchFeatureScript(item.id);
const expected = (item.sha256 || payload.sha256 || '').toLowerCase();
if (expected) {
const hash = await sha256Hex(payload.content);
if (hash !== expected) {
throw new Error(`功能脚本校验失败:${item.id}(sha256 不匹配)`);
}
return { code: payload.content, verified: true, remoteVersion: payload.version };
}
return { code: payload.content, verified: false, remoteVersion: payload.version };
}
async function sha256Hex(text: string): Promise<string> {
const data = new TextEncoder().encode(text);
const digest = await crypto.subtle.digest('SHA-256', data);
return [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, '0')).join('');
}
@@ -0,0 +1,101 @@
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[];
}
/** 导入任务摘要(创建立即返回 pending,需轮询至终态) */
export interface PddGoodsAdFeeImportTask {
id: number;
companyId?: number;
channelShopId: number;
status: 'pending' | 'processing' | 'success' | 'partial' | 'failed' | string;
totalCount: number;
successCount: number;
failCount: number;
authExpired?: number;
message?: string | null;
startedAt?: string | null;
finishedAt?: string | null;
createTime?: string;
}
const TERMINAL_STATUS = new Set(['success', 'partial', 'failed']);
const POLL_INTERVAL_MS = 2500;
const POLL_TIMEOUT_MS = 30 * 60 * 1000;
/** 插件统一模型 → 后端 batch-import 入参(日期取自每条 item;金额须大于 0) */
export function toBatchImportRequest(
batch: AdvertisingCostBatch,
): BatchImportPddGoodsAdFeeRequest {
return {
items: batch.items
.filter((item) => Number(item.feeAmount) > 0)
.map((item) => ({
channelShopId: batch.channelShopId,
feeDate: item.feeDate,
goodsId: item.goodsId,
feeAmount: item.feeAmount,
})),
};
}
export async function getPddGoodsAdFeeImportTask(
taskId: number,
): Promise<PddGoodsAdFeeImportTask> {
return openApiRequest<PddGoodsAdFeeImportTask>(
`${OPEN_API_PATHS.pddGoodsAdFeeImportTask}/${taskId}`,
);
}
export async function waitForPddGoodsAdFeeImportTask(
taskId: number,
onProgress?: (task: PddGoodsAdFeeImportTask) => void,
): Promise<PddGoodsAdFeeImportTask> {
const deadline = Date.now() + POLL_TIMEOUT_MS;
while (Date.now() < deadline) {
const task = await getPddGoodsAdFeeImportTask(taskId);
onProgress?.(task);
if (TERMINAL_STATUS.has(task.status)) {
return task;
}
await sleep(POLL_INTERVAL_MS);
}
throw new Error('导入超时,请稍后在后台查看任务进度');
}
/** 提交导入任务并等到处理结束 */
export async function batchImportPddGoodsAdFee(
batch: AdvertisingCostBatch,
onProgress?: (task: PddGoodsAdFeeImportTask) => void,
): Promise<PddGoodsAdFeeImportTask> {
const body = toBatchImportRequest(batch);
if (!body.items.length) {
throw new Error('没有可传入的记录(推广费须大于 0)');
}
const created = await openApiRequest<PddGoodsAdFeeImportTask>(
OPEN_API_PATHS.pddGoodsAdFeeBatchImport,
{
method: 'POST',
body: JSON.stringify(body),
},
);
onProgress?.(created);
return waitForPddGoodsAdFeeImportTask(created.id, onProgress);
}
function sleep(ms: number): Promise<void> {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}
@@ -0,0 +1,47 @@
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 matchPddChannelShopByMallName(
mallName: string,
): Promise<PddChannelShop | null> {
const name = mallName.trim();
if (!name) return null;
const qs = new URLSearchParams({ mallName: name });
return openApiRequest<PddChannelShop | null>(
`${OPEN_API_PATHS.pddShopMatchByName}?${qs.toString()}`,
{ method: 'GET' },
);
}
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),
});
}
@@ -0,0 +1,64 @@
import { ExtensionError } from '@/shared/errors';
import { getSettings } from '@/storage/settings';
export interface ApiResponseBody<T> {
code: number;
message: string;
data: T;
}
/** 在扩展上下文(Background / Popup)内直连 Open API */
export async function executeOpenApiFetch<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})`,
);
}
if (body.code !== 0 && body.code !== 200) {
throw new ExtensionError(
'API_BUSINESS_ERROR',
body.message || `业务错误(code=${body.code})`,
);
}
return body.data;
}
+6
View File
@@ -0,0 +1,6 @@
export type {
BatchImportPddGoodsAdFeeItem,
BatchImportPddGoodsAdFeeRequest,
PddGoodsAdFeeImportTask,
} from './open/pddGoodsAdFee';
export type { PddChannelShop, PageQueryDTO, PageResultVO } from './open/pddShop';
@@ -0,0 +1,138 @@
/**
* Background:向页面 MAIN world 注入远程功能脚本并调用 mount/unmount。
* chrome.scripting + world:MAIN 可绕过页面 CSP(inline script 会被拦)。
* Open API 亦在此代发,避免 HTTPS 页面直连 HTTP 本地服务被混合内容拦截。
*/
import { executeOpenApiFetch } from '@/api/openApiFetch';
import { ExtensionError } from '@/shared/errors';
type InjectMessage = {
type: 'INJECT_MAIN_SCRIPT';
payload: { code: string };
};
type CallMessage = {
type: 'CALL_MAIN_FEATURE';
payload: { featureId: string; action: 'mount' | 'unmount' };
};
type OpenApiMessage = {
type: 'OPEN_API_REQUEST';
payload: {
path: string;
method?: string;
body?: string;
headers?: Record<string, string>;
};
};
type BgMessage =
| InjectMessage
| CallMessage
| OpenApiMessage
| { type: 'BACKGROUND_PING' };
chrome.runtime.onInstalled.addListener(() => {
console.info('[ecbi-extension] installed');
});
chrome.runtime.onMessage.addListener((message: BgMessage, sender, sendResponse) => {
if (message?.type === 'BACKGROUND_PING') {
sendResponse({ ok: true, data: { pong: true } });
return true;
}
if (message?.type === 'OPEN_API_REQUEST') {
const { path, method, body, headers } = message.payload;
void executeOpenApiFetch(path, { method, body, headers })
.then((data) => sendResponse({ ok: true, data }))
.catch((error: unknown) => {
const err =
error instanceof ExtensionError
? error
: new ExtensionError(
'UNKNOWN',
error instanceof Error ? error.message : 'Open API 请求失败',
);
sendResponse({ ok: false, code: err.code, message: err.message });
});
return true;
}
const tabId = sender.tab?.id;
if (tabId == null) {
sendResponse({ ok: false, message: '缺少 tabId(仅 Content Script 可请求注入)' });
return true;
}
if (message?.type === 'INJECT_MAIN_SCRIPT') {
void chrome.scripting
.executeScript({
target: { tabId },
world: 'MAIN',
func: (source: string) => {
// 扩展注入的 MAIN world 函数内执行,不受页面 CSP 限制
const run = new Function(source);
run();
},
args: [message.payload.code],
})
.then(() => sendResponse({ ok: true }))
.catch((error: unknown) => {
sendResponse({
ok: false,
message: error instanceof Error ? error.message : '注入脚本失败',
});
});
return true;
}
if (message?.type === 'CALL_MAIN_FEATURE') {
const { featureId, action } = message.payload;
void chrome.scripting
.executeScript({
target: { tabId },
world: 'MAIN',
func: async (id: string, act: 'mount' | 'unmount') => {
const bag = (
globalThis as typeof globalThis & {
__ECBI_FEATURES__?: Record<
string,
{
mount?: () => void | Promise<void>;
unmount?: () => void | Promise<void>;
}
>;
}
).__ECBI_FEATURES__;
const mod = bag?.[id];
if (!mod) {
throw new Error(`功能未注册:${id}`);
}
if (act === 'mount') {
if (typeof mod.mount !== 'function') {
throw new Error(`功能无 mount:${id}`);
}
await mod.mount();
return;
}
if (typeof mod.unmount !== 'function') {
throw new Error(`功能无 unmount:${id}`);
}
await mod.unmount();
},
args: [featureId, action],
})
.then(() => sendResponse({ ok: true }))
.catch((error: unknown) => {
sendResponse({
ok: false,
message: error instanceof Error ? error.message : '调用功能失败',
});
});
return true;
}
return false;
});
@@ -0,0 +1,100 @@
<script setup lang="ts">
import { computed } from 'vue';
import type { AdvertisingCostItem } from '@/types/advertisingCost';
import {
buildHeatmapWeeks,
cellTitle,
monthLabelsForWeeks,
summarizeByDate,
type HeatDayCell,
} from '@/shared/dateHeatmap';
const props = defineProps<{
items: AdvertisingCostItem[];
pageDate?: string;
selectedDate?: string;
}>();
const emit = defineEmits<{
select: [date: string | undefined];
}>();
const WEEKDAY_LABELS = ['', '一', '', '三', '', '五', ''];
const stats = computed(() => summarizeByDate(props.items));
const weeks = computed(() =>
buildHeatmapWeeks({
weeks: 13,
stats: stats.value,
pageDate: props.pageDate,
}),
);
const monthLabelMap = computed(() => {
const map = new Map<number, string>();
for (const item of monthLabelsForWeeks(weeks.value)) {
map.set(item.index, item.label);
}
return map;
});
function onCellClick(cell: HeatDayCell) {
if (!cell.inRange || !cell.stat) return;
emit('select', props.selectedDate === cell.date ? undefined : cell.date);
}
function cellClass(cell: HeatDayCell): string[] {
const classes = [`ecbi-heat-l${cell.level}`];
if (!cell.inRange) classes.push('ecbi-heat-out');
if (cell.isToday) classes.push('ecbi-heat-today');
if (cell.isPageDate) classes.push('ecbi-heat-page');
if (props.selectedDate === cell.date) classes.push('ecbi-heat-selected');
if (cell.stat) classes.push('ecbi-heat-lit');
return classes;
}
</script>
<template>
<div class="ecbi-heat">
<div class="ecbi-heat-head">
<span class="ecbi-heat-title">读取日历</span>
<span class="ecbi-muted">点亮=已读 · 点击筛选当日</span>
</div>
<div class="ecbi-heat-body">
<div class="ecbi-heat-dows">
<span class="ecbi-heat-month-spacer" />
<span v-for="(label, i) in WEEKDAY_LABELS" :key="i" class="ecbi-heat-dow">{{ label }}</span>
</div>
<div class="ecbi-heat-weeks">
<div v-for="(week, wi) in weeks" :key="wi" class="ecbi-heat-week">
<span class="ecbi-heat-month">{{ monthLabelMap.get(wi) || '' }}</span>
<button
v-for="cell in week"
:key="cell.date"
type="button"
class="ecbi-heat-cell"
:class="cellClass(cell)"
:title="cellTitle(cell)"
:disabled="!cell.inRange || !cell.stat"
@click="onCellClick(cell)"
/>
</div>
</div>
</div>
<div class="ecbi-heat-legend">
<span class="ecbi-muted">少</span>
<span class="ecbi-heat-cell ecbi-heat-l0" />
<span class="ecbi-heat-cell ecbi-heat-l1" />
<span class="ecbi-heat-cell ecbi-heat-l2" />
<span class="ecbi-heat-cell ecbi-heat-l3" />
<span class="ecbi-heat-cell ecbi-heat-l4" />
<span class="ecbi-muted">多</span>
<span class="ecbi-heat-gap" />
<span class="ecbi-heat-cell ecbi-heat-l0 ecbi-heat-page" />
<span class="ecbi-muted">当前页日期</span>
</div>
</div>
</template>
@@ -0,0 +1,641 @@
<script setup lang="ts">
import { computed, onMounted, onUnmounted, ref } from 'vue';
import { batchImportPddGoodsAdFee } from '@/api/open/pddGoodsAdFee';
import DateHeatmap from './DateHeatmap.vue';
import { resolveAdapter } from '@/platform/core/PlatformDetector';
import {
MAX_AUTO_COLLECT_DAYS,
listDatesInclusive,
runAutoCollectByDates,
} from '@/platform/pdd/autoCollectDates';
import { matchChannelShopByMallName, shopAuthorizeHint } 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 channelShopId = ref<number | undefined>(undefined);
const channelShopName = ref('');
const pageMallName = ref('');
const shopMatching = ref(false);
const shopMatched = ref(false);
const pageContext = ref<PageContext | null>(null);
const batch = ref<AdvertisingCostBatch | null>(null);
const filterDate = ref<string | undefined>(undefined);
const statusText = ref('等待读取');
const errorText = ref('');
const syncResultText = ref('');
const busy = ref(false);
const autoStartDate = ref('');
const autoEndDate = ref('');
const autoSkipRead = ref(true);
const autoRunning = ref(false);
let autoAbort: AbortController | null = null;
/** 自动切日期期间禁止 URL 轮询触发二次读取 */
let suppressUrlAutoRead = 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 : '';
function todayIso(): string {
const now = new Date();
const y = now.getFullYear();
const m = String(now.getMonth() + 1).padStart(2, '0');
const d = String(now.getDate()).padStart(2, '0');
return `${y}-${m}-${d}`;
}
function shiftIso(iso: string, deltaDays: number): string {
const dt = new Date(`${iso}T00:00:00`);
dt.setDate(dt.getDate() + deltaDays);
const y = dt.getFullYear();
const m = String(dt.getMonth() + 1).padStart(2, '0');
const d = String(dt.getDate()).padStart(2, '0');
return `${y}-${m}-${d}`;
}
function initAutoDateRange(preferredEnd?: string) {
const end = preferredEnd && /^\d{4}-\d{2}-\d{2}$/.test(preferredEnd) ? preferredEnd : todayIso();
autoEndDate.value = end;
autoStartDate.value = shiftIso(end, -(Math.min(6, MAX_AUTO_COLLECT_DAYS - 1)));
}
const totalFee = computed(() =>
(batch.value?.items ?? []).reduce((sum, item) => sum + Number(item.feeAmount || 0), 0),
);
const itemCount = computed(() => batch.value?.items.length ?? 0);
const dateCount = computed(() => listFeeDates(batch.value?.items ?? []).length);
const previewItems = computed(() => {
const items = batch.value?.items ?? [];
if (!filterDate.value) return items;
return items.filter((item) => item.feeDate === filterDate.value);
});
const previewFee = computed(() =>
previewItems.value.reduce((sum, item) => sum + Number(item.feeAmount || 0), 0),
);
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} 条`;
});
const previewLabel = computed(() => {
if (!filterDate.value) return '全部已读';
return filterDate.value;
});
const autoDaySpanLabel = computed(() => {
try {
if (!autoStartDate.value || !autoEndDate.value) return `最多 ${MAX_AUTO_COLLECT_DAYS} 天`;
const n = listDatesInclusive(autoStartDate.value, autoEndDate.value).length;
return `${n} 天(上限 ${MAX_AUTO_COLLECT_DAYS})`;
} catch (error) {
return error instanceof Error ? error.message : '日期无效';
}
});
const shopTagLabel = computed(() => {
if (shopMatching.value) return '匹配中';
if (shopMatched.value && channelShopId.value != null) return '已授权';
if (pageMallName.value.trim()) return '未授权';
return '未识别';
});
const shopTagClass = computed(() => {
if (shopMatching.value) return 'ecbi-shop-tag--loading';
if (shopMatched.value && channelShopId.value != null) return 'ecbi-shop-tag--ok';
if (pageMallName.value.trim()) return 'ecbi-shop-tag--warn';
return 'ecbi-shop-tag--muted';
});
const headerShopTitle = computed(() => {
const name = pageMallName.value.trim() || '未识别店铺';
return `${name} · ${shopTagLabel.value}`;
});
function onHeatSelect(date: string | undefined) {
filterDate.value = date;
}
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 ?? '';
// 缓存仅作提示;真正读写前会按页面店名再精确校验
shopMatched.value =
channelShopId.value != null &&
Boolean(channelShopName.value) &&
channelShopName.value.trim() === (pageMallName.value || channelShopName.value).trim();
}
async function persistShop() {
await saveSettings({
channelShopId: channelShopId.value,
channelShopName: channelShopName.value,
});
}
async function clearMatchedShop() {
channelShopId.value = undefined;
channelShopName.value = '';
shopMatched.value = false;
await persistShop();
}
/** 仅按页面店铺名完全匹配;失败时提示去系统授权 */
async function matchShopFromPage(options: { quiet?: boolean } = {}): Promise<boolean> {
await refreshContext();
const mallName = pageMallName.value.trim();
if (!mallName) {
await clearMatchedShop();
if (!options.quiet) {
errorText.value = '未识别到页面店铺名,请确认已打开推广总览';
statusText.value = '无法匹配店铺';
}
return false;
}
// 已与当前页店名精确对应则复用
if (
channelShopId.value != null &&
channelShopName.value.trim() === mallName
) {
shopMatched.value = true;
return true;
}
shopMatching.value = true;
if (!options.quiet) errorText.value = '';
try {
const matched = await matchChannelShopByMallName(mallName);
if (!matched) {
await clearMatchedShop();
const hint = shopAuthorizeHint(mallName);
errorText.value = hint;
statusText.value = '店铺未授权';
return false;
}
channelShopId.value = matched.id;
channelShopName.value = matched.mallName ?? mallName;
shopMatched.value = true;
await persistShop();
statusText.value = `已匹配授权店铺:${channelShopName.value}`;
return true;
} catch (error) {
await clearMatchedShop();
errorText.value = toUserMessage(error);
statusText.value = '店铺匹配失败';
return false;
} finally {
shopMatching.value = false;
}
}
async function ensureChannelShop(): Promise<void> {
const ok = await matchShopFromPage();
if (!ok || channelShopId.value == null) {
const mallName = pageMallName.value.trim();
throw new Error(
mallName ? shopAuthorizeHint(mallName) : '未识别到页面店铺名,请确认已打开推广总览',
);
}
}
async function handleRead(fromAuto = false, allowEmpty = 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;
}
await ensureChannelShop();
statusText.value = '检查分页(每页 100)…';
const adapter = resolveAdapter(location.href);
const parsed = await adapter.parseAdvertisingCost({ allowEmpty });
const incomingDate = parsed.items[0]?.feeDate ?? pageContext.value?.feeDate;
const addedOrUpdated = parsed.items.length;
if (parsed.items.length > 0) {
batch.value = {
platform: parsed.platform,
channelShopId: channelShopId.value!,
items: mergeAdvertisingItems(batch.value?.items ?? [], parsed.items),
source: 'browser-extension',
importedAt: new Date().toISOString(),
};
if (incomingDate) filterDate.value = incomingDate;
}
await refreshContext();
const tag = parsed.platform === 'mock' ? 'Mock' : '页面';
if (addedOrUpdated === 0) {
statusText.value = incomingDate
? `${incomingDate} 无推广费数据(已跳过)· 累计 ${dateCount.value} 天`
: '当日无推广费数据';
return;
}
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;
filterDate.value = undefined;
syncResultText.value = '';
errorText.value = '';
statusText.value = '已清空累计数据';
}
function scheduleAutoRead(delayMs = 450) {
if (suppressUrlAutoRead || autoRunning.value) return;
if (readTimer) clearTimeout(readTimer);
readTimer = setTimeout(() => {
void handleRead(true).catch(() => {
// 错误已写入 errorText
});
}, delayMs);
}
async function onPageUrlChanged() {
if (suppressUrlAutoRead || autoRunning.value) {
await refreshContext();
return;
}
await refreshContext();
if (pageContext.value?.dateMode === 'single') {
errorText.value = '';
scheduleAutoRead(1200);
return;
}
if (pageContext.value?.dateMode === 'range') {
statusText.value = '范围视图不追加;已累计数据仍保留';
}
}
async function handleAutoCollect() {
if (autoRunning.value) return;
errorText.value = '';
syncResultText.value = '';
try {
listDatesInclusive(autoStartDate.value, autoEndDate.value);
} catch (error) {
errorText.value = toUserMessage(error);
return;
}
autoAbort = new AbortController();
autoRunning.value = true;
suppressUrlAutoRead = true;
busy.value = true;
if (readTimer) {
clearTimeout(readTimer);
readTimer = null;
}
try {
await ensureChannelShop();
await runAutoCollectByDates({
startDate: autoStartDate.value,
endDate: autoEndDate.value,
skipDates: autoSkipRead.value ? listFeeDates(batch.value?.items ?? []) : [],
signal: autoAbort.signal,
onProgress: (p) => {
statusText.value = p.message;
},
readDay: async () => {
await refreshContext();
await ensureChannelShop();
const adapter = resolveAdapter(location.href);
const parsed = await adapter.parseAdvertisingCost({ allowEmpty: true });
const incomingDate = parsed.items[0]?.feeDate ?? pageContext.value?.feeDate;
if (parsed.items.length > 0) {
batch.value = {
platform: parsed.platform,
channelShopId: channelShopId.value!,
items: mergeAdvertisingItems(batch.value?.items ?? [], parsed.items),
source: 'browser-extension',
importedAt: new Date().toISOString(),
};
if (incomingDate) filterDate.value = incomingDate;
}
await refreshContext();
lastHref = location.href;
},
});
statusText.value = `自动读取完成 · 累计 ${dateCount.value} 天 ${itemCount.value} 条`;
} catch (error) {
if (error instanceof DOMException && error.name === 'AbortError') {
statusText.value = `已停止自动读取 · 累计 ${dateCount.value} 天`;
} else {
statusText.value = '自动读取中断';
errorText.value = toUserMessage(error);
}
} finally {
autoRunning.value = false;
suppressUrlAutoRead = false;
busy.value = false;
autoAbort = null;
lastHref = location.href;
}
}
function stopAutoCollect() {
autoAbort?.abort();
}
async function handleSync() {
if (!batch.value) {
errorText.value = '请先读取数据';
return;
}
busy.value = true;
errorText.value = '';
syncResultText.value = '';
statusText.value = '正在同步…';
try {
await ensureChannelShop();
const payload: AdvertisingCostBatch = {
...batch.value,
channelShopId: channelShopId.value!,
};
const result = await batchImportPddGoodsAdFee(payload, (task) => {
const done = (task.successCount ?? 0) + (task.failCount ?? 0);
statusText.value = `正在导入… ${done}/${task.totalCount ?? 0}`;
});
const failed = result.status === 'failed';
const partial = result.status === 'partial';
statusText.value = failed ? '同步失败' : partial ? '部分成功' : '同步完成';
const authHint = result.authExpired
? ',授权已失效请重新授权后再导失败商品'
: '';
syncResultText.value =
`成功 ${result.successCount}/${result.totalCount}` +
(result.failCount ? `,失败 ${result.failCount}` : '') +
authHint;
} 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();
initAutoDateRange(pageContext.value?.feeDate);
const matched = await matchShopFromPage({ quiet: true });
if (pageContext.value?.dateMode === 'range') {
statusText.value = '范围视图不追加;请切到单日逐日读取并累计';
errorText.value = pageContext.value.message ?? '';
} else if (matched) {
scheduleAutoRead();
} else if (pageMallName.value.trim()) {
errorText.value = shopAuthorizeHint(pageMallName.value);
statusText.value = '店铺未授权';
}
lastHref = location.href;
urlPollTimer = setInterval(() => {
if (location.href === lastHref) return;
lastHref = location.href;
void onPageUrlChanged();
}, 800);
});
onUnmounted(() => {
autoAbort?.abort();
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 class="ecbi-header-main">
<h1>{{ EXTENSION_NAME }}</h1>
<div class="ecbi-header-shop" :title="headerShopTitle">
<span class="ecbi-header-shop-name">{{ pageMallName.trim() || '未识别店铺' }}</span>
<span class="ecbi-shop-tag" :class="shopTagClass">{{ shopTagLabel }}</span>
</div>
<p class="ecbi-header-stats">{{ accumulatedLabel }}</p>
</div>
<div class="ecbi-header-actions">
<button
class="ecbi-header-link"
type="button"
title="按页面店名重新精确匹配"
:disabled="shopMatching || busy || autoRunning"
@pointerdown.stop
@click="matchShopFromPage()"
>
{{ shopMatching ? '…' : '匹配' }}
</button>
<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-status-bar">
<p class="ecbi-status" :class="{ 'ecbi-status-busy': busy || autoRunning }">
{{ statusText }}
</p>
<p v-if="syncResultText" class="ecbi-ok">{{ syncResultText }}</p>
<p v-if="errorText" class="ecbi-error">{{ errorText }}</p>
</div>
<div class="ecbi-meta">
<span>{{ dateModeLabel }}</span>
<span class="ecbi-meta-sep">·</span>
<span class="ecbi-fee">¥{{ totalFee.toFixed(2) }}</span>
<span class="ecbi-muted">/ {{ itemCount }} 条</span>
</div>
<section class="ecbi-card ecbi-card-tight">
<DateHeatmap
:items="batch?.items ?? []"
:page-date="pageContext?.feeDate"
:selected-date="filterDate"
@select="onHeatSelect"
/>
<div v-if="filterDate" class="ecbi-heat-filter">
<span class="ecbi-muted">筛选 {{ filterDate }} · ¥{{ previewFee.toFixed(2) }}</span>
<button class="ecbi-link" type="button" @click="filterDate = undefined">全部</button>
</div>
</section>
<div class="ecbi-actions">
<button
class="ecbi-btn ecbi-btn-ghost"
type="button"
:disabled="busy || autoRunning"
@click="handleRead(false)"
>
读当日
</button>
<button
class="ecbi-btn ecbi-btn-ghost"
type="button"
:disabled="busy || autoRunning || !batch?.items?.length"
@click="clearAccumulated"
>
清空累计
</button>
<button
class="ecbi-btn ecbi-btn-primary"
type="button"
:disabled="busy || autoRunning || !batch?.items?.length"
@click="handleSync"
>
同步到系统
</button>
</div>
<details class="ecbi-fold">
<summary>自动逐日 · {{ autoDaySpanLabel }}</summary>
<div class="ecbi-fold-body">
<div class="ecbi-date-row">
<label class="ecbi-date-field">
<span class="ecbi-muted">开始</span>
<input
v-model="autoStartDate"
class="ecbi-date-input"
type="date"
:disabled="autoRunning"
/>
</label>
<label class="ecbi-date-field">
<span class="ecbi-muted">结束</span>
<input
v-model="autoEndDate"
class="ecbi-date-input"
type="date"
:disabled="autoRunning"
/>
</label>
</div>
<div class="ecbi-row" style="margin-top: 8px">
<label class="ecbi-check">
<input v-model="autoSkipRead" type="checkbox" :disabled="autoRunning" />
跳过已读
</label>
</div>
<div class="ecbi-actions" style="margin-top: 10px">
<button
v-if="!autoRunning"
class="ecbi-btn ecbi-btn-ghost"
type="button"
:disabled="busy"
@click="handleAutoCollect"
>
开始
</button>
<button v-else class="ecbi-btn ecbi-btn-ghost" type="button" @click="stopAutoCollect">
停止
</button>
</div>
</div>
</details>
<details class="ecbi-fold">
<summary>明细 · {{ previewLabel }}({{ previewItems.length }})</summary>
<div class="ecbi-fold-body">
<ul v-if="previewItems.length" class="ecbi-list">
<li v-for="item in previewItems" :key="`${item.feeDate}-${item.goodsId}`">
<span>{{ item.feeDate }} · {{ item.goodsId }}</span>
<span>¥{{ Number(item.feeAmount).toFixed(2) }}</span>
</li>
</ul>
<p v-else class="ecbi-muted" style="margin: 0">暂无数据</p>
</div>
</details>
</div>
</div>
</template>
@@ -0,0 +1,141 @@
import { createApp, type App } from 'vue';
import { emitFeatureEvent } from '@/features/runtime/mainWorldAdapters';
import FloatingPanel from './FloatingPanel.vue';
import styles from './styles.css?inline';
const HOST_ID = 'ecbi-float-host';
const LAUNCHER_ID = 'ecbi-float-launcher';
const FEATURE_ID = 'pdd-ad-fee';
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 setHostHidden(hidden: boolean) {
const host = document.getElementById(HOST_ID);
if (host) {
host.style.display = hidden ? 'none' : '';
}
}
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 16px',
background: '#1677ff',
color: '#fff',
fontSize: '13px',
fontWeight: '500',
cursor: 'pointer',
boxShadow: '0 6px 16px rgba(22, 119, 255, 0.35)',
} as CSSStyleDeclaration);
btn.addEventListener('click', () => {
minimized = false;
setFloatingVisible(true);
emitFeatureEvent(FEATURE_ID, 'restored');
});
document.documentElement.appendChild(btn);
}
function unmountApp() {
if (app) {
app.unmount();
app = null;
}
const host = document.getElementById(HOST_ID);
if (host?.shadowRoot) {
host.shadowRoot.innerHTML = '';
}
if (host) {
host.style.display = '';
}
}
function mountApp() {
const host = ensureHost();
const shadow = ensureShadow(host);
shadow.innerHTML = '';
host.style.display = '';
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: () => {
// 只隐藏,不销毁 Vue,保留已累计的多日数据
minimized = true;
setHostHidden(true);
showLauncher();
visible = true;
emitFeatureEvent(FEATURE_ID, 'minimized');
},
});
app.mount(mountEl);
}
export function isFloatingVisible(): boolean {
return visible;
}
export function setFloatingVisible(next: boolean): boolean {
if (!next) {
const wasVisible = visible;
visible = false;
minimized = false;
unmountApp();
removeLauncher();
if (wasVisible) {
emitFeatureEvent(FEATURE_ID, 'closed');
}
return false;
}
visible = true;
minimized = false;
removeLauncher();
setHostHidden(false);
if (!app) {
mountApp();
}
return true;
}
export function toggleFloatingPanel(): boolean {
return setFloatingVisible(!visible || minimized);
}
@@ -0,0 +1,673 @@
#ecbi-float-host {
all: initial;
}
/* Ant Design 风格 token(不引入组件库,仅对齐色板与圆角) */
.ecbi-panel {
--ecbi-primary: #1677ff;
--ecbi-primary-hover: #4096ff;
--ecbi-primary-active: #0958d9;
--ecbi-primary-bg: #e6f4ff;
--ecbi-text: rgba(0, 0, 0, 0.88);
--ecbi-text-secondary: rgba(0, 0, 0, 0.45);
--ecbi-text-tertiary: rgba(0, 0, 0, 0.25);
--ecbi-border: #d9d9d9;
--ecbi-border-secondary: #f0f0f0;
--ecbi-fill: #f5f5f5;
--ecbi-bg: #ffffff;
--ecbi-success: #52c41a;
--ecbi-error: #ff4d4f;
--ecbi-radius: 8px;
--ecbi-radius-lg: 12px;
--ecbi-radius-sm: 6px;
position: fixed;
z-index: 2147483646;
width: 380px;
max-height: min(640px, calc(100vh - 24px));
overflow: hidden;
display: flex;
flex-direction: column;
border-radius: var(--ecbi-radius-lg);
border: 1px solid var(--ecbi-border-secondary);
background: var(--ecbi-bg);
color: var(--ecbi-text);
box-shadow:
0 6px 16px 0 rgb(0 0 0 / 0.08),
0 3px 6px -4px rgb(0 0 0 / 0.12),
0 9px 28px 8px rgb(0 0 0 / 0.05);
font-family:
-apple-system,
BlinkMacSystemFont,
'Segoe UI',
Roboto,
'Helvetica Neue',
Arial,
'Noto Sans',
sans-serif;
font-size: 13px;
line-height: 1.5714;
}
/* 面板内所有滚动条统一细条 */
.ecbi-panel,
.ecbi-panel * {
scrollbar-width: thin;
scrollbar-color: rgb(0 0 0 / 0.28) transparent;
}
.ecbi-panel::-webkit-scrollbar,
.ecbi-panel *::-webkit-scrollbar {
width: 6px;
height: 6px;
}
.ecbi-panel::-webkit-scrollbar-thumb,
.ecbi-panel *::-webkit-scrollbar-thumb {
background: rgb(0 0 0 / 0.28);
border-radius: 3px;
}
.ecbi-panel::-webkit-scrollbar-thumb:hover,
.ecbi-panel *::-webkit-scrollbar-thumb:hover {
background: rgb(0 0 0 / 0.4);
}
.ecbi-panel::-webkit-scrollbar-track,
.ecbi-panel *::-webkit-scrollbar-track {
background: transparent;
}
.ecbi-header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
padding: 12px 14px;
background: var(--ecbi-primary);
color: #fff;
cursor: move;
user-select: none;
border-radius: var(--ecbi-radius-lg) var(--ecbi-radius-lg) 0 0;
}
.ecbi-header h1 {
margin: 0;
font-size: 14px;
font-weight: 600;
}
.ecbi-header p {
margin: 2px 0 0;
font-size: 12px;
opacity: 0.85;
}
.ecbi-header-main {
min-width: 0;
flex: 1;
}
.ecbi-header-sub {
max-width: 100%;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.ecbi-header-stats {
margin: 2px 0 0;
font-size: 12px;
opacity: 0.8;
max-width: 100%;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.ecbi-header-sub-warn {
color: #ffe58f;
opacity: 1;
}
.ecbi-header-shop {
display: flex;
align-items: center;
gap: 6px;
margin-top: 2px;
min-width: 0;
}
.ecbi-header-shop-name {
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
font-size: 12px;
opacity: 0.92;
}
.ecbi-shop-tag {
flex-shrink: 0;
display: inline-flex;
align-items: center;
height: 20px;
padding: 0 8px;
border-radius: 4px;
font-size: 11px;
font-weight: 600;
line-height: 1;
}
.ecbi-shop-tag--ok {
background: #f6ffed;
color: #389e0d;
border: 1px solid #b7eb8f;
box-shadow: 0 0 0 1px rgb(255 255 255 / 0.35);
}
.ecbi-shop-tag--warn {
background: #fffbe6;
color: #ad6800;
border: 1px solid #ffe58f;
}
.ecbi-shop-tag--loading {
background: rgb(255 255 255 / 0.22);
color: #fff;
border: 1px solid rgb(255 255 255 / 0.4);
}
.ecbi-shop-tag--muted {
background: rgb(255 255 255 / 0.16);
color: rgb(255 255 255 / 0.9);
border: 1px solid rgb(255 255 255 / 0.28);
}
.ecbi-status-bar {
display: flex;
flex-direction: column;
gap: 4px;
padding: 8px 10px;
border-radius: var(--ecbi-radius);
background: var(--ecbi-fill);
border: 1px solid var(--ecbi-border-secondary);
}
.ecbi-status-bar .ecbi-status,
.ecbi-status-bar .ecbi-ok,
.ecbi-status-bar .ecbi-error {
margin: 0;
}
.ecbi-header-link {
border: 0;
background: rgb(255 255 255 / 0.16);
color: #fff;
height: 28px;
padding: 0 8px;
border-radius: var(--ecbi-radius-sm);
font-size: 12px;
cursor: pointer;
}
.ecbi-header-link:hover:not(:disabled) {
background: rgb(255 255 255 / 0.28);
}
.ecbi-header-link:disabled {
opacity: 0.5;
cursor: not-allowed;
}
.ecbi-header-actions {
display: flex;
gap: 4px;
}
.ecbi-icon-btn {
border: 0;
background: transparent;
color: #fff;
width: 28px;
height: 28px;
border-radius: var(--ecbi-radius-sm);
cursor: pointer;
}
.ecbi-icon-btn:hover {
background: rgb(255 255 255 / 0.16);
}
.ecbi-body {
padding: 12px 14px 14px;
overflow: auto;
display: flex;
flex-direction: column;
gap: 10px;
}
.ecbi-meta {
display: flex;
align-items: baseline;
flex-wrap: wrap;
gap: 4px 6px;
font-size: 13px;
}
.ecbi-meta-sep {
color: var(--ecbi-text-tertiary);
}
.ecbi-row-links {
display: inline-flex;
gap: 10px;
}
.ecbi-card-tight {
padding: 10px;
}
.ecbi-fold {
border: 1px solid var(--ecbi-border-secondary);
border-radius: var(--ecbi-radius);
background: var(--ecbi-bg);
padding: 0 10px;
}
.ecbi-fold > summary {
cursor: pointer;
list-style: none;
padding: 8px 0;
font-size: 12px;
color: var(--ecbi-text-secondary);
user-select: none;
}
.ecbi-fold > summary::-webkit-details-marker {
display: none;
}
.ecbi-fold > summary::before {
content: '▸';
display: inline-block;
margin-right: 6px;
transition: transform 0.15s;
}
.ecbi-fold[open] > summary::before {
transform: rotate(90deg);
}
.ecbi-fold-body {
padding: 0 0 10px;
}
.ecbi-status {
margin: 0;
font-size: 12px;
color: var(--ecbi-text-secondary);
line-height: 1.4;
}
.ecbi-status-busy {
color: var(--ecbi-primary);
}
.ecbi-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
}
.ecbi-label {
color: var(--ecbi-text-secondary);
flex-shrink: 0;
}
.ecbi-input,
.ecbi-select {
width: 100%;
border: 1px solid var(--ecbi-border);
border-radius: var(--ecbi-radius);
padding: 6px 11px;
font-size: 13px;
outline: none;
background: var(--ecbi-bg);
color: var(--ecbi-text);
box-sizing: border-box;
transition:
border-color 0.2s,
box-shadow 0.2s;
}
.ecbi-input:focus,
.ecbi-select:focus {
border-color: var(--ecbi-primary);
box-shadow: 0 0 0 2px rgb(22 119 255 / 0.2);
}
.ecbi-field {
display: flex;
flex-direction: column;
gap: 6px;
}
.ecbi-actions {
display: flex;
gap: 8px;
}
.ecbi-btn {
flex: 1;
border-radius: var(--ecbi-radius);
border: 1px solid var(--ecbi-border);
background: var(--ecbi-bg);
color: var(--ecbi-text);
padding: 6px 12px;
font-size: 13px;
font-weight: 400;
line-height: 1.5714;
cursor: pointer;
transition:
color 0.2s,
border-color 0.2s,
background 0.2s;
}
.ecbi-btn:disabled {
opacity: 0.45;
cursor: not-allowed;
}
.ecbi-btn-primary {
border-color: var(--ecbi-primary);
background: var(--ecbi-primary);
color: #fff;
}
.ecbi-btn-primary:hover:not(:disabled) {
border-color: var(--ecbi-primary-hover);
background: var(--ecbi-primary-hover);
}
.ecbi-btn-primary:active:not(:disabled) {
border-color: var(--ecbi-primary-active);
background: var(--ecbi-primary-active);
}
.ecbi-btn-ghost:hover:not(:disabled) {
color: var(--ecbi-primary);
border-color: var(--ecbi-primary);
}
.ecbi-card {
border: 1px solid var(--ecbi-border-secondary);
border-radius: var(--ecbi-radius-lg);
padding: 12px;
background: var(--ecbi-fill);
}
.ecbi-card h2 {
margin: 0 0 8px;
font-size: 12px;
font-weight: 600;
color: var(--ecbi-text-secondary);
}
.ecbi-fee {
font-weight: 600;
color: var(--ecbi-error);
}
.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: var(--ecbi-text-secondary);
padding: 3px 0;
}
.ecbi-muted {
color: var(--ecbi-text-tertiary);
font-size: 12px;
}
.ecbi-error {
color: var(--ecbi-error);
font-size: 12px;
margin: 0;
}
.ecbi-ok {
color: var(--ecbi-success);
font-size: 12px;
margin: 0;
}
.ecbi-link {
border: 0;
background: transparent;
color: var(--ecbi-primary);
font-size: 12px;
cursor: pointer;
padding: 0;
}
.ecbi-link:hover {
color: var(--ecbi-primary-hover);
}
/* —— 读取日历(贡献图,蓝色阶) —— */
.ecbi-heat {
display: flex;
flex-direction: column;
gap: 6px;
}
.ecbi-heat-head {
display: flex;
align-items: baseline;
justify-content: space-between;
gap: 8px;
}
.ecbi-heat-title {
font-size: 12px;
font-weight: 600;
color: var(--ecbi-text-secondary);
}
.ecbi-heat-body {
display: flex;
gap: 4px;
overflow-x: auto;
padding-bottom: 2px;
}
.ecbi-heat-dows {
display: flex;
flex-direction: column;
gap: 3px;
flex-shrink: 0;
}
.ecbi-heat-month-spacer {
height: 14px;
}
.ecbi-heat-dow {
height: 11px;
width: 14px;
font-size: 9px;
line-height: 11px;
color: var(--ecbi-text-tertiary);
text-align: right;
}
.ecbi-heat-weeks {
display: flex;
gap: 3px;
}
.ecbi-heat-week {
display: flex;
flex-direction: column;
gap: 3px;
width: 11px;
}
.ecbi-heat-month {
height: 14px;
font-size: 9px;
line-height: 14px;
color: var(--ecbi-text-tertiary);
white-space: nowrap;
width: max-content;
max-width: none;
position: relative;
z-index: 1;
pointer-events: none;
}
.ecbi-heat-cell {
width: 11px;
height: 11px;
border-radius: 3px;
border: 0;
padding: 0;
display: block;
box-sizing: border-box;
background: #ebedf0;
cursor: default;
}
button.ecbi-heat-cell:not(:disabled) {
cursor: pointer;
}
button.ecbi-heat-cell:disabled {
opacity: 1;
}
.ecbi-heat-l0 {
background: #ebedf0;
}
.ecbi-heat-l1 {
background: #9be9a8;
}
.ecbi-heat-l2 {
background: #40c463;
}
.ecbi-heat-l3 {
background: #30a14e;
}
.ecbi-heat-l4 {
background: #216e39;
}
.ecbi-heat-out {
opacity: 0.35;
}
.ecbi-heat-page {
outline: 1px dashed var(--ecbi-primary);
outline-offset: 0;
}
.ecbi-heat-today:not(.ecbi-heat-selected) {
box-shadow: inset 0 0 0 1px var(--ecbi-text-secondary);
}
.ecbi-heat-selected {
outline: 2px solid var(--ecbi-text);
outline-offset: 0;
}
.ecbi-heat-legend {
display: flex;
align-items: center;
gap: 3px;
flex-wrap: wrap;
}
.ecbi-heat-gap {
width: 8px;
}
.ecbi-heat-filter {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
margin-top: 2px;
}
.ecbi-date-row {
display: flex;
flex-direction: column;
gap: 8px;
align-items: stretch;
}
.ecbi-date-field {
display: flex;
flex-direction: column;
gap: 4px;
width: 100%;
min-width: 0;
}
.ecbi-date-input {
box-sizing: border-box;
width: 100%;
max-width: 100%;
min-width: 0;
height: 32px;
padding: 4px 8px;
border: 1px solid var(--ecbi-border);
border-radius: var(--ecbi-radius-sm);
background: var(--ecbi-bg);
color: var(--ecbi-text);
font-size: 13px;
outline: none;
}
.ecbi-date-input:focus {
border-color: var(--ecbi-primary);
box-shadow: 0 0 0 2px rgb(22 119 255 / 0.1);
}
.ecbi-date-input:disabled {
background: var(--ecbi-fill);
color: var(--ecbi-text-secondary);
cursor: not-allowed;
}
.ecbi-check {
display: inline-flex;
align-items: center;
gap: 6px;
font-size: 12px;
color: var(--ecbi-text);
cursor: pointer;
user-select: none;
}
.ecbi-check input {
margin: 0;
}
+106
View File
@@ -0,0 +1,106 @@
import {
getActiveFeatureId,
isFeatureUiVisible,
mountFeature,
unmountActiveFeature,
} from '@/features/runtime/registry';
import { startBridgeHost } from '@/features/runtime/bridgeHost';
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';
startBridgeHost();
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();
const data: AdvertisingCostBatch = {
...parsed,
channelShopId: 0,
};
return { ok: true, data };
}
case 'TOGGLE_FLOATING_PANEL': {
if (isFeatureUiVisible()) {
await unmountActiveFeature();
return { ok: true, data: { visible: false } };
}
return {
ok: false,
code: 'UNKNOWN',
message: '请从 Popup 打开功能(需下载远程脚本)',
};
}
case 'SET_FLOATING_PANEL': {
if (!message.payload.visible) {
await unmountActiveFeature();
return { ok: true, data: { visible: false } };
}
return {
ok: false,
code: 'UNKNOWN',
message: '请从 Popup 打开功能(需下载远程脚本)',
};
}
case 'GET_FLOATING_PANEL_STATE': {
return { ok: true, data: { visible: isFeatureUiVisible() } };
}
case 'MOUNT_FEATURE': {
await mountFeature(message.payload.featureId, message.payload.code);
return { ok: true, data: { featureId: message.payload.featureId } };
}
case 'UNMOUNT_FEATURE': {
await unmountActiveFeature();
return { ok: true, data: { featureId: null } };
}
case 'GET_ACTIVE_FEATURE': {
return { ok: true, data: { featureId: getActiveFeatureId() } };
}
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',
error instanceof Error ? error.message : 'Content Script 处理失败',
);
const response: ExtensionResponse = {
ok: false,
code: err.code,
message: err.message,
};
sendResponse(response);
});
return true;
});
+12
View File
@@ -0,0 +1,12 @@
/// <reference types="vite/client" />
declare module '*.vue' {
import type { DefineComponent } from 'vue';
const component: DefineComponent<object, object, unknown>;
export default component;
}
declare module '*.css?inline' {
const css: string;
export default css;
}
@@ -0,0 +1,45 @@
/**
* 远程功能包入口(IIFE → artifacts/features/pdd-ad-fee.js)。
* 在页面 MAIN world 执行;Open API / 设置走壳侧 postMessage 桥接。
*/
import { installMainWorldAdapters } from '@/features/runtime/mainWorldAdapters';
import { setFloatingVisible } from '@/content/floating/mount';
const FEATURE_ID = 'pdd-ad-fee';
const FEATURE_VERSION = '0.3.10';
export interface RemoteFeatureExport {
id: string;
version: string;
executionWorld: 'main';
mount: () => Promise<void>;
unmount: () => Promise<void>;
}
installMainWorldAdapters();
const feature: RemoteFeatureExport = {
id: FEATURE_ID,
version: FEATURE_VERSION,
executionWorld: 'main',
async mount() {
setFloatingVisible(true);
},
async unmount() {
setFloatingVisible(false);
},
};
declare global {
interface Window {
__ECBI_FEATURES__?: Record<string, RemoteFeatureExport>;
}
}
const g = globalThis as typeof globalThis & {
__ECBI_FEATURES__?: Record<string, RemoteFeatureExport>;
};
g.__ECBI_FEATURES__ = g.__ECBI_FEATURES__ ?? {};
g.__ECBI_FEATURES__[FEATURE_ID] = feature;
export default feature;
@@ -0,0 +1,89 @@
/**
* Content Script(isolated)侧桥接主机:代发 Open API、读写 chrome.storage。
*/
import { openApiRequest } from '@/api/client';
import { ExtensionError } from '@/shared/errors';
import { getSettings, saveSettings } from '@/storage/settings';
import {
ECBI_SHELL_SOURCE,
isBridgeFeatureEvent,
isBridgeRpcRequest,
type BridgeRpcRequest,
type BridgeRpcResult,
} from './bridgeProtocol';
import { clearActiveIfFeature, notifyFeatureEvent } from './registry';
let started = false;
function reply(result: BridgeRpcResult): void {
window.postMessage(result, '*');
}
async function handleRpc(msg: BridgeRpcRequest): Promise<void> {
try {
let data: unknown;
switch (msg.rpc) {
case 'OPEN_API': {
if (!msg.path) throw new ExtensionError('UNKNOWN', '缺少 path');
data = await openApiRequest(msg.path, {
method: msg.method || 'GET',
body: msg.body,
});
break;
}
case 'GET_SETTINGS':
data = await getSettings();
break;
case 'SAVE_SETTINGS':
data = await saveSettings(msg.patch ?? {});
break;
default:
throw new ExtensionError('UNKNOWN', `未知 RPC:${(msg as { rpc: string }).rpc}`);
}
reply({
source: ECBI_SHELL_SOURCE,
type: 'RPC_RESULT',
requestId: msg.requestId,
ok: true,
data,
});
} catch (error) {
const err =
error instanceof ExtensionError
? error
: new ExtensionError(
'UNKNOWN',
error instanceof Error ? error.message : '桥接处理失败',
);
reply({
source: ECBI_SHELL_SOURCE,
type: 'RPC_RESULT',
requestId: msg.requestId,
ok: false,
error: { code: err.code, message: err.message },
});
}
}
export function startBridgeHost(): void {
if (started) return;
started = true;
window.addEventListener('message', (event) => {
if (event.source !== window) return;
const data = event.data;
if (isBridgeRpcRequest(data)) {
void handleRpc(data);
return;
}
if (isBridgeFeatureEvent(data)) {
if (data.event === 'closed') {
clearActiveIfFeature(data.featureId);
}
notifyFeatureEvent(data.featureId, data.event);
}
});
}
@@ -0,0 +1,51 @@
/** 壳(isolated)↔ 功能(main world)postMessage 协议 */
export const ECBI_SHELL_SOURCE = 'ecbi-shell';
export const ECBI_FEATURE_SOURCE = 'ecbi-feature';
export type BridgeRpcType = 'OPEN_API' | 'GET_SETTINGS' | 'SAVE_SETTINGS';
export interface BridgeRpcRequest {
source: typeof ECBI_FEATURE_SOURCE;
type: 'RPC';
rpc: BridgeRpcType;
requestId: string;
path?: string;
method?: string;
body?: string;
patch?: Record<string, unknown>;
}
export interface BridgeRpcResult {
source: typeof ECBI_SHELL_SOURCE;
type: 'RPC_RESULT';
requestId: string;
ok: boolean;
data?: unknown;
error?: { code: string; message: string };
}
export interface BridgeFeatureEvent {
source: typeof ECBI_FEATURE_SOURCE;
type: 'FEATURE_EVENT';
featureId: string;
event: 'closed' | 'minimized' | 'restored';
}
export type BridgeIncoming = BridgeRpcRequest | BridgeFeatureEvent;
export function isBridgeRpcRequest(data: unknown): data is BridgeRpcRequest {
if (!data || typeof data !== 'object') return false;
const msg = data as BridgeRpcRequest;
return msg.source === ECBI_FEATURE_SOURCE && msg.type === 'RPC' && typeof msg.requestId === 'string';
}
export function isBridgeFeatureEvent(data: unknown): data is BridgeFeatureEvent {
if (!data || typeof data !== 'object') return false;
const msg = data as BridgeFeatureEvent;
return (
msg.source === ECBI_FEATURE_SOURCE &&
msg.type === 'FEATURE_EVENT' &&
typeof msg.featureId === 'string'
);
}
@@ -0,0 +1,96 @@
/**
* Main world 适配:把 Open API / chrome.storage 换成 postMessage RPC。
* 功能包 IIFE 加载时调用 installMainWorldAdapters()。
*/
import { ExtensionError } from '@/shared/errors';
import { setOpenApiRequestOverride } from '@/api/client';
import { setSettingsOverride, type ExtensionSettings } from '@/storage/settings';
import {
ECBI_FEATURE_SOURCE,
ECBI_SHELL_SOURCE,
type BridgeRpcResult,
type BridgeRpcType,
} from './bridgeProtocol';
const RPC_TIMEOUT_MS = 30_000;
function postRpc<T>(rpc: BridgeRpcType, payload: Record<string, unknown> = {}): Promise<T> {
const requestId = `${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
return new Promise<T>((resolve, reject) => {
const timer = window.setTimeout(() => {
window.removeEventListener('message', onMessage);
reject(new ExtensionError('NETWORK_ERROR', `桥接超时(${rpc})`));
}, RPC_TIMEOUT_MS);
function onMessage(event: MessageEvent) {
if (event.source !== window) return;
const data = event.data as BridgeRpcResult | undefined;
if (!data || data.source !== ECBI_SHELL_SOURCE || data.type !== 'RPC_RESULT') return;
if (data.requestId !== requestId) return;
window.clearTimeout(timer);
window.removeEventListener('message', onMessage);
if (!data.ok) {
reject(
new ExtensionError(
(data.error?.code as never) || 'UNKNOWN',
data.error?.message || '桥接调用失败',
),
);
return;
}
resolve(data.data as T);
}
window.addEventListener('message', onMessage);
window.postMessage(
{
source: ECBI_FEATURE_SOURCE,
type: 'RPC',
rpc,
requestId,
...payload,
},
'*',
);
});
}
let installed = false;
export function installMainWorldAdapters(): void {
if (installed) return;
installed = true;
setOpenApiRequestOverride(async <T,>(path: string, init: RequestInit = {}) => {
const method = (init.method || 'GET').toUpperCase();
const body = typeof init.body === 'string' ? init.body : undefined;
return postRpc<T>('OPEN_API', { path, method, body });
});
setSettingsOverride({
get: () => postRpc<ExtensionSettings>('GET_SETTINGS'),
save: (patch) =>
postRpc<ExtensionSettings>('SAVE_SETTINGS', {
patch: patch as Record<string, unknown>,
}),
});
}
export function emitFeatureEvent(
featureId: string,
event: 'closed' | 'minimized' | 'restored',
): void {
window.postMessage(
{
source: ECBI_FEATURE_SOURCE,
type: 'FEATURE_EVENT',
featureId,
event,
},
'*',
);
}
@@ -0,0 +1,39 @@
/** 通过 Background 向页面 MAIN world 注入/调用功能脚本(绕过页面 CSP) */
interface BgResponse {
ok: boolean;
message?: string;
}
function sendToBackground(message: unknown): Promise<void> {
return new Promise((resolve, reject) => {
chrome.runtime.sendMessage(message, (response: BgResponse | undefined) => {
if (chrome.runtime.lastError) {
reject(new Error(chrome.runtime.lastError.message));
return;
}
if (!response?.ok) {
reject(new Error(response?.message || 'Background 执行失败'));
return;
}
resolve();
});
});
}
export async function injectMainWorldScript(code: string): Promise<void> {
await sendToBackground({
type: 'INJECT_MAIN_SCRIPT',
payload: { code },
});
}
export async function callMainWorldFeature(
featureId: string,
action: 'mount' | 'unmount',
): Promise<void> {
await sendToBackground({
type: 'CALL_MAIN_FEATURE',
payload: { featureId, action },
});
}
@@ -0,0 +1,81 @@
import type { FeatureHandle } from '@/features/runtime/types';
import {
callMainWorldFeature,
injectMainWorldScript,
} from '@/features/runtime/mainWorldInject';
let active: { id: string; handle: FeatureHandle } | null = null;
type FeatureEventListener = (
featureId: string,
event: 'closed' | 'minimized' | 'restored',
) => void;
const listeners = new Set<FeatureEventListener>();
export function onFeatureEvent(listener: FeatureEventListener): () => void {
listeners.add(listener);
return () => listeners.delete(listener);
}
export function notifyFeatureEvent(
featureId: string,
event: 'closed' | 'minimized' | 'restored',
): void {
for (const listener of listeners) {
try {
listener(featureId, event);
} catch {
// ignore
}
}
}
export function getActiveFeatureId(): string | null {
return active?.id ?? null;
}
export function clearActiveIfFeature(featureId: string): void {
if (active?.id === featureId) {
active = null;
}
}
export async function mountFeature(featureId: string, code: string): Promise<void> {
if (!code?.trim()) {
throw new Error('缺少远程功能脚本,无法挂载');
}
if (active?.id === featureId) {
// 同一功能重新打开:先卸再挂,确保用最新脚本
await unmountActiveFeature();
} else {
await unmountActiveFeature();
}
await injectMainWorldScript(code);
await callMainWorldFeature(featureId, 'mount');
active = {
id: featureId,
handle: {
unmount: async () => {
await callMainWorldFeature(featureId, 'unmount');
},
},
};
}
export async function unmountActiveFeature(): Promise<void> {
if (!active) return;
const current = active;
active = null;
try {
await current.handle.unmount();
} catch {
// 页面可能已刷新,忽略
}
}
export function isFeatureUiVisible(): boolean {
return active != null;
}
@@ -0,0 +1,57 @@
/** 功能清单与模块约定(壳 / 远程脚本共用) */
export interface ExtensionFeatureItem {
id: string;
name: string;
version: string;
description?: string;
/** 匹配当前页才可打开,chrome match pattern 风格简化:含 host 即可 */
matchUrlPatterns: string[];
/** 相对静态目录的入口文件,如 pdd-ad-fee.js */
entry: string;
/** 脚本 sha256(hex),可选;有则下载后校验 */
sha256?: string;
/** main=页面 MAIN world 执行(可热更新);extension=仅壳内(已弃用) */
executionWorld?: 'extension' | 'main';
}
export interface ExtensionFeatureManifest {
schemaVersion: number;
updatedAt?: string;
features: ExtensionFeatureItem[];
}
export interface FeatureHandle {
unmount: () => void | Promise<void>;
}
export interface FeatureModule {
id: string;
mount: (ctx: FeatureMountContext) => FeatureHandle | Promise<FeatureHandle>;
}
export interface FeatureMountContext {
featureId: string;
/** 打开/关闭由壳控制时可回调 */
onClose?: () => void;
}
export function urlMatchesPatterns(url: string, patterns: string[] | null | undefined): boolean {
if (!patterns?.length) return true;
try {
return patterns.some((pattern) => matchPattern(url, pattern));
} catch {
// 非法 pattern 时不拖垮 Popup
return false;
}
}
/** 将 chrome 风格 * 通配转为安全正则(先按 * 切开再转义各段) */
function matchPattern(url: string, pattern: string): boolean {
if (!pattern) return false;
if (!pattern.includes('*')) {
return url.includes(pattern);
}
const parts = pattern.split('*').map((part) => part.replace(/[.+?^${}()|[\]\\]/g, '\\$&'));
return new RegExp(`^${parts.join('.*')}$`).test(url);
}
@@ -0,0 +1,15 @@
import type {
AdvertisingCostBatch,
PageContext,
PlatformType,
} from '@/types/advertisingCost';
export interface PlatformAdapter {
readonly platform: PlatformType;
canHandle(url: string): boolean;
getPageContext(): Promise<PageContext>;
/** 从当前页解析推广费;每条 item 自带 feeDate */
parseAdvertisingCost(
options?: { allowEmpty?: boolean },
): Promise<Omit<AdvertisingCostBatch, 'channelShopId'>>;
}
@@ -0,0 +1,25 @@
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 PddPlatformAdapter(), 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.find((item) => item.platform === 'mock') ?? 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,37 @@
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 {
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(): Promise<Omit<AdvertisingCostBatch, 'channelShopId'>> {
return {
platform: 'mock',
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,77 @@
import type { PlatformAdapter } from '@/platform/core/PlatformAdapter';
import type { AdvertisingCostBatch, PageContext } from '@/types/advertisingCost';
import { ensurePageSize100 } from './ensurePageSize';
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(
options: { allowEmpty?: boolean } = {},
): 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 ?? '未能识别单日报表日期');
}
// 读取前把「每页」自动切到 100,减少分页漏读
await ensurePageSize100();
const items = parsePromotionItems(dateInfo.feeDate);
if (items.length === 0 && !options.allowEmpty) {
throw new Error('未解析到商品推广费,请确认表格已加载且包含「总花费」列');
}
return {
platform: 'pdd',
items,
source: 'browser-extension',
importedAt: new Date().toISOString(),
};
}
}
@@ -0,0 +1,117 @@
import { normalizePddDate } from './parseReport';
import { humanPauseMs, sleep } from './domInteract';
import { switchToSingleDay } from './switchReportDate';
/** 单次自动逐日最多天数(含起止) */
export const MAX_AUTO_COLLECT_DAYS = 31;
export function listDatesInclusive(startIso: string, endIso: string): string[] {
const start = normalizePddDate(startIso) ?? startIso;
const end = normalizePddDate(endIso) ?? endIso;
if (!/^\d{4}-\d{2}-\d{2}$/.test(start) || !/^\d{4}-\d{2}-\d{2}$/.test(end)) {
throw new Error('起止日期格式无效');
}
if (start > end) {
throw new Error('开始日期不能晚于结束日期');
}
const dates: string[] = [];
const cursor = new Date(`${start}T00:00:00`);
const endDate = new Date(`${end}T00:00:00`);
while (cursor <= endDate) {
const y = cursor.getFullYear();
const m = String(cursor.getMonth() + 1).padStart(2, '0');
const d = String(cursor.getDate()).padStart(2, '0');
dates.push(`${y}-${m}-${d}`);
if (dates.length > MAX_AUTO_COLLECT_DAYS) {
throw new Error(`单次最多 ${MAX_AUTO_COLLECT_DAYS} 天,请缩小范围`);
}
cursor.setDate(cursor.getDate() + 1);
}
return dates;
}
export interface AutoCollectProgress {
index: number;
total: number;
date: string;
phase: 'switch' | 'read' | 'pause' | 'done' | 'skip';
message: string;
}
export interface AutoCollectOptions {
startDate: string;
endDate: string;
/** 已累计过的日期,默认跳过 */
skipDates?: Set<string> | string[];
signal?: AbortSignal;
onProgress?: (p: AutoCollectProgress) => void;
/** 切到该日后执行读取;返回是否成功(无数据也可 true) */
readDay: (date: string) => Promise<void>;
}
/**
* 按日拟人切换并读取。日间有随机停顿,避免过快连点。
*/
export async function runAutoCollectByDates(options: AutoCollectOptions): Promise<void> {
const dates = listDatesInclusive(options.startDate, options.endDate);
const skip = new Set(
[...(options.skipDates ?? [])].map((d) => normalizePddDate(d) ?? d),
);
for (let i = 0; i < dates.length; i++) {
if (options.signal?.aborted) {
throw new DOMException('已取消自动读取', 'AbortError');
}
const date = dates[i]!;
if (skip.has(date)) {
options.onProgress?.({
index: i + 1,
total: dates.length,
date,
phase: 'skip',
message: `跳过已读 ${date}(${i + 1}/${dates.length})`,
});
continue;
}
options.onProgress?.({
index: i + 1,
total: dates.length,
date,
phase: 'switch',
message: `切换日期 ${date}(${i + 1}/${dates.length})…`,
});
await switchToSingleDay(date, { signal: options.signal });
options.onProgress?.({
index: i + 1,
total: dates.length,
date,
phase: 'read',
message: `读取 ${date}(${i + 1}/${dates.length})…`,
});
await options.readDay(date);
if (i < dates.length - 1) {
const pause = humanPauseMs('betweenDays');
options.onProgress?.({
index: i + 1,
total: dates.length,
date,
phase: 'pause',
message: `已读 ${date},停顿 ${(pause / 1000).toFixed(1)}s 后继续…`,
});
await sleep(pause);
}
}
options.onProgress?.({
index: dates.length,
total: dates.length,
date: dates[dates.length - 1] ?? '',
phase: 'done',
message: `自动读取完成(${dates.length} 天)`,
});
}
@@ -0,0 +1,41 @@
/** 轻量 DOM 拟人点击(供分页、切日期等复用) */
export function sleep(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}
/** 均匀随机整数 [min, max] */
export function randomInt(min: number, max: number): number {
const lo = Math.ceil(min);
const hi = Math.floor(max);
return Math.floor(Math.random() * (hi - lo + 1)) + lo;
}
export function dispatchMouse(el: HTMLElement, type: string): void {
el.dispatchEvent(
new MouseEvent(type, {
bubbles: true,
cancelable: true,
view: window,
buttons: 1,
}),
);
}
/** Ant Design 控件开合依赖 mousedown,单用 click() 常无效 */
export function pointerClick(el: HTMLElement): void {
el.scrollIntoView({ block: 'center', inline: 'nearest' });
dispatchMouse(el, 'pointerdown');
dispatchMouse(el, 'mousedown');
dispatchMouse(el, 'pointerup');
dispatchMouse(el, 'mouseup');
dispatchMouse(el, 'click');
}
/** 操作间隔:略留余量等 UI/拉数,不再刻意拖慢 */
export function humanPauseMs(kind: 'betweenDays' | 'afterUi' | 'afterNav' = 'betweenDays'): number {
if (kind === 'afterUi') return randomInt(80, 180);
if (kind === 'afterNav') return randomInt(400, 800);
// 日与日之间:约 0.6s~1.2s
return randomInt(600, 1200);
}
@@ -0,0 +1,212 @@
import { PDD_SELECTORS } from './selectors';
const TARGET_PAGE_SIZE = 100;
function sleep(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}
function dispatchMouse(el: HTMLElement, type: string): void {
el.dispatchEvent(
new MouseEvent(type, {
bubbles: true,
cancelable: true,
view: window,
buttons: 1,
}),
);
}
/** Ant Design Select 开合依赖 mousedown,单用 click() 首次常打不开 */
function pointerClick(el: HTMLElement): void {
dispatchMouse(el, 'pointerdown');
dispatchMouse(el, 'mousedown');
dispatchMouse(el, 'pointerup');
dispatchMouse(el, 'mouseup');
dispatchMouse(el, 'click');
}
function findPageSizeSelect(doc: Document = document): HTMLElement | null {
const wrap =
doc.querySelector(PDD_SELECTORS.overviewTable) ??
doc.querySelector(PDD_SELECTORS.paginationWrap) ??
doc;
const perPage = wrap.querySelector(PDD_SELECTORS.perPageText);
const li = perPage?.closest('li') ?? wrap.querySelector('.anq-pagination-total-text');
const select =
(li?.querySelector(PDD_SELECTORS.pageSizeSelect) as HTMLElement | null) ??
(wrap.querySelector(
`${PDD_SELECTORS.paginationWrap} ${PDD_SELECTORS.pageSizeSelect}`,
) as HTMLElement | null);
return select;
}
function readCurrentPageSize(select: Element): number | undefined {
const item = select.querySelector(PDD_SELECTORS.pageSizeValue);
const raw = (item?.getAttribute('title') || item?.textContent || '').trim();
const value = Number(raw.replace(/[^\d]/g, ''));
return Number.isFinite(value) && value > 0 ? value : undefined;
}
function getCombobox(select: Element): HTMLInputElement | null {
return select.querySelector('input[role="combobox"], .anq-select-selection-search-input');
}
function isSelectOpen(select: Element): boolean {
return getCombobox(select)?.getAttribute('aria-expanded') === 'true';
}
/** 仅认「当前可见」的下拉,避免点到手动操作后残留的 hidden dropdown */
function findVisibleDropdown(doc: Document = document): HTMLElement | null {
const dropdowns = Array.from(doc.querySelectorAll('.anq-select-dropdown'));
for (const el of dropdowns) {
if (el.classList.contains('anq-select-dropdown-hidden')) continue;
const style = window.getComputedStyle(el);
if (style.display === 'none' || style.visibility === 'hidden') continue;
if (style.pointerEvents === 'none') continue;
return el as HTMLElement;
}
return null;
}
function isTargetOption(el: Element, target: number): boolean {
const title = (el.getAttribute('title') || '').trim();
const text = (el.textContent || '').replace(/\s+/g, ' ').trim();
if (title === String(target)) return true;
if (text === String(target)) return true;
if (text === `${target}条` || text === `${target} 条`) return true;
return false;
}
function findOptionIn(root: ParentNode, target: number): HTMLElement | null {
const candidates = root.querySelectorAll(
[
'.anq-select-item-option',
'[class*="select-item-option"]',
'[role="option"]',
].join(','),
);
for (const el of candidates) {
if (el.classList.contains('anq-select-item-option-disabled')) continue;
if (isTargetOption(el, target)) return el as HTMLElement;
}
return null;
}
async function waitForVisibleOption(
target: number,
timeoutMs: number,
doc: Document,
): Promise<HTMLElement | null> {
const started = Date.now();
while (Date.now() - started < timeoutMs) {
const dropdown = findVisibleDropdown(doc);
if (dropdown) {
const option = findOptionIn(dropdown, target);
if (option) return option;
}
await sleep(80);
}
return null;
}
async function waitUntilPageSize(
select: Element,
target: number,
timeoutMs = 4000,
): Promise<boolean> {
const started = Date.now();
while (Date.now() - started < timeoutMs) {
if (readCurrentPageSize(select) === target) return true;
await sleep(100);
}
return readCurrentPageSize(select) === target;
}
async function openPageSizeSelect(select: HTMLElement, doc: Document): Promise<boolean> {
const trigger =
(select.querySelector('.anq-select-selector') as HTMLElement | null) ?? select;
const input = getCombobox(select);
trigger.scrollIntoView({ block: 'center', inline: 'nearest' });
await sleep(50);
input?.focus({ preventScroll: true });
// 已打开则先关掉,保证重新挂载可见下拉(避免点到残留 hidden 节点)
if (isSelectOpen(select) || findVisibleDropdown(doc)) {
doc.body.dispatchEvent(
new KeyboardEvent('keydown', { key: 'Escape', bubbles: true, cancelable: true }),
);
await sleep(120);
}
pointerClick(trigger);
const started = Date.now();
while (Date.now() - started < 1500) {
if (isSelectOpen(select) && findVisibleDropdown(doc)) return true;
await sleep(80);
}
// 再试一次:部分 antd 版本首次 mousedown 被挡
pointerClick(trigger);
const retryStart = Date.now();
while (Date.now() - retryStart < 1500) {
if (isSelectOpen(select) && findVisibleDropdown(doc)) return true;
await sleep(80);
}
return Boolean(isSelectOpen(select) && findVisibleDropdown(doc));
}
/**
* 将推广商品表分页「每页」自动切到 100(若已是 100 则跳过)。
*
* 注意:首次进入页面时下拉选项不在 DOM;手动切换过后,antd 常把
* `.anq-select-dropdown-hidden` 残留在 body。若只搜全局 option,
* 会点到不可见节点「看似成功」或首次完全失败。因此必须:
* 1) 用 mousedown 序列真正打开 Select
* 2) 只点击「可见」dropdown 内的 100
*/
export async function ensurePageSize100(doc: Document = document): Promise<{
changed: boolean;
pageSize?: number;
}> {
const select = findPageSizeSelect(doc);
if (!select) {
return { changed: false };
}
const current = readCurrentPageSize(select);
if (current === TARGET_PAGE_SIZE) {
return { changed: false, pageSize: current };
}
const opened = await openPageSizeSelect(select, doc);
if (!opened) {
doc.body.dispatchEvent(
new KeyboardEvent('keydown', { key: 'Escape', bubbles: true, cancelable: true }),
);
throw new Error(
`未能打开每页条数下拉(当前 ${current ?? '未知'})。请先滚动到表格底部分页区后重试`,
);
}
const option = await waitForVisibleOption(TARGET_PAGE_SIZE, 2500, doc);
if (!option) {
doc.body.dispatchEvent(
new KeyboardEvent('keydown', { key: 'Escape', bubbles: true, cancelable: true }),
);
throw new Error(
`下拉已打开但未找到 ${TARGET_PAGE_SIZE} 选项,请确认分页支持该页大小`,
);
}
pointerClick(option);
const ok = await waitUntilPageSize(select, TARGET_PAGE_SIZE);
if (!ok) {
throw new Error(`切换每页 ${TARGET_PAGE_SIZE} 未生效,请手动切换后重试`);
}
await sleep(900);
return { changed: true, pageSize: TARGET_PAGE_SIZE };
}
@@ -0,0 +1,19 @@
import type { PddChannelShop } from '@/api/open/pddShop';
import { matchPddChannelShopByMallName } from '@/api/open/pddShop';
/**
* 用页面店铺名匹配 BI channelShop:后端按 mallName trim 后精确匹配。
*/
export async function matchChannelShopByMallName(
mallName: string,
): Promise<PddChannelShop | null> {
const name = mallName.trim();
if (!name) return null;
const shop = await matchPddChannelShopByMallName(name);
return shop ?? null;
}
export function shopAuthorizeHint(mallName: string): string {
const name = mallName.trim() || '当前店铺';
return `未在系统中找到与「${name}」完全同名的授权店铺,请先到 BI 系统完成该店铺授权后再试`;
}
@@ -0,0 +1,165 @@
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;
}
/** 优先主 RangePicker 显示值(页面真实选中),URL 仅作回退。
* 勿只信 URL:history.pushState 改地址栏不会驱动 React 重拉数据。 */
export function readReportDate(doc: Document = document, href = location.href): PddReportDateInfo {
const fromPicker = readDateFromMainPicker(doc);
if (fromPicker) return fromPicker;
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
}
return { mode: 'unknown', message: '未能识别报表日期,请确认已打开商品推广总览且选择了日期' };
}
/** 读取 DateArea 主日期选择器(跳过对比日期) */
export function readDateFromMainPicker(doc: Document = document): PddReportDateInfo | null {
const pickers = Array.from(doc.querySelectorAll(PDD_SELECTORS.rangePicker));
for (const picker of pickers) {
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 null;
}
/**
* 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);
// 总花费为 0 / 空 不记录
if (feeAmount == null || feeAmount <= 0) continue;
seen.add(goodsId);
items.push({
feeDate,
goodsId,
feeAmount,
metadata: {
goodsName: row
.querySelector('[class*="OverviewTable_goodsName"]')
?.getAttribute('title')
?.replace(/^商品名:/, ''),
},
});
}
return items.sort((a, b) => Number(b.feeAmount) - Number(a.feeAmount));
}
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,23 @@
/** 拼多多推广报表 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',
/** 分页「每页」 */
paginationWrap: '[class*="OverviewTable_paginationWrap"], .anq-pagination-wrapper',
perPageText: '.anq-perpage-text',
pageSizeSelect: '.anq-select',
pageSizeValue: '.anq-select-selection-item',
} 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})/;
@@ -0,0 +1,272 @@
import { normalizePddDate, readDateFromMainPicker, readReportDate } from './parseReport';
import { PDD_SELECTORS } from './selectors';
import { humanPauseMs, pointerClick, sleep } from './domInteract';
const MAX_WAIT_MS = 15_000;
function throwIfAborted(signal?: AbortSignal): void {
if (signal?.aborted) {
throw new DOMException('已取消自动切换日期', 'AbortError');
}
}
function findMainRangePicker(doc: Document = document): HTMLElement | null {
const pickers = Array.from(doc.querySelectorAll(PDD_SELECTORS.rangePicker));
for (const picker of pickers) {
if (picker.closest('[class*="CompareDate"]')) continue;
if (picker.closest('[class*="DateArea"]')) return picker as HTMLElement;
}
for (const picker of pickers) {
if (picker.closest('[class*="CompareDate"]')) continue;
return picker as HTMLElement;
}
return null;
}
function findVisiblePickerDropdown(doc: Document = document): HTMLElement | null {
const dropdowns = Array.from(
doc.querySelectorAll('.anq-picker-dropdown, [class*="picker-dropdown"]'),
);
for (const el of dropdowns) {
if (el.classList.contains('anq-picker-dropdown-hidden')) continue;
const style = window.getComputedStyle(el);
if (style.display === 'none' || style.visibility === 'hidden') continue;
if (style.pointerEvents === 'none') continue;
// 排除完全不可见
const rect = el.getBoundingClientRect();
if (rect.width < 2 || rect.height < 2) continue;
return el as HTMLElement;
}
return null;
}
function closePicker(doc: Document = document): void {
doc.body.dispatchEvent(
new KeyboardEvent('keydown', { key: 'Escape', bubbles: true, cancelable: true }),
);
}
async function openRangePicker(doc: Document, signal?: AbortSignal): Promise<HTMLElement> {
const picker = findMainRangePicker(doc);
if (!picker) throw new Error('未找到日期范围选择器');
// 先关掉残留面板,避免点到 hidden 节点
if (findVisiblePickerDropdown(doc)) {
closePicker(doc);
await sleep(180);
}
const triggers: HTMLElement[] = [];
const startInput = picker.querySelector(
'.anq-picker-input input, .anq-picker-input-active input',
) as HTMLElement | null;
const anyInput = picker.querySelector('input') as HTMLElement | null;
const suffix = picker.querySelector('.anq-picker-suffix') as HTMLElement | null;
if (startInput) triggers.push(startInput);
if (anyInput && anyInput !== startInput) triggers.push(anyInput);
if (suffix) triggers.push(suffix);
triggers.push(picker);
for (const trigger of triggers) {
throwIfAborted(signal);
pointerClick(trigger);
// 部分环境还吃原生 click
try {
trigger.click();
} catch {
// ignore
}
await sleep(humanPauseMs('afterUi'));
const started = Date.now();
while (Date.now() - started < 1800) {
throwIfAborted(signal);
const dropdown = findVisiblePickerDropdown(doc);
if (dropdown) return dropdown;
await sleep(80);
}
}
throw new Error('未能打开日期面板,请手动点开日期选择器后再试自动读取');
}
function titleCandidates(isoDate: string): string[] {
const [y, m, d] = isoDate.split('-');
if (!y || !m || !d) return [isoDate];
return [
isoDate,
`${y}/${m}/${d}`,
`${y}/${Number(m)}/${Number(d)}`,
`${y}-${Number(m)}-${Number(d)}`,
];
}
function findDateCell(dropdown: HTMLElement, isoDate: string): HTMLElement | null {
for (const title of titleCandidates(isoDate)) {
const cells = Array.from(
dropdown.querySelectorAll(`.anq-picker-cell[title="${title}"], td[title="${title}"]`),
) as HTMLElement[];
const preferred =
cells.find(
(el) =>
el.classList.contains('anq-picker-cell-in-view') &&
!el.classList.contains('anq-picker-cell-disabled'),
) ??
cells.find((el) => !el.classList.contains('anq-picker-cell-disabled')) ??
null;
if (preferred) {
return (
(preferred.querySelector('.anq-picker-cell-inner') as HTMLElement | null) ?? preferred
);
}
}
return null;
}
function parseHeaderYearMonth(dropdown: HTMLElement): { y: number; m: number } | null {
const headers = Array.from(
dropdown.querySelectorAll('.anq-picker-header-view, [class*="picker-header-view"]'),
);
// Range 常左右两个月面板,取第一个可见头
for (const header of headers) {
const text = (header.textContent || '').replace(/\s+/g, '');
let m = text.match(/(\d{4})\s*年\s*(\d{1,2})\s*月/);
if (m) return { y: Number(m[1]), m: Number(m[2]) };
m = text.match(/(\d{4})[/.-](\d{1,2})/);
if (m) return { y: Number(m[1]), m: Number(m[2]) };
}
return null;
}
async function navigateToMonth(
dropdown: HTMLElement,
isoDate: string,
signal?: AbortSignal,
): Promise<void> {
const [ys, ms] = isoDate.split('-');
const targetY = Number(ys);
const targetM = Number(ms);
if (!targetY || !targetM) throw new Error(`非法日期:${isoDate}`);
for (let i = 0; i < 36; i++) {
throwIfAborted(signal);
if (findDateCell(dropdown, isoDate)) return;
const current = parseHeaderYearMonth(dropdown);
if (!current) break;
const curIdx = current.y * 12 + current.m;
const tgtIdx = targetY * 12 + targetM;
if (curIdx === tgtIdx) {
// 头已对齐但仍找不到 cell — 可能 title 格式不同
break;
}
const wantNext = curIdx < tgtIdx;
const buttons = Array.from(
dropdown.querySelectorAll(
wantNext
? '.anq-picker-header-next-btn'
: '.anq-picker-header-prev-btn',
),
) as HTMLElement[];
// 双月面板时点左侧(第一个)的 prev/next
const btn = buttons[0];
if (!btn) break;
pointerClick(btn);
await sleep(humanPauseMs('afterUi'));
}
if (!findDateCell(dropdown, isoDate)) {
throw new Error(`日期面板中找不到 ${isoDate},请确认未超出可选范围`);
}
}
/** 以选择器输入值为准,确认已切到目标单日(不认仅改 URL) */
async function waitUntilPickerSingleDay(
isoDate: string,
signal?: AbortSignal,
): Promise<void> {
const started = Date.now();
while (Date.now() - started < MAX_WAIT_MS) {
throwIfAborted(signal);
const picker = readDateFromMainPicker();
if (picker?.mode === 'single' && picker.feeDate === isoDate) return;
await sleep(200);
}
const picker = readDateFromMainPicker();
const fallback = readReportDate();
throw new Error(
`切换到 ${isoDate} 超时(选择器:${picker?.mode ?? '无'} ${picker?.feeDate ?? picker?.beginDate ?? '?'};页面:${fallback.feeDate ?? '?'})`,
);
}
async function clickCellTwiceForSingleDay(
dropdown: HTMLElement,
isoDate: string,
doc: Document,
signal?: AbortSignal,
): Promise<void> {
const cell = findDateCell(dropdown, isoDate);
if (!cell) throw new Error(`未找到日期单元格 ${isoDate}`);
// RangePicker:起、止各点同一天
pointerClick(cell);
try {
cell.click();
} catch {
// ignore
}
await sleep(humanPauseMs('afterUi'));
throwIfAborted(signal);
const dropdown2 = findVisiblePickerDropdown(doc);
if (dropdown2) {
const cell2 = findDateCell(dropdown2, isoDate);
if (cell2) {
pointerClick(cell2);
try {
cell2.click();
} catch {
// ignore
}
await sleep(humanPauseMs('afterUi'));
}
}
}
/**
* 将推广总览切到指定单日。
* 只通过 DateArea RangePicker 拟人点击;禁止 pushState 假切换。
*/
export async function switchToSingleDay(
isoDate: string,
options: { signal?: AbortSignal; doc?: Document } = {},
): Promise<void> {
const date = normalizePddDate(isoDate) ?? isoDate;
if (!/^\d{4}-\d{2}-\d{2}$/.test(date)) {
throw new Error(`日期格式无效:${isoDate}`);
}
const { signal, doc = document } = options;
throwIfAborted(signal);
const current = readDateFromMainPicker(doc) ?? readReportDate(doc);
if (current.mode === 'single' && current.feeDate === date) {
return;
}
const dropdown = await openRangePicker(doc, signal);
await navigateToMonth(dropdown, date, signal);
await clickCellTwiceForSingleDay(dropdown, date, doc, signal);
// 若面板仍开着,再 Esc(有的版本选完自动关)
if (findVisiblePickerDropdown(doc)) {
closePicker(doc);
await sleep(200);
}
await waitUntilPickerSingleDay(date, signal);
// 等报表按新日期拉数
await sleep(humanPauseMs('afterNav'));
}
+258
View File
@@ -0,0 +1,258 @@
<script setup lang="ts">
import { computed, onMounted, ref } from 'vue';
import {
downloadAndVerifyFeature,
fetchFeatureManifest,
} from '@/api/open/extensionFeatures';
import type { ExtensionFeatureItem } from '@/features/runtime/types';
import { urlMatchesPatterns } from '@/features/runtime/types';
import { EXTENSION_NAME } from '@/shared/constants';
import { toUserMessage } from '@/shared/errors';
import { getSettings, saveSettings } from '@/storage/settings';
import {
getFloatingPanelState,
mountFeatureOnPage,
unmountFeatureOnPage,
} from './messaging';
const apiBaseUrl = ref('');
const apiKey = ref('');
const features = ref<ExtensionFeatureItem[]>([]);
const featuresLoading = ref(false);
const featuresUpdatedAt = ref('');
const activeFeatureId = ref<string | null>(null);
const currentTabUrl = ref('');
const statusText = ref('');
const errorText = ref('');
const busy = ref(false);
const checking = ref(false);
const configOpen = ref(false);
const hasConfig = computed(() => Boolean(apiBaseUrl.value.trim() && apiKey.value.trim()));
const matchedFeatures = computed(() => {
const list = Array.isArray(features.value) ? features.value : [];
if (!currentTabUrl.value) return list;
return list.filter((f) => urlMatchesPatterns(currentTabUrl.value, f?.matchUrlPatterns ?? []));
});
const configSummary = computed(() => {
if (!hasConfig.value) return '未配置';
try {
const host = new URL(apiBaseUrl.value.trim()).host;
return host || '已配置';
} catch {
return '已配置';
}
});
async function loadLocalSettings() {
const settings = await getSettings();
apiBaseUrl.value = settings.apiBaseUrl;
apiKey.value = settings.apiKey;
// 未配置时默认展开
configOpen.value = !(settings.apiBaseUrl && settings.apiKey);
}
async function saveConfig() {
await saveSettings({
apiBaseUrl: apiBaseUrl.value.trim(),
apiKey: apiKey.value.trim(),
});
}
async function persistAndCheck() {
checking.value = true;
errorText.value = '';
statusText.value = '';
try {
await saveConfig();
const manifest = await fetchFeatureManifest();
features.value = manifest.features ?? [];
featuresUpdatedAt.value = manifest.updatedAt ?? '';
const count = features.value.length;
statusText.value = `已连接 · 清单 ${count} 项`;
configOpen.value = false;
} catch (error) {
errorText.value = toUserMessage(error);
configOpen.value = true;
} finally {
checking.value = false;
}
}
async function refreshTabUrl() {
try {
const tabs = await chrome.tabs.query({ active: true, currentWindow: true });
currentTabUrl.value = tabs[0]?.url ?? '';
} catch {
currentTabUrl.value = '';
}
}
async function loadFeatures() {
featuresLoading.value = true;
errorText.value = '';
try {
await saveConfig();
const manifest = await fetchFeatureManifest();
features.value = manifest.features ?? [];
featuresUpdatedAt.value = manifest.updatedAt ?? '';
statusText.value = `清单已刷新(${features.value.length})`;
} catch (error) {
errorText.value = toUserMessage(error);
configOpen.value = true;
} finally {
featuresLoading.value = false;
}
}
async function refreshPanelState() {
try {
const state = await getFloatingPanelState();
activeFeatureId.value = state.visible ? 'pdd-ad-fee' : null;
} catch {
activeFeatureId.value = null;
}
}
async function handleOpenFeature(item: ExtensionFeatureItem) {
busy.value = true;
errorText.value = '';
statusText.value = '';
try {
await saveConfig();
const remote = await downloadAndVerifyFeature(item);
await mountFeatureOnPage(item.id, remote.code);
activeFeatureId.value = item.id;
statusText.value = `已打开 ${item.name}`;
} catch (error) {
errorText.value = toUserMessage(error);
} finally {
busy.value = false;
}
}
async function handleCloseFeature() {
busy.value = true;
errorText.value = '';
try {
await unmountFeatureOnPage();
activeFeatureId.value = null;
statusText.value = '已关闭';
} catch (error) {
errorText.value = toUserMessage(error);
} finally {
busy.value = false;
}
}
onMounted(async () => {
await loadLocalSettings();
await refreshTabUrl();
await refreshPanelState();
if (hasConfig.value) {
await loadFeatures();
}
});
</script>
<template>
<div class="popup-root">
<header class="popup-header">
<div class="min-w-0 flex-1">
<h1>{{ EXTENSION_NAME }}</h1>
<p class="popup-sub">{{ configSummary }}</p>
</div>
<button
class="popup-link"
type="button"
:disabled="busy || checking"
@click="configOpen = !configOpen"
>
{{ configOpen ? '收起配置' : '配置' }}
</button>
</header>
<section v-show="configOpen" class="popup-card space-y-2">
<label class="popup-label">
Base URL
<input
v-model="apiBaseUrl"
class="popup-input"
placeholder="https://host/api"
autocomplete="off"
/>
</label>
<label class="popup-label">
API Key
<input
v-model="apiKey"
class="popup-input"
type="password"
placeholder="sk_live_..."
autocomplete="off"
/>
</label>
<button
class="popup-btn popup-btn-primary w-full"
type="button"
:disabled="busy || checking || !apiBaseUrl.trim() || !apiKey.trim()"
@click="persistAndCheck"
>
{{ checking ? '连接中…' : '保存并连接' }}
</button>
</section>
<section class="popup-card space-y-2">
<div class="flex items-center justify-between gap-2">
<h2 class="popup-section-title">功能</h2>
<button
class="popup-link"
type="button"
:disabled="featuresLoading || busy || checking || !hasConfig"
:title="featuresUpdatedAt ? `更新于 ${featuresUpdatedAt}` : ''"
@click="loadFeatures"
>
{{ featuresLoading ? '…' : '刷新' }}
</button>
</div>
<p v-if="!hasConfig" class="popup-hint">先填写上方连接配置</p>
<p v-else-if="!matchedFeatures.length && !featuresLoading" class="popup-hint">
{{ features.length ? '当前页无匹配功能,请打开对应后台页' : '暂无清单,点「刷新」或「保存并连接」' }}
</p>
<div v-for="item in matchedFeatures" :key="item.id" class="popup-feature">
<div class="min-w-0 flex-1">
<div class="truncate text-sm font-medium text-antd-text">{{ item.name }}</div>
<div class="text-[11px] text-antd-text-tertiary">v{{ item.version }}</div>
</div>
<div class="flex shrink-0 gap-1.5">
<button
v-if="activeFeatureId === item.id"
class="popup-btn popup-btn-ghost"
type="button"
:disabled="busy || checking"
@click="handleCloseFeature"
>
关闭
</button>
<button
class="popup-btn popup-btn-primary"
type="button"
:disabled="busy || checking"
@click="handleOpenFeature(item)"
>
{{ activeFeatureId === item.id ? '重新打开' : '打开' }}
</button>
</div>
</div>
</section>
<p v-if="statusText" class="popup-status">{{ statusText }}</p>
<p v-if="errorText" class="popup-error">{{ errorText }}</p>
</div>
</template>
@@ -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');
@@ -0,0 +1,64 @@
import type { ExtensionMessage, ExtensionResponse } from '@/shared/messages';
import { ExtensionError } from '@/shared/errors';
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',
'无法连接页面脚本。请刷新目标页面后再打开功能。',
);
}
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 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' });
}
export async function mountFeatureOnPage(
featureId: string,
code: string,
): Promise<{ featureId: string | null }> {
return sendToActiveTab<{ featureId: string | null }>({
type: 'MOUNT_FEATURE',
payload: { featureId, code },
});
}
export async function unmountFeatureOnPage(): Promise<{ featureId: string | null }> {
return sendToActiveTab<{ featureId: string | null }>({ type: 'UNMOUNT_FEATURE' });
}
+265
View File
@@ -0,0 +1,265 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
html,
body {
margin: 0;
min-width: 320px;
color: rgba(0, 0, 0, 0.88);
background: #f5f5f5;
font-family:
-apple-system,
BlinkMacSystemFont,
'Segoe UI',
Roboto,
'Helvetica Neue',
Arial,
'Noto Sans',
sans-serif;
scrollbar-width: thin;
scrollbar-color: rgb(0 0 0 / 0.28) transparent;
}
html::-webkit-scrollbar,
body::-webkit-scrollbar,
.popup-root::-webkit-scrollbar {
width: 6px;
height: 6px;
}
html::-webkit-scrollbar-thumb,
body::-webkit-scrollbar-thumb,
.popup-root::-webkit-scrollbar-thumb {
background: rgb(0 0 0 / 0.28);
border-radius: 3px;
}
.popup-root {
box-sizing: border-box;
width: 320px;
display: flex;
flex-direction: column;
gap: 10px;
padding: 12px;
background: #f5f5f5;
color: rgba(0, 0, 0, 0.88);
}
.popup-header {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 8px;
padding: 2px 2px 0;
}
.popup-header h1 {
margin: 0;
font-size: 15px;
font-weight: 600;
line-height: 1.3;
}
.popup-sub {
margin: 2px 0 0;
font-size: 12px;
color: rgba(0, 0, 0, 0.45);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
max-width: 220px;
}
.popup-card {
border: 1px solid #f0f0f0;
border-radius: 12px;
background: #fff;
padding: 12px;
box-shadow: 0 1px 2px rgb(0 0 0 / 0.03);
}
.popup-section-title {
margin: 0;
font-size: 12px;
font-weight: 600;
color: rgba(0, 0, 0, 0.45);
}
.popup-label {
display: block;
font-size: 12px;
color: rgba(0, 0, 0, 0.45);
}
.popup-input {
box-sizing: border-box;
display: block;
width: 100%;
margin-top: 4px;
border: 1px solid #d9d9d9;
border-radius: 8px;
padding: 6px 10px;
font-size: 13px;
outline: none;
background: #fff;
color: rgba(0, 0, 0, 0.88);
}
.popup-input:focus {
border-color: #1677ff;
box-shadow: 0 0 0 2px rgb(22 119 255 / 0.2);
}
.popup-btn {
border-radius: 8px;
border: 1px solid #d9d9d9;
background: #fff;
color: rgba(0, 0, 0, 0.88);
padding: 5px 10px;
font-size: 12px;
line-height: 1.4;
cursor: pointer;
transition:
color 0.15s,
border-color 0.15s,
background 0.15s;
}
.popup-btn:disabled {
opacity: 0.45;
cursor: not-allowed;
}
.popup-btn-primary {
border-color: #1677ff;
background: #1677ff;
color: #fff;
}
.popup-btn-primary:hover:not(:disabled) {
border-color: #4096ff;
background: #4096ff;
}
.popup-btn-ghost:hover:not(:disabled) {
color: #1677ff;
border-color: #1677ff;
}
.popup-link {
border: 0;
background: transparent;
color: #1677ff;
font-size: 12px;
padding: 0;
cursor: pointer;
white-space: nowrap;
}
.popup-link:hover:not(:disabled) {
text-decoration: underline;
}
.popup-link:disabled {
opacity: 0.45;
cursor: not-allowed;
}
.popup-feature {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
border: 1px solid #f0f0f0;
border-radius: 8px;
background: #fafafa;
padding: 8px 10px;
}
.popup-hint {
margin: 0;
font-size: 12px;
color: rgba(0, 0, 0, 0.25);
line-height: 1.4;
}
.popup-status {
margin: 0;
font-size: 12px;
color: #52c41a;
line-height: 1.4;
}
.popup-error {
margin: 0;
font-size: 12px;
color: #ff4d4f;
line-height: 1.4;
}
.w-full {
width: 100%;
}
.space-y-2 > * + * {
margin-top: 8px;
}
.flex {
display: flex;
}
.items-center {
align-items: center;
}
.justify-between {
justify-content: space-between;
}
.gap-1\.5 {
gap: 6px;
}
.gap-2 {
gap: 8px;
}
.min-w-0 {
min-width: 0;
}
.flex-1 {
flex: 1;
}
.shrink-0 {
flex-shrink: 0;
}
.truncate {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.text-sm {
font-size: 13px;
}
.font-medium {
font-weight: 500;
}
.text-antd-text {
color: rgba(0, 0, 0, 0.88);
}
.text-antd-text-tertiary {
color: rgba(0, 0, 0, 0.25);
}
.text-\[11px\] {
font-size: 11px;
}
@@ -0,0 +1,16 @@
export const EXTENSION_NAME = 'ECBI 数据同步';
export const OPEN_API_PATHS = {
pddShopList: '/open/v1/channel/pdd/shop/list',
pddShopMatchByName: '/open/v1/channel/pdd/shop/match-by-name',
pddGoodsAdFeeBatchImport: '/open/v1/channel/pdd/goods/adfee/batch-import',
pddGoodsAdFeeImportTask: '/open/v1/channel/pdd/goods/adfee/import-task',
extensionFeatureList: '/open/v1/extension/features',
extensionFeatureScript: '/open/v1/extension/features',
} as const;
export const OPEN_SCOPES = {
pddShopRead: 'openapi:shop:pdd:read',
pddGoodsAdFeeImport: 'openapi:product:adfee',
extensionFeatureRead: 'openapi:extension:feature:read',
} as const;
@@ -0,0 +1,136 @@
import type { AdvertisingCostItem } from '@/types/advertisingCost';
export type HeatLevel = 0 | 1 | 2 | 3 | 4;
export interface DayStat {
date: string;
itemCount: number;
feeTotal: number;
level: HeatLevel;
}
export interface HeatDayCell {
date: string;
inRange: boolean;
isToday: boolean;
isPageDate: boolean;
stat: DayStat | null;
level: HeatLevel;
}
function toDateKey(d: Date): string {
const y = d.getFullYear();
const m = String(d.getMonth() + 1).padStart(2, '0');
const day = String(d.getDate()).padStart(2, '0');
return `${y}-${m}-${day}`;
}
function startOfDay(d: Date): Date {
return new Date(d.getFullYear(), d.getMonth(), d.getDate());
}
function addDays(d: Date, n: number): Date {
const next = new Date(d);
next.setDate(next.getDate() + n);
return next;
}
/** 按花费分档:0 无数据,1~4 由浅到深 */
export function feeToLevel(feeTotal: number, maxFee: number): HeatLevel {
if (feeTotal <= 0 || maxFee <= 0) return 0;
const ratio = feeTotal / maxFee;
if (ratio <= 0.25) return 1;
if (ratio <= 0.5) return 2;
if (ratio <= 0.75) return 3;
return 4;
}
export function summarizeByDate(items: AdvertisingCostItem[]): Map<string, DayStat> {
const map = new Map<string, { itemCount: number; feeTotal: number }>();
for (const item of items) {
const prev = map.get(item.feeDate) ?? { itemCount: 0, feeTotal: 0 };
prev.itemCount += 1;
prev.feeTotal += Number(item.feeAmount) || 0;
map.set(item.feeDate, prev);
}
let maxFee = 0;
for (const value of map.values()) {
maxFee = Math.max(maxFee, value.feeTotal);
}
const result = new Map<string, DayStat>();
for (const [date, value] of map) {
result.set(date, {
date,
itemCount: value.itemCount,
feeTotal: value.feeTotal,
level: feeToLevel(value.feeTotal, maxFee),
});
}
return result;
}
/**
* GitHub 贡献图布局:列=周(旧→新),行=周日…周六。
* weeks 默认 13(约一季,适合窄面板)。
*/
export function buildHeatmapWeeks(options: {
weeks?: number;
endDate?: Date;
stats: Map<string, DayStat>;
pageDate?: string;
}): HeatDayCell[][] {
const weeks = options.weeks ?? 13;
const end = startOfDay(options.endDate ?? new Date());
const todayKey = toDateKey(end);
// 对齐到本周周六(与 GitHub 行末一致:日一二三四五六)
const endWeekday = end.getDay(); // 0=Sun
const gridEnd = addDays(end, 6 - endWeekday);
const totalDays = weeks * 7;
const gridStart = addDays(gridEnd, -(totalDays - 1));
const columns: HeatDayCell[][] = [];
for (let w = 0; w < weeks; w++) {
const col: HeatDayCell[] = [];
for (let dow = 0; dow < 7; dow++) {
const date = addDays(gridStart, w * 7 + dow);
const key = toDateKey(date);
const inRange = date.getTime() <= end.getTime();
const stat = options.stats.get(key) ?? null;
col.push({
date: key,
inRange,
isToday: key === todayKey,
isPageDate: Boolean(options.pageDate && key === options.pageDate),
stat,
level: inRange ? (stat?.level ?? 0) : 0,
});
}
columns.push(col);
}
return columns;
}
export function monthLabelsForWeeks(weeks: HeatDayCell[][]): Array<{ index: number; label: string }> {
const labels: Array<{ index: number; label: string }> = [];
let lastMonth = -1;
for (let i = 0; i < weeks.length; i++) {
const first = weeks[i]?.[0];
if (!first) continue;
const month = Number(first.date.slice(5, 7));
if (month !== lastMonth) {
labels.push({ index: i, label: `${month}月` });
lastMonth = month;
}
}
return labels;
}
export function cellTitle(cell: HeatDayCell): string {
if (!cell.inRange) return cell.date;
if (!cell.stat) {
return cell.isPageDate ? `${cell.date} · 当前页面日期(未读取)` : `${cell.date} · 未读取`;
}
return `${cell.date} · ${cell.stat.itemCount} 条 · ¥${cell.stat.feeTotal.toFixed(2)}`;
}
@@ -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 '发生未知错误,请稍后重试';
}
@@ -0,0 +1,36 @@
import type { AdvertisingCostItem } from '@/types/advertisingCost';
function itemKey(item: AdvertisingCostItem): string {
return `${item.feeDate}::${item.goodsId}`;
}
function compareByAmountDesc(a: AdvertisingCostItem, b: AdvertisingCostItem): number {
const byAmount = Number(b.feeAmount) - Number(a.feeAmount);
if (byAmount !== 0) return byAmount;
const byDate = b.feeDate.localeCompare(a.feeDate);
if (byDate !== 0) return byDate;
return a.goodsId.localeCompare(b.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(compareByAmountDesc);
}
export function listFeeDates(items: AdvertisingCostItem[]): string[] {
return [...new Set(items.map((item) => item.feeDate))].sort();
}
@@ -0,0 +1,40 @@
import type { AdvertisingCostBatch, PageContext } from '@/types/advertisingCost';
import type { ExtensionFeatureManifest } from '@/features/runtime/types';
export type ExtensionMessage =
| { type: 'GET_PAGE_CONTEXT' }
| { type: 'PARSE_ADVERTISING_COST' }
| { type: 'TOGGLE_FLOATING_PANEL' }
| { type: 'SET_FLOATING_PANEL'; payload: { visible: boolean } }
| { type: 'GET_FLOATING_PANEL_STATE' }
| { type: 'MOUNT_FEATURE'; payload: { featureId: string; code: string } }
| { type: 'UNMOUNT_FEATURE' }
| { type: 'GET_ACTIVE_FEATURE' }
| { type: 'PING' };
export type ExtensionResponse =
| { ok: true; data: PageContext }
| { ok: true; data: AdvertisingCostBatch }
| { ok: true; data: { pong: true } }
| { ok: true; data: { visible: boolean } }
| { ok: true; data: { featureId: string | null } }
| { ok: true; data: ExtensionFeatureManifest }
| { 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',
'MOUNT_FEATURE',
'UNMOUNT_FEATURE',
'GET_ACTIVE_FEATURE',
'PING',
]);
export function isExtensionMessage(value: unknown): value is ExtensionMessage {
if (!value || typeof value !== 'object') return false;
const type = (value as { type?: unknown }).type;
return typeof type === 'string' && MESSAGE_TYPES.has(type);
}
@@ -0,0 +1,60 @@
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 type SettingsOverride = {
get: () => Promise<ExtensionSettings>;
save: (patch: Partial<ExtensionSettings>) => Promise<ExtensionSettings>;
};
let settingsOverride: SettingsOverride | null = null;
/** 功能包在 main world 安装桥接实现时调用 */
export function setSettingsOverride(override: SettingsOverride | null): void {
settingsOverride = override;
}
export async function getSettings(): Promise<ExtensionSettings> {
if (settingsOverride) {
return settingsOverride.get();
}
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> {
if (settingsOverride) {
return settingsOverride.save(patch);
}
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;
}
@@ -0,0 +1 @@
export type { ExtensionSettings } from './settings';
@@ -0,0 +1,39 @@
/** 插件侧统一广告费模型(平台无关) */
export type PlatformType = 'pdd' | 'taobao' | 'jd' | 'mock' | 'unknown';
/** 单条推广费:日期来自页面数据本身,不由用户手选 */
export interface AdvertisingCostItem {
/** 统计日期 YYYY-MM-DD(每条各自一份) */
feeDate: string;
goodsId: string;
feeAmount: number;
metadata?: Record<string, unknown>;
}
/**
* 一次读取/同步批次。
* channelShopId = BI channel_pdd_shop.id(不是 mallId)
* 日期在 items[].feeDate,由 Adapter 从页面解析
*/
export interface AdvertisingCostBatch {
platform: PlatformType;
channelShopId: number;
items: AdvertisingCostItem[];
source: 'browser-extension';
importedAt: string;
}
export interface PageContext {
url: string;
title: string;
platform: PlatformType;
ready: boolean;
message?: string;
/** 页面展示的店铺名(用于匹配 BI channelShop) */
mallName?: string;
/** 单日模式下的统计日期 YYYY-MM-DD */
feeDate?: string;
/** single=可同步;range=范围报表不记录 */
dateMode?: 'single' | 'range' | 'unknown';
}