Commit ea31538e by 张立顺

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

Feature/zls

See merge request !950
2 parents 49bd794f 818111af
Showing 92 changed files with 3287 additions and 310 deletions
# Journal Store Daily Only Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** Make `/journalRecord` store-daily-only, block retired report detail links before API access, and render the latest V2.3.0 `F2-101`–`F2-107` detail content correctly.
**Architecture:** Centralize allowed report-type decisions in a small pure helper used by list and detail pages. Keep `jsonContent` as the primary echo source, extend the current readonly normalizer for App object values, and replace the limited child-rule evaluator with the safe parser pattern already proven in the Mini Program.
**Tech Stack:** Vue 2 Options API, Vue Router 3, Element UI, Babel/Jest, JavaScript pure utilities.
## Global Constraints
- Only `storeDaily` / `templateType: 2` remains available.
- Retired or invalid detail types must not call `dailyReport.detail.select`.
- Do not use `eval` or `new Function` for `childrenShowRules`.
- Preserve the current API wrapper and readonly component structure; do not migrate the Mini Program form engine.
- Follow `.ai/rules/ESLINT.md`: double quotes, semicolons, tabs in scripts, and touched-file lint checks.
---
### Task 1: Restrict list and detail access to store daily
**Files:**
- Create: `src/views/residentManage/journalRecord/utils/journalAccess.js`
- Create: `src/views/residentManage/journalRecord/utils/journalAccess.spec.js`
- Modify: `src/views/residentManage/journalRecord/constants.js`
- Create: `src/views/residentManage/journalRecord/constants.spec.js`
- Modify: `src/views/residentManage/journalRecord/index.vue`
- Modify: `src/views/residentManage/journalRecord/detail.vue`
- Modify: `src/api/adapters/journalRecord/mapDetailResponse.js`
- Create: `src/api/adapters/journalRecord/mapDetailResponse.spec.js`
**Interfaces:**
- Produces: `STORE_DAILY_TAB_KEY`, `STORE_DAILY_TEMPLATE_TYPE`, `isStoreDailyJournalType(type)`, `normalizeJournalListQuery(query)`, and `isStoreDailyTemplateType(type)`.
- Consumes: route query and optional detail response `templateType`.
- [ ] **Step 1: Write pure access and constants tests**
Assert that only `{ key: "storeDaily", journalType: 2 }` remains, list queries normalize retired/invalid types to `storeDaily`, only `storeDaily` is allowed for details, and response template type `1/3` is rejected while `2` is accepted.
- [ ] **Step 2: Run focused tests and verify failure**
```powershell
npm run test:unit -- src/views/residentManage/journalRecord/utils/journalAccess.spec.js src/views/residentManage/journalRecord/constants.spec.js src/api/adapters/journalRecord/mapDetailResponse.spec.js
```
Expected: helper files/functions do not exist and constants still expose three tabs.
- [ ] **Step 3: Implement the pure access helper and reduce constants**
Create constants for `storeDaily` and `2`; normalize list query by returning a copy with `journalType: "storeDaily"`; validate details by exact key; treat a missing response `templateType` as compatible and a present non-2 value as incompatible. Remove retired tab columns/title branches/tracking entries and make template lookup fallback `2`.
- [ ] **Step 4: Make the list page store-daily-only**
Set `activeTab` to `storeDaily`, normalize old query parameters during initialization, keep merchant-only search and store-daily columns, and ensure detail navigation always writes `journalType: "storeDaily"`.
- [ ] **Step 5: Block retired detail links before API access and validate responses**
At the start of `fetchDetail`, reject any query type other than `storeDaily`, call `this.$message.warning("该汇报类型已停用")`, and `replace` the list route without invoking the API. After a successful response, apply the same redirect if a present `templateType` is not `2`. Add `templateType` to `mapDetailResponse`.
- [ ] **Step 6: Run focused access tests**
Run the Step 2 command. Expected: all selected tests pass.
### Task 2: Support the latest V2.3.0 child visibility expressions
**Files:**
- Modify: `src/views/residentManage/journalRecord/utils/journalFormVisibility/groupShowRuleEval.js`
- Create: `src/views/residentManage/journalRecord/utils/journalFormVisibility/groupShowRuleEval.spec.js`
- Modify: `src/views/residentManage/journalRecord/utils/journalFormVisibility/groupVisibility.js`
- Modify: `src/views/residentManage/journalRecord/utils/journalFormVisibility/index.js`
- Modify: `tests/unit/views/residentManage/journalRecord/journalFormVisibility.spec.js`
**Interfaces:**
- Consumes: `childrenShowRules.keys/result`, row fields, and detail context `{ sceneList, baseSceneCode, sceneType, brandIds }`.
- Produces: safe Boolean evaluation for comparisons, arrays, includes, unary NOT, AND/OR, parentheses, `$sceneCodes`, and `$brandIds`.
- [ ] **Step 1: Add failing parser and F2-107 integration tests**
Cover the real delivery-date expression with three inputs, tag rules such as `val1.includes('已触客')`, negated includes for `F2-107-17`, malformed syntax fail-closed, and context keys resolved as string arrays.
- [ ] **Step 2: Run focused visibility tests and verify failure**
```powershell
npm run test:unit -- src/views/residentManage/journalRecord/utils/journalFormVisibility/groupShowRuleEval.spec.js tests/unit/views/residentManage/journalRecord/journalFormVisibility.spec.js
```
Expected: the current split-on-`&&` evaluator cannot parse arrays, includes, OR, parentheses, or context keys.
- [ ] **Step 3: Port the safe tokenizer/parser pattern**
Replace the limited evaluator with a tokenizer and recursive-descent parser supporting only the approved grammar. Export `fallbackEvaluate` for direct tests; catch unsupported syntax and return `false`.
- [ ] **Step 4: Normalize rule values and inject detail context**
For object selections, resolve rule values through static option ID to option value/label, then fall back through `name`, `label`, `text`, `value`, and `id`. For arrays, normalize every item. Resolve `$sceneCodes` from effective detail scenes and `$brandIds` from detail brands, then pass context from `filterFieldNode` to `filterVisibleRowFields`.
- [ ] **Step 5: Run focused visibility tests**
Run the Step 2 command. Expected: all parser and F2-107 integration tests pass.
### Task 3: Render App object selections and representative V2.3.0 content
**Files:**
- Modify: `src/views/residentManage/journalRecord/utils/journalFormEcho.js`
- Create: `src/views/residentManage/journalRecord/utils/journalFormEcho.spec.js`
**Interfaces:**
- Consumes: App `origin_children + childrenValue` and values shaped as scalar, `{ text, value }`, or `{ id, name }`.
- Produces: sorted readonly blocks and subform cells with human-readable labels.
- [ ] **Step 1: Add a representative latest-store-detail fixture in the test**
Build a minimal `F2-101`–`F2-107` form list in the test, including `F2-107-7` with `optionsKey: "options"`, `{ id, name }` customer tags, a car object, and delivery-date/tag `childrenShowRules`. Assert top-level order, visible columns, hidden columns, and no `[object Object]` output.
- [ ] **Step 2: Run the echo test and verify failure**
```powershell
npm run test:unit -- src/views/residentManage/journalRecord/utils/journalFormEcho.spec.js
```
Expected: `{ id, name }` selections stringify as objects and dependent column assertions fail before Task 2/3 behavior is complete.
- [ ] **Step 3: Extend label-value formatting without changing data precedence**
Update object detection and display resolution to accept both object families. For multiple selection arrays, display `name/label/text`, fall back to matching static options, and join with `,`. Keep `jsonContent` primary and schema/fieldData fallback unchanged.
- [ ] **Step 4: Run echo and complete journal tests**
```powershell
npm run test:unit -- src/views/residentManage/journalRecord src/api/adapters/journalRecord tests/unit/views/residentManage/journalRecord tests/unit/api/adapters/journalRecord
```
Expected: all journal-related unit tests pass.
### Task 4: Lint, verify, and commit
**Files:**
- Verify all Task 1–3 files.
**Interfaces:**
- Produces: a reviewable backend commit with no unrelated changes.
- [ ] **Step 1: Run touched-file lint without relying on user fixes**
```powershell
npx eslint src/views/residentManage/journalRecord src/api/adapters/journalRecord/mapDetailResponse.js src/api/adapters/journalRecord/mapDetailResponse.spec.js
```
Expected: zero errors.
- [ ] **Step 2: Run the full unit suite**
```powershell
npm run test:unit -- --runInBand
```
Expected: zero failures.
- [ ] **Step 3: Inspect and commit the scoped diff**
Run `git diff --check`, verify only journal/access/adapter/tests/docs are staged, and commit:
```powershell
git commit -m "feat: 门店工作汇报仅保留门店日报"
```
# 门店工作汇报仅保留门店日报设计
## 目标
`/journalRecord` 只展示门店日报,禁止继续查看驻店日报和洽谈明细,并让最新 V2.3.0 门店日报 `F2-101~F2-107` 在详情页正常回显。
## 列表页
- `JOURNAL_TABS` 只保留 `{ key: "storeDaily", label: "门店日报", journalType: 2 }`。
- 页面默认且固定使用 `storeDaily`,列表请求固定传 `templateType: 2`。
- 页面不再呈现“驻店日报”和“洽谈明细”页签,也不再保留两类页签的列、搜索条件和埋点分支。
- 访问带旧 `journalType=staffDaily` 或 `journalType=negotiation` 的列表链接时,将查询参数规范为 `storeDaily`,进入可用的门店日报列表。
## 旧详情禁用
- 只有 `journalType=storeDaily` 的详情链接可以调用 `dailyReport.detail.select`。
- 直接访问 `staffDaily` / `negotiation` 详情链接时,在发起详情请求前拦截,提示“该汇报类型已停用”,然后 `replace` 回 `/journalRecord`。
- 缺少或非法 `journalType` 同样按不可用类型处理,不猜测详情类型。
- 详情响应若包含 `templateType`,必须为 `2`;否则不展示内容,提示已停用并返回列表。详情响应没有 `templateType` 时,依赖已校验的路由类型继续回显,兼容现有接口合同。
## 最新模板回显
详情仍以接口 `jsonContent` 为优先数据源,为空时才回退到 `schema.list + fieldDataList`。不在后台内置一份可能过期的 V2.3.0 模板。
### 子表单数据
- 支持 `children[0] + value`、`origin_children + childrenValue` 两种已使用的保存结构。
- `childrenValue` 中的 `{ [subformKey]: { [childKey]: value } }` 转换为只读表格需要的字段行。
- 子表单不从 `subformDataList` 重复组装;该列表仅作为接口存储数据,`jsonContent` 才是带字段元数据的主回显源。
### 值格式化
- `select` / `multipleSelect` 支持标量、`{ text, value }` 和 `{ id, name }`。
- 客户标签 `F2-107-7` 按 `name`、`label`、`text`、静态 options 的顺序取展示文案,不输出 `[object Object]`。
- 日期、数字单位、车型级联和文本保持现有格式化逻辑。
### 子字段显隐
扩展现有安全规则求值器,不使用 `eval` 或 `new Function`。语法与最新门店日报模板对齐:
- `valN == 'x'` / `valN != null`
- `Array.isArray(valN)`
- `valN.includes('x')`
- `!`、`&&`、`||` 和括号
- `keys` 中的 `$sceneCodes` 来自 `detail.sceneList[].baseSceneCode`,回退到 `baseSceneCode` 或 `sceneType`
- `$brandIds` 来自 `detail.brandIds`
求值失败时 fail-closed,对有规则的子字段不展示,并保留控制台错误便于排查。
## 验证
- 列表只有门店日报,请求 `templateType=2`。
- 旧列表链接归一为门店日报。
- 驻店日报/洽谈明细详情链接不发起详情请求,提示并返回列表。
- 响应 `templateType != 2` 时不展示。
- V2.3.0 顶层 `F2-101~F2-106` 按顺序显示。
- `F2-107` 每行的客户标签、车型、责任驻店等对象值显示人类可读文案。
- “实际交付日期”按场景、经营品牌和客户来源显隐。
- “已触客/已交付引荐”相关子字段与“未触客原因”按标签值显隐。
- 旧格式的门店日报回显不回归。
## 范围外
- 不删除后端的驻店日报或洽谈明细历史数据。
- 不调整后端接口权限或数据存储。
- 不把小程序整套动态表单引擎迁入 Vue 2 后台。
# 门店工作汇报需求对齐设计
## 目标
对齐 `/journalRecord` 门店日报列表与详情的已确认验收要求,修正时间和门店提示文案,补齐“延保”展示能力与详情场景上下文,并兼容开发环境最新版门店日报 `jsonContent` 的真实保存结构。
## 范围
本次处理以下内容:
1. 列表时间统一显示为 `YYYY-MM-DD HH:mm`,空值显示 `-`。
2. 门店选择框空值提示改为“请选择门店”。
3. 列表严格沿用后端接口返回顺序,不在前端增加排序。
4. 业务大类支持“轻改、延保、权益”展示。
5. 列表到详情保留场景与品牌上下文,详情兼容最新版模板的选项值和多选包装结构。
以下内容明确不改:
- `journal_web_view_detail` 埋点名称及调用时机。
- 后端接口、分页方式和后端排序规则。
- Vue 2、Element UI、D2Admin 现有页面结构。
## 列表页设计
### 时间与空值
复用 `journalDateTime.js` 的统一格式化函数,将日期时间格式从带秒调整为分钟精度。所有使用该函数的门店日报列表时间列同步生效;无值或非法值统一返回半角连字符 `-`。
### 门店选择
保留远程搜索、清空、分页加载和白名单门店接口,仅将输入框提示文案改为“请选择门店”。
### 顺序
`mapOverviewPageResponse` 保持响应 `list` 的原始顺序。前端不增加 `sort`,请求参数不增加未在接口合同中定义的排序字段,相关测试保护这一约定。
### 业务大类
业务大类按以下优先级解析:
1. 后端明确返回的 `bizTypeName`。
2. `baseSceneCode` 或 `sceneList[].baseSceneCode` 中的精确场景码。
3. 现有 `sceneType` 兜底映射。
精确场景码中,`100101~100103` 映射轻改,`110201/110202` 映射延保,`110101/110102` 映射权益。若只有 `sceneType=0` 且没有精确场景码,继续显示权益,不在前端猜测延保。样式表新增“延保”配置;已有后端 `bizType` 值保持原样。
## 详情页设计
### 上下文传递
列表行适配器保留 `sceneType`,并继续保留 `baseSceneCode`、`sceneList`、`brandIds`。详情接口响应优先,缺失时使用路由上下文;品牌缺失时仍通过门店品牌接口补齐。
### 最新模板值归一化
开发环境真实数据包含两种当前实现未完整处理的结构:
- 客户来源保存为展示文案,例如“销售端引流-售前”,而 `childrenShowRules` 比较选项值 `"0"`。
- 客户标签保存为 `{ text: "已触客/已拉群", value: ["1", "2"] }`,而显隐规则要求数组值。
规则求值前按字段 options 归一化:
- 标量既可以按 option `value` 匹配,也可以按 option `label` 匹配,最终使用 option `value`。
- 对象的 `value` 为数组时,逐项归一化并返回数组,不降级成 `text` 字符串。
- 对象的 `value` 为标量时优先归一化该值;缺少可用值时再回退 `name/label/text/id`。
- 展示格式仍优先使用 `text/name/label`,不改变用户当前看到的可读文案。
这样可保证“实际交付日期、是否有效引荐、无效引荐说明、是否有效到店、未触客原因、未成交原因”等字段按真实模板规则显示。
## 错误与兼容策略
- 不支持或格式错误的规则继续 fail-closed,不使用 `eval` 或 `new Function`。
- 历史字符串、对象数组和旧 `children[0] + value` 结构保持兼容。
- 缺少精确业务场景时不猜测延保,避免把历史权益数据错误分类。
- 不改变接口异常处理和现有全局 Message 行为。
## 测试设计
遵循 TDD,先写失败测试再修改实现:
1. 日期时间分钟格式、空值和非法值测试。
2. 列表真实顺序保持测试。
3. 精确场景码识别轻改、延保、权益及后端名称优先测试。
4. 列表行保留 `sceneType` 测试。
5. 使用开发环境完整 `jsonContent` 的详情回显测试,覆盖客户来源 label 到 value 的归一化,以及 `{ text, value: [] }` 客户标签触发的行内显隐。
6. 运行门店日报相关单测和 touched files ESLint。
## 验收标准
- 列表时间精确到分钟,空值显示 `-`。
- 门店下拉空值提示为“请选择门店”。
- 列表顺序与后端响应一致。
- 有精确场景信息时正确显示轻改、延保或权益;仅有旧 `sceneType` 时保持兼容。
- 详情展示开发环境最新版门店日报数据时,人员、客户来源、客户标签和车型为可读文案,条件字段显隐符合 `childrenShowRules`。
- 埋点实现无变化。
......@@ -3,7 +3,7 @@ import { getTemplateTypeByTabKey } from "@/views/residentManage/journalRecord/co
/**
* d2-table 查询参数 → dailyReport.overview.page 请求体
*/
export function buildOverviewParams(params = {}, activeTabKey = "staffDaily") {
export function buildOverviewParams(params = {}, activeTabKey = "storeDaily") {
const payload = {
templateType: getTemplateTypeByTabKey(activeTabKey),
reportDate: params.reportDate,
......
import { mapSceneType } from "./mapSceneType";
function normalizeContextList(value) {
if (Array.isArray(value)) {
return value;
}
if (value == null || value === "") {
return [];
}
return String(value).split(",").filter(Boolean);
}
function resolveBusinessValue(...values) {
const value = values.find(item => item != null && item !== "");
return value ?? "";
}
/**
* 详情路由 query → dailyReport.detail.select 请求体
*/
......@@ -11,25 +26,42 @@ export function buildDetailSelectParams({ id } = {}) {
* dailyReport.detail.select 响应 → 详情页 detail 对象
*/
export function mapDetailResponse(res = {}, fallback = {}) {
const scene = mapSceneType(res.sceneType ?? fallback.sceneType);
const sceneType = res.sceneType ?? fallback.sceneType;
const sceneContext = {
baseSceneCode: res.baseSceneCode ?? fallback.baseSceneCode,
sceneList: res.sceneList ?? fallback.sceneList,
};
const preciseScene = mapSceneType(undefined, sceneContext);
const legacyScene = mapSceneType(sceneType);
return {
...res,
id: res.id ?? res.dailyReportRecordId ?? fallback.id,
staffName: res.staffName ?? fallback.staffName,
merchantName: res.merchantName ?? fallback.merchantName,
bizType: res.bizType ?? scene.bizType ?? fallback.bizType,
bizTypeName: res.bizTypeName || scene.bizTypeName || fallback.bizTypeName,
templateType: res.templateType ?? fallback.templateType,
bizType: resolveBusinessValue(
res.bizType,
preciseScene.bizType,
fallback.bizType,
legacyScene.bizType,
),
bizTypeName: resolveBusinessValue(
res.bizTypeName,
preciseScene.bizTypeName,
fallback.bizTypeName,
legacyScene.bizTypeName,
),
reportDate: res.reportDate ?? fallback.reportDate,
jsonContent: res.jsonContent,
fieldDataList: res.fieldDataList,
subformDataList: res.subformDataList,
reportTemplateId: res.reportTemplateId,
baseSceneCode: res.baseSceneCode,
sceneType: res.sceneType ?? fallback.sceneType,
baseSceneCode: sceneContext.baseSceneCode,
sceneType,
schema: res.schema,
brandIds: res.brandIds ?? fallback.brandIds ?? [],
sceneList: res.sceneList ?? fallback.sceneList ?? [],
brandIds: normalizeContextList(res.brandIds ?? fallback.brandIds),
sceneList: sceneContext.sceneList ?? [],
};
}
......
export function mapMerchantBrandContext(res = {}, merchantId) {
const list = Array.isArray(res.list) ? res.list : [];
const merchant = list.find(item => String(item.merchantId) === String(merchantId));
if (!merchant || !Array.isArray(merchant.merchantBrandList)) {
return [];
}
return merchant.merchantBrandList
.map(item => item.childId ?? item.brandId)
.filter(id => id != null && id !== "");
}
export default mapMerchantBrandContext;
import { mapSceneType } from "./mapSceneType";
import { collectSceneCodes, mapSceneType } from "./mapSceneType";
/**
* dailyReport.overview.page 行数据 → 表格行
*/
export function mapOverviewRow(row = {}) {
const scene = mapSceneType(row.sceneType);
const scene = mapSceneType(row.sceneType, row);
const reportStatus = row.reportStatus;
const createdDate = row.createdDate ?? row.lastSaveTime ?? row.updatedDate;
let baseSceneCode = row.baseSceneCode;
if (!collectSceneCodes(baseSceneCode).length) {
const sceneListCodes = collectSceneCodes(row.sceneList);
baseSceneCode = sceneListCodes.length ? sceneListCodes : undefined;
}
return {
id: row.id ?? row.dailyReportRecordId,
......@@ -22,6 +27,10 @@ export function mapOverviewRow(row = {}) {
submitTime: reportStatus === 1 ? (row.submitTime ?? createdDate) : (row.submitTime || ""),
reportDate: row.reportDate,
templateType: row.templateType,
baseSceneCode,
sceneType: row.sceneType,
brandIds: row.brandIds,
sceneList: row.sceneList,
reportStatus,
};
}
......
/**
* Swagger sceneType(0:权益,1:轻改)→ 页面 bizType / bizTypeName
*/
const SCENE_TYPE_MAP = {
0: { bizType: 2, bizTypeName: "权益" },
1: { bizType: 1, bizTypeName: "轻改" },
"0": { bizType: 2, bizTypeName: "权益" },
"1": { bizType: 1, bizTypeName: "轻改" },
};
export function mapSceneType(sceneType) {
const SCENE_CODE_MAP = {
100101: { bizType: 1, bizTypeName: "轻改" },
100102: { bizType: 1, bizTypeName: "轻改" },
100103: { bizType: 1, bizTypeName: "轻改" },
110101: { bizType: 2, bizTypeName: "权益" },
110102: { bizType: 2, bizTypeName: "权益" },
110201: { bizType: "延保", bizTypeName: "延保" },
110202: { bizType: "延保", bizTypeName: "延保" },
};
export function collectSceneCodes(value) {
const codes = [];
const append = (item) => {
if (Array.isArray(item)) {
item.forEach(append);
return;
}
if (item && typeof item === "object") {
append(item.baseSceneCode);
return;
}
if (typeof item === "string") {
item.split(",").forEach((code) => {
const trimmedCode = code.trim();
if (trimmedCode) {
codes.push(trimmedCode);
}
});
return;
}
if (item != null) {
codes.push(item);
}
};
append(value);
return codes;
}
/**
* Swagger sceneType(0:权益,1:轻改)→ 页面 bizType / bizTypeName
*/
export function mapSceneType(sceneType, context = {}) {
const sceneByCode = collectSceneCodes([context.baseSceneCode, context.sceneList])
.map(code => SCENE_CODE_MAP[code])
.find(Boolean);
if (sceneByCode) {
return sceneByCode;
}
if (sceneType == null || sceneType === "") {
return { bizType: "", bizTypeName: "" };
}
......
{
"method": "dj.api.smartcarlife.MerchantGoodsStockMonthReport.stockMove",
"route": "/router/dj.api.smartcarlife.MerchantGoodsStockMonthReport.stockMove/1.0.0",
"summary": "单产品库存移动",
"request": {
"parameters": [
{
"name": "upgradeGoodsId",
"in": "query",
"type": "int",
"required": false,
"description": "旧产品ID(dj_car_life_upgrade_goods.id)"
},
{
"name": "yqMerchantId",
"in": "query",
"type": "int",
"required": false,
"description": "园区店商户号"
},
{
"name": "targetUpgradeGoodsId",
"in": "query",
"type": "int",
"required": false,
"description": "新产品ID"
},
{
"name": "sessionId",
"in": "query",
"type": "string",
"required": true,
"description": "会话ID"
}
]
},
"response": {
"fields": [
{
"name": "code",
"type": "string",
"description": "响应状态(0:成功;1:失败)",
"required": false
},
{
"name": "errId",
"type": "string",
"description": "错误码",
"required": false
},
{
"name": "message",
"type": "string",
"description": "错误描述",
"required": false
},
{
"name": "data",
"type": "boolean",
"description": "成功返回数据",
"required": false
}
],
"pagination": null,
"rootType": "RopResponse<Boolean>"
}
}
# dj.api.smartcarlife.MerchantGoodsStockMonthReport.stockMove
> 单产品库存移动
## Request
| 参数 | 位置 | 类型 | 必填 | 说明 |
|------|------|------|------|------|
| upgradeGoodsId | query | int | 否 | 旧产品ID(dj_car_life_upgrade_goods.id) |
| yqMerchantId | query | int | 否 | 园区店商户号 |
| targetUpgradeGoodsId | query | int | 否 | 新产品ID |
| sessionId | query | string | 是 | 会话ID |
## Response
| 字段 | 类型 | 说明 |
|------|------|------|
| code | string | 响应状态(0:成功;1:失败) |
| errId | string | 错误码 |
| message | string | 错误描述 |
| data | boolean | 成功返回数据 |
{
"method": "dj.api.smartcarlife.MerchantGoodsStockMonthReport.stockMove.import",
"route": "/router/dj.api.smartcarlife.MerchantGoodsStockMonthReport.stockMove.import/1.0.0",
"summary": "移动库存批量导入",
"request": {
"parameters": [
{
"name": "file.fileType",
"in": "query",
"type": "string",
"required": false,
"description": ""
},
{
"name": "sessionId",
"in": "query",
"type": "string",
"required": true,
"description": "会话ID"
}
]
},
"response": {
"fields": [
{
"name": "code",
"type": "string",
"description": "响应状态(0:成功;1:失败)",
"required": false
},
{
"name": "errId",
"type": "string",
"description": "错误码",
"required": false
},
{
"name": "message",
"type": "string",
"description": "错误描述",
"required": false
},
{
"name": "data",
"type": "string",
"description": "成功返回数据",
"required": false
}
],
"pagination": null,
"rootType": "RopResponse<String>"
}
}
# dj.api.smartcarlife.MerchantGoodsStockMonthReport.stockMove.import
> 移动库存批量导入
## Request
| 参数 | 位置 | 类型 | 必填 | 说明 |
|------|------|------|------|------|
| file.fileType | query | string | 否 | |
| sessionId | query | string | 是 | 会话ID |
## Response
| 字段 | 类型 | 说明 |
|------|------|------|
| code | string | 响应状态(0:成功;1:失败) |
| errId | string | 错误码 |
| message | string | 错误描述 |
| data | string | 成功返回数据 |
{
"method": "dj.api.smartcarlife.MerchantGoodsStockMonthReport.stockMove.log.page",
"route": "/router/dj.api.smartcarlife.MerchantGoodsStockMonthReport.stockMove.log.page/1.0.0",
"summary": "移动库存日志分页查询",
"request": {
"parameters": [
{
"name": "upgradeGoodsId",
"in": "query",
"type": "int",
"required": false,
"description": "旧产品ID(仅匹配旧UID)"
},
{
"name": "yqMerchantId",
"in": "query",
"type": "int",
"required": false,
"description": "园区店商户号"
},
{
"name": "sessionId",
"in": "query",
"type": "string",
"required": true,
"description": "会话ID"
}
]
},
"response": {
"fields": [
{
"name": "code",
"type": "string",
"description": "响应状态(0:成功;1:失败)",
"required": false
},
{
"name": "errId",
"type": "string",
"description": "错误码",
"required": false
},
{
"name": "message",
"type": "string",
"description": "错误描述",
"required": false
},
{
"name": "data",
"type": "RpcPagination<MerchantGoodsStockMoveLogResponse>",
"description": "成功返回数据",
"required": false
},
{
"name": "data.pageNum",
"type": "integer:int32",
"description": "",
"required": false
},
{
"name": "data.pageSize",
"type": "integer:int32",
"description": "",
"required": false
},
{
"name": "data.startRow",
"type": "integer:int64",
"description": "",
"required": false
},
{
"name": "data.endRow",
"type": "integer:int64",
"description": "",
"required": false
},
{
"name": "data.total",
"type": "integer:int64",
"description": "",
"required": false
},
{
"name": "data.pages",
"type": "integer:int32",
"description": "",
"required": false
},
{
"name": "data.list",
"type": "array<MerchantGoodsStockMoveLogResponse>",
"description": "",
"required": false
},
{
"name": "data.condition",
"type": "MerchantGoodsStockMoveLogResponse",
"description": "",
"required": false
},
{
"name": "data.needCount",
"type": "boolean",
"description": "",
"required": false
}
],
"pagination": {
"wrapper": "RopResponse<RpcPagination<MerchantGoodsStockMoveLogResponse>>",
"type": "RpcPagination<MerchantGoodsStockMoveLogResponse>",
"fields": [
"pageNum",
"pageSize",
"total",
"list"
]
},
"rootType": "RopResponse<RpcPagination<MerchantGoodsStockMoveLogResponse>>"
}
}
# dj.api.smartcarlife.MerchantGoodsStockMonthReport.stockMove.log.page
> 移动库存日志分页查询
## Request
| 参数 | 位置 | 类型 | 必填 | 说明 |
|------|------|------|------|------|
| upgradeGoodsId | query | int | 否 | 旧产品ID(仅匹配旧UID) |
| yqMerchantId | query | int | 否 | 园区店商户号 |
| sessionId | query | string | 是 | 会话ID |
## Response
分页: `RpcPagination<MerchantGoodsStockMoveLogResponse>` (pageNum, pageSize, total, list)
| 字段 | 类型 | 说明 |
|------|------|------|
| code | string | 响应状态(0:成功;1:失败) |
| errId | string | 错误码 |
| message | string | 错误描述 |
| data | RpcPagination<MerchantGoodsStockMoveLogResponse> | 成功返回数据 |
| data.pageNum | integer:int32 | |
| data.pageSize | integer:int32 | |
| data.startRow | integer:int64 | |
| data.endRow | integer:int64 | |
| data.total | integer:int64 | |
| data.pages | integer:int32 | |
| data.list | array<MerchantGoodsStockMoveLogResponse> | |
| data.condition | MerchantGoodsStockMoveLogResponse | |
| data.needCount | boolean | |
{
"method": "dj.api.smartcarlife.MerchantGoodsStockMonthReport.stockMove.template.export",
"route": "/router/dj.api.smartcarlife.MerchantGoodsStockMonthReport.stockMove.template.export/1.0.0",
"summary": "移动库存导入模版下载",
"request": {
"parameters": [
{
"name": "sessionId",
"in": "query",
"type": "string",
"required": true,
"description": "会话ID"
}
]
},
"response": {
"fields": [
{
"name": "code",
"type": "string",
"description": "响应状态(0:成功;1:失败)",
"required": false
},
{
"name": "errId",
"type": "string",
"description": "错误码",
"required": false
},
{
"name": "message",
"type": "string",
"description": "错误描述",
"required": false
},
{
"name": "data",
"type": "string",
"description": "成功返回数据",
"required": false
}
],
"pagination": null,
"rootType": "RopResponse<String>"
}
}
# dj.api.smartcarlife.MerchantGoodsStockMonthReport.stockMove.template.export
> 移动库存导入模版下载
## Request
| 参数 | 位置 | 类型 | 必填 | 说明 |
|------|------|------|------|------|
| sessionId | query | string | 是 | 会话ID |
## Response
| 字段 | 类型 | 说明 |
|------|------|------|
| code | string | 响应状态(0:成功;1:失败) |
| errId | string | 错误码 |
| message | string | 错误描述 |
| data | string | 成功返回数据 |
{
"method": "dj.api.smartcarlife.productManager.listUpgradeGoodsSimple",
"route": "/router/dj.api.smartcarlife.productManager.listUpgradeGoodsSimple/1.0.0",
"summary": "分页查询产品(轻改/权益延保)",
"request": {
"parameters": [
{
"name": "currentPage",
"in": "query",
"type": "integer",
"required": false,
"description": "当前页码"
},
{
"name": "pageSize",
"in": "query",
"type": "integer",
"required": false,
"description": "每页条数"
},
{
"name": "commodityCode",
"in": "query",
"type": "string",
"required": false,
"description": "UID(产品编码,模糊查询)对应commodity_code"
},
{
"name": "productType",
"in": "query",
"type": "byte",
"required": false,
"description": "产品类型 1-轻改 2-权益、延保"
},
{
"name": "sessionId",
"in": "query",
"type": "string",
"required": true,
"description": "会话ID"
}
]
},
"response": {
"fields": [
{
"name": "code",
"type": "string",
"description": "响应状态(0:成功;1:失败)",
"required": false
},
{
"name": "errId",
"type": "string",
"description": "错误码",
"required": false
},
{
"name": "message",
"type": "string",
"description": "错误描述",
"required": false
},
{
"name": "data",
"type": "RpcPagination<UpgradeGoodsDTO>",
"description": "成功返回数据",
"required": false
},
{
"name": "data.pageNum",
"type": "integer:int32",
"description": "",
"required": false
},
{
"name": "data.pageSize",
"type": "integer:int32",
"description": "",
"required": false
},
{
"name": "data.startRow",
"type": "integer:int64",
"description": "",
"required": false
},
{
"name": "data.endRow",
"type": "integer:int64",
"description": "",
"required": false
},
{
"name": "data.total",
"type": "integer:int64",
"description": "",
"required": false
},
{
"name": "data.pages",
"type": "integer:int32",
"description": "",
"required": false
},
{
"name": "data.list",
"type": "array<UpgradeGoodsDTO>",
"description": "",
"required": false
},
{
"name": "data.condition",
"type": "UpgradeGoodsDTO",
"description": "",
"required": false
},
{
"name": "data.needCount",
"type": "boolean",
"description": "",
"required": false
}
],
"pagination": {
"wrapper": "RopResponse<RpcPagination<UpgradeGoodsDTO>>",
"type": "RpcPagination<UpgradeGoodsDTO>",
"fields": [
"pageNum",
"pageSize",
"total",
"list"
]
},
"rootType": "RopResponse<RpcPagination<UpgradeGoodsDTO>>"
}
}
# dj.api.smartcarlife.productManager.listUpgradeGoodsSimple
> 分页查询产品(轻改/权益延保)
## Request
| 参数 | 位置 | 类型 | 必填 | 说明 |
|------|------|------|------|------|
| currentPage | query | integer | 否 | 当前页码 |
| pageSize | query | integer | 否 | 每页条数 |
| commodityCode | query | string | 否 | UID(产品编码,模糊查询)对应commodity_code |
| productType | query | byte | 否 | 产品类型 1-轻改 2-权益、延保 |
| sessionId | query | string | 是 | 会话ID |
## Response
分页: `RpcPagination<UpgradeGoodsDTO>` (pageNum, pageSize, total, list)
| 字段 | 类型 | 说明 |
|------|------|------|
| code | string | 响应状态(0:成功;1:失败) |
| errId | string | 错误码 |
| message | string | 错误描述 |
| data | RpcPagination<UpgradeGoodsDTO> | 成功返回数据 |
| data.pageNum | integer:int32 | |
| data.pageSize | integer:int32 | |
| data.startRow | integer:int64 | |
| data.endRow | integer:int64 | |
| data.total | integer:int64 | |
| data.pages | integer:int32 | |
| data.list | array<UpgradeGoodsDTO> | |
| data.condition | UpgradeGoodsDTO | |
| data.needCount | boolean | |
/* eslint-disable jsdoc/require-property-description, jsdoc/require-returns-description */
/**
* @typedef {Object} LogPageParams
* @property {number} upgradeGoodsId [optional] - 旧产品ID(仅匹配旧UID)
* @property {number} yqMerchantId [optional] - 园区店商户号
*/
/**
* @typedef {Object} LogPageRow
* @property {string} errId - 错误码
* @property {string} data - 成功返回数据
*/
/**
* @typedef {Object} LogPagePageResponse
* @property {number} [pageNum]
* @property {number} [pageSize]
* @property {number} [total]
* @property {LogPageRow[]} [list]
*/
/**
* UI/表格参数 → dj.api.smartcarlife.MerchantGoodsStockMonthReport.stockMove.log.page 请求体
* @param {LogPageParams} [params]
* @returns {LogPageParams}
* @see __contracts__/dj_api_smartcarlife_MerchantGoodsStockMonthReport_stockMove_log_page.contract.md
*/
export function buildLogPageParams(params = {}) {
const payload = {};
if (params.upgradeGoodsId != null && params.upgradeGoodsId !== "") {
payload.upgradeGoodsId = params.upgradeGoodsId;
}
if (params.yqMerchantId != null && params.yqMerchantId !== "") {
payload.yqMerchantId = params.yqMerchantId;
}
return payload;
}
export default buildLogPageParams;
/* eslint-disable jsdoc/require-returns-description */
/**
* @typedef {Object} MerchantGoodsStockMonthReportStockMoveParams
* @property {number} upgradeGoodsId [optional] - 旧产品ID(dj_car_life_upgrade_goods.id)
* @property {number} yqMerchantId [optional] - 园区店商户号
* @property {number} targetUpgradeGoodsId [optional] - 新产品ID
*/
/**
* @typedef {Object} MerchantGoodsStockMonthReportStockMoveRow
* @property {string} errId - 错误码
* @property {boolean} data - 成功返回数据
*/
/**
* UI/表格参数 → dj.api.smartcarlife.MerchantGoodsStockMonthReport.stockMove 请求体
* @param {MerchantGoodsStockMonthReportStockMoveParams} [params]
* @returns {MerchantGoodsStockMonthReportStockMoveParams}
* @see __contracts__/dj_api_smartcarlife_MerchantGoodsStockMonthReport_stockMove.contract.md
*/
export function buildMerchantGoodsStockMonthReportStockMoveParams(params = {}) {
const payload = {};
if (params.upgradeGoodsId != null && params.upgradeGoodsId !== "") {
payload.upgradeGoodsId = params.upgradeGoodsId;
}
if (params.yqMerchantId != null && params.yqMerchantId !== "") {
payload.yqMerchantId = params.yqMerchantId;
}
if (params.targetUpgradeGoodsId != null && params.targetUpgradeGoodsId !== "") {
payload.targetUpgradeGoodsId = params.targetUpgradeGoodsId;
}
return payload;
}
export default buildMerchantGoodsStockMonthReportStockMoveParams;
/* eslint-disable jsdoc/require-property-description, jsdoc/require-returns-description */
/**
* @typedef {Object} ProductManagerListUpgradeGoodsSimpleParams
* @property {number} currentPage [optional] - 当前页码
* @property {number} pageSize [optional] - 每页条数
* @property {string} commodityCode [optional] - UID(产品编码,模糊查询)对应commodity_code
* @property {string} productType [optional] - 产品类型 1-轻改 2-权益、延保
*/
/**
* @typedef {Object} ProductManagerListUpgradeGoodsSimpleRow
* @property {string} errId - 错误码
* @property {string} data - 成功返回数据
*/
/**
* @typedef {Object} ProductManagerListUpgradeGoodsSimplePageResponse
* @property {number} [pageNum]
* @property {number} [pageSize]
* @property {number} [total]
* @property {ProductManagerListUpgradeGoodsSimpleRow[]} [list]
*/
/**
* UI/表格参数 → dj.api.smartcarlife.productManager.listUpgradeGoodsSimple 请求体
* @param {ProductManagerListUpgradeGoodsSimpleParams} [params]
* @returns {ProductManagerListUpgradeGoodsSimpleParams}
* @see __contracts__/dj_api_smartcarlife_productManager_listUpgradeGoodsSimple.contract.md
*/
export function buildProductManagerListUpgradeGoodsSimpleParams(params = {}) {
const payload = {};
if (params.currentPage != null && params.currentPage !== "") {
payload.currentPage = params.currentPage;
}
if (params.pageSize != null && params.pageSize !== "") {
payload.pageSize = params.pageSize;
}
if (params.commodityCode != null && params.commodityCode !== "") {
payload.commodityCode = params.commodityCode;
}
if (params.productType != null && params.productType !== "") {
payload.productType = params.productType;
}
return payload;
}
export default buildProductManagerListUpgradeGoodsSimpleParams;
/* eslint-disable jsdoc/require-returns-description */
/**
* @typedef {Object} StockMoveImportParams
* @property {*} file - 导入文件
*/
/**
* @typedef {Object} StockMoveImportRow
* @property {string} errId - 错误码
* @property {string} data - 成功返回数据
*/
/**
* UI/表格参数 → dj.api.smartcarlife.MerchantGoodsStockMonthReport.stockMove.import 请求体
* @param {StockMoveImportParams} [params]
* @returns {StockMoveImportParams}
* @see __contracts__/dj_api_smartcarlife_MerchantGoodsStockMonthReport_stockMove_import.contract.md
*/
export function buildStockMoveImportParams(params = {}) {
const payload = {};
if (params.file != null && params.file !== "") {
payload.file = params.file;
}
return payload;
}
export default buildStockMoveImportParams;
/* eslint-disable jsdoc/require-property-description, jsdoc/require-returns-description */
/**
* @typedef {Object} TemplateExportParams
* @property {*} [field]
*/
/**
* @typedef {Object} TemplateExportRow
* @property {string} errId - 错误码
* @property {string} data - 成功返回数据
*/
/**
* UI/表格参数 → dj.api.smartcarlife.MerchantGoodsStockMonthReport.stockMove.template.export 请求体
* @param {TemplateExportParams} [params]
* @returns {TemplateExportParams}
* @see __contracts__/dj_api_smartcarlife_MerchantGoodsStockMonthReport_stockMove_template_export.contract.md
*/
export function buildTemplateExportParams(params = {}) {
const payload = {};
// TODO: 映射请求参数
return payload;
}
export default buildTemplateExportParams;
/* eslint-disable jsdoc/require-property-description, jsdoc/require-returns-description */
/**
* @typedef {Object} LogPageParams
* @property {number} upgradeGoodsId [optional] - 旧产品ID(仅匹配旧UID)
* @property {number} yqMerchantId [optional] - 园区店商户号
*/
/**
* @typedef {Object} LogPageRow
* @property {string} errId - 错误码
* @property {string} data - 成功返回数据
*/
/**
* @typedef {Object} LogPagePageResponse
* @property {number} [pageNum]
* @property {number} [pageSize]
* @property {number} [total]
* @property {LogPageRow[]} [list]
*/
/**
* dj.api.smartcarlife.MerchantGoodsStockMonthReport.stockMove.log.page 响应 → 页面数据
* @param {LogPageRow} [row]
* @returns {LogPageRow}
* @see __contracts__/dj_api_smartcarlife_MerchantGoodsStockMonthReport_stockMove_log_page.contract.md
*/
export function mapLogPageRow(row = {}) {
return {
oldCommodityCode: row.oldCommodityCode,
newCommodityCode: row.newCommodityCode,
moveStockNum: row.moveStockNum,
createdBy: row.createdBy,
createdDate: row.createdDate,
};
}
/**
* @param {LogPagePageResponse} [res]
* @returns {LogPagePageResponse}
*/
export function mapLogPagePageResponse(res = {}) {
const list = Array.isArray(res.list) ? res.list.map(mapLogPageRow) : [];
return {
...res,
list,
pageNum: res.pageNum ?? res.currentPage,
};
}
export default mapLogPageRow;
/* eslint-disable jsdoc/require-returns-description */
/**
* @typedef {Object} MerchantGoodsStockMonthReportStockMoveParams
* @property {number} upgradeGoodsId [optional] - 旧产品ID(dj_car_life_upgrade_goods.id)
* @property {number} yqMerchantId [optional] - 园区店商户号
* @property {number} targetUpgradeGoodsId [optional] - 新产品ID
*/
/**
* @typedef {Object} MerchantGoodsStockMonthReportStockMoveRow
* @property {string} errId - 错误码
* @property {boolean} data - 成功返回数据
*/
/**
* dj.api.smartcarlife.MerchantGoodsStockMonthReport.stockMove 响应 → 页面数据
* @param {*} [res]
* @returns {*}
* @see __contracts__/dj_api_smartcarlife_MerchantGoodsStockMonthReport_stockMove.contract.md
*/
export function mapMerchantGoodsStockMonthReportStockMoveResponse(res = {}) {
return res;
}
export default mapMerchantGoodsStockMonthReportStockMoveResponse;
/* eslint-disable jsdoc/require-property-description, jsdoc/require-returns-description */
/**
* @typedef {Object} ProductManagerListUpgradeGoodsSimpleParams
* @property {number} currentPage [optional] - 当前页码
* @property {number} pageSize [optional] - 每页条数
* @property {string} commodityCode [optional] - UID(产品编码,模糊查询)对应commodity_code
* @property {string} productType [optional] - 产品类型 1-轻改 2-权益、延保
*/
/**
* @typedef {Object} ProductManagerListUpgradeGoodsSimpleRow
* @property {string} errId - 错误码
* @property {string} data - 成功返回数据
*/
/**
* @typedef {Object} ProductManagerListUpgradeGoodsSimplePageResponse
* @property {number} [pageNum]
* @property {number} [pageSize]
* @property {number} [total]
* @property {ProductManagerListUpgradeGoodsSimpleRow[]} [list]
*/
/**
* dj.api.smartcarlife.productManager.listUpgradeGoodsSimple 响应 → 页面数据
* @param {ProductManagerListUpgradeGoodsSimpleRow} [row]
* @returns {ProductManagerListUpgradeGoodsSimpleRow}
* @see __contracts__/dj_api_smartcarlife_productManager_listUpgradeGoodsSimple.contract.md
*/
export function mapProductManagerListUpgradeGoodsSimpleRow(row = {}) {
return { ...row };
}
/**
* @param {ProductManagerListUpgradeGoodsSimplePageResponse} [res]
* @returns {ProductManagerListUpgradeGoodsSimplePageResponse}
*/
export function mapProductManagerListUpgradeGoodsSimplePageResponse(res = {}) {
const list = Array.isArray(res.list) ? res.list.map(mapProductManagerListUpgradeGoodsSimpleRow) : [];
return {
...res,
list,
pageNum: res.pageNum ?? res.currentPage,
};
}
export default mapProductManagerListUpgradeGoodsSimpleRow;
/* eslint-disable jsdoc/require-returns-description */
/**
* @typedef {Object} StockMoveImportParams
* @property {*} file - 导入文件
*/
/**
* @typedef {Object} StockMoveImportRow
* @property {string} errId - 错误码
* @property {string} data - 成功返回数据
*/
/**
* dj.api.smartcarlife.MerchantGoodsStockMonthReport.stockMove.import 响应 → 页面数据
* @param {*} [res]
* @returns {*}
* @see __contracts__/dj_api_smartcarlife_MerchantGoodsStockMonthReport_stockMove_import.contract.md
*/
export function mapStockMoveImportResponse(res = {}) {
return res;
}
export default mapStockMoveImportResponse;
/* eslint-disable jsdoc/require-property-description, jsdoc/require-returns-description */
/**
* @typedef {Object} TemplateExportParams
* @property {*} [field]
*/
/**
* @typedef {Object} TemplateExportRow
* @property {string} errId - 错误码
* @property {string} data - 成功返回数据
*/
/**
* dj.api.smartcarlife.MerchantGoodsStockMonthReport.stockMove.template.export 响应 → 页面数据
* @param {*} [res]
* @returns {*}
* @see __contracts__/dj_api_smartcarlife_MerchantGoodsStockMonthReport_stockMove_template_export.contract.md
*/
export function mapTemplateExportResponse(res = {}) {
return res;
}
export default mapTemplateExportResponse;
import { buildStockMoveImportParams } from "./buildStockMoveImportParams";
import { mapLogPagePageResponse } from "./mapLogPageResponse";
import { mapProductManagerListUpgradeGoodsSimplePageResponse } from "./mapProductManagerListUpgradeGoodsSimpleResponse";
describe("stock move adapters", () => {
it("passes the import file through without reading generated nested properties", () => {
const file = new FormData();
expect(buildStockMoveImportParams({ file })).toEqual({ file });
});
it("keeps product fields used by the remote selector", () => {
const response = mapProductManagerListUpgradeGoodsSimplePageResponse({
currentPage: 2,
list: [{ id: 9, commodityCode: "UID-9", upgradeGoodsName: "产品A" }],
});
expect(response.pageNum).toBe(2);
expect(response.list[0]).toMatchObject({
id: 9,
commodityCode: "UID-9",
upgradeGoodsName: "产品A",
});
});
it("keeps migration log fields used by the drawer", () => {
const response = mapLogPagePageResponse({
list: [{
oldCommodityCode: "OLD",
newCommodityCode: "NEW",
moveStockNum: 3,
createdBy: "张三",
createdDate: "2026-08-05 12:30:00",
}],
});
expect(response.list[0]).toEqual({
oldCommodityCode: "OLD",
newCommodityCode: "NEW",
moveStockNum: 3,
createdBy: "张三",
createdDate: "2026-08-05 12:30:00",
});
});
});
......@@ -164,6 +164,12 @@ export function purchaseGoodsInfoUpdateBatchWaitAudit(data) {
return request(data, "post");
}
// 批量修改采购价
export function purchaseGoodsInfoUpdateBatchPrice(data) {
data.method = `${path}purchaseGoodsInfo.updateBatchPrice`;
return request(data, "post");
}
// 上下架操作
export function purchaseGoodsInfoUpdateStatus(data) {
data.method = `${path}purchaseGoodsInfo.updateStatus`;
......@@ -184,8 +190,8 @@ export function savePaymentChannelConfig(data) {
// 根据已选产品实时查询运营成本
export function getOperationCost(data) {
data.method = 'dj.api.smartcarlife.merchantGoodsInfo.operationCost.calculate'
return request(data, "post")
data.method = "dj.api.smartcarlife.merchantGoodsInfo.operationCost.calculate";
return request(data, "post");
}
// 查询商品成本(默认带入产品成本)
......
import { purchaseGoodsInfoUpdateBatchPrice } from "./grounding";
import mockRequest from "./request";
jest.mock("./request", () => jest.fn((data, method) => Promise.resolve({ data, method })));
describe("grounding api", () => {
beforeEach(() => {
mockRequest.mockClear();
});
it("submits selected purchase ids and price to the batch price endpoint", async () => {
const payload = { ids: [1, "2"], purchasePrice: 88.5 };
await purchaseGoodsInfoUpdateBatchPrice(payload);
expect(mockRequest).toHaveBeenCalledWith({
ids: [1, "2"],
purchasePrice: 88.5,
method: "dj.api.smartcarlife.purchaseGoodsInfo.updateBatchPrice",
}, "post");
});
});
import request from "./request";
import RequestMethods from "./request.methods";
import { buildOverviewParams } from "./adapters/journalRecord/buildOverviewParams";
import { mapOverviewPageResponse } from "./adapters/journalRecord/mapOverviewRow";
import {
buildDetailSelectParams,
mapDetailResponse,
} from "./adapters/journalRecord/mapDetailResponse";
import { mapMerchantBrandContext } from "./adapters/journalRecord/mapMerchantBrandContext";
import { mapMerchantListResponse } from "./adapters/journalRecord/mapMerchantList";
import { mapMerchantStaffListResponse } from "./adapters/journalRecord/mapMerchantStaffList";
import { mapOverviewPageResponse } from "./adapters/journalRecord/mapOverviewRow";
import request from "./request";
import RequestMethods from "./request.methods";
const path = "dj.api.smartcarlife.";
// Vue CLI 在浏览器构建时注入 process.env。
// eslint-disable-next-line node/prefer-global/process
const USE_MOCK = process.env.VUE_APP_JOURNAL_MOCK === "true";
function loadMock() {
......@@ -23,7 +26,7 @@ export function getDailyReportMerchantList(data = {}) {
...data,
};
if (USE_MOCK) {
return loadMock().then((m) => m.mockDailyReportMerchantList(payload));
return loadMock().then(m => m.mockDailyReportMerchantList(payload));
}
payload.method = `${path}dailyReport.merchant.list`;
return request(payload, RequestMethods.POST).then(mapMerchantListResponse);
......@@ -37,8 +40,8 @@ export function getDailyReportMerchantListPage(data = {}) {
};
if (USE_MOCK) {
return loadMock()
.then((m) => m.mockDailyReportMerchantList(payload))
.then((list) => ({
.then(m => m.mockDailyReportMerchantList(payload))
.then(list => ({
list,
total: list.length,
pages: 1,
......@@ -46,7 +49,7 @@ export function getDailyReportMerchantListPage(data = {}) {
}));
}
payload.method = `${path}dailyReport.merchant.list`;
return request(payload, RequestMethods.POST).then((res) => ({
return request(payload, RequestMethods.POST).then(res => ({
list: mapMerchantListResponse(res),
total: res.total ?? 0,
pages: res.pages ?? 1,
......@@ -56,7 +59,7 @@ export function getDailyReportMerchantListPage(data = {}) {
export function getDailyReportMerchantStaffList(data = {}) {
if (USE_MOCK) {
return loadMock().then((m) => m.mockDailyReportMerchantStaffList(data));
return loadMock().then(m => m.mockDailyReportMerchantStaffList(data));
}
const payload = {
...data,
......@@ -65,9 +68,26 @@ export function getDailyReportMerchantStaffList(data = {}) {
return request(payload, RequestMethods.POST).then(mapMerchantStaffListResponse);
}
export function getDailyReportOverviewPage(data = {}, activeTabKey = "staffDaily") {
export function getDailyReportMerchantBrandIds(merchantId) {
if (!merchantId) {
return Promise.resolve([]);
}
if (USE_MOCK) {
return Promise.resolve([3454]);
}
const payload = {
merchantId,
currentPage: 1,
pageSize: 1,
method: "dj.staff.api.service.merchant.page.with.brand",
};
return request(payload, RequestMethods.POST)
.then(res => mapMerchantBrandContext(res, merchantId));
}
export function getDailyReportOverviewPage(data = {}, activeTabKey = "storeDaily") {
if (USE_MOCK) {
return loadMock().then((m) => m.mockDailyReportOverviewPage({
return loadMock().then(m => m.mockDailyReportOverviewPage({
...data,
...buildOverviewParams(data, activeTabKey),
}));
......@@ -81,11 +101,11 @@ export function getDailyReportOverviewPage(data = {}, activeTabKey = "staffDaily
export function getDailyReportDetailSelect(data = {}) {
if (USE_MOCK) {
return loadMock().then((m) => m.mockDailyReportDetailSelect(data));
return loadMock().then(m => m.mockDailyReportDetailSelect(data));
}
const payload = {
...buildDetailSelectParams(data),
method: `${path}dailyReport.detail.select`,
};
return request(payload, RequestMethods.POST).then((res) => mapDetailResponse(res, data));
return request(payload, RequestMethods.POST).then(res => mapDetailResponse(res, data));
}
import { buildLogPageParams } from "./adapters/stockMove/buildLogPageParams";
import { buildMerchantGoodsStockMonthReportStockMoveParams } from "./adapters/stockMove/buildMerchantGoodsStockMonthReportStockMoveParams";
import { buildProductManagerListUpgradeGoodsSimpleParams } from "./adapters/stockMove/buildProductManagerListUpgradeGoodsSimpleParams";
import { buildStockMoveImportParams } from "./adapters/stockMove/buildStockMoveImportParams";
import { buildTemplateExportParams } from "./adapters/stockMove/buildTemplateExportParams";
import { mapLogPagePageResponse } from "./adapters/stockMove/mapLogPageResponse";
import { mapMerchantGoodsStockMonthReportStockMoveResponse } from "./adapters/stockMove/mapMerchantGoodsStockMonthReportStockMoveResponse";
import { mapProductManagerListUpgradeGoodsSimplePageResponse } from "./adapters/stockMove/mapProductManagerListUpgradeGoodsSimpleResponse";
import { mapStockMoveImportResponse } from "./adapters/stockMove/mapStockMoveImportResponse";
import { mapTemplateExportResponse } from "./adapters/stockMove/mapTemplateExportResponse";
import request from "./request";
import RequestMethods from "./request.methods";
......@@ -286,3 +296,50 @@ export function getReplenishLogListApi(data) {
data.method = "dj.api.smartcarlife.labelCode.recodeLog";
return request(data, RequestMethods.POST);
}
// 迁移库存-模糊查询轻改产品
export function listUpgradeGoodsSimple(data = {}) {
const payload = {
...buildProductManagerListUpgradeGoodsSimpleParams(data),
method: "dj.api.smartcarlife.productManager.listUpgradeGoodsSimple",
};
return request(payload, RequestMethods.POST)
.then(mapProductManagerListUpgradeGoodsSimplePageResponse);
}
// 单产品库存迁移
export function moveMerchantGoodsStock(data = {}) {
const payload = {
...buildMerchantGoodsStockMonthReportStockMoveParams(data),
method: "dj.api.smartcarlife.MerchantGoodsStockMonthReport.stockMove",
};
return request(payload, RequestMethods.POST, [], { useResponseMessage: true })
.then(mapMerchantGoodsStockMonthReportStockMoveResponse);
}
// 库存迁移导入模板
export function exportStockMoveTemplate(data = {}) {
const payload = {
...buildTemplateExportParams(data),
method: "dj.api.smartcarlife.MerchantGoodsStockMonthReport.stockMove.template.export",
};
return request(payload, RequestMethods.POST).then(mapTemplateExportResponse);
}
// 批量导入库存迁移
export function importStockMove(data = {}) {
const payload = {
...buildStockMoveImportParams(data),
method: "dj.api.smartcarlife.MerchantGoodsStockMonthReport.stockMove.import",
};
return request(payload, RequestMethods.POST, ["file"]).then(mapStockMoveImportResponse);
}
// 库存迁移日志
export function getStockMoveLogPage(data = {}) {
const payload = {
...buildLogPageParams(data),
method: "dj.api.smartcarlife.MerchantGoodsStockMonthReport.stockMove.log.page",
};
return request(payload, RequestMethods.POST).then(mapLogPagePageResponse);
}
import mockRequest from "./request";
import {
exportStockMoveTemplate,
getStockMoveLogPage,
importStockMove,
listUpgradeGoodsSimple,
moveMerchantGoodsStock,
} from "./stockManage";
jest.mock("./request", () => jest.fn(data => Promise.resolve(data)));
describe("stock move api", () => {
beforeEach(() => {
mockRequest.mockClear();
});
it("queries light-modification products for the target UID selector", async () => {
await listUpgradeGoodsSimple({
currentPage: 1,
pageSize: 20,
commodityCode: "UID",
productType: 1,
});
expect(mockRequest).toHaveBeenCalledWith({
currentPage: 1,
pageSize: 20,
commodityCode: "UID",
productType: 1,
method: "dj.api.smartcarlife.productManager.listUpgradeGoodsSimple",
}, "post");
});
it("submits all identifiers required by a single stock move", async () => {
await moveMerchantGoodsStock({
upgradeGoodsId: 1,
yqMerchantId: 2,
targetUpgradeGoodsId: 3,
});
expect(mockRequest).toHaveBeenCalledWith({
upgradeGoodsId: 1,
yqMerchantId: 2,
targetUpgradeGoodsId: 3,
method: "dj.api.smartcarlife.MerchantGoodsStockMonthReport.stockMove",
}, "post", [], { useResponseMessage: true });
});
it("uploads the batch file without including it in the signature", async () => {
const file = { name: "stock.xlsx" };
await importStockMove({ file });
expect(mockRequest).toHaveBeenCalledWith({
file,
method: "dj.api.smartcarlife.MerchantGoodsStockMonthReport.stockMove.import",
}, "post", ["file"]);
});
it("exposes template and log endpoints", async () => {
await exportStockMoveTemplate();
expect(mockRequest).toHaveBeenLastCalledWith({
method: "dj.api.smartcarlife.MerchantGoodsStockMonthReport.stockMove.template.export",
}, "post");
await getStockMoveLogPage({ upgradeGoodsId: 1, yqMerchantId: 2 });
expect(mockRequest).toHaveBeenLastCalledWith({
upgradeGoodsId: 1,
yqMerchantId: 2,
method: "dj.api.smartcarlife.MerchantGoodsStockMonthReport.stockMove.log.page",
}, "post");
});
});
import auth from "@/store/modules/d2admin/modules/auth";
// eslint-disable-next-line node/prefer-global/process
const _import = require("@/libs/util.import." + process.env.NODE_ENV);
export const routerName = {
903: {
......@@ -645,6 +644,14 @@ export const routerName = {
type: "primary",
handle: "handleBatchImport",
},
{
authId: "9031412",
parentId: "90314",
label: "批量修改采购价",
category: "Button",
type: "primary",
handle: "handleBatchModifyPrice",
},
],
component: _import("goods/purchaseOnShelves/index"),
},
......
// eslint-disable-next-line node/prefer-global/process
const _import = require("@/libs/util.import." + process.env.NODE_ENV);
export const routerName = {
908: {
......@@ -81,6 +82,21 @@ export const routerName = {
label: "日志",
handle: "handleLog",
},
{
authId: "9080207",
parentId: "90802",
label: "迁移库存",
handle: "handleStockMove",
},
{
authId: "9080208",
parentId: "90802",
label: "批量迁移库存",
category: "Button",
// type: "danger",
type: "primary",
handle: "handleBatchStockMove",
},
],
component: _import("stockManage/stock/stockList"),
},
......@@ -541,10 +557,12 @@ export const routerName = {
parentId: "90809",
cache: false,
dynamicTitle: (route) => {
if (route.query.reviewType === "operator")
if (route.query.reviewType === "operator") {
return "运营审核";
if (route.query.reviewType === "business")
}
if (route.query.reviewType === "business") {
return "商务审核";
}
return "审批";
},
},
......@@ -559,10 +577,12 @@ export const routerName = {
parentId: "90809",
cache: false,
dynamicTitle: (route) => {
if (route.query.reviewType === "operator")
if (route.query.reviewType === "operator") {
return "运营驳回";
if (route.query.reviewType === "business")
}
if (route.query.reviewType === "business") {
return "商务驳回";
}
return "驳回";
},
},
......@@ -577,10 +597,12 @@ export const routerName = {
parentId: "90810",
cache: false,
dynamicTitle: (route) => {
if (route.query.reviewType === "operator")
if (route.query.reviewType === "operator") {
return "运营审核";
if (route.query.reviewType === "business")
}
if (route.query.reviewType === "business") {
return "商务审核";
}
return "审批";
},
},
......@@ -595,10 +617,12 @@ export const routerName = {
parentId: "90810",
cache: false,
dynamicTitle: (route) => {
if (route.query.reviewType === "operator")
if (route.query.reviewType === "operator") {
return "运营驳回";
if (route.query.reviewType === "business")
}
if (route.query.reviewType === "business") {
return "商务驳回";
}
return "驳回";
},
},
......
......@@ -269,6 +269,7 @@
:label="item.label ? `${item.label}:` : ''"
:label-width="item.label ? '180px' : '0px'"
:prop="item.name"
:required="item.name === 'saleMode' ? isSaleModeRequiredScene(formData.baseSceneCode) : undefined"
:style="{ 'margin-bottom': !item.type ? '0px' : '22px' }"
>
<el-radio-group
......@@ -622,6 +623,7 @@ import {
crowdUpgradeSupplyModeList,
upgradeSupplyModeList,
} from "../constants/data";
import { isSaleModeRequiredScene } from "../utils/saleMode";
import relateStoreDialog from "./relateStoreDialog.vue";
import relateStoreTable from "./relateStoreTable.vue";
......@@ -861,6 +863,18 @@ export default {
trigger: ["change", "blur"],
},
],
saleMode: [
{
validator: (rule, value, callback) => {
if (isSaleModeRequiredScene(this.formData.baseSceneCode) && (value === "" || value === null || value === undefined)) {
callback(new Error("请选择销售模式"));
return;
}
callback();
},
trigger: ["change", "blur"],
},
],
},
storeSelected: [],
relateStoreVisible: false,
......@@ -948,6 +962,7 @@ export default {
},
methods: {
isSaleModeRequiredScene,
shouldShowPosition,
...mapActions({
get: "d2admin/base/get",
......
export const SALE_MODE_RETAIL = 0;
export const SALE_MODE_WHOLESALE = 1;
export const SALE_MODE_REQUIRED_SCENE_CODES = ["110101", "110102", "110201", "110202"];
export const saleModeList = [
{ confId: SALE_MODE_RETAIL, confName: "零售" },
{ confId: SALE_MODE_WHOLESALE, confName: "批发" },
];
export function resolveSaleMode(saleMode, saleModeStr) {
if (saleMode !== "" && saleMode !== null && saleMode !== undefined) {
return Number(saleMode) === SALE_MODE_WHOLESALE ? SALE_MODE_WHOLESALE : SALE_MODE_RETAIL;
}
return saleModeStr === "批发" ? SALE_MODE_WHOLESALE : SALE_MODE_RETAIL;
}
export function isSaleModeRequiredScene(baseSceneCode) {
return SALE_MODE_REQUIRED_SCENE_CODES.includes(String(baseSceneCode || ""));
}
import { isSaleModeRequiredScene, resolveSaleMode } from "./saleMode";
describe("sale mode", () => {
it.each([
["零售", 0],
["批发", 1],
["", 0],
[undefined, 0],
])("maps %s to %s", (saleModeStr, expected) => {
expect(resolveSaleMode(undefined, saleModeStr)).toBe(expected);
});
it("prefers a numeric API value when available", () => {
expect(resolveSaleMode("1", "零售")).toBe(1);
});
it.each(["110101", 110102, "110201", 110202])(
"requires sale mode for supported rights and warranty scene %s",
(sceneCode) => {
expect(isSaleModeRequiredScene(sceneCode)).toBe(true);
},
);
it("does not require sale mode for other scenes", () => {
expect(isSaleModeRequiredScene("100101")).toBe(false);
expect(isSaleModeRequiredScene(undefined)).toBe(false);
});
});
......@@ -78,6 +78,10 @@ export default {
type: "table",
},
{
name: "saleModeStr",
label: "销售模式",
},
{
name: "voucherList",
label: "上架凭证",
type: "upload",
......
......@@ -28,6 +28,7 @@ import { convertYuanToWan, filterSpecsStr } from "@/views/goods/filterOption";
import groundingForm from "@/views/goods/grounding/components/groundingForm.vue";
import { baseSupplyModeList, productList, upgradeSupplyModeList } from "@/views/goods/grounding/constants/data";
import { isSelfOperatedEquityExtended, mapServiceItemOption } from "@/views/goods/grounding/utils/productCost";
import { resolveSaleMode, saleModeList } from "@/views/goods/grounding/utils/saleMode";
export default {
name: "EditGrounding",
......@@ -62,6 +63,15 @@ export default {
type: "button",
},
{
name: "saleMode",
label: "销售模式",
type: "flagRadio",
radioGroupList: saleModeList.map(item => ({
label: item.confName,
value: item.confId,
})),
},
{
name: "voucherList",
label: "上架凭证",
type: "upload",
......@@ -343,6 +353,7 @@ export default {
financeCheckFlag: "N",
serviceItemId: "",
productCostType: "",
saleMode: 0,
warrantyType: 0,
},
secondGoodsList: [],
......@@ -446,6 +457,7 @@ export default {
if (isSelfOperatedEquityExtended(res.goodsType, res.supplierCode)) {
res.productCostType = 1;
}
res.saleMode = resolveSaleMode(res.saleMode, res.saleModeStr);
res.upgradeGoods = {
...res?.upgradeGoods,
goodsName: res.goodsInfo.goodsName,
......@@ -610,6 +622,7 @@ export default {
thirdPartyCost: "",
serviceItemId: "",
productCostType: "",
saleMode: 0,
};
addOrUpdateAPI(this.dealObjectValue(params)).then((res) => {
this.notice.okTips();
......
import { getShopMerchantList } from "@api/deviceManage";
import { getParkStore } from "@api/editCustomer";
import { getAllCategory, getList as getProductList } from "@api/product";
import { getAreaDataList, getBaseSceneCodeList } from "@api/productManage";
import { getList as getProductList } from "@api/product";
import { getBaseSceneCodeList } from "@api/productManage";
import { cloneDeep, isFunction } from "lodash-es";
import { BaseData, sceneCodeList } from "@/common/constants.js";
import { BaseData } from "@/common/constants.js";
import { Util } from "@/common/util";
import store from "@/store";
import { baseSupplyModeList, upgradeSupplyModeList } from "@/views/goods/grounding/constants/data";
import { financeCheckFlagList, inventoryTypeList, productCostTypeList, sellPriceTempValidStatusList, statusList } from "@/views/goods/grounding/constants/index";
import { priceFilter } from "@/views/goods/grounding/utils/number";
import { saleModeList } from "@/views/goods/grounding/utils/saleMode";
export async function getSearchFromSchema(_refreshTableFn) {
const refreshTableFn = isFunction(_refreshTableFn) ? _refreshTableFn : () => {};
......@@ -81,6 +82,15 @@ export async function getSearchFromSchema(_refreshTableFn) {
keyFn: refreshTableFn,
},
{
label: "销售模式",
name: "saleMode",
type: "select",
optionList: cloneDeep(saleModeList),
optionId: "confId",
optionLabel: "confName",
optionsName: "saleModeList",
},
{
label: "状态",
name: "status",
type: "select",
......@@ -299,6 +309,11 @@ export async function getTableSchema() {
width: 140,
},
{
label: "销售模式",
prop: "saleModeStr",
width: 100,
},
{
label: "服务对接",
prop: "yqMerchantName",
type: "slot",
......@@ -317,7 +332,7 @@ export async function getTableSchema() {
label: "业务场景",
prop: "baseSceneCode",
formatter: (cellValue) => {
return baseSceneList.find(val => val.baseSceneCode == cellValue.baseSceneCode)?.name || "-";
return baseSceneList.find(val => String(val.baseSceneCode) === String(cellValue.baseSceneCode))?.name || "-";
},
width: 130,
},
......@@ -351,7 +366,7 @@ export async function getTableSchema() {
prop: "position",
width: 140,
formatter: (cellValue) => {
return positionTypeList?.filter(val => cellValue?.position == val.position)[0]?.confName || "-";
return positionTypeList?.filter(val => String(cellValue?.position) === String(val.position))[0]?.confName || "-";
},
},
{
......@@ -366,7 +381,7 @@ export async function getTableSchema() {
prop: "baseSupplyMode",
width: 150,
formatter: (cellValue) => {
return baseSupplyModeList.find(val => val.confId == cellValue.baseSupplyMode)?.confName || "-";
return baseSupplyModeList.find(val => String(val.confId) === String(cellValue.baseSupplyMode))?.confName || "-";
},
},
{
......@@ -374,7 +389,7 @@ export async function getTableSchema() {
prop: "upgradeSupplyMode",
width: 150,
formatter: (cellValue) => {
return upgradeSupplyModeList.find(val => val.confId == cellValue.upgradeSupplyMode)?.confName || "-";
return upgradeSupplyModeList.find(val => String(val.confId) === String(cellValue.upgradeSupplyMode))?.confName || "-";
},
},
{
......@@ -382,7 +397,7 @@ export async function getTableSchema() {
prop: "inventoryType",
width: "120",
formatter: (cellValue) => {
return cellValue.inventoryType == 1 ? "虚拟" : cellValue.inventoryType == 2 ? "实物" : "-";
return Number(cellValue.inventoryType) === 1 ? "虚拟" : Number(cellValue.inventoryType) === 2 ? "实物" : "-";
},
},
{
......@@ -431,9 +446,9 @@ export async function getTableSchema() {
width: "196px",
formatter: (cellValue) => {
let sellPricevalidTypeText = "-";
if (cellValue.sellPriceValidType == 1) {
if (Number(cellValue.sellPriceValidType) === 1) {
sellPricevalidTypeText = "终生有效";
} else if (cellValue.sellPriceValidType == 2) {
} else if (Number(cellValue.sellPriceValidType) === 2) {
sellPricevalidTypeText = "临时有效";
if (cellValue.tempValidStartDate && cellValue.tempValidEndDate) {
sellPricevalidTypeText = `${Util.dateFormate(cellValue.tempValidStartDate, "YYYY-MM-DD")} 至 ${Util.dateFormate(cellValue.tempValidEndDate, "YYYY-MM-DD")}`;
......
import { getSearchFromSchema, getTableSchema } from "./index.data";
jest.mock("@api/deviceManage", () => ({ getShopMerchantList: jest.fn().mockResolvedValue([]) }));
jest.mock("@api/editCustomer", () => ({ getParkStore: jest.fn().mockResolvedValue([]) }));
jest.mock("@api/product", () => ({ getList: jest.fn().mockResolvedValue({ list: [] }) }));
jest.mock("@api/productManage", () => ({
getAreaDataList: jest.fn(),
getBaseSceneCodeList: jest.fn().mockResolvedValue([]),
}));
jest.mock("@/store", () => ({ dispatch: jest.fn().mockResolvedValue([]) }));
describe("grounding table schema", () => {
it("includes sale mode in search and result columns", async () => {
const searchSchema = await getSearchFromSchema();
const tableSchema = await getTableSchema();
expect(searchSchema.find(item => item.name === "saleMode")).toMatchObject({
type: "select",
optionId: "confId",
});
expect(tableSchema.find(item => item.label === "销售模式")).toMatchObject({
label: "销售模式",
prop: "saleModeStr",
});
const merchantIndex = tableSchema.findIndex(item => item.addHtml === "merchantName");
const saleModeIndex = tableSchema.findIndex(item => item.prop === "saleModeStr");
expect(saleModeIndex).toBe(merchantIndex + 1);
});
});
......@@ -251,6 +251,7 @@ export default {
financeCheckFlag: "",
inventoryType: "",
productCostType: "",
saleMode: "",
cityCodeList: [],
},
tempGoodsType: [],
......@@ -459,6 +460,8 @@ export default {
financeCheckFlag: "",
inventoryType: "",
productCostType: "",
saleMode: "",
cityCodeList: [],
};
this.tempGoodsType = [];
this.applicableAreas = [];
......
......@@ -230,9 +230,11 @@ export default {
// 出来form表单显示内容
filterEditForm() {
const { copyFormList, formData } = this
const productFormIndex = this.formList.findIndex(item => item.title === '产品信息')
const copyProductFormIndex = copyFormList.findIndex(item => item.title === '产品信息')
// 1 太阳膜 2 (1.3场景商品)
const shopType = formData?.goodsType == 1 ? '1' : formData?.sceneType == 3 ? '2' : ''
const shopForm = deepClone(copyFormList[0].formBlock)
const shopForm = deepClone(copyFormList[copyProductFormIndex].formBlock)
// 太阳膜保留上架部位字段 positionStr
const spliceForm = shopType == '1'
? ['giftCost', 'recoveryCost', 'virtualAccountCost', 'djCost', 'thirdPartyCost']
......@@ -258,7 +260,7 @@ export default {
// 仅选中基础产品类型 不展示 售价字段
if (formData.productType?.length == 1 && formData.productType?.includes(1)) spliceForm.push('sellPrice', 'minSellPrice', 'upgradeProductCost', 'upgradeSupplyModeStr')
const newForm = shopForm.filter(v => !spliceForm?.includes(v.name))
this.$set(this.formList[0], 'formBlock', newForm)
this.$set(this.formList[productFormIndex], 'formBlock', newForm)
this.$nextTick(() => {
this.show = true
})
......
import { validateStoreRegion } from "@api/grounding";
import GroundingForm from "./groundingForm.vue";
jest.mock("@api/grounding", () => ({
validateStoreRegion: jest.fn(),
}));
jest.mock("@api/serviceManage", () => ({ searchServiceMerchant: jest.fn() }));
jest.mock("glsk-oss-jssdk", () => jest.fn());
jest.mock("./relateStoreDialog.vue", () => ({}));
jest.mock("./relateStoreTable.vue", () => ({}));
jest.mock("../../components/selectGoodsDialog.vue", () => ({}));
jest.mock("../../components/ellipsisPopover.vue", () => ({}));
jest.mock("@/main", () => ({
baseConfig: {
equitySceneType: [],
extendedPosiType: [],
membraneTypeList: [],
},
}));
describe("purchase grounding form", () => {
it("blocks product selection until stores are selected", () => {
const warning = jest.fn();
const context = {
formData: { merchantRefList: [] },
$message: { warning },
selectGoodsVisible: false,
};
GroundingForm.methods.handleSelectGoods.call(context);
expect(warning).toHaveBeenCalledWith("请选择上架商户");
expect(context.selectGoodsVisible).toBe(false);
});
it("rolls stores back when an invalid region confirmation is cancelled", async () => {
validateStoreRegion.mockResolvedValue({
allMatch: false,
invalidUpgradeGoodsIds: [10],
});
const previousStores = [{ merchantId: 1 }];
const context = {
formData: {
upgradeGoodsId: 10,
merchantRefList: [{ merchantId: 2 }],
upgradeGoods: { upgradeGoodsName: "测试产品" },
},
$confirm: jest.fn().mockRejectedValue(new Error("cancel")),
$set(target, key, value) {
target[key] = value;
},
clearPurchaseGoods: jest.fn(),
};
await GroundingForm.methods.validateStoreRegionAfterChange.call(context, {
previousMerchantRefList: previousStores,
revertStoresOnCancel: true,
});
expect(context.formData.merchantRefList).toEqual(previousStores);
expect(context.clearPurchaseGoods).not.toHaveBeenCalled();
});
it("keeps the new stores and clears product data after invalid-region confirmation", async () => {
validateStoreRegion.mockResolvedValue({
allMatch: false,
invalidUpgradeGoodsIds: [10],
});
const context = {
formData: {
upgradeGoodsId: 10,
merchantRefList: [{ merchantId: 2 }],
upgradeGoods: { upgradeGoodsName: "测试产品" },
},
$confirm: jest.fn().mockResolvedValue(),
$set: jest.fn(),
clearPurchaseGoods: jest.fn(),
};
await GroundingForm.methods.validateStoreRegionAfterChange.call(context);
expect(context.clearPurchaseGoods).toHaveBeenCalledTimes(1);
expect(context.formData.merchantRefList).toEqual([{ merchantId: 2 }]);
});
it("blocks submit and identifies stores outside the product supply region", async () => {
validateStoreRegion
.mockResolvedValueOnce({ allMatch: true, invalidUpgradeGoodsIds: [] })
.mockResolvedValueOnce({ allMatch: false, invalidUpgradeGoodsIds: [10] });
const warning = jest.fn();
const context = {
formData: {
upgradeGoodsId: 10,
upgradeGoods: { upgradeGoodsName: "产品A" },
merchantRefList: [
{ merchantId: 1, merchantName: "杭州店" },
{ merchantId: 2, merchantName: "宁波店" },
],
},
$message: { warning },
};
const result = await GroundingForm.methods.validateCurrentStoreRegions.call(context);
expect(result).toBe(false);
expect(warning).toHaveBeenCalledWith("产品A不在宁波店供给范围内");
});
it("leaves product supply-source validation to the backend", async () => {
const emit = jest.fn();
const validate = jest.fn(callback => callback(true));
const context = {
formData: {
purchaseCostType: 0,
upgradeGoods: {
supplySource: "3",
},
},
formRef: "",
$message: { warning: jest.fn() },
$refs: {
d2FormRuleForm: { validate },
},
$emit: emit,
validateCurrentStoreRegions: jest.fn().mockResolvedValue(true),
};
await GroundingForm.methods.handleUp.call(context, 1);
expect(validate).toHaveBeenCalledTimes(1);
expect(emit).toHaveBeenCalledWith("handleAddConfirm", expect.objectContaining({ num: 1 }));
});
});
import { shallowMount } from "@vue/test-utils";
import RelateStoreDialog from "./relateStoreDialog.vue";
describe("purchase shelves merchant dialog", () => {
it("shows merchant address immediately after merchant name", async () => {
const wrapper = shallowMount(RelateStoreDialog, {
propsData: {
storeApi: jest.fn().mockResolvedValue({ list: [], total: 0 }),
},
stubs: {
"d2-dialog": { template: "<div><slot /></div>" },
"el-button": { template: "<button><slot /></button>" },
"el-pagination": true,
"el-row": { template: "<div><slot /></div>" },
"el-table": { template: "<div><slot /></div>" },
"el-table-column": {
props: ["prop"],
template: "<div class='merchant-column' :data-prop='prop'></div>",
},
},
});
await wrapper.vm.$nextTick();
const columnProps = wrapper.findAll(".merchant-column").wrappers.map(column => column.attributes("data-prop"));
expect(columnProps.slice(1, 4)).toEqual(["merchantName", "address", "merchantId"]);
});
});
......@@ -17,6 +17,7 @@ import { mapActions } from 'vuex'
import { deepClone } from '@/common/util'
import { baseConfig } from '@/main'
import { filterSpecsStr, convertYuanToWan } from "../filterOption"
import { purchaseCostTypeList, resolvePurchasePrice } from "./utils/purchaseCost"
export default {
name: 'EditGrounding',
components: {
......@@ -64,6 +65,11 @@ export default {
unit: true
},
{
label: '运营成本',
value: 'operationCost',
unit: true
},
{
label: '参考售价',
value: 'upgradePrice',
unit: true
......@@ -101,6 +107,15 @@ export default {
value: "purchaseGoodsName"
},
{
name: 'purchaseCostType',
label: '采购价带入方式',
type: 'flagRadio',
radioGroupList: purchaseCostTypeList.map(item => ({
label: item.confName,
value: item.confId
}))
},
{
name: 'purchasePrice',
label: '采购价',
type: 'input',
......@@ -164,6 +179,7 @@ export default {
baseSupplyMode: '',
upgradeSupplyMode: '',
purchasePrice: '',
purchaseCostType: 1,
// minSellPrice: '',
giveCostPrice: '',
recoveryCostPrice: '',
......@@ -183,6 +199,7 @@ export default {
}
},
mounted() {
this.editForm = [this.editForm[1], this.editForm[0]]
this.getBaseData()
const id = this.$route.query.id
if (!id) {
......@@ -253,6 +270,11 @@ export default {
carTypeConfigName: res?.upgradeGoods?.carTypeConfigList?.map(item => item.seriesName).join('/'),
upgradeCommodityCode: res?.upgradeGoods?.commodityCode
}
res.purchasePrice = resolvePurchasePrice({
purchaseCostType: res.purchaseCostType,
purchasePrice: res.purchasePrice,
operationCost: res.upgradeGoods?.operationCost
})
this.editData = res || {}
this.$nextTick(() => {
this.show = true
......
......@@ -17,6 +17,7 @@ import { deepClone, Util } from '@/common/util'
import { productList, baseSupplyModeList, upgradeSupplyModeList, crowdUpgradeSupplyModeList } from './constants/data'
import { baseConfig } from "@/main"
import { filterSpecsStr, convertYuanToWan } from '../filterOption'
import { getPurchaseCostTypeText } from './utils/purchaseCost'
export default {
name: 'purchaseOnShelvesGroundingDetail',
components: {
......@@ -115,6 +116,19 @@ export default {
handleInput: true
},
{
name: 'operationCost',
label: '产品运营成本',
type: 'input',
width: '432px',
unit: true
},
{
name: 'purchaseCostTypeStr',
label: '采购价带入方式',
type: 'input',
width: '432px'
},
{
name: 'suitCarType',
label: '适用车型',
type: 'flagRadio',
......@@ -255,6 +269,7 @@ export default {
}
},
mounted() {
this.editForm = [this.editForm[1], this.editForm[0], this.editForm[2]]
this.getBaseData()
// 获取商品详情
const id = this.$route.query.id
......@@ -318,6 +333,8 @@ export default {
carTypeConfigName: res?.upgradeGoods?.carTypeConfigList?.map(item => item.seriesName).join('/'),
upgradeCommodityCode: res?.upgradeGoods?.commodityCode
}
res.operationCost = res.upgradeGoods?.operationCost
res.purchaseCostTypeStr = getPurchaseCostTypeText(res.purchaseCostType)
const { commodityCode, upgradeGoodsName } = res.upgradeGoods
res.commodityCode = commodityCode
res.upgradeGoodsName = upgradeGoodsName
......
......@@ -45,6 +45,10 @@
<span style="display: inline-block;margin-left: 10px;">
<auth-button category="Button" :show-btn-ids="['9031402']" />
</span>
<!-- 批量修改采购价 -->
<span style="display: inline-block;margin-left: 10px;">
<auth-button category="Button" :show-btn-ids="['9031412']" />
</span>
</d2-table-header>
<d2-table ref="groundingIndexTable" :has-num="false" :search-form="searchForm" :table-params="tableParams"
:get-list-api="getListApi" :before-search-fn="beforeSearchFn" :selectable-fn="selectableFn"
......@@ -119,6 +123,18 @@
</batch-copy-dialog>
<d2-file-import-dialog :is-visible="fileVisible" title="上传文件" @closeDialog="handleBatchImport"
@confirmDialog="handleConfirmImport" @downloadTemplate="exportTemplate" />
<d2-dialog title="批量修改采购价" width="480px" :is-visible="batchPriceVisible"
@closeDialog="handleBatchPriceClose" @confirmDialog="handleBatchPriceConfirm">
<p class="batch-price-summary">
已选择{{ batchPriceSummary.goodsCount }}个商品和涉及{{ batchPriceSummary.merchantCount }}个门店
</p>
<el-form ref="batchPriceForm" :model="batchPriceForm" :rules="batchPriceRules" label-width="100px">
<el-form-item label="采购价:" prop="purchasePrice">
<el-input-number v-model="batchPriceForm.purchasePrice" :min="0" :max="999999.99" :precision="2"
:step="1" controls-position="right" style="width: 300px;" />
</el-form-item>
</el-form>
</d2-dialog>
</d2-container>
</template>
<script>
......@@ -127,7 +143,8 @@ import { getList, getAllCategory } from '@api/product'
import {
purchaseGoodsInfoPage as getGroundingManageList, purchaseGoodsInfoUpdateStatus as updateGoodsStatus, purchaseGoodsInfoUpdateBatchWaitAudit as batchReviewAPI,
purchaseGoodsInfoDeleteById as delGroundingById, purchaseGoodsInfoUpdateBatchOffShelf as batchUpdateStatus,
batchUpdateBatchCopy, batchSetValidMinSellPrice, purchaseGoodsInfoImport as groundingImport
batchUpdateBatchCopy, batchSetValidMinSellPrice, purchaseGoodsInfoImport as groundingImport,
purchaseGoodsInfoUpdateBatchPrice
} from '@api/grounding'
import { deepClone, Util } from '@/common/util'
import { sceneCodeList, sceneList, BaseData } from '@/common/constants.js'
......@@ -135,6 +152,8 @@ import { getParkStore } from '@api/editCustomer'
import { mapActions, mapState, mapMutations } from 'vuex'
import { baseConfig } from '@/main'
import batchCopyDialog from './components/batchCopyDialog.vue'
import { getBatchPriceSelectionSummary, hasUnsupportedPurchaseCostType } from './utils/batchPrice'
import { getPurchaseCostTypeText, purchaseCostTypeList } from './utils/purchaseCost'
export default {
components: { batchCopyDialog },
name: 'PurchaseOnShelves',
......@@ -157,7 +176,8 @@ export default {
goodsSource: 0,
financeCheckFlag: '',
thirdPartyName: '',
thirdPartyCode: ''
thirdPartyCode: '',
purchaseCostType: ''
},
tempGoodsType: [],
getListApi: getGroundingManageList,
......@@ -260,6 +280,14 @@ export default {
type: 'input',
isClear: true,
keyFn: this.keyDowmGetList
}, {
label: '采购价带入方式',
name: 'purchaseCostType',
type: 'select',
optionList: [],
optionId: 'confId',
optionLabel: 'confName',
optionsName: 'purchaseCostTypeList'
}
// {
// label: '财务校验',
......@@ -363,6 +391,12 @@ export default {
addHtml: 'merchantName',
width: 140
},
{
label: '采购价带入方式',
prop: 'purchaseCostType',
width: 160,
formatter: cellValue => getPurchaseCostTypeText(cellValue.purchaseCostType)
},
// {
// label: '服务对接',
// prop: 'yqMerchantName',
......@@ -519,13 +553,25 @@ export default {
}, {
confId: 'N',
confValue: '关闭'
}]
}],
purchaseCostTypeList: deepClone(purchaseCostTypeList)
},
selfBuildGoodsType: baseConfig.selfBuildGoodsType || '',
batchCopySelectScene: '', // 批量复制选中的场景值
batchCopyVisible: false,
batchCopySelectData: [], // 批量辅助选中的上架数据
fileVisible: false
fileVisible: false,
batchPriceVisible: false,
batchPriceForm: {
purchasePrice: undefined
},
batchPriceSummary: {
goodsCount: 0,
merchantCount: 0
},
batchPriceRules: {
purchasePrice: [{ required: true, message: '请输入采购价', trigger: 'blur' }]
}
}
},
mounted() {
......@@ -740,7 +786,8 @@ export default {
status: '',
yqMerchantId: '',
goodsSource: 0,
financeCheckFlag: ''
financeCheckFlag: '',
purchaseCostType: ''
}
this.tempGoodsType = []
// 重新查询
......@@ -788,7 +835,7 @@ export default {
})
},
handleExport() {
var params = this.searchForm
var params = deepClone(this.searchForm)
params.method = 'dj.api.smartcarlife.purchaseGoodsInfo.export.async'
const list = [
...this.dowloadList,
......@@ -801,6 +848,43 @@ export default {
]
this.actionSetDownloadList({ list, type: 'dowloadList' })
},
getSelectedRows() {
return this.$refs.groundingIndexTable?.mutiSelectArr?.groundingIndex || []
},
handleBatchModifyPrice() {
const selectedRows = this.getSelectedRows()
if (!selectedRows.length) {
return this.$message.warning('请选择需要修改采购价的记录')
}
if (hasUnsupportedPurchaseCostType(selectedRows)) {
return this.$message.warning('批量修改仅支持自定义成本的上架ID')
}
this.batchPriceSummary = getBatchPriceSelectionSummary(selectedRows)
this.batchPriceVisible = true
},
handleBatchPriceClose() {
this.batchPriceVisible = false
this.batchPriceForm.purchasePrice = undefined
this.batchPriceSummary = {
goodsCount: 0,
merchantCount: 0
}
this.$refs.batchPriceForm?.clearValidate()
},
handleBatchPriceConfirm() {
this.$refs.batchPriceForm.validate(valid => {
if (!valid) return
const ids = this.getSelectedRows().map(item => item.id)
purchaseGoodsInfoUpdateBatchPrice({
ids,
purchasePrice: this.batchPriceForm.purchasePrice
}).then(() => {
this.notice.okTips()
this.handleBatchPriceClose()
this.$refs.groundingIndexTable.refreshTable()
})
})
},
// 校验是否为空 不包含0
filterEmpty(data) {
return data instanceof Array ? data.length <= 0 : (data ?? '') === ''
......@@ -958,5 +1042,10 @@ export default {
margin-left: 8px;
}
.batch-price-summary {
margin: 0 0 20px 100px;
color: #606266;
}
}
</style>
import { PURCHASE_COST_TYPE_CUSTOM } from "./purchaseCost";
export function hasUnsupportedPurchaseCostType(rows = []) {
return rows.some(row => Number(row.purchaseCostType) !== PURCHASE_COST_TYPE_CUSTOM);
}
export function getBatchPriceSelectionSummary(rows = []) {
const merchantNumberSet = new Set();
rows.forEach((row) => {
(row.merchantRefList || []).forEach((merchant) => {
const merchantNumber = merchant.merchantId ?? merchant.merchantNo;
if (merchantNumber !== "" && merchantNumber !== null && merchantNumber !== undefined) {
merchantNumberSet.add(String(merchantNumber));
}
});
});
return {
goodsCount: rows.length,
merchantCount: merchantNumberSet.size,
};
}
import {
getBatchPriceSelectionSummary,
hasUnsupportedPurchaseCostType,
} from "./batchPrice";
describe("purchase batch price", () => {
it("rejects selections containing an automatic-cost record", () => {
expect(hasUnsupportedPurchaseCostType([
{ purchaseCostType: 0 },
{ purchaseCostType: "1" },
])).toBe(true);
expect(hasUnsupportedPurchaseCostType([
{ purchaseCostType: 0 },
{ purchaseCostType: "0" },
])).toBe(false);
});
it("counts selected goods and distinct merchant numbers", () => {
expect(getBatchPriceSelectionSummary([
{
id: 1,
merchantRefList: [
{ merchantId: 1001 },
{ merchantNo: "1002" },
],
},
{
id: 2,
merchantRefList: [
{ merchantId: "1001" },
{ merchantId: 1003 },
],
},
])).toEqual({
goodsCount: 2,
merchantCount: 3,
});
});
});
export const PURCHASE_COST_TYPE_CUSTOM = 0;
export const PURCHASE_COST_TYPE_AUTO = 1;
export const purchaseCostTypeList = [
{ confId: PURCHASE_COST_TYPE_AUTO, confName: "默认带入产品成本" },
{ confId: PURCHASE_COST_TYPE_CUSTOM, confName: "自定义成本" },
];
export function isAutoPurchaseCostType(value) {
return Number(value) === PURCHASE_COST_TYPE_AUTO;
}
export function hasOperationCost(value) {
return value !== "" && value !== null && value !== undefined;
}
export function resolvePurchasePrice({ purchaseCostType, purchasePrice, operationCost }) {
return isAutoPurchaseCostType(purchaseCostType) ? operationCost : purchasePrice;
}
export function getPurchaseCostTypeText(value) {
return Number(value) === PURCHASE_COST_TYPE_CUSTOM ? "自定义成本" : "默认带入产品成本";
}
import {
getPurchaseCostTypeText,
hasOperationCost,
resolvePurchasePrice,
} from "./purchaseCost";
describe("purchase cost mode", () => {
it("uses the precise SKU operation cost in automatic mode", () => {
expect(resolvePurchasePrice({
purchaseCostType: 1,
purchasePrice: 20,
operationCost: 36.8,
})).toBe(36.8);
});
it("keeps the current price in custom mode", () => {
expect(resolvePurchasePrice({
purchaseCostType: 0,
purchasePrice: 20,
operationCost: 36.8,
})).toBe(20);
});
it("treats zero as a maintained operation cost", () => {
expect(hasOperationCost(0)).toBe(true);
expect(hasOperationCost("")).toBe(false);
});
it("maps cost modes to display text", () => {
expect(getPurchaseCostTypeText(0)).toBe("自定义成本");
expect(getPurchaseCostTypeText("1")).toBe("默认带入产品成本");
});
});
......@@ -27,6 +27,11 @@
inactive-value="0">
</el-switch>
</template>
<template #lowPriceOrder>
<el-switch v-model="searchForm.lowPriceFlag" active-color="#2A58AD" active-value="1"
inactive-value="0">
</el-switch>
</template>
</d2-search>
<div class="up-btns">
<el-button size="small" type="primary" @click="handleSearch">
......@@ -174,11 +179,11 @@
<auth-button v-if="scope.row.profitAllocationStatus == 5" :data="scope.row" :show-btn-ids="['9040107']" />
<div>
<!-- 通过 -->
<auth-button v-if="scope.row.canApplyFlag == 1" :data="scope.row" :show-btn-ids="['9040147']" />
<auth-button v-if="scope.row.canApplyFlag == 1 || approveAuthFlag" :data="scope.row" :show-btn-ids="['9040147']" />
</div>
<div>
<!-- 驳回 -->
<auth-button v-if="scope.row.canApplyFlag == 1" :data="scope.row" :show-btn-ids="['9040148']" />
<auth-button v-if="scope.row.canApplyFlag == 1 || rejectAuthFlag" :data="scope.row" :show-btn-ids="['9040148']" />
</div>
</template>
</el-table-column>
......@@ -578,6 +583,10 @@ export default {
label: "我的待审",
addHtml: "myPendingReview",
},
{
label: "仅查看低价订单",
addHtml: "lowPriceOrder",
},
],
searchForm: {
sceneType: 1,
......@@ -605,6 +614,7 @@ export default {
djOrderType: "",
goodsOrderApplyStatus: "",
myWaitApplySwitch: 0,
lowPriceFlag: 0,
},
baseData: {
orderStatusList: [
......@@ -756,6 +766,8 @@ export default {
totalCount: "",
jurisdictionFlag: false, // 待补录按钮权限标识
signRefundFlag: false, // 标记退款权限标识
approveAuthFlag: false, // 通过按钮权限标识
rejectAuthFlag: false, // 驳回按钮权限标识
subShopMerchanShowHide: true,
ruleVisible: false,
recordInfo: null,
......@@ -893,6 +905,14 @@ export default {
if (signRefundItem) {
this.signRefundFlag = true; // 是否有标记退款权限
}
const approveItem = $store.find(i => i.authId === "9040147");
const rejectItem = $store.find(i => i.authId === "9040148");
if (approveItem) {
this.approveAuthFlag = true;
}
if (rejectItem) {
this.rejectAuthFlag = true;
}
this.getBaseData();
const hasCustomerFilter = this.customerFilter
&& (this.customerFilter.customerName || this.customerFilter.customerPhone);
......@@ -973,6 +993,7 @@ export default {
djOrderType: "",
goodsOrderApplyStatus: "",
myWaitApplySwitch: 0,
lowPriceFlag: 0,
};
this.tempGoodsType = [];
// this.baseData.storeIdList = []
......
......@@ -21,8 +21,8 @@ export default {
},
computed: {
styleConfig() {
return BIZ_TYPE_STYLE[this.bizType]
|| BIZ_TYPE_STYLE[this.bizTypeName]
return BIZ_TYPE_STYLE[this.bizTypeName]
|| BIZ_TYPE_STYLE[this.bizType]
|| { label: this.bizTypeName || "—", bg: "#F5F5F5", color: "#666" };
},
displayLabel() {
......
......@@ -5,40 +5,35 @@ import {
} from "./utils/journalDateTime";
export const JOURNAL_TABS = [
{ key: "staffDaily", label: "驻店日报", journalType: 1 },
{ key: "storeDaily", label: "门店日报", journalType: 2 },
{ key: "negotiation", label: "洽谈明细", journalType: 3 },
];
export const BIZ_TYPE_TOOLTIP = "轻改:1.1精品升级、1.2次新车升配、1.3售后众筹;权益:2.1.1售前会员权益升级、2.1.2售后会员权益升级、2.3.1售前延保、2.3.2售后延保";
export const BIZ_TYPE_TOOLTIP = "轻改:1.1精品升级、1.2次新车升配、1.3售后众筹;延保:2.3.1售前延保、2.3.2售后延保;权益:2.1.1售前会员权益升级、2.1.2售后会员权益升级";
export const BIZ_TYPE_STYLE = {
1: { label: "轻改", bg: "#E8F3FF", color: "#1677FF" },
2: { label: "权益", bg: "#F3E8FF", color: "#722ED1" },
轻改: { label: "轻改", bg: "#E8F3FF", color: "#1677FF" },
延保: { label: "延保", bg: "#FFF7E6", color: "#D46B08" },
权益: { label: "权益", bg: "#F3E8FF", color: "#722ED1" },
};
export const TAB_TRACK_CODE_MAP = {
staffDaily: "journal_web_tab_click_staff_daily",
storeDaily: "journal_web_tab_click_store_daily",
negotiation: "journal_web_tab_click_negotiation_detail",
};
export const LIST_API_MAP = {
staffDaily: "getDailyReportOverviewPage",
storeDaily: "getDailyReportOverviewPage",
negotiation: "getDailyReportOverviewPage",
};
export function getTemplateTypeByTabKey(tabKey) {
const tab = JOURNAL_TABS.find(item => item.key === tabKey);
return tab?.journalType ?? 1;
return tab?.journalType ?? 2;
}
export function getTabKeyByTemplateType(templateType) {
const tab = JOURNAL_TABS.find(item => item.journalType === templateType);
return tab?.key ?? "staffDaily";
return tab?.key ?? "storeDaily";
}
export { formatJournalDate, formatJournalDateTime } from "./utils/journalDateTime";
......@@ -77,13 +72,6 @@ function createEmptyTextColumn(label, prop, options = {}) {
}
export const TABLE_COLUMNS_MAP = {
staffDaily: [
{ label: "驻店人员", prop: "staffName", minWidth: "100px", showOverFlow: true },
bizTypeColumn,
{ label: "所属门店", prop: "merchantName", minWidth: "160px", showOverFlow: true, align: "center" },
createEmptyTextColumn("今日出勤", "attendanceStatus", { width: "100px" }),
createDateTimeColumn("最近保存时间", "lastSaveTime"),
],
storeDaily: [
{
label: "所属门店",
......@@ -107,22 +95,14 @@ export const TABLE_COLUMNS_MAP = {
showOverFlow: true,
}),
],
negotiation: [
{ label: "驻店人员", prop: "staffName", minWidth: "100px", showOverFlow: true },
bizTypeColumn,
{ label: "所属门店", prop: "merchantName", minWidth: "160px", showOverFlow: true, align: "center" },
createDateTimeColumn("最近保存时间", "lastSaveTime"),
],
};
export function getDetailTitle(detail, journalType) {
const { staffName, merchantName, reportDate } = detail;
const { merchantName, reportDate } = detail;
const formattedDate = formatJournalDate(reportDate);
const dateText = formattedDate !== JOURNAL_EMPTY_TEXT ? `(${formattedDate})` : "";
const titleMap = {
staffDaily: `${staffName}的驻店日报${dateText}`,
storeDaily: `${merchantName}的门店日报${dateText}`,
negotiation: `${staffName}的洽谈明细${dateText}`,
};
return titleMap[journalType] || "";
}
......@@ -20,11 +20,21 @@
</template>
<script>
import {
getDailyReportDetailSelect,
getDailyReportMerchantBrandIds,
} from "@api/journalRecord";
import VenusBackButton from "@/components/venusBackButton/index.vue";
import { getDailyReportDetailSelect } from "@api/journalRecord";
import BizTypeTag from "./components/BizTypeTag.vue";
import DynamicFormReadonly from "./components/DynamicFormReadonly.vue";
import { getDetailTitle } from "./constants";
import {
isStoreDailyJournalType,
isStoreDailyTemplateType,
normalizeJournalListQuery,
STORE_DAILY_TAB_KEY,
STORE_DAILY_TEMPLATE_TYPE,
} from "./utils/journalAccess";
export default {
name: "JournalDetail",
......@@ -49,6 +59,24 @@ export default {
this.fetchDetail();
},
methods: {
async resolveDetailBrandIds(detail, merchantId) {
if (Array.isArray(detail.brandIds) && detail.brandIds.length) {
return detail.brandIds;
}
try {
return await getDailyReportMerchantBrandIds(detail.merchantId || merchantId);
} catch (error) {
console.error("[JournalDetail] merchant brand query failed", error);
return [];
}
},
redirectDisabledJournal(reportDate) {
this.$message.warning("该汇报类型已停用");
this.$router.replace({
name: "journalRecord",
query: normalizeJournalListQuery({ reportDate }),
});
},
async fetchDetail() {
const {
id,
......@@ -57,11 +85,19 @@ export default {
merchantId,
staffUuid,
sceneType,
baseSceneCode,
brandIds,
bizType,
bizTypeName,
} = this.$route.query;
if (!isStoreDailyJournalType(journalType)) {
this.redirectDisabledJournal(reportDate);
return;
}
if (!id) {
return;
}
this.journalType = journalType;
this.journalType = STORE_DAILY_TAB_KEY;
this.pageLoading = true;
try {
const res = await getDailyReportDetailSelect({
......@@ -71,9 +107,20 @@ export default {
merchantId,
staffUuid,
sceneType,
baseSceneCode,
brandIds,
bizType,
bizTypeName,
templateType: STORE_DAILY_TEMPLATE_TYPE,
});
if (!isStoreDailyTemplateType(res.templateType)) {
this.redirectDisabledJournal(reportDate);
return;
}
const resolvedBrandIds = await this.resolveDetailBrandIds(res, merchantId);
this.detail = {
...res,
brandIds: resolvedBrandIds,
reportDate: res.reportDate || reportDate,
};
} finally {
......
......@@ -14,21 +14,20 @@
</div>
<div class="journal-record__search">
<d2-search ref="showSearch"
class="show-search"
<d2-search class="show-search"
:form-data="currentFormData"
:label-width="labelWidth"
:search-form="searchForm">
<template slot="merchantHtml">
<el-select v-model="searchForm.merchantId"
v-el-select-loadmore="loadMoreMerchants"
placeholder="请选择门店"
style="width: 100%;"
clearable
filterable
:loading="merchantLoading"
placeholder="请输入门店名称搜索"
remote
reserve-keyword
style="width: 100%;"
:loading="merchantLoading"
:remote-method="remoteMerchantMethod"
@change="handleMerchantChange"
@visible-change="handleMerchantVisibleChange">
......@@ -52,8 +51,8 @@
</div>
</div>
<d2-table ref="journalTable"
:key="activeTab"
<d2-table :key="activeTab"
ref="journalTable"
:before-search-fn="beforeSearchFn"
:get-list-api="currentListApi"
:has-num="false"
......@@ -76,13 +75,13 @@
</template>
<script>
import dayjs from "dayjs";
import { deepClone } from "@/common/util";
import reportTrackFunMixin from "@/mixins/reportTrackFunMixin";
import {
getDailyReportMerchantListPage,
getDailyReportOverviewPage,
} from "@api/journalRecord";
import dayjs from "dayjs";
import { deepClone } from "@/common/util";
import reportTrackFunMixin from "@/mixins/reportTrackFunMixin";
import BizTypeTag from "./components/BizTypeTag.vue";
import DateNav from "./components/DateNav.vue";
import {
......@@ -90,6 +89,10 @@ import {
TAB_TRACK_CODE_MAP,
TABLE_COLUMNS_MAP,
} from "./constants";
import {
normalizeJournalListQuery,
STORE_DAILY_TAB_KEY,
} from "./utils/journalAccess";
const DEFAULT_SEARCH_FORM = {
merchantId: "",
......@@ -127,7 +130,7 @@ export default {
return {
labelWidth: "90px",
tabList: JOURNAL_TABS,
activeTab: "staffDaily",
activeTab: STORE_DAILY_TAB_KEY,
reportDate: dayjs().format("YYYY-MM-DD"),
searchForm: deepClone(DEFAULT_SEARCH_FORM),
searchFormSearch: {},
......@@ -146,27 +149,17 @@ export default {
name: "merchantId",
addHtml: "merchantHtml",
},
{
label: "驻店人员",
name: "staffName",
type: "input",
isClear: true,
placeholder: "请输入",
},
],
};
},
computed: {
currentListApi() {
return (params) => getDailyReportOverviewPage({
return params => getDailyReportOverviewPage({
...params,
reportDate: params.reportDate || this.reportDate,
}, this.activeTab);
},
currentFormData() {
if (this.activeTab === "storeDaily") {
return this.baseFormData.filter((item) => item.name === "merchantId");
}
return this.baseFormData;
},
tableParams() {
......@@ -186,10 +179,8 @@ export default {
},
methods: {
restoreStateFromRoute() {
const { journalType, reportDate } = this.$route.query;
if (journalType && this.tabList.some((item) => item.key === journalType)) {
this.activeTab = journalType;
}
const { reportDate } = this.$route.query;
this.activeTab = STORE_DAILY_TAB_KEY;
if (reportDate && dayjs(reportDate).isValid()) {
this.reportDate = reportDate;
}
......@@ -202,15 +193,15 @@ export default {
return;
}
this.$router.replace({
query: {
query: normalizeJournalListQuery({
...this.$route.query,
journalType: this.activeTab,
reportDate: this.reportDate,
},
}),
});
},
async initPage() {
this.restoreStateFromRoute();
this.syncRouteQuery();
this.setReportTrackData(0, "journal_web_page_entry", {});
this.handleSearch();
},
......@@ -273,7 +264,7 @@ export default {
return;
}
this.selectedMerchant = this.baseData.storeOptions.find(
(item) => item.merchantId === merchantId,
item => item.merchantId === merchantId,
) || this.selectedMerchant;
},
resetMerchantSearch() {
......@@ -341,6 +332,10 @@ export default {
merchantId: row.merchantId,
staffUuid: row.staffUuid,
sceneType: row.sceneType,
baseSceneCode: row.baseSceneCode,
brandIds: row.brandIds,
bizType: row.bizType,
bizTypeName: row.bizTypeName,
},
});
}
......
export const STORE_DAILY_TAB_KEY = "storeDaily";
export const STORE_DAILY_TEMPLATE_TYPE = 2;
export function isStoreDailyJournalType(journalType) {
return journalType === STORE_DAILY_TAB_KEY;
}
export function isStoreDailyTemplateType(templateType) {
return templateType == null || Number(templateType) === STORE_DAILY_TEMPLATE_TYPE;
}
export function normalizeJournalListQuery(query = {}) {
return {
...query,
journalType: STORE_DAILY_TAB_KEY,
};
}
import dayjs from "dayjs";
import customParseFormat from "dayjs/plugin/customParseFormat";
export const JOURNAL_EMPTY_TEXT = "—";
dayjs.extend(customParseFormat);
export const JOURNAL_EMPTY_TEXT = "-";
const JOURNAL_DATE_TIME_FORMATS = [
"YYYY-MM-DD",
"YYYY-MM-DD HH:mm",
"YYYY-MM-DD HH:mm:ss",
"YYYY-MM-DDTHH:mm",
"YYYY-MM-DDTHH:mm:ss",
];
function parseJournalDateTime(value) {
if (typeof value !== "string") {
return dayjs(value);
}
const normalized = value.trim();
for (const sourcePattern of JOURNAL_DATE_TIME_FORMATS) {
const parsed = dayjs(normalized, sourcePattern, true);
if (parsed.isValid()) {
return parsed;
}
}
return null;
}
function formatByPattern(value, pattern) {
if (value == null || value === "") {
return JOURNAL_EMPTY_TEXT;
}
const formatted = dayjs(value).format(pattern);
return formatted === "Invalid Date" ? JOURNAL_EMPTY_TEXT : formatted;
const parsed = parseJournalDateTime(value);
return parsed?.isValid() ? parsed.format(pattern) : JOURNAL_EMPTY_TEXT;
}
export function formatJournalDate(value) {
......@@ -15,5 +40,5 @@ export function formatJournalDate(value) {
}
export function formatJournalDateTime(value) {
return formatByPattern(value, "YYYY-MM-DD HH:mm:ss");
return formatByPattern(value, "YYYY-MM-DD HH:mm");
}
......@@ -7,7 +7,7 @@ import { filterFormListForDisplay } from "./journalFormVisibility";
const EMPTY_TEXT = "—";
function sortBySortNum(list = []) {
return [ ...list ].sort((a, b) => String(a.sortNum || "").localeCompare(String(b.sortNum || ""), undefined, { numeric: true }));
return [...list].sort((a, b) => String(a.sortNum || "").localeCompare(String(b.sortNum || ""), undefined, { numeric: true }));
}
function parseJsonContent(jsonContent) {
......@@ -38,7 +38,7 @@ function mergeSchemaWithFieldDataList(schemaList = [], fieldDataList = []) {
valueMap[item.fieldKey] = item.fieldValue;
}
});
return schemaList.map((field) => ({
return schemaList.map(field => ({
...field,
value: valueMap[field.key] !== undefined ? valueMap[field.key] : field.value,
}));
......@@ -69,7 +69,7 @@ function hasSubformRowData(value) {
if (!Array.isArray(value) || !value.length) {
return false;
}
return value.some((row) => Array.isArray(row) && row.length);
return value.some(row => Array.isArray(row) && row.length);
}
function normalizeSubformField(field = {}) {
......@@ -81,7 +81,7 @@ function normalizeSubformField(field = {}) {
if (!hasSubformRowData(value) && Array.isArray(field.childrenValue) && field.childrenValue.length) {
value = field.childrenValue.map((rowEntry) => {
const rowData = extractSubformRowData(rowEntry, field.key);
return template.map((col) => ({
return template.map(col => ({
...col,
value: rowData[col.key],
}));
......@@ -89,13 +89,13 @@ function normalizeSubformField(field = {}) {
}
return {
...field,
children: template.length ? [ template ] : field.children,
children: template.length ? [template] : field.children,
value,
};
}
function normalizeFormList(formList = []) {
return formList.map((field) => normalizeSubformField(field));
return formList.map(field => normalizeSubformField(field));
}
/**
......@@ -113,7 +113,14 @@ function findOptionLabel(options = [], value) {
if (value == null || value === "") {
return "";
}
const hit = (options || []).find((item) => String(item.value) === String(value));
const valueAliases = typeof value === "object"
? [value.value, value.id].filter(alias => alias != null && alias !== "").map(String)
: [String(value)];
const hit = (options || []).find(item =>
[item.value, item.id]
.filter(alias => alias != null && alias !== "")
.map(String)
.some(alias => valueAliases.includes(alias)));
return hit?.label ?? "";
}
......@@ -130,14 +137,14 @@ function formatCarBrandValue(raw) {
raw.vehicleSubBrandName,
raw.vehicleSeriesName,
raw.vehicleShapeName,
].filter((part) => part != null && part !== "");
].filter(part => part != null && part !== "");
return parts.length ? parts.join(" / ") : EMPTY_TEXT;
}
return String(raw);
}
function isLabelValueObject(raw) {
return raw != null && typeof raw === "object" && !Array.isArray(raw) && "text" in raw;
return raw != null && typeof raw === "object" && !Array.isArray(raw);
}
function resolveLabelValueRaw(raw, type) {
......@@ -147,6 +154,12 @@ function resolveLabelValueRaw(raw, type) {
if (raw.text != null && raw.text !== "") {
return raw.text;
}
if (raw.name != null && raw.name !== "") {
return raw.name;
}
if (raw.label != null && raw.label !== "") {
return raw.label;
}
if (type === "carBrandSelect" && raw.value != null) {
return formatCarBrandValue(raw.value);
}
......@@ -169,6 +182,10 @@ export function formatEchoValue(field = {}) {
switch (type) {
case "radio":
case "select": {
const optionLabel = findOptionLabel(options, raw);
if (optionLabel) {
return optionLabel;
}
const displayRaw = resolveLabelValueRaw(raw, type);
if (displayRaw !== raw) {
return String(displayRaw);
......@@ -176,8 +193,12 @@ export function formatEchoValue(field = {}) {
return findOptionLabel(options, raw) || String(raw);
}
case "multipleSelect": {
const list = Array.isArray(raw) ? raw : [ raw ];
const list = Array.isArray(raw) ? raw : [raw];
const labels = list.map((item) => {
const optionLabel = findOptionLabel(options, item);
if (optionLabel) {
return optionLabel;
}
const displayItem = resolveLabelValueRaw(item, "select");
if (displayItem !== item) {
return String(displayItem);
......@@ -282,7 +303,7 @@ export function buildSubformTable(field = {}) {
const template = getSubformTemplate(field);
const rowFieldsList = Array.isArray(field.value) ? field.value : [];
const columns = template.map((col) => ({
const columns = template.map(col => ({
prop: col.key,
label: col.label || col.key,
minWidth: "120px",
......
function evalPart(part = "", ctx = {}) {
const trimmed = part.trim();
const eqMatch = trimmed.match(/^val(\d+)\s*==\s*(?:'([^']*)'|"([^"]*)")$/);
if (eqMatch) {
const actual = ctx[`val${eqMatch[1]}`];
const expected = eqMatch[2] != null ? eqMatch[2] : eqMatch[3];
return actual == expected;
function tokenize(expr = "") {
const tokens = [];
let index = 0;
while (index < expr.length) {
const char = expr[index];
if (/\s/.test(char)) {
index += 1;
continue;
}
const pair = expr.slice(index, index + 2);
if (["&&", "||", "==", "!="].includes(pair)) {
tokens.push({ type: "operator", value: pair });
index += 2;
continue;
}
if (["!", "(", ")"].includes(char)) {
tokens.push({ type: "operator", value: char });
index += 1;
continue;
}
if (char === "'" || char === "\"") {
const quote = char;
let value = "";
let closed = false;
index += 1;
while (index < expr.length) {
const current = expr[index];
if (current === quote) {
closed = true;
index += 1;
break;
}
if (current === "\\" && index + 1 < expr.length) {
const escaped = expr[index + 1];
const escapeMap = { n: "\n", r: "\r", t: "\t" };
value += escapeMap[escaped] ?? escaped;
index += 2;
continue;
}
value += current;
index += 1;
}
if (!closed) {
throw new Error("unterminated string");
}
tokens.push({ type: "string", value });
continue;
}
const identifier = expr.slice(index).match(/^[A-Z_$][\w$]*(?:\.[A-Z_$][\w$]*)*/i);
if (identifier) {
tokens.push({ type: "identifier", value: identifier[0] });
index += identifier[0].length;
continue;
}
throw new Error(`unsupported token at ${index}`);
}
const neNullMatch = trimmed.match(/^val(\d+)\s*!=\s*null$/);
if (neNullMatch) {
const actual = ctx[`val${neNullMatch[1]}`];
return actual != null && actual !== "";
return tokens;
}
function parseExpression(tokens = [], ctx = {}) {
let index = 0;
const peek = () => tokens[index];
const take = () => tokens[index++];
const match = (value) => {
if (peek()?.value !== value) {
return false;
}
index += 1;
return true;
};
const expect = (value) => {
if (!match(value)) {
throw new Error(`expected ${value}`);
}
};
const expectType = (type) => {
const token = take();
if (!token || token.type !== type) {
throw new Error(`expected ${type}`);
}
return token.value;
};
const resolveVal = (name) => {
if (!/^val\d+$/.test(name)) {
throw new Error(`unsupported variable ${name}`);
}
return ctx[name];
};
let parseOr;
const parsePrimary = () => {
if (match("(")) {
const value = parseOr();
expect(")");
return value;
}
const identifier = expectType("identifier");
if (identifier === "Array.isArray") {
expect("(");
const variable = expectType("identifier");
expect(")");
return Array.isArray(resolveVal(variable));
}
if (/^val\d+\.includes$/.test(identifier)) {
const variable = identifier.slice(0, identifier.indexOf("."));
expect("(");
const expected = expectType("string");
expect(")");
const actual = resolveVal(variable);
return Array.isArray(actual) && actual.includes(expected);
}
if (/^val\d+$/.test(identifier)) {
if (!["==", "!="].includes(peek()?.value)) {
return Boolean(resolveVal(identifier));
}
const operator = take()?.value;
const expectedToken = take();
if (!expectedToken) {
throw new Error("missing comparison value");
}
const actual = resolveVal(identifier);
if (expectedToken.type === "identifier" && expectedToken.value === "null") {
const isEmpty = actual == null || actual === "";
return operator === "!=" ? !isEmpty : isEmpty;
}
if (expectedToken.type !== "string") {
throw new Error("unsupported comparison value");
}
const equals = String(actual) === expectedToken.value;
return operator === "==" ? equals : !equals;
}
throw new Error(`unsupported expression ${identifier}`);
};
const parseUnary = () => (match("!") ? !parseUnary() : parsePrimary());
const parseAnd = () => {
let value = parseUnary();
while (match("&&")) {
const right = parseUnary();
value = value && right;
}
return value;
};
parseOr = () => {
let value = parseAnd();
while (match("||")) {
const right = parseAnd();
value = value || right;
}
return value;
};
const result = parseOr();
if (index !== tokens.length) {
throw new Error("unexpected trailing expression");
}
return false;
return result;
}
function fallbackEvaluate(expr = "", ctx = {}) {
export function fallbackEvaluate(expr = "", ctx = {}) {
if (!expr) {
return true;
}
return expr.split("&&").every((part) => evalPart(part, ctx));
try {
return parseExpression(tokenize(expr), ctx);
} catch (error) {
return false;
}
}
export function evaluateShowRule(keys = [], resultExpr = "", rowFields = [], getRowFieldValue) {
......@@ -27,8 +176,8 @@ export function evaluateShowRule(keys = [], resultExpr = "", rowFields = [], get
}
try {
const ctx = {};
keys.forEach((key, index) => {
ctx[`val${index + 1}`] = getRowFieldValue(rowFields, key);
keys.forEach((key, keyIndex) => {
ctx[`val${keyIndex + 1}`] = getRowFieldValue(rowFields, key);
});
return fallbackEvaluate(resultExpr, ctx);
} catch (error) {
......
import { evaluateShowRule } from "./groupShowRuleEval";
import { getEffectiveSceneCodes } from "./visibilityHelpers";
function getRowFieldValue(rowFields = [], key = "", rowMap = null) {
const field = (rowFields || []).find((item) => item.key === key);
function findOptionByAlias(options = [], raw, optionKeys = []) {
if (raw == null || raw === "" || typeof raw === "object") {
return null;
}
const alias = String(raw);
for (const key of optionKeys) {
const option = options.find((item) => {
const value = item?.[key];
return value != null && value !== "" && String(value) === alias;
});
if (option) {
return option;
}
}
return null;
}
function resolveStaticOptionValue(field = {}, raw) {
const options = field.options || [];
let option = null;
if (raw && typeof raw === "object") {
option = findOptionByAlias(options, raw.value, ["value", "id", "label"])
|| findOptionByAlias(options, raw.id, ["id", "value", "label"]);
for (const key of ["name", "label", "text"]) {
option = option || findOptionByAlias(options, raw[key], ["label", "value", "id"]);
}
} else {
option = findOptionByAlias(options, raw, ["value", "id", "label"]);
}
return option?.value ?? option?.label ?? null;
}
function normalizeRuleScalar(raw, field = {}) {
if (raw == null || raw === "") {
return null;
}
const staticValue = resolveStaticOptionValue(field, raw);
if (staticValue != null && staticValue !== "") {
return staticValue;
}
if (typeof raw !== "object") {
return raw;
}
if (raw.value != null && raw.value !== "" && typeof raw.value !== "object") {
return normalizeRuleScalar(raw.value, field);
}
return raw.name ?? raw.label ?? raw.text ?? raw.id ?? null;
}
function normalizeRuleValue(raw, field = {}) {
if (Array.isArray(raw)) {
return raw
.map(item => normalizeRuleScalar(item, field))
.filter(value => value != null);
}
if (raw && typeof raw === "object" && Array.isArray(raw.value)) {
return normalizeRuleValue(raw.value, field);
}
return normalizeRuleScalar(raw, field);
}
function findGroupChild(group = {}, key = "") {
const children = Array.isArray(group.children) ? group.children : [];
const fields = Array.isArray(children[0]) ? children.flat() : children;
return fields.find(item => item?.key === key);
}
function getRowFieldValue(
rowFields = [],
key = "",
rowMap = null,
pageContext = {},
group = {},
) {
if (key === "$sceneCodes") {
return getEffectiveSceneCodes(pageContext).map(String);
}
if (key === "$brandIds") {
return (pageContext.brandIds || []).map(String);
}
const field = (rowFields || []).find(item => item.key === key);
const fieldMeta = findGroupChild(group, key);
if (field) {
if (field.value != null && field.value !== "") {
return field.value;
return normalizeRuleValue(field.value, { ...fieldMeta, ...field });
}
const metaKey = field.key;
if (metaKey != null && field[metaKey] != null && field[metaKey] !== "") {
const meta = field[metaKey];
if (typeof meta === "object" && !Array.isArray(meta)) {
return meta.name ?? meta.label ?? meta.id ?? meta;
}
return meta;
return normalizeRuleValue(meta, { ...fieldMeta, ...field });
}
}
if (rowMap && rowMap[key] != null && rowMap[key] !== "") {
return rowMap[key];
return normalizeRuleValue(rowMap[key]);
}
return null;
}
function isGroupChildVisibleInRow(group = {}, child = {}, rowFields = [], rowMap = null) {
function isGroupChildVisibleInRow(
group = {},
child = {},
rowFields = [],
rowMap = null,
pageContext = {},
) {
const rules = group.childrenShowRules;
if (!rules || !child?.key) {
return true;
}
const rule = rules[child.key];
if (!rule) {
if (!Object.prototype.hasOwnProperty.call(rules, child.key)) {
return true;
}
const keys = rule.keys || [];
const resultExpr = rule.result;
const rule = rules[child.key];
if (!rule || typeof rule !== "object") {
return false;
}
const keys = Array.isArray(rule.keys)
? rule.keys.filter(key => key != null && String(key).trim())
: [];
const resultExpr = typeof rule.result === "string" ? rule.result.trim() : "";
if (!keys.length || !resultExpr) {
return true;
return false;
}
return evaluateShowRule(keys, resultExpr, rowFields, (rf, k) =>
getRowFieldValue(rf, k, rowMap));
getRowFieldValue(rf, k, rowMap, pageContext, group));
}
export function filterVisibleRowFields(group = {}, rowFields = [], rowMap = null) {
return (rowFields || []).filter((field) =>
isGroupChildVisibleInRow(group, field, rowFields, rowMap));
export function filterVisibleRowFields(
group = {},
rowFields = [],
rowMap = null,
pageContext = {},
) {
return (rowFields || []).filter(field =>
isGroupChildVisibleInRow(group, field, rowFields, rowMap, pageContext));
}
......@@ -17,15 +17,15 @@ import {
import { isFieldVisibleBySpecs } from "./visibilitySpecs";
function sortBySortNum(list = []) {
return [ ...list ].sort((a, b) =>
return [...list].sort((a, b) =>
String(a.sortNum || "").localeCompare(String(b.sortNum || ""), undefined, { numeric: true }));
}
function getEchoKeysFromFormList(formList = []) {
const echoSubformKeys = formList
.filter((item) => item?.key && (item.type === "subform" || item.type === "group"))
.map((item) => item.key);
const echoTopLevelKeys = formList.filter((item) => item?.key).map((item) => item.key);
.filter(item => item?.key && (item.type === "subform" || item.type === "group"))
.map(item => item.key);
const echoTopLevelKeys = formList.filter(item => item?.key).map(item => item.key);
return { echoSubformKeys, echoTopLevelKeys };
}
......@@ -98,8 +98,8 @@ function getVisibleSubformChildren(group, ctx, values, schemaList = [], formList
echoParentKey: group?.key,
};
return getSubformRowTemplate(group)
.map((child) => mergeFieldMeta(child, schemaList, formList))
.filter((child) => isFieldVisibleBySpecs(child, ctx, values, visibilityOptions))
.map(child => mergeFieldMeta(child, schemaList, formList))
.filter(child => isFieldVisibleBySpecs(child, ctx, values, visibilityOptions))
.sort((a, b) => Number(a.sortNum) - Number(b.sortNum));
}
......@@ -112,8 +112,8 @@ function getVisibleGroupChildren(group, ctx, values, schemaList = [], formList =
echoParentKey: group?.key,
};
return getStaticGroupChildren(group)
.map((child) => mergeFieldMeta(child, schemaList, formList))
.filter((child) => isFieldVisibleBySpecs(child, ctx, values, visibilityOptions))
.map(child => mergeFieldMeta(child, schemaList, formList))
.filter(child => isFieldVisibleBySpecs(child, ctx, values, visibilityOptions))
.sort((a, b) => Number(a.sortNum) - Number(b.sortNum));
}
......@@ -135,11 +135,11 @@ function filterFieldNode(field, schemaList, formList, ctx, values, options) {
return null;
}
const childMap = new Map(
getStaticGroupChildren(merged).map((child) => [child.key, child]),
getStaticGroupChildren(merged).map(child => [child.key, child]),
);
return {
...merged,
children: visibleChildren.map((child) => ({
children: visibleChildren.map(child => ({
...child,
...(childMap.get(child.key) || {}),
value: childMap.get(child.key)?.value ?? child.value,
......@@ -153,15 +153,15 @@ function filterFieldNode(field, schemaList, formList, ctx, values, options) {
return null;
}
const templateMap = new Map(
getSubformRowTemplate(merged).map((col) => [col.key, col]),
getSubformRowTemplate(merged).map(col => [col.key, col]),
);
const mergedTemplate = visibleTemplate.map((col) => ({
const mergedTemplate = visibleTemplate.map(col => ({
...col,
...(templateMap.get(col.key) || {}),
}));
const rowFieldsList = Array.isArray(merged.value) ? merged.value : [];
const groupDef = mergeFieldMeta(merged, schemaList, formList);
const allowedKeys = new Set(mergedTemplate.map((col) => col.key));
const allowedKeys = new Set(mergedTemplate.map(col => col.key));
const filteredRows = rowFieldsList
.map((rowCells) => {
const cells = Array.isArray(rowCells) ? rowCells : [];
......@@ -171,14 +171,20 @@ function filterFieldNode(field, schemaList, formList, ctx, values, options) {
rowMap[cell.key] = cell.value;
}
});
const visibleInRow = filterVisibleRowFields(groupDef, cells, rowMap);
return visibleInRow.filter((cell) => allowedKeys.has(cell.key));
const visibleInRow = filterVisibleRowFields(groupDef, cells, rowMap, ctx);
return visibleInRow.filter(cell => allowedKeys.has(cell.key));
})
.filter((row) => row.length);
.filter(row => row.length);
const visibleColumnKeys = new Set(
filteredRows.flatMap(row => row.map(cell => cell.key)),
);
const filteredTemplate = filteredRows.length
? mergedTemplate.filter(col => visibleColumnKeys.has(col.key))
: mergedTemplate;
return {
...merged,
children: [mergedTemplate],
children: [filteredTemplate],
value: filteredRows,
};
}
......@@ -197,7 +203,7 @@ export function filterFormListForDisplay(formList = [], detail = {}) {
return sortBySortNum(
formList
.map((field) => filterFieldNode(field, schemaList, formList, ctx, values, options))
.map(field => filterFieldNode(field, schemaList, formList, ctx, values, options))
.filter(Boolean),
);
}
......
......@@ -13,15 +13,35 @@ const SCENE_TYPE_RIGHTS_CODES = [110101, 110102, 110201, 110202];
export const ATTENDANCE_KEY = "F1-1";
export function hasIntersection(a = [], b = []) {
return a.some((id) => b.includes(id));
return a.some(id => b.includes(id));
}
export function normalizeSceneCodeList(codes) {
if (codes == null || codes === "") {
return [];
}
const list = Array.isArray(codes) ? codes : [codes];
return list.map((code) => Number(code)).filter((code) => !Number.isNaN(code));
const normalized = [];
const append = (value) => {
if (Array.isArray(value)) {
value.forEach(append);
return;
}
if (value && typeof value === "object") {
append(value.baseSceneCode);
return;
}
const scalar = typeof value === "string" ? value.trim() : value;
if (scalar == null || scalar === "") {
return;
}
if (typeof scalar === "string" && scalar.includes(",")) {
scalar.split(",").forEach(append);
return;
}
const sceneCode = Number(scalar);
if (Number.isFinite(sceneCode)) {
normalized.push(sceneCode);
}
};
append(codes);
return normalized;
}
export function flattenFields(list = []) {
......@@ -39,7 +59,7 @@ export function flattenFields(list = []) {
}
export function schemaHasAttendanceField(list = []) {
return flattenFields(list).some((field) => field.key === ATTENDANCE_KEY);
return flattenFields(list).some(field => field.key === ATTENDANCE_KEY);
}
/** 字段是否受 F1-1 出勤 rules.result 联动 */
......@@ -52,7 +72,7 @@ export function isAttendanceGatedField(field = {}) {
/** 优先取带 keys/result 的出勤联动 rules,避免被 min/integer 等校验 rules 覆盖 */
export function resolveFieldShowRules(field = {}, schemaField = {}) {
const candidates = [field?.rules, schemaField?.rules];
const withGate = candidates.find((rules) => rules?.keys?.length && rules?.result);
const withGate = candidates.find(rules => rules?.keys?.length && rules?.result);
if (withGate) {
return withGate;
}
......@@ -60,8 +80,8 @@ export function resolveFieldShowRules(field = {}, schemaField = {}) {
}
export function findSchemaFieldInContext(schemaList = [], formList = [], key = "") {
return flattenFields(schemaList).find((field) => field.key === key)
|| flattenFields(formList).find((field) => field.key === key);
return flattenFields(schemaList).find(field => field.key === key)
|| flattenFields(formList).find(field => field.key === key);
}
/** 驻店日报调休时隐藏 brand group(对 merge 后的字段判断) */
......@@ -91,7 +111,7 @@ export function resolveSchemaList(detail = {}, formList = []) {
}
export function getMerchantSceneCodes(sceneList = []) {
return normalizeSceneCodeList((sceneList || []).map((item) => item?.baseSceneCode));
return normalizeSceneCodeList(sceneList);
}
export function getEffectiveSceneCodes(ctx = {}) {
......@@ -108,7 +128,7 @@ export function matchesBaseSceneCode(field, ctx = {}) {
return true;
}
const effective = getEffectiveSceneCodes(ctx);
return fieldCodes.some((code) => effective.includes(code));
return fieldCodes.some(code => effective.includes(code));
}
export function isDividerVisible(field, ctx = {}) {
......@@ -138,7 +158,7 @@ export function shouldHideByFilterBrandId(field = {}, brandIds = []) {
if (!field.filterBrandId?.length || !brandIds.length) {
return false;
}
const hasOtherBrand = brandIds.some((id) => !field.filterBrandId.includes(id));
const hasOtherBrand = brandIds.some(id => !field.filterBrandId.includes(id));
return !hasOtherBrand;
}
......@@ -152,7 +172,7 @@ export function inferSceneListFromSceneType(sceneType) {
: String(sceneType) === "0"
? SCENE_TYPE_RIGHTS_CODES
: [];
return codes.map((baseSceneCode) => ({ baseSceneCode }));
return codes.map(baseSceneCode => ({ baseSceneCode }));
}
/** 详情 sceneList 解析:接口 sceneList → baseSceneCode → sceneType */
......
<!-- 补库存标签码日志弹窗 -->
<template>
<baseDialog :config="config"
:dialog-config="dialogConfig"
:is-show.sync="visible">
<div class="complement-log-content">
<!-- 产品基础信息 -->
<el-drawer direction="rtl"
size="820px"
title="日志"
append-to-body
:visible.sync="visible">
<div v-loading="loading" class="stock-log-drawer">
<div class="section-title">
产品基础信息
</div>
<div class="info-box">
<el-row>
<el-col class="info-item" :span="24">
<span class="label">产品名称:</span>
<span class="value">{{ row.upgradeGoodsName || '-' }}</span>
</el-col>
<el-col class="info-item" :span="24">
<span class="label">产品编码:</span>
<span class="value">{{ row.productCode || '-' }}</span>
</el-col>
<el-col class="info-item" :span="24">
<span class="label">产品ID:</span>
<span class="value">{{ row.upgradeCommodityCode || '-' }}</span>
</el-col>
</el-row>
<div class="info-item">
<span class="label">产品名称:</span>
<span>{{ row.upgradeGoodsName || "-" }}</span>
</div>
<div class="info-item">
<span class="label">产品编码:</span>
<span>{{ row.productCode || "-" }}</span>
</div>
<div class="info-item">
<span class="label">产品UID:</span>
<span>{{ row.upgradeCommodityCode || "-" }}</span>
</div>
</div>
<!-- 操作日志 -->
<template v-if="tableData.length">
<div class="section-title" style="margin-top: 20px;">
操作日志
<template v-if="row.canScanEnable">
<div class="section-title section-gap">
补码日志
</div>
<el-table v-loading="loading"
style="width: 100%"
border
:data="tableData">
<el-table border :data="complementLogList">
<el-table-column align="center"
label="序号"
type="index"
width="80">
</el-table-column>
width="70" />
<el-table-column v-if="row.isFilm"
align="center"
label="库存数量"
prop="stockNum">
</el-table-column>
prop="stockNum" />
<el-table-column align="center"
label="操作人"
prop="createdBy">
</el-table-column>
prop="createdBy" />
<el-table-column align="center"
label="操作时间">
label="操作时间"
min-width="160">
<template #default="scope">
{{ scope.row.createdDate | formatDate }}
</template>
......@@ -57,21 +49,52 @@
</el-table>
</template>
<div class="section-title section-gap">
迁移库存日志
</div>
<el-table border :data="stockMoveLogList">
<el-table-column align="center"
label="序号"
type="index"
width="70" />
<el-table-column align="center"
label="旧UID"
min-width="130"
prop="oldCommodityCode" />
<el-table-column align="center"
label="新UID"
min-width="130"
prop="newCommodityCode" />
<el-table-column align="center"
label="库存数量"
prop="moveStockNum"
width="100" />
<el-table-column align="center"
label="操作人"
min-width="100"
prop="createdBy" />
<el-table-column align="center"
label="操作时间"
min-width="160">
<template #default="scope">
{{ scope.row.createdDate | formatDate }}
</template>
</el-table-column>
</el-table>
</div>
</baseDialog>
</el-drawer>
</template>
<script>
import dayjs from "dayjs";
import { getReplenishLogListApi } from "@/api/stockManage";
import { getReplenishLogListApi, getStockMoveLogPage } from "@/api/stockManage";
import { sortStockMoveLogs } from "./stockMove";
export default {
name: "ComplementLogDialog",
filters: {
formatDate(val) {
if (!val)
return "-";
return dayjs(val).format("YYYY-MM-DD HH:mm:ss");
formatDate(value) {
return value ? dayjs(value).format("YYYY-MM-DD HH:mm:ss") : "-";
},
},
props: {
......@@ -86,16 +109,8 @@ export default {
},
data() {
return {
config: {
showClose: true,
appendToBody: false,
isShowFooter: false, // 日志弹窗只需要展示,不需要底部确认/取消按钮
},
dialogConfig: {
title: "补库存标签码日志",
width: "700px",
},
tableData: [],
complementLogList: [],
stockMoveLogList: [],
loading: false,
};
},
......@@ -104,8 +119,8 @@ export default {
get() {
return this.visibleSync;
},
set(newVal) {
this.$emit("update:visibleSync", newVal);
set(value) {
this.$emit("update:visibleSync", value);
},
},
},
......@@ -113,60 +128,72 @@ export default {
this.fetchLogData();
},
methods: {
fetchLogData() {
async fetchLogData() {
this.loading = true;
const params = {
pageSize: 1000,
currentPage: 1,
upgradeGoodsId: this.row.upgradeGoodsId,
merchantId: this.row.yqMerchantId,
};
getReplenishLogListApi(params).then((res) => {
const complementRequest = this.row.canScanEnable
? getReplenishLogListApi({
currentPage: 1,
pageSize: 1000,
upgradeGoodsId: this.row.upgradeGoodsId,
merchantId: this.row.yqMerchantId,
})
: Promise.resolve({ list: [] });
try {
const [complementResponse, stockMoveResponse] = await Promise.all([
complementRequest,
getStockMoveLogPage({
upgradeGoodsId: this.row.upgradeGoodsId,
yqMerchantId: this.row.yqMerchantId,
}),
]);
this.complementLogList = complementResponse?.list || [];
this.stockMoveLogList = sortStockMoveLogs(stockMoveResponse?.list || []);
} catch (error) {
void error;
this.complementLogList = [];
this.stockMoveLogList = [];
} finally {
this.loading = false;
if (res && res.list) {
this.tableData = res.list;
} else {
this.tableData = [];
}
}).catch(() => {
this.loading = false;
this.tableData = [];
});
}
},
},
};
</script>
<style scoped lang="scss">
.complement-log-content {
padding: 0 10px 20px 10px;
.stock-log-drawer {
box-sizing: border-box;
height: calc(100vh - 80px);
overflow-y: auto;
padding: 0 24px 30px;
}
.section-title {
font-size: 16px;
font-weight: bold;
color: #333;
margin-bottom: 15px;
}
.section-title {
font-size: 16px;
font-weight: bold;
color: #333;
margin-bottom: 16px;
}
.info-box {
padding: 0 20px;
.section-gap {
margin-top: 28px;
}
.info-item {
margin-bottom: 12px;
font-size: 14px;
.info-box {
display: flex;
flex-wrap: wrap;
padding: 4px 12px;
background: #f7f8fa;
}
.label {
color: #666;
display: inline-block;
width: 80px;
text-align: right;
}
.info-item {
box-sizing: border-box;
width: 50%;
padding: 10px 8px;
font-size: 14px;
}
.value {
color: #333;
}
}
}
.label {
color: #666;
}
</style>
......@@ -4,8 +4,7 @@
<d2-container>
<template #header>
<div class="header" style="padding: 10px 20px;">
<d2-search ref="showSearch"
class="show-search"
<d2-search class="show-search"
:form-data="showFormData"
:search-form="searchForm" />
<div class="up-btns">
......@@ -37,14 +36,18 @@
:search-form="searchFormSearch"
:table-params="tableParams">
<template #stockHtml="scope">
<span class="count-txt" @click="gotoInventoryTransaction">{{ (scope.scope.stock || scope.scope.stock == 0) ? Number.parseFloat(scope.scope.stock).toFixed(2) + (membraneTypeList.includes(scope.scope.goodsType) == 1 ? "米" : "件") : "-" }}</span>
<span class="count-txt" @click="gotoInventoryTransaction">{{ (scope.scope.stock || scope.scope.stock === 0) ? Number.parseFloat(scope.scope.stock).toFixed(2) + (membraneTypeList.includes(scope.scope.goodsType) ? "米" : "件") : "-" }}</span>
</template>
<template #auth-button="scope">
<auth-button :data="scope.scope" :show-btn-ids="['9080202', '9080203']" />
<!-- 补码 日志 -->
<auth-button :data="scope.scope" :show-btn-ids="['9080207', '9080202', '9080203']" />
<!-- 补码维持原有展示条件 -->
<span v-if="scope.scope.canScanEnable" style="margin-left:10px">
<auth-button :data="scope.scope" :show-btn-ids="['9080205', '9080206']" />
<auth-button :data="scope.scope" :show-btn-ids="['9080205']" />
</span>
<!-- 日志常驻展示 -->
<span style="margin-left:10px">
<auth-button :data="scope.scope" :show-btn-ids="['9080206']" />
</span>
</template>
</d2-table>
......@@ -66,18 +69,33 @@
</StatementOfAccountDialog>
<ComplementCodeDialog v-if="complementDialogVisible"
:row="recordInfo"
:visibleSync.sync="complementDialogVisible">
:visible-sync.sync="complementDialogVisible">
</ComplementCodeDialog>
<ComplementLogDialog v-if="complementLogDialogVisible"
:row="recordInfo"
:visibleSync.sync="complementLogDialogVisible">
:visible-sync.sync="complementLogDialogVisible">
</ComplementLogDialog>
<StockMoveDialog v-if="stockMoveDialogVisible"
:row="recordInfo"
:visible-sync.sync="stockMoveDialogVisible"
@success="handleStockMoveSuccess">
</StockMoveDialog>
<d2-file-import-dialog title="批量迁移库存"
:is-visible="stockMoveImportVisible"
@closeDialog="handleStockMoveImportClose"
@confirmDialog="handleConfirmStockMoveImport"
@downloadTemplate="downloadStockMoveTemplate" />
</div>
</template>
<script>
import { getProductTypeBySceneId } from "@api/product";
import { getMerchantGoodsStockMonthReport, getyqMerchantList, stockMonthReportCount } from "@api/stockManage";
import {
getMerchantGoodsStockMonthReport,
getyqMerchantList,
importStockMove,
stockMonthReportCount,
} from "@api/stockManage";
import { mapActions, mapState } from "vuex";
import { deepClone, Util } from "@/common/util";
import { baseConfig } from "@/main";
......@@ -86,6 +104,8 @@ import complementLogDialog from "./complementLogDialog";
import statementOfAccountDialog from "./statementOfAccountDialog";
import stockDetailDialog from "./stockDetailDialog";
import stockMonthDialog from "./stockMonthDialog";
import { hasStockToMove, STOCK_MOVE_ZERO_MESSAGE } from "./stockMove";
import stockMoveDialog from "./stockMoveDialog";
export default {
name: "StockList",
......@@ -95,6 +115,7 @@ export default {
StatementOfAccountDialog: statementOfAccountDialog,
ComplementCodeDialog: complementCodeDialog,
ComplementLogDialog: complementLogDialog,
StockMoveDialog: stockMoveDialog,
},
data() {
return {
......@@ -207,13 +228,13 @@ export default {
label: "上月结存库存",
prop: "lastMonthRemainStock",
formatter: (cellValue) => {
return (cellValue.lastMonthRemainStock || cellValue.lastMonthRemainStock == 0) ? Number.parseFloat(cellValue.lastMonthRemainStock).toFixed(2) + (this.membraneTypeList.includes(cellValue.goodsType) ? "米" : "件") : "-";
return (cellValue.lastMonthRemainStock || cellValue.lastMonthRemainStock === 0) ? Number.parseFloat(cellValue.lastMonthRemainStock).toFixed(2) + (this.membraneTypeList.includes(cellValue.goodsType) ? "米" : "件") : "-";
},
}, {
label: "上月结存金额",
prop: "lastMonthRemainMoney",
formatter: (cellValue) => {
return (cellValue.lastMonthRemainMoney || cellValue.lastMonthRemainMoney == 0) ? "¥" + cellValue.lastMonthRemainMoney.toFixed(2) : "-";
return (cellValue.lastMonthRemainMoney || cellValue.lastMonthRemainMoney === 0) ? "¥" + cellValue.lastMonthRemainMoney.toFixed(2) : "-";
},
}, {
label: "当前库存",
......@@ -240,6 +261,8 @@ export default {
stockMonthVisible: false,
complementDialogVisible: false,
complementLogDialogVisible: false,
stockMoveDialogVisible: false,
stockMoveImportVisible: false,
recordInfo: null,
statisticsData: {},
statementOfAccountDialogVisible: false,
......@@ -248,6 +271,7 @@ export default {
computed: {
...mapState({
dowloadList: state => state.d2admin.user.dowloadList,
updateList: state => state.d2admin.user.updateList,
}),
},
mounted() {
......@@ -278,7 +302,7 @@ export default {
// this.getOptionsList()
// },
gotoInventoryTransaction() {
let query = {};
const query = {};
if (this.searchForm.selectData && this.searchForm.selectData.length === 2) {
query.startDate = Util.dateFormate(this.searchForm.selectData[0], "YYYY-MM-DD");
query.endDate = Util.dateFormate(this.searchForm.selectData[1], "YYYY-MM-DD");
......@@ -298,6 +322,60 @@ export default {
this.recordInfo = row;
this.complementLogDialogVisible = true;
},
// 单产品迁移库存
handleStockMove(row) {
if (!hasStockToMove(row)) {
this.$message.warning(STOCK_MOVE_ZERO_MESSAGE);
return;
}
this.recordInfo = row;
this.stockMoveDialogVisible = true;
},
handleStockMoveSuccess() {
this.$refs.recordTable.refreshTable();
this.stockMonthReportCount();
},
// 批量迁移库存
handleBatchStockMove() {
this.stockMoveImportVisible = true;
},
handleStockMoveImportClose() {
this.stockMoveImportVisible = false;
},
handleConfirmStockMoveImport({ fileName, fileData }) {
importStockMove({ file: fileData }).then((response) => {
if (!response) {
return;
}
const list = [
...this.updateList,
{
name: fileName,
ifSuccess: false,
uuid: response,
type: "upload",
},
];
this.actionSetDownloadList({ list, type: "updateList" });
this.notice.okTips("上传成功");
this.handleStockMoveImportClose();
});
},
downloadStockMoveTemplate() {
const params = {
method: "dj.api.smartcarlife.MerchantGoodsStockMonthReport.stockMove.template.export",
};
const list = [
...this.dowloadList,
{
name: "批量迁移库存导入模板",
exportParam: JSON.stringify(params),
status: "waiting",
timeid: new Date().getTime(),
},
];
this.actionSetDownloadList({ list, type: "dowloadList" });
},
// 库存记录统计
stockMonthReportCount() {
this.beforeSearchFn();
......@@ -358,7 +436,7 @@ export default {
// 库存对账单导出
handleRelateProConfirm(data) {
let params = data;
const params = data;
params.method = "dj.api.smartcarlife.merchantShopGoodsStock.statement.exportAsync";
// return
......@@ -376,7 +454,7 @@ export default {
},
handleExport() {
let params = this.searchFormSearch;
const params = this.searchFormSearch;
params.method = "dj.api.smartcarlife.MerchantGoodsStockMonthReport.export.async";
const list = [
...this.dowloadList,
......
export const STOCK_MOVE_ZERO_MESSAGE = "产品UID当前库存为0,无需迁移库存";
export function hasStockToMove(row = {}) {
return Number(row.stock) > 0;
}
export function filterStockMoveTargets(list = [], row = {}) {
return list.filter((item) => {
const isSameId = String(item.id) === String(row.upgradeGoodsId);
const isSameCommodityCode
= item.commodityCode && row.upgradeCommodityCode
&& String(item.commodityCode) === String(row.upgradeCommodityCode);
return !isSameId && !isSameCommodityCode;
});
}
export function sortStockMoveLogs(list = []) {
return [...list].sort((left, right) => {
return new Date(right.createdDate || 0).getTime() - new Date(left.createdDate || 0).getTime();
});
}
import {
filterStockMoveTargets,
hasStockToMove,
sortStockMoveLogs,
STOCK_MOVE_ZERO_MESSAGE,
} from "./stockMove";
describe("stock move helpers", () => {
it("uses the confirmed zero-stock warning copy", () => {
expect(STOCK_MOVE_ZERO_MESSAGE).toBe("产品UID当前库存为0,无需迁移库存");
});
it("only allows rows with stock greater than zero", () => {
expect(hasStockToMove({ stock: "0.01" })).toBe(true);
expect(hasStockToMove({ stock: 0 })).toBe(false);
expect(hasStockToMove({ stock: undefined })).toBe(false);
});
it("removes the current product from target options", () => {
expect(filterStockMoveTargets([
{ id: 1, commodityCode: "UID-1" },
{ id: 2, commodityCode: "UID-2" },
], {
upgradeGoodsId: 1,
upgradeCommodityCode: "UID-1",
})).toEqual([{ id: 2, commodityCode: "UID-2" }]);
});
it("sorts migration logs by operation time descending", () => {
const logs = [
{ id: 1, createdDate: "2026-08-01 10:00:00" },
{ id: 2, createdDate: "2026-08-02 10:00:00" },
];
expect(sortStockMoveLogs(logs).map(item => item.id)).toEqual([2, 1]);
});
});
import { listUpgradeGoodsSimple, moveMerchantGoodsStock } from "@api/stockManage";
import { STOCK_MOVE_ZERO_MESSAGE } from "./stockMove";
import StockMoveDialog from "./stockMoveDialog.vue";
jest.mock("@api/stockManage", () => ({
listUpgradeGoodsSimple: jest.fn(),
moveMerchantGoodsStock: jest.fn(),
}));
describe("stock move dialog", () => {
beforeEach(() => {
jest.clearAllMocks();
});
it("queries light-modification products and excludes the current UID", async () => {
listUpgradeGoodsSimple.mockResolvedValue({
list: [
{ id: 1, commodityCode: "OLD" },
{ id: 2, commodityCode: "NEW" },
],
});
const context = {
requestSequence: 0,
loading: false,
targetOptions: [],
row: { upgradeGoodsId: 1, upgradeCommodityCode: "OLD" },
};
await StockMoveDialog.methods.fetchTargetOptions.call(context, "UID");
expect(listUpgradeGoodsSimple).toHaveBeenCalledWith({
currentPage: 1,
pageSize: 20,
commodityCode: "UID",
productType: 1,
});
expect(context.targetOptions).toEqual([{ id: 2, commodityCode: "NEW" }]);
});
it("blocks zero-stock rows before validating or submitting", () => {
const warning = jest.fn();
const validate = jest.fn();
StockMoveDialog.methods.handleConfirm.call({
submitting: false,
row: { stock: 0 },
$message: { warning },
$refs: { stockMoveForm: { validate } },
});
expect(warning).toHaveBeenCalledWith(STOCK_MOVE_ZERO_MESSAGE);
expect(validate).not.toHaveBeenCalled();
expect(moveMerchantGoodsStock).not.toHaveBeenCalled();
});
});
<template>
<d2-dialog title="迁移库存"
width="600px"
:is-visible="visible"
@closeDialog="handleClose"
@confirmDialog="handleConfirm">
<el-form ref="stockMoveForm"
label-width="130px"
:model="form"
:rules="rules">
<el-form-item label="产品名称:">
<span>{{ row.upgradeGoodsName || "-" }}</span>
</el-form-item>
<el-form-item label="产品编码:">
<span>{{ row.productCode || "-" }}</span>
</el-form-item>
<el-form-item label="产品UID:">
<span>{{ row.upgradeCommodityCode || "-" }}</span>
</el-form-item>
<el-form-item label="库存数量:">
<span>{{ row.stock == null ? "-" : row.stock }}</span>
</el-form-item>
<el-form-item label="迁移到新UID:" prop="targetUpgradeGoodsId">
<el-select v-model="form.targetUpgradeGoodsId"
placeholder="请输入UID模糊搜索"
style="width: 380px;"
clearable
filterable
remote
reserve-keyword
:loading="loading"
:remote-method="remoteSearch"
@visible-change="handleVisibleChange">
<el-option v-for="item in targetOptions"
:key="item.id"
:label="getOptionLabel(item)"
:value="item.id" />
</el-select>
</el-form-item>
</el-form>
</d2-dialog>
</template>
<script>
import { listUpgradeGoodsSimple, moveMerchantGoodsStock } from "@api/stockManage";
import { filterStockMoveTargets, hasStockToMove, STOCK_MOVE_ZERO_MESSAGE } from "./stockMove";
export default {
name: "StockMoveDialog",
props: {
visibleSync: {
type: Boolean,
default: false,
},
row: {
type: Object,
default: () => ({}),
},
},
data() {
return {
form: {
targetUpgradeGoodsId: "",
},
rules: {
targetUpgradeGoodsId: [{ required: true, message: "请选择迁移到的新UID", trigger: "change" }],
},
targetOptions: [],
loading: false,
submitting: false,
requestSequence: 0,
};
},
computed: {
visible: {
get() {
return this.visibleSync;
},
set(value) {
this.$emit("update:visibleSync", value);
},
},
},
mounted() {
this.fetchTargetOptions();
},
methods: {
async fetchTargetOptions(commodityCode = "") {
const currentSequence = ++this.requestSequence;
this.loading = true;
try {
const response = await listUpgradeGoodsSimple({
currentPage: 1,
pageSize: 20,
commodityCode,
productType: 1,
});
if (currentSequence === this.requestSequence) {
this.targetOptions = filterStockMoveTargets(response?.list || [], this.row);
}
} catch (error) {
void error;
if (currentSequence === this.requestSequence) {
this.targetOptions = [];
}
} finally {
if (currentSequence === this.requestSequence) {
this.loading = false;
}
}
},
remoteSearch(query) {
this.fetchTargetOptions(query.trim());
},
handleVisibleChange(visible) {
if (visible && !this.targetOptions.length) {
this.fetchTargetOptions();
}
},
getOptionLabel(item) {
return item.upgradeGoodsName
? `${item.commodityCode || "-"} / ${item.upgradeGoodsName}`
: item.commodityCode || "-";
},
handleClose() {
this.visible = false;
},
handleConfirm() {
if (this.submitting) {
return;
}
if (!hasStockToMove(this.row)) {
this.$message.warning(STOCK_MOVE_ZERO_MESSAGE);
return;
}
this.$refs.stockMoveForm.validate(async (valid) => {
if (!valid) {
return;
}
this.submitting = true;
try {
const result = await moveMerchantGoodsStock({
upgradeGoodsId: this.row.upgradeGoodsId,
yqMerchantId: this.row.yqMerchantId,
targetUpgradeGoodsId: this.form.targetUpgradeGoodsId,
});
if (result === false) {
this.$message.error("库存迁移失败");
return;
}
this.$message.success("操作成功");
this.$emit("success");
this.handleClose();
} catch (error) {
void error;
} finally {
this.submitting = false;
}
});
},
},
};
</script>
const { mapDetailResponse } = require("@/api/adapters/journalRecord/mapDetailResponse");
describe("mapDetailResponse", () => {
it("应保留接口返回的模板类型", () => {
expect(mapDetailResponse({ templateType: 2 }).templateType).toBe(2);
});
it("接口缺少模板类型时使用调用上下文", () => {
expect(mapDetailResponse({}, { templateType: 2 }).templateType).toBe(2);
});
it("路由中的单个品牌应归一化成品牌数组", () => {
expect(mapDetailResponse({}, { brandIds: "3454" }).brandIds).toEqual(["3454"]);
});
it("接口缺少场景码时应保留路由上下文", () => {
expect(mapDetailResponse({}, { baseSceneCode: "100101" }).baseSceneCode).toBe("100101");
});
it("详情应使用精确场景码识别延保", () => {
const detail = mapDetailResponse({
sceneType: 0,
baseSceneCode: 110201,
});
expect(detail.bizTypeName).toBe("延保");
});
it("列表业务兜底应优先于旧 sceneType 映射", () => {
const detail = mapDetailResponse(
{ sceneType: "0" },
{ bizType: 9, bizTypeName: "延保" },
);
expect(detail.bizType).toBe(9);
expect(detail.bizTypeName).toBe("延保");
});
it("精确场景码应优先于列表业务兜底", () => {
const detail = mapDetailResponse(
{ sceneType: "1" },
{ baseSceneCode: 110201, bizType: 9, bizTypeName: "列表兜底" },
);
expect(detail.bizType).toBe("延保");
expect(detail.bizTypeName).toBe("延保");
});
it("详情接口明确业务字段应优先于精确场景和列表兜底", () => {
const detail = mapDetailResponse(
{
sceneType: "0",
baseSceneCode: 110201,
bizType: 7,
bizTypeName: "接口业务",
},
{ bizType: 9, bizTypeName: "列表兜底" },
);
expect(detail.bizType).toBe(7);
expect(detail.bizTypeName).toBe("接口业务");
});
it("空字符串列表兜底应视为缺失并继续使用旧 sceneType", () => {
const detail = mapDetailResponse(
{ sceneType: "1" },
{ bizType: "", bizTypeName: "" },
);
expect(detail.bizType).toBe(1);
expect(detail.bizTypeName).toBe("轻改");
});
});
const {
mapMerchantBrandContext,
} = require("@/api/adapters/journalRecord/mapMerchantBrandContext");
describe("mapMerchantBrandContext", () => {
it("应从门店经营品牌列表提取子品牌 ID", () => {
expect(mapMerchantBrandContext({
list: [{
merchantId: 1001,
merchantBrandList: [
{ brandId: 1, childId: 3454 },
{ brandId: 2, childId: "3503" },
],
}],
}, 1001)).toEqual([3454, "3503"]);
});
it("没有匹配门店时返回空数组", () => {
expect(mapMerchantBrandContext({ list: [] }, 1001)).toEqual([]);
});
});
const { mapOverviewRow } = require("@/api/adapters/journalRecord/mapOverviewRow");
const { mapOverviewPageResponse, mapOverviewRow } = require("@/api/adapters/journalRecord/mapOverviewRow");
describe("mapOverviewRow", () => {
it("应将 Swagger 字段映射为表格字段", () => {
......@@ -21,4 +21,47 @@ describe("mapOverviewRow", () => {
expect(row.bizTypeName).toBe("权益");
expect(row.bizType).toBe(2);
});
it("应保留详情显隐需要的品牌和场景上下文", () => {
const row = mapOverviewRow({
brandIds: [3454, 3503],
baseSceneCode: 100101,
sceneList: [{ baseSceneCode: 100101 }],
});
expect(row.brandIds).toEqual([3454, 3503]);
expect(row.baseSceneCode).toBe(100101);
expect(row.sceneList).toEqual([{ baseSceneCode: 100101 }]);
});
it("仅有 sceneList 时应派生详情路由使用的精确场景码", () => {
const row = mapOverviewRow({
sceneType: "0",
sceneList: [{ baseSceneCode: 110202 }],
});
expect(row.bizTypeName).toBe("延保");
expect(row.baseSceneCode).toEqual([110202]);
});
it("应保留 sceneType 并优先使用后端业务名称", () => {
const row = mapOverviewRow({
sceneType: "0",
baseSceneCode: 110101,
bizType: 9,
bizTypeName: "延保",
});
expect(row.sceneType).toBe("0");
expect(row.bizType).toBe(9);
expect(row.bizTypeName).toBe("延保");
});
it("分页适配应保持后端 list 顺序", () => {
const response = mapOverviewPageResponse({
list: [
{ id: "third", sceneType: "1" },
{ id: "first", sceneType: "0" },
{ id: "second", sceneType: "1" },
],
});
expect(response.list.map(item => item.id)).toEqual(["third", "first", "second"]);
});
});
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!