From c35c985eb0b781f3f4b3a72ee6948e2176f6dd4b Mon Sep 17 00:00:00 2001 From: ah-max150 Date: Sun, 16 Aug 2026 17:28:53 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E5=AE=8C=E6=88=90=E5=A4=9A=E6=97=A5?= =?UTF-8?q?=E8=AF=BB=E5=8F=96=E6=94=AF=E6=8C=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- browser-extension/.gitignore | 1 + browser-extension/README.md | 32 +- browser-extension/design.md | 12 +- browser-extension/package.json | 1 + .../src/api/open/pddGoodsAdFee.ts | 4 +- .../src/content/floating/FloatingPanel.vue | 433 ++++++++++++++++++ .../src/content/floating/mount.ts | 121 +++++ .../src/content/floating/styles.css | 222 +++++++++ browser-extension/src/content/index.ts | 20 +- browser-extension/src/env.d.ts | 5 + .../src/platform/core/PlatformAdapter.ts | 3 +- .../src/platform/core/PlatformDetector.ts | 7 +- .../src/platform/mock/MockPlatformAdapter.ts | 21 +- .../src/platform/pdd/PddPlatformAdapter.ts | 71 +++ .../src/platform/pdd/matchShop.ts | 26 ++ .../src/platform/pdd/parseReport.ts | 157 +++++++ .../src/platform/pdd/selectors.ts | 18 + browser-extension/src/popup/App.vue | 267 ++++------- browser-extension/src/popup/messaging.ts | 25 +- browser-extension/src/shared/mergeItems.ts | 30 ++ browser-extension/src/shared/messages.ts | 21 +- .../src/types/advertisingCost.ts | 12 +- 22 files changed, 1263 insertions(+), 246 deletions(-) create mode 100644 browser-extension/src/content/floating/FloatingPanel.vue create mode 100644 browser-extension/src/content/floating/mount.ts create mode 100644 browser-extension/src/content/floating/styles.css create mode 100644 browser-extension/src/platform/pdd/PddPlatformAdapter.ts create mode 100644 browser-extension/src/platform/pdd/matchShop.ts create mode 100644 browser-extension/src/platform/pdd/parseReport.ts create mode 100644 browser-extension/src/platform/pdd/selectors.ts create mode 100644 browser-extension/src/shared/mergeItems.ts diff --git a/browser-extension/.gitignore b/browser-extension/.gitignore index e921db93..af6b9dde 100644 --- a/browser-extension/.gitignore +++ b/browser-extension/.gitignore @@ -2,3 +2,4 @@ dist node_modules *.local .DS_Store +temp \ No newline at end of file diff --git a/browser-extension/README.md b/browser-extension/README.md index 438ab065..f4725e93 100644 --- a/browser-extension/README.md +++ b/browser-extension/README.md @@ -39,20 +39,20 @@ pnpm build ## 项目架构 ```text -Popup(配置 / 选店 / 读数 / 同步) +Popup(配置 API Key / 默认店铺 / 打开悬浮层) ↓ chrome.tabs.sendMessage -Content Script(Platform Adapter) - ↓ Mock / 未来真实平台 -统一 AdvertisingCostBatch - ↓ 映射 -BI Open API(API Key) +Content Script + ├─ 页内悬浮层(选日期、自动读取、同步) + └─ Platform Adapter(当前 Mock) + ↓ +BI Open API ``` | 环境 | 职责 | |------|------| -| Popup | UI、配置、选 channelShopId、发起同步 | -| Content Script | 调 Adapter,不直接调 BI API | -| Background | 生命周期占位,业务不塞这里 | +| Popup | 配置、打开/开关页内悬浮层 | +| Content 悬浮层 | 选日期(变更自动读取)、选店、预览、同步到 BI | +| Background | 生命周期占位 | 新增平台:在 `src/platform//` 实现 `PlatformAdapter`,并注册到 `PlatformDetector`。 @@ -75,7 +75,7 @@ Key 需具备: | 插件 | 后端 batch-import | |------|-------------------| | `channelShopId` | `channelShopId`(`channel_pdd_shop.id`) | -| `feeDate` | `feeDate`(YYYY-MM-DD,以 Popup 所选为准) | +| `items[].feeDate` | `feeDate`(YYYY-MM-DD,来自页面每条数据) | | `items[].goodsId` | `goodsId` | | `items[].feeAmount` | `feeAmount`(元) | @@ -86,11 +86,15 @@ Key 需具备: 鉴权头:`X-Api-Key: `(或 `Authorization: Bearer `)。 -## 当前 Mock 说明 +## 当前能力说明 -- 任意页面均可由 `MockPlatformAdapter` 处理 -- 「读取数据」返回 3 条样例 `goodsId` / 金额 -- 同步仍会打真实 Open API;若要用 Mock 联调,请先在 BI 侧准备对应 `channel_pdd_goods` 与 Key +- **拼多多推广总览**(`yingxiao.pinduoduo.com/.../report/promotion/overView`)已接入真实 DOM 解析: + - 店铺名:`AccountNew_mallName` → 调用店铺分页接口按名匹配 `channelShopId` + - 日期:URL `beginDate`/`endDate`(或主 RangePicker);**仅 begin=end 的单日**才读取 + - 商品:`OverviewTable_goodsId`;费用列:**总花费(元)** +- 范围日期报表会提示「不记录」,不写入预览/同步 +- 非上述页面仍回退 `MockPlatformAdapter` 便于本地联调 +- Popup 只负责配置与打开悬浮层 ## 权限说明 diff --git a/browser-extension/design.md b/browser-extension/design.md index 7551c923..76d6d017 100644 --- a/browser-extension/design.md +++ b/browser-extension/design.md @@ -188,6 +188,8 @@ interface PlatformAdapter { ```ts /** 单条商品广告费(插件内统一模型) */ interface AdvertisingCostItem { + /** 统计日期 YYYY-MM-DD(每条各自一份,来自页面数据) */ + feeDate: string; /** 平台商品 ID,如拼多多 goods_id */ goodsId: string; /** 广告费金额(元) */ @@ -199,12 +201,11 @@ interface AdvertisingCostItem { /** * 一次读取/同步的批次(插件内) * channelShopId:BI 侧渠道店铺主键;拼多多 = channel_pdd_shop.id(不是 mallId) - * feeDate:以 Popup 用户选择的同步日期为准(YYYY-MM-DD) + * 日期在 items[].feeDate,由 Adapter 从页面解析,不用用户手选 */ interface AdvertisingCostBatch { platform: 'pdd' | 'taobao' | 'jd' | 'mock'; channelShopId: number; - feeDate: string; items: AdvertisingCostItem[]; source: 'browser-extension'; importedAt: string; // ISO 时间,仅插件侧审计用,不必提交后端 @@ -263,7 +264,7 @@ interface BatchImportPddGoodsAdFeeRequest { AdvertisingCostBatch → items[] = batch.items.map(i => ({ channelShopId: batch.channelShopId, - feeDate: batch.feeDate, // 整批同一天 + feeDate: i.feeDate, // 每条各自日期 goodsId: i.goodsId, feeAmount: i.feeAmount, })) @@ -450,7 +451,7 @@ BI 渠道店铺:测试店铺(channelShopId=1) 调用 Open API:`POST .../channel/pdd/goods/adfee/batch-import`(开发环境可用 Mock Client 或真实 Key)。 -日期约定:**以 Popup 所选「同步日期」为准**写入每条 `feeDate`;页面解析出的日期仅作校验/提示,不一致时提示用户确认后再同步。 +日期约定:**每条推广数据自带 `feeDate`**(由 Adapter 从页面解析);悬浮层 / Popup **不提供手选同步日期**。 --- @@ -467,9 +468,6 @@ type ExtensionMessage = } | { type: 'PARSE_ADVERTISING_COST'; - payload: { - feeDate: string; // YYYY-MM-DD,与 Popup 同步日期一致 - }; } | { type: 'SYNC_ADVERTISING_COST'; diff --git a/browser-extension/package.json b/browser-extension/package.json index 7d16a0e9..2f78963e 100644 --- a/browser-extension/package.json +++ b/browser-extension/package.json @@ -24,6 +24,7 @@ "autoprefixer": "^10.4.20", "eslint": "^9.17.0", "eslint-plugin-vue": "^9.32.0", + "linkedom": "^0.18.13", "postcss": "^8.4.49", "prettier": "^3.4.2", "tailwindcss": "^3.4.17", diff --git a/browser-extension/src/api/open/pddGoodsAdFee.ts b/browser-extension/src/api/open/pddGoodsAdFee.ts index 5ae613fd..83c5d9f8 100644 --- a/browser-extension/src/api/open/pddGoodsAdFee.ts +++ b/browser-extension/src/api/open/pddGoodsAdFee.ts @@ -27,14 +27,14 @@ export interface BatchImportPddGoodsAdFeeResult { }>; } -/** 插件统一模型 → 后端 batch-import 入参 */ +/** 插件统一模型 → 后端 batch-import 入参(日期取自每条 item) */ export function toBatchImportRequest( batch: AdvertisingCostBatch, ): BatchImportPddGoodsAdFeeRequest { return { items: batch.items.map((item) => ({ channelShopId: batch.channelShopId, - feeDate: batch.feeDate, + feeDate: item.feeDate, goodsId: item.goodsId, feeAmount: item.feeAmount, })), diff --git a/browser-extension/src/content/floating/FloatingPanel.vue b/browser-extension/src/content/floating/FloatingPanel.vue new file mode 100644 index 00000000..865cb399 --- /dev/null +++ b/browser-extension/src/content/floating/FloatingPanel.vue @@ -0,0 +1,433 @@ + + + diff --git a/browser-extension/src/content/floating/mount.ts b/browser-extension/src/content/floating/mount.ts new file mode 100644 index 00000000..2deb0502 --- /dev/null +++ b/browser-extension/src/content/floating/mount.ts @@ -0,0 +1,121 @@ +import { createApp, type App } from 'vue'; + +import FloatingPanel from './FloatingPanel.vue'; +import styles from './styles.css?inline'; + +const HOST_ID = 'ecbi-float-host'; +const LAUNCHER_ID = 'ecbi-float-launcher'; + +let app: App | null = null; +let visible = false; +let minimized = false; + +function ensureHost(): HTMLElement { + let host = document.getElementById(HOST_ID); + if (!host) { + host = document.createElement('div'); + host.id = HOST_ID; + document.documentElement.appendChild(host); + } + return host; +} + +function ensureShadow(host: HTMLElement): ShadowRoot { + return host.shadowRoot ?? host.attachShadow({ mode: 'open' }); +} + +function removeLauncher() { + document.getElementById(LAUNCHER_ID)?.remove(); +} + +function showLauncher() { + removeLauncher(); + const btn = document.createElement('button'); + btn.id = LAUNCHER_ID; + btn.type = 'button'; + btn.textContent = 'ECBI'; + btn.title = '展开 ECBI 悬浮面板'; + Object.assign(btn.style, { + position: 'fixed', + right: '16px', + bottom: '16px', + zIndex: '2147483646', + border: '0', + borderRadius: '999px', + padding: '10px 14px', + background: '#0f172a', + color: '#fff', + fontSize: '12px', + fontWeight: '600', + cursor: 'pointer', + boxShadow: '0 8px 20px rgb(15 23 42 / 0.25)', + } as CSSStyleDeclaration); + btn.addEventListener('click', () => { + minimized = false; + setFloatingVisible(true); + }); + document.documentElement.appendChild(btn); +} + +function unmountApp() { + if (app) { + app.unmount(); + app = null; + } + const host = document.getElementById(HOST_ID); + if (host?.shadowRoot) { + host.shadowRoot.innerHTML = ''; + } +} + +function mountApp() { + const host = ensureHost(); + const shadow = ensureShadow(host); + shadow.innerHTML = ''; + + const styleEl = document.createElement('style'); + styleEl.textContent = styles; + shadow.appendChild(styleEl); + + const mountEl = document.createElement('div'); + shadow.appendChild(mountEl); + + app = createApp(FloatingPanel, { + onClose: () => setFloatingVisible(false), + onMinimize: () => { + minimized = true; + unmountApp(); + showLauncher(); + visible = true; + }, + }); + app.mount(mountEl); +} + +export function isFloatingVisible(): boolean { + return visible; +} + +export function setFloatingVisible(next: boolean): boolean { + if (!next) { + visible = false; + minimized = false; + unmountApp(); + removeLauncher(); + return false; + } + + visible = true; + removeLauncher(); + if (minimized) { + minimized = false; + } + if (!app) { + mountApp(); + } + return true; +} + +export function toggleFloatingPanel(): boolean { + return setFloatingVisible(!visible || minimized); +} diff --git a/browser-extension/src/content/floating/styles.css b/browser-extension/src/content/floating/styles.css new file mode 100644 index 00000000..c984c91a --- /dev/null +++ b/browser-extension/src/content/floating/styles.css @@ -0,0 +1,222 @@ +#ecbi-float-host { + all: initial; +} + +.ecbi-panel { + position: fixed; + z-index: 2147483646; + width: 360px; + max-height: min(560px, calc(100vh - 24px)); + overflow: hidden; + display: flex; + flex-direction: column; + border-radius: 12px; + border: 1px solid #e2e8f0; + background: #ffffff; + color: #0f172a; + box-shadow: + 0 10px 15px -3px rgb(15 23 42 / 0.12), + 0 4px 6px -4px rgb(15 23 42 / 0.08); + font-family: + ui-sans-serif, + system-ui, + -apple-system, + 'Segoe UI', + Roboto, + 'Helvetica Neue', + Arial, + 'Noto Sans', + sans-serif; + font-size: 13px; + line-height: 1.4; +} + +.ecbi-header { + display: flex; + align-items: center; + justify-content: space-between; + gap: 8px; + padding: 10px 12px; + background: #0f172a; + color: #f8fafc; + cursor: move; + user-select: none; +} + +.ecbi-header h1 { + margin: 0; + font-size: 13px; + font-weight: 600; +} + +.ecbi-header p { + margin: 2px 0 0; + font-size: 11px; + opacity: 0.75; +} + +.ecbi-header-actions { + display: flex; + gap: 4px; +} + +.ecbi-icon-btn { + border: 0; + background: transparent; + color: #e2e8f0; + width: 24px; + height: 24px; + border-radius: 6px; + cursor: pointer; +} + +.ecbi-icon-btn:hover { + background: rgb(255 255 255 / 0.12); +} + +.ecbi-body { + padding: 12px; + overflow: auto; + display: flex; + flex-direction: column; + gap: 10px; +} + +.ecbi-row { + display: flex; + align-items: center; + justify-content: space-between; + gap: 8px; +} + +.ecbi-label { + color: #64748b; + flex-shrink: 0; +} + +.ecbi-input, +.ecbi-select { + width: 100%; + border: 1px solid #e2e8f0; + border-radius: 8px; + padding: 6px 8px; + font-size: 13px; + outline: none; + background: #fff; + color: #0f172a; + box-sizing: border-box; +} + +.ecbi-input:focus, +.ecbi-select:focus { + border-color: #94a3b8; +} + +.ecbi-field { + display: flex; + flex-direction: column; + gap: 4px; +} + +.ecbi-actions { + display: flex; + gap: 8px; +} + +.ecbi-btn { + flex: 1; + border-radius: 8px; + border: 1px solid #cbd5e1; + background: #fff; + padding: 8px 10px; + font-size: 13px; + font-weight: 500; + cursor: pointer; +} + +.ecbi-btn:disabled { + opacity: 0.5; + cursor: not-allowed; +} + +.ecbi-btn-primary { + border-color: #059669; + background: #059669; + color: #fff; +} + +.ecbi-btn-primary:hover:not(:disabled) { + background: #047857; +} + +.ecbi-btn-ghost:hover:not(:disabled) { + background: #f8fafc; +} + +.ecbi-card { + border: 1px solid #e2e8f0; + border-radius: 8px; + padding: 10px; + background: #f8fafc; +} + +.ecbi-card h2 { + margin: 0 0 8px; + font-size: 11px; + font-weight: 600; + letter-spacing: 0.04em; + text-transform: uppercase; + color: #64748b; +} + +.ecbi-fee { + font-weight: 700; + color: #e11d48; +} + +.ecbi-list { + margin: 8px 0 0; + padding: 0; + list-style: none; + max-height: 120px; + overflow: auto; +} + +.ecbi-list li { + display: flex; + justify-content: space-between; + gap: 8px; + font-size: 12px; + color: #475569; + padding: 2px 0; +} + +.ecbi-muted { + color: #94a3b8; + font-size: 12px; +} + +.ecbi-error { + color: #e11d48; + font-size: 12px; + margin: 0; +} + +.ecbi-ok { + color: #047857; + font-size: 12px; + margin: 0; +} + +.ecbi-link { + border: 0; + background: transparent; + color: #0369a1; + font-size: 12px; + cursor: pointer; + padding: 0; +} + +.ecbi-link:hover { + text-decoration: underline; +} diff --git a/browser-extension/src/content/index.ts b/browser-extension/src/content/index.ts index 2609f580..501b6148 100644 --- a/browser-extension/src/content/index.ts +++ b/browser-extension/src/content/index.ts @@ -7,6 +7,12 @@ import { } from '@/shared/messages'; import type { AdvertisingCostBatch } from '@/types/advertisingCost'; +import { + isFloatingVisible, + setFloatingVisible, + toggleFloatingPanel, +} from './floating/mount'; + async function handleMessage(message: ExtensionMessage): Promise { const adapter = resolveAdapter(location.href); @@ -18,14 +24,24 @@ async function handleMessage(message: ExtensionMessage): Promise; export default component; } + +declare module '*.css?inline' { + const css: string; + export default css; +} diff --git a/browser-extension/src/platform/core/PlatformAdapter.ts b/browser-extension/src/platform/core/PlatformAdapter.ts index 21c83925..5ba965b2 100644 --- a/browser-extension/src/platform/core/PlatformAdapter.ts +++ b/browser-extension/src/platform/core/PlatformAdapter.ts @@ -8,5 +8,6 @@ export interface PlatformAdapter { readonly platform: PlatformType; canHandle(url: string): boolean; getPageContext(): Promise; - parseAdvertisingCost(feeDate: string): Promise>; + /** 从当前页解析推广费;每条 item 自带 feeDate */ + parseAdvertisingCost(): Promise>; } diff --git a/browser-extension/src/platform/core/PlatformDetector.ts b/browser-extension/src/platform/core/PlatformDetector.ts index eef09045..20d8a8c6 100644 --- a/browser-extension/src/platform/core/PlatformDetector.ts +++ b/browser-extension/src/platform/core/PlatformDetector.ts @@ -2,8 +2,9 @@ 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 MockPlatformAdapter()]; +const adapters: PlatformAdapter[] = [new PddPlatformAdapter(), new MockPlatformAdapter()]; export function detectPlatform(url: string): PlatformType { const adapter = adapters.find((item) => item.canHandle(url)); @@ -15,8 +16,8 @@ export function resolveAdapter(url: string): PlatformAdapter { if (matched) { return matched; } - // 第一阶段:未识别平台时回退 Mock,保证链路可跑通 - return adapters[0]!; + // 非拼多多推广页时回退 Mock,便于本地联调 + return adapters.find((item) => item.platform === 'mock') ?? adapters[0]!; } export function listAdapters(): PlatformAdapter[] { diff --git a/browser-extension/src/platform/mock/MockPlatformAdapter.ts b/browser-extension/src/platform/mock/MockPlatformAdapter.ts index aeaf0bdf..239cbb20 100644 --- a/browser-extension/src/platform/mock/MockPlatformAdapter.ts +++ b/browser-extension/src/platform/mock/MockPlatformAdapter.ts @@ -2,13 +2,13 @@ import type { PlatformAdapter } from '@/platform/core/PlatformAdapter'; import type { AdvertisingCostBatch, PageContext } from '@/types/advertisingCost'; /** - * 第一阶段 Mock Adapter:不读真实 DOM,返回固定样例数据。 + * 第一阶段 Mock Adapter:不读真实 DOM,返回带日期的样例。 + * 真实页面解析等接入平台后再实现。 */ export class MockPlatformAdapter implements PlatformAdapter { readonly platform = 'mock' as const; canHandle(_url: string): boolean { - // 未接入真实平台前,任意页面均可由 Mock 处理 return true; } @@ -22,19 +22,14 @@ export class MockPlatformAdapter implements PlatformAdapter { }; } - async parseAdvertisingCost( - feeDate: string, - ): Promise> { - const items = [ - { goodsId: 'mock-goods-1001', feeAmount: 128.5 }, - { goodsId: 'mock-goods-1002', feeAmount: 56.0 }, - { goodsId: 'mock-goods-1003', feeAmount: 1050.06 }, - ]; - + async parseAdvertisingCost(): Promise> { return { platform: 'mock', - feeDate, - items, + 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(), }; diff --git a/browser-extension/src/platform/pdd/PddPlatformAdapter.ts b/browser-extension/src/platform/pdd/PddPlatformAdapter.ts new file mode 100644 index 00000000..d29df8de --- /dev/null +++ b/browser-extension/src/platform/pdd/PddPlatformAdapter.ts @@ -0,0 +1,71 @@ +import type { PlatformAdapter } from '@/platform/core/PlatformAdapter'; +import type { AdvertisingCostBatch, PageContext } from '@/types/advertisingCost'; + +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 { + 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(): Promise> { + const dateInfo = readReportDate(); + if (dateInfo.mode === 'range') { + throw new Error(dateInfo.message ?? '范围报表不记录,请切换为单日查看'); + } + if (dateInfo.mode !== 'single' || !dateInfo.feeDate) { + throw new Error(dateInfo.message ?? '未能识别单日报表日期'); + } + + const items = parsePromotionItems(dateInfo.feeDate); + if (items.length === 0) { + throw new Error('未解析到商品推广费,请确认表格已加载且包含「总花费」列'); + } + + return { + platform: 'pdd', + items, + source: 'browser-extension', + importedAt: new Date().toISOString(), + }; + } +} diff --git a/browser-extension/src/platform/pdd/matchShop.ts b/browser-extension/src/platform/pdd/matchShop.ts new file mode 100644 index 00000000..c99674c4 --- /dev/null +++ b/browser-extension/src/platform/pdd/matchShop.ts @@ -0,0 +1,26 @@ +import type { PddChannelShop } from '@/api/open/pddShop'; +import { listPddChannelShops } from '@/api/open/pddShop'; + +/** + * 用页面店铺名通过 Open 店铺分页接口匹配 BI channelShop。 + * 优先精确匹配 mallName,其次仅当筛选结果唯一时采用。 + */ +export async function matchChannelShopByMallName( + mallName: string, +): Promise { + const name = mallName.trim(); + if (!name) return null; + + const result = await listPddChannelShops({ + page: 1, + pageSize: 50, + filters: { mallName: name }, + }); + const records = result.records ?? []; + if (records.length === 0) return null; + + const exact = records.find((shop) => (shop.mallName ?? '').trim() === name); + if (exact) return exact; + if (records.length === 1) return records[0]!; + return null; +} diff --git a/browser-extension/src/platform/pdd/parseReport.ts b/browser-extension/src/platform/pdd/parseReport.ts new file mode 100644 index 00000000..bb08a8ba --- /dev/null +++ b/browser-extension/src/platform/pdd/parseReport.ts @@ -0,0 +1,157 @@ +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; +} + +/** 优先 URL beginDate/endDate,其次主 RangePicker 两个 input */ +export function readReportDate(doc: Document = document, href = location.href): PddReportDateInfo { + 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 + } + + const pickers = Array.from(doc.querySelectorAll(PDD_SELECTORS.rangePicker)); + for (const picker of pickers) { + // 跳过对比日期区(CompareDate 内嵌 picker) + 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 { mode: 'unknown', message: '未能识别报表日期,请确认已打开商品推广总览且选择了日期' }; +} + +/** + * 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(); + + 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); + if (feeAmount == null) continue; + + seen.add(goodsId); + items.push({ + feeDate, + goodsId, + feeAmount, + metadata: { + goodsName: row + .querySelector('[class*="OverviewTable_goodsName"]') + ?.getAttribute('title') + ?.replace(/^商品名:/, ''), + }, + }); + } + + return items; +} + +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; + } +} diff --git a/browser-extension/src/platform/pdd/selectors.ts b/browser-extension/src/platform/pdd/selectors.ts new file mode 100644 index 00000000..357ecb84 --- /dev/null +++ b/browser-extension/src/platform/pdd/selectors.ts @@ -0,0 +1,18 @@ +/** 拼多多推广报表 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', +} 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})/; diff --git a/browser-extension/src/popup/App.vue b/browser-extension/src/popup/App.vue index b3e90e11..0335d96e 100644 --- a/browser-extension/src/popup/App.vue +++ b/browser-extension/src/popup/App.vue @@ -1,45 +1,24 @@ diff --git a/browser-extension/src/popup/messaging.ts b/browser-extension/src/popup/messaging.ts index 7dddb55c..f5472508 100644 --- a/browser-extension/src/popup/messaging.ts +++ b/browser-extension/src/popup/messaging.ts @@ -1,6 +1,5 @@ import type { ExtensionMessage, ExtensionResponse } from '@/shared/messages'; import { ExtensionError } from '@/shared/errors'; -import type { AdvertisingCostBatch, PageContext } from '@/types/advertisingCost'; async function getActiveTabId(): Promise { const tabs = await chrome.tabs.query({ active: true, currentWindow: true }); @@ -19,7 +18,7 @@ async function sendToActiveTab(message: ExtensionMessage): Promise { } catch { throw new ExtensionError( 'PAGE_NOT_READY', - '无法连接页面脚本。请刷新目标页面后重试(需已注入 Content Script)。', + '无法连接页面脚本。请刷新目标页面后再打开悬浮层。', ); } @@ -35,15 +34,17 @@ async function sendToActiveTab(message: ExtensionMessage): Promise { return response.data as T; } -export async function fetchPageContext(): Promise { - return sendToActiveTab({ type: 'GET_PAGE_CONTEXT' }); -} - -export async function parseAdvertisingCostFromPage( - feeDate: string, -): Promise { - return sendToActiveTab({ - type: 'PARSE_ADVERTISING_COST', - payload: { feeDate }, +export async function openFloatingPanel(): Promise<{ visible: boolean }> { + return sendToActiveTab<{ visible: boolean }>({ + type: 'SET_FLOATING_PANEL', + payload: { visible: true }, }); } + +export async function toggleFloatingPanel(): Promise<{ visible: boolean }> { + return sendToActiveTab<{ visible: boolean }>({ type: 'TOGGLE_FLOATING_PANEL' }); +} + +export async function getFloatingPanelState(): Promise<{ visible: boolean }> { + return sendToActiveTab<{ visible: boolean }>({ type: 'GET_FLOATING_PANEL_STATE' }); +} diff --git a/browser-extension/src/shared/mergeItems.ts b/browser-extension/src/shared/mergeItems.ts new file mode 100644 index 00000000..0fa6bcd9 --- /dev/null +++ b/browser-extension/src/shared/mergeItems.ts @@ -0,0 +1,30 @@ +import type { AdvertisingCostItem } from '@/types/advertisingCost'; + +function itemKey(item: AdvertisingCostItem): string { + return `${item.feeDate}::${item.goodsId}`; +} + +/** + * 合并多次单日读取:按 (feeDate, goodsId) upsert。 + * 换日再读保留已有日期;同日再读覆盖该日同商品。 + */ +export function mergeAdvertisingItems( + previous: AdvertisingCostItem[], + incoming: AdvertisingCostItem[], +): AdvertisingCostItem[] { + const map = new Map(); + 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((a, b) => { + const byDate = a.feeDate.localeCompare(b.feeDate); + return byDate !== 0 ? byDate : a.goodsId.localeCompare(b.goodsId); + }); +} + +export function listFeeDates(items: AdvertisingCostItem[]): string[] { + return [...new Set(items.map((item) => item.feeDate))].sort(); +} diff --git a/browser-extension/src/shared/messages.ts b/browser-extension/src/shared/messages.ts index 7163d1b9..532ab9d3 100644 --- a/browser-extension/src/shared/messages.ts +++ b/browser-extension/src/shared/messages.ts @@ -2,21 +2,30 @@ import type { AdvertisingCostBatch, PageContext } from '@/types/advertisingCost' export type ExtensionMessage = | { type: 'GET_PAGE_CONTEXT' } - | { type: 'PARSE_ADVERTISING_COST'; payload: { feeDate: string } } + | { type: 'PARSE_ADVERTISING_COST' } + | { type: 'TOGGLE_FLOATING_PANEL' } + | { type: 'SET_FLOATING_PANEL'; payload: { visible: boolean } } + | { type: 'GET_FLOATING_PANEL_STATE' } | { type: 'PING' }; export type ExtensionResponse = | { ok: true; data: PageContext } | { ok: true; data: AdvertisingCostBatch } | { ok: true; data: { pong: true } } + | { ok: true; data: { visible: boolean } } | { 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', + 'PING', +]); + export function isExtensionMessage(value: unknown): value is ExtensionMessage { if (!value || typeof value !== 'object') return false; const type = (value as { type?: unknown }).type; - return ( - type === 'GET_PAGE_CONTEXT' || - type === 'PARSE_ADVERTISING_COST' || - type === 'PING' - ); + return typeof type === 'string' && MESSAGE_TYPES.has(type); } diff --git a/browser-extension/src/types/advertisingCost.ts b/browser-extension/src/types/advertisingCost.ts index e9e17c26..5bb08d70 100644 --- a/browser-extension/src/types/advertisingCost.ts +++ b/browser-extension/src/types/advertisingCost.ts @@ -2,7 +2,10 @@ export type PlatformType = 'pdd' | 'taobao' | 'jd' | 'mock' | 'unknown'; +/** 单条推广费:日期来自页面数据本身,不由用户手选 */ export interface AdvertisingCostItem { + /** 统计日期 YYYY-MM-DD(每条各自一份) */ + feeDate: string; goodsId: string; feeAmount: number; metadata?: Record; @@ -11,12 +14,11 @@ export interface AdvertisingCostItem { /** * 一次读取/同步批次。 * channelShopId = BI channel_pdd_shop.id(不是 mallId) - * feeDate = Popup 所选日期 YYYY-MM-DD + * 日期在 items[].feeDate,由 Adapter 从页面解析 */ export interface AdvertisingCostBatch { platform: PlatformType; channelShopId: number; - feeDate: string; items: AdvertisingCostItem[]; source: 'browser-extension'; importedAt: string; @@ -28,4 +30,10 @@ export interface PageContext { platform: PlatformType; ready: boolean; message?: string; + /** 页面展示的店铺名(用于匹配 BI channelShop) */ + mallName?: string; + /** 单日模式下的统计日期 YYYY-MM-DD */ + feeDate?: string; + /** single=可同步;range=范围报表不记录 */ + dateMode?: 'single' | 'range' | 'unknown'; }