Commit 1223e903 by 张立顺

feat 分账测试功能开发

1 parent 477bdf25
Showing 49 changed files with 2995 additions and 126 deletions
...@@ -11,6 +11,7 @@ ...@@ -11,6 +11,7 @@
"build:nomock": "vue-cli-service build --mode nomock", "build:nomock": "vue-cli-service build --mode nomock",
"lint": "vue-cli-service lint --fix", "lint": "vue-cli-service lint --fix",
"test:unit": "set NODE_OPTIONS=--openssl-legacy-provider && vue-cli-service test:unit", "test:unit": "set NODE_OPTIONS=--openssl-legacy-provider && vue-cli-service test:unit",
"test:financialRules": "vue-cli-service test:unit tests/unit/financialRules --no-coverage",
"report": "set NODE_OPTIONS=--openssl-legacy-provider && vue-cli-service build --report" "report": "set NODE_OPTIONS=--openssl-legacy-provider && vue-cli-service build --report"
}, },
"dependencies": { "dependencies": {
......
...@@ -8,6 +8,7 @@ ...@@ -8,6 +8,7 @@
*/ */
import request from "./request"; import request from "./request";
import RequestMethods from "./request.methods"; import RequestMethods from "./request.methods";
import { applyDivisionRuleTestGetMock } from "./mockDivisionRuleTestGetResponse";
const path = "dj.api."; const path = "dj.api.";
const path2 = "dj.api.smartcarlife."; const path2 = "dj.api.smartcarlife.";
...@@ -280,7 +281,9 @@ export function scenemerchantrefQueryServiceRefByShop(data) { ...@@ -280,7 +281,9 @@ export function scenemerchantrefQueryServiceRefByShop(data) {
// 获取商户财务设置进度 // 获取商户财务设置进度
export function divisionRuleTestGet(data) { export function divisionRuleTestGet(data) {
data.method = `${path2}divisionRuleTest.get`; data.method = `${path2}divisionRuleTest.get`;
return request(data, RequestMethods.POST); return request(data, RequestMethods.POST).then((result) =>
applyDivisionRuleTestGetMock(result)
);
} }
// 分账测试验证分账金额 // 分账测试验证分账金额
...@@ -288,6 +291,24 @@ export function divisionRuleTestMoneyValid(data) { ...@@ -288,6 +291,24 @@ export function divisionRuleTestMoneyValid(data) {
data.method = `${path2}divisionRuleTest.money.valid`; data.method = `${path2}divisionRuleTest.money.valid`;
return request(data, RequestMethods.POST); return request(data, RequestMethods.POST);
} }
/** 分账测试-重新测试 divisionRuleId + paymentChannelId */
export function divisionRuleTestRetest(data) {
data.method = `${path2}divisionRuleTest.retest`;
return request(data, RequestMethods.POST);
}
/** 分账测试-步骤2发起分账 */
export function divisionRuleTestDivisionSubmit(data) {
data.method = `${path2}divisionRuleTest.division.submit`;
return request(data, RequestMethods.POST);
}
/** 分账测试-同步主步骤 progress 1/2/3 */
export function divisionRuleTestUpdateMainProgress(data) {
data.method = `${path2}divisionRuleTest.updateMainProgress`;
return request(data, RequestMethods.POST);
}
// // 分账测算 // // 分账测算
// export function merchantSettleDistributeRuleTestRule(data) { // export function merchantSettleDistributeRuleTestRule(data) {
// data.method = `${path}merchantSettleDistributeRule.testRule` // data.method = `${path}merchantSettleDistributeRule.testRule`
......
/** 联调:强制 divisionRuleTest.get 回包 subProgress(根级 + divisionRuleTestItem) */
export const FORCE_DIVISION_TEST_SUB_PROGRESS = 35
/**
* 联调开关:true 时 get 回包 subProgress 强制为 35;也可设 VUE_APP_MOCK_DIVISION_TEST_SUB_PROGRESS=true
*/
export const ENABLE_DIVISION_TEST_SUB_PROGRESS_MOCK =
process.env.VUE_APP_MOCK_DIVISION_TEST_SUB_PROGRESS === 'true'
/**
* divisionRuleTest.get 回包处理入口(按开关决定是否 mock)
* @param {*} result
* @returns {*}
*/
export function applyDivisionRuleTestGetMock(result) {
if (!ENABLE_DIVISION_TEST_SUB_PROGRESS_MOCK) {
return result
}
return mockDivisionRuleTestGetSubProgress(result)
}
/**
* @param {*} result divisionRuleTest.get 原始回包
* @returns {*} 注入 subProgress 后的回包
*/
export function mockDivisionRuleTestGetSubProgress(result) {
if (result == null || typeof result !== 'object') {
return result
}
const sp = FORCE_DIVISION_TEST_SUB_PROGRESS
const next = { ...result, subProgress: sp }
if (next.divisionRuleTestItem && typeof next.divisionRuleTestItem === 'object') {
next.divisionRuleTestItem = {
...next.divisionRuleTestItem,
subProgress: sp
}
}
if (Array.isArray(next.divisionRuleTests)) {
next.divisionRuleTests = next.divisionRuleTests.map((item) => {
if (!item || typeof item !== 'object') return item
const patch = { ...item, subProgress: sp }
if (item.divisionRuleTestItem && typeof item.divisionRuleTestItem === 'object') {
patch.divisionRuleTestItem = {
...item.divisionRuleTestItem,
subProgress: sp
}
}
return patch
})
}
return next
}
<template> <template>
<div class="classificationCptContainer"> <div class="classificationCptContainer">
<ClassificationRuleHeader :goods-type-group-division-id="goodsTypeGroupDivisionId" <ClassificationRuleHeader @rule-test="ruleTest" />
@rule-test="ruleTest"
@get-progress="getProgress" />
<el-form ref="classification" <el-form ref="classification"
:model="classificationObj" :model="classificationObj"
:rules="rules" :rules="rules"
...@@ -1012,18 +1010,6 @@ ...@@ -1012,18 +1010,6 @@
:table-select-options="tableSelectOptions" :table-select-options="tableSelectOptions"
:classification-obj-select="tableClassificationObjSelect" :classification-obj-select="tableClassificationObjSelect"
@distribution-rules-change="onDistributionRulesChange" /> @distribution-rules-change="onDistributionRulesChange" />
<TipsDialog v-if="tipsDialogVisible"
:account-valid-merchants="accountValidMerchants"
:visible.sync="tipsDialogVisible" />
<FinancialCalculationDialog v-if="financialCalculationVisible"
:financial-calculation-obj="financialCalculationObj"
:visible.sync="financialCalculationVisible"
v-on="$listeners" />
<ChannelSelectDialog v-if="channelSelectDialogVisible"
:division-rule-tests="divisionRuleTests"
:visible.sync="channelSelectDialogVisible"
v-on="$listeners"
@handleConfirm="channelConfirm" />
</div> </div>
</template> </template>
...@@ -1040,9 +1026,6 @@ import { ...@@ -1040,9 +1026,6 @@ import {
getUpgradeGoodsRowKey, getUpgradeGoodsRowKey,
filterUpgradeGoodsByMerchantCode, filterUpgradeGoodsByMerchantCode,
} from "../../merchantStep/utils/groundingUpgradeList"; } from "../../merchantStep/utils/groundingUpgradeList";
import { divisionRuleTestGet } from "@api/merchant";
// 1按毛利比例;2按收入比例;3按固定金额
// 1按收入比例;2按毛利比例;3按固定金额;4按(产值-流量成本)比例;5按(产值-流量成本-其他费用不包含产品成本))比例;6按(产值-流量成本-其他费用包含产品成本)比例);其他费用:1按收入比例
import { mapGetters, mapMutations } from "vuex"; import { mapGetters, mapMutations } from "vuex";
import { import {
defaultSelectOptions, defaultSelectOptions,
...@@ -1053,20 +1036,14 @@ import { limitPrice } from "@/common/format"; ...@@ -1053,20 +1036,14 @@ import { limitPrice } from "@/common/format";
import { deepClone } from "@/common/util"; import { deepClone } from "@/common/util";
import { expenseSideRowKey } from "../utils/expenseRowKey"; import { expenseSideRowKey } from "../utils/expenseRowKey";
import { CLASSIFICATION_EMIT } from "../utils/classificationEmitTypes"; import { CLASSIFICATION_EMIT } from "../utils/classificationEmitTypes";
import channelSelectDialog from "./channelSelectDialog";
import ClassificationRuleHeader from "./classificationCpt/ClassificationRuleHeader.vue"; import ClassificationRuleHeader from "./classificationCpt/ClassificationRuleHeader.vue";
import GoodsSourceCategoryPicker from "./classificationCpt/GoodsSourceCategoryPicker.vue"; import GoodsSourceCategoryPicker from "./classificationCpt/GoodsSourceCategoryPicker.vue";
import financialCalculationDialog from "./financialCalculationDialog";
import tableAccount from "./tableAccount"; import tableAccount from "./tableAccount";
import tipsDialog from "./tipsDialog";
export default { export default {
name: "ClassificationCpt", name: "ClassificationCpt",
components: { components: {
TableAccount: tableAccount, TableAccount: tableAccount,
TipsDialog: tipsDialog,
FinancialCalculationDialog: financialCalculationDialog,
ChannelSelectDialog: channelSelectDialog,
ClassificationRuleHeader, ClassificationRuleHeader,
GoodsSourceCategoryPicker, GoodsSourceCategoryPicker,
}, },
...@@ -1147,11 +1124,6 @@ export default { ...@@ -1147,11 +1124,6 @@ export default {
: callback(new Error("请输入折算比例")); : callback(new Error("请输入折算比例"));
}; };
return { return {
channelSelectDialogVisible: false,
divisionRuleTests: [],
financialCalculationVisible: false,
tipsDialogVisible: false,
accountValidMerchants: [],
classificationObj: { classificationObj: {
goodsTypes: [], goodsTypes: [],
// trafficSide: [], // trafficSide: [],
...@@ -1235,7 +1207,6 @@ export default { ...@@ -1235,7 +1207,6 @@ export default {
], ],
}, },
serviceSelectList: [], serviceSelectList: [],
financialCalculationObj: {},
currentPage: 1, currentPage: 1,
pageSize: 20, pageSize: 20,
currentPagePackage: 1, currentPagePackage: 1,
...@@ -1468,15 +1439,6 @@ export default { ...@@ -1468,15 +1439,6 @@ export default {
// return this.classificationObjSelect // return this.classificationObjSelect
// } // }
}, },
goodsTypeGroupDivisionId() {
// console.log(
// this.tabItem.groupDivisionRuleId,
// "this.tabItem.groupDivisionRuleId"
// )
const id
= this.tabItem.testFlag == "N" ? this.tabItem.groupDivisionRuleId : false;
return id || false;
},
}, },
watch: { watch: {
"classificationObj.goodsSource": { "classificationObj.goodsSource": {
...@@ -1601,13 +1563,6 @@ export default { ...@@ -1601,13 +1563,6 @@ export default {
deep: true, deep: true,
// immediate: true // immediate: true
}, },
"tabItem.groupDivisionRuleId": {
handler() {
this.resetGoodsTypeGroupDivisionId();
},
deep: true,
immediate: true,
},
"tabItem.pendingCalculateErrorOps": { "tabItem.pendingCalculateErrorOps": {
handler() { handler() {
this.$nextTick(() => this.replayPendingCalculateErrorOps()); this.$nextTick(() => this.replayPendingCalculateErrorOps());
...@@ -1905,66 +1860,6 @@ export default { ...@@ -1905,66 +1860,6 @@ export default {
); );
}, },
// ...mapActions("FinancialRules", ["reset"]), // ...mapActions("FinancialRules", ["reset"]),
resetGoodsTypeGroupDivisionId() {
// goodsTypeGroupDivisionId() {
// console.log(
// this.tabItem.groupDivisionRuleId,
// "this.tabItem.groupDivisionRuleId"
// )
// const id = this.tabItem.testFlag != 'Y' ? this.tabItem.groupDivisionRuleId : false
// this.goodsTypeGroupDivisionId = id || false
// }
},
getProgress() {
if (!this.goodsTypeGroupDivisionId)
return;
divisionRuleTestGet({
goodsTypeGroupDivisionId: this.goodsTypeGroupDivisionId,
}).then((result) => {
if (!result)
return;
const {
notInForceAccountMerchants,
divisionRuleTests,
subProgress,
accountValidMerchants,
} = result;
if (notInForceAccountMerchants) {
this.tipsDialogVisible = true;
this.accountValidMerchants = notInForceAccountMerchants;
return;
}
if (subProgress == 32) {
this.tipsDialogVisible = true;
this.accountValidMerchants = accountValidMerchants;
return;
}
if (Array.isArray(divisionRuleTests) && divisionRuleTests.length > 0) {
if (divisionRuleTests.length === 1) {
this.channelConfirm(divisionRuleTests[0]);
} else {
this.channelSelectDialogVisible = true;
this.divisionRuleTests = divisionRuleTests;
}
return;
}
const sp = Number(subProgress);
if ([34, 35, 36, 31].includes(sp)) {
this.financialCalculationVisible = true;
this.financialCalculationObj = result;
}
}).catch((err) => {
console.error("[FinancialRules/classificationCpt] getProgress", err);
});
},
channelConfirm(result) {
this.financialCalculationVisible = true;
this.financialCalculationObj = { ...result, ...result.divisionRuleTestItem };
// }
},
ruleTest() { ruleTest() {
this.emitClassificationChange(CLASSIFICATION_EMIT.RULES_TEST); this.emitClassificationChange(CLASSIFICATION_EMIT.RULES_TEST);
}, },
...@@ -2264,8 +2159,6 @@ export default { ...@@ -2264,8 +2159,6 @@ export default {
"upgradeGoods", "upgradeGoods",
"packageGoods", "packageGoods",
"goodsSource", "goodsSource",
"testFlag",
"groupDivisionRuleId",
"goodsCostConvertRate", "goodsCostConvertRate",
"virtualAccountCostConvertRate", "virtualAccountCostConvertRate",
"recoveryCostConvertRate", "recoveryCostConvertRate",
...@@ -2487,8 +2380,6 @@ export default { ...@@ -2487,8 +2380,6 @@ export default {
partnerDeductChargeFlag: obj.partnerDeductChargeFlag, partnerDeductChargeFlag: obj.partnerDeductChargeFlag,
virtualAccountCostFlag: obj.virtualAccountCostFlag, virtualAccountCostFlag: obj.virtualAccountCostFlag,
recoveryCostFlag: obj.recoveryCostFlag, recoveryCostFlag: obj.recoveryCostFlag,
testFlag: obj.testFlag,
groupDivisionRuleId: obj.groupDivisionRuleId,
djCostFlag: obj.djCostFlag, djCostFlag: obj.djCostFlag,
thirdPartyCostFlag: obj.thirdPartyCostFlag, thirdPartyCostFlag: obj.thirdPartyCostFlag,
goodsCostFlag: obj.goodsCostFlag, goodsCostFlag: obj.goodsCostFlag,
......
...@@ -2,20 +2,12 @@ ...@@ -2,20 +2,12 @@
<div class="hederContainer"> <div class="hederContainer">
<span class="tips ruleTest">不确定规则是否正确?点击 <span class="tips ruleTest">不确定规则是否正确?点击
<el-button type="text" @click="$emit('rule-test')">进行测算</el-button></span> <el-button type="text" @click="$emit('rule-test')">进行测算</el-button></span>
<span v-show="goodsTypeGroupDivisionId" class="tips dimensionTest">未进行分账测试,点击
<el-button type="text" @click="$emit('get-progress')">立即测试</el-button></span>
</div> </div>
</template> </template>
<script> <script>
export default { export default {
name: "ClassificationRuleHeader", name: "ClassificationRuleHeader"
props: {
goodsTypeGroupDivisionId: {
type: [String, Number, Boolean],
default: false
}
}
} }
</script> </script>
...@@ -42,9 +34,5 @@ export default { ...@@ -42,9 +34,5 @@ export default {
background: #185efe; background: #185efe;
} }
} }
.dimensionTest {
margin-left: 80px;
}
} }
</style> </style>
<template>
<div class="division-test-step1">
<div v-if="!step1Paid" class="pay-qrcode-wrap">
<img v-if="qrCodeURL" :src="qrCodeURL" class="pay-qrcode" alt="支付二维码">
<div v-else class="pay-qrcode pay-qrcode--loading" v-loading="true" />
<p class="pay-tip">微信扫码支付({{ payAmount }}元)</p>
</div>
<div v-else class="order-linked">
<span>关联测试订单:{{ orderCode }}</span>
<el-button
type="text"
class="retest-link"
@click="$emit('retest')"
>
重新测试
</el-button>
</div>
</div>
</template>
<script>
export default {
name: 'DivisionTestStep1Pay',
props: {
step1Paid: {
type: Boolean,
default: false
},
orderCode: {
type: String,
default: ''
},
qrCodeURL: {
type: String,
default: ''
},
payAmount: {
type: [String, Number],
default: 3.5
},
readOnly: {
type: Boolean,
default: false
}
}
}
</script>
<style scoped lang="scss">
.division-test-step1 {
min-height: 280px;
display: flex;
align-items: center;
justify-content: center;
background: #f5f7fa;
border-radius: 8px;
padding: 24px;
}
.pay-qrcode-wrap {
text-align: center;
}
.pay-qrcode {
width: 200px;
height: 200px;
object-fit: contain;
display: block;
margin: 0 auto 16px;
background: #fff;
}
.pay-qrcode--loading {
min-height: 200px;
}
.pay-tip {
font-size: 14px;
color: #333;
margin: 0;
}
.order-linked {
font-size: 14px;
color: #333;
.retest-link {
margin-left: 8px;
padding: 0;
}
}
</style>
<template>
<div class="division-test-step2">
<div class="merchant-grid">
<div
v-for="(item, index) in merchants"
:key="merchantKey(item, index)"
class="merchant-grid-item"
>
<p class="merchant-name">
<span class="bullet">•</span>{{ item.merchantName }}
</p>
<div v-if="item.testCompleted" class="completed-tag">已完成测试</div>
<el-input
v-else
:value="item.displayDivisionMoney"
size="small"
disabled
placeholder="请输入分润金额"
/>
</div>
</div>
<p class="step2-hint">
设置待测试商户的分润金额<br>
说明:分润总金额必须等于3.5元,最后一个商户默认承担手续费
</p>
</div>
</template>
<script>
export default {
name: 'DivisionTestStep2Allocate',
props: {
merchants: {
type: Array,
default: () => []
}
},
methods: {
merchantKey(item, index) {
return item.merchantId ?? item.merchantName ?? index
}
}
}
</script>
<style scoped lang="scss">
.division-test-step2 {
background: #f5f7fa;
border-radius: 8px;
padding: 24px 32px 20px;
min-height: 280px;
}
.merchant-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 16px 40px;
max-width: 640px;
margin: 0 auto;
}
.merchant-grid-item {
.merchant-name {
margin: 0 0 8px;
font-size: 14px;
color: #333;
.bullet {
margin-right: 4px;
color: #666;
}
}
.completed-tag {
height: 32px;
line-height: 32px;
font-size: 14px;
color: #2b58ad;
padding-left: 8px;
}
}
.step2-hint {
text-align: center;
font-size: 12px;
color: #666;
line-height: 1.6;
margin: 24px 0 0;
}
</style>
<template>
<div class="division-test-step3">
<el-form ref="verifyForm" :model="form" :rules="rules" class="merchant-grid-form">
<div class="merchant-grid">
<el-form-item
v-for="(item, index) in form.testMerchantDivisions"
:key="merchantKey(item, index)"
:prop="'testMerchantDivisions.' + index + '.confirmDivisionMoney'"
:rules="item.testCompleted ? [] : amountRules"
class="merchant-grid-item"
>
<p class="merchant-name">
<span class="bullet">•</span>{{ item.merchantName }}
</p>
<div v-if="item.testCompleted" class="completed-tag">已完成测试</div>
<el-input
v-else
v-model="form.testMerchantDivisions[index].confirmDivisionMoney"
size="small"
placeholder="请输入到账金额"
:disabled="readOnly"
@input="onAmountInput($event, index)"
/>
</el-form-item>
</div>
</el-form>
<p class="step3-hint">次日分账成功后确认分账方到账金额</p>
</div>
</template>
<script>
/** 步骤3仅负责表单;提交由父组件 handleCompleteTest 调用 divisionRuleTest.money.valid */
import { limitPrice } from '@/common/format'
import { isValidAmountInput, mergeStep3FormMerchants } from '../../utils/validateStep3Amounts'
export default {
name: 'DivisionTestStep3Verify',
props: {
merchants: {
type: Array,
default: () => []
},
readOnly: {
type: Boolean,
default: false
}
},
data() {
return {
form: {
testMerchantDivisions: []
},
amountRules: [
{
required: true,
message: '请输入到账金额',
trigger: ['blur', 'change']
},
{
validator: (rule, value, callback) => {
if (!isValidAmountInput(value)) {
callback(new Error('请输入0-3.5的数字,最多两位小数'))
} else {
callback()
}
},
trigger: ['blur', 'change']
}
]
}
},
computed: {
rules() {
return {}
}
},
watch: {
merchants: {
immediate: true,
deep: true,
handler(list) {
this.form.testMerchantDivisions = mergeStep3FormMerchants(
list,
this.form.testMerchantDivisions
)
}
}
},
methods: {
merchantKey(item, index) {
return item.merchantId ?? item.merchantName ?? index
},
onAmountInput(val, index) {
this.form.testMerchantDivisions[index].confirmDivisionMoney = limitPrice(val, 0, 6, 2)
},
validate() {
return new Promise((resolve) => {
if (!this.$refs.verifyForm) {
resolve(false)
return
}
this.$refs.verifyForm.validate((valid) => resolve(valid))
})
},
getSubmitMerchants() {
return this.form.testMerchantDivisions
}
}
}
</script>
<style scoped lang="scss">
.division-test-step3 {
background: #f5f7fa;
border-radius: 8px;
padding: 24px 32px 20px;
min-height: 280px;
}
.merchant-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 16px 40px;
max-width: 640px;
margin: 0 auto;
}
.merchant-grid-item {
margin-bottom: 0;
::v-deep .el-form-item__content {
line-height: normal;
}
.merchant-name {
margin: 0 0 8px;
font-size: 14px;
color: #333;
.bullet {
margin-right: 4px;
color: #666;
}
}
.completed-tag {
height: 32px;
line-height: 32px;
font-size: 14px;
color: #2b58ad;
padding-left: 8px;
}
}
.step3-hint {
text-align: center;
font-size: 12px;
color: #666;
margin: 24px 0 0;
}
</style>
<template>
<div class="division-test-stepper">
<p class="stepper-label">分账测试步骤</p>
<el-steps
:active="activeIndex"
finish-status="success"
align-center
class="division-test-steps"
>
<el-step
v-for="n in 3"
:key="n"
:title="String(n)"
:status="stepStatus(n)"
@click.native="onStepClick(n)"
class="division-test-step-item"
/>
</el-steps>
</div>
</template>
<script>
export default {
name: 'DivisionTestStepper',
props: {
maxReachedStep: {
type: Number,
default: 1
},
viewStep: {
type: Number,
default: 1
},
stepCompletedFlags: {
type: Array,
default: () => [false, false, false]
}
},
computed: {
activeIndex() {
return Math.max(0, Number(this.viewStep) - 1)
}
},
methods: {
stepStatus(stepNum) {
const idx = stepNum - 1
if (this.stepCompletedFlags[idx] && stepNum < this.viewStep) return 'success'
if (stepNum === this.viewStep) return 'process'
if (stepNum < this.maxReachedStep) return 'success'
return 'wait'
},
onStepClick(stepNum) {
this.$emit('step-click', stepNum)
}
}
}
</script>
<style scoped lang="scss">
.division-test-stepper {
margin-bottom: 16px;
.stepper-label {
font-size: 12px;
color: #6c6f71;
margin: 0 0 12px;
}
.division-test-steps {
max-width: 480px;
margin: 0 auto;
}
.division-test-step-item {
cursor: pointer;
}
}
</style>
import { deepClone } from "@/common/util"
import {
getStableReconciliationRuleId,
mergeReconciliationRuleServerFields
} from "../../merchantStep/utils/reconciliationIncrementalRules"
/**
* 删 Tab 时收集待提交的 DELETE 快照(sessionAdded 的新 Tab 不产生 DELETE)。
*
* @param {object} params
* @param {object|null|undefined} params.removedRule
* @param {object|null|undefined} params.removedTabMeta
* @param {boolean} params.isSessionOnlyNew
* @returns {object|null}
*/
export function collectPendingDeleteForRemovedTab({
removedRule,
removedTabMeta,
isSessionOnlyNew
}) {
if (isSessionOnlyNew) return null
let rid =
removedRule && typeof removedRule === "object"
? getStableReconciliationRuleId(removedRule)
: ""
if (!rid && removedTabMeta) {
const gid = removedTabMeta.groupDivisionRuleId
if (gid != null && String(gid).trim() !== "") {
rid = String(gid).trim()
}
}
if (!rid) return null
const ruleSnapshot =
removedRule && typeof removedRule === "object"
? deepClone(removedRule)
: {}
delete ruleSnapshot.type
delete ruleSnapshot.tabPaneIndex
if (
ruleSnapshot.groupDivisionRuleId == null
|| String(ruleSnapshot.groupDivisionRuleId).trim() === ""
) {
ruleSnapshot.groupDivisionRuleId =
removedTabMeta && removedTabMeta.groupDivisionRuleId != null
? removedTabMeta.groupDivisionRuleId
: rid
}
return ruleSnapshot
}
/**
* splice 后按 oldIdx 从 prev 缓存 merge 服务端 id 字段。
*
* @param {Array<object>} goodsTypeGroupRules
* @param {number} tabIndex
* @param {Array<object>} prevGoodsTypeGroupRules
* @returns {Array<object>}
*/
export function mergeRemainingRulesAfterTabRemoval(
goodsTypeGroupRules,
tabIndex,
prevGoodsTypeGroupRules
) {
const remaining = goodsTypeGroupRules.slice()
remaining.splice(tabIndex, 1)
const prev = prevGoodsTypeGroupRules || []
for (let index = 0; index < remaining.length; index++) {
const oldIdx = index < tabIndex ? index : index + 1
const cachedForId = prev[oldIdx]
if (cachedForId) {
remaining[index] = mergeReconciliationRuleServerFields(
remaining[index],
cachedForId
)
}
}
return remaining
}
/**
* removeTab 核心纯逻辑:收集 pending DELETE + 剩余规则 id 合并。
*
* @param {object} params
* @returns {{ remainingRules: Array<object>, pendingDelete: object|null }}
*/
export function applyRemoveTabToGoodsTypeGroupRules({
goodsTypeGroupRules,
tabIndex,
prevGoodsTypeGroupRules,
removedRule,
removedTabMeta,
isSessionOnlyNew
}) {
const pendingDelete = collectPendingDeleteForRemovedTab({
removedRule,
removedTabMeta,
isSessionOnlyNew
})
const remainingRules = mergeRemainingRulesAfterTabRemoval(
goodsTypeGroupRules,
tabIndex,
prevGoodsTypeGroupRules
)
return { remainingRules, pendingDelete }
}
/**
* 删 Tab 后按 oldIdx 恢复 editableTabs meta(revision / touched / sessionAdded)。
*
* @param {Array<object>} prevTabsMeta
* @param {number} tabIndex
* @param {number} remainingCount
* @returns {Array<object>}
*/
export function mapTabMetaAfterTabRemoval(prevTabsMeta, tabIndex, remainingCount) {
const out = []
for (let index = 0; index < remainingCount; index++) {
const oldIdx = index < tabIndex ? index : index + 1
const meta = prevTabsMeta[oldIdx]
out.push({
sessionAdded: !!(meta && meta.sessionAdded),
ruleCacheRevision:
meta && meta.ruleCacheRevision != null ? Number(meta.ruleCacheRevision) : 0,
confirmedRuleCacheRevision:
meta && meta.confirmedRuleCacheRevision != null
? Number(meta.confirmedRuleCacheRevision)
: 0,
classificationUserTouched: !!(meta && meta.classificationUserTouched)
})
}
return out
}
/**
* 分账测试相关接口公共入参(使用财务详情 divisionRuleId,不再传 goodsTypeGroupDivisionId)
*/
export function buildDivisionRuleTestParams(ctx = {}) {
const {
merchantId,
sceneType,
paymentChannelId,
divisionRuleId,
baseSceneCode
} = ctx
const params = {}
if (merchantId != null && merchantId !== '') {
params.merchantId = merchantId
}
if (sceneType != null && sceneType !== '') {
params.sceneType = sceneType
}
if (paymentChannelId != null && paymentChannelId !== '') {
params.paymentChannelId = paymentChannelId
}
if (divisionRuleId != null && divisionRuleId !== '') {
params.divisionRuleId = divisionRuleId
}
if (baseSceneCode != null && baseSceneCode !== '') {
params.baseSceneCode = baseSceneCode
}
return params
}
/** divisionRuleTest.retest:仅 divisionRuleId + paymentChannelId */
export function buildDivisionRuleTestRetestParams(ctx = {}) {
const { divisionRuleId, paymentChannelId } = ctx
const params = {}
if (divisionRuleId != null && divisionRuleId !== '') {
params.divisionRuleId = divisionRuleId
}
if (paymentChannelId != null && paymentChannelId !== '') {
params.paymentChannelId = paymentChannelId
}
return params
}
/** divisionRuleTest.money.valid:divisionRuleId + paymentChannelId + testMerchantDivisions */
export function buildDivisionRuleTestMoneyValidParams({
testObj = {},
testMerchantDivisions,
divisionRuleId: divisionRuleIdOverride
} = {}) {
const divisionRuleId =
divisionRuleIdOverride
?? testObj.divisionRuleId
const params = {
testMerchantDivisions: testMerchantDivisions || []
}
if (divisionRuleId != null && divisionRuleId !== '') {
params.divisionRuleId = divisionRuleId
}
if (testObj.paymentChannelId != null && testObj.paymentChannelId !== '') {
params.paymentChannelId = testObj.paymentChannelId
}
return params
}
/** divisionRuleTest.updateMainProgress:divisionRuleId + paymentChannelId + progress(1|2|3) */
export function buildDivisionRuleTestUpdateMainProgressParams(ctx = {}) {
const { divisionRuleId, paymentChannelId, progress } = ctx
const params = {}
if (divisionRuleId != null && divisionRuleId !== '') {
params.divisionRuleId = divisionRuleId
}
if (paymentChannelId != null && paymentChannelId !== '') {
params.paymentChannelId = paymentChannelId
}
const p = Number(progress)
if (p >= 1 && p <= 3) {
params.progress = p
}
return params
}
import { deepClone } from "@/common/util"
import { fillDjGoodsTypeGroupRelations } from "../../merchantStep/utils/reconciliationShared"
/**
* 与 index.vue buildFullMergedGoodsTypeGroupRules 一致:冲突检测用全量规则视图。
*
* @param {object} params
* @param {number} params.tabCount editableTabs.length
* @param {Record<number, object>} [params.validatedByIndex]
* @param {Array<object>} [params.slotCaches] financialObj.goodsTypeGroupRules
* @returns {Array<object>}
*/
export function buildFullMergedGoodsTypeGroupRules({
tabCount,
validatedByIndex,
slotCaches
}) {
const n = tabCount
const out = []
const map = validatedByIndex || {}
const caches = slotCaches || []
for (let i = 0; i < n; i++) {
if (map[i]) {
out.push(map[i])
} else {
const cached = caches[i]
out.push(fillDjGoodsTypeGroupRelations(deepClone(cached || {})))
}
}
return out
}
import { sortDivisionTestMerchants, isPlatformMerchant } from './sortDivisionTestMerchants'
import { isMerchantCompletedFromDetail } from './validateStep3Amounts'
export const PLATFORM_FIXED_AMOUNT = 0.5
export const ALLOCATABLE_POOL = 3
export const TOTAL_PROFIT_AMOUNT = 3.5
/** distributionMoney 为 0、null、'' 表示已完成分账测试 */
export function isMerchantTestCompleted(item) {
if (!item) return false
if (item.testCompleted === true) return true
const v = item.distributionMoney
if (v == null || v === '') return true
const n = Number(v)
return Number.isFinite(n) && n === 0
}
function roundMoney(n) {
return Math.round(n * 100) / 100
}
function hasDistributionMoneyValue(item) {
const v = item?.distributionMoney
if (v == null || v === '') return false
const n = Number(v)
return Number.isFinite(n) && n !== 0
}
function hasPresetDivisionMoney(item) {
if (hasDistributionMoneyValue(item)) return true
const v = item.divisionMoney ?? item.testDivisionMoney ?? item.allocateDivisionMoney
return v != null && v !== ''
}
/**
* 对未完成测试的非平台商户随机分配 ALLOCATABLE_POOL 元,最后一户承担尾差。
* @param {object[]} pendingMerchants
* @param {() => number} [randomFn] 0-1,便于单测
*/
export function randomAllocatePool(pendingMerchants, randomFn = Math.random) {
const n = pendingMerchants.length
if (n === 0) return []
if (n === 1) return [ALLOCATABLE_POOL]
const weights = []
let sum = 0
for (let i = 0; i < n - 1; i++) {
const w = randomFn() + 0.01
weights.push(w)
sum += w
}
const amounts = []
let allocated = 0
for (let i = 0; i < n - 1; i++) {
const part = roundMoney((weights[i] / sum) * ALLOCATABLE_POOL)
amounts.push(part)
allocated += part
}
amounts.push(roundMoney(ALLOCATABLE_POOL - allocated))
return amounts
}
function resolveDisplayAmount(item, platform, cache, randomAmounts, pendingIdxRef) {
if (hasDistributionMoneyValue(item)) {
return String(item.distributionMoney)
}
if (platform) {
if (hasPresetDivisionMoney(item)) {
return String(
item.distributionMoney
?? item.divisionMoney
?? item.testDivisionMoney
?? PLATFORM_FIXED_AMOUNT
)
}
return String(PLATFORM_FIXED_AMOUNT)
}
if (hasPresetDivisionMoney(item)) {
return String(
item.distributionMoney
?? item.divisionMoney
?? item.testDivisionMoney
?? item.allocateDivisionMoney
)
}
const key = String(item.merchantId ?? item.merchantName ?? '')
if (cache[key] != null && cache[key] !== '') {
return String(cache[key])
}
const amount = randomAmounts[pendingIdxRef.idx] ?? 0
pendingIdxRef.idx += 1
return String(amount)
}
/**
* @param {object[]} testMerchantDivisions
* @param {{ randomFn?: () => number, cachedAllocations?: Record<string, string> }} [options]
* @returns {object[]} 带 displayDivisionMoney、testCompleted 的副本(已排序)
*/
export function buildStep2DisplayMerchants(testMerchantDivisions, options = {}) {
const sorted = sortDivisionTestMerchants(testMerchantDivisions || [])
const randomFn = options.randomFn || Math.random
const cache = options.cachedAllocations || {}
const pending = sorted.filter((m) => !isMerchantTestCompleted(m) && !isPlatformMerchant(m))
const randomAmounts = randomAllocatePool(pending, randomFn)
const pendingIdxRef = { idx: 0 }
return sorted.map((item) => {
const completed = isMerchantTestCompleted(item)
const platform = isPlatformMerchant(item)
const displayDivisionMoney = completed
? ''
: resolveDisplayAmount(item, platform, cache, randomAmounts, pendingIdxRef)
return {
...item,
testCompleted: completed,
displayDivisionMoney
}
})
}
/** 步骤 3:同一商户列表与完成态,保留 confirmDivisionMoney 供填写 */
export function buildStep3VerifyMerchants(testMerchantDivisions) {
const sorted = sortDivisionTestMerchants(testMerchantDivisions || [])
return sorted.map((m) => ({
...m,
testCompleted: isMerchantCompletedFromDetail(m),
confirmDivisionMoney: m.confirmDivisionMoney ?? ''
}))
}
export function sumDisplayDivisionMoney(merchants) {
return (merchants || []).reduce((sum, m) => {
if (m.testCompleted) return sum
const v = parseFloat(m.displayDivisionMoney)
return sum + (Number.isFinite(v) ? v : 0)
}, 0)
}
export function isTotalProfitAmountValid(merchants, total = TOTAL_PROFIT_AMOUNT) {
const sum = roundMoney(sumDisplayDivisionMoney(merchants))
return Math.abs(sum - total) < 0.001
}
import { deepClone } from "@/common/util"
import { mergeChildClassificationPayload } from "./mergeClassificationPayload"
/**
* 与 index.vue getAllParams 一致:按 editableTabs 顺序收集 rules。
*
* @param {object} params
* @param {Array<object>} params.editableTabs
* @param {Array<object>|undefined} params.slotCaches financialObj.goodsTypeGroupRules
* @param {(paneName: string) => object|null|undefined} [params.getChildPayloadByPaneName]
* 激活 Tab 返回 getClassificationParams();未挂载返回 null/undefined
* @returns {Array<object>}
*/
export function collectGoodsTypeGroupRulesFromTabs({
editableTabs,
slotCaches,
getChildPayloadByPaneName
}) {
const list = deepClone(editableTabs)
const goodsTypeGroupRules = []
const caches = slotCaches || []
for (let index = 0; index < list.length; index++) {
const tabindex = editableTabs.findIndex(
(item) => item.name === list[index].name
)
const getPayload = getChildPayloadByPaneName
let payload = null
if (typeof getPayload === "function") {
try {
payload = getPayload(list[index].name)
} catch (e) {
payload = undefined
}
}
if (payload != null && typeof payload === "object") {
try {
const cached = caches[tabindex]
const { next } = mergeChildClassificationPayload(payload, cached)
goodsTypeGroupRules.push(next)
} catch (e) {
const cached = caches[tabindex]
goodsTypeGroupRules.push(cached ? deepClone(cached) : {})
}
} else {
const cached = caches[tabindex]
goodsTypeGroupRules.push(cached ? deepClone(cached) : {})
}
}
return goodsTypeGroupRules
}
/** autoFlag=Y 且 testFlag 严格为 N(未通过分账测试) */
export function isDivisionRuleAutoTestPending(item) {
return item && item.autoFlag == "Y" && item.testFlag == "N"
}
export function hasPendingDivisionRuleAutoTest(divisionRuleAutos) {
return (divisionRuleAutos || []).some(isDivisionRuleAutoTestPending)
}
export function findPendingDivisionRuleAutoTestIndices(divisionRuleAutos) {
return (divisionRuleAutos || [])
.map((item, index) => (isDivisionRuleAutoTestPending(item) ? index : -1))
.filter((i) => i >= 0)
}
/** subProgress 进行中:34 步骤1 / 35 已付款 / 36 已分账 / 31 失败(不驱动展示步骤) */
export const DIVISION_TEST_SUB_PROGRESS_IN_PROGRESS = [34, 35, 36, 31]
export function isDivisionTestInProgress(subProgress) {
const sp = Number(subProgress)
return DIVISION_TEST_SUB_PROGRESS_IN_PROGRESS.includes(sp)
}
export function isDivisionTestPassed(subProgress) {
const sp = Number(subProgress)
return sp > 0 && !isDivisionTestInProgress(sp)
}
function isOrderPaidFromPayload(payload, sp) {
if (payload.orderPaid === true) return true
if (payload.paymentSuccess === true) return true
if (payload.payStatus === 1 || payload.payStatus === '1' || payload.payStatus === 'Y') {
return true
}
return sp >= 35
}
/**
* 仅从 subProgress / 支付状态解析业务态,不映射展示步骤
* @param {number|string} subProgress
* @param {{ orderPaid?: boolean, payStatus?: *, paymentSuccess?: boolean }} [payload]
*/
export function mapSubProgressToUi(subProgress, payload = {}) {
const sp = Number(subProgress)
const step1Paid = isOrderPaidFromPayload(payload, sp)
return {
step1Paid,
subProgress: sp,
isFailed: sp === 31
}
}
/** 步骤条完成态:[0]=步骤1已付款 [1]=步骤2已提交 [2]=失败标记 */
export function buildStepCompletedFlags(step1Paid, maxReachedStep, isFailed = false) {
const max = Number(maxReachedStep) || 1
return [
!!step1Paid,
max >= 3,
!!isFailed
]
}
/**
* @param {number} targetStep
* @param {{ maxReachedStep: number, step1Paid?: boolean }} uiState
*/
export function canNavigateToStep(targetStep, uiState) {
const step = Number(targetStep)
const max = Number(uiState.maxReachedStep) || 1
if (step < 1 || step > 3) return false
return step <= max
}
/**
* 回看已完成步骤时为只读
* @param {number} viewStep
* @param {{ maxReachedStep: number }} uiState
*/
export function isStepReadOnly(viewStep, uiState) {
const v = Number(viewStep)
const max = Number(uiState.maxReachedStep) || 1
return v < max
}
/**
* subProgress 决定可达的最大步骤
* @param {number|string} subProgress
* @returns {number} 1 | 2 | 3
*/
export function resolveMaxReachedStepFromSubProgress(subProgress) {
const sp = Number(subProgress) || 0
if (sp === 36) return 3
if (sp >= 35) return 2
return 1
}
/**
* 打开弹窗时决定初始展示步骤:优先 progress(为 3 则展示步骤 3),无 progress 时回退 subProgress
* @param {number|string} subProgress
* @param {number|string} [progress] 服务端主步骤 1/2/3
* @returns {{ viewStep: number, maxReachedStep: number }}
*/
export function resolveInitialWizardSteps(subProgress, progress) {
const sp = Number(subProgress) || 0
const mp = Number(progress) || 0
let maxReachedStep = resolveMaxReachedStepFromSubProgress(sp)
if (mp >= 1 && mp <= 3) {
maxReachedStep = Math.max(maxReachedStep, mp)
return { viewStep: mp, maxReachedStep }
}
if (sp === 36) {
return { viewStep: 3, maxReachedStep: 3 }
}
return { viewStep: 1, maxReachedStep }
}
/**
* 保证「全部品类」(groupType===1) 位于 goodsTypeGroupRules[0]。
*
* 旧逻辑在首条为特殊品类时 unshift 空壳 { groupType: 1 },若接口已在其它下标返回带 groupDivisionRuleId
* 的 groupType 1,会导致 Tab0 无 id、真实全部品类错位,提交时 type 误判为 ADD。
*
* @param {Array<object>|null|undefined} rules
* @returns {Array<object>}
*/
export function ensureAllCategoryRuleFirst(rules) {
let list = Array.isArray(rules) ? [...rules] : []
if (!list.length) {
return [{ groupType: 1 }]
}
const allIdx = list.findIndex((r) => r && r.groupType == 1)
if (allIdx > 0) {
const reordered = [...list]
const [allRule] = reordered.splice(allIdx, 1)
reordered.unshift(allRule)
return reordered
}
if (allIdx === 0) {
return list
}
if (list[0] && list[0].groupType == 2) {
return [{ groupType: 1 }, ...list]
}
return list
}
...@@ -9,6 +9,25 @@ const GUARD_EMPTY_ARRAY_KEYS = [ ...@@ -9,6 +9,25 @@ const GUARD_EMPTY_ARRAY_KEYS = [
"packageGoods" "packageGoods"
] ]
/** 服务端主键/关联 id:子组件 getClassificationParams 不带,须从槽位缓存保留 */
const SERVER_ID_FIELDS = ["groupDivisionRuleId", "id", "groupSettleRuleId"]
function preserveServerIdFieldsFromBase(next, base, payload) {
for (let i = 0; i < SERVER_ID_FIELDS.length; i++) {
const key = SERVER_ID_FIELDS[i]
const fromPayload = payload[key]
const payloadHasValue =
Object.prototype.hasOwnProperty.call(payload, key)
&& fromPayload != null
&& String(fromPayload).trim() !== ""
if (payloadHasValue) continue
const fromBase = base[key]
if (fromBase != null && String(fromBase).trim() !== "") {
next[key] = fromBase
}
}
}
/** /**
* 将子组件 getClassificationParams() 的 payload 与槽位缓存合并为 next(与 index buildMerged 一致)。 * 将子组件 getClassificationParams() 的 payload 与槽位缓存合并为 next(与 index buildMerged 一致)。
* *
...@@ -53,5 +72,6 @@ export function mergeChildClassificationPayload(payload, prevStoredRaw) { ...@@ -53,5 +72,6 @@ export function mergeChildClassificationPayload(payload, prevStoredRaw) {
next[key] = b next[key] = b
} }
}) })
preserveServerIdFieldsFromBase(next, base, payload)
return { next, prevStored: prevStoredRaw } return { next, prevStored: prevStoredRaw }
} }
function findDivisionRuleTestChannelEntry(payload = {}) {
const channelId = payload.paymentChannelId
if (!Array.isArray(payload.divisionRuleTests) || !payload.divisionRuleTests.length) {
return null
}
return channelId != null
? payload.divisionRuleTests.find((t) => t && t.paymentChannelId == channelId)
: payload.divisionRuleTests[0]
}
/**
* 分账测试订单号:优先取 divisionRuleTests 项下 divisionRuleTestItem.orderCode
*/
export function resolveDivisionTestOrderCode(payload = {}) {
if (!payload || typeof payload !== 'object') return ''
const entry = findDivisionRuleTestChannelEntry(payload)
const fromList = entry?.divisionRuleTestItem?.orderCode
if (fromList != null && fromList !== '') {
return String(fromList)
}
const fromItem = payload.divisionRuleTestItem?.orderCode
if (fromItem != null && fromItem !== '') {
return String(fromItem)
}
if (payload.orderCode != null && payload.orderCode !== '') {
return String(payload.orderCode)
}
return ''
}
/**
* 分账测试进度:优先取 divisionRuleTests 项下 divisionRuleTestItem.subProgress
*/
export function resolveDivisionTestSubProgress(payload = {}, fallback) {
if (!payload || typeof payload !== 'object') {
return fallback != null ? Number(fallback) || 0 : 0
}
const entry = findDivisionRuleTestChannelEntry(payload)
const fromList = entry?.divisionRuleTestItem?.subProgress ?? entry?.subProgress
if (fromList != null && fromList !== '') {
return Number(fromList) || 0
}
const fromItem = payload.divisionRuleTestItem?.subProgress
if (fromItem != null && fromItem !== '') {
return Number(fromItem) || 0
}
if (payload.subProgress != null && payload.subProgress !== '') {
return Number(payload.subProgress) || 0
}
if (fallback != null && fallback !== '') {
return Number(fallback) || 0
}
return 0
}
/**
* 主步骤 progress(1/2/3):与 subProgress 同源解析
*/
export function resolveDivisionTestProgress(payload = {}, fallback) {
if (!payload || typeof payload !== 'object') {
return fallback != null && fallback !== '' ? Number(fallback) || 0 : 0
}
const entry = findDivisionRuleTestChannelEntry(payload)
const fromList = entry?.divisionRuleTestItem?.progress ?? entry?.progress
if (fromList != null && fromList !== '') {
return Number(fromList) || 0
}
const fromItem = payload.divisionRuleTestItem?.progress
if (fromItem != null && fromItem !== '') {
return Number(fromItem) || 0
}
if (payload.progress != null && payload.progress !== '') {
return Number(payload.progress) || 0
}
if (fallback != null && fallback !== '') {
return Number(fallback) || 0
}
return 0
}
/**
* money.valid 用 goodsTypeGroupDivisionId:与 orderCode 同源解析
*/
export function resolveGoodsTypeGroupDivisionId(payload = {}) {
if (!payload || typeof payload !== 'object') return undefined
const entry = findDivisionRuleTestChannelEntry(payload)
const fromList = entry?.divisionRuleTestItem?.goodsTypeGroupDivisionId
if (fromList != null && fromList !== '') {
return fromList
}
const fromItem = payload.divisionRuleTestItem?.goodsTypeGroupDivisionId
if (fromItem != null && fromItem !== '') {
return fromItem
}
if (payload.goodsTypeGroupDivisionId != null && payload.goodsTypeGroupDivisionId !== '') {
return payload.goodsTypeGroupDivisionId
}
return undefined
}
/**
* 分账测试商户列表:优先取 divisionRuleTests 项下 divisionRuleTestItem.testMerchantDivisions
*/
export function resolveDivisionTestMerchantDivisions(payload = {}) {
if (!payload || typeof payload !== 'object') return []
const entry = findDivisionRuleTestChannelEntry(payload)
const fromList = entry?.divisionRuleTestItem?.testMerchantDivisions
if (Array.isArray(fromList) && fromList.length) {
return fromList
}
const fromItem = payload.divisionRuleTestItem?.testMerchantDivisions
if (Array.isArray(fromItem) && fromItem.length) {
return fromItem
}
if (Array.isArray(payload.testMerchantDivisions)) {
return payload.testMerchantDivisions
}
return []
}
/** 合并接口数据并写入规范化 orderCode、subProgress、testMerchantDivisions */
export function normalizeDivisionTestPayload(payload = {}) {
const orderCode = resolveDivisionTestOrderCode(payload)
const subProgress = resolveDivisionTestSubProgress(payload, payload.subProgress)
const progress = resolveDivisionTestProgress(payload, payload.progress)
const testMerchantDivisions = resolveDivisionTestMerchantDivisions(payload)
return {
...payload,
orderCode,
subProgress,
progress,
testMerchantDivisions
}
}
/**
* 与 index.vue getGoodsTypeGroupRules 全量提交路径一致:
* 仅 touched 或 sessionAdded 的 Tab 进入 indicesForIncremental。
*
* @param {Array<object>} editableTabs
* @returns {number[]}
*/
export function resolveIndicesForIncrementalSubmit(editableTabs) {
const indices = []
const tabs = editableTabs || []
for (let i = 0; i < tabs.length; i++) {
const tab = tabs[i]
if (
tab
&& String(tab.name) !== "add"
&& (tab.classificationUserTouched === true || tab.sessionAdded === true)
) {
indices.push(i)
}
}
return indices
}
/** testMerchantDivisions 展示顺序:targetMerchantType 3 → 2 → 1(4 与 1 同为平台方) */
const TARGET_MERCHANT_TYPE_DISPLAY_ORDER = { 3: 0, 2: 1, 1: 2, 4: 2 }
/**
* @param {object} item testMerchantDivisions 单项
* @returns {number} 越小越靠前
*/
export function getTargetMerchantTypeSortKey(item) {
if (item == null) return 99
const n = Number(item.targetMerchantType)
if (!Number.isFinite(n)) return 99
return TARGET_MERCHANT_TYPE_DISPLAY_ORDER[n] ?? 50
}
export function getMerchantTargetType(item) {
if (item == null) return 99
const tt = Number(item.targetType ?? item.merchantTargetType ?? item.applicationObjectType)
if (Number.isFinite(tt)) return tt
if (item.platformFlag === 'Y' || item.isPlatform === true) return 4
return 99
}
export function isPlatformMerchant(item) {
const tmt = Number(item?.targetMerchantType)
if (tmt === 1 || tmt === 4) return true
const tt = getMerchantTargetType(item)
return tt === 3 || tt === 4
}
/** 按 testMerchantDivisions[].targetMerchantType 顺序 3、2、1 展示;同类型按商户名 */
export function sortDivisionTestMerchants(list) {
if (!Array.isArray(list)) return []
return [...list].sort((a, b) => {
const oa = getTargetMerchantTypeSortKey(a)
const ob = getTargetMerchantTypeSortKey(b)
if (oa !== ob) return oa - ob
return (a.merchantName || '').localeCompare(b.merchantName || '', 'zh')
})
}
const MAX_AMOUNT = 3.5
/**
* 详情回显 distributionMoney 为 0 时视为已完成,不参与 money.valid 提交
*(用户输入 confirmDivisionMoney 为 0 的待确认商户仍应提交)
*/
export function isMerchantCompletedFromDetail(item) {
if (!item) return false
const v = item.distributionMoney
if (v == null || v === '') return false
const n = Number(v)
return Number.isFinite(n) && n === 0
}
/** 步骤3待提交商户(排除详情已为 0 的已完成商户) */
export function getStep3PendingMerchants(merchants) {
return (merchants || []).filter((m) => !isMerchantCompletedFromDetail(m))
}
export function isValidAmountInput(value) {
if (value === '' || value == null) return false
const s = String(value).trim()
if (!/^\d+(\.\d{1,2})?$/.test(s)) return false
const n = parseFloat(s)
return Number.isFinite(n) && n >= 0 && n <= MAX_AMOUNT
}
/**
* @param {object[]} merchants 步骤3表单行(含 confirmDivisionMoney)
* @returns {{ valid: boolean, message?: string }}
*/
export function validateStep3Amounts(merchants) {
const pending = getStep3PendingMerchants(merchants)
if (pending.length === 0) {
return { valid: false, message: '没有待确认到账的商户' }
}
for (const item of pending) {
const val = item.confirmDivisionMoney
if (!isValidAmountInput(val)) {
return { valid: false, message: '请填写正确的到账金额(0-3.5,最多两位小数)' }
}
}
return { valid: true }
}
function step3MerchantKey(item) {
return String(item?.merchantId ?? item?.merchantName ?? '')
}
/** 同步 props 商户列表时保留步骤3已填写的 confirmDivisionMoney */
export function mergeStep3FormMerchants(merchants, previousFormRows) {
const prevMap = new Map()
;(previousFormRows || []).forEach((m) => {
const key = step3MerchantKey(m)
if (key) prevMap.set(key, m.confirmDivisionMoney)
})
return (merchants || []).map((m) => {
const key = step3MerchantKey(m)
const prev = prevMap.get(key)
return {
...m,
confirmDivisionMoney: prev !== undefined ? prev : (m.confirmDivisionMoney ?? '')
}
})
}
export function buildStep3SubmitMerchants(displayMerchants, formMerchants) {
const formMap = new Map()
;(formMerchants || []).forEach((m) => {
const key = step3MerchantKey(m)
if (key) formMap.set(key, m)
})
return getStep3PendingMerchants(displayMerchants).map((m) => {
const key = step3MerchantKey(m)
const form = formMap.get(key) || m
return {
...m,
confirmDivisionMoney: form.confirmDivisionMoney
}
})
}
...@@ -33,6 +33,12 @@ export function mergeReconciliationRuleServerFields(snapshot, cachedRule) { ...@@ -33,6 +33,12 @@ export function mergeReconciliationRuleServerFields(snapshot, cachedRule) {
if (cachedRule.id != null && String(cachedRule.id).trim() !== "") { if (cachedRule.id != null && String(cachedRule.id).trim() !== "") {
out.id = cachedRule.id out.id = cachedRule.id
} }
if (
cachedRule.groupSettleRuleId != null
&& String(cachedRule.groupSettleRuleId).trim() !== ""
) {
out.groupSettleRuleId = cachedRule.groupSettleRuleId
}
return out return out
} }
......
# 真实脱敏 Fixture
将脱敏后的详情/提交 JSON 放在此目录,文件名建议:
- `detail-with-special.json` — 全部品类 + 多特殊品类详情响应
- `submit-after-delete-special.json` — 删光特殊品类后的 submit body
单测通过 `loadFixture(name)` 优先加载 `real/`,不存在则回退 `synthetic/`。
{
"goodsTypeGroupRules": [
{
"groupType": 1,
"groupDivisionRuleId": 17805,
"groupSettleRuleId": 17942,
"shop4sDeductChargeFlag": "Y",
"partnerDeductChargeFlag": "Y",
"goodsCostFlag": "N",
"expenseCategoryRules": [
{
"calculateMode": 1,
"expenseCategoryCalculateType": 1,
"expenseCategoryValue": "10"
}
],
"merchantDistributionRules": [{ "merchantId": "100" }],
"owningMerchantDistributionRules": [{ "merchantId": "100" }]
}
]
}
{
"goodsTypeGroupRules": [
{
"groupType": 1,
"groupDivisionRuleId": 17805,
"groupSettleRuleId": 17942,
"shop4sDeductChargeFlag": "Y",
"partnerDeductChargeFlag": "Y",
"goodsCostFlag": "N",
"expenseCategoryRules": [
{
"calculateMode": 1,
"expenseCategoryCalculateType": 1,
"expenseCategoryValue": "10"
}
],
"merchantDistributionRules": [{ "merchantId": "100" }],
"owningMerchantDistributionRules": [{ "merchantId": "100" }]
},
{
"groupType": 2,
"groupDivisionRuleId": 17806,
"groupSettleRuleId": 17943,
"goodsSource": 1,
"goodsTypeGroupRelations": [{ "goodsType": "G1" }],
"shop4sDeductChargeFlag": "Y",
"partnerDeductChargeFlag": "Y",
"goodsCostFlag": "N",
"expenseCategoryRules": [
{
"calculateMode": 1,
"expenseCategoryCalculateType": 1,
"expenseCategoryValue": "10"
}
],
"merchantDistributionRules": [{ "merchantId": "100" }],
"owningMerchantDistributionRules": [{ "merchantId": "100" }]
},
{
"groupType": 2,
"groupDivisionRuleId": 17808,
"groupSettleRuleId": 17944,
"goodsSource": 1,
"goodsTypeGroupRelations": [{ "goodsType": "G2" }],
"shop4sDeductChargeFlag": "Y",
"partnerDeductChargeFlag": "Y",
"goodsCostFlag": "N",
"expenseCategoryRules": [
{
"calculateMode": 1,
"expenseCategoryCalculateType": 1,
"expenseCategoryValue": "10"
}
],
"merchantDistributionRules": [{ "merchantId": "100" }],
"owningMerchantDistributionRules": [{ "merchantId": "100" }]
}
]
}
{
"description": "删光特殊品类 Tab 后期望的增量提交形态(合成)",
"incrementalRules": [
{
"groupType": 1,
"groupDivisionRuleId": "17805",
"groupSettleRuleId": 17942,
"type": "UPDATE",
"tabPaneIndex": 0
}
],
"pendingDeletes": [
{ "groupType": 2, "groupDivisionRuleId": "17806" },
{ "groupType": 2, "groupDivisionRuleId": "17808" }
],
"mergedSubmitExpectation": {
"firstEntryType": "UPDATE",
"firstEntryId": "17805",
"deleteIds": ["17806", "17808"]
}
}
import {
appendDeleteOpsToIncremental
} from "@/views/systemConfig/merchant/financialRules/utils/buildGoodsTypeGroupIncrementalRules"
import { GOODS_TYPE_GROUP_RULE_OP } from "@/views/systemConfig/merchant/financialRules/utils/goodsTypeGroupRuleOpType"
describe("appendDeleteOpsToIncremental", () => {
test("空 deletedEntries → 原样返回", () => {
const base = [{ type: GOODS_TYPE_GROUP_RULE_OP.UPDATE, groupDivisionRuleId: "17805" }]
expect(appendDeleteOpsToIncremental(base, null)).toEqual(base)
expect(appendDeleteOpsToIncremental(base, [])).toEqual(base)
})
test("追加 DELETE(字符串 id)", () => {
const base = [{ type: GOODS_TYPE_GROUP_RULE_OP.UPDATE, groupDivisionRuleId: "17805" }]
const out = appendDeleteOpsToIncremental(base, ["17806"])
expect(out).toHaveLength(2)
expect(out[1]).toEqual({
type: GOODS_TYPE_GROUP_RULE_OP.DELETE,
groupDivisionRuleId: "17806"
})
})
test("追加 DELETE(完整规则对象)", () => {
const base = [{ type: GOODS_TYPE_GROUP_RULE_OP.UPDATE, groupDivisionRuleId: "17805" }]
const out = appendDeleteOpsToIncremental(base, [
{ groupType: 2, groupDivisionRuleId: 17808, groupSettleRuleId: 17944 }
])
expect(out[1].type).toBe(GOODS_TYPE_GROUP_RULE_OP.DELETE)
expect(out[1].groupDivisionRuleId).toBe("17808")
expect(out[1].groupType).toBe(2)
expect(out[1].groupSettleRuleId).toBe(17944)
expect(out[1].tabPaneIndex).toBeUndefined()
})
test("deletedEntries 内重复 id → 去重", () => {
const out = appendDeleteOpsToIncremental([], ["17806", "17806", 17806])
expect(out).toHaveLength(1)
expect(out[0].groupDivisionRuleId).toBe("17806")
})
test("与 incremental 已有 DELETE 重复 → 跳过", () => {
const base = [
{ type: GOODS_TYPE_GROUP_RULE_OP.DELETE, groupDivisionRuleId: "17806" }
]
const out = appendDeleteOpsToIncremental(base, ["17806", "17808"])
expect(out).toHaveLength(2)
expect(out[1].groupDivisionRuleId).toBe("17808")
})
test("无 id 的对象 entry → 不产出 DELETE", () => {
const out = appendDeleteOpsToIncremental([], [{ groupType: 2, sessionAdded: true }])
expect(out).toHaveLength(0)
})
test("id 字段 fallback", () => {
const out = appendDeleteOpsToIncremental([], [{ id: "99", groupType: 2 }])
expect(out[0].groupDivisionRuleId).toBe("99")
})
})
import {
buildDivisionRuleTestParams,
buildDivisionRuleTestRetestParams,
buildDivisionRuleTestMoneyValidParams,
buildDivisionRuleTestUpdateMainProgressParams
} from "@/views/systemConfig/merchant/financialRules/utils/buildDivisionRuleTestParams"
describe("buildDivisionRuleTestParams", () => {
it("includes divisionRuleId from financial detail, not goodsTypeGroupDivisionId", () => {
const params = buildDivisionRuleTestParams({
merchantId: "m1",
sceneType: 1,
paymentChannelId: "ch1",
divisionRuleId: 4928,
baseSceneCode: "SC001"
})
expect(params).toEqual({
merchantId: "m1",
sceneType: 1,
paymentChannelId: "ch1",
divisionRuleId: 4928,
baseSceneCode: "SC001"
})
expect(params.goodsTypeGroupDivisionId).toBeUndefined()
})
it("omits empty divisionRuleId", () => {
const params = buildDivisionRuleTestParams({
merchantId: "m1",
sceneType: 1,
divisionRuleId: ""
})
expect(params.divisionRuleId).toBeUndefined()
})
it("buildDivisionRuleTestRetestParams only divisionRuleId and paymentChannelId", () => {
const params = buildDivisionRuleTestRetestParams({
divisionRuleId: 4928,
paymentChannelId: "ch1",
merchantId: "m1",
sceneType: 1
})
expect(params).toEqual({
divisionRuleId: 4928,
paymentChannelId: "ch1"
})
})
it("buildDivisionRuleTestMoneyValidParams uses divisionRuleId and paymentChannelId", () => {
const testMerchantDivisions = [
{ merchantId: "m1", distributionMoney: "1.0", confirmDivisionMoney: "1.0" }
]
const params = buildDivisionRuleTestMoneyValidParams({
testObj: { paymentChannelId: "ch1", divisionRuleId: 100 },
testMerchantDivisions
})
expect(params).toEqual({
divisionRuleId: 100,
paymentChannelId: "ch1",
testMerchantDivisions
})
expect(params.goodsTypeGroupDivisionId).toBeUndefined()
})
it("buildDivisionRuleTestMoneyValidParams divisionRuleId from override", () => {
const params = buildDivisionRuleTestMoneyValidParams({
testObj: { paymentChannelId: "ch2" },
testMerchantDivisions: [],
divisionRuleId: 4928
})
expect(params.divisionRuleId).toBe(4928)
expect(params.paymentChannelId).toBe("ch2")
})
it("buildDivisionRuleTestUpdateMainProgressParams three fields", () => {
const params = buildDivisionRuleTestUpdateMainProgressParams({
divisionRuleId: 4928,
paymentChannelId: "ch1",
progress: 2
})
expect(params).toEqual({
divisionRuleId: 4928,
paymentChannelId: "ch1",
progress: 2
})
})
it("buildDivisionRuleTestUpdateMainProgressParams omits invalid progress", () => {
const params = buildDivisionRuleTestUpdateMainProgressParams({
divisionRuleId: 1,
paymentChannelId: "ch1",
progress: 0
})
expect(params.progress).toBeUndefined()
})
})
/**
* @jest-environment jsdom
*/
import { buildFullMergedGoodsTypeGroupRules } from "@/views/systemConfig/merchant/financialRules/utils/buildFullMergedGoodsTypeGroupRules"
import { loadFixture } from "./helpers/financialRulesTestHelpers"
describe("buildFullMergedGoodsTypeGroupRules", () => {
test("validated 槽位用快照,其余用缓存 fillDj", () => {
const fixture = loadFixture("all-plus-special-tabs")
const caches = fixture.goodsTypeGroupRules
const validated = { 1: { groupType: 2, groupDivisionRuleId: "validated-only" } }
const out = buildFullMergedGoodsTypeGroupRules({
tabCount: 3,
validatedByIndex: validated,
slotCaches: caches
})
expect(out).toHaveLength(3)
expect(out[0].groupDivisionRuleId).toBe(17805)
expect(out[1].groupDivisionRuleId).toBe("validated-only")
expect(out[2].groupDivisionRuleId).toBe(17808)
})
test("空缓存槽位 → fillDj 空对象", () => {
const out = buildFullMergedGoodsTypeGroupRules({
tabCount: 1,
validatedByIndex: {},
slotCaches: []
})
expect(out).toHaveLength(1)
expect(out[0]).toEqual({})
})
})
import {
buildStep2DisplayMerchants,
buildStep3VerifyMerchants,
isMerchantTestCompleted,
randomAllocatePool,
sumDisplayDivisionMoney,
isTotalProfitAmountValid,
PLATFORM_FIXED_AMOUNT,
ALLOCATABLE_POOL
} from "@/views/systemConfig/merchant/financialRules/utils/buildStep2DisplayMerchants"
describe("buildStep2DisplayMerchants", () => {
it("randomAllocatePool sums to 3", () => {
const amounts = randomAllocatePool(
[{}, {}, {}],
() => 0.5
)
const sum = amounts.reduce((a, b) => a + b, 0)
expect(Math.round(sum * 100)).toBe(Math.round(ALLOCATABLE_POOL * 100))
})
it("shows distributionMoney in step2 input", () => {
const list = [
{ merchantName: "流量", targetType: 1, distributionMoney: "2.5" },
{ merchantName: "平台", targetType: 4, distributionMoney: "0.5" }
]
const display = buildStep2DisplayMerchants(list)
expect(display.find((m) => m.merchantName === "流量").displayDivisionMoney).toBe("2.5")
expect(display.find((m) => m.merchantName === "平台").displayDivisionMoney).toBe("0.5")
})
it("distributionMoney 0 or empty means testCompleted", () => {
expect(isMerchantTestCompleted({ distributionMoney: 0 })).toBe(true)
expect(isMerchantTestCompleted({ distributionMoney: "0" })).toBe(true)
expect(isMerchantTestCompleted({ distributionMoney: "" })).toBe(true)
expect(isMerchantTestCompleted({ distributionMoney: null })).toBe(true)
expect(isMerchantTestCompleted({ distributionMoney: "1.5" })).toBe(false)
const display = buildStep2DisplayMerchants([
{ merchantName: "已测", targetType: 2, distributionMoney: 0 },
{ merchantName: "待测", targetType: 1, distributionMoney: "3" }
])
expect(display.find((m) => m.merchantName === "已测").testCompleted).toBe(true)
expect(display.find((m) => m.merchantName === "已测").displayDivisionMoney).toBe("")
expect(display.find((m) => m.merchantName === "待测").testCompleted).toBe(false)
expect(display.find((m) => m.merchantName === "待测").displayDivisionMoney).toBe("3")
})
it("platform fallback when no distributionMoney", () => {
const list = [
{ merchantName: "流量", targetType: 1, distributionMoney: "3" },
{ merchantName: "平台", targetType: 4, distributionMoney: "0.5" }
]
const display = buildStep2DisplayMerchants(list, { randomFn: () => 1 })
expect(display.find((m) => m.merchantName === "平台").displayDivisionMoney).toBe("0.5")
})
it("isTotalProfitAmountValid excludes completed merchants", () => {
const merchants = [
{ testCompleted: true, displayDivisionMoney: "" },
{ testCompleted: false, displayDivisionMoney: "0.5" },
{ testCompleted: false, displayDivisionMoney: "3" }
]
expect(isTotalProfitAmountValid(merchants)).toBe(true)
expect(sumDisplayDivisionMoney(merchants)).toBe(3.5)
})
it("uses cache when distributionMoney missing on refetch", () => {
const list = [
{ merchantId: "1", merchantName: "A", targetType: 1, distributionMoney: "3" }
]
const first = buildStep2DisplayMerchants(list)
const cache = { 1: first[0].displayDivisionMoney }
const second = buildStep2DisplayMerchants(
[{ merchantId: "1", merchantName: "A", targetType: 1, distributionMoney: "3" }],
{ randomFn: () => 0.9, cachedAllocations: cache }
)
expect(second[0].displayDivisionMoney).toBe("3")
})
it("buildStep3VerifyMerchants shares testCompleted", () => {
const list = [
{ merchantName: "A", distributionMoney: 0 },
{ merchantName: "B", distributionMoney: "1.2", confirmDivisionMoney: "1.2" }
]
const step3 = buildStep3VerifyMerchants(list)
expect(step3[0].testCompleted).toBe(true)
expect(step3[1].testCompleted).toBe(false)
expect(step3[1].confirmDivisionMoney).toBe("1.2")
})
})
/**
* @jest-environment jsdom
*/
import { collectGoodsTypeGroupRulesFromTabs } from "@/views/systemConfig/merchant/financialRules/utils/collectGoodsTypeGroupRulesFromTabs"
describe("collectGoodsTypeGroupRulesFromTabs", () => {
test("激活 Tab 走 mergeChildClassificationPayload", () => {
const caches = [
{ groupType: 1, groupDivisionRuleId: 17805, expenseCategoryRules: [{ id: 1 }] }
]
const tabs = [{ name: "1", title: "全部品类" }]
const out = collectGoodsTypeGroupRulesFromTabs({
editableTabs: tabs,
slotCaches: caches,
getChildPayloadByPaneName: () => ({ groupType: 1, expenseCategoryRules: [{ id: 1 }] })
})
expect(out[0].groupDivisionRuleId).toBe(17805)
})
test("非激活 Tab 读缓存", () => {
const caches = [
{ groupType: 1, groupDivisionRuleId: 17805 },
{ groupType: 2, groupDivisionRuleId: 17806 }
]
const tabs = [{ name: "1" }, { name: "2" }]
const out = collectGoodsTypeGroupRulesFromTabs({
editableTabs: tabs,
slotCaches: caches,
getChildPayloadByPaneName: (name) => (name === "1" ? { groupType: 1 } : null)
})
expect(out[1].groupDivisionRuleId).toBe(17806)
expect(out[1].groupType).toBe(2)
})
})
import {
isDivisionRuleAutoTestPending,
hasPendingDivisionRuleAutoTest,
findPendingDivisionRuleAutoTestIndices
} from "@/views/systemConfig/merchant/financialRules/utils/divisionRuleAutoTest"
describe("divisionRuleAutoTest", () => {
it("isDivisionRuleAutoTestPending: strict testFlag N and autoFlag Y", () => {
expect(
isDivisionRuleAutoTestPending({ autoFlag: "Y", testFlag: "N" })
).toBe(true)
expect(
isDivisionRuleAutoTestPending({ autoFlag: "Y", testFlag: "Y" })
).toBe(false)
expect(
isDivisionRuleAutoTestPending({ autoFlag: "Y" })
).toBe(false)
expect(
isDivisionRuleAutoTestPending({ autoFlag: "N", testFlag: "N" })
).toBe(false)
})
it("hasPendingDivisionRuleAutoTest", () => {
const list = [
{ autoFlag: "Y", testFlag: "Y" },
{ autoFlag: "Y", testFlag: "N" }
]
expect(hasPendingDivisionRuleAutoTest(list)).toBe(true)
expect(hasPendingDivisionRuleAutoTest([{ autoFlag: "Y", testFlag: "Y" }])).toBe(false)
})
it("findPendingDivisionRuleAutoTestIndices", () => {
const list = [
{ autoFlag: "N", testFlag: "N" },
{ autoFlag: "Y", testFlag: "N" },
{ autoFlag: "Y", testFlag: "Y" }
]
expect(findPendingDivisionRuleAutoTestIndices(list)).toEqual([1])
})
})
import {
mapSubProgressToUi,
isDivisionTestInProgress,
isDivisionTestPassed,
canNavigateToStep,
isStepReadOnly,
buildStepCompletedFlags,
resolveMaxReachedStepFromSubProgress,
resolveInitialWizardSteps
} from "@/views/systemConfig/merchant/financialRules/utils/divisionTestStepProgress"
describe("divisionTestStepProgress", () => {
it("isDivisionTestInProgress", () => {
expect(isDivisionTestInProgress(34)).toBe(true)
expect(isDivisionTestInProgress(35)).toBe(true)
expect(isDivisionTestInProgress(36)).toBe(true)
expect(isDivisionTestInProgress(31)).toBe(true)
expect(isDivisionTestInProgress(30)).toBe(false)
})
it("isDivisionTestPassed", () => {
expect(isDivisionTestPassed(37)).toBe(true)
expect(isDivisionTestPassed(34)).toBe(false)
})
it("mapSubProgressToUi: 34 unpaid", () => {
const ui = mapSubProgressToUi(34, { orderCode: "" })
expect(ui.step1Paid).toBe(false)
expect(ui.currentStep).toBeUndefined()
})
it("mapSubProgressToUi: 35 paid but no display step mapping", () => {
const ui = mapSubProgressToUi(35, { orderCode: "ORD001" })
expect(ui.step1Paid).toBe(true)
expect(ui.currentStep).toBeUndefined()
})
it("canNavigateToStep uses maxReachedStep only", () => {
expect(canNavigateToStep(2, { maxReachedStep: 1, step1Paid: true })).toBe(false)
expect(canNavigateToStep(2, { maxReachedStep: 2 })).toBe(true)
expect(canNavigateToStep(3, { maxReachedStep: 2 })).toBe(false)
})
it("isStepReadOnly when viewing earlier step", () => {
expect(isStepReadOnly(1, { maxReachedStep: 2 })).toBe(true)
expect(isStepReadOnly(2, { maxReachedStep: 2 })).toBe(false)
})
it("buildStepCompletedFlags", () => {
expect(buildStepCompletedFlags(true, 2)).toEqual([true, false, false])
expect(buildStepCompletedFlags(true, 3)).toEqual([true, true, false])
})
it("resolveMaxReachedStepFromSubProgress", () => {
expect(resolveMaxReachedStepFromSubProgress(34)).toBe(1)
expect(resolveMaxReachedStepFromSubProgress(35)).toBe(2)
expect(resolveMaxReachedStepFromSubProgress(36)).toBe(3)
})
it("resolveInitialWizardSteps: progress takes priority over subProgress", () => {
expect(resolveInitialWizardSteps(35, 3)).toEqual({ viewStep: 3, maxReachedStep: 3 })
expect(resolveInitialWizardSteps(34, 3)).toEqual({ viewStep: 3, maxReachedStep: 3 })
expect(resolveInitialWizardSteps(36, 1)).toEqual({ viewStep: 1, maxReachedStep: 3 })
})
it("resolveInitialWizardSteps: 36 without progress falls back to step3", () => {
expect(resolveInitialWizardSteps(36)).toEqual({ viewStep: 3, maxReachedStep: 3 })
})
it("resolveInitialWizardSteps: 35 without progress defaults step1", () => {
expect(resolveInitialWizardSteps(35)).toEqual({ viewStep: 1, maxReachedStep: 2 })
expect(resolveInitialWizardSteps(35, 2)).toEqual({ viewStep: 2, maxReachedStep: 2 })
})
it("resolveInitialWizardSteps: 34 without progress stays step1", () => {
expect(resolveInitialWizardSteps(34)).toEqual({ viewStep: 1, maxReachedStep: 1 })
})
})
/**
* @jest-environment jsdom
*/
import { ensureAllCategoryRuleFirst } from "@/views/systemConfig/merchant/financialRules/utils/ensureAllCategoryRuleFirst"
import { buildGoodsTypeGroupIncrementalRules } from "@/views/systemConfig/merchant/financialRules/utils/buildGoodsTypeGroupIncrementalRules"
import { GOODS_TYPE_GROUP_RULE_OP } from "@/views/systemConfig/merchant/financialRules/utils/goodsTypeGroupRuleOpType"
import { mergeChildClassificationPayload } from "@/views/systemConfig/merchant/financialRules/utils/mergeClassificationPayload"
import {
getStableReconciliationRuleId,
mergeReconciliationRuleServerFields
} from "@/views/systemConfig/merchant/merchantStep/utils/reconciliationIncrementalRules"
import {
mergeActiveTabPayload,
mergePreparedWithCache,
simulateRemoveTab
} from "./helpers/financialRulesTestHelpers"
function resolveIncrementalType(preparedRule, cachedRule) {
const merged = mergeReconciliationRuleServerFields(preparedRule, cachedRule)
const idStr = getStableReconciliationRuleId(merged)
return idStr ? GOODS_TYPE_GROUP_RULE_OP.UPDATE : GOODS_TYPE_GROUP_RULE_OP.ADD
}
describe("ensureAllCategoryRuleFirst", () => {
test("空数组 → 默认 { groupType: 1 }", () => {
expect(ensureAllCategoryRuleFirst(null)).toEqual([{ groupType: 1 }])
})
test("groupType 1 已在 index 0 且带 groupDivisionRuleId 时原样保留", () => {
const rules = [
{
groupType: 1,
groupDivisionRuleId: 17805,
groupSettleRuleId: 17942
}
]
expect(ensureAllCategoryRuleFirst(rules)).toEqual(rules)
expect(getStableReconciliationRuleId(rules[0])).toBe("17805")
})
test("首条为特殊品类、groupType 1 在后时:整条移至 index 0(保留 id)", () => {
const input = [
{ groupType: 2, groupDivisionRuleId: "sp-1" },
{
groupType: 1,
groupDivisionRuleId: 17805,
groupSettleRuleId: 17942
}
]
const out = ensureAllCategoryRuleFirst(input)
expect(out).toHaveLength(2)
expect(out[0].groupType).toBe(1)
expect(out[0].groupDivisionRuleId).toBe(17805)
expect(out[0].groupSettleRuleId).toBe(17942)
expect(out[1].groupType).toBe(2)
})
test("仅有特殊品类时 prepend 空壳全部品类", () => {
const out = ensureAllCategoryRuleFirst([
{ groupType: 2, groupDivisionRuleId: "sp-1" }
])
expect(out[0]).toEqual({ groupType: 1 })
expect(out[1].groupDivisionRuleId).toBe("sp-1")
})
})
describe("goodsTypeGroup ADD type reason (API 有 id)", () => {
test("Tab0 缓存有 groupDivisionRuleId 17805 → UPDATE", () => {
const rules = ensureAllCategoryRuleFirst([
{ groupType: 2, groupDivisionRuleId: "sp-1" },
{ groupType: 1, groupDivisionRuleId: 17805, groupSettleRuleId: 17942 }
])
const cached = rules[0]
const prepared = { groupType: 1, expenseCategoryRules: [{}] }
expect(resolveIncrementalType(prepared, cached)).toBe(
GOODS_TYPE_GROUP_RULE_OP.UPDATE
)
const validatedByIndex = {
0: mergePreparedWithCache(prepared, cached)
}
const out = buildGoodsTypeGroupIncrementalRules(validatedByIndex, [0], false)
expect(out[0].type).toBe(GOODS_TYPE_GROUP_RULE_OP.UPDATE)
expect(out[0].groupDivisionRuleId).toBe(17805)
expect(out[0].groupSettleRuleId).toBe(17942)
})
test("mergeChildClassificationPayload 保留 groupDivisionRuleId / groupSettleRuleId", () => {
const prev = {
groupType: 1,
groupDivisionRuleId: 17805,
groupSettleRuleId: 17942
}
const { next } = mergeChildClassificationPayload(
{ groupType: 1, expenseCategoryRules: [] },
prev
)
expect(next.groupDivisionRuleId).toBe(17805)
expect(next.groupSettleRuleId).toBe(17942)
})
})
describe("removeTab / getAllParams id retention", () => {
test("getAllParams merge 后 index 0 仍保留 groupDivisionRuleId", () => {
const slotCache = {
groupType: 1,
groupDivisionRuleId: 17805,
groupSettleRuleId: 17942,
expenseCategoryRules: [{ id: 1 }]
}
const childPayload = {
groupType: 1,
expenseCategoryRules: [{ id: 1 }]
}
const merged = mergeActiveTabPayload(childPayload, slotCache)
expect(merged.groupDivisionRuleId).toBe(17805)
expect(merged.groupSettleRuleId).toBe(17942)
})
test("删 Tab 后 index 0 保留 id 且 incremental type 为 UPDATE", () => {
const prevRules = [
{
groupType: 1,
groupDivisionRuleId: 17805,
groupSettleRuleId: 17942,
expenseCategoryRules: []
},
{ groupType: 2, groupDivisionRuleId: 17806, groupSettleRuleId: 17943 },
{ groupType: 2, groupDivisionRuleId: 17808, groupSettleRuleId: 17944 }
]
const allParams = [
{ groupType: 1, expenseCategoryRules: [] },
{ groupType: 2, expenseCategoryRules: [] },
{ groupType: 2, expenseCategoryRules: [] }
]
const mergedAllParams = allParams.map((payload, i) => {
const { next } = mergeChildClassificationPayload(payload, prevRules[i])
return next
})
const removedTabIndex = 1
const remaining = simulateRemoveTab(mergedAllParams, prevRules, removedTabIndex)
expect(remaining).toHaveLength(2)
expect(remaining[0].groupDivisionRuleId).toBe(17805)
expect(remaining[0].groupSettleRuleId).toBe(17942)
expect(remaining[1].groupDivisionRuleId).toBe(17808)
const prepared = { groupType: 1, expenseCategoryRules: [] }
expect(resolveIncrementalType(prepared, remaining[0])).toBe(
GOODS_TYPE_GROUP_RULE_OP.UPDATE
)
const validatedByIndex = {
0: mergePreparedWithCache(prepared, remaining[0])
}
const out = buildGoodsTypeGroupIncrementalRules(validatedByIndex, [0], false)
expect(out[0].type).toBe(GOODS_TYPE_GROUP_RULE_OP.UPDATE)
expect(out[0].groupDivisionRuleId).toBe(17805)
expect(out[0].groupSettleRuleId).toBe(17942)
})
test("删光特殊品类后仅剩全部品类仍带 id → UPDATE", () => {
const prevRules = [
{
groupType: 1,
groupDivisionRuleId: 17805,
groupSettleRuleId: 17942
},
{ groupType: 2, groupDivisionRuleId: 17806 },
{ groupType: 2, groupDivisionRuleId: 17808 }
]
let allParams = prevRules.map((cached) =>
mergeChildClassificationPayload(
{ groupType: cached.groupType, expenseCategoryRules: [] },
cached
).next
)
let prevCache = prevRules.slice()
allParams = simulateRemoveTab(allParams, prevCache, 2)
prevCache = simulateRemoveTab(prevCache, prevCache, 2)
allParams = simulateRemoveTab(allParams, prevCache, 1)
expect(allParams).toHaveLength(1)
expect(allParams[0].groupDivisionRuleId).toBe(17805)
const validatedByIndex = {
0: mergePreparedWithCache(
{ groupType: 1, expenseCategoryRules: [] },
allParams[0]
)
}
const out = buildGoodsTypeGroupIncrementalRules(validatedByIndex, [0], false)
expect(out[0].type).toBe(GOODS_TYPE_GROUP_RULE_OP.UPDATE)
expect(out[0].groupDivisionRuleId).toBe(17805)
})
})
import path from "path"
import fs from "fs"
import { mergeChildClassificationPayload } from "@/views/systemConfig/merchant/financialRules/utils/mergeClassificationPayload"
import { mergeReconciliationRuleServerFields } from "@/views/systemConfig/merchant/merchantStep/utils/reconciliationIncrementalRules"
import { applyRemoveTabToGoodsTypeGroupRules } from "@/views/systemConfig/merchant/financialRules/utils/applyRemoveTabToGoodsTypeGroupRules"
const FIXTURE_ROOT = path.join(__dirname, "../../../fixtures/financialRules")
/**
* 优先 real/,回退 synthetic/
* @param {string} name 不含扩展名
*/
export function loadFixture(name) {
const realPath = path.join(FIXTURE_ROOT, "real", `${name}.json`)
if (fs.existsSync(realPath)) {
return JSON.parse(fs.readFileSync(realPath, "utf8"))
}
const syntheticPath = path.join(FIXTURE_ROOT, "synthetic", `${name}.json`)
if (fs.existsSync(syntheticPath)) {
return JSON.parse(fs.readFileSync(syntheticPath, "utf8"))
}
throw new Error(`Fixture not found: ${name}`)
}
/** getAllParams 激活 Tab 分支:子组件 payload 与槽位缓存 merge */
export function mergeActiveTabPayload(childPayload, slotCache) {
const { next } = mergeChildClassificationPayload(childPayload, slotCache)
return next
}
/** removeTab 核心:splice + oldIdx 服务端 id 合并 */
export function simulateRemoveTab(rules, prevRules, removedTabIndex) {
const { remainingRules } = applyRemoveTabToGoodsTypeGroupRules({
goodsTypeGroupRules: rules,
tabIndex: removedTabIndex,
prevGoodsTypeGroupRules: prevRules,
removedRule: rules[removedTabIndex],
removedTabMeta: {},
isSessionOnlyNew: false
})
return remainingRules
}
export function mergeChildPayloadAtIndex(payload, cached) {
return mergeChildClassificationPayload(payload, cached).next
}
export function mergePreparedWithCache(prepared, cached) {
return mergeReconciliationRuleServerFields(prepared, cached)
}
/**
* @jest-environment jsdom
*/
import { mergeChildClassificationPayload } from "@/views/systemConfig/merchant/financialRules/utils/mergeClassificationPayload"
describe("mergeChildClassificationPayload", () => {
test("子组件空数组不覆盖缓存非空数组", () => {
const prev = {
expenseCategoryRules: [{ id: 1, calculateMode: 1 }],
merchantDistributionRules: [{ merchantId: "100" }],
owningMerchantDistributionRules: [{ merchantId: "100" }],
goodsTypes: [{ goodsType: "G1" }]
}
const { next } = mergeChildClassificationPayload(
{
expenseCategoryRules: [],
merchantDistributionRules: [],
owningMerchantDistributionRules: [],
goodsTypes: []
},
prev
)
expect(next.expenseCategoryRules).toEqual(prev.expenseCategoryRules)
expect(next.merchantDistributionRules).toEqual(prev.merchantDistributionRules)
expect(next.owningMerchantDistributionRules).toEqual(prev.owningMerchantDistributionRules)
expect(next.goodsTypes).toEqual(prev.goodsTypes)
})
test("payload 未带 expenseCategoryRules → 保留 base", () => {
const prev = { expenseCategoryRules: [{ id: 1 }] }
const { next } = mergeChildClassificationPayload({ groupType: 1 }, prev)
expect(next.expenseCategoryRules).toEqual(prev.expenseCategoryRules)
})
test("payload 带非空 expenseCategoryRules → 覆盖", () => {
const prev = { expenseCategoryRules: [{ id: 1 }] }
const incoming = [{ id: 2, calculateMode: 1 }]
const { next } = mergeChildClassificationPayload(
{ expenseCategoryRules: incoming },
prev
)
expect(next.expenseCategoryRules).toEqual(incoming)
})
test("保留 SERVER_ID_FIELDS", () => {
const prev = {
groupDivisionRuleId: 17805,
groupSettleRuleId: 17942,
id: "x"
}
const { next } = mergeChildClassificationPayload({ groupType: 1 }, prev)
expect(next.groupDivisionRuleId).toBe(17805)
expect(next.groupSettleRuleId).toBe(17942)
expect(next.id).toBe("x")
})
})
import {
FORCE_DIVISION_TEST_SUB_PROGRESS,
applyDivisionRuleTestGetMock,
mockDivisionRuleTestGetSubProgress
} from '@/api/mockDivisionRuleTestGetResponse'
describe('mockDivisionRuleTestGetSubProgress', () => {
it('applyDivisionRuleTestGetMock passes through when mock disabled', () => {
const raw = { subProgress: 10 }
expect(applyDivisionRuleTestGetMock(raw)).toBe(raw)
expect(applyDivisionRuleTestGetMock(raw).subProgress).toBe(10)
})
it('forces root and nested subProgress to 35', () => {
const raw = {
subProgress: 10,
divisionRuleTestItem: { subProgress: 20, orderCode: 'O1' },
divisionRuleTests: [
{
paymentChannelId: 1,
subProgress: 30,
divisionRuleTestItem: { subProgress: 31 }
}
]
}
const out = mockDivisionRuleTestGetSubProgress(raw)
expect(out.subProgress).toBe(FORCE_DIVISION_TEST_SUB_PROGRESS)
expect(out.divisionRuleTestItem.subProgress).toBe(35)
expect(out.divisionRuleTests[0].subProgress).toBe(35)
expect(out.divisionRuleTests[0].divisionRuleTestItem.subProgress).toBe(35)
expect(out.divisionRuleTestItem.orderCode).toBe('O1')
})
it('returns nullish as-is', () => {
expect(mockDivisionRuleTestGetSubProgress(null)).toBe(null)
expect(mockDivisionRuleTestGetSubProgress(undefined)).toBe(undefined)
})
})
...@@ -27,7 +27,8 @@ describe("normalizeRuleGoodsTypesForCategory", () => { ...@@ -27,7 +27,8 @@ describe("normalizeRuleGoodsTypesForCategory", () => {
categoryType: 2, categoryType: 2,
upgradeGoodsId: "u1", upgradeGoodsId: "u1",
upgradeGoodsName: "U", upgradeGoodsName: "U",
commodityCode: "C1" commodityCode: "C1",
merchantGoodsCode: "M1"
} }
] ]
} }
...@@ -38,7 +39,12 @@ describe("normalizeRuleGoodsTypesForCategory", () => { ...@@ -38,7 +39,12 @@ describe("normalizeRuleGoodsTypesForCategory", () => {
expect(item.goodsTypes).toEqual([]) expect(item.goodsTypes).toEqual([])
expect(item.upgradeGoods).toHaveLength(1) expect(item.upgradeGoods).toHaveLength(1)
expect(upgradeArr).toEqual([ expect(upgradeArr).toEqual([
{ upgradeGoodsId: "u1", upgradeGoodsName: "U", commodityCode: "C1" } {
upgradeGoodsId: "u1",
upgradeGoodsName: "U",
commodityCode: "C1",
merchantGoodsCode: "M1"
}
]) ])
expect(packageArr).toHaveLength(0) expect(packageArr).toHaveLength(0)
}) })
......
import {
getStableReconciliationRuleId,
mergeReconciliationRuleServerFields
} from "@/views/systemConfig/merchant/merchantStep/utils/reconciliationIncrementalRules"
describe("getStableReconciliationRuleId", () => {
test("优先 groupDivisionRuleId", () => {
expect(getStableReconciliationRuleId({ groupDivisionRuleId: 17805 })).toBe("17805")
expect(getStableReconciliationRuleId({ groupDivisionRuleId: "17805" })).toBe("17805")
})
test("groupDivisionRuleId 空时 fallback id", () => {
expect(getStableReconciliationRuleId({ id: 99 })).toBe("99")
expect(getStableReconciliationRuleId({ groupDivisionRuleId: "", id: "abc" })).toBe("abc")
})
test("无效输入 → 空字符串", () => {
expect(getStableReconciliationRuleId(null)).toBe("")
expect(getStableReconciliationRuleId({})).toBe("")
})
})
describe("mergeReconciliationRuleServerFields", () => {
test("prepared 无 id、cached 有 id → 保留", () => {
const prepared = { groupType: 1, expenseCategoryRules: [] }
const cached = {
groupDivisionRuleId: 17805,
groupSettleRuleId: 17942,
id: "server-id"
}
const out = mergeReconciliationRuleServerFields(prepared, cached)
expect(out.groupDivisionRuleId).toBe(17805)
expect(out.groupSettleRuleId).toBe(17942)
expect(out.id).toBe("server-id")
expect(out.groupType).toBe(1)
})
test("cached 有 id 时合并进 prepared", () => {
const prepared = { groupType: 1 }
const cached = { groupDivisionRuleId: "old" }
const out = mergeReconciliationRuleServerFields(prepared, cached)
expect(out.groupDivisionRuleId).toBe("old")
})
test("无 cached → 原样返回", () => {
const prepared = { groupType: 1 }
expect(mergeReconciliationRuleServerFields(prepared, null)).toEqual(prepared)
})
})
/**
* @jest-environment jsdom
*/
import {
appendDeleteOpsToIncremental,
buildGoodsTypeGroupIncrementalRules
} from "@/views/systemConfig/merchant/financialRules/utils/buildGoodsTypeGroupIncrementalRules"
import {
applyRemoveTabToGoodsTypeGroupRules,
collectPendingDeleteForRemovedTab,
mapTabMetaAfterTabRemoval
} from "@/views/systemConfig/merchant/financialRules/utils/applyRemoveTabToGoodsTypeGroupRules"
import { GOODS_TYPE_GROUP_RULE_OP } from "@/views/systemConfig/merchant/financialRules/utils/goodsTypeGroupRuleOpType"
import {
loadFixture,
mergeActiveTabPayload,
mergeChildPayloadAtIndex,
mergePreparedWithCache,
simulateRemoveTab
} from "./helpers/financialRulesTestHelpers"
describe("collectPendingDeleteForRemovedTab", () => {
test("sessionAdded Tab → 不产生 pendingDelete", () => {
expect(
collectPendingDeleteForRemovedTab({
removedRule: { groupType: 2 },
removedTabMeta: { sessionAdded: true },
isSessionOnlyNew: true
})
).toBeNull()
})
test("有 groupDivisionRuleId → 返回快照", () => {
const snap = collectPendingDeleteForRemovedTab({
removedRule: { groupType: 2, groupDivisionRuleId: 17806 },
removedTabMeta: {},
isSessionOnlyNew: false
})
expect(snap.groupDivisionRuleId).toBe(17806)
expect(snap.type).toBeUndefined()
})
})
describe("mapTabMetaAfterTabRemoval", () => {
test("删中间 Tab → revision/touched 按 oldIdx 映射", () => {
const prevTabsMeta = [
{ sessionAdded: false, ruleCacheRevision: 1, confirmedRuleCacheRevision: 1, classificationUserTouched: false },
{ sessionAdded: false, ruleCacheRevision: 5, confirmedRuleCacheRevision: 3, classificationUserTouched: true },
{ sessionAdded: true, ruleCacheRevision: 0, confirmedRuleCacheRevision: 0, classificationUserTouched: false }
]
const out = mapTabMetaAfterTabRemoval(prevTabsMeta, 1, 2)
expect(out[0].ruleCacheRevision).toBe(1)
expect(out[1].ruleCacheRevision).toBe(0)
expect(out[1].sessionAdded).toBe(true)
expect(out[1].classificationUserTouched).toBe(false)
})
})
describe("removeTab full chain", () => {
test("删 Tab 后 appendDeleteOpsToIncremental:UPDATE + DELETE", () => {
const fixture = loadFixture("all-plus-special-tabs")
const prevRules = fixture.goodsTypeGroupRules
let allParams = prevRules.map((cached) =>
mergeChildPayloadAtIndex(
{ groupType: cached.groupType, expenseCategoryRules: cached.expenseCategoryRules || [] },
cached
)
)
const pendingDeletes = []
let prevCache = prevRules.slice()
for (const tabIndex of [2, 1]) {
const removedRule = allParams[tabIndex]
const { remainingRules, pendingDelete } = applyRemoveTabToGoodsTypeGroupRules({
goodsTypeGroupRules: allParams,
tabIndex,
prevGoodsTypeGroupRules: prevCache,
removedRule,
removedTabMeta: { sessionAdded: false },
isSessionOnlyNew: false
})
if (pendingDelete) pendingDeletes.push(pendingDelete)
allParams = remainingRules
prevCache = simulateRemoveTab(prevCache, prevCache, tabIndex)
}
expect(allParams).toHaveLength(1)
expect(allParams[0].groupDivisionRuleId).toBe(17805)
const validatedByIndex = {
0: mergePreparedWithCache(allParams[0], allParams[0])
}
const incremental = buildGoodsTypeGroupIncrementalRules(validatedByIndex, [0], false)
const submit = appendDeleteOpsToIncremental(incremental, pendingDeletes)
expect(submit[0].type).toBe(GOODS_TYPE_GROUP_RULE_OP.UPDATE)
expect(submit[0].groupDivisionRuleId).toBe(17805)
const deleteIds = submit
.filter((r) => r.type === GOODS_TYPE_GROUP_RULE_OP.DELETE)
.map((r) => r.groupDivisionRuleId)
expect(deleteIds).toEqual(expect.arrayContaining(["17806", "17808"]))
})
test("getAllParams merge 后 index 0 仍保留 id", () => {
const slotCache = {
groupType: 1,
groupDivisionRuleId: 17805,
groupSettleRuleId: 17942
}
const merged = mergeActiveTabPayload({ groupType: 1 }, slotCache)
expect(merged.groupDivisionRuleId).toBe(17805)
})
})
import {
resolveDivisionTestOrderCode,
resolveDivisionTestSubProgress,
resolveDivisionTestMerchantDivisions,
resolveGoodsTypeGroupDivisionId,
resolveDivisionTestProgress,
normalizeDivisionTestPayload
} from "@/views/systemConfig/merchant/financialRules/utils/resolveDivisionTestOrderCode"
describe("resolveDivisionTestOrderCode", () => {
it("reads orderCode from divisionRuleTests[].divisionRuleTestItem", () => {
const code = resolveDivisionTestOrderCode({
paymentChannelId: "ch2",
divisionRuleTests: [
{
paymentChannelId: "ch1",
divisionRuleTestItem: { orderCode: "ORD001" }
},
{
paymentChannelId: "ch2",
divisionRuleTestItem: { orderCode: "ORD002" }
}
]
})
expect(code).toBe("ORD002")
})
it("reads from top-level divisionRuleTestItem", () => {
expect(
resolveDivisionTestOrderCode({
divisionRuleTestItem: { orderCode: "ORD003" }
})
).toBe("ORD003")
})
it("normalizeDivisionTestPayload sets orderCode on root", () => {
const payload = normalizeDivisionTestPayload({
divisionRuleTests: [
{ divisionRuleTestItem: { orderCode: "ORD004" } }
]
})
expect(payload.orderCode).toBe("ORD004")
})
it("resolveDivisionTestMerchantDivisions from divisionRuleTestItem", () => {
const list = resolveDivisionTestMerchantDivisions({
paymentChannelId: "ch2",
divisionRuleTests: [
{
paymentChannelId: "ch1",
divisionRuleTestItem: {
testMerchantDivisions: [{ merchantName: "A" }]
}
},
{
paymentChannelId: "ch2",
divisionRuleTestItem: {
testMerchantDivisions: [
{ merchantName: "B", distributionMoney: "1" }
]
}
}
]
})
expect(list).toHaveLength(1)
expect(list[0].merchantName).toBe("B")
expect(list[0].distributionMoney).toBe("1")
})
it("normalizeDivisionTestPayload sets testMerchantDivisions", () => {
const payload = normalizeDivisionTestPayload({
paymentChannelId: "ch1",
divisionRuleTests: [
{
paymentChannelId: "ch1",
divisionRuleTestItem: {
testMerchantDivisions: [{ merchantName: "X" }]
}
}
]
})
expect(payload.testMerchantDivisions).toHaveLength(1)
expect(payload.testMerchantDivisions[0].merchantName).toBe("X")
})
it("resolveDivisionTestSubProgress from divisionRuleTestItem", () => {
expect(
resolveDivisionTestSubProgress({
paymentChannelId: "ch1",
divisionRuleTests: [
{
paymentChannelId: "ch1",
divisionRuleTestItem: { subProgress: 35 }
}
]
})
).toBe(35)
})
it("resolveGoodsTypeGroupDivisionId from divisionRuleTests channel entry", () => {
expect(
resolveGoodsTypeGroupDivisionId({
paymentChannelId: "ch2",
divisionRuleTests: [
{
paymentChannelId: "ch1",
divisionRuleTestItem: { goodsTypeGroupDivisionId: 100 }
},
{
paymentChannelId: "ch2",
divisionRuleTestItem: { goodsTypeGroupDivisionId: 200 }
}
]
})
).toBe(200)
})
it("resolveGoodsTypeGroupDivisionId from top-level divisionRuleTestItem", () => {
expect(
resolveGoodsTypeGroupDivisionId({
divisionRuleTestItem: { goodsTypeGroupDivisionId: 300 }
})
).toBe(300)
})
it("resolveGoodsTypeGroupDivisionId from root", () => {
expect(
resolveGoodsTypeGroupDivisionId({ goodsTypeGroupDivisionId: 400 })
).toBe(400)
})
it("resolveDivisionTestProgress from divisionRuleTests channel entry", () => {
expect(
resolveDivisionTestProgress({
paymentChannelId: "ch2",
divisionRuleTests: [
{
paymentChannelId: "ch1",
divisionRuleTestItem: { progress: 1 }
},
{
paymentChannelId: "ch2",
divisionRuleTestItem: { progress: 2 }
}
]
})
).toBe(2)
})
it("normalizeDivisionTestPayload sets progress on root", () => {
const payload = normalizeDivisionTestPayload({
paymentChannelId: "ch1",
divisionRuleTests: [
{
paymentChannelId: "ch1",
divisionRuleTestItem: { progress: 3 }
}
]
})
expect(payload.progress).toBe(3)
})
})
import { resolveIndicesForIncrementalSubmit } from "@/views/systemConfig/merchant/financialRules/utils/resolveIndicesForIncrementalSubmit"
describe("resolveIndicesForIncrementalSubmit", () => {
test("无 touched/sessionAdded → 空数组", () => {
expect(
resolveIndicesForIncrementalSubmit([
{ name: "1", classificationUserTouched: false, sessionAdded: false },
{ name: "2", classificationUserTouched: false, sessionAdded: false }
])
).toEqual([])
})
test("touched Tab 进入", () => {
expect(
resolveIndicesForIncrementalSubmit([
{ name: "1", classificationUserTouched: true, sessionAdded: false },
{ name: "2", classificationUserTouched: false, sessionAdded: false }
])
).toEqual([0])
})
test("sessionAdded Tab 进入", () => {
expect(
resolveIndicesForIncrementalSubmit([
{ name: "1", classificationUserTouched: false, sessionAdded: false },
{ name: "2", classificationUserTouched: false, sessionAdded: true }
])
).toEqual([1])
})
test("排除 name=add", () => {
expect(
resolveIndicesForIncrementalSubmit([
{ name: "add", classificationUserTouched: true, sessionAdded: true }
])
).toEqual([])
})
})
import {
sortDivisionTestMerchants,
isPlatformMerchant
} from "@/views/systemConfig/merchant/financialRules/utils/sortDivisionTestMerchants"
describe("sortDivisionTestMerchants", () => {
it("sorts by targetMerchantType desc 3, 2, 1", () => {
const list = [
{ merchantName: "平台", targetMerchantType: 1 },
{ merchantName: "4s店", targetMerchantType: 3 },
{ merchantName: "服务商", targetMerchantType: 2 }
]
const sorted = sortDivisionTestMerchants(list)
expect(sorted.map((m) => m.merchantName)).toEqual(["4s店", "服务商", "平台"])
})
it("items without targetMerchantType sort after known types", () => {
const list = [
{ merchantName: "未知", targetType: 1 },
{ merchantName: "4s店", targetMerchantType: 3 }
]
const sorted = sortDivisionTestMerchants(list)
expect(sorted.map((m) => m.merchantName)).toEqual(["4s店", "未知"])
})
it("isPlatformMerchant", () => {
expect(isPlatformMerchant({ targetMerchantType: 1 })).toBe(true)
expect(isPlatformMerchant({ targetMerchantType: 4 })).toBe(true)
expect(isPlatformMerchant({ targetMerchantType: 3 })).toBe(false)
expect(isPlatformMerchant({ targetType: 4 })).toBe(true)
expect(isPlatformMerchant({ targetType: 1 })).toBe(false)
})
})
/**
* @jest-environment jsdom
*/
import {
distributionRulesLookComplete,
distributionRulesConsistentWithLedgerParty,
extractServiceMerchantIdsFromExpenseCategoryRules,
ledgerMerchantIdLooseEqual,
prepareRuleForValidation,
validateGoodsTypeGroupRulePayload
} from "@/views/systemConfig/merchant/financialRules/utils/validateGoodsTypeGroupRulePayload"
function minimalValidRule(overrides = {}) {
return {
groupType: 1,
shop4sDeductChargeFlag: "Y",
partnerDeductChargeFlag: "Y",
goodsCostFlag: "N",
virtualAccountCostFlag: "N",
recoveryCostFlag: "N",
djCostFlag: "N",
thirdPartyCostFlag: "N",
expenseCategoryRules: [
{
calculateMode: 1,
expenseCategoryCalculateType: 1,
expenseCategoryValue: "10"
}
],
merchantDistributionRules: [{ merchantId: "100" }],
owningMerchantDistributionRules: [{ merchantId: "100" }],
...overrides
}
}
describe("distributionRulesLookComplete", () => {
test("完整分账表 → true", () => {
expect(distributionRulesLookComplete(minimalValidRule())).toBe(true)
})
test("空表或缺 merchantId → false", () => {
expect(
distributionRulesLookComplete({
merchantDistributionRules: [],
owningMerchantDistributionRules: [{ merchantId: "1" }]
})
).toBe(false)
expect(
distributionRulesLookComplete({
merchantDistributionRules: [{ merchantId: "" }],
owningMerchantDistributionRules: [{ merchantId: "1" }]
})
).toBe(false)
expect(distributionRulesLookComplete({})).toBe(false)
})
})
describe("ledgerMerchantIdLooseEqual", () => {
test("number / string 同值", () => {
expect(ledgerMerchantIdLooseEqual(100, "100")).toBe(true)
expect(ledgerMerchantIdLooseEqual("100", 100)).toBe(true)
})
test("不等 → false", () => {
expect(ledgerMerchantIdLooseEqual(100, 200)).toBe(false)
})
})
describe("extractServiceMerchantIdsFromExpenseCategoryRules", () => {
test("解析 targetMerchant / targetMerchantId", () => {
const ids = extractServiceMerchantIdsFromExpenseCategoryRules([
{ targetMerchant: { merchantId: "200" } },
{
formType: 2,
children: [{ targetMerchantId: "300" }]
}
])
expect(ids).toEqual(["200", "300"])
})
})
describe("distributionRulesConsistentWithLedgerParty", () => {
const ledger = {
realityPlatformMerchantId: "100",
realityShopMerchantId: "200",
djzhySubMerchantId: "300"
}
test("merchantId 在 ledger + expense 允许集合内 → true", () => {
const rule = minimalValidRule({
expenseCategoryRules: [
{
calculateMode: 1,
expenseCategoryCalculateType: 1,
expenseCategoryValue: "10",
targetMerchantId: "400"
}
],
merchantDistributionRules: [{ merchantId: "100" }],
owningMerchantDistributionRules: [{ merchantId: "400" }]
})
expect(distributionRulesConsistentWithLedgerParty(rule, ledger)).toBe(true)
})
test("merchantId 不在允许集合 → false", () => {
const rule = minimalValidRule({
merchantDistributionRules: [{ merchantId: "999" }],
owningMerchantDistributionRules: [{ merchantId: "999" }]
})
expect(distributionRulesConsistentWithLedgerParty(rule, ledger)).toBe(false)
})
test("targetMerchantType===3 须等于 realityShopMerchantId", () => {
const rule = minimalValidRule({
merchantDistributionRules: [{ merchantId: "200", targetMerchantType: 3 }],
owningMerchantDistributionRules: [{ merchantId: "100" }]
})
expect(distributionRulesConsistentWithLedgerParty(rule, ledger)).toBe(true)
const bad = minimalValidRule({
merchantDistributionRules: [{ merchantId: "100", targetMerchantType: 3 }],
owningMerchantDistributionRules: [{ merchantId: "100" }]
})
expect(distributionRulesConsistentWithLedgerParty(bad, ledger)).toBe(false)
})
})
describe("validateGoodsTypeGroupRulePayload", () => {
test("最小合法 rule → true", () => {
expect(validateGoodsTypeGroupRulePayload(minimalValidRule())).toBe(true)
})
test("缺 expense 必填 → false", () => {
expect(
validateGoodsTypeGroupRulePayload(
minimalValidRule({
expenseCategoryRules: [{ calculateMode: 1 }]
})
)
).toBe(false)
})
test("formType=2 子行缺 value → false", () => {
expect(
validateGoodsTypeGroupRulePayload(
minimalValidRule({
expenseCategoryRules: [
{
calculateMode: 1,
expenseCategoryCalculateType: 1,
expenseCategoryValue: "10",
formType: 2,
children: [{ calculateMode: 1, expenseCategoryCalculateType: 1 }]
}
]
})
)
).toBe(false)
})
test("goodsCostFlag=Y 缺 convertRate → false", () => {
expect(
validateGoodsTypeGroupRulePayload(
minimalValidRule({ goodsCostFlag: "Y" })
)
).toBe(false)
})
test("特殊品类 DJ 须 goodsTypeGroupRelations", () => {
expect(
validateGoodsTypeGroupRulePayload(
minimalValidRule({
groupType: 2,
goodsSource: 1,
goodsTypeGroupRelations: []
})
)
).toBe(false)
expect(
validateGoodsTypeGroupRulePayload(
minimalValidRule({
groupType: 2,
goodsSource: 1,
goodsTypeGroupRelations: [{ goodsType: "G1" }]
})
)
).toBe(true)
})
test("传入 ledgerContext 时分账行须一致", () => {
const ledger = { realityPlatformMerchantId: "100", realityShopMerchantId: "200" }
expect(validateGoodsTypeGroupRulePayload(minimalValidRule(), ledger)).toBe(true)
expect(
validateGoodsTypeGroupRulePayload(
minimalValidRule({
merchantDistributionRules: [{ merchantId: "999" }],
owningMerchantDistributionRules: [{ merchantId: "999" }]
}),
ledger
)
).toBe(false)
})
})
describe("prepareRuleForValidation", () => {
test("返回 fillDj 后的 clone", () => {
const raw = minimalValidRule({ groupType: 1 })
const prepared = prepareRuleForValidation(raw)
expect(prepared).not.toBe(raw)
expect(prepared.groupType).toBe(1)
})
})
import {
validateStep3Amounts,
isValidAmountInput,
buildStep3SubmitMerchants,
mergeStep3FormMerchants,
isMerchantCompletedFromDetail,
getStep3PendingMerchants
} from "@/views/systemConfig/merchant/financialRules/utils/validateStep3Amounts"
describe("validateStep3Amounts", () => {
it("isValidAmountInput", () => {
expect(isValidAmountInput("3.5")).toBe(true)
expect(isValidAmountInput("0")).toBe(true)
expect(isValidAmountInput("3.555")).toBe(false)
expect(isValidAmountInput("4")).toBe(false)
expect(isValidAmountInput("")).toBe(false)
})
it("isMerchantCompletedFromDetail only when detail distributionMoney is 0", () => {
expect(isMerchantCompletedFromDetail({ distributionMoney: 0 })).toBe(true)
expect(isMerchantCompletedFromDetail({ distributionMoney: "0" })).toBe(true)
expect(isMerchantCompletedFromDetail({ distributionMoney: "" })).toBe(false)
expect(isMerchantCompletedFromDetail({ distributionMoney: null })).toBe(false)
expect(isMerchantCompletedFromDetail({ distributionMoney: "1.2" })).toBe(false)
})
it("validateStep3Amounts allows confirmDivisionMoney 0 for pending merchants", () => {
const r = validateStep3Amounts([
{ distributionMoney: "0" },
{ distributionMoney: "1.2", confirmDivisionMoney: "0" }
])
expect(r.valid).toBe(true)
expect(getStep3PendingMerchants([
{ distributionMoney: "0" },
{ distributionMoney: "1.2" }
])).toHaveLength(1)
})
it("validateStep3Amounts requires pending fields", () => {
const r = validateStep3Amounts([
{ testCompleted: false, confirmDivisionMoney: "" }
])
expect(r.valid).toBe(false)
})
it("mergeStep3FormMerchants keeps user-filled amounts when props refresh", () => {
const prev = [
{ merchantId: "m1", confirmDivisionMoney: "1.5" },
{ merchantId: "m2", confirmDivisionMoney: "2.0" }
]
const next = [
{ merchantId: "m1", merchantName: "A", confirmDivisionMoney: "" },
{ merchantId: "m2", merchantName: "B", testCompleted: true }
]
const merged = mergeStep3FormMerchants(next, prev)
expect(merged[0].confirmDivisionMoney).toBe("1.5")
expect(merged[1].confirmDivisionMoney).toBe("2.0")
})
it("buildStep3SubmitMerchants merges confirmDivisionMoney into raw API list", () => {
const rawList = [
{ merchantId: "m1", merchantName: "A", distributionMoney: "1.2" }
]
const form = [
{ merchantId: "m1", confirmDivisionMoney: "1.5" }
]
const out = buildStep3SubmitMerchants(rawList, form)
expect(out).toHaveLength(1)
expect(out[0].distributionMoney).toBe("1.2")
expect(out[0].confirmDivisionMoney).toBe("1.5")
expect(out[0].testCompleted).toBeUndefined()
})
it("buildStep3SubmitMerchants excludes detail-0 only, keeps user input 0", () => {
const rawList = [
{ merchantId: "m1", distributionMoney: "0" },
{ merchantId: "m2", distributionMoney: "1.2" },
{ merchantId: "m3", distributionMoney: null }
]
const form = [
{ merchantId: "m1", confirmDivisionMoney: "9" },
{ merchantId: "m2", confirmDivisionMoney: "0" },
{ merchantId: "m3", confirmDivisionMoney: "0" }
]
const out = buildStep3SubmitMerchants(rawList, form)
expect(out).toHaveLength(2)
expect(out.map((m) => m.merchantId)).toEqual(["m2", "m3"])
expect(out[0].confirmDivisionMoney).toBe("0")
expect(out[1].confirmDivisionMoney).toBe("0")
})
})
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!