import type { CustomerMasterAccount, CustomerRecord } from "./customer-records"; import type { OrganizationData } from "./organization-demo"; import type { DemoIdentity } from "./demo-identities"; import { addClaimDays, createClaimCode, customerMaterialText, fullRegionPath, nextCustomerNo, normalizedIdNo, validateCustomerDraft, type AccountIdentity, type CustomerDraft } from "./customer-onboarding.ts"; export const blankInlineCustomer = (): CustomerDraft => ({ name: "", subject: "企业", idNo: "", contact: "", phone: "", address: "", regionId: "", operatorId: "", partnerId: "", teamIds: [], login: "", masterPhone: "", initialPassword: "", idNoBasis: "" }); /** 只准备数据;客户、主账号和合同全部校验通过后再统一提交。密码不进入持久化数据。 */ export function prepareInlineCustomer(draft: CustomerDraft, records: CustomerRecord[], data: OrganizationData, identity: DemoIdentity | null, accounts: AccountIdentity[], today: string): { ok: false; errors: Record } | { ok: true; customer: CustomerRecord; master: CustomerMasterAccount } { const normalized = { ...draft, login: draft.login.trim(), masterPhone: draft.masterPhone.trim() }; const errors = validateCustomerDraft(normalized, records, data, identity, accounts); if (Object.keys(errors).length) return { ok: false, errors }; const no = nextCustomerNo(records, Number(today.slice(0, 4))); const operator = data.operators.find((item) => item.id === draft.operatorId)!; const customer: CustomerRecord = { no, name: draft.name.trim(), subject: draft.subject, idNo: normalizedIdNo(draft.idNo), contact: draft.contact.trim(), phone: draft.phone.trim(), address: draft.address.trim(), regionId: draft.regionId, regionPath: fullRegionPath(data, draft.regionId), operator: `${fullRegionPath(data, operator.region)} / ${operator.name}`, partner: data.partners.find((item) => item.id === draft.partnerId)?.name || null, teams: [...new Set(draft.teamIds)].map((id) => data.maintenanceTeams.find((item) => item.id === id)!.name), status: "未开通", quota: 0, files: [], materials: customerMaterialText(draft.subject), history: [{ at: today, by: identity?.name || "林管", field: "合同登记建档", before: "未建档", after: `同步建立主账号 ${normalized.login}(${draft.initialPassword ? "已激活,首次登录须改密" : "未激活,激活码 7 天有效"})` }], }; const master: CustomerMasterAccount = { login: normalized.login, phone: normalized.masterPhone || undefined, status: "在用", claimStatus: draft.initialPassword ? "已激活" : "未激活", createdOn: today, mustChange: Boolean(draft.initialPassword), ...(!draft.initialPassword ? { claimOn: today, claimExpireOn: addClaimDays(today, 7), claimCode: createClaimCode() } : {}) }; return { ok: true, customer, master }; }