Commit 0b071352 by 张立顺

feat 知识图谱功能

1 parent 0af7941a
Pipeline #227 for 0b071352 failed in 0 seconds
Showing 49 changed files with 2744 additions and 18 deletions
...@@ -2,8 +2,8 @@ ...@@ -2,8 +2,8 @@
## 问题页面 ## 问题页面
- [`src/views/orderManage/order.vue`](../src/views/orderManage/order.vue)(1.1 精品升级) - [`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/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
...@@ -8,6 +8,7 @@ ...@@ -8,6 +8,7 @@
- /.ai/rules/ESLINT.md(代码格式,生成代码必遵) - /.ai/rules/ESLINT.md(代码格式,生成代码必遵)
- ROP 聊天导入:/.ai/skills/rop-api-import/SKILL.md、/.ai/docs/ROP_CHAT_IMPORT.md - ROP 聊天导入:/.ai/skills/rop-api-import/SKILL.md、/.ai/docs/ROP_CHAT_IMPORT.md
- 开发性能 / Element 主题预研:/.ai/docs/DEV_PERF_AND_THEME_RESEARCH.md - 开发性能 / Element 主题预研:/.ai/docs/DEV_PERF_AND_THEME_RESEARCH.md
- 需求影响分析:/.ai/skills/requirement-impact-analysis/SKILL.md、/.ai/generated/knowledge-graph.json
## 项目概述 ## 项目概述
...@@ -84,6 +85,10 @@ src/ ...@@ -84,6 +85,10 @@ src/
## 编码原则 ## 编码原则
### 需求影响分析
分析需求、评估改动范围或制定实施计划时,先按 `.ai/skills/requirement-impact-analysis/SKILL.md` 查询知识图谱,再结合源码输出“必改、可能波及、明确不改”。静态邻接只表示需要核对,不得直接判定为必改。发现图谱漂移或未解析关系时必须显式说明。
### 优先遵循现有代码风格 ### 优先遵循现有代码风格
修改代码时: 修改代码时:
...@@ -181,3 +186,12 @@ export default {}; ...@@ -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 # 嘀加智享车生活后台 http://192.168.3.233:8090/saas_plus/dj-car-life-system
## node 版本 ## node 版本
14.21.3 20.19.0
## 包管理工具 ## 包管理工具
npm 6.14.8 npm 10.8.2
## AI 相关 ## AI 相关
* 项目忽略所有AI相关文件. 不要提交如 CLAUDE.md 等文件. * 项目忽略所有AI相关文件. 不要提交如 CLAUDE.md 等文件.
...@@ -33,3 +33,179 @@ ...@@ -33,3 +33,179 @@
测试环境账号 15816539335 a123456(超管) 测试环境账号 15816539335 a123456(超管)
aa123456 aa123456 (园区店) aa123456 aa123456 (园区店)
bb123456 bb123456 (服务商) 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
}
]
}
...@@ -33,6 +33,9 @@ module.exports = { ...@@ -33,6 +33,9 @@ module.exports = {
"**/*.integration.spec.js", "**/*.integration.spec.js",
"tests/**/*.spec.js", "tests/**/*.spec.js",
], ],
testPathIgnorePatterns: [
"/scripts/knowledge-graph/__fixtures__/",
],
testURL: "http://localhost/", testURL: "http://localhost/",
testEnvironment: "jsdom", testEnvironment: "jsdom",
setupFiles: ["<rootDir>/jest.setup.js"], setupFiles: ["<rootDir>/jest.setup.js"],
......
...@@ -56,8 +56,10 @@ ...@@ -56,8 +56,10 @@
"devDependencies": { "devDependencies": {
"@antfu/eslint-config": "^6.7.3", "@antfu/eslint-config": "^6.7.3",
"@babel/core": "^7.12.16", "@babel/core": "^7.12.16",
"@babel/parser": "7.29.7",
"@babel/plugin-proposal-nullish-coalescing-operator": "^7.17.12", "@babel/plugin-proposal-nullish-coalescing-operator": "^7.17.12",
"@babel/plugin-proposal-optional-chaining": "7.13.12", "@babel/plugin-proposal-optional-chaining": "7.13.12",
"@babel/traverse": "7.29.7",
"@kazupon/vue-i18n-loader": "^0.4.1", "@kazupon/vue-i18n-loader": "^0.4.1",
"@playwright/test": "^1.39.0", "@playwright/test": "^1.39.0",
"@vue/babel-helper-vue-jsx-merge-props": "^1.4.0", "@vue/babel-helper-vue-jsx-merge-props": "^1.4.0",
...@@ -19434,7 +19436,8 @@ ...@@ -19434,7 +19436,8 @@
"node_modules/picocolors": { "node_modules/picocolors": {
"version": "1.1.1", "version": "1.1.1",
"resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",
"integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==" "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==",
"dev": true
}, },
"node_modules/picomatch": { "node_modules/picomatch": {
"version": "4.0.4", "version": "4.0.4",
...@@ -19590,6 +19593,7 @@ ...@@ -19590,6 +19593,7 @@
"version": "8.5.16", "version": "8.5.16",
"resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.16.tgz", "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.16.tgz",
"integrity": "sha512-vuwillviilfKZsg0VGj5R/YwwcHx4SLsIOI/7K6mQkWx+l5cUHTjj5g0AasTBcyXsbfTgrwsUNmVUb5xVwyPwg==", "integrity": "sha512-vuwillviilfKZsg0VGj5R/YwwcHx4SLsIOI/7K6mQkWx+l5cUHTjj5g0AasTBcyXsbfTgrwsUNmVUb5xVwyPwg==",
"dev": true,
"funding": [ "funding": [
{ {
"type": "opencollective", "type": "opencollective",
...@@ -20840,6 +20844,7 @@ ...@@ -20840,6 +20844,7 @@
"version": "3.3.15", "version": "3.3.15",
"resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.15.tgz", "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.15.tgz",
"integrity": "sha512-y7Wygv/7mEOvxTuEQDB8StXdMRBWf1kR/tlhAzBRUFkB2jfcLOAxO/SHmOO2zgz1pVgK29/kyupn059/bCHdjA==", "integrity": "sha512-y7Wygv/7mEOvxTuEQDB8StXdMRBWf1kR/tlhAzBRUFkB2jfcLOAxO/SHmOO2zgz1pVgK29/kyupn059/bCHdjA==",
"dev": true,
"funding": [ "funding": [
{ {
"type": "github", "type": "github",
...@@ -22621,6 +22626,7 @@ ...@@ -22621,6 +22626,7 @@
"version": "1.2.1", "version": "1.2.1",
"resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz", "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz",
"integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==", "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==",
"dev": true,
"engines": { "engines": {
"node": ">=0.10.0" "node": ">=0.10.0"
} }
......
...@@ -17,7 +17,12 @@ ...@@ -17,7 +17,12 @@
"rop:import": "node scripts/rop-import.js", "rop:import": "node scripts/rop-import.js",
"rop:verify": "npm run test:unit -- tests/unit/libs/rop tests/unit/api/adapters/journalRecord && npm run rop:contract:check && npm run api:smoke:journal", "rop:verify": "npm run test:unit -- tests/unit/libs/rop tests/unit/api/adapters/journalRecord && npm run rop:contract:check && npm run api:smoke:journal",
"report": "set NODE_OPTIONS=--openssl-legacy-provider && vue-cli-service build --report", "report": "set NODE_OPTIONS=--openssl-legacy-provider && vue-cli-service build --report",
"test:unit": "vue-cli-service test:unit" "test:unit": "vue-cli-service test:unit",
"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": { "dependencies": {
"ali-oss": "^6.22.0", "ali-oss": "^6.22.0",
...@@ -68,8 +73,10 @@ ...@@ -68,8 +73,10 @@
"devDependencies": { "devDependencies": {
"@antfu/eslint-config": "^6.7.3", "@antfu/eslint-config": "^6.7.3",
"@babel/core": "^7.12.16", "@babel/core": "^7.12.16",
"@babel/parser": "7.29.7",
"@babel/plugin-proposal-nullish-coalescing-operator": "^7.17.12", "@babel/plugin-proposal-nullish-coalescing-operator": "^7.17.12",
"@babel/plugin-proposal-optional-chaining": "7.13.12", "@babel/plugin-proposal-optional-chaining": "7.13.12",
"@babel/traverse": "7.29.7",
"@kazupon/vue-i18n-loader": "^0.4.1", "@kazupon/vue-i18n-loader": "^0.4.1",
"@playwright/test": "^1.39.0", "@playwright/test": "^1.39.0",
"@vue/babel-helper-vue-jsx-merge-props": "^1.4.0", "@vue/babel-helper-vue-jsx-merge-props": "^1.4.0",
...@@ -98,6 +105,7 @@ ...@@ -98,6 +105,7 @@
"webpack": "^5.74.0" "webpack": "^5.74.0"
}, },
"volta": { "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,
};
...@@ -24,7 +24,7 @@ export function mapOverviewRow(row = {}) { ...@@ -24,7 +24,7 @@ export function mapOverviewRow(row = {}) {
attendanceStatus: row.onBreak ?? row.attendanceStatus ?? row.attendanceStatusName, attendanceStatus: row.onBreak ?? row.attendanceStatus ?? row.attendanceStatusName,
staffCount: row.staffCount, staffCount: row.staffCount,
lastSaveTime: createdDate, lastSaveTime: createdDate,
submitTime: reportStatus === 1 ? (row.submitTime ?? createdDate) : (row.submitTime || ""), submissionDate: row.submissionDate,
reportDate: row.reportDate, reportDate: row.reportDate,
templateType: row.templateType, templateType: row.templateType,
baseSceneCode, baseSceneCode,
......
jest.mock("@api/theAssetData", () => ({
batchPrinting: jest.fn(),
checkPermission: jest.fn(),
getImportTask: jest.fn(),
nbcbAccDetailBatchSync: jest.fn(),
nbcbAccDetailConfig: jest.fn(),
nbcbAccDetailPage: jest.fn(),
nbcbAccFinancialReportEmailConfig: jest.fn(),
nbcbAccFinancialReportEmailConfigSave: jest.fn(),
nbcbAccFinancialReportPush: jest.fn(),
nbcbReceiptPdfUrl: jest.fn(),
}), { virtual: true });
const TransferAccountsList = require("./index.vue").default;
describe("财资数据(广联)筛选布局", () => {
it("交易金额同列下方不再有筛选项", () => {
const componentData = TransferAccountsList.data.call({
$store: {
state: {
d2admin: {
user: {
info: {},
},
},
},
},
});
const transactionMoneyIndex = componentData.showFormData.findIndex(item => item.name === "transactionMoney");
const searchColumnCount = 3;
expect(componentData.showFormData[transactionMoneyIndex + searchColumnCount]).toBeUndefined();
});
});
...@@ -448,9 +448,11 @@ export default { ...@@ -448,9 +448,11 @@ export default {
optionLabel: "confValue", optionLabel: "confValue",
optionsName: "dataSourceOpt", optionsName: "dataSourceOpt",
}, { }, {
label: "交易金额", label: "财务报表口径",
name: "transactionMoney", name: "financialReportCaliber",
addHtml: "transactionMoneyHtml", type: "input",
maxlength: "20",
isClear: true,
}, { }, {
label: "用途", label: "用途",
name: "uses", name: "uses",
...@@ -462,11 +464,9 @@ export default { ...@@ -462,11 +464,9 @@ export default {
name: "accDetailTagPath", name: "accDetailTagPath",
addHtml: "accDetailTagHtml", addHtml: "accDetailTagHtml",
}, { }, {
label: "财务报表口径", label: "交易金额",
name: "financialReportCaliber", name: "transactionMoney",
type: "input", addHtml: "transactionMoneyHtml",
maxlength: "20",
isClear: true,
}], }],
getListApi: nbcbAccDetailPage, getListApi: nbcbAccDetailPage,
tableParams: { tableParams: {
......
...@@ -88,7 +88,7 @@ export const TABLE_COLUMNS_MAP = { ...@@ -88,7 +88,7 @@ export const TABLE_COLUMNS_MAP = {
formatter: row => (row.staffCount != null ? `${row.staffCount}人` : "—"), formatter: row => (row.staffCount != null ? `${row.staffCount}人` : "—"),
}, },
createDateTimeColumn("最近保存时间", "lastSaveTime"), createDateTimeColumn("最近保存时间", "lastSaveTime"),
createDateTimeColumn("提交时间", "submitTime"), createDateTimeColumn("上报时间", "submissionDate"),
createEmptyTextColumn("提交人", "staffName", { createEmptyTextColumn("提交人", "staffName", {
minWidth: "100px", minWidth: "100px",
width: "120px", width: "120px",
......
...@@ -8,12 +8,14 @@ describe("mapOverviewRow", () => { ...@@ -8,12 +8,14 @@ describe("mapOverviewRow", () => {
sceneType: "1", sceneType: "1",
onBreak: "在岗", onBreak: "在岗",
createdDate: "2026-07-16 10:00:00", createdDate: "2026-07-16 10:00:00",
submissionDate: "2026-07-16 11:30:00",
reportStatus: 1, reportStatus: 1,
}); });
expect(row.bizTypeName).toBe("轻改"); expect(row.bizTypeName).toBe("轻改");
expect(row.attendanceStatus).toBe("在岗"); expect(row.attendanceStatus).toBe("在岗");
expect(row.lastSaveTime).toBe("2026-07-16 10:00:00"); expect(row.lastSaveTime).toBe("2026-07-16 10:00:00");
expect(row.submitTime).toBe("2026-07-16 10:00:00"); expect(row.submissionDate).toBe("2026-07-16 11:30:00");
expect(row).not.toHaveProperty("submitTime");
}); });
it("sceneType 0 应映射为权益", () => { it("sceneType 0 应映射为权益", () => {
......
...@@ -16,4 +16,21 @@ describe("journalRecord constants", () => { ...@@ -16,4 +16,21 @@ describe("journalRecord constants", () => {
expect(getTabKeyByTemplateType(1)).toBe("storeDaily"); expect(getTabKeyByTemplateType(1)).toBe("storeDaily");
expect(getTabKeyByTemplateType(2)).toBe("storeDaily"); expect(getTabKeyByTemplateType(2)).toBe("storeDaily");
}); });
it("门店日报应显示上报时间并按最近保存时间格式处理", () => {
const timeColumns = TABLE_COLUMNS_MAP.storeDaily.filter(column => [
"最近保存时间",
"上报时间",
"提交时间",
].includes(column.label));
expect(timeColumns.map(({ label, prop }) => ({ label, prop }))).toEqual([
{ label: "最近保存时间", prop: "lastSaveTime" },
{ label: "上报时间", prop: "submissionDate" },
]);
const submissionColumn = timeColumns.find(column => column.prop === "submissionDate");
expect(submissionColumn.formatter({
submissionDate: "2026-08-14 09:05:37",
})).toBe("2026-08-14 09:05");
});
}); });
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!