mirror of
https://gitee.com/qqtt-ah/ai-crm.git
synced 2026-11-25 03:09:20 +08:00
init
This commit is contained in:
@@ -0,0 +1,7 @@
|
||||
dist
|
||||
dist-features
|
||||
artifacts
|
||||
node_modules
|
||||
*.local
|
||||
.DS_Store
|
||||
temp
|
||||
@@ -0,0 +1 @@
|
||||
ignore-workspace=true
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"singleQuote": true,
|
||||
"semi": true,
|
||||
"trailingComma": "all",
|
||||
"printWidth": 100
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
# ECBI 数据同步扩展
|
||||
|
||||
企业内部用 Chromium 扩展(Manifest V3):在电商后台页面由用户主动读取推广费用,经统一模型通过 **Open API** 同步到 BI。
|
||||
|
||||
第一阶段:**工程骨架 + Mock Adapter**,不解析真实平台 DOM。
|
||||
|
||||
## 环境要求
|
||||
|
||||
- Node.js >= 18
|
||||
- pnpm >= 9
|
||||
|
||||
## 安装依赖
|
||||
|
||||
```bash
|
||||
cd apps/browser-extension
|
||||
pnpm install
|
||||
```
|
||||
|
||||
## 开发
|
||||
|
||||
```bash
|
||||
pnpm dev
|
||||
```
|
||||
|
||||
## 构建
|
||||
|
||||
```bash
|
||||
pnpm build
|
||||
```
|
||||
|
||||
产物(统一在 `artifacts/`,已 gitignore):
|
||||
|
||||
| 路径 | 说明 |
|
||||
|------|------|
|
||||
| `artifacts/extension/` | 扩展壳(可解压加载到浏览器) |
|
||||
| `artifacts/features/` | 功能清单 `manifest.json` + 各功能 JS |
|
||||
| `artifacts/ecbi-data-sync-extension.zip` | 扩展壳压缩包(内含一层 `ecbi-data-sync-extension/` 目录) |
|
||||
|
||||
`pnpm build` 会同步到后端静态目录(本地联调 / 打进 jar):
|
||||
|
||||
| 本地产物 | 后端静态目录 |
|
||||
|----------|--------------|
|
||||
| `artifacts/features/*` | `static/extension-features/` |
|
||||
| `ecbi-data-sync-extension.zip` | `static/extension/` |
|
||||
|
||||
生产更新功能时:只拷贝 `artifacts/features/*` 到服务器 `extension-features/` 即可,扩展壳不必每次重装(壳内 API 未变时)。
|
||||
|
||||
## 安装到 Chrome / Edge
|
||||
|
||||
1. 打开 `chrome://extensions/` 或 `edge://extensions/`
|
||||
2. 开启「开发者模式」
|
||||
3. 「加载已解压的扩展程序」→ 选择 `artifacts/extension`,或后台「开放密钥」页下载 zip 后解压加载
|
||||
|
||||
## 项目架构
|
||||
|
||||
```text
|
||||
Popup(配置 API Key / 默认店铺 / 打开悬浮层)
|
||||
↓ chrome.tabs.sendMessage
|
||||
Content Script
|
||||
├─ 页内悬浮层(选日期、自动读取、同步)
|
||||
└─ Platform Adapter(当前 Mock)
|
||||
↓
|
||||
BI Open API
|
||||
```
|
||||
|
||||
| 环境 | 职责 |
|
||||
|------|------|
|
||||
| Popup | 配置、打开/开关页内悬浮层 |
|
||||
| Content 悬浮层 | 选日期(变更自动读取)、选店、预览、同步到 BI |
|
||||
| Background | 生命周期占位 |
|
||||
|
||||
新增平台:在 `src/platform/<name>/` 实现 `PlatformAdapter`,并注册到 `PlatformDetector`。
|
||||
|
||||
## 配置 BI Open API
|
||||
|
||||
Popup 右上角「配置」:
|
||||
|
||||
| 项 | 说明 |
|
||||
|----|------|
|
||||
| Base URL | 例 `http://localhost:8080/api`(**直连后端**,不要用前端 dev 的 `5666`;不要末尾 `/`) |
|
||||
| API Key | 后台创建的 Open API Key(`sk_...`),**不要**填登录 JWT |
|
||||
|
||||
Open API 请求由 **Background Service Worker 代发**(Content Script 在 HTTPS 拼多多页内不能直连 `http://localhost`,会被混合内容/CORS 拦截,Network 里常无 HTTP 状态码)。
|
||||
|
||||
Key 建议具备:
|
||||
|
||||
- `openapi:extension:feature:read`(功能清单/脚本)
|
||||
- `openapi:shop:pdd:read`
|
||||
- `openapi:product:adfee`
|
||||
|
||||
## 功能清单(静态 JSON)方案
|
||||
|
||||
清单与脚本放在同一静态目录,例如:
|
||||
|
||||
```text
|
||||
static/extension-features/
|
||||
manifest.json
|
||||
pdd-ad-fee.js
|
||||
```
|
||||
|
||||
- **直接读静态文件**:可以,部署简单;但无 API Key 鉴权(取决于网关是否暴露 `/static/**`)。
|
||||
- **推荐(已实现)**:Open API 读同一份 JSON/脚本并鉴权:
|
||||
- `GET /api/open/v1/extension/features`
|
||||
- `GET /api/open/v1/extension/features/{id}/script`
|
||||
|
||||
扩展 Popup 拉清单 → 打开功能时下载脚本并做 sha256 校验 → 当前 UI 仍由壳内嵌入模块挂载(MV3 限制远程 `eval`);远程包用于版本对齐与后续 main-world 执行。
|
||||
|
||||
## 与后端字段对照
|
||||
|
||||
| 插件 | 后端 batch-import |
|
||||
|------|-------------------|
|
||||
| `channelShopId` | `channelShopId`(`channel_pdd_shop.id`) |
|
||||
| `items[].feeDate` | `feeDate`(YYYY-MM-DD,来自页面每条数据) |
|
||||
| `items[].goodsId` | `goodsId` |
|
||||
| `items[].feeAmount` | `feeAmount`(元) |
|
||||
|
||||
相关接口:
|
||||
|
||||
- `GET /open/v1/extension/features`
|
||||
- `GET /open/v1/extension/features/{id}/script`
|
||||
- `GET /open/v1/channel/pdd/shop/match-by-name?mallName=`
|
||||
- `POST /open/v1/channel/pdd/shop/list`
|
||||
- `POST /open/v1/channel/pdd/goods/adfee/batch-import`
|
||||
|
||||
鉴权头:`X-Api-Key: <key>`(或 `Authorization: Bearer <key>`)。
|
||||
|
||||
## 当前能力说明
|
||||
|
||||
- Popup:配置 Base URL / API Key,拉取远程功能清单并打开/关闭功能
|
||||
- **拼多多商品推广费**(`pdd-ad-fee`):页内悬浮读取/累计/同步(逻辑仍在壳内嵌入;远程 JS 同步发布)
|
||||
- 非推广页仍可用 Mock Adapter 联调链路
|
||||
|
||||
## 权限说明
|
||||
|
||||
Manifest 申请:`storage`、`activeTab`、`scripting`;Content Script 匹配 `http(s)://*/*` 以便开发期注入。接入真实平台后应收窄到具体域名。
|
||||
|
||||
## 设计文档
|
||||
|
||||
见同目录 [design.md](./design.md)。
|
||||
@@ -0,0 +1,765 @@
|
||||
可以。你这个项目适合让 Coding Agent **先只搭架构,不要急着实现具体平台的数据解析**。否则 Agent 很容易一上来就把 `content script / popup / background / API` 搞成一坨。
|
||||
|
||||
你可以直接把下面这段给它:
|
||||
|
||||
````text
|
||||
你现在负责创建一个浏览器扩展项目,项目名称暂定为 `ecbi-data-sync-extension`。
|
||||
|
||||
## 一、项目目标
|
||||
|
||||
这是一个用于企业内部使用的浏览器扩展,主要作用是:
|
||||
|
||||
用户登录电商平台后台后,在平台页面中选择指定日期,扩展读取当前页面中用户有权限看到的业务数据,并将数据转换成统一的数据模型,通过 HTTPS Open API 同步到我自己的 BI 系统。
|
||||
|
||||
第一阶段主要用于“推广费用/广告费用”同步。
|
||||
|
||||
目标浏览器:
|
||||
|
||||
- Google Chrome
|
||||
- Microsoft Edge
|
||||
|
||||
要求使用 Chromium Extension 兼容方案,基于 Manifest V3。
|
||||
|
||||
重要:
|
||||
|
||||
- 不需要发布 Chrome Web Store
|
||||
- 不需要实现自动登录
|
||||
- 不需要保存或上传平台 Cookie
|
||||
- 不需要实现后台自动爬取
|
||||
- 不需要实现定时抓取
|
||||
- 必须由用户主动点击“同步”
|
||||
- 第一阶段不要实现任何具体电商平台的解析逻辑
|
||||
- 当前任务重点是搭建一个可长期扩展的工程架构
|
||||
|
||||
---
|
||||
|
||||
# 二、技术栈
|
||||
|
||||
使用:
|
||||
|
||||
- Vue 3
|
||||
- TypeScript
|
||||
- Vite
|
||||
- Manifest V3
|
||||
- pnpm
|
||||
|
||||
UI:
|
||||
|
||||
- 优先使用 Tailwind CSS
|
||||
- 不使用 Element Plus
|
||||
- 不引入重量级 UI 框架
|
||||
|
||||
代码要求:
|
||||
|
||||
- TypeScript strict
|
||||
- ESLint
|
||||
- Prettier
|
||||
- 合理的类型定义
|
||||
- 模块化设计
|
||||
- 避免 any
|
||||
- 避免把业务逻辑全部写进 Vue 组件
|
||||
- 避免平台相关代码污染公共代码
|
||||
|
||||
---
|
||||
|
||||
# 三、先设计架构,再写代码
|
||||
|
||||
在开始创建文件之前,先分析并输出:
|
||||
|
||||
1. 项目整体架构
|
||||
2. Extension 各运行环境之间的职责
|
||||
3. Popup / Content Script / Background Service Worker 的通信方式
|
||||
4. 平台 Adapter 的设计
|
||||
5. BI API Client 的设计
|
||||
6. 数据模型设计
|
||||
7. Token / 配置存储方案
|
||||
8. Manifest 权限设计
|
||||
9. 后续增加多个电商平台时如何扩展
|
||||
|
||||
确认架构合理后再创建代码。
|
||||
|
||||
---
|
||||
|
||||
# 四、运行环境职责
|
||||
|
||||
严格区分以下三个环境:
|
||||
|
||||
## 1. Popup
|
||||
|
||||
负责:
|
||||
|
||||
- 显示当前平台
|
||||
- 显示当前页面状态
|
||||
- 获取用户配置
|
||||
- 获取 BI Open API Key / Base URL
|
||||
- 选择 BI 渠道店铺(channelShopId)
|
||||
- 显示待同步数据
|
||||
- 用户点击“同步”
|
||||
- 显示同步成功/失败
|
||||
- 显示错误信息
|
||||
|
||||
Popup 不负责直接解析平台 DOM。
|
||||
|
||||
---
|
||||
|
||||
## 2. Content Script
|
||||
|
||||
负责:
|
||||
|
||||
- 运行在目标电商平台页面
|
||||
- 读取当前页面已经展示给用户的数据
|
||||
- 获取当前页面 URL
|
||||
- 获取页面上下文信息
|
||||
- 调用对应平台 Adapter
|
||||
- 将平台数据转换为统一业务模型
|
||||
- 将解析结果返回给 Popup / Background
|
||||
|
||||
第一阶段只提供接口和 Mock Adapter,不实现真实平台解析。
|
||||
|
||||
---
|
||||
|
||||
## 3. Background Service Worker
|
||||
|
||||
负责:
|
||||
|
||||
- Extension 全局事件
|
||||
- Popup / Content Script 消息转发
|
||||
- Extension 生命周期相关逻辑
|
||||
- 后续需要跨页面或后台处理的能力
|
||||
|
||||
不要把所有业务逻辑都塞进 background。
|
||||
|
||||
---
|
||||
|
||||
# 五、平台适配器架构
|
||||
|
||||
这是本项目最重要的架构之一。
|
||||
|
||||
必须设计成:
|
||||
|
||||
```text
|
||||
platform/
|
||||
├── core/
|
||||
│ ├── PlatformAdapter.ts
|
||||
│ ├── PlatformDetector.ts
|
||||
│ └── types.ts
|
||||
│
|
||||
├── mock/
|
||||
│ └── MockPlatformAdapter.ts
|
||||
│
|
||||
├── taobao/
|
||||
│ └── ...
|
||||
│
|
||||
├── jd/
|
||||
│ └── ...
|
||||
│
|
||||
└── pdd/
|
||||
└── ...
|
||||
````
|
||||
|
||||
暂时不要实现淘宝、京东、拼多多等真实平台。
|
||||
|
||||
定义统一接口,例如:
|
||||
|
||||
```ts
|
||||
interface PlatformAdapter {
|
||||
platform: PlatformType;
|
||||
|
||||
canHandle(url: string): boolean;
|
||||
|
||||
getPageContext(): Promise<PageContext>;
|
||||
|
||||
parseAdvertisingCost(): Promise<AdvertisingCostBatch>;
|
||||
}
|
||||
```
|
||||
|
||||
具体接口名称可以根据实际架构调整,但必须保持职责清晰。
|
||||
|
||||
---
|
||||
|
||||
# 六、统一业务数据模型
|
||||
|
||||
不要让 BI 后端直接接收某个平台的原始 DOM 数据。
|
||||
|
||||
定义**插件侧统一模型**,再由 API Client **映射**为后端 Open API 入参。
|
||||
|
||||
## 6.1 插件侧统一模型(平台无关)
|
||||
|
||||
```ts
|
||||
/** 单条商品广告费(插件内统一模型) */
|
||||
interface AdvertisingCostItem {
|
||||
/** 统计日期 YYYY-MM-DD(每条各自一份,来自页面数据) */
|
||||
feeDate: string;
|
||||
/** 平台商品 ID,如拼多多 goods_id */
|
||||
goodsId: string;
|
||||
/** 广告费金额(元) */
|
||||
feeAmount: number;
|
||||
/** 可选扩展,不同平台可塞入 metadata,不直接提交后端 */
|
||||
metadata?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
/**
|
||||
* 一次读取/同步的批次(插件内)
|
||||
* channelShopId:BI 侧渠道店铺主键;拼多多 = channel_pdd_shop.id(不是 mallId)
|
||||
* 日期在 items[].feeDate,由 Adapter 从页面解析,不用用户手选
|
||||
*/
|
||||
interface AdvertisingCostBatch {
|
||||
platform: 'pdd' | 'taobao' | 'jd' | 'mock';
|
||||
channelShopId: number;
|
||||
items: AdvertisingCostItem[];
|
||||
source: 'browser-extension';
|
||||
importedAt: string; // ISO 时间,仅插件侧审计用,不必提交后端
|
||||
}
|
||||
```
|
||||
|
||||
## 6.2 与现有 BI Open API 对齐(第一阶段:拼多多商品广告费)
|
||||
|
||||
后端已实现(路径均带 `/api` 前缀):
|
||||
|
||||
| 能力 | Method / Path | Scope |
|
||||
|------|---------------|--------|
|
||||
| 渠道店铺列表 | `POST /api/open/v1/channel/pdd/shop/list` | `open:scope:pdd_shop:read` |
|
||||
| 商品广告费批量导入 | `POST /api/open/v1/channel/pdd/goods/adfee/batch-import` | `open:scope:pdd_goods_ad_fee:import` |
|
||||
|
||||
### 店铺列表(取 channelShopId)
|
||||
|
||||
请求体与内部接口一致,分页查询:
|
||||
|
||||
```ts
|
||||
// POST /api/open/v1/channel/pdd/shop/list
|
||||
interface PageQuery<TFilters> {
|
||||
page: number;
|
||||
pageSize: number;
|
||||
filters?: TFilters; // 可选:mallName 等
|
||||
}
|
||||
|
||||
// 响应 records[].id 即为 channelShopId(channel_pdd_shop.id)
|
||||
interface PddChannelShop {
|
||||
id: number; // → AdvertisingCostBatch.channelShopId
|
||||
mallId?: number; // 拼多多 mall_id,仅展示/核对,不要当 BI 店铺主键提交
|
||||
mallName?: string;
|
||||
// ...
|
||||
}
|
||||
```
|
||||
|
||||
### 批量导入广告费(提交形态)
|
||||
|
||||
后端入参**仅接受**以下字段,插件必须映射到此结构(不要把 platform / source / importedAt 塞进 body):
|
||||
|
||||
```ts
|
||||
// POST /api/open/v1/channel/pdd/goods/adfee/batch-import
|
||||
interface BatchImportPddGoodsAdFeeRequest {
|
||||
items: Array<{
|
||||
channelShopId: number; // channel_pdd_shop.id
|
||||
feeDate: string; // YYYY-MM-DD
|
||||
goodsId: string; // 拼多多 goods_id
|
||||
feeAmount: number; // 元,>= 0
|
||||
}>;
|
||||
}
|
||||
```
|
||||
|
||||
映射规则:
|
||||
|
||||
```text
|
||||
AdvertisingCostBatch
|
||||
→ items[] = batch.items.map(i => ({
|
||||
channelShopId: batch.channelShopId,
|
||||
feeDate: i.feeDate, // 每条各自日期
|
||||
goodsId: i.goodsId,
|
||||
feeAmount: i.feeAmount,
|
||||
}))
|
||||
```
|
||||
|
||||
后端行为:校验店铺归属 + 该店下存在该 `goods_id`;按 `(channelShopId, goodsId, feeDate)` **upsert**(同日覆盖金额)。
|
||||
|
||||
必须保证:
|
||||
|
||||
平台原始数据 → Platform Adapter → 统一模型 →(映射)→ BI Open API
|
||||
|
||||
而不是:平台 A → 一套 API、平台 B → 另一套 API(多平台仍走统一模型,仅 API Client 按平台选择 endpoint)。
|
||||
|
||||
---
|
||||
|
||||
# 七、BI API Client
|
||||
|
||||
创建独立 API 层,例如:
|
||||
|
||||
```text
|
||||
src/api/
|
||||
├── client.ts # Base URL、Header、超时、错误归一
|
||||
├── open/
|
||||
│ ├── pddShop.ts # POST .../channel/pdd/shop/list
|
||||
│ └── pddGoodsAdFee.ts # POST .../channel/pdd/goods/adfee/batch-import
|
||||
└── types.ts
|
||||
```
|
||||
|
||||
统一处理:
|
||||
|
||||
* Base URL(如 `https://xxx/api` 或含网关前缀,以实际部署为准)
|
||||
* 鉴权 Header(Open API Key,**不是** 系统登录 JWT)
|
||||
* 请求超时
|
||||
* HTTP 错误 / 业务错误(`ApiResponse.code`)/ 网络错误
|
||||
|
||||
鉴权头(二选一,与后端 `ApiKeyAuthenticationFilter` 一致):
|
||||
|
||||
```http
|
||||
X-Api-Key: sk_live_xxxxxxxx
|
||||
```
|
||||
|
||||
或:
|
||||
|
||||
```http
|
||||
Authorization: Bearer sk_live_xxxxxxxx
|
||||
```
|
||||
|
||||
注意:后端会拒绝以 `eyJ` 开头的 JWT 当作 Key。扩展配置里只存 **Open API Key**。
|
||||
|
||||
不要在 Vue 组件中直接到处写 fetch。
|
||||
|
||||
BI API Base URL 与 API Key 必须通过 Extension Storage 配置。
|
||||
|
||||
---
|
||||
|
||||
# 八、配置与 API Key
|
||||
|
||||
使用:
|
||||
|
||||
```ts
|
||||
chrome.storage.local
|
||||
```
|
||||
|
||||
保存:
|
||||
|
||||
```text
|
||||
BI Open API Base URL (例:https://host/api)
|
||||
BI Open API Key (创建 Key 时返回的明文,仅本地保存)
|
||||
默认 channelShopId (可选,用户从店铺列表选过一次后记住)
|
||||
```
|
||||
|
||||
设计独立配置模块:
|
||||
|
||||
```text
|
||||
src/storage/
|
||||
├── settings.ts
|
||||
└── types.ts
|
||||
```
|
||||
|
||||
不要直接在业务代码中到处:
|
||||
|
||||
```ts
|
||||
chrome.storage.local.get(...)
|
||||
```
|
||||
|
||||
统一封装。
|
||||
|
||||
注意:
|
||||
|
||||
* 不保存电商平台 Cookie
|
||||
* 不向 BI 服务上传平台 Cookie
|
||||
* 不实现获取平台 Token 的逻辑
|
||||
* **只保存用户自己的 BI Open API Key**(需具备 `open:scope:pdd_shop:read` 与 `open:scope:pdd_goods_ad_fee:import`)
|
||||
* 不使用系统后台登录 JWT 调 `/api/open/**`
|
||||
|
||||
---
|
||||
|
||||
# 九、权限设计
|
||||
|
||||
Manifest V3 遵循最小权限原则。
|
||||
|
||||
只申请实际需要的权限。
|
||||
|
||||
第一阶段优先考虑:
|
||||
|
||||
```text
|
||||
storage
|
||||
activeTab
|
||||
scripting
|
||||
```
|
||||
|
||||
不要为了方便直接申请:
|
||||
|
||||
```text
|
||||
<all_urls>
|
||||
```
|
||||
|
||||
如果后续确实需要指定平台域名,再针对具体平台增加 host_permissions。
|
||||
|
||||
Manifest 中不要提前加入一堆没有实际用途的权限。
|
||||
|
||||
---
|
||||
|
||||
# 十、Popup UI
|
||||
|
||||
先做一个简洁的内部工具 UI。
|
||||
|
||||
页面结构:
|
||||
|
||||
```text
|
||||
┌──────────────────────────────┐
|
||||
│ BI 数据同步 │
|
||||
├──────────────────────────────┤
|
||||
│ 当前平台 │
|
||||
│ 淘宝 / 京东 / 未识别 │
|
||||
│ │
|
||||
│ 当前页面 │
|
||||
│ xxx │
|
||||
│ │
|
||||
│ 同步日期 │
|
||||
│ 2026-08-15 │
|
||||
│ │
|
||||
│ BI 渠道店铺 │
|
||||
│ [下拉:从 open shop/list 选] │
|
||||
│ channelShopId: 12 │
|
||||
│ │
|
||||
│ 数据状态 │
|
||||
│ 等待读取 │
|
||||
│ │
|
||||
│ [读取数据] │
|
||||
│ │
|
||||
│ 数据预览 │
|
||||
│ ─────────────────────────── │
|
||||
│ 推广费用:¥0 │
|
||||
│ 数据条数:0 │
|
||||
│ │
|
||||
│ [同步到 BI] │
|
||||
└──────────────────────────────┘
|
||||
```
|
||||
|
||||
第一阶段使用 Mock 数据。
|
||||
|
||||
例如点击:
|
||||
|
||||
```text
|
||||
读取数据
|
||||
```
|
||||
|
||||
显示:
|
||||
|
||||
```text
|
||||
平台:Mock
|
||||
BI 渠道店铺:测试店铺(channelShopId=1)
|
||||
日期:2026-08-15
|
||||
推广费用:¥1234.56
|
||||
数据条数:10
|
||||
```
|
||||
|
||||
然后:
|
||||
|
||||
```text
|
||||
同步到 BI
|
||||
```
|
||||
|
||||
调用 Open API:`POST .../channel/pdd/goods/adfee/batch-import`(开发环境可用 Mock Client 或真实 Key)。
|
||||
|
||||
日期约定:**每条推广数据自带 `feeDate`**(由 Adapter 从页面解析);悬浮层 / Popup **不提供手选同步日期**。
|
||||
|
||||
---
|
||||
|
||||
# 十一、消息通信
|
||||
|
||||
设计统一消息协议。
|
||||
|
||||
例如:
|
||||
|
||||
```ts
|
||||
type ExtensionMessage =
|
||||
| {
|
||||
type: 'GET_PAGE_CONTEXT';
|
||||
}
|
||||
| {
|
||||
type: 'PARSE_ADVERTISING_COST';
|
||||
}
|
||||
| {
|
||||
type: 'SYNC_ADVERTISING_COST';
|
||||
payload: AdvertisingCostBatch;
|
||||
};
|
||||
```
|
||||
|
||||
不要直接在各处使用字符串:
|
||||
|
||||
```ts
|
||||
chrome.runtime.sendMessage({
|
||||
type: 'xxx'
|
||||
});
|
||||
```
|
||||
|
||||
应该统一定义消息类型,保证 TypeScript 类型安全。
|
||||
|
||||
---
|
||||
|
||||
# 十二、错误处理
|
||||
|
||||
统一错误模型。
|
||||
|
||||
至少区分:
|
||||
|
||||
```text
|
||||
PLATFORM_NOT_SUPPORTED
|
||||
PAGE_NOT_READY
|
||||
DATA_PARSE_FAILED
|
||||
INVALID_DATA
|
||||
AUTH_FAILED
|
||||
API_REQUEST_FAILED
|
||||
API_BUSINESS_ERROR
|
||||
NETWORK_ERROR
|
||||
CONFIG_MISSING
|
||||
```
|
||||
|
||||
UI 给用户显示友好的错误。
|
||||
|
||||
例如:
|
||||
|
||||
```text
|
||||
当前页面不是支持的推广费用页面
|
||||
|
||||
请先进入平台推广费用页面,然后重新点击“读取数据”。
|
||||
```
|
||||
|
||||
不要直接把底层异常堆栈展示给用户。
|
||||
|
||||
---
|
||||
|
||||
# 十三、目录结构
|
||||
|
||||
最终建议类似:
|
||||
|
||||
```text
|
||||
bi-data-sync-extension/
|
||||
│
|
||||
├── src/
|
||||
│ ├── api/
|
||||
│ │ ├── client.ts
|
||||
│ │ ├── open/
|
||||
│ │ │ ├── pddShop.ts
|
||||
│ │ │ └── pddGoodsAdFee.ts
|
||||
│ │ └── types.ts
|
||||
│ │
|
||||
│ ├── background/
|
||||
│ │ └── index.ts
|
||||
│ │
|
||||
│ ├── content/
|
||||
│ │ └── index.ts
|
||||
│ │
|
||||
│ ├── popup/
|
||||
│ │ ├── App.vue
|
||||
│ │ ├── main.ts
|
||||
│ │ └── components/
|
||||
│ │
|
||||
│ ├── platform/
|
||||
│ │ ├── core/
|
||||
│ │ │ ├── types.ts
|
||||
│ │ │ ├── PlatformAdapter.ts
|
||||
│ │ │ └── PlatformDetector.ts
|
||||
│ │ │
|
||||
│ │ └── mock/
|
||||
│ │ └── MockPlatformAdapter.ts
|
||||
│ │
|
||||
│ ├── storage/
|
||||
│ │ ├── settings.ts
|
||||
│ │ └── types.ts
|
||||
│ │
|
||||
│ ├── shared/
|
||||
│ │ ├── messages.ts
|
||||
│ │ ├── constants.ts
|
||||
│ │ └── errors.ts
|
||||
│ │
|
||||
│ └── types/
|
||||
│ └── advertisingCost.ts
|
||||
│
|
||||
├── public/
|
||||
│ └── icons/
|
||||
│
|
||||
├── manifest.config.ts
|
||||
├── vite.config.ts
|
||||
├── tsconfig.json
|
||||
├── package.json
|
||||
├── .eslintrc...
|
||||
├── .prettierrc...
|
||||
└── README.md
|
||||
```
|
||||
|
||||
可以根据 Vite/Extension 构建方式调整目录,但必须保持职责分离。
|
||||
|
||||
---
|
||||
|
||||
# 十四、构建要求
|
||||
|
||||
需要支持:
|
||||
|
||||
```bash
|
||||
pnpm install
|
||||
|
||||
pnpm dev
|
||||
|
||||
pnpm build
|
||||
```
|
||||
|
||||
构建后生成:
|
||||
|
||||
```text
|
||||
dist/
|
||||
```
|
||||
|
||||
能够直接通过:
|
||||
|
||||
Chrome:
|
||||
chrome://extensions/
|
||||
|
||||
Edge:
|
||||
edge://extensions/
|
||||
|
||||
开启开发者模式后加载 `dist` 目录运行。
|
||||
|
||||
README 必须写清楚:
|
||||
|
||||
1. 环境要求
|
||||
2. 安装依赖
|
||||
3. 开发
|
||||
4. 构建
|
||||
5. Chrome 安装方式
|
||||
6. Edge 安装方式
|
||||
7. 项目架构
|
||||
8. 如何增加一个新的平台 Adapter
|
||||
9. 如何配置 BI Open API(Base URL + API Key + 所需 scope)
|
||||
10. 当前 Mock 数据说明
|
||||
11. 与后端 open 接口字段对照(channelShopId / feeDate / goodsId / feeAmount)
|
||||
|
||||
---
|
||||
|
||||
# 十五、测试
|
||||
|
||||
至少建立基础测试结构。
|
||||
|
||||
重点测试:
|
||||
|
||||
* PlatformDetector
|
||||
* MockPlatformAdapter
|
||||
* AdvertisingCost 数据转换
|
||||
* API Client 错误处理
|
||||
* Storage 配置读写
|
||||
|
||||
不需要为了测试而过度设计。
|
||||
|
||||
---
|
||||
|
||||
# 十六、重要约束
|
||||
|
||||
不要做以下事情:
|
||||
|
||||
1. 不要实现任何平台爬虫
|
||||
2. 不要逆向任何平台接口
|
||||
3. 不要读取平台 Cookie
|
||||
4. 不要上传平台 Cookie
|
||||
5. 不要自动登录
|
||||
6. 不要后台定时抓取
|
||||
7. 不要自动模拟用户点击
|
||||
8. 不要申请不必要的 Chrome 权限
|
||||
9. 不要使用 `<all_urls>` 作为偷懒方案
|
||||
10. 不要把平台逻辑写死在 Popup
|
||||
11. 不要把 API 请求散落在 Vue 组件
|
||||
12. 不要引入 Element Plus
|
||||
|
||||
第一阶段只需要:
|
||||
|
||||
“插件工程 + Manifest V3 + Vue + TypeScript + Popup + Content Script + Background + Storage + API Client + Platform Adapter + Mock 数据”。
|
||||
|
||||
---
|
||||
|
||||
# 十七、开发原则
|
||||
|
||||
遵循:
|
||||
|
||||
* KISS
|
||||
* SOLID
|
||||
* 单一职责
|
||||
* 依赖倒置
|
||||
* 类型安全
|
||||
* 最小权限
|
||||
* 平台适配器隔离
|
||||
* 基础设施与业务逻辑分离
|
||||
|
||||
不要为了“以后可能用到”创建大量抽象。
|
||||
|
||||
如果一个抽象目前没有真实需求,优先保持简单。
|
||||
|
||||
---
|
||||
|
||||
# 十八、执行方式
|
||||
|
||||
不要一次性生成大量复杂代码。
|
||||
|
||||
按照以下步骤执行:
|
||||
|
||||
Step 1:
|
||||
分析架构并说明关键设计。
|
||||
|
||||
Step 2:
|
||||
创建项目基础结构和 Vite + Vue + TypeScript + Manifest V3。
|
||||
|
||||
Step 3:
|
||||
实现 Popup / Content Script / Background 的最小通信链路。
|
||||
|
||||
Step 4:
|
||||
实现 Storage。
|
||||
|
||||
Step 5:
|
||||
实现 Platform Adapter 和 Mock Adapter。
|
||||
|
||||
Step 6:
|
||||
实现 BI API Client。
|
||||
|
||||
Step 7:
|
||||
实现 Mock 数据同步流程。
|
||||
|
||||
Step 8:
|
||||
完善 UI。
|
||||
|
||||
Step 9:
|
||||
添加测试。
|
||||
|
||||
Step 10:
|
||||
完善 README。
|
||||
|
||||
每完成一个阶段,先检查 TypeScript、ESLint、Build 是否通过,再进入下一阶段。
|
||||
|
||||
如果发现架构问题,先修正架构,不要通过增加临时代码绕过去。
|
||||
|
||||
最终要求:
|
||||
|
||||
```bash
|
||||
pnpm build
|
||||
```
|
||||
|
||||
必须成功,并且 `dist` 可以直接加载到 Chrome 和 Edge 中运行。
|
||||
|
||||
````
|
||||
|
||||
### 我建议你再给 Agent 加一句
|
||||
|
||||
如果你用的是 **Cursor / Claude Code / Codex / OpenCode** 这类 Coding Agent,我建议第一轮**不要让它直接开发真实平台**。
|
||||
|
||||
先让它把:
|
||||
|
||||
```text
|
||||
Vue
|
||||
↓
|
||||
Popup
|
||||
↓
|
||||
Content Script
|
||||
↓
|
||||
Mock Adapter
|
||||
↓
|
||||
统一 AdvertisingCostBatch
|
||||
↓
|
||||
映射为 batch-import items
|
||||
↓
|
||||
BI Open API(API Key)
|
||||
````
|
||||
|
||||
注意:提交字段必须是 `channelShopId + feeDate + goodsId + feeAmount`;鉴权用 Open API Key,不要用登录 JWT。
|
||||
|
||||
然后第二轮你再告诉它:
|
||||
|
||||
> “现在接入 XX 平台,只允许读取用户当前页面已经展示的数据,实现 XX 平台 Adapter,先分析页面结构,不要修改公共架构。”
|
||||
|
||||
这样会稳很多。
|
||||
@@ -0,0 +1,35 @@
|
||||
import { defineManifest } from '@crxjs/vite-plugin';
|
||||
|
||||
import packageJson from './package.json';
|
||||
|
||||
const { version } = packageJson;
|
||||
|
||||
export default defineManifest({
|
||||
manifest_version: 3,
|
||||
name: 'ECBI 数据同步',
|
||||
description: '从电商平台后台读取推广费用并同步到 BI(企业内用)',
|
||||
version,
|
||||
action: {
|
||||
default_popup: 'src/popup/index.html',
|
||||
default_title: 'ECBI 数据同步',
|
||||
},
|
||||
background: {
|
||||
service_worker: 'src/background/index.ts',
|
||||
type: 'module',
|
||||
},
|
||||
content_scripts: [
|
||||
{
|
||||
matches: ['http://*/*', 'https://*/*'],
|
||||
js: ['src/content/index.ts'],
|
||||
run_at: 'document_idle',
|
||||
},
|
||||
],
|
||||
permissions: ['storage', 'activeTab', 'scripting'],
|
||||
// 开发期便于任意页注入 Content Script;正式接平台后改为具体域名
|
||||
host_permissions: ['http://*/*', 'https://*/*'],
|
||||
icons: {
|
||||
'16': 'public/icons/icon-16.png',
|
||||
'64': 'public/icons/icon-64.png',
|
||||
'128': 'public/icons/icon-128.png',
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,40 @@
|
||||
{
|
||||
"name": "ecbi-data-sync-extension",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"description": "企业内部 BI 数据同步浏览器扩展(Manifest V3)",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "vue-tsc --noEmit && vite build && pnpm build:features",
|
||||
"build:features": "node scripts/build-features.mjs",
|
||||
"typecheck": "vue-tsc --noEmit",
|
||||
"lint": "eslint . --ext .ts,.vue",
|
||||
"format": "prettier --write \"src/**/*.{ts,vue,css,json}\""
|
||||
},
|
||||
"dependencies": {
|
||||
"vue": "^3.5.13"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@crxjs/vite-plugin": "^2.7.1",
|
||||
"@types/chrome": "^0.0.287",
|
||||
"@types/node": "^22.10.2",
|
||||
"@vitejs/plugin-vue": "^5.2.1",
|
||||
"@vue/eslint-config-prettier": "^10.1.0",
|
||||
"@vue/eslint-config-typescript": "^14.1.4",
|
||||
"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",
|
||||
"typescript": "~5.6.3",
|
||||
"vite": "^5.4.11",
|
||||
"vue-tsc": "^2.1.10"
|
||||
},
|
||||
"packageManager": "pnpm@9.15.0",
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
}
|
||||
Generated
+2961
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,6 @@
|
||||
export default {
|
||||
plugins: {
|
||||
tailwindcss: {},
|
||||
autoprefixer: {},
|
||||
},
|
||||
};
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 8.1 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 433 B |
Binary file not shown.
|
After Width: | Height: | Size: 3.0 KiB |
@@ -0,0 +1,132 @@
|
||||
import { createHash } from 'node:crypto';
|
||||
import { execFileSync } from 'node:child_process';
|
||||
import {
|
||||
copyFileSync,
|
||||
existsSync,
|
||||
mkdirSync,
|
||||
readFileSync,
|
||||
renameSync,
|
||||
rmSync,
|
||||
unlinkSync,
|
||||
writeFileSync,
|
||||
} from 'node:fs';
|
||||
import { dirname, resolve } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { build } from 'vite';
|
||||
|
||||
/**
|
||||
* 构建功能脚本 → artifacts/features,打 zip 壳,并同步到后端 static。
|
||||
*/
|
||||
const __dirname = dirname(fileURLToPath(import.meta.url));
|
||||
const root = resolve(__dirname, '..');
|
||||
const artifactsRoot = resolve(root, 'artifacts');
|
||||
const featuresOutDir = resolve(artifactsRoot, 'features');
|
||||
const extensionOutDir = resolve(artifactsRoot, 'extension');
|
||||
const zipName = 'ecbi-data-sync-extension.zip';
|
||||
const zipLocalPath = resolve(artifactsRoot, zipName);
|
||||
|
||||
const backendFeaturesStatic = resolve(
|
||||
root,
|
||||
'../server/src/main/resources/static/extension-features',
|
||||
);
|
||||
const backendExtensionStatic = resolve(
|
||||
root,
|
||||
'../server/src/main/resources/static/extension',
|
||||
);
|
||||
|
||||
function syncDirContents(srcDir, destDir) {
|
||||
if (existsSync(destDir)) {
|
||||
rmSync(destDir, { recursive: true, force: true });
|
||||
}
|
||||
mkdirSync(destDir, { recursive: true });
|
||||
for (const name of ['manifest.json', 'pdd-ad-fee.js', 'pdd-ad-fee.js.map']) {
|
||||
const src = resolve(srcDir, name);
|
||||
if (existsSync(src)) {
|
||||
copyFileSync(src, resolve(destDir, name));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function packExtensionZip() {
|
||||
if (!existsSync(extensionOutDir)) {
|
||||
throw new Error(
|
||||
`扩展壳目录不存在: ${extensionOutDir}(请先执行 vite build)`,
|
||||
);
|
||||
}
|
||||
if (existsSync(zipLocalPath)) {
|
||||
unlinkSync(zipLocalPath);
|
||||
}
|
||||
|
||||
// zip 内一层目录:ecbi-data-sync-extension/…,解压后直接「加载已解压的扩展」
|
||||
const packageDirName = 'ecbi-data-sync-extension';
|
||||
const packageDir = resolve(artifactsRoot, packageDirName);
|
||||
if (existsSync(packageDir)) {
|
||||
rmSync(packageDir, { recursive: true, force: true });
|
||||
}
|
||||
renameSync(extensionOutDir, packageDir);
|
||||
try {
|
||||
execFileSync('zip', ['-r', '-q', zipLocalPath, packageDirName], {
|
||||
cwd: artifactsRoot,
|
||||
});
|
||||
} finally {
|
||||
renameSync(packageDir, extensionOutDir);
|
||||
}
|
||||
|
||||
mkdirSync(backendExtensionStatic, { recursive: true });
|
||||
copyFileSync(zipLocalPath, resolve(backendExtensionStatic, zipName));
|
||||
}
|
||||
|
||||
async function main() {
|
||||
mkdirSync(artifactsRoot, { recursive: true });
|
||||
|
||||
await build({
|
||||
configFile: resolve(root, 'vite.features.config.ts'),
|
||||
});
|
||||
|
||||
const entryFile = 'pdd-ad-fee.js';
|
||||
const jsPath = resolve(featuresOutDir, entryFile);
|
||||
const code = readFileSync(jsPath, 'utf8');
|
||||
const sha256 = createHash('sha256').update(code).digest('hex');
|
||||
|
||||
const manifest = {
|
||||
schemaVersion: 1,
|
||||
updatedAt: new Date().toISOString(),
|
||||
features: [
|
||||
{
|
||||
id: 'pdd-ad-fee',
|
||||
name: '拼多多商品推广费同步',
|
||||
version: '0.3.10',
|
||||
description:
|
||||
'从推广总览读取推广费并同步到 BI(总花费为 0 不记录)',
|
||||
matchUrlPatterns: [
|
||||
'*://yingxiao.pinduoduo.com/*',
|
||||
'https://yingxiao.pinduoduo.com/',
|
||||
],
|
||||
entry: entryFile,
|
||||
sha256,
|
||||
executionWorld: 'main',
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
writeFileSync(
|
||||
resolve(featuresOutDir, 'manifest.json'),
|
||||
`${JSON.stringify(manifest, null, 2)}\n`,
|
||||
'utf8',
|
||||
);
|
||||
|
||||
syncDirContents(featuresOutDir, backendFeaturesStatic);
|
||||
packExtensionZip();
|
||||
|
||||
console.log(`[build-features] wrote ${featuresOutDir}`);
|
||||
console.log(`[build-features] synced features → ${backendFeaturesStatic}`);
|
||||
console.log(
|
||||
`[build-features] packed zip → ${resolve(backendExtensionStatic, zipName)}`,
|
||||
);
|
||||
console.log(`[build-features] pdd-ad-fee sha256=${sha256}`);
|
||||
}
|
||||
|
||||
main().catch((err) => {
|
||||
console.error(err);
|
||||
process.exit(1);
|
||||
});
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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;
|
||||
});
|
||||
Vendored
+12
@@ -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'));
|
||||
}
|
||||
@@ -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>
|
||||
@@ -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' });
|
||||
}
|
||||
@@ -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';
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
/** @type {import('tailwindcss').Config} */
|
||||
export default {
|
||||
content: ['./src/**/*.{vue,ts,html}'],
|
||||
theme: {
|
||||
extend: {
|
||||
colors: {
|
||||
antd: {
|
||||
primary: '#1677ff',
|
||||
'primary-hover': '#4096ff',
|
||||
'primary-active': '#0958d9',
|
||||
text: 'rgba(0, 0, 0, 0.88)',
|
||||
'text-secondary': 'rgba(0, 0, 0, 0.45)',
|
||||
'text-tertiary': 'rgba(0, 0, 0, 0.25)',
|
||||
border: '#d9d9d9',
|
||||
'border-secondary': '#f0f0f0',
|
||||
fill: '#f5f5f5',
|
||||
bg: '#ffffff',
|
||||
success: '#52c41a',
|
||||
error: '#ff4d4f',
|
||||
warning: '#faad14',
|
||||
},
|
||||
},
|
||||
borderRadius: {
|
||||
antd: '8px',
|
||||
'antd-lg': '12px',
|
||||
'antd-sm': '6px',
|
||||
},
|
||||
boxShadow: {
|
||||
antd: '0 6px 16px 0 rgba(0, 0, 0, 0.08), 0 3px 6px -4px rgba(0, 0, 0, 0.12), 0 9px 28px 8px rgba(0, 0, 0, 0.05)',
|
||||
},
|
||||
},
|
||||
},
|
||||
plugins: [],
|
||||
};
|
||||
@@ -0,0 +1,26 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2022",
|
||||
"useDefineForClassFields": true,
|
||||
"module": "ESNext",
|
||||
"lib": ["ES2022", "DOM", "DOM.Iterable"],
|
||||
"skipLibCheck": true,
|
||||
"moduleResolution": "bundler",
|
||||
"allowImportingTsExtensions": true,
|
||||
"resolveJsonModule": true,
|
||||
"isolatedModules": true,
|
||||
"noEmit": true,
|
||||
"jsx": "preserve",
|
||||
"strict": true,
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
"types": ["chrome", "vite/client", "node"],
|
||||
"baseUrl": ".",
|
||||
"paths": {
|
||||
"@/*": ["src/*"]
|
||||
}
|
||||
},
|
||||
"include": ["src/**/*.ts", "src/**/*.tsx", "src/**/*.vue"],
|
||||
"exclude": ["node_modules", "dist"]
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"composite": true,
|
||||
"skipLibCheck": true,
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "bundler",
|
||||
"allowSyntheticDefaultImports": true,
|
||||
"strict": true,
|
||||
"types": ["node"]
|
||||
},
|
||||
"include": ["vite.config.ts", "manifest.config.ts"]
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import { crx } from '@crxjs/vite-plugin';
|
||||
import vue from '@vitejs/plugin-vue';
|
||||
import { resolve } from 'node:path';
|
||||
import { defineConfig } from 'vite';
|
||||
|
||||
import manifest from './manifest.config';
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [vue(), crx({ manifest })],
|
||||
resolve: {
|
||||
alias: {
|
||||
'@': resolve(__dirname, 'src'),
|
||||
},
|
||||
},
|
||||
build: {
|
||||
sourcemap: true,
|
||||
outDir: 'artifacts/extension',
|
||||
emptyOutDir: true,
|
||||
},
|
||||
server: {
|
||||
port: 5173,
|
||||
strictPort: true,
|
||||
hmr: {
|
||||
port: 5173,
|
||||
},
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,33 @@
|
||||
import { resolve } from 'node:path';
|
||||
import { defineConfig } from 'vite';
|
||||
import vue from '@vitejs/plugin-vue';
|
||||
|
||||
/** 功能脚本独立构建 → artifacts/features/(部署到后端静态目录) */
|
||||
export default defineConfig({
|
||||
plugins: [vue()],
|
||||
resolve: {
|
||||
alias: {
|
||||
'@': resolve(__dirname, 'src'),
|
||||
},
|
||||
},
|
||||
define: {
|
||||
'process.env.NODE_ENV': JSON.stringify('production'),
|
||||
},
|
||||
build: {
|
||||
outDir: 'artifacts/features',
|
||||
emptyOutDir: true,
|
||||
lib: {
|
||||
entry: resolve(__dirname, 'src/features/pdd-ad-fee/index.ts'),
|
||||
name: 'EcbiFeaturePddAdFee',
|
||||
formats: ['iife'],
|
||||
fileName: () => 'pdd-ad-fee.js',
|
||||
},
|
||||
rollupOptions: {
|
||||
output: {
|
||||
inlineDynamicImports: true,
|
||||
},
|
||||
},
|
||||
sourcemap: true,
|
||||
minify: true,
|
||||
},
|
||||
});
|
||||
Reference in New Issue
Block a user