Commit a87ffc0d by 张立顺

feat 分账对账功能改造

1 parent 84a142b3
Showing 33 changed files with 3666 additions and 924 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 {
* @param {Object} state state
*/
source(state) {
console.log(state)
// console.log(state)
return state.source
},
/**
......
<!-- 商品管理 -->
<template>
<d2-container class="product-manage">
<template #header>
<div class="header">
<d2-search class="show-search"
:form-data="showFormData"
label-width="100px"
:search-form="searchForm">
<template #goodsCascader>
<el-cascader v-model="tempGoodsType"
filterable
:options="baseData.productTypeList"
placeholder="请选择"
:props="{ checkStrictly: true, label: 'categoryName', value: 'categoryType' }"
style="width: 100%;"
@change="selectAddAttr($event)">
</el-cascader>
</template>
</d2-search>
<div class="up-btns">
<el-button :id="tableParams.btnId"
size="small"
type="primary">
查询
</el-button>
<el-button size="small" @click="handleReset">
重置
</el-button>
</div>
</div>
</template>
<div class="d2-container-content">
<d2-table-header>
<template #left>
<!-- <span> -->
<!-- 新增产品 -->
<!-- <span style="display: inline-block;margin-right: 10px;"> -->
<auth-button category="Button" :show-btn-ids="['9030701', '9030707', '9030709']" />
<!-- </span> -->
<!-- 批量导入 -->
<!-- <auth-button category="Button"
<d2-container class="product-manage">
<template #header>
<div class="header">
<d2-search class="show-search" :form-data="showFormData" label-width="100px" :search-form="searchForm">
<template #goodsCascader>
<el-cascader v-model="tempGoodsType" filterable :options="baseData.productTypeList" placeholder="请选择"
:props="{ checkStrictly: true, label: 'categoryName', value: 'categoryType' }" style="width: 100%;"
@change="selectAddAttr($event)">
</el-cascader>
</template>
</d2-search>
<div class="up-btns">
<el-button :id="tableParams.btnId" size="small" type="primary">
查询
</el-button>
<el-button size="small" @click="handleReset">
重置
</el-button>
</div>
</div>
</template>
<div class="d2-container-content">
<d2-table-header>
<template #left>
<!-- <span> -->
<!-- 新增产品 -->
<!-- <span style="display: inline-block;margin-right: 10px;"> -->
<auth-button category="Button" :show-btn-ids="['9030701', '9030707', '9030709']" />
<!-- </span> -->
<!-- 批量导入 -->
<!-- <auth-button category="Button"
:show-btn-ids="['9030707']"
style="display: inline-block;" /> -->
<!-- </span> -->
</template>
<!-- 导出 -->
<auth-button category="Button"
:show-btn-ids="['9030702']"
style="display: inline-block" />
</d2-table-header>
<d2-table ref="productManageTable"
:before-search-fn="beforeSearchFn"
:filter-list-data-fn="filterProductManageListData"
:get-list-api="getListApi"
:has-num="false"
:search-form="searchForm"
:table-params="tableParams"
@setTableFinishFun="setTableFinishFun">
<template #img="scope">
<div class="material">
<img class="pro-img" :src="(scope.scope.goodsInfo && scope.scope.goodsInfo.thumbUrl) || ''">
<span class="good_name">{{ (scope.scope.goodsInfo && scope.scope.goodsInfo.goodsName) || '-' }}</span>
</div>
</template>
<template #auth-button="scope">
<div>
<span style="margin-right: 10px;">
<auth-button :data="getAuthButtonData(scope.scope)" :show-btn-ids="['9030708']" />
</span>
<span style="margin-right: 10px;">
<auth-button :data="getAuthButtonData(scope.scope)" :show-btn-ids="['9030703']" />
</span>
<auth-button :data="getAuthButtonData(scope.scope)"
:show-btn-ids="['9030706']" />
</div>
</template>
</d2-table>
</div>
<!-- 查看面板 SPU -->
<DrawerDetail v-if="drawerDetailVisible"
:commodity-info-id="commodityDetailInfoId"
:drawer-detail-visible="drawerDetailVisible"
:position-type-list="positionTypeList"
@handleDrawerClose="handleDrawerClose" />
<!-- 查看面板 SKU(分页) -->
<DrawerSkuDetail v-if="drawerSkuDetailVisible"
:commodity-info-id="commodityDetailInfoId"
:commodity-info-sku-id="commodityDetailInfoSkuId"
:drawer-detail-visible="drawerSkuDetailVisible"
:position-type-list="positionTypeList"
@handleDrawerClose="handleSkuDrawerClose" />
<!-- 轻改SKU批量导入 -->
<d2-file-import-dialog :is-visible="fileVisible"
template-name="轻改模版下载"
title="批量导入轻改SKU"
@closeDialog="handleBatchImport"
@confirmDialog="handleConfirmImport"
@downloadTemplate="exportTemplate('qinggai')" />
<!-- 延保SKU批量导入 -->
<d2-file-import-dialog :is-visible="fileVisibleExtension"
template-name="延保模版下载"
title="批量导入延保SKU"
@closeDialog="handleBatchImportExtension"
@confirmDialog="handleConfirmImportExtension"
@downloadTemplate="exportTemplate('yanbao')" />
</d2-container>
<!-- </span> -->
</template>
<!-- 导出 -->
<auth-button category="Button" :show-btn-ids="['9030702']" style="display: inline-block" />
</d2-table-header>
<d2-table ref="productManageTable" :before-search-fn="beforeSearchFn"
:filter-list-data-fn="filterProductManageListData" :get-list-api="getListApi" :has-num="false"
:search-form="searchForm" :table-params="tableParams" @setTableFinishFun="setTableFinishFun">
<template #img="scope">
<div class="material">
<img class="pro-img" :src="(scope.scope.goodsInfo && scope.scope.goodsInfo.thumbUrl) || ''">
<span class="good_name">{{ (scope.scope.goodsInfo && scope.scope.goodsInfo.goodsName) || '-' }}</span>
</div>
</template>
<template #auth-button="scope">
<div>
<span style="margin-right: 10px;">
<auth-button :data="getAuthButtonData(scope.scope)" :show-btn-ids="['9030708']" />
</span>
<span style="margin-right: 10px;">
<auth-button :data="getAuthButtonData(scope.scope)" :show-btn-ids="['9030703']" />
</span>
<auth-button :data="getAuthButtonData(scope.scope)" :show-btn-ids="['9030706']" />
</div>
</template>
</d2-table>
</div>
<!-- 查看面板 SPU -->
<DrawerDetail v-if="drawerDetailVisible" :commodity-info-id="commodityDetailInfoId"
:drawer-detail-visible="drawerDetailVisible" :position-type-list="positionTypeList"
@handleDrawerClose="handleDrawerClose" />
<!-- 查看面板 SKU(分页) -->
<DrawerSkuDetail v-if="drawerSkuDetailVisible" :commodity-info-id="commodityDetailInfoId"
:commodity-info-sku-id="commodityDetailInfoSkuId" :drawer-detail-visible="drawerSkuDetailVisible"
:position-type-list="positionTypeList" @handleDrawerClose="handleSkuDrawerClose" />
<!-- 轻改SKU批量导入 -->
<d2-file-import-dialog :is-visible="fileVisible" template-name="轻改模版下载" title="批量导入轻改SKU"
@closeDialog="handleBatchImport" @confirmDialog="handleConfirmImport"
@downloadTemplate="exportTemplate('qinggai')" />
<!-- 延保SKU批量导入 -->
<d2-file-import-dialog :is-visible="fileVisibleExtension" template-name="延保模版下载" title="批量导入延保SKU"
@closeDialog="handleBatchImportExtension" @confirmDialog="handleConfirmImportExtension"
@downloadTemplate="exportTemplate('yanbao')" />
</d2-container>
</template>
<script>
......@@ -466,7 +438,7 @@ export default {
item.addAllOption !== false
&& this.baseData[item.optionsName].length
&& this.baseData[item.optionsName][0][
this.showFormData[index].optionLabel
this.showFormData[index].optionLabel
] !== "全部"
) {
const temp = {};
......@@ -497,18 +469,19 @@ export default {
},
// 商品管理列表数据转换:N-父级+子级;Y-直接返回 SKU 平铺,均需处理规格、价格等展示数据
filterProductManageListData(listData) {
console.log(listData, "listData");
if (!listData || !Array.isArray(listData))
return listData;
const isSkuMode = this.searchForm.showSkuMode === "Y";
// 新 SPU 接口不返回 upgradeGoodsList,标记为 SPU 平铺模式
this.spuOnlyMode = !listData.some(item => item.upgradeGoodsList && item.upgradeGoodsList.length);
const baseGoodsIdCount = {};
if (isSkuMode) {
listData.forEach((item) => {
const bid = item.baseGoodsId || item.id;
baseGoodsIdCount[bid] = (baseGoodsIdCount[bid] || 0) + 1;
});
}
// if (isSkuMode) {
// listData.forEach((item) => {
// const bid = item.baseGoodsId || item.id;
// baseGoodsIdCount[bid] = (baseGoodsIdCount[bid] || 0) + 1;
// });
// }
listData.forEach((val) => {
if (!val.goodsInfo)
val.goodsInfo = {};
......@@ -568,6 +541,7 @@ export default {
this._setSpuOnlyDefaults(val);
}
});
console.log(listData, "listData");
return listData;
},
// 从多个来源取第一个有效值
......@@ -809,7 +783,7 @@ export default {
confirmButtonText: "确定",
showCancelButton: false,
type: "warning",
}).then(() => {});
}).then(() => { });
return;
}
console.log(row);
......
<template>
<el-row class="description-wrapper">
<template v-for="item in schema">
<el-col v-if="!isHideSchemaItem(item)"
:key="item._key"
:span="item.col || 12">
<slot :name="item.slot || item.name ">
<div class="form-item" :style="item.itemStyle || {}">
<span class="label" :style="{ width: item.labelWidth || '150px' }">
<slot :name="`${item.slot || item.name}-label`">
{{ item.label }}{{ item.hideColon ? "" : ":" }}
</slot>
</span>
<span class="value">
<div class="text-hide" :style="{ width: item.valueWidth || '100%' }">
<template v-if="item.render">
<RenderProxy :render="item.render"
:row="{ data, schemaItem: item, schema }" />
</template>
<template v-else>
<template v-if="item.tooltip && (getValue(item.descKey || item.name))">
<el-tooltip :content="isZeroOrNumber(getValue(item.descKey || item.name)) " v-bind="item.tooltipProps">
<div class="text-hide">
{{ isZeroOrNumber(getValue(item.descKey || item.name)) }}
</div>
</el-tooltip>
</template>
<template v-else>
<slot :name="`${item.slot || item.name}-value`">
{{ isZeroOrNumber(getValue(item.descKey || item.name)) }}
</slot>
</template>
</template>
</div>
</span>
</div>
</slot>
</el-col>
</template>
<el-row class="description-wrapper">
<template v-for="item in schema">
<el-col v-if="!isHideSchemaItem(item)" :key="item._key" :span="item.col || 12">
<slot :name="item.slot || item.name">
<div class="form-item" :style="item.itemStyle || {}">
<span class="label" :style="{ width: item.labelWidth || '150px' }">
<slot :name="`${item.slot || item.name}-label`">
{{ item.label }}{{ item.hideColon ? "" : ":" }}
</slot>
</span>
<span class="value">
<div class="text-hide" :style="{ width: item.valueWidth || '100%' }">
<template v-if="item.render">
<RenderProxy :render="item.render" :row="{ data, schemaItem: item, schema }" />
</template>
<template v-else>
<template v-if="item.tooltip && (getValue(item.descKey || item.name))">
<el-tooltip :content="isZeroOrNumber(getValue(item.descKey || item.name))"
v-bind="item.tooltipProps">
<div class="text-hide">
{{ isZeroOrNumber(getValue(item.descKey || item.name)) }}
</div>
</el-tooltip>
</template>
<template v-else>
<slot :name="`${item.slot || item.name}-value`">
{{ isZeroOrNumber(getValue(item.descKey || item.name)) }}
</slot>
</template>
</template>
</div>
</span>
</div>
</slot>
</el-col>
</template>
</el-row>
</el-row>
</template>
<script>
......@@ -103,6 +101,7 @@ export default {
<style scoped lang="scss">
.description-wrapper {
font-size: 14px;
.form-item {
display: flex;
flex-direction: row;
......@@ -110,13 +109,14 @@ export default {
line-height: 32px;
margin-bottom: 20px;
> .label {
>.label {
text-align: right;
color: #666666;
font-size: 14px;
flex-shrink: 0;
}
> .value {
>.value {
flex-shrink: 0;
flex: 1;
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>
......@@ -123,21 +123,10 @@
</span>
</p>
<div v-if="editableTabs.length" class="classificationCptContainer">
<classificationCpt ref="classificationActive" :key="editableTabsValue" :goods-list="goodsTypeGroupRelations"
:goods-type-group-rules="financialObj['goodsTypeGroupRules'][activeDivisionTabIndex]"
:goods-select-list="goodsSelectList" :financial-ledger-party="financialLedgerParty"
:pane-index="activeDivisionTabIndex" :tab-item="editableTabs[activeDivisionTabIndex]"
:service-merchant-list="serviceMerchantList" :router-info="routerInfo"
:classification-obj-select="classificationObj" @rulesTest="rulesTest"
@assignGoodsTypeList="assignGoodsTypeList" @deleteGoodsTypeItem="deleteGoodsTypeItem"
@checkSuccess="checkSuccess(activeDivisionTabIndex)" :upgrade-goods-list="upgradeGoodsList"
:package-goods-list="packageGoodsList" @assignPackageGoodsList="assignPackageGoodsList"
:select-package-goods-list="selectPackageGoodsList" @deletePackageGoodsItem="deletePackageGoodsItem"
@deleteUpgradeGoodsItem="deleteUpgradeGoodsItem" @assignUpgradeGoodsList="assignUpgradeGoodsList"
:select-upgrade-goods-list="selectUpgradeGoodsList"
@deleteSelectUpgradeGoodsList="deleteSelectUpgradeGoodsList"
@deleteSelectPackageGoodsList="deleteSelectPackageGoodsList"
@deleteSelectGoodsTypeList="deleteSelectGoodsTypeList" />
<classificationCpt ref="classificationActive" :key="editableTabsValue"
:page-context="classificationPageContext" :selection-context="classificationSelectionContext"
:pane-context="classificationPaneContext" @classification-change="handleClassificationChange"
@checkSuccess="checkSuccess(activeDivisionTabIndex)" />
</div>
<div class="footer">
<el-button @click="submit" type="primary">保存</el-button>
......@@ -154,7 +143,7 @@
</template>
<script>
import { mapActions, mapGetters, mapMutations } from "vuex"
import { mapGetters } from "vuex"
import {
sceneList,
userType,
......@@ -186,9 +175,20 @@ import {
} from "@api/grounding"
import {
fillDjGoodsTypeGroupRelations,
filterDivisionTabPanes,
rebuildFinancialCrossTabGoodsSelections
} from "../merchantStep/utils/reconciliationShared"
import {
buildGoodsTypeGroupIncrementalRules,
mergeChildClassificationPayload
} from "./utils/classificationRuleCache"
import {
distributionRulesLookComplete,
prepareRuleForValidation,
validateGoodsTypeGroupRulePayload
} from "./utils/validateGoodsTypeGroupRulePayload"
import { financialRulePayloadDeepEqual } from "./utils/rulePayloadCanonicalCompare"
import { normalizeRuleGoodsTypesForCategory } from "./utils/normalizeRuleGoodsTypesForCategory"
import { CLASSIFICATION_EMIT } from "./utils/classificationEmitTypes"
export default {
name: "FinancialRules",
// isNeedVuex: true,
......@@ -270,7 +270,26 @@ export default {
djzhySubMerchantId: "",
djzhySubMerchantName: ""
},
effectStartDate: false // 规则时间 true 表示可以立即生效 是否立即生效
effectStartDate: false, // 规则时间 true 表示可以立即生效 是否立即生效
/** 会话内删除的已落库分账品类规则 id,随 save 一并提交给后端 */
pendingDeletedGroupDivisionRuleIds: [],
/** 费用类目冲突检测用:与 editableTabs 下标对齐的全量规则视图 */
_fullMergedGoodsTypeGroupRulesForConflict: null,
/**
* 删除「会话新增」Tab 后切回上一 Tab 时,classificationCpt 重挂载瞬间 getClassificationParams 可能与缓存不一致且暂不达纯数据校验;
* 下一次校验该下标时优先按缓存(一次性,与 resolveRulePayloadForTabValidation 配合)。
*/
_preferCachedMergeOnceForTabIndex: null,
/** provide/inject:子组件读取 routerInfo、scene(与 computed routerInfo 同步) */
financialRulesEnv: {
routerInfo: {},
scene: undefined
}
}
},
provide() {
return {
financialRulesEnv: this.financialRulesEnv
}
},
computed: {
......@@ -323,7 +342,8 @@ export default {
/**
* 当前激活 tab 在 editableTabs 中的下标。
* 供单实例 classificationCpt 绑定 pane-index / goodsTypeGroupRules 使用。
* 找不到时兜底返回 0,防止初始化时 editableTabsValue 尚未同步。
* 找不到时兜底返回 0(多为初始化瞬间);新增/删 Tab 后 name 重排时若仍出现 -1,
* 应依赖 ensureDivisionTabSelectionValid 校正 editableTabsValue,勿长期依赖本兜底以免绑错槽位。
*/
activeDivisionTabIndex() {
const i = this.editableTabs.findIndex(
......@@ -343,9 +363,44 @@ export default {
merchantDisplayName() {
const n = this.routerInfo.merchantName
return n != null && String(n).trim() !== "" ? n : "—"
},
/** 见 utils/financialRulesContext.js(FinancialRulesPageContext,不含 routerInfo,由 provide 注入) */
classificationPageContext() {
return {
financialLedgerParty: this.financialLedgerParty,
serviceMerchantList: this.serviceMerchantList
}
},
classificationSelectionContext() {
return {
goodsList: this.goodsTypeGroupRelations,
goodsSelectList: this.goodsSelectList,
upgradeGoodsList: this.upgradeGoodsList,
packageGoodsList: this.packageGoodsList,
selectUpgradeGoodsList: this.selectUpgradeGoodsList,
selectPackageGoodsList: this.selectPackageGoodsList
}
},
classificationPaneContext() {
const idx = this.activeDivisionTabIndex
const rules = this.financialObj.goodsTypeGroupRules
return {
goodsTypeGroupRules: (rules && rules[idx]) ? rules[idx] : {},
paneIndex: idx,
tabItem: this.editableTabs[idx] || {},
classificationObjSelect: this.classificationObj
}
}
},
watch: {
routerInfo: {
immediate: true,
handler(v) {
this.financialRulesEnv.routerInfo = v && typeof v === "object" ? v : {}
const sc = v && v.scene
this.financialRulesEnv.scene = sc != null && sc !== "" ? sc : undefined
}
},
"financialObj.realityShopMerchantId": {
handler(val) {
// this.financialObj.realityShopMerchantId
......@@ -464,10 +519,79 @@ export default {
* 直接用缓存 deepClone 提交,避免千级 Tab 下反复切 Tab + Element 整表 validate。
* - 成功跑完一次「慢路径」handleConfirm 后,会 syncTabConfirmedRuleRevisionByIndex 把
* confirmed 对齐到当前 ruleCacheRevision,表示「当前缓存内容与最后一次校验通过结果一致」。
* - 若本次持久化写入的 next 与内存中已有缓存完全一致(JSON 相等),则既不做 $set 也不
* bump,避免用户仅切换 Tab、未改表单却 invalidate 快路径。
* - 若本次持久化写入的 next 与内存中已有缓存实质一致(对双方先 fillDj 再 financialRulePayloadDeepEqual),
* 则既不做 $set 也不 bump,避免仅切换 Tab、表单与缓存形态差异却 invalidate 快路径。
* - 大对象 JSON.stringify 有开销;若后续 profiling 瓶颈在此,可换成哈希或字段级 dirty。
*/
/**
* 将子组件 getClassificationParams() 与 goodsTypeGroupRules[idx] 合并为待写入对象,供 persist 与「是否需 persist」判断共用。
* @returns {{ next: object, prevStored: object|undefined } | null} 无 ref 或抛错时返回 null(与旧 persist 行为一致:不写缓存)
*/
buildMergedClassificationPayloadAtIndex(idx) {
if (idx == null || idx < 0 || idx >= this.editableTabs.length) return null
const node = this.getClassificationRef(this.editableTabs[idx].name)
if (!node || typeof node.getClassificationParams !== "function") return null
try {
const payload = node.getClassificationParams()
const prevStored = this.financialObj.goodsTypeGroupRules?.[idx]
return mergeChildClassificationPayload(payload, prevStored)
} catch (e) {
console.warn("buildMergedClassificationPayloadAtIndex", e)
return null
}
},
/** 合并结果与缓存经 fillDj + financialRulePayloadDeepEqual 后是否一致(与 persist 内 early-return 条件一致)。 */
classificationMergedAtIndexEqualsCache(idx) {
const built = this.buildMergedClassificationPayloadAtIndex(idx)
if (!built) return true
const { next, prevStored } = built
if (prevStored == null || typeof prevStored !== "object") return false
const nextNorm = fillDjGoodsTypeGroupRelations(deepClone(next))
const prevNorm = fillDjGoodsTypeGroupRelations(deepClone(prevStored))
return financialRulePayloadDeepEqual(nextNorm, prevNorm)
},
/**
* 纯数据校验用:若子组件可合并且与缓存实质不一致,必须校验合并结果 next(用户编辑为中间态非法时 persist 可能拒绝写入,缓存仍旧)。
* 无 ref 或与缓存一致时退回 financialObj 缓存。
*/
resolveRulePayloadForTabValidation(tabindex) {
const cached = this.financialObj.goodsTypeGroupRules[tabindex] || {}
const built = this.buildMergedClassificationPayloadAtIndex(tabindex)
if (!built) return cached
const { next, prevStored } = built
if (prevStored == null || typeof prevStored !== "object") {
return next
}
const nextNorm = fillDjGoodsTypeGroupRelations(deepClone(next))
const prevNorm = fillDjGoodsTypeGroupRelations(deepClone(prevStored))
if (financialRulePayloadDeepEqual(nextNorm, prevNorm)) {
return cached
}
const prevValid = validateGoodsTypeGroupRulePayload(prevStored)
const nextValid = validateGoodsTypeGroupRulePayload(next)
if (
prevValid
&& !nextValid
&& this._preferCachedMergeOnceForTabIndex != null
&& this._preferCachedMergeOnceForTabIndex === tabindex
) {
this._preferCachedMergeOnceForTabIndex = null
return cached
}
return next
},
/**
* 提交 / 测算 / 删 Tab 前是否需执行 persistActiveClassificationTab。
* 冷加载未改任何数据时若仍无条件 persist,getClassificationParams 与缓存可能微差导致误 bump,首条 Tab 被标脏并误报「请完善分账规则」。
* 有待删 id 或当前激活 Tab 合并后与缓存不一致时才 persist。
*/
shouldPersistActiveClassificationTabBeforeSubmit() {
if ((this.pendingDeletedGroupDivisionRuleIds || []).length > 0) return true
const idx = this.activeDivisionTabIndex
if (idx == null || idx < 0) return false
return !this.classificationMergedAtIndexEqualsCache(idx)
},
persistClassificationTabByPaneName(paneName) {
if (paneName == null || paneName === "") return
const idx = this.editableTabs.findIndex(
......@@ -475,54 +599,29 @@ export default {
)
if (idx < 0) return
const node = this.getClassificationRef(this.editableTabs[idx].name)
if (!node || typeof node.getClassificationParams !== "function") return
const built = this.buildMergedClassificationPayloadAtIndex(idx)
if (!built) return
try {
const payload = node.getClassificationParams()
const prev = this.financialObj.goodsTypeGroupRules?.[idx] || {}
const base = deepClone(prev)
const next = { ...base, ...payload }
// getClassificationParams 异常或漏字段时勿用 undefined 盖掉缓存里的类目/分账表
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
const { next, prevStored } = built
const tab = this.editableTabs[idx]
const userTouched = tab && tab.classificationUserTouched === true
// 无实质变更则不调 $set / bump:见上方 JSDoc「提交性能优化 · 缓存 revision」
if (prevStored != null && typeof prevStored === "object") {
const nextNorm = fillDjGoodsTypeGroupRelations(deepClone(next))
const prevNorm = fillDjGoodsTypeGroupRelations(deepClone(prevStored))
if (financialRulePayloadDeepEqual(nextNorm, prevNorm)) {
return
}
// 无实质变更则不调 $set / bump:见上方 JSDoc「提交性能优化 · 缓存 revision」
const prevStored = this.financialObj.goodsTypeGroupRules?.[idx]
if (
prevStored != null &&
typeof prevStored === "object" &&
JSON.stringify(next) === JSON.stringify(prevStored)
) {
// 缓存已通过纯数据校验,合并结果未通过:多为子组件未回显完成或形态差异,勿用劣化快照覆盖接口数据、勿 bump
const prevValid = validateGoodsTypeGroupRulePayload(prevStored)
const nextValid = validateGoodsTypeGroupRulePayload(next)
// 用户已在本 Tab 动过表:切换品类时必须把当前表单写入缓存,否则切回 initList 仍读旧缓存,表现为「改过的没保存」
if (prevValid && !nextValid && !userTouched) {
return
}
this.$set(this.financialObj.goodsTypeGroupRules, idx, next)
this.bumpTabRuleCacheRevisionByIndex(idx)
} catch (e) {
console.warn("persistClassificationTabByPaneName", e)
}
this.$set(this.financialObj.goodsTypeGroupRules, idx, next)
this.bumpTabRuleCacheRevisionByIndex(idx)
},
/** 持久化当前激活 tab,提交 / 删除 tab 前调用,确保最新状态写入缓存。 */
persistActiveClassificationTab() {
......@@ -562,25 +661,6 @@ export default {
return false
},
/**
* 缓存快路径专用:分账表须非空且每行带有效 merchantId(含 -1 等合法值),否则须走慢路径做 Element 校验。
*/
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)
},
/**
* 判断是否允许 getGoodsTypeGroupRules 走「缓存快路径」(不切 Tab、不调 handleConfirm)。
*
* 背景:虚拟 Tab 下一旦 editableTabsValue 切换到某页,子组件必挂载,原 else 分支里
......@@ -593,7 +673,7 @@ export default {
if (!Array.isArray(rule.merchantDistributionRules)) return false
if (!Array.isArray(rule.owningMerchantDistributionRules)) return false
if (!this.hasEchoedGoodsTypeGroupRulePayload(rule)) return false
return this.distributionRulesLookComplete(rule)
return distributionRulesLookComplete(rule)
},
/** 为 Tab 补上 revision 字段(getFinancialObj / addTab / removeTab 已初始化为 0,此处兜底)。 */
ensureTabRevisionFields(tab) {
......@@ -624,8 +704,56 @@ export default {
this.ensureTabRevisionFields(tab)
this.$set(tab, "confirmedRuleCacheRevision", tab.ruleCacheRevision || 0)
},
...mapActions("FinancialRules", ["reset"]),
...mapMutations("FinancialRules", ["toggle", "set4sService"]),
/**
* 与 editableTabs 下标对齐的全量规则视图(冲突检测用):已校验槽位用快照,其余用缓存 + fillDj。
*/
buildFullMergedGoodsTypeGroupRules(validatedByIndex) {
const n = this.editableTabs.length
const out = []
const map = validatedByIndex || {}
for (let i = 0; i < n; i++) {
if (map[i]) {
out.push(map[i])
} else {
const cached = this.financialObj.goodsTypeGroupRules[i]
out.push(fillDjGoodsTypeGroupRelations(deepClone(cached || {})))
}
}
return out
},
/**
* 纯数据校验失败后切到对应品类并走 el-form 标红(仅该 Tab)。
*/
async focusTabAndRunHandleConfirm(paneName) {
if (paneName == null || paneName === "" || String(paneName) === "add") {
return
}
const cur = this.editableTabsValue
if (
cur != null
&& String(cur) !== ""
&& String(cur) !== "add"
&& String(cur) !== String(paneName)
) {
this.persistClassificationTabByPaneName(cur)
await this.$nextTick()
}
this.editableTabsValue = paneName
const MAX_WAIT = 24
let node = null
for (let attempt = 0; attempt < MAX_WAIT; attempt++) {
await this.$nextTick()
node = this.getClassificationRef(paneName)
if (node) break
}
if (node && typeof node.handleConfirm === "function") {
// scheduleInitList → initList 在子组件挂载后的下一拍执行;initList 的 finally 再下一拍 clearValidate。
// 若立即 validate,要么表单项未注册无法标红,要么标红被随后的 clearValidate 清掉。
await this.$nextTick()
await this.$nextTick()
await node.handleConfirm()
}
},
initPaymentChannelList() {
paymentChannelList().then((res) => {
// console.log(res, "paymentChannelList")
......@@ -868,52 +996,12 @@ export default {
this.isDivisionTestTabWarningFromApiRuleItem(item),
// 提交优化:与 getGoodsTypeGroupRules 快路径 / persist bump 配合,详见 getGoodsTypeGroupRules JSDoc
ruleCacheRevision: 0,
confirmedRuleCacheRevision: 0
}
// 按商品分类
if (
item.goodsTypes?.length &&
item.goodsTypes[0]?.categoryType == 1
) {
item.goodsTypes = deepClone(item.goodsTypes)
item.categoryType = 1
item.upgradeGoods = [] // 与具体商品互不干扰
item.packageGoods = []
}
// 按具体商品
if (
item.goodsTypes?.length &&
item.goodsTypes[0]?.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 = []
}
// 按套餐商品
if (
item.goodsTypes?.length &&
item.goodsTypes[0]?.categoryType == 3
) {
item.packageGoods = deepClone(item.goodsTypes)
item.categoryType = 3
item.goodsTypes?.forEach((val) => {
packageArr.push({
packageCode: val.packageCode,
packageName: val.packageName
// commodityCode: val.commodityCode
})
})
item.goodsTypes = [] // 与分类互不干扰
item.upgradeGoods = [] // 与具体商品互不干扰
confirmedRuleCacheRevision: 0,
/** 用户是否在本 Tab 分类表单内产生过交互;详情回填后应为 false */
classificationUserTouched: false,
sessionAdded: false
}
normalizeRuleGoodsTypesForCategory(item, upgradeArr, packageArr)
})
// 获取商品
this.getSelectingList(upgradeArr)
......@@ -924,6 +1012,7 @@ export default {
this.currentIndex = this.editableTabsValue
}
this.rebuildCrossTabGoodsSelectionsFromRules()
this.pendingDeletedGroupDivisionRuleIds = []
this.$nextTick(() => {
if (
this.$refs.divisionRuleRef
......@@ -934,7 +1023,8 @@ export default {
})
resolve()
})
.catch(() => {
.catch((err) => {
console.error("[FinancialRules] getFinancialObj", err)
resolve()
})
})
......@@ -942,6 +1032,45 @@ export default {
initBaseData() {
this.goodsTypeGroupRelations = deepClone(this.productType)
},
handleClassificationChange({ type, payload }) {
switch (type) {
case CLASSIFICATION_EMIT.ASSIGN_GOODS_TYPE_LIST:
this.assignGoodsTypeList(payload)
break
case CLASSIFICATION_EMIT.DELETE_GOODS_TYPE_ITEM:
this.deleteGoodsTypeItem(payload)
break
case CLASSIFICATION_EMIT.ASSIGN_UPGRADE_GOODS_LIST:
this.assignUpgradeGoodsList(payload)
break
case CLASSIFICATION_EMIT.DELETE_UPGRADE_GOODS_ITEM:
this.deleteUpgradeGoodsItem(payload)
break
case CLASSIFICATION_EMIT.ASSIGN_PACKAGE_GOODS_LIST:
this.assignPackageGoodsList(payload)
break
case CLASSIFICATION_EMIT.DELETE_PACKAGE_GOODS_ITEM:
this.deletePackageGoodsItem(payload)
break
case CLASSIFICATION_EMIT.DELETE_SELECT_GOODS_TYPE_LIST:
this.deleteSelectGoodsTypeList(payload)
break
case CLASSIFICATION_EMIT.DELETE_SELECT_UPGRADE_GOODS_LIST:
this.deleteSelectUpgradeGoodsList(payload)
break
case CLASSIFICATION_EMIT.DELETE_SELECT_PACKAGE_GOODS_LIST:
this.deleteSelectPackageGoodsList(payload)
break
case CLASSIFICATION_EMIT.CLASSIFICATION_TOUCHED:
this.onClassificationTouched(payload)
break
case CLASSIFICATION_EMIT.RULES_TEST:
this.rulesTest()
break
default:
break
}
},
assignGoodsTypeList(list) {
// console.log(list)
const newDatas = [...this.goodsSelectList, ...list]
......@@ -987,27 +1116,37 @@ export default {
}, [])
},
async rulesTest() {
this.persistActiveClassificationTab()
await this.$nextTick()
const res = deepClone(await this.handlerConfirm())
delete res.goodsTypeGroupRules
const goodsTypeGroupRules = await this.getGoodsTypeGroupRules(
this.editableTabs,
{ onlyActiveTab: true }
)
// console.log(!this.checkParamsType(res, goodsTypeGroupRules))
if (!this.checkParamsType(res, goodsTypeGroupRules)) {
return this.$message.warning("请完善分账规则")
if (this.shouldPersistActiveClassificationTabBeforeSubmit()) {
this.persistActiveClassificationTab()
}
await this.$nextTick()
try {
const raw = await this.handlerConfirm()
if (raw === false) {
return this.$message.warning("请完善基础信息或分账渠道相关配置")
}
const res = deepClone(raw)
delete res.goodsTypeGroupRules
const ruleResult = await this.getGoodsTypeGroupRules(
this.editableTabs,
{ onlyActiveTab: true }
)
if (!this.checkParamsType(res, ruleResult)) {
return this.$message.warning("请完善分账品类规则")
}
// console.log(res)
// console.log(goodsTypeGroupRules, 'goodsTypeGroupRules')
this.rulesTestParams = {
...res,
goodsTypeGroupRule: goodsTypeGroupRules[0]
const activeRule =
ruleResult.fullMergedRules
&& ruleResult.fullMergedRules[this.activeDivisionTabIndex]
this.rulesTestParams = {
...res,
goodsTypeGroupRule: activeRule
}
// console.log('this.rulesTestParams', this.rulesTestParams)
this.merchantTestVisible = true
} finally {
this._preferCachedMergeOnceForTabIndex = null
}
// console.log('this.rulesTestParams', this.rulesTestParams)
this.merchantTestVisible = true
},
codeHandleConfirm({ smsCode, effectStartDate }) {
this.submitParams.smsCode = smsCode
......@@ -1027,12 +1166,27 @@ export default {
if (testFlag) {
let frequency = 0 // 没通过的账号
goodsTypeGroupRules.forEach((item, index) => {
const tab = this.editableTabs[index]
const id = item && item.groupDivisionRuleId
let tab = null
if (id != null && String(id).trim() !== "") {
tab = this.editableTabs.find(
(t) => String(t.groupDivisionRuleId) === String(id)
)
}
if (!tab && index < this.editableTabs.length) {
tab = this.editableTabs[index]
}
if (!tab) return
if (item.testFlag == "N") {
frequency++
this.$set(tab, "testFlag", "N")
this.$set(tab, "groupDivisionRuleId", item.groupDivisionRuleId)
if (
item.groupDivisionRuleId != null
&& String(item.groupDivisionRuleId).trim() !== ""
) {
this.$set(tab, "sessionAdded", false)
}
this.$set(
tab,
"divisionTestTabWarningFromApi",
......@@ -1059,7 +1213,7 @@ export default {
}, 100)
}
} else {
// this.$ntoe.success('保存成功')
this.pendingDeletedGroupDivisionRuleIds = []
this.$notify({
type: "success",
title: "保存成功"
......@@ -1071,6 +1225,14 @@ export default {
console.error("[FinancialRules] merchantSettleDistributeRule", err)
})
},
/** 子组件 classificationObj 非 init 回填变更时上报,用于提交时仅校验用户交互过的 Tab。 */
onClassificationTouched(paneIndex) {
const idx = Number(paneIndex)
if (!Number.isFinite(idx) || idx < 0 || idx >= this.editableTabs.length) return
const tab = this.editableTabs[idx]
if (!tab || String(tab.name) === "add") return
this.$set(tab, "classificationUserTouched", true)
},
checkSuccess(index) {
// 分账测试通过(避免 deepClone 整表,千 tab 时拷贝成本过高)
this.$set(this.editableTabs[index], "testFlag", "Y")
......@@ -1096,35 +1258,56 @@ export default {
// this.editableTabs[index].testFlag = 'Y'
},
// 校验选项是否都通过
checkParamsType(obj, array) {
const flag = array.every((item) => item)
return obj && flag
/**
* 校验选项是否都通过。array 可为旧版「每 Tab 一个结果的数组」,或 getGoodsTypeGroupRules 返回的对象。
*/
checkParamsType(obj, arrayOrResult) {
if (!obj) return false
if (arrayOrResult && typeof arrayOrResult === "object" && "ok" in arrayOrResult) {
if (arrayOrResult.ok === false) return false
const inc = arrayOrResult.incrementalRules
if (Array.isArray(inc) && inc.length > 0) {
return inc.every((item) => item && typeof item === "object")
}
return true
}
const flag = Array.isArray(arrayOrResult)
? arrayOrResult.every((item) => item)
: false
return flag
},
async submit() {
// 提交前先持久化当前激活 tab 的原始参数到缓存,
// 确保 getGoodsTypeGroupRules 读取到的是最新表单状态(含 revision bump 规则,见 persist* JSDoc)
this.persistActiveClassificationTab()
await this.$nextTick()
const res = await this.handlerConfirm()
// 内部:多 Tab 时 Loading + rAF 切片;已测通且 revision 未脏的 Tab 走缓存快路径,其余切 Tab + handleConfirm
const goodsTypeGroupRules = await this.getGoodsTypeGroupRules(
this.editableTabs
)
if (!this.checkParamsType(res, goodsTypeGroupRules)) {
return this.$message.warning("请完善分账规则")
if (this.shouldPersistActiveClassificationTabBeforeSubmit()) {
this.persistActiveClassificationTab()
}
await this.$nextTick()
try {
this.submitParams = {
...res,
goodsTypeGroupRules
const res = await this.handlerConfirm()
if (res === false) {
return this.$message.warning("请完善基础信息或分账渠道相关配置")
}
if (!this.checkCalculateType()) return
this.verificationCodeVisible = true
} catch (error) {
console.error("[FinancialRules] submit", error)
const ruleResult = await this.getGoodsTypeGroupRules(this.editableTabs)
if (!this.checkParamsType(res, ruleResult)) {
return this.$message.warning("请完善分账品类规则")
}
try {
this._fullMergedGoodsTypeGroupRulesForConflict = ruleResult.fullMergedRules
// getParams 含全量 financialObj.goodsTypeGroupRules,须先去掉再只传增量(无改动时为空数组)
const restPayload = { ...res }
delete restPayload.goodsTypeGroupRules
this.submitParams = {
...restPayload,
goodsTypeGroupRules: ruleResult.incrementalRules,
deletedGroupDivisionRuleIds: ruleResult.deletedGroupDivisionRuleIds || []
}
if (!this.checkCalculateType()) return
this.verificationCodeVisible = true
} catch (error) {
console.error("[FinancialRules] submit", error)
}
} finally {
this._preferCachedMergeOnceForTabIndex = null
}
// if (!res || !goodsTypeGroupRules) return false // 没有通过检验
},
/**
* 费用类目「整单/按品类」组合冲突检测(纯逻辑在 utils/calculateModeConflict.js)。
......@@ -1132,15 +1315,15 @@ export default {
* 改为单次遍历写入 Map(tabIndex → ops[]) 再回填 pendingCalculateErrorOps。
*/
checkCalculateType() {
const { errorTips, ops, tabErrors } = computeCalculateModeConflicts(
this.submitParams?.goodsTypeGroupRules
)
const merged = this._fullMergedGoodsTypeGroupRulesForConflict
|| this.submitParams?.goodsTypeGroupRules
const { errorTips, ops, tabErrors } = computeCalculateModeConflicts(merged)
this.editableTabs.forEach((tab) => {
if (tab && String(tab.name) !== "add") {
this.$set(tab, "pendingCalculateErrorOps", null)
}
})
const ruleLen = this.submitParams?.goodsTypeGroupRules?.length ?? 0
const ruleLen = Array.isArray(merged) ? merged.length : 0
for (let i = 0; i < ruleLen; i++) {
if (this.editableTabs[i]) {
this.$set(
......@@ -1235,175 +1418,164 @@ export default {
}
},
/**
* 按 Tab 收集 goodsTypeGroupRules,供保存前校验与组参。
*
* 【历史问题】虚拟 Tab 下若对每个 pane 都切换并挂载子组件,则始终 if(node) → handleConfirm,
* 千级 Tab 会触发千次切页 + Element 多层 validate,主线程长时间不可用。
*
* 【快路径】当 testFlag=Y、ruleCacheRevision===confirmedRuleCacheRevision 且 canSubmitFromCacheForFastPath
* 通过时:不对 editableTabsValue 赋该 Tab、不挂载 classificationCpt,直接 deepClone 财务缓存,
* 再 fillDjGoodsTypeGroupRelations。特殊品类(groupType===2)永不走快路径,须 handleConfirm。
* revision 语义见 persistClassificationTabByPaneName / bump / sync。
* 收集分账品类规则:先对需校验的 Tab 槽位做纯数据校验,失败即停并仅在该 Tab 调用 el-form 标红。
* 全量保存(onlyActiveTab 为 false):进入分类校验循环的下标为「用户曾触碰过分类表单」或「本会话新增尚未落库」的 Tab(sessionAdded),
* 避免新增 Tab 未产生 touched 时整段被跳过;增量 goodsTypeGroupRules 带 type(ADD/UPDATE);删除 id 见 pendingDeletedGroupDivisionRuleIds。
* 冲突检测:返回 fullMergedRules(与 Tab 下标对齐的全量视图)。
*
* 【慢路径】否则:持久化当前页 → 切换目标 Tab → 双 nextTick 等待挂载 → handleConfirm 或旧版缓存兜底。
* 成功后 syncTabConfirmedRuleRevisionByIndex,使该 Tab 下次在满足条件时可快走。
*
* 【可感知性能】Tab>1 时全屏 Loading(若支持 setText 则刷新进度);每 YIELD_EVERY 个 Tab await rAF,
* 让浏览器有机会重绘,减轻「死机感」。finally 内务必 close,避免异常时遮罩残留。
*
* @param {object} [options]
* @param {boolean} [options.onlyActiveTab] 为 true 时仅校验/收集当前 editableTabsValue 对应分类 Tab(如「进行测算」)
* @returns {Promise<{ ok: boolean, incrementalRules: Array, fullMergedRules: Array|null, deletedGroupDivisionRuleIds: Array, firstErrorTabIndex?: number }>}
*/
getGoodsTypeGroupRules(list, options = {}) {
return new Promise(async (resolve, reject) => {
let panes = filterDivisionTabPanes(list)
if (options.onlyActiveTab) {
const active = this.editableTabsValue
async getGoodsTypeGroupRules(_list, options = {}) {
const onlyActiveTab = options.onlyActiveTab === true
const startTabName = this.editableTabsValue
const deletedGroupDivisionRuleIds = [...this.pendingDeletedGroupDivisionRuleIds]
let indicesToValidate = []
if (onlyActiveTab) {
const idx = this.activeDivisionTabIndex
if (idx >= 0 && this.editableTabs.length) indicesToValidate = [idx]
if (indicesToValidate.length === 0) {
this.rebuildCrossTabGoodsSelectionsFromRules()
return {
ok: false,
incrementalRules: [],
fullMergedRules: null,
deletedGroupDivisionRuleIds
}
}
} else {
const n = this.editableTabs.length
for (let i = 0; i < n; i++) {
const tab = this.editableTabs[i]
if (
active == null ||
String(active) === "" ||
String(active) === "add"
tab
&& String(tab.name) !== "add"
&& (tab.classificationUserTouched === true || tab.sessionAdded === true)
) {
panes = []
} else {
panes = panes.filter(
(p) => String(p.name) === String(active)
)
indicesToValidate.push(i)
}
}
let loadingInst = null
if (panes.length > 1) {
loadingInst = this.$loading({
lock: true,
text: `正在校验分账规则 0/${panes.length}`,
background: "rgba(0, 0, 0, 0.35)"
})
}
// 多 Tab 待校验时优先校验当前激活 Tab,避免先失败在非激活 Tab(如改第二条却标红第一条)
if (
!onlyActiveTab
&& indicesToValidate.length > 1
) {
const ai = this.activeDivisionTabIndex
if (ai >= 0 && indicesToValidate.includes(ai)) {
indicesToValidate = [
ai,
...indicesToValidate.filter((i) => i !== ai).sort((a, b) => a - b)
]
}
const closeLoading = () => {
if (loadingInst) {
loadingInst.close()
loadingInst = null
}
}
const emptyOkResult = () => {
const validatedByIndex = {}
const fullMerged = this.buildFullMergedGoodsTypeGroupRules(validatedByIndex)
return {
ok: true,
incrementalRules: [],
fullMergedRules: fullMerged,
deletedGroupDivisionRuleIds
}
const prevTabName = this.editableTabsValue
const goodsTypeGroupRules = []
// 每处理 N 个 Tab 让出一帧;N 过小会增加总时长,过大则交互仍显卡顿,可按实测调整
const YIELD_EVERY = 15
try {
for (let index = 0; index < panes.length; index++) {
if (loadingInst && typeof loadingInst.setText === "function") {
loadingInst.setText(
`正在校验分账规则 ${index + 1}/${panes.length}`
)
}
if (index > 0 && index % YIELD_EVERY === 0) {
await new Promise((r) => requestAnimationFrame(r))
}
}
const tabindex = this.editableTabs.findIndex(
(item) => item.name == panes[index].name
if (
!onlyActiveTab
&& indicesToValidate.length === 0
) {
this.rebuildCrossTabGoodsSelectionsFromRules()
return emptyOkResult()
}
let loadingInst = null
if (indicesToValidate.length > 1) {
loadingInst = this.$loading({
lock: true,
text: `正在校验分账规则 0/${indicesToValidate.length}`,
background: "rgba(0, 0, 0, 0.35)"
})
}
const closeLoading = () => {
if (loadingInst) {
loadingInst.close()
loadingInst = null
}
}
const YIELD_EVERY = 15
const validatedByIndex = {}
try {
for (let k = 0; k < indicesToValidate.length; k++) {
if (loadingInst && typeof loadingInst.setText === "function") {
loadingInst.setText(
`正在校验分账规则 ${k + 1}/${indicesToValidate.length}`
)
const tab = this.editableTabs[tabindex]
const cachedRule = this.financialObj.goodsTypeGroupRules[tabindex]
this.ensureTabRevisionFields(tab)
// 特殊品类(groupType===2)保存前须走慢路径执行 handleConfirm;否则用户未切换 Tab 时仅 deepClone 会跳过整表校验
const isSpecialCategoryRule =
cachedRule &&
typeof cachedRule === "object" &&
Number(cachedRule.groupType) === 2
// 快路径条件集:见本方法文件头 JSDoc;缺一不可,否则必须慢路径以保证与 handleConfirm 等价
const useFastPath =
tab &&
!isSpecialCategoryRule &&
tab.testFlag === "Y" &&
cachedRule &&
typeof cachedRule === "object" &&
Number(tab.confirmedRuleCacheRevision) ===
Number(tab.ruleCacheRevision) &&
this.canSubmitFromCacheForFastPath(cachedRule)
const nextName = panes[index].name
let node = null
let res
if (useFastPath) {
// 不切 Tab、不 validate;提交体必须与缓存隔离,故 deepClone(与慢路径返回的新对象语义一致)
res = deepClone(cachedRule)
} else {
// 程序赋值 editableTabsValue 不会触发 handleDivisionTabChange;切换前先持久化当前页,
// 否则虚拟渲染卸载上一个 classificationCpt 会丢掉未写入缓存的编辑。
const cur = this.editableTabsValue
if (
cur != null &&
String(cur) !== "" &&
String(cur) !== "add" &&
String(cur) !== String(nextName)
) {
this.persistClassificationTabByPaneName(cur)
await this.$nextTick()
}
this.editableTabsValue = nextName
// 虚拟 Tab 切换后 ref 可能晚于 nextTick 就绪;若用缓存 deepClone 会跳过 handleConfirm,
// 编辑态下特殊品类等必填未校验也能过(原 allowByTestFlag / allowByEditEcho 回退)。
const MAX_CLASSIFICATION_REF_WAIT = 24
for (let attempt = 0; attempt < MAX_CLASSIFICATION_REF_WAIT; attempt++) {
await this.$nextTick()
node = this.getClassificationRef(panes[index].name)
if (node) break
}
if (node && typeof node.handleConfirm === "function") {
res = await node.handleConfirm()
} else {
res = false
}
}
}
if (k > 0 && k % YIELD_EVERY === 0) {
await new Promise((r) => requestAnimationFrame(r))
}
if (tab) {
if (res) {
if (!useFastPath && node) {
tab.testFlag = "Y"
this.$set(tab, "divisionTestTabWarningFromApi", false)
}
} else {
tab.testFlag = "N"
}
}
// 快路径已假定 revision 对齐;仅慢路径成功后把「校验通过快照」写回 confirmed
if (res && !useFastPath) {
this.syncTabConfirmedRuleRevisionByIndex(tabindex)
}
if (res && typeof res === "object") {
fillDjGoodsTypeGroupRelations(res)
}
goodsTypeGroupRules.push(res)
const tabindex = indicesToValidate[k]
const tab = this.editableTabs[tabindex]
const rulePayload = this.resolveRulePayloadForTabValidation(tabindex)
if (!res) {
for (let j = index + 1; j < panes.length; j++) {
goodsTypeGroupRules.push(false)
}
break
if (!validateGoodsTypeGroupRulePayload(rulePayload)) {
await this.focusTabAndRunHandleConfirm(tab.name)
this.rebuildCrossTabGoodsSelectionsFromRules()
return {
ok: false,
incrementalRules: [],
fullMergedRules: null,
deletedGroupDivisionRuleIds,
firstErrorTabIndex: tabindex
}
}
const allPassed = goodsTypeGroupRules.length > 0 &&
goodsTypeGroupRules.every((item) => item)
if (allPassed && prevTabName != null && String(prevTabName) !== "add") {
if (String(this.editableTabsValue) !== String(prevTabName)) {
this.persistClassificationTabByPaneName(this.editableTabsValue)
await this.$nextTick()
}
this.editableTabsValue = prevTabName
await this.$nextTick()
const prepared = prepareRuleForValidation(rulePayload)
validatedByIndex[tabindex] = prepared
if (tab) {
this.$set(tab, "testFlag", "Y")
this.$set(tab, "divisionTestTabWarningFromApi", false)
}
this.syncTabConfirmedRuleRevisionByIndex(tabindex)
}
this.rebuildCrossTabGoodsSelectionsFromRules()
resolve(goodsTypeGroupRules)
} catch (e) {
reject(e)
} finally {
closeLoading()
const incrementalRules = buildGoodsTypeGroupIncrementalRules(
validatedByIndex,
indicesToValidate,
onlyActiveTab
)
const fullMerged = this.buildFullMergedGoodsTypeGroupRules(validatedByIndex)
if (
startTabName != null
&& String(startTabName) !== "add"
&& String(this.editableTabsValue) !== String(startTabName)
) {
this.persistClassificationTabByPaneName(this.editableTabsValue)
await this.$nextTick()
this.editableTabsValue = startTabName
await this.$nextTick()
}
})
this.rebuildCrossTabGoodsSelectionsFromRules()
return {
ok: true,
incrementalRules,
fullMergedRules: fullMerged,
deletedGroupDivisionRuleIds
}
} catch (e) {
console.error("[FinancialRules] getGoodsTypeGroupRules", e)
throw e
} finally {
closeLoading()
}
},
getSelectingList(defaultSelect) {
getAllGoodsList({
......@@ -1624,9 +1796,25 @@ export default {
},
/* 函数定义 */
/**
* 下拉切换品类:受控 el-select,先持久化旧 tab 再更新 editableTabsValue(对齐原 beforeLeave)。
* 新增/删除 Tab 后 name 会重排为 "1","2"…;若 editableTabsValue 仍为旧名,
* activeDivisionTabIndex 会 findIndex 为 -1 并误兜底 0,子组件绑错 goodsTypeGroupRules 槽位。
* 在结构变化后调用,将选中校正为当前存在的 tab.name。
*/
async handleDivisionTabChange(newName) {
ensureDivisionTabSelectionValid() {
const tabs = this.editableTabs
if (!tabs || tabs.length === 0) return
const names = tabs.map((t) => String(t.name))
const cur =
this.editableTabsValue != null ? String(this.editableTabsValue) : ""
if (names.includes(cur)) return
const first = tabs[0].name
this.editableTabsValue = first
this.currentIndex = first
},
/**
* 离开旧 Tab 前持久化,再激活新 Tab(对齐原 el-tabs beforeLeave)。
*/
async persistLeavingTabThenActivateDivisionTab(newName) {
const oldName = this.editableTabsValue
if (String(newName) === String(oldName)) return
await this.$nextTick()
......@@ -1637,6 +1825,12 @@ export default {
this.currentIndex = newName
},
/**
* 下拉切换品类:受控 el-select,先持久化旧 tab 再更新 editableTabsValue。
*/
async handleDivisionTabChange(newName) {
await this.persistLeavingTabThenActivateDivisionTab(newName)
},
/**
* 新增特殊品类 tab:对齐原「+」页签逻辑,先持久化当前 tab 再 addTab。
*/
handleAppendDivisionTab() {
......@@ -1673,7 +1867,10 @@ export default {
testFlag: 'N',
divisionTestTabWarningFromApi: false,
ruleCacheRevision: 0,
confirmedRuleCacheRevision: 0
confirmedRuleCacheRevision: 0,
/** 本会话新增、尚未成功落库的 Tab;删除时仅本地去掉,不向服务端传删除 id */
sessionAdded: true,
classificationUserTouched: false
})
// 为新 tab 预占 goodsTypeGroupRules 槽位,必须用空对象 {},不能为 null:
......@@ -1691,6 +1888,7 @@ export default {
if (String(this.editableTabsValue) !== String(newTabIndex)) {
this.editableTabsValue = newTabIndex
}
this.ensureDivisionTabSelectionValid()
})
},
confirmRemove(targetName) {
......@@ -1715,8 +1913,10 @@ export default {
})
},
async removeTab(targetName) {
// 删除 tab 前先持久化当前激活 tab,保证数据同步到缓存后再重新收集全量参数
this.persistActiveClassificationTab()
// 删除 tab 前先持久化当前激活 tab(有实质变更或待删 id 时),保证数据同步到缓存后再重新收集全量参数
if (this.shouldPersistActiveClassificationTabBeforeSubmit()) {
this.persistActiveClassificationTab()
}
await this.$nextTick()
// 获取当前tab 对应的对象
const goodsTypeGroupRules = this.getAllParams()
......@@ -1750,6 +1950,24 @@ export default {
const tabIndex = this.editableTabs.findIndex(
(item) => item.name == targetName
)
const prevTabsMeta = this.editableTabs.map((t) => ({
sessionAdded: !!t.sessionAdded,
ruleCacheRevision: t.ruleCacheRevision,
confirmedRuleCacheRevision: t.confirmedRuleCacheRevision,
classificationUserTouched: !!t.classificationUserTouched
}))
const removedTabMeta = this.editableTabs[tabIndex]
const removedRule = goodsTypeGroupRules[tabIndex]
// 本会话新增的 Tab 删掉即可,不向服务端提交删除(无落库 id 或仅本地草稿)
const isSessionOnlyNew = removedTabMeta && removedTabMeta.sessionAdded === true
if (!isSessionOnlyNew) {
const removedId =
(removedRule && removedRule.groupDivisionRuleId)
|| (removedTabMeta && removedTabMeta.groupDivisionRuleId)
if (removedId != null && String(removedId).trim() !== "") {
this.pendingDeletedGroupDivisionRuleIds.push(String(removedId))
}
}
const upgradeArr = []
const packageArr = []
this.editableTabs = []
......@@ -1763,6 +1981,16 @@ export default {
this.$set(this.financialObj, "goodsTypeGroupRules", goodsTypeGroupRules)
goodsTypeGroupRules &&
goodsTypeGroupRules.forEach((item, index) => {
const oldIdx = index < tabIndex ? index : index + 1
const meta = prevTabsMeta[oldIdx]
const sessionAdded = !!(meta && meta.sessionAdded)
const rr = meta && meta.ruleCacheRevision != null
? Number(meta.ruleCacheRevision)
: 0
const crr = meta && meta.confirmedRuleCacheRevision != null
? Number(meta.confirmedRuleCacheRevision)
: 0
const classificationUserTouched = !!(meta && meta.classificationUserTouched)
this.editableTabs[index] = {
title: index ? "特殊品类" + index : "全部品类",
name: (index + 1).toString(),
......@@ -1771,57 +1999,24 @@ export default {
item.testFlag == "N" ? item.groupDivisionRuleId || "" : "",
divisionTestTabWarningFromApi:
this.isDivisionTestTabWarningFromApiRuleItem(item),
// 删除 Tab 后重建:revision 从零计,与 getGoodsTypeGroupRules 快路径约定一致
ruleCacheRevision: 0,
confirmedRuleCacheRevision: 0
}
// 按商品分类
if (
item.goodsTypes?.length &&
item.goodsTypes[0]?.categoryType == 1
) {
item.goodsTypes = deepClone(item.goodsTypes)
item.categoryType = 1
item.upgradeGoods = [] // 与具体商品互不干扰
item.packageGoods = []
}
// 按具体商品
if (
item.goodsTypes?.length &&
item.goodsTypes[0]?.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 = []
}
// 按套餐商品
// console.log(item.goodsTypes, 'item.goodsTypes')
if (
item.goodsTypes?.length &&
item.goodsTypes[0]?.categoryType == 3
) {
item.packageGoods = deepClone(item.goodsTypes)
item.categoryType = 3
item.goodsTypes?.forEach((val) => {
packageArr.push({
packageCode: val.packageCode,
packageName: val.packageName
// commodityCode: val.commodityCode
})
})
item.goodsTypes = [] // 与分类互不干扰
item.upgradeGoods = [] // 与具体商品互不干扰
// 删 Tab 后按旧下标恢复 revision,避免误清零导致脏 Tab 丢失或误校验其它 Tab
ruleCacheRevision: rr,
confirmedRuleCacheRevision: crr,
classificationUserTouched,
sessionAdded
}
normalizeRuleGoodsTypesForCategory(item, upgradeArr, packageArr)
})
this.ensureDivisionTabSelectionValid()
if (isSessionOnlyNew) {
const ai = this.editableTabs.findIndex(
(t) => String(t.name) === String(this.editableTabsValue)
)
this._preferCachedMergeOnceForTabIndex = ai >= 0 ? ai : null
}
// 获取商品
this.getSelectingList(upgradeArr)
this.getSelectingListPackage(packageArr)
......
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))
}
......@@ -2,14 +2,15 @@
<div class="classificationCpt-check">
<el-form ref="classification" :model="classificationObj" size="small" label-suffix=":" label-width="260px">
<p class="edit-sub-title">对账品类</p>
<el-form-item v-if="tabindex && classificationObj.groupType == 2" label="商品来源" prop="goodsSource" required :rules="[
<el-form-item v-if="tabindex && classificationObj.groupType == 2" label="商品来源" prop="goodsSource"
:rules="rulesWhenEffectRuleActive([
{
required: true,
message: '请选择商品来源',
trigger: ['change', 'blur']
}
]">
<el-radio-group v-model="classificationObj.goodsSource">
])">
<el-radio-group v-model="classificationObj.goodsSource" @input="emitUserClassificationTouched">
<el-radio v-for="(goodsItem, goodsIndex) in goodsSourceList" :disabled="goodsSourceReconciliationSet.includes(goodsItem.confId) &&
goodsItem.confId != 1 &&
classificationObj.goodsSource != goodsItem.confId
......@@ -18,15 +19,16 @@
</el-radio>
</el-radio-group>
</el-form-item>
<div style="display: flex"
<div
style="display: flex; flex-wrap: wrap; align-items: flex-start; gap: 0 8px"
v-if="tabindex && classificationObj.groupType == 2 && classificationObj.goodsSource == 1">
<el-form-item label="分账品类" prop="categoryType" required :rules="[
<el-form-item label="分账品类" prop="categoryType" :rules="rulesWhenEffectRuleActive([
{
required: true,
message: '请选择分账品类',
trigger: ['change', 'blur']
}
]">
])">
<el-select v-model="classificationObj.categoryType" @change="clearValidate">
<el-option :key="1" label="按商品分类" :value="1"></el-option>
<el-option :key="2" label="按具体商品" :value="2"></el-option>
......@@ -34,9 +36,9 @@
</el-select>
</el-form-item>
<el-form-item label-width="20px" v-if="classificationObj.categoryType == 1" prop="goodsTypeGroupRelations"
:rules="[
:rules="rulesWhenEffectRuleActive([
{ required: true, message: '请选择商品分类', trigger: 'blur' }
]">
])">
<el-select v-model="classificationObj.goodsTypeGroupRelations" @change="goodsSelectChange"
value-key="goodsType" multiple collapse-tags style="width: 320px" placeholder="请选择商品分类">
<el-option v-for="item in goodsList" :key="item.goodsType" :label="item.goodsTypeName"
......@@ -46,7 +48,7 @@
<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="请选择商品" @visible-change="visibleChange" :remote-method="remoteMethod"
placeholder="请选择商品" @change="emitUserClassificationTouched" @visible-change="visibleChange" :remote-method="remoteMethod"
v-el-select-loadmore="interestsLoadmore" style="width: 320px" popper-class="class123"
value-key="upgradeGoodsId" filterable>
<el-option v-for="subItem in copyUpgradeGoodsList" :key="subItem.upgradeGoodsId"
......@@ -58,7 +60,7 @@
<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="请选择套餐商品" @visible-change="visibleChangePackage" :remote-method="remoteMethodPackage"
placeholder="请选择套餐商品" @change="emitUserClassificationTouched" @visible-change="visibleChangePackage" :remote-method="remoteMethodPackage"
v-el-select-loadmore-package="interestsLoadmorePackage" style="width: 370px" value-key="packageCode"
filterable>
<el-option v-for="subItem in copyPackageGoodsList" :key="subItem.packageCode"
......@@ -81,13 +83,13 @@
<template>
<!-- .feeCategoryNameList[0] -->
<el-form-item :label="floweItem.feeCategoryName" label-width="260px"
:prop="'flowCostArr.' + floweIdx + '.calculateMode'" :rules="[
:prop="'flowCostArr.' + floweIdx + '.calculateMode'" :rules="rulesWhenEffectRuleActive([
{
required: true,
message: '请选择计算方式',
trigger: 'change'
}
]" required>
])">
<span slot="label" class="label-span">
<span class="sub-label">{{ floweItem.feeCategoryName }}</span>
<el-tooltip class="item" effect="dark" placement="right">
......@@ -133,13 +135,13 @@
</el-form-item>
<div class="multiple-type">
<el-form-item :prop="'flowCostArr.' + floweIdx + '.expenseCategoryCalculateType'
" :rules="[
" :rules="rulesWhenEffectRuleActive([
{
required: true,
message: '请选择对账模式',
trigger: 'change'
}
]" label-width="260px">
])" label-width="260px">
<el-select class="w432" v-model="classificationObj.flowCostArr[floweIdx]
.expenseCategoryCalculateType
" placeholder="请选择对账模式" @change="($event) => onExpenseCategoryCalculateTypeChange($event, 'flowCostArr', floweIdx)
......@@ -149,13 +151,13 @@
</el-select>
</el-form-item>
<el-form-item label-width="0px" :prop="`flowCostArr[${floweIdx}].expenseCategoryValue`" class="ml20"
:rules="[
:rules="rulesWhenEffectRuleActive([
{
required: true,
message: '请输入',
trigger: ['change', 'blur']
}
]">
])">
<el-input v-model="classificationObj.flowCostArr[floweIdx]
.expenseCategoryValue
" @input="
......@@ -167,7 +169,7 @@
floweIdx
)
" :placeholder="classificationObj.flowCostArr[floweIdx]
.expenseCategoryCalculateType | filerPlaceName
.expenseCategoryCalculateType | filterPlaceName
">
<i slot="suffix" v-if="
classificationObj.flowCostArr[floweIdx]
......@@ -182,7 +184,7 @@
label-width="260px">
<!-- @change="flowListChange" -->
<el-select class="w432" v-model="classificationObj.flowCostArr[floweIdx].merchant"
value-key="merchantId" placeholder="请选择对账对象" clearable>
value-key="merchantId" placeholder="请选择对账对象" clearable @change="emitUserClassificationTouched">
<el-option v-for="(item, index) in flowList" :key="index + 'flowList'" :label="item.merchantName"
:value="item"></el-option>
</el-select>
......@@ -198,13 +200,13 @@
</el-table-column>
<el-table-column label="计算模式" width="250">
<template slot-scope="scope">
<el-form-item :prop="`flowCostArr[${floweIdx}].children[${scope.$index}].calculateMode`" :rules="[
<el-form-item :prop="`flowCostArr[${floweIdx}].children[${scope.$index}].calculateMode`" :rules="rulesWhenEffectRuleActive([
{
required: true,
message: '请选择计算方式',
trigger: 'change'
}
]" style="width: 100%" required>
])" style="width: 100%">
<el-radio-group v-model="scope.row.calculateMode" :disabled="true">
<el-radio :label="1"> 按品类计算 </el-radio>
<el-radio :label="2"> 按整单计算 </el-radio>
......@@ -214,15 +216,14 @@
</el-table-column>
<el-table-column label="对账模式">
<template slot-scope="scope">
<el-form-item v-if="scope.row.nodeType != 4" class="edit-form-item-table-children" required
:prop="`flowCostArr[${floweIdx}].children[${scope.$index}].expenseCategoryCalculateType`"
:rules="[
<el-form-item v-if="scope.row.nodeType != 4" class="edit-form-item-table-children" :prop="`flowCostArr[${floweIdx}].children[${scope.$index}].expenseCategoryCalculateType`"
:rules="rulesWhenEffectRuleActive([
{
required: true,
message: '请选择对账模式',
trigger: 'change'
}
]">
])">
<el-select v-model="scope.row.expenseCategoryCalculateType" placeholder="请选择对账模式" @change="($event) =>
onExpenseCategoryCalculateTypeChange(
$event,
......@@ -240,16 +241,15 @@
</el-table-column>
<el-table-column label="对账模式">
<template slot-scope="scope">
<el-form-item v-if="scope.row.nodeType != 4" class="edit-form-item-table-children" required
:prop="`flowCostArr[${floweIdx}].children[${scope.$index}].expenseCategoryValue`" :rules="[
<el-form-item v-if="scope.row.nodeType != 4" class="edit-form-item-table-children" :prop="`flowCostArr[${floweIdx}].children[${scope.$index}].expenseCategoryValue`" :rules="rulesWhenEffectRuleActive([
{
required: true,
message: '请输入',
trigger: ['change', 'blur']
}
]">
])">
<el-input v-model="scope.row.expenseCategoryValue" style="width: 150px" :placeholder="scope.row.expenseCategoryCalculateType
| filerPlaceName
| filterPlaceName
" @input="
handleInput(
$event,
......@@ -272,7 +272,7 @@
<template slot-scope="scope">
<!-- @change="flowListChange" -->
<el-select class="w432" v-model="scope.row.merchant" value-key="merchantId" placeholder="请选择对账对象"
clearable>
clearable @change="emitUserClassificationTouched">
<el-option v-for="(item, index) in flowList" :key="index + 'flowList'"
:label="item.merchantName" :value="item"></el-option>
</el-select>
......@@ -297,13 +297,13 @@
<div v-for="(serveItem, serveIdx) in titleListServe" :key="serveIdx + 'titleListServe'">
<template>
<el-form-item :label="serveItem.feeCategoryName" label-width="260px"
:prop="'serviceCostArr.' + serveIdx + '.calculateMode'" :rules="[
:prop="'serviceCostArr.' + serveIdx + '.calculateMode'" :rules="rulesWhenEffectRuleActive([
{
required: true,
message: '请选择计算方式',
trigger: 'change'
}
]" required>
])">
<span slot="label" class="label-span">
<span class="sub-label">{{ serveItem.feeCategoryName }}</span>
<el-tooltip class="item" effect="dark" placement="right">
......@@ -364,13 +364,13 @@
<el-form-item :prop="'serviceCostArr.' +
serveIdx +
'.expenseCategoryCalculateType'
" :rules="[
" :rules="rulesWhenEffectRuleActive([
{
required: true,
message: '请选择对账模式',
trigger: 'change'
}
]" label-width="260px">
])" label-width="260px">
<el-select class="w432" v-model="classificationObj.serviceCostArr[serveIdx]
.expenseCategoryCalculateType
" @change="($event) =>
......@@ -380,13 +380,13 @@
:value="item.expenseCategoryCalculateType"></el-option>
</el-select>
</el-form-item>
<el-form-item label-width="0px" :prop="`serviceCostArr[${serveIdx}].expenseCategoryValue`" :rules="[
<el-form-item label-width="0px" :prop="`serviceCostArr[${serveIdx}].expenseCategoryValue`" :rules="rulesWhenEffectRuleActive([
{
required: true,
message: '请输入',
trigger: ['change', 'blur']
}
]" class="ml20">
])" class="ml20">
<el-input v-model="classificationObj.serviceCostArr[serveIdx]
.expenseCategoryValue
" @input="
......@@ -398,7 +398,7 @@
serveIdx
)
" :placeholder="classificationObj.serviceCostArr[serveIdx]
.expenseCategoryCalculateType | filerPlaceName
.expenseCategoryCalculateType | filterPlaceName
">
<i slot="suffix" v-if="
classificationObj.serviceCostArr[serveIdx]
......@@ -412,7 +412,7 @@
<el-form-item label="对账对象" v-if="classificationObj.serviceCostArr[serveIdx].formType != 2"
label-width="260px">
<el-select class="w432" v-model="classificationObj.serviceCostArr[serveIdx].merchant"
value-key="merchantId" placeholder="请选择对账对象" clearable>
value-key="merchantId" placeholder="请选择对账对象" clearable @change="emitUserClassificationTouched">
<!-- @change="serveListChange" -->
<el-option v-for="(item, index) in serveList" :key="index + 'serveList'" :label="item.merchantName"
:value="item"></el-option>
......@@ -432,13 +432,13 @@
<el-table-column label="计算模式" width="250">
<template slot-scope="scope">
<el-form-item :prop="`serviceCostArr[${serveIdx}].children[${scope.$index}].calculateMode`"
:rules="[
:rules="rulesWhenEffectRuleActive([
{
required: true,
message: '请选择计算方式',
trigger: 'change'
}
]" style="width: 100%" required>
])" style="width: 100%">
<el-radio-group v-model="scope.row.calculateMode" :disabled="true">
<el-radio :label="1"> 按品类计算 </el-radio>
<el-radio :label="2"> 按整单计算 </el-radio>
......@@ -448,15 +448,14 @@
</el-table-column>
<el-table-column label="对账模式">
<template slot-scope="scope">
<el-form-item v-if="scope.row.nodeType != 4" class="edit-form-item-table-children" required
:prop="`serviceCostArr[${serveIdx}].children[${scope.$index}].expenseCategoryCalculateType`"
:rules="[
<el-form-item v-if="scope.row.nodeType != 4" class="edit-form-item-table-children" :prop="`serviceCostArr[${serveIdx}].children[${scope.$index}].expenseCategoryCalculateType`"
:rules="rulesWhenEffectRuleActive([
{
required: true,
message: '请选择对账模式',
trigger: 'change'
}
]">
])">
<el-select v-model="scope.row.expenseCategoryCalculateType" placeholder="请选择对账模式" @change="($event) =>
onExpenseCategoryCalculateTypeChange(
$event,
......@@ -474,12 +473,11 @@
</el-table-column>
<el-table-column label="对账模式">
<template slot-scope="scope">
<el-form-item v-if="scope.row.nodeType != 4" class="edit-form-item-table-children" required
:prop="`serviceCostArr[${serveIdx}].children[${scope.$index}].expenseCategoryValue`" :rules="[
<el-form-item v-if="scope.row.nodeType != 4" class="edit-form-item-table-children" :prop="`serviceCostArr[${serveIdx}].children[${scope.$index}].expenseCategoryValue`" :rules="rulesWhenEffectRuleActive([
{ required: true, message: '请输入', trigger: 'blur' }
]">
])">
<el-input v-model="scope.row.expenseCategoryValue" style="width: 150px" :placeholder="scope.row.expenseCategoryCalculateType
| filerPlaceName
| filterPlaceName
" @input="
handleInput(
$event,
......@@ -501,7 +499,7 @@
<el-table-column label="对账对象">
<template slot-scope="scope">
<el-select class="w432" v-model="scope.row.merchant" value-key="merchantId" placeholder="请选择对账对象"
clearable>
clearable @change="emitUserClassificationTouched">
<el-option v-for="(item, index) in serveList" :key="index + 'serveList'"
:label="item.merchantName" :value="item"></el-option>
</el-select>
......@@ -524,13 +522,13 @@
<div v-for="(serveItem, platformIdx) in titleListPlatform" :key="platformIdx + 'titleListPlatform'">
<template>
<el-form-item :label="serveItem.feeCategoryName" label-width="260px"
:prop="'platformCostArr.' + platformIdx + '.calculateMode'" :rules="[
:prop="'platformCostArr.' + platformIdx + '.calculateMode'" :rules="rulesWhenEffectRuleActive([
{
required: true,
message: '请选择计算方式',
trigger: 'change'
}
]" required>
])">
<span slot="label" class="label-span">
<span class="sub-label">{{ serveItem.feeCategoryName }}</span>
<el-tooltip class="item" effect="dark" placement="right">
......@@ -591,13 +589,13 @@
<el-form-item :prop="'platformCostArr.' +
platformIdx +
'.expenseCategoryCalculateType'
" :rules="[
" :rules="rulesWhenEffectRuleActive([
{
required: true,
message: '请选择对账模式',
trigger: ['change', 'blur']
}
]" label-width="260px">
])" label-width="260px">
<el-select class="w432" v-model="classificationObj.platformCostArr[platformIdx]
.expenseCategoryCalculateType
" placeholder="请选择对账模式" @change="($event) =>
......@@ -607,13 +605,13 @@
:label="item.label" :value="item.expenseCategoryCalculateType"></el-option>
</el-select>
</el-form-item>
<el-form-item label-width="0px" :prop="`platformCostArr[${platformIdx}].expenseCategoryValue`" :rules="[
<el-form-item label-width="0px" :prop="`platformCostArr[${platformIdx}].expenseCategoryValue`" :rules="rulesWhenEffectRuleActive([
{
required: true,
message: '请输入',
trigger: ['change', 'blur']
}
]" class="ml20">
])" class="ml20">
<el-input v-model="classificationObj.platformCostArr[platformIdx]
.expenseCategoryValue
" @input="
......@@ -625,7 +623,7 @@
platformIdx
)
" :placeholder="classificationObj.platformCostArr[platformIdx]
.expenseCategoryCalculateType | filerPlaceName
.expenseCategoryCalculateType | filterPlaceName
">
<i slot="suffix" v-if="
classificationObj.platformCostArr[platformIdx]
......@@ -640,7 +638,7 @@
classificationObj.platformCostArr[platformIdx].formType != 2
" label-width="260px">
<el-select class="w432" v-model="classificationObj.platformCostArr[platformIdx].merchant
" value-key="merchantId" placeholder="请选择对账对象" clearable>
" value-key="merchantId" placeholder="请选择对账对象" clearable @change="emitUserClassificationTouched">
<el-option v-for="(item, index) in platformList" :key="index + 'platformList'"
:label="item.merchantName" :value="item"></el-option>
</el-select>
......@@ -660,13 +658,13 @@
<el-table-column label="计算模式" width="250">
<template slot-scope="scope">
<el-form-item :prop="`platformCostArr[${platformIdx}].children[${scope.$index}].calculateMode`"
:rules="[
:rules="rulesWhenEffectRuleActive([
{
required: true,
message: '请选择计算方式',
trigger: 'change'
}
]" style="width: 100%" required>
])" style="width: 100%">
<el-radio-group v-model="scope.row.calculateMode" :disabled="true">
<el-radio :label="1"> 按品类计算 </el-radio>
<el-radio :label="2"> 按整单计算 </el-radio>
......@@ -676,15 +674,14 @@
</el-table-column>
<el-table-column label="对账模式">
<template slot-scope="scope">
<el-form-item v-if="scope.row.nodeType != 4" class="edit-form-item-table-children" required
:prop="`platformCostArr[${platformIdx}].children[${scope.$index}].expenseCategoryCalculateType`"
:rules="[
<el-form-item v-if="scope.row.nodeType != 4" class="edit-form-item-table-children" :prop="`platformCostArr[${platformIdx}].children[${scope.$index}].expenseCategoryCalculateType`"
:rules="rulesWhenEffectRuleActive([
{
required: true,
message: '请选择对账模式',
trigger: 'change'
}
]">
])">
<el-select v-model="scope.row.expenseCategoryCalculateType" placeholder="请选择对账模式" @change="($event) =>
onExpenseCategoryCalculateTypeChange(
$event,
......@@ -702,16 +699,15 @@
</el-table-column>
<el-table-column label="对账模式">
<template slot-scope="scope">
<el-form-item v-if="scope.row.nodeType != 4" class="edit-form-item-table-children" required
:prop="`platformCostArr[${platformIdx}].children[${scope.$index}].expenseCategoryValue`" :rules="[
<el-form-item v-if="scope.row.nodeType != 4" class="edit-form-item-table-children" :prop="`platformCostArr[${platformIdx}].children[${scope.$index}].expenseCategoryValue`" :rules="rulesWhenEffectRuleActive([
{
required: true,
message: '请输入',
trigger: 'change'
}
]">
])">
<el-input v-model="scope.row.expenseCategoryValue" style="width: 150px" :placeholder="scope.row.expenseCategoryCalculateType
| filerPlaceName
| filterPlaceName
" @input="
handleInput(
$event,
......@@ -733,7 +729,7 @@
<el-table-column label="对账对象">
<template slot-scope="scope">
<el-select class="w432" v-model="scope.row.merchant" value-key="merchantId" placeholder="请选择对账对象"
clearable>
clearable @change="emitUserClassificationTouched">
<el-option v-for="(item, index) in platformList" :key="index + 'platformList'"
:label="item.merchantName" :value="item"></el-option>
</el-select>
......@@ -750,6 +746,28 @@
</template>
<script>
/**
* 商户对账页 provide 的 context 形状(与 merchantCheck 中 classification*Context 一致)
* @typedef {Object} MerchantCheckPageContext
* @property {Array} queryFeeCategoryByTypeFlow
* @property {Array} queryFeeCategoryByTypeServe
* @property {Array} queryFeeCategoryByTypePlatform
* @property {Array|Object} goodsTypeGroupReconciliationRules 全量对账规则槽位
* @typedef {Object} MerchantCheckSelectionContext
* @property {Array} goodsList 可选品类(goodsTypeGroupRelations)
* @property {Array} goodsSelectList
* @property {Array} upgradeGoodsList
* @property {Array} packageGoodsList
* @property {Array} selectUpgradeGoodsList
* @property {Array} selectPackageGoodsList
* @typedef {Object} MerchantCheckPaneContext
* @property {number} paneIndex 当前 Tab 下标(与财务规则页 classificationPaneContext 一致)
* @property {number} tabindex 当前 Tab 下标(与 paneIndex 同值,兼容旧逻辑)
* @property {Object} tabItem 当前 Tab 元数据(editableTabs[idx])
* @property {Object} classificationObjSelect 占位,与财务页对齐;对账侧暂无全局聚合时可传 {}
* @property {Object} goodsTypeGroupReconciliationRule 当前 Tab 对应的一条对账规则(phantom 或 rules 槽位)
* @property {Object|null} phantomFullCategoryRule tab0 占位且首条为特殊品类时的快照(与单条规则同源时可并存)
*/
import { mapMutations, mapGetters } from "vuex"
import { listPartnerMerchantApi, getMerchantLevelListApi } from "@api/merchant"
import {
......@@ -768,75 +786,33 @@ import { limitPrice } from "@/common/format"
import { createElSelectLoadmoreDirective } from "../utils/selectLoadmoreDirective"
import {
flatMapUpgradeGoodsFromGoodsListPage,
uniqueUpgradeGoodsById
uniqueUpgradeGoodsById,
uniquePackageByPackageCode
} from "../utils/groundingUpgradeList"
import { CLASSIFICATION_EMIT } from "../../financialRules/utils/classificationEmitTypes"
export default {
name: "ClassificationCpt",
inject: {
financialRulesEnv: {
from: "financialRulesEnv",
default: null
}
},
props: {
goodsList: {
type: Array,
// 必要
/** @type {MerchantCheckPageContext} */
pageContext: {
type: Object,
required: true
},
goodsSelectList: {
type: Array,
default: () => []
},
tabindex: {
type: Number,
default: 0
},
goodsTypeGroupReconciliationRules: {
type: [Array, Object],
default: () => []
},
queryFeeCategoryByTypeFlow: {
type: Array,
default: () => []
},
queryFeeCategoryByTypeServe: {
type: Array,
default: () => []
},
queryFeeCategoryByTypePlatform: {
type: Array,
default: () => []
},
upgradeGoodsList: {
type: Array,
default() {
return []
}
},
packageGoodsList: {
type: Array,
default() {
return []
}
},
selectUpgradeGoodsList: {
type: Array,
default() {
return []
}
},
selectPackageGoodsList: {
type: Array,
default() {
return []
}
},
routerInfo: {
/** @type {MerchantCheckSelectionContext} */
selectionContext: {
type: Object,
required: true,
default() {
return {}
}
required: true
},
/** 父页占位 tab0「全部」快照(goodsTypeGroupReconciliationRules 无对应行时) */
phantomFullCategoryRule: {
/** @type {MerchantCheckPaneContext} */
paneContext: {
type: Object,
default: null
required: true
}
},
directives: {
......@@ -922,13 +898,82 @@ export default {
/** getEffectRule 回填期间抑制 goodsTypeGroupRelations 等 watch 向父 $emit */
_suppressSelectionSync: false,
/** 同 tick 内多次触发时只排队一次 getEffectRule */
_getEffectRuleScheduled: false
_getEffectRuleScheduled: false,
/**
* getEffectRule 批量回填时 el-select/el-input 仍会 dispatch 表单变更并触发校验;
* Element 2.13 的 el-select 无 validate-event,async-validator 在开发环境会 console.warn。
* 回填期间临时清空下方费用类 el-form-item 的 rules,避免控制台噪音(保存时仍会整表 validate)。
*/
_suppressEffectRuleFormDispatch: false,
/**
* 切 Tab 时 persist 改 rules 与 pane 变更多会并发/紧挨触发多次 getEffectRule;
* 若某次先 finally 把 _suppressEffectRuleFormDispatch 置 false,另一次仍在回填则会误校验。用计数仅最后一次结束再关闭。
*/
_getEffectRuleInFlight: 0,
/**
* validateFormOnly / handleConfirm 等需整表 el-form 标红时,getEffectRule 也会 _suppressEffectRuleFormDispatch;
* 若此期间 rules 被清空,Element 2 在异步回填结束后仍可能不展示字段错误。为 true 时仍下发 rules,与纯回填分流。
*/
_bypassRuleSuppressForValidation: false
}
},
computed: {
...mapGetters("FinancialRules", {
goodsSourceReconciliationSet: "goodsSourceReconciliationSet"
}),
routerInfo() {
const inj = this.financialRulesEnv
if (inj && inj.routerInfo) return inj.routerInfo
return {}
},
goodsList() {
return (this.selectionContext && this.selectionContext.goodsList) || []
},
goodsSelectList() {
return (this.selectionContext && this.selectionContext.goodsSelectList) || []
},
tabindex() {
const t = this.paneContext && this.paneContext.tabindex
return t != null ? t : 0
},
/** 与财务规则页一致:优先 paneContext.paneIndex,否则回退 tabindex */
paneIndex() {
const p = this.paneContext
if (p && p.paneIndex != null) return p.paneIndex
return this.tabindex
},
/**
* 回填中 rulesWhenEffectRuleActive 返回空 rules,不触发表单校验;勿再与 el-form-item 的 required 同挂,
* 否则 getRules 会拼入无 message 的 { required: true },出现英文 `categoryType is required` 且与自定义 message 重复。
*/
goodsTypeGroupReconciliationRules() {
const r = this.pageContext && this.pageContext.goodsTypeGroupReconciliationRules
return r != null ? r : []
},
queryFeeCategoryByTypeFlow() {
return (this.pageContext && this.pageContext.queryFeeCategoryByTypeFlow) || []
},
queryFeeCategoryByTypeServe() {
return (this.pageContext && this.pageContext.queryFeeCategoryByTypeServe) || []
},
queryFeeCategoryByTypePlatform() {
return (this.pageContext && this.pageContext.queryFeeCategoryByTypePlatform) || []
},
phantomFullCategoryRule() {
return this.paneContext && this.paneContext.phantomFullCategoryRule
},
upgradeGoodsList() {
return (this.selectionContext && this.selectionContext.upgradeGoodsList) || []
},
packageGoodsList() {
return (this.selectionContext && this.selectionContext.packageGoodsList) || []
},
selectUpgradeGoodsList() {
return (this.selectionContext && this.selectionContext.selectUpgradeGoodsList) || []
},
selectPackageGoodsList() {
return (this.selectionContext && this.selectionContext.selectPackageGoodsList) || []
},
// 不可选择的商品分类
disabledGoodsTypeList() {
// 根据区别已选的过滤出该组件自己勾选的 剩下的就是其他组件选的 要禁用
......@@ -989,7 +1034,7 @@ export default {
filterPackageGoodsItem(item, list) {
return list.findIndex((el) => el.packageCode == item.packageCode) != -1
},
filerPlaceName(value) {
filterPlaceName(value) {
// value? :''
if (!value) return ""
return value == 3 || value == 10 ? "请输入金额" : "请输入比例"
......@@ -1020,9 +1065,18 @@ export default {
return item
}
})
this.$emit("deleteGoodsTypeItem", deleteItem)
this.emitClassificationChange(
CLASSIFICATION_EMIT.DELETE_GOODS_TYPE_ITEM,
deleteItem
)
this.emitUserClassificationTouched()
} else {
val && this.$emit("assignGoodsTypeList", val)
val &&
this.emitClassificationChange(
CLASSIFICATION_EMIT.ASSIGN_GOODS_TYPE_LIST,
val
)
if (val) this.emitUserClassificationTouched()
}
},
deep: true
......@@ -1056,9 +1110,17 @@ export default {
return item
}
})
this.$emit("deleteUpgradeGoodsItem", deleteItem)
this.emitClassificationChange(
CLASSIFICATION_EMIT.DELETE_UPGRADE_GOODS_ITEM,
deleteItem
)
this.emitUserClassificationTouched()
} else {
this.$emit("assignUpgradeGoodsList", val)
this.emitClassificationChange(
CLASSIFICATION_EMIT.ASSIGN_UPGRADE_GOODS_LIST,
val
)
this.emitUserClassificationTouched()
}
}
},
......@@ -1076,9 +1138,17 @@ export default {
return item
}
})
this.$emit("deletePackageGoodsItem", deleteItem)
this.emitClassificationChange(
CLASSIFICATION_EMIT.DELETE_PACKAGE_GOODS_ITEM,
deleteItem
)
this.emitUserClassificationTouched()
} else {
this.$emit("assignPackageGoodsList", val)
this.emitClassificationChange(
CLASSIFICATION_EMIT.ASSIGN_PACKAGE_GOODS_LIST,
val
)
this.emitUserClassificationTouched()
}
}
},
......@@ -1093,6 +1163,10 @@ export default {
deep: true,
immediate: true
},
/** 去掉父级 :key 重挂载后,切换 Tab 依赖 pane 下标驱动回显 */
paneIndex() {
this.scheduleGetEffectRule()
},
phantomFullCategoryRule: {
handler() {
if (this.tabindex !== 0) return
......@@ -1143,6 +1217,19 @@ export default {
},
methods: {
/**
* 仅真实交互时通知父级(已移除 classificationObj deep watch);merchantCheck 提交流程以基线 diff 为准,本事件仅作 Tab 元数据等辅助。
*/
emitUserClassificationTouched() {
if (this._suppressSelectionSync) return
this.emitClassificationChange(
CLASSIFICATION_EMIT.CLASSIFICATION_TOUCHED,
this.tabindex
)
},
emitClassificationChange(type, payload) {
this.$emit("classification-change", { type, payload })
},
...mapMutations("FinancialRules", [
"setGoodsSourceReconciliation",
"delGoodsSourceReconciliation"
......@@ -1156,21 +1243,22 @@ export default {
this.copyUpgradeGoodsList = deepClone(this.upgradeGoodsList)
this.copyPackageGoodsList = deepClone(this.packageGoodsList)
// 清空 商品分类 具体商品 套餐商品
this.$emit(
"deleteSelectGoodsTypeList",
this.emitClassificationChange(
CLASSIFICATION_EMIT.DELETE_SELECT_GOODS_TYPE_LIST,
this.classificationObj.goodsTypeGroupRelations
)
this.classificationObj.goodsTypeGroupRelations = []
this.$emit(
"deleteSelectUpgradeGoodsList",
this.emitClassificationChange(
CLASSIFICATION_EMIT.DELETE_SELECT_UPGRADE_GOODS_LIST,
this.classificationObj.upgradeGoods
)
this.classificationObj.upgradeGoods = []
this.$emit(
"deleteSelectPackageGoodsList",
this.emitClassificationChange(
CLASSIFICATION_EMIT.DELETE_SELECT_PACKAGE_GOODS_LIST,
this.classificationObj.packageGoods
)
this.classificationObj.packageGoods = []
this.emitUserClassificationTouched()
},
filterEmpty(data) {
return (data ?? "") === ""
......@@ -1190,6 +1278,7 @@ export default {
""
)
}
this.emitUserClassificationTouched()
},
/**
* B2:从父级 goodsTypeGroupReconciliationRules 批量合并进大表单后,深层 el-form-item 偶发不同步;
......@@ -1231,7 +1320,7 @@ export default {
if (newValue < 0) newValue = 0
valueName.expenseCategoryValue = newValue
}
// 直接改嵌套字段已可驱动视图,无需整组件刷新
this.emitUserClassificationTouched()
},
// 获取商品数据
remoteMethod(query) {
......@@ -1334,19 +1423,12 @@ export default {
let arr = this.copyPackageGoodsList.concat(resArr)
if (defaultSelect?.length) arr = arr.concat(defaultSelect)
// this.packageGoodsList = this.unique(arr)
this.copyPackageGoodsList = this.uniquePackage(arr)
this.copyPackageGoodsList = uniquePackageByPackageCode(arr)
})
.catch(() => { })
},
uniquePackage(arr) {
const res = new Map()
return arr.filter(
(a) => !res.has(a.packageCode) && res.set(a.packageCode, 1)
)
},
goodsSelectChange(item) {
// this.$forceUpdate()
// this.$emit('assignGoodsList', this.classificationObj.goodsTypeGroupRelations)
goodsSelectChange() {
this.emitUserClassificationTouched()
},
getParams() {
const obj = deepClone(this.classificationObj)
......@@ -1460,6 +1542,7 @@ export default {
return item
})
this.$set(this.classificationObj[name][index], "children", nextChildren)
this.emitUserClassificationTouched()
},
/* 合并表头最后两项*/
headerCellStyle({ row, columnIndex }) {
......@@ -1743,84 +1826,145 @@ export default {
this.getEffectRule()
})
},
/** 整表清除校验(含 flowCostArr 等动态 prop);避免切 Tab / 回显批量赋值时 async-validator 控制台报错 */
clearEntireFormValidate() {
const form = this.$refs.classification
if (form && typeof form.clearValidate === "function") {
form.clearValidate()
}
},
/** 与 _suppressEffectRuleFormDispatch 配合,回填中不挂载 required 规则;整表 validate 时见 _bypassRuleSuppressForValidation */
rulesWhenEffectRuleActive(rules) {
if (this._suppressEffectRuleFormDispatch && !this._bypassRuleSuppressForValidation) {
return []
}
return rules
},
/**
* 对账规则回显:合并父级 goodsTypeGroupReconciliationRules 到本 Tab 的 classificationObj。
* B1:async + await,错误栈与调试体验优于 .then 链。
* 从整表 rules 数组按 tabindex 取当前槽位(含 tab0 phantom 分支);无 pane 单条时的回退路。
*/
async getEffectRule(name, value) {
await Promise.all([
this.getListPartnerMerchant(),
this.getMerchantLevelList(),
this.getListPlatformMerchant()
])
const res = deepClone(value || this.goodsTypeGroupReconciliationRules)
const that = this
if (!res || !res.length || !res[0]) {
this.flushNestedFormView()
return
}
pickRuleFromRulesArray(res) {
if (!res || !res.length || !res[0]) return null
const checkType = res[0].groupType == 1
let checkRecordItem = null
if (that.tabindex == 0 && res[0].groupType == 2) {
const draft = that.phantomFullCategoryRule
if (draft && typeof draft === "object") {
checkRecordItem = deepClone(draft)
} else {
this.flushNestedFormView()
return
if (this.tabindex == 0 && res[0].groupType == 2) {
const draft = this.phantomFullCategoryRule
return draft && typeof draft === "object" ? deepClone(draft) : null
}
const item = res[+this.tabindex - (checkType ? 0 : 1)]
return item ? deepClone(item) : null
},
/**
* 优先 pane 下发的 goodsTypeGroupReconciliationRule,否则整表 + tabindex(与财务单条驱动一致)。
*/
resolveCheckRecordItemForEffectRule(value) {
if (value != null) {
const res = deepClone(value)
if (Array.isArray(res) && res.length && res[0]) {
return this.pickRuleFromRulesArray(res)
}
} else {
checkRecordItem = res[+that.tabindex - (checkType ? 0 : 1)]
return null
}
const pane = this.paneContext
if (
pane &&
pane.goodsTypeGroupReconciliationRule != null &&
typeof pane.goodsTypeGroupReconciliationRule === "object"
) {
const pr = pane.goodsTypeGroupReconciliationRule
if (Object.keys(pr).length > 0) {
return deepClone(pr)
}
}
const res = deepClone(this.goodsTypeGroupReconciliationRules)
return this.pickRuleFromRulesArray(res)
},
/**
* 对账规则回显:合并父级规则到本 Tab 的 classificationObj。
* B1:async + await,错误栈与调试体验优于 .then 链。
*/
async getEffectRule(name, value) {
this._getEffectRuleInFlight += 1
this._suppressEffectRuleFormDispatch = true
try {
await Promise.all([
this.getListPartnerMerchant(),
this.getMerchantLevelList(),
this.getListPlatformMerchant()
])
await this.$nextTick()
this.clearEntireFormValidate()
const that = this
const checkRecordItem = this.resolveCheckRecordItemForEffectRule(value)
if (checkRecordItem) {
this._suppressSelectionSync = true
try {
that.classificationObj.categoryType =
checkRecordItem?.categoryType || ""
that.classificationObj.goodsTypeGroupRelations =
checkRecordItem?.goodsTypeGroupRelations || []
that.classificationObj.upgradeGoods =
checkRecordItem?.upgradeGoods || []
that.classificationObj.packageGoods =
checkRecordItem?.packageGoods || []
that.classificationObj.flowCostArr = that.getClassificationObjFormat(
that.classificationObj.flowCostArr,
checkRecordItem?.expenseCategoryRules || [],
"flowCost"
)
that.classificationObj.serviceCostArr =
that.getClassificationObjFormat(
that.classificationObj.serviceCostArr,
checkRecordItem?.expenseCategoryRules || [],
"serviceCost"
)
that.classificationObj.goodsSource =
checkRecordItem?.goodsSource || 1
that.classificationObj.formType = checkRecordItem?.formType || ""
that.classificationObj.groupType = checkRecordItem?.groupType || 2
that.classificationObj.platformCostArr =
that.getClassificationObjFormat(
that.classificationObj.platformCostArr,
if (checkRecordItem) {
this._suppressSelectionSync = true
try {
that.classificationObj.categoryType =
checkRecordItem?.categoryType || ""
that.classificationObj.goodsTypeGroupRelations =
checkRecordItem?.goodsTypeGroupRelations || []
that.classificationObj.upgradeGoods =
checkRecordItem?.upgradeGoods || []
that.classificationObj.packageGoods =
checkRecordItem?.packageGoods || []
that.classificationObj.flowCostArr = that.getClassificationObjFormat(
that.classificationObj.flowCostArr,
checkRecordItem?.expenseCategoryRules || [],
"platformCost"
"flowCost"
)
that.classificationObj.serviceCostArr =
that.getClassificationObjFormat(
that.classificationObj.serviceCostArr,
checkRecordItem?.expenseCategoryRules || [],
"serviceCost"
)
that.classificationObj.goodsSource =
checkRecordItem?.goodsSource || 1
that.classificationObj.formType = checkRecordItem?.formType || ""
that.classificationObj.groupType = checkRecordItem?.groupType || 2
that.classificationObj.platformCostArr =
that.getClassificationObjFormat(
that.classificationObj.platformCostArr,
checkRecordItem?.expenseCategoryRules || [],
"platformCost"
)
this.flushNestedFormView()
} finally {
this.$nextTick(() => {
this._suppressSelectionSync = false
})
}
} else {
this.flushNestedFormView()
} finally {
}
await this.$nextTick()
await this.$nextTick()
await this.$nextTick()
} finally {
this._getEffectRuleInFlight -= 1
if (this._getEffectRuleInFlight <= 0) {
this._getEffectRuleInFlight = 0
this._suppressEffectRuleFormDispatch = false
this.$nextTick(() => {
this._suppressSelectionSync = false
this.clearEntireFormValidate()
})
}
} else {
this.flushNestedFormView()
}
},
/**
* 与 getEffectRule 一致:从父级下发的 goodsTypeGroupReconciliationRules 中取「当前 Tab」对应的一条规则。
* 与 getEffectRule 一致:优先 pane 单条,再从整表按 Tab 取下标。
* 用于提交时兜底:表单里 categoryType 与真实有数据的维度不一致时,仍能从回显缓存里带出商品/品类列表。
* (与货架分账侧 this.goodsTypeGroupRules 单条回显同源。)
*/
getReconciliationRuleItemForTab() {
const pane = this.paneContext
if (
pane &&
pane.goodsTypeGroupReconciliationRule != null &&
typeof pane.goodsTypeGroupReconciliationRule === "object"
) {
const pr = pane.goodsTypeGroupReconciliationRule
if (Object.keys(pr).length > 0) return pr
}
const res = this.goodsTypeGroupReconciliationRules
if (!Array.isArray(res) || !res.length) return null
const firstIsFullCategory = res[0]?.groupType == 1
......@@ -1997,17 +2141,105 @@ export default {
packageGoods: deepClone(this.classificationObj.packageGoods || [])
}
},
/**
* 与 handleConfirm 相同前置合并,仅产出 getBackendFormat 快照,供父页纯数据校验。
*/
async getBackendFormatForValidation() {
this._bypassRuleSuppressForValidation = true
try {
await this.getEffectRule()
await this.$nextTick()
return this.getBackendFormat()
} finally {
this._bypassRuleSuppressForValidation = false
}
},
/**
* 单字段 el-form 标红(与 getReconciliationRuleValidationResult 的 fieldProp 配合)。
*/
async validateReconciliationFormField(prop) {
if (!prop) return
this._bypassRuleSuppressForValidation = true
try {
await this.getEffectRule()
await this.$nextTick()
const form = this.$refs.classification
if (!form || !form.fields) return
const has = form.fields.some((f) => f && f.prop === prop)
if (!has) return
return await new Promise((resolve) => {
form.validateField(prop, (message) => {
resolve(!!message)
})
})
} finally {
this._bypassRuleSuppressForValidation = false
}
},
/**
* 按表单项注册顺序首个失败即停,避免整表 form.validate 扫全行。
*/
async validateReconciliationFormFirstErrorOnly() {
this._bypassRuleSuppressForValidation = true
try {
await this.getEffectRule()
await this.$nextTick()
const form = this.$refs.classification
if (!form || !form.fields || !form.fields.length) return true
for (let i = 0; i < form.fields.length; i++) {
const field = form.fields[i]
const p = field.prop
if (!p || p === "empty") continue
// eslint-disable-next-line no-await-in-loop
const hasErr = await new Promise((resolve) => {
form.validateField(p, (message) => {
resolve(!!message)
})
})
if (hasErr) return false
}
return true
} finally {
this._bypassRuleSuppressForValidation = false
}
},
/**
* 仅 el-form 校验标红,不返回提交数据(需整表标红时仍可用,提交路径已优先首错/单字段)。
*/
async validateFormOnly() {
this._bypassRuleSuppressForValidation = true
try {
await this.getEffectRule()
await this.$nextTick()
await this.$nextTick()
const form = this.$refs.classification
if (!form) return false
return await new Promise((resolve) => {
form.validate((valid) => {
resolve(!!valid)
})
})
} finally {
this._bypassRuleSuppressForValidation = false
}
},
// 确定:先 await getEffectRule 合并回显,再校验(切 Tab / 懒加载时避免校验跑在合并前)
async handleConfirm() {
await this.getEffectRule()
await this.$nextTick()
const form = this.$refs.classification
if (!form) return false
return await new Promise((resolve) => {
form.validate((valid) => {
resolve(valid ? this.getBackendFormat() : false)
this._bypassRuleSuppressForValidation = true
try {
await this.getEffectRule()
await this.$nextTick()
await this.$nextTick()
const form = this.$refs.classification
if (!form) return false
return await new Promise((resolve) => {
form.validate((valid) => {
resolve(valid ? this.getBackendFormat() : false)
})
})
})
} finally {
this._bypassRuleSuppressForValidation = false
}
},
// 取消
handleReset() {
......
......@@ -456,8 +456,6 @@ export default {
// deep: true
// }
},
created() { },
mounted() { },
methods: {
// inItem() {
// const obj = deepClone(this.ledgerInfo)
......
......@@ -37,21 +37,9 @@
</span>
</p>
<div v-if="editableTabs.length" class="classificationCptContainer">
<classificationCpt ref="classificationActive" :key="editableTabsValue" :goods-list="goodsTypeGroupRelations"
:router-info="routerInfo"
:phantom-full-category-rule="activeDivisionTabIndex === 0 && hasPhantomFullCategoryTab() ? phantomFullCategoryRule : null"
:goods-type-group-reconciliation-rules="goodsTypeGroupReconciliationRules"
:goods-select-list="goodsSelectList" :query-fee-category-by-type-flow="queryFeeCategoryByTypeFlow"
:query-fee-category-by-type-serve="queryFeeCategoryByTypeServe"
:query-fee-category-by-type-platform="queryFeeCategoryByTypePlatform" :tabindex="activeDivisionTabIndex"
@assignGoodsTypeList="assignGoodsTypeList" @deleteGoodsTypeItem="deleteGoodsTypeItem"
:upgrade-goods-list="upgradeGoodsList" @deleteUpgradeGoodsItem="deleteUpgradeGoodsItem"
@assignUpgradeGoodsList="assignUpgradeGoodsList" :select-upgrade-goods-list="selectUpgradeGoodsList"
:package-goods-list="packageGoodsList" @assignPackageGoodsList="assignPackageGoodsList"
:select-package-goods-list="selectPackageGoodsList" @deletePackageGoodsItem="deletePackageGoodsItem"
@deleteSelectUpgradeGoodsList="deleteSelectUpgradeGoodsList"
@deleteSelectPackageGoodsList="deleteSelectPackageGoodsList"
@deleteSelectGoodsTypeList="deleteSelectGoodsTypeList" />
<classificationCpt ref="classificationActive"
:page-context="classificationPageContext" :selection-context="classificationSelectionContext"
:pane-context="classificationPaneContext" @classification-change="handleClassificationChange" />
</div>
</div>
<div class="check-btns">
......@@ -69,9 +57,44 @@
<script>
/**
* 商户对账编辑页(merchantCheck)
* 后续优化要点(对应规划 A 段):sceneLabel 计算属性、productType 浅监听、allSettled 并行加载、
* 费用类别 Promise.all、getAllReconciliationParams 免克隆 Tab 元数据、persist 单次深拷贝合并、
* uniqueBy 去重、errorIndex + focusTabByErrorIndex、子组件见 merchantStep/components/classificationCpt.vue(B 段)。
*
* 数据获取
* - created:getRowItem(路由 params)+ 并行 getQueryFeeCategoryByType(三路费用类别,不 await)
* - mounted:Promise.allSettled(fetchGoodsCategoryConfiguration → productType,getEffectRule → rules/tabs/formObj/baseline) + ruleAuditSituation(effectStartDate)
* - watch productType → initBaseData;仅当前 Tab 挂载 classificationCpt(ref classificationActive)
*
* 校验(保存)
* - showsmCode → verifyFormData → getReconciliationGoodsTypeGroupRules:persist 后按 diff +(有基线槽位时 touched/sessionAdded)定待校验 Tab;
* 先首遍仅缓存的 getReconciliationRuleValidationResult(无 merge/getEffectRule)首错即停,通过后再第二遍
* resolveReconciliationRulePayloadForTabValidation + getReconciliationRuleValidationResult;失败时 Toast + 单字段或首错 el-form 标红
* - checkParamsType 通过后打开验证码弹窗;失败 focusTabByErrorIndex
*
* 提交
* - codeHandleConfirm → submitFormData:再次 verifyFormData;saveRuleApi 传 goodsTypeGroupRules(增量)、deletedGroupDivisionRuleIds、
* smsCode/effectStartDate、formObj 四项费用字段、merchantId/sceneType
*
* 后续优化要点(A 段):sceneLabel、productType 浅监听、allSettled、费用 Promise.all、getAllReconciliationParams、
* persist 深拷贝、uniqueBy、errorIndex;子组件见 merchantStep/components/classificationCpt.vue(B 段)。
*
* @typedef {Object} MerchantCheckPageContext
* @property {Array} queryFeeCategoryByTypeFlow
* @property {Array} queryFeeCategoryByTypeServe
* @property {Array} queryFeeCategoryByTypePlatform
* @property {Array|Object} goodsTypeGroupReconciliationRules
* @typedef {Object} MerchantCheckSelectionContext
* @property {Array} goodsList
* @property {Array} goodsSelectList
* @property {Array} upgradeGoodsList
* @property {Array} packageGoodsList
* @property {Array} selectUpgradeGoodsList
* @property {Array} selectPackageGoodsList
* @typedef {Object} MerchantCheckPaneContext
* @property {number} paneIndex
* @property {number} tabindex
* @property {Object} tabItem
* @property {Object} classificationObjSelect
* @property {Object} goodsTypeGroupReconciliationRule
* @property {Object|null} phantomFullCategoryRule
*/
import { deepClone } from "@/common/util"
import { sceneList } from "@/common/constants"
......@@ -98,9 +121,34 @@ import {
rebuildCrossTabReconciliationSelections
} from "./utils/reconciliationShared"
import {
getReconciliationRuleValidationResult,
reconciliationRulePayloadIsSubstantive
} from "./utils/validateReconciliationRulePayload"
import {
buildReconciliationIncrementalRules,
getStableReconciliationRuleId,
mergeReconciliationRuleServerFields
} from "./utils/reconciliationIncrementalRules"
import { financialRulePayloadDeepEqual } from "../financialRules/utils/rulePayloadCanonicalCompare"
import { CLASSIFICATION_EMIT } from "../financialRules/utils/classificationEmitTypes"
import {
flatMapUpgradeGoodsFromGoodsListPage,
uniqueUpgradeGoodsById
uniqueUpgradeGoodsById,
uniquePackageByPackageCode
} from "./utils/groundingUpgradeList"
import { normalizeReconciliationRuleForCompare } from "./utils/normalizeReconciliationRuleForCompare"
import { getEffectivePhantomFullCategoryRuleRaw as resolveEffectivePhantomRaw } from "./utils/effectivePhantomReconciliationRule"
import { prepareRuleForValidation } from "../financialRules/utils/validateGoodsTypeGroupRulePayload"
import { shouldIncludeReconciliationTabForProcess } from "./utils/reconciliationSubmitTabGate"
/** 提交前与基线比对时剥离 buildReconciliationIncrementalRules 注入的 type / tabPaneIndex */
function stripReconciliationIncrementalMeta(rule) {
if (!rule || typeof rule !== "object") {
return { tabPaneIndex: undefined, payload: null }
}
const { type, tabPaneIndex, ...payload } = rule
return { tabPaneIndex, payload }
}
export default {
name: "MerchantCheck",
......@@ -115,13 +163,21 @@ export default {
sceneList,
verificationCodeVisible: false,
smsCode: "",
goodsTypeGroupRulesAll: [], // 所有的要提交的formdata goodsTypeGroupRules
/**
* 最近一次 verifyFormData 结果:增量 goodsTypeGroupRules + 全量合并视图(仅前端)。
* submitFormData 会在请求前对 incrementalRules 再按基线过滤后写入此处,与实际上报一致。
*/
reconciliationLastVerifyResult: null,
/** 本会话删除的已落库对账规则 id(与 reconciliation.saveRule 的 deletedGroupDivisionRuleIds 对齐) */
pendingDeletedGroupDivisionRuleIds: [],
editableTabsValue: "1",
addIndex: 1,
editableTabs: [
{
title: "全部品类",
name: "1"
name: "1",
classificationUserTouched: false,
sessionAdded: false
}
],
/** 全量校验失败时,首个未通过 Tab 在 editableTabs 中的下标;已用于校验循环内定位,模板未展示时可做「切 Tab / 提示」扩展 */
......@@ -144,7 +200,21 @@ export default {
goodsNameKeyword: "",
allPages: 1,
/** 占位「全部品类」tab0:无 rules[0] 行时的表单快照,供回填与防 watch 刷空(不写进 goodsTypeGroupReconciliationRules[0]) */
phantomFullCategoryRule: null
phantomFullCategoryRule: null,
/**
* getEffectRule 成功后的规则快照,用于与当前缓存比对「是否有改动」。
*/
reconciliationRulesBaseline: null,
/** provide/inject:子组件读取 routerInfo、scene(与 computed routerInfo 同步) */
financialRulesEnv: {
routerInfo: {},
scene: undefined
}
}
},
provide() {
return {
financialRulesEnv: this.financialRulesEnv
}
},
computed: {
......@@ -152,7 +222,6 @@ export default {
return parseRouteMerchantRow(this.$route.query?.params)
},
addVisible() {
// return false
// 已选中的小于全部商品即可追加
const length1 = this.goodsTypeGroupRelations.length
const length2 = this.editableTabs.length - 1
......@@ -171,6 +240,40 @@ export default {
if (key == null || key === "") return "-"
const label = this.sceneList[key]
return label != null && label !== "" ? label : "-"
},
/** @returns {MerchantCheckPageContext} */
classificationPageContext() {
return {
queryFeeCategoryByTypeFlow: this.queryFeeCategoryByTypeFlow,
queryFeeCategoryByTypeServe: this.queryFeeCategoryByTypeServe,
queryFeeCategoryByTypePlatform: this.queryFeeCategoryByTypePlatform,
goodsTypeGroupReconciliationRules: this.goodsTypeGroupReconciliationRules
}
},
classificationSelectionContext() {
return {
goodsList: this.goodsTypeGroupRelations,
goodsSelectList: this.goodsSelectList,
upgradeGoodsList: this.upgradeGoodsList,
packageGoodsList: this.packageGoodsList,
selectUpgradeGoodsList: this.selectUpgradeGoodsList,
selectPackageGoodsList: this.selectPackageGoodsList
}
},
classificationPaneContext() {
const idx = this.activeDivisionTabIndex
return {
paneIndex: idx,
tabindex: idx,
tabItem: this.editableTabs[idx] || {},
classificationObjSelect: {},
goodsTypeGroupReconciliationRule:
this.resolveReconciliationRuleForPaneIndex(idx),
phantomFullCategoryRule:
idx === 0 && this.hasPhantomFullCategoryTab()
? this.getEffectivePhantomFullCategoryRuleRaw()
: null
}
}
},
created() {
......@@ -179,7 +282,7 @@ export default {
void this.getQueryFeeCategoryByType()
},
async mounted() {
this.addContactgetReconciliationHistoryRecordApi()
this.fetchReconciliationRuleAuditSituation()
/**
* A3 策略:分类与对账规则并行加载;互不拖死。
* - 分类失败:提示,规则仍可能成功。
......@@ -201,6 +304,14 @@ export default {
}
},
watch: {
routerInfo: {
immediate: true,
handler(v) {
this.financialRulesEnv.routerInfo = v && typeof v === "object" ? v : {}
const sc = v && v.scene
this.financialRulesEnv.scene = sc != null && sc !== "" ? sc : undefined
}
},
// A2:productType 仅整表替换(见 fetchGoodsCategoryConfiguration),无需 deep,减少 initBaseData / deepClone
productType: {
handler() {
......@@ -221,6 +332,14 @@ export default {
const ref = this.$refs.classificationActive
return Array.isArray(ref) ? ref[0] : ref
},
/** 子组件 classificationObj 非 init 回填变更时上报(与 financialRules onClassificationTouched 一致)。 */
onClassificationTouched(tabIndex) {
const idx = Number(tabIndex)
if (!Number.isFinite(idx) || idx < 0 || idx >= this.editableTabs.length) return
const tab = this.editableTabs[idx]
if (!tab || String(tab.name) === "add") return
this.$set(tab, "classificationUserTouched", true)
},
/**
* 下拉切换品类:受控 el-select,先持久化旧 tab 再更新 editableTabsValue(对齐原 beforeLeave)。
*/
......@@ -265,11 +384,271 @@ export default {
return tabIndex
},
/**
* live phantom 在 getEffectRule 末尾会清空;与基线比对、resolve、子组件 props 需回落 baseline.phantomFullCategoryRule。
*/
getEffectivePhantomFullCategoryRuleRaw() {
const b = this.reconciliationRulesBaseline
return resolveEffectivePhantomRaw(
this.phantomFullCategoryRule,
b && b.phantomFullCategoryRule
)
},
/**
* 当前 Tab 槽位对应的一条对账规则(与财务 goodsTypeGroupRules[i] 同构)。
* tab0 占位用 phantomFullCategoryRule,否则取 goodsTypeGroupReconciliationRules[ruleIdx],缺省 {}。
*/
resolveReconciliationRuleForPaneIndex(idx) {
const ruleIdx = this.reconciliationRuleIndexForTabIndex(idx)
if (ruleIdx == null && idx === 0 && this.hasPhantomFullCategoryTab()) {
const p = this.getEffectivePhantomFullCategoryRuleRaw()
return p && typeof p === "object" ? p : {}
}
if (ruleIdx != null && Array.isArray(this.goodsTypeGroupReconciliationRules)) {
const r = this.goodsTypeGroupReconciliationRules[ruleIdx]
return r && typeof r === "object" ? r : {}
}
return {}
},
/**
* tab0「全部品类」仅占位:首条接口规则为特殊品类时,tab0 无 goodsTypeGroupReconciliationRules 行。
*/
hasPhantomFullCategoryTab() {
return this.reconciliationRuleIndexForTabIndex(0) == null
},
/**
* 与 getReconciliationGoodsTypeGroupRules 内「从缓存拼规则」一致,供基线比对复用。
*/
buildRuleFromCacheForTabIndex(ti) {
const ruleIdx = this.reconciliationRuleIndexForTabIndex(ti)
let raw = null
if (ruleIdx == null && ti === 0 && this.hasPhantomFullCategoryTab()) {
raw = this.getEffectivePhantomFullCategoryRuleRaw()
} else if (ruleIdx != null) {
raw = this.goodsTypeGroupReconciliationRules[ruleIdx]
}
if (!raw || typeof raw !== "object") return null
const o = deepClone(raw)
fillDjGoodsTypeGroupRelations(o)
return o
},
/**
* 与 financialRules buildMergedClassificationPayloadAtIndex 对位:仅当该 Tab 的 classificationCpt 已挂载时,
* await getEffectRule 后再 getBackendFormat,并与对账缓存行浅合并为 next;无 ref 返回 null(校验退回 resolve 内纯缓存)。
*/
async buildMergedReconciliationPayloadAtTabIndex(idx) {
if (idx == null || idx < 0 || idx >= this.editableTabs.length) return null
const tabPane = this.editableTabs[idx]
if (!tabPane) return null
const node = this.getClassificationRef(tabPane.name)
if (
!node
|| typeof node.getBackendFormat !== "function"
|| typeof node.getEffectRule !== "function"
) {
return null
}
const ruleIdx = this.reconciliationRuleIndexForTabIndex(idx)
let prevStored
if (ruleIdx == null) {
if (idx === 0 && this.hasPhantomFullCategoryTab()) {
const eff = this.getEffectivePhantomFullCategoryRuleRaw()
prevStored = eff && typeof eff === "object" ? eff : {}
} else {
return null
}
} else {
prevStored = this.goodsTypeGroupReconciliationRules[ruleIdx] || {}
}
try {
await node.getEffectRule()
await this.$nextTick()
const raw = node.getBackendFormat()
return { next: deepClone({ ...prevStored, ...raw }), prevStored }
} catch (e) {
console.warn("buildMergedReconciliationPayloadAtTabIndex", e)
return null
}
},
/**
* 纯数据校验用 payload:与 financial resolveRulePayloadForTabValidation 对位。
* 合并结果与缓存经归一化后一致时用缓存;无 ref 时仅用缓存(依赖 persist / 切 Tab 时已写入 goodsTypeGroupReconciliationRules)。
*/
async resolveReconciliationRulePayloadForTabValidation(tabindex) {
const ruleIdx = this.reconciliationRuleIndexForTabIndex(tabindex)
let cachedRaw = {}
if (ruleIdx == null && tabindex === 0 && this.hasPhantomFullCategoryTab()) {
const eff = this.getEffectivePhantomFullCategoryRuleRaw()
cachedRaw = eff && typeof eff === "object" ? eff : {}
} else if (ruleIdx != null) {
cachedRaw = this.goodsTypeGroupReconciliationRules[ruleIdx] || {}
}
const filledFromCache = () =>
fillDjGoodsTypeGroupRelations(deepClone(cachedRaw))
const built = await this.buildMergedReconciliationPayloadAtTabIndex(tabindex)
if (!built) {
return filledFromCache()
}
const { next, prevStored } = built
if (prevStored == null || typeof prevStored !== "object") {
return fillDjGoodsTypeGroupRelations(deepClone(next))
}
const nextNorm = normalizeReconciliationRuleForCompare(
fillDjGoodsTypeGroupRelations(deepClone(next))
)
const prevNorm = normalizeReconciliationRuleForCompare(
fillDjGoodsTypeGroupRelations(deepClone(prevStored))
)
if (financialRulePayloadDeepEqual(nextNorm, prevNorm)) {
return filledFromCache()
}
return fillDjGoodsTypeGroupRelations(deepClone(next))
},
/** 当前 Tab 槽位规则是否与进入页时的基线一致(fillDj 后深度比较) */
reconciliationTabDiffersFromBaseline(ti) {
const b = this.reconciliationRulesBaseline
if (!b) return false
let prevRaw = null
const ruleIdx = this.reconciliationRuleIndexForTabIndex(ti)
if (ruleIdx == null && ti === 0 && this.hasPhantomFullCategoryTab()) {
prevRaw = b.phantomFullCategoryRule
} else if (ruleIdx != null && Array.isArray(b.goodsTypeGroupReconciliationRules)) {
prevRaw = b.goodsTypeGroupReconciliationRules[ruleIdx]
}
const cur = this.buildRuleFromCacheForTabIndex(ti)
if (!prevRaw) {
if (!cur) return false
return reconciliationRulePayloadIsSubstantive(cur)
}
const prevNorm = normalizeReconciliationRuleForCompare(
fillDjGoodsTypeGroupRelations(deepClone(prevRaw))
)
const curNorm = cur
? normalizeReconciliationRuleForCompare(cur)
: null
if (!curNorm && !prevNorm) return false
if (!curNorm || !prevNorm) return true
return !financialRulePayloadDeepEqual(curNorm, prevNorm)
},
/**
* 基线中是否存在与当前 Tab 可成对比对的行(含 tab0 phantom);与 reconciliationTabDiffersFromBaseline 的 prevRaw 解析一致。
*/
reconciliationBaselineHasSlotForTabIndex(ti) {
const b = this.reconciliationRulesBaseline
if (!b) return false
let prevRaw = null
const ruleIdx = this.reconciliationRuleIndexForTabIndex(ti)
if (ruleIdx == null && ti === 0 && this.hasPhantomFullCategoryTab()) {
prevRaw = b.phantomFullCategoryRule
} else if (ruleIdx != null && Array.isArray(b.goodsTypeGroupReconciliationRules)) {
prevRaw = b.goodsTypeGroupReconciliationRules[ruleIdx]
}
return !!(prevRaw && typeof prevRaw === "object")
},
/**
* 校验通过后的单条规则快照是否与进入页基线一致(用于收缩 goodsTypeGroupRules 增量)。
*/
reconciliationSnapshotEqualsBaseline(ti, snapshot) {
const b = this.reconciliationRulesBaseline
if (!b || !snapshot || typeof snapshot !== "object") return false
let prevRaw = null
const ruleIdx = this.reconciliationRuleIndexForTabIndex(ti)
if (ruleIdx == null && ti === 0 && this.hasPhantomFullCategoryTab()) {
prevRaw = b.phantomFullCategoryRule
} else if (ruleIdx != null && Array.isArray(b.goodsTypeGroupReconciliationRules)) {
prevRaw = b.goodsTypeGroupReconciliationRules[ruleIdx]
}
if (!prevRaw) {
if (!reconciliationRulePayloadIsSubstantive(snapshot)) return true
return false
}
const curNorm = normalizeReconciliationRuleForCompare(
fillDjGoodsTypeGroupRelations(deepClone(snapshot))
)
const prevNorm = normalizeReconciliationRuleForCompare(
fillDjGoodsTypeGroupRelations(deepClone(prevRaw))
)
if (!curNorm && !prevNorm) return true
if (!curNorm || !prevNorm) return false
return financialRulePayloadDeepEqual(curNorm, prevNorm)
},
/**
* 校验通过的 Tab 中下,仅「快照与基线仍不一致」的进入提交(无基线时仅 sessionAdded)。
*/
filterIndicesToSubmitIncremental(dirtyIndices, validatedByTabIndex) {
return dirtyIndices.filter((ti) => {
const rule = validatedByTabIndex[ti]
if (!rule || typeof rule !== "object") return false
if (!this.reconciliationRulesBaseline) {
return this.editableTabs[ti]?.sessionAdded === true
&& reconciliationRulePayloadIsSubstantive(rule)
}
return !this.reconciliationSnapshotEqualsBaseline(ti, rule)
})
},
/**
* 提交前再收敛 goodsTypeGroupRules:去掉与基线一致的行(payload 不含 type/tabPaneIndex)。
* 无基线时仅保留 sessionAdded 的 Tab,与 filterIndicesToSubmitIncremental 一致。
*/
filterIncrementalRulesForSubmit(incrementalRules) {
if (!Array.isArray(incrementalRules) || incrementalRules.length === 0) return []
const out = []
for (let i = 0; i < incrementalRules.length; i++) {
const rule = incrementalRules[i]
const { tabPaneIndex, payload } = stripReconciliationIncrementalMeta(rule)
const ti = Number(tabPaneIndex)
if (
!Number.isFinite(ti)
|| ti < 0
|| ti >= this.editableTabs.length
) {
console.warn("[MerchantCheck] incremental rule invalid tabPaneIndex", rule)
continue
}
if (!payload || typeof payload !== "object") continue
if (!this.reconciliationRulesBaseline) {
if (
this.editableTabs[ti]?.sessionAdded === true
&& reconciliationRulePayloadIsSubstantive(payload)
) {
out.push(rule)
}
continue
}
if (!this.reconciliationSnapshotEqualsBaseline(ti, payload)) {
out.push(rule)
}
}
return out
},
/**
* 序列化前再压一遍归一化(去掉 merchant / 空 children / 空数组键等)。
* forCompare: false 保留 expenseCategoryRules 的表单顺序,排序仅用于基线 deepEqual。
*/
shapeGoodsTypeGroupRulesForApi(rules) {
if (!Array.isArray(rules) || !rules.length) return []
return rules.map((rule) => {
const type = rule.type
const tabPaneIndex = rule.tabPaneIndex
const { payload } = stripReconciliationIncrementalMeta(rule)
const body = normalizeReconciliationRuleForCompare(
payload && typeof payload === "object" ? payload : {},
{ forCompare: false }
)
return { ...body, type, tabPaneIndex }
})
},
/**
* 相对进入页有改动或可提交关注的 Tab 下标(与基线比对;提交增量见 getReconciliationGoodsTypeGroupRules)。
*/
getReconciliationChangedTabIndices() {
const out = []
for (let ti = 0; ti < this.editableTabs.length; ti++) {
if (this.reconciliationTabDiffersFromBaseline(ti)) out.push(ti)
}
return out
},
persistClassificationTabByPaneName(paneName) {
if (paneName == null || paneName === "" || paneName === "add") return
const idx = this.editableTabs.findIndex(
......@@ -323,32 +702,13 @@ export default {
this.goodsTypeGroupReconciliationRules,
{
includePhantom: this.hasPhantomFullCategoryTab(),
phantomRule: this.phantomFullCategoryRule
phantomRule: this.getEffectivePhantomFullCategoryRuleRaw()
}
)
this.goodsSelectList = sel.goodsSelectList
this.selectUpgradeGoodsList = sel.selectUpgradeGoodsList
this.selectPackageGoodsList = sel.selectPackageGoodsList
},
/** 判断单条对账规则是否像接口回显的完整数据(新增 Tab 空壳为 false) */
hasEchoedReconciliationRulePayload(rule) {
if (!rule || typeof rule !== "object") return false
if (
Array.isArray(rule.expenseCategoryRules) &&
rule.expenseCategoryRules.length > 0
) {
if (rule.groupType == 2 && rule.goodsSource == 1) {
const rel =
(Array.isArray(rule.goodsTypeGroupRelations) &&
rule.goodsTypeGroupRelations.length) ||
(Array.isArray(rule.upgradeGoods) && rule.upgradeGoods.length) ||
(Array.isArray(rule.packageGoods) && rule.packageGoods.length)
return !!rel
}
return true
}
return false
},
/**
* 收集所有 Tab 的原始参数(不做 handleConfirm),删除 Tab 等与财务 getAllParams 对齐。
*/
......@@ -380,15 +740,42 @@ export default {
return rows
},
/**
* 按 Tab 顺序激活并校验(与财务 getGoodsTypeGroupRules 一致),返回每条规则或 false。
* 对账数据校验未通过:切 Tab、提示、单字段或首错 el-form 标红(不整表 form.validate)。
*/
async applyReconciliationDataValidationFailure(pane, tabindex, tab, vr) {
this.errorIndex = tabindex
if (tab) tab.validError = "Y"
this.editableTabsValue = pane.name
await this.$nextTick()
await this.$nextTick()
this.$message.warning(vr.message)
const nodeMounted = this.getClassificationRef(pane.name)
if (!nodeMounted) return
await this.$nextTick()
if (
vr.fieldProp
&& typeof nodeMounted.validateReconciliationFormField === "function"
) {
await nodeMounted.validateReconciliationFormField(vr.fieldProp)
} else if (
typeof nodeMounted.validateReconciliationFormFirstErrorOnly === "function"
) {
await nodeMounted.validateReconciliationFormFirstErrorOnly()
}
},
/**
* 对账规则校验与组装:persist 后 reconciliationTabDiffersFromBaseline 为 true 的 Tab 中,若基线已有可对齐行,
* 需 classificationUserTouched 或 sessionAdded(避免接口行与 getBackendFormat 合并假脏全量进增量);无基线槽位时仍只依赖 diff/substantive 语义。
* 本轮会话新增 Tab(sessionAdded)即使与基线 diff 为 false(如未填完),也须进校验循环,由 getReconciliationRuleValidationResult 拦截。
* 首遍仅 buildRuleFromCacheForTabIndex + getReconciliationRuleValidationResult,无 merge/getEffectRule;
* 全过后第二遍 resolveReconciliationRulePayloadForTabValidation + 校验并组快照。失败时切 Tab + 轻量 el-form 标红。
* 首段 persist 后仍无待校验 Tab 则增量为空。
*
* @returns {Promise<{ ok: boolean, incrementalRules: Array, fullMergedRules: Array|null, firstErrorTabIndex?: number }>}
*/
async getReconciliationGoodsTypeGroupRules(list) {
const panes = filterDivisionTabPanes(list)
/**
* tab0 固定为「全部品类」:须参与 handleConfirm,否则费用项未填也会被 el-form 跳过(误通过)。
* 占位全部(接口首条为特殊)仍无 rules 行,persist 仍靠 reconciliationRuleIndexForTabIndex 跳过写缓存。
*/
const panesToValidate = panes.filter((pane) => {
const eligiblePanes = panes.filter((pane) => {
const ti = this.editableTabs.findIndex(
(t) => String(t.name) === String(pane.name)
)
......@@ -396,82 +783,219 @@ export default {
return this.reconciliationRuleIndexForTabIndex(ti) != null
})
const prevTabName = this.editableTabsValue
const goodsTypeGroupRules = []
for (let index = 0; index < panesToValidate.length; index++) {
const nextName = panesToValidate[index].name
const cur = this.editableTabsValue
const getTabIndexForPane = (pane) =>
this.editableTabs.findIndex(
(t) => String(t.name) === String(pane.name)
)
this.persistActiveClassificationTab()
await this.$nextTick()
const mergeFullRules = (validatedByTabIndex) => {
return eligiblePanes.map((pane) => {
const ti = getTabIndexForPane(pane)
if (ti < 0) return false
const snap = validatedByTabIndex[ti]
if (snap != null) return snap
const fromCache = this.buildRuleFromCacheForTabIndex(ti)
return fromCache || false
})
}
let indicesToProcess = []
const tabCount = this.editableTabs.length
for (let i = 0; i < tabCount; i++) {
const tab = this.editableTabs[i]
if (!tab || String(tab.name) === "add") continue
const differs = this.reconciliationTabDiffersFromBaseline(i)
const isSessionAdded = tab.sessionAdded === true
if (!differs && !isSessionAdded) continue
if (differs) {
if (
!shouldIncludeReconciliationTabForProcess({
hasBaselineSlot: this.reconciliationBaselineHasSlotForTabIndex(i),
classificationUserTouched: tab.classificationUserTouched === true,
sessionAdded: isSessionAdded
})
) {
continue
}
}
indicesToProcess.push(i)
}
indicesToProcess = [...new Set(indicesToProcess)]
const ai = this.activeDivisionTabIndex
if (indicesToProcess.length > 1 && ai >= 0 && indicesToProcess.includes(ai)) {
indicesToProcess = [
ai,
...indicesToProcess.filter((x) => x !== ai).sort((a, b) => a - b)
]
} else {
indicesToProcess.sort((a, b) => a - b)
}
/** 无待提交 Tab:不跑分类校验;增量为空数组 */
if (indicesToProcess.length === 0) {
const fullMergedRules = mergeFullRules({})
const allPassed =
fullMergedRules.length > 0 &&
fullMergedRules.every((item) => item)
if (allPassed) {
if (this.hasPhantomFullCategoryTab()) {
fullMergedRules.slice(1).forEach((rule, i) => {
if (rule && typeof rule === "object") {
this.$set(
this.goodsTypeGroupReconciliationRules,
i,
deepClone(rule)
)
}
})
const fullSnap = fullMergedRules[0]
if (fullSnap && typeof fullSnap === "object") {
this.phantomFullCategoryRule = deepClone(fullSnap)
}
} else {
fullMergedRules.forEach((rule, i) => {
if (rule && typeof rule === "object") {
this.$set(
this.goodsTypeGroupReconciliationRules,
i,
deepClone(rule)
)
}
})
}
}
if (
cur != null &&
String(cur) !== "" &&
String(cur) !== "add" &&
String(cur) !== String(nextName)
allPassed &&
prevTabName != null &&
String(prevTabName) !== "add"
) {
this.persistClassificationTabByPaneName(cur)
this.editableTabsValue = prevTabName
await this.$nextTick()
}
this.editableTabsValue = nextName
await this.$nextTick()
/**
* A5:第二次 $nextTick — 父页 shouldRenderClassificationTab 懒挂载子组件,需多等一轮再取 ref / handleConfirm。
* 若减为一次,需在多 Tab + 慢设备上回归「保存 / 校验」是否偶发拿不到实例。
*/
await this.$nextTick()
this.rebuildCrossTabGoodsSelectionsFromRules()
let firstErrorTabIndex
if (!allPassed) {
const failI = fullMergedRules.findIndex((item) => !item)
if (failI >= 0 && eligiblePanes[failI]) {
firstErrorTabIndex = getTabIndexForPane(eligiblePanes[failI])
if (firstErrorTabIndex >= 0) this.errorIndex = firstErrorTabIndex
}
}
return {
ok: allPassed,
incrementalRules: [],
fullMergedRules,
firstErrorTabIndex
}
}
const tabindex = this.editableTabs.findIndex(
(item) => item.name == panesToValidate[index].name
)
const node = this.getClassificationRef(panesToValidate[index].name)
const ruleIdx = this.reconciliationRuleIndexForTabIndex(tabindex)
const cachedRule =
ruleIdx == null
? null
: this.goodsTypeGroupReconciliationRules[ruleIdx]
const tab = this.editableTabs[tabindex]
const validatedByTabIndex = {}
let failedTabIndex = -1
let res
if (node) {
res = await node.handleConfirm()
} else if (cachedRule && typeof cachedRule === "object") {
const allowByEditEcho =
this.hasEchoedReconciliationRulePayload(cachedRule)
res = allowByEditEcho ? deepClone(cachedRule) : false
} else {
res = false
for (let v = 0; v < indicesToProcess.length; v++) {
const tabindex = indicesToProcess[v]
const pane = eligiblePanes.find((p) => getTabIndexForPane(p) === tabindex)
if (!pane) continue
const tab = this.editableTabs[tabindex]
const fromCache = this.buildRuleFromCacheForTabIndex(tabindex)
const cacheVr = getReconciliationRuleValidationResult(fromCache || {})
if (!cacheVr.ok) {
failedTabIndex = tabindex
await this.applyReconciliationDataValidationFailure(
pane,
tabindex,
tab,
cacheVr
)
break
}
}
if (tab) {
tab.validError = res ? "N" : "Y"
}
if (res && typeof res === "object") {
fillDjGoodsTypeGroupRelations(res)
/**
* getBackendFormat 内费用节点与子组件 classificationObj 共用引用;切到下一 Tab 会卸载当前实例,
* 若不深拷贝则已 push 的首条特殊规则等会出现嵌套被清空、提交空值到后端。
*/
goodsTypeGroupRules.push(deepClone(res))
} else {
goodsTypeGroupRules.push(res)
for (let v = 0; v < indicesToProcess.length && failedTabIndex < 0; v++) {
const tabindex = indicesToProcess[v]
const pane = eligiblePanes.find((p) => getTabIndexForPane(p) === tabindex)
if (!pane) continue
const tab = this.editableTabs[tabindex]
const rulePayload =
await this.resolveReconciliationRulePayloadForTabValidation(tabindex)
const payloadVr = getReconciliationRuleValidationResult(rulePayload)
if (!payloadVr.ok) {
failedTabIndex = tabindex
await this.applyReconciliationDataValidationFailure(
pane,
tabindex,
tab,
payloadVr
)
break
}
if (!res) {
this.errorIndex = tabindex
for (let j = index + 1; j < panesToValidate.length; j++) {
goodsTypeGroupRules.push(false)
if (tab) tab.validError = "N"
let snap = prepareRuleForValidation(rulePayload)
const cachedForId = this.buildRuleFromCacheForTabIndex(tabindex)
snap = mergeReconciliationRuleServerFields(snap, cachedForId)
validatedByTabIndex[tabindex] = snap
}
if (failedTabIndex >= 0) {
this.errorIndex = failedTabIndex
const failEligibleIdx = eligiblePanes.findIndex(
(p) => getTabIndexForPane(p) === failedTabIndex
)
const out = []
for (let i = 0; i < eligiblePanes.length; i++) {
const ti = getTabIndexForPane(eligiblePanes[i])
if (failEligibleIdx < 0) {
out.push(false)
continue
}
break
if (i < failEligibleIdx) {
if (validatedByTabIndex[ti] != null) {
out.push(validatedByTabIndex[ti])
} else {
const c = this.buildRuleFromCacheForTabIndex(ti)
out.push(c || false)
}
} else if (i === failEligibleIdx) {
out.push(false)
} else {
out.push(false)
}
}
this.rebuildCrossTabGoodsSelectionsFromRules()
return {
ok: false,
incrementalRules: [],
fullMergedRules: out,
firstErrorTabIndex: failedTabIndex
}
}
const fullMergedRules = mergeFullRules(validatedByTabIndex)
const allPassed =
goodsTypeGroupRules.length > 0 &&
goodsTypeGroupRules.every((item) => item)
fullMergedRules.length > 0 &&
fullMergedRules.every((item) => item)
const indicesToSubmit = allPassed
? this.filterIndicesToSubmitIncremental(
indicesToProcess,
validatedByTabIndex
)
: []
const incrementalRules = allPassed && indicesToSubmit.length
? buildReconciliationIncrementalRules(
validatedByTabIndex,
indicesToSubmit
)
: []
if (allPassed) {
/**
* 回写父级缓存:与 goodsTypeGroupReconciliationRules 下标对齐。
* 占位全部时校验结果为 [全部快照, 特殊1, 特殊2…],缓存仍为 [特殊1, 特殊2…],不得把全部写入 index0。
* 全部快照仅存在于本次返回值 / 提交;合成空全部已改为由用户在校验 tab0 时真实填写,不再 unshift 占位对象。
*/
if (this.hasPhantomFullCategoryTab()) {
goodsTypeGroupRules.slice(1).forEach((rule, i) => {
fullMergedRules.slice(1).forEach((rule, i) => {
if (rule && typeof rule === "object") {
this.$set(
this.goodsTypeGroupReconciliationRules,
......@@ -480,12 +1004,12 @@ export default {
)
}
})
const fullSnap = goodsTypeGroupRules[0]
const fullSnap = fullMergedRules[0]
if (fullSnap && typeof fullSnap === "object") {
this.phantomFullCategoryRule = deepClone(fullSnap)
}
} else {
goodsTypeGroupRules.forEach((rule, i) => {
fullMergedRules.forEach((rule, i) => {
if (rule && typeof rule === "object") {
this.$set(
this.goodsTypeGroupReconciliationRules,
......@@ -501,19 +1025,28 @@ export default {
prevTabName != null &&
String(prevTabName) !== "add"
) {
/**
* 已 allPassed 时缓存已由上一步与本次校验结果对齐;勿再 persist 当前 Tab——
* 虚拟 Tab 下该 ref 可能已卸载或空实例,getBackendFormat 会覆盖掉首条等特殊规则。
*/
this.editableTabsValue = prevTabName
await this.$nextTick()
}
this.rebuildCrossTabGoodsSelectionsFromRules()
return goodsTypeGroupRules
let firstErrorTabIndex
if (!allPassed) {
const failI = fullMergedRules.findIndex((item) => !item)
if (failI >= 0 && eligiblePanes[failI]) {
firstErrorTabIndex = getTabIndexForPane(eligiblePanes[failI])
if (firstErrorTabIndex >= 0) this.errorIndex = firstErrorTabIndex
}
}
return {
ok: allPassed,
incrementalRules,
fullMergedRules,
firstErrorTabIndex
}
},
addContactgetReconciliationHistoryRecordApi() {
// 根据历史记录 处理财务生效记录的选项
/** 拉取对账规则生效态:是否可立即生效(effectStartDate),内部 ruleAuditSituation */
fetchReconciliationRuleAuditSituation() {
const { merchantId, scene: sceneType } = this.routerInfo
ruleAuditSituation({
merchantId,
......@@ -581,6 +1114,42 @@ export default {
initBaseData() {
this.goodsTypeGroupRelations = deepClone(this.productType)
},
handleClassificationChange({ type, payload }) {
switch (type) {
case CLASSIFICATION_EMIT.ASSIGN_GOODS_TYPE_LIST:
this.assignGoodsTypeList(payload)
break
case CLASSIFICATION_EMIT.DELETE_GOODS_TYPE_ITEM:
this.deleteGoodsTypeItem(payload)
break
case CLASSIFICATION_EMIT.ASSIGN_UPGRADE_GOODS_LIST:
this.assignUpgradeGoodsList(payload)
break
case CLASSIFICATION_EMIT.DELETE_UPGRADE_GOODS_ITEM:
this.deleteUpgradeGoodsItem(payload)
break
case CLASSIFICATION_EMIT.ASSIGN_PACKAGE_GOODS_LIST:
this.assignPackageGoodsList(payload)
break
case CLASSIFICATION_EMIT.DELETE_PACKAGE_GOODS_ITEM:
this.deletePackageGoodsItem(payload)
break
case CLASSIFICATION_EMIT.DELETE_SELECT_GOODS_TYPE_LIST:
this.deleteSelectGoodsTypeList(payload)
break
case CLASSIFICATION_EMIT.DELETE_SELECT_UPGRADE_GOODS_LIST:
this.deleteSelectUpgradeGoodsList(payload)
break
case CLASSIFICATION_EMIT.DELETE_SELECT_PACKAGE_GOODS_LIST:
this.deleteSelectPackageGoodsList(payload)
break
case CLASSIFICATION_EMIT.CLASSIFICATION_TOUCHED:
this.onClassificationTouched(payload)
break
default:
break
}
},
assignGoodsTypeList(list) {
this.goodsSelectList = uniqueBy(
[...this.goodsSelectList, ...list],
......@@ -647,17 +1216,11 @@ export default {
})
let arr = this.packageGoodsList.concat(resArr)
if (defaultSelect?.length) arr = arr.concat(defaultSelect)
this.packageGoodsList = this.uniquePackage(arr)
this.packageGoodsList = uniquePackageByPackageCode(arr)
})
.catch(() => { })
},
uniquePackage(arr) {
const res = new Map()
return arr.filter(
(a) => !res.has(a.packageCode) && res.set(a.packageCode, 1)
)
},
addTab() {
const length = this.editableTabs.length
this.addIndex = length
......@@ -670,7 +1233,9 @@ export default {
this.editableTabs.push({
title: "特殊品类" + this.addIndex++,
name: newTabIndex
name: newTabIndex,
classificationUserTouched: false,
sessionAdded: true
})
const newIdx = this.editableTabs.length - 1
......@@ -723,6 +1288,20 @@ export default {
)
if (removeIdx < 0) return false
const removedTab = tabs[removeIdx]
const ruleIdxRemoved = this.reconciliationRuleIndexForTabIndex(removeIdx)
if (
removedTab
&& removedTab.sessionAdded !== true
&& ruleIdxRemoved != null
) {
const cached = this.goodsTypeGroupReconciliationRules[ruleIdxRemoved]
const rid = getStableReconciliationRuleId(cached)
if (rid) {
this.pendingDeletedGroupDivisionRuleIds.push(rid)
}
}
let activeIdx = tabs.findIndex(
(item) => String(item.name) === String(this.editableTabsValue)
)
......@@ -738,6 +1317,10 @@ export default {
const goodsTypeGroupRules = this.getAllReconciliationParams()
const upgradeArr = []
const packageArr = []
const prevTabsMeta = this.editableTabs.map((t) => ({
classificationUserTouched: !!t.classificationUserTouched,
sessionAdded: !!t.sessionAdded
}))
this.editableTabs = []
goodsTypeGroupRules.splice(removeIdx, 1)
// this.$set(this.goodsTypeGroupReconciliationRules, goodsTypeGroupRules)
......@@ -750,9 +1333,15 @@ export default {
this.editableTabsValue = (newActiveIndex + 1).toString()
typeList.forEach((item, index) => {
const oldIdx = index < removeIdx ? index : index + 1
const meta = prevTabsMeta[oldIdx]
const classificationUserTouched = !!(meta && meta.classificationUserTouched)
const sessionAdded = !!(meta && meta.sessionAdded)
this.editableTabs[index] = {
title: index ? "特殊品类" + index : "全部品类",
name: (index + 1).toString()
name: (index + 1).toString(),
classificationUserTouched,
sessionAdded
}
applyGoodsTypeGroupRelationBranches(
item,
......@@ -826,7 +1415,10 @@ export default {
getRowItem() {
this.merchantRow = parseRouteMerchantRow(this.$route.query?.params)
},
// 对账item的详情
/**
* 拉取对账生效规则(仅进入页 / mounted 等调用 getEffectRuleApi)。
* 提交保存时不会走本方法;子组件 classificationCpt.getEffectRule 是本地合并回显,非接口请求。
*/
async getEffectRule() {
const params = {
merchantId: this.merchantRow.merchantId,
......@@ -854,7 +1446,9 @@ export default {
(typeList[0].groupType == 2 ? index + 1 : index),
name: (
(typeList[0].groupType == 2 ? index + 1 : index) + 1
).toString()
).toString(),
classificationUserTouched: false,
sessionAdded: false
})
}
......@@ -874,27 +1468,50 @@ export default {
this.getSelectingListPackage()
this.rebuildCrossTabGoodsSelectionsFromRules()
}
this.editableTabs.forEach((tab) => {
this.$set(tab, "classificationUserTouched", false)
this.$set(tab, "sessionAdded", false)
})
this.reconciliationRulesBaseline = {
goodsTypeGroupReconciliationRules: deepClone(
this.goodsTypeGroupReconciliationRules || []
),
phantomFullCategoryRule: this.phantomFullCategoryRule
? deepClone(this.phantomFullCategoryRule)
: null
}
/** 与基线比对、resolve、跨 Tab 聚合见 getEffectivePhantomFullCategoryRuleRaw(回落 baseline.phantom) */
this.phantomFullCategoryRule = null
this.pendingDeletedGroupDivisionRuleIds = []
},
checkParamsType(array) {
const flag = array.every((item) => item)
return flag
/**
* 校验结果:支持增量对象 `{ ok, incrementalRules }` 或旧版「每 Tab 一项」数组。
*/
checkParamsType(obj) {
if (!obj) return false
if (typeof obj === "object" && "ok" in obj) {
if (obj.ok === false) return false
const inc = obj.incrementalRules
if (Array.isArray(inc)) {
if (inc.length === 0) return true
return inc.every((item) => item && typeof item === "object")
}
return true
}
if (Array.isArray(obj)) {
return obj.length > 0 && obj.every((item) => item)
}
return false
},
// 显示smcode弹框
async showsmCode() {
// this.$refs.classification.validate(async (valid) => {
// if (valid) {
// this.errorIndex = -1
let res = await this.verifyFormData()
const res = await this.verifyFormData()
if (!this.checkParamsType(res)) {
this.focusTabByErrorIndex()
return this.$message.warning("请完善对账规则")
}
// 检验已经通过了
this.errorIndex = -1
this.verificationCodeVisible = true
// }
// })
},
// 获取弹框中的验证码
codeHandleConfirm({ smsCode, effectStartDate }) {
......@@ -904,33 +1521,42 @@ export default {
this.smsCode = smsCode
this.submitFormData()
},
// 提交信息(短信验证码确认后调用;请勿再次全量 verify,否则清空 goodsTypeGroupRulesAll 并重跑 Tab,占位「全部品类」未进缓存会导致 tab0 空表误失败)
/**
* 提交对账规则:`goodsTypeGroupRules` 为相对基线仍有变更的增量(含 type / tabPaneIndex),
* 无变更则为 [];`deletedGroupDivisionRuleIds` 为本会话删除的已落库 id。
*/
async submitFormData() {
const rulesReady =
Array.isArray(this.goodsTypeGroupRulesAll) &&
this.goodsTypeGroupRulesAll.length > 0 &&
this.checkParamsType(this.goodsTypeGroupRulesAll)
if (!rulesReady) {
const res = await this.verifyFormData()
if (!this.checkParamsType(res)) {
this.focusTabByErrorIndex()
return this.$message.warning("请完善对账规则")
}
const res = await this.verifyFormData()
if (!this.checkParamsType(res)) {
this.focusTabByErrorIndex()
return this.$message.warning("请完善对账规则")
}
this.errorIndex = -1
// this.effectStartDateDate = this.effectStartDate ? this.effectStartDate + ' 00:00:00' : ''
const {
shopMerchantTotalFeeCalculateType,
shopMerchantExpenseCategoryValue,
partnerMerchantTotalFeeCalculateType,
partnerMerchantExpenseCategoryValue
} = this.formObj
const rawIncremental =
this.reconciliationLastVerifyResult?.incrementalRules ?? []
const goodsTypeGroupRules = this.shapeGoodsTypeGroupRulesForApi(
this.filterIncrementalRulesForSubmit(rawIncremental)
)
if (this.reconciliationLastVerifyResult?.ok) {
this.reconciliationLastVerifyResult.incrementalRules = deepClone(
goodsTypeGroupRules
)
}
const params = {
smsCode: this.smsCode,
effectStartDate: this.effectStartDateDate,
merchantId: this.merchantRow.merchantId,
sceneType: this.merchantRow.scene,
goodsTypeGroupRules: this.goodsTypeGroupRulesAll,
goodsTypeGroupRules,
deletedGroupDivisionRuleIds: [
...new Set(this.pendingDeletedGroupDivisionRuleIds)
],
shopMerchantTotalFeeCalculateType,
shopMerchantExpenseCategoryValue,
partnerMerchantTotalFeeCalculateType,
......@@ -938,6 +1564,7 @@ export default {
}
const result = await saveRuleApi({ json: JSON.stringify(params) })
if (result) {
this.pendingDeletedGroupDivisionRuleIds = []
this.$message({
message: "提交成功",
type: "success"
......@@ -945,22 +1572,25 @@ export default {
this.$router.push({ name: "merchantManage" })
}
},
// 校验所有form数据
// 校验所有form数据(persist 仅在 getReconciliationGoodsTypeGroupRules 内、有待校验 Tab 时执行,避免无操作保存前污染缓存)
async verifyFormData() {
this.persistActiveClassificationTab()
await this.$nextTick()
this.goodsTypeGroupRulesAll = []
const goodsTypeGroupRules = await this.getReconciliationGoodsTypeGroupRules(
const result = await this.getReconciliationGoodsTypeGroupRules(
this.editableTabs
)
if (
goodsTypeGroupRules.length > 0 &&
goodsTypeGroupRules.every((item) => item)
) {
this.goodsTypeGroupRulesAll = deepClone(goodsTypeGroupRules)
if (result.ok) {
this.reconciliationLastVerifyResult = {
ok: true,
incrementalRules: deepClone(result.incrementalRules || []),
fullMergedRules: result.fullMergedRules
? deepClone(result.fullMergedRules)
: null
}
this.errorIndex = -1
} else {
this.reconciliationLastVerifyResult = { ok: false, incrementalRules: [], fullMergedRules: null }
}
return goodsTypeGroupRules
return result
},
/**
* A7:errorIndex 与 getReconciliationGoodsTypeGroupRules 联动;校验失败时显式切到首个有误 Tab(避免恢复焦点后仍停在其它 Tab)
......@@ -1068,6 +1698,7 @@ export default {
.classificationCptContainer {
margin-top: 8px;
padding-bottom: 8px;
}
.check-btns {
......@@ -1124,11 +1755,11 @@ export default {
align-items: center;
overflow: hidden;
> .icons {
>.icons {
flex-shrink: 0;
}
> .label {
>.label {
flex: 1;
min-width: 0;
margin: 0 4px;
......@@ -1137,7 +1768,7 @@ export default {
white-space: nowrap;
}
> .actions {
>.actions {
flex-shrink: 0;
margin-left: auto;
}
......
/**
* 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) {
(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) {
/**
* 从 goodsTypeGroupReconciliationRules + 可选占位 tab 快照聚合跨 Tab 已选品类/商品/套餐(对账编辑页)。
* 与 {@link rebuildFinancialCrossTabGoodsSelections} 字段与去重策略相近;合并为单实现前需对财务/对账两页做回归(禁用列表、phantom 等差异)。
*/
export function rebuildCrossTabReconciliationSelections(
rules,
......@@ -145,6 +146,7 @@ export function rebuildCrossTabReconciliationSelections(
/**
* 财务分账页:从 goodsTypeGroupRules 聚合跨 Tab 已选(浅拷贝条目,与 classificationCpt 禁用列表语义一致)。
* @see rebuildCrossTabReconciliationSelections — 对账侧聚合;两函数刻意分叉,合并前需专项测试。
*/
export function rebuildFinancialCrossTabGoodsSelections(rules) {
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!