Commit 2f472807 by 前端

Merge branch 'SAAS+V5.8.5' into 'master'

上线合并

See merge request !976
2 parents fe63646f 09fb1e00
Pipeline #240 for 2f472807 failed in 0 seconds
Showing 223 changed files with 4642 additions and 37 deletions
......@@ -65,7 +65,7 @@ const _import = require("@/libs/util.import." + process.env.NODE_ENV)
本项目不是「换个 CLI」那么简单,需重做大量 Webpack 定制:
- [`vue.config.js`](../../vue.config.js):`chainWebpack`、`ThemeColorReplacer`、`CopyDir`、`SentryWebpackPlugin`、CDN externals、全局 sass `public.scss` 注入、`svg-sprite-loader`、UMD output 等
- [`vue.config.js`](../../vue.config.js):`chainWebpack`、`ThemeColorReplacer`、`CopyDir`、CDN externals、全局 sass `public.scss` 注入、`svg-sprite-loader`、UMD output 等
- Vue **2.6** + Element UI 2 + D2Admin:需 `vite-plugin-vue2`(维护已进入尾声,生态弱于 Vue3+Vite)
- 约 **20+ 路由模块 / 1100+ 页面**:需全面验证 HMR、动态路由、权限、i18n、`require.context` 等
- [`AGENTS.md`](../../AGENTS.md) 明确:除非明确要求,**不要升级 Vue3**;Vite 最佳实践仍偏向 Vue3
......@@ -325,7 +325,7 @@ flowchart TD
### C. `devtool: eval`
- [ ] 对比 `cheap-source-map` vs `eval`:冷启动时间、内存、控制台报错行号是否够用
- [ ] 确认 Sentry / 本地调试不依赖 dev source map
- [ ] 确认本地调试不依赖 dev source map
### D. serve 常驻规范(运维)
......
......@@ -2,8 +2,8 @@
## 问题页面
- [`src/views/orderManage/order.vue`](../src/views/orderManage/order.vue)(1.1 精品升级)
- [`src/views/orderManage/carDamage.vue`](../src/views/orderManage/carDamage.vue)(2.1 会员权益 / 2.3 延保,共用同一列表组件)
- [`src/views/orderManage/order.vue`](../../src/views/orderManage/order.vue)(1.1 精品升级)
- [`src/views/orderManage/carDamage.vue`](../../src/views/orderManage/carDamage.vue)(2.1 会员权益 / 2.3 延保,共用同一列表组件)
## 根因(按影响排序)
......
# 903 产品管理域
本文维护 903 域的业务语义;路由、组件、API、权限和测试关系由知识图谱自动扫描。描述以当前代码事实为边界,不补写后端未在前端表达的规则。
## 范围与入口
- 路由事实位于 [903_productManagement.js](../../../src/router/modules/903_productManagement.js),根权限为 `903`。
- 产品主数据入口为 `productManage`,由 [productManage/index.vue](../../../src/views/goods/productManage/index.vue) 承载。
- 传统上架入口为 `grounding`,列表、编辑、详情分别落在 [table/index.vue](../../../src/views/goods/grounding/views/table/index.vue)、[modify/index.vue](../../../src/views/goods/grounding/views/modify/index.vue)、[detail/index.vue](../../../src/views/goods/grounding/views/detail/index.vue)。
- 采购上架入口为 `purchaseOnShelves`,目录在 [purchaseOnShelves](../../../src/views/goods/purchaseOnShelves)。
- 新商品上架入口为 `GoodsShelf`,列表、常规上架、特殊上架、详情与编辑位于 [shelfProduct](../../../src/views/goods/shelfProduct)。
- 套餐、发券宝、服务项目分别由 `packageManage`、`coupons`、`servicesManage` 路由承载。
## 主要流程
### 商品上架
`grounding` 列表负责查询、审核、上下架、复制、导入导出和批量设置等入口;编辑页读取商品详情、场景与服务项目,并提交新增或更新;详情页复用只读展示。对应 API 集中在 [grounding.js](../../../src/api/grounding.js),可识别的 ROP 标识包括 `merchantGoodsInfo.page`、`merchantGoodsInfo.getById`、`merchantGoodsInfo.insertOrUpdate` 和批量状态操作。
`GoodsShelf` 是另一套上架链路,页面内 API 位于 [shelfProduct/api/index.js](../../../src/views/goods/shelfProduct/api/index.js)。该链路明确拆分基础信息、审批步骤、商品套餐,以及分账和对账规则配置;列表跳转到常规/特殊上架、查看和编辑路由。
### 采购与配置
采购上架围绕 `purchaseGoodsInfo` 的分页、详情、保存、审核、上下架、批量价格、导入导出展开。价格计算、门店关联和表单逻辑分别有独立工具/组件测试,修改采购成本或批量定价时需要同时检查这些关系。
套餐管理通过 `packageManage` 的列表、编辑和详情路由维护套餐。商品上架中的分账、对账、特殊品类规则属于共享配置能力,变更时可能波及库存、订单和营销中引用商品的页面。
## 权限与跨域风险
- 按钮权限和 `addRoutePath` 以路由模块为准;新增查看/编辑入口时必须同步权限 `authId`、父子关系和目标路由。
- `src/api/grounding.js`、商品分类、服务项目、门店与商户 API 被多条链路复用。静态图谱出现跨域邻接只表示“需要核对”,不能直接判定所有邻接文件都必须修改。
- `src/views/vehicleDamage` 同时被 904/911 使用;类似共享路径应由 affected 规则升级或人工确认,而不是写宽泛忽略。
## 测试落点
- 上架列表数据和销售模式:[index.data.spec.js](../../../src/views/goods/grounding/views/table/index.data.spec.js)、[saleMode.spec.js](../../../src/views/goods/grounding/utils/saleMode.spec.js)。
- 采购成本、批量价格、门店关联和表单:[purchaseCost.spec.js](../../../src/views/goods/purchaseOnShelves/utils/purchaseCost.spec.js)、[batchPrice.spec.js](../../../src/views/goods/purchaseOnShelves/utils/batchPrice.spec.js)、[relateStoreDialog.spec.js](../../../src/views/goods/purchaseOnShelves/components/relateStoreDialog.spec.js)、[groundingForm.spec.js](../../../src/views/goods/purchaseOnShelves/components/groundingForm.spec.js)。
- 特殊品类配置:[modify.spec.js](../../../src/views/goods/shelfProduct/components/reconciliationConfig/components/specialCategory/modify.spec.js)。
## 维护提示
新增商品路由或权限后运行 `npm run knowledge:build`;修改共享商品 API、公共组件或无法静态解析的跳转时,优先执行 `npm run test:affected -- --list --verbose` 检查是否升级全量测试。
# 904 订单管理域
本文记录 904 域当前前端可验证的流程。订单状态和审核规则若只存在于后端,不在本文推断。
## 范围与入口
- 路由与按钮权限位于 [904_orderManagement.js](../../../src/router/modules/904_orderManagement.js),根权限为 `904`。
- `orderList` 由 [orderList.vue](../../../src/views/orderManage/orderList.vue) 组合不同订单场景;主要列表实现和展示规则分布在 [order.vue](../../../src/views/orderManage/order.vue)、[carDamage.vue](../../../src/views/orderManage/carDamage.vue) 与 [utils](../../../src/views/orderManage/utils)。
- 详情入口为 `orderDetail`,页面是 [orderDetail.vue](../../../src/views/orderManage/orderDetail.vue)。
- 补录与交易号关联分别为 `orderSupplement`、`orderRelate`,页面是 [orderSupplement.vue](../../../src/views/orderManage/orderSupplement.vue) 与 [orderRelate.vue](../../../src/views/orderManage/orderRelate.vue)。
- 退款审核为 `refundExamine`;车损列表/详情/导入详情为 `vehicleDamageTabList`、`vehicleDamageDetail`、`vehicleDamageOderImportDetail`。
- 施工单列表与详情为 `constructionOrder`、`constructionOrderDetail`,目录在 [constructionOrder](../../../src/views/orderManage/constructionOrder)。
## 主要流程
### 列表、详情与补录
订单列表按场景选择对应列表组件,并承担查看详情、补录、导入导出、退款/分账等按钮入口。路由参数转换、导航和展示逻辑已经拆出单测,修改查询条件或路由 query 时应同步这些测试。
订单详情通过订单 API 获取主单/子单、车辆资料和上传记录,并提供开票标记、退款拦截等当前页面已声明的操作。补录链路包含单笔补录和交易号/订单号批量关联;权限中的 `addRoutePath` 决定从列表进入这些隐藏路由。
### 退款、车损与施工单
退款审核页面及其弹窗使用 `refundExamine`、订单和文件上传 API,覆盖审核、驳回、结算与退款资料更新入口。车损页面位于共享的 [vehicleDamage](../../../src/views/vehicleDamage) 目录,同时被 904 与 911 路由引用,属于明确跨域风险点。
施工单由列表进入详情,详情读取时间节点等施工信息。修改订单到施工单的跳转、标识或权限时,需要同时核对 904 路由中的 `constructionOrder`/`constructionOrderDetail`。
## 权限与影响边界
- 导出、补录、详情、退款、核销、分账等按钮权限均以 `authId` 和 `handle` 建模;同名 handle 可能服务不同订单场景,不能仅按方法名判断必改范围。
- 订单页共享商品、商户、门店、文件和财务 API。图谱中的跨域结果应列为“可能波及”,由具体需求确认。
- `src/views/vehicleDamage` 的任何运行时代码变更会按共享基础/多域证据提高测试范围。
## 测试落点
- 路由与导航:[orderListRouteGuard.spec.js](../../../tests/unit/views/orderManage/orderListRouteGuard.spec.js)、[orderListRouteParams.spec.js](../../../tests/unit/views/orderManage/orderListRouteParams.spec.js)、[orderListNavigation.spec.js](../../../tests/unit/views/orderManage/orderListNavigation.spec.js)。
- 列表展示与筛选:[orderListRowDisplay.spec.js](../../../tests/unit/views/orderManage/orderListRowDisplay.spec.js)、[orderLowPriceFilterParam.spec.js](../../../tests/unit/views/orderManage/orderLowPriceFilterParam.spec.js)、[carDamageListRowDisplay.spec.js](../../../tests/unit/views/orderManage/carDamageListRowDisplay.spec.js)。
- 权限与性能观察:[orderApprovalButtonVisibility.spec.js](../../../tests/unit/views/orderManage/orderApprovalButtonVisibility.spec.js)、[orderListPerfMetrics.spec.js](../../../tests/unit/views/orderManage/orderListPerfMetrics.spec.js)、[carDamagePerfMetrics.spec.js](../../../tests/unit/views/orderManage/carDamagePerfMetrics.spec.js)。
- 审核弹窗和行展示工具:[approvalDialog.spec.js](../../../src/views/orderManage/components/approvalDialog.spec.js)、[orderListRowDisplay.spec.js](../../../src/views/orderManage/utils/orderListRowDisplay.spec.js)。
## 维护提示
新增订单场景时同时维护路由、权限、场景映射、页面组件和对应测试。修改 API method、隐藏详情路由或共享车损目录后,重新构建图谱并查看 affected 计划。
# 912 驻店管理域
912 路由根标题目前为“人员管理”,但代码覆盖驻店人员、任务、日报、绩效和多类管理流程。本文使用“驻店管理域”统称,具体页面标题以路由事实为准。
## 范围与入口
- 路由和权限位于 [912_residentManage.js](../../../src/router/modules/912_residentManage.js),根权限为 `912`。
- 驻店人员和资料入口包括 `inStoreManage`、`staffInfo`;任务中心为 `residentManageTaskCenter` 与详情路由。
- 日报/工作汇报入口为 `journalRecord`,列表和详情分别是 [journalRecord/index.vue](../../../src/views/residentManage/journalRecord/index.vue) 与 [journalRecord/detail.vue](../../../src/views/residentManage/journalRecord/detail.vue)。
- 绩效相关入口包括 `salaryPerformance`、`performanceScheme`、`configurationPerformance`、`configureCommissionPlan` 和 `configureStoreCommissionPlan`。
- 日报管理、驻店目标、积分、成长等级、晋升降级、督导和招聘等入口也属于 912,但没有在本文补写源码之外的审批规则。
## 主要流程
### 任务中心
任务中心列表、分类、详情和计数 API 位于 [taskCenter/api/index.js](../../../src/views/residentManage/taskCenter/api/index.js),对应结构化 method 为 `dj.api.taskcenter.task.page`、`dj.api.taskcenter.bizcategory.list`、`dj.api.taskcenter.task.detail` 和 `dj.api.taskcenter.task.count`。列表进入详情路由,表格与详情数据转换有独立测试。
### 门店工作汇报/日报
列表按汇报类型组织查询条件,调用 [journalRecord.js](../../../src/api/journalRecord.js) 的门店、人员、汇报分页和详情函数。API 层在请求前构造参数、在响应后调用 adapter;契约快照位于 [journalRecord/__contracts__](../../../src/api/adapters/journalRecord/__contracts__)。
当前可识别的 ROP 契约包括:
- `dj.api.smartcarlife.dailyReport.overview.page`
- `dj.api.smartcarlife.dailyReport.detail.select`
- `dj.api.smartcarlife.dailyReport.merchant.list`
- `dj.api.smartcarlife.merchant.staff.list`
详情页通过 [mapDetailResponse.js](../../../src/api/adapters/journalRecord/mapDetailResponse.js) 和 [journalFormEcho](../../../src/views/residentManage/journalRecord/utils/journalFormEcho.js) 解析回显;字段可见性位于 [journalFormVisibility](../../../src/views/residentManage/journalRecord/utils/journalFormVisibility),包含场景、品牌、考勤、分组规则和子表单处理。该逻辑是日报展示的高风险区域。
### 人员与绩效
驻店人员、工资绩效、绩效方案、提成方案和目标配置由不同路由/目录承载。修改人员标识、门店上下文或绩效配置的共享 API 时,应查询 912 全域,而不是只检查当前页面。
## 测试落点
- 日报页面与详情:[index.spec.js](../../../tests/unit/views/residentManage/journalRecord/index.spec.js)、[detail.spec.js](../../../tests/unit/views/residentManage/journalRecord/detail.spec.js)。
- 表单回显和可见性:[journalFormEcho.spec.js](../../../tests/unit/views/residentManage/journalRecord/journalFormEcho.spec.js)、[journalFormVisibility.spec.js](../../../tests/unit/views/residentManage/journalRecord/journalFormVisibility.spec.js)、[groupShowRuleEval.spec.js](../../../tests/unit/views/residentManage/journalRecord/groupShowRuleEval.spec.js)。
- adapter:[mapOverviewRow.spec.js](../../../tests/unit/api/adapters/journalRecord/mapOverviewRow.spec.js)、[mapDetailResponse.spec.js](../../../tests/unit/api/adapters/journalRecord/mapDetailResponse.spec.js)、[mapSceneType.spec.js](../../../tests/unit/api/adapters/journalRecord/mapSceneType.spec.js)。
- ROP 集成契约:[journalRecord.api.spec.js](../../../tests/integration/journalRecord.api.spec.js)。该测试默认不应在本计划中触发真实业务写操作。
- 任务中心:[taskCenter.integration.spec.js](../../../src/views/residentManage/taskCenter/taskCenter.integration.spec.js)、[api/index.spec.js](../../../src/views/residentManage/taskCenter/api/index.spec.js)。
## 维护提示
ROP method 或契约变更先遵循 ROP 导入规程,再运行 `npm run rop:verify` 和知识图谱检查。动态详情跳转会进入 unresolved;其文件发生变更时 affected 测试按安全规则升级全量,除非代码改为可静态解析。
# 922 营销管理域
本文聚焦营销活动和营销推送策略,尤其是条件分支、消息配置、执行记录和页面配置的组件链。
## 范围与入口
- 路由与权限位于 [922_marketingManagement.js](../../../src/router/modules/922_marketingManagement.js),根权限为 `922`。
- 营销活动列表、新增、查看分别为 `marketingActivity`、`addMarketingActivity`、`viewMarketingActivity`。
- 推送策略列表为 `marketingPushStrategy`,页面是 [views/table/index.vue](../../../src/views/marketingManagement/marketingPushStrategy/views/table/index.vue)。
- 策略新增/修改共用 `marketingPushStrategyModify` 路由和 [views/modify/index.vue](../../../src/views/marketingManagement/marketingPushStrategy/views/modify/index.vue);路由标题当前为“新增策略”,编辑语义由页面参数和数据决定。
## 策略组件链
修改页组织基础表单、条件和动作配置。条件链由 `conditionContainer`、`conditionGroup`、`conditionItem` 及条件面板组件组成;分支链由 `branchGroup`、`branchItem` 和 `actionsItem` 组成。默认条件、分支和动作由 [constant/index.js](../../../src/views/marketingManagement/marketingPushStrategy/constant/index.js) 提供。
消息配置由 `messageType`、`variableTextarea` 等组件承载;门店选择由 `selectStoreDialog` 调用商户 API。页面配置集中在 [pageConfig/index.vue](../../../src/views/marketingManagement/marketingPushStrategy/components/pageConfig/index.vue),改变页面字段或消息变量时应同时检查条件/动作序列化和回显。
## API 与记录
策略 API 位于 [api/index.js](../../../src/views/marketingManagement/marketingPushStrategy/api/index.js),静态 method 包括:
- `dj.api.smartcarlife.sop.strategy.list/query/create/update`
- `dj.api.smartcarlife.sop.strategy.status/delete/confirm`
- `dj.api.smartcarlife.sop.strategy.records/record.detail/meta`
列表页提供状态、删除、确认和执行记录入口;`recordDialog` 展示记录列表,`recordDetailDialog` 通过 [detailFormat.js](../../../src/views/marketingManagement/marketingPushStrategy/components/recordDetailDialog/detailFormat.js) 组织基础、客户、触发和分支信息。API 只记录结构化 method,图谱不会保存请求参数值。
## 测试落点
- 主流程集成:[marketingPushStrategy.integration.spec.js](../../../src/views/marketingManagement/marketingPushStrategy/marketingPushStrategy.integration.spec.js)、[marketingPushStrategy.webpage.integration.spec.js](../../../src/views/marketingManagement/marketingPushStrategy/marketingPushStrategy.webpage.integration.spec.js)。
- 组件链集成与执行记录:[marketingPushStrategy.components.integration.spec.js](../../../src/views/marketingManagement/marketingPushStrategy/marketingPushStrategy.components.integration.spec.js)、[marketingPushStrategy.record.integration.spec.js](../../../src/views/marketingManagement/marketingPushStrategy/marketingPushStrategy.record.integration.spec.js)。
- API:[api/index.spec.js](../../../src/views/marketingManagement/marketingPushStrategy/api/index.spec.js)。
- 条件、分支、动作、消息和页面配置在各组件目录内均有 `index.spec.js`;修改默认结构时还需运行 [constant/index.spec.js](../../../src/views/marketingManagement/marketingPushStrategy/constant/index.spec.js) 和 [modify.data.spec.js](../../../src/views/marketingManagement/marketingPushStrategy/views/modify/modify.data.spec.js)。
## 权限与跨域风险
新增和修改按钮通过 `addRoutePath` 指向同一修改页。策略元数据、门店和商品引用会连接商户/商品等其他业务域;这些关系属于“可能波及”,需要根据需求确认是否修改。若条件表达式或动态组件无法静态解析,应记录 unresolved,不得添加宽泛 known gap。
## 维护提示
新增条件类型、动作类型或消息类型时,至少同步默认结构、编辑回显、序列化/API、对应组件测试和本文。完成后查询 `marketingPushStrategy` 并检查列表、修改页、组件链、API 与集成测试是否同时出现。
This diff could not be displayed because it is too large.
{
"schemaVersion": 1,
"domains": [
{
"id": "902",
"title": "流量管理",
"aliases": [ "flowManage", "customerList" ],
"routeModule": "src/router/modules/902_trafficManagement.js",
"entrypoints": [ "src/views/customer" ],
"riskKeywords": [ "客户", "画像", "群关联" ]
},
{
"id": "903",
"title": "产品管理",
"aliases": [ "goods", "productManage", "商品库" ],
"routeModule": "src/router/modules/903_productManagement.js",
"entrypoints": [ "src/views/goods" ],
"roots": [ "src/api/grounding.js" ],
"documents": [ ".ai/docs/knowledge/903-product-management.md" ],
"riskKeywords": [ "上架", "采购", "配置", "共享商品" ]
},
{
"id": "904",
"title": "订单管理",
"aliases": [ "orderManage", "orderList" ],
"routeModule": "src/router/modules/904_orderManagement.js",
"entrypoints": [ "src/views/orderManage", "src/views/vehicleDamage" ],
"roots": [ "tests/unit/views/orderManage" ],
"documents": [ ".ai/docs/knowledge/904-order-management.md" ],
"riskKeywords": [ "订单", "补录", "退款", "车损", "施工单" ]
},
{
"id": "905",
"title": "财务管理",
"aliases": [ "financeManage" ],
"routeModule": "src/router/modules/905_financialManagement.js",
"entrypoints": [ "src/views/financeManage" ],
"riskKeywords": [ "财务", "对账", "结算" ]
},
{
"id": "906",
"title": "系统设置",
"aliases": [ "systemConfig" ],
"routeModule": "src/router/modules/906_systemSettings.js",
"entrypoints": [ "src/views/system", "src/views/systemConfig" ],
"riskKeywords": [ "系统", "门店", "组织" ]
},
{
"id": "907",
"title": "总览",
"aliases": [ "index", "home" ],
"routeModule": "src/router/modules/907_home.js",
"entrypoints": [ "src/views/index" ],
"riskKeywords": [ "总览", "首页" ]
},
{
"id": "908",
"title": "库存管理",
"aliases": [ "stockManage" ],
"routeModule": "src/router/modules/908_stockManagement.js",
"entrypoints": [ "src/views/stockManage" ],
"riskKeywords": [ "库存", "入库", "出库", "盘点" ]
},
{
"id": "909",
"title": "采购管理",
"aliases": [ "purchaseManage", "purchase" ],
"routeModule": "src/router/modules/909_purchase.js",
"entrypoints": [ "src/views/purchase" ],
"riskKeywords": [ "采购", "审核", "发货" ]
},
{
"id": "910",
"title": "权益配置",
"aliases": [ "rightsAndInterestsManage" ],
"routeModule": "src/router/modules/910_rightsAndInterestsManage.js",
"entrypoints": [ "src/views/rightsAndInterestsManage" ],
"riskKeywords": [ "权益", "规则" ]
},
{
"id": "911",
"title": "车损管理",
"aliases": [ "vehicleDamage" ],
"routeModule": "src/router/modules/911_vehicleDamage.js",
"entrypoints": [ "src/views/vehicleDamage" ],
"riskKeywords": [ "车损", "报价单" ]
},
{
"id": "912",
"title": "驻店管理",
"aliases": [ "residentManage", "journalRecord", "人员管理" ],
"routeModule": "src/router/modules/912_residentManage.js",
"entrypoints": [ "src/views/residentManage" ],
"roots": [ "src/api/journalRecord.js", "src/api/adapters/journalRecord", "tests/unit/views/residentManage", "tests/unit/api/adapters/journalRecord", "tests/integration/journalRecord.api.spec.js" ],
"documents": [ ".ai/docs/knowledge/912-resident-management.md" ],
"riskKeywords": [ "驻店", "任务", "日报", "人员", "绩效" ]
},
{
"id": "913",
"title": "内容管理",
"aliases": [ "contentManager" ],
"routeModule": "src/router/modules/913_contentManager.js",
"entrypoints": [ "src/views/contentManager" ],
"riskKeywords": [ "内容", "群发", "客户文件" ]
},
{
"id": "914",
"title": "积分管理",
"aliases": [ "pointManagement" ],
"routeModule": "src/router/modules/914_pointManagement.js",
"entrypoints": [ "src/views/pointManagement" ],
"riskKeywords": [ "积分" ]
},
{
"id": "915",
"title": "预警管理",
"aliases": [ "earlyWarningManager" ],
"routeModule": "src/router/modules/915_earlyWarningManager.js",
"entrypoints": [ "src/views/earlyWarningManager" ],
"riskKeywords": [ "预警", "策略" ]
},
{
"id": "916",
"title": "AI 大模型",
"aliases": [ "largeModel" ],
"routeModule": "src/router/modules/916_largeModel.js",
"entrypoints": [ "src/views/largeModel" ],
"riskKeywords": [ "大模型", "AI" ]
},
{
"id": "917",
"title": "发票管理",
"aliases": [ "invoiceManage" ],
"routeModule": "src/router/modules/917_invoiceManager.js",
"entrypoints": [ "src/views/invoiceManage" ],
"riskKeywords": [ "发票", "红冲" ]
},
{
"id": "918",
"title": "话术库",
"aliases": [ "verbalTrickManage" ],
"routeModule": "src/router/modules/918_verbalTrickManage.js",
"entrypoints": [ "src/views/verbalTrickManage" ],
"riskKeywords": [ "话术" ]
},
{
"id": "919",
"title": "学习中心",
"aliases": [ "serviceCentre" ],
"routeModule": "src/router/modules/919_serviceCentre.js",
"entrypoints": [ "src/views/serviceCentre" ],
"riskKeywords": [ "学习", "服务中心" ]
},
{
"id": "920",
"title": "二手车管理",
"aliases": [ "usedCarManagement" ],
"routeModule": "src/router/modules/920_usedCarManagement.js",
"entrypoints": [ "src/views/usedCarManagement" ],
"riskKeywords": [ "二手车" ]
},
{
"id": "921",
"title": "销售管理",
"aliases": [ "salesManagement" ],
"routeModule": "src/router/modules/921_salesManagement.js",
"entrypoints": [ "src/views/salesManagement" ],
"riskKeywords": [ "销售" ]
},
{
"id": "922",
"title": "营销管理",
"aliases": [ "marketingManagement", "marketingPushStrategy" ],
"routeModule": "src/router/modules/922_marketingManagement.js",
"entrypoints": [ "src/views/marketingManagement" ],
"documents": [ ".ai/docs/knowledge/922-marketing-management.md" ],
"riskKeywords": [ "营销", "策略", "条件分支", "消息", "执行记录", "页面配置" ]
},
{
"id": "923",
"title": "标签管理",
"aliases": [ "tagManagement", "tagManagementGroup" ],
"routeModule": "src/router/modules/923_tagManagement.js",
"entrypoints": [ "src/views/tagCustomerManagement" ],
"riskKeywords": [ "标签", "枚举" ]
}
]
}
{
"schemaVersion": 1,
"gaps": [
{
"kind": "document-link",
"path": ".ai/docs/DEV_PERF_AND_THEME_RESEARCH.md",
"line": 367,
"column": 0,
"reason": "missing-target",
"note": "预研文档引用尚未实施的候选样式文件"
},
{
"kind": "dynamic-route",
"path": "src/store/modules/d2admin/modules/auth.js",
"line": 159,
"column": 10,
"reason": "runtime-registration",
"note": "权限初始化按后端资源运行时注册 frameInRoutes"
},
{
"kind": "route",
"path": "src/layout/header-aside/components/header-log/index.vue",
"line": 48,
"column": 6,
"reason": "missing-target",
"note": "log 路由不在 22 个静态业务模块中"
},
{
"kind": "route",
"path": "src/layout/header-aside/components/tabs/index.vue",
"line": 167,
"column": 8,
"reason": "dynamic-expression",
"note": "标签页按运行时 page 对象恢复路由"
},
{
"kind": "route",
"path": "src/views/account/myAccount.vue",
"line": 269,
"column": 6,
"reason": "missing-target",
"note": "myAccountRecord 由运行时权限资源提供"
},
{
"kind": "route",
"path": "src/views/contentManager/staffMassSending/index.vue",
"line": 331,
"column": 6,
"reason": "dynamic-expression",
"note": "统计目标由 contentType 条件选择"
},
{
"kind": "route",
"path": "src/views/purchase/batchReview.vue",
"line": 171,
"column": 6,
"reason": "dynamic-expression",
"note": "返回目标由来源页运行时决定"
},
{
"kind": "route",
"path": "src/views/purchase/singleReview.vue",
"line": 408,
"column": 3,
"reason": "dynamic-expression",
"note": "返回目标由来源页运行时决定"
},
{
"kind": "route",
"path": "src/views/salesManagement/availableInStores/index.vue",
"line": 383,
"column": 6,
"reason": "dynamic-expression",
"note": "销售页面按业务数据选择目标路由"
},
{
"kind": "route",
"path": "src/views/system/login/index.vue",
"line": 279,
"column": 8,
"reason": "dynamic-expression",
"note": "登录后恢复 redirect 或缓存路由"
},
{
"kind": "route",
"path": "src/views/system/login/index.vue",
"line": 325,
"column": 8,
"reason": "dynamic-expression",
"note": "另一登录分支恢复 redirect 或缓存路由"
},
{
"kind": "route",
"path": "src/views/systemConfig/businessSchoolManage/mentorConfig.vue",
"line": 269,
"column": 6,
"reason": "missing-target",
"note": "staffManage 由运行时权限资源提供"
},
{
"kind": "route",
"path": "src/views/systemConfig/businessSchoolManage/performanceConfig.vue",
"line": 468,
"column": 6,
"reason": "missing-target",
"note": "staffManage 由运行时权限资源提供"
},
{
"kind": "route",
"path": "src/views/systemConfig/businessSchoolManage/staffList.vue",
"line": 445,
"column": 6,
"reason": "missing-target",
"note": "performanceConfig 目标未在静态业务路由表中声明"
},
{
"kind": "route",
"path": "src/views/systemConfig/businessSchoolManage/staffList.vue",
"line": 471,
"column": 6,
"reason": "missing-target",
"note": "mentorConfig 目标未在静态业务路由表中声明"
}
]
}
---
name: requirement-impact-analysis
description: Use when analyzing a requirement, estimating change scope, reviewing an implementation plan, or deciding affected Vue2 files and tests in dj-car-life-system. Queries the generated knowledge graph before conclusions and separates required changes, possible ripple effects, and explicitly excluded areas.
---
# Requirement Impact Analysis
## Workflow
1. Confirm `.ai/generated/knowledge-graph.json` exists. Run `npm run knowledge:check`; if it reports drift, state that the graph is stale and run `npm run knowledge:build` only when updating generated artifacts is in scope.
2. Extract stable requirement identifiers: route name/path, permission `authId`/handle, view/component, API function or ROP method, Vuex key, event, and business wording.
3. Query every useful identifier together:
```bash
npm run impact -- --keyword <value> --keyword <value> --depth 2 --direction both --format markdown
```
4. Read evidence paths/locations and the relevant source. For 903/904/912/922, also read the matching file under `.ai/docs/knowledge/`.
5. Classify findings:
- **必改**: directly required by the request and confirmed by source/evidence.
- **可能波及**: graph neighbors, shared APIs/components, navigation, permissions, events, Vuex, tests, or documents needing verification.
- **明确不改**: examined areas that are outside the requested behavior, with a short reason.
6. Report unresolved and cross-domain risks separately. A static edge is evidence to inspect, never proof that both endpoints must change.
7. Before implementation, preview tests with `npm run test:affected -- --list --verbose`. If the planner upgrades to full, preserve that safety decision unless the underlying unresolved relation is made statically resolvable.
## Output contract
Always provide these headings in Chinese:
```markdown
## 必改
## 可能波及
## 明确不改
## 测试建议
## 未解析与风险
```
For each non-empty item, cite a file/route/API/Vuex/event identifier and explain why it belongs in that category. Say “未找到静态证据” instead of guessing when a query has no match.
## Guardrails
- Do not copy request values, credentials, tokens, environment values, or ordinary URLs into graph/manual knowledge.
- Do not hide new unresolved items with path globs or broad patterns; known gaps require exact `kind/path/line/column/reason` matches.
- Do not recommend Vue3, Pinia, Composition API, Vite, or runtime refactors for this Vue2 impact-analysis workflow.
- Do not treat generated Markdown as business truth; automatic output is code fact, while `.ai/docs/knowledge/` carries reviewed semantics.
workflow:
rules:
- if: '$CI_PIPELINE_SOURCE == "merge_request_event"'
- if: '$CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH'
- when: never
stages:
- verify
default:
stage: verify
before_script:
- node -e "const [major,minor]=process.versions.node.split('.').map(Number); if(major!==20||minor<19){throw new Error('Node 20.19+ and <21 is required')}"
- node -e "const {execFileSync}=require('node:child_process'); const [major,minor]=execFileSync(process.platform==='win32'?'npm.cmd':'npm',['--version'],{encoding:'utf8'}).trim().split('.').map(Number); if(major!==10||minor<8){throw new Error('npm 10.8+ and <11 is required')}"
- npm ci --legacy-peer-deps
knowledge_graph_check:
rules:
- if: '$CI_PIPELINE_SOURCE == "merge_request_event"'
script:
- npm run knowledge:test
- npm run knowledge:check
allow_failure: false
affected_tests:
rules:
- if: '$CI_PIPELINE_SOURCE == "merge_request_event"'
script:
- npm run test:affected -- --format json
full_unit_tests:
rules:
- if: '$CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH'
script:
- npm run test:unit -- --ci
auth.token=45d2be625091494b9a0de35af25bb273c0a471650575471096d60dd61f6995e6
defaults.url = http://sentry.glsx.com.cn
defaults.org = sentry
defaults.project =dj-carlife-web
......@@ -8,6 +8,7 @@
- /.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
- 需求影响分析:/.ai/skills/requirement-impact-analysis/SKILL.md、/.ai/generated/knowledge-graph.json
## 项目概述
......@@ -84,6 +85,10 @@ src/
## 编码原则
### 需求影响分析
分析需求、评估改动范围或制定实施计划时,先按 `.ai/skills/requirement-impact-analysis/SKILL.md` 查询知识图谱,再结合源码输出“必改、可能波及、明确不改”。静态邻接只表示需要核对,不得直接判定为必改。发现图谱漂移或未解析关系时必须显式说明。
### 优先遵循现有代码风格
修改代码时:
......@@ -181,3 +186,12 @@ export default {};
然后再补充可选优化建议。
不要把优化建议当成必须任务。
<!-- rop-api-contract-gate:start -->
## API 契约门禁
- 导入、对接或修改 ROP API 及其请求/响应参数前,先读取 `docs/reference/api/swagger-sources.json` 并同步 `develop` Swagger。
- 在线 Swagger 有定义时以最新契约为准;在线同步成功但未收录接口时,可按用户提供的完整契约实现并明确提示“Swagger 尚未收录”。
- 用户定义与 Swagger 冲突,或参数修改未出现在最新 Swagger 中时,必须先展示差异并取得确认。
- 任一候选网关未验证时不得写代码;仅可离线读取快照时,必须先展示同步时间并确认时效。
<!-- rop-api-contract-gate:end -->
# 嘀加智享车生活后台 http://192.168.3.233:8090/saas_plus/dj-car-life-system
## node 版本
14.21.3
20.19.0
## 包管理工具
npm 6.14.8
npm 10.8.2
## AI 相关
* 项目忽略所有AI相关文件. 不要提交如 CLAUDE.md 等文件.
......@@ -33,3 +33,179 @@
测试环境账号 15816539335 a123456(超管)
aa123456 aa123456 (园区店)
bb123456 bb123456 (服务商)
# 项目搭建、知识图谱与维护指南
本章是当前 Vue 2 / D2Admin 项目的统一搭建和维护入口。知识图谱只分析仓库源码,不会访问真实业务环境,也不会保存请求参数值、账号、密码、Token、环境变量或普通 URL。
## 1. 环境与首次安装
项目固定使用 Node `20.19.0`、npm `10.8.2`,版本也声明在 `package.json` 的 `volta` 字段中。Vue、Vue CLI、Webpack、Jest 保持现有版本。
安装 Volta 后进入仓库,Volta 会自动选择固定版本;也可以手工确认:
```bash
node --version
npm --version
```
首次安装依赖:
```bash
npm ci --legacy-peer-deps
```
`--legacy-peer-deps` 用于兼容仓库现有 `sass-loader@7` 与 Webpack 5 的历史 peer 声明,不代表升级或替换构建栈。`package-lock.json` 保持 lockfile v3。
常用启动和构建命令:
```bash
npm run dev
npm run build
npm run test:unit
```
## 2. 知识库结构与首次构建
知识库采用“代码事实自动生成、业务语义人工维护”的分层方式:
- `.ai/knowledge/domain-catalog.json`:22 个路由业务域、别名、入口和风险关键词。
- `.ai/knowledge/known-gaps.json`:按 `kind/path/line/column/reason` 精确登记的已知盲区。
- `.ai/docs/knowledge/`:人工维护的业务语义;当前深度覆盖 903、904、912、922。
- `.ai/generated/knowledge-graph.json`:机器查询图谱,顶层固定为 `schemaVersion/nodes/edges/unresolved/stats`。
- `.ai/generated/domain-index.md`:22 个域的入口、路由、视图/组件、API/ROP、Vuex、测试和文档缺口索引。
- `scripts/knowledge-graph/`:扫描、查询、增量测试规划和 fixture 测试。
首次构建:
```bash
npm run knowledge:test
npm run knowledge:build
npm run knowledge:check
```
`knowledge:build` 的输出固定排序,不包含时间戳或 Git SHA;相同源码连续构建应字节一致。生成的 JSON/Markdown 需要和代码一起提交。
## 3. 查询需求影响
需求分析必须先查图谱,再结合源码判断。项目规程见 [requirement-impact-analysis](.ai/skills/requirement-impact-analysis/SKILL.md)。
```bash
npm run impact -- --keyword orderList --depth 2 --direction both --format markdown
npm run impact -- --keyword journalRecord --keyword dailyReport.overview.page --depth 3 --format json
npm run impact -- --keyword marketingPushStrategy --depth 3 --format markdown
npm run impact -- --keyword d2admin/auth/init --depth 4 --format markdown
```
查询固定返回 `seeds`、`directMatches`、`upstreamConsumers`、`downstreamDependencies`、`crossDomainRisks`、`testCandidates`、`documents`、`unresolved` 和 `evidence`。输出应进一步分为:
- 必改:需求直接要求且已由源码/证据确认。
- 可能波及:共享组件、API、事件、Vuex、权限、导航、测试或文档,需要人工核对。
- 明确不改:已经检查、但与本次行为无关的范围。
静态邻接只是核对线索,不能直接判定相邻文件都必须修改。没有命中时应说明“未找到静态证据”,不要猜测业务规则。
## 4. 修改后的 affected 与全量测试
本地预览测试计划,不执行测试:
```bash
npm run test:affected -- --list --verbose
```
执行当前工作区相对 `HEAD` 的 affected 测试:
```bash
npm run test:affected
```
指定 Git 范围:
```bash
npm run test:affected -- --base origin/master --head HEAD --list --format json
```
强制全量或直接运行原有安全兜底:
```bash
npm run test:affected -- --full
npm run test:unit -- --ci
```
选测会合并两类证据:Jest `--findRelatedTests` 提供标准 import 依赖,图谱补充路由、权限、事件、Vuex、API/ROP 和文档关系;最终通过 `--runTestsByPath` 精确执行候选测试。规划阶段读取已生成图谱,只对新增/修改文件做内存 overlay。
以下情况自动升级全量测试:
- 删除或重命名运行时代码。
- 修改 package/lock、Vue/Jest/Babel 配置、入口、请求封装、路由基础设施、全局 store 或公共 `libs/components/common/plugin`。
- 影响 3 个及以上业务域。
- 变更文件存在未解析关系、无法归域,或运行时代码没有任何候选测试。
纯知识文档/知识配置改动只运行知识单测和漂移检查;只改测试文件时直接执行这些测试。
## 5. 新增功能时如何维护
### 新增路由或业务域
1. 按现有方式在 `src/router/modules/` 维护路由、`authId`、`parentId`、按钮权限和 `addRoutePath`。
2. 新业务域在 `.ai/knowledge/domain-catalog.json` 增加精确的 route module、入口、别名和风险关键词;不要用覆盖整个 `src` 的宽泛 roots。
3. 运行 `npm run knowledge:build`,确认生成索引中路由、入口和文档缺口正确。
### 新增 API 或 ROP method
1. 继续复用项目 request 封装,method 使用可静态解析的字符串/常量。
2. ROP 适配和契约遵循 [ROP_CHAT_IMPORT.md](.ai/docs/ROP_CHAT_IMPORT.md),契约放在对应 adapter 的 `__contracts__`。
3. 添加 API/adapter 测试,运行 `npm run rop:verify`(适用时)和知识图谱检查。
### 新增 Vuex、组件事件或测试
1. Vuex 保持现有 module/state/getter/action/mutation 命名空间写法,尽量避免计算出的 store key。
2. 组件 props、`$emit`、模板监听和组件注册使用静态名称,便于扫描。
3. 测试通过 import/require/jest.mock 指向真实文件,并用 `mount`/`shallowMount` 保留覆盖证据。
4. 修改后先预览 affected 计划,再执行选测或全量测试。
### 维护人工文档与 known gaps
903/904/912/922 的流程变化必须同步 `.ai/docs/knowledge/`。其他域先依赖自动索引,只有经过源码/业务确认后再补深度语义,不臆造规则。
动态路由、动态 store key、计算出的 API method 等无法可靠判断时会进入 `unresolved`。只有确认是长期、可解释盲区时,才在 `.ai/knowledge/known-gaps.json` 按完整位置精确登记;禁止使用目录通配或只按 kind 忽略。代码行变化后旧登记应失配,促使重新审核。
## 6. GitLab 门禁
`.gitlab-ci.yml` 只创建 Merge Request 和默认分支流水线,不绑定 Runner 镜像。所有作业先校验 Node 20.19+/npm 10.8+(限制在对应主版本),再使用 `npm ci --legacy-peer-deps`。
- Merge Request:`affected_tests` 阻断执行 affected 测试;`knowledge_graph_check` 阻断执行知识单测和漂移检查。
- 默认分支 `master`:`full_unit_tests` 阻断执行 `npm run test:unit -- --ci`。
- MR 变更范围由 CLI 读取 `CI_MERGE_REQUEST_DIFF_BASE_SHA` 和 `CI_COMMIT_SHA`。
日常提交 Merge Request 前按顺序执行:
```bash
npm run knowledge:test
npm run knowledge:build
npm run knowledge:check
npm run test:affected -- --list --verbose
```
`knowledge:build` 产生差异时,将 `.ai/generated/` 与代码一起提交。图谱测试、生成物漂移或未登记的 unresolved 任一失败,都会阻断 Merge Request。
## 7. 常见失败与排查
- `Generated artifacts drifted`:运行 `npm run knowledge:build`,检查并提交 `.ai/generated/` 差异。
- `Unregistered unresolved relationships`:查看 JSON 的 `unresolved`;优先把代码改成静态可解析,确为长期盲区才精确登记。
- `runtime-change-without-tests`:新增/补齐测试 import,或确认属于需要全量回归的运行时代码。
- `unresolved-change` / `cross-domain-change`:查看 `--verbose --format json` 的文件、域和证据,保留全量测试或消除根因。
- `global-infrastructure`:这是安全升级,公共组件、请求层、路由/全局 store 和构建配置默认跑全量。
- `npm ci` peer 冲突:确认使用 Node/npm 固定版本和 `--legacy-peer-deps`,不要通过升级 Vue/Webpack/Sass 栈绕过。
- 查询没有预期页面/API/测试:先运行 `npm run knowledge:check`;再检查别名、静态 import、路由 `_import()`、API method 和测试引用是否可解析。
维护知识配置或排查门禁后,仍可使用同一组命令复验:
```bash
npm run knowledge:test
npm run knowledge:build
npm run knowledge:check
npm run test:affected -- --list --verbose
```
高风险或共享基础设施改动继续执行完整 `npm run test:unit -- --ci`。
{
"schemaVersion": 1,
"configCenter": {
"endpoint": "https://config-center-backend.glsx.com.cn/glsxAdmin/config",
"moduleUrl": "dj-car-life-system-config",
"defaultEnv": "develop"
},
"sources": [
{
"id": "rop-dj-smartcarlife",
"configKey": "axios",
"env": "develop",
"swaggerPath": "/swagger-rop/api-docs",
"snapshot": "src/libs/rop/__snapshots__/smartcarlife.swagger.json",
"sha256": "5324f2c256ac54fadecd80e69111ebc407eb74e0535168973441680019e19ac7",
"syncedAt": "2026-08-21T09:21:56.374Z",
"methodCount": 1633
}
]
}
# Journal Store Daily Only Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** Make `/journalRecord` store-daily-only, block retired report detail links before API access, and render the latest V2.3.0 `F2-101`–`F2-107` detail content correctly.
**Architecture:** Centralize allowed report-type decisions in a small pure helper used by list and detail pages. Keep `jsonContent` as the primary echo source, extend the current readonly normalizer for App object values, and replace the limited child-rule evaluator with the safe parser pattern already proven in the Mini Program.
**Tech Stack:** Vue 2 Options API, Vue Router 3, Element UI, Babel/Jest, JavaScript pure utilities.
## Global Constraints
- Only `storeDaily` / `templateType: 2` remains available.
- Retired or invalid detail types must not call `dailyReport.detail.select`.
- Do not use `eval` or `new Function` for `childrenShowRules`.
- Preserve the current API wrapper and readonly component structure; do not migrate the Mini Program form engine.
- Follow `.ai/rules/ESLINT.md`: double quotes, semicolons, tabs in scripts, and touched-file lint checks.
---
### Task 1: Restrict list and detail access to store daily
**Files:**
- Create: `src/views/residentManage/journalRecord/utils/journalAccess.js`
- Create: `src/views/residentManage/journalRecord/utils/journalAccess.spec.js`
- Modify: `src/views/residentManage/journalRecord/constants.js`
- Create: `src/views/residentManage/journalRecord/constants.spec.js`
- Modify: `src/views/residentManage/journalRecord/index.vue`
- Modify: `src/views/residentManage/journalRecord/detail.vue`
- Modify: `src/api/adapters/journalRecord/mapDetailResponse.js`
- Create: `src/api/adapters/journalRecord/mapDetailResponse.spec.js`
**Interfaces:**
- Produces: `STORE_DAILY_TAB_KEY`, `STORE_DAILY_TEMPLATE_TYPE`, `isStoreDailyJournalType(type)`, `normalizeJournalListQuery(query)`, and `isStoreDailyTemplateType(type)`.
- Consumes: route query and optional detail response `templateType`.
- [ ] **Step 1: Write pure access and constants tests**
Assert that only `{ key: "storeDaily", journalType: 2 }` remains, list queries normalize retired/invalid types to `storeDaily`, only `storeDaily` is allowed for details, and response template type `1/3` is rejected while `2` is accepted.
- [ ] **Step 2: Run focused tests and verify failure**
```powershell
npm run test:unit -- src/views/residentManage/journalRecord/utils/journalAccess.spec.js src/views/residentManage/journalRecord/constants.spec.js src/api/adapters/journalRecord/mapDetailResponse.spec.js
```
Expected: helper files/functions do not exist and constants still expose three tabs.
- [ ] **Step 3: Implement the pure access helper and reduce constants**
Create constants for `storeDaily` and `2`; normalize list query by returning a copy with `journalType: "storeDaily"`; validate details by exact key; treat a missing response `templateType` as compatible and a present non-2 value as incompatible. Remove retired tab columns/title branches/tracking entries and make template lookup fallback `2`.
- [ ] **Step 4: Make the list page store-daily-only**
Set `activeTab` to `storeDaily`, normalize old query parameters during initialization, keep merchant-only search and store-daily columns, and ensure detail navigation always writes `journalType: "storeDaily"`.
- [ ] **Step 5: Block retired detail links before API access and validate responses**
At the start of `fetchDetail`, reject any query type other than `storeDaily`, call `this.$message.warning("该汇报类型已停用")`, and `replace` the list route without invoking the API. After a successful response, apply the same redirect if a present `templateType` is not `2`. Add `templateType` to `mapDetailResponse`.
- [ ] **Step 6: Run focused access tests**
Run the Step 2 command. Expected: all selected tests pass.
### Task 2: Support the latest V2.3.0 child visibility expressions
**Files:**
- Modify: `src/views/residentManage/journalRecord/utils/journalFormVisibility/groupShowRuleEval.js`
- Create: `src/views/residentManage/journalRecord/utils/journalFormVisibility/groupShowRuleEval.spec.js`
- Modify: `src/views/residentManage/journalRecord/utils/journalFormVisibility/groupVisibility.js`
- Modify: `src/views/residentManage/journalRecord/utils/journalFormVisibility/index.js`
- Modify: `tests/unit/views/residentManage/journalRecord/journalFormVisibility.spec.js`
**Interfaces:**
- Consumes: `childrenShowRules.keys/result`, row fields, and detail context `{ sceneList, baseSceneCode, sceneType, brandIds }`.
- Produces: safe Boolean evaluation for comparisons, arrays, includes, unary NOT, AND/OR, parentheses, `$sceneCodes`, and `$brandIds`.
- [ ] **Step 1: Add failing parser and F2-107 integration tests**
Cover the real delivery-date expression with three inputs, tag rules such as `val1.includes('已触客')`, negated includes for `F2-107-17`, malformed syntax fail-closed, and context keys resolved as string arrays.
- [ ] **Step 2: Run focused visibility tests and verify failure**
```powershell
npm run test:unit -- src/views/residentManage/journalRecord/utils/journalFormVisibility/groupShowRuleEval.spec.js tests/unit/views/residentManage/journalRecord/journalFormVisibility.spec.js
```
Expected: the current split-on-`&&` evaluator cannot parse arrays, includes, OR, parentheses, or context keys.
- [ ] **Step 3: Port the safe tokenizer/parser pattern**
Replace the limited evaluator with a tokenizer and recursive-descent parser supporting only the approved grammar. Export `fallbackEvaluate` for direct tests; catch unsupported syntax and return `false`.
- [ ] **Step 4: Normalize rule values and inject detail context**
For object selections, resolve rule values through static option ID to option value/label, then fall back through `name`, `label`, `text`, `value`, and `id`. For arrays, normalize every item. Resolve `$sceneCodes` from effective detail scenes and `$brandIds` from detail brands, then pass context from `filterFieldNode` to `filterVisibleRowFields`.
- [ ] **Step 5: Run focused visibility tests**
Run the Step 2 command. Expected: all parser and F2-107 integration tests pass.
### Task 3: Render App object selections and representative V2.3.0 content
**Files:**
- Modify: `src/views/residentManage/journalRecord/utils/journalFormEcho.js`
- Create: `src/views/residentManage/journalRecord/utils/journalFormEcho.spec.js`
**Interfaces:**
- Consumes: App `origin_children + childrenValue` and values shaped as scalar, `{ text, value }`, or `{ id, name }`.
- Produces: sorted readonly blocks and subform cells with human-readable labels.
- [ ] **Step 1: Add a representative latest-store-detail fixture in the test**
Build a minimal `F2-101`–`F2-107` form list in the test, including `F2-107-7` with `optionsKey: "options"`, `{ id, name }` customer tags, a car object, and delivery-date/tag `childrenShowRules`. Assert top-level order, visible columns, hidden columns, and no `[object Object]` output.
- [ ] **Step 2: Run the echo test and verify failure**
```powershell
npm run test:unit -- src/views/residentManage/journalRecord/utils/journalFormEcho.spec.js
```
Expected: `{ id, name }` selections stringify as objects and dependent column assertions fail before Task 2/3 behavior is complete.
- [ ] **Step 3: Extend label-value formatting without changing data precedence**
Update object detection and display resolution to accept both object families. For multiple selection arrays, display `name/label/text`, fall back to matching static options, and join with `,`. Keep `jsonContent` primary and schema/fieldData fallback unchanged.
- [ ] **Step 4: Run echo and complete journal tests**
```powershell
npm run test:unit -- src/views/residentManage/journalRecord src/api/adapters/journalRecord tests/unit/views/residentManage/journalRecord tests/unit/api/adapters/journalRecord
```
Expected: all journal-related unit tests pass.
### Task 4: Lint, verify, and commit
**Files:**
- Verify all Task 1–3 files.
**Interfaces:**
- Produces: a reviewable backend commit with no unrelated changes.
- [ ] **Step 1: Run touched-file lint without relying on user fixes**
```powershell
npx eslint src/views/residentManage/journalRecord src/api/adapters/journalRecord/mapDetailResponse.js src/api/adapters/journalRecord/mapDetailResponse.spec.js
```
Expected: zero errors.
- [ ] **Step 2: Run the full unit suite**
```powershell
npm run test:unit -- --runInBand
```
Expected: zero failures.
- [ ] **Step 3: Inspect and commit the scoped diff**
Run `git diff --check`, verify only journal/access/adapter/tests/docs are staged, and commit:
```powershell
git commit -m "feat: 门店工作汇报仅保留门店日报"
```
# Order Approval Button Visibility Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** 让精品订单和权益订单列表的“通过/驳回”按钮只在订单审批状态为“运营待审批”且满足原有权限条件时显示。
**Architecture:** 在现有订单列表显示工具中增加一个无副作用的共享判断函数,统一处理状态值和权限值的数字/字符串兼容。两个 Vue 2 页面把该函数注册为模板方法,分别传入通过或驳回的菜单权限标记;单元测试同时验证判断矩阵和两个模板的接入。
**Tech Stack:** Vue 2.6、JavaScript、Jest 27、Vue CLI 5、ESLint 9
## Global Constraints
- 仅修改精品订单、权益订单的列表按钮显示,不修改审批接口、审批弹窗或提交逻辑。
- “运营待审批”的精确状态值为 `2`,状态 `1`“区域运营待审批”不显示按钮。
- 保留原有 `canApplyFlag == 1 || 对应菜单权限` 的权限语义,并兼容接口返回数字或字符串。
- 使用 Vue 2 Options API,不引入 Composition API、TypeScript 或新依赖。
- 不触碰工作区内商品上架模块的未提交改动。
---
## File Structure
- `src/views/orderManage/utils/orderListRowDisplay.js`:新增共享的审批按钮显示判断函数。
- `tests/unit/views/orderManage/orderApprovalButtonVisibility.spec.js`:验证判断矩阵,并静态检查两个列表模板均复用该函数。
- `src/views/orderManage/order.vue`:精品订单通过/驳回按钮接入共享判断。
- `src/views/orderManage/carDamage.vue`:权益订单通过/驳回按钮接入共享判断。
### Task 1: 共享审批按钮显示规则
**Files:**
- Create: `tests/unit/views/orderManage/orderApprovalButtonVisibility.spec.js`
- Modify: `src/views/orderManage/utils/orderListRowDisplay.js`
**Interfaces:**
- Consumes: 列表行对象 `{ goodsOrderApplyStatus, canApplyFlag }` 和当前按钮的菜单权限标记 `authFlag`。
- Produces: `canShowOrderApprovalButton(row, authFlag): boolean`,供两个 Vue 页面模板调用。
- [x] **Step 1: 编写状态和权限判断的失败测试**
```js
import { canShowOrderApprovalButton } from "@/views/orderManage/utils/orderListRowDisplay";
describe("orderApprovalButtonVisibility", () => {
it.each([2, "2"])("运营待审批状态 %p 且有行级权限时显示", (status) => {
expect(canShowOrderApprovalButton({
canApplyFlag: "1",
goodsOrderApplyStatus: status,
}, false)).toBe(true);
});
it("运营待审批且有对应菜单权限时显示", () => {
expect(canShowOrderApprovalButton({
canApplyFlag: 0,
goodsOrderApplyStatus: 2,
}, true)).toBe(true);
});
it.each([1, 3, 4, null, undefined, ""])("非运营待审批状态 %p 不显示", (status) => {
expect(canShowOrderApprovalButton({
canApplyFlag: 1,
goodsOrderApplyStatus: status,
}, true)).toBe(false);
});
it("运营待审批但无原有权限时不显示", () => {
expect(canShowOrderApprovalButton({
canApplyFlag: 0,
goodsOrderApplyStatus: 2,
}, false)).toBe(false);
});
it("缺少订单行时不显示", () => {
expect(canShowOrderApprovalButton(undefined, true)).toBe(false);
});
});
```
- [x] **Step 2: 运行测试并确认因缺少导出函数而失败**
Run: `npm run test:unit -- tests/unit/views/orderManage/orderApprovalButtonVisibility.spec.js --runInBand`
Expected: FAIL,提示 `canShowOrderApprovalButton is not a function` 或导出不存在。
- [x] **Step 3: 实现最小共享判断函数**
在 `src/views/orderManage/utils/orderListRowDisplay.js` 的格式化函数之前新增:
```js
/**
* @param {object} [row]
* @param {boolean} [authFlag]
* @returns {boolean} 是否显示订单审批按钮
*/
export function canShowOrderApprovalButton(row, authFlag = false) {
return Number(row?.goodsOrderApplyStatus) === 2
&& (Number(row?.canApplyFlag) === 1 || Boolean(authFlag));
}
```
- [x] **Step 4: 运行定向测试并确认通过**
Run: `npm run test:unit -- tests/unit/views/orderManage/orderApprovalButtonVisibility.spec.js --runInBand`
Expected: PASS,全部判断矩阵通过。
### Task 2: 精品和权益列表接入共享规则
**Files:**
- Modify: `tests/unit/views/orderManage/orderApprovalButtonVisibility.spec.js`
- Modify: `src/views/orderManage/order.vue`
- Modify: `src/views/orderManage/carDamage.vue`
**Interfaces:**
- Consumes: Task 1 导出的 `canShowOrderApprovalButton(row, authFlag): boolean`。
- Produces: 两个列表模板对“通过”和“驳回”分别调用统一规则。
- [x] **Step 1: 补充两个页面注册共享规则的失败测试**
测试导入两个真实页面组件;用 Jest 隔离页面 API 模块的请求封装,避免加载仅支持 Webpack 浏览器环境的入口文件:
```js
import CarDamage from "@/views/orderManage/carDamage.vue";
import Order from "@/views/orderManage/order.vue";
jest.mock("@/api/request", () => jest.fn());
```
在 `describe` 中加入组件行为断言:
```js
it.each([
["精品订单", Order],
["权益订单", CarDamage],
])("%s 页面注册统一的审批按钮显示规则", (name, component) => {
expect(component.methods.canShowOrderApprovalButton).toBeInstanceOf(Function);
expect(component.methods.canShowOrderApprovalButton({
canApplyFlag: 1,
goodsOrderApplyStatus: 3,
}, true)).toBe(false);
});
```
- [x] **Step 2: 运行测试并确认页面尚未注册方法而失败**
Run: `npm run test:unit -- tests/unit/views/orderManage/orderApprovalButtonVisibility.spec.js --runInBand`
Expected: FAIL,指出两个页面的 `methods.canShowOrderApprovalButton` 为 `undefined`。
- [x] **Step 3: 在两个 Vue 页面导入并注册共享函数**
精品订单导入改为:
```js
import { canShowOrderApprovalButton, mapOrderListRow } from "./utils/orderListRowDisplay";
```
权益订单导入改为:
```js
import { canShowOrderApprovalButton, mapCarDamageListRow } from "./utils/orderListRowDisplay";
```
两个页面的 `methods` 对象中都注册:
```js
canShowOrderApprovalButton,
```
- [x] **Step 4: 替换两个页面共四个按钮的显示条件**
“通过”统一使用:
```vue
v-if="canShowOrderApprovalButton(scope.row, approveAuthFlag)"
```
“驳回”统一使用:
```vue
v-if="canShowOrderApprovalButton(scope.row, rejectAuthFlag)"
```
- [x] **Step 5: 运行定向测试并确认通过**
Run: `npm run test:unit -- tests/unit/views/orderManage/orderApprovalButtonVisibility.spec.js --runInBand`
Expected: PASS,判断矩阵和两个模板接入测试全部通过。
### Task 3: 回归与代码质量验证
**Files:**
- Verify: `src/views/orderManage/utils/orderListRowDisplay.js`
- Verify: `tests/unit/views/orderManage/orderApprovalButtonVisibility.spec.js`
- Verify: `src/views/orderManage/order.vue`
- Verify: `src/views/orderManage/carDamage.vue`
**Interfaces:**
- Consumes: Task 1 和 Task 2 的完整实现。
- Produces: 可提交的、通过测试与静态检查的订单审批按钮显示优化。
- [x] **Step 1: 运行订单列表相关单元测试**
Run: `npm run test:unit -- tests/unit/views/orderManage src/views/orderManage/utils/orderListRowDisplay.spec.js --runInBand`
Expected: PASS,无订单列表回归失败。
- [x] **Step 2: 对新增工具和测试运行 ESLint**
Run: `npx eslint src/views/orderManage/utils/orderListRowDisplay.js tests/unit/views/orderManage/orderApprovalButtonVisibility.spec.js`
Expected: exit code `0`,无 ESLint 诊断。
- [x] **Step 3: 检查两个历史页面的本次差异**
Run: `git diff --check -- src/views/orderManage/order.vue src/views/orderManage/carDamage.vue`
Expected: exit code `0`,无空白错误;确认每个页面只有导入、方法注册和两个 `v-if` 条件发生变化。
- [x] **Step 4: 检查暂存范围并提交实现**
```bash
git status --short
git diff -- src/views/orderManage/utils/orderListRowDisplay.js tests/unit/views/orderManage/orderApprovalButtonVisibility.spec.js src/views/orderManage/order.vue src/views/orderManage/carDamage.vue docs/superpowers/plans/2026-08-17-order-approval-button-visibility.md
git add docs/superpowers/plans/2026-08-17-order-approval-button-visibility.md src/views/orderManage/utils/orderListRowDisplay.js tests/unit/views/orderManage/orderApprovalButtonVisibility.spec.js src/views/orderManage/order.vue src/views/orderManage/carDamage.vue
git commit -m "fix: 限制订单审批按钮显示状态"
```
Expected: 只提交本功能的五个文件,不包含 `src/views/goods/purchaseOnShelves/` 下的用户改动。
# 订单列表日报字段 Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** 在订单管理的精品、权益订单列表展示中文日报标签和 `YYYY-MM-DD` 实际交付日期,并验证现有导出链路包含对应字段。
**Architecture:** 复用现有 `orderListRowDisplay.js` 行映射层,新增两个纯格式化函数并由精品、权益映射函数共同输出显示字段。两个 Vue 页面只增加表格列,不重复格式化;导出继续使用现有 Swagger 已支持的字段模板和异步导出接口。
**Tech Stack:** Vue 2.6、Element UI 2、JavaScript、dayjs、Jest、现有 ROP Swagger 工具链
## Global Constraints
- 保持 Vue 2 Options API,不引入 Composition API、`script setup` 或 TypeScript 改造。
- `customerTags` 最终必须显示中文;兼容中文原值及 Swagger 定义的数字编码。
- `actualDeliveryDate` 仅显示 `YYYY-MM-DD`。
- 两个字段插入“升级状态”之后,空值显示 `-`。
- 保留现有订单导出队列和接口,不新增请求框架或新 API。
- 修改代码必须符合 `eslint.config.js` 和 `.ai/rules/ESLINT.md`。
---
### Task 1: 共享日报字段格式化与行映射
**Files:**
- Create: `src/views/orderManage/utils/orderListRowDisplay.spec.js`
- Modify: `src/views/orderManage/utils/orderListRowDisplay.js`
**Interfaces:**
- Consumes: Swagger 字段 `customerTags: string|null`、`actualDeliveryDate: string|number|null`
- Produces: `formatCustomerTags(customerTags): string`、`formatActualDeliveryDate(actualDeliveryDate): string`、行字段 `customerTagsDisplay`、`actualDeliveryDateDisplay`
- [x] **Step 1: 写失败测试**
```js
import {
formatActualDeliveryDate,
formatCustomerTags,
mapCarDamageListRow,
mapOrderListRow,
} from "./orderListRowDisplay";
describe("订单列表日报字段显示", () => {
it("将数字日报标签转换为中文并保留中文标签", () => {
expect(formatCustomerTags("1,2,已交付引荐,5")).toBe("已触客,已拉群,已交付引荐,事故车客户");
});
it("将实际交付时间格式化为日期", () => {
expect(formatActualDeliveryDate(1786934049000)).toBe("2026-08-17");
});
it("空值显示横线", () => {
expect(formatCustomerTags(null)).toBe("-");
expect(formatActualDeliveryDate(null)).toBe("-");
});
it("精品和权益行映射输出相同日报字段", () => {
const row = { customerTags: "1,3", actualDeliveryDate: 1786934049000 };
expect(mapOrderListRow(row, { maps: {} })).toMatchObject({
customerTagsDisplay: "已触客,已交付引荐",
actualDeliveryDateDisplay: "2026-08-17",
});
expect(mapCarDamageListRow(row, { maps: {} })).toMatchObject({
customerTagsDisplay: "已触客,已交付引荐",
actualDeliveryDateDisplay: "2026-08-17",
});
});
});
```
- [x] **Step 2: 运行测试并确认因缺少导出函数失败**
Run: `npm run test:unit -- src/views/orderManage/utils/orderListRowDisplay.spec.js --runInBand`
Expected: FAIL,提示 `formatCustomerTags` 或 `formatActualDeliveryDate` 不是函数。
- [x] **Step 3: 实现最小格式化与映射**
```js
import dayjs from "dayjs";
const CUSTOMER_TAG_MAP = {
1: "已触客",
2: "已拉群",
3: "已交付引荐",
4: "首保维保客户",
5: "事故车客户",
};
export function formatCustomerTags(value) {
if (value == null || String(value).trim() === "") {
return "-";
}
return String(value)
.split(/[,,]/)
.map(item => item.trim())
.filter(Boolean)
.map(item => CUSTOMER_TAG_MAP[item] || item)
.join(",") || "-";
}
export function formatActualDeliveryDate(value) {
if (value == null || value === "") {
return "-";
}
const result = dayjs(value).format("YYYY-MM-DD");
return result === "Invalid Date" ? "-" : result;
}
```
在 `mapOrderListRow` 和 `mapCarDamageListRow` 返回值中加入:
```js
customerTagsDisplay: formatCustomerTags(row.customerTags),
actualDeliveryDateDisplay: formatActualDeliveryDate(row.actualDeliveryDate),
```
- [x] **Step 4: 运行定向测试并确认通过**
Run: `npm run test:unit -- src/views/orderManage/utils/orderListRowDisplay.spec.js --runInBand`
Expected: PASS。
### Task 2: 精品和权益列表增加两列
**Files:**
- Modify: `src/views/orderManage/order.vue`
- Modify: `src/views/orderManage/carDamage.vue`
**Interfaces:**
- Consumes: Task 1 生成的 `customerTagsDisplay`、`actualDeliveryDateDisplay`
- Produces: 两个订单列表在“升级状态”后展示“日报标签”和“实际交付日期”
- [x] **Step 1: 在两个列表加入字段列**
精品列表在升级状态列后加入:
```vue
<el-table-column align="center" label="日报标签" prop="customerTagsDisplay" show-overflow-tooltip width="180" />
<el-table-column align="center" label="实际交付日期" prop="actualDeliveryDateDisplay" width="120" />
```
权益列表按现有多行属性格式加入相同列与宽度。
- [x] **Step 2: 运行 Vue 模板差异检查与共享映射测试**
Run:
```powershell
npx eslint src/views/orderManage/order.vue src/views/orderManage/carDamage.vue -f json
npm run test:unit -- src/views/orderManage/utils/orderListRowDisplay.spec.js --runInBand
```
Expected: Vue 模板可解析;两个旧页面存在的历史诊断保持不扩散,本次新增列无 ESLint 诊断;共享映射测试 PASS。人工核对两个模板中字段均紧跟“升级状态”。
### Task 3: Swagger、导出和代码质量验证
**Files:**
- Verify: `src/api/order.js`
- Verify: `src/views/orderManage/order.vue`
- Verify: `src/views/orderManage/carDamage.vue`
**Interfaces:**
- Consumes: `dj.api.smartcarlife.ordermanage.page`、`ordermanage.export.head.template`、`ordermanage.export.async`
- Produces: 接口契约证据、导出表头验收结果、无 ESLint 诊断的最终改动
- [x] **Step 1: 读取线上 Swagger 契约**
Run:
```powershell
npm run rop:swagger -- --swagger http://dj.dev.glsx.com.cn/rop-dj-smartcarlife/swagger-rop/api-docs --method dj.api.smartcarlife.ordermanage.page --out src/api/adapters/orderManage --dry-run --contracts-only --json
```
Expected: `OrderManagePageResponse` 定义包含 `customerTags` 和 `actualDeliveryDate`。
- [x] **Step 2: 读取真实导出字段模板并核验权益实际导出**
Run: 使用 `src/libs/rop/ropClient.js` 登录开发环境,只输出 `customerTags` 和 `actualDeliveryDate` 两个模板项;按权益页面现有参数提交一条订单的异步导出,并使用电子表格工具读取表头。
Expected: 返回“日报标签/customerTags”和“实际交付日期/actualDeliveryDate”,权益实际导出表头也包含“日报标签”和“实际交付日期”。
- [x] **Step 3: 运行共享逻辑定向 ESLint**
Run:
```powershell
npx eslint src/views/orderManage/utils/orderListRowDisplay.js src/views/orderManage/utils/orderListRowDisplay.spec.js
```
Expected: exit code 0;页面新增列使用上一步确认过的无诊断格式。
- [x] **Step 4: 运行完整定向测试**
Run:
```powershell
npm run test:unit -- src/views/orderManage/utils/orderListRowDisplay.spec.js --runInBand
```
Expected: 全部 PASS,无新增错误或警告。
- [x] **Step 5: 检查改动范围并提交**
Run:
```powershell
git diff --check
git status --short
git diff -- src/views/orderManage/order.vue src/views/orderManage/carDamage.vue src/views/orderManage/utils/orderListRowDisplay.js src/views/orderManage/utils/orderListRowDisplay.spec.js
git add docs/superpowers/plans/2026-08-17-order-list-daily-fields.md src/views/orderManage/order.vue src/views/orderManage/carDamage.vue src/views/orderManage/utils/orderListRowDisplay.js src/views/orderManage/utils/orderListRowDisplay.spec.js
git commit -m "feat: 增加订单日报标签和实际交付日期"
```
Expected: 仅提交本功能计划、两个列表、共享映射和对应测试。
# Order Low Price Filter Parameter Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** 让精品订单“仅查看低价订单”开关只有开启时才向列表、累计金额和导出请求传递数字 `lowPriceFlag: 1`。
**Architecture:** 保留精品订单页面现有开关值、表单结构和三个请求对 `getParams()` 的复用,只在 `getParams()` 中对 `lowPriceFlag` 做字段级规范化。单元测试直接调用真实 Vue 组件方法,验证开关值的数字/字符串形态及其他值为 `0` 的筛选字段不受影响。
**Tech Stack:** Vue 2.6、JavaScript、Jest 27、Vue CLI 5、ESLint 9
## Global Constraints
- 仅修改精品订单低价筛选参数处理,不修改权益订单。
- 数字 `1` 和字符串 `"1"` 统一输出数字 `1`。
- 数字 `0`、字符串 `"0"`、空值和其他值不输出 `lowPriceFlag` 属性。
- 不修改其他筛选字段的通用清理规则。
- 列表查询、累计金额统计和导出继续共用 `getParams()`。
- 使用 Vue 2 Options API,不引入新依赖。
- 直接在当前分支修改,不切换分支或创建 worktree。
---
## File Structure
- `tests/unit/views/orderManage/orderLowPriceFilterParam.spec.js`:直接验证精品订单组件真实 `getParams()` 的低价筛选参数输出。
- `src/views/orderManage/order.vue`:在现有 `getParams()` 内显式保留或删除 `lowPriceFlag`。
### Task 1: 低价筛选参数规范化
**Files:**
- Create: `tests/unit/views/orderManage/orderLowPriceFilterParam.spec.js`
- Modify: `src/views/orderManage/order.vue:1142-1198`
**Interfaces:**
- Consumes: `searchForm.lowPriceFlag`,可能是数字、字符串、空值或其他值。
- Produces: `Order.methods.getParams()` 返回的请求参数;只有开启时包含数字 `lowPriceFlag: 1`。
- [x] **Step 1: 编写失败测试**
```js
import Order from "@/views/orderManage/order.vue";
jest.mock("@/api/request", () => jest.fn());
function getParams(lowPriceFlag) {
return Order.methods.getParams.call({
baseSceneCode: "",
sceneBusinessType: undefined,
searchForm: {
lowPriceFlag,
myWaitApplySwitch: 0,
orderTime: "",
paySuccessDate: "",
sellerNameVague: "",
sourceList: "",
},
});
}
describe("orderLowPriceFilterParam", () => {
it.each([0, "0", null, undefined, "", "other"])(
"关闭或非开启值 %p 不传 lowPriceFlag",
(value) => {
const params = getParams(value);
expect(params).not.toHaveProperty("lowPriceFlag");
expect(params.myWaitApplySwitch).toBe(0);
},
);
it.each([1, "1"])("开启值 %p 固定传数字 1", (value) => {
expect(getParams(value)).toMatchObject({ lowPriceFlag: 1 });
});
});
```
- [x] **Step 2: 运行测试并确认当前关闭值仍被保留**
Run: `npm run test:unit -- tests/unit/views/orderManage/orderLowPriceFilterParam.spec.js --runInBand`
Expected: FAIL;数字 `0` 和字符串 `"0"` 的用例收到包含 `lowPriceFlag` 的参数,字符串 `"1"` 用例收到的值不是数字 `1`。
- [x] **Step 3: 在 getParams 中实现字段级处理**
在克隆 `searchForm` 并处理 `sellerNameVague` 后加入:
```js
if (Number(params.lowPriceFlag) === 1) {
params.lowPriceFlag = 1;
} else {
delete params.lowPriceFlag;
}
```
- [x] **Step 4: 运行定向测试并确认通过**
Run: `npm run test:unit -- tests/unit/views/orderManage/orderLowPriceFilterParam.spec.js --runInBand`
Expected: PASS;8 个参数规范化用例全部通过。
### Task 2: 回归、静态检查与提交
**Files:**
- Verify: `tests/unit/views/orderManage/orderLowPriceFilterParam.spec.js`
- Verify: `src/views/orderManage/order.vue`
- Include: `docs/superpowers/plans/2026-08-17-order-low-price-filter-param.md`
**Interfaces:**
- Consumes: Task 1 完成的 `getParams()` 行为。
- Produces: 已验证并提交到当前分支的精品订单低价筛选参数修复。
- [x] **Step 1: 运行订单管理相关测试**
Run: `npm run test:unit -- tests/unit/views/orderManage src/views/orderManage/utils/orderListRowDisplay.spec.js --runInBand`
Expected: PASS,无订单管理回归失败。
- [x] **Step 2: 运行修改范围 ESLint 和差异检查**
```powershell
npx eslint tests/unit/views/orderManage/orderLowPriceFilterParam.spec.js
git diff --check -- src/views/orderManage/order.vue tests/unit/views/orderManage/orderLowPriceFilterParam.spec.js docs/superpowers/plans/2026-08-17-order-low-price-filter-param.md
```
Expected: 两个命令 exit code 均为 `0`;精品订单旧页面的历史 ESLint 诊断另行对比本次新增行,确认没有新增诊断。
- [x] **Step 3: 运行完整单元测试**
Run: `npm run test:unit -- --runInBand`
Expected: PASS,0 个失败测试。
- [x] **Step 4: 检查范围并提交**
```powershell
git status --short
git diff -- src/views/orderManage/order.vue tests/unit/views/orderManage/orderLowPriceFilterParam.spec.js docs/superpowers/plans/2026-08-17-order-low-price-filter-param.md
git add -- docs/superpowers/plans/2026-08-17-order-low-price-filter-param.md src/views/orderManage/order.vue tests/unit/views/orderManage/orderLowPriceFilterParam.spec.js
git commit -m "fix: 调整精品订单低价筛选参数"
```
Expected: 提交只包含实施计划、精品订单页面和新增测试。
# 门店工作汇报仅保留门店日报设计
## 目标
`/journalRecord` 只展示门店日报,禁止继续查看驻店日报和洽谈明细,并让最新 V2.3.0 门店日报 `F2-101~F2-107` 在详情页正常回显。
## 列表页
- `JOURNAL_TABS` 只保留 `{ key: "storeDaily", label: "门店日报", journalType: 2 }`。
- 页面默认且固定使用 `storeDaily`,列表请求固定传 `templateType: 2`。
- 页面不再呈现“驻店日报”和“洽谈明细”页签,也不再保留两类页签的列、搜索条件和埋点分支。
- 访问带旧 `journalType=staffDaily` 或 `journalType=negotiation` 的列表链接时,将查询参数规范为 `storeDaily`,进入可用的门店日报列表。
## 旧详情禁用
- 只有 `journalType=storeDaily` 的详情链接可以调用 `dailyReport.detail.select`。
- 直接访问 `staffDaily` / `negotiation` 详情链接时,在发起详情请求前拦截,提示“该汇报类型已停用”,然后 `replace` 回 `/journalRecord`。
- 缺少或非法 `journalType` 同样按不可用类型处理,不猜测详情类型。
- 详情响应若包含 `templateType`,必须为 `2`;否则不展示内容,提示已停用并返回列表。详情响应没有 `templateType` 时,依赖已校验的路由类型继续回显,兼容现有接口合同。
## 最新模板回显
详情仍以接口 `jsonContent` 为优先数据源,为空时才回退到 `schema.list + fieldDataList`。不在后台内置一份可能过期的 V2.3.0 模板。
### 子表单数据
- 支持 `children[0] + value`、`origin_children + childrenValue` 两种已使用的保存结构。
- `childrenValue` 中的 `{ [subformKey]: { [childKey]: value } }` 转换为只读表格需要的字段行。
- 子表单不从 `subformDataList` 重复组装;该列表仅作为接口存储数据,`jsonContent` 才是带字段元数据的主回显源。
### 值格式化
- `select` / `multipleSelect` 支持标量、`{ text, value }` 和 `{ id, name }`。
- 客户标签 `F2-107-7` 按 `name`、`label`、`text`、静态 options 的顺序取展示文案,不输出 `[object Object]`。
- 日期、数字单位、车型级联和文本保持现有格式化逻辑。
### 子字段显隐
扩展现有安全规则求值器,不使用 `eval` 或 `new Function`。语法与最新门店日报模板对齐:
- `valN == 'x'` / `valN != null`
- `Array.isArray(valN)`
- `valN.includes('x')`
- `!`、`&&`、`||` 和括号
- `keys` 中的 `$sceneCodes` 来自 `detail.sceneList[].baseSceneCode`,回退到 `baseSceneCode` 或 `sceneType`
- `$brandIds` 来自 `detail.brandIds`
求值失败时 fail-closed,对有规则的子字段不展示,并保留控制台错误便于排查。
## 验证
- 列表只有门店日报,请求 `templateType=2`。
- 旧列表链接归一为门店日报。
- 驻店日报/洽谈明细详情链接不发起详情请求,提示并返回列表。
- 响应 `templateType != 2` 时不展示。
- V2.3.0 顶层 `F2-101~F2-106` 按顺序显示。
- `F2-107` 每行的客户标签、车型、责任驻店等对象值显示人类可读文案。
- “实际交付日期”按场景、经营品牌和客户来源显隐。
- “已触客/已交付引荐”相关子字段与“未触客原因”按标签值显隐。
- 旧格式的门店日报回显不回归。
## 范围外
- 不删除后端的驻店日报或洽谈明细历史数据。
- 不调整后端接口权限或数据存储。
- 不把小程序整套动态表单引擎迁入 Vue 2 后台。
# 门店工作汇报需求对齐设计
## 目标
对齐 `/journalRecord` 门店日报列表与详情的已确认验收要求,修正时间和门店提示文案,补齐“延保”展示能力与详情场景上下文,并兼容开发环境最新版门店日报 `jsonContent` 的真实保存结构。
## 范围
本次处理以下内容:
1. 列表时间统一显示为 `YYYY-MM-DD HH:mm`,空值显示 `-`。
2. 门店选择框空值提示改为“请选择门店”。
3. 列表严格沿用后端接口返回顺序,不在前端增加排序。
4. 业务大类支持“轻改、延保、权益”展示。
5. 列表到详情保留场景与品牌上下文,详情兼容最新版模板的选项值和多选包装结构。
以下内容明确不改:
- `journal_web_view_detail` 埋点名称及调用时机。
- 后端接口、分页方式和后端排序规则。
- Vue 2、Element UI、D2Admin 现有页面结构。
## 列表页设计
### 时间与空值
复用 `journalDateTime.js` 的统一格式化函数,将日期时间格式从带秒调整为分钟精度。所有使用该函数的门店日报列表时间列同步生效;无值或非法值统一返回半角连字符 `-`。
### 门店选择
保留远程搜索、清空、分页加载和白名单门店接口,仅将输入框提示文案改为“请选择门店”。
### 顺序
`mapOverviewPageResponse` 保持响应 `list` 的原始顺序。前端不增加 `sort`,请求参数不增加未在接口合同中定义的排序字段,相关测试保护这一约定。
### 业务大类
业务大类按以下优先级解析:
1. 后端明确返回的 `bizTypeName`。
2. `baseSceneCode` 或 `sceneList[].baseSceneCode` 中的精确场景码。
3. 现有 `sceneType` 兜底映射。
精确场景码中,`100101~100103` 映射轻改,`110201/110202` 映射延保,`110101/110102` 映射权益。若只有 `sceneType=0` 且没有精确场景码,继续显示权益,不在前端猜测延保。样式表新增“延保”配置;已有后端 `bizType` 值保持原样。
## 详情页设计
### 上下文传递
列表行适配器保留 `sceneType`,并继续保留 `baseSceneCode`、`sceneList`、`brandIds`。详情接口响应优先,缺失时使用路由上下文;品牌缺失时仍通过门店品牌接口补齐。
### 最新模板值归一化
开发环境真实数据包含两种当前实现未完整处理的结构:
- 客户来源保存为展示文案,例如“销售端引流-售前”,而 `childrenShowRules` 比较选项值 `"0"`。
- 客户标签保存为 `{ text: "已触客/已拉群", value: ["1", "2"] }`,而显隐规则要求数组值。
规则求值前按字段 options 归一化:
- 标量既可以按 option `value` 匹配,也可以按 option `label` 匹配,最终使用 option `value`。
- 对象的 `value` 为数组时,逐项归一化并返回数组,不降级成 `text` 字符串。
- 对象的 `value` 为标量时优先归一化该值;缺少可用值时再回退 `name/label/text/id`。
- 展示格式仍优先使用 `text/name/label`,不改变用户当前看到的可读文案。
这样可保证“实际交付日期、是否有效引荐、无效引荐说明、是否有效到店、未触客原因、未成交原因”等字段按真实模板规则显示。
## 错误与兼容策略
- 不支持或格式错误的规则继续 fail-closed,不使用 `eval` 或 `new Function`。
- 历史字符串、对象数组和旧 `children[0] + value` 结构保持兼容。
- 缺少精确业务场景时不猜测延保,避免把历史权益数据错误分类。
- 不改变接口异常处理和现有全局 Message 行为。
## 测试设计
遵循 TDD,先写失败测试再修改实现:
1. 日期时间分钟格式、空值和非法值测试。
2. 列表真实顺序保持测试。
3. 精确场景码识别轻改、延保、权益及后端名称优先测试。
4. 列表行保留 `sceneType` 测试。
5. 使用开发环境完整 `jsonContent` 的详情回显测试,覆盖客户来源 label 到 value 的归一化,以及 `{ text, value: [] }` 客户标签触发的行内显隐。
6. 运行门店日报相关单测和 touched files ESLint。
## 验收标准
- 列表时间精确到分钟,空值显示 `-`。
- 门店下拉空值提示为“请选择门店”。
- 列表顺序与后端响应一致。
- 有精确场景信息时正确显示轻改、延保或权益;仅有旧 `sceneType` 时保持兼容。
- 详情展示开发环境最新版门店日报数据时,人员、客户来源、客户标签和车型为可读文案,条件字段显隐符合 `childrenShowRules`。
- 埋点实现无变化。
# 订单审批按钮显示优化设计
## 目标
修正订单管理列表中“通过”和“驳回”按钮的显示条件:精品订单和权益订单只有处于“运营待审批”状态,并且满足原有审批权限条件时,才显示对应按钮。
## 现状与根因
以下两个页面目前只判断行级审批标记或菜单按钮权限,没有判断订单审批状态:
- `src/views/orderManage/order.vue`:精品订单
- `src/views/orderManage/carDamage.vue`:权益订单
因此拥有菜单权限的用户会在非待审批订单上看到“通过”或“驳回”。
项目常量 `auditStatusMap` 和 `goodsAuditStatusList` 已明确审批状态:
- `1`:区域运营待审批
- `2`:运营待审批
- `3`:审批通过
- `4`:审批驳回
本次仅允许状态 `2`,不包含状态 `1`。
## 显示规则
“通过”和“驳回”分别保留现有权限判断,并在外层增加审批状态限制。
| 审批状态 | 行级审批标记/对应菜单权限 | 是否显示对应按钮 |
| --- | --- | --- |
| `2` 或字符串 `"2"` | 满足 | 显示 |
| `2` 或字符串 `"2"` | 不满足 | 不显示 |
| `1`、`3`、`4`、空值或其他值 | 任意 | 不显示 |
其中:
- “通过”使用原有 `canApplyFlag == 1 || approveAuthFlag` 权限语义。
- “驳回”使用原有 `canApplyFlag == 1 || rejectAuthFlag` 权限语义。
- 两个按钮的权限仍独立判断,不互相放宽。
## 实现方案
在 `src/views/orderManage/utils/orderListRowDisplay.js` 中增加纯函数,统一判断审批按钮是否可显示。函数对审批状态和行级审批标记做数值兼容,以适配接口可能返回数字或字符串的情况。
精品和权益页面复用该函数,避免两个模板分别维护一套条件。除按钮显示外,不修改接口请求、列表映射、审批弹窗和审批提交逻辑。
未采用的方案:
- 直接在两个模板内联条件:改动行数少,但条件重复且不便独立测试。
- 在列表行映射时写入最终显示布尔值:页面级菜单权限不属于接口行数据,混入映射会增加耦合。
## 测试与验收
- 先为共享判断函数补充失败测试,再实现代码。
- 覆盖数字/字符串状态 `2`、其他审批状态、行级审批标记、通过权限和驳回权限场景。
- 运行订单列表相关单元测试。
- 对修改文件运行 ESLint,并检查两个页面模板均调用统一判断。
## 范围与风险
- 不新增或修改后端接口。
- 不改变审批操作本身的权限校验,只收紧列表入口的显示条件。
- 前端隐藏按钮不是后端安全控制的替代;审批接口仍应保留服务端状态和权限校验。
# 订单列表日报字段设计
## 目标
在订单管理的“精品订单”和“权益订单”列表中新增“日报标签”和“实际交付日期”,并确保现有订单导出支持这两个字段。
## 接口契约
线上 Swagger 接口 `dj.api.smartcarlife.ordermanage.page` 已提供:
- `customerTags`:日报标签。Swagger 描述为逗号分隔的标签编码,真实接口当前也可能直接返回逗号分隔的中文标签。
- `actualDeliveryDate`:客户实际交付日期,类型为 `date-time`,真实接口返回毫秒时间戳。
线上 Swagger 接口 `dj.api.smartcarlife.ordermanage.export.head.template` 已提供以下可选导出字段:
- `customerTags` / 日报标签
- `actualDeliveryDate` / 实际交付日期
精品和权益列表均调用现有 `dj.api.smartcarlife.ordermanage.export.async` 异步导出接口,不新增接口。
## 页面设计
在以下两个列表的“升级状态”之后依次插入:
1. 日报标签
2. 实际交付日期
涉及页面:
- `src/views/orderManage/order.vue`:精品订单
- `src/views/orderManage/carDamage.vue`:权益订单
空值统一显示 `-`。
## 数据映射
在 `src/views/orderManage/utils/orderListRowDisplay.js` 中集中处理显示值,供两个页面复用:
- `customerTagsDisplay`
- 中文标签原样展示。
- 数字编码按 `1=已触客`、`2=已拉群`、`3=已交付引荐`、`4=首保维保客户`、`5=事故车客户` 转成中文。
- 同时兼容英文逗号和中文逗号分隔。
- 未知值保留原文,避免丢失后端新增标签。
- `actualDeliveryDateDisplay`
- 有效时间统一格式化为 `YYYY-MM-DD`。
- 无效或空值显示 `-`。
## 导出设计
- 精品订单保留现有导出字段选择弹窗;后端模板返回的两个字段会出现在可选项中,用户勾选后随现有 `fieldList` 提交。
- 权益订单保留现有直接异步导出流程;不改变筛选参数和场景参数,由后端按已发布的导出字段定义生成文件。
- 验证阶段检查精品导出模板字段,并检查权益实际导出的 Excel 表头包含两个字段。
## 测试与验收
- 为共享行映射补充单元测试,覆盖中文标签、数字标签、空标签、时间戳日期和空日期。
- 运行订单行映射定向单测。
- 对修改文件运行 ESLint。
- 读取线上 Swagger 再次确认字段契约。
- 验证精品、权益列表字段顺序和空值展示。
- 验证导出文件包含“日报标签”和“实际交付日期”。
## 范围与风险
- 不新增接口,不调整筛选条件,不改订单详情。
- 不改 Vue 版本、组件体系或现有导出队列。
- Swagger 对 `customerTags` 的描述与真实返回形式存在差异,因此前端兼容编码和中文两种形式。
- 权益导出内容由后端异步生成;若运行环境尚未发布对应导出字段,前端列表仍可正常展示,但导出验收会明确报出后端环境差异。
# 精品订单低价筛选参数设计
## 目标
修正订单管理“精品订单”列表中“仅查看低价订单”筛选字段的请求参数:开关开启时传 `lowPriceFlag: 1`,关闭或重置时不传 `lowPriceFlag`。
## 现状与根因
精品订单页面的 `searchForm.lowPriceFlag` 默认值和重置值为数字 `0`,Element UI 开关关闭时也可能写入字符串 `"0"`。
页面 `getParams()` 当前只清理 `null`、空字符串和空数组,不会清理数字 `0` 或字符串 `"0"`,所以关闭开关后仍会向后端发送 `lowPriceFlag: 0`。
## 范围
仅修改:
- `src/views/orderManage/order.vue` 中精品订单的低价筛选参数处理。
精品订单列表查询、累计订单金额统计和订单导出均复用 `getParams()`,因此三类请求统一遵循本规则。
不修改:
- 权益订单页面。
- 开关展示、默认关闭状态和重置行为。
- 其他筛选字段的空值清理规则。
- API、导出字段、审批流程和订单详情。
## 参数规则
| 表单值 | 请求参数 |
| --- | --- |
| 数字 `1` | `lowPriceFlag: 1` |
| 字符串 `"1"` | `lowPriceFlag: 1` |
| 数字 `0` | 不传 `lowPriceFlag` |
| 字符串 `"0"` | 不传 `lowPriceFlag` |
| 空值或其他值 | 不传 `lowPriceFlag` |
## 实现方案
在精品订单 `getParams()` 克隆表单后,对 `lowPriceFlag` 做字段级显式处理:
- `Number(params.lowPriceFlag) === 1` 时规范为数字 `1`。
- 其他情况删除 `params.lowPriceFlag`。
不修改通用空值清理循环,避免误删其他业务上有意义的数字 `0`。
## 测试与验收
- 直接测试精品订单组件真实的 `getParams()`。
- 覆盖数字/字符串的开启和关闭值,以及默认关闭、重置后的典型值。
- 确认开启结果固定为数字 `1`,关闭结果不存在 `lowPriceFlag` 属性。
- 运行订单管理相关单元测试、全量单元测试和修改文件 ESLint。
## 风险
本次只改变请求参数是否包含 `lowPriceFlag`,不改变页面状态。由于列表、统计和导出共用 `getParams()`,三者会同时修正;如果后端曾依赖关闭时显式接收 `0`,行为会改变,但这正是本次确认的接口契约。
# 移除 Sentry 与 glsk-toolkit 设计
## 背景
项目已不再使用 Sentry 上报,但当前仍保留浏览器端初始化、生产构建 sourcemap 上传、上传配置文件及相关依赖。`glsk-toolkit` 虽只用于 GSC 请求封装,却硬依赖 `@sentry/browser`,因此仅删除项目直接声明的 Sentry 包仍无法从依赖树中彻底清除 Sentry。
## 目标
- 停止浏览器错误与性能数据上报。
- 停止生产构建上传 sourcemap。
- 从直接依赖、间接依赖和锁文件中清除全部 `@sentry/*` 包。
- 删除仓库中的 Sentry 上传配置。
- 保持现有 GSC 接口调用方式和业务行为不变。
## 非目标
- 不调整现有 ROP/axios 请求体系。
- 不改动约 72 个 `gscPost()` 业务调用点。
- 不升级 Vue、axios 或构建工具。
- 不借机重构配置中心加载流程。
## 基线失败处理
当前完整单测基线包含 11 个失败套件、22 个失败用例。逐项结合提交历史与当前实现核对后,处理原则如下:
- 以已经提交的业务行为为准,不为了匹配旧断言回退营销条件默认值、多选枚举、任务详情换行展示、财务接口映射和金额格式。
- 更新营销、任务中心和财务模块中未随业务提交同步的测试数据与断言;页面配置测试改为直接验证数据或补齐方法上下文,避免重复挂载即时 watcher 造成 Vue Test Utils 假失败。
- 修正 `tests/integration/journalRecord.api.spec.js` 指向现有 `tests/helpers/ropTestClient.js` 的错误相对路径;未启用 `ROP_INTEGRATION` 时仍保持跳过外部集成请求。
- 营销策略编辑集成测试的分支数据补齐契约要求的 `conditionGroups`,动作确认项改为验证项目常量配置,不改业务实现。
- 基线修复后先运行 11 个原失败套件,再运行全量单测;只有基线恢复后才继续验收 GSC 替换,避免新增改动掩盖既有问题。
## 方案
### Sentry 接入移除
从 `src/main.js` 删除 Sentry 与 BrowserTracing 导入及生产环境初始化逻辑;从 `vue.config.js` 删除 Sentry Webpack 插件导入和生产构建上传配置;删除 `.sentryclirc`。同步移除文档中把 Sentry 描述为当前构建能力的内容。
### GSC 请求客户端替换
新增项目内最小 GSC 客户端,替代 `glsk-toolkit` 的 `Request`。客户端只实现项目实际使用的能力:
- `post(url, data, config)` 调用入口。
- 读取配置中心下发的 `baseURL`、`appId`、`appSecret`、响应字段规则和默认超时。
- 每次请求读取当前登录 token,并按现有配置注入 `sessionId`。
- 使用 HMAC-SHA256 生成 `X-App-Id`、`X-Nonce`、`X-Timestamp`、`X-Sign` 请求头。
- 支持调用点正在使用的 `timeout` 和 `returnAll` 选项。
- 按配置中心的 `code_key`、`code_success_value`、`data_key`、`errId`、`errId_logout_value` 规则处理业务响应。
- 保留现有成功数据解包、完整响应返回、错误提示和登录失效跳转行为。
`src/api/gscRequest.js` 的导出和现有 `gscPost()` 调用保持不变,`src/main.js` 仍在配置中心响应后创建 `window.$gscApi`,将影响范围限制在客户端底层。
为兼容当前浏览器范围,签名使用直接声明的轻量 `crypto-js` 依赖,不依赖现代浏览器 Web Crypto API。
### 依赖调整
删除以下依赖:
- `@sentry/browser`
- `@sentry/integrations`
- `@sentry/tracing`
- `@sentry/vue`
- `@sentry/webpack-plugin`
- `glsk-toolkit`
新增直接依赖 `crypto-js`,并重新生成 `package-lock.json`。完成后依赖树与锁文件中不应再出现 `@sentry/*`。
## 错误处理
- HTTP、网络、超时或解析失败继续调用现有 `events.error`,由页面统一显示 Element Message,并向调用方抛出错误。
- 业务失败按现有响应配置触发 `events.error`,返回结构保持兼容。
- 命中登录失效码时调用 `events.logout`,继续清理用户状态、移除 token、跳转登录页并提示。
- 配置缺少签名所需的 `appId` 或 `appSecret` 时沿用当前行为:输出警告但仍发起请求。
## 测试与验收
- 为 GSC 客户端补充同目录单元测试,覆盖签名、Session 注入、成功解包、`returnAll`、业务失败、登录失效及网络错误。
- 对修改的 JavaScript 文件执行 ESLint 检查。
- 执行相关 Jest 单测。
- 执行依赖树检查并扫描仓库,确认代码、配置、`package.json` 和 `package-lock.json` 中不存在有效 Sentry 接入或依赖。
- 按项目规范不执行生产构建;如后续需要验证生产产物,再单独运行构建。
## 风险与控制
- 最大风险是替换请求客户端后签名或响应解包细节变化。通过保持 `gscPost()` 接口不变、复刻当前算法并增加单测控制风险。
- 配置中心规则来自运行时,测试将覆盖字段名可配置场景,避免只适配固定响应格式。
- 删除 `.sentryclirc` 会移除仓库中的上传凭据和目标配置;这是停止 Sentry 上传的预期结果。
......@@ -33,6 +33,9 @@ module.exports = {
"**/*.integration.spec.js",
"tests/**/*.spec.js",
],
testPathIgnorePatterns: [
"/scripts/knowledge-graph/__fixtures__/",
],
testURL: "http://localhost/",
testEnvironment: "jsdom",
setupFiles: ["<rootDir>/jest.setup.js"],
......
......@@ -17,13 +17,14 @@
"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"
"test:unit": "vue-cli-service test:unit",
"knowledge:build": "node scripts/knowledge-graph/cli.js build",
"knowledge:check": "node scripts/knowledge-graph/cli.js check",
"knowledge:test": "vue-cli-service test:unit scripts/knowledge-graph --runInBand",
"impact": "node scripts/knowledge-graph/cli.js impact",
"test:affected": "node scripts/knowledge-graph/cli.js affected"
},
"dependencies": {
"@sentry/browser": "^7.12.1",
"@sentry/integrations": "^7.12.1",
"@sentry/tracing": "^7.3.0",
"@sentry/vue": "^7.3.0",
"ali-oss": "^6.22.0",
"axios": "^0.18.0",
"baseline-browser-mapping": "^2.10.42",
......@@ -31,6 +32,7 @@
"bignumber.js": "^9.1.1",
"caniuse-lite": "^1.0.30001803",
"core-js": "^3.8.3",
"crypto-js": "^4.2.0",
"dayjs": "^1.8.12",
"default-passive-events": "^2.0.0",
"echarts": "^5.3.2",
......@@ -40,7 +42,6 @@
"flex.css": "^1.1.7",
"fuse.js": "^3.4.4",
"glsk-oss-jssdk": "^1.0.6",
"glsk-toolkit": "^1.0.5",
"glsx-common-sdk": "^0.3.0",
"hotkeys-js": "^3.6.2",
"html2canvas": "^1.4.1",
......@@ -72,11 +73,12 @@
"devDependencies": {
"@antfu/eslint-config": "^6.7.3",
"@babel/core": "^7.12.16",
"@babel/parser": "7.29.7",
"@babel/plugin-proposal-nullish-coalescing-operator": "^7.17.12",
"@babel/plugin-proposal-optional-chaining": "7.13.12",
"@babel/traverse": "7.29.7",
"@kazupon/vue-i18n-loader": "^0.4.1",
"@playwright/test": "^1.39.0",
"@sentry/webpack-plugin": "^1.18.9",
"@vue/babel-helper-vue-jsx-merge-props": "^1.4.0",
"@vue/cli-plugin-babel": "~5.0.8",
"@vue/cli-plugin-unit-jest": "~5.0.8",
......@@ -103,6 +105,7 @@
"webpack": "^5.74.0"
},
"volta": {
"node": "14.21.3"
"node": "20.19.0",
"npm": "10.8.2"
}
}
# 产品管理
- [商品列表](../../../src/views/goods/list.vue)
- [商品 API](../../../src/api/goods.js)
- [不存在的说明](./missing.md)
{
"schemaVersion": 1,
"domains": [
{
"id": "903",
"name": "productManagement",
"title": "产品管理",
"aliases": ["商品", "goods"],
"routeModule": "src/router/modules/903_productManagement.js",
"roots": ["src/views/goods", "src/api/goods.js", "src/store/modules/catalog.js"],
"entrypoints": ["src/views/goods/list.vue"],
"riskKeywords": ["listGoods"],
"documents": [".ai/docs/knowledge/903-product.md"]
}
]
}
{
"schemaVersion": 1,
"gaps": [
{
"kind": "route",
"path": "src/views/goods/list.vue",
"line": 38,
"column": 3,
"reason": "dynamic-expression",
"note": "测试夹具中的预期动态跳转"
}
]
}
# Fixture
password: fixture-password
private URL: https://private.example.com
import request from "./request";
export function listGoods(data) {
data.method = "dj.api.smartcarlife.product.list";
return request(data);
}
export default function request(data) {
return data;
}
<template>
<button @click="select">
选择
</button>
</template>
<script>
export default {
name: "SharedCard",
methods: {
select() {
this.$emit("select");
},
},
};
</script>
const _import = require("@/libs/util.import." + process.env.NODE_ENV);
export const routerName = {
903: {
path: "/goods",
name: "goods",
meta: {
title: "产品管理",
authId: "903",
parentId: "1",
},
},
90301: {
path: "/goods/list",
name: "goodsList",
meta: {
title: "商品列表",
authId: "90301",
parentId: "903",
},
auth: [
{
authId: "9030101",
parentId: "90301",
label: "查看详情",
handle: "openDetail",
addRoutePath: [
{
authId: "90302",
name: "goodsDetail",
parentId: "90301",
},
],
},
],
component: _import("goods/list"),
},
90302: {
path: "/goods/detail",
name: "goodsDetail",
meta: {
title: "商品详情",
authId: "90302",
parentId: "90301",
},
component: _import("goods/detail"),
},
};
export default {
namespaced: true,
state: {
items: [],
},
getters: {
itemCount(state) {
return state.items.length;
},
},
actions: {
load() {
return [];
},
},
mutations: {
setItems(state, items) {
state.items = items;
},
},
};
<template>
<div>
商品详情
</div>
</template>
<script>
export default {
name: "GoodsDetail",
};
</script>
<template>
<section>
<shared-card @select="handleSelect"></shared-card>
</section>
</template>
<script>
import { mapActions, mapGetters, mapState } from "vuex";
import SharedCard from "@/components/SharedCard.vue";
import { listGoods } from "@/api/goods";
export default {
name: "GoodsList",
components: {
SharedCard,
},
computed: {
...mapState("catalog", [ "items" ]),
...mapGetters("catalog", [ "itemCount" ]),
},
created() {
this.loadGoods();
},
methods: {
...mapActions("catalog", [ "load" ]),
async loadGoods() {
const items = await listGoods({});
await this.$store.dispatch("catalog/load");
this.$store.commit("catalog/setItems", items);
},
handleSelect() {
this.openDetail();
},
openDetail() {
this.$router.push({ name: "goodsDetail" });
},
openDynamic(target) {
this.$router.push(target);
},
},
};
</script>
const GoodsList = require("@/views/goods/list.vue").default;
describe("商品列表", () => {
it("应导出页面组件", () => {
expect(GoodsList.name).toBe("GoodsList");
});
});
const fs = require("node:fs");
const path = require("node:path");
const process = require("node:process");
const GLOBAL_FILES = new Set([
"package.json",
"package-lock.json",
"babel.config.js",
"jest.config.js",
"vue.config.js",
"eslint.config.js",
"src/main.js",
"src/router/index.js",
"src/router/routes.js",
"src/store/index.js",
"src/api/request.js",
]);
const GLOBAL_PREFIXES = [
"src/components/",
"src/libs/",
"src/common/",
"src/plugin/",
"src/store/modules/d2admin/",
];
function isRuntimeFile(filePath) {
return /^src\/.*\.(?:js|vue)$/.test(filePath);
}
function isKnowledgeOnly(filePath) {
return /^\.ai\/(?:docs\/knowledge|knowledge|generated)\//.test(filePath)
|| /^\.ai\/skills\/requirement-impact-analysis\//.test(filePath)
|| /^scripts\/knowledge-graph\//.test(filePath)
|| filePath.endsWith(".md")
|| filePath === ".gitlab-ci.yml"
|| filePath === "AGENTS.md"
|| filePath === "README.md";
}
function uniqueSorted(values) {
return [...new Set(values)].sort((left, right) => left.localeCompare(right, "en"));
}
function inferDomains(graph, changedFiles) {
const result = new Set(graph.nodes
.filter(node => node.path && changedFiles.includes(node.path))
.flatMap(node => node.domainIds || []));
for (const node of graph.nodes.filter(item => item.type === "domain")) {
const entrypoints = [...(node.meta?.entrypoints || []), ...(node.meta?.roots || [])];
if (changedFiles.some(file => file === node.path
|| entrypoints.some(entrypoint => file === entrypoint || file.startsWith(`${entrypoint}/`)))) {
result.add(node.id.slice("domain:".length));
}
}
return uniqueSorted(result);
}
function relatedNodes(graph, startIds, maxDepth = 4) {
const visited = new Set(startIds);
let frontier = [...startIds];
for (let depth = 0; depth < maxDepth && frontier.length; depth += 1) {
const next = [];
for (const edge of graph.edges) {
if (frontier.includes(edge.from) && !visited.has(edge.to)) {
visited.add(edge.to);
next.push(edge.to);
}
if (frontier.includes(edge.to) && !visited.has(edge.from)) {
visited.add(edge.from);
next.push(edge.from);
}
}
frontier = next;
}
return visited;
}
function targetedCommand(testFiles, verbose) {
const reporter = verbose ? " --verbose" : "";
return `npm run test:unit -- --runTestsByPath ${testFiles.map(file => `"${file}"`).join(" ")}${reporter}`;
}
function planAffectedTests(options) {
const rootDir = path.resolve(options.rootDir || process.cwd());
const graph = options.graph;
const changedFiles = uniqueSorted((options.changedFiles || []).map(file => file.replace(/\\/g, "/")));
const deletedFiles = new Set((options.deletedFiles || []).map(file => file.replace(/\\/g, "/")));
const renamedFiles = new Set((options.renamedFiles || []).map(file => file.replace(/\\/g, "/")));
const reasons = [];
if (options.full) {
reasons.push("forced-full");
}
if (changedFiles.some(file => deletedFiles.has(file) && isRuntimeFile(file))) {
reasons.push("deleted-runtime-file");
}
if (changedFiles.some(file => renamedFiles.has(file) && isRuntimeFile(file))) {
reasons.push("renamed-runtime-file");
}
if (changedFiles.some(file => GLOBAL_FILES.has(file) || GLOBAL_PREFIXES.some(prefix => file.startsWith(prefix)))) {
reasons.push("global-infrastructure");
}
if (reasons.length) {
return {
mode: "full",
changedFiles,
reasons: uniqueSorted(reasons),
domains: [],
testFiles: [],
commands: ["npm run test:unit -- --ci"],
};
}
if (changedFiles.length && changedFiles.every(isKnowledgeOnly)) {
return {
mode: "knowledge-only",
changedFiles,
reasons: ["knowledge-only-change"],
domains: [],
testFiles: [],
commands: ["npm run knowledge:test", "npm run knowledge:check"],
};
}
const changedTestFiles = changedFiles
.filter(file => /\.(?:spec|test)\.js$/.test(file) && fs.existsSync(path.join(rootDir, file)));
if (changedFiles.length && changedTestFiles.length === changedFiles.length) {
return {
mode: "targeted",
changedFiles,
reasons: ["changed-tests-only"],
domains: inferDomains(graph, changedFiles),
testFiles: changedTestFiles,
commands: [targetedCommand(changedTestFiles, options.verbose)],
};
}
const changedNodes = graph.nodes.filter(node => node.path && changedFiles.includes(node.path));
const domains = inferDomains(graph, changedFiles);
if (domains.length >= 3) {
return {
mode: "full",
changedFiles,
reasons: ["cross-domain-change"],
domains,
testFiles: [],
commands: ["npm run test:unit -- --ci"],
};
}
const unresolvedChanged = graph.unresolved.some(item => changedFiles.includes(item.path));
if (unresolvedChanged) {
return {
mode: "full",
changedFiles,
reasons: ["unresolved-change"],
domains,
testFiles: [],
commands: ["npm run test:unit -- --ci"],
};
}
const startIds = changedNodes.map(node => node.id);
const related = relatedNodes(graph, startIds);
const graphTestFiles = uniqueSorted(graph.nodes
.filter(node => node.type === "test" && related.has(node.id))
.map(node => node.path));
const standardTestFiles = uniqueSorted(options.standardTestFiles || []);
const testFiles = uniqueSorted([...graphTestFiles, ...standardTestFiles]);
const runtimeChanges = changedFiles.filter(isRuntimeFile);
if (runtimeChanges.length && (!domains.length || !testFiles.length)) {
return {
mode: "full",
changedFiles,
reasons: ["runtime-change-without-tests"],
domains,
testFiles: [],
commands: ["npm run test:unit -- --ci"],
};
}
const directTests = changedTestFiles;
const selectedTests = uniqueSorted([...testFiles, ...directTests]);
return {
mode: selectedTests.length ? "targeted" : "none",
changedFiles,
reasons: selectedTests.length ? ["related-tests-found"] : ["no-runtime-change"],
domains,
testFiles: selectedTests,
commands: selectedTests.length ? [targetedCommand(selectedTests, options.verbose)] : [],
};
}
module.exports = {
planAffectedTests,
};
const fs = require("node:fs");
const path = require("node:path");
const fixtureRoot = path.resolve(__dirname, "__fixtures__/vue2-app");
const builderPath = path.resolve(__dirname, "build-knowledge-graph.js");
const affectedPath = path.resolve(__dirname, "affected-tests.js");
function loadModules() {
expect(fs.existsSync(builderPath)).toBe(true);
expect(fs.existsSync(affectedPath)).toBe(true);
return {
...require(builderPath),
...require(affectedPath),
};
}
describe("affected 测试规划", () => {
it("业务域文件应选择图谱覆盖测试", () => {
const { buildKnowledgeGraph, planAffectedTests } = loadModules();
const graph = buildKnowledgeGraph({ rootDir: fixtureRoot });
const result = planAffectedTests({
rootDir: fixtureRoot,
graph,
changedFiles: ["src/api/goods.js"],
});
expect(result.mode).toBe("targeted");
expect(result.domains).toContain("903");
expect(result.testFiles).toContain("tests/goods-list.spec.js");
});
it.each([
["package.json", "global-infrastructure"],
["src/router/index.js", "global-infrastructure"],
["src/components/SharedCard.vue", "global-infrastructure"],
])("共享基础设施 %s 应升级全量", (changedFile, reason) => {
const { buildKnowledgeGraph, planAffectedTests } = loadModules();
const graph = buildKnowledgeGraph({ rootDir: fixtureRoot });
const result = planAffectedTests({
rootDir: fixtureRoot,
graph,
changedFiles: [changedFile],
});
expect(result.mode).toBe("full");
expect(result.reasons).toContain(reason);
});
it("纯知识文档改动应只运行知识检查", () => {
const { buildKnowledgeGraph, planAffectedTests } = loadModules();
const graph = buildKnowledgeGraph({ rootDir: fixtureRoot });
const result = planAffectedTests({
rootDir: fixtureRoot,
graph,
changedFiles: [".ai/docs/knowledge/903-product.md"],
});
expect(result.mode).toBe("knowledge-only");
expect(result.commands).toEqual([
"npm run knowledge:test",
"npm run knowledge:check",
]);
});
it("删除运行时代码应升级全量", () => {
const { buildKnowledgeGraph, planAffectedTests } = loadModules();
const graph = buildKnowledgeGraph({ rootDir: fixtureRoot });
const result = planAffectedTests({
rootDir: fixtureRoot,
graph,
changedFiles: ["src/views/goods/removed.vue"],
deletedFiles: ["src/views/goods/removed.vue"],
});
expect(result.mode).toBe("full");
expect(result.reasons).toContain("deleted-runtime-file");
});
it("jest 标准依赖证据应补充新文件的候选测试", () => {
const { buildKnowledgeGraph, planAffectedTests } = loadModules();
const graph = buildKnowledgeGraph({ rootDir: fixtureRoot });
const result = planAffectedTests({
rootDir: fixtureRoot,
graph,
changedFiles: ["src/views/goods/new.vue"],
standardTestFiles: ["tests/goods-list.spec.js"],
});
expect(result.mode).toBe("targeted");
expect(result.domains).toContain("903");
expect(result.testFiles).toEqual(["tests/goods-list.spec.js"]);
});
it("overlay 发现变更文件有 unresolved 时应升级全量", () => {
const { buildKnowledgeGraph, planAffectedTests } = loadModules();
const graph = buildKnowledgeGraph({ rootDir: fixtureRoot });
const result = planAffectedTests({
rootDir: fixtureRoot,
graph,
changedFiles: ["src/views/goods/list.vue"],
});
expect(result.mode).toBe("full");
expect(result.reasons).toContain("unresolved-change");
});
it("运行时代码重命名应升级全量", () => {
const { buildKnowledgeGraph, planAffectedTests } = loadModules();
const graph = buildKnowledgeGraph({ rootDir: fixtureRoot });
const result = planAffectedTests({
rootDir: fixtureRoot,
graph,
changedFiles: ["src/views/goods/detail.vue", "src/views/goods/detail-new.vue"],
renamedFiles: ["src/views/goods/detail.vue", "src/views/goods/detail-new.vue"],
});
expect(result.mode).toBe("full");
expect(result.reasons).toContain("renamed-runtime-file");
});
it("三个业务域受影响时应升级全量", () => {
const { buildKnowledgeGraph, planAffectedTests } = loadModules();
const graph = buildKnowledgeGraph({ rootDir: fixtureRoot });
graph.nodes.push(
{ id: "module:src/domain904.js", type: "module", name: "domain904", path: "src/domain904.js", domainIds: ["904"] },
{ id: "module:src/domain912.js", type: "module", name: "domain912", path: "src/domain912.js", domainIds: ["912"] },
);
const result = planAffectedTests({
rootDir: fixtureRoot,
graph,
changedFiles: ["src/api/goods.js", "src/domain904.js", "src/domain912.js"],
});
expect(result.mode).toBe("full");
expect(result.reasons).toContain("cross-domain-change");
});
it("只修改测试文件时应直接运行该测试", () => {
const { buildKnowledgeGraph, planAffectedTests } = loadModules();
const graph = buildKnowledgeGraph({ rootDir: fixtureRoot });
const result = planAffectedTests({
rootDir: fixtureRoot,
graph,
changedFiles: ["tests/goods-list.spec.js"],
});
expect(result.mode).toBe("targeted");
expect(result.reasons).toEqual(["changed-tests-only"]);
expect(result.testFiles).toEqual(["tests/goods-list.spec.js"]);
});
});
const parser = require("@babel/parser");
function parseJavaScript(source, filePath) {
return parser.parse(source, {
sourceType: "unambiguous",
sourceFilename: filePath,
plugins: [
"dynamicImport",
"jsx",
"objectRestSpread",
"optionalCatchBinding",
"optionalChaining",
"nullishCoalescingOperator",
"classProperties",
],
});
}
function propertyName(property) {
if (!property || !property.key) {
return null;
}
if (property.computed) {
return null;
}
return property.key.name || property.key.value || null;
}
function findProperty(objectNode, name) {
if (!objectNode || objectNode.type !== "ObjectExpression") {
return null;
}
return objectNode.properties.find(property => String(propertyName(property)) === String(name)) || null;
}
function staticPrimitive(node, constants = new Map()) {
if (!node) {
return null;
}
if (["StringLiteral", "NumericLiteral", "BooleanLiteral"].includes(node.type)) {
return node.value;
}
if (node.type === "Identifier" && constants.has(node.name)) {
return constants.get(node.name);
}
if (node.type === "TemplateLiteral") {
let value = "";
for (let index = 0; index < node.quasis.length; index += 1) {
value += node.quasis[index].value.cooked || "";
if (index < node.expressions.length) {
const expressionValue = staticPrimitive(node.expressions[index], constants);
if (expressionValue === null) {
return null;
}
value += String(expressionValue);
}
}
return value;
}
if (node.type === "BinaryExpression" && node.operator === "+") {
const left = staticPrimitive(node.left, constants);
const right = staticPrimitive(node.right, constants);
return left === null || right === null ? null : `${left}${right}`;
}
return null;
}
function locationOf(node, filePath) {
return {
path: filePath,
line: node && node.loc ? node.loc.start.line : 1,
column: node && node.loc ? node.loc.start.column : 0,
};
}
function objectEntries(objectNode) {
if (!objectNode || objectNode.type !== "ObjectExpression") {
return [];
}
return objectNode.properties
.map(property => ({
name: propertyName(property),
node: property,
value: property.value || property,
}))
.filter(entry => entry.name !== null);
}
function arrayValues(node, constants = new Map()) {
if (!node || node.type !== "ArrayExpression") {
return [];
}
return node.elements.map(element => staticPrimitive(element, constants)).filter(value => value !== null);
}
module.exports = {
arrayValues,
findProperty,
locationOf,
objectEntries,
parseJavaScript,
propertyName,
staticPrimitive,
};
const fs = require("node:fs");
const path = require("node:path");
const process = require("node:process");
const { GraphStore } = require("./graph-store");
const { collectFiles } = require("./path-utils");
const {
finalizeRouteLinks,
scanRouterFile,
scanRouterInfrastructure,
} = require("./scan-router");
const {
scanContractFile,
scanDocument,
scanJavaScriptFile,
scanVueFile,
} = require("./scan-sources");
function readJson(filePath, fallback) {
if (!fs.existsSync(filePath)) {
return fallback;
}
return JSON.parse(fs.readFileSync(filePath, "utf8"));
}
function loadDomainCatalog(rootDir) {
const catalogPath = path.join(rootDir, ".ai/knowledge/domain-catalog.json");
const catalog = readJson(catalogPath, { schemaVersion: 1, domains: [] });
if (catalog.schemaVersion !== 1 || !Array.isArray(catalog.domains)) {
throw new Error("Invalid domain catalog");
}
return catalog;
}
function loadKnownGaps(rootDir) {
const knownGapsPath = path.join(rootDir, ".ai/knowledge/known-gaps.json");
const knownGaps = readJson(knownGapsPath, { schemaVersion: 1, gaps: [] });
if (knownGaps.schemaVersion !== 1 || !Array.isArray(knownGaps.gaps)) {
throw new Error("Invalid known gaps configuration");
}
return knownGaps;
}
function markKnownGaps(unresolved, knownGaps) {
const keys = ["kind", "path", "line", "column", "reason"];
return unresolved.map(item => ({
...item,
known: knownGaps.gaps.some(gap => keys.every(key => gap[key] === item[key])),
}));
}
function createContext() {
return {
constants: new Map(),
currentRouterModuleId: null,
pendingRouteLinks: [],
routesByAuthId: new Map(),
routesByName: new Map(),
routesByPath: new Map(),
routeViewPaths: new Set(),
};
}
function hydrateContext(baseGraph) {
const context = createContext();
for (const node of baseGraph?.nodes || []) {
if (node.type !== "route") {
continue;
}
if (node.meta?.authId) {
context.routesByAuthId.set(String(node.meta.authId), node.id);
}
if (node.meta?.routeName) {
context.routesByName.set(String(node.meta.routeName), node.id);
}
if (node.meta?.routePath) {
context.routesByPath.set(String(node.meta.routePath), node.id);
}
}
for (const edge of baseGraph?.edges || []) {
if (edge.type === "renders") {
const target = baseGraph.nodes.find(node => node.id === edge.to);
if (target?.path) {
context.routeViewPaths.add(target.path);
}
}
}
return context;
}
function addDomainNodes(store, catalog) {
for (const domain of catalog.domains) {
store.addNode({
id: `domain:${domain.id}`,
type: "domain",
name: domain.title || domain.name || String(domain.id),
path: domain.routeModule,
domainIds: [String(domain.id)],
meta: {
aliases: domain.aliases || [],
entrypoints: domain.entrypoints || [],
roots: domain.roots || [],
documents: domain.documents || [],
riskKeywords: domain.riskKeywords || [],
},
});
}
}
function validateDomainCatalog(rootDir, store, catalog) {
for (const domain of catalog.domains) {
for (const configuredPath of [
domain.routeModule,
...(domain.roots || []),
...(domain.entrypoints || []),
...(domain.documents || []),
].filter(Boolean)) {
if (!fs.existsSync(path.join(rootDir, configuredPath))) {
store.addUnresolved({
kind: "catalog-path",
path: configuredPath,
reason: "missing-target",
expressionKind: "DomainCatalog",
});
}
}
}
}
function buildKnowledgeGraph(options = {}) {
const rootDir = path.resolve(options.rootDir || process.cwd());
if (!fs.existsSync(rootDir) || !fs.statSync(rootDir).isDirectory()) {
throw new Error(`Invalid root directory: ${rootDir}`);
}
const catalog = loadDomainCatalog(rootDir);
const knownGaps = loadKnownGaps(rootDir);
const store = new GraphStore(catalog);
const context = createContext();
addDomainNodes(store, catalog);
validateDomainCatalog(rootDir, store, catalog);
const files = collectFiles(rootDir);
const routerFiles = files.filter(file => /^src\/router\/modules\/.*\.js$/.test(file));
routerFiles.forEach(file => scanRouterFile(rootDir, file, store, context));
if (files.includes("src/router/routes.js")) {
scanRouterInfrastructure(rootDir, "src/router/routes.js", store, context);
}
finalizeRouteLinks(store, context);
for (const file of files) {
if (routerFiles.includes(file) || file.startsWith(".ai/knowledge/")) {
continue;
}
if (file.endsWith(".vue")) {
scanVueFile(rootDir, file, store, context);
} else if (file.endsWith(".js")) {
scanJavaScriptFile(rootDir, file, store, context);
} else if (file.endsWith(".contract.json")) {
scanContractFile(rootDir, file, store, context);
} else if (file.endsWith(".md")) {
scanDocument(rootDir, file, store, context);
}
}
const graph = store.toGraph();
graph.unresolved = markKnownGaps(graph.unresolved, knownGaps);
return graph;
}
function buildKnowledgeOverlay(options = {}) {
const rootDir = path.resolve(options.rootDir || process.cwd());
if (!fs.existsSync(rootDir) || !fs.statSync(rootDir).isDirectory()) {
throw new Error(`Invalid root directory: ${rootDir}`);
}
const catalog = loadDomainCatalog(rootDir);
const knownGaps = loadKnownGaps(rootDir);
const store = new GraphStore(catalog);
const context = hydrateContext(options.baseGraph);
addDomainNodes(store, catalog);
const files = [...new Set((options.files || []).map(file => file.replace(/\\/g, "/")))]
.filter(file => fs.existsSync(path.join(rootDir, file)))
.sort();
const routerFiles = files.filter(file => /^src\/router\/modules\/.*\.js$/.test(file));
routerFiles.forEach(file => scanRouterFile(rootDir, file, store, context));
if (files.includes("src/router/routes.js")) {
scanRouterInfrastructure(rootDir, "src/router/routes.js", store, context);
}
finalizeRouteLinks(store, context);
for (const file of files) {
if (routerFiles.includes(file) || file === "src/router/routes.js" || file.startsWith(".ai/knowledge/")) {
continue;
}
if (file.endsWith(".vue")) {
scanVueFile(rootDir, file, store, context);
} else if (file.endsWith(".js")) {
scanJavaScriptFile(rootDir, file, store, context);
} else if (file.endsWith(".contract.json")) {
scanContractFile(rootDir, file, store, context);
} else if (file.endsWith(".md")) {
scanDocument(rootDir, file, store, context);
}
}
const graph = store.toGraph();
graph.unresolved = markKnownGaps(graph.unresolved, knownGaps);
return graph;
}
function serializeGraph(graph) {
return `${JSON.stringify(graph)}\n`;
}
module.exports = {
buildKnowledgeGraph,
buildKnowledgeOverlay,
loadDomainCatalog,
loadKnownGaps,
markKnownGaps,
serializeGraph,
};
const fs = require("node:fs");
const path = require("node:path");
const fixtureRoot = path.resolve(__dirname, "__fixtures__/vue2-app");
const builderPath = path.resolve(__dirname, "build-knowledge-graph.js");
function loadBuilder() {
expect(fs.existsSync(builderPath)).toBe(true);
return require(builderPath);
}
function findEdge(graph, type, fromIncludes, toIncludes) {
return graph.edges.find(edge => edge.type === type
&& edge.from.includes(fromIncludes)
&& edge.to.includes(toIncludes));
}
describe("vue2 知识图谱构建", () => {
it("应从路由、SFC、Vuex、API、测试和文档生成公开图谱契约", () => {
const { buildKnowledgeGraph } = loadBuilder();
const graph = buildKnowledgeGraph({ rootDir: fixtureRoot });
expect(Object.keys(graph)).toEqual([
"schemaVersion",
"nodes",
"edges",
"unresolved",
"stats",
]);
expect(graph.schemaVersion).toBe("1.0.0");
const nodeTypes = new Set(graph.nodes.map(node => node.type));
[
"domain",
"route",
"view",
"component",
"module",
"function",
"apiOperation",
"endpoint",
"vuexState",
"vuexGetter",
"vuexAction",
"vuexMutation",
"permission",
"event",
"test",
"document",
].forEach(type => expect(nodeTypes.has(type)).toBe(true));
expect(findEdge(graph, "renders", "route:90301", "views/goods/list.vue")).toBeTruthy();
expect(findEdge(graph, "requiresPermission", "route:90301", "permission:9030101")).toBeTruthy();
expect(findEdge(graph, "usesComponent", "views/goods/list.vue", "components/SharedCard.vue")).toBeTruthy();
expect(findEdge(graph, "listensEvent", "views/goods/list.vue", "event:select")).toBeTruthy();
expect(findEdge(graph, "emitsEvent", "components/SharedCard.vue", "event:select")).toBeTruthy();
expect(findEdge(graph, "calls", "#created", "#loadGoods")).toBeTruthy();
expect(findEdge(graph, "navigatesTo", "#openDetail", "route:90302")).toBeTruthy();
expect(findEdge(graph, "callsApi", "#loadGoods", "api/goods.js#listGoods")).toBeTruthy();
expect(findEdge(graph, "callsEndpoint", "api/goods.js#listGoods", "dj.api.smartcarlife.product.list")).toBeTruthy();
expect(findEdge(graph, "readsState", "views/goods/list.vue", "catalog.items")).toBeTruthy();
expect(findEdge(graph, "readsGetter", "views/goods/list.vue", "catalog.itemCount")).toBeTruthy();
expect(findEdge(graph, "dispatchesAction", "#loadGoods", "catalog/load")).toBeTruthy();
expect(findEdge(graph, "commitsMutation", "#loadGoods", "catalog/setItems")).toBeTruthy();
expect(findEdge(graph, "coveredBy", "views/goods/list.vue", "tests/goods-list.spec.js")).toBeTruthy();
expect(findEdge(graph, "documentedBy", "views/goods/list.vue", ".ai/docs/knowledge/903-product.md")).toBeTruthy();
graph.edges.forEach((edge) => {
expect(typeof edge.confidence).toBe("number");
expect(edge.evidence.path).not.toContain("\\");
expect(Number.isInteger(edge.evidence.line)).toBe(true);
expect(Number.isInteger(edge.evidence.column)).toBe(true);
});
});
it("应记录动态表达式但不复制源码和敏感字面量", () => {
const { buildKnowledgeGraph } = loadBuilder();
const graph = buildKnowledgeGraph({ rootDir: fixtureRoot });
const serialized = JSON.stringify(graph);
expect(graph.unresolved).toEqual(expect.arrayContaining([
expect.objectContaining({
kind: "route",
path: "src/views/goods/list.vue",
known: true,
}),
expect.objectContaining({
kind: "document-link",
path: ".ai/docs/knowledge/903-product.md",
known: false,
}),
]));
expect(serialized).not.toContain("fixture-password");
expect(serialized).not.toContain("this.$router.push(target)");
expect(serialized).not.toContain("https://private.example.com");
});
it("known gaps 必须按结构化证据精确匹配", () => {
const { markKnownGaps } = loadBuilder();
const gaps = [{
kind: "route",
path: "src/views/goods/list.vue",
line: 38,
column: 3,
reason: "dynamic-expression",
}];
expect(markKnownGaps(gaps, { gaps })[0].known).toBe(true);
expect(markKnownGaps([{ ...gaps[0], line: 39 }], { gaps })[0].known).toBe(false);
});
it("无效扫描目录应明确失败", () => {
const { buildKnowledgeGraph } = loadBuilder();
expect(() => buildKnowledgeGraph({ rootDir: path.join(fixtureRoot, "missing") }))
.toThrow("Invalid root directory");
});
it("overlay 应只重扫指定文件并保留动态关系告警", () => {
const { buildKnowledgeGraph, buildKnowledgeOverlay } = loadBuilder();
const baseGraph = buildKnowledgeGraph({ rootDir: fixtureRoot });
const overlay = buildKnowledgeOverlay({
rootDir: fixtureRoot,
baseGraph,
files: ["src/views/goods/list.vue"],
});
expect(overlay.nodes.some(node => node.path === "src/views/goods/list.vue")).toBe(true);
expect(overlay.nodes.some(node => node.path === "src/views/goods/detail.vue")).toBe(false);
expect(overlay.unresolved).toEqual(expect.arrayContaining([
expect.objectContaining({ path: "src/views/goods/list.vue", known: true }),
]));
});
it("应连续产生字节一致且以换行结尾的输出", () => {
const { buildKnowledgeGraph, serializeGraph } = loadBuilder();
const first = serializeGraph(buildKnowledgeGraph({ rootDir: fixtureRoot }));
const second = serializeGraph(buildKnowledgeGraph({ rootDir: fixtureRoot }));
expect(first).toBe(second);
expect(first.endsWith("\n")).toBe(true);
});
});
const fs = require("node:fs");
const path = require("node:path");
const yaml = require("js-yaml");
const rootDir = path.resolve(__dirname, "../..");
describe("gitLab CI 知识图谱门禁", () => {
it("应在 Merge Request 中阻断图谱测试或漂移检查失败", () => {
const config = yaml.load(fs.readFileSync(path.join(rootDir, ".gitlab-ci.yml"), "utf8"));
const job = config.knowledge_graph_check;
expect(job).toBeDefined();
expect(job.allow_failure).toBe(false);
expect(job.rules).toContainEqual({
if: "$CI_PIPELINE_SOURCE == \"merge_request_event\"",
});
expect(job.script).toEqual([
"npm run knowledge:test",
"npm run knowledge:check",
]);
});
});
const fs = require("node:fs");
const path = require("node:path");
const fixtureRoot = path.resolve(__dirname, "__fixtures__/vue2-app");
const cliPath = path.resolve(__dirname, "cli.js");
function loadCli() {
expect(fs.existsSync(cliPath)).toBe(true);
return require(cliPath);
}
describe("知识图谱 CLI", () => {
it("应解析重复 keyword 和影响查询选项", () => {
const { parseArguments } = loadCli();
const options = parseArguments([
"impact",
"--keyword",
"orderList",
"--keyword",
"refund",
"--depth",
"3",
"--direction",
"upstream",
"--format",
"json",
]);
expect(options.command).toBe("impact");
expect(options.keywords).toEqual(["orderList", "refund"]);
expect(options.depth).toBe(3);
expect(options.direction).toBe("upstream");
expect(options.format).toBe("json");
});
it("应为每个业务域生成入口、关系计数和文档缺口", () => {
const { buildKnowledgeGraph } = require("./build-knowledge-graph");
const { renderDomainIndex } = loadCli();
const graph = buildKnowledgeGraph({ rootDir: fixtureRoot });
const markdown = renderDomainIndex(graph);
expect(markdown).toContain("## 903 产品管理");
expect(markdown).toContain("goodsList");
expect(markdown).toContain("listGoods");
expect(markdown).toContain("tests/goods-list.spec.js");
expect(markdown.endsWith("\n")).toBe(true);
});
it("应解析 Git 删除和重命名状态", () => {
const { parseGitDiff } = loadCli();
const result = parseGitDiff("M\tsrc/api/goods.js\nD\tsrc/views/old.vue\nR100\tsrc/a.vue\tsrc/b.vue\n");
expect(result.changedFiles).toEqual(["src/a.vue", "src/api/goods.js", "src/b.vue", "src/views/old.vue"]);
expect(result.deletedFiles).toEqual(["src/views/old.vue"]);
expect(result.renamedFiles).toEqual(["src/a.vue", "src/b.vue"]);
});
});
const { toPosix } = require("./path-utils");
function normalizeEvidence(evidence = {}) {
return {
path: toPosix(evidence.path || "unknown"),
line: Number.isInteger(evidence.line) ? evidence.line : 1,
column: Number.isInteger(evidence.column) ? evidence.column : 0,
};
}
function compareSerialized(left, right) {
return JSON.stringify(left).localeCompare(JSON.stringify(right), "en");
}
class GraphStore {
constructor(domainCatalog) {
this.nodes = new Map();
this.edges = new Map();
this.unresolved = new Map();
this.domainCatalog = domainCatalog;
}
domainsForPath(filePath) {
const normalized = toPosix(filePath);
return this.domainCatalog.domains
.filter(domain => [
domain.routeModule,
...(domain.roots || []),
...(domain.entrypoints || []),
...(domain.documents || []),
].filter(Boolean).some((root) => {
const normalizedRoot = toPosix(root).replace(/\/$/, "");
return normalized === normalizedRoot || normalized.startsWith(`${normalizedRoot}/`);
}))
.map(domain => String(domain.id))
.sort();
}
addNode(node) {
if (!node || !node.id || !node.type) {
throw new Error("Invalid graph node");
}
const normalized = {
id: node.id,
type: node.type,
name: node.name || node.id,
};
if (node.path) {
normalized.path = toPosix(node.path);
}
const domainIds = node.domainIds || (node.path ? this.domainsForPath(node.path) : []);
if (domainIds.length) {
normalized.domainIds = [...new Set(domainIds.map(String))].sort();
}
if (node.meta && Object.keys(node.meta).length) {
normalized.meta = node.meta;
}
const previous = this.nodes.get(normalized.id);
this.nodes.set(normalized.id, previous
? {
...previous,
...normalized,
domainIds: [...new Set([...(previous.domainIds || []), ...(normalized.domainIds || [])])].sort(),
}
: normalized);
return normalized.id;
}
addEdge(edge) {
if (!edge || !edge.from || !edge.to || !edge.type) {
throw new Error("Invalid graph edge");
}
const normalized = {
from: edge.from,
to: edge.to,
type: edge.type,
confidence: typeof edge.confidence === "number" ? edge.confidence : 1,
evidence: normalizeEvidence(edge.evidence),
};
const key = `${normalized.type}|${normalized.from}|${normalized.to}|${JSON.stringify(normalized.evidence)}`;
this.edges.set(key, normalized);
}
addUnresolved(item) {
const normalized = {
kind: item.kind,
path: toPosix(item.path),
line: Number.isInteger(item.line) ? item.line : 1,
column: Number.isInteger(item.column) ? item.column : 0,
reason: item.reason,
expressionKind: item.expressionKind || "Unknown",
};
const key = `${normalized.kind}|${normalized.path}|${normalized.line}|${normalized.column}|${normalized.reason}`;
this.unresolved.set(key, normalized);
}
propagateDomains() {
const propagatingEdges = new Set([
"contains",
"renders",
"declares",
"calls",
"usesComponent",
"definesApi",
"callsApi",
"callsEndpoint",
"readsState",
"readsGetter",
"dispatchesAction",
"commitsMutation",
]);
let changed = true;
while (changed) {
changed = false;
for (const edge of this.edges.values()) {
if (!propagatingEdges.has(edge.type)) {
continue;
}
const source = this.nodes.get(edge.from);
const target = this.nodes.get(edge.to);
if (edge.type === "calls" && (!source?.path || source.path !== target?.path)) {
continue;
}
if (!source?.domainIds?.length || !target) {
continue;
}
const merged = [...new Set([...(target.domainIds || []), ...source.domainIds])].sort();
if (merged.length !== (target.domainIds || []).length) {
target.domainIds = merged;
changed = true;
}
}
}
for (const edge of this.edges.values()) {
if (edge.type !== "coveredBy") {
continue;
}
const source = this.nodes.get(edge.from);
const target = this.nodes.get(edge.to);
if (source?.domainIds?.length === 1 && target) {
target.domainIds = [...new Set([...(target.domainIds || []), source.domainIds[0]])].sort();
}
}
}
toGraph() {
this.propagateDomains();
const nodes = [...this.nodes.values()].sort((left, right) => left.id.localeCompare(right.id, "en"));
const edges = [...this.edges.values()].sort(compareSerialized);
const unresolved = [...this.unresolved.values()].sort(compareSerialized);
const nodeTypes = {};
const edgeTypes = {};
nodes.forEach((node) => {
nodeTypes[node.type] = (nodeTypes[node.type] || 0) + 1;
});
edges.forEach((edge) => {
edgeTypes[edge.type] = (edgeTypes[edge.type] || 0) + 1;
});
return {
schemaVersion: "1.0.0",
nodes,
edges,
unresolved,
stats: {
nodeCount: nodes.length,
edgeCount: edges.length,
unresolvedCount: unresolved.length,
nodeTypes,
edgeTypes,
},
};
}
}
module.exports = {
GraphStore,
normalizeEvidence,
};
const fs = require("node:fs");
const path = require("node:path");
const SOURCE_EXTENSIONS = [".js", ".vue", ".json"];
const IGNORED_DIRECTORIES = new Set([
"node_modules",
"dist",
"coverage",
".git",
".cache",
"copyDirTarget",
]);
function toPosix(filePath) {
return filePath.replace(/\\/g, "/");
}
function relativePath(rootDir, filePath) {
return toPosix(path.relative(rootDir, filePath));
}
function isTestFile(filePath) {
return /(?:^|\/)(?:tests?\/.*|.*\.(?:spec|test)\.js$)/.test(toPosix(filePath));
}
function isDocumentFile(filePath) {
const normalized = toPosix(filePath);
return normalized.endsWith(".md")
|| /src\/api\/adapters\/.*\/__contracts__\/.*\.contract\.json$/.test(normalized);
}
function shouldIncludeFile(relativeFile) {
const normalized = toPosix(relativeFile);
if (normalized.startsWith("scripts/knowledge-graph/__fixtures__/")) {
return false;
}
if (normalized.startsWith(".ai/generated/")) {
return false;
}
if (normalized.endsWith(".vue") || normalized.endsWith(".js")) {
return true;
}
if (isDocumentFile(normalized)) {
return true;
}
return normalized === ".ai/knowledge/domain-catalog.json"
|| normalized === ".ai/knowledge/known-gaps.json"
|| /src\/api\/adapters\/.*\/__contracts__\/.*\.contract\.json$/.test(normalized);
}
function collectFiles(rootDir) {
const files = [];
function walk(currentDir) {
for (const entry of fs.readdirSync(currentDir, { withFileTypes: true })) {
if (entry.isDirectory() && IGNORED_DIRECTORIES.has(entry.name)) {
continue;
}
const absolutePath = path.join(currentDir, entry.name);
if (entry.isDirectory()) {
walk(absolutePath);
continue;
}
const relativeFile = relativePath(rootDir, absolutePath);
if (shouldIncludeFile(relativeFile)) {
files.push(relativeFile);
}
}
}
walk(rootDir);
return files.sort();
}
function resolveWithCandidates(absoluteBase) {
const candidates = [absoluteBase];
SOURCE_EXTENSIONS.forEach(extension => candidates.push(`${absoluteBase}${extension}`));
SOURCE_EXTENSIONS.forEach(extension => candidates.push(path.join(absoluteBase, `index${extension}`)));
return candidates.find(candidate => fs.existsSync(candidate) && fs.statSync(candidate).isFile()) || null;
}
function resolveModule(rootDir, fromFile, specifier) {
if (typeof specifier !== "string" || !specifier) {
return null;
}
let absoluteBase;
if (specifier.startsWith("@/")) {
absoluteBase = path.join(rootDir, "src", specifier.slice(2));
} else if (specifier.startsWith("@api/")) {
absoluteBase = path.join(rootDir, "src/api", specifier.slice(5));
} else if (specifier.startsWith(".")) {
absoluteBase = path.resolve(rootDir, path.dirname(fromFile), specifier);
} else {
return null;
}
const resolved = resolveWithCandidates(absoluteBase);
return resolved ? relativePath(rootDir, resolved) : null;
}
function resolveView(rootDir, importPath) {
return resolveWithCandidates(path.join(rootDir, "src/views", importPath));
}
module.exports = {
collectFiles,
isDocumentFile,
isTestFile,
relativePath,
resolveModule,
resolveView,
toPosix,
};
function uniqueNodes(nodes) {
const byId = new Map();
nodes.forEach((node) => {
if (node) {
byId.set(node.id, node);
}
});
return [...byId.values()].sort((left, right) => left.id.localeCompare(right.id, "en"));
}
function searchableText(node) {
return JSON.stringify({
id: node.id,
name: node.name,
path: node.path,
meta: node.meta,
}).toLowerCase();
}
function createAdjacency(graph) {
const incoming = new Map();
const outgoing = new Map();
for (const edge of graph.edges) {
if (!incoming.has(edge.to)) {
incoming.set(edge.to, []);
}
if (!outgoing.has(edge.from)) {
outgoing.set(edge.from, []);
}
incoming.get(edge.to).push(edge);
outgoing.get(edge.from).push(edge);
}
return { incoming, outgoing };
}
function traverseDirection(graph, seedIds, direction, depth, adjacency = createAdjacency(graph)) {
const nodeById = new Map(graph.nodes.map(node => [node.id, node]));
const visited = new Set(seedIds);
let frontier = [...seedIds];
const result = [];
const evidence = [];
for (let level = 0; level < depth && frontier.length; level += 1) {
const next = [];
for (const currentId of frontier) {
const candidateEdges = direction === "upstream"
? adjacency.incoming.get(currentId) || []
: adjacency.outgoing.get(currentId) || [];
for (const edge of candidateEdges) {
const relatedId = direction === "upstream" ? edge.from : edge.to;
evidence.push(edge);
if (!visited.has(relatedId)) {
visited.add(relatedId);
next.push(relatedId);
if (nodeById.has(relatedId)) {
result.push(nodeById.get(relatedId));
}
}
}
}
frontier = next;
}
return { nodes: uniqueNodes(result), evidence };
}
function traverseUndirected(graph, seedIds, depth, adjacency) {
const nodeById = new Map(graph.nodes.map(node => [node.id, node]));
const visited = new Set(seedIds);
let frontier = [...seedIds];
const result = [];
const evidence = [];
for (let level = 0; level < depth && frontier.length; level += 1) {
const next = [];
for (const currentId of frontier) {
const edges = [
...(adjacency.incoming.get(currentId) || []),
...(adjacency.outgoing.get(currentId) || []),
];
for (const edge of edges) {
const relatedId = edge.from === currentId ? edge.to : edge.from;
evidence.push(edge);
if (!visited.has(relatedId)) {
visited.add(relatedId);
next.push(relatedId);
if (nodeById.has(relatedId)) {
result.push(nodeById.get(relatedId));
}
}
}
}
frontier = next;
}
return { nodes: uniqueNodes(result), evidence };
}
function collectLinkedType(graph, relatedIds, edgeType, nodeType) {
const nodeById = new Map(graph.nodes.map(node => [node.id, node]));
return uniqueNodes(graph.edges
.filter(edge => edge.type === edgeType && relatedIds.has(edge.from))
.map(edge => nodeById.get(edge.to))
.filter(node => node?.type === nodeType));
}
function queryImpact(graph, options = {}) {
const keywords = (options.keywords || []).map(keyword => String(keyword).trim().toLowerCase()).filter(Boolean);
const depth = Number.isInteger(options.depth) ? Math.max(0, options.depth) : 2;
const direction = options.direction || "both";
const directMatches = keywords.length
? graph.nodes.filter(node => keywords.some(keyword => searchableText(node).includes(keyword)))
: [];
const seeds = uniqueNodes(directMatches);
const seedIds = seeds.map(node => node.id);
const adjacency = createAdjacency(graph);
const upstream = ["both", "upstream"].includes(direction)
? traverseDirection(graph, seedIds, "upstream", depth, adjacency)
: { nodes: [], evidence: [] };
const downstream = ["both", "downstream"].includes(direction)
? traverseDirection(graph, seedIds, "downstream", depth, adjacency)
: { nodes: [], evidence: [] };
const neighborhood = direction === "both"
? traverseUndirected(graph, seedIds, depth, adjacency)
: { nodes: [], evidence: [] };
if (direction === "both") {
const upstreamIds = new Set(upstream.nodes.map(node => node.id));
downstream.nodes = uniqueNodes([
...downstream.nodes,
...neighborhood.nodes.filter(node => !upstreamIds.has(node.id)),
]);
downstream.evidence.push(...neighborhood.evidence);
}
const relatedNodes = uniqueNodes([...seeds, ...upstream.nodes, ...downstream.nodes]);
const relatedIds = new Set(relatedNodes.map(node => node.id));
const domainSet = new Set(relatedNodes.flatMap(node => node.domainIds || []));
const crossDomainRisks = domainSet.size > 1
? relatedNodes.filter(node => (node.domainIds || []).length > 1 || node.type === "domain")
: [];
const evidenceByKey = new Map();
for (const edge of [...upstream.evidence, ...downstream.evidence]) {
evidenceByKey.set(JSON.stringify(edge), edge);
}
const evidence = [...evidenceByKey.values()]
.sort((left, right) => JSON.stringify(left).localeCompare(JSON.stringify(right), "en"));
const relatedPaths = new Set(relatedNodes.map(node => node.path).filter(Boolean));
return {
seeds,
directMatches: seeds,
upstreamConsumers: upstream.nodes,
downstreamDependencies: downstream.nodes,
crossDomainRisks: uniqueNodes(crossDomainRisks),
testCandidates: collectLinkedType(graph, relatedIds, "coveredBy", "test"),
documents: collectLinkedType(graph, relatedIds, "documentedBy", "document"),
unresolved: graph.unresolved.filter(item => relatedPaths.has(item.path)),
evidence,
};
}
module.exports = {
queryImpact,
};
const fs = require("node:fs");
const path = require("node:path");
const fixtureRoot = path.resolve(__dirname, "__fixtures__/vue2-app");
const builderPath = path.resolve(__dirname, "build-knowledge-graph.js");
const queryPath = path.resolve(__dirname, "query-impact.js");
function loadModules() {
expect(fs.existsSync(builderPath)).toBe(true);
expect(fs.existsSync(queryPath)).toBe(true);
return {
...require(builderPath),
...require(queryPath),
};
}
describe("影响分析查询", () => {
it("应按固定结构返回上下游、跨域风险、测试和文档证据", () => {
const { buildKnowledgeGraph, queryImpact } = loadModules();
const graph = buildKnowledgeGraph({ rootDir: fixtureRoot });
const result = queryImpact(graph, {
keywords: ["listGoods"],
depth: 2,
direction: "both",
});
expect(Object.keys(result)).toEqual([
"seeds",
"directMatches",
"upstreamConsumers",
"downstreamDependencies",
"crossDomainRisks",
"testCandidates",
"documents",
"unresolved",
"evidence",
]);
expect(result.directMatches.some(item => item.id.includes("api/goods.js#listGoods"))).toBe(true);
expect(result.upstreamConsumers.some(item => item.id.includes("views/goods/list.vue"))).toBe(true);
expect(result.testCandidates.some(item => item.path === "tests/goods-list.spec.js")).toBe(true);
expect(result.documents.some(item => item.path === ".ai/docs/knowledge/903-product.md")).toBe(true);
expect(result.evidence.length).toBeGreaterThan(0);
});
it("无命中时应返回空集合而不是猜测结果", () => {
const { buildKnowledgeGraph, queryImpact } = loadModules();
const graph = buildKnowledgeGraph({ rootDir: fixtureRoot });
const result = queryImpact(graph, { keywords: ["not-exists"] });
expect(result.directMatches).toEqual([]);
expect(result.testCandidates).toEqual([]);
expect(result.evidence).toEqual([]);
});
});
const fs = require("node:fs");
const traverse = require("@babel/traverse").default;
const {
findProperty,
locationOf,
objectEntries,
parseJavaScript,
staticPrimitive,
} = require("./ast-utils");
const { relativePath, resolveView } = require("./path-utils");
function routeNodeId(authId) {
return `route:${authId}`;
}
function addPermission(store, authNode, routeId, filePath, context) {
if (!authNode || authNode.type !== "ObjectExpression") {
return;
}
const authId = staticPrimitive(findProperty(authNode, "authId")?.value, context.constants);
if (authId === null) {
return;
}
const permissionId = `permission:${authId}`;
const label = staticPrimitive(findProperty(authNode, "label")?.value, context.constants);
const handle = staticPrimitive(findProperty(authNode, "handle")?.value, context.constants);
store.addNode({
id: permissionId,
type: "permission",
name: label || String(authId),
path: filePath,
meta: {
authId: String(authId),
handle: handle || null,
},
});
store.addEdge({
from: routeId,
to: permissionId,
type: "requiresPermission",
evidence: locationOf(authNode, filePath),
});
if (context.currentRouterModuleId) {
store.addEdge({
from: context.currentRouterModuleId,
to: permissionId,
type: "declares",
evidence: locationOf(authNode, filePath),
});
}
const linkedRoutes = findProperty(authNode, "addRoutePath")?.value;
if (linkedRoutes?.type === "ArrayExpression") {
for (const item of linkedRoutes.elements) {
const linkedAuthId = staticPrimitive(findProperty(item, "authId")?.value, context.constants);
const linkedName = staticPrimitive(findProperty(item, "name")?.value, context.constants);
context.pendingRouteLinks.push({
from: permissionId,
authId: linkedAuthId === null ? null : String(linkedAuthId),
name: linkedName,
evidence: locationOf(item, filePath),
});
}
}
}
function scanRouterFile(rootDir, filePath, store, context) {
const source = fs.readFileSync(`${rootDir}/${filePath}`, "utf8");
const sourceId = `module:${filePath}`;
store.addNode({ id: sourceId, type: "module", name: filePath.split("/").pop(), path: filePath });
context.currentRouterModuleId = sourceId;
let ast;
try {
ast = parseJavaScript(source, filePath);
} catch (error) {
store.addUnresolved({
kind: "parse",
path: filePath,
reason: error.reasonCode || "syntax-error",
expressionKind: "Program",
});
return;
}
traverse(ast, {
VariableDeclarator(path) {
if (path.node.id.type === "Identifier") {
const value = staticPrimitive(path.node.init, context.constants);
if (value !== null) {
context.constants.set(path.node.id.name, value);
}
}
if (path.node.id.type !== "Identifier" || path.node.id.name !== "routerName") {
return;
}
for (const routeEntry of objectEntries(path.node.init)) {
const routeObject = routeEntry.value;
if (routeObject.type !== "ObjectExpression") {
continue;
}
const authId = String(routeEntry.name);
const routeId = routeNodeId(authId);
const routePath = staticPrimitive(findProperty(routeObject, "path")?.value, context.constants);
const routeName = staticPrimitive(findProperty(routeObject, "name")?.value, context.constants);
const metaNode = findProperty(routeObject, "meta")?.value;
const title = staticPrimitive(findProperty(metaNode, "title")?.value, context.constants);
const parentId = staticPrimitive(findProperty(metaNode, "parentId")?.value, context.constants);
store.addNode({
id: routeId,
type: "route",
name: routeName || title || authId,
path: filePath,
meta: {
authId,
parentId: parentId === null ? null : String(parentId),
routeName,
routePath,
title,
},
});
store.addEdge({
from: sourceId,
to: routeId,
type: "declares",
evidence: locationOf(routeEntry.node, filePath),
});
context.routesByAuthId.set(authId, routeId);
if (routeName) {
context.routesByName.set(String(routeName), routeId);
}
if (routePath) {
context.routesByPath.set(String(routePath), routeId);
}
const domainId = filePath.match(/modules\/(\d+)_/)?.[1];
if (domainId) {
store.addEdge({
from: `domain:${domainId}`,
to: routeId,
type: "contains",
evidence: locationOf(routeEntry.node, filePath),
});
}
if (parentId !== null && context.routesByAuthId.has(String(parentId))) {
store.addEdge({
from: context.routesByAuthId.get(String(parentId)),
to: routeId,
type: "contains",
evidence: locationOf(metaNode, filePath),
});
}
const componentCall = findProperty(routeObject, "component")?.value;
if (componentCall?.type === "CallExpression") {
const importPath = staticPrimitive(componentCall.arguments[0], context.constants);
if (typeof importPath === "string") {
const absoluteView = resolveView(rootDir, importPath);
if (absoluteView) {
const viewPath = relativePath(rootDir, absoluteView);
context.routeViewPaths.add(viewPath);
store.addNode({
id: `view:${viewPath}`,
type: "view",
name: routeName || importPath,
path: viewPath,
});
store.addEdge({
from: routeId,
to: `view:${viewPath}`,
type: "renders",
evidence: locationOf(componentCall, filePath),
});
}
} else {
store.addUnresolved({
kind: "route-component",
path: filePath,
line: componentCall.loc?.start.line,
column: componentCall.loc?.start.column,
reason: "dynamic-expression",
expressionKind: componentCall.arguments[0]?.type || "Unknown",
});
}
}
const authArray = findProperty(routeObject, "auth")?.value;
if (authArray?.type === "ArrayExpression") {
authArray.elements.forEach(authNode => addPermission(store, authNode, routeId, filePath, context));
}
}
},
});
context.currentRouterModuleId = null;
}
function scanRouterInfrastructure(rootDir, filePath, store, context) {
const source = fs.readFileSync(`${rootDir}/${filePath}`, "utf8");
let ast;
try {
ast = parseJavaScript(source, filePath);
} catch (error) {
store.addUnresolved({
kind: "parse",
path: filePath,
reason: error.reasonCode || "syntax-error",
expressionKind: "Program",
});
return;
}
traverse(ast, {
ObjectExpression(objectPath) {
const routePath = staticPrimitive(findProperty(objectPath.node, "path")?.value, context.constants);
const routeName = staticPrimitive(findProperty(objectPath.node, "name")?.value, context.constants);
const componentCall = findProperty(objectPath.node, "component")?.value;
if (typeof routePath !== "string" || typeof routeName !== "string" || !componentCall) {
return;
}
const metaNode = findProperty(objectPath.node, "meta")?.value;
const authId = staticPrimitive(findProperty(metaNode, "authId")?.value, context.constants);
const routeId = authId === null ? `route:local:${routeName}` : routeNodeId(String(authId));
store.addNode({
id: routeId,
type: "route",
name: routeName,
path: filePath,
domainIds: authId === null ? [] : [String(authId).slice(0, 3)],
meta: {
authId: authId === null ? null : String(authId),
parentId: null,
routeName,
routePath,
title: staticPrimitive(findProperty(metaNode, "title")?.value, context.constants),
},
});
context.routesByName.set(routeName, routeId);
context.routesByPath.set(routePath, routeId);
if (authId !== null) {
context.routesByAuthId.set(String(authId), routeId);
}
const importPath = componentCall.type === "CallExpression"
? staticPrimitive(componentCall.arguments[0], context.constants)
: null;
if (typeof importPath === "string") {
const absoluteView = resolveView(rootDir, importPath);
if (absoluteView) {
const viewPath = relativePath(rootDir, absoluteView);
context.routeViewPaths.add(viewPath);
store.addNode({ id: `view:${viewPath}`, type: "view", name: routeName, path: viewPath });
store.addEdge({
from: routeId,
to: `view:${viewPath}`,
type: "renders",
evidence: locationOf(componentCall, filePath),
});
}
}
const authArray = findProperty(objectPath.node, "auth")?.value;
if (authArray?.type === "ArrayExpression") {
authArray.elements.forEach(authNode => addPermission(store, authNode, routeId, filePath, context));
}
objectPath.skip();
},
});
}
function finalizeRouteLinks(store, context) {
for (const link of context.pendingRouteLinks) {
const target = (link.authId && context.routesByAuthId.get(link.authId))
|| (link.name && context.routesByName.get(String(link.name)));
if (target) {
store.addEdge({
from: link.from,
to: target,
type: "linksRoute",
evidence: link.evidence,
});
} else {
store.addUnresolved({
kind: "route-link",
path: link.evidence.path,
line: link.evidence.line,
column: link.evidence.column,
reason: "missing-target",
expressionKind: "addRoutePath",
});
}
}
}
module.exports = {
finalizeRouteLinks,
routeNodeId,
scanRouterInfrastructure,
scanRouterFile,
};
......@@ -208,7 +208,8 @@ export function queryMarketTransferFee(data) {
// 市场费转账-收款账户
export function getMarketTransferBankAccounts(data) {
data.method = "dj.api.smartcarlife.merchantBankEnterpriseAccount.listWithPage";
// data.method = "dj.api.smartcarlife.merchantBankEnterpriseAccount.listWithPage";
data.method = "dj.api.smartcarlife.merchantBankEnterpriseAccount.listBankAccount";
return request(data, "post");
}
......
......@@ -3,7 +3,7 @@ import { getTemplateTypeByTabKey } from "@/views/residentManage/journalRecord/co
/**
* d2-table 查询参数 → dailyReport.overview.page 请求体
*/
export function buildOverviewParams(params = {}, activeTabKey = "staffDaily") {
export function buildOverviewParams(params = {}, activeTabKey = "storeDaily") {
const payload = {
templateType: getTemplateTypeByTabKey(activeTabKey),
reportDate: params.reportDate,
......
import { mapSceneType } from "./mapSceneType";
function normalizeContextList(value) {
if (Array.isArray(value)) {
return value;
}
if (value == null || value === "") {
return [];
}
return String(value).split(",").filter(Boolean);
}
function resolveBusinessValue(...values) {
const value = values.find(item => item != null && item !== "");
return value ?? "";
}
/**
* 详情路由 query → dailyReport.detail.select 请求体
*/
......@@ -11,25 +26,42 @@ export function buildDetailSelectParams({ id } = {}) {
* dailyReport.detail.select 响应 → 详情页 detail 对象
*/
export function mapDetailResponse(res = {}, fallback = {}) {
const scene = mapSceneType(res.sceneType ?? fallback.sceneType);
const sceneType = res.sceneType ?? fallback.sceneType;
const sceneContext = {
baseSceneCode: res.baseSceneCode ?? fallback.baseSceneCode,
sceneList: res.sceneList ?? fallback.sceneList,
};
const preciseScene = mapSceneType(undefined, sceneContext);
const legacyScene = mapSceneType(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,
templateType: res.templateType ?? fallback.templateType,
bizType: resolveBusinessValue(
res.bizType,
preciseScene.bizType,
fallback.bizType,
legacyScene.bizType,
),
bizTypeName: resolveBusinessValue(
res.bizTypeName,
preciseScene.bizTypeName,
fallback.bizTypeName,
legacyScene.bizTypeName,
),
reportDate: res.reportDate ?? fallback.reportDate,
jsonContent: res.jsonContent,
fieldDataList: res.fieldDataList,
subformDataList: res.subformDataList,
reportTemplateId: res.reportTemplateId,
baseSceneCode: res.baseSceneCode,
sceneType: res.sceneType ?? fallback.sceneType,
baseSceneCode: sceneContext.baseSceneCode,
sceneType,
schema: res.schema,
brandIds: res.brandIds ?? fallback.brandIds ?? [],
sceneList: res.sceneList ?? fallback.sceneList ?? [],
brandIds: normalizeContextList(res.brandIds ?? fallback.brandIds),
sceneList: sceneContext.sceneList ?? [],
};
}
......
export function mapMerchantBrandContext(res = {}, merchantId) {
const list = Array.isArray(res.list) ? res.list : [];
const merchant = list.find(item => String(item.merchantId) === String(merchantId));
if (!merchant || !Array.isArray(merchant.merchantBrandList)) {
return [];
}
return merchant.merchantBrandList
.map(item => item.childId ?? item.brandId)
.filter(id => id != null && id !== "");
}
export default mapMerchantBrandContext;
import { mapSceneType } from "./mapSceneType";
import { collectSceneCodes, mapSceneType } from "./mapSceneType";
/**
* dailyReport.overview.page 行数据 → 表格行
*/
export function mapOverviewRow(row = {}) {
const scene = mapSceneType(row.sceneType);
const scene = mapSceneType(row.sceneType, row);
const reportStatus = row.reportStatus;
const createdDate = row.createdDate ?? row.lastSaveTime ?? row.updatedDate;
let baseSceneCode = row.baseSceneCode;
if (!collectSceneCodes(baseSceneCode).length) {
const sceneListCodes = collectSceneCodes(row.sceneList);
baseSceneCode = sceneListCodes.length ? sceneListCodes : undefined;
}
return {
id: row.id ?? row.dailyReportRecordId,
......@@ -19,9 +24,13 @@ export function mapOverviewRow(row = {}) {
attendanceStatus: row.onBreak ?? row.attendanceStatus ?? row.attendanceStatusName,
staffCount: row.staffCount,
lastSaveTime: createdDate,
submitTime: reportStatus === 1 ? (row.submitTime ?? createdDate) : (row.submitTime || ""),
submissionDate: row.submissionDate,
reportDate: row.reportDate,
templateType: row.templateType,
baseSceneCode,
sceneType: row.sceneType,
brandIds: row.brandIds,
sceneList: row.sceneList,
reportStatus,
};
}
......
/**
* 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) {
const SCENE_CODE_MAP = {
100101: { bizType: 1, bizTypeName: "轻改" },
100102: { bizType: 1, bizTypeName: "轻改" },
100103: { bizType: 1, bizTypeName: "轻改" },
110101: { bizType: 2, bizTypeName: "权益" },
110102: { bizType: 2, bizTypeName: "权益" },
110201: { bizType: "延保", bizTypeName: "延保" },
110202: { bizType: "延保", bizTypeName: "延保" },
};
export function collectSceneCodes(value) {
const codes = [];
const append = (item) => {
if (Array.isArray(item)) {
item.forEach(append);
return;
}
if (item && typeof item === "object") {
append(item.baseSceneCode);
return;
}
if (typeof item === "string") {
item.split(",").forEach((code) => {
const trimmedCode = code.trim();
if (trimmedCode) {
codes.push(trimmedCode);
}
});
return;
}
if (item != null) {
codes.push(item);
}
};
append(value);
return codes;
}
/**
* Swagger sceneType(0:权益,1:轻改)→ 页面 bizType / bizTypeName
*/
export function mapSceneType(sceneType, context = {}) {
const sceneByCode = collectSceneCodes([context.baseSceneCode, context.sceneList])
.map(code => SCENE_CODE_MAP[code])
.find(Boolean);
if (sceneByCode) {
return sceneByCode;
}
if (sceneType == null || sceneType === "") {
return { bizType: "", bizTypeName: "" };
}
......
{
"method": "dj.api.smartcarlife.MerchantGoodsStockMonthReport.stockMove",
"route": "/router/dj.api.smartcarlife.MerchantGoodsStockMonthReport.stockMove/1.0.0",
"summary": "单产品库存移动",
"request": {
"parameters": [
{
"name": "upgradeGoodsId",
"in": "query",
"type": "int",
"required": false,
"description": "旧产品ID(dj_car_life_upgrade_goods.id)"
},
{
"name": "yqMerchantId",
"in": "query",
"type": "int",
"required": false,
"description": "园区店商户号"
},
{
"name": "targetUpgradeGoodsId",
"in": "query",
"type": "int",
"required": false,
"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": "boolean",
"description": "成功返回数据",
"required": false
}
],
"pagination": null,
"rootType": "RopResponse<Boolean>"
}
}
# dj.api.smartcarlife.MerchantGoodsStockMonthReport.stockMove
> 单产品库存移动
## Request
| 参数 | 位置 | 类型 | 必填 | 说明 |
|------|------|------|------|------|
| upgradeGoodsId | query | int | 否 | 旧产品ID(dj_car_life_upgrade_goods.id) |
| yqMerchantId | query | int | 否 | 园区店商户号 |
| targetUpgradeGoodsId | query | int | 否 | 新产品ID |
| sessionId | query | string | 是 | 会话ID |
## Response
| 字段 | 类型 | 说明 |
|------|------|------|
| code | string | 响应状态(0:成功;1:失败) |
| errId | string | 错误码 |
| message | string | 错误描述 |
| data | boolean | 成功返回数据 |
{
"method": "dj.api.smartcarlife.MerchantGoodsStockMonthReport.stockMove.import",
"route": "/router/dj.api.smartcarlife.MerchantGoodsStockMonthReport.stockMove.import/1.0.0",
"summary": "移动库存批量导入",
"request": {
"parameters": [
{
"name": "file.fileType",
"in": "query",
"type": "string",
"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": "string",
"description": "成功返回数据",
"required": false
}
],
"pagination": null,
"rootType": "RopResponse<String>"
}
}
# dj.api.smartcarlife.MerchantGoodsStockMonthReport.stockMove.import
> 移动库存批量导入
## Request
| 参数 | 位置 | 类型 | 必填 | 说明 |
|------|------|------|------|------|
| file.fileType | query | string | 否 | |
| sessionId | query | string | 是 | 会话ID |
## Response
| 字段 | 类型 | 说明 |
|------|------|------|
| code | string | 响应状态(0:成功;1:失败) |
| errId | string | 错误码 |
| message | string | 错误描述 |
| data | string | 成功返回数据 |
{
"method": "dj.api.smartcarlife.MerchantGoodsStockMonthReport.stockMove.log.page",
"route": "/router/dj.api.smartcarlife.MerchantGoodsStockMonthReport.stockMove.log.page/1.0.0",
"summary": "移动库存日志分页查询",
"request": {
"parameters": [
{
"name": "upgradeGoodsId",
"in": "query",
"type": "int",
"required": false,
"description": "旧产品ID(仅匹配旧UID)"
},
{
"name": "yqMerchantId",
"in": "query",
"type": "int",
"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": "RpcPagination<MerchantGoodsStockMoveLogResponse>",
"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<MerchantGoodsStockMoveLogResponse>",
"description": "",
"required": false
},
{
"name": "data.condition",
"type": "MerchantGoodsStockMoveLogResponse",
"description": "",
"required": false
},
{
"name": "data.needCount",
"type": "boolean",
"description": "",
"required": false
}
],
"pagination": {
"wrapper": "RopResponse<RpcPagination<MerchantGoodsStockMoveLogResponse>>",
"type": "RpcPagination<MerchantGoodsStockMoveLogResponse>",
"fields": [
"pageNum",
"pageSize",
"total",
"list"
]
},
"rootType": "RopResponse<RpcPagination<MerchantGoodsStockMoveLogResponse>>"
}
}
# dj.api.smartcarlife.MerchantGoodsStockMonthReport.stockMove.log.page
> 移动库存日志分页查询
## Request
| 参数 | 位置 | 类型 | 必填 | 说明 |
|------|------|------|------|------|
| upgradeGoodsId | query | int | 否 | 旧产品ID(仅匹配旧UID) |
| yqMerchantId | query | int | 否 | 园区店商户号 |
| sessionId | query | string | 是 | 会话ID |
## Response
分页: `RpcPagination<MerchantGoodsStockMoveLogResponse>` (pageNum, pageSize, total, list)
| 字段 | 类型 | 说明 |
|------|------|------|
| code | string | 响应状态(0:成功;1:失败) |
| errId | string | 错误码 |
| message | string | 错误描述 |
| data | RpcPagination<MerchantGoodsStockMoveLogResponse> | 成功返回数据 |
| 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<MerchantGoodsStockMoveLogResponse> | |
| data.condition | MerchantGoodsStockMoveLogResponse | |
| data.needCount | boolean | |
{
"method": "dj.api.smartcarlife.MerchantGoodsStockMonthReport.stockMove.template.export",
"route": "/router/dj.api.smartcarlife.MerchantGoodsStockMonthReport.stockMove.template.export/1.0.0",
"summary": "移动库存导入模版下载",
"request": {
"parameters": [
{
"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": "string",
"description": "成功返回数据",
"required": false
}
],
"pagination": null,
"rootType": "RopResponse<String>"
}
}
# dj.api.smartcarlife.MerchantGoodsStockMonthReport.stockMove.template.export
> 移动库存导入模版下载
## Request
| 参数 | 位置 | 类型 | 必填 | 说明 |
|------|------|------|------|------|
| sessionId | query | string | 是 | 会话ID |
## Response
| 字段 | 类型 | 说明 |
|------|------|------|
| code | string | 响应状态(0:成功;1:失败) |
| errId | string | 错误码 |
| message | string | 错误描述 |
| data | string | 成功返回数据 |
{
"method": "dj.api.smartcarlife.productManager.listUpgradeGoodsSimple",
"route": "/router/dj.api.smartcarlife.productManager.listUpgradeGoodsSimple/1.0.0",
"summary": "分页查询产品(轻改/权益延保)",
"request": {
"parameters": [
{
"name": "currentPage",
"in": "query",
"type": "integer",
"required": false,
"description": "当前页码"
},
{
"name": "pageSize",
"in": "query",
"type": "integer",
"required": false,
"description": "每页条数"
},
{
"name": "commodityCode",
"in": "query",
"type": "string",
"required": false,
"description": "UID(产品编码,模糊查询)对应commodity_code"
},
{
"name": "productType",
"in": "query",
"type": "byte",
"required": false,
"description": "产品类型 1-轻改 2-权益、延保"
},
{
"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<UpgradeGoodsDTO>",
"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<UpgradeGoodsDTO>",
"description": "",
"required": false
},
{
"name": "data.condition",
"type": "UpgradeGoodsDTO",
"description": "",
"required": false
},
{
"name": "data.needCount",
"type": "boolean",
"description": "",
"required": false
}
],
"pagination": {
"wrapper": "RopResponse<RpcPagination<UpgradeGoodsDTO>>",
"type": "RpcPagination<UpgradeGoodsDTO>",
"fields": [
"pageNum",
"pageSize",
"total",
"list"
]
},
"rootType": "RopResponse<RpcPagination<UpgradeGoodsDTO>>"
}
}
# dj.api.smartcarlife.productManager.listUpgradeGoodsSimple
> 分页查询产品(轻改/权益延保)
## Request
| 参数 | 位置 | 类型 | 必填 | 说明 |
|------|------|------|------|------|
| currentPage | query | integer | 否 | 当前页码 |
| pageSize | query | integer | 否 | 每页条数 |
| commodityCode | query | string | 否 | UID(产品编码,模糊查询)对应commodity_code |
| productType | query | byte | 否 | 产品类型 1-轻改 2-权益、延保 |
| sessionId | query | string | 是 | 会话ID |
## Response
分页: `RpcPagination<UpgradeGoodsDTO>` (pageNum, pageSize, total, list)
| 字段 | 类型 | 说明 |
|------|------|------|
| code | string | 响应状态(0:成功;1:失败) |
| errId | string | 错误码 |
| message | string | 错误描述 |
| data | RpcPagination<UpgradeGoodsDTO> | 成功返回数据 |
| 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<UpgradeGoodsDTO> | |
| data.condition | UpgradeGoodsDTO | |
| data.needCount | boolean | |
/* eslint-disable jsdoc/require-property-description, jsdoc/require-returns-description */
/**
* @typedef {Object} LogPageParams
* @property {number} upgradeGoodsId [optional] - 旧产品ID(仅匹配旧UID)
* @property {number} yqMerchantId [optional] - 园区店商户号
*/
/**
* @typedef {Object} LogPageRow
* @property {string} errId - 错误码
* @property {string} data - 成功返回数据
*/
/**
* @typedef {Object} LogPagePageResponse
* @property {number} [pageNum]
* @property {number} [pageSize]
* @property {number} [total]
* @property {LogPageRow[]} [list]
*/
/**
* UI/表格参数 → dj.api.smartcarlife.MerchantGoodsStockMonthReport.stockMove.log.page 请求体
* @param {LogPageParams} [params]
* @returns {LogPageParams}
* @see __contracts__/dj_api_smartcarlife_MerchantGoodsStockMonthReport_stockMove_log_page.contract.md
*/
export function buildLogPageParams(params = {}) {
const payload = {};
if (params.upgradeGoodsId != null && params.upgradeGoodsId !== "") {
payload.upgradeGoodsId = params.upgradeGoodsId;
}
if (params.yqMerchantId != null && params.yqMerchantId !== "") {
payload.yqMerchantId = params.yqMerchantId;
}
return payload;
}
export default buildLogPageParams;
/* eslint-disable jsdoc/require-returns-description */
/**
* @typedef {Object} MerchantGoodsStockMonthReportStockMoveParams
* @property {number} upgradeGoodsId [optional] - 旧产品ID(dj_car_life_upgrade_goods.id)
* @property {number} yqMerchantId [optional] - 园区店商户号
* @property {number} targetUpgradeGoodsId [optional] - 新产品ID
*/
/**
* @typedef {Object} MerchantGoodsStockMonthReportStockMoveRow
* @property {string} errId - 错误码
* @property {boolean} data - 成功返回数据
*/
/**
* UI/表格参数 → dj.api.smartcarlife.MerchantGoodsStockMonthReport.stockMove 请求体
* @param {MerchantGoodsStockMonthReportStockMoveParams} [params]
* @returns {MerchantGoodsStockMonthReportStockMoveParams}
* @see __contracts__/dj_api_smartcarlife_MerchantGoodsStockMonthReport_stockMove.contract.md
*/
export function buildMerchantGoodsStockMonthReportStockMoveParams(params = {}) {
const payload = {};
if (params.upgradeGoodsId != null && params.upgradeGoodsId !== "") {
payload.upgradeGoodsId = params.upgradeGoodsId;
}
if (params.yqMerchantId != null && params.yqMerchantId !== "") {
payload.yqMerchantId = params.yqMerchantId;
}
if (params.targetUpgradeGoodsId != null && params.targetUpgradeGoodsId !== "") {
payload.targetUpgradeGoodsId = params.targetUpgradeGoodsId;
}
return payload;
}
export default buildMerchantGoodsStockMonthReportStockMoveParams;
/* eslint-disable jsdoc/require-property-description, jsdoc/require-returns-description */
/**
* @typedef {Object} ProductManagerListUpgradeGoodsSimpleParams
* @property {number} currentPage [optional] - 当前页码
* @property {number} pageSize [optional] - 每页条数
* @property {string} commodityCode [optional] - UID(产品编码,模糊查询)对应commodity_code
* @property {string} productType [optional] - 产品类型 1-轻改 2-权益、延保
*/
/**
* @typedef {Object} ProductManagerListUpgradeGoodsSimpleRow
* @property {string} errId - 错误码
* @property {string} data - 成功返回数据
*/
/**
* @typedef {Object} ProductManagerListUpgradeGoodsSimplePageResponse
* @property {number} [pageNum]
* @property {number} [pageSize]
* @property {number} [total]
* @property {ProductManagerListUpgradeGoodsSimpleRow[]} [list]
*/
/**
* UI/表格参数 → dj.api.smartcarlife.productManager.listUpgradeGoodsSimple 请求体
* @param {ProductManagerListUpgradeGoodsSimpleParams} [params]
* @returns {ProductManagerListUpgradeGoodsSimpleParams}
* @see __contracts__/dj_api_smartcarlife_productManager_listUpgradeGoodsSimple.contract.md
*/
export function buildProductManagerListUpgradeGoodsSimpleParams(params = {}) {
const payload = {};
if (params.currentPage != null && params.currentPage !== "") {
payload.currentPage = params.currentPage;
}
if (params.pageSize != null && params.pageSize !== "") {
payload.pageSize = params.pageSize;
}
if (params.commodityCode != null && params.commodityCode !== "") {
payload.commodityCode = params.commodityCode;
}
if (params.productType != null && params.productType !== "") {
payload.productType = params.productType;
}
return payload;
}
export default buildProductManagerListUpgradeGoodsSimpleParams;
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!