import type { Field } from '@/types/field' /** * Quantity field stores linkage and future payment metadata in `htmlContent` as JSON * (same persistence path as the product field’s `htmlContent` blob). */ export interface QuantityFieldConfig { quantityConfigVersion?: number /** `fieldIndex` of the product field on this form. */ linkedProductFieldIndex: number | null } const CURRENT_CONFIG_VERSION = 1 const defaultConfig = (): QuantityFieldConfig => ({ quantityConfigVersion: CURRENT_CONFIG_VERSION, linkedProductFieldIndex: null, }) export function parseQuantityFieldConfig(field?: Field | null): QuantityFieldConfig { if (!field) { return defaultConfig() } const raw = field.htmlContent if (typeof raw !== 'string' || raw.trim() === '') { return defaultConfig() } try { const parsed = JSON.parse(raw) as Record const linked = parsed['linkedProductFieldIndex'] let linkedProductFieldIndex: number | null = null if (typeof linked === 'number' && Number.isFinite(linked) && linked >= 0) { linkedProductFieldIndex = Math.round(linked) } else if (typeof linked === 'string' && linked.trim() !== '') { const n = Number(linked) if (Number.isFinite(n) && n >= 0) { linkedProductFieldIndex = Math.round(n) } } const versionRaw = parsed['quantityConfigVersion'] const quantityConfigVersion = typeof versionRaw === 'number' && Number.isFinite(versionRaw) ? versionRaw : 0 return { ...defaultConfig(), quantityConfigVersion, linkedProductFieldIndex, } } catch { return defaultConfig() } } export function stringifyQuantityFieldConfig(config: QuantityFieldConfig): string { return JSON.stringify({ quantityConfigVersion: CURRENT_CONFIG_VERSION, linkedProductFieldIndex: config.linkedProductFieldIndex, }) }