Commit 228258f5 by 张立顺

feat 开发agent模式也能新增接口接入

1 parent a65a43d5
...@@ -13,6 +13,8 @@ ...@@ -13,6 +13,8 @@
| 契约 diff | [`src/libs/rop/contractDiff.js`](../../src/libs/rop/contractDiff.js) | | 契约 diff | [`src/libs/rop/contractDiff.js`](../../src/libs/rop/contractDiff.js) |
| Swagger 快照 | [`src/libs/rop/__snapshots__/smartcarlife.swagger.json`](../../src/libs/rop/__snapshots__/smartcarlife.swagger.json) | | Swagger 快照 | [`src/libs/rop/__snapshots__/smartcarlife.swagger.json`](../../src/libs/rop/__snapshots__/smartcarlife.swagger.json) |
| 脚手架 CLI | `npm run rop:swagger -- [--prefix\|--method] --out <dir> [--dry-run] [--force] [--contracts-only]` | | 脚手架 CLI | `npm run rop:swagger -- [--prefix\|--method] --out <dir> [--dry-run] [--force] [--contracts-only]` |
| 一键导入 CLI | `npm run rop:import -- --method <method> [--dry-run] [--force] [--json]` |
| 聊天导入 | [ROP_CHAT_IMPORT.md](./ROP_CHAT_IMPORT.md)(自然语言触发,读 [SKILL.md](../skills/rop-api-import/SKILL.md)) |
| 拉取快照 | `npm run rop:swagger:fetch` | | 拉取快照 | `npm run rop:swagger:fetch` |
| 契约校验 | `npm run rop:contract:check` | | 契约校验 | `npm run rop:contract:check` |
| 一键验证 | `npm run rop:verify` | | 一键验证 | `npm run rop:verify` |
...@@ -146,7 +148,7 @@ export function getXxx(data) { ...@@ -146,7 +148,7 @@ export function getXxx(data) {
} }
``` ```
Mock 开关:`VUE_APP_{FEATURE}_MOCK=false`(参考 `VUE_APP_JOURNAL_MOCK`)。 Mock 开关:`VUE_APP_{FEATURE}_MOCK=true` 时启用(参考 `VUE_APP_JOURNAL_MOCK` / `VUE_APP_ABNORMAL_FLOW_MOCK`),默认走真实接口。
--- ---
...@@ -199,7 +201,7 @@ async function main() { ...@@ -199,7 +201,7 @@ async function main() {
- [ ] 编写/补全 `src/api/adapters/{feature}/` adapters - [ ] 编写/补全 `src/api/adapters/{feature}/` adapters
- [ ] `src/api/*.js` 接入 request + adapter - [ ] `src/api/*.js` 接入 request + adapter
- [ ] Mock 数据对齐 Swagger 字段 - [ ] Mock 数据对齐 Swagger 字段
- [ ] `.env.development`:`VUE_APP_USE_DEVELOP_AXIOS=true`,关闭 feature mock - [ ] `.env.development`:`VUE_APP_USE_DEVELOP_AXIOS=true`,确认未设置 feature mock 开关(或 `VUE_APP_*_MOCK` 非 `true`)
- [ ] `npm run rop:contract:check` 契约基线通过 - [ ] `npm run rop:contract:check` 契约基线通过
- [ ] `npm run api:smoke:journal`(或对应冒烟脚本)通过 - [ ] `npm run api:smoke:journal`(或对应冒烟脚本)通过
- [ ] 浏览器登录验证页面 - [ ] 浏览器登录验证页面
...@@ -252,7 +254,7 @@ async function main() { ...@@ -252,7 +254,7 @@ async function main() {
- [ ] adapter 单测通过(至少覆盖请求映射 + 行映射) - [ ] adapter 单测通过(至少覆盖请求映射 + 行映射)
- [ ] `npm run rop:contract:check` 通过 - [ ] `npm run rop:contract:check` 通过
- [ ] `npm run api:smoke:{feature}` 或 `npm run rop:verify` exit 0 - [ ] `npm run api:smoke:{feature}` 或 `npm run rop:verify` exit 0
- [ ] `.env.development` 已设 `VUE_APP_USE_DEVELOP_AXIOS=true`,feature mock 已关闭 - [ ] `.env.development` 已设 `VUE_APP_USE_DEVELOP_AXIOS=true`,未误开 feature mock(`VUE_APP_*_MOCK=true`)
- [ ] 浏览器页面可访问(需账号具备对应菜单权限) - [ ] 浏览器页面可访问(需账号具备对应菜单权限)
- [ ] 脚手架未误覆盖已有 adapter(默认 skip;必要时才用 `--force`) - [ ] 脚手架未误覆盖已有 adapter(默认 skip;必要时才用 `--force`)
...@@ -263,3 +265,17 @@ npm run rop:verify ...@@ -263,3 +265,17 @@ npm run rop:verify
``` ```
包含 ROP 单测 + 契约校验 + dailyReport 冒烟,用于确认工具链本身可复用。 包含 ROP 单测 + 契约校验 + dailyReport 冒烟,用于确认工具链本身可复用。
---
## 12. 聊天导入
在 Cursor 聊天框用自然语言导入单接口,详见 [ROP_CHAT_IMPORT.md](./ROP_CHAT_IMPORT.md)。
Agent 规程:[`/.ai/skills/rop-api-import/SKILL.md`](../skills/rop-api-import/SKILL.md)
```text
导入接口 dj.api.smartcarlife.pc.abnormalFlowDeclaration.approve(总部运营审批流水报备)
```
流程:dry-run 预览 → 用户确认 → `rop:import` 落盘 → `rop:contract:check`。
# ROP 聊天导入
在 Cursor 聊天框用自然语言导入 ROP 接口,基于本地 Swagger 快照自动生成分层 adapter 并迁移已有 API 函数。
Agent 规程见 [/.ai/skills/rop-api-import/SKILL.md](../skills/rop-api-import/SKILL.md)。
---
## 快速开始
在 Cursor 聊天输入:
```text
导入接口 dj.api.smartcarlife.pc.abnormalFlowDeclaration.approve(总部运营审批流水报备)
```
Agent 将:
1. 从本地 Swagger 快照解析契约(`src/libs/rop/__snapshots__/smartcarlife.swagger.json`)
2. 执行 `npm run rop:import -- ... --dry-run --json` 展示预览
3. 等你回复「确认导入」后落盘
4. 运行 `npm run rop:contract:check` 校验
等价终端命令:
```bash
# 预览
npm run rop:import -- "导入接口 dj.api.smartcarlife.pc.abnormalFlowDeclaration.approve" --dry-run
# 落盘
npm run rop:import -- --method dj.api.smartcarlife.pc.abnormalFlowDeclaration.approve
# 校验
npm run rop:contract:check
```
---
## 流程图
```mermaid
sequenceDiagram
participant User as 用户
participant Agent as Cursor_Agent
participant CLI as rop_import
participant Swagger as 本地快照
User->>Agent: 导入接口 dj.api...
Agent->>CLI: --dry-run --json
CLI->>Swagger: buildContract
CLI-->>Agent: 导入报告
Agent->>User: 预览 + 询问确认
User->>Agent: 确认导入
Agent->>CLI: 正式导入 --json
Agent->>CLI: rop:contract:check
Agent->>User: 汇总结果
```
---
## 与 rop:swagger 的区别
| 维度 | `rop:swagger` | `rop:import`(聊天导入) |
|------|---------------|--------------------------|
| 用途 | 批量生成契约/adapter 模板 | 单接口导入 + 迁移已有 API |
| 自然语言 | 不支持 | 支持 |
| API 文件改写 | 不处理 | 自动 migrateApiFile |
| 聊天场景 | 不适合 | **推荐** |
---
## 导入产出
```text
src/api/adapters/{feature}/
build{Method}Params.js
map{Method}Response.js
__contracts__/{method}.contract.json
__contracts__/{method}.contract.md
```
若 `src/api/*.js` 中已有引用该 method 的 `export function`,将自动迁移为 adapter 模式(函数名不变,Vue 通常无需修改)。
---
## 常见问题
### method 在 Swagger 中找不到
本地快照过旧,先更新:
```bash
npm run rop:swagger:fetch
```
### 文件显示 skipped
默认不覆盖已有契约/adapter。需要覆盖时:
```bash
npm run rop:import -- --method <method> --force
```
### 没有已有 API 函数
`rop:import` 不会自动新建 `export function`,需在 `src/api/*.js` 手工补充,模式见 [ROP_API_INTEGRATION.md](./ROP_API_INTEGRATION.md) §5。
### Mock 未自动迁移
目前仅 `abnormalFlow.mock.js` 支持自动迁移,其他 feature 需手工改 mock。
---
## 验收 checklist
- [ ] 聊天输入 method,Agent 先 dry-run 不写文件
- [ ] 确认后落盘,`rop-import.report.json` 生成
- [ ] `npm run rop:contract:check` 通过
- [ ] Swagger 缺失时提示 `rop:swagger:fetch`
...@@ -13,7 +13,10 @@ ...@@ -13,7 +13,10 @@
"Bash(volta install:*)", "Bash(volta install:*)",
"Bash(where:*)", "Bash(where:*)",
"Bash(volta list:*)", "Bash(volta list:*)",
"Bash(rm:*)" "Bash(rm:*)",
"Bash(npm run rop:import:*)",
"Bash(npm run rop:contract:check:*)",
"Bash(npm run rop:swagger:fetch:*)"
] ]
} }
} }
---
name: rop-api-import
description: >-
从 Cursor 聊天导入 ROP 接口。当用户说「导入接口」「对接接口」「ROP 导入」或消息含
dj.api.smartcarlife.* 时使用。基于本地 Swagger 快照执行 npm run rop:import,
先 dry-run 预览,用户确认后再落盘。
---
# ROP 聊天导入
详细说明见 [ROP_CHAT_IMPORT.md](../../docs/ROP_CHAT_IMPORT.md)。
## 触发条件
满足**任一**即执行本 skill:
| 类型 | 模式 |
|------|------|
| 动词 | `导入接口`、`对接接口`、`ROP 导入`、`swagger 导入` |
| method | 文本含 `dj.api.smartcarlife.` |
| 组合 | `导入` + `dj.api.*` |
**不触发:** 仅讨论字段、仅问接口用法、无导入意图。
## 工作流(必须按顺序)
### 1. 解析 method
从用户原文提取 `dj.api.smartcarlife.*`。用户若指定 `--api` / `--feature`,保留给 CLI。
### 2. dry-run 预览(不落盘)
```bash
npm run rop:import -- "<用户原文或 method>" --dry-run --json
```
解析 stdout JSON,按下方模板回复用户。
### 3. 等待确认
仅当用户明确回复「确认导入」「落盘」「继续」后进入步骤 4。
用户回复「取消」则结束,不执行落盘。
用户明确说「跳过预览直接导入」时,可跳过 dry-run,但仍需告知将写入哪些文件。
### 4. 正式落盘
```bash
npm run rop:import -- --method <method> --json
```
若用户要求覆盖已有文件,加 `--force` 并二次确认。
### 5. 契约校验
```bash
npm run rop:contract:check
```
将结果汇总给用户。
## dry-run 回复模板
```markdown
## ROP 接口导入预览
| 项 | 值 |
|----|-----|
| 接口 | `<method>` |
| 说明 | <summary> |
| Feature | <feature> |
| API 文件 | <apiFile> |
| 已有函数 | <existingFunction 或「无,需手工补 export」> |
**请求参数:** <name* 表示必填,逗号分隔>
**响应:** <responseRoot> <pagination 时标注 (pagination)>
**文件计划:**
- <status>: <path>(逐项列出 files 数组)
数据源:本地 Swagger 快照 `src/libs/rop/__snapshots__/smartcarlife.swagger.json`
确认后我将执行落盘并运行 `npm run rop:contract:check`。回复「确认导入」继续,或「取消」放弃。
```
## 落盘完成回复模板
```markdown
## 导入完成
- 文件变更:(按 files 数组列出 status + path)
- 契约校验:<通过 / 失败及原因>
**后续建议:**
1. 检查 adapter 内字段映射是否符合页面需求
2. 关闭 feature mock 后浏览器验证页面
```
## 错误处理
| 错误 | Agent 动作 |
|------|-----------|
| 未找到 method | 请用户提供完整 `dj.api.smartcarlife.*` |
| Swagger 中未找到 method | 建议 `npm run rop:swagger:fetch` 后重试 dry-run |
| 仅支持 dj.api.smartcarlife.* | 检查 method 拼写 |
| files 多为 skipped | 说明默认不覆盖;覆盖需 `--force` |
| rop:contract:check 失败 | 展示失败信息,建议检查契约 diff |
| 无 existingFunction | 提示在 `src/api/*.js` 手工补 export,参考 [ROP_API_INTEGRATION.md](../../docs/ROP_API_INTEGRATION.md) §5 |
## 禁止事项
- 不要手写 adapter 替代 CLI(CLI 失败且用户明确要求手工补除外)
- 不要在 Vue 页面引用 `ropClient`
- 不要未经确认直接落盘(用户明确跳过预览除外)
- 不要误用 `rop:swagger`;聊天导入默认走 `rop:import`
- 不要修改 `src/libs/rop/__snapshots__/` 快照内容
## 能力边界
- Mock 迁移目前仅支持 `abnormalFlow.mock.js`
- 无已有 API 函数时不自动新建 `export function`
- 默认不覆盖已有 adapter/契约文件
...@@ -9,5 +9,4 @@ VUE_APP_REPO=http://192.168.3.171:7300/mock/5be17454f31545347559d499/config ...@@ -9,5 +9,4 @@ VUE_APP_REPO=http://192.168.3.171:7300/mock/5be17454f31545347559d499/config
VUE_APP_CONFIG_CENTER_URL=https://oss-config.test.glsx.com.cn/mock/5be17454f31545347559d499/config VUE_APP_CONFIG_CENTER_URL=https://oss-config.test.glsx.com.cn/mock/5be17454f31545347559d499/config
VUE_APP_USE_DEVELOP_AXIOS=true VUE_APP_USE_DEVELOP_AXIOS=true
# 门店工作汇报:关闭 Mock,走真实 dailyReport 接口 # 门店工作汇报:默认走真实 dailyReport 接口;本地需 Mock 时设 VUE_APP_JOURNAL_MOCK=true
VUE_APP_JOURNAL_MOCK=false
...@@ -42,3 +42,6 @@ yarn-error.log* ...@@ -42,3 +42,6 @@ yarn-error.log*
# test # test
/playwright/ /playwright/
/testCase/ /testCase/
# ROP import runtime report
rop-import.report.json
...@@ -6,6 +6,7 @@ ...@@ -6,6 +6,7 @@
- /.ai/rules/ 目录下的文件 - /.ai/rules/ 目录下的文件
- /.ai/rules/ESLINT.md(代码格式,生成代码必遵) - /.ai/rules/ESLINT.md(代码格式,生成代码必遵)
- ROP 聊天导入:/.ai/skills/rop-api-import/SKILL.md、/.ai/docs/ROP_CHAT_IMPORT.md
- 开发性能 / Element 主题预研:/.ai/docs/DEV_PERF_AND_THEME_RESEARCH.md - 开发性能 / Element 主题预研:/.ai/docs/DEV_PERF_AND_THEME_RESEARCH.md
## 项目概述 ## 项目概述
......
...@@ -14,6 +14,7 @@ ...@@ -14,6 +14,7 @@
"rop:swagger": "node scripts/rop-swagger-scaffold.js", "rop:swagger": "node scripts/rop-swagger-scaffold.js",
"rop:swagger:fetch": "node scripts/rop-swagger-fetch.js", "rop:swagger:fetch": "node scripts/rop-swagger-fetch.js",
"rop:contract:check": "node scripts/rop-contract-diff.js", "rop:contract:check": "node scripts/rop-contract-diff.js",
"rop:import": "node scripts/rop-import.js",
"rop:verify": "npm run test:unit -- tests/unit/libs/rop tests/unit/api/adapters/journalRecord && npm run rop:contract:check && npm run api:smoke:journal", "rop:verify": "npm run test:unit -- tests/unit/libs/rop tests/unit/api/adapters/journalRecord && npm run rop:contract:check && npm run api:smoke:journal",
"report": "set NODE_OPTIONS=--openssl-legacy-provider && vue-cli-service build --report", "report": "set NODE_OPTIONS=--openssl-legacy-provider && vue-cli-service build --report",
"test:unit": "vue-cli-service test:unit" "test:unit": "vue-cli-service test:unit"
......
#!/usr/bin/env node
/**
* ROP 接口一键导入(契约 + adapter + 迁移已有 API)
*
* npm run rop:import -- --method dj.api.smartcarlife.pc.abnormalFlowDeclaration.approve
* npm run rop:import -- --method ... --dry-run
*/
const { runImport, extractMethodFromText } = require("../src/libs/rop/ropImport");
function parseArgs(argv) {
const args = {};
for (let i = 2; i < argv.length; i += 1) {
const key = argv[i];
if (!key.startsWith("--")) {
if (!args._text) {
args._text = key;
} else {
args._text += ` ${key}`;
}
continue;
}
const name = key.slice(2);
const value = argv[i + 1];
if (value && !value.startsWith("--")) {
args[name] = value;
i += 1;
} else {
args[name] = true;
}
}
return args;
}
function printReport(report) {
console.log("\n=== ROP Import Report ===");
console.log("Method:", report.method);
if (report.summary) {
console.log("Summary:", report.summary);
}
console.log("Feature:", report.feature);
console.log("API file:", report.apiFile);
if (report.existingFunction) {
console.log("Migrated function:", report.existingFunction);
}
console.log("Request:", report.requestParams.map((p) => `${p.name}${p.required ? "*" : ""}`).join(", "));
console.log("Response:", report.responseRoot, report.pagination ? "(pagination)" : "");
console.log("\nFiles:");
report.files.forEach((item) => {
console.log(`- ${item.status}: ${item.path}`);
});
console.log("\nNext steps:");
report.nextSteps.forEach((step) => console.log(`- ${step}`));
if (report.reportPath) {
console.log("\nReport:", report.reportPath);
}
}
const USAGE = "Usage: npm run rop:import -- --method <dj.api.smartcarlife.*> "
+ "[--feature name] [--api finance] [--dry-run] [--force] [--json]";
async function runCli(argv, deps = {}) {
const runImportFn = deps.runImport || runImport;
const extractFn = deps.extractMethodFromText || extractMethodFromText;
const args = parseArgs(argv);
const method = args.method || extractFn(args._text || "");
if (!method) {
const error = new Error(USAGE);
error.code = "USAGE";
throw error;
}
const report = await runImportFn({
method,
feature: args.feature,
api: args.api,
dryRun: !!args["dry-run"],
force: !!args.force,
swagger: args.swagger,
});
return { report, json: !!args.json };
}
async function main() {
const { report, json } = await runCli(process.argv);
if (json) {
console.log(JSON.stringify(report, null, 2));
} else {
printReport(report);
}
}
if (require.main === module) {
main().catch((error) => {
console.error("Import failed:", error.message);
if (error.cause?.message) {
console.error("Cause:", error.cause.message);
}
process.exit(error.code === "USAGE" ? 1 : 1);
});
}
module.exports = {
parseArgs,
printReport,
runCli,
USAGE,
};
import { mapAbnormalFlowDeclarationApproveResponse } from "./adapters/abnormalFlowDeclaration/mapAbnormalFlowDeclarationApproveResponse";
import { mapAbnormalFlowDeclarationDetailResponse } from "./adapters/abnormalFlowDeclaration/mapAbnormalFlowDeclarationDetailResponse";
function delay(result, ms = 300) { function delay(result, ms = 300) {
return new Promise((resolve) => { return new Promise((resolve) => {
setTimeout(() => resolve(result), ms); setTimeout(() => resolve(result), ms);
...@@ -218,7 +220,7 @@ export function mockPcAbnormalFlowDeclarationDetail(data = {}) { ...@@ -218,7 +220,7 @@ export function mockPcAbnormalFlowDeclarationDetail(data = {}) {
if (!item) { if (!item) {
return delayReject(new Error("报备记录不存在")); return delayReject(new Error("报备记录不存在"));
} }
return delay({ return delay(mapAbnormalFlowDeclarationDetailResponse({
tradeInfo: buildTradeFields(item), tradeInfo: buildTradeFields(item),
declarationInfo: { declarationInfo: {
abnormalType: item.abnormalType, abnormalType: item.abnormalType,
...@@ -228,7 +230,7 @@ export function mockPcAbnormalFlowDeclarationDetail(data = {}) { ...@@ -228,7 +230,7 @@ export function mockPcAbnormalFlowDeclarationDetail(data = {}) {
voucherImageUrls: item.voucherImageUrls, voucherImageUrls: item.voucherImageUrls,
}, },
approvalLogs: item.approvalLogs || [], approvalLogs: item.approvalLogs || [],
}); }));
} }
export function mockApprovePcAbnormalFlowDeclaration(data = {}) { export function mockApprovePcAbnormalFlowDeclaration(data = {}) {
...@@ -248,5 +250,5 @@ export function mockApprovePcAbnormalFlowDeclaration(data = {}) { ...@@ -248,5 +250,5 @@ export function mockApprovePcAbnormalFlowDeclaration(data = {}) {
remark: data.remark || "", remark: data.remark || "",
approvalSource: "1", approvalSource: "1",
}); });
return delay(true); return delay(mapAbnormalFlowDeclarationApproveResponse(true));
} }
{
"method": "dj.api.smartcarlife.pc.abnormalFlowDeclaration.approve",
"route": "/router/dj.api.smartcarlife.pc.abnormalFlowDeclaration.approve/1.0.0",
"summary": "总部运营审批流水报备",
"request": {
"parameters": [
{
"name": "id",
"in": "query",
"type": "Integer",
"required": true,
"description": "异常流水报备记录ID"
},
{
"name": "approvalStatus",
"in": "query",
"type": "Byte",
"required": true,
"description": "审批状态(4-后台审批驳回 5-审批通过)"
},
{
"name": "remark",
"in": "query",
"type": "String",
"required": false,
"description": "审批备注"
},
{
"name": "delayDeadline",
"in": "query",
"type": "Date",
"required": false,
"description": "延期截止时间"
},
{
"name": "sessionId",
"in": "query",
"type": "string",
"required": true,
"description": "会话ID"
}
]
},
"response": {
"fields": [
{
"name": "code",
"type": "string",
"description": "响应状态(0:成功;1:失败)",
"required": false
},
{
"name": "errId",
"type": "string",
"description": "错误码",
"required": false
},
{
"name": "message",
"type": "string",
"description": "错误描述",
"required": false
},
{
"name": "data",
"type": "boolean",
"description": "成功返回数据",
"required": false
}
],
"pagination": null,
"rootType": "RopResponse<Boolean>"
}
}
# dj.api.smartcarlife.pc.abnormalFlowDeclaration.approve
> 总部运营审批流水报备
## Request
| 参数 | 位置 | 类型 | 必填 | 说明 |
|------|------|------|------|------|
| id | query | Integer | 是 | 异常流水报备记录ID |
| approvalStatus | query | Byte | 是 | 审批状态(4-后台审批驳回 5-审批通过) |
| remark | query | String | 否 | 审批备注 |
| delayDeadline | query | Date | 否 | 延期截止时间 |
| sessionId | query | string | 是 | 会话ID |
## Response
| 字段 | 类型 | 说明 |
|------|------|------|
| code | string | 响应状态(0:成功;1:失败) |
| errId | string | 错误码 |
| message | string | 错误描述 |
| data | boolean | 成功返回数据 |
{
"method": "dj.api.smartcarlife.pc.abnormalFlowDeclaration.detail",
"route": "/router/dj.api.smartcarlife.pc.abnormalFlowDeclaration.detail/1.0.0",
"summary": "查询异常流水报备详情",
"request": {
"parameters": [
{
"name": "id",
"in": "query",
"type": "Integer",
"required": true,
"description": "异常流水报备记录ID"
},
{
"name": "sessionId",
"in": "query",
"type": "string",
"required": true,
"description": "会话ID"
}
]
},
"response": {
"fields": [
{
"name": "code",
"type": "string",
"description": "响应状态(0:成功;1:失败)",
"required": false
},
{
"name": "errId",
"type": "string",
"description": "错误码",
"required": false
},
{
"name": "message",
"type": "string",
"description": "错误描述",
"required": false
},
{
"name": "data",
"type": "AbnormalFlowDeclarationDetailDTO",
"description": "成功返回数据",
"required": false
},
{
"name": "data.tradeInfo",
"type": "AbnormalPaymentDetailListDTO",
"description": "流水信息",
"required": false
},
{
"name": "data.declarationInfo",
"type": "AbnormalFlowDeclarationInfoDTO",
"description": "报备信息",
"required": false
},
{
"name": "data.approvalLogs",
"type": "array<AbnormalFlowApprovalLogItemDTO>",
"description": "审批日志列表",
"required": false
}
],
"pagination": null,
"rootType": "RopResponse<AbnormalFlowDeclarationDetailDTO>"
}
}
# dj.api.smartcarlife.pc.abnormalFlowDeclaration.detail
> 查询异常流水报备详情
## Request
| 参数 | 位置 | 类型 | 必填 | 说明 |
|------|------|------|------|------|
| id | query | Integer | 是 | 异常流水报备记录ID |
| sessionId | query | string | 是 | 会话ID |
## Response
| 字段 | 类型 | 说明 |
|------|------|------|
| code | string | 响应状态(0:成功;1:失败) |
| errId | string | 错误码 |
| message | string | 错误描述 |
| data | AbnormalFlowDeclarationDetailDTO | 成功返回数据 |
| data.tradeInfo | AbnormalPaymentDetailListDTO | 流水信息 |
| data.declarationInfo | AbnormalFlowDeclarationInfoDTO | 报备信息 |
| data.approvalLogs | array<AbnormalFlowApprovalLogItemDTO> | 审批日志列表 |
/**
* @typedef {Object} AbnormalFlowDeclarationApproveParams
* @property {number} id - 异常流水报备记录ID
* @property {string} approvalStatus - 审批状态(4-后台审批驳回 5-审批通过)
* @property {string} remark [optional] - 审批备注
* @property {string} delayDeadline [optional] - 延期截止时间
*/
/**
* @typedef {Object} AbnormalFlowDeclarationApproveRow
* @property {string} errId - 错误码
* @property {boolean} data - 成功返回数据
*/
/**
* UI/表格参数 → dj.api.smartcarlife.pc.abnormalFlowDeclaration.approve 请求体
* @param {AbnormalFlowDeclarationApproveParams} [params]
* @returns {AbnormalFlowDeclarationApproveParams}
* @see __contracts__/dj_api_smartcarlife_pc_abnormalFlowDeclaration_approve.contract.md
*/
export function buildAbnormalFlowDeclarationApproveParams(params = {}) {
const payload = {};
if (params.id != null && params.id !== "") {
payload.id = params.id;
}
if (params.approvalStatus != null && params.approvalStatus !== "") {
payload.approvalStatus = params.approvalStatus;
}
if (params.remark != null && params.remark !== "") {
payload.remark = params.remark;
}
if (params.delayDeadline != null && params.delayDeadline !== "") {
payload.delayDeadline = params.delayDeadline;
}
return payload;
}
export default buildAbnormalFlowDeclarationApproveParams;
/**
* @typedef {Object} AbnormalFlowDeclarationDetailParams
* @property {number} id - 异常流水报备记录ID
*/
/**
* @typedef {Object} AbnormalFlowDeclarationDetailRow
* @property {string} errId - 错误码
* @property {string} data - 成功返回数据
*/
/**
* UI/表格参数 → dj.api.smartcarlife.pc.abnormalFlowDeclaration.detail 请求体
* @param {AbnormalFlowDeclarationDetailParams} [params]
* @returns {AbnormalFlowDeclarationDetailParams}
* @see __contracts__/dj_api_smartcarlife_pc_abnormalFlowDeclaration_detail.contract.md
*/
export function buildAbnormalFlowDeclarationDetailParams(params = {}) {
const payload = {};
if (params.id != null && params.id !== "") {
payload.id = params.id;
}
return payload;
}
export default buildAbnormalFlowDeclarationDetailParams;
/**
* @typedef {Object} AbnormalFlowDeclarationApproveParams
* @property {number} id - 异常流水报备记录ID
* @property {string} approvalStatus - 审批状态(4-后台审批驳回 5-审批通过)
* @property {string} remark [optional] - 审批备注
* @property {string} delayDeadline [optional] - 延期截止时间
*/
/**
* @typedef {Object} AbnormalFlowDeclarationApproveRow
* @property {string} errId - 错误码
* @property {boolean} data - 成功返回数据
*/
/**
* dj.api.smartcarlife.pc.abnormalFlowDeclaration.approve 响应 → 页面数据
* @param {*} [res]
* @returns {*}
* @see __contracts__/dj_api_smartcarlife_pc_abnormalFlowDeclaration_approve.contract.md
*/
export function mapAbnormalFlowDeclarationApproveResponse(res = {}) {
return res;
}
export default mapAbnormalFlowDeclarationApproveResponse;
/**
* @typedef {Object} AbnormalFlowDeclarationDetailParams
* @property {number} id - 异常流水报备记录ID
*/
/**
* @typedef {Object} AbnormalFlowDeclarationDetailRow
* @property {string} errId - 错误码
* @property {string} data - 成功返回数据
*/
/**
* dj.api.smartcarlife.pc.abnormalFlowDeclaration.detail 响应 → 页面数据
* @param {*} [res]
* @returns {*}
* @see __contracts__/dj_api_smartcarlife_pc_abnormalFlowDeclaration_detail.contract.md
*/
export function mapAbnormalFlowDeclarationDetailResponse(res = {}) {
return res;
}
export default mapAbnormalFlowDeclarationDetailResponse;
import request from "./request" import request from "./request"
import { mapAbnormalFlowDeclarationApproveResponse } from "./adapters/abnormalFlowDeclaration/mapAbnormalFlowDeclarationApproveResponse";
import { buildAbnormalFlowDeclarationApproveParams } from "./adapters/abnormalFlowDeclaration/buildAbnormalFlowDeclarationApproveParams";
import { mapAbnormalFlowDeclarationDetailResponse } from "./adapters/abnormalFlowDeclaration/mapAbnormalFlowDeclarationDetailResponse";
import { buildAbnormalFlowDeclarationDetailParams } from "./adapters/abnormalFlowDeclaration/buildAbnormalFlowDeclarationDetailParams";
import RequestMethods from "./request.methods" import RequestMethods from "./request.methods"
const USE_ABNORMAL_FLOW_MOCK = process.env.VUE_APP_ABNORMAL_FLOW_MOCK === "true" const USE_ABNORMAL_FLOW_MOCK = process.env.VUE_APP_ABNORMAL_FLOW_MOCK === "true"
...@@ -235,26 +239,21 @@ export function saveShopLockConfig(data) { ...@@ -235,26 +239,21 @@ export function saveShopLockConfig(data) {
*/ */
export function getPcAbnormalFlowDeclarationDetail(data) { export function getPcAbnormalFlowDeclarationDetail(data) {
if (USE_ABNORMAL_FLOW_MOCK) { if (USE_ABNORMAL_FLOW_MOCK) {
return loadAbnormalFlowMock().then((m) => m.mockPcAbnormalFlowDeclarationDetail(data)) return loadAbnormalFlowMock().then((m) => m.mockPcAbnormalFlowDeclarationDetail(data));
} }
data.method = "dj.api.smartcarlife.pc.abnormalFlowDeclaration.detail" const payload = {
return request(data, RequestMethods.POST) ...buildAbnormalFlowDeclarationDetailParams(data),
method: "dj.api.smartcarlife.pc.abnormalFlowDeclaration.detail",
};
return request(payload, RequestMethods.POST).then(mapAbnormalFlowDeclarationDetailResponse);
} }
/**
* 总部运营审批流水报备
* dj.api.smartcarlife.pc.abnormalFlowDeclaration.approve
* @param {Object} data
* @param {number} data.id 异常流水报备记录 ID(必填)
* @param {number|string} data.approvalStatus 审批状态 4=后台审批驳回 5=审批通过(必填)
* @param {string} [data.remark] 审批备注
* @param {string|Date} [data.delayDeadline] 延期截止时间
* @returns {Promise<boolean>}
*/
export function approvePcAbnormalFlowDeclaration(data) { export function approvePcAbnormalFlowDeclaration(data) {
if (USE_ABNORMAL_FLOW_MOCK) { if (USE_ABNORMAL_FLOW_MOCK) {
return loadAbnormalFlowMock().then((m) => m.mockApprovePcAbnormalFlowDeclaration(data)) return loadAbnormalFlowMock().then((m) => m.mockApprovePcAbnormalFlowDeclaration(data));
} }
data.method = "dj.api.smartcarlife.pc.abnormalFlowDeclaration.approve" const payload = {
return request(data, RequestMethods.POST) ...buildAbnormalFlowDeclarationApproveParams(data),
method: "dj.api.smartcarlife.pc.abnormalFlowDeclaration.approve",
};
return request(payload, RequestMethods.POST).then(mapAbnormalFlowDeclarationApproveResponse);
} }
...@@ -10,7 +10,7 @@ import { mapMerchantListResponse } from "./adapters/journalRecord/mapMerchantLis ...@@ -10,7 +10,7 @@ import { mapMerchantListResponse } from "./adapters/journalRecord/mapMerchantLis
import { mapMerchantStaffListResponse } from "./adapters/journalRecord/mapMerchantStaffList"; import { mapMerchantStaffListResponse } from "./adapters/journalRecord/mapMerchantStaffList";
const path = "dj.api.smartcarlife."; const path = "dj.api.smartcarlife.";
const USE_MOCK = process.env.VUE_APP_JOURNAL_MOCK !== "false"; const USE_MOCK = process.env.VUE_APP_JOURNAL_MOCK === "true";
function loadMock() { function loadMock() {
return import("./journalRecord.mock"); return import("./journalRecord.mock");
...@@ -29,6 +29,31 @@ export function getDailyReportMerchantList(data = {}) { ...@@ -29,6 +29,31 @@ export function getDailyReportMerchantList(data = {}) {
return request(payload, RequestMethods.POST).then(mapMerchantListResponse); return request(payload, RequestMethods.POST).then(mapMerchantListResponse);
} }
export function getDailyReportMerchantListPage(data = {}) {
const payload = {
currentPage: 1,
pageSize: 20,
...data,
};
if (USE_MOCK) {
return loadMock()
.then((m) => m.mockDailyReportMerchantList(payload))
.then((list) => ({
list,
total: list.length,
pages: 1,
pageNum: payload.currentPage,
}));
}
payload.method = `${path}dailyReport.merchant.list`;
return request(payload, RequestMethods.POST).then((res) => ({
list: mapMerchantListResponse(res),
total: res.total ?? 0,
pages: res.pages ?? 1,
pageNum: res.pageNum ?? payload.currentPage,
}));
}
export function getDailyReportMerchantStaffList(data = {}) { export function getDailyReportMerchantStaffList(data = {}) {
if (USE_MOCK) { if (USE_MOCK) {
return loadMock().then((m) => m.mockDailyReportMerchantStaffList(data)); return loadMock().then((m) => m.mockDailyReportMerchantStaffList(data));
......
...@@ -7,6 +7,7 @@ const ropClient = require("./ropClient"); ...@@ -7,6 +7,7 @@ const ropClient = require("./ropClient");
const swaggerInspect = require("./swaggerInspect"); const swaggerInspect = require("./swaggerInspect");
const resolveApiName = require("./resolveApiName"); const resolveApiName = require("./resolveApiName");
const contractDiff = require("./contractDiff"); const contractDiff = require("./contractDiff");
const ropImport = require("./ropImport");
module.exports = { module.exports = {
buildRopPayload, buildRopPayload,
...@@ -18,4 +19,5 @@ module.exports = { ...@@ -18,4 +19,5 @@ module.exports = {
...resolveApiName, ...resolveApiName,
swaggerInspect, swaggerInspect,
contractDiff, contractDiff,
ropImport,
}; };
const qs = require("qs"); const qs = require("qs");
const md5 = require("md5");
const sha1 = require("sha1"); const sha1 = require("sha1");
function deepClone(obj) { function deepClone(obj) {
...@@ -9,9 +10,9 @@ function deepClone(obj) { ...@@ -9,9 +10,9 @@ function deepClone(obj) {
* ROP 请求签名(与 src/api/sign.js 逻辑一致) * ROP 请求签名(与 src/api/sign.js 逻辑一致)
*/ */
function sign(params, noSignAttr = [], secret, way = "sha1") { function sign(params, noSignAttr = [], secret, way = "sha1") {
const signed = { ...params }; const payload = { ...params };
delete signed.sign; delete payload.sign;
const objStr = qs.stringify(deepClone(signed), { const objStr = qs.stringify(deepClone(payload), {
arrayFormat: "indices", arrayFormat: "indices",
allowDots: true, allowDots: true,
encodeValuesOnly: true, encodeValuesOnly: true,
...@@ -37,9 +38,9 @@ function sign(params, noSignAttr = [], secret, way = "sha1") { ...@@ -37,9 +38,9 @@ function sign(params, noSignAttr = [], secret, way = "sha1") {
str.push(e + realObj[e]); str.push(e + realObj[e]);
} }
}); });
const signObj = { sha1 }; const signObj = { sha1, md5 };
signed.sign = signObj[way](secret + str.join("") + secret).toUpperCase(); realObj.sign = signObj[way](secret + str.join("") + secret).toUpperCase();
return signed; return realObj;
} }
module.exports = sign; module.exports = sign;
...@@ -53,7 +53,7 @@ export const TABLE_COLUMNS_MAP = { ...@@ -53,7 +53,7 @@ export const TABLE_COLUMNS_MAP = {
{ label: "最近保存时间", prop: "lastSaveTime", width: "160px" }, { label: "最近保存时间", prop: "lastSaveTime", width: "160px" },
], ],
storeDaily: [ storeDaily: [
{ label: "所属门店", prop: "merchantName", minWidth: "200px", showOverFlow: true }, { label: "所属门店", prop: "merchantName", minWidth: "180px", showOverFlow: true },
bizTypeColumn, bizTypeColumn,
{ {
label: "今日驻店人数", label: "今日驻店人数",
......
...@@ -18,7 +18,27 @@ ...@@ -18,7 +18,27 @@
class="show-search" class="show-search"
:form-data="currentFormData" :form-data="currentFormData"
:label-width="labelWidth" :label-width="labelWidth"
:search-form="searchForm" /> :search-form="searchForm">
<template slot="merchantHtml">
<el-select v-model="searchForm.merchantId"
v-el-select-loadmore="loadMoreMerchants"
clearable
filterable
:loading="merchantLoading"
placeholder="请输入门店名称搜索"
remote
reserve-keyword
style="width: 100%;"
:remote-method="remoteMerchantMethod"
@change="handleMerchantChange"
@visible-change="handleMerchantVisibleChange">
<el-option v-for="item in baseData.storeOptions"
:key="item.merchantId"
:label="item.merchantName"
:value="item.merchantId" />
</el-select>
</template>
</d2-search>
<div class="up-btns"> <div class="up-btns">
<el-button size="small" <el-button size="small"
type="primary" type="primary"
...@@ -60,8 +80,7 @@ import dayjs from "dayjs"; ...@@ -60,8 +80,7 @@ import dayjs from "dayjs";
import { deepClone } from "@/common/util"; import { deepClone } from "@/common/util";
import reportTrackFunMixin from "@/mixins/reportTrackFunMixin"; import reportTrackFunMixin from "@/mixins/reportTrackFunMixin";
import { import {
getDailyReportMerchantList, getDailyReportMerchantListPage,
getDailyReportMerchantStaffList,
getDailyReportOverviewPage, getDailyReportOverviewPage,
} from "@api/journalRecord"; } from "@api/journalRecord";
import BizTypeTag from "./components/BizTypeTag.vue"; import BizTypeTag from "./components/BizTypeTag.vue";
...@@ -74,11 +93,31 @@ import { ...@@ -74,11 +93,31 @@ import {
const DEFAULT_SEARCH_FORM = { const DEFAULT_SEARCH_FORM = {
merchantId: "", merchantId: "",
staffUuid: "", staffName: "",
}; };
export default { export default {
name: "JournalRecord", name: "JournalRecord",
directives: {
"el-select-loadmore": {
bind(el, binding) {
setTimeout(() => {
const selectWrap = el.querySelector(
".el-select-dropdown .el-select-dropdown__wrap",
);
if (!selectWrap) {
return;
}
selectWrap.addEventListener("scroll", function onScroll() {
const reachBottom = this.scrollHeight - this.scrollTop <= this.clientHeight;
if (reachBottom) {
binding.value();
}
});
}, 100);
},
},
},
components: { components: {
BizTypeTag, BizTypeTag,
DateNav, DateNav,
...@@ -94,42 +133,35 @@ export default { ...@@ -94,42 +133,35 @@ export default {
searchFormSearch: {}, searchFormSearch: {},
baseData: { baseData: {
storeOptions: [], storeOptions: [],
staffOptions: [],
}, },
merchantKeyword: "",
merchantCurrentPage: 1,
merchantPageSize: 20,
merchantTotalPages: 1,
merchantLoading: false,
selectedMerchant: null,
baseFormData: [ baseFormData: [
{ {
label: "所属门店", label: "所属门店",
name: "merchantId", name: "merchantId",
type: "select", addHtml: "merchantHtml",
isClear: true,
placeholder: "请选择",
optionList: [],
optionId: "merchantId",
optionLabel: "merchantName",
optionsName: "storeOptions",
changeAttr: () => {
this.searchForm.staffUuid = "";
this.loadStaffOptions();
},
}, },
{ {
label: "驻店人员", label: "驻店人员",
name: "staffUuid", name: "staffName",
type: "select", type: "input",
isClear: true, isClear: true,
filterable: true, placeholder: "请输入",
placeholder: "请选择",
optionList: [],
optionId: "staffUuid",
optionLabel: "staffName",
optionsName: "staffOptions",
}, },
], ],
}; };
}, },
computed: { computed: {
currentListApi() { currentListApi() {
return (params) => getDailyReportOverviewPage(params, this.activeTab); return (params) => getDailyReportOverviewPage({
...params,
reportDate: params.reportDate || this.reportDate,
}, this.activeTab);
}, },
currentFormData() { currentFormData() {
if (this.activeTab === "storeDaily") { if (this.activeTab === "storeDaily") {
...@@ -150,55 +182,107 @@ export default { ...@@ -150,55 +182,107 @@ export default {
this.initPage(); this.initPage();
}, },
methods: { methods: {
restoreStateFromRoute() {
const { journalType, reportDate } = this.$route.query;
if (journalType && this.tabList.some((item) => item.key === journalType)) {
this.activeTab = journalType;
}
if (reportDate && dayjs(reportDate).isValid()) {
this.reportDate = reportDate;
}
},
syncRouteQuery() {
if (
this.$route.query.journalType === this.activeTab
&& this.$route.query.reportDate === this.reportDate
) {
return;
}
this.$router.replace({
query: {
...this.$route.query,
journalType: this.activeTab,
reportDate: this.reportDate,
},
});
},
async initPage() { async initPage() {
this.restoreStateFromRoute();
this.setReportTrackData(0, "journal_web_page_entry", {}); this.setReportTrackData(0, "journal_web_page_entry", {});
await this.loadStoreOptions();
await this.loadStaffOptions();
this.handleSearch(); this.handleSearch();
}, },
async loadStoreOptions() { remoteMerchantMethod(query) {
const list = await getDailyReportMerchantList(); this.merchantKeyword = query || "";
this.baseData.storeOptions = Array.isArray(list) ? list : []; this.merchantCurrentPage = 1;
this.syncStoreOptions(); this.fetchMerchantOptions(true);
}, },
async loadStaffOptions() { handleMerchantVisibleChange(visible) {
if (!this.searchForm.merchantId) { if (!visible || this.baseData.storeOptions.length) {
this.baseData.staffOptions = [];
this.syncStaffOptions();
return; return;
} }
const list = await getDailyReportMerchantStaffList({ this.merchantKeyword = "";
merchantId: this.searchForm.merchantId, this.merchantCurrentPage = 1;
}); this.fetchMerchantOptions(true);
this.baseData.staffOptions = Array.isArray(list) ? list : [];
this.syncStaffOptions();
}, },
syncStoreOptions() { loadMoreMerchants() {
this.baseFormData.forEach((item, index) => { if (this.merchantLoading || this.merchantCurrentPage >= this.merchantTotalPages) {
if (item.name === "merchantId") { return;
this.$set(this.baseFormData[index], "optionList", this.baseData.storeOptions);
} }
this.merchantCurrentPage += 1;
this.fetchMerchantOptions(false);
},
async fetchMerchantOptions(reset = false) {
this.merchantLoading = true;
try {
const res = await getDailyReportMerchantListPage({
merchantName: this.merchantKeyword || undefined,
currentPage: this.merchantCurrentPage,
pageSize: this.merchantPageSize,
}); });
const list = Array.isArray(res.list) ? res.list : [];
this.merchantTotalPages = res.pages || 1;
const mergedList = reset
? list
: this.baseData.storeOptions.concat(list);
this.baseData.storeOptions = this.mergeSelectedMerchantOptions(mergedList);
} finally {
this.merchantLoading = false;
}
}, },
syncStaffOptions() { mergeSelectedMerchantOptions(list) {
this.baseFormData.forEach((item, index) => { const optionMap = new Map();
if (item.name === "staffUuid") { list.forEach((item) => {
this.$set(this.baseFormData[index], "optionList", this.baseData.staffOptions); if (item?.merchantId != null) {
optionMap.set(item.merchantId, item);
} }
}); });
if (
this.selectedMerchant?.merchantId != null
&& !optionMap.has(this.selectedMerchant.merchantId)
) {
optionMap.set(this.selectedMerchant.merchantId, this.selectedMerchant);
}
return Array.from(optionMap.values());
},
handleMerchantChange(merchantId) {
if (!merchantId) {
this.selectedMerchant = null;
return;
}
this.selectedMerchant = this.baseData.storeOptions.find(
(item) => item.merchantId === merchantId,
) || this.selectedMerchant;
},
resetMerchantSearch() {
this.merchantKeyword = "";
this.merchantCurrentPage = 1;
this.merchantTotalPages = 1;
this.selectedMerchant = null;
this.baseData.storeOptions = [];
}, },
beforeSearchFn() { beforeSearchFn() {
return new Promise((resolve) => { return new Promise((resolve) => {
const params = deepClone(this.searchFormSearch); const params = deepClone(this.searchFormSearch);
if (params.staffUuid) {
const staff = this.baseData.staffOptions.find(
(item) => item.staffUuid === params.staffUuid,
);
if (staff?.staffName) {
params.staffName = staff.staffName;
}
delete params.staffUuid;
}
Object.keys(params).forEach((key) => { Object.keys(params).forEach((key) => {
if (params[key] === "" || params[key] == null) { if (params[key] === "" || params[key] == null) {
delete params[key]; delete params[key];
...@@ -220,12 +304,11 @@ export default { ...@@ -220,12 +304,11 @@ export default {
}, },
async handleReset() { async handleReset() {
this.searchForm = deepClone(DEFAULT_SEARCH_FORM); this.searchForm = deepClone(DEFAULT_SEARCH_FORM);
await this.loadStaffOptions(); this.resetMerchantSearch();
this.handleSearch(); this.handleSearch();
}, },
async handleDateChange() { async handleDateChange() {
await this.loadStoreOptions(); this.syncRouteQuery();
await this.loadStaffOptions();
this.handleSearch(); this.handleSearch();
}, },
handleTabClick(tab) { handleTabClick(tab) {
...@@ -233,6 +316,7 @@ export default { ...@@ -233,6 +316,7 @@ export default {
if (eventCode) { if (eventCode) {
this.setReportTrackData(0, eventCode, { reportDate: this.reportDate }); this.setReportTrackData(0, eventCode, { reportDate: this.reportDate });
} }
this.syncRouteQuery();
this.$nextTick(() => { this.$nextTick(() => {
this.handleSearch(); this.handleSearch();
}); });
......
const { runCli, parseArgs } = require("../../../../scripts/rop-import");
describe("rop-import CLI", () => {
it("parseArgs 应解析 --json 与 --dry-run", () => {
const args = parseArgs([
"node", "rop-import.js",
"--method", "dj.api.smartcarlife.pc.abnormalFlowDeclaration.approve",
"--dry-run", "--json",
]);
expect(args.method).toBe("dj.api.smartcarlife.pc.abnormalFlowDeclaration.approve");
expect(args["dry-run"]).toBe(true);
expect(args.json).toBe(true);
});
it("runCli --json 应返回 report 对象", async () => {
const mockReport = {
method: "dj.api.smartcarlife.pc.abnormalFlowDeclaration.approve",
summary: "总部运营审批流水报备",
feature: "abnormalFlowDeclaration",
apiFile: "finance.js",
existingFunction: "approvePcAbnormalFlowDeclaration",
requestParams: [{ name: "id", required: true, type: "Integer" }],
responseRoot: "RopResponse<Boolean>",
pagination: false,
files: [{ path: "/tmp/finance.js", status: "dry-run" }],
nextSteps: ["npm run rop:contract:check"],
};
const { report, json } = await runCli(
["node", "rop-import.js", "--method", mockReport.method, "--dry-run", "--json"],
{
runImport: jest.fn().mockResolvedValue(mockReport),
},
);
expect(json).toBe(true);
expect(report).toEqual(mockReport);
});
it("runCli 未提供 method 时应抛出 USAGE", async () => {
await expect(runCli(["node", "rop-import.js"])).rejects.toMatchObject({
code: "USAGE",
});
});
});
const fs = require("fs");
const path = require("path");
const {
extractMethodFromText,
inferFeatureName,
detectApiFile,
findExistingApiBinding,
} = require("@/libs/rop/ropImport");
describe("ropImport", () => {
it("extractMethodFromText 应提取最长 method", () => {
const text = "导入接口 dj.api.smartcarlife.pc.abnormalFlowDeclaration.approve(总部运营审批)";
expect(extractMethodFromText(text)).toBe("dj.api.smartcarlife.pc.abnormalFlowDeclaration.approve");
});
it("inferFeatureName 应跳过 pc 网关前缀", () => {
expect(inferFeatureName("dj.api.smartcarlife.pc.abnormalFlowDeclaration.approve"))
.toBe("abnormalFlowDeclaration");
});
it("detectApiFile 应命中 finance.js", () => {
const method = "dj.api.smartcarlife.pc.abnormalFlowDeclaration.approve";
const apiFile = detectApiFile(method);
expect(path.basename(apiFile)).toBe("finance.js");
});
it("findExistingApiBinding 应找到 approve 函数", () => {
const method = "dj.api.smartcarlife.pc.abnormalFlowDeclaration.approve";
const apiFile = detectApiFile(method);
const binding = findExistingApiBinding(apiFile, method);
expect(binding.functionName).toBe("approvePcAbnormalFlowDeclaration");
expect(binding.block).toContain("dj.api.smartcarlife.pc.abnormalFlowDeclaration.approve");
});
});
...@@ -23,4 +23,35 @@ describe("rop signCore", () => { ...@@ -23,4 +23,35 @@ describe("rop signCore", () => {
const signedB = sign({ ...base, foo: "baz" }, [], secret, "sha1"); const signedB = sign({ ...base, foo: "baz" }, [], secret, "sha1");
expect(signedA.sign).not.toBe(signedB.sign); expect(signedA.sign).not.toBe(signedB.sign);
}); });
it("recordList 数组应返回扁平化参数(与 axios 发送形态一致)", () => {
const secret = "test-secret";
const params = buildRopPayload(
"appkey",
"clue.api.burial.point.record.batch.insert",
{
recordList: [
{ loginAccount: "demo", uuid: "u1", userType: 1 },
],
},
);
params.timestamp = 1700000000000;
const signed = sign(params, [], secret, "sha1");
expect(signed.recordList).toBeUndefined();
expect(signed["recordList[0].loginAccount"]).toBe("demo");
expect(signed["recordList[0].uuid"]).toBe("u1");
expect(signed.sign).toMatch(/^[A-F0-9]{40}$/);
const again = sign({ ...params }, [], secret, "sha1");
expect(again.sign).toBe(signed.sign);
});
it("md5 签名方式应可用", () => {
const secret = "test-secret";
const params = buildRopPayload("appkey", "glsx.api.test", { foo: "bar" });
params.timestamp = 1700000000000;
const signed = sign(params, [], secret, "md5");
expect(signed.sign).toMatch(/^[A-F0-9]{32}$/);
});
}); });
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!