@realtek/zinnext-theme 1.0.8 → 1.0.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist-lib/{DocumentViewer-BaSdIaiX.js → DocumentViewer-D928QglB.js} +2 -2
- package/dist-lib/{DocumentViewer-BaSdIaiX.js.map → DocumentViewer-D928QglB.js.map} +1 -1
- package/dist-lib/{DocumentViewer-DyVOzGFs.cjs → DocumentViewer-Djvgj6nH.cjs} +2 -2
- package/dist-lib/{DocumentViewer-DyVOzGFs.cjs.map → DocumentViewer-Djvgj6nH.cjs.map} +1 -1
- package/dist-lib/{FileField-DqvRspcF.cjs → FileField-BCI-_Iu3.cjs} +2 -2
- package/dist-lib/{FileField-DqvRspcF.cjs.map → FileField-BCI-_Iu3.cjs.map} +1 -1
- package/dist-lib/{FileField-Ch5i-nX0.js → FileField-Crphi905.js} +2 -2
- package/dist-lib/{FileField-Ch5i-nX0.js.map → FileField-Crphi905.js.map} +1 -1
- package/dist-lib/{LinkedRecordFileField-DOFmEwO1.js → LinkedRecordFileField-BpiT6dDg.js} +6 -6
- package/dist-lib/{LinkedRecordFileField-DOFmEwO1.js.map → LinkedRecordFileField-BpiT6dDg.js.map} +1 -1
- package/dist-lib/{LinkedRecordFileField-DVcRqY2w.cjs → LinkedRecordFileField-D27QHPlj.cjs} +3 -3
- package/dist-lib/{LinkedRecordFileField-DVcRqY2w.cjs.map → LinkedRecordFileField-D27QHPlj.cjs.map} +1 -1
- package/dist-lib/{addFormApi-jmGt33G8.js → addFormApi-BVqmS70h.js} +3 -3
- package/dist-lib/{addFormApi-jmGt33G8.js.map → addFormApi-BVqmS70h.js.map} +1 -1
- package/dist-lib/{addFormApi-C0xRFSDt.cjs → addFormApi-DkJesIBU.cjs} +2 -2
- package/dist-lib/{addFormApi-C0xRFSDt.cjs.map → addFormApi-DkJesIBU.cjs.map} +1 -1
- package/dist-lib/{authApi-CERg2tGa.js → authApi-CwQa0oId.js} +7 -1
- package/dist-lib/authApi-CwQa0oId.js.map +1 -0
- package/dist-lib/authApi-tkqCStVu.cjs +2 -0
- package/dist-lib/authApi-tkqCStVu.cjs.map +1 -0
- package/dist-lib/dropdownApi-42OJ5VI6.cjs +2 -0
- package/dist-lib/dropdownApi-42OJ5VI6.cjs.map +1 -0
- package/dist-lib/{dropdownApi-hFjvfyNX.js → dropdownApi-C4IO2saX.js} +6 -3
- package/dist-lib/dropdownApi-C4IO2saX.js.map +1 -0
- package/dist-lib/index.cjs +3 -3
- package/dist-lib/index.js +8 -8
- package/package.json +1 -1
- package/dist-lib/authApi-CERg2tGa.js.map +0 -1
- package/dist-lib/authApi-D4ufO1Os.cjs +0 -2
- package/dist-lib/authApi-D4ufO1Os.cjs.map +0 -1
- package/dist-lib/dropdownApi-CCsEgXRh.cjs +0 -2
- package/dist-lib/dropdownApi-CCsEgXRh.cjs.map +0 -1
- package/dist-lib/dropdownApi-hFjvfyNX.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"FileField-Ch5i-nX0.js","names":[],"sources":["../src/services/adminApi.js","../src/components/detailViewMode.js","../src/services/detailDefaults.js","../src/services/timezone.js","../src/utils/modulePath.js","../src/services/documentApi.js","../src/components/form/savedValueValidation.js","../src/components/form/inputSecurity.js","../src/components/detail/phoneDisplay.js","../src/components/detail/renderConfig.js","../src/components/form/conditionalFieldLabel.js"],"sourcesContent":["import { fetchJsonWithAuth } from './authApi';\nimport { invalidateFormGroupsCache } from './formGroupsCache';\nimport { AUTH_URL, SUBMISSIONS_URL } from './apiConfig';\n\nconst FIELD_CONFIG_PATH = '/admin/field-config';\n\nconst CUSTOMIZABLE_MODULES = [\n { key: 'clients', apiModule: 'clients' },\n { key: 'job', apiModule: 'jobs' },\n { key: 'candidate', apiModule: 'candidates' },\n { key: 'submissions', apiModule: 'submissions' },\n { key: 'onboarding', apiModule: 'onboarding' },\n { key: 'billing', apiModule: 'billing' },\n { key: 'payroll', apiModule: 'payroll' },\n];\n\n// ── Shared Utilities ──────────────────────────────────────────────────────────\n\nfunction firstArray(...values) {\n return values.find(Array.isArray) ?? [];\n}\n\nfunction firstValue(record, keys, fallback) {\n return keys.map((k) => record?.[k]).find((v) => v !== undefined && v !== null && v !== '') ?? fallback;\n}\n\nfunction normalizeTotal(payload, items) {\n return (\n payload?.total ?? payload?.totalCount ?? payload?.count ??\n payload?.recordsTotal ?? payload?.meta?.total ?? payload?.pagination?.total ?? items.length\n );\n}\n\nfunction normalizeModuleField(field, index) {\n const fieldName = firstValue(field, ['label', 'Label', 'fieldName', 'field_name', 'name', 'fieldLabel', 'value'], `Field ${index + 1}`);\n const fieldKey = firstValue(field, ['field', 'Field', 'fieldKey', 'field_key', 'key', 'value', 'fieldName', 'name'], fieldName);\n const showValue = firstValue(field, ['isVisible', 'is_visible', 'visible', 'show', 'is_show', 'isShow', 'enabled'], true);\n const mandatoryValue = firstValue(field, ['ismandatory', 'isMandatory', 'is_mandatory', 'mandatory', 'required', 'req'], false);\n const orderValue = firstValue(field, ['order', 'Order', 'sortOrder', 'position'], index);\n\n return {\n ...field,\n fieldKey,\n fieldName,\n type: firstValue(field, ['type', 'Type'], 'text'),\n isVisible: typeof showValue === 'string'\n ? !['false', '0', 'hide', 'hidden', 'no'].includes(showValue.toLowerCase())\n : Boolean(showValue),\n ismandatory: typeof mandatoryValue === 'string'\n ? ['true', '1', 'yes', 'required'].includes(mandatoryValue.toLowerCase())\n : Boolean(mandatoryValue),\n order: typeof orderValue === 'number' ? orderValue : index,\n isLink: Boolean(field.isLink),\n linkTemplate: field.linkTemplate ?? '',\n linkType: field.linkType ?? 'internal',\n linkTarget: field.linkTarget ?? '_self',\n action: field.action ?? 'navigate',\n allowedTabs: Array.isArray(field.allowedTabs) ? field.allowedTabs : [],\n secondaryField: field.secondaryField ?? '',\n secondaryLabel: field.secondaryLabel ?? '',\n secondaryFields: Array.isArray(field.secondaryFields) ? field.secondaryFields : [],\n secondarySeparator: field.secondarySeparator ?? '',\n lookup: field.lookup\n ? { ...field.lookup, projectFields: Array.isArray(field.lookup.projectFields) ? field.lookup.projectFields : [] }\n : null,\n derived: field.derived ?? null,\n computed: field.computed\n ? { ...field.computed, operands: Array.isArray(field.computed.operands) ? field.computed.operands : [] }\n : null,\n actionButtons: Array.isArray(field.actionButtons) ? field.actionButtons : [],\n displayRules: Array.isArray(field.displayRules) ? field.displayRules : [],\n renderType: field.renderType ?? '',\n renderConfig: field.renderConfig\n ? {\n ...field.renderConfig,\n treatZeroAsEmpty: Boolean(field.renderConfig.treatZeroAsEmpty),\n cleanEmptyTemplateSeparators: Boolean(field.renderConfig.cleanEmptyTemplateSeparators),\n }\n : null,\n valueStyles: Array.isArray(field.valueStyles) ? field.valueStyles : [],\n commonStyle: field.commonStyle ?? null,\n displayTemplate: field.displayTemplate ?? '',\n defaultValue: field.defaultValue ?? '',\n defaultValueField: field.defaultValueField ?? '',\n dataSource: field.dataSource ?? 'module',\n groupName: field.groupName ?? '',\n filterGroupFields: Array.isArray(field.filterGroupFields) ? field.filterGroupFields : [],\n filterGroupSeparator: field.filterGroupSeparator ?? ' ',\n filterArrayLabelField: field.filterArrayLabelField ?? '',\n filterArrayValueField: field.filterArrayValueField ?? '',\n };\n}\n\nfunction normalizeCustomizableModule(module) {\n if (typeof module === 'string') {\n return { key: module, apiModule: module };\n }\n\n const key = firstValue(\n module,\n ['key', 'moduleKey', 'value', 'module', 'apiModule', 'name', 'modulename', 'menuName'],\n ''\n );\n if (!key) return null;\n\n return {\n key,\n apiModule: firstValue(\n module,\n ['apiModule', 'api_module', 'module', 'value', 'key', 'name', 'modulename', 'menuName'],\n key\n ),\n };\n}\n\nfunction normalizeCustomizableModules(modules = CUSTOMIZABLE_MODULES) {\n const source = Array.isArray(modules) && modules.length ? modules : CUSTOMIZABLE_MODULES;\n const seen = new Set();\n return source\n .map(normalizeCustomizableModule)\n .filter(Boolean)\n .filter((module) => {\n if (seen.has(module.key)) return false;\n seen.add(module.key);\n return true;\n });\n}\n\n// ── Modules ───────────────────────────────────────────────────────────────────\n\nconst MODULES_PATH = '/admin/modules';\n\nexport async function getModules() {\n const json = await fetchJsonWithAuth(AUTH_URL, MODULES_PATH);\n const payload = json?.data;\n if (Array.isArray(payload)) return payload;\n if (Array.isArray(json)) return json;\n return [];\n}\n\n// createModule/updateModule let Admin define workflow modules (e.g. \"Source\n// Candidates\") that extend an existing module via baseModule, inheriting its\n// forms/columns/tabs/filters/actions wherever the new module hasn't\n// configured its own — see the backend's ModuleLookupChain.\nexport async function createModule({ key, label, collectionName, baseModule = '', order = 0 }) {\n return fetchJsonWithAuth(AUTH_URL, MODULES_PATH, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ key, label, collectionName, baseModule, order }),\n });\n}\n\nexport async function updateModule(key, { label, collectionName, baseModule = '', order = 0, isActive = true }) {\n return fetchJsonWithAuth(AUTH_URL, `${MODULES_PATH}/${encodeURIComponent(key)}`, {\n method: 'PUT',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ label, collectionName, baseModule, order, isActive }),\n });\n}\n\n// getModuleAutomations/saveModuleAutomations edit a module's Gateway +\n// Strategies — the Admin \"Automations\" screen. This is the config-driven\n// replacement for logic legacy services used to hardcode in Go (reference-id\n// generation, duplicate checks, cross-module field snapshots, reporting-chain\n// hierarchy expansion, board updates, notifications, cache invalidation).\n// Separate endpoint from updateModule() above, so saving automations can\n// never touch label/forms/columns, and vice versa.\nexport async function getModuleAutomations(key) {\n const json = await fetchJsonWithAuth(AUTH_URL, `${MODULES_PATH}/${encodeURIComponent(key)}/automations`);\n const data = json?.data ?? json ?? {};\n return { gateway: data.gateway ?? null, strategies: data.strategies ?? null };\n}\n\n// Platform metadata (workflows / resolvers / state-machines / applications) —\n// the event-driven behavior layer. kind ∈ 'workflows' | 'resolvers' |\n// 'state-machines' | 'applications'. Docs are keyed by their \"key\" field.\nexport async function listPlatformDocs(kind) {\n const json = await fetchJsonWithAuth(AUTH_URL, `/admin/platform/${kind}`);\n const data = json?.data ?? json;\n return Array.isArray(data) ? data : [];\n}\n\nexport async function savePlatformDoc(kind, doc) {\n return fetchJsonWithAuth(AUTH_URL, `/admin/platform/${kind}`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(doc),\n });\n}\n\nexport async function deletePlatformDoc(kind, key) {\n return fetchJsonWithAuth(AUTH_URL, `/admin/platform/${kind}/${encodeURIComponent(key)}`, {\n method: 'DELETE',\n });\n}\n\nexport async function saveModuleAutomations(key, { gateway, strategies }) {\n return fetchJsonWithAuth(AUTH_URL, `${MODULES_PATH}/${encodeURIComponent(key)}/automations`, {\n method: 'PUT',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ gateway, strategies }),\n });\n}\n\n// getAvailableModules() is the single source of truth for \"which modules can\n// be picked in an Admin configuration screen\" (Form Groups, Detail Groups,\n// Row Actions, Module Action Rules, Templates, Role Configuration). It's\n// driven by the curated Menus list (an admin explicitly adds/removes/disables\n// entries there) rather than the `modules` collection, which is really the\n// CRUD/gateway registry and accumulates every module ever wired for storage\n// (including disabled/legacy ones no admin actively curates).\n//\n// Falls back to getModules() when Menus has nothing configured yet, so a\n// project that hasn't set up Menus keeps working exactly as before.\nexport async function getAvailableModules() {\n let menus = [];\n try {\n menus = await getMenuModules();\n } catch {\n menus = [];\n }\n const active = (Array.isArray(menus) ? menus : []).filter((m) => (\n m?.isDeleted !== true\n && String(m?.status ?? 'active').toLowerCase() !== 'inactive'\n && String(m?.status ?? 'active').toLowerCase() !== 'disabled'\n ));\n if (active.length > 0) return active;\n return getModules();\n}\n\n// getModuleCollectionMap resolves module key → the Mongo collection that module\n// is stored in, straight from the module registry (`modules`, the CRUD/gateway\n// registry that owns `collectionName`). It exists so an Admin screen can DISPLAY\n// the collection a configuration will act on without ever asking the admin to\n// type a collection name — the collection is module configuration, and the\n// server resolves it authoritatively on every request regardless of what this\n// map says. If the registry is unreachable the map is simply empty and callers\n// fall back to \"resolved on the server\".\n//\n// Module names are matched loosely on purpose: config is stored sometimes under\n// the singular key and sometimes the plural one (the backend's own\n// ModuleAliasVariants exists for the same reason), so both spellings are\n// indexed here. Real registry entries always win over a generated alias, so an\n// alias can never shadow a module that genuinely exists.\nexport async function getModuleCollectionMap() {\n let modules;\n try {\n modules = await getModules();\n } catch {\n return {};\n }\n const map = {};\n const put = (key, collection, exact) => {\n const k = String(key ?? '').trim().toLowerCase();\n if (!k || !collection) return;\n if (exact || map[k] === undefined) map[k] = collection;\n };\n for (const m of Array.isArray(modules) ? modules : []) {\n const collection = String(m?.collectionName ?? '').trim();\n if (!collection) continue;\n put(m?.key, collection, true);\n }\n // Second pass so aliases never overwrite a registered key from pass one.\n for (const m of Array.isArray(modules) ? modules : []) {\n const collection = String(m?.collectionName ?? '').trim();\n const key = String(m?.key ?? '').trim().toLowerCase();\n if (!collection || !key) continue;\n if (key.endsWith('s')) put(key.slice(0, -1), collection, false);\n else put(`${key}s`, collection, false);\n }\n return map;\n}\n\n// ── Admin Form Groups ─────────────────────────────────────────────────────────\n\nconst FORM_GROUPS_PATH = '/admin/form-groups';\nconst CONFIG_DEFAULTS_PATH = '/admin/config-defaults';\n\nexport async function exportFormGroupSeed(module, scope = {}) {\n const json = await fetchJsonWithAuth(AUTH_URL, `/admin/form-group-seeds/export${formGroupScopeQuery({ ...scope, module })}`);\n return json?.data ?? json;\n}\n\nexport async function previewFormGroupSeed(module, scope, seed, mode) {\n const json = await fetchJsonWithAuth(AUTH_URL, `/admin/form-group-seeds/preview${formGroupScopeQuery({ ...scope, module })}`, {\n method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ seed, mode }),\n });\n return json?.data ?? json;\n}\n\nexport async function applyFormGroupSeed(module, scope, seed, mode, revision) {\n const json = await fetchJsonWithAuth(AUTH_URL, `/admin/form-group-seeds/apply${formGroupScopeQuery({ ...scope, module })}`, {\n method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ seed, mode, revision }),\n });\n invalidateFormGroupsCache();\n return json?.data ?? json;\n}\n\nexport async function downloadFormGroupSeedBackup(id) {\n const json = await fetchJsonWithAuth(AUTH_URL, `/admin/form-group-seeds/backups/${encodeURIComponent(id)}`);\n return json?.data ?? json;\n}\n\nconst NIL_OBJECT_ID = '000000000000000000000000';\n\n/** True for an absent id or Go's zero-value ObjectID (24 zeros). */\nfunction isNilObjectId(value) {\n const id = String(value ?? '').trim();\n return id === '' || id === NIL_OBJECT_ID;\n}\n\nfunction formGroupScopeQuery(scope = {}) {\n const params = new URLSearchParams();\n if (scope.module) params.set('module', scope.module);\n if (scope.clientId) params.set('clientId', scope.clientId);\n if (scope.region) params.set('region', scope.region);\n const qs = params.toString();\n return qs ? `?${qs}` : '';\n}\n\nexport async function getAdminFormGroups(module = '', scope = {}) {\n const query = formGroupScopeQuery({ ...scope, module: module || scope.module || '' });\n const path = `${FORM_GROUPS_PATH}${query}`;\n const json = await fetchJsonWithAuth(AUTH_URL, path, { cache: 'no-store' });\n const payload = json?.data;\n // Backend returns EITHER a flat array of groups, OR a wrapper object\n // { id, module, ..., groups: [...] }. Support both shapes.\n if (Array.isArray(payload)) return payload;\n if (payload && Array.isArray(payload.groups)) return payload.groups;\n if (Array.isArray(json)) return json;\n if (json && Array.isArray(json.groups)) return json.groups;\n return [];\n}\n\nexport async function getPreviewConfig(module = '', scope = {}) {\n const query = formGroupScopeQuery({ ...scope, module: module || scope.module || '' });\n const json = await fetchJsonWithAuth(AUTH_URL, `${FORM_GROUPS_PATH}/preview-config${query}`);\n return json?.data ?? json ?? {};\n}\n\nexport async function savePreviewConfig(module = '', config = {}, scope = {}) {\n const query = formGroupScopeQuery(scope);\n return fetchJsonWithAuth(AUTH_URL, `${FORM_GROUPS_PATH}/preview-config${query}`, {\n method: 'PUT',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ module, ...config }),\n });\n}\n\nexport async function getAdminClients({ offset = 0, limit = 100, sortBy = 'new', searchvalue = '' } = {}) {\n const params = new URLSearchParams({\n offset: String(offset),\n limit: String(limit),\n sortBy,\n searchvalue,\n });\n // Scope the list to the active tenant/business/businessUnit captured from the\n // login token (authApi stores these on login). The backend uses them when\n // present, otherwise falls back to the token claims — so the dropdown lists\n // the right clients for the selected project, same as the legacy flow.\n const tenantId = localStorage.getItem('tenantId') || '';\n const businessId = localStorage.getItem('businessId') || '';\n const businessUnitId = localStorage.getItem('businessUnitId') || '';\n if (tenantId) params.set('tenantId', tenantId);\n if (businessId) params.set('businessId', businessId);\n if (businessUnitId) params.set('businessUnitId', businessUnitId);\n const json = await fetchJsonWithAuth(AUTH_URL, `/client/view?${params.toString()}`);\n const data = json?.data ?? json;\n return data?.clients ?? data?.Clients ?? data?.items ?? [];\n}\n\nexport async function getModuleFields(module) {\n const json = await fetchJsonWithAuth(AUTH_URL, `/filter-dropdown-fields?module=${encodeURIComponent(module)}`);\n const fields = json?.data ?? json;\n return Array.isArray(fields) ? fields : [];\n}\n\nexport async function createAdminFormGroup(group, scope = {}) {\n return fetchJsonWithAuth(AUTH_URL, `${FORM_GROUPS_PATH}${formGroupScopeQuery(scope)}`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(group),\n });\n}\n\nexport async function updateAdminFormGroup(id, group, scope = {}) {\n const result = await fetchJsonWithAuth(AUTH_URL, `${FORM_GROUPS_PATH}/${id}${formGroupScopeQuery(scope)}`, {\n method: 'PUT',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(group),\n });\n invalidateFormGroupsCache();\n // Verify the server's persisted configuration before the editor closes or\n // announces success. Older backend builds can silently discard unknown keys.\n const expected = (group.fields ?? []).filter(field => typeof field.enforceOptions === 'boolean');\n if (expected.length) {\n let groups;\n try {\n groups = await getAdminFormGroups(group.module || scope.module || '', scope);\n } catch {\n throw new Error('The update was sent, but the saved settings could not be verified. Reopen this configuration before retrying.');\n }\n const key = value => String(value?.$oid ?? value ?? '');\n const saved = groups.find(candidate => key(candidate.id ?? candidate._id) === key(id));\n const mismatched = expected.filter(field =>\n saved?.fields?.find(candidate => candidate.field === field.field)?.enforceOptions !== field.enforceOptions);\n if (mismatched.length) {\n throw new Error(`Dropdown validation settings were not saved for: ${mismatched.map(field => field.label || field.field).join(', ')}. Check the running backend version and selected client/region configuration.`);\n }\n }\n return result;\n}\n\n// Scope-aware, like create/update: with a client selected the group is removed\n// from THAT client's list only. A client-scoped config is a fork of the module\n// default and keeps the same group ids, so an unscoped delete would clear the\n// group from the default and every other client at once.\nexport async function deleteAdminFormGroup(id, scope = {}) {\n return fetchJsonWithAuth(AUTH_URL, `${FORM_GROUPS_PATH}/${id}${formGroupScopeQuery(scope)}`, { method: 'DELETE' });\n}\n\nexport async function seedAdminFormGroups() {\n return fetchJsonWithAuth(AUTH_URL, `${FORM_GROUPS_PATH}/seed`, { method: 'POST' });\n}\n\nexport async function requestConfigOtp(scope, action) {\n return fetchJsonWithAuth(AUTH_URL, `${CONFIG_DEFAULTS_PATH}/request-otp`, {\n method: 'POST',\n body: JSON.stringify({ scope, action }),\n });\n}\n\nexport async function applyConfigDefault(scope, action, otp) {\n return fetchJsonWithAuth(AUTH_URL, `${CONFIG_DEFAULTS_PATH}/apply`, {\n method: 'POST',\n body: JSON.stringify({ scope, action, otp }),\n });\n}\n\n// ── Admin Detail-View Config ──────────────────────────────────────────────────\n// Per-module customization layered on top of the form groups, applied only by\n// the detail view (?view=detail). Shape: { module, fields:[…], merges:[…] }.\n\nconst DETAIL_CONFIG_PATH = '/admin/detail-config';\n\n// Client scope mirrors the form-group admin exactly: pass a clientId to read /\n// write THAT client's detail config, omit it for the module default. The backend\n// falls back to the default when the client has none of its own, so a client\n// with no overrides still renders.\nexport async function getDetailConfig(module, scope = {}) {\n const query = formGroupScopeQuery({ module, clientId: scope.clientId });\n const json = await fetchJsonWithAuth(AUTH_URL, `${DETAIL_CONFIG_PATH}${query}`);\n const data = json?.data ?? json ?? {};\n return {\n module: data.module ?? module,\n // Which scope the response belongs to — '' means the module default. Go\n // serialises an unset ObjectID as 24 zeros, which is NOT a client.\n clientId: isNilObjectId(data.clientId) ? '' : String(data.clientId),\n fields: Array.isArray(data.fields) ? data.fields : [],\n merges: Array.isArray(data.merges) ? data.merges : [],\n sourceFields: Array.isArray(data.sourceFields) ? data.sourceFields : [],\n // Detail-only group title overrides. Absent on an older backend, so default\n // to [] rather than undefined -- the editor treats undefined as \"unknown\"\n // and would refuse to send the key at all.\n groups: Array.isArray(data.groups) ? data.groups : [],\n };\n}\n\nexport async function saveDetailConfig({ module, fields = [], merges = [], sourceFields = [], groups = [], clientId = '' }) {\n const result = await fetchJsonWithAuth(AUTH_URL, DETAIL_CONFIG_PATH, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n // clientId travels in the BODY (this is a JSON POST); the backend treats an\n // absent/zero id as \"the module default\".\n body: JSON.stringify({ module, fields, merges, sourceFields, groups, ...(clientId ? { clientId } : {}) }),\n });\n invalidateFormGroupsCache();\n return result;\n}\n\nexport async function discoverDetailFields({ module, clientId = '', otp }) {\n return fetchJsonWithAuth(AUTH_URL, `${DETAIL_CONFIG_PATH}/discover-fields`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ module, otp, ...(clientId ? { clientId } : {}) }),\n });\n}\n\n// ── Detail-View Display Defaults ──────────────────────────────────────────────\n// Tenant-wide display settings (S3 base, date format, boolean/empty labels,\n// separator, document name order) — the configurable home of what used to be\n// hard-coded in fileUtils.js / FieldValue.jsx.\n\nconst DETAIL_DEFAULTS_PATH = '/admin/detail-defaults';\n\nexport async function getDetailDefaults() {\n const json = await fetchJsonWithAuth(AUTH_URL, DETAIL_DEFAULTS_PATH);\n return json?.data ?? json ?? {};\n}\n\nexport async function saveDetailDefaults(defaults) {\n return fetchJsonWithAuth(AUTH_URL, DETAIL_DEFAULTS_PATH, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(defaults),\n });\n}\n\n// ── AI Service registry (backends AI Actions can call) ─────────────────────\n\nconst AI_SERVICE_CONFIG_PATH = '/admin/ai-service-config';\n\nexport async function getAiServiceConfigs() {\n const json = await fetchJsonWithAuth(AUTH_URL, AI_SERVICE_CONFIG_PATH);\n return json?.data ?? json ?? [];\n}\n\nexport async function saveAiServiceConfig(config) {\n return fetchJsonWithAuth(AUTH_URL, AI_SERVICE_CONFIG_PATH, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(config),\n });\n}\n\nexport async function deleteAiServiceConfig(serviceKey) {\n return fetchJsonWithAuth(AUTH_URL, `${AI_SERVICE_CONFIG_PATH}?serviceKey=${encodeURIComponent(serviceKey)}`, {\n method: 'DELETE',\n });\n}\n\n/**\n * Ask the SERVER whether it can reach an AI service base URL.\n *\n * Deliberately server-side. /ai-action is a server-to-server call made by the\n * Go backend, so only that process can answer the question that matters. A\n * browser-side probe would test the admin's laptop instead: an internal\n * address (http://pyops:7020) is reachable from the backend and not from a\n * remote admin, and a public URL can be reachable from a browser while blocked\n * by cluster egress rules. Testing from the wrong place proves nothing.\n *\n * Resolves with { reachable, status, latencyMs, target, detail, looksLikeWebApp }.\n * An unreachable service is a SUCCESSFUL test with reachable:false — the\n * detail is what the admin needs to see.\n */\nexport async function testAiServiceConnection({ baseUrl, authHeader, authValue }) {\n const json = await fetchJsonWithAuth(AUTH_URL, `${AI_SERVICE_CONFIG_PATH}/test`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ baseUrl, authHeader, authValue }),\n });\n return json?.data ?? json;\n}\n\n// ── Background Check integration ───────────────────────────────────────────\n\nconst BGC_INTEGRATION_CONFIG_PATH = '/admin/bgc-integration-config';\n\nexport async function getBgcIntegrationConfig() {\n const json = await fetchJsonWithAuth(AUTH_URL, BGC_INTEGRATION_CONFIG_PATH);\n return json?.data ?? json ?? { updateMethod: 'MANUAL', enabled: true };\n}\n\nexport async function saveBgcIntegrationConfig(config) {\n return fetchJsonWithAuth(AUTH_URL, BGC_INTEGRATION_CONFIG_PATH, {\n method: 'PUT',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(config),\n });\n}\n\n// Safe runtime view for consumers such as the onboarding BGC stage. It never\n// contains credential values, only credentialsConfigured/webhookConfigured.\nexport async function getBgcIntegrationSummary() {\n const json = await fetchJsonWithAuth(AUTH_URL, '/integration-config/bgc/summary');\n return json?.data ?? json ?? { updateMethod: 'MANUAL', enabled: true };\n}\n\nconst INTEGRATION_CONFIG_PATH = '/admin/integration-config';\n\nexport async function getIntegrationConfigs() {\n const json = await fetchJsonWithAuth(AUTH_URL, INTEGRATION_CONFIG_PATH);\n return json?.data ?? json ?? [];\n}\n\nexport async function getIntegrationConfig(integrationKey) {\n const json = await fetchJsonWithAuth(\n AUTH_URL,\n `${INTEGRATION_CONFIG_PATH}/${encodeURIComponent(integrationKey)}`,\n );\n return json?.data ?? json;\n}\n\nexport async function saveIntegrationConfig(config) {\n const key = config?.integrationKey;\n const path = key\n ? `${INTEGRATION_CONFIG_PATH}/${encodeURIComponent(key)}`\n : INTEGRATION_CONFIG_PATH;\n return fetchJsonWithAuth(AUTH_URL, path, {\n method: key ? 'PUT' : 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(config),\n });\n}\n\nexport async function deleteIntegrationConfig(integrationKey) {\n return fetchJsonWithAuth(\n AUTH_URL,\n `${INTEGRATION_CONFIG_PATH}/${encodeURIComponent(integrationKey)}`,\n { method: 'DELETE' },\n );\n}\n\nexport async function testIntegrationConnection(config) {\n const json = await fetchJsonWithAuth(AUTH_URL, `${INTEGRATION_CONFIG_PATH}/test`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(config),\n });\n return json?.data ?? json;\n}\n\nexport async function getIntegrationSummary(integrationKey) {\n const json = await fetchJsonWithAuth(\n AUTH_URL,\n `/integration-config/${encodeURIComponent(integrationKey)}/summary`,\n );\n return json?.data ?? json;\n}\n\nexport async function applyIntegrationStatus(integrationKey, recordId, providerResponse) {\n const json = await fetchJsonWithAuth(\n AUTH_URL,\n `/integration-config/${encodeURIComponent(integrationKey)}/apply-status/${encodeURIComponent(recordId)}`,\n {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(providerResponse),\n },\n );\n return json?.data ?? json;\n}\n\n// getModuleDetailPreview fetches a record's detail-view groups WITH resolved\n// values (references → {id,value}, documents → full object) so the admin page\n// can preview exactly what the detail view will render.\nexport async function getModuleDetailPreview(module, id) {\n const path = `${FORM_GROUPS_PATH}?module=${encodeURIComponent(module)}&id=${encodeURIComponent(id)}&view=detail`;\n const json = await fetchJsonWithAuth(AUTH_URL, path);\n const data = json?.data ?? json;\n return Array.isArray(data) ? data : [];\n}\n\n// ── Roles ─────────────────────────────────────────────────────────────────────\n\nfunction normalizeRole(record) {\n return {\n key: record.role_id ?? record.id,\n roleId: record.role_id ?? record.id,\n roleName: record.role_name ?? 'N/A',\n description: record.role_description ?? 'N/A',\n userCount: record.user_count ?? 0,\n roleType: record.role_type ?? 0,\n raw: record,\n };\n}\n\nexport function getRoleId(role) {\n return role?.raw?.role_id ?? role?.roleId ?? role?.key;\n}\n\nexport async function getAllRoles() {\n const json = await fetchJsonWithAuth(AUTH_URL, '/get-roles');\n const payload = json.data ?? json;\n const defaultRoles = firstArray(payload?.zinnext_default).map(normalizeRole);\n const customRoles = firstArray(payload?.custom_roles).map(normalizeRole);\n const all = [...defaultRoles, ...customRoles];\n return { roles: all, total: all.length };\n}\n\n// ── Teams ─────────────────────────────────────────────────────────────────────\n\nfunction normalizeTeam(record) {\n return {\n key: record.teamId,\n teamId: record.teamId,\n teamName: record.teamName ?? 'N/A',\n manager: record.reportingManager ?? 'N/A',\n managerId: record.reportingManagerId ?? 0,\n memberCount: record.noOfTeamMembers ?? 0,\n members: firstArray(record.teamMembers),\n memberIds: firstArray(record.teamMembersIds),\n raw: record,\n };\n}\n\nexport function getTeamId(team) {\n return team?.raw?.teamId ?? team?.teamId ?? team?.key;\n}\n\nexport async function getAllTeams({ offset = 0, limit = 10, sortBy = 'new', search = '' } = {}) {\n const params = new URLSearchParams({ searchquery: search, sortBy, limit: String(limit), offset: String(offset) });\n const json = await fetchJsonWithAuth(AUTH_URL, `/get-teams?${params}`);\n const payload = json.data ?? json;\n const teams = firstArray(payload?.teams, payload, json?.teams);\n const total = payload?.totalCount ?? payload?.total ?? teams.length;\n return { teams: teams.map(normalizeTeam), total };\n}\n\nexport async function updateTeam(team, { teamName, managerId, memberIds = [] }) {\n const teamId = getTeamId(team);\n return fetchJsonWithAuth(AUTH_URL, `/team/edit?teamId=${teamId}`, {\n method: 'PUT',\n body: JSON.stringify({\n team_name: teamName,\n team_manager: managerId,\n other_team_members: memberIds,\n reporting_team_member: [],\n }),\n });\n}\n\n// ── Role / Team Field Config ──────────────────────────────────────────────────\n\nasync function fetchFieldConfigModule(apiModule, idParam, idValue, configType = 'listView', includeMeta = false) {\n const params = new URLSearchParams({ module: apiModule, userId: '0', [idParam]: String(idValue), configType });\n if (includeMeta) params.set('includeMeta', '1');\n const json = await fetchJsonWithAuth(AUTH_URL, `${FIELD_CONFIG_PATH}?${params}`);\n const payload = json.data ?? json;\n const fields = firstArray(payload, payload?.visibleFields, json?.visibleFields);\n return includeMeta\n ? {\n fields,\n dataVisibilityMode: payload?.dataVisibilityMode ?? json?.dataVisibilityMode ?? 'all',\n dataOwnerField: payload?.dataOwnerField ?? json?.dataOwnerField ?? 'createdBy',\n filterDisplayMode: payload?.filterDisplayMode === 'top' ? 'top' : 'popup',\n exportEnabled: payload?.exportEnabled !== false,\n }\n : fields;\n}\n\nexport async function getRoleModuleFields(role, configType = 'listView', modules = CUSTOMIZABLE_MODULES) {\n const roleId = getRoleId(role);\n const customizableModules = normalizeCustomizableModules(modules);\n const entries = await Promise.all(\n customizableModules.map(async ({ key, apiModule }) => {\n const fields = await fetchFieldConfigModule(apiModule, 'roleId', roleId, configType);\n return [key, fields.map((f, i) => ({ ...normalizeModuleField(f, i), module: key, apiModule, roleId }))];\n })\n );\n return Object.fromEntries(entries);\n}\n\n\nexport async function getRoleModuleFieldsWithMeta(role, configType = 'listView', modules = CUSTOMIZABLE_MODULES) {\n const roleId = getRoleId(role);\n const customizableModules = normalizeCustomizableModules(modules);\n const entries = await Promise.all(\n customizableModules.map(async ({ key, apiModule }) => {\n const result = await fetchFieldConfigModule(apiModule, 'roleId', roleId, configType, true);\n const fields = result.fields.map((f, i) => ({ ...normalizeModuleField(f, i), module: key, apiModule, roleId }));\n return [key, {\n fields,\n dataVisibilityMode: result.dataVisibilityMode ?? 'all',\n dataOwnerField: result.dataOwnerField ?? 'createdBy',\n filterDisplayMode: result.filterDisplayMode ?? 'popup',\n exportEnabled: result.exportEnabled !== false,\n }];\n })\n );\n return Object.fromEntries(entries);\n}\n\nexport async function getTeamModuleFields(team, configType = 'listView') {\n const teamId = getTeamId(team);\n const entries = await Promise.all(\n CUSTOMIZABLE_MODULES.map(async ({ key, apiModule }) => {\n const fields = await fetchFieldConfigModule(apiModule, 'teamId', teamId, configType);\n return [key, fields.map((f, i) => ({ ...normalizeModuleField(f, i), module: key, apiModule, teamId }))];\n })\n );\n return Object.fromEntries(entries);\n}\n\nfunction normalizeListViewLookup(field) {\n if (!field?.lookup) return null;\n\n const lookup = { ...field.lookup };\n const localField = String(lookup.localField ?? '').trim() || String(field.fieldKey ?? '').trim();\n const valueField = String(lookup.valueField ?? lookup.foreignField ?? '').trim() || '_id';\n const displayField = String(lookup.displayField ?? lookup.projectField ?? '').trim();\n const displayField2 = String(lookup.displayField2 ?? '').trim();\n\n let projectFields = Array.isArray(lookup.projectFields)\n ? lookup.projectFields.map((value) => String(value ?? '').trim()).filter(Boolean)\n : [];\n\n // The list API accepts displayField, projectField and projectFields. Persist\n // projectFields as well so old/new backend versions resolve the same config.\n if (projectFields.length === 0) {\n projectFields = [displayField, displayField2].filter(Boolean);\n }\n\n return {\n ...lookup,\n localField,\n valueField,\n displayField,\n ...(displayField2 ? { displayField2 } : {}),\n projectFields,\n };\n}\n\nfunction visibleFieldPayload(fields, configType) {\n const isListView = !configType || configType === 'listView';\n return fields.map((field, index) => {\n const base = {\n label: field.fieldName, field: field.fieldKey,\n isVisible: field.isVisible, type: field.type ?? 'text', order: field.order ?? index,\n };\n if (isListView) {\n Object.assign(base, {\n ...(typeof field.exportable === 'boolean' ? { exportable: field.exportable } : {}),\n ...(typeof field.showByDefault === 'boolean' ? { showByDefault: field.showByDefault } : {}),\n ...(typeof field.exportable === 'boolean' ? { exportable: field.exportable } : {}),\n allowedTabs: Array.isArray(field.allowedTabs) ? field.allowedTabs : [],\n isLink: field.isLink ?? false, linkTemplate: field.linkTemplate ?? '',\n linkType: field.linkType ?? 'internal', linkTarget: field.linkTarget ?? '_self',\n action: field.action ?? 'navigate',\n secondaryField: field.secondaryField ?? '', secondaryLabel: field.secondaryLabel ?? '',\n secondaryFields: Array.isArray(field.secondaryFields) ? field.secondaryFields : [],\n secondarySeparator: field.secondarySeparator ?? '',\n lookup: normalizeListViewLookup(field), actionButtons: field.actionButtons ?? [],\n derived: field.derived ?? null, computed: field.computed ?? null,\n displayRules: Array.isArray(field.displayRules) ? field.displayRules : [],\n renderType: field.renderType ?? '',\n valueStyles: Array.isArray(field.valueStyles) ? field.valueStyles : [],\n commonStyle: field.commonStyle ?? null, displayTemplate: field.displayTemplate ?? '',\n defaultValue: field.defaultValue ?? '',\n defaultValueField: field.defaultValueField ?? '',\n renderConfig: field.renderConfig\n ? {\n ...field.renderConfig,\n treatZeroAsEmpty: Boolean(field.renderConfig.treatZeroAsEmpty),\n cleanEmptyTemplateSeparators: Boolean(field.renderConfig.cleanEmptyTemplateSeparators),\n }\n : null,\n });\n } else {\n base.isEditable = field.isEditable ?? false;\n base.ismandatory = field.ismandatory ?? field.isMandatory ?? false;\n if (configType === 'filter') {\n base.filterInputType = field.filterInputType ?? 'dropdown';\n base.filterToolbar = Boolean(field.filterToolbar);\n base.filterOptions = Array.isArray(field.filterOptions)?field.filterOptions:[];\n base.quickFilterOptions = Array.isArray(field.quickFilterOptions)?field.quickFilterOptions:[];\n base.isDefaultFilter = Boolean(field.isDefaultFilter);\n base.dataSource = field.dataSource ?? 'module';\n if (field.dataSource === 'group') base.groupName = field.groupName ?? '';\n base.filterGroupFields = Array.isArray(field.filterGroupFields) ? field.filterGroupFields : [];\n base.filterGroupSeparator = field.filterGroupSeparator ?? ' ';\n base.filterArrayLabelField = field.filterArrayLabelField ?? '';\n base.filterArrayValueField = field.filterArrayValueField ?? '';\n if (field.lookup) base.lookup = field.lookup;\n } else {\n if (['select', 'radio', 'checkbox'].includes(field.type)) {\n base.dataSource = field.dataSource ?? 'module';\n if (field.dataSource === 'group') base.groupName = field.groupName ?? '';\n }\n }\n }\n return base;\n });\n}\n\nexport async function updateRoleModuleFieldConfig(role, module, fields, configType = 'listView', modules = CUSTOMIZABLE_MODULES, dataVisibilityMode = '', dataOwnerField = 'createdBy', updateAllRoles = false, filterDisplayMode = 'popup', exportEnabled = true) {\n const roleId = getRoleId(role);\n const apiModule = normalizeCustomizableModules(modules).find((m) => m.key === module)?.apiModule ?? module;\n return fetchJsonWithAuth(AUTH_URL, `${FIELD_CONFIG_PATH}/role`, {\n method: 'PUT',\n body: JSON.stringify({\n module: apiModule, roleId, configType, updateAllRoles,\n ...(!configType || configType === 'listView' ? { exportEnabled } : {}),\n ...(configType === 'filter' ? { filterDisplayMode } : {}),\n ...(!configType || configType === 'listView' ? { exportEnabled } : {}),\n visibleFields: visibleFieldPayload(fields, configType),\n ...((!configType || configType === 'listView') && dataVisibilityMode\n ? { dataVisibilityMode, dataOwnerField: String(dataOwnerField || 'createdBy').trim() || 'createdBy' }\n : {}),\n }),\n });\n}\n\n// ── Role Configure → Form (derived from Form Groups) ─────────────────────────\n// Unlike getRoleModuleFields/updateRoleModuleFieldConfig above (an\n// independently-seeded flat field list), these back the Form tab's grouped\n// view: the backend derives groups/fields straight from the module's Form\n// Groups config and overlays this role's saved grants (GET\n// /admin/role-form-permissions), so Form Groups stays the single source of\n// truth and new/renamed/removed fields sync automatically. Saving still goes\n// through the existing PUT /admin/field-config/role (configType \"form\") —\n// the backend clamps it against Form Groups' global Show flags either way.\nconst ROLE_FORM_PERMISSIONS_PATH = '/admin/role-form-permissions';\n\n// Must match Be_Auth_DevOps models/roleFormPermissions.go's\n// roleGroupPermissionKey — the synthetic field-config key a group-level\n// ON/OFF toggle is persisted under, alongside real per-field grants, in the\n// same flat visibleFields list (no separate schema/endpoint needed).\nfunction roleGroupPermissionKey(groupName) {\n return `__group__:${groupName}`;\n}\n\n// scope: { clientId, region } — same client/region scope as\n// getAdminFormGroups/AddFormV1's effectiveClientId+effectiveRegion, so a\n// client- or region-scoped Form Groups override (e.g. a per-client Jobs\n// variant) is reflected here too, not just the tenant-wide default. Generic\n// for any module — GetFormGroupConfigScoped falls back to the default when\n// no scoped config exists for the given module, so this is always safe to pass.\nexport async function getRoleFormPermissions(role, module, scope = {}) {\n const roleId = getRoleId(role);\n const params = new URLSearchParams({ module, roleId: String(roleId ?? '') });\n if (scope.clientId) params.set('clientId', scope.clientId);\n if (scope.region) params.set('region', scope.region);\n const json = await fetchJsonWithAuth(AUTH_URL, `${ROLE_FORM_PERMISSIONS_PATH}?${params}`);\n const payload = json?.data ?? json;\n return Array.isArray(payload) ? payload : [];\n}\n\n// groups: [{ name, label, enabled, locked, fields: [{ field, label, enabled, locked, editable }] }]\n// as edited in the UI (see RoleFormPermissionsEditor). Group toggles are sent\n// as synthetic visibleFields rows so the existing role-save + clamp pipeline\n// needs no changes.\n//\n// A role's field-level grants are NOT stored per client/region — they're one\n// shared set overlaid onto whichever scoped Form Groups structure a caller\n// requests (getRoleFormPermissions). So any group/field that's `locked` in\n// the CURRENTLY VIEWED scope (globally disabled there, but possibly enabled\n// under the tenant-wide default or a different client's scope) is left out\n// of the payload entirely — sending its scope-computed `enabled: false`\n// would silently overwrite the role's real, scope-independent stored\n// preference the next time anyone loads a different scope. Locked items\n// aren't editable in this view anyway (their Switch is disabled), so there's\n// nothing this save is meant to change for them.\nexport async function saveRoleFormPermissions(role, module, groups) {\n const roleId = getRoleId(role);\n const visibleFields = [];\n let order = 0;\n for (const group of groups) {\n if (!group.locked) {\n visibleFields.push({\n label: group.label,\n field: roleGroupPermissionKey(group.name),\n // A group carries two independent role toggles: isVisible = shown,\n // isEditable = not-disabled (read-only when false). Default both true.\n isVisible: group.enabled,\n isEditable: group.editable !== false,\n order: order++,\n });\n }\n for (const field of group.fields ?? []) {\n if (field.locked) continue;\n visibleFields.push({\n label: field.label,\n field: field.field,\n isVisible: field.enabled,\n isEditable: field.editable !== false,\n order: order++,\n });\n }\n }\n return fetchJsonWithAuth(AUTH_URL, `${FIELD_CONFIG_PATH}/role`, {\n method: 'PUT',\n body: JSON.stringify({ module, roleId, configType: 'form', visibleFields }),\n });\n}\n\nexport async function updateTeamModuleFieldConfig(team, module, fields, configType = 'listView') {\n const teamId = getTeamId(team);\n const apiModule = CUSTOMIZABLE_MODULES.find((m) => m.key === module)?.apiModule ?? module;\n return fetchJsonWithAuth(AUTH_URL, `${FIELD_CONFIG_PATH}/team`, {\n method: 'PUT',\n body: JSON.stringify({ module: apiModule, teamId, configType, visibleFields: visibleFieldPayload(fields, configType) }),\n });\n}\n\n// ── Users ─────────────────────────────────────────────────────────────────────\n\nexport async function getAllUsers({ offset = 0, limit = 10, sortBy = 'new', searchQuery = '' } = {}) {\n const params = new URLSearchParams({ offset: String(offset), limit: String(limit), sortBy });\n if (searchQuery) params.set('searchquery', searchQuery);\n const json = await fetchJsonWithAuth(AUTH_URL, `/get-all-users?${params}`);\n const payload = json.data ?? json;\n const users = firstArray(\n payload, json.users, json.rows, json.items, json.records,\n payload?.users, payload?.data, payload?.rows, payload?.items,\n payload?.records, payload?.docs, payload?.result, payload?.results,\n );\n return { users, total: normalizeTotal({ ...json, ...payload }, users) };\n}\n\nexport function getUserId(user) {\n const value = firstValue(\n user?.raw ?? user,\n ['USER_ID', 'user_id', 'userId', 'id', '_id', 'uuid'],\n user?.key\n );\n const num = Number(value);\n return Number.isFinite(num) ? num : value;\n}\n\nexport function getUserRoleId(user) {\n const value = firstValue(user?.raw ?? user, ['ROLE_ID', 'role_id', 'roleId', 'ROLEID'], 0);\n const num = Number(value);\n return Number.isFinite(num) && num > 0 ? num : 0;\n}\n\nasync function getFieldConfigModule(apiModule, userId, roleId, configType) {\n const params = new URLSearchParams({ module: apiModule, userId: String(userId ?? ''), roleId: String(roleId ?? ''), configType });\n const json = await fetchJsonWithAuth(AUTH_URL, `${FIELD_CONFIG_PATH}?${params}`);\n const payload = json.data ?? json;\n return firstArray(payload, payload?.visibleFields, json?.visibleFields);\n}\n\nasync function getDropdownModuleFields(apiModule) {\n const json = await fetchJsonWithAuth(SUBMISSIONS_URL, `/filter-dropdown-fields?module=${encodeURIComponent(apiModule)}`);\n const payload = json.data ?? json;\n return firstArray(payload, payload?.fields, payload?.items, payload?.rows, json?.fields);\n}\n\nexport async function getUserModuleFields(user, configType = 'listView', modules = CUSTOMIZABLE_MODULES) {\n const userId = getUserId(user);\n const roleId = getUserRoleId(user);\n const customizableModules = normalizeCustomizableModules(modules);\n const entries = await Promise.all(\n customizableModules.map(async ({ key, apiModule }) => {\n let fields;\n try {\n fields = await getFieldConfigModule(apiModule, userId, roleId, configType);\n } catch {\n try { fields = await getDropdownModuleFields(apiModule); } catch { fields = []; }\n }\n if ((fields?.length ?? 0) === 0) {\n try { fields = await getDropdownModuleFields(apiModule); } catch { fields = []; }\n }\n return [key, fields.map((f, i) => ({ ...normalizeModuleField(f, i), module: key, apiModule, userId, roleId }))];\n })\n );\n return Object.fromEntries(entries);\n}\n\nexport async function hasUserFieldConfigData(user, configType = 'listView', modules = CUSTOMIZABLE_MODULES) {\n const userId = getUserId(user);\n const roleId = getUserRoleId(user);\n const customizableModules = normalizeCustomizableModules(modules);\n const results = await Promise.all(\n customizableModules.map(async ({ apiModule }) => {\n try {\n const fields = await getFieldConfigModule(apiModule, userId, roleId, configType);\n return (fields?.length ?? 0) > 0;\n } catch {\n return false;\n }\n })\n );\n return results.some(Boolean);\n}\n\nexport async function seedFieldConfig(collections = []) {\n return fetchJsonWithAuth(AUTH_URL, `${FIELD_CONFIG_PATH}/seed`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ collections }),\n });\n}\n\nexport async function getFieldConfigSeedStatus() {\n const json = await fetchJsonWithAuth(AUTH_URL, `${FIELD_CONFIG_PATH}/seed-status`);\n const data = json?.data ?? json ?? {};\n return {\n modules: Array.isArray(data.modules) ? data.modules : [],\n seededModules: data.seededModules ?? {},\n };\n}\n\nexport async function updateUserModuleFieldConfig(user, module, fields, configType = 'listView', modules = CUSTOMIZABLE_MODULES) {\n const userId = getUserId(user);\n const roleId = getUserRoleId(user);\n const apiModule = normalizeCustomizableModules(modules).find((m) => m.key === module)?.apiModule ?? module;\n return fetchJsonWithAuth(AUTH_URL, FIELD_CONFIG_PATH, {\n method: 'PUT',\n body: JSON.stringify({ module: apiModule, userId, roleId, configType, visibleFields: visibleFieldPayload(fields, configType) }),\n });\n}\n\nexport async function updateUserModuleFields(user, moduleFields, configType = 'listView') {\n return Promise.all(\n Object.entries(moduleFields).map(([module, fields]) => updateUserModuleFieldConfig(user, module, fields, configType))\n );\n}\n\nexport async function uploadFormGroupIcon(file) {\n const token = localStorage.getItem('authToken');\n const formData = new FormData();\n formData.append('icon', file);\n const res = await fetch(`${AUTH_URL}/admin/form-groups/icon`, {\n method: 'POST',\n headers: { Authorization: `Bearer ${token}` },\n body: formData,\n });\n if (!res.ok) { const e = new Error(`Upload failed: ${res.status}`); e.status = res.status; throw e; }\n const json = await res.json();\n return json.data ?? json;\n}\n\nexport async function uploadListViewActionIcon(file) {\n const token = localStorage.getItem('authToken');\n const formData = new FormData();\n formData.append('icon', file);\n const res = await fetch(`${AUTH_URL}/admin/field-config/action-icon`, {\n method: 'POST',\n headers: { Authorization: `Bearer ${token}` },\n body: formData,\n });\n if (!res.ok) { const e = new Error(`Upload failed: ${res.status}`); e.status = res.status; throw e; }\n const json = await res.json();\n return json.data ?? json;\n}\n\n// Module options for the Actions admin screens: the configured menu/module\n// catalog PLUS every collection in this app's database, so row actions can be\n// configured for ANY module (onboarding, movements, a brand-new collection…)\n// without first registering it as a menu module. Resolves per app DB via\n// X-App-Id, so each project sees its own collections.\nexport async function getActionConfigModules() {\n const [modules, collections, existingConfigs] = await Promise.all([\n getAvailableModules().catch(() => []),\n getAvailableCollections().catch(() => []),\n getRowActionConfigs().catch(() => []),\n ]);\n const baseModules = Array.isArray(modules) ? modules : [];\n // Detail-view action variants: a module's DETAIL page can carry its own row\n // actions (e.g. an \"Open JD\" primary button on the submission detail view)\n // without those actions also appearing on the LIST view. The detail page\n // fetches actions under whatever key it passes as DetailHeaderCard's\n // customConfigName — \"submissiondetails\", \"submissionJob\" — which follows no\n // derivable rule. This used to GENERATE `${key}detail` names, which produced\n // keys nothing ever requests (\"submissionsdetail\" vs the real\n // \"submissiondetails\"), so configuring one silently changed nothing.\n // Offer the keys that actually exist in rowActionConfig instead.\n const variantKeys = existingConfigs\n .map((config) => String(config?.module ?? '').trim())\n .filter(Boolean);\n return [\n ...baseModules,\n ...(Array.isArray(collections) ? collections : []),\n ...variantKeys,\n ];\n}\n\n// Generic module CRUD — used by the Masters admin screen (locations/taxes),\n// but not specific to either: works for any module via the dynamic gateway.\nexport async function listModuleRecords(module, { page = 1, limit = 100 } = {}) {\n const params = new URLSearchParams({ module, page: String(page), limit: String(limit) });\n const json = await fetchJsonWithAuth(AUTH_URL, `/module/list?${params}`);\n const data = json?.data ?? json ?? {};\n return { items: Array.isArray(data.data) ? data.data : [], total: data.pagination?.total ?? 0 };\n}\n\nexport async function createModuleRecordGeneric(module, payload) {\n return fetchJsonWithAuth(AUTH_URL, `/module/create?module=${encodeURIComponent(module)}`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(payload),\n });\n}\n\nexport async function updateModuleRecordGeneric(module, id, payload) {\n return fetchJsonWithAuth(AUTH_URL, `/module/update/${encodeURIComponent(id)}?module=${encodeURIComponent(module)}`, {\n method: 'PUT',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(payload),\n });\n}\n\nexport async function deleteModuleRecordGeneric(module, id) {\n return fetchJsonWithAuth(AUTH_URL, `/module/delete/${encodeURIComponent(id)}?module=${encodeURIComponent(module)}`, {\n method: 'DELETE',\n });\n}\n\n// Searchable \"City, State, Country\" options from the locationMasters collection\n// — the same source AddFormV1's `location` field type uses. Used by the Location\n// Tax Master screen to pick a real location instead of free-typing one.\nexport async function getLocationMasterOptions(search = '', limit = 50) {\n const params = new URLSearchParams({ search, limit: String(limit), offset: '0' });\n const json = await fetchJsonWithAuth(AUTH_URL, `/admin/location-dropdown-values?${params}`);\n const raw = json?.data ?? json ?? [];\n return (Array.isArray(raw) ? raw : [])\n .map((item) => {\n const label = typeof item === 'string' ? item : (item.label ?? item.value ?? '');\n return { label, value: label };\n })\n .filter((option) => option.label);\n}\n\n// Generic record options for any lookup-configured field — used by the Form\n// Groups editor's \"Conditional Default\" record picker (e.g. choose the default\n// Employer applied when Contract Type is W2). Returns { label, value } pairs\n// where value is the record's valueField (usually _id).\nexport async function getLookupRecordOptions(collection, displayField, valueField = '_id') {\n const params = new URLSearchParams({\n collection: String(collection),\n displayField: String(displayField),\n valueField: String(valueField),\n });\n const json = await fetchJsonWithAuth(AUTH_URL, `/admin/lookup-dropdown-values?${params}`);\n const raw = json?.data ?? json ?? [];\n return (Array.isArray(raw) ? raw : [])\n .map((item) => ({\n label: item.label ?? item.displayValue ?? item[displayField] ?? String(item.value ?? ''),\n value: String(item.value ?? item._id ?? item.id ?? ''),\n }))\n .filter((option) => option.value && option.label);\n}\n\n// Default Fields — per-module rules that LOCK a field in the Form Groups editor\n// and can optionally force it visible and/or required at render time.\n// getModuleDefaultFields is also called at runtime by AddFormV1/EditFormV1.\n// Saving is OTP-gated: request the code (requestConfigOtp('defaultFields','save'))\n// then pass it here.\n//\n// TWO WIRE SHAPES, and both must keep working:\n// \"jobTitle\" legacy — force show + force req + lock\n// { field, locked, forceShow, forceReq } each intent stated separately\n//\n// The legacy reading is not a courtesy: ~145 live fields are stored as bare\n// strings, and 29 of them (US unit) are configured differently from what\n// membership forces — 25 submission fields are configured req:0 yet required\n// today. Treating a string as \"lock only\" would quietly make those optional.\n// normalizeDefaultFieldRule is the ONE place that decision is made, so the\n// forms, the field editor and the admin panel cannot disagree about it.\nexport function normalizeDefaultFieldRule(entry) {\n if (typeof entry === 'string') {\n const field = entry.trim();\n return field ? { field, locked: true, forceShow: true, forceReq: true } : null;\n }\n if (!entry || typeof entry !== 'object') return null;\n const field = String(entry.field ?? '').trim();\n if (!field) return null;\n // Explicit === true, so a missing key is FALSE rather than truthy-by-accident.\n return {\n field,\n locked: entry.locked === true,\n forceShow: entry.forceShow === true,\n forceReq: entry.forceReq === true,\n };\n}\n\n// normalizeDefaultFieldRules -> Map(fieldKey -> rule). A Map because every\n// consumer wants \"what is the rule for THIS field\", which a Set of keys could\n// no longer answer once membership stopped implying all three intents.\nexport function normalizeDefaultFieldRules(list) {\n const out = new Map();\n (Array.isArray(list) ? list : []).forEach((entry) => {\n const rule = normalizeDefaultFieldRule(entry);\n if (rule && !out.has(rule.field)) out.set(rule.field, rule);\n });\n return out;\n}\n\nexport async function getModuleDefaultFields(module) {\n const json = await fetchJsonWithAuth(AUTH_URL, `/admin/default-fields?module=${encodeURIComponent(module)}`);\n const data = json?.data ?? json ?? {};\n return Array.isArray(data.fields) ? data.fields : [];\n}\n\n// getModuleDefaultFieldRules is what runtime consumers should call: it returns\n// the resolved Map, so no caller re-implements the legacy-string rule.\nexport async function getModuleDefaultFieldRules(module) {\n return normalizeDefaultFieldRules(await getModuleDefaultFields(module));\n}\n\nexport async function saveModuleDefaultFields(module, fields, otp) {\n return fetchJsonWithAuth(AUTH_URL, '/admin/default-fields', {\n method: 'PUT',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ module, fields, otp }),\n });\n}\n\n// Generic email verification — used by any admin-configured\n// field.verifyAction === \"email\" (AddFormV1/EditFormV1's VerifyFieldButton).\n//\n// The backend runs a layered check (syntax -> MX -> Mailgun -> SMTP mailbox\n// probe -> catch-all detection), so the verdict is richer than a boolean:\n//\n// valid keep/reject the address (unchanged meaning — the form gate)\n// result 'deliverable' | 'undeliverable' | 'risky' | 'unknown'\n// mailboxConfirmed the receiving server confirmed THIS mailbox specifically\n// catchAll the domain accepts every address, so the mailbox is unproven\n//\n// mailboxConfirmed is the one to trust for \"this person will actually get mail\".\n// A catch-all domain (Google Workspace default, many corporates) can never be\n// proven from outside — the UI says so rather than implying certainty.\nexport async function verifyEmail(email) {\n const json = await fetchJsonWithAuth(AUTH_URL, '/email-verify', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ email }),\n });\n const data = json?.data ?? json ?? {};\n return {\n valid: Boolean(data.valid),\n reason: data.reason ?? '',\n result: data.result ?? '',\n mailboxConfirmed: Boolean(data.mailboxConfirmed),\n catchAll: Boolean(data.catchAll),\n disposable: Boolean(data.disposable),\n roleAddress: Boolean(data.roleAddress),\n risk: data.risk ?? '',\n checks: Array.isArray(data.checks) ? data.checks : [],\n };\n}\n\nexport async function getAvailableCollections() {\n const json = await fetchJsonWithAuth(AUTH_URL, '/admin/lookup/collections');\n const data = json.data ?? json;\n return Array.isArray(data) ? data : [];\n}\n\nexport async function getCollectionFields(collection) {\n const json = await fetchJsonWithAuth(AUTH_URL, `/admin/lookup/collection-fields?collection=${encodeURIComponent(collection)}`);\n const data = json.data ?? json;\n return Array.isArray(data) ? data : [];\n}\n\nexport async function getArraySubfields(module, field) {\n const json = await fetchJsonWithAuth(AUTH_URL, `/admin/field-array-subfields?module=${encodeURIComponent(module)}&field=${encodeURIComponent(field)}`);\n const data = json.data ?? json;\n return Array.isArray(data?.fields) ? data.fields : [];\n}\n\n// ── Menu Modules & Actions (master data management) ──────────────────────────\n\nexport async function getMenuModules() {\n const json = await fetchJsonWithAuth(AUTH_URL, '/admin/menu-modules');\n return firstArray(json.data, json);\n}\n\nexport async function createMenuModule({ menuName, apiUrl = '', menuType = 'menu', parentMenuId = 0, displayOrder = 0 }) {\n const json = await fetchJsonWithAuth(AUTH_URL, '/admin/menu-modules', {\n method: 'POST',\n body: JSON.stringify({ menuName, apiUrl, menuType, parentMenuId, displayOrder }),\n });\n return json.data ?? json;\n}\n\nexport async function updateMenuModule(id, { menuName }) {\n const json = await fetchJsonWithAuth(AUTH_URL, `/admin/menu-modules/${id}`, {\n method: 'PUT',\n body: JSON.stringify({ menuName }),\n });\n return json.data ?? json;\n}\n\nexport async function deleteMenuModule(id) {\n const json = await fetchJsonWithAuth(AUTH_URL, `/admin/menu-modules/${id}`, { method: 'DELETE' });\n return json.data ?? json;\n}\n\nexport async function getMenuActions() {\n const json = await fetchJsonWithAuth(AUTH_URL, '/admin/menu-actions');\n return firstArray(json.data, json);\n}\n\nexport async function createMenuAction({ permissionName, permissionKey }) {\n const json = await fetchJsonWithAuth(AUTH_URL, '/admin/menu-actions', {\n method: 'POST',\n body: JSON.stringify({ permissionName, permissionKey }),\n });\n return json.data ?? json;\n}\n\nexport async function updateMenuAction(id, { permissionName }) {\n const json = await fetchJsonWithAuth(AUTH_URL, `/admin/menu-actions/${id}`, {\n method: 'PUT',\n body: JSON.stringify({ permissionName }),\n });\n return json.data ?? json;\n}\n\nexport async function deleteMenuAction(id) {\n const json = await fetchJsonWithAuth(AUTH_URL, `/admin/menu-actions/${id}`, { method: 'DELETE' });\n return json.data ?? json;\n}\n\nfunction normalizeRolePermissionValue(value) {\n if (value && typeof value === 'object' && !Array.isArray(value)) {\n return normalizeRolePermissionValue(\n value.value ?? value.access_value ?? value.accessValue ?? value.permissionValue ?? value.enabled,\n );\n }\n if (value === true || value === 1 || value === '1') return '1';\n const normalized = String(value ?? '').trim().toLowerCase();\n return normalized === 'true' || normalized === 'yes' || normalized === 'active' ? '1' : '0';\n}\n\nfunction normalizeRoleMenusForSave(menus = {}) {\n if (!menus || typeof menus !== 'object' || Array.isArray(menus)) return menus;\n return Object.fromEntries(Object.entries(menus).map(([menuName, menu]) => [\n menuName,\n {\n ...menu,\n menuId: menu?.menuId ?? menu?.menu_id ?? 0,\n permissions: Object.fromEntries(Object.entries(menu?.permissions ?? {}).map(([key, entry]) => [\n key,\n {\n ...(entry && typeof entry === 'object' && !Array.isArray(entry) ? entry : {}),\n id: entry?.id ?? entry?.permission_id ?? entry?.permissionId ?? 0,\n value: normalizeRolePermissionValue(entry),\n },\n ])),\n },\n ]));\n}\n\n// ── Permissions ───────────────────────────────────────────────────────────────\n\nexport async function getRolePermissions(roleId) {\n const json = await fetchJsonWithAuth(AUTH_URL, `/get-role-details?roleid=${roleId}`);\n return (json?.data ?? json) ?? {};\n}\n\nexport async function updateRolePermissions(roleId, menus) {\n return fetchJsonWithAuth(AUTH_URL, '/edit-role-details', {\n method: 'PUT',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ roleId, menus: normalizeRoleMenusForSave(menus) }),\n });\n}\n\n// Resolved permissions for the logged-in user's own role — moduleName ->\n// actionKey -> allowed (or the wildcard shape { \"*\": { \"*\": true } } for\n// full-access roles). Fetched once on login by PermissionContext.\nexport async function getMyPermissions() {\n const json = await fetchJsonWithAuth(AUTH_URL, '/me/permissions');\n return (json?.data ?? json) ?? {};\n}\n\n// ── Custom Forms ──────────────────────────────────────────────────────────────\n\nconst CUSTOM_FORMS_PATH = '/admin/custom-forms';\n\nexport async function getCustomForms(module = '', type = '', action = '') {\n const params = new URLSearchParams();\n if (module) params.append('module', module);\n if (type) params.append('formType', type);\n if (action) params.append('action', action);\n const path = `${CUSTOM_FORMS_PATH}?${params.toString()}`;\n const json = await fetchJsonWithAuth(AUTH_URL, path);\n const payload = json?.data;\n if (Array.isArray(payload)) return payload;\n if (Array.isArray(json)) return json;\n return [];\n}\n\nexport async function createCustomForm(form) {\n return fetchJsonWithAuth(AUTH_URL, CUSTOM_FORMS_PATH, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(form),\n });\n}\n\nexport async function updateCustomForm(id, form) {\n return fetchJsonWithAuth(AUTH_URL, `${CUSTOM_FORMS_PATH}/${id}`, {\n method: 'PUT',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(form),\n });\n}\n\nexport async function deleteCustomForm(id) {\n return fetchJsonWithAuth(AUTH_URL, `${CUSTOM_FORMS_PATH}/${id}`, { method: 'DELETE' });\n}\n\n// ── Row Action Config ─────────────────────────────────────────────────────────\n\nconst ROW_ACTION_CONFIG_PATH = '/admin/row-action-config';\n\n// Keep the module key written by Admin identical to the key used by ListView.\n// Module labels/keys supplied by the module catalog (or typed into the tags\n// selector) may contain casing and surrounding whitespace, while list routes\n// consistently request normalized keys.\nfunction normalizeRowActionModule(module) {\n return String(module ?? '').trim().toLowerCase();\n}\n\nexport async function getRowActionConfigs(module = '') {\n const normalizedModule = normalizeRowActionModule(module);\n const path = normalizedModule\n ? `${ROW_ACTION_CONFIG_PATH}?module=${encodeURIComponent(normalizedModule)}`\n : ROW_ACTION_CONFIG_PATH;\n const json = await fetchJsonWithAuth(AUTH_URL, path);\n const payload = json?.data;\n if (Array.isArray(payload)) return payload;\n if (Array.isArray(json)) return json;\n return [];\n}\n\nexport async function createRowActionConfig({ module, roleId = 0, rowActions = [] }) {\n const normalizedModule = normalizeRowActionModule(module);\n return fetchJsonWithAuth(AUTH_URL, ROW_ACTION_CONFIG_PATH, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ module: normalizedModule, roleId, rowActions }),\n });\n}\n\nexport async function updateRowActionConfig(id, rowActions = []) {\n return fetchJsonWithAuth(AUTH_URL, `${ROW_ACTION_CONFIG_PATH}/${id}`, {\n method: 'PUT',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ rowActions }),\n });\n}\n\nexport async function deleteRowActionConfig(id) {\n return fetchJsonWithAuth(AUTH_URL, `${ROW_ACTION_CONFIG_PATH}/${id}`, { method: 'DELETE' });\n}\n\nexport async function seedRowActionConfigs() {\n return fetchJsonWithAuth(AUTH_URL, `${ROW_ACTION_CONFIG_PATH}/seed`, { method: 'POST' });\n}\n\n// ── Module Action Rules ───────────────────────────────────────────────────────\n// Per-module configurable rules stored in auth repo, returned by module-data-list.\n// Frontend evaluates these rules per-row to show/hide row action buttons.\n\nconst MODULE_ACTION_RULES_PATH = '/admin/module-action-rules';\n\nexport async function getActivityRules(module) {\n const result = await fetchJsonWithAuth(AUTH_URL, `/admin/activity-rules?module=${encodeURIComponent(module)}`);\n return Array.isArray(result?.data) ? result.data : Array.isArray(result) ? result : [];\n}\n\nexport function saveActivityRule(id, rule) {\n return fetchJsonWithAuth(AUTH_URL, `/admin/activity-rules${id ? `/${id}` : ''}`, {\n method: id ? 'PUT' : 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(rule),\n });\n}\n\nexport function deleteActivityRule(id) {\n return fetchJsonWithAuth(AUTH_URL, `/admin/activity-rules/${id}`, { method: 'DELETE' });\n}\n\nexport async function getModuleActionRules(module) {\n const json = await fetchJsonWithAuth(AUTH_URL, `${MODULE_ACTION_RULES_PATH}?module=${encodeURIComponent(module)}`);\n const payload = json?.data;\n if (Array.isArray(payload)) return payload;\n if (Array.isArray(json)) return json;\n return [];\n}\n\n// allowedActions is an ALLOW-LIST: when the rule fires, every action it does\n// not name is blocked, including actions added later. That is what makes\n// \"Inactive jobs — Edit and Delete only\" expressible as one rule instead of a\n// blockedActions list that has to be revisited every time an action is added.\n//\n// REQ-20260908-01 — it was missing from both of these functions. The admin UI\n// collects it, the Go model stores it, and the evaluator honours it; only the\n// two lines below dropped it, so an admin picked the actions, saw them in the\n// drawer, saved, and the field silently never left the browser. The reported\n// symptom was \"the admin screen does nothing\", and the whole gap was that this\n// key was absent from a destructure and a JSON body.\n//\n// On the empty case, which is the dangerous one: an allow-list of [] would mean\n// \"block every action\". Both ends already guard it — the controller stores nil\n// when the list is empty, and allowedActionsOf() treats an empty array as \"no\n// allow-list\" — so the admin form's default of [] round-trips as \"unset\" rather\n// than as a total lockout. The default here is undefined for programmatic\n// callers that omit the key entirely; it is not load-bearing, and the guard\n// that matters is on the other two layers.\n// primaryAction / appliesTo (REQ-20261021-05) follow allowedActions' convention:\n// undefined is left out of the JSON, so the server keeps what it has stored.\nexport async function createModuleActionRule({ module, name, description = '', conditions = [], blockedActions = [], disabledActions = [], allowedActions = undefined, primaryAction = undefined, appliesTo = undefined, isActive = true }) {\n return fetchJsonWithAuth(AUTH_URL, MODULE_ACTION_RULES_PATH, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ module, name, description, conditions, blockedActions, disabledActions, allowedActions, primaryAction, appliesTo, isActive }),\n });\n}\n\nexport async function updateModuleActionRule(id, { name, description = '', conditions = [], blockedActions = [], disabledActions = [], allowedActions = undefined, primaryAction = undefined, appliesTo = undefined, isActive = true }) {\n return fetchJsonWithAuth(AUTH_URL, `${MODULE_ACTION_RULES_PATH}/${id}`, {\n method: 'PUT',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ name, description, conditions, blockedActions, disabledActions, allowedActions, primaryAction, appliesTo, isActive }),\n });\n}\n\nexport async function deleteModuleActionRule(id) {\n return fetchJsonWithAuth(AUTH_URL, `${MODULE_ACTION_RULES_PATH}/${id}`, { method: 'DELETE' });\n}\n\n\nexport async function getRoleOnboardingTabs(role, module = 'onboarding') {\n const params = new URLSearchParams({ module, configType: 'tabs', userId: '0', roleId: String(getRoleId(role)) });\n const json = await fetchJsonWithAuth(AUTH_URL, `${FIELD_CONFIG_PATH}?${params}`);\n return json.data ?? json;\n}\n\nexport async function saveRoleOnboardingTabs(role, onboardingTabs, module = 'onboarding') {\n return fetchJsonWithAuth(AUTH_URL, `${FIELD_CONFIG_PATH}/role`, {\n method: 'PUT', body: JSON.stringify({ module, roleId: getRoleId(role), configType: 'tabs', onboardingTabs }),\n });\n}\n\nexport async function getModuleTabConfig(module) {\n const json=await fetchJsonWithAuth(AUTH_URL,`/admin/module-tabs?module=${encodeURIComponent(module)}`);\n return json?.data ?? json ?? {};\n}\nexport async function saveModuleTabConfig(config) {\n return fetchJsonWithAuth(AUTH_URL,'/admin/module-tabs',{method:'PUT',headers:{'Content-Type':'application/json'},body:JSON.stringify(config)});\n}\n","// How a result row opens the record's detail view.\n//\n// Same vocabulary as the search form's action button (`actionButtonOpenAs` /\n// `OPEN_AS_OPTIONS` in searchBuilder/actionButtons.js) so an admin only learns\n// one set of words:\n//\n// self full route swap to /<module>/detailview/:id — the browser default,\n// and what every list did before this existed.\n// newTab the detail page in a new browser tab.\n// popup a Modal over the search page (/popup/<module>-detail/:id with a\n// `background` location) — the search stays mounted, so typed filters\n// survive. THE DEFAULT for the Sourcing search results.\n//\n// Options are defined inline (not imported from actionButtons.js) to avoid an\n// import cycle: services/detailDefaults.js imports this module.\nexport const DETAIL_VIEW_MODE_OPTIONS = [\n { value: 'self', label: 'Same page' },\n { value: 'newTab', label: 'New tab' },\n { value: 'popup', label: 'Popup' },\n];\n\nexport const DETAIL_VIEW_MODE_VALUES = DETAIL_VIEW_MODE_OPTIONS.map((o) => o.value);\n\n// Accepts any casing / spelling the config might carry (\"popUp\", \"POPUP\", \"\") —\n// anything unrecognised (including empty/undefined) resolves to 'popup', the\n// default. Only an explicit 'self' opts out of interception.\nexport function normalizeDetailViewMode(mode) {\n return { self: 'self', newtab: 'newTab', popup: 'popup' }[String(mode ?? '').trim().toLowerCase()] || 'popup';\n}\n\n// Route the popup mode navigates to. The host app registers exactly this path\n// (App.jsx, inside the `{background && <Routes>}` block). Fixed rather than\n// derived from moduleName: the search component runs as moduleName=\"candidates\"\n// (plural), and interpolating that produced \"/popup/candidates-detail/:id\",\n// which matched no route and silently rendered nothing.\nexport const DETAIL_VIEW_POPUP_PATH = '/popup/candidate-detail';\n\n// `href` is an already-resolved internal path, e.g. \"/candidates/detailview/<id>\"\n// (optionally with a query string / hash). Returns true when it has taken over\n// navigation; false means \"not handled — let the normal <Link>/navigate proceed\"\n// (which is the 'self' case).\n//\n// `location` is optional — the page to return to when the popup closes. When\n// omitted it is taken from window.location, so callers do not need useLocation().\nexport function runDetailViewOpen(mode, { href, navigate, location } = {}) {\n if (!href) return false;\n const resolved = normalizeDetailViewMode(mode);\n\n if (resolved === 'self') return false;\n\n if (resolved === 'newTab') {\n window.open(href, '_blank', 'noopener');\n return true;\n }\n\n // popup\n const str = String(href);\n const id = (str.split('/detailview/')[1] ?? str.split('/detail-view/')[1])?.split(/[/?#]/)[0];\n if (!id || typeof navigate !== 'function') return false;\n const background = location\n || (typeof window !== 'undefined'\n ? {\n pathname: window.location.pathname,\n search: window.location.search,\n hash: window.location.hash,\n }\n : undefined);\n navigate(`${DETAIL_VIEW_POPUP_PATH}/${id}`, { state: { background } });\n return true;\n}\n","// Central source-of-truth for detail-view DISPLAY defaults.\n//\n// These values used to be hard-coded inside components/detail/fileUtils.js and\n// components/detail/FieldValue.jsx. They now live here, are seeded with the same\n// built-in defaults, and are overridable from the admin page\n// (Admin → Detail Groups → Display Defaults), which persists them via\n// GET/POST /admin/detail-defaults.\n//\n// This is a plain module (not a React component / context) so fileUtils.js — a\n// non-component helper — can read it synchronously. Consumers read getDefaults()\n// at render time; loadDetailDefaults() fetches the saved values once and updates\n// the store (falling back to the built-ins on any failure).\n\nimport { getDetailDefaults as fetchDetailDefaults } from './adminApi';\nimport { DETAIL_VIEW_MODE_VALUES } from '../components/detailViewMode';\n\n// Built-in defaults — exactly the previous hard-coded behaviour. S3 base still\n// honours VITE_S3_BASE_URL as the env-level seed; the admin value overrides it.\nexport const BUILT_IN_DEFAULTS = Object.freeze({\n s3BaseUrl: (\n import.meta.env?.VITE_S3_BASE_URL ||\n 'https://zinnext-devlopment-ap-south-1.s3.ap-south-1.amazonaws.com'\n ).replace(/\\/+$/, ''),\n // A pure CALENDAR date — a date of birth, an expiry. No time, and no zone\n // suffix: stamping a clock on a birthday claims precision it does not have.\n dateFormat: 'DD MMM YYYY',\n // An INSTANT — created/updated stamps, interview slots. Carries the time and,\n // unless switched off below, the zone it is being shown in. Without the zone\n // a timestamp is ambiguous the moment two people in different countries read\n // it.\n dateTimeFormat: 'MMM DD, YYYY | hh:mm A',\n showTimeZoneLabel: true,\n // The tenant's clock. EMPTY means \"use the viewer's browser zone\", which is\n // exactly the behaviour before this setting existed — so nothing changes for\n // a tenant that never sets it. See services/timezone.js.\n timeZone: '',\n // Short labels for zones (\"Asia/Kolkata\" → \"IST\"). Abbreviations are NOT\n // valid IANA identifiers and are dangerously ambiguous as inputs, so they\n // exist only as display labels here.\n timeZoneAliases: {},\n // Which per-region rule profile form groups apply (\"US\"/\"UK\"/\"IND\"/'' for\n // the default). Carries no logic — it is a KEY into group.regionRules, which\n // is what lets a new market be added as config rather than as code.\n region: '',\n booleanTrueLabel: 'Yes',\n booleanFalseLabel: 'No',\n emptyPlaceholder: '-',\n // Per-render-type empty texts. The single `emptyPlaceholder` above could only\n // ever say one thing (\"-\"), which cannot distinguish \"no work experience\" from\n // \"no document\" and reads as a rendering fault rather than as information.\n // Built-in per-type defaults live in components/detail/emptyText.js; anything\n // set here overrides them, and `default` covers every unlisted type.\n emptyTexts: {},\n separator: ' - ',\n documentNameOrder: ['name', 'documentName', 'uploadName', 'uploadedFileName', 'uniqueName'],\n // Common phone-number format — one place, applied everywhere (forms + detail),\n // exactly like `dateFormat`. Groups of digit counts separated by a literal\n // separator: \"3-3-4\" → 999-878-3413 (total 10 digits). Change it here (or in\n // Admin → Display Defaults) and every phone field re-formats to match.\n phoneFormat: '3-3-4',\n // LAST-RESORT country code, used only when the record itself carries none\n // (see components/detail/phoneDisplay.js). Deliberately EMPTY: a tenant that\n // wants every unqualified number stamped \"+1\" sets it in Admin → Display\n // Defaults, but nothing invents a country for a record that never stated one\n // — that is exactly how every candidate ended up displayed as \"+1\".\n phoneCountryCode: '',\n // How a candidate row in the Sourcing search results opens the detail view:\n // 'popup' (a modal over the search — the default, so typed search filters\n // survive) | 'self' (full route swap) | 'newTab'. Same vocabulary as\n // actionButtonOpenAs; see components/detailViewMode.js. This is the tenant\n // FALLBACK — a per-search-form `detailViewOpenMode` wins over it. An admin\n // sets it in Admin > Detail Groups > Display Defaults.\n candidateDetailViewMode: 'popup',\n});\n\nlet current = { ...BUILT_IN_DEFAULTS };\nlet loadPromise = null;\n\n// getDefaults returns the live defaults (built-ins until loadDetailDefaults runs).\nexport function getDefaults() {\n return current;\n}\n\n// sanitize keeps only the keys that carry a real value, so a partial/empty saved\n// config never blanks out a built-in.\nfunction sanitize(d) {\n if (!d || typeof d !== 'object') return {};\n const out = {};\n if (d.s3BaseUrl) out.s3BaseUrl = String(d.s3BaseUrl).replace(/\\/+$/, '');\n if (d.dateFormat) out.dateFormat = d.dateFormat;\n if (d.dateTimeFormat) out.dateTimeFormat = d.dateTimeFormat;\n // A saved `false` is a real setting (\"never print the zone\"), so the key is\n // honoured whenever it is present as a boolean rather than only when truthy.\n if (typeof d.showTimeZoneLabel === 'boolean') out.showTimeZoneLabel = d.showTimeZoneLabel;\n // '' is meaningful (fall back to the browser zone), so any string is honoured.\n if (typeof d.timeZone === 'string') out.timeZone = d.timeZone.trim();\n // '' is meaningful: \"use each group's own defaults, no region profile\".\n if (typeof d.region === 'string') out.region = d.region.trim();\n if (d.timeZoneAliases && typeof d.timeZoneAliases === 'object' && !Array.isArray(d.timeZoneAliases)) {\n out.timeZoneAliases = { ...current.timeZoneAliases, ...d.timeZoneAliases };\n }\n if (d.booleanTrueLabel) out.booleanTrueLabel = d.booleanTrueLabel;\n if (d.booleanFalseLabel) out.booleanFalseLabel = d.booleanFalseLabel;\n if (d.emptyPlaceholder) out.emptyPlaceholder = d.emptyPlaceholder;\n // Objects merge key-wise rather than replacing wholesale, so configuring one\n // render type does not blank out the others.\n if (d.emptyTexts && typeof d.emptyTexts === 'object' && !Array.isArray(d.emptyTexts)) {\n const texts = {};\n Object.entries(d.emptyTexts).forEach(([key, value]) => {\n if (typeof value === 'string' && value.trim() !== '') texts[key] = value.trim();\n });\n if (Object.keys(texts).length) out.emptyTexts = { ...current.emptyTexts, ...texts };\n }\n if (typeof d.separator === 'string' && d.separator !== '') out.separator = d.separator;\n if (typeof d.phoneFormat === 'string' && d.phoneFormat.trim() !== '') out.phoneFormat = d.phoneFormat.trim();\n // Unlike the others, an EMPTY country code is a meaningful setting (\"stamp\n // nothing on a record that stated no country\"), so '' is honoured instead of\n // being treated as \"unset, keep the built-in\".\n if (typeof d.phoneCountryCode === 'string') out.phoneCountryCode = d.phoneCountryCode.trim();\n // A saved empty string is meaningful here (\"show no code at all\"), so unlike\n // the others this key is accepted whenever it is present as a string.\n if (typeof d.phoneCountryCode === 'string') out.phoneCountryCode = d.phoneCountryCode.trim();\n if (Array.isArray(d.documentNameOrder) && d.documentNameOrder.length) out.documentNameOrder = d.documentNameOrder;\n // Only a recognised value (self | newTab | popup) overrides the built-in;\n // anything else — empty, or a stale 'redirect' from an earlier build — is\n // ignored, so the store keeps the 'popup' default.\n if (DETAIL_VIEW_MODE_VALUES.includes(d.candidateDetailViewMode)) {\n out.candidateDetailViewMode = d.candidateDetailViewMode;\n }\n // Per-module format for FORM date pickers ({ candidates: 'MM/DD/YYYY' }).\n // Replaced wholesale — it is one admin-edited map, and {} is how it is cleared.\n if (d.formDateFormats && typeof d.formDateFormats === 'object' && !Array.isArray(d.formDateFormats)) {\n const formats = {};\n Object.entries(d.formDateFormats).forEach(([module, format]) => {\n if (typeof format === 'string' && format.trim() !== '') formats[module] = format.trim();\n });\n out.formDateFormats = formats;\n }\n return out;\n}\n\n// ── Phone number formatting (common, config-driven) ──────────────────────────\n// The format string is groups of digit counts joined by a literal separator,\n// e.g. \"3-3-4\" → [3,3,4] joined by \"-\". parsePhoneFormat returns { groups, sep,\n// total } so both the formatter and the length validation share one definition.\nexport function parsePhoneFormat(format = getPhoneFormat()) {\n const groups = (String(format).match(/\\d+/g) ?? ['3', '3', '4']).map(Number).filter((n) => n > 0);\n const sep = (String(format).match(/\\D+/)?.[0]) ?? '-';\n const safeGroups = groups.length ? groups : [3, 3, 4];\n return { groups: safeGroups, sep, total: safeGroups.reduce((a, b) => a + b, 0) };\n}\n\n// Live phone format from the same singleton the detail defaults use.\nexport function getPhoneFormat() {\n return current.phoneFormat || BUILT_IN_DEFAULTS.phoneFormat;\n}\n\n// The tenant-wide fallback country code — see BUILT_IN_DEFAULTS for why it is\n// empty by default. Consumed by components/detail/phoneDisplay.js as the LAST\n// resort, after the record's own code.\nexport function getPhoneCountryCode() {\n return current.phoneCountryCode ?? BUILT_IN_DEFAULTS.phoneCountryCode;\n}\n\n// Strips everything but digits, capped at the configured total (default 10).\nexport function phoneDigits(value, format = getPhoneFormat()) {\n const { total } = parsePhoneFormat(format);\n return String(value ?? '').replace(/\\D/g, '').slice(0, total);\n}\n\n// formatPhone turns any input into the configured mask as the user types:\n// \"9998783413\" → \"999-878-3413\". Partial input formats progressively\n// (\"99987\" → \"999-87\"); non-digits are ignored.\nexport function formatPhone(value, format = getPhoneFormat()) {\n const { groups, sep } = parsePhoneFormat(format);\n const digits = phoneDigits(value, format);\n if (!digits) return '';\n const chunks = [];\n let i = 0;\n for (const size of groups) {\n if (i >= digits.length) break;\n chunks.push(digits.slice(i, i + size));\n i += size;\n }\n return chunks.join(sep);\n}\n\n// applyDefaults merges a (partial) config over the current store immediately —\n// used by the admin page right after a successful save so the change is live\n// without a reload.\nexport function applyDefaults(partial) {\n const clean = sanitize(partial);\n Object.keys(clean).forEach((key) => configuredKeys.add(key));\n current = { ...current, ...clean };\n return current;\n}\n\n// Keys a tenant has actually SAVED, as opposed to built-ins. getDefaults()\n// cannot tell the two apart, and some consumers must: see\n// getConfiguredDateFormat.\nconst configuredKeys = new Set();\n\n// getConfiguredDateFormat — the tenant's saved `dateFormat`, or undefined when\n// the tenant never set one.\n//\n// Date PICKERS and the LIST VIEW read this instead of getDefaults().dateFormat\n// on purpose. Their behaviour predates the display defaults (antd's picker\n// default and the list's own layout), and the built-in 'DD MMM YYYY' was only\n// ever the DETAIL view's default. Falling back to it here would silently\n// re-format every picker and list column of every tenant that never asked for\n// it. So: a tenant that saves a date format (Admin → Display Defaults) gets it\n// everywhere; a tenant that does not sees exactly what it saw before.\nexport function getConfiguredDateFormat() {\n return configuredKeys.has('dateFormat') ? current.dateFormat : undefined;\n}\n\n// getFormDateFormat — the format a module's Add/Edit form DATE PICKERS use, from\n// Admin → Display Defaults → formDateFormats, or undefined when that module has\n// none (the caller then falls back to getConfiguredDateFormat). Module names\n// arrive as either \"candidate\" or \"candidates\", so both spellings match.\nexport function getFormDateFormat(moduleName) {\n const formats = current.formDateFormats;\n const key = String(moduleName ?? '').trim().toLowerCase();\n if (!formats || !key) return undefined;\n const base = key.endsWith('s') ? key.slice(0, -1) : key;\n const match = Object.keys(formats).find((module) => {\n const candidate = module.trim().toLowerCase();\n return candidate === key || candidate === base || candidate === `${base}s`;\n });\n return match ? formats[match] : undefined;\n}\n\n// loadDetailDefaults fetches the saved defaults once (cached). Safe to call from\n// anywhere — failures silently keep the built-ins. Pass force=true to refetch.\nexport function loadDetailDefaults(force = false) {\n if (loadPromise && !force) return loadPromise;\n // Promise.resolve().then(...) so a synchronous throw from fetchDetailDefaults\n // (e.g. a test that partially mocks adminApi and leaves it undefined) lands in\n // the .catch below and keeps the built-ins, exactly like a network failure.\n loadPromise = Promise.resolve()\n .then(() => fetchDetailDefaults())\n .then((d) => applyDefaults(d))\n .catch(() => current);\n return loadPromise;\n}\n","// ─────────────────────────────────────────────────────────────────────────\n// timezone — the application's clock.\n//\n// THE REQUIREMENT\n// \"We work with multiple locations, so we need to see the time based on\n// location. Set up a common time setup like GST, UTC, IST — list all the time\n// zones, and if I select the time zone the entire application has to work on\n// that time zone. It won't reflect the system time.\"\n//\n// So: one tenant-wide zone, chosen in admin, used for RENDERING every\n// date-time AND for interpreting what the user types — never the browser's.\n//\n// WHERE THE SETTING LIVES\n// detailViewDefaults.timeZone, alongside dateFormat / phoneFormat / the empty\n// texts. That store already exists, is already tenant-scoped, and is already\n// loaded once at startup — a second settings store would only create a second\n// thing to keep in sync.\n//\n// THE ZONE LIST IS NOT HARDCODED\n// It comes from Intl.supportedValuesOf('timeZone') — every IANA zone the\n// browser knows. The abbreviations the requirement names (IST, GST, UTC) are\n// not IANA identifiers, so they are provided as an admin-editable ALIAS map\n// (detailViewDefaults.timeZoneAliases) that labels the real zones. Nothing in\n// this file enumerates a country.\n//\n// ── THE CALENDAR-DATE TRAP (the important part) ──────────────────────────\n// A date of birth, a passport expiry, an education start date are CALENDAR\n// dates: \"7 July 2026\" means the same thing in Dubai and in New York. Passing\n// one through a timezone conversion shifts it by a day for half the world's\n// zones — silently corrupting data that was never about an instant in time.\n//\n// So conversion is OPT-IN, never blanket: only `datetime`/`time` fields, or a\n// field explicitly marked `tzAware`, are converted. Plain `date` fields keep\n// their calendar semantics. See shouldConvertToZone below.\n// ─────────────────────────────────────────────────────────────────────────\nimport dayjs from 'dayjs';\nimport utc from 'dayjs/plugin/utc';\nimport timezonePlugin from 'dayjs/plugin/timezone';\nimport { getDefaults } from './detailDefaults';\n\ndayjs.extend(utc);\ndayjs.extend(timezonePlugin);\n\n// The browser's own zone, used when the tenant has not chosen one. Resolved\n// lazily and cached: dayjs.tz.guess() reads Intl on every call.\nlet guessed = null;\nfunction browserZone() {\n if (guessed === null) {\n try {\n guessed = dayjs.tz.guess() || 'UTC';\n } catch {\n guessed = 'UTC';\n }\n }\n return guessed;\n}\n\n/**\n * isValidZone — is this a zone we are willing to run the application on?\n *\n * Deliberately STRICTER than Intl. ICU accepts bare abbreviations, but does so\n * inconsistently and with traps that would be invisible until a DST boundary:\n *\n * 'IST' → Asia/Calcutta (yet IST is equally Irish and Israel Standard Time)\n * 'EST' → America/Panama (a fixed -05:00 that NEVER shifts to EDT, so a\n * tenant picking \"EST\" would silently be an hour\n * wrong for two-thirds of the year)\n * 'GST' → rejected entirely\n *\n * So an accepted zone must be a real IANA identifier — \"Area/Location\", or the\n * one legitimate bare name, UTC. Abbreviations remain available to users as\n * LABELS through the alias map, where they are unambiguous because they point\n * at a specific IANA zone.\n */\nexport function isValidZone(zone) {\n const name = String(zone ?? '').trim();\n if (!name) return false;\n if (name !== 'UTC' && !name.includes('/')) return false;\n try {\n new Intl.DateTimeFormat('en-US', { timeZone: name });\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * getAppTimeZone — the zone everything renders and is interpreted in.\n *\n * An unset or unknown value falls back to the browser's zone, so the app keeps\n * working exactly as it did before anyone configured this. Written so a\n * per-user override can be layered in later without touching any call site.\n */\nexport function getAppTimeZone(defaults = getDefaults()) {\n const configured = String(defaults?.timeZone ?? '').trim();\n return isValidZone(configured) ? configured : browserZone();\n}\n\n/** appNow — \"now\", in the application's zone. */\nexport function appNow(defaults) {\n return dayjs().tz(getAppTimeZone(defaults));\n}\n\n/**\n * toApp — read an instant (ISO string, Date, dayjs, epoch ms) as it appears in\n * the application's zone. Invalid input returns an invalid dayjs, so callers\n * can keep using .isValid() exactly as they do now.\n */\nexport function toApp(value, defaults) {\n const parsed = dayjs(value?.$date ?? value);\n return parsed.isValid() ? parsed.tz(getAppTimeZone(defaults)) : parsed;\n}\n\n/**\n * formatApp — the one formatter. Falls back to the tenant's configured\n * dateFormat, so changing the format still happens in exactly one place.\n */\nexport function formatApp(value, format, defaults = getDefaults()) {\n const d = toApp(value, defaults);\n if (!d.isValid()) return '';\n return d.format(format || defaults?.dateFormat || 'DD MMM YYYY');\n}\n\n/**\n * tzShortLabel — the small suffix printed after a TIME so a reader knows which\n * clock they are looking at: \"IST\", \"GST\", or the zone's own name when nobody\n * has given it a short one.\n *\n * Deliberately NOT printed after a plain calendar date. A date of birth has no\n * time and no zone; stamping one on it claims a precision the value does not\n * have.\n */\nexport function tzShortLabel(defaults = getDefaults(), at) {\n const zone = getAppTimeZone(defaults);\n const alias = aliasFor(zone, defaults);\n // A zone that changes abbreviation across the year is stored as a PAIR\n // (\"EST/EDT\"), because the table cannot know which applies. Given the instant\n // being printed we can: a timestamp reading \"12:37 AM EST/EDT\" tells the\n // reader the two things it might be and leaves them to work out which, which\n // is precisely the ambiguity the suffix exists to remove.\n if (alias && alias.includes('/')) {\n const inEffect = zoneAbbreviation(zone, at);\n if (inEffect) {\n const halves = alias.split('/').map((half) => half.trim());\n const matched = halves.find((half) => half.toUpperCase() === inEffect.toUpperCase());\n return matched || inEffect;\n }\n // No abbreviation available: the pair is still more informative than the\n // raw zone name, so it stands.\n }\n return alias || zoneAbbreviation(zone, at) || zone;\n}\n\n/**\n * zoneAbbreviation — the short name a zone actually goes by AT a given instant\n * (\"EDT\" in August, \"EST\" in January), or '' when it has no letter form.\n *\n * Intl answers this correctly including the daylight-saving rules, which is why\n * it is asked rather than a lookup table: the rules change, and a table that\n * says \"EST/EDT\" is a table admitting it does not know.\n *\n * Zones with no common abbreviation come back as an offset (\"GMT+5:30\"). Those\n * are rejected here so the caller falls through to its configured alias — India\n * is written \"IST\", never \"GMT+5:30\".\n */\nexport function zoneAbbreviation(zone, at) {\n try {\n const when = at === undefined ? new Date() : new Date(dayjs(at?.$date ?? at).valueOf());\n if (Number.isNaN(when.valueOf())) return '';\n const parts = new Intl.DateTimeFormat('en-US', {\n timeZone: zone,\n timeZoneName: 'short',\n }).formatToParts(when);\n const name = parts.find((part) => part.type === 'timeZoneName')?.value ?? '';\n // Letters only. \"GMT+5:30\" is an offset wearing a name badge.\n return /^[A-Za-z]+$/.test(name) ? name : '';\n } catch {\n // An unknown zone throws rather than guessing. The caller has a fallback.\n return '';\n }\n}\n\n/**\n * formatAppDateTime — an INSTANT, in the tenant's zone, with the zone named.\n *\n * \"Aug 06, 2026 | 07:03 PM IST\"\n *\n * The format and whether to show the zone are both config, so a tenant can\n * change either without a deploy. The zone suffix is what turns an ambiguous\n * timestamp into a fact: without it, a team spread across countries cannot tell\n * whether 07:03 PM is theirs or someone else's.\n */\nexport function formatAppDateTime(value, defaults = getDefaults()) {\n const shown = formatApp(value, defaults?.dateTimeFormat || 'MMM DD, YYYY | hh:mm A', defaults);\n if (!shown) return '';\n if (defaults?.showTimeZoneLabel === false) return shown;\n // The label is resolved FOR THIS INSTANT, so a summer timestamp reads \"EDT\"\n // and a winter one \"EST\" — rather than both reading \"EST/EDT\".\n const label = tzShortLabel(defaults, value);\n return label ? `${shown} ${label}` : shown;\n}\n\n/**\n * shouldConvertToZone — may this field's value be moved between zones?\n *\n * FALSE for plain calendar dates. This is the guard described in the header,\n * and it is deliberately conservative: a field must SAY it carries an instant\n * (type datetime/time) or opt in with `tzAware`, otherwise it is left alone.\n * Being wrong in this direction shows a time in the wrong zone; being wrong in\n * the other direction changes a stored date by a day.\n */\nexport function shouldConvertToZone(field) {\n if (!field) return false;\n if (field.tzAware === true) return true;\n if (field.tzAware === false) return false;\n const type = String(field.type ?? '').toLowerCase();\n return type === 'datetime' || type === 'time' || type === 'datetime-local';\n}\n\n/**\n * fromAppInput — a picker value the user entered MEANING the application's\n * zone, converted to the correct absolute instant for storage.\n *\n * A DatePicker hands back a dayjs in the BROWSER's zone. If the tenant zone is\n * Asia/Dubai and the user picks 09:00, they mean 09:00 in Dubai — storing the\n * browser's 09:00 would be a different moment entirely.\n */\nexport function fromAppInput(value, defaults) {\n // An EMPTY input is not a moment, and must never become one.\n //\n // dayjs(undefined) returns the CURRENT time and reports isValid() === true —\n // so without this guard an untouched picker was serialised as \"now\". On the\n // submission form that wrote the moment of saving into interviewAvailability\n // .startTime AND .endTime, giving every submission an interview slot the\n // recruiter never entered, with both ends identical. dayjs(null) and\n // dayjs('') are correctly invalid; only `undefined` has this behaviour, which\n // is exactly the shape a registered-but-empty antd picker hands back.\n if (value === undefined || value === null || value === '') return null;\n const d = dayjs(value);\n if (!d.isValid()) return null;\n const zone = getAppTimeZone(defaults);\n // Re-interpret the WALL-CLOCK reading in the target zone, rather than\n // converting the instant (which would keep the wrong moment and merely\n // relabel it).\n return dayjs.tz(d.format('YYYY-MM-DDTHH:mm:ss'), zone);\n}\n\n/**\n * zoneOffsetLabel — \"UTC+05:30\" for a zone, at the current moment.\n * Computed rather than tabulated, so it stays correct across DST.\n */\nexport function zoneOffsetLabel(zone = getAppTimeZone()) {\n try {\n const minutes = dayjs().tz(zone).utcOffset();\n const sign = minutes < 0 ? '-' : '+';\n const abs = Math.abs(minutes);\n const hh = String(Math.floor(abs / 60)).padStart(2, '0');\n const mm = String(abs % 60).padStart(2, '0');\n return `UTC${sign}${hh}:${mm}`;\n } catch {\n return '';\n }\n}\n\n/**\n * tzLabel — what a viewer sees next to a time so they know WHICH zone they are\n * reading: \"IST (UTC+05:30)\" when an alias names it, else\n * \"Asia/Kolkata (UTC+05:30)\".\n */\nexport function tzLabel(defaults = getDefaults()) {\n const zone = getAppTimeZone(defaults);\n const alias = aliasFor(zone, defaults);\n return `${alias || zone} (${zoneOffsetLabel(zone)})`;\n}\n\n// Built-in aliases covering the abbreviations the requirement names, plus the\n// common business zones. Admin-editable via detailViewDefaults.timeZoneAliases;\n// anything configured there wins, and unknown zones simply have no alias.\nexport const BUILT_IN_TZ_ALIASES = Object.freeze({\n UTC: 'UTC',\n 'Asia/Kolkata': 'IST',\n 'Asia/Calcutta': 'IST',\n 'Asia/Dubai': 'GST',\n 'America/New_York': 'EST/EDT',\n 'America/Chicago': 'CST/CDT',\n 'America/Denver': 'MST/MDT',\n 'America/Los_Angeles': 'PST/PDT',\n 'Europe/London': 'GMT/BST',\n 'Europe/Berlin': 'CET/CEST',\n 'Asia/Singapore': 'SGT',\n 'Asia/Tokyo': 'JST',\n 'Australia/Sydney': 'AEST/AEDT',\n});\n\n/** aliasFor — the short name for a zone, config first. */\nexport function aliasFor(zone, defaults = getDefaults()) {\n const configured = defaults?.timeZoneAliases ?? {};\n return configured[zone] ?? BUILT_IN_TZ_ALIASES[zone] ?? '';\n}\n\n/**\n * listTimeZones — every zone the runtime knows, labelled with its alias and\n * current offset, sorted by offset then name so the picker reads like a map\n * rather than an alphabetical wall.\n *\n * Returns [{ value, label, alias, offsetLabel, offsetMinutes }].\n */\nexport function listTimeZones(defaults = getDefaults()) {\n let enumerated = [];\n try {\n enumerated = Intl.supportedValuesOf('timeZone') ?? [];\n } catch {\n // Older runtimes cannot enumerate at all; the union below still yields the\n // named zones, so the picker is never empty.\n enumerated = [];\n }\n\n // UNION, not just the enumerated list. ICU builds disagree about which name\n // is canonical: this runtime enumerates \"Asia/Calcutta\" and omits both\n // \"Asia/Kolkata\" and \"UTC\", yet accepts all three. Listing only what is\n // enumerated would therefore hide IST and UTC — two of the three zones the\n // requirement names by hand — on some machines and not others.\n // Everything is validated, so an alias for a zone this runtime does not know\n // is dropped rather than offered and then failing at format time.\n const named = ['UTC', ...Object.keys(BUILT_IN_TZ_ALIASES), ...Object.keys(defaults?.timeZoneAliases ?? {})];\n const zones = [...new Set([...named, ...enumerated])].filter(isValidZone);\n\n return zones\n .map((zone) => {\n let offsetMinutes = 0;\n try {\n offsetMinutes = dayjs().tz(zone).utcOffset();\n } catch {\n return null;\n }\n const alias = aliasFor(zone, defaults);\n const offsetLabel = zoneOffsetLabel(zone);\n return {\n value: zone,\n alias,\n offsetLabel,\n offsetMinutes,\n label: `${alias ? `${alias} — ` : ''}${zone} (${offsetLabel})`,\n };\n })\n .filter(Boolean)\n .sort((a, b) => a.offsetMinutes - b.offsetMinutes || a.value.localeCompare(b.value));\n}\n","// Dot-notation module names: \"job.client.company\" means \"fetch the `job`\n// module, then display the data found at `client.company` inside each record\".\n// Only the segment before the first dot is a real backend module — every API\n// call (module-data-list, field-config, permissions) must use it, while the\n// remaining segments are resolved client-side against each fetched record.\n\nexport function parseModulePath(moduleName) {\n const raw = String(moduleName ?? '').trim();\n if (!raw) return { baseModule: '', nestedPath: '' };\n\n const [baseModule, ...rest] = raw.split('.');\n return {\n baseModule: baseModule.trim(),\n nestedPath: rest.map((part) => part.trim()).filter(Boolean).join('.'),\n };\n}\n\nexport function getBaseModuleName(moduleName) {\n return parseModulePath(moduleName).baseModule;\n}\n\nexport function getValueAtPath(source, path) {\n return String(path ?? '')\n .split('.')\n .filter(Boolean)\n .reduce((value, key) => (value == null ? undefined : value[key]), source);\n}\n","import { ensureToken, fetchJsonWithAuth } from './authApi';\nimport { AUTH_URL } from './apiConfig';\n\n// ── Common Module Documents API ───────────────────────────────────────────────\n// Module-agnostic document registry (Auth gateway \"documents\" collection, files\n// in S3). Every module's Add Form registers its uploads here AFTER the module\n// record is created — the module's Create API generates the reference id\n// (jobId / candidateId / submissionId), and that id is what links each document\n// row back to its record.\n\n// Strips the transport decorations collectFileParts may leave on a part key —\n// the moduleWrites routing prefix (\"__mw__<module>__\") and an addRow row-index\n// suffix (\"[0]\") — so the registered fieldName is the clean form-field key\n// (e.g. \"resume\", \"jobDescription\", \"offerLetter\").\nfunction cleanFieldName(formKey) {\n return String(formKey ?? '')\n .replace(/^__mw__.*?__/, '')\n .replace(/\\[\\d+\\]$/, '')\n .trim() || 'file';\n}\n\n/**\n * uploadModuleDocuments — registers uploaded files against a created module\n * record. Common across ALL modules: pass the module name and the record id\n * its Create API returned.\n *\n * @param moduleName the module key (e.g. \"jobs\", \"candidates\", \"submissions\")\n * @param refId the created record's _id (jobId / candidateId / …)\n * @param fileParts [{ formKey, file }] — the shape collectFileParts returns;\n * formKey is the form field the file was uploaded against\n * @param metadata optional { [fieldName]: {...} } extra metadata per field\n */\nexport async function uploadModuleDocuments(moduleName, refId, fileParts = [], metadata = {}) {\n if (!moduleName) throw new Error('moduleName is required to upload documents');\n if (!refId) throw new Error('refId (created record id) is required to upload documents');\n if (!fileParts.length) return { data: [], total: 0 };\n\n const token = await ensureToken();\n\n // NOTE: do NOT set Content-Type — the browser must add the multipart\n // boundary itself (same convention as createModuleRecord).\n const formData = new FormData();\n fileParts.forEach(({ formKey, file }) => {\n const fileName = file?.name ?? undefined;\n formData.append(cleanFieldName(formKey), file, fileName);\n });\n if (metadata && Object.keys(metadata).length > 0) {\n formData.append('metadata', JSON.stringify(metadata));\n }\n\n const params = new URLSearchParams({ module: moduleName, refId: String(refId) });\n let res;\n try {\n res = await fetch(`${AUTH_URL}/documents/upload?${params.toString()}`, {\n method: 'POST',\n headers: { Authorization: `Bearer ${token}` },\n body: formData,\n });\n } catch (netErr) {\n const error = new Error('Unable to connect to the server. Please check your network connection.');\n error.originalError = netErr;\n throw error;\n }\n\n const contentType = res.headers.get('content-type') || '';\n const data = contentType.includes('application/json') ? await res.json() : await res.text();\n if (!res.ok) {\n const errorMsg = (typeof data === 'object' ? (data?.error || data?.message) : data) || `Server returned status ${res.status}`;\n const error = new Error(errorMsg);\n error.status = res.status;\n error.data = data;\n throw error;\n }\n return data?.data ?? data;\n}\n\n/**\n * getModuleDocuments — lists a module record's documents (newest first), each\n * carrying a 24h presigned S3 download URL as `fileUrl`.\n *\n * @param moduleName the module key (e.g. \"jobs\", \"candidates\", \"submissions\")\n * @param refId the module record's _id\n * @param fieldName optional — only documents uploaded against this form field\n */\nexport async function getModuleDocuments(moduleName, refId, fieldName = '') {\n if (!moduleName) throw new Error('moduleName is required to fetch documents');\n if (!refId) throw new Error('refId is required to fetch documents');\n const params = new URLSearchParams({ module: moduleName, refId: String(refId) });\n if (fieldName) params.set('fieldName', fieldName);\n const json = await fetchJsonWithAuth(AUTH_URL, `/documents?${params.toString()}`);\n const payload = json?.data ?? json ?? {};\n return {\n data: Array.isArray(payload?.data) ? payload.data : (Array.isArray(payload) ? payload : []),\n total: payload?.total ?? 0,\n };\n}\n\n/**\n * deleteModuleDocument — soft-delete one registry document.\n *\n * Needed because removing a document ROW from a record left the registry entry\n * behind, and EditFormV1 rebuilds an empty repeatable group FROM the registry.\n * The row therefore came back on the next load, which reads as \"the delete did\n * not save\". The registry has to be told, or it will keep resurrecting the file.\n *\n * Resolves to false rather than throwing when the id is missing or the call\n * fails: a registry that will not accept the delete must not block the record's\n * own update, which is the change the user actually asked for. The caller\n * decides whether to warn.\n */\nexport async function deleteModuleDocument(documentId) {\n if (!documentId) return false;\n try {\n await fetchJsonWithAuth(AUTH_URL, `/documents/${encodeURIComponent(String(documentId))}`, {\n method: 'DELETE',\n });\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * generateModuleId — generates a valid 24-character hexadecimal MongoDB ObjectID\n * string on the client so documents can be uploaded and stored against `moduleId`\n * BEFORE the module record itself is created in the module collection.\n */\nexport function generateModuleId() {\n const timestampHex = Math.floor(Date.now() / 1000)\n .toString(16)\n .padStart(8, '0')\n .slice(0, 8);\n const randomBytes = new Uint8Array(8);\n if (typeof crypto !== 'undefined' && typeof crypto.getRandomValues === 'function') {\n crypto.getRandomValues(randomBytes);\n } else {\n for (let i = 0; i < randomBytes.length; i += 1) {\n randomBytes[i] = Math.floor(Math.random() * 256);\n }\n }\n const randomHex = Array.from(randomBytes, (b) => b.toString(16).padStart(2, '0')).join('');\n return `${timestampHex}${randomHex}`;\n}\n\n/**\n * extractDocumentIds — extracts created document IDs from the `/documents/upload` response.\n */\nexport function extractDocumentIds(uploadResponse) {\n const list = Array.isArray(uploadResponse)\n ? uploadResponse\n : Array.isArray(uploadResponse?.data)\n ? uploadResponse.data\n : [];\n return list\n .map((doc) => String(doc?.id ?? doc?._id ?? '').trim())\n .filter(Boolean);\n}\n\n/**\n * rollbackModuleDocuments — compensating rollback: deletes documents created in the\n * `documents` collection if the subsequent module creation call fails.\n */\nexport async function rollbackModuleDocuments(documentIds = []) {\n const ids = Array.from(new Set((documentIds || []).map((id) => String(id || '').trim()).filter(Boolean)));\n if (ids.length === 0) return;\n\n await Promise.allSettled(\n ids.map((id) => deleteModuleDocument(id)),\n );\n}\n","// Compare exact values, so even a one-character change restores every configured rule.\nexport const isSavedValue = (field, value) => field?._savedValueValidation === true\n && Object.is(value, field.value);\n\n// A rule that always passes. It must carry a `validator`: a bare `{}` has no\n// `type`, so async-validator falls back to type \"string\" and rejects any saved\n// boolean/number with \"is not a valid undefined\" (e.g. an untouched checkbox).\nexport const NOOP_RULE = Object.freeze({ validator: () => Promise.resolve() });\n\nexport function gateSavedValueRules(rules, field, name) {\n if (!field?._savedValueValidation) return rules;\n return rules.map(rule => form => isSavedValue(field, form.getFieldValue(name))\n ? NOOP_RULE : (typeof rule === 'function' ? rule(form) : rule));\n}\n","import { isSavedValue } from './savedValueValidation';\nimport DOMPurify from 'dompurify';\n\nconst RICH_TEXT_TAGS = [\n 'p', 'br', 'strong', 'b', 'em', 'i', 'u', 's', 'ul', 'ol', 'li',\n 'blockquote', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'a', 'code', 'pre',\n];\nconst RICH_TEXT_ATTRS = ['href', 'title', 'target', 'rel'];\nconst INVISIBLE_RE = /[\\u200B-\\u200D\\u2060\\uFEFF]/g;\n// Security normalization intentionally targets ASCII control characters.\n// eslint-disable-next-line no-control-regex\nconst CONTROL_RE = /[\\u0000-\\u0008\\u000B\\u000C\\u000E-\\u001F\\u007F]/g;\nconst NAME_RE = /^[\\p{L}\\p{M}\\p{N} .'-]+$/u;\nconst PHONE_RE = /^\\+?[0-9 ()-]+$/;\nconst NUMBER_RE = /^-?(?:\\d+|\\d*\\.\\d+)$/;\n\n// The ONE definition of hostile input on the client, kept deliberately in step\n// with utils/inputsecurity/patterns.go on the server. When the two disagree the\n// user gets the worst possible experience: a form that refuses what the API\n// would have accepted, or accepts what the API then rejects.\n//\n// Split by whether the text could EVER be legitimate prose. This is an ATS:\n// job descriptions for database and DevOps roles contain \"DROP TABLE\" and\n// \"&&\", and refusing them blocks real work without closing any sink — React\n// escapes on render, and the server sends BSON values, never query strings.\n// Markup and script are refused, because those are only ever an attack.\n//\n// `plainOnly` marks a rule that applies to plain fields but not to a rich-text\n// editor, where markup is the entire point. This replaces an earlier\n// `slice(0, 3)` that depended on the ARRAY ORDER — reordering the list silently\n// changed what rich text allowed.\nconst REJECT_PATTERNS = [\n { re: /<\\s*\\/?\\s*(?:script|iframe|object|embed|svg|img|form|input|style|link|meta|base|applet|frame|frameset)\\b/i, message: 'HTML/script content is not allowed' },\n { re: /\\b(?:javascript|vbscript)\\s*:|\\bdata\\s*:\\s*text\\/html/i, message: 'Unsafe URL protocol is not allowed' },\n { re: /\\bon[a-z]+\\s*=/i, message: 'HTML event handlers are not allowed' },\n { re: /[\"']?\\$(?:where|gt|gte|lt|lte|ne|nin|regex|or|and|not|nor|expr|function|jsonSchema|accumulator)\\b/i, message: 'MongoDB operators are not allowed in input values' },\n // Refused rather than tolerated: dangerous anywhere a value becomes a\n // filename, and rare in recruiter prose. Narrower than it once was — the old\n // pattern also matched a bare \"%2f\", i.e. any URL-encoded slash.\n { re: /(?:\\.\\.[/\\\\])|(?:%2e%2e|%5c)/i, message: 'Path traversal is not allowed' },\n // Any other HTML-looking tag (\"<b>\", \"<div class=x>\", \"</span>\"). Plain\n // fields never legitimately contain markup; a text-editor field does, and is\n // sanitised through DOMPurify instead.\n { re: /<\\/?[a-zA-Z][a-zA-Z0-9]*(?:\\s[^<>]*)?>/, message: 'HTML tags are not allowed', plainOnly: true },\n];\n\n// Permitted as typed text. Kept compiled rather than deleted so the policy is\n// visible in one place, and so switching to strict-everywhere is a matter of\n// concatenating this list onto REJECT_PATTERNS.\nexport const ALLOWED_TECHNICAL_PATTERNS = [\n { re: /\\b(?:union\\s+(?:all\\s+)?select|drop\\s+table|delete\\s+from|insert\\s+into|xp_cmdshell)\\b/i, message: 'database command patterns' },\n { re: /(?:['\"]\\s*)?\\b(?:or|and)\\s+\\d+\\s*=\\s*\\d+/i, message: 'injection patterns' },\n { re: /&&|\\|\\||\\$\\(|\\$\\{|`|\\b(?:rm\\s+-rf|cat\\s+\\/etc\\/|whoami\\b)/i, message: 'command execution patterns' },\n];\n\nfunction decodeHtmlEntities(value) {\n if (typeof document === 'undefined') return value;\n const textarea = document.createElement('textarea');\n textarea.innerHTML = value;\n return textarea.value;\n}\n\nexport function canonicalizeForSecurityScan(value) {\n let result = String(value ?? '');\n for (let i = 0; i < 2; i += 1) {\n try {\n const decoded = decodeURIComponent(result);\n if (decoded === result) break;\n result = decoded;\n } catch { break; }\n }\n result = decodeHtmlEntities(result)\n .replace(/\\\\x([0-9a-f]{2})/gi, (_, hex) => String.fromCharCode(Number.parseInt(hex, 16)))\n .replace(/\\\\u([0-9a-f]{4})/gi, (_, hex) => String.fromCharCode(Number.parseInt(hex, 16)));\n return result.normalize('NFC');\n}\n\nexport function sanitizeRichText(value) {\n return DOMPurify.sanitize(String(value ?? ''), {\n ALLOWED_TAGS: RICH_TEXT_TAGS,\n ALLOWED_ATTR: RICH_TEXT_ATTRS,\n ALLOW_DATA_ATTR: false,\n FORBID_TAGS: ['script', 'style', 'iframe', 'object', 'embed', 'svg', 'img', 'form', 'input'],\n FORBID_ATTR: ['style', 'src', 'srcset'],\n });\n}\n\nfunction validationMax(field) {\n const rule = (field.validations ?? []).find((item) => item?.type === 'max');\n const configured = Number(field.validator?.maxLength ?? rule?.value ?? field.maxLength);\n if (Number.isFinite(configured) && configured > 0) return configured;\n if (field.type === 'email' || field.formatter === 'email') return 255;\n if (field.formatter === 'phone' || field.formatter === 'digits') return 32;\n if (field.formatter === 'name') return 100;\n if (field.type === 'text-editor') return 50000;\n if (field.type === 'textarea') return 5000;\n return 5000;\n}\n\nfunction isMultiline(field) {\n return field.type === 'textarea' || field.type === 'text-editor';\n}\n\nexport function normalizeSecureString(value, field = {}) {\n if (typeof value !== 'string') return value;\n if (field.type === 'text-editor') return sanitizeRichText(value.normalize('NFC'));\n\n let normalized = value.normalize('NFC')\n .replace(INVISIBLE_RE, '')\n .replace(/\\u00A0/g, ' ')\n .replace(CONTROL_RE, '');\n if (isMultiline(field)) {\n normalized = normalized.replace(/\\r\\n?/g, '\\n').replace(/[ \\t]{2,}/g, ' ').trim();\n } else {\n normalized = normalized.replace(/\\s+/g, ' ').trim();\n }\n return normalized;\n}\n\nexport function validateSecureString(value, field = {}) {\n if (isSavedValue(field, value)) field = {};\n if (typeof value !== 'string' || value === '') return null;\n const label = field.label || field.field || 'Field';\n const canonical = canonicalizeForSecurityScan(value);\n\n if (canonical.includes('\\0') || canonical.includes('\\u0000')) return `${label} contains a null byte`;\n const richText = field.type === 'text-editor';\n const attack = REJECT_PATTERNS.find(\n ({ re, plainOnly }) => (!plainOnly || !richText) && re.test(canonical),\n );\n if (attack) return `${label}: ${attack.message}`;\n\n const normalized = normalizeSecureString(value, field);\n if ([...normalized].length > validationMax(field)) return `${label} is too long`;\n if (field.formatter === 'name' && normalized && !NAME_RE.test(normalized)) {\n return `${label} allows only letters, numbers, spaces, apostrophes, hyphens and periods`;\n }\n if ((field.formatter === 'phone' || field.formatter === 'digits') && normalized && !PHONE_RE.test(normalized)) {\n return `${label} contains invalid phone characters`;\n }\n if (field.type === 'number' && normalized && !NUMBER_RE.test(normalized)) {\n return `${label} must contain only a valid number`;\n }\n if ((field.type === 'url' || field.formatter === 'url') && normalized && !/^https?:\\/\\//i.test(normalized)) {\n return `${label} must use http:// or https://`;\n }\n return null;\n}\n\nexport function securityValidationRule(field) {\n return {\n validator: (_, value) => {\n const values = Array.isArray(value) ? value : [value];\n const error = values.map((item) => validateSecureString(item, field)).find(Boolean);\n return error ? Promise.reject(new Error(error)) : Promise.resolve();\n },\n };\n}\n\nfunction policyMap(groups = []) {\n const policies = new Map();\n groups.forEach((group) => {\n (group.fields ?? []).forEach((field) => {\n if (field.type === 'file') return;\n const destination = field.payloadKey || field.field;\n if (!destination) return;\n const path = group.addRow ? `${group.payloadKey || group.name}[].${destination}` : destination;\n policies.set(path, field);\n });\n });\n return policies;\n}\n\nexport function securePayload(payload, groups = []) {\n const policies = policyMap(groups);\n const walk = (node, path = '') => {\n if (typeof node === 'string') {\n const field = policies.get(path) ?? {};\n const error = validateSecureString(node, field);\n if (error) throw new Error(error);\n return normalizeSecureString(node, field);\n }\n if (Array.isArray(node)) return node.map((item) => walk(item, `${path}[]`));\n if (node && typeof node === 'object') {\n return Object.fromEntries(Object.entries(node).map(([key, value]) => {\n if (key.startsWith('$') || key.includes('.') || key.includes('\\0')) {\n throw new Error(`Unsafe object key: ${key}`);\n }\n const childPath = path ? `${path}.${key}` : key;\n return [key, walk(value, childPath)];\n }));\n }\n return node;\n };\n return walk(payload);\n}\n","// ─────────────────────────────────────────────────────────────────────────\n// phoneDisplay — a contact number as the RECORD stores it, not as the tenant's\n// default happens to be set.\n//\n// The detail view formats every phone through one admin-configured mask\n// (detailDefaults.phoneFormat, e.g. \"3-3-4\"). That part is right and stays.\n// What was wrong is the country code: it came from a single global default, so\n// a candidate who stored +91 was displayed as \"+1 999-878-3413\" — a number that\n// does not exist, printed with total confidence.\n//\n// Resolution order, most specific first:\n// 1. a code embedded in the value itself (\"+91 9998783413\") — unambiguous\n// 2. `renderOptions.countryCodeField` — the Detail Groups admin naming the\n// sibling key that holds this record's code\n// 3. the conventional siblings (<field>CountryCode, countryCode,\n// phoneCountryCode, mobileCountryCode, …)\n// 4. the global default — ONLY when the record carries nothing, and it ships\n// empty so a missing code renders as no code instead of a wrong one.\n//\n// Nothing here knows a module or a field name: (2) is config and (3) is a\n// naming convention applied to whatever key the field itself has.\n// ─────────────────────────────────────────────────────────────────────────\n\nimport { formatPhone, getPhoneCountryCode } from '../../services/detailDefaults';\n\nconst isEmpty = (v) => v === undefined || v === null || v === '';\n\n// getPath — dotted-path read, so a configured countryCodeField may point at a\n// nested container key (\"contact.countryCode\") as well as a flat one.\nfunction getPath(source, path) {\n return String(path ?? '')\n .split('.')\n .filter(Boolean)\n .reduce((current, key) => (current == null ? undefined : current[key]), source);\n}\n\n/**\n * normalizeDialCode — \"+91\" | \"91\" | 91 → \"+91\". Anything that is not a dial\n * code (a country NAME, an empty string, a stray label) resolves to '' so it is\n * never printed in front of a number.\n */\nexport function normalizeDialCode(value) {\n const raw = String(value ?? '').trim().replace(/[\\s()-]/g, '');\n if (!raw) return '';\n const digits = raw.replace(/^\\+/, '');\n return /^\\d{1,4}$/.test(digits) ? `+${digits}` : '';\n}\n\n/**\n * countryCodeKeys — the sibling keys to probe for a phone field's own code.\n * The field-derived candidates come first (\"mobileNumberCountryCode\",\n * \"mobileCountryCode\" for a `mobileNumber` field) so a record holding several\n * numbers keeps each one's code attached to the right number.\n */\nexport function countryCodeKeys(field) {\n const key = String(field?.field ?? '').trim();\n const base = key.replace(/(number|no|phone|mobile|contact)$/i, '');\n return [\n ...(key ? [`${key}CountryCode`, `${key}Code`] : []),\n ...(base && base !== key ? [`${base}CountryCode`] : []),\n 'countryCode',\n 'phoneCountryCode',\n 'mobileCountryCode',\n 'contactCountryCode',\n 'dialCode',\n 'isdCode',\n ];\n}\n\n/**\n * resolveCountryCode — this record's dial code for this field.\n * `record` is the flattened value map of the record being displayed; pass the\n * addRow ROW when formatting a repeatable row, so a row's own code wins.\n */\nexport function resolveCountryCode(field, record, fallback = '') {\n const configured = field?.renderOptions?.countryCodeField ?? field?.countryCodeField;\n const keys = configured ? [configured, ...countryCodeKeys(field)] : countryCodeKeys(field);\n for (const key of keys) {\n const code = normalizeDialCode(getPath(record, key));\n if (code) return code;\n }\n return normalizeDialCode(fallback);\n}\n\n/**\n * splitDialCode — separate a code the value already carries from the number.\n */\nexport function splitDialCode(raw) {\n const str = String(raw ?? '').trim();\n const match = str.match(/^(\\+\\d{1,4})[\\s-]*(.*)$/);\n return match ? { code: match[1], rest: match[2] } : { code: '', rest: str };\n}\n\n/**\n * displayPhone — the finished, maskable display string.\n * `countryCode` is whatever resolveCountryCode produced; a code embedded in the\n * value still wins, because that is the record speaking for itself.\n */\nexport function displayPhone(raw, countryCode = '') {\n if (isEmpty(raw)) return '';\n const { code, rest } = splitDialCode(raw);\n const cc = code || normalizeDialCode(countryCode);\n const formatted = formatPhone(rest) || rest;\n return `${cc ? `${cc} ` : ''}${formatted}`.trim();\n}\n\n/**\n * displayPhoneForField — the one call sites use: resolve the code off the\n * record, then format. Falls back to the global default only as a last resort.\n */\nexport function displayPhoneForField(field, value, record) {\n const code = resolveCountryCode(field, record, getPhoneCountryCode());\n return displayPhone(value, code);\n}\n","// renderConfig — non-component shared module for the detail-view render engine.\n// Holds the Admin-facing option lists and the file/document resolution helpers,\n// kept out of the .jsx engine so React Fast Refresh stays happy and so other\n// modules (DocumentLink, the admin screen) can reuse them.\n\nimport { getDefaults } from '../../services/detailDefaults';\n\n// ── Admin option lists ───────────────────────────────────────────────────────\nexport const RENDER_TYPES = [\n { value: 'auto', label: 'Default (auto)' },\n { value: 'text', label: 'Text' },\n { value: 'multiline', label: 'Multiline Text' },\n { value: 'tag', label: 'Tag' },\n { value: 'tags', label: 'Multi Tag (Skills)' },\n { value: 'badge', label: 'Badge' },\n { value: 'chip', label: 'Chip' },\n { value: 'document', label: 'Document' },\n { value: 'link', label: 'Link' },\n { value: 'email', label: 'Email' },\n { value: 'phone', label: 'Phone' },\n { value: 'date', label: 'Date' },\n { value: 'currency', label: 'Currency' },\n { value: 'budget', label: 'Budget' },\n { value: 'html', label: 'HTML' },\n];\n\nexport const DOCUMENT_MODES = [\n { value: 'preview', label: 'Preview (viewer)' },\n { value: 'download', label: 'Download button' },\n { value: 'link', label: 'Link (filename)' },\n { value: 'tag', label: 'Tag' },\n { value: 'text', label: 'Text (filename)' },\n];\n\nexport const TEXT_TRANSFORMS = [\n { value: 'none', label: 'None' },\n { value: 'upper', label: 'UPPERCASE' },\n { value: 'lower', label: 'lowercase' },\n { value: 'title', label: 'Title Case' },\n];\n\n// ── file / document resolution ───────────────────────────────────────────────\nconst LOC_EXACT = ['location', 'path', 'url', 'key'];\nconst LOC_SUFFIX = ['location', 'filepath', 'path', 'url', 'key'];\nconst NAME_SUFFIX = ['uploadedfilename', 'uploadname', 'originalname', 'displayname', 'documentname', 'filename'];\nconst NAME_LAST = ['name'];\nconst lc = (s) => String(s).toLowerCase();\nconst isEmpty = (v) => v === undefined || v === null || v === '';\n\nfunction pickExact(obj, keys) {\n for (const key of keys) {\n const v = obj[key];\n if (typeof v === 'string' && v) return v;\n }\n return '';\n}\n\nfunction pickSuffix(obj, suffixes) {\n for (const suffix of suffixes) {\n for (const [key, val] of Object.entries(obj)) {\n if (typeof val === 'string' && val && lc(key).endsWith(suffix)) return val;\n }\n }\n return '';\n}\n\nexport function fileNameFromPath(path) {\n if (!path) return '';\n const clean = String(path).split('?')[0].split('#')[0];\n return decodeURIComponent(clean.split('/').pop() || '');\n}\n\n/**\n * buildFileUrl — resolves a file value to a directly-openable URL, or ''.\n *\n * IT NO LONGER BUILDS AN S3 URL FROM A STORED OBJECT KEY.\n *\n * It used to return `s3BaseUrl + key`. The bucket is PRIVATE, so that URL\n * carries no signature and S3 answers 403 — every resume in the product failed\n * to open with exactly that symptom. The key is not a URL; it is an identifier\n * that only the backend is allowed to resolve, because only the backend can\n * check that the caller is permitted to read that record.\n *\n * An absolute http(s) URL is still returned as-is — some fields genuinely hold\n * a public link (a company website, an externally hosted JD). But a bare\n * object key now returns '', which makes callers fall through to the\n * authenticated resolver (services/documentContentApi.js) instead of silently\n * producing a URL that 403s.\n *\n * Returning '' rather than throwing is deliberate: every caller already treats\n * '' as \"not directly linkable\", so this degrades into the resolver path\n * instead of turning a broken preview into a crashed page.\n */\nexport function buildFileUrl(location) {\n if (!location) return '';\n const loc = String(location);\n if (/^https?:\\/\\//i.test(loc)) return loc;\n return '';\n}\n\n/**\n * isStorageKey — true when a value is a stored object key rather than a URL,\n * i.e. it must be fetched through the authenticated document endpoint.\n */\nexport function isStorageKey(location) {\n const loc = String(location ?? '').trim();\n if (!loc) return false;\n if (/^https?:\\/\\//i.test(loc)) return false;\n if (loc.startsWith('blob:') || loc.startsWith('data:')) return false;\n return loc.includes('/');\n}\n\nexport function locationOf(doc) {\n if (typeof doc === 'string') return doc.includes('/') ? doc : '';\n if (!doc || typeof doc !== 'object') return '';\n return pickExact(doc, LOC_EXACT) || pickSuffix(doc, LOC_SUFFIX);\n}\n\nexport function docDisplayName(doc) {\n if (!doc) return 'Document';\n if (typeof doc === 'string') return fileNameFromPath(doc) || doc;\n if (typeof doc !== 'object') return 'Document';\n const order = getDefaults().documentNameOrder ?? [];\n return (\n pickExact(doc, order) ||\n pickSuffix(doc, NAME_SUFFIX) ||\n fileNameFromPath(locationOf(doc)) ||\n pickSuffix(doc, NAME_LAST) ||\n 'Document'\n );\n}\n\n// extractDocuments flattens any file-field value (array | object | string) into\n// a list of { location, name, url }.\nexport function extractDocuments(value) {\n if (isEmpty(value)) return [];\n const items = Array.isArray(value) ? value : [value];\n const out = [];\n for (const item of items) {\n if (isEmpty(item)) continue;\n if (typeof item === 'string') {\n const location = item.includes('/') ? item : '';\n out.push({\n location,\n name: fileNameFromPath(item) || item,\n url: buildFileUrl(location),\n needsAuthFetch: isStorageKey(location),\n });\n } else if (typeof item === 'object') {\n const location = locationOf(item);\n // A doc from the central `documents` collection already carries a 24h\n // presigned download URL (fileUrl) — prefer it over the raw location.\n const presigned = item.fileUrl || item.downloadUrl || item.signedUrl || '';\n out.push({\n location,\n name: docDisplayName(item),\n url: presigned || buildFileUrl(location),\n documentId: item.id || item._id || item.documentId || '',\n // `needsAuthFetch` marks a document whose bytes must come from the\n // authenticated backend because all we hold is a private-bucket object\n // key. Before this existed, callers built s3BaseUrl + key and got a\n // 403 — the key was indistinguishable from a usable URL once\n // buildFileUrl had concatenated it.\n needsAuthFetch: !presigned && isStorageKey(location),\n });\n }\n }\n return out;\n}\n","function comparisonValues(value) {\n if (Array.isArray(value)) return value.map((item) => String(item ?? '').trim());\n return String(value ?? '').split(',').map((item) => item.trim());\n}\n\n// Matches the same generic operators supported by showIf. Keeping this helper\n// independent of React makes conditional labels usable in Add/Edit forms and\n// straightforward to test without module- or field-specific code.\nexport function conditionMatches(condition, value) {\n if (!condition?.field) return false;\n switch (condition.operator ?? 'eq') {\n case 'eq': return String(value ?? '') === String(condition.value ?? '');\n case 'neq': return String(value ?? '') !== String(condition.value ?? '');\n case 'truthy': return value !== undefined && value !== null && value !== '' && value !== false;\n case 'falsy': return value === undefined || value === null || value === '' || value === false;\n case 'notEmpty': return Array.isArray(value) ? value.length > 0 : Boolean(value);\n case 'in': return comparisonValues(condition.value).includes(String(value ?? ''));\n case 'notIn': return !comparisonValues(condition.value).includes(String(value ?? ''));\n default: return false;\n }\n}\n\nexport function configuredFieldLabel(field, watchedValue, combined = false) {\n const fallback = combined\n ? (field?.combineLabel ?? field?.label)\n : field?.label;\n const rule = field?.labelWhen;\n return conditionMatches(rule, watchedValue) && rule?.label\n ? rule.label\n : fallback;\n}\n\n// Flatten a showIf into its leaf conditions: the top-level {field,operator,value}\n// plus any \"add more\" entries in conditions[]. Mirrors how the forms read it.\nexport function showIfConditions(showIf) {\n if (!showIf) return [];\n const leaf = showIf.field ? [showIf] : [];\n return [...leaf, ...(showIf.conditions ?? []).filter((c) => c?.field)];\n}\n\n// Evaluate a showIf against an arbitrary value source. readValue(fieldKey) lets\n// the caller decide where values come from — live form state in the forms, or a\n// saved record in the detail view — so one condition definition drives both.\nexport function evaluateShowIfWith(showIf, readValue) {\n const conditions = showIfConditions(showIf);\n if (!conditions.length) return true;\n const results = conditions.map((c) => conditionMatches(c, readValue(c.field)));\n return showIf.logic === 'or' ? results.some(Boolean) : results.every(Boolean);\n}\n\n// colWhen — conditionally override a field's grid column span, so one field can\n// shrink to make room for a sibling that a showIf has just revealed (e.g. Work\n// Authorization narrows when its expiry date appears). Config is a rule, or a\n// list of rules, each {field, operator, value, col}; the first match wins.\n// Display only — the field key, payload mapping and validation are untouched.\nexport function colWhenRules(field) {\n const raw = field?.colWhen;\n if (!raw) return [];\n return (Array.isArray(raw) ? raw : [raw])\n .filter((rule) => rule?.field && Number(rule?.col) > 0);\n}\n\n// readValue(rule) resolves the watched value for one rule — the caller owns path\n// resolution so a rule can reference a sibling in the same addRow row or a\n// top-level field, exactly like showIf.\nexport function resolveColSpan(field, fallbackSpan, readValue) {\n for (const rule of colWhenRules(field)) {\n if (conditionMatches(rule, readValue(rule))) return Number(rule.col);\n }\n return fallbackSpan;\n}\n\nexport function conditionFieldPath(condition, siblingPrefix) {\n if (!condition?.field) return ['__noop_conditional_label__'];\n return siblingPrefix != null\n ? [...(Array.isArray(siblingPrefix) ? siblingPrefix : [siblingPrefix]), condition.field]\n : [condition.field];\n}\n"],"mappings":";;;;;;;AAIA,IAAM,IAAoB,uBAEpB,IAAuB;CAC3B;EAAE,KAAK;EAAe,WAAW;CAAc;CAC/C;EAAE,KAAK;EAAe,WAAW;CAAc;CAC/C;EAAE,KAA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phi905.js","names":[],"sources":["../src/services/adminApi.js","../src/components/detailViewMode.js","../src/services/detailDefaults.js","../src/services/timezone.js","../src/utils/modulePath.js","../src/services/documentApi.js","../src/components/form/savedValueValidation.js","../src/components/form/inputSecurity.js","../src/components/detail/phoneDisplay.js","../src/components/detail/renderConfig.js","../src/components/form/conditionalFieldLabel.js"],"sourcesContent":["import { fetchJsonWithAuth } from './authApi';\nimport { invalidateFormGroupsCache } from './formGroupsCache';\nimport { AUTH_URL, SUBMISSIONS_URL } from './apiConfig';\n\nconst FIELD_CONFIG_PATH = '/admin/field-config';\n\nconst CUSTOMIZABLE_MODULES = [\n { key: 'clients', apiModule: 'clients' },\n { key: 'job', apiModule: 'jobs' },\n { key: 'candidate', apiModule: 'candidates' },\n { key: 'submissions', apiModule: 'submissions' },\n { key: 'onboarding', apiModule: 'onboarding' },\n { key: 'billing', apiModule: 'billing' },\n { key: 'payroll', apiModule: 'payroll' },\n];\n\n// ── Shared Utilities ──────────────────────────────────────────────────────────\n\nfunction firstArray(...values) {\n return values.find(Array.isArray) ?? [];\n}\n\nfunction firstValue(record, keys, fallback) {\n return keys.map((k) => record?.[k]).find((v) => v !== undefined && v !== null && v !== '') ?? fallback;\n}\n\nfunction normalizeTotal(payload, items) {\n return (\n payload?.total ?? payload?.totalCount ?? payload?.count ??\n payload?.recordsTotal ?? payload?.meta?.total ?? payload?.pagination?.total ?? items.length\n );\n}\n\nfunction normalizeModuleField(field, index) {\n const fieldName = firstValue(field, ['label', 'Label', 'fieldName', 'field_name', 'name', 'fieldLabel', 'value'], `Field ${index + 1}`);\n const fieldKey = firstValue(field, ['field', 'Field', 'fieldKey', 'field_key', 'key', 'value', 'fieldName', 'name'], fieldName);\n const showValue = firstValue(field, ['isVisible', 'is_visible', 'visible', 'show', 'is_show', 'isShow', 'enabled'], true);\n const mandatoryValue = firstValue(field, ['ismandatory', 'isMandatory', 'is_mandatory', 'mandatory', 'required', 'req'], false);\n const orderValue = firstValue(field, ['order', 'Order', 'sortOrder', 'position'], index);\n\n return {\n ...field,\n fieldKey,\n fieldName,\n type: firstValue(field, ['type', 'Type'], 'text'),\n isVisible: typeof showValue === 'string'\n ? !['false', '0', 'hide', 'hidden', 'no'].includes(showValue.toLowerCase())\n : Boolean(showValue),\n ismandatory: typeof mandatoryValue === 'string'\n ? ['true', '1', 'yes', 'required'].includes(mandatoryValue.toLowerCase())\n : Boolean(mandatoryValue),\n order: typeof orderValue === 'number' ? orderValue : index,\n isLink: Boolean(field.isLink),\n linkTemplate: field.linkTemplate ?? '',\n linkType: field.linkType ?? 'internal',\n linkTarget: field.linkTarget ?? '_self',\n action: field.action ?? 'navigate',\n allowedTabs: Array.isArray(field.allowedTabs) ? field.allowedTabs : [],\n secondaryField: field.secondaryField ?? '',\n secondaryLabel: field.secondaryLabel ?? '',\n secondaryFields: Array.isArray(field.secondaryFields) ? field.secondaryFields : [],\n secondarySeparator: field.secondarySeparator ?? '',\n lookup: field.lookup\n ? { ...field.lookup, projectFields: Array.isArray(field.lookup.projectFields) ? field.lookup.projectFields : [] }\n : null,\n derived: field.derived ?? null,\n computed: field.computed\n ? { ...field.computed, operands: Array.isArray(field.computed.operands) ? field.computed.operands : [] }\n : null,\n actionButtons: Array.isArray(field.actionButtons) ? field.actionButtons : [],\n displayRules: Array.isArray(field.displayRules) ? field.displayRules : [],\n renderType: field.renderType ?? '',\n renderConfig: field.renderConfig\n ? {\n ...field.renderConfig,\n treatZeroAsEmpty: Boolean(field.renderConfig.treatZeroAsEmpty),\n cleanEmptyTemplateSeparators: Boolean(field.renderConfig.cleanEmptyTemplateSeparators),\n }\n : null,\n valueStyles: Array.isArray(field.valueStyles) ? field.valueStyles : [],\n commonStyle: field.commonStyle ?? null,\n displayTemplate: field.displayTemplate ?? '',\n defaultValue: field.defaultValue ?? '',\n defaultValueField: field.defaultValueField ?? '',\n dataSource: field.dataSource ?? 'module',\n groupName: field.groupName ?? '',\n filterGroupFields: Array.isArray(field.filterGroupFields) ? field.filterGroupFields : [],\n filterGroupSeparator: field.filterGroupSeparator ?? ' ',\n filterArrayLabelField: field.filterArrayLabelField ?? '',\n filterArrayValueField: field.filterArrayValueField ?? '',\n };\n}\n\nfunction normalizeCustomizableModule(module) {\n if (typeof module === 'string') {\n return { key: module, apiModule: module };\n }\n\n const key = firstValue(\n module,\n ['key', 'moduleKey', 'value', 'module', 'apiModule', 'name', 'modulename', 'menuName'],\n ''\n );\n if (!key) return null;\n\n return {\n key,\n apiModule: firstValue(\n module,\n ['apiModule', 'api_module', 'module', 'value', 'key', 'name', 'modulename', 'menuName'],\n key\n ),\n };\n}\n\nfunction normalizeCustomizableModules(modules = CUSTOMIZABLE_MODULES) {\n const source = Array.isArray(modules) && modules.length ? modules : CUSTOMIZABLE_MODULES;\n const seen = new Set();\n return source\n .map(normalizeCustomizableModule)\n .filter(Boolean)\n .filter((module) => {\n if (seen.has(module.key)) return false;\n seen.add(module.key);\n return true;\n });\n}\n\n// ── Modules ───────────────────────────────────────────────────────────────────\n\nconst MODULES_PATH = '/admin/modules';\n\nexport async function getModules() {\n const json = await fetchJsonWithAuth(AUTH_URL, MODULES_PATH);\n const payload = json?.data;\n if (Array.isArray(payload)) return payload;\n if (Array.isArray(json)) return json;\n return [];\n}\n\n// createModule/updateModule let Admin define workflow modules (e.g. \"Source\n// Candidates\") that extend an existing module via baseModule, inheriting its\n// forms/columns/tabs/filters/actions wherever the new module hasn't\n// configured its own — see the backend's ModuleLookupChain.\nexport async function createModule({ key, label, collectionName, baseModule = '', order = 0 }) {\n return fetchJsonWithAuth(AUTH_URL, MODULES_PATH, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ key, label, collectionName, baseModule, order }),\n });\n}\n\nexport async function updateModule(key, { label, collectionName, baseModule = '', order = 0, isActive = true }) {\n return fetchJsonWithAuth(AUTH_URL, `${MODULES_PATH}/${encodeURIComponent(key)}`, {\n method: 'PUT',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ label, collectionName, baseModule, order, isActive }),\n });\n}\n\n// getModuleAutomations/saveModuleAutomations edit a module's Gateway +\n// Strategies — the Admin \"Automations\" screen. This is the config-driven\n// replacement for logic legacy services used to hardcode in Go (reference-id\n// generation, duplicate checks, cross-module field snapshots, reporting-chain\n// hierarchy expansion, board updates, notifications, cache invalidation).\n// Separate endpoint from updateModule() above, so saving automations can\n// never touch label/forms/columns, and vice versa.\nexport async function getModuleAutomations(key) {\n const json = await fetchJsonWithAuth(AUTH_URL, `${MODULES_PATH}/${encodeURIComponent(key)}/automations`);\n const data = json?.data ?? json ?? {};\n return { gateway: data.gateway ?? null, strategies: data.strategies ?? null };\n}\n\n// Platform metadata (workflows / resolvers / state-machines / applications) —\n// the event-driven behavior layer. kind ∈ 'workflows' | 'resolvers' |\n// 'state-machines' | 'applications'. Docs are keyed by their \"key\" field.\nexport async function listPlatformDocs(kind) {\n const json = await fetchJsonWithAuth(AUTH_URL, `/admin/platform/${kind}`);\n const data = json?.data ?? json;\n return Array.isArray(data) ? data : [];\n}\n\nexport async function savePlatformDoc(kind, doc) {\n return fetchJsonWithAuth(AUTH_URL, `/admin/platform/${kind}`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(doc),\n });\n}\n\nexport async function deletePlatformDoc(kind, key) {\n return fetchJsonWithAuth(AUTH_URL, `/admin/platform/${kind}/${encodeURIComponent(key)}`, {\n method: 'DELETE',\n });\n}\n\nexport async function saveModuleAutomations(key, { gateway, strategies }) {\n return fetchJsonWithAuth(AUTH_URL, `${MODULES_PATH}/${encodeURIComponent(key)}/automations`, {\n method: 'PUT',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ gateway, strategies }),\n });\n}\n\n// getAvailableModules() is the single source of truth for \"which modules can\n// be picked in an Admin configuration screen\" (Form Groups, Detail Groups,\n// Row Actions, Module Action Rules, Templates, Role Configuration). It's\n// driven by the curated Menus list (an admin explicitly adds/removes/disables\n// entries there) rather than the `modules` collection, which is really the\n// CRUD/gateway registry and accumulates every module ever wired for storage\n// (including disabled/legacy ones no admin actively curates).\n//\n// Falls back to getModules() when Menus has nothing configured yet, so a\n// project that hasn't set up Menus keeps working exactly as before.\nexport async function getAvailableModules() {\n let menus = [];\n try {\n menus = await getMenuModules();\n } catch {\n menus = [];\n }\n const active = (Array.isArray(menus) ? menus : []).filter((m) => (\n m?.isDeleted !== true\n && String(m?.status ?? 'active').toLowerCase() !== 'inactive'\n && String(m?.status ?? 'active').toLowerCase() !== 'disabled'\n ));\n if (active.length > 0) return active;\n return getModules();\n}\n\n// getModuleCollectionMap resolves module key → the Mongo collection that module\n// is stored in, straight from the module registry (`modules`, the CRUD/gateway\n// registry that owns `collectionName`). It exists so an Admin screen can DISPLAY\n// the collection a configuration will act on without ever asking the admin to\n// type a collection name — the collection is module configuration, and the\n// server resolves it authoritatively on every request regardless of what this\n// map says. If the registry is unreachable the map is simply empty and callers\n// fall back to \"resolved on the server\".\n//\n// Module names are matched loosely on purpose: config is stored sometimes under\n// the singular key and sometimes the plural one (the backend's own\n// ModuleAliasVariants exists for the same reason), so both spellings are\n// indexed here. Real registry entries always win over a generated alias, so an\n// alias can never shadow a module that genuinely exists.\nexport async function getModuleCollectionMap() {\n let modules;\n try {\n modules = await getModules();\n } catch {\n return {};\n }\n const map = {};\n const put = (key, collection, exact) => {\n const k = String(key ?? '').trim().toLowerCase();\n if (!k || !collection) return;\n if (exact || map[k] === undefined) map[k] = collection;\n };\n for (const m of Array.isArray(modules) ? modules : []) {\n const collection = String(m?.collectionName ?? '').trim();\n if (!collection) continue;\n put(m?.key, collection, true);\n }\n // Second pass so aliases never overwrite a registered key from pass one.\n for (const m of Array.isArray(modules) ? modules : []) {\n const collection = String(m?.collectionName ?? '').trim();\n const key = String(m?.key ?? '').trim().toLowerCase();\n if (!collection || !key) continue;\n if (key.endsWith('s')) put(key.slice(0, -1), collection, false);\n else put(`${key}s`, collection, false);\n }\n return map;\n}\n\n// ── Admin Form Groups ─────────────────────────────────────────────────────────\n\nconst FORM_GROUPS_PATH = '/admin/form-groups';\nconst CONFIG_DEFAULTS_PATH = '/admin/config-defaults';\n\nexport async function exportFormGroupSeed(module, scope = {}) {\n const json = await fetchJsonWithAuth(AUTH_URL, `/admin/form-group-seeds/export${formGroupScopeQuery({ ...scope, module })}`);\n return json?.data ?? json;\n}\n\nexport async function previewFormGroupSeed(module, scope, seed, mode) {\n const json = await fetchJsonWithAuth(AUTH_URL, `/admin/form-group-seeds/preview${formGroupScopeQuery({ ...scope, module })}`, {\n method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ seed, mode }),\n });\n return json?.data ?? json;\n}\n\nexport async function applyFormGroupSeed(module, scope, seed, mode, revision) {\n const json = await fetchJsonWithAuth(AUTH_URL, `/admin/form-group-seeds/apply${formGroupScopeQuery({ ...scope, module })}`, {\n method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ seed, mode, revision }),\n });\n invalidateFormGroupsCache();\n return json?.data ?? json;\n}\n\nexport async function downloadFormGroupSeedBackup(id) {\n const json = await fetchJsonWithAuth(AUTH_URL, `/admin/form-group-seeds/backups/${encodeURIComponent(id)}`);\n return json?.data ?? json;\n}\n\nconst NIL_OBJECT_ID = '000000000000000000000000';\n\n/** True for an absent id or Go's zero-value ObjectID (24 zeros). */\nfunction isNilObjectId(value) {\n const id = String(value ?? '').trim();\n return id === '' || id === NIL_OBJECT_ID;\n}\n\nfunction formGroupScopeQuery(scope = {}) {\n const params = new URLSearchParams();\n if (scope.module) params.set('module', scope.module);\n if (scope.clientId) params.set('clientId', scope.clientId);\n if (scope.region) params.set('region', scope.region);\n const qs = params.toString();\n return qs ? `?${qs}` : '';\n}\n\nexport async function getAdminFormGroups(module = '', scope = {}) {\n const query = formGroupScopeQuery({ ...scope, module: module || scope.module || '' });\n const path = `${FORM_GROUPS_PATH}${query}`;\n const json = await fetchJsonWithAuth(AUTH_URL, path, { cache: 'no-store' });\n const payload = json?.data;\n // Backend returns EITHER a flat array of groups, OR a wrapper object\n // { id, module, ..., groups: [...] }. Support both shapes.\n if (Array.isArray(payload)) return payload;\n if (payload && Array.isArray(payload.groups)) return payload.groups;\n if (Array.isArray(json)) return json;\n if (json && Array.isArray(json.groups)) return json.groups;\n return [];\n}\n\nexport async function getPreviewConfig(module = '', scope = {}) {\n const query = formGroupScopeQuery({ ...scope, module: module || scope.module || '' });\n const json = await fetchJsonWithAuth(AUTH_URL, `${FORM_GROUPS_PATH}/preview-config${query}`);\n return json?.data ?? json ?? {};\n}\n\nexport async function savePreviewConfig(module = '', config = {}, scope = {}) {\n const query = formGroupScopeQuery(scope);\n return fetchJsonWithAuth(AUTH_URL, `${FORM_GROUPS_PATH}/preview-config${query}`, {\n method: 'PUT',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ module, ...config }),\n });\n}\n\nexport async function getAdminClients({ offset = 0, limit = 100, sortBy = 'new', searchvalue = '' } = {}) {\n const params = new URLSearchParams({\n offset: String(offset),\n limit: String(limit),\n sortBy,\n searchvalue,\n });\n // Scope the list to the active tenant/business/businessUnit captured from the\n // login token (authApi stores these on login). The backend uses them when\n // present, otherwise falls back to the token claims — so the dropdown lists\n // the right clients for the selected project, same as the legacy flow.\n const tenantId = localStorage.getItem('tenantId') || '';\n const businessId = localStorage.getItem('businessId') || '';\n const businessUnitId = localStorage.getItem('businessUnitId') || '';\n if (tenantId) params.set('tenantId', tenantId);\n if (businessId) params.set('businessId', businessId);\n if (businessUnitId) params.set('businessUnitId', businessUnitId);\n const json = await fetchJsonWithAuth(AUTH_URL, `/client/view?${params.toString()}`);\n const data = json?.data ?? json;\n return data?.clients ?? data?.Clients ?? data?.items ?? [];\n}\n\nexport async function getModuleFields(module) {\n const json = await fetchJsonWithAuth(AUTH_URL, `/filter-dropdown-fields?module=${encodeURIComponent(module)}`);\n const fields = json?.data ?? json;\n return Array.isArray(fields) ? fields : [];\n}\n\nexport async function createAdminFormGroup(group, scope = {}) {\n return fetchJsonWithAuth(AUTH_URL, `${FORM_GROUPS_PATH}${formGroupScopeQuery(scope)}`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(group),\n });\n}\n\nexport async function updateAdminFormGroup(id, group, scope = {}) {\n const result = await fetchJsonWithAuth(AUTH_URL, `${FORM_GROUPS_PATH}/${id}${formGroupScopeQuery(scope)}`, {\n method: 'PUT',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(group),\n });\n invalidateFormGroupsCache();\n // Verify the server's persisted configuration before the editor closes or\n // announces success. Older backend builds can silently discard unknown keys.\n const expected = (group.fields ?? []).filter(field => typeof field.enforceOptions === 'boolean');\n if (expected.length) {\n let groups;\n try {\n groups = await getAdminFormGroups(group.module || scope.module || '', scope);\n } catch {\n throw new Error('The update was sent, but the saved settings could not be verified. Reopen this configuration before retrying.');\n }\n const key = value => String(value?.$oid ?? value ?? '');\n const saved = groups.find(candidate => key(candidate.id ?? candidate._id) === key(id));\n const mismatched = expected.filter(field =>\n saved?.fields?.find(candidate => candidate.field === field.field)?.enforceOptions !== field.enforceOptions);\n if (mismatched.length) {\n throw new Error(`Dropdown validation settings were not saved for: ${mismatched.map(field => field.label || field.field).join(', ')}. Check the running backend version and selected client/region configuration.`);\n }\n }\n return result;\n}\n\n// Scope-aware, like create/update: with a client selected the group is removed\n// from THAT client's list only. A client-scoped config is a fork of the module\n// default and keeps the same group ids, so an unscoped delete would clear the\n// group from the default and every other client at once.\nexport async function deleteAdminFormGroup(id, scope = {}) {\n return fetchJsonWithAuth(AUTH_URL, `${FORM_GROUPS_PATH}/${id}${formGroupScopeQuery(scope)}`, { method: 'DELETE' });\n}\n\nexport async function seedAdminFormGroups() {\n return fetchJsonWithAuth(AUTH_URL, `${FORM_GROUPS_PATH}/seed`, { method: 'POST' });\n}\n\nexport async function requestConfigOtp(scope, action) {\n return fetchJsonWithAuth(AUTH_URL, `${CONFIG_DEFAULTS_PATH}/request-otp`, {\n method: 'POST',\n body: JSON.stringify({ scope, action }),\n });\n}\n\nexport async function applyConfigDefault(scope, action, otp) {\n return fetchJsonWithAuth(AUTH_URL, `${CONFIG_DEFAULTS_PATH}/apply`, {\n method: 'POST',\n body: JSON.stringify({ scope, action, otp }),\n });\n}\n\n// ── Admin Detail-View Config ──────────────────────────────────────────────────\n// Per-module customization layered on top of the form groups, applied only by\n// the detail view (?view=detail). Shape: { module, fields:[…], merges:[…] }.\n\nconst DETAIL_CONFIG_PATH = '/admin/detail-config';\n\n// Client scope mirrors the form-group admin exactly: pass a clientId to read /\n// write THAT client's detail config, omit it for the module default. The backend\n// falls back to the default when the client has none of its own, so a client\n// with no overrides still renders.\nexport async function getDetailConfig(module, scope = {}) {\n const query = formGroupScopeQuery({ module, clientId: scope.clientId });\n const json = await fetchJsonWithAuth(AUTH_URL, `${DETAIL_CONFIG_PATH}${query}`);\n const data = json?.data ?? json ?? {};\n return {\n module: data.module ?? module,\n // Which scope the response belongs to — '' means the module default. Go\n // serialises an unset ObjectID as 24 zeros, which is NOT a client.\n clientId: isNilObjectId(data.clientId) ? '' : String(data.clientId),\n fields: Array.isArray(data.fields) ? data.fields : [],\n merges: Array.isArray(data.merges) ? data.merges : [],\n sourceFields: Array.isArray(data.sourceFields) ? data.sourceFields : [],\n // Detail-only group title overrides. Absent on an older backend, so default\n // to [] rather than undefined -- the editor treats undefined as \"unknown\"\n // and would refuse to send the key at all.\n groups: Array.isArray(data.groups) ? data.groups : [],\n };\n}\n\nexport async function saveDetailConfig({ module, fields = [], merges = [], sourceFields = [], groups = [], clientId = '' }) {\n const result = await fetchJsonWithAuth(AUTH_URL, DETAIL_CONFIG_PATH, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n // clientId travels in the BODY (this is a JSON POST); the backend treats an\n // absent/zero id as \"the module default\".\n body: JSON.stringify({ module, fields, merges, sourceFields, groups, ...(clientId ? { clientId } : {}) }),\n });\n invalidateFormGroupsCache();\n return result;\n}\n\nexport async function discoverDetailFields({ module, clientId = '', otp }) {\n return fetchJsonWithAuth(AUTH_URL, `${DETAIL_CONFIG_PATH}/discover-fields`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ module, otp, ...(clientId ? { clientId } : {}) }),\n });\n}\n\n// ── Detail-View Display Defaults ──────────────────────────────────────────────\n// Tenant-wide display settings (S3 base, date format, boolean/empty labels,\n// separator, document name order) — the configurable home of what used to be\n// hard-coded in fileUtils.js / FieldValue.jsx.\n\nconst DETAIL_DEFAULTS_PATH = '/admin/detail-defaults';\n\nexport async function getDetailDefaults() {\n const json = await fetchJsonWithAuth(AUTH_URL, DETAIL_DEFAULTS_PATH);\n return json?.data ?? json ?? {};\n}\n\nexport async function saveDetailDefaults(defaults) {\n return fetchJsonWithAuth(AUTH_URL, DETAIL_DEFAULTS_PATH, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(defaults),\n });\n}\n\n// ── AI Service registry (backends AI Actions can call) ─────────────────────\n\nconst AI_SERVICE_CONFIG_PATH = '/admin/ai-service-config';\n\nexport async function getAiServiceConfigs() {\n const json = await fetchJsonWithAuth(AUTH_URL, AI_SERVICE_CONFIG_PATH);\n return json?.data ?? json ?? [];\n}\n\nexport async function saveAiServiceConfig(config) {\n return fetchJsonWithAuth(AUTH_URL, AI_SERVICE_CONFIG_PATH, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(config),\n });\n}\n\nexport async function deleteAiServiceConfig(serviceKey) {\n return fetchJsonWithAuth(AUTH_URL, `${AI_SERVICE_CONFIG_PATH}?serviceKey=${encodeURIComponent(serviceKey)}`, {\n method: 'DELETE',\n });\n}\n\n/**\n * Ask the SERVER whether it can reach an AI service base URL.\n *\n * Deliberately server-side. /ai-action is a server-to-server call made by the\n * Go backend, so only that process can answer the question that matters. A\n * browser-side probe would test the admin's laptop instead: an internal\n * address (http://pyops:7020) is reachable from the backend and not from a\n * remote admin, and a public URL can be reachable from a browser while blocked\n * by cluster egress rules. Testing from the wrong place proves nothing.\n *\n * Resolves with { reachable, status, latencyMs, target, detail, looksLikeWebApp }.\n * An unreachable service is a SUCCESSFUL test with reachable:false — the\n * detail is what the admin needs to see.\n */\nexport async function testAiServiceConnection({ baseUrl, authHeader, authValue }) {\n const json = await fetchJsonWithAuth(AUTH_URL, `${AI_SERVICE_CONFIG_PATH}/test`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ baseUrl, authHeader, authValue }),\n });\n return json?.data ?? json;\n}\n\n// ── Background Check integration ───────────────────────────────────────────\n\nconst BGC_INTEGRATION_CONFIG_PATH = '/admin/bgc-integration-config';\n\nexport async function getBgcIntegrationConfig() {\n const json = await fetchJsonWithAuth(AUTH_URL, BGC_INTEGRATION_CONFIG_PATH);\n return json?.data ?? json ?? { updateMethod: 'MANUAL', enabled: true };\n}\n\nexport async function saveBgcIntegrationConfig(config) {\n return fetchJsonWithAuth(AUTH_URL, BGC_INTEGRATION_CONFIG_PATH, {\n method: 'PUT',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(config),\n });\n}\n\n// Safe runtime view for consumers such as the onboarding BGC stage. It never\n// contains credential values, only credentialsConfigured/webhookConfigured.\nexport async function getBgcIntegrationSummary() {\n const json = await fetchJsonWithAuth(AUTH_URL, '/integration-config/bgc/summary');\n return json?.data ?? json ?? { updateMethod: 'MANUAL', enabled: true };\n}\n\nconst INTEGRATION_CONFIG_PATH = '/admin/integration-config';\n\nexport async function getIntegrationConfigs() {\n const json = await fetchJsonWithAuth(AUTH_URL, INTEGRATION_CONFIG_PATH);\n return json?.data ?? json ?? [];\n}\n\nexport async function getIntegrationConfig(integrationKey) {\n const json = await fetchJsonWithAuth(\n AUTH_URL,\n `${INTEGRATION_CONFIG_PATH}/${encodeURIComponent(integrationKey)}`,\n );\n return json?.data ?? json;\n}\n\nexport async function saveIntegrationConfig(config) {\n const key = config?.integrationKey;\n const path = key\n ? `${INTEGRATION_CONFIG_PATH}/${encodeURIComponent(key)}`\n : INTEGRATION_CONFIG_PATH;\n return fetchJsonWithAuth(AUTH_URL, path, {\n method: key ? 'PUT' : 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(config),\n });\n}\n\nexport async function deleteIntegrationConfig(integrationKey) {\n return fetchJsonWithAuth(\n AUTH_URL,\n `${INTEGRATION_CONFIG_PATH}/${encodeURIComponent(integrationKey)}`,\n { method: 'DELETE' },\n );\n}\n\nexport async function testIntegrationConnection(config) {\n const json = await fetchJsonWithAuth(AUTH_URL, `${INTEGRATION_CONFIG_PATH}/test`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(config),\n });\n return json?.data ?? json;\n}\n\nexport async function getIntegrationSummary(integrationKey) {\n const json = await fetchJsonWithAuth(\n AUTH_URL,\n `/integration-config/${encodeURIComponent(integrationKey)}/summary`,\n );\n return json?.data ?? json;\n}\n\nexport async function applyIntegrationStatus(integrationKey, recordId, providerResponse) {\n const json = await fetchJsonWithAuth(\n AUTH_URL,\n `/integration-config/${encodeURIComponent(integrationKey)}/apply-status/${encodeURIComponent(recordId)}`,\n {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(providerResponse),\n },\n );\n return json?.data ?? json;\n}\n\n// getModuleDetailPreview fetches a record's detail-view groups WITH resolved\n// values (references → {id,value}, documents → full object) so the admin page\n// can preview exactly what the detail view will render.\nexport async function getModuleDetailPreview(module, id) {\n const path = `${FORM_GROUPS_PATH}?module=${encodeURIComponent(module)}&id=${encodeURIComponent(id)}&view=detail`;\n const json = await fetchJsonWithAuth(AUTH_URL, path);\n const data = json?.data ?? json;\n return Array.isArray(data) ? data : [];\n}\n\n// ── Roles ─────────────────────────────────────────────────────────────────────\n\nfunction normalizeRole(record) {\n return {\n key: record.role_id ?? record.id,\n roleId: record.role_id ?? record.id,\n roleName: record.role_name ?? 'N/A',\n description: record.role_description ?? 'N/A',\n userCount: record.user_count ?? 0,\n roleType: record.role_type ?? 0,\n raw: record,\n };\n}\n\nexport function getRoleId(role) {\n return role?.raw?.role_id ?? role?.roleId ?? role?.key;\n}\n\nexport async function getAllRoles() {\n const json = await fetchJsonWithAuth(AUTH_URL, '/get-roles');\n const payload = json.data ?? json;\n const defaultRoles = firstArray(payload?.zinnext_default).map(normalizeRole);\n const customRoles = firstArray(payload?.custom_roles).map(normalizeRole);\n const all = [...defaultRoles, ...customRoles];\n return { roles: all, total: all.length };\n}\n\n// ── Teams ─────────────────────────────────────────────────────────────────────\n\nfunction normalizeTeam(record) {\n return {\n key: record.teamId,\n teamId: record.teamId,\n teamName: record.teamName ?? 'N/A',\n manager: record.reportingManager ?? 'N/A',\n managerId: record.reportingManagerId ?? 0,\n memberCount: record.noOfTeamMembers ?? 0,\n members: firstArray(record.teamMembers),\n memberIds: firstArray(record.teamMembersIds),\n raw: record,\n };\n}\n\nexport function getTeamId(team) {\n return team?.raw?.teamId ?? team?.teamId ?? team?.key;\n}\n\nexport async function getAllTeams({ offset = 0, limit = 10, sortBy = 'new', search = '' } = {}) {\n const params = new URLSearchParams({ searchquery: search, sortBy, limit: String(limit), offset: String(offset) });\n const json = await fetchJsonWithAuth(AUTH_URL, `/get-teams?${params}`);\n const payload = json.data ?? json;\n const teams = firstArray(payload?.teams, payload, json?.teams);\n const total = payload?.totalCount ?? payload?.total ?? teams.length;\n return { teams: teams.map(normalizeTeam), total };\n}\n\nexport async function updateTeam(team, { teamName, managerId, memberIds = [] }) {\n const teamId = getTeamId(team);\n return fetchJsonWithAuth(AUTH_URL, `/team/edit?teamId=${teamId}`, {\n method: 'PUT',\n body: JSON.stringify({\n team_name: teamName,\n team_manager: managerId,\n other_team_members: memberIds,\n reporting_team_member: [],\n }),\n });\n}\n\n// ── Role / Team Field Config ──────────────────────────────────────────────────\n\nasync function fetchFieldConfigModule(apiModule, idParam, idValue, configType = 'listView', includeMeta = false) {\n const params = new URLSearchParams({ module: apiModule, userId: '0', [idParam]: String(idValue), configType });\n if (includeMeta) params.set('includeMeta', '1');\n const json = await fetchJsonWithAuth(AUTH_URL, `${FIELD_CONFIG_PATH}?${params}`);\n const payload = json.data ?? json;\n const fields = firstArray(payload, payload?.visibleFields, json?.visibleFields);\n return includeMeta\n ? {\n fields,\n dataVisibilityMode: payload?.dataVisibilityMode ?? json?.dataVisibilityMode ?? 'all',\n dataOwnerField: payload?.dataOwnerField ?? json?.dataOwnerField ?? 'createdBy',\n filterDisplayMode: payload?.filterDisplayMode === 'top' ? 'top' : 'popup',\n exportEnabled: payload?.exportEnabled !== false,\n }\n : fields;\n}\n\nexport async function getRoleModuleFields(role, configType = 'listView', modules = CUSTOMIZABLE_MODULES) {\n const roleId = getRoleId(role);\n const customizableModules = normalizeCustomizableModules(modules);\n const entries = await Promise.all(\n customizableModules.map(async ({ key, apiModule }) => {\n const fields = await fetchFieldConfigModule(apiModule, 'roleId', roleId, configType);\n return [key, fields.map((f, i) => ({ ...normalizeModuleField(f, i), module: key, apiModule, roleId }))];\n })\n );\n return Object.fromEntries(entries);\n}\n\n\nexport async function getRoleModuleFieldsWithMeta(role, configType = 'listView', modules = CUSTOMIZABLE_MODULES) {\n const roleId = getRoleId(role);\n const customizableModules = normalizeCustomizableModules(modules);\n const entries = await Promise.all(\n customizableModules.map(async ({ key, apiModule }) => {\n const result = await fetchFieldConfigModule(apiModule, 'roleId', roleId, configType, true);\n const fields = result.fields.map((f, i) => ({ ...normalizeModuleField(f, i), module: key, apiModule, roleId }));\n return [key, {\n fields,\n dataVisibilityMode: result.dataVisibilityMode ?? 'all',\n dataOwnerField: result.dataOwnerField ?? 'createdBy',\n filterDisplayMode: result.filterDisplayMode ?? 'popup',\n exportEnabled: result.exportEnabled !== false,\n }];\n })\n );\n return Object.fromEntries(entries);\n}\n\nexport async function getTeamModuleFields(team, configType = 'listView') {\n const teamId = getTeamId(team);\n const entries = await Promise.all(\n CUSTOMIZABLE_MODULES.map(async ({ key, apiModule }) => {\n const fields = await fetchFieldConfigModule(apiModule, 'teamId', teamId, configType);\n return [key, fields.map((f, i) => ({ ...normalizeModuleField(f, i), module: key, apiModule, teamId }))];\n })\n );\n return Object.fromEntries(entries);\n}\n\nfunction normalizeListViewLookup(field) {\n if (!field?.lookup) return null;\n\n const lookup = { ...field.lookup };\n const localField = String(lookup.localField ?? '').trim() || String(field.fieldKey ?? '').trim();\n const valueField = String(lookup.valueField ?? lookup.foreignField ?? '').trim() || '_id';\n const displayField = String(lookup.displayField ?? lookup.projectField ?? '').trim();\n const displayField2 = String(lookup.displayField2 ?? '').trim();\n\n let projectFields = Array.isArray(lookup.projectFields)\n ? lookup.projectFields.map((value) => String(value ?? '').trim()).filter(Boolean)\n : [];\n\n // The list API accepts displayField, projectField and projectFields. Persist\n // projectFields as well so old/new backend versions resolve the same config.\n if (projectFields.length === 0) {\n projectFields = [displayField, displayField2].filter(Boolean);\n }\n\n return {\n ...lookup,\n localField,\n valueField,\n displayField,\n ...(displayField2 ? { displayField2 } : {}),\n projectFields,\n };\n}\n\nfunction visibleFieldPayload(fields, configType) {\n const isListView = !configType || configType === 'listView';\n return fields.map((field, index) => {\n const base = {\n label: field.fieldName, field: field.fieldKey,\n isVisible: field.isVisible, type: field.type ?? 'text', order: field.order ?? index,\n };\n if (isListView) {\n Object.assign(base, {\n ...(typeof field.exportable === 'boolean' ? { exportable: field.exportable } : {}),\n ...(typeof field.showByDefault === 'boolean' ? { showByDefault: field.showByDefault } : {}),\n ...(typeof field.exportable === 'boolean' ? { exportable: field.exportable } : {}),\n allowedTabs: Array.isArray(field.allowedTabs) ? field.allowedTabs : [],\n isLink: field.isLink ?? false, linkTemplate: field.linkTemplate ?? '',\n linkType: field.linkType ?? 'internal', linkTarget: field.linkTarget ?? '_self',\n action: field.action ?? 'navigate',\n secondaryField: field.secondaryField ?? '', secondaryLabel: field.secondaryLabel ?? '',\n secondaryFields: Array.isArray(field.secondaryFields) ? field.secondaryFields : [],\n secondarySeparator: field.secondarySeparator ?? '',\n lookup: normalizeListViewLookup(field), actionButtons: field.actionButtons ?? [],\n derived: field.derived ?? null, computed: field.computed ?? null,\n displayRules: Array.isArray(field.displayRules) ? field.displayRules : [],\n renderType: field.renderType ?? '',\n valueStyles: Array.isArray(field.valueStyles) ? field.valueStyles : [],\n commonStyle: field.commonStyle ?? null, displayTemplate: field.displayTemplate ?? '',\n defaultValue: field.defaultValue ?? '',\n defaultValueField: field.defaultValueField ?? '',\n renderConfig: field.renderConfig\n ? {\n ...field.renderConfig,\n treatZeroAsEmpty: Boolean(field.renderConfig.treatZeroAsEmpty),\n cleanEmptyTemplateSeparators: Boolean(field.renderConfig.cleanEmptyTemplateSeparators),\n }\n : null,\n });\n } else {\n base.isEditable = field.isEditable ?? false;\n base.ismandatory = field.ismandatory ?? field.isMandatory ?? false;\n if (configType === 'filter') {\n base.filterInputType = field.filterInputType ?? 'dropdown';\n base.filterToolbar = Boolean(field.filterToolbar);\n base.filterOptions = Array.isArray(field.filterOptions)?field.filterOptions:[];\n base.quickFilterOptions = Array.isArray(field.quickFilterOptions)?field.quickFilterOptions:[];\n base.isDefaultFilter = Boolean(field.isDefaultFilter);\n base.dataSource = field.dataSource ?? 'module';\n if (field.dataSource === 'group') base.groupName = field.groupName ?? '';\n base.filterGroupFields = Array.isArray(field.filterGroupFields) ? field.filterGroupFields : [];\n base.filterGroupSeparator = field.filterGroupSeparator ?? ' ';\n base.filterArrayLabelField = field.filterArrayLabelField ?? '';\n base.filterArrayValueField = field.filterArrayValueField ?? '';\n if (field.lookup) base.lookup = field.lookup;\n } else {\n if (['select', 'radio', 'checkbox'].includes(field.type)) {\n base.dataSource = field.dataSource ?? 'module';\n if (field.dataSource === 'group') base.groupName = field.groupName ?? '';\n }\n }\n }\n return base;\n });\n}\n\nexport async function updateRoleModuleFieldConfig(role, module, fields, configType = 'listView', modules = CUSTOMIZABLE_MODULES, dataVisibilityMode = '', dataOwnerField = 'createdBy', updateAllRoles = false, filterDisplayMode = 'popup', exportEnabled = true) {\n const roleId = getRoleId(role);\n const apiModule = normalizeCustomizableModules(modules).find((m) => m.key === module)?.apiModule ?? module;\n return fetchJsonWithAuth(AUTH_URL, `${FIELD_CONFIG_PATH}/role`, {\n method: 'PUT',\n body: JSON.stringify({\n module: apiModule, roleId, configType, updateAllRoles,\n ...(!configType || configType === 'listView' ? { exportEnabled } : {}),\n ...(configType === 'filter' ? { filterDisplayMode } : {}),\n ...(!configType || configType === 'listView' ? { exportEnabled } : {}),\n visibleFields: visibleFieldPayload(fields, configType),\n ...((!configType || configType === 'listView') && dataVisibilityMode\n ? { dataVisibilityMode, dataOwnerField: String(dataOwnerField || 'createdBy').trim() || 'createdBy' }\n : {}),\n }),\n });\n}\n\n// ── Role Configure → Form (derived from Form Groups) ─────────────────────────\n// Unlike getRoleModuleFields/updateRoleModuleFieldConfig above (an\n// independently-seeded flat field list), these back the Form tab's grouped\n// view: the backend derives groups/fields straight from the module's Form\n// Groups config and overlays this role's saved grants (GET\n// /admin/role-form-permissions), so Form Groups stays the single source of\n// truth and new/renamed/removed fields sync automatically. Saving still goes\n// through the existing PUT /admin/field-config/role (configType \"form\") —\n// the backend clamps it against Form Groups' global Show flags either way.\nconst ROLE_FORM_PERMISSIONS_PATH = '/admin/role-form-permissions';\n\n// Must match Be_Auth_DevOps models/roleFormPermissions.go's\n// roleGroupPermissionKey — the synthetic field-config key a group-level\n// ON/OFF toggle is persisted under, alongside real per-field grants, in the\n// same flat visibleFields list (no separate schema/endpoint needed).\nfunction roleGroupPermissionKey(groupName) {\n return `__group__:${groupName}`;\n}\n\n// scope: { clientId, region } — same client/region scope as\n// getAdminFormGroups/AddFormV1's effectiveClientId+effectiveRegion, so a\n// client- or region-scoped Form Groups override (e.g. a per-client Jobs\n// variant) is reflected here too, not just the tenant-wide default. Generic\n// for any module — GetFormGroupConfigScoped falls back to the default when\n// no scoped config exists for the given module, so this is always safe to pass.\nexport async function getRoleFormPermissions(role, module, scope = {}) {\n const roleId = getRoleId(role);\n const params = new URLSearchParams({ module, roleId: String(roleId ?? '') });\n if (scope.clientId) params.set('clientId', scope.clientId);\n if (scope.region) params.set('region', scope.region);\n const json = await fetchJsonWithAuth(AUTH_URL, `${ROLE_FORM_PERMISSIONS_PATH}?${params}`);\n const payload = json?.data ?? json;\n return Array.isArray(payload) ? payload : [];\n}\n\n// groups: [{ name, label, enabled, locked, fields: [{ field, label, enabled, locked, editable }] }]\n// as edited in the UI (see RoleFormPermissionsEditor). Group toggles are sent\n// as synthetic visibleFields rows so the existing role-save + clamp pipeline\n// needs no changes.\n//\n// A role's field-level grants are NOT stored per client/region — they're one\n// shared set overlaid onto whichever scoped Form Groups structure a caller\n// requests (getRoleFormPermissions). So any group/field that's `locked` in\n// the CURRENTLY VIEWED scope (globally disabled there, but possibly enabled\n// under the tenant-wide default or a different client's scope) is left out\n// of the payload entirely — sending its scope-computed `enabled: false`\n// would silently overwrite the role's real, scope-independent stored\n// preference the next time anyone loads a different scope. Locked items\n// aren't editable in this view anyway (their Switch is disabled), so there's\n// nothing this save is meant to change for them.\nexport async function saveRoleFormPermissions(role, module, groups) {\n const roleId = getRoleId(role);\n const visibleFields = [];\n let order = 0;\n for (const group of groups) {\n if (!group.locked) {\n visibleFields.push({\n label: group.label,\n field: roleGroupPermissionKey(group.name),\n // A group carries two independent role toggles: isVisible = shown,\n // isEditable = not-disabled (read-only when false). Default both true.\n isVisible: group.enabled,\n isEditable: group.editable !== false,\n order: order++,\n });\n }\n for (const field of group.fields ?? []) {\n if (field.locked) continue;\n visibleFields.push({\n label: field.label,\n field: field.field,\n isVisible: field.enabled,\n isEditable: field.editable !== false,\n order: order++,\n });\n }\n }\n return fetchJsonWithAuth(AUTH_URL, `${FIELD_CONFIG_PATH}/role`, {\n method: 'PUT',\n body: JSON.stringify({ module, roleId, configType: 'form', visibleFields }),\n });\n}\n\nexport async function updateTeamModuleFieldConfig(team, module, fields, configType = 'listView') {\n const teamId = getTeamId(team);\n const apiModule = CUSTOMIZABLE_MODULES.find((m) => m.key === module)?.apiModule ?? module;\n return fetchJsonWithAuth(AUTH_URL, `${FIELD_CONFIG_PATH}/team`, {\n method: 'PUT',\n body: JSON.stringify({ module: apiModule, teamId, configType, visibleFields: visibleFieldPayload(fields, configType) }),\n });\n}\n\n// ── Users ─────────────────────────────────────────────────────────────────────\n\nexport async function getAllUsers({ offset = 0, limit = 10, sortBy = 'new', searchQuery = '' } = {}) {\n const params = new URLSearchParams({ offset: String(offset), limit: String(limit), sortBy });\n if (searchQuery) params.set('searchquery', searchQuery);\n const json = await fetchJsonWithAuth(AUTH_URL, `/get-all-users?${params}`);\n const payload = json.data ?? json;\n const users = firstArray(\n payload, json.users, json.rows, json.items, json.records,\n payload?.users, payload?.data, payload?.rows, payload?.items,\n payload?.records, payload?.docs, payload?.result, payload?.results,\n );\n return { users, total: normalizeTotal({ ...json, ...payload }, users) };\n}\n\nexport function getUserId(user) {\n const value = firstValue(\n user?.raw ?? user,\n ['USER_ID', 'user_id', 'userId', 'id', '_id', 'uuid'],\n user?.key\n );\n const num = Number(value);\n return Number.isFinite(num) ? num : value;\n}\n\nexport function getUserRoleId(user) {\n const value = firstValue(user?.raw ?? user, ['ROLE_ID', 'role_id', 'roleId', 'ROLEID'], 0);\n const num = Number(value);\n return Number.isFinite(num) && num > 0 ? num : 0;\n}\n\nasync function getFieldConfigModule(apiModule, userId, roleId, configType) {\n const params = new URLSearchParams({ module: apiModule, userId: String(userId ?? ''), roleId: String(roleId ?? ''), configType });\n const json = await fetchJsonWithAuth(AUTH_URL, `${FIELD_CONFIG_PATH}?${params}`);\n const payload = json.data ?? json;\n return firstArray(payload, payload?.visibleFields, json?.visibleFields);\n}\n\nasync function getDropdownModuleFields(apiModule) {\n const json = await fetchJsonWithAuth(SUBMISSIONS_URL, `/filter-dropdown-fields?module=${encodeURIComponent(apiModule)}`);\n const payload = json.data ?? json;\n return firstArray(payload, payload?.fields, payload?.items, payload?.rows, json?.fields);\n}\n\nexport async function getUserModuleFields(user, configType = 'listView', modules = CUSTOMIZABLE_MODULES) {\n const userId = getUserId(user);\n const roleId = getUserRoleId(user);\n const customizableModules = normalizeCustomizableModules(modules);\n const entries = await Promise.all(\n customizableModules.map(async ({ key, apiModule }) => {\n let fields;\n try {\n fields = await getFieldConfigModule(apiModule, userId, roleId, configType);\n } catch {\n try { fields = await getDropdownModuleFields(apiModule); } catch { fields = []; }\n }\n if ((fields?.length ?? 0) === 0) {\n try { fields = await getDropdownModuleFields(apiModule); } catch { fields = []; }\n }\n return [key, fields.map((f, i) => ({ ...normalizeModuleField(f, i), module: key, apiModule, userId, roleId }))];\n })\n );\n return Object.fromEntries(entries);\n}\n\nexport async function hasUserFieldConfigData(user, configType = 'listView', modules = CUSTOMIZABLE_MODULES) {\n const userId = getUserId(user);\n const roleId = getUserRoleId(user);\n const customizableModules = normalizeCustomizableModules(modules);\n const results = await Promise.all(\n customizableModules.map(async ({ apiModule }) => {\n try {\n const fields = await getFieldConfigModule(apiModule, userId, roleId, configType);\n return (fields?.length ?? 0) > 0;\n } catch {\n return false;\n }\n })\n );\n return results.some(Boolean);\n}\n\nexport async function seedFieldConfig(collections = []) {\n return fetchJsonWithAuth(AUTH_URL, `${FIELD_CONFIG_PATH}/seed`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ collections }),\n });\n}\n\nexport async function getFieldConfigSeedStatus() {\n const json = await fetchJsonWithAuth(AUTH_URL, `${FIELD_CONFIG_PATH}/seed-status`);\n const data = json?.data ?? json ?? {};\n return {\n modules: Array.isArray(data.modules) ? data.modules : [],\n seededModules: data.seededModules ?? {},\n };\n}\n\nexport async function updateUserModuleFieldConfig(user, module, fields, configType = 'listView', modules = CUSTOMIZABLE_MODULES) {\n const userId = getUserId(user);\n const roleId = getUserRoleId(user);\n const apiModule = normalizeCustomizableModules(modules).find((m) => m.key === module)?.apiModule ?? module;\n return fetchJsonWithAuth(AUTH_URL, FIELD_CONFIG_PATH, {\n method: 'PUT',\n body: JSON.stringify({ module: apiModule, userId, roleId, configType, visibleFields: visibleFieldPayload(fields, configType) }),\n });\n}\n\nexport async function updateUserModuleFields(user, moduleFields, configType = 'listView') {\n return Promise.all(\n Object.entries(moduleFields).map(([module, fields]) => updateUserModuleFieldConfig(user, module, fields, configType))\n );\n}\n\nexport async function uploadFormGroupIcon(file) {\n const token = localStorage.getItem('authToken');\n const formData = new FormData();\n formData.append('icon', file);\n const res = await fetch(`${AUTH_URL}/admin/form-groups/icon`, {\n method: 'POST',\n headers: { Authorization: `Bearer ${token}` },\n body: formData,\n });\n if (!res.ok) { const e = new Error(`Upload failed: ${res.status}`); e.status = res.status; throw e; }\n const json = await res.json();\n return json.data ?? json;\n}\n\nexport async function uploadListViewActionIcon(file) {\n const token = localStorage.getItem('authToken');\n const formData = new FormData();\n formData.append('icon', file);\n const res = await fetch(`${AUTH_URL}/admin/field-config/action-icon`, {\n method: 'POST',\n headers: { Authorization: `Bearer ${token}` },\n body: formData,\n });\n if (!res.ok) { const e = new Error(`Upload failed: ${res.status}`); e.status = res.status; throw e; }\n const json = await res.json();\n return json.data ?? json;\n}\n\n// Module options for the Actions admin screens: the configured menu/module\n// catalog PLUS every collection in this app's database, so row actions can be\n// configured for ANY module (onboarding, movements, a brand-new collection…)\n// without first registering it as a menu module. Resolves per app DB via\n// X-App-Id, so each project sees its own collections.\nexport async function getActionConfigModules() {\n const [modules, collections, existingConfigs] = await Promise.all([\n getAvailableModules().catch(() => []),\n getAvailableCollections().catch(() => []),\n getRowActionConfigs().catch(() => []),\n ]);\n const baseModules = Array.isArray(modules) ? modules : [];\n // Detail-view action variants: a module's DETAIL page can carry its own row\n // actions (e.g. an \"Open JD\" primary button on the submission detail view)\n // without those actions also appearing on the LIST view. The detail page\n // fetches actions under whatever key it passes as DetailHeaderCard's\n // customConfigName — \"submissiondetails\", \"submissionJob\" — which follows no\n // derivable rule. This used to GENERATE `${key}detail` names, which produced\n // keys nothing ever requests (\"submissionsdetail\" vs the real\n // \"submissiondetails\"), so configuring one silently changed nothing.\n // Offer the keys that actually exist in rowActionConfig instead.\n const variantKeys = existingConfigs\n .map((config) => String(config?.module ?? '').trim())\n .filter(Boolean);\n return [\n ...baseModules,\n ...(Array.isArray(collections) ? collections : []),\n ...variantKeys,\n ];\n}\n\n// Generic module CRUD — used by the Masters admin screen (locations/taxes),\n// but not specific to either: works for any module via the dynamic gateway.\nexport async function listModuleRecords(module, { page = 1, limit = 100 } = {}) {\n const params = new URLSearchParams({ module, page: String(page), limit: String(limit) });\n const json = await fetchJsonWithAuth(AUTH_URL, `/module/list?${params}`);\n const data = json?.data ?? json ?? {};\n return { items: Array.isArray(data.data) ? data.data : [], total: data.pagination?.total ?? 0 };\n}\n\nexport async function createModuleRecordGeneric(module, payload) {\n return fetchJsonWithAuth(AUTH_URL, `/module/create?module=${encodeURIComponent(module)}`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(payload),\n });\n}\n\nexport async function updateModuleRecordGeneric(module, id, payload) {\n return fetchJsonWithAuth(AUTH_URL, `/module/update/${encodeURIComponent(id)}?module=${encodeURIComponent(module)}`, {\n method: 'PUT',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(payload),\n });\n}\n\nexport async function deleteModuleRecordGeneric(module, id) {\n return fetchJsonWithAuth(AUTH_URL, `/module/delete/${encodeURIComponent(id)}?module=${encodeURIComponent(module)}`, {\n method: 'DELETE',\n });\n}\n\n// Searchable \"City, State, Country\" options from the locationMasters collection\n// — the same source AddFormV1's `location` field type uses. Used by the Location\n// Tax Master screen to pick a real location instead of free-typing one.\nexport async function getLocationMasterOptions(search = '', limit = 50) {\n const params = new URLSearchParams({ search, limit: String(limit), offset: '0' });\n const json = await fetchJsonWithAuth(AUTH_URL, `/admin/location-dropdown-values?${params}`);\n const raw = json?.data ?? json ?? [];\n return (Array.isArray(raw) ? raw : [])\n .map((item) => {\n const label = typeof item === 'string' ? item : (item.label ?? item.value ?? '');\n return { label, value: label };\n })\n .filter((option) => option.label);\n}\n\n// Generic record options for any lookup-configured field — used by the Form\n// Groups editor's \"Conditional Default\" record picker (e.g. choose the default\n// Employer applied when Contract Type is W2). Returns { label, value } pairs\n// where value is the record's valueField (usually _id).\nexport async function getLookupRecordOptions(collection, displayField, valueField = '_id') {\n const params = new URLSearchParams({\n collection: String(collection),\n displayField: String(displayField),\n valueField: String(valueField),\n });\n const json = await fetchJsonWithAuth(AUTH_URL, `/admin/lookup-dropdown-values?${params}`);\n const raw = json?.data ?? json ?? [];\n return (Array.isArray(raw) ? raw : [])\n .map((item) => ({\n label: item.label ?? item.displayValue ?? item[displayField] ?? String(item.value ?? ''),\n value: String(item.value ?? item._id ?? item.id ?? ''),\n }))\n .filter((option) => option.value && option.label);\n}\n\n// Default Fields — per-module rules that LOCK a field in the Form Groups editor\n// and can optionally force it visible and/or required at render time.\n// getModuleDefaultFields is also called at runtime by AddFormV1/EditFormV1.\n// Saving is OTP-gated: request the code (requestConfigOtp('defaultFields','save'))\n// then pass it here.\n//\n// TWO WIRE SHAPES, and both must keep working:\n// \"jobTitle\" legacy — force show + force req + lock\n// { field, locked, forceShow, forceReq } each intent stated separately\n//\n// The legacy reading is not a courtesy: ~145 live fields are stored as bare\n// strings, and 29 of them (US unit) are configured differently from what\n// membership forces — 25 submission fields are configured req:0 yet required\n// today. Treating a string as \"lock only\" would quietly make those optional.\n// normalizeDefaultFieldRule is the ONE place that decision is made, so the\n// forms, the field editor and the admin panel cannot disagree about it.\nexport function normalizeDefaultFieldRule(entry) {\n if (typeof entry === 'string') {\n const field = entry.trim();\n return field ? { field, locked: true, forceShow: true, forceReq: true } : null;\n }\n if (!entry || typeof entry !== 'object') return null;\n const field = String(entry.field ?? '').trim();\n if (!field) return null;\n // Explicit === true, so a missing key is FALSE rather than truthy-by-accident.\n return {\n field,\n locked: entry.locked === true,\n forceShow: entry.forceShow === true,\n forceReq: entry.forceReq === true,\n };\n}\n\n// normalizeDefaultFieldRules -> Map(fieldKey -> rule). A Map because every\n// consumer wants \"what is the rule for THIS field\", which a Set of keys could\n// no longer answer once membership stopped implying all three intents.\nexport function normalizeDefaultFieldRules(list) {\n const out = new Map();\n (Array.isArray(list) ? list : []).forEach((entry) => {\n const rule = normalizeDefaultFieldRule(entry);\n if (rule && !out.has(rule.field)) out.set(rule.field, rule);\n });\n return out;\n}\n\nexport async function getModuleDefaultFields(module) {\n const json = await fetchJsonWithAuth(AUTH_URL, `/admin/default-fields?module=${encodeURIComponent(module)}`);\n const data = json?.data ?? json ?? {};\n return Array.isArray(data.fields) ? data.fields : [];\n}\n\n// getModuleDefaultFieldRules is what runtime consumers should call: it returns\n// the resolved Map, so no caller re-implements the legacy-string rule.\nexport async function getModuleDefaultFieldRules(module) {\n return normalizeDefaultFieldRules(await getModuleDefaultFields(module));\n}\n\nexport async function saveModuleDefaultFields(module, fields, otp) {\n return fetchJsonWithAuth(AUTH_URL, '/admin/default-fields', {\n method: 'PUT',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ module, fields, otp }),\n });\n}\n\n// Generic email verification — used by any admin-configured\n// field.verifyAction === \"email\" (AddFormV1/EditFormV1's VerifyFieldButton).\n//\n// The backend runs a layered check (syntax -> MX -> Mailgun -> SMTP mailbox\n// probe -> catch-all detection), so the verdict is richer than a boolean:\n//\n// valid keep/reject the address (unchanged meaning — the form gate)\n// result 'deliverable' | 'undeliverable' | 'risky' | 'unknown'\n// mailboxConfirmed the receiving server confirmed THIS mailbox specifically\n// catchAll the domain accepts every address, so the mailbox is unproven\n//\n// mailboxConfirmed is the one to trust for \"this person will actually get mail\".\n// A catch-all domain (Google Workspace default, many corporates) can never be\n// proven from outside — the UI says so rather than implying certainty.\nexport async function verifyEmail(email) {\n const json = await fetchJsonWithAuth(AUTH_URL, '/email-verify', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ email }),\n });\n const data = json?.data ?? json ?? {};\n return {\n valid: Boolean(data.valid),\n reason: data.reason ?? '',\n result: data.result ?? '',\n mailboxConfirmed: Boolean(data.mailboxConfirmed),\n catchAll: Boolean(data.catchAll),\n disposable: Boolean(data.disposable),\n roleAddress: Boolean(data.roleAddress),\n risk: data.risk ?? '',\n checks: Array.isArray(data.checks) ? data.checks : [],\n };\n}\n\nexport async function getAvailableCollections() {\n const json = await fetchJsonWithAuth(AUTH_URL, '/admin/lookup/collections');\n const data = json.data ?? json;\n return Array.isArray(data) ? data : [];\n}\n\nexport async function getCollectionFields(collection) {\n const json = await fetchJsonWithAuth(AUTH_URL, `/admin/lookup/collection-fields?collection=${encodeURIComponent(collection)}`);\n const data = json.data ?? json;\n return Array.isArray(data) ? data : [];\n}\n\nexport async function getArraySubfields(module, field) {\n const json = await fetchJsonWithAuth(AUTH_URL, `/admin/field-array-subfields?module=${encodeURIComponent(module)}&field=${encodeURIComponent(field)}`);\n const data = json.data ?? json;\n return Array.isArray(data?.fields) ? data.fields : [];\n}\n\n// ── Menu Modules & Actions (master data management) ──────────────────────────\n\nexport async function getMenuModules() {\n const json = await fetchJsonWithAuth(AUTH_URL, '/admin/menu-modules');\n return firstArray(json.data, json);\n}\n\nexport async function createMenuModule({ menuName, apiUrl = '', menuType = 'menu', parentMenuId = 0, displayOrder = 0 }) {\n const json = await fetchJsonWithAuth(AUTH_URL, '/admin/menu-modules', {\n method: 'POST',\n body: JSON.stringify({ menuName, apiUrl, menuType, parentMenuId, displayOrder }),\n });\n return json.data ?? json;\n}\n\nexport async function updateMenuModule(id, { menuName }) {\n const json = await fetchJsonWithAuth(AUTH_URL, `/admin/menu-modules/${id}`, {\n method: 'PUT',\n body: JSON.stringify({ menuName }),\n });\n return json.data ?? json;\n}\n\nexport async function deleteMenuModule(id) {\n const json = await fetchJsonWithAuth(AUTH_URL, `/admin/menu-modules/${id}`, { method: 'DELETE' });\n return json.data ?? json;\n}\n\nexport async function getMenuActions() {\n const json = await fetchJsonWithAuth(AUTH_URL, '/admin/menu-actions');\n return firstArray(json.data, json);\n}\n\nexport async function createMenuAction({ permissionName, permissionKey }) {\n const json = await fetchJsonWithAuth(AUTH_URL, '/admin/menu-actions', {\n method: 'POST',\n body: JSON.stringify({ permissionName, permissionKey }),\n });\n return json.data ?? json;\n}\n\nexport async function updateMenuAction(id, { permissionName }) {\n const json = await fetchJsonWithAuth(AUTH_URL, `/admin/menu-actions/${id}`, {\n method: 'PUT',\n body: JSON.stringify({ permissionName }),\n });\n return json.data ?? json;\n}\n\nexport async function deleteMenuAction(id) {\n const json = await fetchJsonWithAuth(AUTH_URL, `/admin/menu-actions/${id}`, { method: 'DELETE' });\n return json.data ?? json;\n}\n\nfunction normalizeRolePermissionValue(value) {\n if (value && typeof value === 'object' && !Array.isArray(value)) {\n return normalizeRolePermissionValue(\n value.value ?? value.access_value ?? value.accessValue ?? value.permissionValue ?? value.enabled,\n );\n }\n if (value === true || value === 1 || value === '1') return '1';\n const normalized = String(value ?? '').trim().toLowerCase();\n return normalized === 'true' || normalized === 'yes' || normalized === 'active' ? '1' : '0';\n}\n\nfunction normalizeRoleMenusForSave(menus = {}) {\n if (!menus || typeof menus !== 'object' || Array.isArray(menus)) return menus;\n return Object.fromEntries(Object.entries(menus).map(([menuName, menu]) => [\n menuName,\n {\n ...menu,\n menuId: menu?.menuId ?? menu?.menu_id ?? 0,\n permissions: Object.fromEntries(Object.entries(menu?.permissions ?? {}).map(([key, entry]) => [\n key,\n {\n ...(entry && typeof entry === 'object' && !Array.isArray(entry) ? entry : {}),\n id: entry?.id ?? entry?.permission_id ?? entry?.permissionId ?? 0,\n value: normalizeRolePermissionValue(entry),\n },\n ])),\n },\n ]));\n}\n\n// ── Permissions ───────────────────────────────────────────────────────────────\n\nexport async function getRolePermissions(roleId) {\n const json = await fetchJsonWithAuth(AUTH_URL, `/get-role-details?roleid=${roleId}`);\n return (json?.data ?? json) ?? {};\n}\n\nexport async function updateRolePermissions(roleId, menus) {\n return fetchJsonWithAuth(AUTH_URL, '/edit-role-details', {\n method: 'PUT',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ roleId, menus: normalizeRoleMenusForSave(menus) }),\n });\n}\n\n// Resolved permissions for the logged-in user's own role — moduleName ->\n// actionKey -> allowed (or the wildcard shape { \"*\": { \"*\": true } } for\n// full-access roles). Fetched once on login by PermissionContext.\nexport async function getMyPermissions() {\n const json = await fetchJsonWithAuth(AUTH_URL, '/me/permissions');\n return (json?.data ?? json) ?? {};\n}\n\n// ── Custom Forms ──────────────────────────────────────────────────────────────\n\nconst CUSTOM_FORMS_PATH = '/admin/custom-forms';\n\nexport async function getCustomForms(module = '', type = '', action = '') {\n const params = new URLSearchParams();\n if (module) params.append('module', module);\n if (type) params.append('formType', type);\n if (action) params.append('action', action);\n const path = `${CUSTOM_FORMS_PATH}?${params.toString()}`;\n const json = await fetchJsonWithAuth(AUTH_URL, path);\n const payload = json?.data;\n if (Array.isArray(payload)) return payload;\n if (Array.isArray(json)) return json;\n return [];\n}\n\nexport async function createCustomForm(form) {\n return fetchJsonWithAuth(AUTH_URL, CUSTOM_FORMS_PATH, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(form),\n });\n}\n\nexport async function updateCustomForm(id, form) {\n return fetchJsonWithAuth(AUTH_URL, `${CUSTOM_FORMS_PATH}/${id}`, {\n method: 'PUT',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(form),\n });\n}\n\nexport async function deleteCustomForm(id) {\n return fetchJsonWithAuth(AUTH_URL, `${CUSTOM_FORMS_PATH}/${id}`, { method: 'DELETE' });\n}\n\n// ── Row Action Config ─────────────────────────────────────────────────────────\n\nconst ROW_ACTION_CONFIG_PATH = '/admin/row-action-config';\n\n// Keep the module key written by Admin identical to the key used by ListView.\n// Module labels/keys supplied by the module catalog (or typed into the tags\n// selector) may contain casing and surrounding whitespace, while list routes\n// consistently request normalized keys.\nfunction normalizeRowActionModule(module) {\n return String(module ?? '').trim().toLowerCase();\n}\n\nexport async function getRowActionConfigs(module = '') {\n const normalizedModule = normalizeRowActionModule(module);\n const path = normalizedModule\n ? `${ROW_ACTION_CONFIG_PATH}?module=${encodeURIComponent(normalizedModule)}`\n : ROW_ACTION_CONFIG_PATH;\n const json = await fetchJsonWithAuth(AUTH_URL, path);\n const payload = json?.data;\n if (Array.isArray(payload)) return payload;\n if (Array.isArray(json)) return json;\n return [];\n}\n\nexport async function createRowActionConfig({ module, roleId = 0, rowActions = [] }) {\n const normalizedModule = normalizeRowActionModule(module);\n return fetchJsonWithAuth(AUTH_URL, ROW_ACTION_CONFIG_PATH, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ module: normalizedModule, roleId, rowActions }),\n });\n}\n\nexport async function updateRowActionConfig(id, rowActions = []) {\n return fetchJsonWithAuth(AUTH_URL, `${ROW_ACTION_CONFIG_PATH}/${id}`, {\n method: 'PUT',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ rowActions }),\n });\n}\n\nexport async function deleteRowActionConfig(id) {\n return fetchJsonWithAuth(AUTH_URL, `${ROW_ACTION_CONFIG_PATH}/${id}`, { method: 'DELETE' });\n}\n\nexport async function seedRowActionConfigs() {\n return fetchJsonWithAuth(AUTH_URL, `${ROW_ACTION_CONFIG_PATH}/seed`, { method: 'POST' });\n}\n\n// ── Module Action Rules ───────────────────────────────────────────────────────\n// Per-module configurable rules stored in auth repo, returned by module-data-list.\n// Frontend evaluates these rules per-row to show/hide row action buttons.\n\nconst MODULE_ACTION_RULES_PATH = '/admin/module-action-rules';\n\nexport async function getActivityRules(module) {\n const result = await fetchJsonWithAuth(AUTH_URL, `/admin/activity-rules?module=${encodeURIComponent(module)}`);\n return Array.isArray(result?.data) ? result.data : Array.isArray(result) ? result : [];\n}\n\nexport function saveActivityRule(id, rule) {\n return fetchJsonWithAuth(AUTH_URL, `/admin/activity-rules${id ? `/${id}` : ''}`, {\n method: id ? 'PUT' : 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(rule),\n });\n}\n\nexport function deleteActivityRule(id) {\n return fetchJsonWithAuth(AUTH_URL, `/admin/activity-rules/${id}`, { method: 'DELETE' });\n}\n\nexport async function getModuleActionRules(module) {\n const json = await fetchJsonWithAuth(AUTH_URL, `${MODULE_ACTION_RULES_PATH}?module=${encodeURIComponent(module)}`);\n const payload = json?.data;\n if (Array.isArray(payload)) return payload;\n if (Array.isArray(json)) return json;\n return [];\n}\n\n// allowedActions is an ALLOW-LIST: when the rule fires, every action it does\n// not name is blocked, including actions added later. That is what makes\n// \"Inactive jobs — Edit and Delete only\" expressible as one rule instead of a\n// blockedActions list that has to be revisited every time an action is added.\n//\n// REQ-20260908-01 — it was missing from both of these functions. The admin UI\n// collects it, the Go model stores it, and the evaluator honours it; only the\n// two lines below dropped it, so an admin picked the actions, saw them in the\n// drawer, saved, and the field silently never left the browser. The reported\n// symptom was \"the admin screen does nothing\", and the whole gap was that this\n// key was absent from a destructure and a JSON body.\n//\n// On the empty case, which is the dangerous one: an allow-list of [] would mean\n// \"block every action\". Both ends already guard it — the controller stores nil\n// when the list is empty, and allowedActionsOf() treats an empty array as \"no\n// allow-list\" — so the admin form's default of [] round-trips as \"unset\" rather\n// than as a total lockout. The default here is undefined for programmatic\n// callers that omit the key entirely; it is not load-bearing, and the guard\n// that matters is on the other two layers.\n// primaryAction / appliesTo (REQ-20261021-05) follow allowedActions' convention:\n// undefined is left out of the JSON, so the server keeps what it has stored.\nexport async function createModuleActionRule({ module, name, description = '', conditions = [], blockedActions = [], disabledActions = [], allowedActions = undefined, primaryAction = undefined, appliesTo = undefined, isActive = true }) {\n return fetchJsonWithAuth(AUTH_URL, MODULE_ACTION_RULES_PATH, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ module, name, description, conditions, blockedActions, disabledActions, allowedActions, primaryAction, appliesTo, isActive }),\n });\n}\n\nexport async function updateModuleActionRule(id, { name, description = '', conditions = [], blockedActions = [], disabledActions = [], allowedActions = undefined, primaryAction = undefined, appliesTo = undefined, isActive = true }) {\n return fetchJsonWithAuth(AUTH_URL, `${MODULE_ACTION_RULES_PATH}/${id}`, {\n method: 'PUT',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ name, description, conditions, blockedActions, disabledActions, allowedActions, primaryAction, appliesTo, isActive }),\n });\n}\n\nexport async function deleteModuleActionRule(id) {\n return fetchJsonWithAuth(AUTH_URL, `${MODULE_ACTION_RULES_PATH}/${id}`, { method: 'DELETE' });\n}\n\n\nexport async function getRoleOnboardingTabs(role, module = 'onboarding') {\n const params = new URLSearchParams({ module, configType: 'tabs', userId: '0', roleId: String(getRoleId(role)) });\n const json = await fetchJsonWithAuth(AUTH_URL, `${FIELD_CONFIG_PATH}?${params}`);\n return json.data ?? json;\n}\n\nexport async function saveRoleOnboardingTabs(role, onboardingTabs, module = 'onboarding') {\n return fetchJsonWithAuth(AUTH_URL, `${FIELD_CONFIG_PATH}/role`, {\n method: 'PUT', body: JSON.stringify({ module, roleId: getRoleId(role), configType: 'tabs', onboardingTabs }),\n });\n}\n\nexport async function getModuleTabConfig(module) {\n const json=await fetchJsonWithAuth(AUTH_URL,`/admin/module-tabs?module=${encodeURIComponent(module)}`);\n return json?.data ?? json ?? {};\n}\nexport async function saveModuleTabConfig(config) {\n return fetchJsonWithAuth(AUTH_URL,'/admin/module-tabs',{method:'PUT',headers:{'Content-Type':'application/json'},body:JSON.stringify(config)});\n}\n","// How a result row opens the record's detail view.\n//\n// Same vocabulary as the search form's action button (`actionButtonOpenAs` /\n// `OPEN_AS_OPTIONS` in searchBuilder/actionButtons.js) so an admin only learns\n// one set of words:\n//\n// self full route swap to /<module>/detailview/:id — the browser default,\n// and what every list did before this existed.\n// newTab the detail page in a new browser tab.\n// popup a Modal over the search page (/popup/<module>-detail/:id with a\n// `background` location) — the search stays mounted, so typed filters\n// survive. THE DEFAULT for the Sourcing search results.\n//\n// Options are defined inline (not imported from actionButtons.js) to avoid an\n// import cycle: services/detailDefaults.js imports this module.\nexport const DETAIL_VIEW_MODE_OPTIONS = [\n { value: 'self', label: 'Same page' },\n { value: 'newTab', label: 'New tab' },\n { value: 'popup', label: 'Popup' },\n];\n\nexport const DETAIL_VIEW_MODE_VALUES = DETAIL_VIEW_MODE_OPTIONS.map((o) => o.value);\n\n// Accepts any casing / spelling the config might carry (\"popUp\", \"POPUP\", \"\") —\n// anything unrecognised (including empty/undefined) resolves to 'popup', the\n// default. Only an explicit 'self' opts out of interception.\nexport function normalizeDetailViewMode(mode) {\n return { self: 'self', newtab: 'newTab', popup: 'popup' }[String(mode ?? '').trim().toLowerCase()] || 'popup';\n}\n\n// Route the popup mode navigates to. The host app registers exactly this path\n// (App.jsx, inside the `{background && <Routes>}` block). Fixed rather than\n// derived from moduleName: the search component runs as moduleName=\"candidates\"\n// (plural), and interpolating that produced \"/popup/candidates-detail/:id\",\n// which matched no route and silently rendered nothing.\nexport const DETAIL_VIEW_POPUP_PATH = '/popup/candidate-detail';\n\n// `href` is an already-resolved internal path, e.g. \"/candidates/detailview/<id>\"\n// (optionally with a query string / hash). Returns true when it has taken over\n// navigation; false means \"not handled — let the normal <Link>/navigate proceed\"\n// (which is the 'self' case).\n//\n// `location` is optional — the page to return to when the popup closes. When\n// omitted it is taken from window.location, so callers do not need useLocation().\nexport function runDetailViewOpen(mode, { href, navigate, location } = {}) {\n if (!href) return false;\n const resolved = normalizeDetailViewMode(mode);\n\n if (resolved === 'self') return false;\n\n if (resolved === 'newTab') {\n window.open(href, '_blank', 'noopener');\n return true;\n }\n\n // popup\n const str = String(href);\n const id = (str.split('/detailview/')[1] ?? str.split('/detail-view/')[1])?.split(/[/?#]/)[0];\n if (!id || typeof navigate !== 'function') return false;\n const background = location\n || (typeof window !== 'undefined'\n ? {\n pathname: window.location.pathname,\n search: window.location.search,\n hash: window.location.hash,\n }\n : undefined);\n navigate(`${DETAIL_VIEW_POPUP_PATH}/${id}`, { state: { background } });\n return true;\n}\n","// Central source-of-truth for detail-view DISPLAY defaults.\n//\n// These values used to be hard-coded inside components/detail/fileUtils.js and\n// components/detail/FieldValue.jsx. They now live here, are seeded with the same\n// built-in defaults, and are overridable from the admin page\n// (Admin → Detail Groups → Display Defaults), which persists them via\n// GET/POST /admin/detail-defaults.\n//\n// This is a plain module (not a React component / context) so fileUtils.js — a\n// non-component helper — can read it synchronously. Consumers read getDefaults()\n// at render time; loadDetailDefaults() fetches the saved values once and updates\n// the store (falling back to the built-ins on any failure).\n\nimport { getDetailDefaults as fetchDetailDefaults } from './adminApi';\nimport { DETAIL_VIEW_MODE_VALUES } from '../components/detailViewMode';\n\n// Built-in defaults — exactly the previous hard-coded behaviour. S3 base still\n// honours VITE_S3_BASE_URL as the env-level seed; the admin value overrides it.\nexport const BUILT_IN_DEFAULTS = Object.freeze({\n s3BaseUrl: (\n import.meta.env?.VITE_S3_BASE_URL ||\n 'https://zinnext-devlopment-ap-south-1.s3.ap-south-1.amazonaws.com'\n ).replace(/\\/+$/, ''),\n // A pure CALENDAR date — a date of birth, an expiry. No time, and no zone\n // suffix: stamping a clock on a birthday claims precision it does not have.\n dateFormat: 'DD MMM YYYY',\n // An INSTANT — created/updated stamps, interview slots. Carries the time and,\n // unless switched off below, the zone it is being shown in. Without the zone\n // a timestamp is ambiguous the moment two people in different countries read\n // it.\n dateTimeFormat: 'MMM DD, YYYY | hh:mm A',\n showTimeZoneLabel: true,\n // The tenant's clock. EMPTY means \"use the viewer's browser zone\", which is\n // exactly the behaviour before this setting existed — so nothing changes for\n // a tenant that never sets it. See services/timezone.js.\n timeZone: '',\n // Short labels for zones (\"Asia/Kolkata\" → \"IST\"). Abbreviations are NOT\n // valid IANA identifiers and are dangerously ambiguous as inputs, so they\n // exist only as display labels here.\n timeZoneAliases: {},\n // Which per-region rule profile form groups apply (\"US\"/\"UK\"/\"IND\"/'' for\n // the default). Carries no logic — it is a KEY into group.regionRules, which\n // is what lets a new market be added as config rather than as code.\n region: '',\n booleanTrueLabel: 'Yes',\n booleanFalseLabel: 'No',\n emptyPlaceholder: '-',\n // Per-render-type empty texts. The single `emptyPlaceholder` above could only\n // ever say one thing (\"-\"), which cannot distinguish \"no work experience\" from\n // \"no document\" and reads as a rendering fault rather than as information.\n // Built-in per-type defaults live in components/detail/emptyText.js; anything\n // set here overrides them, and `default` covers every unlisted type.\n emptyTexts: {},\n separator: ' - ',\n documentNameOrder: ['name', 'documentName', 'uploadName', 'uploadedFileName', 'uniqueName'],\n // Common phone-number format — one place, applied everywhere (forms + detail),\n // exactly like `dateFormat`. Groups of digit counts separated by a literal\n // separator: \"3-3-4\" → 999-878-3413 (total 10 digits). Change it here (or in\n // Admin → Display Defaults) and every phone field re-formats to match.\n phoneFormat: '3-3-4',\n // LAST-RESORT country code, used only when the record itself carries none\n // (see components/detail/phoneDisplay.js). Deliberately EMPTY: a tenant that\n // wants every unqualified number stamped \"+1\" sets it in Admin → Display\n // Defaults, but nothing invents a country for a record that never stated one\n // — that is exactly how every candidate ended up displayed as \"+1\".\n phoneCountryCode: '',\n // How a candidate row in the Sourcing search results opens the detail view:\n // 'popup' (a modal over the search — the default, so typed search filters\n // survive) | 'self' (full route swap) | 'newTab'. Same vocabulary as\n // actionButtonOpenAs; see components/detailViewMode.js. This is the tenant\n // FALLBACK — a per-search-form `detailViewOpenMode` wins over it. An admin\n // sets it in Admin > Detail Groups > Display Defaults.\n candidateDetailViewMode: 'popup',\n});\n\nlet current = { ...BUILT_IN_DEFAULTS };\nlet loadPromise = null;\n\n// getDefaults returns the live defaults (built-ins until loadDetailDefaults runs).\nexport function getDefaults() {\n return current;\n}\n\n// sanitize keeps only the keys that carry a real value, so a partial/empty saved\n// config never blanks out a built-in.\nfunction sanitize(d) {\n if (!d || typeof d !== 'object') return {};\n const out = {};\n if (d.s3BaseUrl) out.s3BaseUrl = String(d.s3BaseUrl).replace(/\\/+$/, '');\n if (d.dateFormat) out.dateFormat = d.dateFormat;\n if (d.dateTimeFormat) out.dateTimeFormat = d.dateTimeFormat;\n // A saved `false` is a real setting (\"never print the zone\"), so the key is\n // honoured whenever it is present as a boolean rather than only when truthy.\n if (typeof d.showTimeZoneLabel === 'boolean') out.showTimeZoneLabel = d.showTimeZoneLabel;\n // '' is meaningful (fall back to the browser zone), so any string is honoured.\n if (typeof d.timeZone === 'string') out.timeZone = d.timeZone.trim();\n // '' is meaningful: \"use each group's own defaults, no region profile\".\n if (typeof d.region === 'string') out.region = d.region.trim();\n if (d.timeZoneAliases && typeof d.timeZoneAliases === 'object' && !Array.isArray(d.timeZoneAliases)) {\n out.timeZoneAliases = { ...current.timeZoneAliases, ...d.timeZoneAliases };\n }\n if (d.booleanTrueLabel) out.booleanTrueLabel = d.booleanTrueLabel;\n if (d.booleanFalseLabel) out.booleanFalseLabel = d.booleanFalseLabel;\n if (d.emptyPlaceholder) out.emptyPlaceholder = d.emptyPlaceholder;\n // Objects merge key-wise rather than replacing wholesale, so configuring one\n // render type does not blank out the others.\n if (d.emptyTexts && typeof d.emptyTexts === 'object' && !Array.isArray(d.emptyTexts)) {\n const texts = {};\n Object.entries(d.emptyTexts).forEach(([key, value]) => {\n if (typeof value === 'string' && value.trim() !== '') texts[key] = value.trim();\n });\n if (Object.keys(texts).length) out.emptyTexts = { ...current.emptyTexts, ...texts };\n }\n if (typeof d.separator === 'string' && d.separator !== '') out.separator = d.separator;\n if (typeof d.phoneFormat === 'string' && d.phoneFormat.trim() !== '') out.phoneFormat = d.phoneFormat.trim();\n // Unlike the others, an EMPTY country code is a meaningful setting (\"stamp\n // nothing on a record that stated no country\"), so '' is honoured instead of\n // being treated as \"unset, keep the built-in\".\n if (typeof d.phoneCountryCode === 'string') out.phoneCountryCode = d.phoneCountryCode.trim();\n // A saved empty string is meaningful here (\"show no code at all\"), so unlike\n // the others this key is accepted whenever it is present as a string.\n if (typeof d.phoneCountryCode === 'string') out.phoneCountryCode = d.phoneCountryCode.trim();\n if (Array.isArray(d.documentNameOrder) && d.documentNameOrder.length) out.documentNameOrder = d.documentNameOrder;\n // Only a recognised value (self | newTab | popup) overrides the built-in;\n // anything else — empty, or a stale 'redirect' from an earlier build — is\n // ignored, so the store keeps the 'popup' default.\n if (DETAIL_VIEW_MODE_VALUES.includes(d.candidateDetailViewMode)) {\n out.candidateDetailViewMode = d.candidateDetailViewMode;\n }\n // Per-module format for FORM date pickers ({ candidates: 'MM/DD/YYYY' }).\n // Replaced wholesale — it is one admin-edited map, and {} is how it is cleared.\n if (d.formDateFormats && typeof d.formDateFormats === 'object' && !Array.isArray(d.formDateFormats)) {\n const formats = {};\n Object.entries(d.formDateFormats).forEach(([module, format]) => {\n if (typeof format === 'string' && format.trim() !== '') formats[module] = format.trim();\n });\n out.formDateFormats = formats;\n }\n return out;\n}\n\n// ── Phone number formatting (common, config-driven) ──────────────────────────\n// The format string is groups of digit counts joined by a literal separator,\n// e.g. \"3-3-4\" → [3,3,4] joined by \"-\". parsePhoneFormat returns { groups, sep,\n// total } so both the formatter and the length validation share one definition.\nexport function parsePhoneFormat(format = getPhoneFormat()) {\n const groups = (String(format).match(/\\d+/g) ?? ['3', '3', '4']).map(Number).filter((n) => n > 0);\n const sep = (String(format).match(/\\D+/)?.[0]) ?? '-';\n const safeGroups = groups.length ? groups : [3, 3, 4];\n return { groups: safeGroups, sep, total: safeGroups.reduce((a, b) => a + b, 0) };\n}\n\n// Live phone format from the same singleton the detail defaults use.\nexport function getPhoneFormat() {\n return current.phoneFormat || BUILT_IN_DEFAULTS.phoneFormat;\n}\n\n// The tenant-wide fallback country code — see BUILT_IN_DEFAULTS for why it is\n// empty by default. Consumed by components/detail/phoneDisplay.js as the LAST\n// resort, after the record's own code.\nexport function getPhoneCountryCode() {\n return current.phoneCountryCode ?? BUILT_IN_DEFAULTS.phoneCountryCode;\n}\n\n// Strips everything but digits, capped at the configured total (default 10).\nexport function phoneDigits(value, format = getPhoneFormat()) {\n const { total } = parsePhoneFormat(format);\n return String(value ?? '').replace(/\\D/g, '').slice(0, total);\n}\n\n// formatPhone turns any input into the configured mask as the user types:\n// \"9998783413\" → \"999-878-3413\". Partial input formats progressively\n// (\"99987\" → \"999-87\"); non-digits are ignored.\nexport function formatPhone(value, format = getPhoneFormat()) {\n const { groups, sep } = parsePhoneFormat(format);\n const digits = phoneDigits(value, format);\n if (!digits) return '';\n const chunks = [];\n let i = 0;\n for (const size of groups) {\n if (i >= digits.length) break;\n chunks.push(digits.slice(i, i + size));\n i += size;\n }\n return chunks.join(sep);\n}\n\n// applyDefaults merges a (partial) config over the current store immediately —\n// used by the admin page right after a successful save so the change is live\n// without a reload.\nexport function applyDefaults(partial) {\n const clean = sanitize(partial);\n Object.keys(clean).forEach((key) => configuredKeys.add(key));\n current = { ...current, ...clean };\n return current;\n}\n\n// Keys a tenant has actually SAVED, as opposed to built-ins. getDefaults()\n// cannot tell the two apart, and some consumers must: see\n// getConfiguredDateFormat.\nconst configuredKeys = new Set();\n\n// getConfiguredDateFormat — the tenant's saved `dateFormat`, or undefined when\n// the tenant never set one.\n//\n// Date PICKERS and the LIST VIEW read this instead of getDefaults().dateFormat\n// on purpose. Their behaviour predates the display defaults (antd's picker\n// default and the list's own layout), and the built-in 'DD MMM YYYY' was only\n// ever the DETAIL view's default. Falling back to it here would silently\n// re-format every picker and list column of every tenant that never asked for\n// it. So: a tenant that saves a date format (Admin → Display Defaults) gets it\n// everywhere; a tenant that does not sees exactly what it saw before.\nexport function getConfiguredDateFormat() {\n return configuredKeys.has('dateFormat') ? current.dateFormat : undefined;\n}\n\n// getFormDateFormat — the format a module's Add/Edit form DATE PICKERS use, from\n// Admin → Display Defaults → formDateFormats, or undefined when that module has\n// none (the caller then falls back to getConfiguredDateFormat). Module names\n// arrive as either \"candidate\" or \"candidates\", so both spellings match.\nexport function getFormDateFormat(moduleName) {\n const formats = current.formDateFormats;\n const key = String(moduleName ?? '').trim().toLowerCase();\n if (!formats || !key) return undefined;\n const base = key.endsWith('s') ? key.slice(0, -1) : key;\n const match = Object.keys(formats).find((module) => {\n const candidate = module.trim().toLowerCase();\n return candidate === key || candidate === base || candidate === `${base}s`;\n });\n return match ? formats[match] : undefined;\n}\n\n// loadDetailDefaults fetches the saved defaults once (cached). Safe to call from\n// anywhere — failures silently keep the built-ins. Pass force=true to refetch.\nexport function loadDetailDefaults(force = false) {\n if (loadPromise && !force) return loadPromise;\n // Promise.resolve().then(...) so a synchronous throw from fetchDetailDefaults\n // (e.g. a test that partially mocks adminApi and leaves it undefined) lands in\n // the .catch below and keeps the built-ins, exactly like a network failure.\n loadPromise = Promise.resolve()\n .then(() => fetchDetailDefaults())\n .then((d) => applyDefaults(d))\n .catch(() => current);\n return loadPromise;\n}\n","// ─────────────────────────────────────────────────────────────────────────\n// timezone — the application's clock.\n//\n// THE REQUIREMENT\n// \"We work with multiple locations, so we need to see the time based on\n// location. Set up a common time setup like GST, UTC, IST — list all the time\n// zones, and if I select the time zone the entire application has to work on\n// that time zone. It won't reflect the system time.\"\n//\n// So: one tenant-wide zone, chosen in admin, used for RENDERING every\n// date-time AND for interpreting what the user types — never the browser's.\n//\n// WHERE THE SETTING LIVES\n// detailViewDefaults.timeZone, alongside dateFormat / phoneFormat / the empty\n// texts. That store already exists, is already tenant-scoped, and is already\n// loaded once at startup — a second settings store would only create a second\n// thing to keep in sync.\n//\n// THE ZONE LIST IS NOT HARDCODED\n// It comes from Intl.supportedValuesOf('timeZone') — every IANA zone the\n// browser knows. The abbreviations the requirement names (IST, GST, UTC) are\n// not IANA identifiers, so they are provided as an admin-editable ALIAS map\n// (detailViewDefaults.timeZoneAliases) that labels the real zones. Nothing in\n// this file enumerates a country.\n//\n// ── THE CALENDAR-DATE TRAP (the important part) ──────────────────────────\n// A date of birth, a passport expiry, an education start date are CALENDAR\n// dates: \"7 July 2026\" means the same thing in Dubai and in New York. Passing\n// one through a timezone conversion shifts it by a day for half the world's\n// zones — silently corrupting data that was never about an instant in time.\n//\n// So conversion is OPT-IN, never blanket: only `datetime`/`time` fields, or a\n// field explicitly marked `tzAware`, are converted. Plain `date` fields keep\n// their calendar semantics. See shouldConvertToZone below.\n// ─────────────────────────────────────────────────────────────────────────\nimport dayjs from 'dayjs';\nimport utc from 'dayjs/plugin/utc';\nimport timezonePlugin from 'dayjs/plugin/timezone';\nimport { getDefaults } from './detailDefaults';\n\ndayjs.extend(utc);\ndayjs.extend(timezonePlugin);\n\n// The browser's own zone, used when the tenant has not chosen one. Resolved\n// lazily and cached: dayjs.tz.guess() reads Intl on every call.\nlet guessed = null;\nfunction browserZone() {\n if (guessed === null) {\n try {\n guessed = dayjs.tz.guess() || 'UTC';\n } catch {\n guessed = 'UTC';\n }\n }\n return guessed;\n}\n\n/**\n * isValidZone — is this a zone we are willing to run the application on?\n *\n * Deliberately STRICTER than Intl. ICU accepts bare abbreviations, but does so\n * inconsistently and with traps that would be invisible until a DST boundary:\n *\n * 'IST' → Asia/Calcutta (yet IST is equally Irish and Israel Standard Time)\n * 'EST' → America/Panama (a fixed -05:00 that NEVER shifts to EDT, so a\n * tenant picking \"EST\" would silently be an hour\n * wrong for two-thirds of the year)\n * 'GST' → rejected entirely\n *\n * So an accepted zone must be a real IANA identifier — \"Area/Location\", or the\n * one legitimate bare name, UTC. Abbreviations remain available to users as\n * LABELS through the alias map, where they are unambiguous because they point\n * at a specific IANA zone.\n */\nexport function isValidZone(zone) {\n const name = String(zone ?? '').trim();\n if (!name) return false;\n if (name !== 'UTC' && !name.includes('/')) return false;\n try {\n new Intl.DateTimeFormat('en-US', { timeZone: name });\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * getAppTimeZone — the zone everything renders and is interpreted in.\n *\n * An unset or unknown value falls back to the browser's zone, so the app keeps\n * working exactly as it did before anyone configured this. Written so a\n * per-user override can be layered in later without touching any call site.\n */\nexport function getAppTimeZone(defaults = getDefaults()) {\n const configured = String(defaults?.timeZone ?? '').trim();\n return isValidZone(configured) ? configured : browserZone();\n}\n\n/** appNow — \"now\", in the application's zone. */\nexport function appNow(defaults) {\n return dayjs().tz(getAppTimeZone(defaults));\n}\n\n/**\n * toApp — read an instant (ISO string, Date, dayjs, epoch ms) as it appears in\n * the application's zone. Invalid input returns an invalid dayjs, so callers\n * can keep using .isValid() exactly as they do now.\n */\nexport function toApp(value, defaults) {\n const parsed = dayjs(value?.$date ?? value);\n return parsed.isValid() ? parsed.tz(getAppTimeZone(defaults)) : parsed;\n}\n\n/**\n * formatApp — the one formatter. Falls back to the tenant's configured\n * dateFormat, so changing the format still happens in exactly one place.\n */\nexport function formatApp(value, format, defaults = getDefaults()) {\n const d = toApp(value, defaults);\n if (!d.isValid()) return '';\n return d.format(format || defaults?.dateFormat || 'DD MMM YYYY');\n}\n\n/**\n * tzShortLabel — the small suffix printed after a TIME so a reader knows which\n * clock they are looking at: \"IST\", \"GST\", or the zone's own name when nobody\n * has given it a short one.\n *\n * Deliberately NOT printed after a plain calendar date. A date of birth has no\n * time and no zone; stamping one on it claims a precision the value does not\n * have.\n */\nexport function tzShortLabel(defaults = getDefaults(), at) {\n const zone = getAppTimeZone(defaults);\n const alias = aliasFor(zone, defaults);\n // A zone that changes abbreviation across the year is stored as a PAIR\n // (\"EST/EDT\"), because the table cannot know which applies. Given the instant\n // being printed we can: a timestamp reading \"12:37 AM EST/EDT\" tells the\n // reader the two things it might be and leaves them to work out which, which\n // is precisely the ambiguity the suffix exists to remove.\n if (alias && alias.includes('/')) {\n const inEffect = zoneAbbreviation(zone, at);\n if (inEffect) {\n const halves = alias.split('/').map((half) => half.trim());\n const matched = halves.find((half) => half.toUpperCase() === inEffect.toUpperCase());\n return matched || inEffect;\n }\n // No abbreviation available: the pair is still more informative than the\n // raw zone name, so it stands.\n }\n return alias || zoneAbbreviation(zone, at) || zone;\n}\n\n/**\n * zoneAbbreviation — the short name a zone actually goes by AT a given instant\n * (\"EDT\" in August, \"EST\" in January), or '' when it has no letter form.\n *\n * Intl answers this correctly including the daylight-saving rules, which is why\n * it is asked rather than a lookup table: the rules change, and a table that\n * says \"EST/EDT\" is a table admitting it does not know.\n *\n * Zones with no common abbreviation come back as an offset (\"GMT+5:30\"). Those\n * are rejected here so the caller falls through to its configured alias — India\n * is written \"IST\", never \"GMT+5:30\".\n */\nexport function zoneAbbreviation(zone, at) {\n try {\n const when = at === undefined ? new Date() : new Date(dayjs(at?.$date ?? at).valueOf());\n if (Number.isNaN(when.valueOf())) return '';\n const parts = new Intl.DateTimeFormat('en-US', {\n timeZone: zone,\n timeZoneName: 'short',\n }).formatToParts(when);\n const name = parts.find((part) => part.type === 'timeZoneName')?.value ?? '';\n // Letters only. \"GMT+5:30\" is an offset wearing a name badge.\n return /^[A-Za-z]+$/.test(name) ? name : '';\n } catch {\n // An unknown zone throws rather than guessing. The caller has a fallback.\n return '';\n }\n}\n\n/**\n * formatAppDateTime — an INSTANT, in the tenant's zone, with the zone named.\n *\n * \"Aug 06, 2026 | 07:03 PM IST\"\n *\n * The format and whether to show the zone are both config, so a tenant can\n * change either without a deploy. The zone suffix is what turns an ambiguous\n * timestamp into a fact: without it, a team spread across countries cannot tell\n * whether 07:03 PM is theirs or someone else's.\n */\nexport function formatAppDateTime(value, defaults = getDefaults()) {\n const shown = formatApp(value, defaults?.dateTimeFormat || 'MMM DD, YYYY | hh:mm A', defaults);\n if (!shown) return '';\n if (defaults?.showTimeZoneLabel === false) return shown;\n // The label is resolved FOR THIS INSTANT, so a summer timestamp reads \"EDT\"\n // and a winter one \"EST\" — rather than both reading \"EST/EDT\".\n const label = tzShortLabel(defaults, value);\n return label ? `${shown} ${label}` : shown;\n}\n\n/**\n * shouldConvertToZone — may this field's value be moved between zones?\n *\n * FALSE for plain calendar dates. This is the guard described in the header,\n * and it is deliberately conservative: a field must SAY it carries an instant\n * (type datetime/time) or opt in with `tzAware`, otherwise it is left alone.\n * Being wrong in this direction shows a time in the wrong zone; being wrong in\n * the other direction changes a stored date by a day.\n */\nexport function shouldConvertToZone(field) {\n if (!field) return false;\n if (field.tzAware === true) return true;\n if (field.tzAware === false) return false;\n const type = String(field.type ?? '').toLowerCase();\n return type === 'datetime' || type === 'time' || type === 'datetime-local';\n}\n\n/**\n * fromAppInput — a picker value the user entered MEANING the application's\n * zone, converted to the correct absolute instant for storage.\n *\n * A DatePicker hands back a dayjs in the BROWSER's zone. If the tenant zone is\n * Asia/Dubai and the user picks 09:00, they mean 09:00 in Dubai — storing the\n * browser's 09:00 would be a different moment entirely.\n */\nexport function fromAppInput(value, defaults) {\n // An EMPTY input is not a moment, and must never become one.\n //\n // dayjs(undefined) returns the CURRENT time and reports isValid() === true —\n // so without this guard an untouched picker was serialised as \"now\". On the\n // submission form that wrote the moment of saving into interviewAvailability\n // .startTime AND .endTime, giving every submission an interview slot the\n // recruiter never entered, with both ends identical. dayjs(null) and\n // dayjs('') are correctly invalid; only `undefined` has this behaviour, which\n // is exactly the shape a registered-but-empty antd picker hands back.\n if (value === undefined || value === null || value === '') return null;\n const d = dayjs(value);\n if (!d.isValid()) return null;\n const zone = getAppTimeZone(defaults);\n // Re-interpret the WALL-CLOCK reading in the target zone, rather than\n // converting the instant (which would keep the wrong moment and merely\n // relabel it).\n return dayjs.tz(d.format('YYYY-MM-DDTHH:mm:ss'), zone);\n}\n\n/**\n * zoneOffsetLabel — \"UTC+05:30\" for a zone, at the current moment.\n * Computed rather than tabulated, so it stays correct across DST.\n */\nexport function zoneOffsetLabel(zone = getAppTimeZone()) {\n try {\n const minutes = dayjs().tz(zone).utcOffset();\n const sign = minutes < 0 ? '-' : '+';\n const abs = Math.abs(minutes);\n const hh = String(Math.floor(abs / 60)).padStart(2, '0');\n const mm = String(abs % 60).padStart(2, '0');\n return `UTC${sign}${hh}:${mm}`;\n } catch {\n return '';\n }\n}\n\n/**\n * tzLabel — what a viewer sees next to a time so they know WHICH zone they are\n * reading: \"IST (UTC+05:30)\" when an alias names it, else\n * \"Asia/Kolkata (UTC+05:30)\".\n */\nexport function tzLabel(defaults = getDefaults()) {\n const zone = getAppTimeZone(defaults);\n const alias = aliasFor(zone, defaults);\n return `${alias || zone} (${zoneOffsetLabel(zone)})`;\n}\n\n// Built-in aliases covering the abbreviations the requirement names, plus the\n// common business zones. Admin-editable via detailViewDefaults.timeZoneAliases;\n// anything configured there wins, and unknown zones simply have no alias.\nexport const BUILT_IN_TZ_ALIASES = Object.freeze({\n UTC: 'UTC',\n 'Asia/Kolkata': 'IST',\n 'Asia/Calcutta': 'IST',\n 'Asia/Dubai': 'GST',\n 'America/New_York': 'EST/EDT',\n 'America/Chicago': 'CST/CDT',\n 'America/Denver': 'MST/MDT',\n 'America/Los_Angeles': 'PST/PDT',\n 'Europe/London': 'GMT/BST',\n 'Europe/Berlin': 'CET/CEST',\n 'Asia/Singapore': 'SGT',\n 'Asia/Tokyo': 'JST',\n 'Australia/Sydney': 'AEST/AEDT',\n});\n\n/** aliasFor — the short name for a zone, config first. */\nexport function aliasFor(zone, defaults = getDefaults()) {\n const configured = defaults?.timeZoneAliases ?? {};\n return configured[zone] ?? BUILT_IN_TZ_ALIASES[zone] ?? '';\n}\n\n/**\n * listTimeZones — every zone the runtime knows, labelled with its alias and\n * current offset, sorted by offset then name so the picker reads like a map\n * rather than an alphabetical wall.\n *\n * Returns [{ value, label, alias, offsetLabel, offsetMinutes }].\n */\nexport function listTimeZones(defaults = getDefaults()) {\n let enumerated = [];\n try {\n enumerated = Intl.supportedValuesOf('timeZone') ?? [];\n } catch {\n // Older runtimes cannot enumerate at all; the union below still yields the\n // named zones, so the picker is never empty.\n enumerated = [];\n }\n\n // UNION, not just the enumerated list. ICU builds disagree about which name\n // is canonical: this runtime enumerates \"Asia/Calcutta\" and omits both\n // \"Asia/Kolkata\" and \"UTC\", yet accepts all three. Listing only what is\n // enumerated would therefore hide IST and UTC — two of the three zones the\n // requirement names by hand — on some machines and not others.\n // Everything is validated, so an alias for a zone this runtime does not know\n // is dropped rather than offered and then failing at format time.\n const named = ['UTC', ...Object.keys(BUILT_IN_TZ_ALIASES), ...Object.keys(defaults?.timeZoneAliases ?? {})];\n const zones = [...new Set([...named, ...enumerated])].filter(isValidZone);\n\n return zones\n .map((zone) => {\n let offsetMinutes = 0;\n try {\n offsetMinutes = dayjs().tz(zone).utcOffset();\n } catch {\n return null;\n }\n const alias = aliasFor(zone, defaults);\n const offsetLabel = zoneOffsetLabel(zone);\n return {\n value: zone,\n alias,\n offsetLabel,\n offsetMinutes,\n label: `${alias ? `${alias} — ` : ''}${zone} (${offsetLabel})`,\n };\n })\n .filter(Boolean)\n .sort((a, b) => a.offsetMinutes - b.offsetMinutes || a.value.localeCompare(b.value));\n}\n","// Dot-notation module names: \"job.client.company\" means \"fetch the `job`\n// module, then display the data found at `client.company` inside each record\".\n// Only the segment before the first dot is a real backend module — every API\n// call (module-data-list, field-config, permissions) must use it, while the\n// remaining segments are resolved client-side against each fetched record.\n\nexport function parseModulePath(moduleName) {\n const raw = String(moduleName ?? '').trim();\n if (!raw) return { baseModule: '', nestedPath: '' };\n\n const [baseModule, ...rest] = raw.split('.');\n return {\n baseModule: baseModule.trim(),\n nestedPath: rest.map((part) => part.trim()).filter(Boolean).join('.'),\n };\n}\n\nexport function getBaseModuleName(moduleName) {\n return parseModulePath(moduleName).baseModule;\n}\n\nexport function getValueAtPath(source, path) {\n return String(path ?? '')\n .split('.')\n .filter(Boolean)\n .reduce((value, key) => (value == null ? undefined : value[key]), source);\n}\n","import { ensureToken, fetchJsonWithAuth } from './authApi';\nimport { AUTH_URL } from './apiConfig';\n\n// ── Common Module Documents API ───────────────────────────────────────────────\n// Module-agnostic document registry (Auth gateway \"documents\" collection, files\n// in S3). Every module's Add Form registers its uploads here AFTER the module\n// record is created — the module's Create API generates the reference id\n// (jobId / candidateId / submissionId), and that id is what links each document\n// row back to its record.\n\n// Strips the transport decorations collectFileParts may leave on a part key —\n// the moduleWrites routing prefix (\"__mw__<module>__\") and an addRow row-index\n// suffix (\"[0]\") — so the registered fieldName is the clean form-field key\n// (e.g. \"resume\", \"jobDescription\", \"offerLetter\").\nfunction cleanFieldName(formKey) {\n return String(formKey ?? '')\n .replace(/^__mw__.*?__/, '')\n .replace(/\\[\\d+\\]$/, '')\n .trim() || 'file';\n}\n\n/**\n * uploadModuleDocuments — registers uploaded files against a created module\n * record. Common across ALL modules: pass the module name and the record id\n * its Create API returned.\n *\n * @param moduleName the module key (e.g. \"jobs\", \"candidates\", \"submissions\")\n * @param refId the created record's _id (jobId / candidateId / …)\n * @param fileParts [{ formKey, file }] — the shape collectFileParts returns;\n * formKey is the form field the file was uploaded against\n * @param metadata optional { [fieldName]: {...} } extra metadata per field\n */\nexport async function uploadModuleDocuments(moduleName, refId, fileParts = [], metadata = {}) {\n if (!moduleName) throw new Error('moduleName is required to upload documents');\n if (!refId) throw new Error('refId (created record id) is required to upload documents');\n if (!fileParts.length) return { data: [], total: 0 };\n\n const token = await ensureToken();\n\n // NOTE: do NOT set Content-Type — the browser must add the multipart\n // boundary itself (same convention as createModuleRecord).\n const formData = new FormData();\n fileParts.forEach(({ formKey, file }) => {\n const fileName = file?.name ?? undefined;\n formData.append(cleanFieldName(formKey), file, fileName);\n });\n if (metadata && Object.keys(metadata).length > 0) {\n formData.append('metadata', JSON.stringify(metadata));\n }\n\n const params = new URLSearchParams({ module: moduleName, refId: String(refId) });\n let res;\n try {\n res = await fetch(`${AUTH_URL}/documents/upload?${params.toString()}`, {\n method: 'POST',\n headers: { Authorization: `Bearer ${token}` },\n body: formData,\n });\n } catch (netErr) {\n const error = new Error('Unable to connect to the server. Please check your network connection.');\n error.originalError = netErr;\n throw error;\n }\n\n const contentType = res.headers.get('content-type') || '';\n const data = contentType.includes('application/json') ? await res.json() : await res.text();\n if (!res.ok) {\n const errorMsg = (typeof data === 'object' ? (data?.error || data?.message) : data) || `Server returned status ${res.status}`;\n const error = new Error(errorMsg);\n error.status = res.status;\n error.data = data;\n throw error;\n }\n return data?.data ?? data;\n}\n\n/**\n * getModuleDocuments — lists a module record's documents (newest first), each\n * carrying a 24h presigned S3 download URL as `fileUrl`.\n *\n * @param moduleName the module key (e.g. \"jobs\", \"candidates\", \"submissions\")\n * @param refId the module record's _id\n * @param fieldName optional — only documents uploaded against this form field\n */\nexport async function getModuleDocuments(moduleName, refId, fieldName = '') {\n if (!moduleName) throw new Error('moduleName is required to fetch documents');\n if (!refId) throw new Error('refId is required to fetch documents');\n const params = new URLSearchParams({ module: moduleName, refId: String(refId) });\n if (fieldName) params.set('fieldName', fieldName);\n const json = await fetchJsonWithAuth(AUTH_URL, `/documents?${params.toString()}`);\n const payload = json?.data ?? json ?? {};\n return {\n data: Array.isArray(payload?.data) ? payload.data : (Array.isArray(payload) ? payload : []),\n total: payload?.total ?? 0,\n };\n}\n\n/**\n * deleteModuleDocument — soft-delete one registry document.\n *\n * Needed because removing a document ROW from a record left the registry entry\n * behind, and EditFormV1 rebuilds an empty repeatable group FROM the registry.\n * The row therefore came back on the next load, which reads as \"the delete did\n * not save\". The registry has to be told, or it will keep resurrecting the file.\n *\n * Resolves to false rather than throwing when the id is missing or the call\n * fails: a registry that will not accept the delete must not block the record's\n * own update, which is the change the user actually asked for. The caller\n * decides whether to warn.\n */\nexport async function deleteModuleDocument(documentId) {\n if (!documentId) return false;\n try {\n await fetchJsonWithAuth(AUTH_URL, `/documents/${encodeURIComponent(String(documentId))}`, {\n method: 'DELETE',\n });\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * generateModuleId — generates a valid 24-character hexadecimal MongoDB ObjectID\n * string on the client so documents can be uploaded and stored against `moduleId`\n * BEFORE the module record itself is created in the module collection.\n */\nexport function generateModuleId() {\n const timestampHex = Math.floor(Date.now() / 1000)\n .toString(16)\n .padStart(8, '0')\n .slice(0, 8);\n const randomBytes = new Uint8Array(8);\n if (typeof crypto !== 'undefined' && typeof crypto.getRandomValues === 'function') {\n crypto.getRandomValues(randomBytes);\n } else {\n for (let i = 0; i < randomBytes.length; i += 1) {\n randomBytes[i] = Math.floor(Math.random() * 256);\n }\n }\n const randomHex = Array.from(randomBytes, (b) => b.toString(16).padStart(2, '0')).join('');\n return `${timestampHex}${randomHex}`;\n}\n\n/**\n * extractDocumentIds — extracts created document IDs from the `/documents/upload` response.\n */\nexport function extractDocumentIds(uploadResponse) {\n const list = Array.isArray(uploadResponse)\n ? uploadResponse\n : Array.isArray(uploadResponse?.data)\n ? uploadResponse.data\n : [];\n return list\n .map((doc) => String(doc?.id ?? doc?._id ?? '').trim())\n .filter(Boolean);\n}\n\n/**\n * rollbackModuleDocuments — compensating rollback: deletes documents created in the\n * `documents` collection if the subsequent module creation call fails.\n */\nexport async function rollbackModuleDocuments(documentIds = []) {\n const ids = Array.from(new Set((documentIds || []).map((id) => String(id || '').trim()).filter(Boolean)));\n if (ids.length === 0) return;\n\n await Promise.allSettled(\n ids.map((id) => deleteModuleDocument(id)),\n );\n}\n","// Compare exact values, so even a one-character change restores every configured rule.\nexport const isSavedValue = (field, value) => field?._savedValueValidation === true\n && Object.is(value, field.value);\n\n// A rule that always passes. It must carry a `validator`: a bare `{}` has no\n// `type`, so async-validator falls back to type \"string\" and rejects any saved\n// boolean/number with \"is not a valid undefined\" (e.g. an untouched checkbox).\nexport const NOOP_RULE = Object.freeze({ validator: () => Promise.resolve() });\n\nexport function gateSavedValueRules(rules, field, name) {\n if (!field?._savedValueValidation) return rules;\n return rules.map(rule => form => isSavedValue(field, form.getFieldValue(name))\n ? NOOP_RULE : (typeof rule === 'function' ? rule(form) : rule));\n}\n","import { isSavedValue } from './savedValueValidation';\nimport DOMPurify from 'dompurify';\n\nconst RICH_TEXT_TAGS = [\n 'p', 'br', 'strong', 'b', 'em', 'i', 'u', 's', 'ul', 'ol', 'li',\n 'blockquote', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'a', 'code', 'pre',\n];\nconst RICH_TEXT_ATTRS = ['href', 'title', 'target', 'rel'];\nconst INVISIBLE_RE = /[\\u200B-\\u200D\\u2060\\uFEFF]/g;\n// Security normalization intentionally targets ASCII control characters.\n// eslint-disable-next-line no-control-regex\nconst CONTROL_RE = /[\\u0000-\\u0008\\u000B\\u000C\\u000E-\\u001F\\u007F]/g;\nconst NAME_RE = /^[\\p{L}\\p{M}\\p{N} .'-]+$/u;\nconst PHONE_RE = /^\\+?[0-9 ()-]+$/;\nconst NUMBER_RE = /^-?(?:\\d+|\\d*\\.\\d+)$/;\n\n// The ONE definition of hostile input on the client, kept deliberately in step\n// with utils/inputsecurity/patterns.go on the server. When the two disagree the\n// user gets the worst possible experience: a form that refuses what the API\n// would have accepted, or accepts what the API then rejects.\n//\n// Split by whether the text could EVER be legitimate prose. This is an ATS:\n// job descriptions for database and DevOps roles contain \"DROP TABLE\" and\n// \"&&\", and refusing them blocks real work without closing any sink — React\n// escapes on render, and the server sends BSON values, never query strings.\n// Markup and script are refused, because those are only ever an attack.\n//\n// `plainOnly` marks a rule that applies to plain fields but not to a rich-text\n// editor, where markup is the entire point. This replaces an earlier\n// `slice(0, 3)` that depended on the ARRAY ORDER — reordering the list silently\n// changed what rich text allowed.\nconst REJECT_PATTERNS = [\n { re: /<\\s*\\/?\\s*(?:script|iframe|object|embed|svg|img|form|input|style|link|meta|base|applet|frame|frameset)\\b/i, message: 'HTML/script content is not allowed' },\n { re: /\\b(?:javascript|vbscript)\\s*:|\\bdata\\s*:\\s*text\\/html/i, message: 'Unsafe URL protocol is not allowed' },\n { re: /\\bon[a-z]+\\s*=/i, message: 'HTML event handlers are not allowed' },\n { re: /[\"']?\\$(?:where|gt|gte|lt|lte|ne|nin|regex|or|and|not|nor|expr|function|jsonSchema|accumulator)\\b/i, message: 'MongoDB operators are not allowed in input values' },\n // Refused rather than tolerated: dangerous anywhere a value becomes a\n // filename, and rare in recruiter prose. Narrower than it once was — the old\n // pattern also matched a bare \"%2f\", i.e. any URL-encoded slash.\n { re: /(?:\\.\\.[/\\\\])|(?:%2e%2e|%5c)/i, message: 'Path traversal is not allowed' },\n // Any other HTML-looking tag (\"<b>\", \"<div class=x>\", \"</span>\"). Plain\n // fields never legitimately contain markup; a text-editor field does, and is\n // sanitised through DOMPurify instead.\n { re: /<\\/?[a-zA-Z][a-zA-Z0-9]*(?:\\s[^<>]*)?>/, message: 'HTML tags are not allowed', plainOnly: true },\n];\n\n// Permitted as typed text. Kept compiled rather than deleted so the policy is\n// visible in one place, and so switching to strict-everywhere is a matter of\n// concatenating this list onto REJECT_PATTERNS.\nexport const ALLOWED_TECHNICAL_PATTERNS = [\n { re: /\\b(?:union\\s+(?:all\\s+)?select|drop\\s+table|delete\\s+from|insert\\s+into|xp_cmdshell)\\b/i, message: 'database command patterns' },\n { re: /(?:['\"]\\s*)?\\b(?:or|and)\\s+\\d+\\s*=\\s*\\d+/i, message: 'injection patterns' },\n { re: /&&|\\|\\||\\$\\(|\\$\\{|`|\\b(?:rm\\s+-rf|cat\\s+\\/etc\\/|whoami\\b)/i, message: 'command execution patterns' },\n];\n\nfunction decodeHtmlEntities(value) {\n if (typeof document === 'undefined') return value;\n const textarea = document.createElement('textarea');\n textarea.innerHTML = value;\n return textarea.value;\n}\n\nexport function canonicalizeForSecurityScan(value) {\n let result = String(value ?? '');\n for (let i = 0; i < 2; i += 1) {\n try {\n const decoded = decodeURIComponent(result);\n if (decoded === result) break;\n result = decoded;\n } catch { break; }\n }\n result = decodeHtmlEntities(result)\n .replace(/\\\\x([0-9a-f]{2})/gi, (_, hex) => String.fromCharCode(Number.parseInt(hex, 16)))\n .replace(/\\\\u([0-9a-f]{4})/gi, (_, hex) => String.fromCharCode(Number.parseInt(hex, 16)));\n return result.normalize('NFC');\n}\n\nexport function sanitizeRichText(value) {\n return DOMPurify.sanitize(String(value ?? ''), {\n ALLOWED_TAGS: RICH_TEXT_TAGS,\n ALLOWED_ATTR: RICH_TEXT_ATTRS,\n ALLOW_DATA_ATTR: false,\n FORBID_TAGS: ['script', 'style', 'iframe', 'object', 'embed', 'svg', 'img', 'form', 'input'],\n FORBID_ATTR: ['style', 'src', 'srcset'],\n });\n}\n\nfunction validationMax(field) {\n const rule = (field.validations ?? []).find((item) => item?.type === 'max');\n const configured = Number(field.validator?.maxLength ?? rule?.value ?? field.maxLength);\n if (Number.isFinite(configured) && configured > 0) return configured;\n if (field.type === 'email' || field.formatter === 'email') return 255;\n if (field.formatter === 'phone' || field.formatter === 'digits') return 32;\n if (field.formatter === 'name') return 100;\n if (field.type === 'text-editor') return 50000;\n if (field.type === 'textarea') return 5000;\n return 5000;\n}\n\nfunction isMultiline(field) {\n return field.type === 'textarea' || field.type === 'text-editor';\n}\n\nexport function normalizeSecureString(value, field = {}) {\n if (typeof value !== 'string') return value;\n if (field.type === 'text-editor') return sanitizeRichText(value.normalize('NFC'));\n\n let normalized = value.normalize('NFC')\n .replace(INVISIBLE_RE, '')\n .replace(/\\u00A0/g, ' ')\n .replace(CONTROL_RE, '');\n if (isMultiline(field)) {\n normalized = normalized.replace(/\\r\\n?/g, '\\n').replace(/[ \\t]{2,}/g, ' ').trim();\n } else {\n normalized = normalized.replace(/\\s+/g, ' ').trim();\n }\n return normalized;\n}\n\nexport function validateSecureString(value, field = {}) {\n if (isSavedValue(field, value)) field = {};\n if (typeof value !== 'string' || value === '') return null;\n const label = field.label || field.field || 'Field';\n const canonical = canonicalizeForSecurityScan(value);\n\n if (canonical.includes('\\0') || canonical.includes('\\u0000')) return `${label} contains a null byte`;\n const richText = field.type === 'text-editor';\n const attack = REJECT_PATTERNS.find(\n ({ re, plainOnly }) => (!plainOnly || !richText) && re.test(canonical),\n );\n if (attack) return `${label}: ${attack.message}`;\n\n const normalized = normalizeSecureString(value, field);\n if ([...normalized].length > validationMax(field)) return `${label} is too long`;\n if (field.formatter === 'name' && normalized && !NAME_RE.test(normalized)) {\n return `${label} allows only letters, numbers, spaces, apostrophes, hyphens and periods`;\n }\n if ((field.formatter === 'phone' || field.formatter === 'digits') && normalized && !PHONE_RE.test(normalized)) {\n return `${label} contains invalid phone characters`;\n }\n if (field.type === 'number' && normalized && !NUMBER_RE.test(normalized)) {\n return `${label} must contain only a valid number`;\n }\n if ((field.type === 'url' || field.formatter === 'url') && normalized && !/^https?:\\/\\//i.test(normalized)) {\n return `${label} must use http:// or https://`;\n }\n return null;\n}\n\nexport function securityValidationRule(field) {\n return {\n validator: (_, value) => {\n const values = Array.isArray(value) ? value : [value];\n const error = values.map((item) => validateSecureString(item, field)).find(Boolean);\n return error ? Promise.reject(new Error(error)) : Promise.resolve();\n },\n };\n}\n\nfunction policyMap(groups = []) {\n const policies = new Map();\n groups.forEach((group) => {\n (group.fields ?? []).forEach((field) => {\n if (field.type === 'file') return;\n const destination = field.payloadKey || field.field;\n if (!destination) return;\n const path = group.addRow ? `${group.payloadKey || group.name}[].${destination}` : destination;\n policies.set(path, field);\n });\n });\n return policies;\n}\n\nexport function securePayload(payload, groups = []) {\n const policies = policyMap(groups);\n const walk = (node, path = '') => {\n if (typeof node === 'string') {\n const field = policies.get(path) ?? {};\n const error = validateSecureString(node, field);\n if (error) throw new Error(error);\n return normalizeSecureString(node, field);\n }\n if (Array.isArray(node)) return node.map((item) => walk(item, `${path}[]`));\n if (node && typeof node === 'object') {\n return Object.fromEntries(Object.entries(node).map(([key, value]) => {\n if (key.startsWith('$') || key.includes('.') || key.includes('\\0')) {\n throw new Error(`Unsafe object key: ${key}`);\n }\n const childPath = path ? `${path}.${key}` : key;\n return [key, walk(value, childPath)];\n }));\n }\n return node;\n };\n return walk(payload);\n}\n","// ─────────────────────────────────────────────────────────────────────────\n// phoneDisplay — a contact number as the RECORD stores it, not as the tenant's\n// default happens to be set.\n//\n// The detail view formats every phone through one admin-configured mask\n// (detailDefaults.phoneFormat, e.g. \"3-3-4\"). That part is right and stays.\n// What was wrong is the country code: it came from a single global default, so\n// a candidate who stored +91 was displayed as \"+1 999-878-3413\" — a number that\n// does not exist, printed with total confidence.\n//\n// Resolution order, most specific first:\n// 1. a code embedded in the value itself (\"+91 9998783413\") — unambiguous\n// 2. `renderOptions.countryCodeField` — the Detail Groups admin naming the\n// sibling key that holds this record's code\n// 3. the conventional siblings (<field>CountryCode, countryCode,\n// phoneCountryCode, mobileCountryCode, …)\n// 4. the global default — ONLY when the record carries nothing, and it ships\n// empty so a missing code renders as no code instead of a wrong one.\n//\n// Nothing here knows a module or a field name: (2) is config and (3) is a\n// naming convention applied to whatever key the field itself has.\n// ─────────────────────────────────────────────────────────────────────────\n\nimport { formatPhone, getPhoneCountryCode } from '../../services/detailDefaults';\n\nconst isEmpty = (v) => v === undefined || v === null || v === '';\n\n// getPath — dotted-path read, so a configured countryCodeField may point at a\n// nested container key (\"contact.countryCode\") as well as a flat one.\nfunction getPath(source, path) {\n return String(path ?? '')\n .split('.')\n .filter(Boolean)\n .reduce((current, key) => (current == null ? undefined : current[key]), source);\n}\n\n/**\n * normalizeDialCode — \"+91\" | \"91\" | 91 → \"+91\". Anything that is not a dial\n * code (a country NAME, an empty string, a stray label) resolves to '' so it is\n * never printed in front of a number.\n */\nexport function normalizeDialCode(value) {\n const raw = String(value ?? '').trim().replace(/[\\s()-]/g, '');\n if (!raw) return '';\n const digits = raw.replace(/^\\+/, '');\n return /^\\d{1,4}$/.test(digits) ? `+${digits}` : '';\n}\n\n/**\n * countryCodeKeys — the sibling keys to probe for a phone field's own code.\n * The field-derived candidates come first (\"mobileNumberCountryCode\",\n * \"mobileCountryCode\" for a `mobileNumber` field) so a record holding several\n * numbers keeps each one's code attached to the right number.\n */\nexport function countryCodeKeys(field) {\n const key = String(field?.field ?? '').trim();\n const base = key.replace(/(number|no|phone|mobile|contact)$/i, '');\n return [\n ...(key ? [`${key}CountryCode`, `${key}Code`] : []),\n ...(base && base !== key ? [`${base}CountryCode`] : []),\n 'countryCode',\n 'phoneCountryCode',\n 'mobileCountryCode',\n 'contactCountryCode',\n 'dialCode',\n 'isdCode',\n ];\n}\n\n/**\n * resolveCountryCode — this record's dial code for this field.\n * `record` is the flattened value map of the record being displayed; pass the\n * addRow ROW when formatting a repeatable row, so a row's own code wins.\n */\nexport function resolveCountryCode(field, record, fallback = '') {\n const configured = field?.renderOptions?.countryCodeField ?? field?.countryCodeField;\n const keys = configured ? [configured, ...countryCodeKeys(field)] : countryCodeKeys(field);\n for (const key of keys) {\n const code = normalizeDialCode(getPath(record, key));\n if (code) return code;\n }\n return normalizeDialCode(fallback);\n}\n\n/**\n * splitDialCode — separate a code the value already carries from the number.\n */\nexport function splitDialCode(raw) {\n const str = String(raw ?? '').trim();\n const match = str.match(/^(\\+\\d{1,4})[\\s-]*(.*)$/);\n return match ? { code: match[1], rest: match[2] } : { code: '', rest: str };\n}\n\n/**\n * displayPhone — the finished, maskable display string.\n * `countryCode` is whatever resolveCountryCode produced; a code embedded in the\n * value still wins, because that is the record speaking for itself.\n */\nexport function displayPhone(raw, countryCode = '') {\n if (isEmpty(raw)) return '';\n const { code, rest } = splitDialCode(raw);\n const cc = code || normalizeDialCode(countryCode);\n const formatted = formatPhone(rest) || rest;\n return `${cc ? `${cc} ` : ''}${formatted}`.trim();\n}\n\n/**\n * displayPhoneForField — the one call sites use: resolve the code off the\n * record, then format. Falls back to the global default only as a last resort.\n */\nexport function displayPhoneForField(field, value, record) {\n const code = resolveCountryCode(field, record, getPhoneCountryCode());\n return displayPhone(value, code);\n}\n","// renderConfig — non-component shared module for the detail-view render engine.\n// Holds the Admin-facing option lists and the file/document resolution helpers,\n// kept out of the .jsx engine so React Fast Refresh stays happy and so other\n// modules (DocumentLink, the admin screen) can reuse them.\n\nimport { getDefaults } from '../../services/detailDefaults';\n\n// ── Admin option lists ───────────────────────────────────────────────────────\nexport const RENDER_TYPES = [\n { value: 'auto', label: 'Default (auto)' },\n { value: 'text', label: 'Text' },\n { value: 'multiline', label: 'Multiline Text' },\n { value: 'tag', label: 'Tag' },\n { value: 'tags', label: 'Multi Tag (Skills)' },\n { value: 'badge', label: 'Badge' },\n { value: 'chip', label: 'Chip' },\n { value: 'document', label: 'Document' },\n { value: 'link', label: 'Link' },\n { value: 'email', label: 'Email' },\n { value: 'phone', label: 'Phone' },\n { value: 'date', label: 'Date' },\n { value: 'currency', label: 'Currency' },\n { value: 'budget', label: 'Budget' },\n { value: 'html', label: 'HTML' },\n];\n\nexport const DOCUMENT_MODES = [\n { value: 'preview', label: 'Preview (viewer)' },\n { value: 'download', label: 'Download button' },\n { value: 'link', label: 'Link (filename)' },\n { value: 'tag', label: 'Tag' },\n { value: 'text', label: 'Text (filename)' },\n];\n\nexport const TEXT_TRANSFORMS = [\n { value: 'none', label: 'None' },\n { value: 'upper', label: 'UPPERCASE' },\n { value: 'lower', label: 'lowercase' },\n { value: 'title', label: 'Title Case' },\n];\n\n// ── file / document resolution ───────────────────────────────────────────────\nconst LOC_EXACT = ['location', 'path', 'url', 'key'];\nconst LOC_SUFFIX = ['location', 'filepath', 'path', 'url', 'key'];\nconst NAME_SUFFIX = ['uploadedfilename', 'uploadname', 'originalname', 'displayname', 'documentname', 'filename'];\nconst NAME_LAST = ['name'];\nconst lc = (s) => String(s).toLowerCase();\nconst isEmpty = (v) => v === undefined || v === null || v === '';\n\nfunction pickExact(obj, keys) {\n for (const key of keys) {\n const v = obj[key];\n if (typeof v === 'string' && v) return v;\n }\n return '';\n}\n\nfunction pickSuffix(obj, suffixes) {\n for (const suffix of suffixes) {\n for (const [key, val] of Object.entries(obj)) {\n if (typeof val === 'string' && val && lc(key).endsWith(suffix)) return val;\n }\n }\n return '';\n}\n\nexport function fileNameFromPath(path) {\n if (!path) return '';\n const clean = String(path).split('?')[0].split('#')[0];\n return decodeURIComponent(clean.split('/').pop() || '');\n}\n\n/**\n * buildFileUrl — resolves a file value to a directly-openable URL, or ''.\n *\n * IT NO LONGER BUILDS AN S3 URL FROM A STORED OBJECT KEY.\n *\n * It used to return `s3BaseUrl + key`. The bucket is PRIVATE, so that URL\n * carries no signature and S3 answers 403 — every resume in the product failed\n * to open with exactly that symptom. The key is not a URL; it is an identifier\n * that only the backend is allowed to resolve, because only the backend can\n * check that the caller is permitted to read that record.\n *\n * An absolute http(s) URL is still returned as-is — some fields genuinely hold\n * a public link (a company website, an externally hosted JD). But a bare\n * object key now returns '', which makes callers fall through to the\n * authenticated resolver (services/documentContentApi.js) instead of silently\n * producing a URL that 403s.\n *\n * Returning '' rather than throwing is deliberate: every caller already treats\n * '' as \"not directly linkable\", so this degrades into the resolver path\n * instead of turning a broken preview into a crashed page.\n */\nexport function buildFileUrl(location) {\n if (!location) return '';\n const loc = String(location);\n if (/^https?:\\/\\//i.test(loc)) return loc;\n return '';\n}\n\n/**\n * isStorageKey — true when a value is a stored object key rather than a URL,\n * i.e. it must be fetched through the authenticated document endpoint.\n */\nexport function isStorageKey(location) {\n const loc = String(location ?? '').trim();\n if (!loc) return false;\n if (/^https?:\\/\\//i.test(loc)) return false;\n if (loc.startsWith('blob:') || loc.startsWith('data:')) return false;\n return loc.includes('/');\n}\n\nexport function locationOf(doc) {\n if (typeof doc === 'string') return doc.includes('/') ? doc : '';\n if (!doc || typeof doc !== 'object') return '';\n return pickExact(doc, LOC_EXACT) || pickSuffix(doc, LOC_SUFFIX);\n}\n\nexport function docDisplayName(doc) {\n if (!doc) return 'Document';\n if (typeof doc === 'string') return fileNameFromPath(doc) || doc;\n if (typeof doc !== 'object') return 'Document';\n const order = getDefaults().documentNameOrder ?? [];\n return (\n pickExact(doc, order) ||\n pickSuffix(doc, NAME_SUFFIX) ||\n fileNameFromPath(locationOf(doc)) ||\n pickSuffix(doc, NAME_LAST) ||\n 'Document'\n );\n}\n\n// extractDocuments flattens any file-field value (array | object | string) into\n// a list of { location, name, url }.\nexport function extractDocuments(value) {\n if (isEmpty(value)) return [];\n const items = Array.isArray(value) ? value : [value];\n const out = [];\n for (const item of items) {\n if (isEmpty(item)) continue;\n if (typeof item === 'string') {\n const location = item.includes('/') ? item : '';\n out.push({\n location,\n name: fileNameFromPath(item) || item,\n url: buildFileUrl(location),\n needsAuthFetch: isStorageKey(location),\n });\n } else if (typeof item === 'object') {\n const location = locationOf(item);\n // A doc from the central `documents` collection already carries a 24h\n // presigned download URL (fileUrl) — prefer it over the raw location.\n const presigned = item.fileUrl || item.downloadUrl || item.signedUrl || '';\n out.push({\n location,\n name: docDisplayName(item),\n url: presigned || buildFileUrl(location),\n documentId: item.id || item._id || item.documentId || '',\n // `needsAuthFetch` marks a document whose bytes must come from the\n // authenticated backend because all we hold is a private-bucket object\n // key. Before this existed, callers built s3BaseUrl + key and got a\n // 403 — the key was indistinguishable from a usable URL once\n // buildFileUrl had concatenated it.\n needsAuthFetch: !presigned && isStorageKey(location),\n });\n }\n }\n return out;\n}\n","function comparisonValues(value) {\n if (Array.isArray(value)) return value.map((item) => String(item ?? '').trim());\n return String(value ?? '').split(',').map((item) => item.trim());\n}\n\n// Matches the same generic operators supported by showIf. Keeping this helper\n// independent of React makes conditional labels usable in Add/Edit forms and\n// straightforward to test without module- or field-specific code.\nexport function conditionMatches(condition, value) {\n if (!condition?.field) return false;\n switch (condition.operator ?? 'eq') {\n case 'eq': return String(value ?? '') === String(condition.value ?? '');\n case 'neq': return String(value ?? '') !== String(condition.value ?? '');\n case 'truthy': return value !== undefined && value !== null && value !== '' && value !== false;\n case 'falsy': return value === undefined || value === null || value === '' || value === false;\n case 'notEmpty': return Array.isArray(value) ? value.length > 0 : Boolean(value);\n case 'in': return comparisonValues(condition.value).includes(String(value ?? ''));\n case 'notIn': return !comparisonValues(condition.value).includes(String(value ?? ''));\n default: return false;\n }\n}\n\nexport function configuredFieldLabel(field, watchedValue, combined = false) {\n const fallback = combined\n ? (field?.combineLabel ?? field?.label)\n : field?.label;\n const rule = field?.labelWhen;\n return conditionMatches(rule, watchedValue) && rule?.label\n ? rule.label\n : fallback;\n}\n\n// Flatten a showIf into its leaf conditions: the top-level {field,operator,value}\n// plus any \"add more\" entries in conditions[]. Mirrors how the forms read it.\nexport function showIfConditions(showIf) {\n if (!showIf) return [];\n const leaf = showIf.field ? [showIf] : [];\n return [...leaf, ...(showIf.conditions ?? []).filter((c) => c?.field)];\n}\n\n// Evaluate a showIf against an arbitrary value source. readValue(fieldKey) lets\n// the caller decide where values come from — live form state in the forms, or a\n// saved record in the detail view — so one condition definition drives both.\nexport function evaluateShowIfWith(showIf, readValue) {\n const conditions = showIfConditions(showIf);\n if (!conditions.length) return true;\n const results = conditions.map((c) => conditionMatches(c, readValue(c.field)));\n return showIf.logic === 'or' ? results.some(Boolean) : results.every(Boolean);\n}\n\n// colWhen — conditionally override a field's grid column span, so one field can\n// shrink to make room for a sibling that a showIf has just revealed (e.g. Work\n// Authorization narrows when its expiry date appears). Config is a rule, or a\n// list of rules, each {field, operator, value, col}; the first match wins.\n// Display only — the field key, payload mapping and validation are untouched.\nexport function colWhenRules(field) {\n const raw = field?.colWhen;\n if (!raw) return [];\n return (Array.isArray(raw) ? raw : [raw])\n .filter((rule) => rule?.field && Number(rule?.col) > 0);\n}\n\n// readValue(rule) resolves the watched value for one rule — the caller owns path\n// resolution so a rule can reference a sibling in the same addRow row or a\n// top-level field, exactly like showIf.\nexport function resolveColSpan(field, fallbackSpan, readValue) {\n for (const rule of colWhenRules(field)) {\n if (conditionMatches(rule, readValue(rule))) return Number(rule.col);\n }\n return fallbackSpan;\n}\n\nexport function conditionFieldPath(condition, siblingPrefix) {\n if (!condition?.field) return ['__noop_conditional_label__'];\n return siblingPrefix != null\n ? [...(Array.isArray(siblingPrefix) ? siblingPrefix : [siblingPrefix]), condition.field]\n : [condition.field];\n}\n"],"mappings":";;;;;;;AAIA,IAAM,IAAoB,uBAEpB,IAAuB;CAC3B;EAAE,KAAK;EAAe,WAAW;CAAc;CAC/C;EAAE,KAAK;EAAe,WAAW;CAAc;CAC/C;EAAE,KAAK;EAAe,WAAW;CAAc;CAC/C;EAAE,KAAK;EAAe,WAAW;CAAc;CAC/C;EAAE,KAAK;EAAe,WAAW;CAAc;CAC/C;EAAE,KAAK;EAAe,WAAW;CAAc;CAC/C;EAAE,KAAK;EAAe,WAAW;CAAc;AACjD;AAIA,SAAS,EAAW,GAAG,GAAQ;CAC7B,OAAO,EAAO,KAAK,MAAM,OAAO,KAAK,CAAC;AACxC;AAEA,SAAS,EAAW,GAAQ,GAAM,GAAU;CAC1C,OAAO,EAAK,KAAK,MAAM,IAAS,EAAE,CAAC,CAAC,MAAM,MAAM,KAAyB,QAAQ,MAAM,EAAE,KAAK;AAChG;AAEA,SAAS,EAAe,GAAS,GAAO;CACtC,OACE,GAAS,SAAS,GAAS,cAAc,GAAS,SAClD,GAAS,gBAAgB,GAAS,MAAM,SAAS,GAAS,YAAY,SAAS,EAAM;AAEzF;AAEA,SAAS,EAAqB,GAAO,GAAO;CAC1C,IAAM,IAAY,EAAW,GAAO;EAAC;EAAS;EAAS;EAAa;EAAc;EAAQ;EAAc;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