import type { Field } from '@/types/field' /** * Total field stores summary UI and empty-state HTML in `htmlContent` as JSON. * Amounts are derived on the public form from all product × quantity pairs (form cart). */ export interface TotalFieldConfig { totalConfigVersion?: number enablePaymentSummary: boolean showPaymentSummaryCloseButton: boolean emptyPaymentMessageHtml: string enableAutocomplete: boolean } const CURRENT_CONFIG_VERSION = 1 const defaultConfig = (): TotalFieldConfig => ({ totalConfigVersion: CURRENT_CONFIG_VERSION, enablePaymentSummary: false, showPaymentSummaryCloseButton: true, emptyPaymentMessageHtml: '', enableAutocomplete: false, }) /** True only for boolean `true` or string `'true'` (JSON / loose storage must not coerce `"false"` to true). */ function parseBooleanStrict(value: unknown): boolean { return value === true || value === 'true' } export function parseTotalFieldConfig(field?: Field | null): TotalFieldConfig { if (!field) { return defaultConfig() } const blob = field.htmlContent if (typeof blob !== 'string' || blob.trim() === '') { return defaultConfig() } try { const parsed = JSON.parse(blob) as Record const versionRaw = parsed['totalConfigVersion'] const totalConfigVersion = typeof versionRaw === 'number' && Number.isFinite(versionRaw) ? versionRaw : 0 const emptyRaw = parsed['emptyPaymentMessageHtml'] const emptyPaymentMessageHtml = typeof emptyRaw === 'string' ? emptyRaw : defaultConfig().emptyPaymentMessageHtml const hasShowCloseButtonKey = Object.prototype.hasOwnProperty.call( parsed, 'showPaymentSummaryCloseButton', ) return { ...defaultConfig(), totalConfigVersion, enablePaymentSummary: parseBooleanStrict(parsed['enablePaymentSummary']), showPaymentSummaryCloseButton: hasShowCloseButtonKey ? parseBooleanStrict(parsed['showPaymentSummaryCloseButton']) : defaultConfig().showPaymentSummaryCloseButton, emptyPaymentMessageHtml, enableAutocomplete: parseBooleanStrict(parsed['enableAutocomplete']), } } catch { return defaultConfig() } } export function stringifyTotalFieldConfig(config: TotalFieldConfig): string { return JSON.stringify({ totalConfigVersion: CURRENT_CONFIG_VERSION, enablePaymentSummary: config.enablePaymentSummary, showPaymentSummaryCloseButton: config.showPaymentSummaryCloseButton, emptyPaymentMessageHtml: config.emptyPaymentMessageHtml, enableAutocomplete: config.enableAutocomplete, }) }