Commit 0b4b23aa by 张立顺

Merge branch 'feature/V5.8.4/zls' into 'SAAS+V5.8.4'

feat swagger文档接入功能开发

See merge request !854
2 parents 69443621 ed3f8d5c
Showing 78 changed files with 3776 additions and 345 deletions
# ROP 接口对接指南
本文档沉淀门店工作汇报(dailyReport)联调经验,供后续新接口快速对接复用。
## 1. 工具与模块
| 能力 | 路径 / 命令 |
|------|-------------|
| ROP 客户端(Node/脚本/集成测) | [`src/libs/rop/`](../../src/libs/rop/) |
| apiName 统一解析 | [`src/libs/rop/resolveApiName.js`](../../src/libs/rop/resolveApiName.js) |
| 签名(浏览器与 Node 共用) | [`src/libs/rop/signCore.js`](../../src/libs/rop/signCore.js) |
| Swagger 契约解析 | [`src/libs/rop/swaggerInspect.js`](../../src/libs/rop/swaggerInspect.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) |
| 脚手架 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:contract:check` |
| 一键验证 | `npm run rop:verify` |
| 冒烟示例 | `npm run api:smoke:journal` |
| 冒烟模板 | [`scripts/rop-api-smoke.template.js`](../../scripts/rop-api-smoke.template.js) |
| Jest 测试辅助 | [`tests/helpers/ropTestClient.js`](../../tests/helpers/ropTestClient.js) |
浏览器内请求仍使用 [`src/api/request.js`](../../src/api/request.js)(内部已复用 `resolveApiName`),**不要**在 Vue 页面直接引用 `ropClient`。
---
## 2. 拉取 Swagger
**正确地址**(本项目 ROP):
```text
{host}/rop-dj-smartcarlife/swagger-rop/api-docs
```
不要使用 `/v3/api-docs`。
开发环境示例:
```text
http://dj.dev.glsx.com.cn/rop-dj-smartcarlife/swagger-rop/api-docs
```
接口路径约定:
```text
/router/{method}/1.0.0 → POST
```
### 契约更新流程
后端发版或联调前:
```bash
npm run rop:swagger:fetch
git diff src/libs/rop/__snapshots__/smartcarlife.swagger.json
npm run rop:contract:check
```
提交快照 diff,便于团队感知契约变更。
---
## 3. 读契约(ROP 特点)
1. **请求参数多为 query**,不是 JSON body(与常见 OpenAPI 不同)
2. **响应**为 `RopResponse<T>`,浏览器 axios 拦截器已解包 `data`(见 `baseConfig.axios.result`)
3. **列表**常为 `RpcPagination<T>`:`list / total / pageNum / pageSize`
4. `sessionId` 由 [`request.js`](../../src/api/request.js) 自动注入,adapter **不需要**处理
### 脚手架生成契约
省略 `--swagger` 时默认读取本地快照。
**单接口:**
```bash
npm run rop:swagger -- \
--method dj.api.smartcarlife.dailyReport.overview.page \
--feature journalRecord \
--out src/api/adapters/journalRecord \
--dry-run
```
**按前缀批量:**
```bash
npm run rop:swagger -- \
--prefix dj.api.smartcarlife.dailyReport \
--out src/api/adapters/journalRecord \
--contracts-only
```
`--contracts-only` 仅生成 `__contracts__`,不覆盖已有 adapter 实现文件。
生成物:
```text
src/api/adapters/{feature}/
build{Method}Params.js # 含 @typedef JSDoc
map{Method}Response.js
__contracts__/{method}.contract.json
__contracts__/{method}.contract.md
```
去掉 `--dry-run` 后落盘。已存在文件默认 **skip**(加 `--force` 才覆盖)。`--feature` 仅打印 mock 模板提示,不自动改已有 mock 文件;新建 mock 可加 `--mock`。
---
## 3.1 新接口 5 分钟上手
1. `npm run rop:swagger -- --prefix <prefix> --out src/api/adapters/{feature} --contracts-only --dry-run` 核对契约
2. 生成 adapter 模板或手工编写,补业务映射
3. `src/api/{feature}.js` 接入 `request` + adapter + mock
4. 复制 [`rop-api-smoke.template.js`](../../scripts/rop-api-smoke.template.js) 写冒烟脚本
5. `npm run rop:verify`(单测 + 契约校验 + 冒烟)通过后再测页面
---
## 4. Adapter 三层约定
以 [`src/api/adapters/journalRecord/`](../../src/api/adapters/journalRecord/) 为范本:
| 层级 | 命名 | 职责 |
|------|------|------|
| 请求 | `buildXxxParams(uiParams)` | 页面/表格筛选 → ROP 请求字段 |
| 行映射 | `mapXxxRow(dto)` | 单行 DTO → 表格列字段 |
| 分页 | `mapXxxPageResponse(res)` | 分页响应 → d2-table 结构 |
### UI 与 API 字段不一致
在 **adapter** 处理,例如:
- 下拉存 `staffUuid`,接口要 `staffName` → 在 `beforeSearchFn` 解析姓名后传入 `buildOverviewParams`
- `sceneType`(0 权益 / 1 轻改)→ `bizType` / `bizTypeName` → [`mapSceneType.js`](../../src/api/adapters/journalRecord/mapSceneType.js)
---
## 5. API 层(`src/api/*.js`)
```js
// 模式
export function getXxx(data) {
if (USE_MOCK) return loadMock().then(m => m.mockXxx(data));
const payload = { ...buildXxxParams(data), method: `${path}xxx.yyy` };
return request(payload, RequestMethods.POST).then(mapXxxPageResponse);
}
```
Mock 开关:`VUE_APP_{FEATURE}_MOCK=true` 时启用(参考 `VUE_APP_JOURNAL_MOCK` / `VUE_APP_ABNORMAL_FLOW_MOCK`),默认走真实接口。
---
## 6. Mock 规范
[`journalRecord.mock.js`](../../src/api/journalRecord.mock.js):
1. Mock 原始数据使用 **Swagger 字段名**(如 `sceneType`、`onBreak`、`createdDate`)
2. 必须经 **同一套 adapter** 输出,保证 Mock / 真实接口行为一致
3. 不要在 mock 里写 UI 字段名(如 `bizTypeName`),除非 adapter 不再转换
---
## 7. Node 客户端用法
```js
const { createLoggedInClient } = require("../src/libs/rop/ropClient");
async function main() {
const client = await createLoggedInClient({
userName: "glsadmin",
password: "123456",
apiName: "dj", // 可选,默认 dj
});
const data = await client.callSmartcarlife("dailyReport.overview.page", {
currentPage: 1,
pageSize: 10,
templateType: 1,
reportDate: "2026-07-16",
});
console.log(data.total, data.list?.length);
}
```
环境变量:
| 变量 | 说明 |
|------|------|
| `ROP_TEST_USER` / `ROP_TEST_PASSWORD` | 集成测试账号 |
| `ROP_SWAGGER_URL` | 拉取快照 / `--online` 校验时的 Swagger 地址 |
| `VUE_APP_CONFIG_CENTER_URL` | 配置中心;失败回退 `baseConfig.develop.json` |
| `ROP_INTEGRATION=1` | 开启集成测试(默认 skip) |
---
## 8. 联调 Checklist
- [ ] `npm run rop:swagger:fetch` 更新快照(或确认本地快照可用)
- [ ] `npm run rop:swagger -- ... --dry-run` 核对参数/响应
- [ ] 编写/补全 `src/api/adapters/{feature}/` adapters
- [ ] `src/api/*.js` 接入 request + adapter
- [ ] Mock 数据对齐 Swagger 字段
- [ ] `.env.development`:`VUE_APP_USE_DEVELOP_AXIOS=true`,确认未设置 feature mock 开关(或 `VUE_APP_*_MOCK` 非 `true`)
- [ ] `npm run rop:contract:check` 契约基线通过
- [ ] `npm run api:smoke:journal`(或对应冒烟脚本)通过
- [ ] 浏览器登录验证页面
---
## 9. 附录:dailyReport 接口索引
| method | adapter 请求 | adapter 响应 |
|--------|-------------|--------------|
| `dailyReport.merchant.list` | (API 层补分页) | `mapMerchantList.js` |
| `dailyReport.overview.page` | `buildOverviewParams.js` | `mapOverviewRow.js` |
| `dailyReport.detail.select` | `buildDetailSelectParams` in `mapDetailResponse.js` | `mapDetailResponse.js` |
| `merchant.staff.list` | `merchantId` | `mapMerchantStaffList.js` |
契约文件见 [`__contracts__/`](../../src/api/adapters/journalRecord/__contracts__/)。
### overview.page 请求参数
`currentPage`, `pageSize`, `merchantId`, `staffName`, `reportDate`, `templateType`
### overview 列表关键响应字段
`sceneType`, `onBreak`, `createdDate`, `reportStatus`, `staffName`, `merchantName`
### detail.select
请求:`id`(必填)
响应:`jsonContent` + 基础元信息
---
## 10. 测试策略
| 类型 | 做法 |
|------|------|
| adapter 单测 | 直接 import 纯函数,传入 fixture DTO |
| API 层单测 | `jest.mock('@/api/request')`(见 [JEST_TESTING.md](../rules/JEST_TESTING.md)) |
| 契约校验 | `npm run rop:contract:check`(对比快照与 `__contracts__`) |
| 集成测 | `tests/helpers/ropTestClient.js` + `ROP_INTEGRATION=1` |
| 冒烟脚本 | `scripts/*-smoke.js` 调用 `createLoggedInClient` |
---
## 11. 复用验收清单
新 feature 接入完成后,逐项确认:
- [ ] `npm run rop:swagger -- ... --contracts-only` 生成并提交 `__contracts__`
- [ ] adapter 单测通过(至少覆盖请求映射 + 行映射)
- [ ] `npm run rop:contract:check` 通过
- [ ] `npm run api:smoke:{feature}` 或 `npm run rop:verify` exit 0
- [ ] `.env.development` 已设 `VUE_APP_USE_DEVELOP_AXIOS=true`,未误开 feature mock(`VUE_APP_*_MOCK=true`)
- [ ] 浏览器页面可访问(需账号具备对应菜单权限)
- [ ] 脚手架未误覆盖已有 adapter(默认 skip;必要时才用 `--force`)
**一键验证命令**:
```bash
npm run rop:verify
```
包含 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`
......@@ -5,5 +5,6 @@
* 优先复用现有 API
* 使用项目已有 axios 封装
* 保持统一错误处理
* 新接口对接流程、Swagger 脚手架、adapter 约定见 [ROP 接口对接指南](../docs/ROP_API_INTEGRATION.md)
不要直接创建新的请求框架。
不要直接创建新的请求框架。Node/脚本/集成测试使用 `src/libs/rop/`,浏览器仍走 `src/api/request.js`。
......@@ -13,7 +13,10 @@
"Bash(volta install:*)",
"Bash(where:*)",
"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/契约文件
<!-- HTML for static distribution bundle build -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Swagger UI</title>
<link rel="stylesheet" type="text/css" href="./swagger-ui.css" >
<link rel="icon" type="image/png" href="./favicon-32x32.png" sizes="32x32" />
<link rel="icon" type="image/png" href="./favicon-16x16.png" sizes="16x16" />
<style>
html
{
box-sizing: border-box;
overflow: -moz-scrollbars-vertical;
overflow-y: scroll;
}
*,
*:before,
*:after
{
box-sizing: inherit;
}
body {
margin:0;
background: #fafafa;
}
.swagger-ui .topbar .download-url-wrapper{
display: none;
}
</style>
</head>
<body>
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" style="position:absolute;width:0;height:0">
<defs>
<symbol viewBox="0 0 20 20" id="unlocked">
<path d="M15.8 8H14V5.6C14 2.703 12.665 1 10 1 7.334 1 6 2.703 6 5.6V6h2v-.801C8 3.754 8.797 3 10 3c1.203 0 2 .754 2 2.199V8H4c-.553 0-1 .646-1 1.199V17c0 .549.428 1.139.951 1.307l1.197.387C5.672 18.861 6.55 19 7.1 19h5.8c.549 0 1.428-.139 1.951-.307l1.196-.387c.524-.167.953-.757.953-1.306V9.199C17 8.646 16.352 8 15.8 8z"></path>
</symbol>
<symbol viewBox="0 0 20 20" id="locked">
<path d="M15.8 8H14V5.6C14 2.703 12.665 1 10 1 7.334 1 6 2.703 6 5.6V8H4c-.553 0-1 .646-1 1.199V17c0 .549.428 1.139.951 1.307l1.197.387C5.672 18.861 6.55 19 7.1 19h5.8c.549 0 1.428-.139 1.951-.307l1.196-.387c.524-.167.953-.757.953-1.306V9.199C17 8.646 16.352 8 15.8 8zM12 8H8V5.199C8 3.754 8.797 3 10 3c1.203 0 2 .754 2 2.199V8z"/>
</symbol>
<symbol viewBox="0 0 20 20" id="close">
<path d="M14.348 14.849c-.469.469-1.229.469-1.697 0L10 11.819l-2.651 3.029c-.469.469-1.229.469-1.697 0-.469-.469-.469-1.229 0-1.697l2.758-3.15-2.759-3.152c-.469-.469-.469-1.228 0-1.697.469-.469 1.228-.469 1.697 0L10 8.183l2.651-3.031c.469-.469 1.228-.469 1.697 0 .469.469.469 1.229 0 1.697l-2.758 3.152 2.758 3.15c.469.469.469 1.229 0 1.698z"/>
</symbol>
<symbol viewBox="0 0 20 20" id="large-arrow">
<path d="M13.25 10L6.109 2.58c-.268-.27-.268-.707 0-.979.268-.27.701-.27.969 0l7.83 7.908c.268.271.268.709 0 .979l-7.83 7.908c-.268.271-.701.27-.969 0-.268-.269-.268-.707 0-.979L13.25 10z"/>
</symbol>
<symbol viewBox="0 0 20 20" id="large-arrow-down">
<path d="M17.418 6.109c.272-.268.709-.268.979 0s.271.701 0 .969l-7.908 7.83c-.27.268-.707.268-.979 0l-7.908-7.83c-.27-.268-.27-.701 0-.969.271-.268.709-.268.979 0L10 13.25l7.418-7.141z"/>
</symbol>
<symbol viewBox="0 0 24 24" id="jump-to">
<path d="M19 7v4H5.83l3.58-3.59L8 6l-6 6 6 6 1.41-1.41L5.83 13H21V7z"/>
</symbol>
<symbol viewBox="0 0 24 24" id="expand">
<path d="M10 18h4v-2h-4v2zM3 6v2h18V6H3zm3 7h12v-2H6v2z"/>
</symbol>
</defs>
</svg>
<div id="swagger-ui"></div>
<script src="./swagger-ui-bundle.js"> </script>
<script src="./swagger-ui-standalone-preset.js"> </script>
<script>
window.onload = function() {
// Build a system
const ui = SwaggerUIBundle({
url: window.location.href.replace(/swagger-ui\/v3\/index.html/, "swagger-rop/api-docs"),
dom_id: '#swagger-ui',
deepLinking: true,
presets: [
SwaggerUIBundle.presets.apis,
SwaggerUIStandalonePreset
],
plugins: [
SwaggerUIBundle.plugins.DownloadUrl
],
layout: "StandaloneLayout"
})
window.ui = ui
}
</script>
</body>
</html>
......@@ -4,4 +4,9 @@
# VUE_APP_API=http://192.168.3.171:7300/mock/5d638b3b6fbe9a0ac59d872e/tFIMS
VUE_APP_REPO=http://192.168.3.171:7300/mock/5be17454f31545347559d499/config
VUE_APP_CONFIG_CENTER_URL=https://config-center-backend.glsx.com.cn/glsxAdmin/config?moduleUrl=dj-car-life-system-config
# 使用 develop 环境完整配置(含 axios.appkey/secret/baseURL)
# oss mock 不可用时,main.js 会回退到 src/common/baseConfig.develop.json
VUE_APP_CONFIG_CENTER_URL=https://oss-config.test.glsx.com.cn/mock/5be17454f31545347559d499/config
VUE_APP_USE_DEVELOP_AXIOS=true
# 门店工作汇报:默认走真实 dailyReport 接口;本地需 Mock 时设 VUE_APP_JOURNAL_MOCK=true
......@@ -42,3 +42,6 @@ yarn-error.log*
# test
/playwright/
/testCase/
# ROP import runtime report
rop-import.report.json
......@@ -6,6 +6,7 @@
- /.ai/rules/ 目录下的文件
- /.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
## 项目概述
......
/**
* E2E 登录辅助(Vuex 内存登录态)
*
* 本项目路由守卫依赖 store 内存,不能用 storageState 跨 context。
* 新用例请在 beforeAll 中调用 createLoggedInPage,整文件复用返回的 page。
*/
export function getBaseUrl() {
return (process.env.BASE_URL || "http://192.168.1.146:8080/dj-carlife-web/").replace(
/\/$/,
"",
);
}
export async function login(page, {
account = "glsadmin",
password = "123456",
} = {}) {
const baseUrl = getBaseUrl();
await page.goto(`${baseUrl}/#/login`);
await page.getByPlaceholder("账户").fill(account);
await page.getByPlaceholder("密码").fill(password);
await page.getByRole("button", { name: "登录" }).click();
await page.waitForURL(/#\/index/);
await page.waitForLoadState("networkidle");
}
/**
* 创建已登录的共享 page(beforeAll 调用一次即可)
* @returns {Promise<import('@playwright/test').Page>}
*/
export async function createLoggedInPage(browser, options = {}) {
const context = await browser.newContext();
const page = await context.newPage();
page.setDefaultTimeout(options.timeout || 10000);
page.setDefaultNavigationTimeout(options.navigationTimeout || 30000);
await login(page, options);
return page;
}
import path from "path";
import { expect, test } from "@playwright/test";
import { createLoggedInPage, getBaseUrl } from "./helpers/auth.js";
const BASE_URL = (process.env.BASE_URL || "http://192.168.1.146:8080/dj-carlife-web/").replace(/\/$/, "");
const BASE_URL = getBaseUrl();
const IMAGE_FIXTURE = path.resolve(process.cwd(), "public", "header-man.jpg");
const LOGIN_ACCOUNT = "glsadmin";
......@@ -41,15 +42,6 @@ async function waitForModifyPageReady(page) {
}, null, { timeout: 60000 });
}
async function login(page) {
await page.goto(`${BASE_URL}/#/login`);
await page.getByPlaceholder("账户").fill(LOGIN_ACCOUNT);
await page.getByPlaceholder("密码").fill(LOGIN_PASSWORD);
await page.getByRole("button", { name: "登录" }).click();
await page.waitForURL(/#\/index/);
await waitForNetworkStable(page);
}
async function gotoStrategyList(page) {
await page.goto(`${BASE_URL}/#/marketing-push-strategy`);
await waitForNetworkStable(page);
......@@ -205,11 +197,13 @@ test.describe.serial("营销推送策略 E2E", () => {
let editedStrategyName = "";
test.beforeAll(async ({ browser }) => {
const context = await browser.newContext();
sharedPage = await context.newPage();
sharedPage.setDefaultTimeout(20000);
sharedPage.setDefaultNavigationTimeout(60000);
await login(sharedPage);
sharedPage = await createLoggedInPage(browser, {
account: LOGIN_ACCOUNT,
password: LOGIN_PASSWORD,
timeout: 20000,
navigationTimeout: 60000,
});
await sharedPage.waitForTimeout(500);
});
test.afterAll(async () => {
......
......@@ -15,32 +15,19 @@
*/
import { expect, test } from "@playwright/test";
import { createLoggedInPage, getBaseUrl } from "./helpers/auth.js";
const BASE_URL = "http://192.168.1.146:8080/dj-carlife-web";
const BASE_URL = getBaseUrl();
test.describe("任务中心 (Task Center)", () => {
let sharedPage;
// 全局前置:只运行一次,登录后共享 page
// 全局前置:只运行一次,登录后共享 page(Vuex 内存态)
test.beforeAll(async ({ browser }) => {
const context = await browser.newContext();
sharedPage = await context.newPage();
// 执行登录
await sharedPage.goto(`${BASE_URL}/#/login`);
await sharedPage.getByPlaceholder("账户").fill("glsadmin");
await sharedPage.getByPlaceholder("密码").fill("123456");
await sharedPage.getByRole("button", { name: "登录" }).click();
await sharedPage.waitForURL(/#\/index/);
await sharedPage.waitForLoadState("networkidle");
sharedPage = await createLoggedInPage(browser);
console.log("登录完成");
});
// 每个 test 复用共享 page,设置默认超时
test.beforeEach(async () => {
sharedPage.setDefaultTimeout(10000);
sharedPage.setDefaultNavigationTimeout(30000);
});
// 全部测试结束后清理
test.afterAll(async () => {
await sharedPage.context().close();
......
......@@ -31,6 +31,7 @@ module.exports = {
testMatch: [
"**/*.spec.js",
"**/*.integration.spec.js",
"tests/**/*.spec.js",
],
testURL: "http://localhost/",
testEnvironment: "jsdom",
......
......@@ -10,6 +10,12 @@
"build": "vue-cli-service build --no-module",
"build:nomock": "vue-cli-service build --mode nomock",
"lint": "vue-cli-service lint --fix",
"api:smoke:journal": "node scripts/journalRecord.api-smoke.js",
"rop:swagger": "node scripts/rop-swagger-scaffold.js",
"rop:swagger:fetch": "node scripts/rop-swagger-fetch.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",
"report": "set NODE_OPTIONS=--openssl-legacy-provider && vue-cli-service build --report",
"test:unit": "vue-cli-service test:unit"
},
......
......@@ -14,7 +14,8 @@ import { defineConfig, devices } from "@playwright/test";
import dayjs from "dayjs";
// 生成时间戳,用于报告和结果目录
const timestamp = dayjs().format("YYYY-MM-DD HH:mm:ss");
// Windows 路径不能含冒号;报告/结果目录用安全时间戳
const timestamp = dayjs().format("YYYY-MM-DD_HH-mm-ss");
export default defineConfig({
// 测试文件位置
......
/**
* dailyReport 接口冒烟测试
* 用法: npm run api:smoke:journal
*/
const { createLoggedInClient } = require("../src/libs/rop/ropClient");
async function main() {
const client = await createLoggedInClient();
console.log("axios.baseURL:", client.config.baseURL);
console.log("axios.appkey:", client.config.appkey);
console.log("env:", client.config.env);
const merchantData = await client.callSmartcarlife("dailyReport.merchant.list", {
currentPage: 1,
pageSize: 10,
});
console.log(" merchant.list total:", merchantData?.total, "listLen:", merchantData?.list?.length);
const reportDate = new Date().toISOString().slice(0, 10);
const tabs = [
["staffDaily", 1],
["storeDaily", 2],
["negotiation", 3],
];
let fallbackMerchantId = merchantData?.list?.[0]?.merchantId;
for (const [tabKey, templateType] of tabs) {
const overviewData = await client.callSmartcarlife("dailyReport.overview.page", {
currentPage: 1,
pageSize: 10,
templateType,
reportDate,
});
console.log(`[OK] dailyReport.overview.page (${tabKey}) total:`, overviewData?.total);
if (!fallbackMerchantId && overviewData?.list?.[0]?.merchantId) {
fallbackMerchantId = overviewData.list[0].merchantId;
}
const firstId = overviewData?.list?.[0]?.id;
if (firstId) {
const detailData = await client.callSmartcarlife("dailyReport.detail.select", { id: firstId });
console.log(` detail ${tabKey} id=${firstId} jsonContent=`, !!detailData?.jsonContent);
}
}
if (fallbackMerchantId) {
const staffData = await client.callSmartcarlife("merchant.staff.list", {
merchantId: fallbackMerchantId,
});
const staffLen = Array.isArray(staffData) ? staffData.length : staffData?.list?.length;
console.log(`[OK] merchant.staff.list merchantId=${fallbackMerchantId} len=`, staffLen);
} else {
console.log("[SKIP] merchant.staff.list: 无可用 merchantId");
}
console.log("\nAll dailyReport smoke tests passed.");
}
main().catch((error) => {
console.error("\nSmoke test failed:", error.message);
process.exit(1);
});
/**
* ROP 接口冒烟模板(复制后改名使用)
*
* 1. 复制为 scripts/{feature}.api-smoke.js
* 2. 替换 METHOD_SUFFIX / PARAMS / 日志标签
* 3. package.json 增加 "api:smoke:{feature}": "node scripts/{feature}.api-smoke.js"
*/
const { createLoggedInClient } = require("../src/libs/rop/ropClient");
// TODO: 改为真实接口后缀,如 dailyReport.overview.page
const METHOD_SUFFIX = "your.api.suffix";
// TODO: 按 Swagger 契约填写请求参数
const PARAMS = {
currentPage: 1,
pageSize: 10,
};
async function main() {
const client = await createLoggedInClient();
console.log("axios.baseURL:", client.config.baseURL);
const data = await client.callSmartcarlife(METHOD_SUFFIX, PARAMS);
console.log(`[OK] ${METHOD_SUFFIX}`, {
isArray: Array.isArray(data),
total: data?.total,
listLen: Array.isArray(data) ? data.length : data?.list?.length,
});
console.log("\nSmoke test passed.");
}
main().catch((error) => {
console.error("\nSmoke test failed:", error.message);
process.exit(1);
});
#!/usr/bin/env node
/**
* 校验已跟踪 contract 与 Swagger 快照是否一致
*
* 默认离线模式(读本地快照):
* npm run rop:contract:check
*
* 对比线上与快照差异后校验:
* npm run rop:contract:check -- --online
*/
const {
loadSwagger,
DEFAULT_SWAGGER_SNAPSHOT,
} = require("../src/libs/rop/swaggerInspect");
const {
findTrackedContracts,
diffSnapshotWithTracked,
diffOnlineSnapshot,
} = require("../src/libs/rop/contractDiff");
const DEFAULT_ONLINE_URL = process.env.ROP_SWAGGER_URL
|| "http://dj.dev.glsx.com.cn/rop-dj-smartcarlife/swagger-rop/api-docs";
function parseArgs(argv) {
const args = {};
for (let i = 2; i < argv.length; i += 1) {
const key = argv[i];
if (!key.startsWith("--")) {
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(title, report) {
console.log(`\n=== ${title} ===`);
if (report.checked != null) {
console.log(`Checked: ${report.checked}`);
}
if (report.added?.length) {
console.log("Added methods:", report.added.slice(0, 5).join(", "), report.added.length > 5 ? "..." : "");
}
if (report.removed?.length) {
console.log("Removed methods:", report.removed.slice(0, 5).join(", "), report.removed.length > 5 ? "..." : "");
}
report.warnings?.forEach((message) => console.warn("WARN:", message));
report.errors?.forEach((message) => console.error("ERROR:", message));
}
async function main() {
const args = parseArgs(process.argv);
const snapshotPath = args.snapshot || DEFAULT_SWAGGER_SNAPSHOT;
const tracked = findTrackedContracts();
if (!tracked.length) {
console.warn("No tracked contracts found under src/api/adapters/**/__contracts__");
process.exit(0);
}
const snapshot = await loadSwagger(snapshotPath);
let errors = [];
let warnings = [];
if (args.online) {
const onlineUrl = args.url || DEFAULT_ONLINE_URL;
const online = await loadSwagger(onlineUrl);
const onlineReport = diffOnlineSnapshot(snapshot, online);
printReport("Online vs Snapshot", onlineReport);
warnings = warnings.concat(onlineReport.warnings || []);
}
const trackedReport = diffSnapshotWithTracked(snapshot, tracked);
printReport("Tracked Contracts vs Snapshot", trackedReport);
errors = errors.concat(trackedReport.errors || []);
warnings = warnings.concat(trackedReport.warnings || []);
if (errors.length) {
console.error(`\nContract check failed with ${errors.length} error(s).`);
process.exit(1);
}
console.log(`\nContract check passed (${tracked.length} tracked, ${warnings.length} warning(s)).`);
}
main().catch((error) => {
console.error("Contract check failed:", error.message);
process.exit(1);
});
#!/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,
};
#!/usr/bin/env node
/**
* 拉取 ROP Swagger 契约快照
*
* 示例:
* npm run rop:swagger:fetch
* npm run rop:swagger:fetch -- --url http://dj.dev.glsx.com.cn/rop-dj-smartcarlife/swagger-rop/api-docs
*/
const fs = require("fs");
const path = require("path");
const { loadSwagger, countRouterMethods } = require("../src/libs/rop/swaggerInspect");
const DEFAULT_URL = process.env.ROP_SWAGGER_URL
|| "http://dj.dev.glsx.com.cn/rop-dj-smartcarlife/swagger-rop/api-docs";
const DEFAULT_OUT = path.join(
__dirname,
"../src/libs/rop/__snapshots__/smartcarlife.swagger.json",
);
function parseArgs(argv) {
const args = {};
for (let i = 2; i < argv.length; i += 1) {
const key = argv[i];
if (!key.startsWith("--")) {
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;
}
async function main() {
const args = parseArgs(process.argv);
const url = args.url || DEFAULT_URL;
const out = path.resolve(args.out || DEFAULT_OUT);
const swagger = await loadSwagger(url);
const methodCount = countRouterMethods(swagger);
ensureDir(path.dirname(out));
fs.writeFileSync(out, `${JSON.stringify(swagger, null, 2)}\n`, "utf8");
console.log("Fetched:", url);
console.log("Wrote:", out);
console.log("Router methods:", methodCount);
}
function ensureDir(dir) {
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir, { recursive: true });
}
}
main().catch((error) => {
console.error("Fetch failed:", error.message);
process.exit(1);
});
#!/usr/bin/env node
/**
* ROP Swagger 契约查阅 + adapter 脚手架
*
* 示例:
* node scripts/rop-swagger-scaffold.js \
* --prefix dj.api.smartcarlife.dailyReport \
* --out src/api/adapters/journalRecord
*
* node scripts/rop-swagger-scaffold.js \
* --method dj.api.smartcarlife.dailyReport.overview.page \
* --out src/api/adapters/journalRecord
*/
const fs = require("fs");
const path = require("path");
const {
loadSwagger,
buildContract,
formatContractMarkdown,
buildParamsTemplate,
buildResponseTemplate,
buildMockStub,
toMethodFileName,
methodSuffixToPascal,
listMethodsByPrefix,
DEFAULT_SWAGGER_SNAPSHOT,
} = require("../src/libs/rop/swaggerInspect");
function parseArgs(argv) {
const args = {};
for (let i = 2; i < argv.length; i += 1) {
const key = argv[i];
if (!key.startsWith("--")) {
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 ensureDir(dir) {
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir, { recursive: true });
}
}
function writeFileSafe(filePath, content, { dryRun, force }) {
if (dryRun) {
console.log(`\n--- ${filePath} ---\n${content}`);
return "wrote";
}
if (fs.existsSync(filePath) && !force) {
console.warn("Skipped (exists, use --force to overwrite):", filePath);
return "skipped";
}
ensureDir(path.dirname(filePath));
fs.writeFileSync(filePath, content, "utf8");
console.log("Wrote:", filePath);
return "wrote";
}
function scaffoldMethod(swaggerDoc, method, out, feature, writeOpts) {
const contract = buildContract(swaggerDoc, method);
const pascal = methodSuffixToPascal(method);
const methodFile = toMethodFileName(method);
const adaptersDir = path.resolve(out);
const contractsDir = path.join(adaptersDir, "__contracts__");
const paramsFile = path.join(adaptersDir, `build${pascal}Params.js`);
const responseFile = path.join(adaptersDir, `map${pascal}Response.js`);
const contractJson = path.join(contractsDir, `${methodFile}.contract.json`);
const contractMd = path.join(contractsDir, `${methodFile}.contract.md`);
const results = {
method,
files: [],
};
results.files.push(writeFileSafe(contractJson, `${JSON.stringify(contract, null, 2)}\n`, writeOpts));
results.files.push(writeFileSafe(contractMd, `${formatContractMarkdown(contract)}\n`, writeOpts));
if (!writeOpts.contractsOnly) {
results.files.push(writeFileSafe(paramsFile, buildParamsTemplate(contract), writeOpts));
results.files.push(writeFileSafe(responseFile, buildResponseTemplate(contract), writeOpts));
}
if (feature && !writeOpts.contractsOnly) {
const mockPath = path.resolve("src/api", `${feature}.mock.js`);
const fnName = `mock${pascal}`;
const mockStub = buildMockStub(contract, feature);
console.log(`\nMock 提示: 请在 src/api/${feature}.mock.js 中手动添加 ${fnName}`);
console.log("参考模板:");
console.log(mockStub.trim());
if (mockFlag(writeOpts) && !writeOpts.dryRun) {
if (fs.existsSync(mockPath)) {
console.warn("Mock 文件已存在,未自动修改:", mockPath);
} else {
const mockContent = `function delay(result, ms = 300) {
\treturn new Promise((resolve) => {
\t\tsetTimeout(() => resolve(result), ms);
\t});
}
${mockStub}`;
writeFileSafe(mockPath, mockContent, writeOpts);
}
}
}
return results;
}
function mockFlag(writeOpts) {
return !!writeOpts.mock;
}
function summarizeRow(results) {
const wrote = results.files.filter((s) => s === "wrote").length;
const skipped = results.files.filter((s) => s === "skipped").length;
return { wrote, skipped, failed: 0 };
}
async function main() {
const args = parseArgs(process.argv);
const {
swagger,
method,
prefix,
feature,
out,
"dry-run": dryRunFlag,
force: forceFlag,
mock: mockFlagArg,
"contracts-only": contractsOnlyFlag,
} = args;
if (!out || (!method && !prefix)) {
console.error(
"Usage: node scripts/rop-swagger-scaffold.js "
+ "--out <adapterDir> (--method <rop.method> | --prefix <rop.prefix>) "
+ "[--swagger <url|path>] [--feature name] [--dry-run] [--force] [--mock] [--contracts-only]",
);
process.exit(1);
}
if (method && prefix) {
console.error("Error: --method and --prefix are mutually exclusive");
process.exit(1);
}
const swaggerSource = swagger || DEFAULT_SWAGGER_SNAPSHOT;
const writeOpts = {
dryRun: !!dryRunFlag,
force: !!forceFlag,
mock: !!mockFlagArg,
contractsOnly: !!contractsOnlyFlag,
};
const swaggerDoc = await loadSwagger(swaggerSource);
const methods = method ? [method] : listMethodsByPrefix(swaggerDoc, prefix);
if (!methods.length) {
console.error(prefix ? `No methods found for prefix: ${prefix}` : `Method not found: ${method}`);
process.exit(1);
}
console.log(`Swagger: ${swaggerSource}`);
console.log(`Methods: ${methods.length}`);
const summary = [];
methods.forEach((item) => {
try {
const result = scaffoldMethod(swaggerDoc, item, out, feature, writeOpts);
const row = summarizeRow(result);
summary.push({ method: item, ...row });
console.log("\nContract summary:", item);
const contract = buildContract(swaggerDoc, item);
console.log("Request params:", contract.request.parameters.map((p) => p.name).join(", "));
console.log("Response root:", contract.response.rootType);
if (contract.response.pagination) {
console.log("Pagination:", contract.response.pagination.type);
}
} catch (error) {
console.error(`Failed: ${item} - ${error.message}`);
summary.push({ method: item, wrote: 0, skipped: 0, failed: 1 });
}
});
console.log("\n=== Summary ===");
console.log("method | wrote | skipped | failed");
summary.forEach((row) => {
console.log(`${row.method} | ${row.wrote} | ${row.skipped} | ${row.failed}`);
});
if (summary.some((row) => row.failed > 0)) {
process.exit(1);
}
}
main().catch((error) => {
console.error("Scaffold failed:", error.message);
process.exit(1);
});
import { mapAbnormalFlowDeclarationApproveResponse } from "./adapters/abnormalFlowDeclaration/mapAbnormalFlowDeclarationApproveResponse";
import { mapAbnormalFlowDeclarationDetailResponse } from "./adapters/abnormalFlowDeclaration/mapAbnormalFlowDeclarationDetailResponse";
function delay(result, ms = 300) {
return new Promise((resolve) => {
setTimeout(() => resolve(result), ms);
......@@ -218,17 +220,17 @@ export function mockPcAbnormalFlowDeclarationDetail(data = {}) {
if (!item) {
return delayReject(new Error("报备记录不存在"));
}
return delay({
tradeInfo: buildTradeFields(item),
declarationInfo: {
abnormalType: item.abnormalType,
remark: item.remark,
createdBy: item.createdBy,
createdDate: item.createdDate,
voucherImageUrls: item.voucherImageUrls,
},
approvalLogs: item.approvalLogs || [],
});
return delay(mapAbnormalFlowDeclarationDetailResponse({
tradeInfo: buildTradeFields(item),
declarationInfo: {
abnormalType: item.abnormalType,
remark: item.remark,
createdBy: item.createdBy,
createdDate: item.createdDate,
voucherImageUrls: item.voucherImageUrls,
},
approvalLogs: item.approvalLogs || [],
}));
}
export function mockApprovePcAbnormalFlowDeclaration(data = {}) {
......@@ -248,5 +250,5 @@ export function mockApprovePcAbnormalFlowDeclaration(data = {}) {
remark: data.remark || "",
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;
{
"method": "dj.api.smartcarlife.dailyReport.detail.select",
"route": "/router/dj.api.smartcarlife.dailyReport.detail.select/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": "DailyReportDetailResponse",
"description": "成功返回数据",
"required": false
},
{
"name": "data.merchantId",
"type": "integer:int32",
"description": "4s店商户号",
"required": false
},
{
"name": "data.merchantName",
"type": "string",
"description": "4s店商户名称",
"required": false
},
{
"name": "data.staffName",
"type": "string",
"description": "驻店员工",
"required": false
},
{
"name": "data.staffUuid",
"type": "string",
"description": "驻店员工uuid",
"required": false
},
{
"name": "data.sceneType",
"type": "string:byte",
"description": "业务场景(0:权益,1:轻改)",
"required": false
},
{
"name": "data.reportStatus",
"type": "integer:int32",
"description": "填报状态:0=草稿,1=已提交",
"required": false
},
{
"name": "data.reportDate",
"type": "string",
"description": "日期(yyyy-MM-dd)",
"required": false
},
{
"name": "data.jsonContent",
"type": "string",
"description": "填报内容",
"required": false
}
],
"pagination": null,
"rootType": "RopResponse<DailyReportDetailResponse>"
}
}
# dj.api.smartcarlife.dailyReport.detail.select
> 门店工作汇报(日报)详情查询
## Request
| 参数 | 位置 | 类型 | 必填 | 说明 |
|------|------|------|------|------|
| id | query | integer | 是 | 日报记录ID |
| sessionId | query | string | 是 | 会话ID |
## Response
| 字段 | 类型 | 说明 |
|------|------|------|
| code | string | 响应状态(0:成功;1:失败) |
| errId | string | 错误码 |
| message | string | 错误描述 |
| data | DailyReportDetailResponse | 成功返回数据 |
| data.merchantId | integer:int32 | 4s店商户号 |
| data.merchantName | string | 4s店商户名称 |
| data.staffName | string | 驻店员工 |
| data.staffUuid | string | 驻店员工uuid |
| data.sceneType | string:byte | 业务场景(0:权益,1:轻改) |
| data.reportStatus | integer:int32 | 填报状态:0=草稿,1=已提交 |
| data.reportDate | string | 日期(yyyy-MM-dd) |
| data.jsonContent | string | 填报内容 |
{
"method": "dj.api.smartcarlife.dailyReport.merchant.list",
"route": "/router/dj.api.smartcarlife.dailyReport.merchant.list/1.0.0",
"summary": "新版本日报填报门店列表查询",
"request": {
"parameters": [
{
"name": "currentPage",
"in": "query",
"type": "int",
"required": false,
"description": "当前页码"
},
{
"name": "pageSize",
"in": "query",
"type": "int",
"required": false,
"description": "每页条数"
},
{
"name": "merchantName",
"in": "query",
"type": "string",
"required": false,
"description": "商户名称"
}
]
},
"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": "RpcPagination<DailyReportWhiteListMerchantResponse>",
"description": "成功返回数据",
"required": false
},
{
"name": "data.pageNum",
"type": "integer:int32",
"description": "",
"required": false
},
{
"name": "data.pageSize",
"type": "integer:int32",
"description": "",
"required": false
},
{
"name": "data.startRow",
"type": "integer:int64",
"description": "",
"required": false
},
{
"name": "data.endRow",
"type": "integer:int64",
"description": "",
"required": false
},
{
"name": "data.total",
"type": "integer:int64",
"description": "",
"required": false
},
{
"name": "data.pages",
"type": "integer:int32",
"description": "",
"required": false
},
{
"name": "data.list",
"type": "array<DailyReportWhiteListMerchantResponse>",
"description": "",
"required": false
},
{
"name": "data.condition",
"type": "DailyReportWhiteListMerchantResponse",
"description": "",
"required": false
},
{
"name": "data.needCount",
"type": "boolean",
"description": "",
"required": false
}
],
"pagination": {
"wrapper": "RopResponse<RpcPagination<DailyReportWhiteListMerchantResponse>>",
"type": "RpcPagination<DailyReportWhiteListMerchantResponse>",
"fields": [
"pageNum",
"pageSize",
"total",
"list"
]
},
"rootType": "RopResponse<RpcPagination<DailyReportWhiteListMerchantResponse>>"
}
}
# dj.api.smartcarlife.dailyReport.merchant.list
> 新版本日报填报门店列表查询
## Request
| 参数 | 位置 | 类型 | 必填 | 说明 |
|------|------|------|------|------|
| currentPage | query | int | 否 | 当前页码 |
| pageSize | query | int | 否 | 每页条数 |
| merchantName | query | string | 否 | 商户名称 |
## Response
分页: `RpcPagination<DailyReportWhiteListMerchantResponse>` (pageNum, pageSize, total, list)
| 字段 | 类型 | 说明 |
|------|------|------|
| code | string | 响应状态(0:成功;1:失败) |
| errId | string | 错误码 |
| message | string | 错误描述 |
| data | RpcPagination<DailyReportWhiteListMerchantResponse> | 成功返回数据 |
| data.pageNum | integer:int32 | |
| data.pageSize | integer:int32 | |
| data.startRow | integer:int64 | |
| data.endRow | integer:int64 | |
| data.total | integer:int64 | |
| data.pages | integer:int32 | |
| data.list | array<DailyReportWhiteListMerchantResponse> | |
| data.condition | DailyReportWhiteListMerchantResponse | |
| data.needCount | boolean | |
{
"method": "dj.api.smartcarlife.dailyReport.overview.page",
"route": "/router/dj.api.smartcarlife.dailyReport.overview.page/1.0.0",
"summary": "门店工作汇报(日报)列表查询",
"request": {
"parameters": [
{
"name": "currentPage",
"in": "query",
"type": "int",
"required": false,
"description": "当前页码"
},
{
"name": "pageSize",
"in": "query",
"type": "int",
"required": false,
"description": "每页条数"
},
{
"name": "merchantId",
"in": "query",
"type": "integer",
"required": false,
"description": "商户ID"
},
{
"name": "staffName",
"in": "query",
"type": "string",
"required": false,
"description": "驻店员工"
},
{
"name": "reportDate",
"in": "query",
"type": "string",
"required": false,
"description": "日期(yyyy-MM-dd)"
},
{
"name": "templateType",
"in": "query",
"type": "byte",
"required": false,
"description": "模板类型:1=驻店日报,2=门店日报,3=洽谈明细"
},
{
"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": "RpcPagination<DailyReportOverviewResponse>",
"description": "成功返回数据",
"required": false
},
{
"name": "data.pageNum",
"type": "integer:int32",
"description": "",
"required": false
},
{
"name": "data.pageSize",
"type": "integer:int32",
"description": "",
"required": false
},
{
"name": "data.startRow",
"type": "integer:int64",
"description": "",
"required": false
},
{
"name": "data.endRow",
"type": "integer:int64",
"description": "",
"required": false
},
{
"name": "data.total",
"type": "integer:int64",
"description": "",
"required": false
},
{
"name": "data.pages",
"type": "integer:int32",
"description": "",
"required": false
},
{
"name": "data.list",
"type": "array<DailyReportOverviewResponse>",
"description": "",
"required": false
},
{
"name": "data.condition",
"type": "DailyReportOverviewResponse",
"description": "",
"required": false
},
{
"name": "data.needCount",
"type": "boolean",
"description": "",
"required": false
}
],
"pagination": {
"wrapper": "RopResponse<RpcPagination<DailyReportOverviewResponse>>",
"type": "RpcPagination<DailyReportOverviewResponse>",
"fields": [
"pageNum",
"pageSize",
"total",
"list"
]
},
"rootType": "RopResponse<RpcPagination<DailyReportOverviewResponse>>"
}
}
# dj.api.smartcarlife.dailyReport.overview.page
> 门店工作汇报(日报)列表查询
## Request
| 参数 | 位置 | 类型 | 必填 | 说明 |
|------|------|------|------|------|
| currentPage | query | int | 否 | 当前页码 |
| pageSize | query | int | 否 | 每页条数 |
| merchantId | query | integer | 否 | 商户ID |
| staffName | query | string | 否 | 驻店员工 |
| reportDate | query | string | 否 | 日期(yyyy-MM-dd) |
| templateType | query | byte | 否 | 模板类型:1=驻店日报,2=门店日报,3=洽谈明细 |
| sessionId | query | string | 是 | 会话ID |
## Response
分页: `RpcPagination<DailyReportOverviewResponse>` (pageNum, pageSize, total, list)
| 字段 | 类型 | 说明 |
|------|------|------|
| code | string | 响应状态(0:成功;1:失败) |
| errId | string | 错误码 |
| message | string | 错误描述 |
| data | RpcPagination<DailyReportOverviewResponse> | 成功返回数据 |
| data.pageNum | integer:int32 | |
| data.pageSize | integer:int32 | |
| data.startRow | integer:int64 | |
| data.endRow | integer:int64 | |
| data.total | integer:int64 | |
| data.pages | integer:int32 | |
| data.list | array<DailyReportOverviewResponse> | |
| data.condition | DailyReportOverviewResponse | |
| data.needCount | boolean | |
{
"method": "dj.api.smartcarlife.merchant.staff.list",
"route": "/router/dj.api.smartcarlife.merchant.staff.list/1.0.0",
"summary": "根据4s店或者园区店查询员工信息",
"request": {
"parameters": [
{
"name": "merchantId",
"in": "query",
"type": "integer",
"required": false,
"description": "4s店商户号"
},
{
"name": "yqMerchantId",
"in": "query",
"type": "integer",
"required": false,
"description": "园区店店商户号"
}
]
},
"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": "array<ServiceStaffRopResponse>",
"description": "成功返回数据",
"required": false
},
{
"name": "data[].id",
"type": "integer:int32",
"description": "",
"required": false
},
{
"name": "data[].merchantNo",
"type": "integer:int32",
"description": "员工所在商户号",
"required": false
},
{
"name": "data[].merchantName",
"type": "string",
"description": "员工所在商户名",
"required": false
},
{
"name": "data[].staffName",
"type": "string",
"description": "员工姓名",
"required": false
},
{
"name": "data[].staffPhone",
"type": "string",
"description": "员工手机号",
"required": false
},
{
"name": "data[].departmentName",
"type": "string",
"description": "员工所属部门",
"required": false
},
{
"name": "data[].visibleMerchantNo",
"type": "string",
"description": "员工可见4s店",
"required": false
},
{
"name": "data[].visibleMerchantList",
"type": "array<MerchantNoNameRpcResponse>",
"description": "员工可见列表",
"required": false
},
{
"name": "data[].weChatAvatarUrl",
"type": "string",
"description": "微信头像",
"required": false
},
{
"name": "data[].staffUuid",
"type": "string",
"description": "员工uuid",
"required": false
},
{
"name": "data[].visualType",
"type": "integer:int32",
"description": "可见范围:0全部客户: 1:部分可见",
"required": false
},
{
"name": "data[].createdDate",
"type": "string",
"description": "",
"required": false
},
{
"name": "data[].staffBusinessType",
"type": "string:byte",
"description": "员工类型 0-驻店 1-技师",
"required": false
},
{
"name": "data[].staffLabel",
"type": "string",
"description": "员工开通业务场景标签",
"required": false
},
{
"name": "data[].auditStatus",
"type": "integer:int32",
"description": "审核状态 0:待审核 1:审核通过 2:已驳回",
"required": false
},
{
"name": "data[].merchantBrandCars",
"type": "string",
"description": "",
"required": false
},
{
"name": "data[].merchantBrandMain",
"type": "string",
"description": "",
"required": false
}
],
"pagination": null,
"rootType": "RopResponse<List<ServiceStaffRopResponse>>"
}
}
# dj.api.smartcarlife.merchant.staff.list
> 根据4s店或者园区店查询员工信息
## Request
| 参数 | 位置 | 类型 | 必填 | 说明 |
|------|------|------|------|------|
| merchantId | query | integer | 否 | 4s店商户号 |
| yqMerchantId | query | integer | 否 | 园区店店商户号 |
## Response
| 字段 | 类型 | 说明 |
|------|------|------|
| code | string | 响应状态(0:成功;1:失败) |
| errId | string | 错误码 |
| message | string | 错误描述 |
| data | array<ServiceStaffRopResponse> | 成功返回数据 |
| data[].id | integer:int32 | |
| data[].merchantNo | integer:int32 | 员工所在商户号 |
| data[].merchantName | string | 员工所在商户名 |
| data[].staffName | string | 员工姓名 |
| data[].staffPhone | string | 员工手机号 |
| data[].departmentName | string | 员工所属部门 |
| data[].visibleMerchantNo | string | 员工可见4s店 |
| data[].visibleMerchantList | array<MerchantNoNameRpcResponse> | 员工可见列表 |
| data[].weChatAvatarUrl | string | 微信头像 |
| data[].staffUuid | string | 员工uuid |
| data[].visualType | integer:int32 | 可见范围:0全部客户: 1:部分可见 |
| data[].createdDate | string | |
| data[].staffBusinessType | string:byte | 员工类型 0-驻店 1-技师 |
| data[].staffLabel | string | 员工开通业务场景标签 |
| data[].auditStatus | integer:int32 | 审核状态 0:待审核 1:审核通过 2:已驳回 |
| data[].merchantBrandCars | string | |
| data[].merchantBrandMain | string | |
import { getTemplateTypeByTabKey } from "@/views/residentManage/journalRecord/constants";
/**
* d2-table 查询参数 → dailyReport.overview.page 请求体
*/
export function buildOverviewParams(params = {}, activeTabKey = "staffDaily") {
const payload = {
templateType: getTemplateTypeByTabKey(activeTabKey),
reportDate: params.reportDate,
currentPage: params.currentPage,
pageSize: params.pageSize,
};
if (params.merchantId) {
payload.merchantId = params.merchantId;
}
if (params.staffName) {
payload.staffName = params.staffName;
}
return payload;
}
export default buildOverviewParams;
import { mapSceneType } from "./mapSceneType";
/**
* 详情路由 query → dailyReport.detail.select 请求体
*/
export function buildDetailSelectParams({ id } = {}) {
return { id };
}
/**
* dailyReport.detail.select 响应 → 详情页 detail 对象
*/
export function mapDetailResponse(res = {}, fallback = {}) {
const scene = mapSceneType(res.sceneType ?? fallback.sceneType);
return {
...res,
id: res.id ?? res.dailyReportRecordId ?? fallback.id,
staffName: res.staffName ?? fallback.staffName,
merchantName: res.merchantName ?? fallback.merchantName,
bizType: res.bizType ?? scene.bizType ?? fallback.bizType,
bizTypeName: res.bizTypeName || scene.bizTypeName || fallback.bizTypeName,
reportDate: res.reportDate ?? fallback.reportDate,
jsonContent: res.jsonContent,
fieldDataList: res.fieldDataList,
subformDataList: res.subformDataList,
reportTemplateId: res.reportTemplateId,
baseSceneCode: res.baseSceneCode,
schema: res.schema,
};
}
export default mapDetailResponse;
/**
* dailyReport.merchant.list 响应 → 门店下拉选项
*/
export function mapMerchantListResponse(res = {}) {
const list = Array.isArray(res.list) ? res.list : (Array.isArray(res) ? res : []);
return list.map((item) => ({
merchantId: item.merchantId ?? item.shopMerchantId,
merchantName: item.merchantName ?? item.shopMerchantName,
sceneType: item.sceneType,
}));
}
export default mapMerchantListResponse;
/**
* merchant.staff.list 响应 → 驻店人员下拉选项
*/
export function mapMerchantStaffListResponse(res = {}) {
const list = Array.isArray(res.list)
? res.list
: (Array.isArray(res.data) ? res.data : (Array.isArray(res) ? res : []));
return list.map((item) => ({
staffUuid: item.staffUuid ?? item.staffId ?? item.id,
staffName: item.staffName,
})).filter((item) => item.staffUuid);
}
export default mapMerchantStaffListResponse;
import { mapSceneType } from "./mapSceneType";
/**
* dailyReport.overview.page 行数据 → 表格行
*/
export function mapOverviewRow(row = {}) {
const scene = mapSceneType(row.sceneType);
const reportStatus = row.reportStatus;
const createdDate = row.createdDate ?? row.lastSaveTime ?? row.updatedDate;
return {
id: row.id ?? row.dailyReportRecordId,
staffName: row.staffName,
staffUuid: row.staffUuid,
merchantId: row.merchantId,
merchantName: row.merchantName,
bizType: row.bizType ?? scene.bizType,
bizTypeName: row.bizTypeName || scene.bizTypeName,
attendanceStatus: row.onBreak ?? row.attendanceStatus ?? row.attendanceStatusName,
staffCount: row.staffCount,
lastSaveTime: createdDate,
submitTime: reportStatus === 1 ? (row.submitTime ?? createdDate) : (row.submitTime || ""),
submitUserName: row.submitUserName ?? row.submitStaffName ?? "",
reportDate: row.reportDate,
templateType: row.templateType,
reportStatus,
};
}
export function mapOverviewPageResponse(res = {}) {
const list = Array.isArray(res.list) ? res.list.map(mapOverviewRow) : [];
return {
...res,
list,
pageNum: res.pageNum ?? res.currentPage,
};
}
export default mapOverviewRow;
/**
* Swagger sceneType(0:权益,1:轻改)→ 页面 bizType / bizTypeName
*/
const SCENE_TYPE_MAP = {
0: { bizType: 2, bizTypeName: "权益" },
1: { bizType: 1, bizTypeName: "轻改" },
"0": { bizType: 2, bizTypeName: "权益" },
"1": { bizType: 1, bizTypeName: "轻改" },
};
export function mapSceneType(sceneType) {
if (sceneType == null || sceneType === "") {
return { bizType: "", bizTypeName: "" };
}
return SCENE_TYPE_MAP[sceneType] || { bizType: sceneType, bizTypeName: "" };
}
export default mapSceneType;
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"
const USE_ABNORMAL_FLOW_MOCK = process.env.VUE_APP_ABNORMAL_FLOW_MOCK === "true"
......@@ -234,27 +238,22 @@ export function saveShopLockConfig(data) {
* approvalSource: 0=区域经理审批 1=总部运营
*/
export function getPcAbnormalFlowDeclarationDetail(data) {
if (USE_ABNORMAL_FLOW_MOCK) {
return loadAbnormalFlowMock().then((m) => m.mockPcAbnormalFlowDeclarationDetail(data))
}
data.method = "dj.api.smartcarlife.pc.abnormalFlowDeclaration.detail"
return request(data, RequestMethods.POST)
if (USE_ABNORMAL_FLOW_MOCK) {
return loadAbnormalFlowMock().then((m) => m.mockPcAbnormalFlowDeclarationDetail(data));
}
const payload = {
...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) {
if (USE_ABNORMAL_FLOW_MOCK) {
return loadAbnormalFlowMock().then((m) => m.mockApprovePcAbnormalFlowDeclaration(data))
}
data.method = "dj.api.smartcarlife.pc.abnormalFlowDeclaration.approve"
return request(data, RequestMethods.POST)
if (USE_ABNORMAL_FLOW_MOCK) {
return loadAbnormalFlowMock().then((m) => m.mockApprovePcAbnormalFlowDeclaration(data));
}
const payload = {
...buildAbnormalFlowDeclarationApproveParams(data),
method: "dj.api.smartcarlife.pc.abnormalFlowDeclaration.approve",
};
return request(payload, RequestMethods.POST).then(mapAbnormalFlowDeclarationApproveResponse);
}
import request from "./request";
import RequestMethods from "./request.methods";
import { buildOverviewParams } from "./adapters/journalRecord/buildOverviewParams";
import { mapOverviewPageResponse } from "./adapters/journalRecord/mapOverviewRow";
import {
buildDetailSelectParams,
mapDetailResponse,
} from "./adapters/journalRecord/mapDetailResponse";
import { mapMerchantListResponse } from "./adapters/journalRecord/mapMerchantList";
import { mapMerchantStaffListResponse } from "./adapters/journalRecord/mapMerchantStaffList";
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() {
return import("./journalRecord.mock");
}
export function getStaffDailyPage(data) {
export function getDailyReportMerchantList(data = {}) {
const payload = {
currentPage: 1,
pageSize: 500,
...data,
};
if (USE_MOCK) {
return loadMock().then((m) => m.mockStaffDailyPage(data));
return loadMock().then((m) => m.mockDailyReportMerchantList(payload));
}
data.method = `${path}journal.staffDaily.page`;
return request(data, RequestMethods.POST);
payload.method = `${path}dailyReport.merchant.list`;
return request(payload, RequestMethods.POST).then(mapMerchantListResponse);
}
export function getStoreDailyPage(data) {
export function getDailyReportMerchantListPage(data = {}) {
const payload = {
currentPage: 1,
pageSize: 20,
...data,
};
if (USE_MOCK) {
return loadMock().then((m) => m.mockStoreDailyPage(data));
return loadMock()
.then((m) => m.mockDailyReportMerchantList(payload))
.then((list) => ({
list,
total: list.length,
pages: 1,
pageNum: payload.currentPage,
}));
}
data.method = `${path}journal.storeDaily.page`;
return request(data, RequestMethods.POST);
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 getNegotiationPage(data) {
export function getDailyReportMerchantStaffList(data = {}) {
if (USE_MOCK) {
return loadMock().then((m) => m.mockNegotiationPage(data));
return loadMock().then((m) => m.mockDailyReportMerchantStaffList(data));
}
data.method = `${path}journal.negotiation.page`;
return request(data, RequestMethods.POST);
const payload = {
...data,
method: `${path}merchant.staff.list`,
};
return request(payload, RequestMethods.POST).then(mapMerchantStaffListResponse);
}
export function getJournalDetail(data) {
export function getDailyReportOverviewPage(data = {}, activeTabKey = "staffDaily") {
if (USE_MOCK) {
return loadMock().then((m) => m.mockJournalDetail(data));
return loadMock().then((m) => m.mockDailyReportOverviewPage({
...data,
...buildOverviewParams(data, activeTabKey),
}));
}
data.method = `${path}journal.detail`;
return request(data, RequestMethods.POST);
const payload = {
...buildOverviewParams(data, activeTabKey),
method: `${path}dailyReport.overview.page`,
};
return request(payload, RequestMethods.POST).then(mapOverviewPageResponse);
}
export function getDailyReportDetailSelect(data = {}) {
if (USE_MOCK) {
return loadMock().then((m) => m.mockDailyReportDetailSelect(data));
}
const payload = {
...buildDetailSelectParams(data),
method: `${path}dailyReport.detail.select`,
};
return request(payload, RequestMethods.POST).then((res) => mapDetailResponse(res, data));
}
import { buildJournalDetailJsonContent } from "../views/residentManage/journalRecord/fixtures/journalDetailEcho.sample.js";
import { mapOverviewPageResponse } from "./adapters/journalRecord/mapOverviewRow";
import { mapDetailResponse } from "./adapters/journalRecord/mapDetailResponse";
import { mapMerchantListResponse } from "./adapters/journalRecord/mapMerchantList";
import { mapMerchantStaffListResponse } from "./adapters/journalRecord/mapMerchantStaffList";
const MERCHANT_NAME = "深圳市鹏程汽车有限公司";
const STORE_LIST = [
{ merchantId: "1001", merchantName: MERCHANT_NAME },
{ merchantId: "1002", merchantName: "广州天河汽车销售服务有限公司" },
{ merchantId: "1003", merchantName: "东莞南城汽车贸易有限公司" },
{ merchantId: "1004", merchantName: "佛山顺德智行汽车销售有限公司" },
{ merchantId: "1005", merchantName: "惠州惠城汽车服务有限公司" },
{ merchantId: "1001", merchantName: MERCHANT_NAME, sceneType: 1 },
{ merchantId: "1002", merchantName: "广州天河汽车销售服务有限公司", sceneType: 1 },
{ merchantId: "1003", merchantName: "东莞南城汽车贸易有限公司", sceneType: 0 },
{ merchantId: "1004", merchantName: "佛山顺德智行汽车销售有限公司", sceneType: 1 },
{ merchantId: "1005", merchantName: "惠州惠城汽车服务有限公司", sceneType: 0 },
];
const STAFF_LIST = [
{ staffId: "staff-001", staffName: "袁春梅", bizType: 2, bizTypeName: "权益", attendanceStatus: "在岗" },
{ staffId: "staff-002", staffName: "韩文", bizType: 1, bizTypeName: "轻改", attendanceStatus: "在岗" },
{ staffId: "staff-003", staffName: "刘明杰", bizType: 2, bizTypeName: "权益", attendanceStatus: "外出" },
{ staffId: "staff-004", staffName: "王芳", bizType: 1, bizTypeName: "轻改", attendanceStatus: "在岗" },
{ staffId: "staff-005", staffName: "张伟", bizType: 2, bizTypeName: "权益", attendanceStatus: "在岗" },
{ staffId: "staff-006", staffName: "李娜", bizType: 1, bizTypeName: "轻改", attendanceStatus: "外出" },
{ staffId: "staff-007", staffName: "陈静", bizType: 2, bizTypeName: "权益", attendanceStatus: "在岗" },
{ staffId: "staff-008", staffName: "赵强", bizType: 1, bizTypeName: "轻改", attendanceStatus: "在岗" },
{ staffId: "staff-009", staffName: "孙丽", bizType: 2, bizTypeName: "权益", attendanceStatus: "在岗" },
{ staffId: "staff-010", staffName: "周涛", bizType: 1, bizTypeName: "轻改", attendanceStatus: "外出" },
{ staffUuid: "staff-uuid-001", staffName: "袁春梅" },
{ staffUuid: "staff-uuid-002", staffName: "韩文" },
{ staffUuid: "staff-uuid-003", staffName: "刘明杰" },
{ staffUuid: "staff-uuid-004", staffName: "王芳" },
{ staffUuid: "staff-uuid-005", staffName: "张伟" },
{ staffUuid: "staff-uuid-006", staffName: "李娜" },
{ staffUuid: "staff-uuid-007", staffName: "陈静" },
{ staffUuid: "staff-uuid-008", staffName: "赵强" },
{ staffUuid: "staff-uuid-009", staffName: "孙丽" },
{ staffUuid: "staff-uuid-010", staffName: "周涛" },
];
function delay(result, ms = 300) {
......@@ -41,12 +45,12 @@ function paginate(list, params) {
}
function filterStaffList(list, params) {
let result = [...list];
let result = [ ...list ];
if (params.merchantId) {
result = result.filter((item) => item.merchantId === params.merchantId);
}
if (params.staffId) {
result = result.filter((item) => item.staffId === params.staffId);
if (params.staffName) {
result = result.filter((item) => item.staffName === params.staffName);
}
return result;
}
......@@ -54,11 +58,16 @@ function filterStaffList(list, params) {
function buildStaffDailyList(params) {
return STAFF_LIST.map((item, index) => ({
id: `staff-daily-${index + 1}`,
...item,
staffUuid: item.staffUuid,
staffName: item.staffName,
merchantId: STORE_LIST[index % STORE_LIST.length].merchantId,
merchantName: STORE_LIST[index % STORE_LIST.length].merchantName,
lastSaveTime: "2026-06-12 14:41",
sceneType: index % 2 === 0 ? "1" : "0",
onBreak: index % 3 === 0 ? "调休" : "在岗",
createdDate: "2026-06-12 14:41:00",
reportStatus: 0,
reportDate: params.reportDate,
templateType: 1,
}));
}
......@@ -67,24 +76,28 @@ function buildStoreDailyList(params) {
id: `store-daily-${index + 1}`,
merchantId: store.merchantId,
merchantName: store.merchantName,
bizType: index % 2 === 0 ? 2 : 1,
bizTypeName: index % 2 === 0 ? "权益" : "轻改",
sceneType: String(store.sceneType),
staffCount: 3,
lastSaveTime: "2026-06-12 14:41",
submitTime: index % 3 === 0 ? "" : "2026-06-12 15:30",
submitUserName: index % 3 === 0 ? "" : STAFF_LIST[index % STAFF_LIST.length].staffName,
createdDate: "2026-06-12 14:41:00",
reportStatus: index % 3 === 0 ? 0 : 1,
reportDate: params.reportDate,
templateType: 2,
}));
}
function buildNegotiationList(params) {
return STAFF_LIST.map((item, index) => ({
id: `negotiation-${index + 1}`,
...item,
staffUuid: item.staffUuid,
staffName: item.staffName,
merchantId: STORE_LIST[index % STORE_LIST.length].merchantId,
merchantName: STORE_LIST[index % STORE_LIST.length].merchantName,
lastSaveTime: "2026-06-12 14:41",
sceneType: index % 2 === 0 ? "0" : "1",
onBreak: "在岗",
createdDate: "2026-06-12 14:41:00",
reportStatus: 1,
reportDate: params.reportDate,
templateType: 3,
}));
}
......@@ -94,22 +107,22 @@ function buildDetailMeta(journalType, reportDate) {
journalType: "staffDaily",
staffName: "高思琪",
merchantName: MERCHANT_NAME,
bizType: 1,
bizTypeName: "轻改",
sceneType: "1",
templateType: 1,
},
storeDaily: {
journalType: "storeDaily",
staffName: "",
merchantName: MERCHANT_NAME,
bizType: 1,
bizTypeName: "轻改",
sceneType: "1",
templateType: 2,
},
negotiation: {
journalType: "negotiation",
staffName: "高思琪",
merchantName: MERCHANT_NAME,
bizType: 2,
bizTypeName: "权益",
sceneType: "0",
templateType: 3,
},
};
return {
......@@ -127,25 +140,40 @@ const DETAIL_MAP = {
"negotiation-1": buildDetailMeta("negotiation", "2026-03-30"),
};
export function mockStaffDailyPage(params) {
const list = filterStaffList(buildStaffDailyList(params), params);
return delay(paginate(list, params));
export function mockDailyReportMerchantList(params) {
return delay(mapMerchantListResponse({ list: STORE_LIST }));
}
export function mockStoreDailyPage(params) {
let list = buildStoreDailyList(params);
export function mockDailyReportMerchantStaffList(params) {
let list = STAFF_LIST.map((item, index) => ({
...item,
merchantId: STORE_LIST[index % STORE_LIST.length].merchantId,
}));
if (params.merchantId) {
list = list.filter((item) => item.merchantId === params.merchantId);
}
return delay(paginate(list, params));
return delay(mapMerchantStaffListResponse({ list }));
}
export function mockNegotiationPage(params) {
const list = filterStaffList(buildNegotiationList(params), params);
return delay(paginate(list, params));
export function mockDailyReportOverviewPage(params) {
const { templateType } = params;
let list = [];
if (templateType === 1) {
list = filterStaffList(buildStaffDailyList(params), params);
} else if (templateType === 2) {
list = buildStoreDailyList(params);
if (params.merchantId) {
list = list.filter((item) => item.merchantId === params.merchantId);
}
} else if (templateType === 3) {
list = filterStaffList(buildNegotiationList(params), params);
} else {
list = filterStaffList(buildStaffDailyList(params), params);
}
return delay(mapOverviewPageResponse(paginate(list, params)));
}
export function mockJournalDetail(params) {
export function mockDailyReportDetailSelect(params) {
const { id, journalType, reportDate } = params;
let detail = DETAIL_MAP[id];
if (!detail) {
......@@ -154,5 +182,5 @@ export function mockJournalDetail(params) {
...buildDetailMeta(journalType || "staffDaily", reportDate),
};
}
return delay({ ...detail, id: id || detail.id });
return delay(mapDetailResponse({ ...detail, id: id || detail.id }, params));
}
......@@ -11,6 +11,7 @@ import { baseConfig } from "@/main";
// import axios from "@/plugin/axios"
import axios from "@/plugin/axios/index_code";
import RequestMethods from "./request.methods";
import resolveApiName, { getAxiosConfigKey, getSignWay } from "./resolveApiName";
import sign from "./sign";
function request(
......@@ -19,65 +20,11 @@ function request(
noSignAttr = [],
options = {},
) {
// 兼容线上dj和scrm appkey和secret不一样的情况
let apiName = "";
if (params.method.includes("dj.api.smartcarlife.sop.strategy")) {
apiName = "strategy";
} else if (params.method.includes("dj.api.smartcarlife")) {
apiName = "dj";
} else if (params.method.includes("dj.api.script")) {
apiName = "script";
} else if (params.method.includes("dj.staff.api")) {
apiName = "staff";
} else if (params.method.includes("dj.smartcarlife.stock")) {
apiName = "dj.smartcarlife";
} else if (params.method.includes("risk.manage.api")) {
apiName = "riskmanage";
} else if (params.method.includes("dj.api.strategy")) {
apiName = "strategy";
} else if (params.method.includes("dj.api.supervisor")) {
apiName = "supervisor";
} else if (params.method.includes("dj.pad.api")) {
// rop-dj-pad 等方法名含 dj.pad,split(".api") 会得到 dj.pad 无 mapping;签名与 appKey 沿用 dj
apiName = "dj";
} else if (params.method.includes("dj.api.oaapproval")) {
apiName = "oaapproval";
} else if (params.method.includes("dj.api.taskcenter")) {
apiName = "taskcenter";
} else if (params.method.includes("merchants.api.open.createMerchantWithPermissions") || params.method.includes("merchants.api.oaapproval")) {
/** 开放平台创建商户 — 与同网关 oaapproval 一致,使用 axios_oaapproval / baseURL */
apiName = "oaapproval";
} else if (params.method.includes("dj.api.marketing")) {
apiName = "strategy";
} else {
// console.log(params.method.split(".api"))
apiName = params.method.split(".api")[0];
}
// console.log("params.method", params.method)
// console.log("apiName", apiName)
// 为空报错
const apiName = resolveApiName(params.method);
if (!apiName) {
throw new Error("apiName is null");
}
const mappingName = {
"dj.smartcarlife": "axios",
"dj": "axios",
"scrm": "axios2",
"merchants": "axios3",
"reportExport": "axios4",
"glsx.accounts.biz.common.pictureUpload": "common",
"clue": "axios5",
"dj.businessSchool": "axios6",
"script": "axios7",
"staff": "axios9",
"riskmanage": "axios10",
"strategy": "axios_strategy",
"supervisor": "axios_supervisor",
"oaapproval": "axios_oaapproval",
"taskcenter": "axiosTaskCenter",
};
const baseApiName = mappingName[apiName];
const baseApiName = getAxiosConfigKey(apiName);
// console.log(baseApiName, "baseApiName")
// params.appKey = baseConfig[baseApiName].appkey
if (baseApiName == "common") {
......@@ -102,29 +49,15 @@ function request(
/**
* 调后端接口,请使用以下代码。
*/
const signWay = {
"dj.smartcarlife": "sha1",
"dj": "sha1",
"scrm": "sha1",
"glsx": "md5",
"glsx.accounts.biz.common.pictureUpload": "md5",
"clue": "sha1",
"script": "sha1",
"staff": "sha1",
"riskmanage": "sha1",
"oaapproval": "sha1",
"taskcenter": "sha1",
};
// console.log(signWay[apiName], "baseApiName")
const secret = baseConfig[baseApiName].secret;
const CancelToken = axiosPackage.CancelToken;
let reqData
= method === RequestMethods.POST
? {
baseURL: "/",
data: sign(params, noSignAttr, secret, signWay[apiName]),
data: sign(params, noSignAttr, secret, getSignWay(apiName)),
}
: { params: sign(params, noSignAttr, secret, signWay[apiName]) };
: { params: sign(params, noSignAttr, secret, getSignWay(apiName)) };
reqData = Object.assign(reqData, options, {});
// 请求进度
......
......@@ -3,6 +3,9 @@
* @Date: 2019-08-26 18:02:41
* @Last Modified by: chenwq
* @Last Modified time: 2021-06-30 14:30:41
*
* 注意:apiName 规则为 request.js 的子集,仅覆盖 dj / split(".api")。
* 主请求请使用 request.js;本文件供 index_code 插件专用。
*/
import axios from "@/plugin/axios/index_code"
......
export {
resolveApiName as default,
resolveApiName,
getAxiosConfigKey,
getSignWay,
} from "@/libs/rop/resolveApiName";
......@@ -4,60 +4,4 @@
* @Last Modified by: chenwq
* @Last Modified time: 2021-06-18 10:04:32
*/
import sha1 from "sha1"
import md5 from "md5"
import qs from "qs"
import { deepClone } from "@/common/util"
const sign = (params, noSignAttr = [], secret, way = "sha1") => {
// console.log(way, "way")
delete params.sign
var objStr = qs.stringify(deepClone(params), {
arrayFormat: "indices",
allowDots: true,
encodeValuesOnly: true
})
var objVal = objStr.split("&")
var realObj = {}
objVal.forEach((item) => {
const idx = item.indexOf("=")
realObj[item.split("=")[0]] = decodeURIComponent(item.slice(idx + 1))
})
// console.log(realObj)
const keys = Object.keys(realObj).sort()
var str = []
var obj = null
for (const key in realObj) {
obj = realObj[key]
if (obj === null) {
obj = ""
} else if (typeof obj === "object") {
obj = JSON.stringify(obj)
}
realObj[key] = obj
}
keys.forEach((e) => {
!noSignAttr.includes(e) && str.push(e + realObj[e])
})
// realObj.sign = sha1(secret + str.join("") + secret).toUpperCase()
const signObj = { sha1, md5 }
realObj.sign = signObj[way](secret + str.join("") + secret).toUpperCase()
return realObj
}
//精确计算2个数的加减运算
function add(num1, num2) {
var r1, r2, m
try {
r1 = num1.toString().split(".")[1].length
} catch (e) {
r1 = 0
}
try {
r2 = num2.toString().split(".")[1].length
} catch (e) {
r2 = 0
}
m = Math.pow(10, Math.max(r1, r2))
return (Math.round(num1 * m) + Math.round(num2 * m)) / m
}
export default sign
export { default } from "@/libs/rop/signCore";
{
"env": "develop",
"axios": {
"baseURL": "http://dj.dev.glsx.com.cn/rop-dj-smartcarlife/router",
"appkey": "48e5e13229b82c1b4e6e8c96151f0637",
"secret": "c24619ed7fef02a0ae16328146bca5f97cc6493957a2137b",
"timeout": 50000,
"result": {
"data_key": "data",
"message_key": "message",
"code_key": "code",
"code_success_value": 0,
"code_error_value": -1,
"code_message_map": {}
}
}
}
/**
* 组装 ROP 网关公共请求字段
*/
function buildRopPayload(appkey, method, extra = {}, sessionId) {
const payload = {
appKey: appkey,
method,
timestamp: Date.now(),
v: "1.0.0",
format: "json",
locale: "zh_CN",
...extra,
};
if (sessionId) {
payload.sessionId = sessionId;
}
return payload;
}
module.exports = buildRopPayload;
const fs = require("fs");
const path = require("path");
const { buildContract, toMethodFileName } = require("./swaggerInspect");
const ADAPTERS_GLOB_ROOT = path.join(__dirname, "../../api/adapters");
function normalizeParams(parameters = []) {
return parameters
.filter((p) => p.in === "query" && p.name !== "sessionId")
.map((p) => ({
name: p.name,
type: p.type || "",
required: !!p.required,
}))
.sort((a, b) => a.name.localeCompare(b.name));
}
function normalizeResponse(contract = {}) {
return {
hasPagination: !!contract.response?.pagination,
paginationFields: contract.response?.pagination?.fields || [],
fieldNames: (contract.response?.fields || [])
.filter((f) => !f.name.includes("."))
.map((f) => f.name.split(".").pop())
.filter((name) => name !== "code" && name !== "message"),
};
}
function findTrackedContracts(rootDir = ADAPTERS_GLOB_ROOT) {
const results = [];
if (!fs.existsSync(rootDir)) {
return results;
}
function walk(dir) {
fs.readdirSync(dir, { withFileTypes: true }).forEach((entry) => {
const fullPath = path.join(dir, entry.name);
if (entry.isDirectory()) {
walk(fullPath);
return;
}
if (entry.isFile() && entry.name.endsWith(".contract.json")) {
const raw = JSON.parse(fs.readFileSync(fullPath, "utf8"));
results.push({
filePath: fullPath,
method: raw.method,
contract: raw,
});
}
});
}
walk(rootDir);
return results;
}
function compareContracts(tracked, fresh) {
const errors = [];
const warnings = [];
const trackedParams = normalizeParams(tracked.request?.parameters);
const freshParams = normalizeParams(fresh.request?.parameters);
const trackedMap = new Map(trackedParams.map((p) => [p.name, p]));
const freshMap = new Map(freshParams.map((p) => [p.name, p]));
trackedParams.forEach((param) => {
if (!freshMap.has(param.name)) {
errors.push(`请求参数已删除: ${param.name}`);
}
});
freshParams.forEach((param) => {
const old = trackedMap.get(param.name);
if (!old) {
if (param.required) {
errors.push(`新增必填请求参数: ${param.name}`);
} else {
warnings.push(`新增可选请求参数: ${param.name}`);
}
return;
}
if (old.required !== param.required && param.required) {
errors.push(`请求参数变为必填: ${param.name}`);
}
if (old.type && param.type && old.type !== param.type) {
warnings.push(`请求参数类型变更: ${param.name} (${old.type} -> ${param.type})`);
}
});
const trackedResponse = normalizeResponse(tracked);
const freshResponse = normalizeResponse(fresh);
if (trackedResponse.hasPagination && !freshResponse.hasPagination) {
errors.push("响应分页结构消失");
}
if (trackedResponse.hasPagination && !freshResponse.paginationFields.includes("list")) {
errors.push("分页响应缺少 list 字段");
}
trackedResponse.fieldNames.forEach((name) => {
if (!freshResponse.fieldNames.includes(name)) {
warnings.push(`响应字段可能移除: ${name}`);
}
});
freshResponse.fieldNames.forEach((name) => {
if (!trackedResponse.fieldNames.includes(name)) {
warnings.push(`新增响应字段: ${name}`);
}
});
return { errors, warnings };
}
function diffSnapshotWithTracked(swagger, trackedItems) {
const report = {
errors: [],
warnings: [],
checked: 0,
};
trackedItems.forEach((item) => {
report.checked += 1;
let fresh;
try {
fresh = buildContract(swagger, item.method);
} catch (error) {
report.errors.push(`${item.method}: method 在快照中不存在 (${error.message})`);
return;
}
const { errors, warnings } = compareContracts(item.contract, fresh);
errors.forEach((message) => report.errors.push(`${item.method}: ${message}`));
warnings.forEach((message) => report.warnings.push(`${item.method}: ${message}`));
});
return report;
}
function diffOnlineSnapshot(oldSwagger, newSwagger) {
const report = {
errors: [],
warnings: [],
added: [],
removed: [],
};
const oldMethods = new Set(Object.keys(oldSwagger.paths || {})
.filter((route) => route.startsWith("/router/"))
.map((route) => route.slice("/router/".length, -"/1.0.0".length)));
const newMethods = new Set(Object.keys(newSwagger.paths || {})
.filter((route) => route.startsWith("/router/"))
.map((route) => route.slice("/router/".length, -"/1.0.0".length)));
oldMethods.forEach((method) => {
if (!newMethods.has(method)) {
report.removed.push(method);
}
});
newMethods.forEach((method) => {
if (!oldMethods.has(method)) {
report.added.push(method);
}
});
if (report.removed.length) {
report.warnings.push(`快照相比线上减少 ${report.removed.length} 个 method,建议 npm run rop:swagger:fetch`);
}
if (report.added.length) {
report.warnings.push(`快照相比线上新增 ${report.added.length} 个 method,建议 npm run rop:swagger:fetch`);
}
return report;
}
module.exports = {
findTrackedContracts,
compareContracts,
diffSnapshotWithTracked,
diffOnlineSnapshot,
normalizeParams,
toMethodFileName,
ADAPTERS_GLOB_ROOT,
};
const buildRopPayload = require("./buildRopPayload");
const sign = require("./signCore");
const postRop = require("./ropHttpClient");
const loadAxiosConfig = require("./loadAxiosConfig");
const ropSession = require("./ropSession");
const ropClient = require("./ropClient");
const swaggerInspect = require("./swaggerInspect");
const resolveApiName = require("./resolveApiName");
const contractDiff = require("./contractDiff");
const ropImport = require("./ropImport");
module.exports = {
buildRopPayload,
sign,
postRop,
...loadAxiosConfig,
...ropSession,
...ropClient,
...resolveApiName,
swaggerInspect,
contractDiff,
ropImport,
};
const fs = require("fs");
const http = require("http");
const https = require("https");
const path = require("path");
const { getAxiosConfigKey } = require("./resolveApiName");
const DEFAULT_CONFIG_URL = process.env.VUE_APP_CONFIG_CENTER_URL
|| "https://oss-config.test.glsx.com.cn/mock/5be17454f31545347559d499/config";
const DEVELOP_CONFIG_PATH = path.join(__dirname, "../../common/baseConfig.develop.json");
function fetchJson(url) {
return new Promise((resolve, reject) => {
const lib = url.startsWith("https") ? https : http;
lib.get(url, (res) => {
let raw = "";
res.on("data", (chunk) => { raw += chunk; });
res.on("end", () => {
try {
resolve(JSON.parse(raw));
} catch (error) {
reject(new Error(`JSON parse failed: ${raw.slice(0, 200)}`));
}
});
}).on("error", reject);
});
}
function loadDevelopFallback() {
return JSON.parse(fs.readFileSync(DEVELOP_CONFIG_PATH, "utf8"));
}
function pickAxiosBlock(baseConfig, apiName = "dj") {
const configKey = getAxiosConfigKey(apiName);
if (!configKey) {
throw new Error(`Unknown apiName for axios config: ${apiName}`);
}
const block = baseConfig?.[configKey];
if (!block?.baseURL || !block?.appkey || !block?.secret) {
throw new Error(`Invalid ROP config: missing ${configKey}.baseURL/appkey/secret`);
}
return {
baseURL: block.baseURL,
appkey: block.appkey,
secret: block.secret,
configKey,
};
}
/**
* 加载 axios 配置:优先配置中心,失败回退 baseConfig.develop.json
* @param {string|{ configUrl?: string, apiName?: string }} options
*/
async function loadAxiosConfig(options) {
let configUrl = DEFAULT_CONFIG_URL;
let apiName = "dj";
if (typeof options === "string") {
configUrl = options;
} else if (options && typeof options === "object") {
configUrl = options.configUrl || DEFAULT_CONFIG_URL;
apiName = options.apiName || "dj";
}
let baseConfig = null;
try {
const response = await fetchJson(configUrl);
baseConfig = response.code == "200" ? response.data : response;
} catch (error) {
// 回退 develop 本地配置
}
if (!baseConfig?.axios?.appkey || !baseConfig?.axios?.secret) {
baseConfig = loadDevelopFallback();
}
const { baseURL, appkey, secret, configKey } = pickAxiosBlock(baseConfig, apiName);
return {
baseURL,
appkey,
secret,
env: baseConfig.env,
apiName,
configKey,
};
}
module.exports = {
loadAxiosConfig,
loadDevelopFallback,
pickAxiosBlock,
DEFAULT_CONFIG_URL,
};
/**
* ROP method → apiName / axios 配置键 / 签名方式
* 与 src/api/request.js 保持一致,供浏览器与 Node 共用
*/
const API_NAME_MAPPING = {
"dj.smartcarlife": "axios",
dj: "axios",
scrm: "axios2",
merchants: "axios3",
reportExport: "axios4",
"glsx.accounts.biz.common.pictureUpload": "common",
clue: "axios5",
"dj.businessSchool": "axios6",
script: "axios7",
staff: "axios9",
riskmanage: "axios10",
strategy: "axios_strategy",
supervisor: "axios_supervisor",
oaapproval: "axios_oaapproval",
taskcenter: "axiosTaskCenter",
};
const SIGN_WAY = {
"dj.smartcarlife": "sha1",
dj: "sha1",
scrm: "sha1",
glsx: "md5",
"glsx.accounts.biz.common.pictureUpload": "md5",
clue: "sha1",
script: "sha1",
staff: "sha1",
riskmanage: "sha1",
oaapproval: "sha1",
taskcenter: "sha1",
};
/**
* 根据 ROP method 解析 apiName
* @param {string} method
* @returns {string}
*/
function resolveApiName(method = "") {
if (!method) {
return "";
}
if (method.includes("dj.api.smartcarlife.sop.strategy")) {
return "strategy";
}
if (method.includes("dj.api.smartcarlife")) {
return "dj";
}
if (method.includes("dj.api.script")) {
return "script";
}
if (method.includes("dj.staff.api")) {
return "staff";
}
if (method.includes("dj.smartcarlife.stock")) {
return "dj.smartcarlife";
}
if (method.includes("risk.manage.api")) {
return "riskmanage";
}
if (method.includes("dj.api.strategy")) {
return "strategy";
}
if (method.includes("dj.api.supervisor")) {
return "supervisor";
}
if (method.includes("dj.pad.api")) {
return "dj";
}
if (method.includes("dj.api.oaapproval")) {
return "oaapproval";
}
if (method.includes("dj.api.taskcenter")) {
return "taskcenter";
}
if (method.includes("merchants.api.open.createMerchantWithPermissions")) {
return "oaapproval";
}
if (method.includes("dj.api.marketing")) {
return "strategy";
}
return method.split(".api")[0];
}
/**
* apiName → baseConfig 中的 axios 块键名
* @param {string} apiName
* @returns {string|undefined}
*/
function getAxiosConfigKey(apiName) {
return API_NAME_MAPPING[apiName];
}
/**
* apiName → 签名算法
* @param {string} apiName
* @returns {string}
*/
function getSignWay(apiName) {
return SIGN_WAY[apiName] || "sha1";
}
module.exports = {
resolveApiName,
getAxiosConfigKey,
getSignWay,
API_NAME_MAPPING,
SIGN_WAY,
};
const buildRopPayload = require("./buildRopPayload");
const { loadAxiosConfig } = require("./loadAxiosConfig");
const { login } = require("./ropSession");
const postRop = require("./ropHttpClient");
const SMARTCARLIFE_PREFIX = "dj.api.smartcarlife.";
function isSuccessCode(code) {
return String(code) === "0";
}
/**
* 创建 ROP 客户端(Node / 脚本 / 集成测试)
*/
function createRopClient(config, sessionId) {
const { baseURL, appkey, secret } = config;
async function callRaw(method, params = {}, options = {}) {
const payload = buildRopPayload(appkey, method, params, sessionId);
return postRop(baseURL, secret, payload, options);
}
async function call(method, params = {}, options = {}) {
const res = await callRaw(method, params, options);
if (!isSuccessCode(res.code)) {
throw new Error(`${method} failed: ${res.message || res.code}`);
}
return res.data;
}
async function callSmartcarlife(suffix, params = {}, options = {}) {
return call(`${SMARTCARLIFE_PREFIX}${suffix}`, params, options);
}
return {
config,
sessionId,
call,
callRaw,
callSmartcarlife,
};
}
/**
* 加载配置 + 登录 + 创建客户端
*/
async function createLoggedInClient({
userName = process.env.ROP_TEST_USER || "glsadmin",
password = process.env.ROP_TEST_PASSWORD || "123456",
configUrl,
apiName = "dj",
} = {}) {
const config = await loadAxiosConfig({ configUrl, apiName });
const sessionId = await login(config, { userName, password });
return createRopClient(config, sessionId);
}
module.exports = {
createRopClient,
createLoggedInClient,
isSuccessCode,
SMARTCARLIFE_PREFIX,
};
const http = require("http");
const https = require("https");
const qs = require("qs");
const sign = require("./signCore");
/**
* POST 到 ROP router,返回原始响应体 { code, data, message, errId }
*/
function postRop(baseURL, secret, data, options = {}) {
const body = qs.stringify(sign(data, options.noSignAttr || [], secret, options.signWay || "sha1"));
const url = new URL(baseURL);
const lib = url.protocol === "https:" ? https : http;
return new Promise((resolve, reject) => {
const req = lib.request({
hostname: url.hostname,
port: url.port || (url.protocol === "https:" ? 443 : 80),
path: url.pathname,
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
"Content-Length": Buffer.byteLength(body),
},
}, (res) => {
let raw = "";
res.on("data", (chunk) => { raw += chunk; });
res.on("end", () => {
try {
resolve(JSON.parse(raw));
} catch (error) {
reject(new Error(`ROP response parse failed: ${raw.slice(0, 300)}`));
}
});
});
req.on("error", reject);
req.write(body);
req.end();
});
}
module.exports = postRop;
const crypto = require("crypto");
const buildRopPayload = require("./buildRopPayload");
const postRop = require("./ropHttpClient");
const LOGIN_METHOD = "dj.api.user.login";
function hashPassword(password) {
return crypto.createHash("md5").update(password).digest("hex").toLowerCase();
}
function extractSessionId(loginData = {}) {
return loginData.sessionId || loginData.accountList?.[0]?.sessionId;
}
/**
* 登录并返回 sessionId
*/
async function login(config, { userName, password }) {
const { baseURL, appkey, secret } = config;
const payload = buildRopPayload(appkey, LOGIN_METHOD, {
userName,
password: hashPassword(password),
});
const res = await postRop(baseURL, secret, payload);
if (String(res.code) !== "0") {
throw new Error(`Login failed: ${res.message || res.code}`);
}
const sessionId = extractSessionId(res.data);
if (!sessionId) {
throw new Error("Login succeeded but sessionId missing");
}
return sessionId;
}
module.exports = {
login,
hashPassword,
extractSessionId,
LOGIN_METHOD,
};
export { default } from "@/libs/rop/signCore";
const qs = require("qs");
const md5 = require("md5");
const sha1 = require("sha1");
function deepClone(obj) {
return JSON.parse(JSON.stringify(obj));
}
/**
* ROP 请求签名(与 src/api/sign.js 逻辑一致)
*/
function sign(params, noSignAttr = [], secret, way = "sha1") {
const payload = { ...params };
delete payload.sign;
const objStr = qs.stringify(deepClone(payload), {
arrayFormat: "indices",
allowDots: true,
encodeValuesOnly: true,
});
const realObj = {};
objStr.split("&").forEach((item) => {
const idx = item.indexOf("=");
realObj[item.slice(0, idx)] = decodeURIComponent(item.slice(idx + 1));
});
const keys = Object.keys(realObj).sort();
const str = [];
for (const key in realObj) {
let obj = realObj[key];
if (obj === null) {
obj = "";
} else if (typeof obj === "object") {
obj = JSON.stringify(obj);
}
realObj[key] = obj;
}
keys.forEach((e) => {
if (!noSignAttr.includes(e)) {
str.push(e + realObj[e]);
}
});
const signObj = { sha1, md5 };
realObj.sign = signObj[way](secret + str.join("") + secret).toUpperCase();
return realObj;
}
module.exports = sign;
......@@ -8,6 +8,7 @@ import Vue from "vue";
import VueLazyload from "vue-lazyload";
import { config } from "@/common/baseConfig";
import developConfig from "@/common/baseConfig.develop.json";
import { installVueMapApi } from "@/common/installVueMapApi";
import notice from "@/common/notice";
import util from "@/libs/util.js";
......@@ -184,7 +185,24 @@ fetch(configCenterUrl)
.finally(() => {
init();
});
function applyDevelopAxiosConfig() {
if (
process.env.NODE_ENV === "development"
&& process.env.VUE_APP_USE_DEVELOP_AXIOS === "true"
&& developConfig?.axios
) {
baseConfig.axios = {
...baseConfig.axios,
...developConfig.axios,
};
if (developConfig.env) {
baseConfig.env = developConfig.env;
}
}
}
function init() {
applyDevelopAxiosConfig();
new Vue({
router,
store,
......
......@@ -21,11 +21,21 @@ export const TAB_TRACK_CODE_MAP = {
};
export const LIST_API_MAP = {
staffDaily: "getStaffDailyPage",
storeDaily: "getStoreDailyPage",
negotiation: "getNegotiationPage",
staffDaily: "getDailyReportOverviewPage",
storeDaily: "getDailyReportOverviewPage",
negotiation: "getDailyReportOverviewPage",
};
export function getTemplateTypeByTabKey(tabKey) {
const tab = JOURNAL_TABS.find((item) => item.key === tabKey);
return tab?.journalType ?? 1;
}
export function getTabKeyByTemplateType(templateType) {
const tab = JOURNAL_TABS.find((item) => item.journalType === templateType);
return tab?.key ?? "staffDaily";
}
const bizTypeColumn = {
label: "业务大类",
prop: "bizTypeName",
......@@ -43,7 +53,7 @@ export const TABLE_COLUMNS_MAP = {
{ label: "最近保存时间", prop: "lastSaveTime", width: "160px" },
],
storeDaily: [
{ label: "所属门店", prop: "merchantName", minWidth: "200px", showOverFlow: true },
{ label: "所属门店", prop: "merchantName", minWidth: "180px", showOverFlow: true },
bizTypeColumn,
{
label: "今日驻店人数",
......
......@@ -21,7 +21,7 @@
<script>
import VenusBackButton from "@/components/venusBackButton/index.vue";
import { getJournalDetail } from "@api/journalRecord";
import { getDailyReportDetailSelect } from "@api/journalRecord";
import BizTypeTag from "./components/BizTypeTag.vue";
import DynamicFormReadonly from "./components/DynamicFormReadonly.vue";
import { getDetailTitle } from "./constants";
......@@ -50,14 +50,20 @@ export default {
},
methods: {
async fetchDetail() {
const { id, journalType, reportDate } = this.$route.query;
const { id, journalType, reportDate, merchantId, staffUuid } = this.$route.query;
if (!id) {
return;
}
this.journalType = journalType;
this.pageLoading = true;
try {
const res = await getJournalDetail({ id, journalType, reportDate });
const res = await getDailyReportDetailSelect({
id,
journalType,
reportDate,
merchantId,
staffUuid,
});
this.detail = {
...res,
reportDate: res.reportDate || reportDate,
......
......@@ -18,7 +18,27 @@
class="show-search"
:form-data="currentFormData"
: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">
<el-button size="small"
type="primary"
......@@ -60,14 +80,9 @@ import dayjs from "dayjs";
import { deepClone } from "@/common/util";
import reportTrackFunMixin from "@/mixins/reportTrackFunMixin";
import {
getNegotiationPage,
getStaffDailyPage,
getStoreDailyPage,
getDailyReportMerchantListPage,
getDailyReportOverviewPage,
} from "@api/journalRecord";
import {
getStoreListBySceneApi,
staffBaseInfoPageList,
} from "@api/resident";
import BizTypeTag from "./components/BizTypeTag.vue";
import DateNav from "./components/DateNav.vue";
import {
......@@ -76,19 +91,33 @@ import {
TABLE_COLUMNS_MAP,
} from "./constants";
const API_MAP = {
staffDaily: getStaffDailyPage,
storeDaily: getStoreDailyPage,
negotiation: getNegotiationPage,
};
const DEFAULT_SEARCH_FORM = {
merchantId: "",
staffId: "",
staffName: "",
};
export default {
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: {
BizTypeTag,
DateNav,
......@@ -104,42 +133,35 @@ export default {
searchFormSearch: {},
baseData: {
storeOptions: [],
staffOptions: [],
},
merchantKeyword: "",
merchantCurrentPage: 1,
merchantPageSize: 20,
merchantTotalPages: 1,
merchantLoading: false,
selectedMerchant: null,
baseFormData: [
{
label: "所属门店",
name: "merchantId",
type: "select",
isClear: true,
placeholder: "请选择",
optionList: [],
optionId: "merchantId",
optionLabel: "merchantName",
optionsName: "storeOptions",
changeAttr: (value) => {
this.searchForm.staffId = "";
this.loadStaffOptions();
},
addHtml: "merchantHtml",
},
{
label: "驻店人员",
name: "staffId",
type: "select",
name: "staffName",
type: "input",
isClear: true,
filterable: true,
placeholder: "请选择",
optionList: [],
optionId: "staffId",
optionLabel: "staffName",
optionsName: "staffOptions",
placeholder: "请输入",
},
],
};
},
computed: {
currentListApi() {
return API_MAP[this.activeTab];
return (params) => getDailyReportOverviewPage({
...params,
reportDate: params.reportDate || this.reportDate,
}, this.activeTab);
},
currentFormData() {
if (this.activeTab === "storeDaily") {
......@@ -160,57 +182,103 @@ export default {
this.initPage();
},
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() {
this.restoreStateFromRoute();
this.setReportTrackData(0, "journal_web_page_entry", {});
await Promise.all([
this.loadStoreOptions(),
this.loadStaffOptions(),
]);
this.handleSearch();
},
async loadStoreOptions() {
const res = await getStoreListBySceneApi({
currentPage: 1,
pageSize: 9999,
});
this.baseData.storeOptions = (res.list || []).map((item) => ({
merchantId: item.shopMerchantId,
merchantName: item.shopMerchantName,
}));
this.syncStoreOptions();
remoteMerchantMethod(query) {
this.merchantKeyword = query || "";
this.merchantCurrentPage = 1;
this.fetchMerchantOptions(true);
},
async loadStaffOptions() {
const params = {
currentPage: 1,
pageSize: 9999,
workingStatus: 1,
};
const store = this.baseData.storeOptions.find(
(item) => item.merchantId === this.searchForm.merchantId,
);
if (store?.merchantName) {
params.merchantName = store.merchantName;
handleMerchantVisibleChange(visible) {
if (!visible || this.baseData.storeOptions.length) {
return;
}
const res = await staffBaseInfoPageList(params);
this.baseData.staffOptions = (res.list || []).map((item) => ({
staffId: item.staffId || item.id || item.staffUuid,
staffName: item.staffName,
})).filter((item) => item.staffId);
this.syncStaffOptions();
this.merchantKeyword = "";
this.merchantCurrentPage = 1;
this.fetchMerchantOptions(true);
},
syncStoreOptions() {
this.baseFormData.forEach((item, index) => {
if (item.name === "merchantId") {
this.$set(this.baseFormData[index], "optionList", this.baseData.storeOptions);
}
});
loadMoreMerchants() {
if (this.merchantLoading || this.merchantCurrentPage >= this.merchantTotalPages) {
return;
}
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() {
this.baseFormData.forEach((item, index) => {
if (item.name === "staffId") {
this.$set(this.baseFormData[index], "optionList", this.baseData.staffOptions);
mergeSelectedMerchantOptions(list) {
const optionMap = new Map();
list.forEach((item) => {
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() {
return new Promise((resolve) => {
......@@ -236,10 +304,11 @@ export default {
},
async handleReset() {
this.searchForm = deepClone(DEFAULT_SEARCH_FORM);
await this.loadStaffOptions();
this.resetMerchantSearch();
this.handleSearch();
},
handleDateChange() {
async handleDateChange() {
this.syncRouteQuery();
this.handleSearch();
},
handleTabClick(tab) {
......@@ -247,6 +316,7 @@ export default {
if (eventCode) {
this.setReportTrackData(0, eventCode, { reportDate: this.reportDate });
}
this.syncRouteQuery();
this.$nextTick(() => {
this.handleSearch();
});
......@@ -265,6 +335,8 @@ export default {
id: row.id,
journalType: this.activeTab,
reportDate: this.reportDate,
merchantId: row.merchantId,
staffUuid: row.staffUuid,
},
});
}
......
const { createLoggedInClient } = require("../../src/libs/rop/ropClient");
/**
* Jest / 集成测试用 ROP 客户端
*/
async function createTestClient(options = {}) {
return createLoggedInClient({
userName: process.env.ROP_TEST_USER || "glsadmin",
password: process.env.ROP_TEST_PASSWORD || "123456",
...options,
});
}
function isIntegrationEnabled() {
return process.env.ROP_INTEGRATION === "1" || process.env.ROP_INTEGRATION === "true";
}
module.exports = {
createTestClient,
isIntegrationEnabled,
};
const { createTestClient, isIntegrationEnabled } = require("../../helpers/ropTestClient");
const describeIntegration = isIntegrationEnabled() ? describe : describe.skip;
describeIntegration("journalRecord ROP integration", () => {
jest.setTimeout(60000);
it("overview.page 应返回分页数据", async () => {
const client = await createTestClient();
const data = await client.callSmartcarlife("dailyReport.overview.page", {
currentPage: 1,
pageSize: 5,
templateType: 1,
reportDate: new Date().toISOString().slice(0, 10),
});
expect(data).toBeDefined();
expect(typeof data.total).toBe("number");
});
});
const { mapOverviewRow } = require("@/api/adapters/journalRecord/mapOverviewRow");
describe("mapOverviewRow", () => {
it("应将 Swagger 字段映射为表格字段", () => {
const row = mapOverviewRow({
id: 1,
staffName: "张三",
sceneType: "1",
onBreak: "在岗",
createdDate: "2026-07-16 10:00:00",
reportStatus: 1,
});
expect(row.bizTypeName).toBe("轻改");
expect(row.attendanceStatus).toBe("在岗");
expect(row.lastSaveTime).toBe("2026-07-16 10:00:00");
expect(row.submitTime).toBe("2026-07-16 10:00:00");
});
it("sceneType 0 应映射为权益", () => {
const row = mapOverviewRow({ sceneType: "0" });
expect(row.bizTypeName).toBe("权益");
expect(row.bizType).toBe(2);
});
});
const {
compareContracts,
normalizeParams,
} = require("@/libs/rop/contractDiff");
describe("contractDiff", () => {
const base = {
method: "dj.api.smartcarlife.demo.list",
request: {
parameters: [
{ name: "currentPage", in: "query", type: "int", required: false },
{ name: "pageSize", in: "query", type: "int", required: false },
],
},
response: {
pagination: { fields: ["list", "total", "pageNum", "pageSize"] },
fields: [{ name: "id", type: "integer" }, { name: "name", type: "string" }],
},
};
it("normalizeParams 应忽略 sessionId", () => {
const params = normalizeParams([
{ name: "sessionId", in: "query", required: true },
{ name: "currentPage", in: "query", type: "int", required: false },
]);
expect(params.map((p) => p.name)).toEqual(["currentPage"]);
});
it("新增必填参数应视为 breaking", () => {
const fresh = {
...base,
request: {
parameters: [
...base.request.parameters,
{ name: "merchantId", in: "query", type: "string", required: true },
],
},
};
const { errors } = compareContracts(base, fresh);
expect(errors).toContain("新增必填请求参数: merchantId");
});
it("分页结构消失应视为 breaking", () => {
const fresh = {
...base,
response: { pagination: null, fields: [] },
};
const { errors } = compareContracts(base, fresh);
expect(errors).toContain("响应分页结构消失");
});
});
const {
resolveApiName,
getAxiosConfigKey,
getSignWay,
} = require("@/libs/rop/resolveApiName");
describe("resolveApiName", () => {
it("smartcarlife 日常接口应走 dj", () => {
expect(resolveApiName("dj.api.smartcarlife.dailyReport.overview.page")).toBe("dj");
expect(getAxiosConfigKey("dj")).toBe("axios");
expect(getSignWay("dj")).toBe("sha1");
});
it("sop.strategy 应走 strategy", () => {
expect(resolveApiName("dj.api.smartcarlife.sop.strategy.xxx")).toBe("strategy");
expect(getAxiosConfigKey("strategy")).toBe("axios_strategy");
});
it("pad.api 应沿用 dj", () => {
expect(resolveApiName("dj.pad.api.something")).toBe("dj");
});
it("oaapproval 与开放平台创建商户", () => {
expect(resolveApiName("dj.api.oaapproval.flow.start")).toBe("oaapproval");
expect(resolveApiName("merchants.api.open.createMerchantWithPermissions")).toBe("oaapproval");
expect(getAxiosConfigKey("oaapproval")).toBe("axios_oaapproval");
});
it("stock 应走 dj.smartcarlife", () => {
expect(resolveApiName("dj.smartcarlife.stock.outbound.list")).toBe("dj.smartcarlife");
expect(getAxiosConfigKey("dj.smartcarlife")).toBe("axios");
});
it("fallback 应取 .api 前段", () => {
expect(resolveApiName("scrm.api.user.list")).toBe("scrm");
expect(getAxiosConfigKey("scrm")).toBe("axios2");
});
it("空 method 返回空字符串", () => {
expect(resolveApiName("")).toBe("");
});
});
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");
});
});
const sign = require("@/libs/rop/signCore");
const buildRopPayload = require("@/libs/rop/buildRopPayload");
describe("rop signCore", () => {
it("相同参数应生成稳定签名", () => {
const secret = "test-secret";
const params = buildRopPayload("appkey", "dj.api.user.login", {
userName: "demo",
password: "abc",
}, null);
params.timestamp = 1700000000000;
const first = sign(params, [], secret, "sha1");
const second = sign({ ...params }, [], secret, "sha1");
expect(first.sign).toBe(second.sign);
expect(first.sign).toMatch(/^[A-F0-9]{40}$/);
});
it("修改参数后签名应变化", () => {
const secret = "test-secret";
const base = buildRopPayload("appkey", "dj.api.test", { foo: "bar" });
base.timestamp = 1700000000000;
const signedA = sign(base, [], secret, "sha1");
const signedB = sign({ ...base, foo: "baz" }, [], secret, "sha1");
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}$/);
});
});
const {
buildContract,
extractRequestContract,
detectPagination,
methodSuffixToPascal,
} = require("@/libs/rop/swaggerInspect");
const miniSwagger = {
paths: {
"/router/dj.api.smartcarlife.demo.list/1.0.0": {
post: {
summary: "演示列表",
parameters: [
{ name: "currentPage", in: "query", type: "int", required: false, description: "页码" },
{ name: "sessionId", in: "query", type: "string", required: true, description: "会话" },
],
responses: {
200: {
schema: { $ref: "#/definitions/RopResponse<RpcPagination<DemoRow>>" },
},
},
},
},
},
definitions: {
"RopResponse<RpcPagination<DemoRow>>": {
properties: {
code: { type: "string" },
data: { $ref: "#/definitions/RpcPagination<DemoRow>" },
},
},
"RpcPagination<DemoRow>": {
properties: {
pageNum: { type: "integer" },
pageSize: { type: "integer" },
total: { type: "integer" },
list: { type: "array", items: { $ref: "#/definitions/DemoRow" } },
},
},
DemoRow: {
properties: {
id: { type: "integer" },
name: { type: "string" },
},
},
},
};
describe("swaggerInspect", () => {
it("应解析请求 query 参数", () => {
const op = miniSwagger.paths["/router/dj.api.smartcarlife.demo.list/1.0.0"].post;
const request = extractRequestContract(op);
expect(request.parameters.map((p) => p.name)).toEqual(["currentPage", "sessionId"]);
});
it("应识别 RpcPagination", () => {
const pagination = detectPagination(miniSwagger, "RopResponse<RpcPagination<DemoRow>>");
expect(pagination.type).toContain("RpcPagination");
expect(pagination.fields).toContain("list");
});
it("应生成完整 contract", () => {
const contract = buildContract(miniSwagger, "dj.api.smartcarlife.demo.list");
expect(contract.method).toBe("dj.api.smartcarlife.demo.list");
expect(contract.summary).toBe("演示列表");
expect(contract.response.pagination).toBeTruthy();
});
it("methodSuffixToPascal 应组合末两段", () => {
expect(methodSuffixToPascal("dj.api.smartcarlife.dailyReport.overview.page")).toBe("OverviewPage");
expect(methodSuffixToPascal("dj.api.smartcarlife.dailyReport.detail.select")).toBe("DetailSelect");
});
it("listMethodsByPrefix 应按前缀过滤", () => {
const { listMethodsByPrefix } = require("@/libs/rop/swaggerInspect");
const all = listMethodsByPrefix(miniSwagger, "dj.api.smartcarlife");
expect(all).toEqual(["dj.api.smartcarlife.demo.list"]);
const none = listMethodsByPrefix(miniSwagger, "dj.api.other");
expect(none).toEqual([]);
});
it("buildJsdocTypedefs 应包含请求与分页 typedef", () => {
const { buildJsdocTypedefs } = require("@/libs/rop/swaggerInspect");
const contract = buildContract(miniSwagger, "dj.api.smartcarlife.demo.list");
const typedefs = buildJsdocTypedefs(contract);
expect(typedefs).toContain("@typedef {Object} DemoListParams");
expect(typedefs).toContain("@property {number} currentPage");
expect(typedefs).toContain("@typedef {Object} DemoListPageResponse");
expect(typedefs).toContain("@property {DemoListRow[]} [list]");
});
});
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!