Commit bad969b4 by wangzhihui

Merge branch 'feature/strategy-center' of http://192.168.3.233:8090/saas_plus/dj…

…-car-life-system into feature/strategy-center
2 parents 88943137 ce30de47
...@@ -17,7 +17,6 @@ npx playwright test tests/e2e/xxx.spec.js ...@@ -17,7 +17,6 @@ npx playwright test tests/e2e/xxx.spec.js
# 核心规范(必须严格遵守) # 核心规范(必须严格遵守)
## 1. 测试分类与文件存放规范 ## 1. 测试分类与文件存放规范
请根据我的要求,将测试严格分类,并【在回复中明确指出该测试文件应该存放的路径】:
* 【单元测试 (Unit Test)】 * 【单元测试 (Unit Test)】
- 命名格式:`*.spec.js` - 命名格式:`*.spec.js`
...@@ -31,14 +30,37 @@ npx playwright test tests/e2e/xxx.spec.js ...@@ -31,14 +30,37 @@ npx playwright test tests/e2e/xxx.spec.js
* 【E2E 测试 (End-to-End Test)】 * 【E2E 测试 (End-to-End Test)】
- 命名格式:`*.e2e.js` - 命名格式:`*.e2e.js`
- 存放位置:必须独立于 src,统一存放在项目根目录的 【`/e2e`】 文件夹下。 - 存放位置:必须独立于 src,统一存放在项目根目录的【`/e2e`】文件夹下。
- 测试原则:站在真实用户视角测试完整业务流,不涉及任何 Vue 内部实现细节。 - 测试原则:站在真实用户视角测试完整业务流,不涉及任何 Vue 内部实现细节。
## 2. Vue 2 测试代码编写守则 ## 2. 测试编写原则
**重要:如果单元测试暴露出来业务代码的问题,不要修改业务代码,只修复测试代码。**
业务代码的逻辑应该由业务需求驱动,而不是为了通过测试而修改。
## 3. Vue 2 测试代码编写守则
* 【内存泄露防护】:在单测和集成测试的 `afterEach` 钩子中,必须调用 `wrapper.destroy()` 销毁实例。 * 【内存泄露防护】:在单测和集成测试的 `afterEach` 钩子中,必须调用 `wrapper.destroy()` 销毁实例。
* 【异步处理】:遇到事件触发、数据改变后影响 DOM 的情况,必须使用 `await localVue.nextTick()` 或 `await wrapper.vm.$nextTick()`。 * 【异步处理】:遇到事件触发、数据改变后影响 DOM 的情况,必须使用 `await localVue.nextTick()` 或 `await wrapper.vm.$nextTick()`。
* 【Vuex 注入】:如果组件依赖 Vuex,必须使用 `createLocalVue()` 并注入对应的局部 store module,禁止直接污染全局 store。 * 【Vuex 注入】:如果组件依赖 Vuex,必须使用 `createLocalVue()` 并注入对应的局部 store module,禁止直接污染全局 store。
* 【测试用例结构】:遵循 AAA 模式(Arrange 准备数据, Act 执行操作, Assert 断言结果)。描述性文字(`describe`, `it`)要清晰表达业务意图。 * 【测试用例结构】:遵循 AAA 模式(Arrange 准备数据,Act 执行操作,Assert 断言结果)。描述性文字(`describe`, `it`)要清晰表达业务意图。
## 4. E2E 测试编写指南
### 测试场景设计
- 从真实用户视角出发,测试完整业务流程
- 覆盖主要功能路径和常见边缘情况
- 验证页面导航、数据展示、表单交互等
### 最佳实践
- 使用 `test.beforeEach` 进行登录等前置操作
- 使用 `page.waitForLoadState('networkidle')` 等待异步请求完成
- 使用有意义的测试用例名称,描述业务意图
- 截图和录屏仅在失败时保存(已在配置中设置)
### 文件命名
- 格式:`*.e2e.js`
- 示例:`e2e/taskCenter.e2e.js`
--- ---
...@@ -47,13 +69,60 @@ npx playwright test tests/e2e/xxx.spec.js ...@@ -47,13 +69,60 @@ npx playwright test tests/e2e/xxx.spec.js
1. 💡 这是一个 [单元测试 / 集成测试 / E2E 测试]。 1. 💡 这是一个 [单元测试 / 集成测试 / E2E 测试]。
2. 📂 推荐的文件存放路径是:`[具体路径/文件名]` 2. 📂 推荐的文件存放路径是:`[具体路径/文件名]`
3. 📝 测试代码:[具体的测试代码] 3. 📝 测试代码:[具体的测试代码]
### E2E 测试 (End-to-End Tests)
存放位置:放在项目根目录的 e2e/ 文件夹下。
原因:Vue 2 官方早期推荐的 vue-cli 工具链(如 Cypress 或 Nightwatch 插件)默认也会在根目录生成 tests/e2e。由于 E2E 模拟的是真实用户在浏览器里点来点去,它会经历“登录 -> 个人中心 -> 购物车 -> 结账”一整套完整业务,无法归属于任何一个单一的 feature 目录,所以必须独立出来。
## 已修改的配置文件 ## 已修改的配置文件
- `jest.config.js` - 添加了 transformIgnorePatterns - `jest.config.js` - 添加了 transformIgnorePatterns
- `package.json` - 修复了 test:unit 脚本,添加了 test:unit:legacy - `package.json` - 修复了 test:unit 脚本,添加了 test:unit:legacy
- `playwright.config.js` - 新增 E2E 测试配置 - `playwright.config.js` - 新增 E2E 测试配置
---
## 5. E2E 登录态处理(重要)
### 问题背景
本项目(D2Admin + Vuex)的登录态判断依赖 **Vuex 内存状态**(`store.state.d2admin.user.info`),
而非仅 Cookie/Token。路由守卫逻辑:
```
store.state.d2admin.user.info 存在 → 放行
store.state.d2admin.user.info 为空 → 跳转 /login
```
Playwright 的 `storageState` 只能持久化 **Cookie + localStorage**,无法保存 Vuex 内存,
因此每个新 browser context 都会丢失登录态,无法通过 `storageState` 跨 context 保持登录。
### 解决方案:共享 context
**不动业务代码**,在 `beforeAll` 中创建 context 并登录一次,同一个 describe 内的
所有 test 复用同一个 `sharedPage`,Vuex 内存态自然保持。
```js
let sharedPage;
test.beforeAll(async ({ browser }) => {
const context = await browser.newContext();
sharedPage = await context.newPage();
await sharedPage.goto("/#/login");
await sharedPage.getByPlaceholder("账户").fill("xxx");
await sharedPage.getByPlaceholder("密码").fill("xxx");
await sharedPage.getByRole("button", { name: "登录" }).click();
await sharedPage.waitForURL(/#\/index/);
});
test("用例1", async () => {
await sharedPage.goto("/#/target-page"); // 复用已登录的 page
});
test.afterAll(async () => {
await sharedPage.context().close();
});
```
### 注意事项
1. **不使用 Playwright 默认的 `page` fixture**,改用闭包变量 `sharedPage`
2. **每个 test 开头做 `goto`** 导航到目标页面,用 URL 导航来隔离 test 间状态
3. **afterAll 关闭 context**,避免资源泄漏
4. URL 提取为常量(如 `BASE_URL`),方便切换测试环境
# CodeGraph data files
# These are local to each machine and should not be committed
# Database
*.db-wal
*.db-shm
# Cache
cache/
# Logs
*.log
# Hook markers
.dirty
This file is too large to display.
...@@ -28,9 +28,15 @@ yarn-error.log* ...@@ -28,9 +28,15 @@ yarn-error.log*
*.sw* *.sw*
# AI Local # AI Local
.cursor/ .cursor/
.claude/settings.local.json .claude/settings.local.json
.roo/ .roo/
.copilot/ .copilot/
.windsurf/ .windsurf/
/.codegraph/
# test
/playwright/
## 变更内容
-
## 测试情况
-
## 风险评估
-
## Checklist
- [ ] 已自测
- [ ] 已更新文档
- [ ] 已通知相关人员
...@@ -12,7 +12,6 @@ export default antfu({ ...@@ -12,7 +12,6 @@ export default antfu({
"dist", "dist",
// unplugin-auto-import 生成的类型文件,每次提交都改变,所以加入这里吧,与 .gitignore 配合使用 // unplugin-auto-import 生成的类型文件,每次提交都改变,所以加入这里吧,与 .gitignore 配合使用
"auto-import.d.ts", "auto-import.d.ts",
"e2e/",
"build/", "build/",
"node_modules/", "node_modules/",
// # node 覆盖率文件 // # node 覆盖率文件
......
This diff could not be displayed because it is too large.
...@@ -68,7 +68,7 @@ ...@@ -68,7 +68,7 @@
"@babel/plugin-proposal-nullish-coalescing-operator": "^7.17.12", "@babel/plugin-proposal-nullish-coalescing-operator": "^7.17.12",
"@babel/plugin-proposal-optional-chaining": "7.13.12", "@babel/plugin-proposal-optional-chaining": "7.13.12",
"@kazupon/vue-i18n-loader": "^0.4.1", "@kazupon/vue-i18n-loader": "^0.4.1",
"@playwright/test": "^1.60.0", "@playwright/test": "^1.39.0",
"@sentry/webpack-plugin": "^1.18.9", "@sentry/webpack-plugin": "^1.18.9",
"@vue/babel-helper-vue-jsx-merge-props": "^1.4.0", "@vue/babel-helper-vue-jsx-merge-props": "^1.4.0",
"@vue/cli-plugin-babel": "~5.0.8", "@vue/cli-plugin-babel": "~5.0.8",
...@@ -85,6 +85,7 @@ ...@@ -85,6 +85,7 @@
"jest-serializer-vue": "^3.1.0", "jest-serializer-vue": "^3.1.0",
"jest-transform-stub": "^2.0.0", "jest-transform-stub": "^2.0.0",
"md5": "^2.3.0", "md5": "^2.3.0",
"playwright": "^1.39.0",
"postcss-preset-env": "^7.7.2", "postcss-preset-env": "^7.7.2",
"postcss-px-to-viewport": "^1.1.1", "postcss-px-to-viewport": "^1.1.1",
"sass": "~1.62.0", "sass": "~1.62.0",
......
...@@ -11,11 +11,18 @@ ...@@ -11,11 +11,18 @@
*/ */
import { defineConfig, devices } from "@playwright/test"; import { defineConfig, devices } from "@playwright/test";
import dayjs from "dayjs";
// 生成时间戳,用于报告和结果目录
const timestamp = dayjs().format("YYYY-MM-DD HH");
export default defineConfig({ export default defineConfig({
// 测试文件位置 // 测试文件位置
testDir: "./e2e", testDir: "./e2e",
// 测试文件匹配模式
testMatch: "**/*.e2e.js",
// 超时时间 // 超时时间
timeout: 30 * 1000, timeout: 30 * 1000,
...@@ -28,21 +35,28 @@ export default defineConfig({ ...@@ -28,21 +35,28 @@ export default defineConfig({
retries: 1, retries: 1,
// 并行执行配置 // 并行执行配置
workers: 4, workers: 1,
// 是否失败即停止 // 是否失败即停止
failOnFlakyTests: false, failOnFlakyTests: false,
// 报告配置 // 报告配置
// 产出到 playwright/report/index.YYYY-MM-DD hh-mm.html
reporter: [ reporter: [
["list"], ["list"],
["html", { outputFolder: "playwright-report", open: "never" }], [
"html",
{
outputFolder: `playwright/report/${timestamp}`,
open: "never",
},
],
], ],
// 共享配置 // 共享配置
use: { use: {
// 基础 URL // 基础 URL - 使用当前 IP 访问
baseURL: process.env.BASE_URL || "http://localhost:8080", baseURL: process.env.BASE_URL || "http://192.168.1.146:8080/dj-carlife-web/",
// 截图配置 // 截图配置
screenshot: "only-on-failure", screenshot: "only-on-failure",
...@@ -58,6 +72,10 @@ export default defineConfig({ ...@@ -58,6 +72,10 @@ export default defineConfig({
navigationTimeout: 30000, navigationTimeout: 30000,
}, },
// 测试结果目录(截图、视频、trace)
// 产出到 playwright/result/YYYY-MM-DD hh-mm/
outputDir: `playwright/result/${timestamp}`,
// 浏览器配置 // 浏览器配置
projects: [ projects: [
{ {
...@@ -67,40 +85,19 @@ export default defineConfig({ ...@@ -67,40 +85,19 @@ export default defineConfig({
viewport: { width: 1920, height: 1080 }, viewport: { width: 1920, height: 1080 },
}, },
}, },
{
name: "firefox",
use: {
...devices["Desktop Firefox"],
viewport: { width: 1920, height: 1080 },
},
},
{
name: "webkit",
use: {
...devices["Desktop Safari"],
viewport: { width: 1920, height: 1080 },
},
},
// 移动端测试
{
name: "Mobile Chrome",
use: {
...devices["Pixel 5"],
},
},
{
name: "Mobile Safari",
use: {
...devices["iPhone 12"],
},
},
], ],
// Web 服务器配置 (可选,用于自动启动开发服务器) // Web 服务器配置 (用于自动启动开发服务器)
// webServer: { // 如果在远程机器运行,请设置 SKIP_WEBSERVER=true 并手动启动服务
// command: "npm run dev", webServer: process.env.SKIP_WEBSERVER
// port: 8080, ? undefined
// timeout: 120 * 1000, : {
// reuseExistingServer: true, command: "npm run serve",
// }, timeout: 120 * 1000,
reuseExistingServer: true,
// 等待 URL,确保服务器准备好
url: process.env.BASE_URL
? process.env.BASE_URL.replace(/\/$/, "") + "/#/"
: "http://192.168.1.146:8080/dj-carlife-web/#/",
},
}); });
...@@ -141,8 +141,7 @@ ...@@ -141,8 +141,7 @@
<el-tag v-if="hasValue(sub, scope.row)" :type="getSchemaTagOptions(sub, scope.row).type"> <el-tag v-if="hasValue(sub, scope.row)" :type="getSchemaTagOptions(sub, scope.row).type">
{{ getSchemaTagOptions(sub, scope.row).label }} {{ getSchemaTagOptions(sub, scope.row).label }}
</el-tag> </el-tag>
<span v-else>-</span> <span v-else>-</span>
</div> </div>
</template> </template>
...@@ -256,7 +255,9 @@ ...@@ -256,7 +255,9 @@
<el-tag v-if="hasValue(item, scope.row)" :type="getSchemaTagOptions(item, scope.row).type"> <el-tag v-if="hasValue(item, scope.row)" :type="getSchemaTagOptions(item, scope.row).type">
{{ getSchemaTagOptions(item, scope.row).label }} {{ getSchemaTagOptions(item, scope.row).label }}
</el-tag> </el-tag>
<span v-else>-</span> <span v-else>-</span>
</div> </div>
</template> </template>
...@@ -866,4 +867,4 @@ export default { ...@@ -866,4 +867,4 @@ export default {
margin-bottom: 8px; margin-bottom: 8px;
} }
} }
</style>
\ No newline at end of file \ No newline at end of file
</style>
<template> <template>
<div class="dashboard-card rank-card"> <div class="dashboard-card rank-card">
<div class="card-header"> <div class="card-header">
<span class="card-title">线上运营分布</span> <span class="card-title">线上运营分布</span>
</div> </div>
<div class="rank-list"> <div class="rank-list">
<!-- 表头 --> <!-- 表头 -->
<div class="rank-header"> <div class="rank-header">
<span class="rank-header-col" style="flex: 1;">排名</span> <div v-for="col in rankColumns"
<span class="rank-header-col" style="flex: 1;">姓名</span> :key="col.key"
<span class="rank-header-col" style="flex: 1; text-align: center;">策略总数</span> :class="col.className">
<span class="rank-header-col" style="flex: 1; text-align: center;">占比</span> {{ col.label }}
<span class="rank-header-col" style="flex: 1; text-align: center;">门店总数</span>
<span class="rank-header-col" style="flex: 1; text-align: center;">占比</span>
</div>
<!-- 列表内容 -->
<block v-if="rankData.length > 0">
<div v-for="(item, index) in rankData"
:key="index"
class="rank-item">
<!-- 排名 Icon 处理 -->
<div class="rank-index"
:class="`rank-${index + 1}`">
<img v-if="index < 3"
:src="require(`@/assets/strategy/icon-strategy-rank0${index + 1}.png`)"
style="width: 24px; height: 24px;" />
<span v-else
style="width: 20px; height: 20px; border-radius: 50%; opacity: 1; background: #2a58ad1a; display: inline-block; text-align: center; line-height: 20px;">
{{ index + 1 }}
</span>
</div>
<div class="rank-name" :title="item.staffName">
{{ item.staffName }}
</div>
<div class="rank-col">
{{ item.strategyCount }}
</div>
<div class="rank-col">
{{ item.strategyCountPercent }}%
</div>
<div class="rank-col">
{{ item.storeCount }}
</div>
<div class="rank-col">
{{ item.storeCountPercent }}%
</div>
</div>
</block>
<block v-else>
<!-- 空数据占位,实际显示在 .dashboard-card 层级 -->
</block>
</div> </div>
<div v-if="rankData.length === 0" class="empty-box"> </div>
<img alt="暂无数据" :src="noDataImg"> <!-- 列表内容 -->
<div class="empty-text"> <template v-if="rankData.length > 0">
暂无数据 <div v-for="(item, index) in rankData"
</div> :key="index"
class="rank-item">
<!-- 排名 Icon 处理 -->
<div class="rank-index"
:class="`rank-${index + 1}`">
<img v-if="index < 3"
style="width: 24px; height: 24px;"
:src="require(`@/assets/strategy/icon-strategy-rank0${index + 1}.png`)" />
<span v-else
style="width: 20px; height: 20px; border-radius: 50%; opacity: 1; background: #2a58ad1a; display: inline-block; text-align: center; line-height: 20px;">
{{ index + 1 }}
</span>
</div>
<div class="rank-name" :title="item.staffName">
{{ item.staffName || '-' }}
</div>
<div class="rank-col">
{{ item.strategyCount }}
</div>
<div class="rank-col">
{{ item.strategyCountPercent }}%
</div>
<div class="rank-col">
{{ item.storeCount }}
</div>
<div class="rank-col">
{{ item.storeCountPercent }}%
</div>
</div> </div>
<div class="bottom-cover"></div> </template>
</div>
<div v-if="rankData.length === 0" class="empty-box">
<img alt="暂无数据" :src="noDataImg">
<div class="empty-text">
暂无数据
</div>
</div> </div>
<div class="bottom-cover"></div>
</div>
</template> </template>
<script> <script>
import noDataImg from "@/assets/strategy/emepty-strategy.png"; import noDataImg from "@/assets/strategy/emepty-strategy.png";
const RANK_COLUMNS = [
{ key: "rank", label: "排名", className: "rank-index" },
{ key: "name", label: "姓名", className: "rank-name" },
{ key: "strategyCount", label: "策略总数", className: "rank-col" },
{ key: "strategyPercent", label: "占比", className: "rank-col" },
{ key: "storeCount", label: "门店总数", className: "rank-col" },
{ key: "storePercent", label: "占比", className: "rank-col" },
];
export default { export default {
name: "OnlineOperatorRanking", name: "OnlineOperatorRanking",
props: { props: {
...@@ -75,6 +80,7 @@ export default { ...@@ -75,6 +80,7 @@ export default {
data() { data() {
return { return {
noDataImg, noDataImg,
rankColumns: RANK_COLUMNS,
}; };
}, },
}; };
...@@ -123,13 +129,19 @@ $bg-white: #fff; ...@@ -123,13 +129,19 @@ $bg-white: #fff;
font-size: 13px; font-size: 13px;
overflow: scroll; overflow: scroll;
max-height: 260px; max-height: 260px;
.rank-index,
.rank-name,
.rank-col {
flex: 1;
}
.rank-col {
text-align: center;
}
.rank-header { .rank-header {
display: flex; display: flex;
color: #909399; color: #909399;
.rank-header-col {
display: inline-block;
}
} }
.rank-item { .rank-item {
...@@ -141,12 +153,7 @@ $bg-white: #fff; ...@@ -141,12 +153,7 @@ $bg-white: #fff;
border-bottom: none; border-bottom: none;
} }
.rank-index {
flex: 1;
}
.rank-name { .rank-name {
flex: 1;
color: #303133; color: #303133;
overflow: hidden; overflow: hidden;
white-space: nowrap; white-space: nowrap;
...@@ -154,8 +161,6 @@ $bg-white: #fff; ...@@ -154,8 +161,6 @@ $bg-white: #fff;
} }
.rank-col { .rank-col {
flex: 1;
text-align: center;
color: #606266; color: #606266;
} }
} }
......
...@@ -715,7 +715,6 @@ export default { ...@@ -715,7 +715,6 @@ export default {
uuid: this.strategyTypeOperatorFilter, uuid: this.strategyTypeOperatorFilter,
}; };
const res = await getStrategyTypeDist(params); const res = await getStrategyTypeDist(params);
console.log("getStrategyTypeDist", res);
this.strategyTypeData = res || []; this.strategyTypeData = res || [];
} catch (error) { } catch (error) {
console.error("获取策略类型分布失败:", error); console.error("获取策略类型分布失败:", error);
......
...@@ -193,12 +193,13 @@ ...@@ -193,12 +193,13 @@
<div v-loading="staffRightLoading" <div v-loading="staffRightLoading"
class="staff-overview-item right"> class="staff-overview-item right">
<div class="content"> <div class="content">
<OverViewList :business-type="paramsInfo.bizs" <OverViewList v-if="paramsInfo.bizs != 3"
:business-type="paramsInfo.bizs"
:is-harmony="isHarmony" :is-harmony="isHarmony"
:is-staff="true" :is-staff="true"
:view-data="viewData"> :view-data="viewData">
</OverViewList> </OverViewList>
<div v-show="!isHarmony" class="empty-box"> <div v-show="!isHarmony || paramsInfo.bizs == 3" class="empty-box">
<img alt="暂无数据" src="@/assets/strategy/emepty-strategy.png"> <img alt="暂无数据" src="@/assets/strategy/emepty-strategy.png">
<div class="empty-text"> <div class="empty-text">
暂无数据 暂无数据
......
...@@ -149,13 +149,14 @@ ...@@ -149,13 +149,14 @@
<div class="summary-overview-item right"> <div class="summary-overview-item right">
<div v-loading="summaryRightLoading" <div v-loading="summaryRightLoading"
class="content"> class="content">
<OverViewList has-e-hi <OverViewList v-if="paramsInfo.bizs != 3"
has-e-hi
:business-type="paramsInfo.bizs" :business-type="paramsInfo.bizs"
:is-harmony="isHarmony" :is-harmony="isHarmony"
:is-oem-data-source="activeDataSource === 2" :is-oem-data-source="activeDataSource === 2"
:view-data="viewData"> :view-data="viewData">
</OverViewList> </OverViewList>
<div v-show="!isHarmony" class="empty-box"> <div v-show="!isHarmony || paramsInfo.bizs == 3" class="empty-box">
<img alt="暂无数据" src="@/assets/strategy/emepty-strategy.png"> <img alt="暂无数据" src="@/assets/strategy/emepty-strategy.png">
<div class="empty-text"> <div class="empty-text">
暂无数据 暂无数据
......
...@@ -1030,8 +1030,6 @@ export default { ...@@ -1030,8 +1030,6 @@ export default {
pageSize: 20, pageSize: 20,
currentPage: 1, currentPage: 1,
approvalVisible: false, approvalVisible: false,
/** 请求序列号:防止快速查询时旧请求覆盖新数据 */
_searchSeq: 0,
}; };
}, },
computed: { computed: {
...@@ -1506,13 +1504,11 @@ export default { ...@@ -1506,13 +1504,11 @@ export default {
this.getList(); this.getList();
}, },
getList() { getList() {
const seq = ++this._searchSeq
let params = this.getParams(); let params = this.getParams();
let eventParams = deepClone({ ...this.page, ...params }); let eventParams = deepClone({ ...this.page, ...params });
if (eventParams?.zyVoucherStatus == 1) if (eventParams?.zyVoucherStatus == 1)
eventParams.status = 13; eventParams.status = 13;
getList(eventParams).then((res) => { getList(eventParams).then((res) => {
if (seq !== this._searchSeq) return
this.tableData = res.list.map((item) => { this.tableData = res.list.map((item) => {
item.paySuccessDate = item.paySuccessDate item.paySuccessDate = item.paySuccessDate
? Util.dateFormate(item.paySuccessDate, "YYYY-MM-DD HH:mm:ss") ? Util.dateFormate(item.paySuccessDate, "YYYY-MM-DD HH:mm:ss")
...@@ -1525,13 +1521,11 @@ export default { ...@@ -1525,13 +1521,11 @@ export default {
}); });
}, },
getOrderCount() { getOrderCount() {
const seq = ++this._searchSeq
let params = this.getParams(); let params = this.getParams();
let eventParams = deepClone({ ...params }); let eventParams = deepClone({ ...params });
if (eventParams?.zyVoucherStatus == 1) if (eventParams?.zyVoucherStatus == 1)
eventParams.status = 13; eventParams.status = 13;
getOrderCount(eventParams).then((res) => { getOrderCount(eventParams).then((res) => {
if (seq !== this._searchSeq) return
this.totalCount = res.totalPriceCount; this.totalCount = res.totalPriceCount;
}); });
}, },
......
...@@ -966,8 +966,6 @@ export default { ...@@ -966,8 +966,6 @@ export default {
pageSize: 20, pageSize: 20,
currentPage: 1, currentPage: 1,
approvalVisible: false, approvalVisible: false,
/** 请求序列号:防止快速查询时旧请求覆盖新数据 */
_searchSeq: 0,
}; };
}, },
computed: { computed: {
...@@ -1360,7 +1358,6 @@ export default { ...@@ -1360,7 +1358,6 @@ export default {
this.getList(); this.getList();
}, },
getList() { getList() {
const seq = ++this._searchSeq
let params = this.getParams(); let params = this.getParams();
params = { params = {
...this.page, ...this.page,
...@@ -1368,7 +1365,6 @@ export default { ...@@ -1368,7 +1365,6 @@ export default {
}; };
// console.log(params) // console.log(params)
getList(params).then((res) => { getList(params).then((res) => {
if (seq !== this._searchSeq) return
this.tableData = res.list.map((item) => { this.tableData = res.list.map((item) => {
item.paySuccessDate = item.paySuccessDate item.paySuccessDate = item.paySuccessDate
? Util.dateFormate(item.paySuccessDate, "YYYY-MM-DD HH:mm:ss") ? Util.dateFormate(item.paySuccessDate, "YYYY-MM-DD HH:mm:ss")
...@@ -1387,13 +1383,11 @@ export default { ...@@ -1387,13 +1383,11 @@ export default {
}); });
}, },
getOrderCount() { getOrderCount() {
const seq = ++this._searchSeq
let params = this.getParams(); let params = this.getParams();
params = { params = {
...params, ...params,
}; };
getOrderCount(params).then((res) => { getOrderCount(params).then((res) => {
if (seq !== this._searchSeq) return
this.totalCount = res.totalPriceCount; this.totalCount = res.totalPriceCount;
}); });
}, },
......
...@@ -142,9 +142,7 @@ export default { ...@@ -142,9 +142,7 @@ export default {
light: [] light: []
}, },
/** 路由带入:匹配完成后清空 */ /** 路由带入:匹配完成后清空 */
pendingLegacyLeaf: null, pendingLegacyLeaf: null
/** 请求序列号:防止快速切换时旧请求覆盖新数据 */
_loadScenesSeq: 0
} }
}, },
computed: { computed: {
...@@ -276,13 +274,11 @@ export default { ...@@ -276,13 +274,11 @@ export default {
if (category === "renewal") { if (category === "renewal") {
return return
} }
const seq = ++this._loadScenesSeq
this.scenesLoading = category === "light" this.scenesLoading = category === "light"
this.rightsScenesLoading = category === "rights" this.rightsScenesLoading = category === "rights"
try { try {
if (category === "light") { if (category === "light") {
const res = await sceneListWithOrder({ bizTypeCode: "1" }) const res = await sceneListWithOrder({ bizTypeCode: "1" })
if (seq !== this._loadScenesSeq) return
const arr = normalizeSceneResponse(res) const arr = normalizeSceneResponse(res)
const mapped = arr.map(s => buildSceneLeafItem(s, "light")) const mapped = arr.map(s => buildSceneLeafItem(s, "light"))
this.sceneSubs.light = mapped.length ? mapped : [...FALLBACK_LIGHT] this.sceneSubs.light = mapped.length ? mapped : [...FALLBACK_LIGHT]
...@@ -291,12 +287,10 @@ export default { ...@@ -291,12 +287,10 @@ export default {
sceneListWithOrder({ bizTypeCode: "2", businessType: 1 }), sceneListWithOrder({ bizTypeCode: "2", businessType: 1 }),
sceneListWithOrder({ bizTypeCode: "2", businessType: 2 }) sceneListWithOrder({ bizTypeCode: "2", businessType: 2 })
]) ])
if (seq !== this._loadScenesSeq) return
this.rightsScenesForEquity = normalizeSceneResponse(res1) this.rightsScenesForEquity = normalizeSceneResponse(res1)
this.rightsScenesForWarranty = normalizeSceneResponse(res2) this.rightsScenesForWarranty = normalizeSceneResponse(res2)
} }
} catch (e) { } catch (e) {
if (seq !== this._loadScenesSeq) return
if (category === "light") { if (category === "light") {
this.sceneSubs.light = [...FALLBACK_LIGHT] this.sceneSubs.light = [...FALLBACK_LIGHT]
} else { } else {
...@@ -304,10 +298,8 @@ export default { ...@@ -304,10 +298,8 @@ export default {
this.rightsScenesForWarranty = [] this.rightsScenesForWarranty = []
} }
} finally { } finally {
if (seq === this._loadScenesSeq) { this.scenesLoading = false
this.scenesLoading = false this.rightsScenesLoading = false
this.rightsScenesLoading = false
}
} }
}, },
ensureLeafInCategory() { ensureLeafInCategory() {
......
...@@ -124,6 +124,37 @@ describe('taskCenter 集成测试', () => { ...@@ -124,6 +124,37 @@ describe('taskCenter 集成测试', () => {
// 验证 optionList 使用的是 overdueFlagOptions // 验证 optionList 使用的是 overdueFlagOptions
expect(overdueItem.optionList).toBe(overdueFlagOptions); expect(overdueItem.optionList).toBe(overdueFlagOptions);
}); });
it('表格列应该包含任务分类列', async () => {
const mockCategories = [
{ bizType: 'type1', categoryName: '分类 1' },
{ bizType: 'type2', categoryName: '分类 2' },
];
mockGetTaskCenterBizCategoryListApi.mockResolvedValue(mockCategories);
const columns = await getTableColumns();
const bizTypeCol = columns.find((col) => col.prop === 'bizTypeName');
expect(bizTypeCol).toBeDefined();
expect(bizTypeCol.label).toBe('任务分类');
expect(bizTypeCol.prop).toBe('bizTypeName');
});
it('表格搜索表单的任务分类选项应该来自 API', async () => {
const mockCategories = [
{ bizType: 'type1', categoryName: '分类 1' },
{ bizType: 'type2', categoryName: '分类 2' },
];
mockGetTaskCenterBizCategoryListApi.mockResolvedValue(mockCategories);
const schema = await getTableFormSchema();
const bizTypeItem = schema.find((item) => item.name === 'condition.bizTypes');
expect(bizTypeItem).toBeDefined();
expect(bizTypeItem.optionList).toEqual(mockCategories);
expect(bizTypeItem.optionId).toBe('bizType');
expect(bizTypeItem.optionLabel).toBe('categoryName');
});
}); });
describe('数据结构完整性测试', () => { describe('数据结构完整性测试', () => {
...@@ -141,7 +172,7 @@ describe('taskCenter 集成测试', () => { ...@@ -141,7 +172,7 @@ describe('taskCenter 集成测试', () => {
const tableFields = tableColumns.map((col) => col.prop); const tableFields = tableColumns.map((col) => col.prop);
// 共同的字段应该都存在 // 共同的字段应该都存在
const commonFields = ['taskNo', 'createdBy', 'createdDate', 'dueTime', 'completeTime']; const commonFields = ['taskNo', 'createdBy', 'createdDate', 'dueTime', 'completeTime', 'bizTypeName'];
commonFields.forEach((field) => { commonFields.forEach((field) => {
expect(detailFields).toContain(field); expect(detailFields).toContain(field);
expect(tableFields).toContain(field); expect(tableFields).toContain(field);
......
...@@ -7,7 +7,7 @@ export async function getTaskCenterTaskDescriptionSchema() { ...@@ -7,7 +7,7 @@ export async function getTaskCenterTaskDescriptionSchema() {
label: "任务描述", label: "任务描述",
col: 24, col: 24,
labelWidth: "120px", labelWidth: "120px",
// slot : 整体的插槽名,优先级高于 name // slot : 整体的插槽名,优先级高于name
// itemStyle: 每一项的样式 // itemStyle: 每一项的样式
// tooltipProps: el-tooltip 的传参 // tooltipProps: el-tooltip 的传参
render: (h, { data, schemaItem, schema }) => { render: (h, { data, schemaItem, schema }) => {
...@@ -67,7 +67,7 @@ export async function getTaskCenterTaskDescriptionSchema() { ...@@ -67,7 +67,7 @@ export async function getTaskCenterTaskDescriptionSchema() {
col: 24, col: 24,
labelWidth: "120px", labelWidth: "120px",
render: (h, { data }) => { render: (h, { data }) => {
const names = data.assignees.map(item => item.assigneeName).join(",") || "-"; const names = (data.assignees || []).map(item => item.assigneeName).join(",") || "-";
return h("span", { return h("span", {
style: { style: {
whiteSpace: "normal", whiteSpace: "normal",
......
import { getTaskCenterTaskDescriptionSchema } from './detail.data.js'; import { getTaskCenterTaskDescriptionSchema } from "./detail.data.js";
// Mock h 函数(Vue 的渲染函数) // Mock h 函数(Vue 的渲染函数)
const createMockH = () => { function createMockH() {
return jest.fn((tag, data, children) => ({ tag, data, children })); return jest.fn((tag, data, children) => ({ tag, data, children }));
}; }
describe('detail.data.js 测试', () => { describe("detail.data.js 测试", () => {
describe('getTaskCenterTaskDescriptionSchema', () => { describe("getTaskCenterTaskDescriptionSchema", () => {
it('应该返回一个数组', async () => { it("应该返回一个数组", async () => {
const schema = await getTaskCenterTaskDescriptionSchema(); const schema = await getTaskCenterTaskDescriptionSchema();
expect(Array.isArray(schema)).toBe(true); expect(Array.isArray(schema)).toBe(true);
}); });
it('应该包含基本的 schema 项', async () => { it("应该包含基本的 schema 项", async () => {
const schema = await getTaskCenterTaskDescriptionSchema(); const schema = await getTaskCenterTaskDescriptionSchema();
const names = schema.map((item) => item.name).filter(Boolean); const names = schema.map(item => item.name).filter(Boolean);
expect(names).toContain('description'); expect(names).toContain("description");
expect(names).toContain('bizTypeName'); expect(names).toContain("bizTypeName");
expect(names).toContain('status'); expect(names).toContain("status");
expect(names).toContain('priority'); expect(names).toContain("priority");
expect(names).toContain('assignees'); expect(names).toContain("assignees");
expect(names).toContain('taskNo'); expect(names).toContain("taskNo");
expect(names).toContain('createdBy'); expect(names).toContain("createdBy");
expect(names).toContain('createdDate'); expect(names).toContain("createdDate");
expect(names).toContain('dueTime'); expect(names).toContain("dueTime");
expect(names).toContain('completeTime'); expect(names).toContain("completeTime");
}); });
it('每个 schema 项应该包含 name 和 label 属性', async () => { it("每个 schema 项应该包含 name 和 label 属性", async () => {
const schema = await getTaskCenterTaskDescriptionSchema(); const schema = await getTaskCenterTaskDescriptionSchema();
const itemsWithName = schema.filter((item) => item.name); const itemsWithName = schema.filter(item => item.name);
itemsWithName.forEach((item) => { itemsWithName.forEach((item) => {
expect(item).toHaveProperty('name'); expect(item).toHaveProperty("name");
expect(item).toHaveProperty('label'); expect(item).toHaveProperty("label");
}); });
}); });
it('description 字段应该有正确的配置', async () => { it("description 字段应该有正确的配置", async () => {
const schema = await getTaskCenterTaskDescriptionSchema(); const schema = await getTaskCenterTaskDescriptionSchema();
const descriptionItem = schema.find((item) => item.name === 'description'); const descriptionItem = schema.find(item => item.name === "description");
expect(descriptionItem).toEqual({ expect(descriptionItem).toEqual({
name: 'description', name: "description",
label: '任务描述', label: "任务描述",
col: 24, col: 24,
labelWidth: '120px', labelWidth: "120px",
tooltip: true, tooltip: true,
parentProps: { parentProps: {
style: { style: {
display: 'inline-block', display: "inline-block",
height: '32px', height: "32px",
width: 'auto', width: "auto",
maxWidth: '100%', maxWidth: "100%",
verticalAlign: 'top', verticalAlign: "top",
}, },
}, },
render: expect.any(Function), render: expect.any(Function),
...@@ -62,29 +62,29 @@ describe('detail.data.js 测试', () => { ...@@ -62,29 +62,29 @@ describe('detail.data.js 测试', () => {
}); });
}); });
it('status 字段应该有 render 函数', async () => { it("status 字段应该有 render 函数", async () => {
const schema = await getTaskCenterTaskDescriptionSchema(); const schema = await getTaskCenterTaskDescriptionSchema();
const statusItem = schema.find((item) => item.name === 'status'); const statusItem = schema.find(item => item.name === "status");
expect(statusItem.render).toBeInstanceOf(Function); expect(statusItem.render).toBeInstanceOf(Function);
}); });
it('priority 字段应该有 render 函数', async () => { it("priority 字段应该有 render 函数", async () => {
const schema = await getTaskCenterTaskDescriptionSchema(); const schema = await getTaskCenterTaskDescriptionSchema();
const priorityItem = schema.find((item) => item.name === 'priority'); const priorityItem = schema.find(item => item.name === "priority");
expect(priorityItem.render).toBeInstanceOf(Function); expect(priorityItem.render).toBeInstanceOf(Function);
}); });
it('assignees 字段的 render 函数应该正确处理执行人列表', async () => { it("assignees 字段的 render 函数应该正确处理执行人列表", async () => {
const schema = await getTaskCenterTaskDescriptionSchema(); const schema = await getTaskCenterTaskDescriptionSchema();
const assigneesItem = schema.find((item) => item.name === 'assignees'); const assigneesItem = schema.find(item => item.name === "assignees");
const h = createMockH(); const h = createMockH();
const data = { const data = {
assignees: [ assignees: [
{ assigneeName: '张三' }, { assigneeName: "张三" },
{ assigneeName: '李四' }, { assigneeName: "李四" },
], ],
}; };
...@@ -94,9 +94,9 @@ describe('detail.data.js 测试', () => { ...@@ -94,9 +94,9 @@ describe('detail.data.js 测试', () => {
expect(h).toHaveBeenCalled(); expect(h).toHaveBeenCalled();
}); });
it('assignees 字段的 render 函数应该处理空列表', async () => { it("assignees 字段的 render 函数应该处理空列表", async () => {
const schema = await getTaskCenterTaskDescriptionSchema(); const schema = await getTaskCenterTaskDescriptionSchema();
const assigneesItem = schema.find((item) => item.name === 'assignees'); const assigneesItem = schema.find(item => item.name === "assignees");
const h = createMockH(); const h = createMockH();
const data = { assignees: [] }; const data = { assignees: [] };
...@@ -106,29 +106,41 @@ describe('detail.data.js 测试', () => { ...@@ -106,29 +106,41 @@ describe('detail.data.js 测试', () => {
expect(h).toHaveBeenCalled(); expect(h).toHaveBeenCalled();
}); });
it('description 的 isHide 函数应该在 formModel.description 为空时返回 true', async () => { it("assignees 字段的 render 函数应该处理 undefined 情况", async () => {
const schema = await getTaskCenterTaskDescriptionSchema(); const schema = await getTaskCenterTaskDescriptionSchema();
const descriptionItem = schema.find((item) => item.name === 'description'); const assigneesItem = schema.find(item => item.name === "assignees");
const h = createMockH();
const data = { };
const result = assigneesItem.render(h, { data });
expect(h).toHaveBeenCalledWith("span", {}, "-");
});
it("description 的 isHide 函数应该在 formModel.description 为空时返回 true", async () => {
const schema = await getTaskCenterTaskDescriptionSchema();
const descriptionItem = schema.find(item => item.name === "description");
const result = descriptionItem.isHide({ formModel: {} }); const result = descriptionItem.isHide({ formModel: {} });
expect(result).toBe(true); expect(result).toBe(true);
}); });
it('description 的 isHide 函数应该在 formModel.description 有值时返回 false', async () => { it("description 的 isHide 函数应该在 formModel.description 有值时返回 false", async () => {
const schema = await getTaskCenterTaskDescriptionSchema(); const schema = await getTaskCenterTaskDescriptionSchema();
const descriptionItem = schema.find((item) => item.name === 'description'); const descriptionItem = schema.find(item => item.name === "description");
const result = descriptionItem.isHide({ const result = descriptionItem.isHide({
formModel: { description: '测试描述' }, formModel: { description: "测试描述" },
}); });
expect(result).toBe(false); expect(result).toBe(false);
}); });
it('应该包含两个 divider 项', async () => { it("应该包含两个 divider 项", async () => {
const schema = await getTaskCenterTaskDescriptionSchema(); const schema = await getTaskCenterTaskDescriptionSchema();
const dividers = schema.filter((item) => item.divider === true); const dividers = schema.filter(item => item.divider === true);
expect(dividers).toHaveLength(2); expect(dividers).toHaveLength(2);
}); });
......
...@@ -15,6 +15,17 @@ jest.mock("@/views/residentManage/taskCenter/api/index.js", () => ({ ...@@ -15,6 +15,17 @@ jest.mock("@/views/residentManage/taskCenter/api/index.js", () => ({
getTaskCenterBizCategoryListApi: mockGetTaskCenterBizCategoryListApi, getTaskCenterBizCategoryListApi: mockGetTaskCenterBizCategoryListApi,
})); }));
// Mock lodash-es 的 keyBy
jest.mock("lodash-es", () => ({
keyBy: jest.fn((arr, key) => {
const result = {};
arr.forEach(item => {
result[item[key]] = item;
});
return result;
}),
}));
// 在 mock 之后才导入被测试模块 // 在 mock 之后才导入被测试模块
const { getTableFormSchema, getTableColumns } = require("./table.data.js"); const { getTableFormSchema, getTableColumns } = require("./table.data.js");
...@@ -268,6 +279,18 @@ describe("table.data.js 测试", () => { ...@@ -268,6 +279,18 @@ describe("table.data.js 测试", () => {
expect(dueTimeCol.valueClass).toBeInstanceOf(Function); expect(dueTimeCol.valueClass).toBeInstanceOf(Function);
}); });
it("应该包含任务分类列", async () => {
const columns = await getTableColumns();
const bizTypeCol = columns.find(col => col.prop === "bizTypeName");
expect(bizTypeCol).toEqual({
label: "任务分类",
prop: "bizTypeName",
width: "180px",
align: "left",
});
});
it("应该包含 10 个列", async () => { it("应该包含 10 个列", async () => {
const columns = await getTableColumns(); const columns = await getTableColumns();
expect(columns).toHaveLength(10); expect(columns).toHaveLength(10);
......
...@@ -161,7 +161,7 @@ ...@@ -161,7 +161,7 @@
</template> </template>
</el-input> </el-input>
</el-form-item> </el-form-item>
<span class="range-sep">&lt;</span> <span class="range-sep">&lt;=</span>
<span class="range-mid">选中的指标值</span> <span class="range-mid">选中的指标值</span>
<span class="range-sep">&lt;</span> <span class="range-sep">&lt;</span>
<el-form-item class="condition-row__item condition-row__item--range-end" <el-form-item class="condition-row__item condition-row__item--range-end"
...@@ -800,9 +800,7 @@ export default { ...@@ -800,9 +800,7 @@ export default {
const isLastCondition = condIndex === conditions.length - 1; const isLastCondition = condIndex === conditions.length - 1;
const condLogic = this.getConditionNextLogic(cond) || fallbackLogic; const condLogic = this.getConditionNextLogic(cond) || fallbackLogic;
const metricId = cond.metricId != null && cond.metricId !== "" const metricId = this.getMetricId(group, cond);
? Number(cond.metricId)
: null;
const rule = { const rule = {
sortNo: rules.length + 1, sortNo: rules.length + 1,
......
...@@ -321,7 +321,7 @@ export default { ...@@ -321,7 +321,7 @@ export default {
async getMerchantList() { async getMerchantList() {
this.merchantSearchLoading = true; this.merchantSearchLoading = true;
try { try {
const data = await listShop4sByRef({}); const data = await listShop4sByRef({ queryAbsoluteEnable: 1 });
this.setMerchantOptions(Array.isArray(data) ? data : []); this.setMerchantOptions(Array.isArray(data) ? data : []);
} finally { } finally {
this.merchantSearchLoading = false; this.merchantSearchLoading = false;
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!