mergeClassificationPayload.js 2.37 KB
import { deepClone } from "@/common/util"

const GUARD_EMPTY_ARRAY_KEYS = [
  "expenseCategoryRules",
  "merchantDistributionRules",
  "owningMerchantDistributionRules",
  "goodsTypes",
  "upgradeGoods",
  "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 一致)。
 *
 * @param {object} payload 子组件返回
 * @param {object|undefined} prevStoredRaw financialObj.goodsTypeGroupRules[idx] 原始引用
 * @returns {{ next: object, prevStored: object|undefined }}
 */
export function mergeChildClassificationPayload(payload, prevStoredRaw) {
  const prev = prevStoredRaw || {}
  const base = deepClone(prev)
  const next = { ...base, ...payload }
  if (
    !Object.prototype.hasOwnProperty.call(payload, "expenseCategoryRules") ||
    payload.expenseCategoryRules == null
  ) {
    next.expenseCategoryRules = base.expenseCategoryRules
  }
  if (
    !Object.prototype.hasOwnProperty.call(payload, "merchantDistributionRules") ||
    payload.merchantDistributionRules == null
  ) {
    next.merchantDistributionRules = base.merchantDistributionRules
  }
  if (
    !Object.prototype.hasOwnProperty.call(
      payload,
      "owningMerchantDistributionRules"
    ) ||
    payload.owningMerchantDistributionRules == null
  ) {
    next.owningMerchantDistributionRules = base.owningMerchantDistributionRules
  }
  GUARD_EMPTY_ARRAY_KEYS.forEach((key) => {
    const p = payload[key]
    const b = base[key]
    if (
      Array.isArray(p) &&
      p.length === 0 &&
      Array.isArray(b) &&
      b.length > 0
    ) {
      next[key] = b
    }
  })
  preserveServerIdFieldsFromBase(next, base, payload)
  return { next, prevStored: prevStoredRaw }
}