diff --git a/ecom-license/DESIGN.md b/ecom-license/DESIGN.md index fd858c3b..e9390d4a 100644 --- a/ecom-license/DESIGN.md +++ b/ecom-license/DESIGN.md @@ -1,5 +1,7 @@ # Ecom-DMB 授权许可与系统初始化设计方案 +> **v2 变更(2026-05)**:License 授权管理平台的管理端由 **Vue Web 后台** 改为 **CLI 命令行工具**。NestJS 后端与 REST API 保持不变,运营方通过 `ecom-license` CLI 完成客户管理、签发/吊销 License 等操作,更适合运维、脚本化与 CI 集成。 + ## 1. 概述 ### 1.1 目标 @@ -20,7 +22,7 @@ Ecom-DMB 支持 **SaaS 部署** 和 **私有部署** 两种模式,所有模式 | 概念 | 说明 | |------|------| -| **License 服务器** | 运营方部署的授权管理平台(NestJS + Vue 3),用于签发和管理 License | +| **License 服务器** | 运营方部署的授权管理平台(NestJS + **CLI**),用于签发和管理 License | | **License JWT** | RS256 签名的 JWT Token,包含授权信息和机器指纹,不可篡改 | | **机器指纹** | 根据系统 machine-id(`/etc/machine-id`)+ 主机名生成的唯一哈希值 | | **安装 ID** | 系统 machine-id(Linux `/etc/machine-id`),由 systemd 在首次启动时自动生成,唯一标识一次 OS 安装 | @@ -37,34 +39,39 @@ Ecom-DMB 支持 **SaaS 部署** 和 **私有部署** 两种模式,所有模式 │ License 授权管理服务器 │ │ Ecom-DMB 主应用 │ │ │ │ │ │ ┌──────────────────┐ ┌─────────────┐ │ │ ┌─────────────────────────┐ │ - │ │ Vue 3 管理后台 │ │ NestJS 后端 │ │ │ │ Spring Boot 后端 │ │ - │ │ (Ant Design Vue) │──▶│ │ │ │ │ │ │ - │ │ │ │ · 客户管理 │──┼─────┼──│ · LicenseValidator │ │ - │ │ · 客户管理 │ │ · 签发License│ │ │ │ · MachineFingerprint │ │ - │ │ · 签发License │ │ · 在线验证 │ │ │ │ · InitController │ │ - │ │ · 下载License文件 │ │ · 操作日志 │ │ │ │ · LicenseAspect │ │ - │ │ · 操作日志 │ └─────────────┘ │ │ └─────────────────────────┘ │ - │ └──────────────────┘ │ │ │ - └──────────────────────────────────────────┘ │ ┌─────────────────────────┐ │ + │ │ ecom-license CLI │ │ NestJS 后端 │ │ │ │ Spring Boot 后端 │ │ + │ │ (运营方本地/CI) │──▶│ REST API │ │ │ │ │ │ + │ │ │ │ │ │ │ │ · LicenseValidator │ │ + │ │ · customer * │ │ · 客户管理 │──┼─────┼──│ · MachineFingerprint │ │ + │ │ · license * │ │ · 签发License│ │ │ │ · InitController │ │ + │ │ · stats / login │ │ · 操作日志 │ │ │ │ · LicenseAspect │ │ + │ └──────────────────┘ └─────────────┘ │ │ └─────────────────────────┘ │ + └──────────────────────────────────────────┘ │ │ + │ ┌─────────────────────────┐ │ │ │ Vue 3 前端 (Vben Admin) │ │ - │ │ │ │ - │ │ · 初始化向导页面 │ │ - │ │ · 订单导入页面 │ │ - │ │ · 系统设置页面 │ │ + │ │ · 初始化向导 / License 设置│ │ │ └─────────────────────────┘ │ └───────────────────────────────┘ ``` +**管理端形态说明**: + +| 原方案 | 新方案 | 原因 | +|--------|--------|------| +| Vue 3 + Ant Design Vue 管理后台 | **Node.js CLI**(`ecom-license` 命令) | 运营操作低频、偏运维;CLI 便于 SSH/脚本/CI;无需维护第二套 Web UI | +| 浏览器登录后台 | `ecom-license login` + 本地 Token 缓存 | 与 API 认证一致,支持非交互 `--token` | +| 页面表单签发 | `ecom-license license generate` | 支持交互式向导 + 全参数非交互模式 | + ### 2.1 两种部署模式的 License 获取方式 ``` 私有部署模式: 客户部署系统 → 初始化页面显示机器指纹 → 客户将指纹发给运营方 - → 运营方在 License 后台签发绑定该指纹的 License + → 运营方通过 `ecom-license` CLI 签发绑定该指纹的 License → 客户输入 License Key → 系统校验通过 → 激活完成 SaaS 部署模式: - 运营方在 License 后台签发一个不限指纹的 License(machineFingerprint 填 "*") + 运营方通过 CLI 签发一个不限指纹的 License(machineFingerprint 填 "*") → 部署系统时直接配置 License → 初始化时自动完成激活 → License 校验时跳过指纹比对 ``` @@ -111,8 +118,8 @@ SaaS 部署模式: │ │ [激活] [离线激活说明] │ │ │ └────────────────────────────────────┘ │ │ │ -│ 说明:客户将机器指纹发给运营方,运营方 │ -│ 在 License 后台生成绑定该指纹的 License │ +│ 说明:客户将机器指纹发给运营方,运营方通过 │ +│ `ecom-license license generate` 签发 License │ └────────────────┬─────────────────────────┘ ▼ ┌──────────────────────────────────────────┐ @@ -530,6 +537,151 @@ License JWT 支持三种来源,按优先级从高到低: } ``` +### 6.6 CLI 命令与 API 映射 + +CLI 是 License 服务器的**唯一管理端**,不单独提供 Web UI。所有运营操作通过 `ecom-license` 命令调用上述 REST API。 + +#### 6.6.1 命令总览 + +``` +ecom-license +├── login [--url] [--username] [--password] # 登录,Token 写入本地配置 +├── logout # 清除本地 Token +├── whoami # 当前 API 地址与登录用户 +│ +├── stats [--json] # GET /api/dashboard/stats +│ +├── customer +│ ├── list [--page] [--size] [--json] # GET /api/customers +│ ├── create [--code] [--name] ... # POST /api/customers(缺参时交互) +│ ├── show [--json] # GET /api/customers/:id +│ ├── update [--name] ... # PUT /api/customers/:id +│ ├── delete [--force] # DELETE /api/customers/:id +│ └── licenses [--json] # GET /api/customers/:id/licenses +│ +└── license + ├── list [--customer-id] [--status] [--json] # GET /api/licenses + ├── show [--json] # GET /api/licenses/:id + ├── generate [options] # POST /api/licenses/generate + ├── revoke [--reason] # POST /api/licenses/:id/revoke + └── download [-o license.key] # GET /api/licenses/:id/download +``` + +**全局选项**(所有子命令可用): + +| 选项 | 环境变量 | 说明 | +|------|----------|------| +| `--url ` | `ECOM_LICENSE_API_URL` | API 根地址,如 `https://license.example.com` | +| `--token ` | `ECOM_LICENSE_TOKEN` | 跳过本地配置,直接带 Bearer Token(CI/脚本) | +| `--json` | — | JSON 输出,便于 `jq` 管道 | +| `--quiet` | — | 仅输出结果字段(如 License Key、文件路径) | +| `--yes` | — | 跳过确认(delete、revoke 等) | + +#### 6.6.2 本地配置 + +默认路径:`~/.config/ecom-license/config.json`(可通过 `ECOM_LICENSE_CONFIG` 覆盖)。 + +```json +{ + "apiUrl": "http://localhost:3100", + "token": "eyJhbGciOiJIUzI1NiIs...", + "username": "admin", + "expiresAt": "2026-05-25T12:00:00Z" +} +``` + +优先级:**命令行 flag > 环境变量 > 配置文件**。 + +#### 6.6.3 交互式 vs 非交互式 + +| 场景 | 推荐方式 | 示例 | +|------|----------|------| +| 日常运维 SSH | 交互式 | `ecom-license login` → `ecom-license license generate`(Inquirer 逐步提问) | +| CI / Ansible | 全非交互 | 环境变量注入 Token + 全参数 `generate` | +| 脚本批量 | `--json` + `jq` | `ecom-license customer list --json \| jq '.items[].code'` | + +**签发 License(非交互示例)**: + +```bash +ecom-license license generate \ + --customer-id 1 \ + --company "某某科技有限公司" \ + --fingerprint "FP-A1B2C3D4E5F67890..." \ + --edition enterprise \ + --expires-at 2027-01-01 \ + --features order-import \ + --json +``` + +**SaaS 不限指纹**: + +```bash +ecom-license license generate \ + --customer-id 2 \ + --company "SaaS 平台" \ + --fingerprint "*" \ + --edition unlimited \ + --expires-at 2028-01-01 +``` + +#### 6.6.4 输出规范 + +**人类可读(默认)**:使用 `chalk` 着色;表格用 `cli-table3`;成功/错误明确分行。 + +**JSON 模式**(`--json`):统一 envelope: + +```json +{ + "ok": true, + "data": { }, + "meta": { "command": "license generate", "apiUrl": "http://localhost:3100" } +} +``` + +错误时 `ok: false`,`error: { "code": "...", "message": "..." }`,进程 exit code 非 0。 + +**安静模式**(`--quiet`):`generate` 只打印 JWT 一行;`download` 只打印文件路径。 + +#### 6.6.5 CLI 技术栈 + +| 项 | 选型 | 说明 | +|----|------|------| +| 运行时 | Node.js ≥ 20 | 与 NestJS 同生态 | +| 命令框架 | **Commander.js** | 子命令、全局 option | +| 交互 | **@inquirer/prompts** | login、generate 缺参时提问 | +| HTTP | **axios** | 与 server 共用类型时可抽 `packages/shared` | +| 配置 | **conf** 或自研 JSON | 读写 `~/.config/ecom-license` | +| 打包 | **tsup** | 产出单文件 `dist/cli.js`,npm bin `ecom-license` | + +#### 6.6.6 典型 CLI 工作流 + +**新客户私有部署(对应 12.1)**: + +```bash +ecom-license login --url https://license.internal +ecom-license customer create --name "某某科技" --contact-name "张三" +ecom-license license generate # 交互输入客户提供的 FP-xxx +ecom-license license download -o customer-001.key +# 将 Key 或 .key 文件发给客户 +``` + +**续期(对应 12.3)**: + +```bash +ecom-license customer licenses 1 +ecom-license license generate \ + --customer-id 1 \ + --fingerprint "FP-原有指纹..." \ + --edition enterprise \ + --expires-at 2028-01-01 +``` + +**吊销**: + +```bash +ecom-license license revoke 42 --reason "合同终止" --yes +``` + --- ## 7. License 服务器数据库设计 @@ -997,19 +1149,22 @@ public class LicenseAspect { | 语言 | **TypeScript** | 类型安全 | | 数据库 | **MySQL 8.0** | 与主应用保持一致 | | ORM | **TypeORM** | NestJS 生态,与 MySQL 配合 | -| 认证 | **Passport + JWT** | 管理后台登录 | +| 认证 | **Passport + JWT** | CLI / API 登录,Bearer Token | | JWT 签名 | **node-rsa / jsonwebtoken** | RS256 算法 | -### 9.2 License 管理后台 +### 9.2 License 管理 CLI | 层 | 技术 | 说明 | |----|------|------| -| 框架 | **Vue 3** | Composition API | -| UI 库 | **Ant Design Vue** | 与主应用前端保持一致 | -| 构建 | **Vite** | 快速构建 | -| 路由 | **Vue Router 4** | 前端路由 | -| 状态 | **Pinia** | 状态管理 | -| HTTP | **Axios** | HTTP 请求 | +| 运行时 | **Node.js ≥ 20** | 与 NestJS 同仓库 monorepo | +| 命令行 | **Commander.js** | 子命令与全局选项 | +| 交互 | **@inquirer/prompts** | login、generate 等缺参时向导 | +| HTTP | **Axios** | 调用 NestJS REST API | +| 配置 | **~/.config/ecom-license/config.json** | 缓存 apiUrl、token | +| 输出 | **chalk + cli-table3** | 终端表格与状态色 | +| 打包 | **tsup** | 全局命令 `ecom-license` | + +> **不再建设** Vue / Vite / Ant Design Vue 管理后台(`admin/`)。若未来需要只读仪表盘,可考虑独立 Grafana 或 CLI `stats --watch`,而非恢复 Web UI。 ### 9.3 主应用 License 模块 @@ -1027,7 +1182,8 @@ public class LicenseAspect { ``` ecom-license/ # ⚠ 新建目录:License 授权管理平台 ├── DESIGN.md # 本设计文档 -├── docker-compose.yml # Docker 编排 +├── package.json # npm workspaces 根(server + cli) +├── docker-compose.yml # Docker 编排(仅 server + MySQL) ├── .env.example # 环境变量模板 │ ├── server/ # NestJS 后端 ← 新建 @@ -1052,22 +1208,20 @@ ecom-license/ # ⚠ 新建目录:License 授权管理 │ ├── tsconfig.json │ └── nest-cli.json │ -└── admin/ # Vue 3 + Ant Design Vue 管理后台 ← 新建 +└── cli/ # ecom-license CLI ← 新建(替代原 admin/) ├── src/ - │ ├── main.ts - │ ├── App.vue - │ ├── router/index.ts - │ ├── stores/ (auth, app) - │ ├── api/ (auth, customer, license) - │ ├── views/ - │ │ ├── login/ - │ │ ├── dashboard/ - │ │ ├── customer/ - │ │ └── license/ - │ └── components/ - ├── package.json - ├── vite.config.ts - └── tsconfig.json + │ ├── index.ts # Commander 入口 + │ ├── config.ts # 读写 ~/.config/ecom-license + │ ├── client.ts # Axios 封装 + 401 处理 + │ ├── output.ts # 表格 / JSON / quiet + │ └── commands/ + │ ├── login.ts + │ ├── customer.ts + │ ├── license.ts + │ └── stats.ts + ├── package.json # bin: { "ecom-license": "./dist/index.js" } + ├── tsconfig.json + └── tsup.config.ts ``` 以下为**现有项目**中需新增或修改的部分: @@ -1186,11 +1340,11 @@ ecom: 4. 填写公司信息 5. 页面显示机器指纹:FP-A1B2C3... ──────────────────────────────────────────▶ 6. 收到客户提供的机器指纹 - 7. 登录 License 后台 - 8. 创建客户资料 - 9. 在后台填写机器指纹并签发 License - 10. 下载 License 文件 / 复制 License Key - ◀────────────────────────────────────────── 11. 将 License Key 发给客户 + 7. ecom-license login + 8. ecom-license customer create ... + 9. ecom-license license generate --fingerprint FP-A1B2C3... + 10. ecom-license license download -o xxx.key + ◀────────────────────────────────────────── 11. 将 License Key 或 .key 文件发给客户 12. 粘贴 License Key 并点击激活 13. 系统校验通过 → 初始化完成 14. 进入系统,正常使用 @@ -1203,7 +1357,7 @@ ecom: ─── 1. 部署 Ecom-DMB(SaaS 环境) 2. 初始化系统,绑定 SaaS 服务器机器指纹 -3. 在 License 后台为每个租户签发 License +3. 用 CLI 为每个租户签发 License(`ecom-license license generate`) 4. 新租户注册时,系统自动或手动分配 License 5. 每个租户导入订单时校验所属 License 是否有效 ``` @@ -1212,8 +1366,8 @@ ecom: ``` 1. 客户联系运营方续期 -2. 运营方在 License 后台找到该客户 -3. 用相同的机器指纹签发新 License(更新有效期) +2. 运营方:`ecom-license customer show ` / `customer licenses ` +3. 用相同机器指纹签发新 License(`license generate --expires-at ...`) 4. 将新的 License Key 发给客户 5. 客户在「系统设置 → License」页面更新 License 6. 系统校验通过,完成续期 @@ -1226,7 +1380,7 @@ ecom: 2. 在新服务器上部署 Ecom-DMB 3. 进入初始化页面,获取新服务器的机器指纹(安装 ID + 主机名) 4. 将新指纹发给运营方 -5. 运营方吊销旧 License(将旧 JWT 的 jti 加入黑名单),用新指纹签发新 License +5. 运营方:`ecom-license license revoke `,再 `license generate --fingerprint <新指纹>` 6. 客户激活 → 迁移完成 7. 旧服务器的下次请求会因指纹不匹配或 jti 已吊销而失效 ``` @@ -1241,7 +1395,7 @@ ecom: | License 来源 | 运营方签发后客户手动激活 | 运营方直接签发并配置 | | 机器指纹 | 客户服务器的安装 ID + 主机名,严格绑定 | License 中指纹填 `*`,跳过指纹校验 | | 初始化流程 | 客户自行完成初始化向导 | 运营方部署时完成初始化 | -| License 更新 | 客户手动更新 License | 运营方在后台更新或自动下发 | +| License 更新 | 客户手动更新 License | 运营方通过 CLI 更新或自动下发 | | 地址限制 | 绑定一台服务器 | 不限服务器 | --- @@ -1274,4 +1428,4 @@ ecom: - **批量部署**:支持预生成 License,客户部署时自动激活(静默安装) - **License 监控**:License 即将过期时在系统内推送通知 - **多服务器**:支持集群部署的 License 校验(允许同一客户的多台服务器共享一个 License) -- **分级权限**:License 后台支持多级管理员 +- **分级权限**:CLI 侧支持多管理员账号;后续可加 `ecom-license admin *` 子命令 diff --git a/ecom-script/.gitignore b/ecom-script/.gitignore new file mode 100644 index 00000000..504afef8 --- /dev/null +++ b/ecom-script/.gitignore @@ -0,0 +1,2 @@ +node_modules/ +package-lock.json diff --git a/ecom-script/main.js b/ecom-script/main.js new file mode 100755 index 00000000..e9b2cb1b --- /dev/null +++ b/ecom-script/main.js @@ -0,0 +1,282 @@ +#!/usr/bin/env node +import { Command } from 'commander'; +import { createConnection } from './src/db.js'; +import { verifyCompany, fetchSpecs, fetchShops, fetchStatuses } from './src/fetcher.js'; +import { generateOrders, formatDate } from './src/generator.js'; +import { deleteExistingOrders, insertOrders } from './src/inserter.js'; +import { promptMissingOptions, pickRandomSpecs } from './src/prompt.js'; + +function parsePriceRange(str) { + if (!str) return null; + const parts = str.split('-'); + if (parts.length === 1) return [Number(parts[0]), Number(parts[0])]; + return [Number(parts[0]), Number(parts[1])]; +} + +const program = new Command(); + +program + .name('seed-orders') + .description('为指定公司的商品规格批量生成测试订单') + .option('-c, --company ', '公司ID(必填)') + .option('-s, --spec ', '商品规格ID或spec_code(逗号分隔;不传则随机选)') + .option('--spec-count ', '随机选取几个规格(配合 -s 不传时使用)', '5') + .option('--start-date ', '开始日期 (YYYY-MM-DD)') + .option('--end-date ', '结束日期 (YYYY-MM-DD)') + .option('--daily-min ', '每店每日最少订单数', '1') + .option('--daily-max ', '每店每日最多订单数', '5') + .option('--shop ', '店铺ID(逗号分隔)') + .option('-p, --unit-price ', '单价区间,如 "19.9-99.9"') + .option('--status ', '订单状态ID(逗号分隔)') + .option('--confirm <0|1>', '确认标记', '1') + .option('--delete-existing', '先清空指定规格的已有订单再刷入') + .option('--dry-run', '试运行,只预览不写入') + .option('-i, --interactive', '交互模式') + .option('-v, --verbose', '详细输出') + .addHelpText('after', ` +示例: + $ npm run seed -- -c 3 -s 845,842 --daily-min 3 --daily-max 8 --start-date 2026-05-01 --end-date 2026-05-28 + $ npm run seed -- -c 3 -s SLJ007,YQ068 --shop 6,7 --daily-min 2 --daily-max 10 --delete-existing --verbose + $ npm run seed:interactive # 交互模式 + `) + .parse(process.argv); + +const opts = program.opts(); + +async function main() { + const interactive = opts.interactive || process.argv.slice(2).length === 0; + const DAYS_AGO = 30; + const now = new Date(); + + // Default date values + let startDate = opts.startDate ? new Date(opts.startDate + 'T00:00:00') : new Date(now - DAYS_AGO * 86400000); + let endDate = opts.endDate ? new Date(opts.endDate + 'T23:59:59') : now; + + let companyId = opts.company ? Number(opts.company) : undefined; + let specEntries = opts.spec ? opts.spec.split(',').map(s => s.trim()).filter(Boolean) : []; + let shopIds = opts.shop ? opts.shop.split(',').map(s => Number(s.trim())).filter(n => !isNaN(n)) : undefined; + let statusIds = opts.status ? opts.status.split(',').map(s => Number(s.trim())).filter(n => !isNaN(n)) : undefined; + let dailyMin = Number(opts.dailyMin); + let dailyMax = Number(opts.dailyMax); + let unitPrice = opts.unitPrice; + let confirm = opts.confirm !== undefined ? Number(opts.confirm) : 1; + let deleteExisting = opts.deleteExisting || false; + const dryRun = opts.dryRun || false; + const verbose = opts.verbose || false; + + const conn = await createConnection(opts); + + try { + // Interactive mode: fetch reference data first + if (interactive) { + console.log('=== 交互模式 ===\n'); + + // Fetch companies + const [companies] = await conn.execute('SELECT id, name FROM org_company ORDER BY id'); + if (companies.length === 0) { + console.error('No companies found in database.'); + process.exit(1); + } + + // Let user pick company + const companyAnswers = await promptMissingOptions({ + company: undefined, + companyList: companies, + }); + companyId = companyAnswers.company; + + const company = await verifyCompany(conn, companyId); + + // Fetch specs for this company + const specList = await fetchSpecs(conn, companyId); + if (specList.length === 0) { + console.error(`No specs found for company ${companyId}.`); + process.exit(1); + } + + // Fetch all shops for this company + const shopList = await fetchShops(conn, companyId, [...new Set(specList.map(s => s.product_id))]); + if (shopList.length === 0) { + console.error(`No shops found for company ${companyId}.`); + process.exit(1); + } + + // Fetch all statuses for this company + const statusList = await fetchStatuses(conn, companyId); + if (statusList.length === 0) { + console.error(`No order statuses found for company ${companyId}.`); + process.exit(1); + } + + const sd = formatDate(startDate); + const ed = formatDate(endDate); + + const answers = await promptMissingOptions({ + company: companyId, + specs: [], + specList, + shops: [], + shopList, + statuses: [], + statusList, + startDate: sd, + endDate: ed, + dailyMin, + dailyMax, + unitPrice: unitPrice || '', + }); + + // Randomly pick specs + const picked = pickRandomSpecs(specList, answers.specCount); + specEntries = picked.map(s => s.spec_code || String(s.id)); + console.log(`随机选中 ${picked.length} 个规格:`); + for (const s of picked) { + console.log(` [${s.id}] ${s.name} (${s.spec_code})`); + } + console.log(''); + shopIds = answers.shops; + statusIds = answers.statuses; + startDate = new Date(answers.startDate + 'T00:00:00'); + endDate = new Date(answers.endDate + 'T23:59:59'); + dailyMin = answers.dailyMin; + dailyMax = answers.dailyMax; + unitPrice = answers.unitPrice || undefined; + deleteExisting = answers.deleteExisting; + + if (!answers.confirmInsert) { + console.log('Cancelled by user.'); + return; + } + } + + const company = await verifyCompany(conn, companyId); + + let specs; + if (specEntries.length === 0) { + const allSpecs = await fetchSpecs(conn, companyId); + if (allSpecs.length === 0) { + console.error(`公司 ${companyId} 下没有商品规格`); + process.exit(1); + } + const specCount = Math.min(Number(opts.specCount), allSpecs.length); + specs = pickRandomSpecs(allSpecs, specCount); + console.log(`随机选中 ${specs.length} 个规格:`); + for (const s of specs) { + console.log(` [${s.id}] ${s.name} (${s.spec_code})`); + } + } else { + const specIds = specEntries.filter(s => /^\d+$/.test(s)).map(Number); + const specCodes = specEntries.filter(s => !/^\d+$/.test(s)); + specs = await fetchSpecs(conn, companyId, specIds, specCodes); + } + if (specs.length === 0) { + console.error(`Error: No specs found for company ${companyId}`); + process.exit(1); + } + const productIds = [...new Set(specs.map(s => s.product_id))]; + + // Fetch shops + const shops = await fetchShops(conn, companyId, productIds, shopIds); + if (shops.length === 0) { + console.error(`Error: No shops found for company ${companyId}`); + process.exit(1); + } + + // Fetch statuses + const statuses = await fetchStatuses(conn, companyId, statusIds); + if (statuses.length === 0) { + console.error(`Error: No order statuses found for company ${companyId}`); + process.exit(1); + } + + if (dailyMin < 0 || dailyMax < 0 || dailyMin > dailyMax) { + console.error('Error: --daily-min must be >= 0 and <= --daily-max'); + process.exit(1); + } + + const dayCount = Math.floor((endDate - startDate) / 86400000) + 1; + const shopDailyAvg = (dailyMin + dailyMax) / 2; + const estimatedTotal = Math.ceil(specs.length * shops.length * dayCount * shopDailyAvg); + + console.log(`\nCompany: ${company.name} (${company.id})`); + console.log(`Period: ${formatDate(startDate)} ~ ${formatDate(endDate)} (${dayCount} days)`); + console.log(`Daily range: ${dailyMin} ~ ${dailyMax} orders/shop/day`); + console.log(`Specs: ${specs.length}`); + if (verbose) { + for (const s of specs) { + console.log(` [${s.id}] ${s.name} (${s.spec_code})`); + } + } + console.log(`Shops: ${shops.length}`); + if (verbose) { + for (const sh of shops) { + console.log(` [${sh.id}] ${sh.name}`); + } + } + console.log(`Statuses: ${statuses.length}`); + console.log(`Estimated total: ~${estimatedTotal} orders`); + console.log(`Delete existing: ${deleteExisting ? 'YES' : 'no'}`); + console.log(`Dry run: ${dryRun ? 'YES' : 'no'}`); + console.log(''); + + // Delete existing if requested + if (deleteExisting && !dryRun) { + console.log('Deleting existing orders...'); + const deleted = await deleteExistingOrders(conn, companyId, specs, verbose); + console.log(`Deleted ${deleted} existing orders.\n`); + } + + // Generate orders + const seenOrderNos = new Set(); + const remarkPool = [ + null, null, null, + '测试数据,请忽略', + '系统生成测试订单', + null, null, + ]; + + const orders = generateOrders({ + companyId, + specs, + shops, + statuses, + priceRange: parsePriceRange(unitPrice), + dailyMin, + dailyMax, + confirm, + startDate, + endDate, + seenOrderNos, + remarkPool, + }); + + console.log(`Generated ${orders.length} orders.`); + + if (dryRun) { + const samples = orders.slice(0, 5); + if (samples.length > 0) { + console.log('\nSample orders:'); + for (const o of samples) { + console.log(` ${o.platform_order_no} | shop=${o.shop_id} | spec=[${o.product_spec_id}] | qty=${o.quantity} | price=${o.unit_price} | received=${o.received_amount} | ${o.order_time}`); + } + if (orders.length > 5) { + console.log(` ... and ${orders.length - 5} more`); + } + } + console.log('\nDry run completed. No data inserted.'); + return; + } + + // Insert orders + console.log('Inserting orders...'); + const { inserted, failed } = await insertOrders(conn, orders, verbose); + console.log(`\nDone. Inserted: ${inserted}, Failed: ${failed}, Total: ${orders.length}`); + } finally { + await conn.end(); + } +} + +main().catch(err => { + console.error('Fatal error:', err.message); + process.exit(1); +}); diff --git a/ecom-script/package.json b/ecom-script/package.json new file mode 100644 index 00000000..b8128d1f --- /dev/null +++ b/ecom-script/package.json @@ -0,0 +1,19 @@ +{ + "name": "ecom-script", + "version": "1.0.0", + "private": true, + "description": "ECOM data seed scripts", + "type": "module", + "scripts": { + "seed": "node main.js", + "seed:help": "node main.js --help", + "seed:interactive": "node main.js -i" + }, + "dependencies": { + "@inquirer/prompts": "^8.5.0", + "cli-progress": "^3.12.0", + "commander": "^14.0.3", + "inquirer": "^9.3.8", + "mysql2": "^3.14.0" + } +} diff --git a/ecom-script/src/db.js b/ecom-script/src/db.js new file mode 100644 index 00000000..fb04cb62 --- /dev/null +++ b/ecom-script/src/db.js @@ -0,0 +1,14 @@ +import mysql from 'mysql2/promise'; + +export async function createConnection(opts) { + const config = { + host: opts.dbHost || '192.168.3.100', + port: opts.dbPort || 3306, + user: opts.dbUser || 'ecom_dmb_dev', + password: opts.dbPassword || 'ecom_dmb_dev', + database: opts.dbName || 'ecom_dmb_dev', + }; + + const conn = await mysql.createConnection(config); + return conn; +} diff --git a/ecom-script/src/fetcher.js b/ecom-script/src/fetcher.js new file mode 100644 index 00000000..6e1f1ff1 --- /dev/null +++ b/ecom-script/src/fetcher.js @@ -0,0 +1,101 @@ +export async function verifyCompany(conn, companyId) { + const [rows] = await conn.execute('SELECT id, name FROM org_company WHERE id = ?', [companyId]); + if (rows.length === 0) { + throw new Error(`Company with id ${companyId} not found`); + } + return rows[0]; +} + +export async function fetchSpecs(conn, companyId, specIds, specCodes) { + const results = []; + + if (specIds && specIds.length > 0) { + const placeholders = specIds.map(() => '?').join(','); + const [rows] = await conn.execute( + `SELECT ps.*, p.name AS product_name, p.product_code + FROM ec_product_spec ps + JOIN ec_product p ON ps.product_id = p.id + WHERE ps.company_id = ? AND ps.id IN (${placeholders})`, + [companyId, ...specIds] + ); + results.push(...rows); + } + + if (specCodes && specCodes.length > 0) { + const placeholders = specCodes.map(() => '?').join(','); + const [rows] = await conn.execute( + `SELECT ps.*, p.name AS product_name, p.product_code + FROM ec_product_spec ps + JOIN ec_product p ON ps.product_id = p.id + WHERE ps.company_id = ? AND ps.spec_code IN (${placeholders})`, + [companyId, ...specCodes] + ); + results.push(...rows); + } + + if (specIds === undefined && specCodes === undefined) { + const [rows] = await conn.execute( + `SELECT ps.*, p.name AS product_name, p.product_code + FROM ec_product_spec ps + JOIN ec_product p ON ps.product_id = p.id + WHERE ps.company_id = ?`, + [companyId] + ); + results.push(...rows); + } + + const seen = new Set(); + return results.filter(s => { + if (seen.has(s.id)) return false; + seen.add(s.id); + return true; + }); +} + +export async function fetchShops(conn, companyId, productIds, shopIds) { + if (shopIds && shopIds.length > 0) { + const placeholders = shopIds.map(() => '?').join(','); + const [rows] = await conn.execute( + `SELECT id, name, platform_id FROM ec_shop + WHERE company_id = ? AND id IN (${placeholders})`, + [companyId, ...shopIds] + ); + return rows; + } + + if (!productIds || productIds.length === 0) { + const [rows] = await conn.execute( + 'SELECT id, name, platform_id FROM ec_shop WHERE company_id = ?', + [companyId] + ); + return rows; + } + + const productPlaceholders = productIds.map(() => '?').join(','); + const [rows] = await conn.execute( + `SELECT DISTINCT s.id, s.name, s.platform_id + FROM ec_shop s + JOIN ec_shop_product_relation spr ON s.id = spr.shop_id + WHERE s.company_id = ? AND spr.product_id IN (${productPlaceholders})`, + [companyId, ...productIds] + ); + return rows; +} + +export async function fetchStatuses(conn, companyId, statusIds) { + if (statusIds && statusIds.length > 0) { + const placeholders = statusIds.map(() => '?').join(','); + const [rows] = await conn.execute( + `SELECT id, status_name FROM ec_order_status + WHERE company_id = ? AND id IN (${placeholders})`, + [companyId, ...statusIds] + ); + return rows; + } + + const [rows] = await conn.execute( + 'SELECT id, status_name FROM ec_order_status WHERE company_id = ? ORDER BY sort_order', + [companyId] + ); + return rows; +} diff --git a/ecom-script/src/generator.js b/ecom-script/src/generator.js new file mode 100644 index 00000000..e58e9288 --- /dev/null +++ b/ecom-script/src/generator.js @@ -0,0 +1,116 @@ +export function rand(min, max) { + return Math.random() * (max - min) + min; +} + +export function randInt(min, max) { + return Math.floor(rand(min, max + 1)); +} + +export function randomDate(start, end) { + return new Date(start.getTime() + Math.random() * (end.getTime() - start.getTime())); +} + +export function formatDateTime(d) { + const y = d.getFullYear(); + const M = String(d.getMonth() + 1).padStart(2, '0'); + const D = String(d.getDate()).padStart(2, '0'); + const h = String(d.getHours()).padStart(2, '0'); + const m = String(d.getMinutes()).padStart(2, '0'); + const s = String(d.getSeconds()).padStart(2, '0'); + return `${y}-${M}-${D} ${h}:${m}:${s}`; +} + +export function formatDate(d) { + const y = d.getFullYear(); + const M = String(d.getMonth() + 1).padStart(2, '0'); + const D = String(d.getDate()).padStart(2, '0'); + return `${y}-${M}-${D}`; +} + +export function generatePlatformOrderNo(companyId, seenSet) { + for (let attempt = 0; attempt < 100; attempt++) { + const ts = Date.now().toString(36).toUpperCase(); + const randStr = Math.random().toString(36).substring(2, 10).toUpperCase(); + const no = `${ts}-${companyId}${randStr}`; + if (!seenSet.has(no)) { + seenSet.add(no); + return no; + } + } + throw new Error('Unable to generate unique platform order number'); +} + +export function generateOrders(config) { + const { + companyId, specs, shops, statuses, priceRange, + dailyMin, dailyMax, confirm, + startDate, endDate, seenOrderNos, + remarkPool, + } = config; + + const orders = []; + + for (const spec of specs) { + let current = new Date(startDate); + const end = new Date(endDate); + + while (current <= end) { + const dayStart = new Date(current); + const dayEnd = new Date(current); + dayEnd.setHours(23, 59, 59, 999); + + for (const shop of shops) { + const count = randInt(dailyMin, dailyMax); + for (let i = 0; i < count; i++) { + const status = statuses[randInt(0, statuses.length - 1)]; + const orderTime = randomDate(dayStart, dayEnd); + const quantity = randInt(1, 5); + + let unitPrice; + if (priceRange) { + unitPrice = Math.round(rand(priceRange[0], priceRange[1]) * 100) / 100; + } else { + const baseCost = Number(spec.product_cost); + if (baseCost >= 10) { + unitPrice = Math.round(baseCost * rand(1.3, 3.0) * 100) / 100; + } else if (baseCost > 0) { + unitPrice = Math.round(rand(9.9, 59.9) * 100) / 100; + } else { + unitPrice = Math.round(rand(9.9, 99.9) * 100) / 100; + } + } + if (unitPrice < 1) unitPrice = Math.round(rand(9.9, 49.9) * 100) / 100; + + const receivedAmount = Math.round(unitPrice * quantity * rand(0.85, 1.0) * 100) / 100; + const platformOrderNo = generatePlatformOrderNo(companyId, seenOrderNos); + const remark = remarkPool[randInt(0, remarkPool.length - 1)]; + + orders.push({ + company_id: companyId, + shop_id: shop.id, + product_spec_id: spec.id, + spec_code: spec.spec_code, + status_id: status.id, + platform_order_no: platformOrderNo, + link_product_name: spec.product_name, + link_spec_name: spec.name, + received_amount: receivedAmount, + quantity, + unit_price: unitPrice, + product_cost: spec.product_cost, + shipping_cost: spec.shipping_cost, + other_cost: spec.other_cost, + remark, + import_task_id: null, + confirm, + order_time: formatDateTime(orderTime), + }); + } + } + + current.setDate(current.getDate() + 1); + } + } + + return orders; +} diff --git a/ecom-script/src/inserter.js b/ecom-script/src/inserter.js new file mode 100644 index 00000000..6d7e516d --- /dev/null +++ b/ecom-script/src/inserter.js @@ -0,0 +1,59 @@ +import cliProgress from 'cli-progress'; + +export async function deleteExistingOrders(conn, companyId, specs, verbose) { + let total = 0; + for (const spec of specs) { + const [result] = await conn.execute( + 'DELETE FROM ec_order WHERE company_id = ? AND product_spec_id = ?', + [companyId, spec.id] + ); + total += result.affectedRows; + if (verbose) { + console.log(` Deleted ${result.affectedRows} orders for spec [${spec.id}] ${spec.name}`); + } + } + return total; +} + +export async function insertOrders(conn, orders, verbose) { + const sql = `INSERT INTO ec_order + (company_id, shop_id, product_spec_id, spec_code, status_id, platform_order_no, + link_product_name, link_spec_name, received_amount, quantity, unit_price, + product_cost, shipping_cost, other_cost, remark, import_task_id, confirm, order_time) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NULL, ?, ?)`; + + const total = orders.length; + let inserted = 0; + let failed = 0; + + const bar = new cliProgress.SingleBar({ + format: '刷入进度 |{bar}| {percentage}% | {value}/{total} 条 | 成功: {inserted} 失败: {failed}', + barCompleteChar: '█', + barIncompleteChar: '░', + hideCursor: true, + }, cliProgress.Presets.shades_classic); + + bar.start(total, 0, { inserted: 0, failed: 0 }); + + for (let i = 0; i < orders.length; i++) { + const o = orders[i]; + try { + await conn.execute(sql, [ + o.company_id, o.shop_id, o.product_spec_id, o.spec_code, o.status_id, o.platform_order_no, + o.link_product_name, o.link_spec_name, o.received_amount, o.quantity, o.unit_price, + o.product_cost, o.shipping_cost, o.other_cost, + o.remark, o.confirm, o.order_time, + ]); + inserted++; + } catch (err) { + failed++; + if (verbose) { + bar.log(` Failed: ${err.message}\n`); + } + } + bar.update(i + 1, { inserted, failed }); + } + + bar.stop(); + return { inserted, failed }; +} diff --git a/ecom-script/src/prompt.js b/ecom-script/src/prompt.js new file mode 100644 index 00000000..b9b641a6 --- /dev/null +++ b/ecom-script/src/prompt.js @@ -0,0 +1,206 @@ +import inquirer from 'inquirer'; + +export async function promptMissingOptions(options) { + const { + company, companyList, + specs, specList, + shops, shopList, + statuses, statusList, + } = options; + + const prompts = []; + + if (!company && companyList) { + prompts.push({ + type: 'list', + name: 'company', + message: '选择公司:', + choices: companyList.map(c => ({ name: `[${c.id}] ${c.name}`, value: c.id })), + pageSize: 15, + }); + } + + if (company) { + prompts.push({ + type: 'list', + name: 'datePreset', + message: '选择时间范围:', + choices: [ + { name: '最近 7 天', value: '7d' }, + { name: '最近 30 天', value: '30d' }, + { name: '最近 90 天', value: '90d' }, + { name: '本月', value: 'thisMonth' }, + { name: '上月', value: 'lastMonth' }, + { name: '自定义', value: 'custom' }, + ], + }); + + { + 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'); + const today = `${y}-${m}-${d}`; + const monthStart = `${y}-${m}-01`; + const lastM = now.getMonth() === 0 ? 12 : now.getMonth(); + const lastY = now.getMonth() === 0 ? y - 1 : y; + const lastMonthStr = `${lastY}-${String(lastM).padStart(2, '0')}-01`; + + prompts.push({ + type: 'input', + name: 'startDate', + message: '开始日期 (YYYY-MM-DD):', + default: options.startDate, + when: a => a.datePreset === 'custom', + validate: v => /^\d{4}-\d{2}-\d{2}$/.test(v) || '格式: YYYY-MM-DD', + }); + + prompts.push({ + type: 'input', + name: 'endDate', + message: '结束日期 (YYYY-MM-DD):', + default: options.endDate, + when: a => a.datePreset === 'custom', + validate: v => /^\d{4}-\d{2}-\d{2}$/.test(v) || '格式: YYYY-MM-DD', + }); + } + + if ((!specs || specs.length === 0) && specList) { + prompts.push({ + type: 'number', + name: 'specCount', + message: `随机选取几个规格刷单?(共有 ${specList.length} 个):`, + default: Math.min(5, specList.length), + validate: v => (v > 0 && v <= specList.length) || `请输入 1~${specList.length}`, + }); + } + + if ((!shops || shops.length === 0) && shopList) { + prompts.push({ + type: 'checkbox', + name: 'shops', + message: '选择店铺(空格勾选):', + choices: shopList.map(sh => ({ + name: `[${sh.id}] ${sh.name}`, + value: sh.id, + checked: true, + })), + pageSize: 15, + validate: v => v.length > 0 || '至少选一个店铺', + }); + } + + if ((!statuses || statuses.length === 0) && statusList) { + prompts.push({ + type: 'checkbox', + name: 'statuses', + message: '选择订单状态(空格勾选):', + choices: statusList.map(st => ({ + name: `[${st.id}] ${st.status_name}`, + value: st.id, + checked: true, + })), + pageSize: 15, + validate: v => v.length > 0 || '至少选一个状态', + }); + } + + prompts.push({ + type: 'input', + name: 'dailyRange', + message: '每店每日单量区间 (如 "3-8"):', + default: `${options.dailyMin ?? 1}-${options.dailyMax ?? 5}`, + validate: v => /^\d+-\d+$/.test(v) || '格式: 最小-最大 (如 3-8)', + }); + + prompts.push({ + type: 'input', + name: 'unitPrice', + message: '单价区间 (如 "19.9-99.9",留空自动生成):', + default: options.unitPrice || '', + }); + + prompts.push({ + type: 'confirm', + name: 'deleteExisting', + message: '是否先清空这些规格的已有订单?', + default: false, + }); + + prompts.push({ + type: 'confirm', + name: 'confirmInsert', + message: '确认写入数据库?', + default: true, + }); + } + + const answers = await inquirer.prompt(prompts); + + if (answers.datePreset && answers.datePreset !== 'custom') { + const now = new Date(); + const y = now.getFullYear(); + const m = now.getMonth() + 1; + const d = now.getDate(); + const pad = (n) => String(n).padStart(2, '0'); + + switch (answers.datePreset) { + case '7d': { + const sd = new Date(now); + sd.setDate(d - 6); + answers.startDate = `${sd.getFullYear()}-${pad(sd.getMonth() + 1)}-${pad(sd.getDate())}`; + answers.endDate = `${y}-${pad(m)}-${pad(d)}`; + break; + } + case '30d': { + const sd = new Date(now); + sd.setDate(d - 29); + answers.startDate = `${sd.getFullYear()}-${pad(sd.getMonth() + 1)}-${pad(sd.getDate())}`; + answers.endDate = `${y}-${pad(m)}-${pad(d)}`; + break; + } + case '90d': { + const sd = new Date(now); + sd.setDate(d - 89); + answers.startDate = `${sd.getFullYear()}-${pad(sd.getMonth() + 1)}-${pad(sd.getDate())}`; + answers.endDate = `${y}-${pad(m)}-${pad(d)}`; + break; + } + case 'thisMonth': + answers.startDate = `${y}-${pad(m)}-01`; + answers.endDate = `${y}-${pad(m)}-${pad(d)}`; + break; + case 'lastMonth': { + const lm = m === 1 ? 12 : m - 1; + const ly = m === 1 ? y - 1 : y; + const lastMonthEnd = new Date(y, m - 1, 0); + answers.startDate = `${ly}-${pad(lm)}-01`; + answers.endDate = `${ly}-${pad(lm)}-${pad(lastMonthEnd.getDate())}`; + break; + } + } + delete answers.datePreset; + } + + if (answers.dailyRange) { + const parts = answers.dailyRange.split('-').map(Number); + answers.dailyMin = parts[0]; + answers.dailyMax = parts[1]; + delete answers.dailyRange; + } + + return answers; +} + +function shuffle(arr) { + for (let i = arr.length - 1; i > 0; i--) { + const j = Math.floor(Math.random() * (i + 1)); + [arr[i], arr[j]] = [arr[j], arr[i]]; + } + return arr; +} + +export function pickRandomSpecs(specList, count) { + const shuffled = shuffle([...specList]); + return shuffled.slice(0, Math.min(count, specList.length)); +}