Commit a87ffc0d by 张立顺

feat 分账对账功能改造

1 parent 84a142b3
Showing 33 changed files with 1749 additions and 65 deletions
# 财务规则页:增量提交与两阶段校验
## 变更摘要
- **增量提交**:`merchantSettleDistributeRule.save` 的 `goodsTypeGroupRules` 仅包含「脏」Tab 的规则;每条增加 `type`(`ADD` / `UPDATE`)与 `tabPaneIndex`(前端 Tab 下标,便于联调)。会话内删除的已落库规则 id 放在 `deletedGroupDivisionRuleIds` 中一并提交。
- **请求体组装**:`getParams()` / `handlerConfirm` 会带上 `financialObj` 中的**全量** `goodsTypeGroupRules`;`submit` 在合并 `submitParams` 时先 `delete` 再写入增量数组,确保序列化后的 JSON **不会**再包含未改动 Tab 的全量规则数据。
- **脏 Tab**:`ruleCacheRevision !== confirmedRuleCacheRevision`(与既有 persist / bump 语义一致)。未改动的 Tab 不参与分类校验、不进入 `goodsTypeGroupRules`。
- **持久化对比**:`persistClassificationTabByPaneName` 对合并结果与缓存**先 `fillDjGoodsTypeGroupRelations` 再 `financialRulePayloadDeepEqual`**(键序无关 + `lodash/isEqualWith` 叶子宽松比较),避免切换 Tab 时 `getClassificationParams` 与接口在 `goodsTypeGroupRelations` 等字段形态不一致而误 bump;并减少 `merchantId`/比例等 number 与 string 差异导致的误校验。
- **仅切换品类 Tab、未改表单**:持久化时用 `financialRulePayloadDeepEqual`(键序无关)与缓存对比;与缓存实质相同则不 bump,仍视为未修改(不校验、不提交该 Tab)。说明文档勿放在 `src/views` 下,避免被 webpack 的 `require.context` 扫入导致编译报错。
- **两阶段校验**:先对「待校验 Tab」的缓存数据做纯数据校验(`utils/validateGoodsTypeGroupRulePayload.js`);**第一个失败即停止**,再切到该品类并调用子组件 `handleConfirm` 做 Element 标红。未失败时不对千级 Tab 逐页挂载 `el-form.validate`。
- **费用类目冲突**:`computeCalculateModeConflicts` 使用与 `editableTabs` 下标对齐的**全量合并视图**(`buildFullMergedGoodsTypeGroupRules`),避免仅用增量数组导致下标错位。
## 后端约定(需与接口文档对齐)
| 字段 | 说明 |
|------|------|
| `goodsTypeGroupRules[]` | 每项为规则对象,并含 `type`: `ADD` \| `UPDATE`;可选 `tabPaneIndex` |
| `deletedGroupDivisionRuleIds[]` | 本次删除的 `groupDivisionRuleId` 字符串列表 |
| 仅改基础信息、无分类变更 | `goodsTypeGroupRules` 可为 `[]`,仅传 `financialObj` 其它字段 |
## 风险与边界
- **纯数据校验与 el-form**:极端情况下若两者不一致,以先失败的为准;纯数据失败会触发 `handleConfirm` 标红。
- **保存回包**:`codeHandleConfirm` 中按 `groupDivisionRuleId` 优先匹配 Tab,否则回退为数组下标,兼容全量/增量回包。
- **删除 Tab**:已落库(非「本会话新增」或已有服务端 `groupDivisionRuleId`)的规则删除时写入 `pendingDeletedGroupDivisionRuleIds`。**本会话点「新增」再删掉的 Tab**(`sessionAdded: true`)只做前端 `goodsTypeGroupRules` / `editableTabs` 同步删除,**不向服务端传删除**。保存回写若带上 `groupDivisionRuleId` 会清除 `sessionAdded`,之后删除再按已落库处理。删除后重建 `editableTabs` 时须按旧下标保留 **`ruleCacheRevision` / `confirmedRuleCacheRevision`**(与 `sessionAdded` 同映射),避免误清零导致未改 Tab 被误判脏或已改 Tab 丢失脏标记。
## 相关文件
- `src/views/systemConfig/merchant/financialRules/index.vue`:`getGoodsTypeGroupRules`、`submit`、`checkCalculateType`、`codeHandleConfirm`、`removeTab`
- `src/views/systemConfig/merchant/financialRules/utils/goodsTypeGroupRuleOpType.js`
- `src/views/systemConfig/merchant/financialRules/utils/validateGoodsTypeGroupRulePayload.js`
...@@ -23,7 +23,7 @@ export default { ...@@ -23,7 +23,7 @@ export default {
* @param {Object} state state * @param {Object} state state
*/ */
source(state) { source(state) {
console.log(state) // console.log(state)
return state.source return state.source
}, },
/** /**
......
...@@ -3,25 +3,16 @@ ...@@ -3,25 +3,16 @@
<d2-container class="product-manage"> <d2-container class="product-manage">
<template #header> <template #header>
<div class="header"> <div class="header">
<d2-search class="show-search" <d2-search class="show-search" :form-data="showFormData" label-width="100px" :search-form="searchForm">
:form-data="showFormData"
label-width="100px"
:search-form="searchForm">
<template #goodsCascader> <template #goodsCascader>
<el-cascader v-model="tempGoodsType" <el-cascader v-model="tempGoodsType" filterable :options="baseData.productTypeList" placeholder="请选择"
filterable :props="{ checkStrictly: true, label: 'categoryName', value: 'categoryType' }" style="width: 100%;"
:options="baseData.productTypeList"
placeholder="请选择"
:props="{ checkStrictly: true, label: 'categoryName', value: 'categoryType' }"
style="width: 100%;"
@change="selectAddAttr($event)"> @change="selectAddAttr($event)">
</el-cascader> </el-cascader>
</template> </template>
</d2-search> </d2-search>
<div class="up-btns"> <div class="up-btns">
<el-button :id="tableParams.btnId" <el-button :id="tableParams.btnId" size="small" type="primary">
size="small"
type="primary">
查询 查询
</el-button> </el-button>
<el-button size="small" @click="handleReset"> <el-button size="small" @click="handleReset">
...@@ -45,18 +36,11 @@ ...@@ -45,18 +36,11 @@
<!-- </span> --> <!-- </span> -->
</template> </template>
<!-- 导出 --> <!-- 导出 -->
<auth-button category="Button" <auth-button category="Button" :show-btn-ids="['9030702']" style="display: inline-block" />
:show-btn-ids="['9030702']"
style="display: inline-block" />
</d2-table-header> </d2-table-header>
<d2-table ref="productManageTable" <d2-table ref="productManageTable" :before-search-fn="beforeSearchFn"
:before-search-fn="beforeSearchFn" :filter-list-data-fn="filterProductManageListData" :get-list-api="getListApi" :has-num="false"
:filter-list-data-fn="filterProductManageListData" :search-form="searchForm" :table-params="tableParams" @setTableFinishFun="setTableFinishFun">
:get-list-api="getListApi"
:has-num="false"
:search-form="searchForm"
:table-params="tableParams"
@setTableFinishFun="setTableFinishFun">
<template #img="scope"> <template #img="scope">
<div class="material"> <div class="material">
<img class="pro-img" :src="(scope.scope.goodsInfo && scope.scope.goodsInfo.thumbUrl) || ''"> <img class="pro-img" :src="(scope.scope.goodsInfo && scope.scope.goodsInfo.thumbUrl) || ''">
...@@ -71,38 +55,26 @@ ...@@ -71,38 +55,26 @@
<span style="margin-right: 10px;"> <span style="margin-right: 10px;">
<auth-button :data="getAuthButtonData(scope.scope)" :show-btn-ids="['9030703']" /> <auth-button :data="getAuthButtonData(scope.scope)" :show-btn-ids="['9030703']" />
</span> </span>
<auth-button :data="getAuthButtonData(scope.scope)" <auth-button :data="getAuthButtonData(scope.scope)" :show-btn-ids="['9030706']" />
:show-btn-ids="['9030706']" />
</div> </div>
</template> </template>
</d2-table> </d2-table>
</div> </div>
<!-- 查看面板 SPU --> <!-- 查看面板 SPU -->
<DrawerDetail v-if="drawerDetailVisible" <DrawerDetail v-if="drawerDetailVisible" :commodity-info-id="commodityDetailInfoId"
:commodity-info-id="commodityDetailInfoId" :drawer-detail-visible="drawerDetailVisible" :position-type-list="positionTypeList"
:drawer-detail-visible="drawerDetailVisible"
:position-type-list="positionTypeList"
@handleDrawerClose="handleDrawerClose" /> @handleDrawerClose="handleDrawerClose" />
<!-- 查看面板 SKU(分页) --> <!-- 查看面板 SKU(分页) -->
<DrawerSkuDetail v-if="drawerSkuDetailVisible" <DrawerSkuDetail v-if="drawerSkuDetailVisible" :commodity-info-id="commodityDetailInfoId"
:commodity-info-id="commodityDetailInfoId" :commodity-info-sku-id="commodityDetailInfoSkuId" :drawer-detail-visible="drawerSkuDetailVisible"
:commodity-info-sku-id="commodityDetailInfoSkuId" :position-type-list="positionTypeList" @handleDrawerClose="handleSkuDrawerClose" />
:drawer-detail-visible="drawerSkuDetailVisible"
:position-type-list="positionTypeList"
@handleDrawerClose="handleSkuDrawerClose" />
<!-- 轻改SKU批量导入 --> <!-- 轻改SKU批量导入 -->
<d2-file-import-dialog :is-visible="fileVisible" <d2-file-import-dialog :is-visible="fileVisible" template-name="轻改模版下载" title="批量导入轻改SKU"
template-name="轻改模版下载" @closeDialog="handleBatchImport" @confirmDialog="handleConfirmImport"
title="批量导入轻改SKU"
@closeDialog="handleBatchImport"
@confirmDialog="handleConfirmImport"
@downloadTemplate="exportTemplate('qinggai')" /> @downloadTemplate="exportTemplate('qinggai')" />
<!-- 延保SKU批量导入 --> <!-- 延保SKU批量导入 -->
<d2-file-import-dialog :is-visible="fileVisibleExtension" <d2-file-import-dialog :is-visible="fileVisibleExtension" template-name="延保模版下载" title="批量导入延保SKU"
template-name="延保模版下载" @closeDialog="handleBatchImportExtension" @confirmDialog="handleConfirmImportExtension"
title="批量导入延保SKU"
@closeDialog="handleBatchImportExtension"
@confirmDialog="handleConfirmImportExtension"
@downloadTemplate="exportTemplate('yanbao')" /> @downloadTemplate="exportTemplate('yanbao')" />
</d2-container> </d2-container>
</template> </template>
...@@ -497,18 +469,19 @@ export default { ...@@ -497,18 +469,19 @@ export default {
}, },
// 商品管理列表数据转换:N-父级+子级;Y-直接返回 SKU 平铺,均需处理规格、价格等展示数据 // 商品管理列表数据转换:N-父级+子级;Y-直接返回 SKU 平铺,均需处理规格、价格等展示数据
filterProductManageListData(listData) { filterProductManageListData(listData) {
console.log(listData, "listData");
if (!listData || !Array.isArray(listData)) if (!listData || !Array.isArray(listData))
return listData; return listData;
const isSkuMode = this.searchForm.showSkuMode === "Y"; const isSkuMode = this.searchForm.showSkuMode === "Y";
// 新 SPU 接口不返回 upgradeGoodsList,标记为 SPU 平铺模式 // 新 SPU 接口不返回 upgradeGoodsList,标记为 SPU 平铺模式
this.spuOnlyMode = !listData.some(item => item.upgradeGoodsList && item.upgradeGoodsList.length); this.spuOnlyMode = !listData.some(item => item.upgradeGoodsList && item.upgradeGoodsList.length);
const baseGoodsIdCount = {}; const baseGoodsIdCount = {};
if (isSkuMode) { // if (isSkuMode) {
listData.forEach((item) => { // listData.forEach((item) => {
const bid = item.baseGoodsId || item.id; // const bid = item.baseGoodsId || item.id;
baseGoodsIdCount[bid] = (baseGoodsIdCount[bid] || 0) + 1; // baseGoodsIdCount[bid] = (baseGoodsIdCount[bid] || 0) + 1;
}); // });
} // }
listData.forEach((val) => { listData.forEach((val) => {
if (!val.goodsInfo) if (!val.goodsInfo)
val.goodsInfo = {}; val.goodsInfo = {};
...@@ -568,6 +541,7 @@ export default { ...@@ -568,6 +541,7 @@ export default {
this._setSpuOnlyDefaults(val); this._setSpuOnlyDefaults(val);
} }
}); });
console.log(listData, "listData");
return listData; return listData;
}, },
// 从多个来源取第一个有效值 // 从多个来源取第一个有效值
...@@ -809,7 +783,7 @@ export default { ...@@ -809,7 +783,7 @@ export default {
confirmButtonText: "确定", confirmButtonText: "确定",
showCancelButton: false, showCancelButton: false,
type: "warning", type: "warning",
}).then(() => {}); }).then(() => { });
return; return;
} }
console.log(row); console.log(row);
......
<template> <template>
<el-row class="description-wrapper"> <el-row class="description-wrapper">
<template v-for="item in schema"> <template v-for="item in schema">
<el-col v-if="!isHideSchemaItem(item)" <el-col v-if="!isHideSchemaItem(item)" :key="item._key" :span="item.col || 12">
:key="item._key" <slot :name="item.slot || item.name">
:span="item.col || 12">
<slot :name="item.slot || item.name ">
<div class="form-item" :style="item.itemStyle || {}"> <div class="form-item" :style="item.itemStyle || {}">
<span class="label" :style="{ width: item.labelWidth || '150px' }"> <span class="label" :style="{ width: item.labelWidth || '150px' }">
<slot :name="`${item.slot || item.name}-label`"> <slot :name="`${item.slot || item.name}-label`">
...@@ -14,12 +12,12 @@ ...@@ -14,12 +12,12 @@
<span class="value"> <span class="value">
<div class="text-hide" :style="{ width: item.valueWidth || '100%' }"> <div class="text-hide" :style="{ width: item.valueWidth || '100%' }">
<template v-if="item.render"> <template v-if="item.render">
<RenderProxy :render="item.render" <RenderProxy :render="item.render" :row="{ data, schemaItem: item, schema }" />
:row="{ data, schemaItem: item, schema }" />
</template> </template>
<template v-else> <template v-else>
<template v-if="item.tooltip && (getValue(item.descKey || item.name))"> <template v-if="item.tooltip && (getValue(item.descKey || item.name))">
<el-tooltip :content="isZeroOrNumber(getValue(item.descKey || item.name)) " v-bind="item.tooltipProps"> <el-tooltip :content="isZeroOrNumber(getValue(item.descKey || item.name))"
v-bind="item.tooltipProps">
<div class="text-hide"> <div class="text-hide">
{{ isZeroOrNumber(getValue(item.descKey || item.name)) }} {{ isZeroOrNumber(getValue(item.descKey || item.name)) }}
</div> </div>
...@@ -103,6 +101,7 @@ export default { ...@@ -103,6 +101,7 @@ export default {
<style scoped lang="scss"> <style scoped lang="scss">
.description-wrapper { .description-wrapper {
font-size: 14px; font-size: 14px;
.form-item { .form-item {
display: flex; display: flex;
flex-direction: row; flex-direction: row;
...@@ -110,13 +109,14 @@ export default { ...@@ -110,13 +109,14 @@ export default {
line-height: 32px; line-height: 32px;
margin-bottom: 20px; margin-bottom: 20px;
> .label { >.label {
text-align: right; text-align: right;
color: #666666; color: #666666;
font-size: 14px; font-size: 14px;
flex-shrink: 0; flex-shrink: 0;
} }
> .value {
>.value {
flex-shrink: 0; flex-shrink: 0;
flex: 1; flex: 1;
overflow: hidden; overflow: hidden;
......
<template>
<div>
<p class="edit-sub-title">
分账品类
</p>
<el-form-item v-if="paneIndex"
label="商品来源"
prop="goodsSource"
required
:rules="[
{
required: true,
message: '请选择商品来源',
trigger: ['change', 'blur'],
},
]">
<el-radio-group v-model="classificationObj.goodsSource">
<el-radio v-for="(goodsItem, goodsIndex) in goodsSourceList"
:key="goodsIndex"
:disabled="goodsSourceSet.includes(goodsItem.confId)
&& goodsItem.confId != 1
&& classificationObj.goodsSource != goodsItem.confId
"
:label="goodsItem.confId">
{{ goodsItem.confValue }}
</el-radio>
</el-radio-group>
</el-form-item>
<div v-if="paneIndex && ![2, 3].includes(classificationObj.goodsSource)" style="display: flex">
<el-form-item label="分账品类"
prop="categoryType"
required
:rules="[
{
required: true,
message: '请选择分账品类',
trigger: ['change', 'blur'],
},
]">
<el-select v-model="classificationObj.categoryType" @change="onCategoryTypeChange">
<el-option :key="1"
label="按商品分类"
:value="1" />
<el-option :key="2"
label="按具体商品"
:value="2" />
<el-option :key="3"
label="按具体套餐"
:value="3" />
</el-select>
</el-form-item>
<el-form-item v-if="classificationObj.categoryType == 1"
prop="goodsTypes"
label-width="20px"
:rules="[
{
required: true,
message: '请选择商品分类',
trigger: ['change', 'blur'],
},
]">
<el-select v-model="classificationObj.goodsTypes"
value-key="goodsType"
multiple
collapse-tags
style="width: 320px"
placeholder="请选择品类">
<el-option v-for="item in goodsList"
:key="item.goodsType"
:label="item.goodsTypeName"
:disabled="filterGoodsTypeItemDisabled(item, disabledGoodsTypeList)"
:value="item" />
</el-select>
</el-form-item>
<el-form-item v-show="classificationObj.categoryType == 2"
:prop="classificationObj.categoryType == 2 ? 'upgradeGoods' : 'empty'"
label-width="20px">
<el-select v-model="classificationObj.upgradeGoods"
multiple
collapse-tags
remote
reserve-keyword
placeholder="请选择商品"
:remote-method="remoteMethod"
popper-class="classification-upgrade-goods-popper"
style="width: 370px"
value-key="upgradeGoodsId"
filterable
@visible-change="visibleChange"
@change="upgradeGoodsChange">
<el-option v-for="subItem in copyUpgradeGoodsList"
:key="subItem.upgradeGoodsId"
:label="`${subItem.upgradeGoodsName}(${subItem.commodityCode})`"
:disabled="filterUpgradeGoodsItemDisabled(subItem, disabledUpgradeGoodsList)"
:value="subItem" />
</el-select>
</el-form-item>
<el-form-item v-show="classificationObj.categoryType == 3"
:prop="classificationObj.categoryType == 3 ? 'packageGoods' : 'empty'"
label-width="20px">
<el-select v-model="classificationObj.packageGoods"
multiple
collapse-tags
remote
reserve-keyword
placeholder="请选择套餐商品"
:remote-method="remoteMethodPackage"
popper-class="classification-package-goods-popper"
style="width: 370px"
value-key="packageCode"
filterable
@visible-change="visibleChangePackage">
<el-option v-for="subItem in copyPackageGoodsList"
:key="subItem.packageCode"
:label="`${subItem.packageName}(${subItem.packageCode})`"
:disabled="filterPackageGoodsItemDisabled(subItem, disabledPackageGoodsList)"
:value="subItem" />
</el-select>
</el-form-item>
</div>
</div>
</template>
<script>
import { goodsSourceList } from "@/common/constant/merchant"
export default {
name: "GoodsSourceCategoryPicker",
props: {
paneIndex: {
type: Number,
default: 0
},
classificationObj: {
type: Object,
required: true
},
goodsList: {
type: Array,
required: true
},
goodsSourceSet: {
type: Array,
default: () => []
},
copyUpgradeGoodsList: {
type: Array,
default: () => []
},
copyPackageGoodsList: {
type: Array,
default: () => []
},
disabledGoodsTypeList: {
type: Array,
default: () => []
},
disabledUpgradeGoodsList: {
type: Array,
default: () => []
},
disabledPackageGoodsList: {
type: Array,
default: () => []
},
filterGoodsTypeItemDisabled: {
type: Function,
required: true
},
filterUpgradeGoodsItemDisabled: {
type: Function,
required: true
},
filterPackageGoodsItemDisabled: {
type: Function,
required: true
},
remoteMethod: {
type: Function,
required: true
},
remoteMethodPackage: {
type: Function,
required: true
},
visibleChange: {
type: Function,
required: true
},
visibleChangePackage: {
type: Function,
required: true
},
upgradeGoodsChange: {
type: Function,
required: true
},
onCategoryTypeChange: {
type: Function,
required: true
}
},
data() {
return {
goodsSourceList: Object.freeze(goodsSourceList)
}
}
}
</script>
import { GOODS_TYPE_GROUP_RULE_OP } from "./goodsTypeGroupRuleOpType"
/**
* 由已通过纯数据校验的 validatedByIndex 生成增量提交行(带 type / tabPaneIndex)。
*
* @param {Record<number, object>} validatedByIndex
* @param {number[]} indicesToValidate
* @param {boolean} onlyActiveTab
* @returns {Array<object>}
*/
export function buildGoodsTypeGroupIncrementalRules(
validatedByIndex,
indicesToValidate,
onlyActiveTab
) {
const incrementalRules = []
if (onlyActiveTab) {
const idx = indicesToValidate[0]
if (idx !== undefined) {
const rule = validatedByIndex[idx]
const id = rule && rule.groupDivisionRuleId
const hasId = id != null && String(id).trim() !== ""
const type = hasId
? GOODS_TYPE_GROUP_RULE_OP.UPDATE
: GOODS_TYPE_GROUP_RULE_OP.ADD
incrementalRules.push({
...rule,
type,
tabPaneIndex: idx
})
}
} else {
for (let j = 0; j < indicesToValidate.length; j++) {
const idx = indicesToValidate[j]
const rule = validatedByIndex[idx]
if (!rule) continue
const id = rule.groupDivisionRuleId
const hasId = id != null && String(id).trim() !== ""
const type = hasId
? GOODS_TYPE_GROUP_RULE_OP.UPDATE
: GOODS_TYPE_GROUP_RULE_OP.ADD
incrementalRules.push({
...rule,
type,
tabPaneIndex: idx
})
}
}
return incrementalRules
}
/**
* classificationCpt → 父组件 classification-change 事件的 type 枚举(与 handleClassificationChange switch 对齐)。
*/
export const CLASSIFICATION_EMIT = {
ASSIGN_GOODS_TYPE_LIST: "assignGoodsTypeList",
DELETE_GOODS_TYPE_ITEM: "deleteGoodsTypeItem",
ASSIGN_UPGRADE_GOODS_LIST: "assignUpgradeGoodsList",
DELETE_UPGRADE_GOODS_ITEM: "deleteUpgradeGoodsItem",
ASSIGN_PACKAGE_GOODS_LIST: "assignPackageGoodsList",
DELETE_PACKAGE_GOODS_ITEM: "deletePackageGoodsItem",
DELETE_SELECT_GOODS_TYPE_LIST: "deleteSelectGoodsTypeList",
DELETE_SELECT_UPGRADE_GOODS_LIST: "deleteSelectUpgradeGoodsList",
DELETE_SELECT_PACKAGE_GOODS_LIST: "deleteSelectPackageGoodsList",
CLASSIFICATION_TOUCHED: "classification-touched",
RULES_TEST: "rulesTest"
}
/**
* 分账品类:子组件 payload 与 financialObj 槽位合并、增量规则构建(供 index.vue 引用)。
*/
export { mergeChildClassificationPayload } from "./mergeClassificationPayload"
export { buildGoodsTypeGroupIncrementalRules } from "./buildGoodsTypeGroupIncrementalRules"
/**
* @typedef {Object} FinancialRulesPageContext
* @property {Object} financialLedgerParty 平台方/流量方/嘀加子商户等分账方展示用
* @property {Array} serviceMerchantList 服务商下拉
*/
/**
* @typedef {Object} FinancialRulesSelectionContext
* @property {Array} goodsList 可选品类(与 goodsTypeGroupRelations 同源)
* @property {Array} goodsSelectList 跨 Tab 已选品类
* @property {Array} upgradeGoodsList 升级商品候选
* @property {Array} packageGoodsList 套餐候选
* @property {Array} selectUpgradeGoodsList 跨 Tab 已选升级商品
* @property {Array} selectPackageGoodsList 跨 Tab 已选套餐
*/
/**
* @typedef {Object} FinancialRulesPaneContext
* @property {Object} goodsTypeGroupRules 当前 Tab 槽位规则
* @property {number} paneIndex 当前 Tab 下标
* @property {Object} tabItem 当前 Tab 元数据(testFlag、revision 等)
* @property {Object} classificationObjSelect 父级 classificationObj 引用
*/
export {}
/**
* 财务规则保存:分账品类规则增量操作类型(与后端约定一致时可调整取值)。
*/
export const GOODS_TYPE_GROUP_RULE_OP = {
ADD: "ADD",
UPDATE: "UPDATE",
DELETE: "DELETE"
}
import { deepClone } from "@/common/util"
const GUARD_EMPTY_ARRAY_KEYS = [
"expenseCategoryRules",
"merchantDistributionRules",
"owningMerchantDistributionRules",
"goodsTypes",
"upgradeGoods",
"packageGoods"
]
/**
* 将子组件 getClassificationParams() 的 payload 与槽位缓存合并为 next(与 index buildMerged 一致)。
*
* @param {object} payload 子组件返回
* @param {object|undefined} prevStoredRaw financialObj.goodsTypeGroupRules[idx] 原始引用
* @returns {{ next: object, prevStored: object|undefined }}
*/
export function mergeChildClassificationPayload(payload, prevStoredRaw) {
const prev = prevStoredRaw || {}
const base = deepClone(prev)
const next = { ...base, ...payload }
if (
!Object.prototype.hasOwnProperty.call(payload, "expenseCategoryRules") ||
payload.expenseCategoryRules == null
) {
next.expenseCategoryRules = base.expenseCategoryRules
}
if (
!Object.prototype.hasOwnProperty.call(payload, "merchantDistributionRules") ||
payload.merchantDistributionRules == null
) {
next.merchantDistributionRules = base.merchantDistributionRules
}
if (
!Object.prototype.hasOwnProperty.call(
payload,
"owningMerchantDistributionRules"
) ||
payload.owningMerchantDistributionRules == null
) {
next.owningMerchantDistributionRules = base.owningMerchantDistributionRules
}
GUARD_EMPTY_ARRAY_KEYS.forEach((key) => {
const p = payload[key]
const b = base[key]
if (
Array.isArray(p) &&
p.length === 0 &&
Array.isArray(b) &&
b.length > 0
) {
next[key] = b
}
})
return { next, prevStored: prevStoredRaw }
}
import { deepClone } from "@/common/util"
/**
* 按 goodsTypes[0].categoryType 将接口 goodsTypes 归一为 classification 表单字段,
* 并向 upgradeArr / packageArr 收集用于远程下拉补全的条目。
* 会直接修改 item(与 getFinancialObj / removeTab 原逻辑一致)。
*
* @param {object} item goodsTypeGroupRules 单项
* @param {Array<{upgradeGoodsId: *, upgradeGoodsName: *, commodityCode: *}>} upgradeArr
* @param {Array<{packageCode: *, packageName: *}>} packageArr
*/
export function normalizeRuleGoodsTypesForCategory(item, upgradeArr, packageArr) {
if (!item || !item.goodsTypes?.length || item.goodsTypes[0]?.categoryType == null) {
return
}
const categoryType = item.goodsTypes[0].categoryType
if (categoryType == 1) {
item.goodsTypes = deepClone(item.goodsTypes)
item.categoryType = 1
item.upgradeGoods = []
item.packageGoods = []
return
}
if (categoryType == 2) {
item.upgradeGoods = deepClone(item.goodsTypes)
item.categoryType = 2
item.goodsTypes.forEach((val) => {
upgradeArr.push({
upgradeGoodsId: val.upgradeGoodsId,
upgradeGoodsName: val.upgradeGoodsName,
commodityCode: val.commodityCode
})
})
item.goodsTypes = []
item.packageGoods = []
return
}
if (categoryType == 3) {
item.packageGoods = deepClone(item.goodsTypes)
item.categoryType = 3
item.goodsTypes.forEach((val) => {
packageArr.push({
packageCode: val.packageCode,
packageName: val.packageName
})
})
item.goodsTypes = []
item.upgradeGoods = []
}
}
import isEqualWith from "lodash/isEqualWith"
/**
* 分账规则缓存对比:排序对象键;再用 isEqualWith 宽松比较叶子,
* 避免 `merchantId`、比例等 number / string 与缓存不一致导致误 bump。
* 数组顺序保持不变(费用类目等顺序有语义)。
*/
function canonicalizeForCompare(val) {
if (val === null || val === undefined) return val
const t = typeof val
if (t !== "object") return val
if (Array.isArray(val)) return val.map((item) => canonicalizeForCompare(item))
const out = {}
Object.keys(val)
.sort()
.forEach((k) => {
const v = val[k]
if (v === undefined) return
out[k] = canonicalizeForCompare(v)
})
return out
}
/**
* 叶子宽松相等:数字与数字字符串、布尔与 "Y"/"N" 等表单与接口常见差异
*/
function looseLeafEqual(val1, val2) {
if (val1 === val2) return true
if (val1 == null && val2 == null) return true
if (val1 == null || val2 == null) return false
const t1 = typeof val1
const t2 = typeof val2
if (t1 === "object" || t2 === "object") return undefined
if (t1 === "boolean" || t2 === "boolean") {
return val1 === val2
}
if (
(t1 === "number" || t1 === "string")
&& (t2 === "number" || t2 === "string")
) {
const s1 = String(val1).trim()
const s2 = String(val2).trim()
if (s1 === "" && s2 === "") return true
const n1 = Number(s1)
const n2 = Number(s2)
if (!Number.isNaN(n1) && !Number.isNaN(n2) && s1 === String(n1) && s2 === String(n2)) {
return n1 === n2
}
return s1 === s2
}
return undefined
}
/**
* @param {object} a
* @param {object} b
* @returns {boolean}
*/
export function financialRulePayloadDeepEqual(a, b) {
if (a === b) return true
try {
const ca = canonicalizeForCompare(a)
const cb = canonicalizeForCompare(b)
return isEqualWith(ca, cb, (v1, v2) => {
const loose = looseLeafEqual(v1, v2)
if (loose === true) return true
if (loose === false) return false
return undefined
})
} catch (e) {
return false
}
}
import { deepClone } from "@/common/util"
import { fillDjGoodsTypeGroupRelations } from "../../merchantStep/utils/reconciliationShared"
function rateFilled(v) {
if (v === null || v === undefined) return false
const s = String(v).trim()
if (s === "") return false
return !Number.isNaN(Number(s))
}
/**
* 与 index.vue distributionRulesLookComplete 一致:分账表每行须带有效 merchantId。
*/
export function distributionRulesLookComplete(rule) {
const md = rule.merchantDistributionRules
const od = rule.owningMerchantDistributionRules
if (!Array.isArray(md) || !Array.isArray(od)) return false
if (md.length === 0 || od.length === 0) return false
const rowOk = (rows) =>
rows.every(
(r) =>
r &&
typeof r === "object" &&
r.merchantId !== "" &&
r.merchantId !== undefined &&
r.merchantId !== null
)
return rowOk(md) && rowOk(od)
}
function ynFlagOk(v) {
return v === "Y" || v === "N"
}
/**
* 单条费用类目行(含 formType===2 子行)必填项检查,对齐 classificationCpt 表单项。
*/
function validateExpenseCategoryLeaf(item) {
if (!item || typeof item !== "object") return false
if (item.nodeType === 4) return true
if (item.calculateMode === undefined || item.calculateMode === null) return false
if (
item.expenseCategoryCalculateType === undefined
|| item.expenseCategoryCalculateType === null
) {
return false
}
const v = item.expenseCategoryValue
if (v === null || v === undefined || String(v).trim() === "") return false
return true
}
function validateExpenseCategoryRulesArray(rules) {
if (!Array.isArray(rules) || rules.length === 0) return false
for (let i = 0; i < rules.length; i++) {
const item = rules[i]
if (!validateExpenseCategoryLeaf(item)) return false
if (item.formType === 2 && Array.isArray(item.children)) {
for (let j = 0; j < item.children.length; j++) {
const ch = item.children[j]
if (ch && ch.nodeType === 4) continue
if (!validateExpenseCategoryLeaf(ch)) return false
}
}
}
return true
}
function validateCostConvertRates(rule) {
if (rule.goodsCostFlag === "Y" && !rateFilled(rule.goodsCostConvertRate)) return false
if (rule.virtualAccountCostFlag === "Y" && !rateFilled(rule.virtualAccountCostConvertRate)) {
return false
}
if (rule.recoveryCostFlag === "Y" && !rateFilled(rule.recoveryCostConvertRate)) return false
if (rule.djCostFlag === "Y" && !rateFilled(rule.djCostConvertRate)) return false
if (rule.thirdPartyCostFlag === "Y" && !rateFilled(rule.thirdPartyCostConvertRate)) {
return false
}
return true
}
/**
* 对单条 goodsTypeGroupRules 项做纯数据校验(不挂载 el-form)。
* 先 fillDjGoodsTypeGroupRelations 再验,与提交流程一致。
*
* @returns {boolean}
*/
export function validateGoodsTypeGroupRulePayload(rawRule) {
if (!rawRule || typeof rawRule !== "object") return false
const rule = fillDjGoodsTypeGroupRelations(deepClone(rawRule))
if (!rule || typeof rule !== "object") return false
if (rule.shop4sDeductChargeFlag == null) rule.shop4sDeductChargeFlag = "Y"
if (rule.partnerDeductChargeFlag == null) rule.partnerDeductChargeFlag = "Y"
if (rule.goodsCostFlag == null) rule.goodsCostFlag = "Y"
if (rule.virtualAccountCostFlag == null) rule.virtualAccountCostFlag = "Y"
if (rule.recoveryCostFlag == null) rule.recoveryCostFlag = "Y"
if (rule.djCostFlag == null) rule.djCostFlag = "Y"
if (rule.thirdPartyCostFlag == null) rule.thirdPartyCostFlag = "Y"
if (!ynFlagOk(rule.shop4sDeductChargeFlag) || !ynFlagOk(rule.partnerDeductChargeFlag)) {
return false
}
if (!validateCostConvertRates(rule)) return false
const expenseCategoryRules = rule.expenseCategoryRules
if (!validateExpenseCategoryRulesArray(expenseCategoryRules)) return false
if (!distributionRulesLookComplete(rule)) return false
const gt = Number(rule.groupType)
const gs = Number(rule.goodsSource)
// 嘀加来源且特殊品类:须指定品类/商品/套餐清单;goodsSource 为 2、3 时模板不展示该校验项
if (gt === 2 && gs === 1) {
const rel = rule.goodsTypeGroupRelations
if (!Array.isArray(rel) || rel.length === 0) return false
}
return true
}
export function prepareRuleForValidation(rawRule) {
return fillDjGoodsTypeGroupRelations(deepClone(rawRule))
}
...@@ -456,8 +456,6 @@ export default { ...@@ -456,8 +456,6 @@ export default {
// deep: true // deep: true
// } // }
}, },
created() { },
mounted() { },
methods: { methods: {
// inItem() { // inItem() {
// const obj = deepClone(this.ledgerInfo) // const obj = deepClone(this.ledgerInfo)
......
/**
* tab0「全部品类」占位:getEffectRule 末尾会清空 live phantom,比对/解析需回落到基线中的快照。
* @param {object|null|undefined} livePhantom
* @param {object|null|undefined} baselinePhantom
* @returns {object|null}
*/
export function getEffectivePhantomFullCategoryRuleRaw(
livePhantom,
baselinePhantom
) {
if (livePhantom && typeof livePhantom === "object") return livePhantom
if (baselinePhantom && typeof baselinePhantom === "object") {
return baselinePhantom
}
return null
}
...@@ -21,3 +21,15 @@ export function uniqueUpgradeGoodsById(arr) { ...@@ -21,3 +21,15 @@ export function uniqueUpgradeGoodsById(arr) {
(a) => !res.has(a.upgradeGoodsId) && res.set(a.upgradeGoodsId, 1) (a) => !res.has(a.upgradeGoodsId) && res.set(a.upgradeGoodsId, 1)
) )
} }
/**
* 套餐商品列表按 packageCode 去重,保留首次出现顺序(grounding 分页与下拉共用)。
* @param {Array<{packageCode: unknown}>|undefined} arr
* @returns {Array<{packageCode: unknown}>}
*/
export function uniquePackageByPackageCode(arr) {
const res = new Map()
return (arr || []).filter(
(a) => !res.has(a.packageCode) && res.set(a.packageCode, 1)
)
}
import { deepClone } from "@/common/util"
const TOP_EMPTY_ARRAY_KEYS = [
"upgradeGoods",
"packageGoods",
"goodsTypeGroupRelations"
]
/** 与 getBackendFormat / 提交体对齐的顶层字段;接口其余字段不参与「是否改动」比对 */
const ALLOWED_TOP_KEYS = new Set([
"groupType",
"categoryType",
"expenseCategoryRules",
"goodsSource",
"upgradeGoods",
"packageGoods",
"goodsTypeGroupRelations",
"goodsTypes",
"id",
"groupDivisionRuleId",
"formType"
])
/** 费用行可比字段(排除接口审计、扩展字段) */
const ALLOWED_EXPENSE_KEYS = new Set([
"targetType",
"expenseCategoryId",
"expenseCategoryName",
"expenseCategoryCalculateType",
"expenseCategoryValue",
"targetMerchantName",
"targetMerchantId",
"calculateMode",
"formType",
"nodeType",
"children",
"categoryType"
])
function omitUndefinedShallow(obj) {
if (!obj || typeof obj !== "object") return
Object.keys(obj).forEach((k) => {
if (obj[k] === undefined) delete obj[k]
})
}
function omitUndefinedDeep(val, maxDepth) {
if (maxDepth <= 0 || val == null || typeof val !== "object") return
if (Array.isArray(val)) {
for (let i = 0; i < val.length; i++) {
omitUndefinedDeep(val[i], maxDepth - 1)
}
return
}
const keys = Object.keys(val)
for (let i = 0; i < keys.length; i++) {
const k = keys[i]
const v = val[k]
if (v === undefined) {
delete val[k]
} else {
omitUndefinedDeep(v, maxDepth - 1)
}
}
}
/** 比对时统一主键:仅 id、或 id 与 groupDivisionRuleId 同值、或仅有 groupDivisionRuleId 时迁到 id */
function normalizePrimaryRuleId(o) {
if (!o || typeof o !== "object") return
const gid = o.groupDivisionRuleId
const rid = o.id
const gStr = gid != null && String(gid).trim() !== "" ? String(gid).trim() : ""
const rStr = rid != null && String(rid).trim() !== "" ? String(rid).trim() : ""
if (gStr && rStr && gStr === rStr) {
delete o.groupDivisionRuleId
return
}
if (gStr && !rStr) {
o.id = gid
delete o.groupDivisionRuleId
}
}
function pruneTargetMerchantEmpties(row) {
if (!row || typeof row !== "object") return
const id = row.targetMerchantId
const name = row.targetMerchantName
if (id === "" || id == null) delete row.targetMerchantId
if (name === "" || name == null) delete row.targetMerchantName
}
/**
* 仅用于对账基线比对:接口返回与 getBackendFormat(流量+服务+平台拼接)行顺序可能不同,
* financialRulePayloadDeepEqual 保留数组顺序,故在此按稳定键排序后再比。
*/
function expenseRowCompareKey(row) {
if (!row || typeof row !== "object") {
return [1e9, 1e9, 1e9, 1e9]
}
const tt = Number(row.targetType)
const eid = Number(row.expenseCategoryId)
const nt = Number(row.nodeType)
const ft = Number(row.formType)
return [
Number.isFinite(tt) ? tt : 1e9,
Number.isFinite(eid) ? eid : 1e9,
Number.isFinite(nt) ? nt : 1e9,
Number.isFinite(ft) ? ft : 1e9
]
}
function compareExpenseRowsForCompare(a, b) {
const ka = expenseRowCompareKey(a)
const kb = expenseRowCompareKey(b)
for (let i = 0; i < ka.length; i++) {
if (ka[i] !== kb[i]) return ka[i] - kb[i]
}
const na = a && a.expenseCategoryName != null ? String(a.expenseCategoryName) : ""
const nb = b && b.expenseCategoryName != null ? String(b.expenseCategoryName) : ""
if (na < nb) return -1
if (na > nb) return 1
return 0
}
function sortExpenseRulesInPlace(arr) {
if (!Array.isArray(arr) || arr.length < 2) return
arr.sort(compareExpenseRowsForCompare)
}
function normalizeExpenseCategoryRowForCompare(row, sortForCompare = true) {
if (!row || typeof row !== "object") return row
const copy = { ...row }
delete copy.merchant
if (copy.categoryType === "" || copy.categoryType == null) {
delete copy.categoryType
}
pruneTargetMerchantEmpties(copy)
let childrenOut
if (Array.isArray(copy.children) && copy.children.length > 0) {
childrenOut = copy.children.map((ch) =>
normalizeExpenseCategoryRowForCompare(ch, sortForCompare)
)
} else if (Array.isArray(copy.children) && copy.children.length === 0) {
delete copy.children
}
const out = {}
ALLOWED_EXPENSE_KEYS.forEach((k) => {
if (k === "children") {
if (childrenOut && childrenOut.length) {
if (sortForCompare) sortExpenseRulesInPlace(childrenOut)
out.children = childrenOut
}
return
}
if (
Object.prototype.hasOwnProperty.call(copy, k)
&& copy[k] !== undefined
) {
out[k] = copy[k]
}
})
omitUndefinedShallow(out)
return out
}
function pickComparableTopRule(o) {
const next = {}
ALLOWED_TOP_KEYS.forEach((k) => {
if (Object.prototype.hasOwnProperty.call(o, k) && o[k] !== undefined) {
next[k] = o[k]
}
})
return next
}
/**
* 对账规则与基线 / 快照比对前归一化(仅用于 financialRulePayloadDeepEqual):
* - 去掉接口多出的顶层/费用行字段,与 getBackendFormat 语义对齐
* - expenseCategoryRules:去掉 merchant;空 categoryType;空 children;空 targetMerchant*
* - 顶层:空 categoryType;空 upgradeGoods/packageGoods/goodsTypeGroupRelations 整键删除
* - groupDivisionRuleId 与 id 相同时去掉重复字段
* - expenseCategoryRules(及行内 children):按 targetType、expenseCategoryId、nodeType、formType、name 稳定排序(默认仅比对;提交序列化可传 { forCompare: false } 保留表单顺序)
*
* @param {object} rule
* @param {{ forCompare?: boolean }} [options]
* @returns {object}
*/
export function normalizeReconciliationRuleForCompare(rule, options = {}) {
const forCompare = options.forCompare !== false
if (!rule || typeof rule !== "object") return rule
const o = deepClone(rule)
if (o.categoryType === "" || o.categoryType == null) {
delete o.categoryType
}
normalizePrimaryRuleId(o)
for (let i = 0; i < TOP_EMPTY_ARRAY_KEYS.length; i++) {
const k = TOP_EMPTY_ARRAY_KEYS[i]
if (Array.isArray(o[k]) && o[k].length === 0) {
delete o[k]
}
}
if (Array.isArray(o.expenseCategoryRules)) {
o.expenseCategoryRules = o.expenseCategoryRules.map((r) =>
normalizeExpenseCategoryRowForCompare(r, forCompare)
)
if (forCompare) sortExpenseRulesInPlace(o.expenseCategoryRules)
}
omitUndefinedShallow(o)
omitUndefinedDeep(o, 24)
const picked = pickComparableTopRule(o)
return picked
}
import { GOODS_TYPE_GROUP_RULE_OP } from "../../financialRules/utils/goodsTypeGroupRuleOpType"
/**
* 对账规则行上可能存在的服务端主键(与 reconciliation.getEffectRule / saveRule 约定一致)。
* @param {object|null|undefined} rule
* @returns {string}
*/
export function getStableReconciliationRuleId(rule) {
if (!rule || typeof rule !== "object") return ""
const a = rule.groupDivisionRuleId
const b = rule.id
const s = a != null && String(a).trim() !== "" ? String(a).trim() : ""
if (s) return s
return b != null && String(b).trim() !== "" ? String(b).trim() : ""
}
/**
* 将缓存中的主键合并进本次校验通过的快照,便于增量 UPDATE 判型。
* @param {object} snapshot - handleConfirm / getBackendFormat 产物
* @param {object|null|undefined} cachedRule - goodsTypeGroupReconciliationRules 槽位
* @returns {object}
*/
export function mergeReconciliationRuleServerFields(snapshot, cachedRule) {
if (!snapshot || typeof snapshot !== "object") return snapshot
if (!cachedRule || typeof cachedRule !== "object") return snapshot
const out = { ...snapshot }
if (
cachedRule.groupDivisionRuleId != null
&& String(cachedRule.groupDivisionRuleId).trim() !== ""
) {
out.groupDivisionRuleId = cachedRule.groupDivisionRuleId
}
if (cachedRule.id != null && String(cachedRule.id).trim() !== "") {
out.id = cachedRule.id
}
return out
}
/**
* 与财务 buildGoodsTypeGroupIncrementalRules 同款语义:仅「本轮已校验」的 Tab 进入增量数组。
* @param {Record<number, object>} validatedByTabIndex
* @param {number[]} touchedIndices
* @returns {Array<object>}
*/
export function buildReconciliationIncrementalRules(
validatedByTabIndex,
touchedIndices
) {
const incrementalRules = []
for (let j = 0; j < touchedIndices.length; j++) {
const idx = touchedIndices[j]
const rule = validatedByTabIndex[idx]
if (!rule) continue
const idStr = getStableReconciliationRuleId(rule)
const type = idStr
? GOODS_TYPE_GROUP_RULE_OP.UPDATE
: GOODS_TYPE_GROUP_RULE_OP.ADD
incrementalRules.push({
...rule,
type,
tabPaneIndex: idx
})
}
return incrementalRules
}
...@@ -90,6 +90,7 @@ function accumulateFromReconciliationRule(rule, sinks) { ...@@ -90,6 +90,7 @@ function accumulateFromReconciliationRule(rule, sinks) {
/** /**
* 从 goodsTypeGroupReconciliationRules + 可选占位 tab 快照聚合跨 Tab 已选品类/商品/套餐(对账编辑页)。 * 从 goodsTypeGroupReconciliationRules + 可选占位 tab 快照聚合跨 Tab 已选品类/商品/套餐(对账编辑页)。
* 与 {@link rebuildFinancialCrossTabGoodsSelections} 字段与去重策略相近;合并为单实现前需对财务/对账两页做回归(禁用列表、phantom 等差异)。
*/ */
export function rebuildCrossTabReconciliationSelections( export function rebuildCrossTabReconciliationSelections(
rules, rules,
...@@ -145,6 +146,7 @@ export function rebuildCrossTabReconciliationSelections( ...@@ -145,6 +146,7 @@ export function rebuildCrossTabReconciliationSelections(
/** /**
* 财务分账页:从 goodsTypeGroupRules 聚合跨 Tab 已选(浅拷贝条目,与 classificationCpt 禁用列表语义一致)。 * 财务分账页:从 goodsTypeGroupRules 聚合跨 Tab 已选(浅拷贝条目,与 classificationCpt 禁用列表语义一致)。
* @see rebuildCrossTabReconciliationSelections — 对账侧聚合;两函数刻意分叉,合并前需专项测试。
*/ */
export function rebuildFinancialCrossTabGoodsSelections(rules) { export function rebuildFinancialCrossTabGoodsSelections(rules) {
if (!Array.isArray(rules) || !rules.length) { if (!Array.isArray(rules) || !rules.length) {
......
/**
* 对账校验/增量待处理 Tab 门控:与基线有 diff 时,若基线中已有可对该 Tab 比对的行(含 phantom),
* 需用户在本会话有交互(classificationUserTouched)或新 Tab(sessionAdded),
* 避免「接口行 vs getBackendFormat 合并」假脏导致无操作也全量进 incremental。
* 无基线槽位时(如新增可提交规则、仅 substantive)不拦,由 reconciliationTabDiffersFromBaseline 侧语义处理。
*
* @param {object} o
* @param {boolean} o.hasBaselineSlot
* @param {boolean} o.classificationUserTouched
* @param {boolean} o.sessionAdded
* @returns {boolean}
*/
export function shouldIncludeReconciliationTabForProcess({
hasBaselineSlot,
classificationUserTouched,
sessionAdded
}) {
if (!hasBaselineSlot) return true
return classificationUserTouched === true || sessionAdded === true
}
/**
* 对单条「对账」规则做纯数据校验(不挂载 el-form),与提交侧 getBackendFormat 结构对齐。
*
* 校验清单(与 merchantStep classificationCpt getBackendFormat 一致):
* - groupType:1 全部品类 / 2 特殊品类
* - goodsSource:嘀加来源 1 时特殊品类须带 goodsTypeGroupRelations 非空(经 fillDj 后)
* - expenseCategoryRules:流量/服务/平台费用合并后的数组,非空;每行含 calculateMode、对账模式、比例/金额等(nodeType===4 兜底行可放宽)
*
* 说明:reconciliation.saveRule 提交侧使用增量 goodsTypeGroupRules(带 type / tabPaneIndex);单条结构仍须满足本校验。
*/
import { deepClone } from "@/common/util"
import { fillDjGoodsTypeGroupRelations } from "./reconciliationShared"
function validateExpenseCategoryLeaf(item) {
if (!item || typeof item !== "object") return false
if (item.nodeType === 4) return true
if (item.calculateMode === undefined || item.calculateMode === null) return false
if (
item.expenseCategoryCalculateType === undefined
|| item.expenseCategoryCalculateType === null
) {
return false
}
const v = item.expenseCategoryValue
if (v === null || v === undefined || String(v).trim() === "") return false
return true
}
function validateExpenseCategoryRulesArray(rules) {
if (!Array.isArray(rules) || rules.length === 0) return false
for (let i = 0; i < rules.length; i++) {
const item = rules[i]
if (!validateExpenseCategoryLeaf(item)) return false
if (item.formType === 2 && Array.isArray(item.children)) {
for (let j = 0; j < item.children.length; j++) {
const ch = item.children[j]
if (ch && ch.nodeType === 4) continue
if (!validateExpenseCategoryLeaf(ch)) return false
}
}
}
return true
}
/**
* 首条不通过项的中文人读提示与可选 el-form prop(供 validateField 单字段标红)。
* @typedef {{ ok: true, message: string, fieldProp: null }} ReconciliationRuleValidationOk
* @typedef {{ ok: false, message: string, fieldProp: (string|null) }} ReconciliationRuleValidationErr
* @param {object} rawRule
* @returns {ReconciliationRuleValidationOk|ReconciliationRuleValidationErr}
*/
export function getReconciliationRuleValidationResult(rawRule) {
if (!rawRule || typeof rawRule !== "object") {
return { ok: false, message: "对账规则数据不完整", fieldProp: null }
}
const rule = fillDjGoodsTypeGroupRelations(deepClone(rawRule))
if (!rule || typeof rule !== "object") {
return { ok: false, message: "对账规则数据不完整", fieldProp: null }
}
const gt = Number(rule.groupType)
if (gt !== 1 && gt !== 2) {
return { ok: false, message: "请选择正确的品类范围(全部/特殊)", fieldProp: null }
}
const gs = Number(rule.goodsSource)
if (gt === 2 && (rule.goodsSource === undefined || rule.goodsSource === null
|| Number.isNaN(gs))) {
return { ok: false, message: "请选择商品来源", fieldProp: "goodsSource" }
}
const expenseCategoryRules = rule.expenseCategoryRules
if (!Array.isArray(expenseCategoryRules) || expenseCategoryRules.length === 0) {
return {
ok: false,
message: "请完善流量方、服务方、平台方对账费用及明细",
fieldProp: "flowCostArr.0.calculateMode"
}
}
for (let i = 0; i < expenseCategoryRules.length; i++) {
const item = expenseCategoryRules[i]
const r = getExpenseRowValidationDetail(item, `费用项 ${i + 1}`)
if (r) return { ok: false, message: r.message, fieldProp: r.fieldProp }
if (item.formType === 2 && Array.isArray(item.children)) {
for (let j = 0; j < item.children.length; j++) {
const ch = item.children[j]
if (ch && ch.nodeType === 4) continue
const r2 = getExpenseRowValidationDetail(
ch,
`子类目第 ${j + 1} 行`
)
if (r2) return { ok: false, message: r2.message, fieldProp: r2.fieldProp }
}
}
}
if (gt === 2 && gs === 1) {
const rel = rule.goodsTypeGroupRelations
if (!Array.isArray(rel) || rel.length === 0) {
const cat = rule.categoryType
if (cat == null || cat === "") {
return { ok: false, message: "请选择分账品类", fieldProp: "categoryType" }
}
if (Number(cat) === 1) {
return { ok: false, message: "请选择商品分类", fieldProp: "goodsTypeGroupRelations" }
}
if (Number(cat) === 2) {
return { ok: false, message: "请选择具体商品", fieldProp: "upgradeGoods" }
}
if (Number(cat) === 3) {
return { ok: false, message: "请选择套餐商品", fieldProp: "packageGoods" }
}
return { ok: false, message: "请完善分账品类相关选择", fieldProp: "categoryType" }
}
}
return { ok: true, message: "", fieldProp: null }
}
/**
* @param {object} item
* @param {string} label
* @returns {{ message: string, fieldProp: string }|null}
*/
function getExpenseRowValidationDetail(item, label) {
if (!item || typeof item !== "object") {
return { message: `${label}:行数据异常`, fieldProp: "flowCostArr.0.calculateMode" }
}
if (item.nodeType === 4) return null
if (item.calculateMode === undefined || item.calculateMode === null) {
return { message: `${label}:请选择计算方式`, fieldProp: null }
}
if (
item.expenseCategoryCalculateType === undefined
|| item.expenseCategoryCalculateType === null
) {
return { message: `${label}:请选择对账模式`, fieldProp: null }
}
const v = item.expenseCategoryValue
if (v === null || v === undefined || String(v).trim() === "") {
return { message: `${label}:请填写费用比例或金额`, fieldProp: null }
}
return null
}
/**
* @param {object} rawRule
* @returns {boolean}
*/
export function validateReconciliationRulePayload(rawRule) {
return reconciliationRulePayloadIsSubstantive(rawRule)
}
/**
* 是否已满足单条对账规则可保存条件(与 validateReconciliationRulePayload 同语义;供基线 diff 空壳判断等复用)。
* @param {object} rawRule
* @returns {boolean}
*/
export function reconciliationRulePayloadIsSubstantive(rawRule) {
if (!rawRule || typeof rawRule !== "object") return false
const rule = fillDjGoodsTypeGroupRelations(deepClone(rawRule))
if (!rule || typeof rule !== "object") return false
const gt = Number(rule.groupType)
const gs = Number(rule.goodsSource)
if (gt !== 1 && gt !== 2) return false
const expenseCategoryRules = rule.expenseCategoryRules
if (!validateExpenseCategoryRulesArray(expenseCategoryRules)) return false
if (gt === 2 && gs === 1) {
const rel = rule.goodsTypeGroupRelations
if (!Array.isArray(rel) || rel.length === 0) return false
}
return true
}
import { buildGoodsTypeGroupIncrementalRules } from "@/views/systemConfig/merchant/financialRules/utils/buildGoodsTypeGroupIncrementalRules"
import { GOODS_TYPE_GROUP_RULE_OP } from "@/views/systemConfig/merchant/financialRules/utils/goodsTypeGroupRuleOpType"
describe("buildGoodsTypeGroupIncrementalRules", () => {
test("onlyActiveTab: single index with id yields UPDATE", () => {
const validatedByIndex = {
0: { groupDivisionRuleId: "99", foo: 1 }
}
const out = buildGoodsTypeGroupIncrementalRules(
validatedByIndex,
[0],
true
)
expect(out).toHaveLength(1)
expect(out[0].type).toBe(GOODS_TYPE_GROUP_RULE_OP.UPDATE)
expect(out[0].tabPaneIndex).toBe(0)
})
test("onlyActiveTab: no id yields ADD", () => {
const validatedByIndex = {
1: { foo: 1 }
}
const out = buildGoodsTypeGroupIncrementalRules(
validatedByIndex,
[1],
true
)
expect(out[0].type).toBe(GOODS_TYPE_GROUP_RULE_OP.ADD)
})
test("full submit: multiple indices", () => {
const validatedByIndex = {
0: { groupDivisionRuleId: "a" },
2: {}
}
const out = buildGoodsTypeGroupIncrementalRules(
validatedByIndex,
[0, 2],
false
)
expect(out).toHaveLength(2)
expect(out[0].tabPaneIndex).toBe(0)
expect(out[1].tabPaneIndex).toBe(2)
})
})
/**
* @jest-environment jsdom
*/
import { normalizeRuleGoodsTypesForCategory } from "@/views/systemConfig/merchant/financialRules/utils/normalizeRuleGoodsTypesForCategory"
describe("normalizeRuleGoodsTypesForCategory", () => {
test("categoryType 1: clones goodsTypes and clears upgrade/package slots", () => {
const item = {
goodsTypes: [{ categoryType: 1, goodsType: 10, goodsTypeName: "A" }]
}
const upgradeArr = []
const packageArr = []
normalizeRuleGoodsTypesForCategory(item, upgradeArr, packageArr)
expect(item.categoryType).toBe(1)
expect(item.goodsTypes).toHaveLength(1)
expect(item.goodsTypes[0].goodsType).toBe(10)
expect(item.upgradeGoods).toEqual([])
expect(item.packageGoods).toEqual([])
expect(upgradeArr).toHaveLength(0)
expect(packageArr).toHaveLength(0)
})
test("categoryType 2: moves to upgradeGoods and collects upgradeArr", () => {
const item = {
goodsTypes: [
{
categoryType: 2,
upgradeGoodsId: "u1",
upgradeGoodsName: "U",
commodityCode: "C1"
}
]
}
const upgradeArr = []
const packageArr = []
normalizeRuleGoodsTypesForCategory(item, upgradeArr, packageArr)
expect(item.categoryType).toBe(2)
expect(item.goodsTypes).toEqual([])
expect(item.upgradeGoods).toHaveLength(1)
expect(upgradeArr).toEqual([
{ upgradeGoodsId: "u1", upgradeGoodsName: "U", commodityCode: "C1" }
])
expect(packageArr).toHaveLength(0)
})
test("categoryType 3: moves to packageGoods and collects packageArr", () => {
const item = {
goodsTypes: [
{ categoryType: 3, packageCode: "p1", packageName: "Pkg" }
]
}
const upgradeArr = []
const packageArr = []
normalizeRuleGoodsTypesForCategory(item, upgradeArr, packageArr)
expect(item.categoryType).toBe(3)
expect(item.goodsTypes).toEqual([])
expect(item.packageGoods).toHaveLength(1)
expect(packageArr).toEqual([{ packageCode: "p1", packageName: "Pkg" }])
expect(upgradeArr).toHaveLength(0)
})
test("no goodsTypes: no-op", () => {
const item = {}
normalizeRuleGoodsTypesForCategory(item, [], [])
expect(item).toEqual({})
})
})
/**
* @jest-environment jsdom
*/
import { getEffectivePhantomFullCategoryRuleRaw } from "@/views/systemConfig/merchant/merchantStep/utils/effectivePhantomReconciliationRule"
describe("getEffectivePhantomFullCategoryRuleRaw", () => {
it("prefers live phantom over baseline", () => {
const live = { id: "1", groupType: 1 }
const base = { id: "2", groupType: 2 }
expect(getEffectivePhantomFullCategoryRuleRaw(live, base)).toBe(live)
})
it("falls back to baseline when live is null", () => {
const base = { expenseCategoryRules: [] }
expect(getEffectivePhantomFullCategoryRuleRaw(null, base)).toBe(base)
})
it("returns null when both missing", () => {
expect(getEffectivePhantomFullCategoryRuleRaw(null, null)).toBe(null)
expect(getEffectivePhantomFullCategoryRuleRaw(undefined, undefined)).toBe(
null
)
})
it("ignores non-object live", () => {
const base = { a: 1 }
expect(getEffectivePhantomFullCategoryRuleRaw("x", base)).toBe(base)
})
})
/**
* @jest-environment jsdom
*/
import { normalizeReconciliationRuleForCompare } from "@/views/systemConfig/merchant/merchantStep/utils/normalizeReconciliationRuleForCompare"
import { fillDjGoodsTypeGroupRelations } from "@/views/systemConfig/merchant/merchantStep/utils/reconciliationShared"
import { financialRulePayloadDeepEqual } from "@/views/systemConfig/merchant/financialRules/utils/rulePayloadCanonicalCompare"
describe("normalizeReconciliationRuleForCompare", () => {
test("aligns form snapshot with API baseline: strip merchant, empty categoryType", () => {
const baseline = {
groupType: 1,
goodsSource: 1,
expenseCategoryRules: [
{
targetType: 1,
expenseCategoryId: 902,
expenseCategoryName: "阳光激励费2",
expenseCategoryCalculateType: 3,
expenseCategoryValue: 10,
formType: 1,
calculateMode: 1,
nodeType: 1,
children: []
}
],
upgradeGoods: [],
packageGoods: [],
goodsTypeGroupRelations: [],
id: 26380
}
const formLikeSnapshot = {
groupType: 1,
categoryType: "",
goodsSource: 1,
expenseCategoryRules: [
{
targetType: 1,
expenseCategoryId: 902,
expenseCategoryName: "阳光激励费2",
expenseCategoryCalculateType: 3,
expenseCategoryValue: 10,
merchant: {},
formType: 1,
calculateMode: 1,
nodeType: 1,
children: []
}
],
upgradeGoods: [],
packageGoods: [],
goodsTypeGroupRelations: [],
id: 26380
}
const a = normalizeReconciliationRuleForCompare(
fillDjGoodsTypeGroupRelations({ ...baseline })
)
const b = normalizeReconciliationRuleForCompare(
fillDjGoodsTypeGroupRelations({ ...formLikeSnapshot })
)
expect(financialRulePayloadDeepEqual(a, b)).toBe(true)
})
test("ignores API-only top-level noise keys when comparing to form snapshot", () => {
const baseline = {
groupType: 1,
goodsSource: 1,
id: 26380,
createTime: "2024-01-01",
revision: 1,
expenseCategoryRules: [
{
targetType: 1,
expenseCategoryId: 902,
expenseCategoryValue: 10,
formType: 1,
nodeType: 1
}
]
}
const snapshot = {
groupType: 1,
goodsSource: 1,
id: 26380,
expenseCategoryRules: [
{
targetType: 1,
expenseCategoryId: 902,
expenseCategoryValue: 10,
merchant: {},
formType: 1,
nodeType: 1
}
]
}
const a = normalizeReconciliationRuleForCompare(
fillDjGoodsTypeGroupRelations({ ...baseline })
)
const b = normalizeReconciliationRuleForCompare(
fillDjGoodsTypeGroupRelations({ ...snapshot })
)
expect(financialRulePayloadDeepEqual(a, b)).toBe(true)
})
test("baseline groupDivisionRuleId only vs snapshot id only", () => {
const baseline = {
groupType: 1,
goodsSource: 1,
groupDivisionRuleId: 26380,
expenseCategoryRules: [
{
targetType: 1,
expenseCategoryId: 902,
expenseCategoryValue: 10,
formType: 1,
nodeType: 1
}
]
}
const snapshot = {
groupType: 1,
goodsSource: 1,
id: 26380,
expenseCategoryRules: [
{
targetType: 1,
expenseCategoryId: 902,
expenseCategoryValue: 10,
merchant: {},
formType: 1,
nodeType: 1,
children: []
}
]
}
const a = normalizeReconciliationRuleForCompare(
fillDjGoodsTypeGroupRelations({ ...baseline })
)
const b = normalizeReconciliationRuleForCompare(
fillDjGoodsTypeGroupRelations({ ...snapshot })
)
expect(financialRulePayloadDeepEqual(a, b)).toBe(true)
})
test("expenseCategoryRules different order compares equal when forCompare default", () => {
const rowsA = [
{
targetType: 1,
expenseCategoryId: 902,
expenseCategoryCalculateType: 3,
expenseCategoryValue: 10,
calculateMode: 1,
formType: 1,
nodeType: 1
},
{
targetType: 3,
expenseCategoryId: 900,
expenseCategoryCalculateType: 3,
expenseCategoryValue: 0,
calculateMode: 1,
formType: 1,
nodeType: 1
}
]
const rowsB = [rowsA[1], rowsA[0]]
const baseline = {
groupType: 1,
goodsSource: 1,
id: 1,
expenseCategoryRules: rowsA
}
const snapshot = {
groupType: 1,
goodsSource: 1,
id: 1,
expenseCategoryRules: rowsB
}
const a = normalizeReconciliationRuleForCompare(
fillDjGoodsTypeGroupRelations({ ...baseline })
)
const b = normalizeReconciliationRuleForCompare(
fillDjGoodsTypeGroupRelations({ ...snapshot })
)
expect(financialRulePayloadDeepEqual(a, b)).toBe(true)
expect(a.expenseCategoryRules[0].expenseCategoryId).toBe(902)
expect(a.expenseCategoryRules[1].expenseCategoryId).toBe(900)
})
test("forCompare false preserves expense row order", () => {
const rowsB = [
{
targetType: 3,
expenseCategoryId: 900,
formType: 1,
nodeType: 1
},
{
targetType: 1,
expenseCategoryId: 902,
formType: 1,
nodeType: 1
}
]
const out = normalizeReconciliationRuleForCompare(
fillDjGoodsTypeGroupRelations({
groupType: 1,
goodsSource: 1,
expenseCategoryRules: rowsB
}),
{ forCompare: false }
)
expect(out.expenseCategoryRules[0].expenseCategoryId).toBe(900)
expect(out.expenseCategoryRules[1].expenseCategoryId).toBe(902)
})
test("strips merchant from nested children for compare", () => {
const baseline = {
groupType: 2,
goodsSource: 1,
categoryType: 1,
expenseCategoryRules: [
{
formType: 2,
nodeType: 1,
children: [
{ expenseCategoryValue: 1, targetType: 1, nodeType: 1 }
]
}
],
goodsTypeGroupRelations: [{ categoryType: 1, goodsType: 1 }]
}
const snapshot = JSON.parse(JSON.stringify(baseline))
snapshot.expenseCategoryRules[0].children[0].merchant = {}
const a = normalizeReconciliationRuleForCompare(
fillDjGoodsTypeGroupRelations({ ...baseline })
)
const b = normalizeReconciliationRuleForCompare(
fillDjGoodsTypeGroupRelations({ ...snapshot })
)
expect(financialRulePayloadDeepEqual(a, b)).toBe(true)
})
})
/**
* @jest-environment jsdom
*/
import {
getReconciliationRuleValidationResult,
reconciliationRulePayloadIsSubstantive
} from "@/views/systemConfig/merchant/merchantStep/utils/validateReconciliationRulePayload"
import { normalizeReconciliationRuleForCompare } from "@/views/systemConfig/merchant/merchantStep/utils/normalizeReconciliationRuleForCompare"
import { financialRulePayloadDeepEqual } from "@/views/systemConfig/merchant/financialRules/utils/rulePayloadCanonicalCompare"
import { fillDjGoodsTypeGroupRelations } from "@/views/systemConfig/merchant/merchantStep/utils/reconciliationShared"
import { deepClone } from "@/common/util"
const minimalSubstantiveRule = {
groupType: 1,
goodsSource: 1,
expenseCategoryRules: [
{
targetType: 1,
expenseCategoryId: 1,
expenseCategoryName: "A",
expenseCategoryCalculateType: 3,
expenseCategoryValue: 10,
formType: 1,
calculateMode: 1,
nodeType: 1
}
],
goodsTypeGroupRelations: []
}
describe("getReconciliationRuleValidationResult", () => {
test("ok for same minimal rule as isSubstantive", () => {
const r = getReconciliationRuleValidationResult(minimalSubstantiveRule)
expect(r.ok).toBe(true)
})
test("empty object is not ok", () => {
const r = getReconciliationRuleValidationResult({})
expect(r.ok).toBe(false)
})
test("groupType 2 without goodsSource fails with prop goodsSource", () => {
const r = getReconciliationRuleValidationResult({
groupType: 2,
expenseCategoryRules: deepClone(minimalSubstantiveRule.expenseCategoryRules)
})
expect(r.ok).toBe(false)
expect(r.fieldProp).toBe("goodsSource")
})
test("groupType 1 can omit goodsSource when expense is valid", () => {
const { goodsSource, ...noGs } = minimalSubstantiveRule
const r = getReconciliationRuleValidationResult(noGs)
expect(r.ok).toBe(true)
})
})
describe("reconciliationRulePayloadIsSubstantive", () => {
test("empty or non-rule object is not substantive", () => {
expect(reconciliationRulePayloadIsSubstantive({})).toBe(false)
expect(reconciliationRulePayloadIsSubstantive(null)).toBe(false)
})
test("valid minimal all-category rule is substantive", () => {
expect(reconciliationRulePayloadIsSubstantive(minimalSubstantiveRule)).toBe(
true
)
})
})
/**
* 与 merchantCheck.reconciliationTabDiffersFromBaseline 在「无基线槽位 / 无 phantom」时一致:仅当可保存才视为相对「无基线」有差异。
*/
describe("reconciliation no-baseline empty shell", () => {
function differsWhenNoPrevRaw(cur) {
if (!cur) return false
return reconciliationRulePayloadIsSubstantive(cur)
}
test("new slot {} does not count as diff vs missing baseline", () => {
const cur = fillDjGoodsTypeGroupRelations(deepClone({}))
expect(differsWhenNoPrevRaw(cur)).toBe(false)
})
test("substantive cur counts as diff vs missing baseline", () => {
expect(
differsWhenNoPrevRaw(
fillDjGoodsTypeGroupRelations(deepClone(minimalSubstantiveRule))
)
).toBe(true)
})
})
describe("reconciliation same baseline and current (normalized)", () => {
test("identical after normalize and deepEqual", () => {
const baseline = {
groupType: 1,
goodsSource: 1,
expenseCategoryRules: [deepClone(minimalSubstantiveRule.expenseCategoryRules[0])],
goodsTypeGroupRelations: []
}
const cur = { ...deepClone(baseline) }
const prevNorm = normalizeReconciliationRuleForCompare(
fillDjGoodsTypeGroupRelations(deepClone(baseline))
)
const curNorm = normalizeReconciliationRuleForCompare(
fillDjGoodsTypeGroupRelations(deepClone(cur))
)
expect(financialRulePayloadDeepEqual(curNorm, prevNorm)).toBe(true)
})
})
/**
* @jest-environment jsdom
*/
import { shouldIncludeReconciliationTabForProcess } from "@/views/systemConfig/merchant/merchantStep/utils/reconciliationSubmitTabGate"
describe("shouldIncludeReconciliationTabForProcess", () => {
test("无基线槽位:不要求 touched,用于新增可提交/无 prev 对齐场景", () => {
expect(
shouldIncludeReconciliationTabForProcess({
hasBaselineSlot: false,
classificationUserTouched: false,
sessionAdded: false
})
).toBe(true)
})
test("有基线槽位且无 touched/sessionAdded:不进入待校验(挡无操作假脏)", () => {
expect(
shouldIncludeReconciliationTabForProcess({
hasBaselineSlot: true,
classificationUserTouched: false,
sessionAdded: false
})
).toBe(false)
})
test("有基线槽位且 touched:可进入", () => {
expect(
shouldIncludeReconciliationTabForProcess({
hasBaselineSlot: true,
classificationUserTouched: true,
sessionAdded: false
})
).toBe(true)
})
test("有基线槽位且 sessionAdded:可进入", () => {
expect(
shouldIncludeReconciliationTabForProcess({
hasBaselineSlot: true,
classificationUserTouched: false,
sessionAdded: true
})
).toBe(true)
})
})
import { uniquePackageByPackageCode } from "@/views/systemConfig/merchant/merchantStep/utils/groundingUpgradeList"
describe("uniquePackageByPackageCode", () => {
test("dedupes by packageCode preserving first occurrence order", () => {
const input = [
{ packageCode: "a", packageName: "A1" },
{ packageCode: "b", packageName: "B" },
{ packageCode: "a", packageName: "A2" }
]
const out = uniquePackageByPackageCode(input)
expect(out).toHaveLength(2)
expect(out[0].packageName).toBe("A1")
expect(out.map((x) => x.packageCode)).toEqual(["a", "b"])
})
test("treats undefined input as empty", () => {
expect(uniquePackageByPackageCode(undefined)).toEqual([])
})
})
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!