@open-mercato/core 0.11.1-develop.8549.1.bd34c91190 → 0.11.1-develop.8556.1.d944a8493f
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/modules/customers/commands/companies.js +8 -6
- package/dist/modules/customers/commands/companies.js.map +2 -2
- package/dist/modules/customers/commands/deals.js +24 -13
- package/dist/modules/customers/commands/deals.js.map +2 -2
- package/dist/modules/customers/commands/people.js +8 -6
- package/dist/modules/customers/commands/people.js.map +2 -2
- package/dist/modules/entities/lib/helpers.js +6 -2
- package/dist/modules/entities/lib/helpers.js.map +2 -2
- package/package.json +8 -8
- package/src/modules/customers/commands/companies.ts +7 -5
- package/src/modules/customers/commands/deals.ts +22 -12
- package/src/modules/customers/commands/people.ts +7 -4
- package/src/modules/entities/lib/helpers.ts +8 -2
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/modules/entities/lib/helpers.ts"],
|
|
4
|
-
"sourcesContent": ["import type { EntityManager } from '@mikro-orm/core'\nimport type { TenantDataEncryptionService } from '@open-mercato/shared/lib/encryption/tenantDataEncryptionService'\nimport { decryptCustomFieldValue, encryptCustomFieldValue, resolveTenantEncryptionService } from '@open-mercato/shared/lib/encryption/customFieldValues'\nimport {\n MAX_CUSTOM_FIELD_KEYS_PER_RECORD,\n TOO_MANY_CUSTOM_FIELDS_ERROR,\n} from '@open-mercato/shared/modules/entities/validation'\nimport { CustomFieldDef, CustomFieldValue } from '../data/entities'\nimport { loadScopedCustomFieldDefs } from './scoped-field-defs'\nimport { encryptCustomEntityDocument } from '@open-mercato/shared/lib/encryption/customEntityDoc'\nimport { isTenantDataEncryptionEnabled } from '@open-mercato/shared/lib/encryption/toggles'\n\n/** @internal */\nexport async function encryptCustomEntityRecordDocument(\n em: EntityManager,\n opts: { entityId: string; organizationId: string | null; tenantId: string | null; doc: Record<string, unknown>; encryptionService?: TenantDataEncryptionService | null },\n): Promise<Record<string, unknown>> {\n if (!isTenantDataEncryptionEnabled() || Object.keys(opts.doc).every((key) => key === 'id')) return opts.doc\n const definitions = await loadScopedCustomFieldDefs(em, opts)\n const fields = Array.from(definitions.values(), (definition) => ({\n key: definition.key,\n kind: definition.kind,\n encrypted: Boolean(definition.configJson?.encrypted),\n }))\n return encryptCustomEntityDocument(opts.doc, fields, opts.tenantId, resolveTenantEncryptionService(em, opts.encryptionService))\n}\n\ntype Primitive = string | number | boolean | null | undefined\ntype PrimitiveOrArray = Primitive | Primitive[]\n\nexport type SetRecordCustomFieldsOptions = {\n entityId: string\n recordId: string\n organizationId?: string | null\n tenantId?: string | null\n values: Record<string, PrimitiveOrArray>\n // When true (default), try to use field definitions to decide storage column\n preferDefs?: boolean\n // Optional: notify external systems (e.g., indexing) when values changed\n onChanged?: (payload: { entityId: string; recordId: string; organizationId: string | null; tenantId: string | null }) => Promise<void> | void\n // Optional: re-use an existing tenant encryption service instance\n encryptionService?: TenantDataEncryptionService | null\n // When true, additionally scope the reconciling delete/lookup by organizationId,\n // restoring the pre-#5970 organization pin. Default false relies on `recordId`\n // being unique across organizations for a given entityId \u2014 true for every\n // ORM-backed entity, where recordId is the record's own primary key. That\n // invariant does not hold for `custom_entities_storage` records written under\n // `ENTITIES_BACKCOMPAT_EAV_FOR_CUSTOM`: the table upserts on\n // `(entity_type, entity_id, organization_id)`, so the same id can be a live\n // record in two organizations of one tenant, and an organization-agnostic\n // delete could remove another organization's values (#6034 review). Callers\n // writing those records must pass pinOrganizationId: true.\n pinOrganizationId?: boolean\n}\n\nfunction columnFromKind(kind: string): keyof CustomFieldValue {\n switch (kind) {\n case 'text':\n case 'select':\n case 'currency':\n case 'dictionary':\n case 'phone':\n return 'valueText'\n case 'multiline':\n return 'valueMultiline'\n case 'integer':\n return 'valueInt'\n case 'float':\n return 'valueFloat'\n case 'boolean':\n return 'valueBool'\n default:\n return 'valueText'\n }\n}\n\nfunction columnFromJsValue(v: Primitive): keyof CustomFieldValue {\n if (v === null || v === undefined) return 'valueText'\n if (typeof v === 'boolean') return 'valueBool'\n if (typeof v === 'number') return Number.isInteger(v) ? 'valueInt' : 'valueFloat'\n return 'valueText'\n}\n\n// Clears all value columns to avoid leftovers on update\nfunction clearValueColumns(cf: CustomFieldValue) {\n cf.valueText = null\n cf.valueMultiline = null\n cf.valueInt = null\n cf.valueFloat = null\n cf.valueBool = null\n}\n\nfunction valueFromRow(row: CustomFieldValue): Primitive {\n if (row.valueMultiline != null) return row.valueMultiline\n if (row.valueText != null) return row.valueText\n if (row.valueInt != null) return row.valueInt\n if (row.valueFloat != null) return row.valueFloat\n if (row.valueBool != null) return row.valueBool\n return null\n}\n\n// Keeps the value the caller's own scope already holds when the echoed array contains it,\n// so a save that never touched the field does not swap in another organization's value.\nfunction pickSingleValue(candidates: Primitive[], currentValue: unknown): Primitive {\n if (currentValue != null) {\n const kept = candidates.find((candidate) => candidate != null && String(candidate) === String(currentValue))\n if (kept !== undefined) return kept\n }\n const present = candidates.filter((candidate) => candidate != null)\n return present.length ? present[present.length - 1] : null\n}\n\nexport async function setRecordCustomFields(\n em: EntityManager,\n opts: SetRecordCustomFieldsOptions,\n): Promise<void> {\n const { entityId, recordId, values } = opts\n const organizationId = opts.organizationId ?? null\n const tenantId = opts.tenantId ?? null\n const preferDefs = opts.preferDefs !== false\n\n let defsByKey: Map<string, CustomFieldDef> | undefined\n if (preferDefs) {\n defsByKey = await loadScopedCustomFieldDefs(em, { entityId, organizationId, tenantId })\n }\n\n const toPersist: CustomFieldValue[] = []\n let encryptionService: TenantDataEncryptionService | null | undefined\n const encryptionCache = new Map<string | null, string | null>()\n const getEncryptionService = () => {\n if (encryptionService !== undefined) return encryptionService\n encryptionService = resolveTenantEncryptionService(em as any, opts.encryptionService)\n return encryptionService\n }\n // A write owns every value row a reader in ITS OWN tenant scope could return for this\n // record: same logical key (entityId, recordId, fieldKey), any organization, and either\n // the caller's tenant or the instance-global NULL tenant \u2014 exactly what the Query Engine\n // matches. Organization is left out because the Query Engine's value join does not filter\n // it (engine.ts, the cf join and the EXISTS subquery), so a row from a scope the record\n // has left is indistinguishable from the live one (#5970). The query-index reader does\n // scope organization_id, but it never sees another organization's row for a record it is\n // indexing, so dropping the column here cannot widen what it returns.\n //\n // This relies on recordId being unique across organizations and tenants for a given\n // entityId \u2014 true of every ORM-backed caller, which passes the record's own primary key.\n // A caller that passed a per-organization natural key \u2014 or a recordId that is only unique\n // WITHIN an organization, as custom_entities_storage's EAV backcompat writes are \u2014 would\n // have one organization's write delete another's live rows. Those callers opt into\n // pinOrganizationId (see SetRecordCustomFieldsOptions) to restore the organization pin.\n //\n // Scope of the delete, precisely: another TENANT's own rows are never touched. Rows with a\n // NULL tenant are, deliberately \u2014 they are instance-global and answer every tenant's reads,\n // so leaving one behind would reproduce the very duplicate this reconciles. Spelled as an\n // explicit $or rather than `$in: [tenantId, null]` because SQL `IN (NULL)` never matches a\n // NULL row.\n const tenantScopeFilter = { $or: [{ tenantId }, { tenantId: null }] }\n const pinOrganizationId = opts.pinOrganizationId === true\n const reconcileScopeFilter = pinOrganizationId\n ? { organizationId, ...tenantScopeFilter }\n : tenantScopeFilter\n const keys = Object.keys(values)\n const presentKeyCount = keys.filter((key) => values[key] !== undefined).length\n if (preferDefs && presentKeyCount > MAX_CUSTOM_FIELD_KEYS_PER_RECORD) {\n throw new Error(TOO_MANY_CUSTOM_FIELDS_ERROR)\n }\n\n // Run the per-key delete+insert work inside ONE database transaction so a\n // multi-value replacement is atomic and isolated. The array branch deletes the\n // existing rows for a key and inserts the replacements; without an enclosing\n // transaction those can land in separate commit boundaries under MikroORM's\n // FlushMode.AUTO (a query elsewhere in the unit auto-flushes part of the work),\n // which intermittently left the field with the delete applied but the inserts\n // missing \u2014 the multi-select EDIT reverted to []. The single commit below makes\n // it all-or-nothing. We only open our own transaction when the caller has not\n // already started one (commands fork the request em and may run setCustomFields\n // outside their own withAtomicFlush tx); join an ambient transaction otherwise.\n const txEm = em as {\n begin?: () => Promise<void>\n commit?: () => Promise<void>\n rollback?: () => Promise<void>\n isInTransaction?: () => boolean\n }\n const txCapable =\n typeof txEm.begin === 'function' &&\n typeof txEm.commit === 'function' &&\n typeof txEm.rollback === 'function' &&\n typeof txEm.isInTransaction === 'function'\n const ownCustomFieldTransaction = txCapable && !txEm.isInTransaction!()\n if (ownCustomFieldTransaction) await txEm.begin!()\n try {\n for (const fieldKey of keys) {\n const raw = values[fieldKey]\n if (raw === undefined) continue\n\n const def = defsByKey?.get(fieldKey)\n const encrypted = Boolean(def?.configJson && (def as any).configJson?.encrypted)\n // A single-value definition never stores an array. One arrives when the detail read\n // returned the duplicate rows #5970 left behind as an array and a form echoed it back\n // unchanged; treating it as a multi-value replacement re-creates every duplicate under\n // the caller's organization (#6468). Collapse it to one value so the scalar branch\n // below reconciles the duplicates away.\n const collapseToSingle = Array.isArray(raw) && Boolean(def) && (def as any).configJson?.multi !== true\n const isArray = (Array.isArray(raw) && !collapseToSingle)\n || (raw === null && def?.configJson?.multi === true)\n // When array (multi-value): replace all existing rows for the key. Delete\n // first, then create replacements, all inside the transaction opened above.\n // Creating rows before a native delete can auto-flush and delete the new\n // values; mixing em.remove(stale) with new rows for the same EAV scope was\n // observed to commit an empty set under MikroORM v7. The explicit order keeps\n // the replacement atomic without letting old-row cleanup target new rows.\n if (isArray) {\n const arr = Array.isArray(raw) ? raw.filter((value) => value != null) : []\n // Reconciling delete (see tenantScopeFilter/reconcileScopeFilter): pinning\n // organizationId here left the rows written under the record's PREVIOUS\n // organization alive next to the replacements, and the Query Engine's value join\n // does not filter organization_id, so both generations answered the same lookup\n // (#5970) \u2014 unless the caller opted into pinOrganizationId because its recordId\n // is not unique across organizations.\n await em.nativeDelete(CustomFieldValue, { entityId, recordId, fieldKey, ...reconcileScopeFilter })\n for (const val of arr) {\n const col: keyof CustomFieldValue = encrypted ? 'valueText' : def ? columnFromKind(def.kind) : columnFromJsValue(val)\n const cf = em.create(CustomFieldValue, { entityId, recordId, organizationId, tenantId, fieldKey, createdAt: new Date() })\n clearValueColumns(cf)\n const stored = encrypted\n ? await encryptCustomFieldValue(val, tenantId, getEncryptionService(), encryptionCache, { entityId, fieldKey })\n : val\n switch (col) {\n case 'valueText': cf.valueText = stored == null ? null : String(stored); break\n case 'valueMultiline': cf.valueMultiline = stored == null ? null : String(stored); break\n case 'valueInt': cf.valueInt = stored == null ? null : Number(stored); break\n case 'valueFloat': cf.valueFloat = stored == null ? null : Number(stored); break\n case 'valueBool': cf.valueBool = stored == null ? null : Boolean(stored); break\n default: cf.valueText = stored == null ? null : String(stored); break\n }\n toPersist.push(cf)\n }\n continue\n }\n\n // Same reconciliation as the multi-value branch (see tenantScopeFilter): load every\n // reachable row for the logical key, reuse the one already in the caller's exact\n // scope and drop the rest, so a row left behind by a previous organization \u2014 and\n // same-scope duplicates from two writes that both missed the lookup \u2014 cannot\n // survive (#5970). Picking the survivor in JS rather than narrowing the query keeps\n // NULL organizations out of SQL three-valued logic, where an inequality predicate\n // would silently spare exactly the stale rows this is meant to remove.\n const existingRows = await em.find(CustomFieldValue, { entityId, recordId, fieldKey, ...reconcileScopeFilter })\n // A soft-deleted row is never the survivor: writing the new value onto it would leave\n // deleted_at set, hiding the field from loadCustomFieldValues while the live row it\n // replaced goes into staleIds. Tombstones still get deleted as stale \u2014 the Query\n // Engine's join does not filter deleted_at, so one left behind would answer reads.\n let cf = existingRows.find((row) => !row.deletedAt\n && (row.organizationId ?? null) === organizationId\n && (row.tenantId ?? null) === tenantId) ?? null\n const value: Primitive = collapseToSingle\n ? pickSingleValue(raw as Primitive[], cf ? await decryptCustomFieldValue(valueFromRow(cf), tenantId, encrypted ? getEncryptionService() : null, encryptionCache, { kind: def?.kind ?? null }) : undefined)\n : raw as Primitive\n const column: keyof CustomFieldValue = encrypted ? 'valueText' : def ? columnFromKind(def.kind) : columnFromJsValue(value)\n const storedValue = encrypted\n ? await encryptCustomFieldValue(value, tenantId, getEncryptionService(), encryptionCache, { entityId, fieldKey })\n : value\n const staleIds = existingRows.filter((row) => row !== cf).map((row) => row.id)\n if (staleIds.length) await em.nativeDelete(CustomFieldValue, { id: { $in: staleIds } })\n if (!cf) {\n cf = em.create(CustomFieldValue, { entityId, recordId, organizationId, tenantId, fieldKey, createdAt: new Date() })\n toPersist.push(cf)\n }\n clearValueColumns(cf)\n switch (column) {\n case 'valueText':\n cf.valueText = (storedValue as Primitive) == null ? null : String(storedValue as Primitive)\n break\n case 'valueMultiline':\n cf.valueMultiline = (storedValue as Primitive) == null ? null : String(storedValue as Primitive)\n break\n case 'valueInt':\n cf.valueInt = (storedValue as Primitive) == null ? null : Number(storedValue as Primitive)\n break\n case 'valueFloat':\n cf.valueFloat = (storedValue as Primitive) == null ? null : Number(storedValue as Primitive)\n break\n case 'valueBool':\n cf.valueBool = (storedValue as Primitive) == null ? null : Boolean(storedValue as Primitive)\n break\n default:\n cf.valueText = (storedValue as Primitive) == null ? null : String(storedValue as Primitive)\n break\n }\n }\n\n if (toPersist.length) em.persist(toPersist)\n await em.flush()\n if (ownCustomFieldTransaction) await txEm.commit!()\n } catch (err) {\n if (ownCustomFieldTransaction) {\n try { await txEm.rollback!() } catch { /* surface the original error, not a rollback failure */ }\n }\n throw err\n }\n // Emit hook for indexing if requested (outside CRUD flows). Runs AFTER the\n // transaction commits so consumers observe the persisted rows.\n try {\n if (typeof opts.onChanged === 'function') {\n await opts.onChanged({ entityId, recordId, organizationId, tenantId })\n }\n } catch {\n // Non-blocking\n }\n}\n"],
|
|
5
|
-
"mappings": "AAEA,SAAS,yBAAyB,yBAAyB,sCAAsC;AACjG;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP,SAAyB,wBAAwB;AACjD,SAAS,iCAAiC;AAC1C,SAAS,mCAAmC;AAC5C,SAAS,qCAAqC;AAG9C,eAAsB,kCACpB,IACA,MACkC;AAClC,MAAI,CAAC,8BAA8B,KAAK,OAAO,KAAK,KAAK,GAAG,EAAE,MAAM,CAAC,QAAQ,QAAQ,IAAI,EAA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O,OAAO,OAAO,MAAM;AAAG;AAAA,YACvE,KAAK;AAAc,cAAAA,IAAG,aAAa,UAAU,OAAO,OAAO,OAAO,MAAM;AAAG;AAAA,YAC3E,KAAK;AAAa,cAAAA,IAAG,YAAY,UAAU,OAAO,OAAO,QAAQ,MAAM;AAAG;AAAA,YAC1E;AAAS,cAAAA,IAAG,YAAY,UAAU,OAAO,OAAO,OAAO,MAAM;AAAG;AAAA,UAClE;AACA,oBAAU,KAAKA,GAAE;AAAA,QACnB;AACA;AAAA,MACF;AASA,YAAM,eAAe,MAAM,GAAG,KAAK,kBAAkB,EAAE,UAAU,UAAU,UAAU,GAAG,qBAAqB,CAAC;AAK9G,UAAI,KAAK,aAAa,KAAK,CAAC,QAAQ,CAAC,IAAI,cACnC,IAAI,kBAAkB,UAAU,mBAChC,IAAI,YAAY,UAAU,QAAQ,KAAK;AAC7C,YAAM,
|
|
4
|
+
"sourcesContent": ["import type { EntityManager } from '@mikro-orm/core'\nimport type { TenantDataEncryptionService } from '@open-mercato/shared/lib/encryption/tenantDataEncryptionService'\nimport { decryptCustomFieldValue, encryptCustomFieldValue, resolveTenantEncryptionService } from '@open-mercato/shared/lib/encryption/customFieldValues'\nimport {\n MAX_CUSTOM_FIELD_KEYS_PER_RECORD,\n TOO_MANY_CUSTOM_FIELDS_ERROR,\n} from '@open-mercato/shared/modules/entities/validation'\nimport { CustomFieldDef, CustomFieldValue } from '../data/entities'\nimport { loadScopedCustomFieldDefs } from './scoped-field-defs'\nimport { encryptCustomEntityDocument } from '@open-mercato/shared/lib/encryption/customEntityDoc'\nimport { isTenantDataEncryptionEnabled } from '@open-mercato/shared/lib/encryption/toggles'\n\n/** @internal */\nexport async function encryptCustomEntityRecordDocument(\n em: EntityManager,\n opts: { entityId: string; organizationId: string | null; tenantId: string | null; doc: Record<string, unknown>; encryptionService?: TenantDataEncryptionService | null },\n): Promise<Record<string, unknown>> {\n if (!isTenantDataEncryptionEnabled() || Object.keys(opts.doc).every((key) => key === 'id')) return opts.doc\n const definitions = await loadScopedCustomFieldDefs(em, opts)\n const fields = Array.from(definitions.values(), (definition) => ({\n key: definition.key,\n kind: definition.kind,\n encrypted: Boolean(definition.configJson?.encrypted),\n }))\n return encryptCustomEntityDocument(opts.doc, fields, opts.tenantId, resolveTenantEncryptionService(em, opts.encryptionService))\n}\n\ntype Primitive = string | number | boolean | null | undefined\ntype PrimitiveOrArray = Primitive | Primitive[]\n\nexport type SetRecordCustomFieldsOptions = {\n entityId: string\n recordId: string\n organizationId?: string | null\n tenantId?: string | null\n values: Record<string, PrimitiveOrArray>\n // When true (default), try to use field definitions to decide storage column\n preferDefs?: boolean\n // Optional: notify external systems (e.g., indexing) when values changed\n onChanged?: (payload: { entityId: string; recordId: string; organizationId: string | null; tenantId: string | null }) => Promise<void> | void\n // Optional: re-use an existing tenant encryption service instance\n encryptionService?: TenantDataEncryptionService | null\n // When true, additionally scope the reconciling delete/lookup by organizationId,\n // restoring the pre-#5970 organization pin. Default false relies on `recordId`\n // being unique across organizations for a given entityId \u2014 true for every\n // ORM-backed entity, where recordId is the record's own primary key. That\n // invariant does not hold for `custom_entities_storage` records written under\n // `ENTITIES_BACKCOMPAT_EAV_FOR_CUSTOM`: the table upserts on\n // `(entity_type, entity_id, organization_id)`, so the same id can be a live\n // record in two organizations of one tenant, and an organization-agnostic\n // delete could remove another organization's values (#6034 review). Callers\n // writing those records must pass pinOrganizationId: true.\n pinOrganizationId?: boolean\n}\n\nfunction columnFromKind(kind: string): keyof CustomFieldValue {\n switch (kind) {\n case 'text':\n case 'select':\n case 'currency':\n case 'dictionary':\n case 'phone':\n return 'valueText'\n case 'multiline':\n return 'valueMultiline'\n case 'integer':\n return 'valueInt'\n case 'float':\n return 'valueFloat'\n case 'boolean':\n return 'valueBool'\n default:\n return 'valueText'\n }\n}\n\nfunction columnFromJsValue(v: Primitive): keyof CustomFieldValue {\n if (v === null || v === undefined) return 'valueText'\n if (typeof v === 'boolean') return 'valueBool'\n if (typeof v === 'number') return Number.isInteger(v) ? 'valueInt' : 'valueFloat'\n return 'valueText'\n}\n\n// Clears all value columns to avoid leftovers on update\nfunction clearValueColumns(cf: CustomFieldValue) {\n cf.valueText = null\n cf.valueMultiline = null\n cf.valueInt = null\n cf.valueFloat = null\n cf.valueBool = null\n}\n\nfunction valueFromRow(row: CustomFieldValue): Primitive {\n if (row.valueMultiline != null) return row.valueMultiline\n if (row.valueText != null) return row.valueText\n if (row.valueInt != null) return row.valueInt\n if (row.valueFloat != null) return row.valueFloat\n if (row.valueBool != null) return row.valueBool\n return null\n}\n\n// Keeps the value the caller's own scope already holds when the echoed array contains it,\n// so a save that never touched the field does not swap in another organization's value.\nfunction pickSingleValue(candidates: Primitive[], currentValue: unknown): Primitive {\n if (currentValue != null) {\n const kept = candidates.find((candidate) => candidate != null && String(candidate) === String(currentValue))\n if (kept !== undefined) return kept\n }\n const present = candidates.filter((candidate) => candidate != null)\n return present.length ? present[present.length - 1] : null\n}\n\nexport async function setRecordCustomFields(\n em: EntityManager,\n opts: SetRecordCustomFieldsOptions,\n): Promise<void> {\n const { entityId, recordId, values } = opts\n const organizationId = opts.organizationId ?? null\n const tenantId = opts.tenantId ?? null\n const preferDefs = opts.preferDefs !== false\n\n let defsByKey: Map<string, CustomFieldDef> | undefined\n if (preferDefs) {\n defsByKey = await loadScopedCustomFieldDefs(em, { entityId, organizationId, tenantId })\n }\n\n const toPersist: CustomFieldValue[] = []\n let encryptionService: TenantDataEncryptionService | null | undefined\n const encryptionCache = new Map<string | null, string | null>()\n const getEncryptionService = () => {\n if (encryptionService !== undefined) return encryptionService\n encryptionService = resolveTenantEncryptionService(em as any, opts.encryptionService)\n return encryptionService\n }\n // A write owns every value row a reader in ITS OWN tenant scope could return for this\n // record: same logical key (entityId, recordId, fieldKey), any organization, and either\n // the caller's tenant or the instance-global NULL tenant \u2014 exactly what the Query Engine\n // matches. Organization is left out because the Query Engine's value join does not filter\n // it (engine.ts, the cf join and the EXISTS subquery), so a row from a scope the record\n // has left is indistinguishable from the live one (#5970). The query-index reader does\n // scope organization_id, but it never sees another organization's row for a record it is\n // indexing, so dropping the column here cannot widen what it returns.\n //\n // This relies on recordId being unique across organizations and tenants for a given\n // entityId \u2014 true of every ORM-backed caller, which passes the record's own primary key.\n // A caller that passed a per-organization natural key \u2014 or a recordId that is only unique\n // WITHIN an organization, as custom_entities_storage's EAV backcompat writes are \u2014 would\n // have one organization's write delete another's live rows. Those callers opt into\n // pinOrganizationId (see SetRecordCustomFieldsOptions) to restore the organization pin.\n //\n // Scope of the delete, precisely: another TENANT's own rows are never touched. Rows with a\n // NULL tenant are, deliberately \u2014 they are instance-global and answer every tenant's reads,\n // so leaving one behind would reproduce the very duplicate this reconciles. Spelled as an\n // explicit $or rather than `$in: [tenantId, null]` because SQL `IN (NULL)` never matches a\n // NULL row.\n const tenantScopeFilter = { $or: [{ tenantId }, { tenantId: null }] }\n const pinOrganizationId = opts.pinOrganizationId === true\n const reconcileScopeFilter = pinOrganizationId\n ? { organizationId, ...tenantScopeFilter }\n : tenantScopeFilter\n const keys = Object.keys(values)\n const presentKeyCount = keys.filter((key) => values[key] !== undefined).length\n if (preferDefs && presentKeyCount > MAX_CUSTOM_FIELD_KEYS_PER_RECORD) {\n throw new Error(TOO_MANY_CUSTOM_FIELDS_ERROR)\n }\n\n // Run the per-key delete+insert work inside ONE database transaction so a\n // multi-value replacement is atomic and isolated. The array branch deletes the\n // existing rows for a key and inserts the replacements; without an enclosing\n // transaction those can land in separate commit boundaries under MikroORM's\n // FlushMode.AUTO (a query elsewhere in the unit auto-flushes part of the work),\n // which intermittently left the field with the delete applied but the inserts\n // missing \u2014 the multi-select EDIT reverted to []. The single commit below makes\n // it all-or-nothing. We only open our own transaction when the caller has not\n // already started one (commands fork the request em and may run setCustomFields\n // outside their own withAtomicFlush tx); join an ambient transaction otherwise.\n const txEm = em as {\n begin?: () => Promise<void>\n commit?: () => Promise<void>\n rollback?: () => Promise<void>\n isInTransaction?: () => boolean\n }\n const txCapable =\n typeof txEm.begin === 'function' &&\n typeof txEm.commit === 'function' &&\n typeof txEm.rollback === 'function' &&\n typeof txEm.isInTransaction === 'function'\n const ownCustomFieldTransaction = txCapable && !txEm.isInTransaction!()\n if (ownCustomFieldTransaction) await txEm.begin!()\n try {\n for (const fieldKey of keys) {\n const raw = values[fieldKey]\n if (raw === undefined) continue\n\n const def = defsByKey?.get(fieldKey)\n const encrypted = Boolean(def?.configJson && (def as any).configJson?.encrypted)\n // A single-value definition never stores an array. One arrives when the detail read\n // returned the duplicate rows #5970 left behind as an array and a form echoed it back\n // unchanged; treating it as a multi-value replacement re-creates every duplicate under\n // the caller's organization (#6468). Collapse it to one value so the scalar branch\n // below reconciles the duplicates away.\n const collapseToSingle = Array.isArray(raw) && Boolean(def) && (def as any).configJson?.multi !== true\n const isArray = (Array.isArray(raw) && !collapseToSingle)\n || (raw === null && def?.configJson?.multi === true)\n // When array (multi-value): replace all existing rows for the key. Delete\n // first, then create replacements, all inside the transaction opened above.\n // Creating rows before a native delete can auto-flush and delete the new\n // values; mixing em.remove(stale) with new rows for the same EAV scope was\n // observed to commit an empty set under MikroORM v7. The explicit order keeps\n // the replacement atomic without letting old-row cleanup target new rows.\n if (isArray) {\n const arr = Array.isArray(raw) ? raw.filter((value) => value != null) : []\n // Reconciling delete (see tenantScopeFilter/reconcileScopeFilter): pinning\n // organizationId here left the rows written under the record's PREVIOUS\n // organization alive next to the replacements, and the Query Engine's value join\n // does not filter organization_id, so both generations answered the same lookup\n // (#5970) \u2014 unless the caller opted into pinOrganizationId because its recordId\n // is not unique across organizations.\n await em.nativeDelete(CustomFieldValue, { entityId, recordId, fieldKey, ...reconcileScopeFilter })\n for (const val of arr) {\n const col: keyof CustomFieldValue = encrypted ? 'valueText' : def ? columnFromKind(def.kind) : columnFromJsValue(val)\n const cf = em.create(CustomFieldValue, { entityId, recordId, organizationId, tenantId, fieldKey, createdAt: new Date() })\n clearValueColumns(cf)\n const stored = encrypted\n ? await encryptCustomFieldValue(val, tenantId, getEncryptionService(), encryptionCache, { entityId, fieldKey })\n : val\n switch (col) {\n case 'valueText': cf.valueText = stored == null ? null : String(stored); break\n case 'valueMultiline': cf.valueMultiline = stored == null ? null : String(stored); break\n case 'valueInt': cf.valueInt = stored == null ? null : Number(stored); break\n case 'valueFloat': cf.valueFloat = stored == null ? null : Number(stored); break\n case 'valueBool': cf.valueBool = stored == null ? null : Boolean(stored); break\n default: cf.valueText = stored == null ? null : String(stored); break\n }\n toPersist.push(cf)\n }\n continue\n }\n\n // Same reconciliation as the multi-value branch (see tenantScopeFilter): load every\n // reachable row for the logical key, reuse the one already in the caller's exact\n // scope and drop the rest, so a row left behind by a previous organization \u2014 and\n // same-scope duplicates from two writes that both missed the lookup \u2014 cannot\n // survive (#5970). Picking the survivor in JS rather than narrowing the query keeps\n // NULL organizations out of SQL three-valued logic, where an inequality predicate\n // would silently spare exactly the stale rows this is meant to remove.\n const existingRows = await em.find(CustomFieldValue, { entityId, recordId, fieldKey, ...reconcileScopeFilter })\n // A soft-deleted row is never the survivor: writing the new value onto it would leave\n // deleted_at set, hiding the field from loadCustomFieldValues while the live row it\n // replaced goes into staleIds. Tombstones still get deleted as stale \u2014 the Query\n // Engine's join does not filter deleted_at, so one left behind would answer reads.\n let cf = existingRows.find((row) => !row.deletedAt\n && (row.organizationId ?? null) === organizationId\n && (row.tenantId ?? null) === tenantId) ?? null\n const currentValue = collapseToSingle && raw.some((candidate) => candidate != null) && cf\n ? await decryptCustomFieldValue(valueFromRow(cf), tenantId, encrypted ? getEncryptionService() : null, encryptionCache, {\n kind: def?.kind ?? null,\n writeContext: encrypted ? { entityId, fieldKey } : undefined,\n })\n : undefined\n const value: Primitive = collapseToSingle\n ? pickSingleValue(raw as Primitive[], currentValue)\n : raw as Primitive\n const column: keyof CustomFieldValue = encrypted ? 'valueText' : def ? columnFromKind(def.kind) : columnFromJsValue(value)\n const storedValue = encrypted && value != null\n ? await encryptCustomFieldValue(value, tenantId, getEncryptionService(), encryptionCache, { entityId, fieldKey })\n : value\n const staleIds = existingRows.filter((row) => row !== cf).map((row) => row.id)\n if (staleIds.length) await em.nativeDelete(CustomFieldValue, { id: { $in: staleIds } })\n if (!cf) {\n cf = em.create(CustomFieldValue, { entityId, recordId, organizationId, tenantId, fieldKey, createdAt: new Date() })\n toPersist.push(cf)\n }\n clearValueColumns(cf)\n switch (column) {\n case 'valueText':\n cf.valueText = (storedValue as Primitive) == null ? null : String(storedValue as Primitive)\n break\n case 'valueMultiline':\n cf.valueMultiline = (storedValue as Primitive) == null ? null : String(storedValue as Primitive)\n break\n case 'valueInt':\n cf.valueInt = (storedValue as Primitive) == null ? null : Number(storedValue as Primitive)\n break\n case 'valueFloat':\n cf.valueFloat = (storedValue as Primitive) == null ? null : Number(storedValue as Primitive)\n break\n case 'valueBool':\n cf.valueBool = (storedValue as Primitive) == null ? null : Boolean(storedValue as Primitive)\n break\n default:\n cf.valueText = (storedValue as Primitive) == null ? null : String(storedValue as Primitive)\n break\n }\n }\n\n if (toPersist.length) em.persist(toPersist)\n await em.flush()\n if (ownCustomFieldTransaction) await txEm.commit!()\n } catch (err) {\n if (ownCustomFieldTransaction) {\n try { await txEm.rollback!() } catch { /* surface the original error, not a rollback failure */ }\n }\n throw err\n }\n // Emit hook for indexing if requested (outside CRUD flows). Runs AFTER the\n // transaction commits so consumers observe the persisted rows.\n try {\n if (typeof opts.onChanged === 'function') {\n await opts.onChanged({ entityId, recordId, organizationId, tenantId })\n }\n } catch {\n // Non-blocking\n }\n}\n"],
|
|
5
|
+
"mappings": "AAEA,SAAS,yBAAyB,yBAAyB,sCAAsC;AACjG;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP,SAAyB,wBAAwB;AACjD,SAAS,iCAAiC;AAC1C,SAAS,mCAAmC;AAC5C,SAAS,qCAAqC;AAG9C,eAAsB,kCACpB,IACA,MACkC;AAClC,MAAI,CAAC,8BAA8B,KAAK,OAAO,KAAK,KAAK,GAAG,EAAE,MAAM,CAAC,QAAQ,QAAQ,IAA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
3
|
+
"version": "0.11.1-develop.8556.1.d944a8493f",
|
|
4
4
|
"license": "MIT",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
"build": "node build.mjs",
|
|
9
9
|
"watch": "node watch.mjs",
|
|
10
10
|
"test": "jest --config jest.config.cjs",
|
|
11
|
-
"test:pg-integration": "cross-env OM_PG_INTEGRATION=1 jest --config jest.config.cjs --runInBand 'src/(modules/((availability|catalog|communication_channels|customer_accounts|eudr|integrations|notifications|progress|staff)/.+\\.integration|workflows/.+\\.pg|customers/migrations/.+\\.integration|entities/__tests__/cli-rehash-lookups\\.integration|payment_gateways/lib/__tests__/gateway-service\\.status-race\\.pg|devices/.+\\.pg)|__tests__/money-numeric-widening-migrations\\.integration)\\.test\\.ts$'",
|
|
11
|
+
"test:pg-integration": "cross-env OM_PG_INTEGRATION=1 jest --config jest.config.cjs --runInBand 'src/(modules/((availability|catalog|communication_channels|customer_accounts|eudr|integrations|notifications|progress|staff)/.+\\.integration|workflows/.+\\.pg|customers/(migrations/.+\\.integration|api/people/__tests__/encrypted-custom-fields\\.pg)|entities/__tests__/cli-rehash-lookups\\.integration|payment_gateways/lib/__tests__/gateway-service\\.status-race\\.pg|devices/.+\\.pg)|__tests__/money-numeric-widening-migrations\\.integration)\\.test\\.ts$'",
|
|
12
12
|
"test:tz": "cross-env TZ=Pacific/Auckland jest --config jest.config.cjs",
|
|
13
13
|
"typecheck": "tsc --noEmit"
|
|
14
14
|
},
|
|
@@ -268,16 +268,16 @@
|
|
|
268
268
|
"zod": "^4.6.6"
|
|
269
269
|
},
|
|
270
270
|
"peerDependencies": {
|
|
271
|
-
"@open-mercato/ai-assistant": "0.11.1-develop.
|
|
272
|
-
"@open-mercato/shared": "0.11.1-develop.
|
|
273
|
-
"@open-mercato/ui": "0.11.1-develop.
|
|
271
|
+
"@open-mercato/ai-assistant": "0.11.1-develop.8556.1.d944a8493f",
|
|
272
|
+
"@open-mercato/shared": "0.11.1-develop.8556.1.d944a8493f",
|
|
273
|
+
"@open-mercato/ui": "0.11.1-develop.8556.1.d944a8493f",
|
|
274
274
|
"react": "^19.0.0",
|
|
275
275
|
"react-dom": "^19.0.0"
|
|
276
276
|
},
|
|
277
277
|
"devDependencies": {
|
|
278
|
-
"@open-mercato/ai-assistant": "0.11.1-develop.
|
|
279
|
-
"@open-mercato/shared": "0.11.1-develop.
|
|
280
|
-
"@open-mercato/ui": "0.11.1-develop.
|
|
278
|
+
"@open-mercato/ai-assistant": "0.11.1-develop.8556.1.d944a8493f",
|
|
279
|
+
"@open-mercato/shared": "0.11.1-develop.8556.1.d944a8493f",
|
|
280
|
+
"@open-mercato/ui": "0.11.1-develop.8556.1.d944a8493f",
|
|
281
281
|
"@testing-library/dom": "^10.4.1",
|
|
282
282
|
"@testing-library/jest-dom": "^7.0.1",
|
|
283
283
|
"@testing-library/react": "^16.3.3",
|
|
@@ -476,10 +476,11 @@ async function setCompanyCustomFields(
|
|
|
476
476
|
profileId: string,
|
|
477
477
|
organizationId: string,
|
|
478
478
|
tenantId: string,
|
|
479
|
-
values: Record<string, unknown
|
|
479
|
+
values: Record<string, unknown>,
|
|
480
|
+
transactionalEm?: EntityManager,
|
|
480
481
|
) {
|
|
481
482
|
if (!values || !Object.keys(values).length) return
|
|
482
|
-
const em = (ctx.container.resolve('em') as EntityManager)
|
|
483
|
+
const em = transactionalEm ?? (ctx.container.resolve('em') as EntityManager)
|
|
483
484
|
const routing = await resolveCompanyCustomFieldRouting(em, tenantId, organizationId)
|
|
484
485
|
const entityScoped: Record<string, unknown> = {}
|
|
485
486
|
const profileScoped: Record<string, unknown> = {}
|
|
@@ -498,6 +499,7 @@ async function setCompanyCustomFields(
|
|
|
498
499
|
organizationId,
|
|
499
500
|
tenantId,
|
|
500
501
|
values: entityScoped,
|
|
502
|
+
transactionalEm,
|
|
501
503
|
notify: false,
|
|
502
504
|
})
|
|
503
505
|
}
|
|
@@ -509,6 +511,7 @@ async function setCompanyCustomFields(
|
|
|
509
511
|
organizationId,
|
|
510
512
|
tenantId,
|
|
511
513
|
values: profileScoped,
|
|
514
|
+
transactionalEm,
|
|
512
515
|
notify: false,
|
|
513
516
|
})
|
|
514
517
|
}
|
|
@@ -594,8 +597,8 @@ const createCompanyCommand: CommandHandler<CompanyCreateInput, { entityId: strin
|
|
|
594
597
|
em.persist(profile)
|
|
595
598
|
},
|
|
596
599
|
() => syncEntityTags(em, entity, parsed.tags),
|
|
600
|
+
() => setCompanyCustomFields(ctx, entity.id, profile.id, entity.organizationId, entity.tenantId, custom, em),
|
|
597
601
|
], { transaction: true })
|
|
598
|
-
await setCompanyCustomFields(ctx, entity.id, profile.id, entity.organizationId, entity.tenantId, custom)
|
|
599
602
|
|
|
600
603
|
const de = (ctx.container.resolve('dataEngine') as DataEngine)
|
|
601
604
|
await emitCrudSideEffects({
|
|
@@ -878,10 +881,9 @@ const updateCompanyCommand = {
|
|
|
878
881
|
}
|
|
879
882
|
},
|
|
880
883
|
() => syncEntityTags(em, record, parsed.tags, { ignoreMissing: ignoreMissingTags }),
|
|
884
|
+
() => setCompanyCustomFields(ctx, record.id, profile.id, record.organizationId, record.tenantId, custom, em),
|
|
881
885
|
], { transaction: true })
|
|
882
886
|
|
|
883
|
-
await setCompanyCustomFields(ctx, record.id, profile.id, record.organizationId, record.tenantId, custom)
|
|
884
|
-
|
|
885
887
|
const de = (ctx.container.resolve('dataEngine') as DataEngine)
|
|
886
888
|
await emitCrudSideEffects({
|
|
887
889
|
dataEngine: de,
|
|
@@ -602,6 +602,7 @@ const createDealCommand: CommandHandler<DealCreateInput, { dealId: string }> = {
|
|
|
602
602
|
let resolvedPipelineStageLabel: string | null = null
|
|
603
603
|
let stageDefaultProbability: number | null = null
|
|
604
604
|
const createdDictionaryKinds = new Set<string>()
|
|
605
|
+
const de = ctx.container.resolve<DataEngine>('dataEngine')
|
|
605
606
|
await withAtomicFlush(em, [
|
|
606
607
|
async () => {
|
|
607
608
|
stageSnapshot = parsed.pipelineStageId
|
|
@@ -667,20 +668,19 @@ const createDealCommand: CommandHandler<DealCreateInput, { dealId: string }> = {
|
|
|
667
668
|
},
|
|
668
669
|
() => syncDealPeople(em, deal, parsed.personIds ?? [], parsed.primaryPersonEntityId, { stampLockToken: false }),
|
|
669
670
|
() => syncDealCompanies(em, deal, parsed.companyIds ?? [], { stampLockToken: false }),
|
|
671
|
+
() => setCustomFieldsIfAny({
|
|
672
|
+
dataEngine: de,
|
|
673
|
+
transactionalEm: em,
|
|
674
|
+
entityId: DEAL_ENTITY_ID,
|
|
675
|
+
recordId: deal.id,
|
|
676
|
+
organizationId: deal.organizationId,
|
|
677
|
+
tenantId: deal.tenantId,
|
|
678
|
+
values: custom,
|
|
679
|
+
notify: false,
|
|
680
|
+
}),
|
|
670
681
|
], { transaction: true })
|
|
671
682
|
await invalidateDictionaryKindCaches(ctx, { tenantId: parsed.tenantId, organizationId: parsed.organizationId }, createdDictionaryKinds)
|
|
672
683
|
|
|
673
|
-
const de = (ctx.container.resolve('dataEngine') as DataEngine)
|
|
674
|
-
await setCustomFieldsIfAny({
|
|
675
|
-
dataEngine: de,
|
|
676
|
-
entityId: DEAL_ENTITY_ID,
|
|
677
|
-
recordId: deal.id,
|
|
678
|
-
organizationId: deal.organizationId,
|
|
679
|
-
tenantId: deal.tenantId,
|
|
680
|
-
values: custom,
|
|
681
|
-
notify: false,
|
|
682
|
-
})
|
|
683
|
-
|
|
684
684
|
await emitCrudSideEffects({
|
|
685
685
|
dataEngine: de,
|
|
686
686
|
action: 'created',
|
|
@@ -839,13 +839,14 @@ const updateDealCommand: CommandHandler<DealUpdateInput, { dealId: string }> = {
|
|
|
839
839
|
let requestedClosureOutcome: DealClosureOutcome | null = null
|
|
840
840
|
const createdDictionaryKinds = new Set<string>()
|
|
841
841
|
|
|
842
|
+
const de = ctx.container.resolve<DataEngine>('dataEngine')
|
|
842
843
|
await runCrudCommandWrite({
|
|
843
844
|
ctx,
|
|
845
|
+
dataEngine: de,
|
|
844
846
|
em,
|
|
845
847
|
entityId: DEAL_ENTITY_ID,
|
|
846
848
|
action: 'updated',
|
|
847
849
|
scope: { tenantId: record.tenantId, organizationId: record.organizationId },
|
|
848
|
-
customFields: custom,
|
|
849
850
|
events: dealCrudEvents,
|
|
850
851
|
indexer: dealCrudIndexer,
|
|
851
852
|
sideEffect: () => ({
|
|
@@ -995,6 +996,15 @@ const updateDealCommand: CommandHandler<DealUpdateInput, { dealId: string }> = {
|
|
|
995
996
|
},
|
|
996
997
|
() => syncDealPeople(em, record, parsed.personIds, parsed.primaryPersonEntityId),
|
|
997
998
|
() => syncDealCompanies(em, record, parsed.companyIds),
|
|
999
|
+
() => setCustomFieldsIfAny({
|
|
1000
|
+
dataEngine: de,
|
|
1001
|
+
transactionalEm: em,
|
|
1002
|
+
entityId: DEAL_ENTITY_ID,
|
|
1003
|
+
recordId: record.id,
|
|
1004
|
+
organizationId: record.organizationId,
|
|
1005
|
+
tenantId: record.tenantId,
|
|
1006
|
+
values: custom,
|
|
1007
|
+
}),
|
|
998
1008
|
],
|
|
999
1009
|
})
|
|
1000
1010
|
await invalidateDictionaryKindCaches(ctx, record, createdDictionaryKinds)
|
|
@@ -562,10 +562,11 @@ async function setCustomFieldsForPerson(
|
|
|
562
562
|
profileId: string,
|
|
563
563
|
organizationId: string,
|
|
564
564
|
tenantId: string,
|
|
565
|
-
values: Record<string, unknown
|
|
565
|
+
values: Record<string, unknown>,
|
|
566
|
+
transactionalEm?: EntityManager,
|
|
566
567
|
): Promise<void> {
|
|
567
568
|
if (!values || !Object.keys(values).length) return
|
|
568
|
-
const em = (ctx.container.resolve('em') as EntityManager)
|
|
569
|
+
const em = transactionalEm ?? (ctx.container.resolve('em') as EntityManager)
|
|
569
570
|
const routing = await resolvePersonCustomFieldRouting(em, tenantId, organizationId)
|
|
570
571
|
const entityScoped: Record<string, unknown> = {}
|
|
571
572
|
const profileScoped: Record<string, unknown> = {}
|
|
@@ -584,6 +585,7 @@ async function setCustomFieldsForPerson(
|
|
|
584
585
|
organizationId,
|
|
585
586
|
tenantId,
|
|
586
587
|
values: entityScoped,
|
|
588
|
+
transactionalEm,
|
|
587
589
|
notify: true,
|
|
588
590
|
})
|
|
589
591
|
}
|
|
@@ -595,6 +597,7 @@ async function setCustomFieldsForPerson(
|
|
|
595
597
|
organizationId,
|
|
596
598
|
tenantId,
|
|
597
599
|
values: profileScoped,
|
|
600
|
+
transactionalEm,
|
|
598
601
|
notify: true,
|
|
599
602
|
})
|
|
600
603
|
}
|
|
@@ -781,12 +784,12 @@ const createPersonCommand: CommandHandler<PersonCreateInput, { entityId: string;
|
|
|
781
784
|
},
|
|
782
785
|
() => syncLegacyPrimaryCompanyLink(em, entity, profile, parsed.companyEntityId ?? null),
|
|
783
786
|
() => syncEntityTags(em, entity, parsed.tags),
|
|
787
|
+
() => setCustomFieldsForPerson(ctx, entity.id, profile.id, entity.organizationId, entity.tenantId, custom, em),
|
|
784
788
|
], { transaction: true })
|
|
785
789
|
|
|
786
790
|
const tenantId = entity.tenantId
|
|
787
791
|
const organizationId = entity.organizationId
|
|
788
792
|
await invalidateDictionaryKindCaches(ctx, { tenantId, organizationId }, createdDictionaryKinds)
|
|
789
|
-
await setCustomFieldsForPerson(ctx, entity.id, profile.id, organizationId, tenantId, custom)
|
|
790
793
|
|
|
791
794
|
const de = (ctx.container.resolve('dataEngine') as DataEngine)
|
|
792
795
|
await emitCrudSideEffects({
|
|
@@ -1140,10 +1143,10 @@ const updatePersonCommand = {
|
|
|
1140
1143
|
}
|
|
1141
1144
|
},
|
|
1142
1145
|
() => syncEntityTags(em, record, parsed.tags, { ignoreMissing: ignoreMissingTags }),
|
|
1146
|
+
() => setCustomFieldsForPerson(ctx, record.id, profile.id, record.organizationId, record.tenantId, custom, em),
|
|
1143
1147
|
], { transaction: true })
|
|
1144
1148
|
|
|
1145
1149
|
await invalidateDictionaryKindCaches(ctx, record, createdDictionaryKinds)
|
|
1146
|
-
await setCustomFieldsForPerson(ctx, record.id, profile.id, record.organizationId, record.tenantId, custom)
|
|
1147
1150
|
|
|
1148
1151
|
const de = (ctx.container.resolve('dataEngine') as DataEngine)
|
|
1149
1152
|
await emitCrudSideEffects({
|
|
@@ -252,11 +252,17 @@ export async function setRecordCustomFields(
|
|
|
252
252
|
let cf = existingRows.find((row) => !row.deletedAt
|
|
253
253
|
&& (row.organizationId ?? null) === organizationId
|
|
254
254
|
&& (row.tenantId ?? null) === tenantId) ?? null
|
|
255
|
+
const currentValue = collapseToSingle && raw.some((candidate) => candidate != null) && cf
|
|
256
|
+
? await decryptCustomFieldValue(valueFromRow(cf), tenantId, encrypted ? getEncryptionService() : null, encryptionCache, {
|
|
257
|
+
kind: def?.kind ?? null,
|
|
258
|
+
writeContext: encrypted ? { entityId, fieldKey } : undefined,
|
|
259
|
+
})
|
|
260
|
+
: undefined
|
|
255
261
|
const value: Primitive = collapseToSingle
|
|
256
|
-
? pickSingleValue(raw as Primitive[],
|
|
262
|
+
? pickSingleValue(raw as Primitive[], currentValue)
|
|
257
263
|
: raw as Primitive
|
|
258
264
|
const column: keyof CustomFieldValue = encrypted ? 'valueText' : def ? columnFromKind(def.kind) : columnFromJsValue(value)
|
|
259
|
-
const storedValue = encrypted
|
|
265
|
+
const storedValue = encrypted && value != null
|
|
260
266
|
? await encryptCustomFieldValue(value, tenantId, getEncryptionService(), encryptionCache, { entityId, fieldKey })
|
|
261
267
|
: value
|
|
262
268
|
const staleIds = existingRows.filter((row) => row !== cf).map((row) => row.id)
|