merchantOnShelfOpenPayload.js 9.58 KB
import NP from "number-precision";
import { resolveSceneTypeFromBaseSceneFilterList } from "./merchantDetailMap";

/** 与 MgBusinessSection 中嘀加毛利/毛利率/产值合计一致 */
function computeDjMetrics(componentData, productDetails) {
	const pd = productDetails || [];
	const { personnelCost, rentCost, depreciationCost, otherCost } = componentData || {};
	let revenue = 0;
	let trafficFee = 0;
	let marketFee1 = 0;
	let marketFee2 = 0;
	let incentive1 = 0;
	let incentive2 = 0;
	let resourceFee = 0;
	let productCost = 0;
	let recyclingFilm = 0;
	pd.forEach((item) => {
		revenue = NP.plus(revenue, item.estimatedRevenue != null ? item.estimatedRevenue : item.revenue || 0);
		trafficFee = NP.plus(trafficFee, item.trafficFee || 0);
		marketFee1 = NP.plus(marketFee1, item.marketFee1 || 0);
		marketFee2 = NP.plus(marketFee2, item.marketFee2 || 0);
		incentive1 = NP.plus(incentive1, item.incentive1 || 0);
		incentive2 = NP.plus(incentive2, item.incentive2 || 0);
		resourceFee = NP.plus(resourceFee, item.resourceFee || 0);
		productCost = NP.plus(productCost, item.productCost || 0);
		recyclingFilm = NP.plus(recyclingFilm, item.recyclingFilm || 0);
	});
	const sum = NP.minus(
		revenue,
		NP.plus(
			trafficFee,
			marketFee1,
			marketFee2,
			incentive1,
			incentive2,
			resourceFee,
			productCost,
			recyclingFilm,
			personnelCost || 0,
			rentCost || 0,
			depreciationCost || 0,
			otherCost || 0,
		),
	);
	const djGrossProfit = Math.floor(sum * 100) / 100;
	const djGpr = revenue === 0 ? 0 : NP.round(NP.times(NP.divide(djGrossProfit, revenue), 100), 2);
	return { djGrossProfit, djGpr, estimatedRevenue: revenue };
}

function joinMultiId(traffic, listKey, scalarKey) {
	const list = traffic[listKey];
	if (Array.isArray(list) && list.length) {
		return list.join(",");
	}
	const s = traffic[scalarKey];
	if (s != null && s !== "") {
		return String(s);
	}
	return "";
}

function numOrNull(v) {
	if (v === "" || v === undefined || v === null) {
		return null;
	}
	const n = Number(v);
	return Number.isNaN(n) ? null : n;
}

/**
 * 详情 queryMerchantDetail.merchantInfo 中与「经营信息区块」一致的字段(与 buildBusinessForm 同源字段名)
 */
const MERCHANT_INFO_BUSINESS_NATIVE_SCALAR_KEYS = [
	"deliveryCount",
	"customerTouchRate",
	"personnelCost",
	"rentCost",
	"depreciationCost",
	"otherCost",
	"storeProfitPerCar",
];

/** 从详情 merchantInfo 拾起经营信息标量,保持接口原始类型(不强制 Number) */
function pickMerchantInfoBusinessNativeScalars(mi) {
	if (!mi || typeof mi !== "object") {
		return {};
	}
	const out = {};
	for (const k of MERCHANT_INFO_BUSINESS_NATIVE_SCALAR_KEYS) {
		if (Object.prototype.hasOwnProperty.call(mi, k)) {
			out[k] = mi[k];
		}
	}
	if (
		!Object.prototype.hasOwnProperty.call(out, "depreciationCost")
		&& Object.prototype.hasOwnProperty.call(mi, "depreciation")
	) {
		out.depreciationCost = mi.depreciation;
	}
	return out;
}

/** 详情原值 + 表单编辑值(后者覆盖);用于经营信息按详情字段名回传 */
function mergeBusinessScalarsWithDetailNative(mi, businessForm) {
	return {
		...pickMerchantInfoBusinessNativeScalars(mi),
		...(businessForm && typeof businessForm === "object" ? businessForm : {}),
	};
}

/** 空串转 null,其余保持原样(与详情/表单原生值一致,不整型化) */
function detailScalarSubmitValue(v) {
	if (v === "" || v === undefined) {
		return null;
	}
	return v;
}

function mapProductDetailBusinessRow(pd) {
	// StepTwo 弹框只绑定 estimatedConversionRate / upgradePrice / revenue,优先于详情里可能未更新的 estimated*
	const estimatedConversionVal = numOrNull(
		pd.estimatedConversionRate != null ? pd.estimatedConversionRate : pd.estimatedConversion,
	);
	const estimatedUpgradePriceVal = numOrNull(
		pd.upgradePrice != null ? pd.upgradePrice : pd.estimatedUpgradePrice,
	);
	const estimatedRevenueVal = numOrNull(
		pd.revenue != null ? pd.revenue : pd.estimatedRevenue,
	);
	const row = {
		productType: pd.productType,
		productCategory: pd.productCategory,
		feeSettlementMode: pd.feeSettlementMode,
		penetrationRate: numOrNull(pd.penetrationRate),
		conversionRate: numOrNull(pd.conversionRate),
		revenuePerCar: numOrNull(pd.revenuePerCar),
		estimatedConversion: estimatedConversionVal,
		estimatedUpgradePrice: estimatedUpgradePriceVal,
		estimatedRevenue: estimatedRevenueVal,
		// 与上列 estimated* 同源,兼容 StepTwo / 历史字段名
		estimatedConversionRate: estimatedConversionVal,
		upgradePrice: estimatedUpgradePriceVal,
		revenue: estimatedRevenueVal,
		recyclingFilm: numOrNull(pd.recyclingFilm),
		trafficFee: numOrNull(pd.trafficFee),
		marketFee1: numOrNull(pd.marketFee1),
		marketFee2: numOrNull(pd.marketFee2),
		incentive1: numOrNull(pd.incentive1),
		incentive2: numOrNull(pd.incentive2),
		resourceFee: numOrNull(pd.resourceFee),
		productCost: numOrNull(pd.productCost),
	};
	if (pd.id != null && pd.id !== "") {
		const nid = Number(pd.id);
		if (!Number.isNaN(nid)) {
			row.id = nid;
		}
	}
	if (pd.partyId != null && pd.partyId !== "") {
		const pid = Number(pd.partyId);
		if (!Number.isNaN(pid)) {
			row.partyId = pid;
		}
	}
	if (pd.createdBy != null) {
		row.createdBy = pd.createdBy;
	}
	if (pd.updatedBy != null) {
		row.updatedBy = pd.updatedBy;
	}
	if (pd.deletedFlag != null) {
		row.deletedFlag = pd.deletedFlag;
	}
	return row;
}

/**
 * addOrUpdateSceneMerchantRefNewOpen 请求体(由 sign/qs 序列化后 POST)
 */
export function buildMerchantOnShelfOpenPayload(options) {
	const {
		detailQueryBaseSceneCode,
		detailQueryMerchantId,
		merchantInfo: mi0,
		traffic,
		businessForm,
		productDetailsForSubmit,
		baseSceneList,
		guaranteeList,
	} = options;
	const mi = mi0 || {};
	/** 与商户管理列表 scene 一致:取自 getBaseSceneCodeList 场景的 sceneType,未命中则 0 */
	const sceneType = resolveSceneTypeFromBaseSceneFilterList(
		detailQueryBaseSceneCode,
		baseSceneList,
	);

	const trafficPartyId
		= mi.trafficPartyId != null && mi.trafficPartyId !== ""
			? Number(mi.trafficPartyId)
			: detailQueryMerchantId;
	const trafficPartyName = (traffic && traffic.trafficPartyName) || mi.trafficPartyName || "";

	const yqId
		= traffic.yqMerchantId != null && traffic.yqMerchantId !== ""
			? Number(traffic.yqMerchantId)
			: null;
	const yqName = traffic.yqMerchantName || mi.parkingStoreName || "";

	const bizMerged = mergeBusinessScalarsWithDetailNative(mi, businessForm);
	const { djGrossProfit, djGpr, estimatedRevenue } = computeDjMetrics(
		bizMerged,
		productDetailsForSubmit,
	);

	const parentSvcId = mi.parentServiceMerchantId;
	const trafficPartyBusinessData = {
		trafficPartyId,
		trafficPartyName,
		parkingStoreId: yqId != null && !Number.isNaN(yqId) ? yqId : null,
		parkingStoreName: yqName || "",
		serviceProviderId: traffic.partnerId != null ? Number(traffic.partnerId) : null,
		parentServiceMerchantId:
			parentSvcId != null && parentSvcId !== "" ? Number(parentSvcId) : null,
		serviceProviderName: traffic.partnerName || "",
		parentServiceMerchantName:
			traffic.parentServiceMerchantName || mi.parentServiceMerchantName || "",
		serviceMerchant2fId:
			traffic.serviceMerchant2fId != null ? Number(traffic.serviceMerchant2fId) : null,
		serviceMerchant2fName: traffic.serviceMerchant2fName || "",
		signingEntityId:
			traffic.signingEntityId != null ? Number(traffic.signingEntityId) : null,
		signingEntityName: traffic.signingEntity || "",
		businessMode: traffic.businessMode != null ? Number(traffic.businessMode) : null,
		operationMode: traffic.operationMode != null ? Number(traffic.operationMode) : null,
		// 经营信息:与详情 merchantInfo 字段名一致;标量为详情原生 + 表单覆盖;产值/毛利/毛利率与页面对齐由销售品类计算
		deliveryCount: detailScalarSubmitValue(bizMerged.deliveryCount),
		customerTouchRate: detailScalarSubmitValue(bizMerged.customerTouchRate),
		personnelCost: detailScalarSubmitValue(bizMerged.personnelCost),
		rentCost: detailScalarSubmitValue(bizMerged.rentCost),
		depreciationCost: detailScalarSubmitValue(bizMerged.depreciationCost),
		otherCost: detailScalarSubmitValue(bizMerged.otherCost),
		storeProfitPerCar: detailScalarSubmitValue(bizMerged.storeProfitPerCar),
		estimatedRevenue,
		djGrossProfit,
		djGpr,
		areaOpId: joinMultiId(traffic, "areaOpIdList", "areaOpId"),
		onlineOpId: joinMultiId(traffic, "onlineOpIdList", "onlineOpId"),
		regionSupervisorId: joinMultiId(traffic, "regionSupervisorIdList", "regionSupervisorId"),
		areaOpName: (traffic && traffic.areaOpName) || "",
		onlineOpName: (traffic && traffic.onlineOpName) || "",
		regionSupervisorName: (traffic && traffic.regionSupervisorName) || "",
		otherServiceProviders:
			traffic && traffic.otherServiceProviders != null && traffic.otherServiceProviders !== ""
				? String(traffic.otherServiceProviders)
				: "",
		estimatedDeliveryCountPerMonth: traffic.estimatedDeliveryCountPerMonth || "",
		personnelCostRate: traffic.personnelCostRate || "",
		renovationEquipmentCost: traffic.renovationEquipmentCost || "",
		otherCostPerMonth: traffic.otherCostPerMonth || "",
		estimatedGrossMargin: traffic.estimatedGrossMargin || "",
		hasGuarantee: traffic.hasGuarantee,
		monthlySettlementDate: traffic.monthlySettlementDate || "",
	};

	const productDetailBusinessDataList = (productDetailsForSubmit || []).map(
		mapProductDetailBusinessRow,
	);

	const payload = {
		baseSceneCode: String(detailQueryBaseSceneCode),
		sceneType,
		merchantId: trafficPartyId,
		partnerMerchantId:
			traffic.partnerId != null ? Number(traffic.partnerId) : null,
		trafficPartyBusinessData,
		productDetailBusinessDataList,
		guaranteeList,
	};
	if (yqId != null && !Number.isNaN(yqId)) {
		payload.yqMerchantId = yqId;
	}
	return payload;
}