refacor: 重构目录架构

This commit is contained in:
2026-09-16 22:43:21 +08:00
parent b37cdb0d54
commit 2754ed1e45
2762 changed files with 0 additions and 1529 deletions
+7
View File
@@ -0,0 +1,7 @@
dist
dist-features
artifacts
node_modules
*.local
.DS_Store
temp
+1
View File
@@ -0,0 +1 @@
ignore-workspace=true
+6
View File
@@ -0,0 +1,6 @@
{
"singleQuote": true,
"semi": true,
"trailingComma": "all",
"printWidth": 100
}
+139
View File
@@ -0,0 +1,139 @@
# ECBI 数据同步扩展
企业内部用 Chromium 扩展(Manifest V3):在电商后台页面由用户主动读取推广费用,经统一模型通过 **Open API** 同步到 BI。
第一阶段:**工程骨架 + Mock Adapter**,不解析真实平台 DOM。
## 环境要求
- Node.js >= 18
- pnpm >= 9
## 安装依赖
```bash
cd 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)。
+765
View File
@@ -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,先分析页面结构,不要修改公共架构。”
这样会稳很多。
+35
View File
@@ -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',
},
});
+40
View File
@@ -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"
}
}
File diff suppressed because it is too large Load Diff
+6
View File
@@ -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,
'../ecom-dmb-backend/src/main/resources/static/extension-features',
);
const backendExtensionStatic = resolve(
root,
'../ecom-dmb-backend/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);
});
+86
View File
@@ -0,0 +1,86 @@
import { ExtensionError } from '@/shared/errors';
import { executeOpenApiFetch } from './openApiFetch';
export type { ApiResponseBody } from './openApiFetch';
export type OpenApiRequestFn = <T>(path: string, init?: RequestInit) => Promise<T>;
let openApiOverride: OpenApiRequestFn | null = null;
/** 功能包在 main world 安装桥接实现时调用 */
export function setOpenApiRequestOverride(fn: OpenApiRequestFn | null): void {
openApiOverride = fn;
}
type OpenApiBgPayload = {
path: string;
method?: string;
body?: string;
headers?: Record<string, string>;
};
type OpenApiBgResponse =
| { ok: true; data: unknown }
| { ok: false; code: string; message: string };
function canUseBackgroundProxy(): boolean {
return typeof chrome !== 'undefined' && Boolean(chrome.runtime?.id);
}
async function requestViaBackground<T>(
path: string,
init: RequestInit = {},
): Promise<T> {
const headers: Record<string, string> = {};
if (init.headers) {
new Headers(init.headers).forEach((value, key) => {
headers[key] = value;
});
}
const payload: OpenApiBgPayload = {
path,
method: init.method,
body: typeof init.body === 'string' ? init.body : undefined,
headers,
};
let response: OpenApiBgResponse | undefined;
try {
response = (await chrome.runtime.sendMessage({
type: 'OPEN_API_REQUEST',
payload,
})) as OpenApiBgResponse | undefined;
} catch {
throw new ExtensionError('NETWORK_ERROR', '无法连接扩展后台,请重载扩展后重试');
}
if (!response) {
throw new ExtensionError('NETWORK_ERROR', '扩展后台无响应');
}
if (!response.ok) {
throw new ExtensionError(
(response.code as ExtensionError['code']) || 'API_REQUEST_FAILED',
response.message || '请求失败',
);
}
return response.data as T;
}
/**
* Open API 统一入口。
* Content Script 在 HTTPS 第三方页内不能直连 HTTP 本地 API(混合内容/CORS),
* 默认经 Background 代发。
*/
export async function openApiRequest<T>(
path: string,
init: RequestInit = {},
): Promise<T> {
if (openApiOverride) {
return openApiOverride<T>(path, init);
}
if (canUseBackgroundProxy()) {
return requestViaBackground<T>(path, init);
}
return executeOpenApiFetch<T>(path, init);
}
@@ -0,0 +1,45 @@
import { openApiRequest } from '@/api/client';
import { OPEN_API_PATHS } from '@/shared/constants';
import type { ExtensionFeatureItem, ExtensionFeatureManifest } from '@/features/runtime/types';
export interface FeatureScriptPayload {
featureId: string;
version?: string;
sha256?: string;
content: string;
}
export async function fetchFeatureManifest(): Promise<ExtensionFeatureManifest> {
return openApiRequest<ExtensionFeatureManifest>(OPEN_API_PATHS.extensionFeatureList, {
method: 'GET',
});
}
export async function fetchFeatureScript(featureId: string): Promise<FeatureScriptPayload> {
return openApiRequest<FeatureScriptPayload>(
`${OPEN_API_PATHS.extensionFeatureScript}/${encodeURIComponent(featureId)}/script`,
{ method: 'GET' },
);
}
/** 下载远程脚本并可选校验 sha256(与静态 manifest 一致) */
export async function downloadAndVerifyFeature(
item: ExtensionFeatureItem,
): Promise<{ code: string; verified: boolean; remoteVersion?: string }> {
const payload = await fetchFeatureScript(item.id);
const expected = (item.sha256 || payload.sha256 || '').toLowerCase();
if (expected) {
const hash = await sha256Hex(payload.content);
if (hash !== expected) {
throw new Error(`功能脚本校验失败:${item.id}(sha256 不匹配)`);
}
return { code: payload.content, verified: true, remoteVersion: payload.version };
}
return { code: payload.content, verified: false, remoteVersion: payload.version };
}
async function sha256Hex(text: string): Promise<string> {
const data = new TextEncoder().encode(text);
const digest = await crypto.subtle.digest('SHA-256', data);
return [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, '0')).join('');
}
@@ -0,0 +1,101 @@
import type { AdvertisingCostBatch } from '@/types/advertisingCost';
import { openApiRequest } from '@/api/client';
import { OPEN_API_PATHS } from '@/shared/constants';
export interface BatchImportPddGoodsAdFeeItem {
channelShopId: number;
feeDate: string;
goodsId: string;
feeAmount: number;
}
export interface BatchImportPddGoodsAdFeeRequest {
items: BatchImportPddGoodsAdFeeItem[];
}
/** 导入任务摘要(创建立即返回 pending,需轮询至终态) */
export interface PddGoodsAdFeeImportTask {
id: number;
companyId?: number;
channelShopId: number;
status: 'pending' | 'processing' | 'success' | 'partial' | 'failed' | string;
totalCount: number;
successCount: number;
failCount: number;
authExpired?: number;
message?: string | null;
startedAt?: string | null;
finishedAt?: string | null;
createTime?: string;
}
const TERMINAL_STATUS = new Set(['success', 'partial', 'failed']);
const POLL_INTERVAL_MS = 2500;
const POLL_TIMEOUT_MS = 30 * 60 * 1000;
/** 插件统一模型 → 后端 batch-import 入参(日期取自每条 item;金额须大于 0) */
export function toBatchImportRequest(
batch: AdvertisingCostBatch,
): BatchImportPddGoodsAdFeeRequest {
return {
items: batch.items
.filter((item) => Number(item.feeAmount) > 0)
.map((item) => ({
channelShopId: batch.channelShopId,
feeDate: item.feeDate,
goodsId: item.goodsId,
feeAmount: item.feeAmount,
})),
};
}
export async function getPddGoodsAdFeeImportTask(
taskId: number,
): Promise<PddGoodsAdFeeImportTask> {
return openApiRequest<PddGoodsAdFeeImportTask>(
`${OPEN_API_PATHS.pddGoodsAdFeeImportTask}/${taskId}`,
);
}
export async function waitForPddGoodsAdFeeImportTask(
taskId: number,
onProgress?: (task: PddGoodsAdFeeImportTask) => void,
): Promise<PddGoodsAdFeeImportTask> {
const deadline = Date.now() + POLL_TIMEOUT_MS;
while (Date.now() < deadline) {
const task = await getPddGoodsAdFeeImportTask(taskId);
onProgress?.(task);
if (TERMINAL_STATUS.has(task.status)) {
return task;
}
await sleep(POLL_INTERVAL_MS);
}
throw new Error('导入超时,请稍后在后台查看任务进度');
}
/** 提交导入任务并等到处理结束 */
export async function batchImportPddGoodsAdFee(
batch: AdvertisingCostBatch,
onProgress?: (task: PddGoodsAdFeeImportTask) => void,
): Promise<PddGoodsAdFeeImportTask> {
const body = toBatchImportRequest(batch);
if (!body.items.length) {
throw new Error('没有可传入的记录(推广费须大于 0)');
}
const created = await openApiRequest<PddGoodsAdFeeImportTask>(
OPEN_API_PATHS.pddGoodsAdFeeBatchImport,
{
method: 'POST',
body: JSON.stringify(body),
},
);
onProgress?.(created);
return waitForPddGoodsAdFeeImportTask(created.id, onProgress);
}
function sleep(ms: number): Promise<void> {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}
@@ -0,0 +1,47 @@
import { openApiRequest } from '@/api/client';
import { OPEN_API_PATHS } from '@/shared/constants';
export interface PageQueryDTO<TFilters> {
page: number;
pageSize: number;
filters?: TFilters;
}
export interface PageResultVO<T> {
records: T[];
total: number;
page?: number;
pageSize?: number;
}
export interface PddChannelShop {
id: number;
mallId?: number;
mallName?: string;
logo?: string;
}
export interface PddShopFilters {
mallName?: string;
}
export async function matchPddChannelShopByMallName(
mallName: string,
): Promise<PddChannelShop | null> {
const name = mallName.trim();
if (!name) return null;
const qs = new URLSearchParams({ mallName: name });
return openApiRequest<PddChannelShop | null>(
`${OPEN_API_PATHS.pddShopMatchByName}?${qs.toString()}`,
{ method: 'GET' },
);
}
export async function listPddChannelShops(
query: PageQueryDTO<PddShopFilters> = { page: 1, pageSize: 50 },
): Promise<PageResultVO<PddChannelShop>> {
return openApiRequest<PageResultVO<PddChannelShop>>(OPEN_API_PATHS.pddShopList, {
method: 'POST',
body: JSON.stringify(query),
});
}
@@ -0,0 +1,64 @@
import { ExtensionError } from '@/shared/errors';
import { getSettings } from '@/storage/settings';
export interface ApiResponseBody<T> {
code: number;
message: string;
data: T;
}
/** 在扩展上下文(Background / Popup)内直连 Open API */
export async function executeOpenApiFetch<T>(
path: string,
init: RequestInit = {},
): Promise<T> {
const settings = await getSettings();
if (!settings.apiBaseUrl) {
throw new ExtensionError('CONFIG_MISSING', '请先配置 BI Open API Base URL');
}
if (!settings.apiKey) {
throw new ExtensionError('CONFIG_MISSING', '请先配置 BI Open API Key');
}
const url = `${settings.apiBaseUrl}${path.startsWith('/') ? path : `/${path}`}`;
const headers = new Headers(init.headers);
headers.set('Content-Type', 'application/json');
headers.set('X-Api-Key', settings.apiKey);
let response: Response;
try {
response = await fetch(url, {
...init,
headers,
});
} catch {
throw new ExtensionError('NETWORK_ERROR', '网络异常,无法连接 BI Open API');
}
if (response.status === 401) {
throw new ExtensionError('AUTH_FAILED', 'API Key 无效、过期或 IP 不在白名单');
}
let body: ApiResponseBody<T>;
try {
body = (await response.json()) as ApiResponseBody<T>;
} catch {
throw new ExtensionError('API_REQUEST_FAILED', `请求失败(HTTP ${response.status})`);
}
if (!response.ok) {
throw new ExtensionError(
'API_REQUEST_FAILED',
body.message || `请求失败(HTTP ${response.status})`,
);
}
if (body.code !== 0 && body.code !== 200) {
throw new ExtensionError(
'API_BUSINESS_ERROR',
body.message || `业务错误(code=${body.code})`,
);
}
return body.data;
}
+6
View File
@@ -0,0 +1,6 @@
export type {
BatchImportPddGoodsAdFeeItem,
BatchImportPddGoodsAdFeeRequest,
PddGoodsAdFeeImportTask,
} from './open/pddGoodsAdFee';
export type { PddChannelShop, PageQueryDTO, PageResultVO } from './open/pddShop';
@@ -0,0 +1,138 @@
/**
* Background:向页面 MAIN world 注入远程功能脚本并调用 mount/unmount。
* chrome.scripting + world:MAIN 可绕过页面 CSP(inline script 会被拦)。
* Open API 亦在此代发,避免 HTTPS 页面直连 HTTP 本地服务被混合内容拦截。
*/
import { executeOpenApiFetch } from '@/api/openApiFetch';
import { ExtensionError } from '@/shared/errors';
type InjectMessage = {
type: 'INJECT_MAIN_SCRIPT';
payload: { code: string };
};
type CallMessage = {
type: 'CALL_MAIN_FEATURE';
payload: { featureId: string; action: 'mount' | 'unmount' };
};
type OpenApiMessage = {
type: 'OPEN_API_REQUEST';
payload: {
path: string;
method?: string;
body?: string;
headers?: Record<string, string>;
};
};
type BgMessage =
| InjectMessage
| CallMessage
| OpenApiMessage
| { type: 'BACKGROUND_PING' };
chrome.runtime.onInstalled.addListener(() => {
console.info('[ecbi-extension] installed');
});
chrome.runtime.onMessage.addListener((message: BgMessage, sender, sendResponse) => {
if (message?.type === 'BACKGROUND_PING') {
sendResponse({ ok: true, data: { pong: true } });
return true;
}
if (message?.type === 'OPEN_API_REQUEST') {
const { path, method, body, headers } = message.payload;
void executeOpenApiFetch(path, { method, body, headers })
.then((data) => sendResponse({ ok: true, data }))
.catch((error: unknown) => {
const err =
error instanceof ExtensionError
? error
: new ExtensionError(
'UNKNOWN',
error instanceof Error ? error.message : 'Open API 请求失败',
);
sendResponse({ ok: false, code: err.code, message: err.message });
});
return true;
}
const tabId = sender.tab?.id;
if (tabId == null) {
sendResponse({ ok: false, message: '缺少 tabId(仅 Content Script 可请求注入)' });
return true;
}
if (message?.type === 'INJECT_MAIN_SCRIPT') {
void chrome.scripting
.executeScript({
target: { tabId },
world: 'MAIN',
func: (source: string) => {
// 扩展注入的 MAIN world 函数内执行,不受页面 CSP 限制
const run = new Function(source);
run();
},
args: [message.payload.code],
})
.then(() => sendResponse({ ok: true }))
.catch((error: unknown) => {
sendResponse({
ok: false,
message: error instanceof Error ? error.message : '注入脚本失败',
});
});
return true;
}
if (message?.type === 'CALL_MAIN_FEATURE') {
const { featureId, action } = message.payload;
void chrome.scripting
.executeScript({
target: { tabId },
world: 'MAIN',
func: async (id: string, act: 'mount' | 'unmount') => {
const bag = (
globalThis as typeof globalThis & {
__ECBI_FEATURES__?: Record<
string,
{
mount?: () => void | Promise<void>;
unmount?: () => void | Promise<void>;
}
>;
}
).__ECBI_FEATURES__;
const mod = bag?.[id];
if (!mod) {
throw new Error(`功能未注册:${id}`);
}
if (act === 'mount') {
if (typeof mod.mount !== 'function') {
throw new Error(`功能无 mount:${id}`);
}
await mod.mount();
return;
}
if (typeof mod.unmount !== 'function') {
throw new Error(`功能无 unmount:${id}`);
}
await mod.unmount();
},
args: [featureId, action],
})
.then(() => sendResponse({ ok: true }))
.catch((error: unknown) => {
sendResponse({
ok: false,
message: error instanceof Error ? error.message : '调用功能失败',
});
});
return true;
}
return false;
});
@@ -0,0 +1,100 @@
<script setup lang="ts">
import { computed } from 'vue';
import type { AdvertisingCostItem } from '@/types/advertisingCost';
import {
buildHeatmapWeeks,
cellTitle,
monthLabelsForWeeks,
summarizeByDate,
type HeatDayCell,
} from '@/shared/dateHeatmap';
const props = defineProps<{
items: AdvertisingCostItem[];
pageDate?: string;
selectedDate?: string;
}>();
const emit = defineEmits<{
select: [date: string | undefined];
}>();
const WEEKDAY_LABELS = ['', '一', '', '三', '', '五', ''];
const stats = computed(() => summarizeByDate(props.items));
const weeks = computed(() =>
buildHeatmapWeeks({
weeks: 13,
stats: stats.value,
pageDate: props.pageDate,
}),
);
const monthLabelMap = computed(() => {
const map = new Map<number, string>();
for (const item of monthLabelsForWeeks(weeks.value)) {
map.set(item.index, item.label);
}
return map;
});
function onCellClick(cell: HeatDayCell) {
if (!cell.inRange || !cell.stat) return;
emit('select', props.selectedDate === cell.date ? undefined : cell.date);
}
function cellClass(cell: HeatDayCell): string[] {
const classes = [`ecbi-heat-l${cell.level}`];
if (!cell.inRange) classes.push('ecbi-heat-out');
if (cell.isToday) classes.push('ecbi-heat-today');
if (cell.isPageDate) classes.push('ecbi-heat-page');
if (props.selectedDate === cell.date) classes.push('ecbi-heat-selected');
if (cell.stat) classes.push('ecbi-heat-lit');
return classes;
}
</script>
<template>
<div class="ecbi-heat">
<div class="ecbi-heat-head">
<span class="ecbi-heat-title">读取日历</span>
<span class="ecbi-muted">点亮=已读 · 点击筛选当日</span>
</div>
<div class="ecbi-heat-body">
<div class="ecbi-heat-dows">
<span class="ecbi-heat-month-spacer" />
<span v-for="(label, i) in WEEKDAY_LABELS" :key="i" class="ecbi-heat-dow">{{ label }}</span>
</div>
<div class="ecbi-heat-weeks">
<div v-for="(week, wi) in weeks" :key="wi" class="ecbi-heat-week">
<span class="ecbi-heat-month">{{ monthLabelMap.get(wi) || '' }}</span>
<button
v-for="cell in week"
:key="cell.date"
type="button"
class="ecbi-heat-cell"
:class="cellClass(cell)"
:title="cellTitle(cell)"
:disabled="!cell.inRange || !cell.stat"
@click="onCellClick(cell)"
/>
</div>
</div>
</div>
<div class="ecbi-heat-legend">
<span class="ecbi-muted">少</span>
<span class="ecbi-heat-cell ecbi-heat-l0" />
<span class="ecbi-heat-cell ecbi-heat-l1" />
<span class="ecbi-heat-cell ecbi-heat-l2" />
<span class="ecbi-heat-cell ecbi-heat-l3" />
<span class="ecbi-heat-cell ecbi-heat-l4" />
<span class="ecbi-muted">多</span>
<span class="ecbi-heat-gap" />
<span class="ecbi-heat-cell ecbi-heat-l0 ecbi-heat-page" />
<span class="ecbi-muted">当前页日期</span>
</div>
</div>
</template>
@@ -0,0 +1,641 @@
<script setup lang="ts">
import { computed, onMounted, onUnmounted, ref } from 'vue';
import { batchImportPddGoodsAdFee } from '@/api/open/pddGoodsAdFee';
import DateHeatmap from './DateHeatmap.vue';
import { resolveAdapter } from '@/platform/core/PlatformDetector';
import {
MAX_AUTO_COLLECT_DAYS,
listDatesInclusive,
runAutoCollectByDates,
} from '@/platform/pdd/autoCollectDates';
import { matchChannelShopByMallName, shopAuthorizeHint } from '@/platform/pdd/matchShop';
import { EXTENSION_NAME } from '@/shared/constants';
import { toUserMessage } from '@/shared/errors';
import { listFeeDates, mergeAdvertisingItems } from '@/shared/mergeItems';
import { getSettings, saveSettings } from '@/storage/settings';
import type { AdvertisingCostBatch, PageContext } from '@/types/advertisingCost';
const emit = defineEmits<{
close: [];
minimize: [];
}>();
const channelShopId = ref<number | undefined>(undefined);
const channelShopName = ref('');
const pageMallName = ref('');
const shopMatching = ref(false);
const shopMatched = ref(false);
const pageContext = ref<PageContext | null>(null);
const batch = ref<AdvertisingCostBatch | null>(null);
const filterDate = ref<string | undefined>(undefined);
const statusText = ref('等待读取');
const errorText = ref('');
const syncResultText = ref('');
const busy = ref(false);
const autoStartDate = ref('');
const autoEndDate = ref('');
const autoSkipRead = ref(true);
const autoRunning = ref(false);
let autoAbort: AbortController | null = null;
/** 自动切日期期间禁止 URL 轮询触发二次读取 */
let suppressUrlAutoRead = false;
const panelRef = ref<HTMLElement | null>(null);
const position = ref({ top: 72, left: Math.max(24, window.innerWidth - 400) });
let dragOffset = { x: 0, y: 0 };
let dragging = false;
let readTimer: ReturnType<typeof setTimeout> | null = null;
let urlPollTimer: ReturnType<typeof setInterval> | null = null;
let lastHref = typeof location !== 'undefined' ? location.href : '';
function todayIso(): string {
const now = new Date();
const y = now.getFullYear();
const m = String(now.getMonth() + 1).padStart(2, '0');
const d = String(now.getDate()).padStart(2, '0');
return `${y}-${m}-${d}`;
}
function shiftIso(iso: string, deltaDays: number): string {
const dt = new Date(`${iso}T00:00:00`);
dt.setDate(dt.getDate() + deltaDays);
const y = dt.getFullYear();
const m = String(dt.getMonth() + 1).padStart(2, '0');
const d = String(dt.getDate()).padStart(2, '0');
return `${y}-${m}-${d}`;
}
function initAutoDateRange(preferredEnd?: string) {
const end = preferredEnd && /^\d{4}-\d{2}-\d{2}$/.test(preferredEnd) ? preferredEnd : todayIso();
autoEndDate.value = end;
autoStartDate.value = shiftIso(end, -(Math.min(6, MAX_AUTO_COLLECT_DAYS - 1)));
}
const totalFee = computed(() =>
(batch.value?.items ?? []).reduce((sum, item) => sum + Number(item.feeAmount || 0), 0),
);
const itemCount = computed(() => batch.value?.items.length ?? 0);
const dateCount = computed(() => listFeeDates(batch.value?.items ?? []).length);
const previewItems = computed(() => {
const items = batch.value?.items ?? [];
if (!filterDate.value) return items;
return items.filter((item) => item.feeDate === filterDate.value);
});
const previewFee = computed(() =>
previewItems.value.reduce((sum, item) => sum + Number(item.feeAmount || 0), 0),
);
const dateModeLabel = computed(() => {
const mode = pageContext.value?.dateMode;
if (mode === 'single') return `单日 ${pageContext.value?.feeDate ?? ''}`;
if (mode === 'range') return '范围(本页不追加)';
return '未知';
});
const accumulatedLabel = computed(() => {
if (!dateCount.value) return '尚未累计';
return `${dateCount.value} 天 · ${itemCount.value} 条`;
});
const previewLabel = computed(() => {
if (!filterDate.value) return '全部已读';
return filterDate.value;
});
const autoDaySpanLabel = computed(() => {
try {
if (!autoStartDate.value || !autoEndDate.value) return `最多 ${MAX_AUTO_COLLECT_DAYS} 天`;
const n = listDatesInclusive(autoStartDate.value, autoEndDate.value).length;
return `${n} 天(上限 ${MAX_AUTO_COLLECT_DAYS})`;
} catch (error) {
return error instanceof Error ? error.message : '日期无效';
}
});
const shopTagLabel = computed(() => {
if (shopMatching.value) return '匹配中';
if (shopMatched.value && channelShopId.value != null) return '已授权';
if (pageMallName.value.trim()) return '未授权';
return '未识别';
});
const shopTagClass = computed(() => {
if (shopMatching.value) return 'ecbi-shop-tag--loading';
if (shopMatched.value && channelShopId.value != null) return 'ecbi-shop-tag--ok';
if (pageMallName.value.trim()) return 'ecbi-shop-tag--warn';
return 'ecbi-shop-tag--muted';
});
const headerShopTitle = computed(() => {
const name = pageMallName.value.trim() || '未识别店铺';
return `${name} · ${shopTagLabel.value}`;
});
function onHeatSelect(date: string | undefined) {
filterDate.value = date;
}
async function refreshContext() {
try {
pageContext.value = await resolveAdapter(location.href).getPageContext();
pageMallName.value = pageContext.value.mallName ?? '';
} catch {
pageContext.value = null;
pageMallName.value = '';
}
}
async function loadLocalSettings() {
const settings = await getSettings();
channelShopId.value = settings.channelShopId;
channelShopName.value = settings.channelShopName ?? '';
// 缓存仅作提示;真正读写前会按页面店名再精确校验
shopMatched.value =
channelShopId.value != null &&
Boolean(channelShopName.value) &&
channelShopName.value.trim() === (pageMallName.value || channelShopName.value).trim();
}
async function persistShop() {
await saveSettings({
channelShopId: channelShopId.value,
channelShopName: channelShopName.value,
});
}
async function clearMatchedShop() {
channelShopId.value = undefined;
channelShopName.value = '';
shopMatched.value = false;
await persistShop();
}
/** 仅按页面店铺名完全匹配;失败时提示去系统授权 */
async function matchShopFromPage(options: { quiet?: boolean } = {}): Promise<boolean> {
await refreshContext();
const mallName = pageMallName.value.trim();
if (!mallName) {
await clearMatchedShop();
if (!options.quiet) {
errorText.value = '未识别到页面店铺名,请确认已打开推广总览';
statusText.value = '无法匹配店铺';
}
return false;
}
// 已与当前页店名精确对应则复用
if (
channelShopId.value != null &&
channelShopName.value.trim() === mallName
) {
shopMatched.value = true;
return true;
}
shopMatching.value = true;
if (!options.quiet) errorText.value = '';
try {
const matched = await matchChannelShopByMallName(mallName);
if (!matched) {
await clearMatchedShop();
const hint = shopAuthorizeHint(mallName);
errorText.value = hint;
statusText.value = '店铺未授权';
return false;
}
channelShopId.value = matched.id;
channelShopName.value = matched.mallName ?? mallName;
shopMatched.value = true;
await persistShop();
statusText.value = `已匹配授权店铺:${channelShopName.value}`;
return true;
} catch (error) {
await clearMatchedShop();
errorText.value = toUserMessage(error);
statusText.value = '店铺匹配失败';
return false;
} finally {
shopMatching.value = false;
}
}
async function ensureChannelShop(): Promise<void> {
const ok = await matchShopFromPage();
if (!ok || channelShopId.value == null) {
const mallName = pageMallName.value.trim();
throw new Error(
mallName ? shopAuthorizeHint(mallName) : '未识别到页面店铺名,请确认已打开推广总览',
);
}
}
async function handleRead(fromAuto = false, allowEmpty = false) {
busy.value = true;
errorText.value = '';
syncResultText.value = '';
statusText.value = fromAuto ? '自动读取中…' : '正在读取…';
try {
await refreshContext();
if (pageContext.value?.dateMode === 'range') {
statusText.value = '范围视图不追加;已累计数据仍保留';
errorText.value = pageContext.value.message ?? '请切回单日后再读取';
return;
}
await ensureChannelShop();
statusText.value = '检查分页(每页 100)…';
const adapter = resolveAdapter(location.href);
const parsed = await adapter.parseAdvertisingCost({ allowEmpty });
const incomingDate = parsed.items[0]?.feeDate ?? pageContext.value?.feeDate;
const addedOrUpdated = parsed.items.length;
if (parsed.items.length > 0) {
batch.value = {
platform: parsed.platform,
channelShopId: channelShopId.value!,
items: mergeAdvertisingItems(batch.value?.items ?? [], parsed.items),
source: 'browser-extension',
importedAt: new Date().toISOString(),
};
if (incomingDate) filterDate.value = incomingDate;
}
await refreshContext();
const tag = parsed.platform === 'mock' ? 'Mock' : '页面';
if (addedOrUpdated === 0) {
statusText.value = incomingDate
? `${incomingDate} 无推广费数据(已跳过)· 累计 ${dateCount.value} 天`
: '当日无推广费数据';
return;
}
statusText.value = incomingDate
? `已合并 ${incomingDate}(${addedOrUpdated} 条,${tag})· 累计 ${dateCount.value} 天`
: `已读取(${tag})`;
} catch (error) {
statusText.value = '读取失败';
errorText.value = toUserMessage(error);
} finally {
busy.value = false;
}
}
function clearAccumulated() {
batch.value = null;
filterDate.value = undefined;
syncResultText.value = '';
errorText.value = '';
statusText.value = '已清空累计数据';
}
function scheduleAutoRead(delayMs = 450) {
if (suppressUrlAutoRead || autoRunning.value) return;
if (readTimer) clearTimeout(readTimer);
readTimer = setTimeout(() => {
void handleRead(true).catch(() => {
// 错误已写入 errorText
});
}, delayMs);
}
async function onPageUrlChanged() {
if (suppressUrlAutoRead || autoRunning.value) {
await refreshContext();
return;
}
await refreshContext();
if (pageContext.value?.dateMode === 'single') {
errorText.value = '';
scheduleAutoRead(1200);
return;
}
if (pageContext.value?.dateMode === 'range') {
statusText.value = '范围视图不追加;已累计数据仍保留';
}
}
async function handleAutoCollect() {
if (autoRunning.value) return;
errorText.value = '';
syncResultText.value = '';
try {
listDatesInclusive(autoStartDate.value, autoEndDate.value);
} catch (error) {
errorText.value = toUserMessage(error);
return;
}
autoAbort = new AbortController();
autoRunning.value = true;
suppressUrlAutoRead = true;
busy.value = true;
if (readTimer) {
clearTimeout(readTimer);
readTimer = null;
}
try {
await ensureChannelShop();
await runAutoCollectByDates({
startDate: autoStartDate.value,
endDate: autoEndDate.value,
skipDates: autoSkipRead.value ? listFeeDates(batch.value?.items ?? []) : [],
signal: autoAbort.signal,
onProgress: (p) => {
statusText.value = p.message;
},
readDay: async () => {
await refreshContext();
await ensureChannelShop();
const adapter = resolveAdapter(location.href);
const parsed = await adapter.parseAdvertisingCost({ allowEmpty: true });
const incomingDate = parsed.items[0]?.feeDate ?? pageContext.value?.feeDate;
if (parsed.items.length > 0) {
batch.value = {
platform: parsed.platform,
channelShopId: channelShopId.value!,
items: mergeAdvertisingItems(batch.value?.items ?? [], parsed.items),
source: 'browser-extension',
importedAt: new Date().toISOString(),
};
if (incomingDate) filterDate.value = incomingDate;
}
await refreshContext();
lastHref = location.href;
},
});
statusText.value = `自动读取完成 · 累计 ${dateCount.value} 天 ${itemCount.value} 条`;
} catch (error) {
if (error instanceof DOMException && error.name === 'AbortError') {
statusText.value = `已停止自动读取 · 累计 ${dateCount.value} 天`;
} else {
statusText.value = '自动读取中断';
errorText.value = toUserMessage(error);
}
} finally {
autoRunning.value = false;
suppressUrlAutoRead = false;
busy.value = false;
autoAbort = null;
lastHref = location.href;
}
}
function stopAutoCollect() {
autoAbort?.abort();
}
async function handleSync() {
if (!batch.value) {
errorText.value = '请先读取数据';
return;
}
busy.value = true;
errorText.value = '';
syncResultText.value = '';
statusText.value = '正在同步…';
try {
await ensureChannelShop();
const payload: AdvertisingCostBatch = {
...batch.value,
channelShopId: channelShopId.value!,
};
const result = await batchImportPddGoodsAdFee(payload, (task) => {
const done = (task.successCount ?? 0) + (task.failCount ?? 0);
statusText.value = `正在导入… ${done}/${task.totalCount ?? 0}`;
});
const failed = result.status === 'failed';
const partial = result.status === 'partial';
statusText.value = failed ? '同步失败' : partial ? '部分成功' : '同步完成';
const authHint = result.authExpired
? ',授权已失效请重新授权后再导失败商品'
: '';
syncResultText.value =
`成功 ${result.successCount}/${result.totalCount}` +
(result.failCount ? `,失败 ${result.failCount}` : '') +
authHint;
} catch (error) {
statusText.value = '同步失败';
errorText.value = toUserMessage(error);
} finally {
busy.value = false;
}
}
function onHeaderPointerDown(event: PointerEvent) {
if ((event.target as HTMLElement).closest('button')) return;
dragging = true;
dragOffset = {
x: event.clientX - position.value.left,
y: event.clientY - position.value.top,
};
(event.currentTarget as HTMLElement).setPointerCapture(event.pointerId);
}
function onHeaderPointerMove(event: PointerEvent) {
if (!dragging) return;
const maxLeft = window.innerWidth - 80;
const maxTop = window.innerHeight - 80;
position.value = {
left: Math.min(maxLeft, Math.max(8, event.clientX - dragOffset.x)),
top: Math.min(maxTop, Math.max(8, event.clientY - dragOffset.y)),
};
}
function onHeaderPointerUp(event: PointerEvent) {
dragging = false;
try {
(event.currentTarget as HTMLElement).releasePointerCapture(event.pointerId);
} catch {
// ignore
}
}
onMounted(async () => {
await loadLocalSettings();
await refreshContext();
initAutoDateRange(pageContext.value?.feeDate);
const matched = await matchShopFromPage({ quiet: true });
if (pageContext.value?.dateMode === 'range') {
statusText.value = '范围视图不追加;请切到单日逐日读取并累计';
errorText.value = pageContext.value.message ?? '';
} else if (matched) {
scheduleAutoRead();
} else if (pageMallName.value.trim()) {
errorText.value = shopAuthorizeHint(pageMallName.value);
statusText.value = '店铺未授权';
}
lastHref = location.href;
urlPollTimer = setInterval(() => {
if (location.href === lastHref) return;
lastHref = location.href;
void onPageUrlChanged();
}, 800);
});
onUnmounted(() => {
autoAbort?.abort();
if (readTimer) clearTimeout(readTimer);
if (urlPollTimer) clearInterval(urlPollTimer);
});
</script>
<template>
<div
ref="panelRef"
class="ecbi-panel"
:style="{ top: `${position.top}px`, left: `${position.left}px` }"
>
<header
class="ecbi-header"
@pointerdown="onHeaderPointerDown"
@pointermove="onHeaderPointerMove"
@pointerup="onHeaderPointerUp"
@pointercancel="onHeaderPointerUp"
>
<div class="ecbi-header-main">
<h1>{{ EXTENSION_NAME }}</h1>
<div class="ecbi-header-shop" :title="headerShopTitle">
<span class="ecbi-header-shop-name">{{ pageMallName.trim() || '未识别店铺' }}</span>
<span class="ecbi-shop-tag" :class="shopTagClass">{{ shopTagLabel }}</span>
</div>
<p class="ecbi-header-stats">{{ accumulatedLabel }}</p>
</div>
<div class="ecbi-header-actions">
<button
class="ecbi-header-link"
type="button"
title="按页面店名重新精确匹配"
:disabled="shopMatching || busy || autoRunning"
@pointerdown.stop
@click="matchShopFromPage()"
>
{{ shopMatching ? '…' : '匹配' }}
</button>
<button class="ecbi-icon-btn" type="button" title="收起" @click="emit('minimize')">
–
</button>
<button class="ecbi-icon-btn" type="button" title="关闭" @click="emit('close')">
×
</button>
</div>
</header>
<div class="ecbi-body">
<div class="ecbi-status-bar">
<p class="ecbi-status" :class="{ 'ecbi-status-busy': busy || autoRunning }">
{{ statusText }}
</p>
<p v-if="syncResultText" class="ecbi-ok">{{ syncResultText }}</p>
<p v-if="errorText" class="ecbi-error">{{ errorText }}</p>
</div>
<div class="ecbi-meta">
<span>{{ dateModeLabel }}</span>
<span class="ecbi-meta-sep">·</span>
<span class="ecbi-fee">¥{{ totalFee.toFixed(2) }}</span>
<span class="ecbi-muted">/ {{ itemCount }} 条</span>
</div>
<section class="ecbi-card ecbi-card-tight">
<DateHeatmap
:items="batch?.items ?? []"
:page-date="pageContext?.feeDate"
:selected-date="filterDate"
@select="onHeatSelect"
/>
<div v-if="filterDate" class="ecbi-heat-filter">
<span class="ecbi-muted">筛选 {{ filterDate }} · ¥{{ previewFee.toFixed(2) }}</span>
<button class="ecbi-link" type="button" @click="filterDate = undefined">全部</button>
</div>
</section>
<div class="ecbi-actions">
<button
class="ecbi-btn ecbi-btn-ghost"
type="button"
:disabled="busy || autoRunning"
@click="handleRead(false)"
>
读当日
</button>
<button
class="ecbi-btn ecbi-btn-ghost"
type="button"
:disabled="busy || autoRunning || !batch?.items?.length"
@click="clearAccumulated"
>
清空累计
</button>
<button
class="ecbi-btn ecbi-btn-primary"
type="button"
:disabled="busy || autoRunning || !batch?.items?.length"
@click="handleSync"
>
同步到系统
</button>
</div>
<details class="ecbi-fold">
<summary>自动逐日 · {{ autoDaySpanLabel }}</summary>
<div class="ecbi-fold-body">
<div class="ecbi-date-row">
<label class="ecbi-date-field">
<span class="ecbi-muted">开始</span>
<input
v-model="autoStartDate"
class="ecbi-date-input"
type="date"
:disabled="autoRunning"
/>
</label>
<label class="ecbi-date-field">
<span class="ecbi-muted">结束</span>
<input
v-model="autoEndDate"
class="ecbi-date-input"
type="date"
:disabled="autoRunning"
/>
</label>
</div>
<div class="ecbi-row" style="margin-top: 8px">
<label class="ecbi-check">
<input v-model="autoSkipRead" type="checkbox" :disabled="autoRunning" />
跳过已读
</label>
</div>
<div class="ecbi-actions" style="margin-top: 10px">
<button
v-if="!autoRunning"
class="ecbi-btn ecbi-btn-ghost"
type="button"
:disabled="busy"
@click="handleAutoCollect"
>
开始
</button>
<button v-else class="ecbi-btn ecbi-btn-ghost" type="button" @click="stopAutoCollect">
停止
</button>
</div>
</div>
</details>
<details class="ecbi-fold">
<summary>明细 · {{ previewLabel }}({{ previewItems.length }})</summary>
<div class="ecbi-fold-body">
<ul v-if="previewItems.length" class="ecbi-list">
<li v-for="item in previewItems" :key="`${item.feeDate}-${item.goodsId}`">
<span>{{ item.feeDate }} · {{ item.goodsId }}</span>
<span>¥{{ Number(item.feeAmount).toFixed(2) }}</span>
</li>
</ul>
<p v-else class="ecbi-muted" style="margin: 0">暂无数据</p>
</div>
</details>
</div>
</div>
</template>
@@ -0,0 +1,141 @@
import { createApp, type App } from 'vue';
import { emitFeatureEvent } from '@/features/runtime/mainWorldAdapters';
import FloatingPanel from './FloatingPanel.vue';
import styles from './styles.css?inline';
const HOST_ID = 'ecbi-float-host';
const LAUNCHER_ID = 'ecbi-float-launcher';
const FEATURE_ID = 'pdd-ad-fee';
let app: App<Element> | null = null;
let visible = false;
let minimized = false;
function ensureHost(): HTMLElement {
let host = document.getElementById(HOST_ID);
if (!host) {
host = document.createElement('div');
host.id = HOST_ID;
document.documentElement.appendChild(host);
}
return host;
}
function ensureShadow(host: HTMLElement): ShadowRoot {
return host.shadowRoot ?? host.attachShadow({ mode: 'open' });
}
function setHostHidden(hidden: boolean) {
const host = document.getElementById(HOST_ID);
if (host) {
host.style.display = hidden ? 'none' : '';
}
}
function removeLauncher() {
document.getElementById(LAUNCHER_ID)?.remove();
}
function showLauncher() {
removeLauncher();
const btn = document.createElement('button');
btn.id = LAUNCHER_ID;
btn.type = 'button';
btn.textContent = 'ECBI';
btn.title = '展开 ECBI 悬浮面板';
Object.assign(btn.style, {
position: 'fixed',
right: '16px',
bottom: '16px',
zIndex: '2147483646',
border: '0',
borderRadius: '999px',
padding: '10px 16px',
background: '#1677ff',
color: '#fff',
fontSize: '13px',
fontWeight: '500',
cursor: 'pointer',
boxShadow: '0 6px 16px rgba(22, 119, 255, 0.35)',
} as CSSStyleDeclaration);
btn.addEventListener('click', () => {
minimized = false;
setFloatingVisible(true);
emitFeatureEvent(FEATURE_ID, 'restored');
});
document.documentElement.appendChild(btn);
}
function unmountApp() {
if (app) {
app.unmount();
app = null;
}
const host = document.getElementById(HOST_ID);
if (host?.shadowRoot) {
host.shadowRoot.innerHTML = '';
}
if (host) {
host.style.display = '';
}
}
function mountApp() {
const host = ensureHost();
const shadow = ensureShadow(host);
shadow.innerHTML = '';
host.style.display = '';
const styleEl = document.createElement('style');
styleEl.textContent = styles;
shadow.appendChild(styleEl);
const mountEl = document.createElement('div');
shadow.appendChild(mountEl);
app = createApp(FloatingPanel, {
onClose: () => setFloatingVisible(false),
onMinimize: () => {
// 只隐藏,不销毁 Vue,保留已累计的多日数据
minimized = true;
setHostHidden(true);
showLauncher();
visible = true;
emitFeatureEvent(FEATURE_ID, 'minimized');
},
});
app.mount(mountEl);
}
export function isFloatingVisible(): boolean {
return visible;
}
export function setFloatingVisible(next: boolean): boolean {
if (!next) {
const wasVisible = visible;
visible = false;
minimized = false;
unmountApp();
removeLauncher();
if (wasVisible) {
emitFeatureEvent(FEATURE_ID, 'closed');
}
return false;
}
visible = true;
minimized = false;
removeLauncher();
setHostHidden(false);
if (!app) {
mountApp();
}
return true;
}
export function toggleFloatingPanel(): boolean {
return setFloatingVisible(!visible || minimized);
}
@@ -0,0 +1,673 @@
#ecbi-float-host {
all: initial;
}
/* Ant Design 风格 token(不引入组件库,仅对齐色板与圆角) */
.ecbi-panel {
--ecbi-primary: #1677ff;
--ecbi-primary-hover: #4096ff;
--ecbi-primary-active: #0958d9;
--ecbi-primary-bg: #e6f4ff;
--ecbi-text: rgba(0, 0, 0, 0.88);
--ecbi-text-secondary: rgba(0, 0, 0, 0.45);
--ecbi-text-tertiary: rgba(0, 0, 0, 0.25);
--ecbi-border: #d9d9d9;
--ecbi-border-secondary: #f0f0f0;
--ecbi-fill: #f5f5f5;
--ecbi-bg: #ffffff;
--ecbi-success: #52c41a;
--ecbi-error: #ff4d4f;
--ecbi-radius: 8px;
--ecbi-radius-lg: 12px;
--ecbi-radius-sm: 6px;
position: fixed;
z-index: 2147483646;
width: 380px;
max-height: min(640px, calc(100vh - 24px));
overflow: hidden;
display: flex;
flex-direction: column;
border-radius: var(--ecbi-radius-lg);
border: 1px solid var(--ecbi-border-secondary);
background: var(--ecbi-bg);
color: var(--ecbi-text);
box-shadow:
0 6px 16px 0 rgb(0 0 0 / 0.08),
0 3px 6px -4px rgb(0 0 0 / 0.12),
0 9px 28px 8px rgb(0 0 0 / 0.05);
font-family:
-apple-system,
BlinkMacSystemFont,
'Segoe UI',
Roboto,
'Helvetica Neue',
Arial,
'Noto Sans',
sans-serif;
font-size: 13px;
line-height: 1.5714;
}
/* 面板内所有滚动条统一细条 */
.ecbi-panel,
.ecbi-panel * {
scrollbar-width: thin;
scrollbar-color: rgb(0 0 0 / 0.28) transparent;
}
.ecbi-panel::-webkit-scrollbar,
.ecbi-panel *::-webkit-scrollbar {
width: 6px;
height: 6px;
}
.ecbi-panel::-webkit-scrollbar-thumb,
.ecbi-panel *::-webkit-scrollbar-thumb {
background: rgb(0 0 0 / 0.28);
border-radius: 3px;
}
.ecbi-panel::-webkit-scrollbar-thumb:hover,
.ecbi-panel *::-webkit-scrollbar-thumb:hover {
background: rgb(0 0 0 / 0.4);
}
.ecbi-panel::-webkit-scrollbar-track,
.ecbi-panel *::-webkit-scrollbar-track {
background: transparent;
}
.ecbi-header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
padding: 12px 14px;
background: var(--ecbi-primary);
color: #fff;
cursor: move;
user-select: none;
border-radius: var(--ecbi-radius-lg) var(--ecbi-radius-lg) 0 0;
}
.ecbi-header h1 {
margin: 0;
font-size: 14px;
font-weight: 600;
}
.ecbi-header p {
margin: 2px 0 0;
font-size: 12px;
opacity: 0.85;
}
.ecbi-header-main {
min-width: 0;
flex: 1;
}
.ecbi-header-sub {
max-width: 100%;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.ecbi-header-stats {
margin: 2px 0 0;
font-size: 12px;
opacity: 0.8;
max-width: 100%;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.ecbi-header-sub-warn {
color: #ffe58f;
opacity: 1;
}
.ecbi-header-shop {
display: flex;
align-items: center;
gap: 6px;
margin-top: 2px;
min-width: 0;
}
.ecbi-header-shop-name {
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
font-size: 12px;
opacity: 0.92;
}
.ecbi-shop-tag {
flex-shrink: 0;
display: inline-flex;
align-items: center;
height: 20px;
padding: 0 8px;
border-radius: 4px;
font-size: 11px;
font-weight: 600;
line-height: 1;
}
.ecbi-shop-tag--ok {
background: #f6ffed;
color: #389e0d;
border: 1px solid #b7eb8f;
box-shadow: 0 0 0 1px rgb(255 255 255 / 0.35);
}
.ecbi-shop-tag--warn {
background: #fffbe6;
color: #ad6800;
border: 1px solid #ffe58f;
}
.ecbi-shop-tag--loading {
background: rgb(255 255 255 / 0.22);
color: #fff;
border: 1px solid rgb(255 255 255 / 0.4);
}
.ecbi-shop-tag--muted {
background: rgb(255 255 255 / 0.16);
color: rgb(255 255 255 / 0.9);
border: 1px solid rgb(255 255 255 / 0.28);
}
.ecbi-status-bar {
display: flex;
flex-direction: column;
gap: 4px;
padding: 8px 10px;
border-radius: var(--ecbi-radius);
background: var(--ecbi-fill);
border: 1px solid var(--ecbi-border-secondary);
}
.ecbi-status-bar .ecbi-status,
.ecbi-status-bar .ecbi-ok,
.ecbi-status-bar .ecbi-error {
margin: 0;
}
.ecbi-header-link {
border: 0;
background: rgb(255 255 255 / 0.16);
color: #fff;
height: 28px;
padding: 0 8px;
border-radius: var(--ecbi-radius-sm);
font-size: 12px;
cursor: pointer;
}
.ecbi-header-link:hover:not(:disabled) {
background: rgb(255 255 255 / 0.28);
}
.ecbi-header-link:disabled {
opacity: 0.5;
cursor: not-allowed;
}
.ecbi-header-actions {
display: flex;
gap: 4px;
}
.ecbi-icon-btn {
border: 0;
background: transparent;
color: #fff;
width: 28px;
height: 28px;
border-radius: var(--ecbi-radius-sm);
cursor: pointer;
}
.ecbi-icon-btn:hover {
background: rgb(255 255 255 / 0.16);
}
.ecbi-body {
padding: 12px 14px 14px;
overflow: auto;
display: flex;
flex-direction: column;
gap: 10px;
}
.ecbi-meta {
display: flex;
align-items: baseline;
flex-wrap: wrap;
gap: 4px 6px;
font-size: 13px;
}
.ecbi-meta-sep {
color: var(--ecbi-text-tertiary);
}
.ecbi-row-links {
display: inline-flex;
gap: 10px;
}
.ecbi-card-tight {
padding: 10px;
}
.ecbi-fold {
border: 1px solid var(--ecbi-border-secondary);
border-radius: var(--ecbi-radius);
background: var(--ecbi-bg);
padding: 0 10px;
}
.ecbi-fold > summary {
cursor: pointer;
list-style: none;
padding: 8px 0;
font-size: 12px;
color: var(--ecbi-text-secondary);
user-select: none;
}
.ecbi-fold > summary::-webkit-details-marker {
display: none;
}
.ecbi-fold > summary::before {
content: '▸';
display: inline-block;
margin-right: 6px;
transition: transform 0.15s;
}
.ecbi-fold[open] > summary::before {
transform: rotate(90deg);
}
.ecbi-fold-body {
padding: 0 0 10px;
}
.ecbi-status {
margin: 0;
font-size: 12px;
color: var(--ecbi-text-secondary);
line-height: 1.4;
}
.ecbi-status-busy {
color: var(--ecbi-primary);
}
.ecbi-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
}
.ecbi-label {
color: var(--ecbi-text-secondary);
flex-shrink: 0;
}
.ecbi-input,
.ecbi-select {
width: 100%;
border: 1px solid var(--ecbi-border);
border-radius: var(--ecbi-radius);
padding: 6px 11px;
font-size: 13px;
outline: none;
background: var(--ecbi-bg);
color: var(--ecbi-text);
box-sizing: border-box;
transition:
border-color 0.2s,
box-shadow 0.2s;
}
.ecbi-input:focus,
.ecbi-select:focus {
border-color: var(--ecbi-primary);
box-shadow: 0 0 0 2px rgb(22 119 255 / 0.2);
}
.ecbi-field {
display: flex;
flex-direction: column;
gap: 6px;
}
.ecbi-actions {
display: flex;
gap: 8px;
}
.ecbi-btn {
flex: 1;
border-radius: var(--ecbi-radius);
border: 1px solid var(--ecbi-border);
background: var(--ecbi-bg);
color: var(--ecbi-text);
padding: 6px 12px;
font-size: 13px;
font-weight: 400;
line-height: 1.5714;
cursor: pointer;
transition:
color 0.2s,
border-color 0.2s,
background 0.2s;
}
.ecbi-btn:disabled {
opacity: 0.45;
cursor: not-allowed;
}
.ecbi-btn-primary {
border-color: var(--ecbi-primary);
background: var(--ecbi-primary);
color: #fff;
}
.ecbi-btn-primary:hover:not(:disabled) {
border-color: var(--ecbi-primary-hover);
background: var(--ecbi-primary-hover);
}
.ecbi-btn-primary:active:not(:disabled) {
border-color: var(--ecbi-primary-active);
background: var(--ecbi-primary-active);
}
.ecbi-btn-ghost:hover:not(:disabled) {
color: var(--ecbi-primary);
border-color: var(--ecbi-primary);
}
.ecbi-card {
border: 1px solid var(--ecbi-border-secondary);
border-radius: var(--ecbi-radius-lg);
padding: 12px;
background: var(--ecbi-fill);
}
.ecbi-card h2 {
margin: 0 0 8px;
font-size: 12px;
font-weight: 600;
color: var(--ecbi-text-secondary);
}
.ecbi-fee {
font-weight: 600;
color: var(--ecbi-error);
}
.ecbi-list {
margin: 8px 0 0;
padding: 0;
list-style: none;
max-height: 120px;
overflow: auto;
}
.ecbi-list li {
display: flex;
justify-content: space-between;
gap: 8px;
font-size: 12px;
color: var(--ecbi-text-secondary);
padding: 3px 0;
}
.ecbi-muted {
color: var(--ecbi-text-tertiary);
font-size: 12px;
}
.ecbi-error {
color: var(--ecbi-error);
font-size: 12px;
margin: 0;
}
.ecbi-ok {
color: var(--ecbi-success);
font-size: 12px;
margin: 0;
}
.ecbi-link {
border: 0;
background: transparent;
color: var(--ecbi-primary);
font-size: 12px;
cursor: pointer;
padding: 0;
}
.ecbi-link:hover {
color: var(--ecbi-primary-hover);
}
/* —— 读取日历(贡献图,蓝色阶) —— */
.ecbi-heat {
display: flex;
flex-direction: column;
gap: 6px;
}
.ecbi-heat-head {
display: flex;
align-items: baseline;
justify-content: space-between;
gap: 8px;
}
.ecbi-heat-title {
font-size: 12px;
font-weight: 600;
color: var(--ecbi-text-secondary);
}
.ecbi-heat-body {
display: flex;
gap: 4px;
overflow-x: auto;
padding-bottom: 2px;
}
.ecbi-heat-dows {
display: flex;
flex-direction: column;
gap: 3px;
flex-shrink: 0;
}
.ecbi-heat-month-spacer {
height: 14px;
}
.ecbi-heat-dow {
height: 11px;
width: 14px;
font-size: 9px;
line-height: 11px;
color: var(--ecbi-text-tertiary);
text-align: right;
}
.ecbi-heat-weeks {
display: flex;
gap: 3px;
}
.ecbi-heat-week {
display: flex;
flex-direction: column;
gap: 3px;
width: 11px;
}
.ecbi-heat-month {
height: 14px;
font-size: 9px;
line-height: 14px;
color: var(--ecbi-text-tertiary);
white-space: nowrap;
width: max-content;
max-width: none;
position: relative;
z-index: 1;
pointer-events: none;
}
.ecbi-heat-cell {
width: 11px;
height: 11px;
border-radius: 3px;
border: 0;
padding: 0;
display: block;
box-sizing: border-box;
background: #ebedf0;
cursor: default;
}
button.ecbi-heat-cell:not(:disabled) {
cursor: pointer;
}
button.ecbi-heat-cell:disabled {
opacity: 1;
}
.ecbi-heat-l0 {
background: #ebedf0;
}
.ecbi-heat-l1 {
background: #9be9a8;
}
.ecbi-heat-l2 {
background: #40c463;
}
.ecbi-heat-l3 {
background: #30a14e;
}
.ecbi-heat-l4 {
background: #216e39;
}
.ecbi-heat-out {
opacity: 0.35;
}
.ecbi-heat-page {
outline: 1px dashed var(--ecbi-primary);
outline-offset: 0;
}
.ecbi-heat-today:not(.ecbi-heat-selected) {
box-shadow: inset 0 0 0 1px var(--ecbi-text-secondary);
}
.ecbi-heat-selected {
outline: 2px solid var(--ecbi-text);
outline-offset: 0;
}
.ecbi-heat-legend {
display: flex;
align-items: center;
gap: 3px;
flex-wrap: wrap;
}
.ecbi-heat-gap {
width: 8px;
}
.ecbi-heat-filter {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
margin-top: 2px;
}
.ecbi-date-row {
display: flex;
flex-direction: column;
gap: 8px;
align-items: stretch;
}
.ecbi-date-field {
display: flex;
flex-direction: column;
gap: 4px;
width: 100%;
min-width: 0;
}
.ecbi-date-input {
box-sizing: border-box;
width: 100%;
max-width: 100%;
min-width: 0;
height: 32px;
padding: 4px 8px;
border: 1px solid var(--ecbi-border);
border-radius: var(--ecbi-radius-sm);
background: var(--ecbi-bg);
color: var(--ecbi-text);
font-size: 13px;
outline: none;
}
.ecbi-date-input:focus {
border-color: var(--ecbi-primary);
box-shadow: 0 0 0 2px rgb(22 119 255 / 0.1);
}
.ecbi-date-input:disabled {
background: var(--ecbi-fill);
color: var(--ecbi-text-secondary);
cursor: not-allowed;
}
.ecbi-check {
display: inline-flex;
align-items: center;
gap: 6px;
font-size: 12px;
color: var(--ecbi-text);
cursor: pointer;
user-select: none;
}
.ecbi-check input {
margin: 0;
}
+106
View File
@@ -0,0 +1,106 @@
import {
getActiveFeatureId,
isFeatureUiVisible,
mountFeature,
unmountActiveFeature,
} from '@/features/runtime/registry';
import { startBridgeHost } from '@/features/runtime/bridgeHost';
import { resolveAdapter } from '@/platform/core/PlatformDetector';
import { ExtensionError } from '@/shared/errors';
import {
isExtensionMessage,
type ExtensionMessage,
type ExtensionResponse,
} from '@/shared/messages';
import type { AdvertisingCostBatch } from '@/types/advertisingCost';
startBridgeHost();
async function handleMessage(message: ExtensionMessage): Promise<ExtensionResponse> {
const adapter = resolveAdapter(location.href);
switch (message.type) {
case 'PING':
return { ok: true, data: { pong: true } };
case 'GET_PAGE_CONTEXT': {
const data = await adapter.getPageContext();
return { ok: true, data };
}
case 'PARSE_ADVERTISING_COST': {
const parsed = await adapter.parseAdvertisingCost();
const data: AdvertisingCostBatch = {
...parsed,
channelShopId: 0,
};
return { ok: true, data };
}
case 'TOGGLE_FLOATING_PANEL': {
if (isFeatureUiVisible()) {
await unmountActiveFeature();
return { ok: true, data: { visible: false } };
}
return {
ok: false,
code: 'UNKNOWN',
message: '请从 Popup 打开功能(需下载远程脚本)',
};
}
case 'SET_FLOATING_PANEL': {
if (!message.payload.visible) {
await unmountActiveFeature();
return { ok: true, data: { visible: false } };
}
return {
ok: false,
code: 'UNKNOWN',
message: '请从 Popup 打开功能(需下载远程脚本)',
};
}
case 'GET_FLOATING_PANEL_STATE': {
return { ok: true, data: { visible: isFeatureUiVisible() } };
}
case 'MOUNT_FEATURE': {
await mountFeature(message.payload.featureId, message.payload.code);
return { ok: true, data: { featureId: message.payload.featureId } };
}
case 'UNMOUNT_FEATURE': {
await unmountActiveFeature();
return { ok: true, data: { featureId: null } };
}
case 'GET_ACTIVE_FEATURE': {
return { ok: true, data: { featureId: getActiveFeatureId() } };
}
default:
return {
ok: false,
code: 'UNKNOWN',
message: '未知消息类型',
};
}
}
chrome.runtime.onMessage.addListener((message, _sender, sendResponse) => {
if (!isExtensionMessage(message)) {
return false;
}
void handleMessage(message)
.then((result) => sendResponse(result))
.catch((error: unknown) => {
const err =
error instanceof ExtensionError
? error
: new ExtensionError(
'UNKNOWN',
error instanceof Error ? error.message : 'Content Script 处理失败',
);
const response: ExtensionResponse = {
ok: false,
code: err.code,
message: err.message,
};
sendResponse(response);
});
return true;
});
+12
View File
@@ -0,0 +1,12 @@
/// <reference types="vite/client" />
declare module '*.vue' {
import type { DefineComponent } from 'vue';
const component: DefineComponent<object, object, unknown>;
export default component;
}
declare module '*.css?inline' {
const css: string;
export default css;
}
@@ -0,0 +1,45 @@
/**
* 远程功能包入口(IIFE → artifacts/features/pdd-ad-fee.js)。
* 在页面 MAIN world 执行;Open API / 设置走壳侧 postMessage 桥接。
*/
import { installMainWorldAdapters } from '@/features/runtime/mainWorldAdapters';
import { setFloatingVisible } from '@/content/floating/mount';
const FEATURE_ID = 'pdd-ad-fee';
const FEATURE_VERSION = '0.3.10';
export interface RemoteFeatureExport {
id: string;
version: string;
executionWorld: 'main';
mount: () => Promise<void>;
unmount: () => Promise<void>;
}
installMainWorldAdapters();
const feature: RemoteFeatureExport = {
id: FEATURE_ID,
version: FEATURE_VERSION,
executionWorld: 'main',
async mount() {
setFloatingVisible(true);
},
async unmount() {
setFloatingVisible(false);
},
};
declare global {
interface Window {
__ECBI_FEATURES__?: Record<string, RemoteFeatureExport>;
}
}
const g = globalThis as typeof globalThis & {
__ECBI_FEATURES__?: Record<string, RemoteFeatureExport>;
};
g.__ECBI_FEATURES__ = g.__ECBI_FEATURES__ ?? {};
g.__ECBI_FEATURES__[FEATURE_ID] = feature;
export default feature;
@@ -0,0 +1,89 @@
/**
* Content Script(isolated)侧桥接主机:代发 Open API、读写 chrome.storage。
*/
import { openApiRequest } from '@/api/client';
import { ExtensionError } from '@/shared/errors';
import { getSettings, saveSettings } from '@/storage/settings';
import {
ECBI_SHELL_SOURCE,
isBridgeFeatureEvent,
isBridgeRpcRequest,
type BridgeRpcRequest,
type BridgeRpcResult,
} from './bridgeProtocol';
import { clearActiveIfFeature, notifyFeatureEvent } from './registry';
let started = false;
function reply(result: BridgeRpcResult): void {
window.postMessage(result, '*');
}
async function handleRpc(msg: BridgeRpcRequest): Promise<void> {
try {
let data: unknown;
switch (msg.rpc) {
case 'OPEN_API': {
if (!msg.path) throw new ExtensionError('UNKNOWN', '缺少 path');
data = await openApiRequest(msg.path, {
method: msg.method || 'GET',
body: msg.body,
});
break;
}
case 'GET_SETTINGS':
data = await getSettings();
break;
case 'SAVE_SETTINGS':
data = await saveSettings(msg.patch ?? {});
break;
default:
throw new ExtensionError('UNKNOWN', `未知 RPC:${(msg as { rpc: string }).rpc}`);
}
reply({
source: ECBI_SHELL_SOURCE,
type: 'RPC_RESULT',
requestId: msg.requestId,
ok: true,
data,
});
} catch (error) {
const err =
error instanceof ExtensionError
? error
: new ExtensionError(
'UNKNOWN',
error instanceof Error ? error.message : '桥接处理失败',
);
reply({
source: ECBI_SHELL_SOURCE,
type: 'RPC_RESULT',
requestId: msg.requestId,
ok: false,
error: { code: err.code, message: err.message },
});
}
}
export function startBridgeHost(): void {
if (started) return;
started = true;
window.addEventListener('message', (event) => {
if (event.source !== window) return;
const data = event.data;
if (isBridgeRpcRequest(data)) {
void handleRpc(data);
return;
}
if (isBridgeFeatureEvent(data)) {
if (data.event === 'closed') {
clearActiveIfFeature(data.featureId);
}
notifyFeatureEvent(data.featureId, data.event);
}
});
}
@@ -0,0 +1,51 @@
/** 壳(isolated)↔ 功能(main world)postMessage 协议 */
export const ECBI_SHELL_SOURCE = 'ecbi-shell';
export const ECBI_FEATURE_SOURCE = 'ecbi-feature';
export type BridgeRpcType = 'OPEN_API' | 'GET_SETTINGS' | 'SAVE_SETTINGS';
export interface BridgeRpcRequest {
source: typeof ECBI_FEATURE_SOURCE;
type: 'RPC';
rpc: BridgeRpcType;
requestId: string;
path?: string;
method?: string;
body?: string;
patch?: Record<string, unknown>;
}
export interface BridgeRpcResult {
source: typeof ECBI_SHELL_SOURCE;
type: 'RPC_RESULT';
requestId: string;
ok: boolean;
data?: unknown;
error?: { code: string; message: string };
}
export interface BridgeFeatureEvent {
source: typeof ECBI_FEATURE_SOURCE;
type: 'FEATURE_EVENT';
featureId: string;
event: 'closed' | 'minimized' | 'restored';
}
export type BridgeIncoming = BridgeRpcRequest | BridgeFeatureEvent;
export function isBridgeRpcRequest(data: unknown): data is BridgeRpcRequest {
if (!data || typeof data !== 'object') return false;
const msg = data as BridgeRpcRequest;
return msg.source === ECBI_FEATURE_SOURCE && msg.type === 'RPC' && typeof msg.requestId === 'string';
}
export function isBridgeFeatureEvent(data: unknown): data is BridgeFeatureEvent {
if (!data || typeof data !== 'object') return false;
const msg = data as BridgeFeatureEvent;
return (
msg.source === ECBI_FEATURE_SOURCE &&
msg.type === 'FEATURE_EVENT' &&
typeof msg.featureId === 'string'
);
}
@@ -0,0 +1,96 @@
/**
* Main world 适配:把 Open API / chrome.storage 换成 postMessage RPC。
* 功能包 IIFE 加载时调用 installMainWorldAdapters()。
*/
import { ExtensionError } from '@/shared/errors';
import { setOpenApiRequestOverride } from '@/api/client';
import { setSettingsOverride, type ExtensionSettings } from '@/storage/settings';
import {
ECBI_FEATURE_SOURCE,
ECBI_SHELL_SOURCE,
type BridgeRpcResult,
type BridgeRpcType,
} from './bridgeProtocol';
const RPC_TIMEOUT_MS = 30_000;
function postRpc<T>(rpc: BridgeRpcType, payload: Record<string, unknown> = {}): Promise<T> {
const requestId = `${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
return new Promise<T>((resolve, reject) => {
const timer = window.setTimeout(() => {
window.removeEventListener('message', onMessage);
reject(new ExtensionError('NETWORK_ERROR', `桥接超时(${rpc})`));
}, RPC_TIMEOUT_MS);
function onMessage(event: MessageEvent) {
if (event.source !== window) return;
const data = event.data as BridgeRpcResult | undefined;
if (!data || data.source !== ECBI_SHELL_SOURCE || data.type !== 'RPC_RESULT') return;
if (data.requestId !== requestId) return;
window.clearTimeout(timer);
window.removeEventListener('message', onMessage);
if (!data.ok) {
reject(
new ExtensionError(
(data.error?.code as never) || 'UNKNOWN',
data.error?.message || '桥接调用失败',
),
);
return;
}
resolve(data.data as T);
}
window.addEventListener('message', onMessage);
window.postMessage(
{
source: ECBI_FEATURE_SOURCE,
type: 'RPC',
rpc,
requestId,
...payload,
},
'*',
);
});
}
let installed = false;
export function installMainWorldAdapters(): void {
if (installed) return;
installed = true;
setOpenApiRequestOverride(async <T,>(path: string, init: RequestInit = {}) => {
const method = (init.method || 'GET').toUpperCase();
const body = typeof init.body === 'string' ? init.body : undefined;
return postRpc<T>('OPEN_API', { path, method, body });
});
setSettingsOverride({
get: () => postRpc<ExtensionSettings>('GET_SETTINGS'),
save: (patch) =>
postRpc<ExtensionSettings>('SAVE_SETTINGS', {
patch: patch as Record<string, unknown>,
}),
});
}
export function emitFeatureEvent(
featureId: string,
event: 'closed' | 'minimized' | 'restored',
): void {
window.postMessage(
{
source: ECBI_FEATURE_SOURCE,
type: 'FEATURE_EVENT',
featureId,
event,
},
'*',
);
}
@@ -0,0 +1,39 @@
/** 通过 Background 向页面 MAIN world 注入/调用功能脚本(绕过页面 CSP) */
interface BgResponse {
ok: boolean;
message?: string;
}
function sendToBackground(message: unknown): Promise<void> {
return new Promise((resolve, reject) => {
chrome.runtime.sendMessage(message, (response: BgResponse | undefined) => {
if (chrome.runtime.lastError) {
reject(new Error(chrome.runtime.lastError.message));
return;
}
if (!response?.ok) {
reject(new Error(response?.message || 'Background 执行失败'));
return;
}
resolve();
});
});
}
export async function injectMainWorldScript(code: string): Promise<void> {
await sendToBackground({
type: 'INJECT_MAIN_SCRIPT',
payload: { code },
});
}
export async function callMainWorldFeature(
featureId: string,
action: 'mount' | 'unmount',
): Promise<void> {
await sendToBackground({
type: 'CALL_MAIN_FEATURE',
payload: { featureId, action },
});
}
@@ -0,0 +1,81 @@
import type { FeatureHandle } from '@/features/runtime/types';
import {
callMainWorldFeature,
injectMainWorldScript,
} from '@/features/runtime/mainWorldInject';
let active: { id: string; handle: FeatureHandle } | null = null;
type FeatureEventListener = (
featureId: string,
event: 'closed' | 'minimized' | 'restored',
) => void;
const listeners = new Set<FeatureEventListener>();
export function onFeatureEvent(listener: FeatureEventListener): () => void {
listeners.add(listener);
return () => listeners.delete(listener);
}
export function notifyFeatureEvent(
featureId: string,
event: 'closed' | 'minimized' | 'restored',
): void {
for (const listener of listeners) {
try {
listener(featureId, event);
} catch {
// ignore
}
}
}
export function getActiveFeatureId(): string | null {
return active?.id ?? null;
}
export function clearActiveIfFeature(featureId: string): void {
if (active?.id === featureId) {
active = null;
}
}
export async function mountFeature(featureId: string, code: string): Promise<void> {
if (!code?.trim()) {
throw new Error('缺少远程功能脚本,无法挂载');
}
if (active?.id === featureId) {
// 同一功能重新打开:先卸再挂,确保用最新脚本
await unmountActiveFeature();
} else {
await unmountActiveFeature();
}
await injectMainWorldScript(code);
await callMainWorldFeature(featureId, 'mount');
active = {
id: featureId,
handle: {
unmount: async () => {
await callMainWorldFeature(featureId, 'unmount');
},
},
};
}
export async function unmountActiveFeature(): Promise<void> {
if (!active) return;
const current = active;
active = null;
try {
await current.handle.unmount();
} catch {
// 页面可能已刷新,忽略
}
}
export function isFeatureUiVisible(): boolean {
return active != null;
}
@@ -0,0 +1,57 @@
/** 功能清单与模块约定(壳 / 远程脚本共用) */
export interface ExtensionFeatureItem {
id: string;
name: string;
version: string;
description?: string;
/** 匹配当前页才可打开,chrome match pattern 风格简化:含 host 即可 */
matchUrlPatterns: string[];
/** 相对静态目录的入口文件,如 pdd-ad-fee.js */
entry: string;
/** 脚本 sha256(hex),可选;有则下载后校验 */
sha256?: string;
/** main=页面 MAIN world 执行(可热更新);extension=仅壳内(已弃用) */
executionWorld?: 'extension' | 'main';
}
export interface ExtensionFeatureManifest {
schemaVersion: number;
updatedAt?: string;
features: ExtensionFeatureItem[];
}
export interface FeatureHandle {
unmount: () => void | Promise<void>;
}
export interface FeatureModule {
id: string;
mount: (ctx: FeatureMountContext) => FeatureHandle | Promise<FeatureHandle>;
}
export interface FeatureMountContext {
featureId: string;
/** 打开/关闭由壳控制时可回调 */
onClose?: () => void;
}
export function urlMatchesPatterns(url: string, patterns: string[] | null | undefined): boolean {
if (!patterns?.length) return true;
try {
return patterns.some((pattern) => matchPattern(url, pattern));
} catch {
// 非法 pattern 时不拖垮 Popup
return false;
}
}
/** 将 chrome 风格 * 通配转为安全正则(先按 * 切开再转义各段) */
function matchPattern(url: string, pattern: string): boolean {
if (!pattern) return false;
if (!pattern.includes('*')) {
return url.includes(pattern);
}
const parts = pattern.split('*').map((part) => part.replace(/[.+?^${}()|[\]\\]/g, '\\$&'));
return new RegExp(`^${parts.join('.*')}$`).test(url);
}
@@ -0,0 +1,15 @@
import type {
AdvertisingCostBatch,
PageContext,
PlatformType,
} from '@/types/advertisingCost';
export interface PlatformAdapter {
readonly platform: PlatformType;
canHandle(url: string): boolean;
getPageContext(): Promise<PageContext>;
/** 从当前页解析推广费;每条 item 自带 feeDate */
parseAdvertisingCost(
options?: { allowEmpty?: boolean },
): Promise<Omit<AdvertisingCostBatch, 'channelShopId'>>;
}
@@ -0,0 +1,25 @@
import type { PlatformType } from '@/types/advertisingCost';
import type { PlatformAdapter } from './PlatformAdapter';
import { MockPlatformAdapter } from '../mock/MockPlatformAdapter';
import { PddPlatformAdapter } from '../pdd/PddPlatformAdapter';
const adapters: PlatformAdapter[] = [new PddPlatformAdapter(), new MockPlatformAdapter()];
export function detectPlatform(url: string): PlatformType {
const adapter = adapters.find((item) => item.canHandle(url));
return adapter?.platform ?? 'unknown';
}
export function resolveAdapter(url: string): PlatformAdapter {
const matched = adapters.find((item) => item.canHandle(url));
if (matched) {
return matched;
}
// 非拼多多推广页时回退 Mock,便于本地联调
return adapters.find((item) => item.platform === 'mock') ?? adapters[0]!;
}
export function listAdapters(): PlatformAdapter[] {
return [...adapters];
}
@@ -0,0 +1,2 @@
export type { PlatformAdapter } from './PlatformAdapter';
export { detectPlatform, listAdapters, resolveAdapter } from './PlatformDetector';
@@ -0,0 +1,37 @@
import type { PlatformAdapter } from '@/platform/core/PlatformAdapter';
import type { AdvertisingCostBatch, PageContext } from '@/types/advertisingCost';
/**
* 第一阶段 Mock Adapter:不读真实 DOM,返回带日期的样例。
* 真实页面解析等接入平台后再实现。
*/
export class MockPlatformAdapter implements PlatformAdapter {
readonly platform = 'mock' as const;
canHandle(_url: string): boolean {
return true;
}
async getPageContext(): Promise<PageContext> {
return {
url: typeof location !== 'undefined' ? location.href : '',
title: typeof document !== 'undefined' ? document.title : '',
platform: 'mock',
ready: true,
message: '当前为 Mock Adapter(未解析真实平台页面)',
};
}
async parseAdvertisingCost(): Promise<Omit<AdvertisingCostBatch, 'channelShopId'>> {
return {
platform: 'mock',
items: [
{ feeDate: '2026-08-14', goodsId: 'mock-goods-1001', feeAmount: 128.5 },
{ feeDate: '2026-08-15', goodsId: 'mock-goods-1002', feeAmount: 56.0 },
{ feeDate: '2026-08-16', goodsId: 'mock-goods-1003', feeAmount: 1050.06 },
],
source: 'browser-extension',
importedAt: new Date().toISOString(),
};
}
}
@@ -0,0 +1,77 @@
import type { PlatformAdapter } from '@/platform/core/PlatformAdapter';
import type { AdvertisingCostBatch, PageContext } from '@/types/advertisingCost';
import { ensurePageSize100 } from './ensurePageSize';
import {
isPddPromotionOverviewUrl,
parsePromotionItems,
readMallName,
readReportDate,
} from './parseReport';
/**
* 拼多多推广平台 · 商品推广总览报表
* https://yingxiao.pinduoduo.com/goods/report/promotion/overView
*/
export class PddPlatformAdapter implements PlatformAdapter {
readonly platform = 'pdd' as const;
canHandle(url: string): boolean {
return isPddPromotionOverviewUrl(url);
}
async getPageContext(): Promise<PageContext> {
const mallName = readMallName();
const dateInfo = readReportDate();
const ready = Boolean(mallName) && dateInfo.mode !== 'unknown';
let message: string | undefined;
if (!mallName) {
message = '未识别到店铺名称';
} else if (dateInfo.mode === 'range') {
message = dateInfo.message;
} else if (dateInfo.mode === 'unknown') {
message = dateInfo.message;
} else {
message = `店铺「${mallName}」· 单日 ${dateInfo.feeDate}`;
}
return {
url: location.href,
title: document.title,
platform: 'pdd',
ready,
message,
mallName,
feeDate: dateInfo.feeDate,
dateMode: dateInfo.mode,
};
}
async parseAdvertisingCost(
options: { allowEmpty?: boolean } = {},
): Promise<Omit<AdvertisingCostBatch, 'channelShopId'>> {
const dateInfo = readReportDate();
if (dateInfo.mode === 'range') {
throw new Error(dateInfo.message ?? '范围报表不记录,请切换为单日查看');
}
if (dateInfo.mode !== 'single' || !dateInfo.feeDate) {
throw new Error(dateInfo.message ?? '未能识别单日报表日期');
}
// 读取前把「每页」自动切到 100,减少分页漏读
await ensurePageSize100();
const items = parsePromotionItems(dateInfo.feeDate);
if (items.length === 0 && !options.allowEmpty) {
throw new Error('未解析到商品推广费,请确认表格已加载且包含「总花费」列');
}
return {
platform: 'pdd',
items,
source: 'browser-extension',
importedAt: new Date().toISOString(),
};
}
}
@@ -0,0 +1,117 @@
import { normalizePddDate } from './parseReport';
import { humanPauseMs, sleep } from './domInteract';
import { switchToSingleDay } from './switchReportDate';
/** 单次自动逐日最多天数(含起止) */
export const MAX_AUTO_COLLECT_DAYS = 31;
export function listDatesInclusive(startIso: string, endIso: string): string[] {
const start = normalizePddDate(startIso) ?? startIso;
const end = normalizePddDate(endIso) ?? endIso;
if (!/^\d{4}-\d{2}-\d{2}$/.test(start) || !/^\d{4}-\d{2}-\d{2}$/.test(end)) {
throw new Error('起止日期格式无效');
}
if (start > end) {
throw new Error('开始日期不能晚于结束日期');
}
const dates: string[] = [];
const cursor = new Date(`${start}T00:00:00`);
const endDate = new Date(`${end}T00:00:00`);
while (cursor <= endDate) {
const y = cursor.getFullYear();
const m = String(cursor.getMonth() + 1).padStart(2, '0');
const d = String(cursor.getDate()).padStart(2, '0');
dates.push(`${y}-${m}-${d}`);
if (dates.length > MAX_AUTO_COLLECT_DAYS) {
throw new Error(`单次最多 ${MAX_AUTO_COLLECT_DAYS} 天,请缩小范围`);
}
cursor.setDate(cursor.getDate() + 1);
}
return dates;
}
export interface AutoCollectProgress {
index: number;
total: number;
date: string;
phase: 'switch' | 'read' | 'pause' | 'done' | 'skip';
message: string;
}
export interface AutoCollectOptions {
startDate: string;
endDate: string;
/** 已累计过的日期,默认跳过 */
skipDates?: Set<string> | string[];
signal?: AbortSignal;
onProgress?: (p: AutoCollectProgress) => void;
/** 切到该日后执行读取;返回是否成功(无数据也可 true) */
readDay: (date: string) => Promise<void>;
}
/**
* 按日拟人切换并读取。日间有随机停顿,避免过快连点。
*/
export async function runAutoCollectByDates(options: AutoCollectOptions): Promise<void> {
const dates = listDatesInclusive(options.startDate, options.endDate);
const skip = new Set(
[...(options.skipDates ?? [])].map((d) => normalizePddDate(d) ?? d),
);
for (let i = 0; i < dates.length; i++) {
if (options.signal?.aborted) {
throw new DOMException('已取消自动读取', 'AbortError');
}
const date = dates[i]!;
if (skip.has(date)) {
options.onProgress?.({
index: i + 1,
total: dates.length,
date,
phase: 'skip',
message: `跳过已读 ${date}(${i + 1}/${dates.length})`,
});
continue;
}
options.onProgress?.({
index: i + 1,
total: dates.length,
date,
phase: 'switch',
message: `切换日期 ${date}(${i + 1}/${dates.length})…`,
});
await switchToSingleDay(date, { signal: options.signal });
options.onProgress?.({
index: i + 1,
total: dates.length,
date,
phase: 'read',
message: `读取 ${date}(${i + 1}/${dates.length})…`,
});
await options.readDay(date);
if (i < dates.length - 1) {
const pause = humanPauseMs('betweenDays');
options.onProgress?.({
index: i + 1,
total: dates.length,
date,
phase: 'pause',
message: `已读 ${date},停顿 ${(pause / 1000).toFixed(1)}s 后继续…`,
});
await sleep(pause);
}
}
options.onProgress?.({
index: dates.length,
total: dates.length,
date: dates[dates.length - 1] ?? '',
phase: 'done',
message: `自动读取完成(${dates.length} 天)`,
});
}
@@ -0,0 +1,41 @@
/** 轻量 DOM 拟人点击(供分页、切日期等复用) */
export function sleep(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}
/** 均匀随机整数 [min, max] */
export function randomInt(min: number, max: number): number {
const lo = Math.ceil(min);
const hi = Math.floor(max);
return Math.floor(Math.random() * (hi - lo + 1)) + lo;
}
export function dispatchMouse(el: HTMLElement, type: string): void {
el.dispatchEvent(
new MouseEvent(type, {
bubbles: true,
cancelable: true,
view: window,
buttons: 1,
}),
);
}
/** Ant Design 控件开合依赖 mousedown,单用 click() 常无效 */
export function pointerClick(el: HTMLElement): void {
el.scrollIntoView({ block: 'center', inline: 'nearest' });
dispatchMouse(el, 'pointerdown');
dispatchMouse(el, 'mousedown');
dispatchMouse(el, 'pointerup');
dispatchMouse(el, 'mouseup');
dispatchMouse(el, 'click');
}
/** 操作间隔:略留余量等 UI/拉数,不再刻意拖慢 */
export function humanPauseMs(kind: 'betweenDays' | 'afterUi' | 'afterNav' = 'betweenDays'): number {
if (kind === 'afterUi') return randomInt(80, 180);
if (kind === 'afterNav') return randomInt(400, 800);
// 日与日之间:约 0.6s~1.2s
return randomInt(600, 1200);
}
@@ -0,0 +1,212 @@
import { PDD_SELECTORS } from './selectors';
const TARGET_PAGE_SIZE = 100;
function sleep(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}
function dispatchMouse(el: HTMLElement, type: string): void {
el.dispatchEvent(
new MouseEvent(type, {
bubbles: true,
cancelable: true,
view: window,
buttons: 1,
}),
);
}
/** Ant Design Select 开合依赖 mousedown,单用 click() 首次常打不开 */
function pointerClick(el: HTMLElement): void {
dispatchMouse(el, 'pointerdown');
dispatchMouse(el, 'mousedown');
dispatchMouse(el, 'pointerup');
dispatchMouse(el, 'mouseup');
dispatchMouse(el, 'click');
}
function findPageSizeSelect(doc: Document = document): HTMLElement | null {
const wrap =
doc.querySelector(PDD_SELECTORS.overviewTable) ??
doc.querySelector(PDD_SELECTORS.paginationWrap) ??
doc;
const perPage = wrap.querySelector(PDD_SELECTORS.perPageText);
const li = perPage?.closest('li') ?? wrap.querySelector('.anq-pagination-total-text');
const select =
(li?.querySelector(PDD_SELECTORS.pageSizeSelect) as HTMLElement | null) ??
(wrap.querySelector(
`${PDD_SELECTORS.paginationWrap} ${PDD_SELECTORS.pageSizeSelect}`,
) as HTMLElement | null);
return select;
}
function readCurrentPageSize(select: Element): number | undefined {
const item = select.querySelector(PDD_SELECTORS.pageSizeValue);
const raw = (item?.getAttribute('title') || item?.textContent || '').trim();
const value = Number(raw.replace(/[^\d]/g, ''));
return Number.isFinite(value) && value > 0 ? value : undefined;
}
function getCombobox(select: Element): HTMLInputElement | null {
return select.querySelector('input[role="combobox"], .anq-select-selection-search-input');
}
function isSelectOpen(select: Element): boolean {
return getCombobox(select)?.getAttribute('aria-expanded') === 'true';
}
/** 仅认「当前可见」的下拉,避免点到手动操作后残留的 hidden dropdown */
function findVisibleDropdown(doc: Document = document): HTMLElement | null {
const dropdowns = Array.from(doc.querySelectorAll('.anq-select-dropdown'));
for (const el of dropdowns) {
if (el.classList.contains('anq-select-dropdown-hidden')) continue;
const style = window.getComputedStyle(el);
if (style.display === 'none' || style.visibility === 'hidden') continue;
if (style.pointerEvents === 'none') continue;
return el as HTMLElement;
}
return null;
}
function isTargetOption(el: Element, target: number): boolean {
const title = (el.getAttribute('title') || '').trim();
const text = (el.textContent || '').replace(/\s+/g, ' ').trim();
if (title === String(target)) return true;
if (text === String(target)) return true;
if (text === `${target}条` || text === `${target} 条`) return true;
return false;
}
function findOptionIn(root: ParentNode, target: number): HTMLElement | null {
const candidates = root.querySelectorAll(
[
'.anq-select-item-option',
'[class*="select-item-option"]',
'[role="option"]',
].join(','),
);
for (const el of candidates) {
if (el.classList.contains('anq-select-item-option-disabled')) continue;
if (isTargetOption(el, target)) return el as HTMLElement;
}
return null;
}
async function waitForVisibleOption(
target: number,
timeoutMs: number,
doc: Document,
): Promise<HTMLElement | null> {
const started = Date.now();
while (Date.now() - started < timeoutMs) {
const dropdown = findVisibleDropdown(doc);
if (dropdown) {
const option = findOptionIn(dropdown, target);
if (option) return option;
}
await sleep(80);
}
return null;
}
async function waitUntilPageSize(
select: Element,
target: number,
timeoutMs = 4000,
): Promise<boolean> {
const started = Date.now();
while (Date.now() - started < timeoutMs) {
if (readCurrentPageSize(select) === target) return true;
await sleep(100);
}
return readCurrentPageSize(select) === target;
}
async function openPageSizeSelect(select: HTMLElement, doc: Document): Promise<boolean> {
const trigger =
(select.querySelector('.anq-select-selector') as HTMLElement | null) ?? select;
const input = getCombobox(select);
trigger.scrollIntoView({ block: 'center', inline: 'nearest' });
await sleep(50);
input?.focus({ preventScroll: true });
// 已打开则先关掉,保证重新挂载可见下拉(避免点到残留 hidden 节点)
if (isSelectOpen(select) || findVisibleDropdown(doc)) {
doc.body.dispatchEvent(
new KeyboardEvent('keydown', { key: 'Escape', bubbles: true, cancelable: true }),
);
await sleep(120);
}
pointerClick(trigger);
const started = Date.now();
while (Date.now() - started < 1500) {
if (isSelectOpen(select) && findVisibleDropdown(doc)) return true;
await sleep(80);
}
// 再试一次:部分 antd 版本首次 mousedown 被挡
pointerClick(trigger);
const retryStart = Date.now();
while (Date.now() - retryStart < 1500) {
if (isSelectOpen(select) && findVisibleDropdown(doc)) return true;
await sleep(80);
}
return Boolean(isSelectOpen(select) && findVisibleDropdown(doc));
}
/**
* 将推广商品表分页「每页」自动切到 100(若已是 100 则跳过)。
*
* 注意:首次进入页面时下拉选项不在 DOM;手动切换过后,antd 常把
* `.anq-select-dropdown-hidden` 残留在 body。若只搜全局 option,
* 会点到不可见节点「看似成功」或首次完全失败。因此必须:
* 1) 用 mousedown 序列真正打开 Select
* 2) 只点击「可见」dropdown 内的 100
*/
export async function ensurePageSize100(doc: Document = document): Promise<{
changed: boolean;
pageSize?: number;
}> {
const select = findPageSizeSelect(doc);
if (!select) {
return { changed: false };
}
const current = readCurrentPageSize(select);
if (current === TARGET_PAGE_SIZE) {
return { changed: false, pageSize: current };
}
const opened = await openPageSizeSelect(select, doc);
if (!opened) {
doc.body.dispatchEvent(
new KeyboardEvent('keydown', { key: 'Escape', bubbles: true, cancelable: true }),
);
throw new Error(
`未能打开每页条数下拉(当前 ${current ?? '未知'})。请先滚动到表格底部分页区后重试`,
);
}
const option = await waitForVisibleOption(TARGET_PAGE_SIZE, 2500, doc);
if (!option) {
doc.body.dispatchEvent(
new KeyboardEvent('keydown', { key: 'Escape', bubbles: true, cancelable: true }),
);
throw new Error(
`下拉已打开但未找到 ${TARGET_PAGE_SIZE} 选项,请确认分页支持该页大小`,
);
}
pointerClick(option);
const ok = await waitUntilPageSize(select, TARGET_PAGE_SIZE);
if (!ok) {
throw new Error(`切换每页 ${TARGET_PAGE_SIZE} 未生效,请手动切换后重试`);
}
await sleep(900);
return { changed: true, pageSize: TARGET_PAGE_SIZE };
}
@@ -0,0 +1,19 @@
import type { PddChannelShop } from '@/api/open/pddShop';
import { matchPddChannelShopByMallName } from '@/api/open/pddShop';
/**
* 用页面店铺名匹配 BI channelShop:后端按 mallName trim 后精确匹配。
*/
export async function matchChannelShopByMallName(
mallName: string,
): Promise<PddChannelShop | null> {
const name = mallName.trim();
if (!name) return null;
const shop = await matchPddChannelShopByMallName(name);
return shop ?? null;
}
export function shopAuthorizeHint(mallName: string): string {
const name = mallName.trim() || '当前店铺';
return `未在系统中找到与「${name}」完全同名的授权店铺,请先到 BI 系统完成该店铺授权后再试`;
}
@@ -0,0 +1,165 @@
import type { AdvertisingCostItem } from '@/types/advertisingCost';
import {
DATE_VALUE_RE,
FEE_COLUMN_LABEL,
GOODS_ID_RE,
PDD_SELECTORS,
} from './selectors';
export type PddDateMode = 'single' | 'range' | 'unknown';
export interface PddReportDateInfo {
mode: PddDateMode;
feeDate?: string;
beginDate?: string;
endDate?: string;
message?: string;
}
export function normalizePddDate(raw: string | null | undefined): string | undefined {
if (!raw) return undefined;
const cleaned = raw.trim().replace(/(.*?)|\(.*?\)/g, '').trim();
const match = cleaned.match(DATE_VALUE_RE);
if (!match) return undefined;
const [, y, m, d] = match;
return `${y}-${m!.padStart(2, '0')}-${d!.padStart(2, '0')}`;
}
export function parseAmount(raw: string | null | undefined): number | undefined {
if (raw == null) return undefined;
const text = raw.replace(/[,\s¥¥]/g, '').trim();
if (!text || text === '-' || text === '--') return undefined;
const value = Number(text);
return Number.isFinite(value) ? value : undefined;
}
export function readMallName(doc: Document = document): string | undefined {
const el = doc.querySelector(PDD_SELECTORS.mallName);
const text = el?.textContent?.trim();
return text || undefined;
}
/** 优先主 RangePicker 显示值(页面真实选中),URL 仅作回退。
* 勿只信 URL:history.pushState 改地址栏不会驱动 React 重拉数据。 */
export function readReportDate(doc: Document = document, href = location.href): PddReportDateInfo {
const fromPicker = readDateFromMainPicker(doc);
if (fromPicker) return fromPicker;
try {
const url = new URL(href);
const begin = normalizePddDate(url.searchParams.get('beginDate') ?? undefined);
const end = normalizePddDate(url.searchParams.get('endDate') ?? undefined);
if (begin && end) {
if (begin === end) {
return { mode: 'single', feeDate: begin, beginDate: begin, endDate: end };
}
return {
mode: 'range',
beginDate: begin,
endDate: end,
message: `当前为范围报表(${begin} ~ ${end}),仅单日查看时才记录`,
};
}
} catch {
// ignore invalid href
}
return { mode: 'unknown', message: '未能识别报表日期,请确认已打开商品推广总览且选择了日期' };
}
/** 读取 DateArea 主日期选择器(跳过对比日期) */
export function readDateFromMainPicker(doc: Document = document): PddReportDateInfo | null {
const pickers = Array.from(doc.querySelectorAll(PDD_SELECTORS.rangePicker));
for (const picker of pickers) {
if (picker.closest('[class*="CompareDate"]')) continue;
const inputs = Array.from(picker.querySelectorAll('input')).slice(0, 2);
if (inputs.length < 2) continue;
const begin = normalizePddDate(inputs[0]?.value);
const end = normalizePddDate(inputs[1]?.value);
if (!begin || !end) continue;
if (begin === end) {
return { mode: 'single', feeDate: begin, beginDate: begin, endDate: end };
}
return {
mode: 'range',
beginDate: begin,
endDate: end,
message: `当前为范围报表(${begin} ~ ${end}),仅单日查看时才记录`,
};
}
return null;
}
/**
* antd 横向滚动表会拆成「sticky 表头 table」+「表体 table」:
* 表头有「总花费」、无商品行;表体有商品行、无 thead。
* 因此列索引从表头取,行数据从含 goodsId 的 tr 取。
*/
function findFeeColumnIndex(root: ParentNode): number {
const headers = Array.from(root.querySelectorAll(PDD_SELECTORS.tableHeaderCell));
return headers.findIndex((th) => (th.textContent ?? '').includes(FEE_COLUMN_LABEL));
}
export function parsePromotionItems(
feeDate: string,
doc: Document = document,
): AdvertisingCostItem[] {
const wrap = doc.querySelector(PDD_SELECTORS.overviewTable) ?? doc;
const feeCol = findFeeColumnIndex(wrap);
if (feeCol < 0) {
throw new Error(`未找到「${FEE_COLUMN_LABEL}」列,请检查报表列配置是否包含总花费`);
}
const goodsNodes = Array.from(wrap.querySelectorAll(PDD_SELECTORS.goodsId));
if (goodsNodes.length === 0) {
throw new Error('未找到商品 ID,请确认推广商品表格已加载完成');
}
const items: AdvertisingCostItem[] = [];
const seen = new Set<string>();
for (const goodsEl of goodsNodes) {
const goodsText = goodsEl.textContent?.trim() ?? '';
const goodsMatch = goodsText.match(GOODS_ID_RE);
if (!goodsMatch) continue;
const goodsId = goodsMatch[1]!;
if (seen.has(goodsId)) continue;
const row = goodsEl.closest('tr');
if (!row) continue;
const cells = Array.from(row.querySelectorAll(':scope > td'));
const feeCell = cells[feeCol];
const feeAmount = parseAmount(feeCell?.textContent);
// 总花费为 0 / 空 不记录
if (feeAmount == null || feeAmount <= 0) continue;
seen.add(goodsId);
items.push({
feeDate,
goodsId,
feeAmount,
metadata: {
goodsName: row
.querySelector('[class*="OverviewTable_goodsName"]')
?.getAttribute('title')
?.replace(/^商品名:/, ''),
},
});
}
return items.sort((a, b) => Number(b.feeAmount) - Number(a.feeAmount));
}
export function isPddPromotionOverviewUrl(url: string): boolean {
try {
const u = new URL(url);
if (!u.hostname.includes('yingxiao.pinduoduo.com')) return false;
return u.pathname.includes('/report/promotion/overView') || u.pathname.includes('/goods/report/promotion');
} catch {
return false;
}
}
@@ -0,0 +1,23 @@
/** 拼多多推广报表 DOM 选择器(CSS Modules hash 会变,用前缀匹配) */
export const PDD_SELECTORS = {
mallName: '[class*="AccountNew_mallName"], [class*="AccountNew_titleName"]',
overviewTable: '[class*="OverviewTable_wrap"]',
goodsId: '[class*="OverviewTable_goodsId"]',
/** 主日期范围选择器(不含对比日期) */
rangePicker: '.anq-picker-range',
rangePickerInput: '.anq-picker-range .anq-picker-input input',
/** 表头可能在 sticky 独立 table 里,需在整个 OverviewTable_wrap 内查找 */
tableHeaderCell: 'thead th',
/** 分页「每页」 */
paginationWrap: '[class*="OverviewTable_paginationWrap"], .anq-pagination-wrapper',
perPageText: '.anq-perpage-text',
pageSizeSelect: '.anq-select',
pageSizeValue: '.anq-select-selection-item',
} as const;
/** 推广费列名:取「总花费(元)」 */
export const FEE_COLUMN_LABEL = '总花费';
export const GOODS_ID_RE = /商品\s*ID\s*[::]\s*(\d+)/i;
export const DATE_VALUE_RE = /^(\d{4})[/-](\d{1,2})[/-](\d{1,2})/;
@@ -0,0 +1,272 @@
import { normalizePddDate, readDateFromMainPicker, readReportDate } from './parseReport';
import { PDD_SELECTORS } from './selectors';
import { humanPauseMs, pointerClick, sleep } from './domInteract';
const MAX_WAIT_MS = 15_000;
function throwIfAborted(signal?: AbortSignal): void {
if (signal?.aborted) {
throw new DOMException('已取消自动切换日期', 'AbortError');
}
}
function findMainRangePicker(doc: Document = document): HTMLElement | null {
const pickers = Array.from(doc.querySelectorAll(PDD_SELECTORS.rangePicker));
for (const picker of pickers) {
if (picker.closest('[class*="CompareDate"]')) continue;
if (picker.closest('[class*="DateArea"]')) return picker as HTMLElement;
}
for (const picker of pickers) {
if (picker.closest('[class*="CompareDate"]')) continue;
return picker as HTMLElement;
}
return null;
}
function findVisiblePickerDropdown(doc: Document = document): HTMLElement | null {
const dropdowns = Array.from(
doc.querySelectorAll('.anq-picker-dropdown, [class*="picker-dropdown"]'),
);
for (const el of dropdowns) {
if (el.classList.contains('anq-picker-dropdown-hidden')) continue;
const style = window.getComputedStyle(el);
if (style.display === 'none' || style.visibility === 'hidden') continue;
if (style.pointerEvents === 'none') continue;
// 排除完全不可见
const rect = el.getBoundingClientRect();
if (rect.width < 2 || rect.height < 2) continue;
return el as HTMLElement;
}
return null;
}
function closePicker(doc: Document = document): void {
doc.body.dispatchEvent(
new KeyboardEvent('keydown', { key: 'Escape', bubbles: true, cancelable: true }),
);
}
async function openRangePicker(doc: Document, signal?: AbortSignal): Promise<HTMLElement> {
const picker = findMainRangePicker(doc);
if (!picker) throw new Error('未找到日期范围选择器');
// 先关掉残留面板,避免点到 hidden 节点
if (findVisiblePickerDropdown(doc)) {
closePicker(doc);
await sleep(180);
}
const triggers: HTMLElement[] = [];
const startInput = picker.querySelector(
'.anq-picker-input input, .anq-picker-input-active input',
) as HTMLElement | null;
const anyInput = picker.querySelector('input') as HTMLElement | null;
const suffix = picker.querySelector('.anq-picker-suffix') as HTMLElement | null;
if (startInput) triggers.push(startInput);
if (anyInput && anyInput !== startInput) triggers.push(anyInput);
if (suffix) triggers.push(suffix);
triggers.push(picker);
for (const trigger of triggers) {
throwIfAborted(signal);
pointerClick(trigger);
// 部分环境还吃原生 click
try {
trigger.click();
} catch {
// ignore
}
await sleep(humanPauseMs('afterUi'));
const started = Date.now();
while (Date.now() - started < 1800) {
throwIfAborted(signal);
const dropdown = findVisiblePickerDropdown(doc);
if (dropdown) return dropdown;
await sleep(80);
}
}
throw new Error('未能打开日期面板,请手动点开日期选择器后再试自动读取');
}
function titleCandidates(isoDate: string): string[] {
const [y, m, d] = isoDate.split('-');
if (!y || !m || !d) return [isoDate];
return [
isoDate,
`${y}/${m}/${d}`,
`${y}/${Number(m)}/${Number(d)}`,
`${y}-${Number(m)}-${Number(d)}`,
];
}
function findDateCell(dropdown: HTMLElement, isoDate: string): HTMLElement | null {
for (const title of titleCandidates(isoDate)) {
const cells = Array.from(
dropdown.querySelectorAll(`.anq-picker-cell[title="${title}"], td[title="${title}"]`),
) as HTMLElement[];
const preferred =
cells.find(
(el) =>
el.classList.contains('anq-picker-cell-in-view') &&
!el.classList.contains('anq-picker-cell-disabled'),
) ??
cells.find((el) => !el.classList.contains('anq-picker-cell-disabled')) ??
null;
if (preferred) {
return (
(preferred.querySelector('.anq-picker-cell-inner') as HTMLElement | null) ?? preferred
);
}
}
return null;
}
function parseHeaderYearMonth(dropdown: HTMLElement): { y: number; m: number } | null {
const headers = Array.from(
dropdown.querySelectorAll('.anq-picker-header-view, [class*="picker-header-view"]'),
);
// Range 常左右两个月面板,取第一个可见头
for (const header of headers) {
const text = (header.textContent || '').replace(/\s+/g, '');
let m = text.match(/(\d{4})\s*年\s*(\d{1,2})\s*月/);
if (m) return { y: Number(m[1]), m: Number(m[2]) };
m = text.match(/(\d{4})[/.-](\d{1,2})/);
if (m) return { y: Number(m[1]), m: Number(m[2]) };
}
return null;
}
async function navigateToMonth(
dropdown: HTMLElement,
isoDate: string,
signal?: AbortSignal,
): Promise<void> {
const [ys, ms] = isoDate.split('-');
const targetY = Number(ys);
const targetM = Number(ms);
if (!targetY || !targetM) throw new Error(`非法日期:${isoDate}`);
for (let i = 0; i < 36; i++) {
throwIfAborted(signal);
if (findDateCell(dropdown, isoDate)) return;
const current = parseHeaderYearMonth(dropdown);
if (!current) break;
const curIdx = current.y * 12 + current.m;
const tgtIdx = targetY * 12 + targetM;
if (curIdx === tgtIdx) {
// 头已对齐但仍找不到 cell — 可能 title 格式不同
break;
}
const wantNext = curIdx < tgtIdx;
const buttons = Array.from(
dropdown.querySelectorAll(
wantNext
? '.anq-picker-header-next-btn'
: '.anq-picker-header-prev-btn',
),
) as HTMLElement[];
// 双月面板时点左侧(第一个)的 prev/next
const btn = buttons[0];
if (!btn) break;
pointerClick(btn);
await sleep(humanPauseMs('afterUi'));
}
if (!findDateCell(dropdown, isoDate)) {
throw new Error(`日期面板中找不到 ${isoDate},请确认未超出可选范围`);
}
}
/** 以选择器输入值为准,确认已切到目标单日(不认仅改 URL) */
async function waitUntilPickerSingleDay(
isoDate: string,
signal?: AbortSignal,
): Promise<void> {
const started = Date.now();
while (Date.now() - started < MAX_WAIT_MS) {
throwIfAborted(signal);
const picker = readDateFromMainPicker();
if (picker?.mode === 'single' && picker.feeDate === isoDate) return;
await sleep(200);
}
const picker = readDateFromMainPicker();
const fallback = readReportDate();
throw new Error(
`切换到 ${isoDate} 超时(选择器:${picker?.mode ?? '无'} ${picker?.feeDate ?? picker?.beginDate ?? '?'};页面:${fallback.feeDate ?? '?'})`,
);
}
async function clickCellTwiceForSingleDay(
dropdown: HTMLElement,
isoDate: string,
doc: Document,
signal?: AbortSignal,
): Promise<void> {
const cell = findDateCell(dropdown, isoDate);
if (!cell) throw new Error(`未找到日期单元格 ${isoDate}`);
// RangePicker:起、止各点同一天
pointerClick(cell);
try {
cell.click();
} catch {
// ignore
}
await sleep(humanPauseMs('afterUi'));
throwIfAborted(signal);
const dropdown2 = findVisiblePickerDropdown(doc);
if (dropdown2) {
const cell2 = findDateCell(dropdown2, isoDate);
if (cell2) {
pointerClick(cell2);
try {
cell2.click();
} catch {
// ignore
}
await sleep(humanPauseMs('afterUi'));
}
}
}
/**
* 将推广总览切到指定单日。
* 只通过 DateArea RangePicker 拟人点击;禁止 pushState 假切换。
*/
export async function switchToSingleDay(
isoDate: string,
options: { signal?: AbortSignal; doc?: Document } = {},
): Promise<void> {
const date = normalizePddDate(isoDate) ?? isoDate;
if (!/^\d{4}-\d{2}-\d{2}$/.test(date)) {
throw new Error(`日期格式无效:${isoDate}`);
}
const { signal, doc = document } = options;
throwIfAborted(signal);
const current = readDateFromMainPicker(doc) ?? readReportDate(doc);
if (current.mode === 'single' && current.feeDate === date) {
return;
}
const dropdown = await openRangePicker(doc, signal);
await navigateToMonth(dropdown, date, signal);
await clickCellTwiceForSingleDay(dropdown, date, doc, signal);
// 若面板仍开着,再 Esc(有的版本选完自动关)
if (findVisiblePickerDropdown(doc)) {
closePicker(doc);
await sleep(200);
}
await waitUntilPickerSingleDay(date, signal);
// 等报表按新日期拉数
await sleep(humanPauseMs('afterNav'));
}
+258
View File
@@ -0,0 +1,258 @@
<script setup lang="ts">
import { computed, onMounted, ref } from 'vue';
import {
downloadAndVerifyFeature,
fetchFeatureManifest,
} from '@/api/open/extensionFeatures';
import type { ExtensionFeatureItem } from '@/features/runtime/types';
import { urlMatchesPatterns } from '@/features/runtime/types';
import { EXTENSION_NAME } from '@/shared/constants';
import { toUserMessage } from '@/shared/errors';
import { getSettings, saveSettings } from '@/storage/settings';
import {
getFloatingPanelState,
mountFeatureOnPage,
unmountFeatureOnPage,
} from './messaging';
const apiBaseUrl = ref('');
const apiKey = ref('');
const features = ref<ExtensionFeatureItem[]>([]);
const featuresLoading = ref(false);
const featuresUpdatedAt = ref('');
const activeFeatureId = ref<string | null>(null);
const currentTabUrl = ref('');
const statusText = ref('');
const errorText = ref('');
const busy = ref(false);
const checking = ref(false);
const configOpen = ref(false);
const hasConfig = computed(() => Boolean(apiBaseUrl.value.trim() && apiKey.value.trim()));
const matchedFeatures = computed(() => {
const list = Array.isArray(features.value) ? features.value : [];
if (!currentTabUrl.value) return list;
return list.filter((f) => urlMatchesPatterns(currentTabUrl.value, f?.matchUrlPatterns ?? []));
});
const configSummary = computed(() => {
if (!hasConfig.value) return '未配置';
try {
const host = new URL(apiBaseUrl.value.trim()).host;
return host || '已配置';
} catch {
return '已配置';
}
});
async function loadLocalSettings() {
const settings = await getSettings();
apiBaseUrl.value = settings.apiBaseUrl;
apiKey.value = settings.apiKey;
// 未配置时默认展开
configOpen.value = !(settings.apiBaseUrl && settings.apiKey);
}
async function saveConfig() {
await saveSettings({
apiBaseUrl: apiBaseUrl.value.trim(),
apiKey: apiKey.value.trim(),
});
}
async function persistAndCheck() {
checking.value = true;
errorText.value = '';
statusText.value = '';
try {
await saveConfig();
const manifest = await fetchFeatureManifest();
features.value = manifest.features ?? [];
featuresUpdatedAt.value = manifest.updatedAt ?? '';
const count = features.value.length;
statusText.value = `已连接 · 清单 ${count} 项`;
configOpen.value = false;
} catch (error) {
errorText.value = toUserMessage(error);
configOpen.value = true;
} finally {
checking.value = false;
}
}
async function refreshTabUrl() {
try {
const tabs = await chrome.tabs.query({ active: true, currentWindow: true });
currentTabUrl.value = tabs[0]?.url ?? '';
} catch {
currentTabUrl.value = '';
}
}
async function loadFeatures() {
featuresLoading.value = true;
errorText.value = '';
try {
await saveConfig();
const manifest = await fetchFeatureManifest();
features.value = manifest.features ?? [];
featuresUpdatedAt.value = manifest.updatedAt ?? '';
statusText.value = `清单已刷新(${features.value.length})`;
} catch (error) {
errorText.value = toUserMessage(error);
configOpen.value = true;
} finally {
featuresLoading.value = false;
}
}
async function refreshPanelState() {
try {
const state = await getFloatingPanelState();
activeFeatureId.value = state.visible ? 'pdd-ad-fee' : null;
} catch {
activeFeatureId.value = null;
}
}
async function handleOpenFeature(item: ExtensionFeatureItem) {
busy.value = true;
errorText.value = '';
statusText.value = '';
try {
await saveConfig();
const remote = await downloadAndVerifyFeature(item);
await mountFeatureOnPage(item.id, remote.code);
activeFeatureId.value = item.id;
statusText.value = `已打开 ${item.name}`;
} catch (error) {
errorText.value = toUserMessage(error);
} finally {
busy.value = false;
}
}
async function handleCloseFeature() {
busy.value = true;
errorText.value = '';
try {
await unmountFeatureOnPage();
activeFeatureId.value = null;
statusText.value = '已关闭';
} catch (error) {
errorText.value = toUserMessage(error);
} finally {
busy.value = false;
}
}
onMounted(async () => {
await loadLocalSettings();
await refreshTabUrl();
await refreshPanelState();
if (hasConfig.value) {
await loadFeatures();
}
});
</script>
<template>
<div class="popup-root">
<header class="popup-header">
<div class="min-w-0 flex-1">
<h1>{{ EXTENSION_NAME }}</h1>
<p class="popup-sub">{{ configSummary }}</p>
</div>
<button
class="popup-link"
type="button"
:disabled="busy || checking"
@click="configOpen = !configOpen"
>
{{ configOpen ? '收起配置' : '配置' }}
</button>
</header>
<section v-show="configOpen" class="popup-card space-y-2">
<label class="popup-label">
Base URL
<input
v-model="apiBaseUrl"
class="popup-input"
placeholder="https://host/api"
autocomplete="off"
/>
</label>
<label class="popup-label">
API Key
<input
v-model="apiKey"
class="popup-input"
type="password"
placeholder="sk_live_..."
autocomplete="off"
/>
</label>
<button
class="popup-btn popup-btn-primary w-full"
type="button"
:disabled="busy || checking || !apiBaseUrl.trim() || !apiKey.trim()"
@click="persistAndCheck"
>
{{ checking ? '连接中…' : '保存并连接' }}
</button>
</section>
<section class="popup-card space-y-2">
<div class="flex items-center justify-between gap-2">
<h2 class="popup-section-title">功能</h2>
<button
class="popup-link"
type="button"
:disabled="featuresLoading || busy || checking || !hasConfig"
:title="featuresUpdatedAt ? `更新于 ${featuresUpdatedAt}` : ''"
@click="loadFeatures"
>
{{ featuresLoading ? '…' : '刷新' }}
</button>
</div>
<p v-if="!hasConfig" class="popup-hint">先填写上方连接配置</p>
<p v-else-if="!matchedFeatures.length && !featuresLoading" class="popup-hint">
{{ features.length ? '当前页无匹配功能,请打开对应后台页' : '暂无清单,点「刷新」或「保存并连接」' }}
</p>
<div v-for="item in matchedFeatures" :key="item.id" class="popup-feature">
<div class="min-w-0 flex-1">
<div class="truncate text-sm font-medium text-antd-text">{{ item.name }}</div>
<div class="text-[11px] text-antd-text-tertiary">v{{ item.version }}</div>
</div>
<div class="flex shrink-0 gap-1.5">
<button
v-if="activeFeatureId === item.id"
class="popup-btn popup-btn-ghost"
type="button"
:disabled="busy || checking"
@click="handleCloseFeature"
>
关闭
</button>
<button
class="popup-btn popup-btn-primary"
type="button"
:disabled="busy || checking"
@click="handleOpenFeature(item)"
>
{{ activeFeatureId === item.id ? '重新打开' : '打开' }}
</button>
</div>
</div>
</section>
<p v-if="statusText" class="popup-status">{{ statusText }}</p>
<p v-if="errorText" class="popup-error">{{ errorText }}</p>
</div>
</template>
@@ -0,0 +1,12 @@
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>ECBI 数据同步</title>
</head>
<body class="bg-slate-50 text-slate-900">
<div id="app"></div>
<script type="module" src="./main.ts"></script>
</body>
</html>
+6
View File
@@ -0,0 +1,6 @@
import { createApp } from 'vue';
import App from './App.vue';
import './styles.css';
createApp(App).mount('#app');
@@ -0,0 +1,64 @@
import type { ExtensionMessage, ExtensionResponse } from '@/shared/messages';
import { ExtensionError } from '@/shared/errors';
async function getActiveTabId(): Promise<number> {
const tabs = await chrome.tabs.query({ active: true, currentWindow: true });
const tabId = tabs[0]?.id;
if (tabId == null) {
throw new ExtensionError('NO_ACTIVE_TAB', '未找到当前标签页');
}
return tabId;
}
async function sendToActiveTab<T>(message: ExtensionMessage): Promise<T> {
const tabId = await getActiveTabId();
let response: ExtensionResponse | undefined;
try {
response = (await chrome.tabs.sendMessage(tabId, message)) as ExtensionResponse;
} catch {
throw new ExtensionError(
'PAGE_NOT_READY',
'无法连接页面脚本。请刷新目标页面后再打开功能。',
);
}
if (!response) {
throw new ExtensionError('PAGE_NOT_READY', '页面无响应');
}
if (!response.ok) {
throw new ExtensionError(
(response.code as never) || 'UNKNOWN',
response.message || '页面处理失败',
);
}
return response.data as T;
}
export async function openFloatingPanel(): Promise<{ visible: boolean }> {
return sendToActiveTab<{ visible: boolean }>({
type: 'SET_FLOATING_PANEL',
payload: { visible: true },
});
}
export async function toggleFloatingPanel(): Promise<{ visible: boolean }> {
return sendToActiveTab<{ visible: boolean }>({ type: 'TOGGLE_FLOATING_PANEL' });
}
export async function getFloatingPanelState(): Promise<{ visible: boolean }> {
return sendToActiveTab<{ visible: boolean }>({ type: 'GET_FLOATING_PANEL_STATE' });
}
export async function mountFeatureOnPage(
featureId: string,
code: string,
): Promise<{ featureId: string | null }> {
return sendToActiveTab<{ featureId: string | null }>({
type: 'MOUNT_FEATURE',
payload: { featureId, code },
});
}
export async function unmountFeatureOnPage(): Promise<{ featureId: string | null }> {
return sendToActiveTab<{ featureId: string | null }>({ type: 'UNMOUNT_FEATURE' });
}
+265
View File
@@ -0,0 +1,265 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
html,
body {
margin: 0;
min-width: 320px;
color: rgba(0, 0, 0, 0.88);
background: #f5f5f5;
font-family:
-apple-system,
BlinkMacSystemFont,
'Segoe UI',
Roboto,
'Helvetica Neue',
Arial,
'Noto Sans',
sans-serif;
scrollbar-width: thin;
scrollbar-color: rgb(0 0 0 / 0.28) transparent;
}
html::-webkit-scrollbar,
body::-webkit-scrollbar,
.popup-root::-webkit-scrollbar {
width: 6px;
height: 6px;
}
html::-webkit-scrollbar-thumb,
body::-webkit-scrollbar-thumb,
.popup-root::-webkit-scrollbar-thumb {
background: rgb(0 0 0 / 0.28);
border-radius: 3px;
}
.popup-root {
box-sizing: border-box;
width: 320px;
display: flex;
flex-direction: column;
gap: 10px;
padding: 12px;
background: #f5f5f5;
color: rgba(0, 0, 0, 0.88);
}
.popup-header {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 8px;
padding: 2px 2px 0;
}
.popup-header h1 {
margin: 0;
font-size: 15px;
font-weight: 600;
line-height: 1.3;
}
.popup-sub {
margin: 2px 0 0;
font-size: 12px;
color: rgba(0, 0, 0, 0.45);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
max-width: 220px;
}
.popup-card {
border: 1px solid #f0f0f0;
border-radius: 12px;
background: #fff;
padding: 12px;
box-shadow: 0 1px 2px rgb(0 0 0 / 0.03);
}
.popup-section-title {
margin: 0;
font-size: 12px;
font-weight: 600;
color: rgba(0, 0, 0, 0.45);
}
.popup-label {
display: block;
font-size: 12px;
color: rgba(0, 0, 0, 0.45);
}
.popup-input {
box-sizing: border-box;
display: block;
width: 100%;
margin-top: 4px;
border: 1px solid #d9d9d9;
border-radius: 8px;
padding: 6px 10px;
font-size: 13px;
outline: none;
background: #fff;
color: rgba(0, 0, 0, 0.88);
}
.popup-input:focus {
border-color: #1677ff;
box-shadow: 0 0 0 2px rgb(22 119 255 / 0.2);
}
.popup-btn {
border-radius: 8px;
border: 1px solid #d9d9d9;
background: #fff;
color: rgba(0, 0, 0, 0.88);
padding: 5px 10px;
font-size: 12px;
line-height: 1.4;
cursor: pointer;
transition:
color 0.15s,
border-color 0.15s,
background 0.15s;
}
.popup-btn:disabled {
opacity: 0.45;
cursor: not-allowed;
}
.popup-btn-primary {
border-color: #1677ff;
background: #1677ff;
color: #fff;
}
.popup-btn-primary:hover:not(:disabled) {
border-color: #4096ff;
background: #4096ff;
}
.popup-btn-ghost:hover:not(:disabled) {
color: #1677ff;
border-color: #1677ff;
}
.popup-link {
border: 0;
background: transparent;
color: #1677ff;
font-size: 12px;
padding: 0;
cursor: pointer;
white-space: nowrap;
}
.popup-link:hover:not(:disabled) {
text-decoration: underline;
}
.popup-link:disabled {
opacity: 0.45;
cursor: not-allowed;
}
.popup-feature {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
border: 1px solid #f0f0f0;
border-radius: 8px;
background: #fafafa;
padding: 8px 10px;
}
.popup-hint {
margin: 0;
font-size: 12px;
color: rgba(0, 0, 0, 0.25);
line-height: 1.4;
}
.popup-status {
margin: 0;
font-size: 12px;
color: #52c41a;
line-height: 1.4;
}
.popup-error {
margin: 0;
font-size: 12px;
color: #ff4d4f;
line-height: 1.4;
}
.w-full {
width: 100%;
}
.space-y-2 > * + * {
margin-top: 8px;
}
.flex {
display: flex;
}
.items-center {
align-items: center;
}
.justify-between {
justify-content: space-between;
}
.gap-1\.5 {
gap: 6px;
}
.gap-2 {
gap: 8px;
}
.min-w-0 {
min-width: 0;
}
.flex-1 {
flex: 1;
}
.shrink-0 {
flex-shrink: 0;
}
.truncate {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.text-sm {
font-size: 13px;
}
.font-medium {
font-weight: 500;
}
.text-antd-text {
color: rgba(0, 0, 0, 0.88);
}
.text-antd-text-tertiary {
color: rgba(0, 0, 0, 0.25);
}
.text-\[11px\] {
font-size: 11px;
}
@@ -0,0 +1,16 @@
export const EXTENSION_NAME = 'ECBI 数据同步';
export const OPEN_API_PATHS = {
pddShopList: '/open/v1/channel/pdd/shop/list',
pddShopMatchByName: '/open/v1/channel/pdd/shop/match-by-name',
pddGoodsAdFeeBatchImport: '/open/v1/channel/pdd/goods/adfee/batch-import',
pddGoodsAdFeeImportTask: '/open/v1/channel/pdd/goods/adfee/import-task',
extensionFeatureList: '/open/v1/extension/features',
extensionFeatureScript: '/open/v1/extension/features',
} as const;
export const OPEN_SCOPES = {
pddShopRead: 'openapi:shop:pdd:read',
pddGoodsAdFeeImport: 'openapi:product:adfee',
extensionFeatureRead: 'openapi:extension:feature:read',
} as const;
@@ -0,0 +1,136 @@
import type { AdvertisingCostItem } from '@/types/advertisingCost';
export type HeatLevel = 0 | 1 | 2 | 3 | 4;
export interface DayStat {
date: string;
itemCount: number;
feeTotal: number;
level: HeatLevel;
}
export interface HeatDayCell {
date: string;
inRange: boolean;
isToday: boolean;
isPageDate: boolean;
stat: DayStat | null;
level: HeatLevel;
}
function toDateKey(d: Date): string {
const y = d.getFullYear();
const m = String(d.getMonth() + 1).padStart(2, '0');
const day = String(d.getDate()).padStart(2, '0');
return `${y}-${m}-${day}`;
}
function startOfDay(d: Date): Date {
return new Date(d.getFullYear(), d.getMonth(), d.getDate());
}
function addDays(d: Date, n: number): Date {
const next = new Date(d);
next.setDate(next.getDate() + n);
return next;
}
/** 按花费分档:0 无数据,1~4 由浅到深 */
export function feeToLevel(feeTotal: number, maxFee: number): HeatLevel {
if (feeTotal <= 0 || maxFee <= 0) return 0;
const ratio = feeTotal / maxFee;
if (ratio <= 0.25) return 1;
if (ratio <= 0.5) return 2;
if (ratio <= 0.75) return 3;
return 4;
}
export function summarizeByDate(items: AdvertisingCostItem[]): Map<string, DayStat> {
const map = new Map<string, { itemCount: number; feeTotal: number }>();
for (const item of items) {
const prev = map.get(item.feeDate) ?? { itemCount: 0, feeTotal: 0 };
prev.itemCount += 1;
prev.feeTotal += Number(item.feeAmount) || 0;
map.set(item.feeDate, prev);
}
let maxFee = 0;
for (const value of map.values()) {
maxFee = Math.max(maxFee, value.feeTotal);
}
const result = new Map<string, DayStat>();
for (const [date, value] of map) {
result.set(date, {
date,
itemCount: value.itemCount,
feeTotal: value.feeTotal,
level: feeToLevel(value.feeTotal, maxFee),
});
}
return result;
}
/**
* GitHub 贡献图布局:列=周(旧→新),行=周日…周六。
* weeks 默认 13(约一季,适合窄面板)。
*/
export function buildHeatmapWeeks(options: {
weeks?: number;
endDate?: Date;
stats: Map<string, DayStat>;
pageDate?: string;
}): HeatDayCell[][] {
const weeks = options.weeks ?? 13;
const end = startOfDay(options.endDate ?? new Date());
const todayKey = toDateKey(end);
// 对齐到本周周六(与 GitHub 行末一致:日一二三四五六)
const endWeekday = end.getDay(); // 0=Sun
const gridEnd = addDays(end, 6 - endWeekday);
const totalDays = weeks * 7;
const gridStart = addDays(gridEnd, -(totalDays - 1));
const columns: HeatDayCell[][] = [];
for (let w = 0; w < weeks; w++) {
const col: HeatDayCell[] = [];
for (let dow = 0; dow < 7; dow++) {
const date = addDays(gridStart, w * 7 + dow);
const key = toDateKey(date);
const inRange = date.getTime() <= end.getTime();
const stat = options.stats.get(key) ?? null;
col.push({
date: key,
inRange,
isToday: key === todayKey,
isPageDate: Boolean(options.pageDate && key === options.pageDate),
stat,
level: inRange ? (stat?.level ?? 0) : 0,
});
}
columns.push(col);
}
return columns;
}
export function monthLabelsForWeeks(weeks: HeatDayCell[][]): Array<{ index: number; label: string }> {
const labels: Array<{ index: number; label: string }> = [];
let lastMonth = -1;
for (let i = 0; i < weeks.length; i++) {
const first = weeks[i]?.[0];
if (!first) continue;
const month = Number(first.date.slice(5, 7));
if (month !== lastMonth) {
labels.push({ index: i, label: `${month}月` });
lastMonth = month;
}
}
return labels;
}
export function cellTitle(cell: HeatDayCell): string {
if (!cell.inRange) return cell.date;
if (!cell.stat) {
return cell.isPageDate ? `${cell.date} · 当前页面日期(未读取)` : `${cell.date} · 未读取`;
}
return `${cell.date} · ${cell.stat.itemCount} 条 · ¥${cell.stat.feeTotal.toFixed(2)}`;
}
@@ -0,0 +1,32 @@
export type ExtensionErrorCode =
| 'PLATFORM_NOT_SUPPORTED'
| 'PAGE_NOT_READY'
| 'DATA_PARSE_FAILED'
| 'INVALID_DATA'
| 'AUTH_FAILED'
| 'API_REQUEST_FAILED'
| 'API_BUSINESS_ERROR'
| 'NETWORK_ERROR'
| 'CONFIG_MISSING'
| 'NO_ACTIVE_TAB'
| 'UNKNOWN';
export class ExtensionError extends Error {
readonly code: ExtensionErrorCode;
constructor(code: ExtensionErrorCode, message: string) {
super(message);
this.name = 'ExtensionError';
this.code = code;
}
}
export function toUserMessage(error: unknown): string {
if (error instanceof ExtensionError) {
return error.message;
}
if (error instanceof Error && error.message) {
return error.message;
}
return '发生未知错误,请稍后重试';
}
@@ -0,0 +1,36 @@
import type { AdvertisingCostItem } from '@/types/advertisingCost';
function itemKey(item: AdvertisingCostItem): string {
return `${item.feeDate}::${item.goodsId}`;
}
function compareByAmountDesc(a: AdvertisingCostItem, b: AdvertisingCostItem): number {
const byAmount = Number(b.feeAmount) - Number(a.feeAmount);
if (byAmount !== 0) return byAmount;
const byDate = b.feeDate.localeCompare(a.feeDate);
if (byDate !== 0) return byDate;
return a.goodsId.localeCompare(b.goodsId);
}
/**
* 合并多次单日读取:按 (feeDate, goodsId) upsert。
* 换日再读保留已有日期;同日再读覆盖该日同商品。
* 合并后按金额降序。
*/
export function mergeAdvertisingItems(
previous: AdvertisingCostItem[],
incoming: AdvertisingCostItem[],
): AdvertisingCostItem[] {
const map = new Map<string, AdvertisingCostItem>();
for (const item of previous) {
map.set(itemKey(item), item);
}
for (const item of incoming) {
map.set(itemKey(item), item);
}
return Array.from(map.values()).sort(compareByAmountDesc);
}
export function listFeeDates(items: AdvertisingCostItem[]): string[] {
return [...new Set(items.map((item) => item.feeDate))].sort();
}
@@ -0,0 +1,40 @@
import type { AdvertisingCostBatch, PageContext } from '@/types/advertisingCost';
import type { ExtensionFeatureManifest } from '@/features/runtime/types';
export type ExtensionMessage =
| { type: 'GET_PAGE_CONTEXT' }
| { type: 'PARSE_ADVERTISING_COST' }
| { type: 'TOGGLE_FLOATING_PANEL' }
| { type: 'SET_FLOATING_PANEL'; payload: { visible: boolean } }
| { type: 'GET_FLOATING_PANEL_STATE' }
| { type: 'MOUNT_FEATURE'; payload: { featureId: string; code: string } }
| { type: 'UNMOUNT_FEATURE' }
| { type: 'GET_ACTIVE_FEATURE' }
| { type: 'PING' };
export type ExtensionResponse =
| { ok: true; data: PageContext }
| { ok: true; data: AdvertisingCostBatch }
| { ok: true; data: { pong: true } }
| { ok: true; data: { visible: boolean } }
| { ok: true; data: { featureId: string | null } }
| { ok: true; data: ExtensionFeatureManifest }
| { ok: false; code: string; message: string };
const MESSAGE_TYPES = new Set([
'GET_PAGE_CONTEXT',
'PARSE_ADVERTISING_COST',
'TOGGLE_FLOATING_PANEL',
'SET_FLOATING_PANEL',
'GET_FLOATING_PANEL_STATE',
'MOUNT_FEATURE',
'UNMOUNT_FEATURE',
'GET_ACTIVE_FEATURE',
'PING',
]);
export function isExtensionMessage(value: unknown): value is ExtensionMessage {
if (!value || typeof value !== 'object') return false;
const type = (value as { type?: unknown }).type;
return typeof type === 'string' && MESSAGE_TYPES.has(type);
}
@@ -0,0 +1,60 @@
export interface ExtensionSettings {
/** 例:https://host/api (不要末尾斜杠) */
apiBaseUrl: string;
/** Open API Key(非 JWT) */
apiKey: string;
/** 记住的渠道店铺 */
channelShopId?: number;
channelShopName?: string;
}
const STORAGE_KEY = 'ecbi.extension.settings';
const DEFAULT_SETTINGS: ExtensionSettings = {
apiBaseUrl: '',
apiKey: '',
};
export type SettingsOverride = {
get: () => Promise<ExtensionSettings>;
save: (patch: Partial<ExtensionSettings>) => Promise<ExtensionSettings>;
};
let settingsOverride: SettingsOverride | null = null;
/** 功能包在 main world 安装桥接实现时调用 */
export function setSettingsOverride(override: SettingsOverride | null): void {
settingsOverride = override;
}
export async function getSettings(): Promise<ExtensionSettings> {
if (settingsOverride) {
return settingsOverride.get();
}
const result = await chrome.storage.local.get(STORAGE_KEY);
const raw = result[STORAGE_KEY] as Partial<ExtensionSettings> | undefined;
return {
...DEFAULT_SETTINGS,
...raw,
apiBaseUrl: (raw?.apiBaseUrl ?? '').replace(/\/+$/, ''),
apiKey: raw?.apiKey ?? '',
};
}
export async function saveSettings(
patch: Partial<ExtensionSettings>,
): Promise<ExtensionSettings> {
if (settingsOverride) {
return settingsOverride.save(patch);
}
const current = await getSettings();
const next: ExtensionSettings = {
...current,
...patch,
apiBaseUrl: (patch.apiBaseUrl ?? current.apiBaseUrl).replace(/\/+$/, ''),
};
await chrome.storage.local.set({ [STORAGE_KEY]: next });
return next;
}
@@ -0,0 +1 @@
export type { ExtensionSettings } from './settings';
@@ -0,0 +1,39 @@
/** 插件侧统一广告费模型(平台无关) */
export type PlatformType = 'pdd' | 'taobao' | 'jd' | 'mock' | 'unknown';
/** 单条推广费:日期来自页面数据本身,不由用户手选 */
export interface AdvertisingCostItem {
/** 统计日期 YYYY-MM-DD(每条各自一份) */
feeDate: string;
goodsId: string;
feeAmount: number;
metadata?: Record<string, unknown>;
}
/**
* 一次读取/同步批次。
* channelShopId = BI channel_pdd_shop.id(不是 mallId)
* 日期在 items[].feeDate,由 Adapter 从页面解析
*/
export interface AdvertisingCostBatch {
platform: PlatformType;
channelShopId: number;
items: AdvertisingCostItem[];
source: 'browser-extension';
importedAt: string;
}
export interface PageContext {
url: string;
title: string;
platform: PlatformType;
ready: boolean;
message?: string;
/** 页面展示的店铺名(用于匹配 BI channelShop) */
mallName?: string;
/** 单日模式下的统计日期 YYYY-MM-DD */
feeDate?: string;
/** single=可同步;range=范围报表不记录 */
dateMode?: 'single' | 'range' | 'unknown';
}
+34
View File
@@ -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: [],
};
+26
View File
@@ -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"]
}
+12
View File
@@ -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"]
}
+27
View File
@@ -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,
},
});
+23
View File
@@ -0,0 +1,23 @@
# 依赖(pnpm workspace 根目录 + 子包软链)
node_modules/
# 构建产物
dist/
*.tsbuildinfo
# 环境变量与密钥(勿提交)
.env
.env.*
!.env.example
server/keys/*.pem
# 日志
logs/
*.log
pnpm-debug.log*
# 系统/编辑器
.DS_Store
.idea/
.vscode/
*.swp
+2
View File
@@ -0,0 +1,2 @@
# 允许 bcrypt 等原生依赖执行 install 脚本
enable-pre-post-scripts=true
+434
View File
@@ -0,0 +1,434 @@
我看完你这份**Ed25519 版 License 设计**了,这一版已经明显比你上一版(JWT + RSA)更专业,基本已经进入“可商用架构”层级了。
我还是按**架构评审的方式**给你拆:
👉 不讲表面优化,只讲**会影响你后期成本 / 安全 / 可维护性**的点
---
# ✅ 一、整体评价(先给结论)
> ✅ 架构成熟度:**85分(可以上线)**
> ⚠️ 差的这 15 分:主要在 **抗破解能力 + 生命周期控制 + 可扩展性**
---
# ✅ 二、这版比上一版“质变”的地方(做对的)
### ✔ 1. 从 RSA → Ed25519(这是关键升级)
👉 这个决策是对的
* 签名更小
* 性能更好
* 无 padding 坑
* 更适合 License 这种高频校验场景
👉 这一点已经是“架构升级”,不是优化
---
### ✔ 2. 去掉 JWT,改自定义结构
你现在:
```json
{
"payload": "...",
"signature": "..."
}
```
👉 这是正确方向:
* 去掉 JWT 历史坑(alg / 解析差异)
* 结构完全可控
* 更适合 License 场景
---
### ✔ 3. 引入 AES 加密(GCM)
👉 很加分的一点
你已经做到:
> “不仅不能改,还看不懂”
这已经是:
```text
签名(防篡改) + 加密(防分析)
```
👉 商业软件常规做法
---
### ✔ 4. LicenseManager 分层设计(非常好)
```text
LicenseManager
├── load
├── verify
├── decrypt
├── cache
```
👉 说明你已经在做:
* 生命周期管理
* 统一入口
👉 这是“工程能力”的体现
---
# ⚠️ 三、关键问题(这一版的“隐患点”)
下面这些才是你现在**真正需要改的**
---
# ❗问题1:AES Key 放在客户端 = “伪加密”
你现在:
> AES key 内置在服务端代码
---
## ⚠️ 本质问题
```text
攻击者 = 有代码
→ 就有 key
→ 就能解密
```
👉 所以:
> ❗这只是“增加难度”,不是安全
---
## ✅ 改进建议(分级)
### ✔ 低成本优化(推荐你现在做)
```text
key = hash(machineId + salt)
```
👉 每台机器不同
---
### ✔ 中级方案
```text
key = 服务端激活时下发
```
👉 不写死
---
### ✔ 高级方案(企业级)
```text
key = 动态生成 + 混淆 + 分段存储
```
---
# ❗问题2:你“只在初始化时验签”(不够)
你现在:
> init 时验证 → 后续只用缓存
---
## ⚠️ 风险
攻击者可以:
* hook verify 方法
* patch init 逻辑
* 修改内存对象
👉 然后:
> 永远有效
---
## ✅ 正确做法(必须改)
👉 增加:
```text
1. 定时重新验签(例如 5~10 分钟)
2. 关键操作前轻量校验
```
---
# ❗问题3:功能校验点太少(严重)
你现在:
> 只在“订单导入接口”校验
---
## ⚠️ 问题
攻击者可以:
* 直接绕 controller
* 或改调用路径
---
## ✅ 正确做法
👉 必须:
```text
License → Feature Gate → Service 层
```
例如:
```java
if (!license.hasFeature("order-import")) {
throw new ForbiddenException();
}
```
👉 不要只放在 controller
---
# ❗问题4:机器指纹还是“硬绑定”(老问题)
你现在:
```text
cpu + mac + disk → hash
```
---
## ⚠️ 现实问题
* 云服务器 → 会变
* docker → 会变
* 虚拟机 → 不稳定
👉 结果:
> ❗客户频繁失效
---
## ✅ 建议(你这一版必须改)
👉 改为:
```text
machineId = 安装时生成 UUID
```
再:
```text
fingerprint = hash(uuid + 部分硬件信息)
```
---
# ❗问题5:没有 License 吊销机制(依然缺)
你现在:
> 完全离线
---
## ⚠️ 风险
* 客户退款
* License 泄露
* 被破解传播
👉 你无法控制
---
## ✅ 必须补
```json
{
"jti": "license-id"
}
```
👉 + 可选:
```text
定期请求 License Server 校验
```
---
# ❗问题6:没有“抗复制机制”
现在可以:
```text
复制:
- DB
- license 文件
```
👉 到另一台机器
---
## ⚠️ 如果指纹被绕:
> 完全成功
---
## ✅ 建议
增加:
* installId
* 激活记录
* 最大激活次数
---
# ❗问题7:加密顺序可以优化
你现在:
```text
payload → AES → sign
```
---
## 更推荐:
```text
payload → sign → encrypt
```
👉 为什么?
* 签名保护“原始数据”
* 加密保护“整体结构”
👉 更标准(类似 TLS 思路)
---
# ❗问题8:缺少“反调试 / 防hook”
你现在:
> 完全信任 JVM
---
## ⚠️ 实际上:
攻击者可以:
* 用 Java Agent
* 用 ByteBuddy
* 改方法返回值
---
## ✅ 建议(至少做一点)
* 校验关键类 hash
* 检测 debug 模式
* 方法多点校验(不要单点)
---
# ✅ 四、推荐你升级后的结构(最终版)
我帮你整理一个更合理的👇
---
## License 结构
```json
{
"data": "AES加密内容",
"signature": "Ed25519"
}
```
---
## payload(解密后)
```json
{
"companyId": "xxx",
"edition": "enterprise",
"expireAt": 1234567890,
"features": ["order-import"],
"machineId": "xxx",
"jti": "xxx"
}
```
---
## 核心机制
| 模块 | 建议 |
| -- | ---------- |
| 签名 | Ed25519 |
| 加密 | AES-GCM |
| 校验 | 启动 + 定时 |
| 指纹 | UUID + 软绑定 |
| 控制 | Service 层 |
| 吊销 | jti + 在线校验 |
---
# ✅ 五、最终结论(很直接)
你现在这版:
> ✅ 已经不是“练手设计”,而是“可卖钱的版本”
但:
> ❗ 还没到“抗破解级”
---
# 👉 如果你下一步想做到“商业对抗级”
我可以帮你补这三块(这才是真正的差距):
1. ✅ License 混淆(防逆向)
2. ✅ 动态校验(防 patch)
3. ✅ 多点校验(防绕过)
你可以直接说:
👉 **“帮我做一版抗破解 license(对抗用户逆向)”**
+298
View File
@@ -0,0 +1,298 @@
# Ecom-DMB License 实施规格
> **v3** · Ed25519 JWT(`alg: EdDSA`)· payload **不加密** · Controller AOP + Service Feature Gate · 本地离线为主
> 架构评审对照见 [`1.md`](./1.md)。本文只保留**开工所需**的决策、契约与分阶段清单。
---
## 1. 目标与边界
| 项 | 规格 |
|----|------|
| 部署 | 私有部署(绑指纹)/ SaaS(指纹 `*`) |
| 授权粒度 | 每套部署 1 个 License |
| 受限能力 | `order-import`(订单批量导入 + 导入任务创建) |
| 校验层次 | `@LicenseRequired`(Controller)+ `LicenseFeatureGuard`(Service) |
| 运行时 | 请求:内存轻量 `check()`;后台:每 10min `fullValidate()` |
| 本地默认 | `ecom.license.enabled=false`,生产 `ECOM_LICENSE_ENABLED=true` |
**首版不做**:自定义 License 格式、AES 加密、反调试/防 Hook、NTP 拒绝请求(仅告警日志)。
---
## 2. 实施阶段(按顺序)
### Phase 1 — 主应用后端 `ecom-dmb-backend` ⬅ 先做
- [ ] SQL:`sys_init`、`sys_license`(`sql/migration/V20260528__sys_license_init.sql`)
- [ ] `modules/license/` 核心类(见 §4.1)
- [ ] `application.yml` + `pom` 增加 `nimbus-jose-jwt`
- [ ] `SecurityConfig` 放行 `/init/**`;`enabled=false` 时全跳过
- [ ] 接入导入链路(见 §4.5)
- [ ] 单测:验签、指纹、feature、吊销 jti
### Phase 2 — 主应用前端 `ecom-dmb-frontend`
- [ ] `views/init/*` 三步向导
- [ ] `views/system/license/*` 信息查看 + 续期 + 指纹展示
- [ ] 路由守卫:未初始化 → `/init`
### Phase 3 — License 服务器 `ecom-license/server`(NestJS)
- [ ] 客户/许可证 CRUD、签发、吊销、激活日志
- [ ] `POST /api/licenses/generate` 用 `jose` + Ed25519 私钥签发
- [ ] `GET /api/licenses/status?jti=` 供在线吊销同步(可选)
### Phase 4 — CLI `ecom-license/cli`
- [ ] `login` / `customer *` / `license generate|revoke|download`
- [ ] **优雅交互**:TTY 下向导式提问、表格/面板输出、加载动画;CI 用 `--json` / `--quiet` 零装饰(见 `DESIGN.reference.md` §E.1)
- [ ] 非交互模式供 CI(`--json` / `--quiet`)
---
## 3. 核心契约
### 3.1 架构(一张图)
```
运营方: ecom-license CLI → NestJS → 签发 EdDSA JWT
客户方: Spring Boot LicenseValidator(验签+缓存)→ AOP + Service Gate → 仅拦截导入
Vue 初始化向导 / License 设置页
```
### 3.2 JWT
**Header**:`{ "alg": "EdDSA", "typ": "JWT", "kid": "2026-v1" }`
**Payload 必填字段**:
| 字段 | 说明 |
|------|------|
| `sub` | 客户编号 |
| `company` | 公司名 |
| `machineFingerprint` | `FP-` + SHA256(machineId\|hostname);SaaS 填 `*` |
| `edition` | `trial` / `enterprise` / `unlimited` |
| `features` | `["order-import"]` |
| `jti` | 唯一 ID,吊销用 |
| `iss` | `ecom-license-server` |
| `iat` / `exp` | 标准 JWT 时间 |
**验签库**:主应用 `nimbus-jose-jwt`(与登录 `jjwt` 分离);签发 `jose`。
### 3.3 机器指纹
```
machineId = /etc/machine-id,否则 /etc/ecom-machine-id(首次写 UUID)
fingerprint = "FP-" + SHA256(machineId + "|" + hostname).toUpperCase()
```
### 3.4 License 加载优先级
| 时机 | 来源顺序 |
|------|----------|
| 启动/定时 revalidate | DB `sys_license` → 环境变量 `ECOM_LICENSE_KEY` → 文件 `config/license.key` |
| 激活后持久化 | 只信 DB;更新/续期写 DB 并刷新内存缓存 |
### 3.5 校验流程
```
导入请求
→ LicenseAspect: check() + requireFeature(ORDER_IMPORT) [enabled 时]
→ Service: licenseFeatureGuard.require(ORDER_IMPORT)
→ 内存判断: 有 License / 未过期 / 指纹匹配或* / jti 未吊销 / 含 order-import
后台定时(不进请求链路)
→ scheduledRevalidate: fullValidate,失败清空 cachedLicense
→ scheduledOnlineRevocationSync: 可选,查 License Server 同步 jti 黑名单
→ scheduledNtpCheck: 仅日志告警
```
---
## 4. Phase 1 后端明细
### 4.1 模块文件
```
modules/license/
├── LicenseProperties.java
├── LicenseAutoConfig.java
├── LicenseValidator.java # load / fullValidate / check / requireFeature / 定时任务
├── LicenseInfo.java
├── LicenseFeature.java # ORDER_IMPORT("order-import")
├── LicenseFeatureGuard.java
├── LicenseRequired.java
├── LicenseAspect.java
├── MachineFingerprintUtil.java
├── InitializeService.java
├── LicenseException.java
├── entity/SysInit.java, SysLicense.java
├── mapper/SysInitMapper.java, SysLicenseMapper.java
└── controller/
├── InitController.java # /init/*
└── SystemLicenseController.java # /system/license, /system/fingerprint
```
### 4.2 数据库
**`sys_init`**(单行 `id=1`):`step`(0~3)、`admin_id`、`company_name`、时间戳
**`sys_license`**:`company_name`、`edition`、`machine_fingerprint`、`installation_id`、`license_key`(text)、`jti`、`issued_at`、`expires_at`、`activated_at`、`is_active`
> 现有环境可 `INSERT sys_init (id,step) VALUES (1,3)` 跳过初始化门禁(仅开发)。
### 4.3 配置 `application.yml`
```yaml
ecom:
license:
enabled: ${ECOM_LICENSE_ENABLED:false}
public-key: ${ECOM_LICENSE_PUBLIC_KEY:} # Ed25519 SPKI PEM,支持 public-keys[]+kid
license-key: ${ECOM_LICENSE_KEY:}
license-file: ${ECOM_LICENSE_FILE:config/license.key}
revocation-file: ${ECOM_LICENSE_REVOCATION_FILE:config/revoked.jti}
revalidate-interval: ${ECOM_LICENSE_REVALIDATE_INTERVAL:10}
online-revocation-check: ${ECOM_LICENSE_ONLINE_REVOKE:false}
license-server-url: ${ECOM_LICENSE_SERVER_URL:}
```
### 4.4 HTTP API(无 `/api` 前缀,与现网一致)
| 方法 | 路径 | 鉴权 | 说明 |
|------|------|------|------|
| GET | `/init/status` | 公开 | 初始化进度 |
| POST | `/init/admin` | 公开 | Step1 超管 |
| POST | `/init/company` | 公开 | Step2 公司 |
| GET | `/init/fingerprint` | 公开 | 机器指纹 |
| POST | `/init/activate` | 公开 | `{ "licenseKey": "..." }` |
| GET | `/system/license` | 登录 | 当前 License 摘要 |
| PUT | `/system/license` | 登录 | 续期/更新 |
| GET | `/system/fingerprint` | 登录 | 查看指纹(迁机用) |
### 4.5 导入链路接入点(必须)
| 层 | 类 | 动作 |
|----|-----|------|
| Controller | `OrderController`、`OpenOrderController` | `@LicenseRequired` |
| Controller | `ImportTaskController` | `@LicenseRequired` |
| Service | `OrderServiceImpl.batchImportOrders` | `featureGuard.require` |
| Service | `ImportTaskServiceImpl.createImportTask` | `featureGuard.require` |
| Service | `ImportTaskProcessorServiceImpl`(`order` 类型) | `featureGuard.require` |
### 4.6 `enabled` 行为
| enabled | 行为 |
|---------|------|
| `false` | AOP / Guard 直接放行(本地开发) |
| `true` | 无有效 License → 导入接口 403 + 业务错误码 |
---
## 5. Phase 2 前端明细
```
apps/web-antd/src/views/
├── init/
│ ├── InitWizard.vue
│ ├── InitStepAdmin.vue
│ ├── InitStepCompany.vue
│ ├── InitStepLicense.vue
│ └── components/FingerprintDisplay.vue
└── system/license/
├── LicenseInfo.vue
└── FingerprintInfo.vue
api: api/system/license/ (对接 §4.4)
路由: 未 initialized → redirect /init
```
---
## 6. Phase 3/4 License 平台 `ecom-license/`
### 6.1 目录
```
ecom-license/
├── server/ # NestJS + TypeORM + MySQL
│ └── keys/ # private.pem / public.pem(Ed25519)
└── cli/ # Commander,bin: ecom-license
```
### 6.2 服务端表(摘要)
`lc_admin`、`lc_customer`、`lc_license`(含 `jti`、`max_activations`、`status`)、`lc_activation_log`、`lc_oper_log`
### 6.3 核心 API
| 方法 | 路径 | 说明 |
|------|------|------|
| POST | `/api/auth/login` | CLI 登录 |
| POST | `/api/licenses/generate` | **签发** |
| POST | `/api/licenses/:id/revoke` | 吊销 |
| GET | `/api/licenses/status` | 在线吊销查询(`?jti=`) |
| CRUD | `/api/customers` | 客户管理 |
### 6.4 CLI 命令树
```
ecom-license login | logout | whoami | stats
ecom-license customer list|create|show|update|delete|licenses
ecom-license license list|show|generate|revoke|download
```
全局:`--url` / `--token` / `--json` / `--quiet` / `--yes`
配置:`~/.config/ecom-license/config.json`
交互:TTY 下向导 + 表格 + spinner(`DESIGN.reference.md` §E.1);CI/管道自动静默
---
## 7. 密钥与运维
```bash
# 生成密钥对(仅 License Server 持私钥)
openssl genpkey -algorithm Ed25519 -out private.pem
openssl pkey -in private.pem -pubout -out public.pem
```
| 环境变量 | 用途 |
|----------|------|
| `ECOM_LICENSE_ENABLED` | 主应用开关 |
| `ECOM_LICENSE_PUBLIC_KEY` | 主应用公钥 PEM |
| `ECOM_LICENSE_KEY` | 预置 License JWT |
| `ECOM_LICENSE_API_URL` | CLI 指向 License Server |
**私有部署**:客户给 `FP-xxx` → `license generate --fingerprint FP-xxx` → 客户 `/init/activate`
**SaaS**:`--fingerprint "*"`
**续期**:同指纹重新签发 → 客户 `PUT /system/license`
**迁机**:新指纹 + 吊销旧 `jti`(见 §8)
---
## 8. 场景速查
1. **新客私有部署**:部署 → 初始化三步 → 指纹给运营 → CLI 签发 → 客户激活
2. **SaaS**:运营签发 `*` → 环境变量注入 License → 初始化
3. **续期**:CLI 新 JWT → 系统设置页更新
4. **迁机**:新服指纹 → revoke 旧证 → 新证激活 → 旧服指纹/jti 失效
---
## 9. 安全要点(实现时记住即可)
- 私钥仅在 License Server;主应用只嵌公钥
- 请求链路零 I/O;篡改内存靠定时 `fullValidate`
- 本地 `revoked.jti` + 可选在线同步
- 指纹防「拷库到新机」;整盘克隆不防
- 公钥轮换:`kid` + `public-keys[]` 多钥列表(首版可单钥)
---
## 10. 后续扩展(勿阻塞首版)
在线激活、License 到期站内通知、多机共享 License、抗逆向、CLI 多管理员
---
**详细参考**(CLI 输出格式、完整 DDL、历史 v2 说明、长代码示例):见 [`DESIGN.reference.md`](./DESIGN.reference.md)
+318
View File
@@ -0,0 +1,318 @@
# Ecom-DMB License 参考附录
> 实施时以 [`DESIGN.md`](./DESIGN.md) 为准。本文供查 JSON 示例、完整 DDL、CLI 细节;**v3 已统一 EdDSA,文中若出现 RS256 请忽略**。
---
## A. 主应用 API 请求/响应
### A.1 `GET /init/status`
```json
{
"initialized": false,
"currentStep": 0,
"adminCreated": false,
"companySaved": false,
"licenseActivated": false
}
```
### A.2 `GET /init/fingerprint`
```json
{
"fingerprint": "FP-A1B2C3D4E5F67890ABCDEF...",
"machineId": "a1b2c3d4-...",
"hostname": "ecom-server-01"
}
```
### A.3 `POST /init/activate` / `PUT /system/license`
请求:
```json
{ "licenseKey": "eyJhbGciOiJFZERTQSJ9..." }
```
激活校验:EdDSA 验签 → `exp` → 指纹匹配(`*` 跳过)→ 写 `sys_license` → `step=3`。
### A.4 `GET /system/license`
```json
{
"companyName": "某某科技",
"edition": "enterprise",
"machineFingerprint": "FP-...",
"features": ["order-import"],
"issuedAt": "2026-01-01T00:00:00Z",
"expiresAt": "2027-01-01T00:00:00Z",
"daysRemaining": 180,
"status": "active"
}
```
### A.5 错误码(导入受限)
| 场景 | HTTP | 业务码建议 |
|------|------|------------|
| 未激活 / 过期 | 403 | `LICENSE_INVALID` |
| 指纹不匹配 | 403 | `LICENSE_FINGERPRINT_MISMATCH` |
| 功能未授权 | 403 | `LICENSE_FEATURE_DENIED` |
| 已吊销 jti | 403 | `LICENSE_REVOKED` |
---
## B. 主应用 DDL(Flyway)
```sql
CREATE TABLE IF NOT EXISTS sys_init (
id BIGINT PRIMARY KEY DEFAULT 1,
step TINYINT NOT NULL DEFAULT 0 COMMENT '0~3',
admin_id BIGINT NULL,
company_name VARCHAR(200) NULL,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) COMMENT '系统初始化状态(单行)';
CREATE TABLE IF NOT EXISTS sys_license (
id BIGINT PRIMARY KEY AUTO_INCREMENT,
company_name VARCHAR(200) NOT NULL,
edition VARCHAR(20) NOT NULL,
machine_fingerprint VARCHAR(100) NOT NULL,
installation_id VARCHAR(64) NULL,
license_key TEXT NOT NULL,
jti VARCHAR(64) NOT NULL,
issued_at DATETIME NOT NULL,
expires_at DATETIME NOT NULL,
activated_at DATETIME NOT NULL,
is_active TINYINT NOT NULL DEFAULT 1,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
UNIQUE KEY uk_jti (jti)
) COMMENT '当前生效 License';
-- 已有环境跳过初始化门禁(仅开发)
INSERT INTO sys_init (id, step) VALUES (1, 3)
ON DUPLICATE KEY UPDATE step = GREATEST(step, 3);
```
---
## C. License 服务器表结构
### `lc_admin`
`id`, `username`, `password`(BCrypt), `nickname`, `status`, `created_at`, `updated_at`
### `lc_customer`
`id`, `code`(UK), `name`, `contact_name`, `contact_phone`, `contact_email`, `status`, `remark`, 时间戳
### `lc_license`
`id`, `customer_id`, `license_key`, `jti`(UK), `edition`, `machine_fingerprint`, `features`(JSON), `status`(active/revoked/expired), `issued_at`, `expires_at`, `revoked_at`, `max_activations`, `activation_count`, 时间戳
### `lc_activation_log`
`license_id`, `machine_fingerprint`, `installation_id`, `hostname`, `ip`, `action`(activate/deactivate), `created_at`
### `lc_oper_log`
`admin_id`, `action`, `target_type`, `target_id`, `detail`(JSON), `ip`, `created_at`
---
## D. License 服务器 API 补充
| 方法 | 路径 | 说明 |
|------|------|------|
| POST | `/api/auth/logout` | 退出 |
| GET | `/api/dashboard/stats` | 统计 |
| GET | `/api/licenses` | 列表 |
| GET | `/api/licenses/:id` | 详情 |
| GET | `/api/licenses/:id/download` | 下载 `.key` 文件 |
| GET | `/api/customers/:id/licenses` | 客户下许可证 |
### `POST /api/licenses/generate`
```json
{
"customerId": 1,
"company": "某某科技有限公司",
"machineFingerprint": "FP-A1B2...",
"edition": "enterprise",
"expiresAt": "2027-01-01T00:00:00Z",
"features": ["order-import"]
}
```
响应含 `licenseKey`(EdDSA JWT)、`jti`、`status: active`。
### `GET /api/licenses/status?jti=xxx`
```json
{ "jti": "uuid", "status": "active", "revokedAt": null }
```
---
## E. CLI 参考
### E.1 交互体验规格(必达)
**原则**:运营工具要「像产品」—— 默认交互模式赏心悦目;脚本/管道模式干净无噪。
#### 技术栈
| 能力 | 库 | 用途 |
|------|-----|------|
| 提问向导 | `@inquirer/prompts` | select / input / confirm / password |
| 颜色语义 | `chalk` | 成功绿、警告黄、错误红、信息灰蓝 |
| 加载态 | `ora` | 请求中 spinner,成功 ✓ / 失败 ✗ |
| 表格 | `cli-table3` | `customer list`、`license list` |
| 信息面板 | `boxen` | 签发结果、whoami、stats 摘要 |
| 品牌标题 | `gradient-string` + `figlet`(可选) | 首次 `login` 或无子命令时轻量 banner |
#### TTY 检测
```
isInteractive = process.stdout.isTTY && !process.env.CI && !--json && !--quiet
```
| 模式 | 行为 |
|------|------|
| 交互(默认) | 缺参走向导;列表用表格;API 用 spinner |
| `--json` | 纯 JSON 一行/结构化,无颜色无 spinner |
| `--quiet` | 只输出关键值(如 `licenseKey`、文件路径) |
| 管道/重定向 | 同 `--json` 语义,禁止 boxen/figlet |
#### 全局体验
- **无子命令** / `ecom-license --help`:简短 banner + 常用命令示例(带颜色)
- **未登录**:友好提示 + 引导 `ecom-license login`,非裸 `401`
- **网络/超时**:spinner 停止后一行人话错误 + 可选 `--verbose` 看堆栈
- **Ctrl+C**:优雅退出,不打印 Node 堆栈
#### 命令级交互
**`login`**(交互)
```
╭─ Ecom License CLI ─────────────────╮
│ 授权管理平台 · 运营端 │
╰─────────────────────────────────────╯
? API 地址 › http://localhost:3100
? 用户名 › admin
? 密码 › ********
⠋ 正在登录...
✔ 登录成功 · admin · Token 有效期至 2026-06-01
```
**`license generate`**(交互向导,分步 confirm)
1. `search` 选客户(支持输入过滤,非手打 ID)
2. 公司名(默认带出客户名,可改)
3. 指纹:`input` 或选「SaaS 不限指纹 (*)」
4. `select` edition:trial / enterprise / unlimited(带简短说明)
5. 过期日:`input` + 校验,提供快捷项「+1年」「+30天」
6. features:默认勾选 `order-import`,`checkbox` 确认
7. **摘要面板**(boxen)展示全部字段 → `confirm` 签发
8. 成功:绿色面板输出 `jti`、过期日;`licenseKey` 可复制(长文本折行 + 提示 `--quiet` 取纯 key)
**`license revoke`**:`confirm` 二次确认(展示 jti/公司/指纹),`--yes` 跳过
**`customer list` / `license list`**:表格列对齐;空列表提示「暂无数据」+ 下一步建议(如 `customer create`)
**`stats`**:boxen 数字卡片风格(客户数 / 有效证 / 即将过期)
**`download`**:spinner + 成功显示保存路径(绿色)
#### 输出示例(列表表格)
```
ID CODE NAME STATUS
─── ──────────────── ─────────────────── ──────
1 CUST-20260101-01 某某科技有限公司 启用
2 CUST-20260215-02 示例客户有限公司 启用
共 2 条 · 第 1/1 页
```
#### 实现约束
- 交互逻辑与 API 调用分离:`commands/*.ts` + `ui/prompts.ts` + `ui/render.ts`
- 所有 spinner 在 `finally` 中 `stop()`,避免残留
- 颜色跟随 `NO_COLOR` / `FORCE_COLOR` 环境变量
- 单元测试覆盖非交互路径;交互路径用 snapshot 测 `render.ts` 纯文本
---
### E.2 配置 `~/.config/ecom-license/config.json`
```json
{
"apiUrl": "http://localhost:3100",
"token": "eyJ...",
"username": "admin",
"expiresAt": "2026-05-25T12:00:00Z"
}
```
优先级:命令行 flag > 环境变量 > 配置文件。
### 全局选项
| 选项 | 环境变量 |
|------|----------|
| `--url` | `ECOM_LICENSE_API_URL` |
| `--token` | `ECOM_LICENSE_TOKEN` |
| `--json` / `--quiet` / `--yes` | — |
### 非交互签发示例
```bash
ecom-license license generate \
--customer-id 1 \
--company "某某科技" \
--fingerprint "FP-A1B2..." \
--edition enterprise \
--expires "2027-01-01" \
--features order-import \
--json
```
SaaS:`--fingerprint "*"`
### E.3 交互式 `license generate` 步骤
客户(可搜索选择)→ 公司名 → 指纹或 `*` → edition → 过期日(快捷 +1年)→ features → 摘要确认 → 签发。
完整视觉与组件选型见 **§E.1**。
---
## F. v3 相对 v2 / 评审 `1.md` 的决策记录
| 议题 | 决策 |
|------|------|
| 签名算法 | **Ed25519 / EdDSA**(非 RSA) |
| 格式 | **标准 JWT**,payload 明文(非自定义结构、非 AES) |
| 校验 | Controller AOP + **Service 双点** |
| 定时验签 | **采纳**,默认 10 分钟 `fullValidate` |
| 在线吊销 | **可选**,默认关 |
| 反调试 / NTP 拒请求 | **首版不做** |
完整评审原文见 [`1.md`](./1.md)。
---
## G. 历史完整设计
Git 中 v2 长文档(RSA、含大段 Java 伪代码)可通过以下命令查看,**勿作为实现依据**:
```bash
git show HEAD:ecom-license/DESIGN.md
```
+58
View File
@@ -0,0 +1,58 @@
# Ecom License 平台
`ecom-license/` 是**文档 + 两个独立 Node 子项目**的目录,不是 pnpm monorepo:
```
ecom-license/
├── DESIGN.md # 设计文档
├── server/ # NestJS 签发服务(独立 pnpm 项目)
└── cli/ # 运营 CLI(独立 pnpm 项目)
```
各子项目在自己的目录里 `pnpm install`,依赖装在 `server/node_modules`、`cli/node_modules`,**根目录不会有 node_modules**。
## 环境要求
- Node.js >= 18
- pnpm >= 8
- MySQL
## Server 快速开始
```bash
cd ecom-license/server
pnpm install
# 初始化表(在目标库执行 sql/schema.sql)
mysql -h <host> -u ecom_license_dev -p ecom_license_dev < sql/schema.sql
# 生成密钥
openssl genpkey -algorithm Ed25519 -out keys/private.pem
openssl pkey -in keys/private.pem -pubout -out keys/public.pem
cp .env.example .env
pnpm build
pnpm start:dev # http://localhost:3100
```
## CLI 快速开始
```bash
cd ecom-license/cli
pnpm install
pnpm build
# 开发(改代码后即时运行,需带子命令)
pnpm dev login
pnpm dev license generate
# 或构建后运行
pnpm start login # 默认 admin / admin123
pnpm stats
```
> 不要用裸 `pnpm dev` / `npm run dev`(无子命令只会显示引导)。请用 `pnpm dev login` 等。
## 主应用公钥
将 `server/keys/public.pem` 配置到主应用 `ECOM_LICENSE_PUBLIC_KEY`。
+10
View File
@@ -0,0 +1,10 @@
# 运行时镜像:业务代码通过 volume 挂载 /app,更新部署无需重建镜像
ARG BASE_IMAGE=docker.m.daocloud.io/library/node:22-alpine
FROM ${BASE_IMAGE}
WORKDIR /app
RUN addgroup -S app && adduser -S app -G app && corepack enable
USER app
EXPOSE 3100
CMD ["node", "dist/main.js"]
+29
View File
@@ -0,0 +1,29 @@
{
"name": "ecom-license-root",
"version": "1.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "ecom-license-root",
"version": "1.0.0",
"devDependencies": {
"typescript": "^5.7.2"
}
},
"node_modules/typescript": {
"version": "5.9.3",
"resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz",
"integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",
"dev": true,
"license": "Apache-2.0",
"bin": {
"tsc": "bin/tsc",
"tsserver": "bin/tsserver"
},
"engines": {
"node": ">=14.17"
}
}
}
}
+8
View File
@@ -0,0 +1,8 @@
{
"name": "ecom-license-root",
"private": true,
"version": "1.0.0",
"devDependencies": {
"typescript": "^5.7.2"
}
}
+10
View File
@@ -0,0 +1,10 @@
PORT=3100
DB_HOST=192.168.3.100
DB_PORT=3306
DB_USERNAME=ecom_license_dev
DB_PASSWORD=ecom_license_dev
DB_DATABASE=ecom_license_dev
JWT_SECRET=change-me-in-production
JWT_EXPIRES_IN=8h
LICENSE_PRIVATE_KEY_PATH=keys/private.pem
LICENSE_KID=2026-v1
+2
View File
@@ -0,0 +1,2 @@
# 提升依赖到 node_modules 顶层,改善 IDE / tsserver 模块解析(pnpm 默认隔离布局对部分编辑器不友好)
shamefully-hoist=true
@@ -0,0 +1,2 @@
*.pem
!/.gitkeep
+9
View File
@@ -0,0 +1,9 @@
{
"$schema": "https://json.schemastore.org/nest-cli",
"collection": "@nestjs/schematics",
"sourceRoot": "src",
"compilerOptions": {
"deleteOutDir": true,
"tsConfigPath": "tsconfig.build.json"
}
}
+47
View File
@@ -0,0 +1,47 @@
{
"name": "ecom-license-server",
"version": "0.1.0",
"private": true,
"packageManager": "pnpm@10.32.0",
"scripts": {
"clean": "rm -rf dist",
"build": "nest build",
"prestart": "pnpm run build",
"start": "node dist/main.js",
"start:dev": "nest start --watch",
"start:prod": "node dist/main.js"
},
"dependencies": {
"@nestjs/common": "^10.4.15",
"@nestjs/config": "^3.3.0",
"@nestjs/core": "^10.4.15",
"@nestjs/jwt": "^10.2.0",
"@nestjs/passport": "^10.0.3",
"@nestjs/platform-express": "^10.4.15",
"@nestjs/typeorm": "^10.0.2",
"bcrypt": "^5.1.1",
"class-transformer": "^0.5.1",
"class-validator": "^0.14.1",
"jose": "^5.9.6",
"mysql2": "^3.11.5",
"passport": "^0.7.0",
"passport-jwt": "^4.0.1",
"reflect-metadata": "^0.2.2",
"rxjs": "^7.8.1",
"typeorm": "^0.3.20",
"uuid": "^11.0.3"
},
"pnpm": {
"onlyBuiltDependencies": ["bcrypt", "@nestjs/core"]
},
"devDependencies": {
"@nestjs/cli": "^10.4.9",
"@nestjs/schematics": "^10.2.3",
"@types/bcrypt": "^5.0.2",
"@types/express": "^5.0.0",
"@types/node": "^22.10.2",
"@types/passport-jwt": "^4.0.1",
"@types/uuid": "^10.0.0",
"typescript": "^5.7.2"
}
}
File diff suppressed because it is too large Load Diff
+77
View File
@@ -0,0 +1,77 @@
-- Ecom License Server 表结构
-- 目标库: ecom_license_dev(执行: mysql ... ecom_license_dev < schema.sql)
CREATE TABLE IF NOT EXISTS lc_admin (
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
username VARCHAR(50) NOT NULL,
password VARCHAR(255) NOT NULL COMMENT 'BCrypt',
nickname VARCHAR(50) NULL,
status TINYINT NOT NULL DEFAULT 1 COMMENT '0=禁用 1=启用',
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (id),
UNIQUE KEY uk_username (username)
) ENGINE=InnoDB COMMENT='License 平台管理员';
CREATE TABLE IF NOT EXISTS lc_customer (
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
code VARCHAR(50) NOT NULL,
name VARCHAR(200) NOT NULL,
contact_name VARCHAR(50) NULL,
contact_phone VARCHAR(20) NULL,
contact_email VARCHAR(100) NULL,
status TINYINT NOT NULL DEFAULT 1,
remark TEXT NULL,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (id),
UNIQUE KEY uk_code (code)
) ENGINE=InnoDB COMMENT='License 客户';
CREATE TABLE IF NOT EXISTS lc_license (
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
customer_id BIGINT UNSIGNED NOT NULL,
license_key TEXT NOT NULL,
jti VARCHAR(64) NOT NULL,
edition VARCHAR(20) NOT NULL,
machine_fingerprint VARCHAR(100) NOT NULL,
features JSON NOT NULL,
status VARCHAR(20) NOT NULL DEFAULT 'active',
issued_at TIMESTAMP NOT NULL,
expires_at TIMESTAMP NOT NULL,
revoked_at TIMESTAMP NULL,
max_activations INT NULL,
max_companies INT NULL COMMENT '允许创建的最大公司数量,NULL 表示使用版本默认值',
activation_count INT NOT NULL DEFAULT 0,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (id),
UNIQUE KEY uk_jti (jti),
KEY idx_customer_id (customer_id),
CONSTRAINT fk_license_customer FOREIGN KEY (customer_id) REFERENCES lc_customer (id)
) ENGINE=InnoDB COMMENT='签发的 License';
CREATE TABLE IF NOT EXISTS lc_activation_log (
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
license_id BIGINT UNSIGNED NOT NULL,
machine_fingerprint VARCHAR(100) NOT NULL,
installation_id VARCHAR(64) NULL,
hostname VARCHAR(200) NULL,
ip VARCHAR(50) NULL,
action VARCHAR(20) NOT NULL,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (id),
KEY idx_license_id (license_id)
) ENGINE=InnoDB COMMENT='激活日志';
CREATE TABLE IF NOT EXISTS lc_oper_log (
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
admin_id BIGINT UNSIGNED NULL,
action VARCHAR(50) NOT NULL,
target_type VARCHAR(50) NULL,
target_id BIGINT UNSIGNED NULL,
detail JSON NULL,
ip VARCHAR(50) NULL,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (id)
) ENGINE=InnoDB COMMENT='操作日志';
@@ -0,0 +1,37 @@
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { TypeOrmModule } from '@nestjs/typeorm';
import { AuthModule } from './modules/auth/auth.module';
import { CustomerModule } from './modules/customer/customer.module';
import { DashboardModule } from './modules/dashboard/dashboard.module';
import { LicenseModule } from './modules/license/license.module';
import { LcAdmin } from './entities/lc-admin.entity';
import { LcActivationLog } from './entities/lc-activation-log.entity';
import { LcCustomer } from './entities/lc-customer.entity';
import { LcLicense } from './entities/lc-license.entity';
import { LcOperLog } from './entities/lc-oper-log.entity';
import { AdminSeedService } from './common/admin-seed.service';
@Module({
imports: [
ConfigModule.forRoot({ isGlobal: true }),
TypeOrmModule.forRoot({
type: 'mysql',
host: process.env.DB_HOST || 'localhost',
port: Number(process.env.DB_PORT || 3306),
username: process.env.DB_USERNAME || 'root',
password: process.env.DB_PASSWORD || '',
database: process.env.DB_DATABASE || 'ecom_license_dev',
entities: [LcAdmin, LcCustomer, LcLicense, LcActivationLog, LcOperLog],
synchronize: process.env.DB_SYNC === 'true',
timezone: '+08:00',
}),
TypeOrmModule.forFeature([LcAdmin]),
AuthModule,
CustomerModule,
LicenseModule,
DashboardModule,
],
providers: [AdminSeedService],
})
export class AppModule {}
@@ -0,0 +1,27 @@
import { Injectable, OnModuleInit } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import * as bcrypt from 'bcrypt';
import { Repository } from 'typeorm';
import { LcAdmin } from '../entities/lc-admin.entity';
/** 首次启动时创建默认管理员 admin / admin123 */
@Injectable()
export class AdminSeedService implements OnModuleInit {
constructor(
@InjectRepository(LcAdmin)
private readonly adminRepo: Repository<LcAdmin>,
) {}
async onModuleInit() {
const count = await this.adminRepo.count();
if (count > 0) return;
const password = await bcrypt.hash('admin123', 10);
await this.adminRepo.save({
username: 'admin',
password,
nickname: '默认管理员',
status: 1,
});
console.log('[seed] 默认管理员已创建: admin / admin123');
}
}
@@ -0,0 +1,67 @@
import { Injectable, OnModuleInit } from '@nestjs/common';
import { readFile } from 'fs/promises';
import { importPKCS8, SignJWT, type KeyLike } from 'jose';
import { join } from 'path';
import { v4 as uuidv4 } from 'uuid';
export interface SignLicenseInput {
sub: string;
company: string;
machineFingerprint: string;
edition: string;
features: string[];
expiresAt: Date;
maxCompanies?: number;
}
export interface SignLicenseResult {
licenseKey: string;
jti: string;
issuedAt: Date;
expiresAt: Date;
}
/** 使用 Ed25519 私钥签发 License JWT */
@Injectable()
export class JwtSignerService implements OnModuleInit {
private privateKey: KeyLike | null = null;
private kid = process.env.LICENSE_KID || '2026-v1';
async onModuleInit() {
const keyPath =
process.env.LICENSE_PRIVATE_KEY_PATH || join(process.cwd(), 'keys', 'private.pem');
try {
const pem = await readFile(keyPath, 'utf8');
this.privateKey = await importPKCS8(pem, 'EdDSA');
} catch (e) {
console.warn(`[license] 未加载私钥 ${keyPath},签发功能不可用。请运行: openssl genpkey -algorithm Ed25519 -out keys/private.pem`);
}
}
async signLicense(input: SignLicenseInput): Promise<SignLicenseResult> {
if (!this.privateKey) {
throw new Error('License 私钥未配置,无法签发');
}
const jti = uuidv4();
const issuedAt = new Date();
const claims: Record<string, unknown> = {
company: input.company,
machineFingerprint: input.machineFingerprint,
edition: input.edition,
features: input.features,
};
if (input.maxCompanies != null && input.maxCompanies > 0) {
claims.maxCompanies = input.maxCompanies;
}
const licenseKey = await new SignJWT(claims)
.setProtectedHeader({ alg: 'EdDSA', typ: 'JWT', kid: this.kid })
.setIssuer('ecom-license-server')
.setSubject(input.sub)
.setJti(jti)
.setIssuedAt(issuedAt)
.setExpirationTime(input.expiresAt)
.sign(this.privateKey);
return { licenseKey, jti, issuedAt, expiresAt: input.expiresAt };
}
}
@@ -0,0 +1,33 @@
import {
Column,
CreateDateColumn,
Entity,
PrimaryGeneratedColumn,
} from 'typeorm';
@Entity('lc_activation_log')
export class LcActivationLog {
@PrimaryGeneratedColumn({ type: 'bigint', unsigned: true })
id!: number;
@Column({ name: 'license_id', type: 'bigint', unsigned: true })
licenseId!: number;
@Column({ name: 'machine_fingerprint', length: 100 })
machineFingerprint!: string;
@Column({ name: 'installation_id', type: 'varchar', length: 64, nullable: true })
installationId!: string | null;
@Column({ type: 'varchar', length: 200, nullable: true })
hostname!: string | null;
@Column({ type: 'varchar', length: 50, nullable: true })
ip!: string | null;
@Column({ length: 20 })
action!: string;
@CreateDateColumn({ name: 'created_at' })
createdAt!: Date;
}
@@ -0,0 +1,31 @@
import {
Column,
CreateDateColumn,
Entity,
PrimaryGeneratedColumn,
UpdateDateColumn,
} from 'typeorm';
@Entity('lc_admin')
export class LcAdmin {
@PrimaryGeneratedColumn({ type: 'bigint', unsigned: true })
id!: number;
@Column({ length: 50, unique: true })
username!: string;
@Column({ length: 255 })
password!: string;
@Column({ type: 'varchar', length: 50, nullable: true })
nickname!: string | null;
@Column({ type: 'tinyint', default: 1 })
status!: number;
@CreateDateColumn({ name: 'created_at' })
createdAt!: Date;
@UpdateDateColumn({ name: 'updated_at' })
updatedAt!: Date;
}
@@ -0,0 +1,45 @@
import {
Column,
CreateDateColumn,
Entity,
OneToMany,
PrimaryGeneratedColumn,
UpdateDateColumn,
} from 'typeorm';
import { LcLicense } from './lc-license.entity';
@Entity('lc_customer')
export class LcCustomer {
@PrimaryGeneratedColumn({ type: 'bigint', unsigned: true })
id!: number;
@Column({ length: 50, unique: true })
code!: string;
@Column({ length: 200 })
name!: string;
@Column({ name: 'contact_name', type: 'varchar', length: 50, nullable: true })
contactName!: string | null;
@Column({ name: 'contact_phone', type: 'varchar', length: 20, nullable: true })
contactPhone!: string | null;
@Column({ name: 'contact_email', type: 'varchar', length: 100, nullable: true })
contactEmail!: string | null;
@Column({ type: 'tinyint', default: 1 })
status!: number;
@Column({ type: 'text', nullable: true })
remark!: string | null;
@OneToMany(() => LcLicense, (license) => license.customer)
licenses!: LcLicense[];
@CreateDateColumn({ name: 'created_at' })
createdAt!: Date;
@UpdateDateColumn({ name: 'updated_at' })
updatedAt!: Date;
}
@@ -0,0 +1,65 @@
import {
Column,
CreateDateColumn,
Entity,
JoinColumn,
ManyToOne,
PrimaryGeneratedColumn,
UpdateDateColumn,
} from 'typeorm';
import { LcCustomer } from './lc-customer.entity';
@Entity('lc_license')
export class LcLicense {
@PrimaryGeneratedColumn({ type: 'bigint', unsigned: true })
id!: number;
@Column({ name: 'customer_id', type: 'bigint', unsigned: true })
customerId!: number;
@ManyToOne(() => LcCustomer, (customer) => customer.licenses)
@JoinColumn({ name: 'customer_id' })
customer!: LcCustomer;
@Column({ name: 'license_key', type: 'text' })
licenseKey!: string;
@Column({ length: 64, unique: true })
jti!: string;
@Column({ length: 20 })
edition!: string;
@Column({ name: 'machine_fingerprint', length: 100 })
machineFingerprint!: string;
@Column({ type: 'json' })
features!: string[];
@Column({ length: 20, default: 'active' })
status!: string;
@Column({ name: 'issued_at', type: 'timestamp' })
issuedAt!: Date;
@Column({ name: 'expires_at', type: 'timestamp' })
expiresAt!: Date;
@Column({ name: 'revoked_at', type: 'timestamp', nullable: true })
revokedAt!: Date | null;
@Column({ name: 'max_activations', type: 'int', nullable: true })
maxActivations!: number | null;
@Column({ name: 'max_companies', type: 'int', nullable: true })
maxCompanies!: number | null;
@Column({ name: 'activation_count', type: 'int', default: 0 })
activationCount!: number;
@CreateDateColumn({ name: 'created_at' })
createdAt!: Date;
@UpdateDateColumn({ name: 'updated_at' })
updatedAt!: Date;
}
@@ -0,0 +1,33 @@
import {
Column,
CreateDateColumn,
Entity,
PrimaryGeneratedColumn,
} from 'typeorm';
@Entity('lc_oper_log')
export class LcOperLog {
@PrimaryGeneratedColumn({ type: 'bigint', unsigned: true })
id!: number;
@Column({ name: 'admin_id', type: 'bigint', unsigned: true, nullable: true })
adminId!: number | null;
@Column({ length: 50 })
action!: string;
@Column({ name: 'target_type', type: 'varchar', length: 50, nullable: true })
targetType!: string | null;
@Column({ name: 'target_id', type: 'bigint', unsigned: true, nullable: true })
targetId!: number | null;
@Column({ type: 'json', nullable: true })
detail!: Record<string, unknown> | null;
@Column({ type: 'varchar', length: 50, nullable: true })
ip!: string | null;
@CreateDateColumn({ name: 'created_at' })
createdAt!: Date;
}
+17
View File
@@ -0,0 +1,17 @@
import { ValidationPipe } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.setGlobalPrefix('api');
app.useGlobalPipes(
new ValidationPipe({ whitelist: true, transform: true, forbidNonWhitelisted: true }),
);
app.enableCors();
const port = process.env.PORT || 3100;
await app.listen(port);
console.log(`Ecom License Server running on http://localhost:${port}`);
}
bootstrap();
@@ -0,0 +1,18 @@
import { Body, Controller, Post } from '@nestjs/common';
import { AuthService } from './auth.service';
import { LoginDto } from './auth.dto';
@Controller('auth')
export class AuthController {
constructor(private readonly authService: AuthService) {}
@Post('login')
login(@Body() dto: LoginDto) {
return this.authService.login(dto);
}
@Post('logout')
logout() {
return { success: true };
}
}
@@ -0,0 +1,11 @@
import { IsNotEmpty, IsString } from 'class-validator';
export class LoginDto {
@IsString()
@IsNotEmpty()
username!: string;
@IsString()
@IsNotEmpty()
password!: string;
}
@@ -0,0 +1,23 @@
import { Module } from '@nestjs/common';
import { JwtModule } from '@nestjs/jwt';
import { PassportModule } from '@nestjs/passport';
import { TypeOrmModule } from '@nestjs/typeorm';
import { LcAdmin } from '../../entities/lc-admin.entity';
import { AuthController } from './auth.controller';
import { AuthService } from './auth.service';
import { JwtStrategy } from './jwt.strategy';
@Module({
imports: [
TypeOrmModule.forFeature([LcAdmin]),
PassportModule.register({ defaultStrategy: 'jwt' }),
JwtModule.register({
secret: process.env.JWT_SECRET || 'change-me-in-production',
signOptions: { expiresIn: process.env.JWT_EXPIRES_IN || '8h' },
}),
],
controllers: [AuthController],
providers: [AuthService, JwtStrategy],
exports: [JwtModule],
})
export class AuthModule {}
@@ -0,0 +1,38 @@
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { InjectRepository } from '@nestjs/typeorm';
import * as bcrypt from 'bcrypt';
import { Repository } from 'typeorm';
import { LcAdmin } from '../../entities/lc-admin.entity';
import { LoginDto } from './auth.dto';
@Injectable()
export class AuthService {
constructor(
@InjectRepository(LcAdmin)
private readonly adminRepo: Repository<LcAdmin>,
private readonly jwtService: JwtService,
) {}
async login(dto: LoginDto) {
const admin = await this.adminRepo.findOne({ where: { username: dto.username } });
if (!admin || admin.status !== 1) {
throw new UnauthorizedException('用户名或密码错误');
}
const ok = await bcrypt.compare(dto.password, admin.password);
if (!ok) {
throw new UnauthorizedException('用户名或密码错误');
}
const expiresIn = process.env.JWT_EXPIRES_IN || '8h';
const token = this.jwtService.sign(
{ sub: admin.id, username: admin.username },
{ expiresIn },
);
const decoded = this.jwtService.decode(token) as { exp?: number };
return {
token,
username: admin.username,
expiresAt: decoded?.exp ? new Date(decoded.exp * 1000).toISOString() : null,
};
}
}
@@ -0,0 +1,5 @@
import { Injectable } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
@Injectable()
export class JwtAuthGuard extends AuthGuard('jwt') {}
@@ -0,0 +1,26 @@
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { ExtractJwt, Strategy } from 'passport-jwt';
export interface AdminJwtPayload {
sub: number;
username: string;
}
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor() {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
ignoreExpiration: false,
secretOrKey: process.env.JWT_SECRET || 'change-me-in-production',
});
}
validate(payload: AdminJwtPayload) {
if (!payload?.sub) {
throw new UnauthorizedException();
}
return { adminId: payload.sub, username: payload.username };
}
}
@@ -0,0 +1,55 @@
import {
Body,
Controller,
Delete,
Get,
Param,
ParseIntPipe,
Post,
Put,
Query,
UseGuards,
} from '@nestjs/common';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { LicenseService } from '../license/license.service';
import { CreateCustomerDto, CustomerQueryDto, UpdateCustomerDto } from './customer.dto';
import { CustomerService } from './customer.service';
@Controller('customers')
@UseGuards(JwtAuthGuard)
export class CustomerController {
constructor(
private readonly customerService: CustomerService,
private readonly licenseService: LicenseService,
) {}
@Get()
list(@Query() query: CustomerQueryDto) {
return this.customerService.list(query);
}
@Post()
create(@Body() dto: CreateCustomerDto) {
return this.customerService.create(dto);
}
@Get(':id')
findOne(@Param('id', ParseIntPipe) id: number) {
return this.customerService.findOne(id);
}
@Put(':id')
update(@Param('id', ParseIntPipe) id: number, @Body() dto: UpdateCustomerDto) {
return this.customerService.update(id, dto);
}
@Delete(':id')
remove(@Param('id', ParseIntPipe) id: number) {
return this.customerService.remove(id);
}
@Get(':id/licenses')
licenses(@Param('id', ParseIntPipe) id: number) {
return this.licenseService.listByCustomer(id);
}
}
@@ -0,0 +1,68 @@
import { IsEmail, IsInt, IsNotEmpty, IsOptional, IsString, Min } from 'class-validator';
import { Type } from 'class-transformer';
export class CreateCustomerDto {
@IsString()
@IsOptional()
code?: string;
@IsString()
@IsNotEmpty()
name!: string;
@IsString()
@IsOptional()
contactName?: string;
@IsString()
@IsOptional()
contactPhone?: string;
@IsEmail()
@IsOptional()
contactEmail?: string;
@IsString()
@IsOptional()
remark?: string;
}
export class UpdateCustomerDto {
@IsString()
@IsOptional()
name?: string;
@IsString()
@IsOptional()
contactName?: string;
@IsString()
@IsOptional()
contactPhone?: string;
@IsEmail()
@IsOptional()
contactEmail?: string;
@IsInt()
@IsOptional()
status?: number;
@IsString()
@IsOptional()
remark?: string;
}
export class CustomerQueryDto {
@Type(() => Number)
@IsInt()
@Min(1)
@IsOptional()
page?: number = 1;
@Type(() => Number)
@IsInt()
@Min(1)
@IsOptional()
size?: number = 20;
}
@@ -0,0 +1,17 @@
import { Module, forwardRef } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { LcCustomer } from '../../entities/lc-customer.entity';
import { LicenseModule } from '../license/license.module';
import { CustomerController } from './customer.controller';
import { CustomerService } from './customer.service';
@Module({
imports: [
TypeOrmModule.forFeature([LcCustomer]),
forwardRef(() => LicenseModule),
],
controllers: [CustomerController],
providers: [CustomerService],
exports: [CustomerService],
})
export class CustomerModule {}
@@ -0,0 +1,67 @@
import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { LcCustomer } from '../../entities/lc-customer.entity';
import { CreateCustomerDto, CustomerQueryDto, UpdateCustomerDto } from './customer.dto';
@Injectable()
export class CustomerService {
constructor(
@InjectRepository(LcCustomer)
private readonly customerRepo: Repository<LcCustomer>,
) {}
async list(query: CustomerQueryDto) {
const page = query.page || 1;
const size = query.size || 20;
const [items, total] = await this.customerRepo.findAndCount({
order: { id: 'DESC' },
skip: (page - 1) * size,
take: size,
});
return { items, total, page, size };
}
async findOne(id: number) {
const customer = await this.customerRepo.findOne({ where: { id } });
if (!customer) throw new NotFoundException('客户不存在');
return customer;
}
async create(dto: CreateCustomerDto) {
const code = dto.code || (await this.generateCode());
const customer = this.customerRepo.create({
code,
name: dto.name,
contactName: dto.contactName ?? null,
contactPhone: dto.contactPhone ?? null,
contactEmail: dto.contactEmail ?? null,
remark: dto.remark ?? null,
status: 1,
});
return this.customerRepo.save(customer);
}
async update(id: number, dto: UpdateCustomerDto) {
const customer = await this.findOne(id);
Object.assign(customer, {
...dto,
contactName: dto.contactName ?? customer.contactName,
contactPhone: dto.contactPhone ?? customer.contactPhone,
contactEmail: dto.contactEmail ?? customer.contactEmail,
});
return this.customerRepo.save(customer);
}
async remove(id: number) {
const customer = await this.findOne(id);
await this.customerRepo.remove(customer);
return { success: true };
}
private async generateCode() {
const date = new Date().toISOString().slice(0, 10).replace(/-/g, '');
const count = await this.customerRepo.count();
return `CUST-${date}-${String(count + 1).padStart(3, '0')}`;
}
}
@@ -0,0 +1,14 @@
import { Controller, Get, UseGuards } from '@nestjs/common';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { DashboardService } from './dashboard.service';
@Controller('dashboard')
@UseGuards(JwtAuthGuard)
export class DashboardController {
constructor(private readonly dashboardService: DashboardService) {}
@Get('stats')
stats() {
return this.dashboardService.stats();
}
}

Some files were not shown because too many files have changed in this diff Show More