@open-mercato/core 0.11.1-develop.8531.1.9c9f5e2b21 → 0.11.1-develop.8533.1.c51008db92

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.
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/customers/commands/shared.ts"],
4
- "sourcesContent": ["import type { EntityManager, EntityName, FilterQuery } from '@mikro-orm/postgresql'\nimport { CustomerDeal, CustomerEntity, CustomerTag, CustomerTagAssignment, CustomerDictionaryEntry, type CustomerEntityKind } from '../data/entities'\nimport { CrudHttpError, forbidden, notFound } from '@open-mercato/shared/lib/crud/errors'\nimport { buildScopedWhere } from '@open-mercato/shared/lib/api/crud'\nimport { isUnrestrictedOrganizationScope } from '@open-mercato/shared/lib/auth/organizationAccess'\nimport type { CommandRuntimeContext } from '@open-mercato/shared/lib/commands'\nimport { ensureOrganizationScope, ensureSameScope, ensureTenantScope } from '@open-mercato/shared/lib/commands/scope'\nimport { loadEntityRecordScope } from '@open-mercato/shared/lib/db/recordScope'\nimport { findOneWithDecryption, findWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport type { EventBus } from '@open-mercato/events'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\nimport type { CacheStrategy } from '@open-mercato/cache'\nimport { invalidateDictionaryCache } from '../api/dictionaries/cache'\n\nconst logger = createLogger('customers')\nexport { ensureOrganizationScope, ensureSameScope, ensureTenantScope } from '@open-mercato/shared/lib/commands/scope'\nexport { extractUndoPayload } from '@open-mercato/shared/lib/commands/undo'\n\nexport const CUSTOMER_ENTITY_UNDO_DATE_OPTIONS = {\n datePaths: ['before.entity.nextInteractionAt'],\n} as const\n\nexport function normalizeDictionaryColor(input: unknown): string | null {\n if (typeof input !== 'string') return null\n const trimmed = input.trim()\n if (!trimmed) return null\n const hexMatch = /^#([0-9a-fA-F]{6})$/.exec(trimmed)\n if (!hexMatch) return null\n return `#${hexMatch[1].toLowerCase()}`\n}\n\nexport function normalizeDictionaryIcon(input: unknown): string | null {\n if (typeof input !== 'string') return null\n const trimmed = input.trim()\n if (!trimmed) return null\n return trimmed.slice(0, 48)\n}\n\nexport { assertFound } from '@open-mercato/shared/lib/crud/errors'\n\nexport type CommandScopeWhere = {\n tenantId?: string\n organizationId?: { $in: string[] }\n}\n\n// Filter to merge into a write command's target lookup so ids outside the caller's\n// tenant (from auth, or organizationScope.tenantId for auth-less callers) and, for\n// restricted callers, outside the allowed organizations resolve as \"not found\"\n// instead of being loaded and rejected afterwards. The ensure*Scope checks stay as\n// the second layer (#7598, mirrors catalog #3825).\nexport function commandScopeWhere(\n ctx: Pick<CommandRuntimeContext, 'auth' | 'organizationScope'>,\n): CommandScopeWhere {\n const where: CommandScopeWhere = {}\n const tenantId = ctx.auth ? ctx.auth.tenantId ?? null : ctx.organizationScope?.tenantId ?? null\n if (tenantId) where.tenantId = tenantId\n const allowedIds = ctx.organizationScope?.allowedIds\n if (ctx.auth?.isSuperAdmin !== true && Array.isArray(allowedIds)) {\n where.organizationId = { $in: [...allowedIds] }\n }\n return where\n}\n\nexport type CustomerEntityScope = {\n tenantId: string\n organizationId: string\n}\n\nexport function buildCustomerCommandLookup(where: Record<string, unknown>, ctx: CommandRuntimeContext) {\n const isSuperAdmin = ctx.auth?.isSuperAdmin === true\n const organizationScope = ctx.organizationScope\n const tenantId = ctx.auth ? (ctx.auth.tenantId ?? null) : (organizationScope?.tenantId ?? null)\n if (ctx.auth && !isSuperAdmin && (!tenantId || (organizationScope && !organizationScope.tenantId))) {\n throw forbidden()\n }\n let organizationIds: string[] | undefined\n if (organizationScope) {\n if (!isUnrestrictedOrganizationScope({ isSuperAdmin, allowedOrganizationIds: organizationScope.allowedIds })) {\n organizationIds = organizationScope.allowedIds ?? []\n }\n } else if (!isSuperAdmin) {\n const organizationId = ctx.selectedOrganizationId ?? ctx.auth?.orgId\n if (organizationId) organizationIds = [organizationId]\n }\n return {\n where: buildScopedWhere(where, {\n tenantId: tenantId ?? undefined,\n organizationIds,\n softDeleteField: null,\n }),\n scope: { tenantId, organizationId: organizationIds?.length === 1 ? organizationIds[0] : null },\n }\n}\n\nexport async function findScopedCustomerCommandRecord<Entity extends object, Hint extends string = never>(\n em: EntityManager,\n entity: EntityName<Entity>,\n where: Record<string, unknown>,\n options: Parameters<typeof findOneWithDecryption<Entity, Hint>>[3],\n ctx: CommandRuntimeContext,\n): Promise<Entity | null> {\n const record = await findScopedCustomerCommandTarget(em, entity, where, options, ctx)\n if (!record && ctx.auth && typeof where.id === 'string') {\n const entityType = em.getMetadata().get(entity).className\n const recordScope = await loadEntityRecordScope(em as unknown as Parameters<typeof loadEntityRecordScope>[0], entityType, where.id)\n if (recordScope && await em.count(entity, { ...where, ...recordScope } as FilterQuery<NoInfer<Entity>>)) {\n if (recordScope.tenantId) ensureTenantScope(ctx, recordScope.tenantId)\n if (recordScope.organizationId) ensureOrganizationScope(ctx, recordScope.organizationId)\n }\n }\n return record\n}\n\nexport async function findScopedCustomerCommandTarget<Entity extends object, Hint extends string = never>(\n em: EntityManager,\n entity: EntityName<Entity>,\n where: Record<string, unknown>,\n options: Parameters<typeof findOneWithDecryption<Entity, Hint>>[3],\n ctx: CommandRuntimeContext,\n): Promise<Entity | null> {\n const lookup = buildCustomerCommandLookup(where, ctx)\n return findOneWithDecryption<Entity, Hint>(em, entity, lookup.where as FilterQuery<Entity>, options, lookup.scope)\n}\n\nexport async function requireCustomerEntity(\n em: EntityManager,\n id: string,\n scope: CustomerEntityScope,\n kind?: CustomerEntityKind,\n message = 'Customer entity not found'\n): Promise<CustomerEntity> {\n const entity = await findOneWithDecryption(\n em,\n CustomerEntity,\n {\n id,\n deletedAt: null,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n },\n undefined,\n scope,\n )\n if (!entity) throw notFound(message)\n if (kind && entity.kind !== kind) {\n throw new CrudHttpError(400, { error: 'Invalid entity type' })\n }\n return entity\n}\n\nexport async function requireTimelineParentEntity(\n em: EntityManager,\n id: string,\n scope: CustomerEntityScope,\n): Promise<CustomerEntity> {\n const entity = await findOneWithDecryption(\n em,\n CustomerEntity,\n {\n id,\n deletedAt: null,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n },\n undefined,\n scope,\n )\n if (entity) {\n if (entity.kind !== 'person' && entity.kind !== 'company') {\n throw new CrudHttpError(422, { error: 'entityId must reference a person or company' })\n }\n return entity\n }\n const deal = await findOneWithDecryption(\n em,\n CustomerDeal,\n {\n id,\n deletedAt: null,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n },\n undefined,\n scope,\n )\n if (deal) {\n throw new CrudHttpError(422, { error: 'entityId must reference a person or company, not a deal' })\n }\n throw notFound('Customer not found')\n}\n\n// Profile columns, custom fields, and tags all live outside CustomerEntity, so a\n// save that only touches one of them never dirties the entity and its `updated_at`\n// (the optimistic-lock version) would stay put \u2014 letting a stale second tab\n// overwrite the change without a 409 (#7033, #8643). Bump it explicitly whenever\n// any sub-collection changed.\nexport function shouldBumpOptimisticLockVersion(\n profileFieldsUpdated: boolean,\n custom: Record<string, unknown>,\n tags: string[] | undefined | null\n): boolean {\n return profileFieldsUpdated || Object.keys(custom).length > 0 || tags !== undefined\n}\n\nexport async function syncEntityTags(\n em: EntityManager,\n entity: CustomerEntity,\n tags: string[] | undefined | null\n): Promise<void> {\n if (tags === undefined) return\n const desired = Array.from(new Set((tags ?? []).filter((id) => typeof id === 'string')))\n const existing = await loadEntityTagIds(em, entity)\n const toRemove = existing.filter((id) => !desired.includes(id))\n if (toRemove.length) {\n await em.nativeDelete(CustomerTagAssignment, { entity, tag: { $in: toRemove } })\n }\n const toAdd = desired.filter((id) => !existing.includes(id))\n if (!toAdd.length) return\n const tagsInScope = await em.find(CustomerTag, {\n id: { $in: toAdd },\n organizationId: entity.organizationId,\n tenantId: entity.tenantId,\n })\n if (tagsInScope.length !== toAdd.length) {\n throw new CrudHttpError(400, { error: 'One or more tags not found for this scope' })\n }\n for (const tag of toAdd) {\n const assignment = em.create(CustomerTagAssignment, {\n tenantId: entity.tenantId,\n organizationId: entity.organizationId,\n tag: em.getReference(CustomerTag, tag),\n entity,\n })\n em.persist(assignment)\n }\n}\n\nexport async function loadEntityTagIds(em: EntityManager, entity: CustomerEntity): Promise<string[]> {\n const scope = { tenantId: entity.tenantId, organizationId: entity.organizationId }\n const assignments = await findWithDecryption(\n em,\n CustomerTagAssignment,\n { entity, ...scope },\n { populate: ['tag'] },\n scope,\n )\n return assignments.map((assignment) =>\n typeof assignment.tag === 'string' ? assignment.tag : assignment.tag.id\n )\n}\n\nexport async function requireDealInScope(\n em: EntityManager,\n dealId: string | null | undefined,\n tenantId: string,\n organizationId: string\n): Promise<CustomerDeal | null> {\n if (!dealId) return null\n const deal = await findOneWithDecryption(\n em,\n CustomerDeal,\n { id: dealId, deletedAt: null, tenantId, organizationId },\n undefined,\n { tenantId, organizationId },\n )\n if (!deal) throw new CrudHttpError(400, { error: 'Deal not found' })\n ensureSameScope(deal, organizationId, tenantId)\n return deal\n}\n\nconst DICTIONARY_KINDS = new Set([\n 'status',\n 'source',\n 'lifecycle_stage',\n 'address_type',\n 'activity_type',\n 'deal_status',\n 'pipeline_stage',\n 'job_title',\n 'industry',\n 'temperature',\n 'renewal_quarter',\n 'person_company_role',\n 'interaction_status',\n])\n\nconst CUSTOM_DICTIONARY_KIND_PATTERN = /^[a-z0-9]+(?:[-_][a-z0-9]+)*$/\n\nexport async function ensureDictionaryEntry(\n em: EntityManager,\n params: {\n tenantId: string\n organizationId: string\n kind: string\n value: string\n label?: string | null\n color?: string | null | undefined\n icon?: string | null | undefined\n },\n createdKinds?: Set<string>,\n): Promise<CustomerDictionaryEntry | null> {\n const trimmed = params.value?.trim()\n if (!trimmed) return null\n if (!DICTIONARY_KINDS.has(params.kind) && !CUSTOM_DICTIONARY_KIND_PATTERN.test(params.kind)) {\n throw new CrudHttpError(400, { error: 'Unsupported dictionary kind' })\n }\n const normalized = trimmed.toLowerCase()\n const color = params.color === undefined ? undefined : normalizeDictionaryColor(params.color)\n const icon = params.icon === undefined ? undefined : normalizeDictionaryIcon(params.icon)\n const scope = {\n tenantId: params.tenantId,\n organizationId: params.organizationId,\n kind: params.kind,\n normalizedValue: normalized,\n }\n const now = new Date()\n let entry = await em.findOne(CustomerDictionaryEntry, scope)\n if (!entry) {\n // Concurrent writers may insert the same entry; ON CONFLICT DO NOTHING keeps the caller's transaction alive.\n entry = await em.upsert(\n CustomerDictionaryEntry,\n {\n ...scope,\n value: trimmed,\n label: params.label?.trim() || trimmed,\n color: color ?? null,\n icon: icon ?? null,\n createdAt: now,\n updatedAt: now,\n },\n { onConflictFields: ['organizationId', 'tenantId', 'kind', 'normalizedValue'], onConflictAction: 'ignore' },\n )\n createdKinds?.add(params.kind)\n }\n let changed = false\n if (color !== undefined && entry.color !== color) {\n entry.color = color ?? null\n changed = true\n }\n if (icon !== undefined && entry.icon !== icon) {\n entry.icon = icon ?? null\n changed = true\n }\n if (changed) {\n entry.updatedAt = now\n em.persist(entry)\n }\n return entry\n}\n\nexport async function invalidateDictionaryKindCaches(\n ctx: CommandRuntimeContext,\n scope: CustomerEntityScope,\n kinds: Iterable<string>,\n): Promise<void> {\n const distinctKinds = Array.from(new Set(kinds))\n if (!distinctKinds.length) return\n let cache: CacheStrategy | undefined\n try {\n cache = ctx.container.resolve('cache') as CacheStrategy\n } catch (err) {\n logger.warn('cache resolve failed; skipping dictionary invalidation', { component: 'commands.shared', err })\n return\n }\n for (const mappedKind of distinctKinds) {\n await invalidateDictionaryCache(cache, {\n tenantId: scope.tenantId,\n mappedKind,\n organizationIds: [scope.organizationId],\n })\n }\n}\n\nexport function resolveParentResourceKind(entityKind: CustomerEntityKind | string | null | undefined): string | null {\n if (entityKind === 'company') return 'customers.company'\n if (entityKind === 'person') return 'customers.person'\n return null\n}\n\nexport type QueryIndexEventEntry = {\n entityType: string\n recordId: string\n tenantId: string | null\n organizationId: string | null\n}\n\ntype QueryIndexEventKind = 'delete' | 'upsert'\n\nfunction normalizeEventEntries(entries: readonly QueryIndexEventEntry[]): QueryIndexEventEntry[] {\n const map = new Map<string, QueryIndexEventEntry>()\n for (const entry of entries) {\n if (!entry || typeof entry !== 'object') continue\n const entityType = String(entry.entityType ?? '')\n const recordId = String(entry.recordId ?? '')\n if (!entityType || !recordId) continue\n const key = [\n entityType,\n recordId,\n entry.organizationId ?? '__org__',\n entry.tenantId ?? '__tenant__',\n ].join('|')\n if (!map.has(key)) {\n map.set(key, {\n entityType,\n recordId,\n organizationId: entry.organizationId ?? null,\n tenantId: entry.tenantId ?? null,\n })\n }\n }\n return Array.from(map.values())\n}\n\nasync function emitQueryIndexEvents(\n ctx: CommandRuntimeContext,\n entries: readonly QueryIndexEventEntry[],\n kind: QueryIndexEventKind,\n): Promise<void> {\n const normalized = normalizeEventEntries(entries)\n if (!normalized.length) return\n\n let bus: EventBus | null = null\n try {\n bus = ctx.container.resolve<EventBus>('eventBus')\n } catch (err) {\n logger.warn('eventBus resolve failed; skipping query index events', { component: 'commands.shared', err })\n bus = null\n }\n if (!bus) return\n\n const eventName = kind === 'delete' ? 'query_index.delete_one' : 'query_index.upsert_one'\n const crudAction = kind === 'delete' ? 'deleted' : 'updated'\n\n await Promise.all(\n normalized.map((entry) =>\n bus!\n .emitEvent(\n eventName,\n {\n entityType: entry.entityType,\n recordId: entry.recordId,\n organizationId: entry.organizationId ?? null,\n tenantId: entry.tenantId ?? null,\n crudAction,\n },\n {\n tenantId: entry.tenantId ?? null,\n organizationId: entry.organizationId ?? null,\n },\n )\n .catch((err) => {\n logger.warn('Query index emitEvent failed', { component: 'commands.shared', entry, err })\n return undefined\n }),\n ),\n )\n}\n\nexport async function emitQueryIndexDeleteEvents(\n ctx: CommandRuntimeContext,\n entries: readonly QueryIndexEventEntry[],\n): Promise<void> {\n await emitQueryIndexEvents(ctx, entries, 'delete')\n}\n\nexport async function emitQueryIndexUpsertEvents(\n ctx: CommandRuntimeContext,\n entries: readonly QueryIndexEventEntry[],\n): Promise<void> {\n await emit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Z,WAAW;AAAA,MAAI,CAAC,UACd,IACG;AAAA,QACC;AAAA,QACA;AAAA,UACE,YAAY,MAAM;AAAA,UAClB,UAAU,MAAM;AAAA,UAChB,gBAAgB,MAAM,kBAAkB;AAAA,UACxC,UAAU,MAAM,YAAY;AAAA,UAC5B;AAAA,QACF;AAAA,QACA;AAAA,UACE,UAAU,MAAM,YAAY;AAAA,UAC5B,gBAAgB,MAAM,kBAAkB;AAAA,QAC1C;AAAA,MACF,EACC,MAAM,CAAC,QAAQ;AACd,eAAO,KAAK,gCAAgC,EAAE,WAAW,mBAAmB,OAAO,IAAI,CAAC;AACxF,eAAO;AAAA,MACT,CAAC;AAAA,IACL;AAAA,EACF;AACF;AAEA,eAAsB,2BACpB,KACA,SACe;AACf,QAAM,qBAAqB,KAAK,SAAS,QAAQ;AACnD;AAEA,eAAsB,2BACpB,KACA,SACe;AACf,QAAM,qBAAqB,KAAK,SAAS,QAAQ;AACnD;",
4
+ "sourcesContent": ["import type { EntityManager, EntityName, FilterQuery } from '@mikro-orm/postgresql'\nimport { CustomerDeal, CustomerEntity, CustomerTag, CustomerTagAssignment, CustomerDictionaryEntry, type CustomerEntityKind } from '../data/entities'\nimport { CrudHttpError, forbidden, notFound } from '@open-mercato/shared/lib/crud/errors'\nimport { buildScopedWhere } from '@open-mercato/shared/lib/api/crud'\nimport { isUnrestrictedOrganizationScope } from '@open-mercato/shared/lib/auth/organizationAccess'\nimport type { CommandRuntimeContext } from '@open-mercato/shared/lib/commands'\nimport { ensureOrganizationScope, ensureSameScope, ensureTenantScope } from '@open-mercato/shared/lib/commands/scope'\nimport { loadEntityRecordScope } from '@open-mercato/shared/lib/db/recordScope'\nimport { findOneWithDecryption, findWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport type { EventBus } from '@open-mercato/events'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\nimport type { CacheStrategy } from '@open-mercato/cache'\nimport { invalidateDictionaryCache } from '../api/dictionaries/cache'\n\nconst logger = createLogger('customers')\nexport { ensureOrganizationScope, ensureSameScope, ensureTenantScope } from '@open-mercato/shared/lib/commands/scope'\nexport { extractUndoPayload } from '@open-mercato/shared/lib/commands/undo'\n\nexport const CUSTOMER_ENTITY_UNDO_DATE_OPTIONS = {\n datePaths: ['before.entity.nextInteractionAt'],\n} as const\n\nexport function normalizeDictionaryColor(input: unknown): string | null {\n if (typeof input !== 'string') return null\n const trimmed = input.trim()\n if (!trimmed) return null\n const hexMatch = /^#([0-9a-fA-F]{6})$/.exec(trimmed)\n if (!hexMatch) return null\n return `#${hexMatch[1].toLowerCase()}`\n}\n\nexport function normalizeDictionaryIcon(input: unknown): string | null {\n if (typeof input !== 'string') return null\n const trimmed = input.trim()\n if (!trimmed) return null\n return trimmed.slice(0, 48)\n}\n\nexport { assertFound } from '@open-mercato/shared/lib/crud/errors'\n\nexport type CommandScopeWhere = {\n tenantId?: string\n organizationId?: { $in: string[] }\n}\n\n// Filter to merge into a write command's target lookup so ids outside the caller's\n// tenant (from auth, or organizationScope.tenantId for auth-less callers) and, for\n// restricted callers, outside the allowed organizations resolve as \"not found\"\n// instead of being loaded and rejected afterwards. The ensure*Scope checks stay as\n// the second layer (#7598, mirrors catalog #3825).\nexport function commandScopeWhere(\n ctx: Pick<CommandRuntimeContext, 'auth' | 'organizationScope'>,\n): CommandScopeWhere {\n const where: CommandScopeWhere = {}\n const tenantId = ctx.auth ? ctx.auth.tenantId ?? null : ctx.organizationScope?.tenantId ?? null\n if (tenantId) where.tenantId = tenantId\n const allowedIds = ctx.organizationScope?.allowedIds\n if (ctx.auth?.isSuperAdmin !== true && Array.isArray(allowedIds)) {\n where.organizationId = { $in: [...allowedIds] }\n }\n return where\n}\n\nexport type CustomerEntityScope = {\n tenantId: string\n organizationId: string\n}\n\nexport function buildCustomerCommandLookup(where: Record<string, unknown>, ctx: CommandRuntimeContext) {\n const isSuperAdmin = ctx.auth?.isSuperAdmin === true\n const organizationScope = ctx.organizationScope\n const tenantId = ctx.auth ? (ctx.auth.tenantId ?? null) : (organizationScope?.tenantId ?? null)\n if (ctx.auth && !isSuperAdmin && (!tenantId || (organizationScope && !organizationScope.tenantId))) {\n throw forbidden()\n }\n let organizationIds: string[] | undefined\n if (organizationScope) {\n if (!isUnrestrictedOrganizationScope({ isSuperAdmin, allowedOrganizationIds: organizationScope.allowedIds })) {\n organizationIds = organizationScope.allowedIds ?? []\n }\n } else if (!isSuperAdmin) {\n const organizationId = ctx.selectedOrganizationId ?? ctx.auth?.orgId\n if (organizationId) organizationIds = [organizationId]\n }\n return {\n where: buildScopedWhere(where, {\n tenantId: tenantId ?? undefined,\n organizationIds,\n softDeleteField: null,\n }),\n scope: { tenantId, organizationId: organizationIds?.length === 1 ? organizationIds[0] : null },\n }\n}\n\nexport async function findScopedCustomerCommandRecord<Entity extends object, Hint extends string = never>(\n em: EntityManager,\n entity: EntityName<Entity>,\n where: Record<string, unknown>,\n options: Parameters<typeof findOneWithDecryption<Entity, Hint>>[3],\n ctx: CommandRuntimeContext,\n): Promise<Entity | null> {\n const record = await findScopedCustomerCommandTarget(em, entity, where, options, ctx)\n if (!record && ctx.auth && typeof where.id === 'string') {\n const entityType = em.getMetadata().get(entity).className\n const recordScope = await loadEntityRecordScope(em as unknown as Parameters<typeof loadEntityRecordScope>[0], entityType, where.id)\n if (recordScope && await em.count(entity, { ...where, ...recordScope } as FilterQuery<NoInfer<Entity>>)) {\n if (recordScope.tenantId) ensureTenantScope(ctx, recordScope.tenantId)\n if (recordScope.organizationId) ensureOrganizationScope(ctx, recordScope.organizationId)\n }\n }\n return record\n}\n\nexport async function findScopedCustomerCommandTarget<Entity extends object, Hint extends string = never>(\n em: EntityManager,\n entity: EntityName<Entity>,\n where: Record<string, unknown>,\n options: Parameters<typeof findOneWithDecryption<Entity, Hint>>[3],\n ctx: CommandRuntimeContext,\n): Promise<Entity | null> {\n const lookup = buildCustomerCommandLookup(where, ctx)\n return findOneWithDecryption<Entity, Hint>(em, entity, lookup.where as FilterQuery<Entity>, options, lookup.scope)\n}\n\nexport async function requireCustomerEntity(\n em: EntityManager,\n id: string,\n scope: CustomerEntityScope,\n kind?: CustomerEntityKind,\n message = 'Customer entity not found'\n): Promise<CustomerEntity> {\n const entity = await findOneWithDecryption(\n em,\n CustomerEntity,\n {\n id,\n deletedAt: null,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n },\n undefined,\n scope,\n )\n if (!entity) throw notFound(message)\n if (kind && entity.kind !== kind) {\n throw new CrudHttpError(400, { error: 'Invalid entity type' })\n }\n return entity\n}\n\nexport async function requireTimelineParentEntity(\n em: EntityManager,\n id: string,\n scope: CustomerEntityScope,\n): Promise<CustomerEntity> {\n const entity = await findOneWithDecryption(\n em,\n CustomerEntity,\n {\n id,\n deletedAt: null,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n },\n undefined,\n scope,\n )\n if (entity) {\n if (entity.kind !== 'person' && entity.kind !== 'company') {\n throw new CrudHttpError(422, { error: 'entityId must reference a person or company' })\n }\n return entity\n }\n const deal = await findOneWithDecryption(\n em,\n CustomerDeal,\n {\n id,\n deletedAt: null,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n },\n undefined,\n scope,\n )\n if (deal) {\n throw new CrudHttpError(422, { error: 'entityId must reference a person or company, not a deal' })\n }\n throw notFound('Customer not found')\n}\n\n// Profile columns, custom fields, and tags all live outside CustomerEntity, so a\n// save that only touches one of them never dirties the entity and its `updated_at`\n// (the optimistic-lock version) would stay put \u2014 letting a stale second tab\n// overwrite the change without a 409 (#7033, #8643). Bump it explicitly whenever\n// any sub-collection changed.\nexport function shouldBumpOptimisticLockVersion(\n profileFieldsUpdated: boolean,\n custom: Record<string, unknown>,\n tags: string[] | undefined | null\n): boolean {\n return profileFieldsUpdated || Object.keys(custom).length > 0 || tags !== undefined\n}\n\nexport async function syncEntityTags(\n em: EntityManager,\n entity: CustomerEntity,\n tags: string[] | undefined | null,\n { ignoreMissing = false }: { ignoreMissing?: boolean } = {},\n): Promise<void> {\n if (tags === undefined) return\n const requested = (tags ?? []).filter((id) => typeof id === 'string')\n const desired = Array.from(new Set(ignoreMissing ? requested.map((id) => id.toLowerCase()) : requested))\n const existing = await loadEntityTagIds(em, entity)\n const toRemove = existing.filter((id) => !desired.includes(id))\n if (toRemove.length) {\n await em.nativeDelete(CustomerTagAssignment, { entity, tag: { $in: toRemove } })\n }\n const toAdd = desired.filter((id) => !existing.includes(id))\n if (!toAdd.length) return\n const tagsInScope = await em.find(CustomerTag, {\n id: { $in: toAdd },\n organizationId: entity.organizationId,\n tenantId: entity.tenantId,\n })\n if (!ignoreMissing && tagsInScope.length !== toAdd.length) {\n throw new CrudHttpError(400, { error: 'One or more tags not found for this scope' })\n }\n const tagsToAssign = ignoreMissing ? tagsInScope.map(({ id }) => id) : toAdd\n for (const tag of tagsToAssign) {\n const assignment = em.create(CustomerTagAssignment, {\n tenantId: entity.tenantId,\n organizationId: entity.organizationId,\n tag: em.getReference(CustomerTag, tag),\n entity,\n })\n em.persist(assignment)\n }\n}\n\nexport async function loadEntityTagIds(em: EntityManager, entity: CustomerEntity): Promise<string[]> {\n const scope = { tenantId: entity.tenantId, organizationId: entity.organizationId }\n const assignments = await findWithDecryption(\n em,\n CustomerTagAssignment,\n { entity, ...scope },\n { populate: ['tag'] },\n scope,\n )\n return assignments.map((assignment) =>\n typeof assignment.tag === 'string' ? assignment.tag : assignment.tag.id\n )\n}\n\nexport async function requireDealInScope(\n em: EntityManager,\n dealId: string | null | undefined,\n tenantId: string,\n organizationId: string\n): Promise<CustomerDeal | null> {\n if (!dealId) return null\n const deal = await findOneWithDecryption(\n em,\n CustomerDeal,\n { id: dealId, deletedAt: null, tenantId, organizationId },\n undefined,\n { tenantId, organizationId },\n )\n if (!deal) throw new CrudHttpError(400, { error: 'Deal not found' })\n ensureSameScope(deal, organizationId, tenantId)\n return deal\n}\n\nconst DICTIONARY_KINDS = new Set([\n 'status',\n 'source',\n 'lifecycle_stage',\n 'address_type',\n 'activity_type',\n 'deal_status',\n 'pipeline_stage',\n 'job_title',\n 'industry',\n 'temperature',\n 'renewal_quarter',\n 'person_company_role',\n 'interaction_status',\n])\n\nconst CUSTOM_DICTIONARY_KIND_PATTERN = /^[a-z0-9]+(?:[-_][a-z0-9]+)*$/\n\nexport async function ensureDictionaryEntry(\n em: EntityManager,\n params: {\n tenantId: string\n organizationId: string\n kind: string\n value: string\n label?: string | null\n color?: string | null | undefined\n icon?: string | null | undefined\n },\n createdKinds?: Set<string>,\n): Promise<CustomerDictionaryEntry | null> {\n const trimmed = params.value?.trim()\n if (!trimmed) return null\n if (!DICTIONARY_KINDS.has(params.kind) && !CUSTOM_DICTIONARY_KIND_PATTERN.test(params.kind)) {\n throw new CrudHttpError(400, { error: 'Unsupported dictionary kind' })\n }\n const normalized = trimmed.toLowerCase()\n const color = params.color === undefined ? undefined : normalizeDictionaryColor(params.color)\n const icon = params.icon === undefined ? undefined : normalizeDictionaryIcon(params.icon)\n const scope = {\n tenantId: params.tenantId,\n organizationId: params.organizationId,\n kind: params.kind,\n normalizedValue: normalized,\n }\n const now = new Date()\n let entry = await em.findOne(CustomerDictionaryEntry, scope)\n if (!entry) {\n // Concurrent writers may insert the same entry; ON CONFLICT DO NOTHING keeps the caller's transaction alive.\n entry = await em.upsert(\n CustomerDictionaryEntry,\n {\n ...scope,\n value: trimmed,\n label: params.label?.trim() || trimmed,\n color: color ?? null,\n icon: icon ?? null,\n createdAt: now,\n updatedAt: now,\n },\n { onConflictFields: ['organizationId', 'tenantId', 'kind', 'normalizedValue'], onConflictAction: 'ignore' },\n )\n createdKinds?.add(params.kind)\n }\n let changed = false\n if (color !== undefined && entry.color !== color) {\n entry.color = color ?? null\n changed = true\n }\n if (icon !== undefined && entry.icon !== icon) {\n entry.icon = icon ?? null\n changed = true\n }\n if (changed) {\n entry.updatedAt = now\n em.persist(entry)\n }\n return entry\n}\n\nexport async function invalidateDictionaryKindCaches(\n ctx: CommandRuntimeContext,\n scope: CustomerEntityScope,\n kinds: Iterable<string>,\n): Promise<void> {\n const distinctKinds = Array.from(new Set(kinds))\n if (!distinctKinds.length) return\n let cache: CacheStrategy | undefined\n try {\n cache = ctx.container.resolve('cache') as CacheStrategy\n } catch (err) {\n logger.warn('cache resolve failed; skipping dictionary invalidation', { component: 'commands.shared', err })\n return\n }\n for (const mappedKind of distinctKinds) {\n await invalidateDictionaryCache(cache, {\n tenantId: scope.tenantId,\n mappedKind,\n organizationIds: [scope.organizationId],\n })\n }\n}\n\nexport function resolveParentResourceKind(entityKind: CustomerEntityKind | string | null | undefined): string | null {\n if (entityKind === 'company') return 'customers.company'\n if (entityKind === 'person') return 'customers.person'\n return null\n}\n\nexport type QueryIndexEventEntry = {\n entityType: string\n recordId: string\n tenantId: string | null\n organizationId: string | null\n}\n\ntype QueryIndexEventKind = 'delete' | 'upsert'\n\nfunction normalizeEventEntries(entries: readonly QueryIndexEventEntry[]): QueryIndexEventEntry[] {\n const map = new Map<string, QueryIndexEventEntry>()\n for (const entry of entries) {\n if (!entry || typeof entry !== 'object') continue\n const entityType = String(entry.entityType ?? '')\n const recordId = String(entry.recordId ?? '')\n if (!entityType || !recordId) continue\n const key = [\n entityType,\n recordId,\n entry.organizationId ?? '__org__',\n entry.tenantId ?? '__tenant__',\n ].join('|')\n if (!map.has(key)) {\n map.set(key, {\n entityType,\n recordId,\n organizationId: entry.organizationId ?? null,\n tenantId: entry.tenantId ?? null,\n })\n }\n }\n return Array.from(map.values())\n}\n\nasync function emitQueryIndexEvents(\n ctx: CommandRuntimeContext,\n entries: readonly QueryIndexEventEntry[],\n kind: QueryIndexEventKind,\n): Promise<void> {\n const normalized = normalizeEventEntries(entries)\n if (!normalized.length) return\n\n let bus: EventBus | null = null\n try {\n bus = ctx.container.resolve<EventBus>('eventBus')\n } catch (err) {\n logger.warn('eventBus resolve failed; skipping query index events', { component: 'commands.shared', err })\n bus = null\n }\n if (!bus) return\n\n const eventName = kind === 'delete' ? 'query_index.delete_one' : 'query_index.upsert_one'\n const crudAction = kind === 'delete' ? 'deleted' : 'updated'\n\n await Promise.all(\n normalized.map((entry) =>\n bus!\n .emitEvent(\n eventName,\n {\n entityType: entry.entityType,\n recordId: entry.recordId,\n organizationId: entry.organizationId ?? null,\n tenantId: entry.tenantId ?? null,\n crudAction,\n },\n {\n tenantId: entry.tenantId ?? null,\n organizationId: entry.organizationId ?? null,\n },\n )\n .catch((err) => {\n logger.warn('Query index emitEvent failed', { component: 'commands.shared', entry, err })\n return undefined\n }),\n ),\n )\n}\n\nexport async function emitQueryIndexDeleteEvents(\n ctx: CommandRuntimeContext,\n entries: readonly QueryIndexEventEntry[],\n): Promise<void> {\n await emitQueryIndexEvents(ctx, entries, 'delete')\n}\n\nexport async function emitQueryIndexUpsertEvents(\n ctx: CommandRuntimeContext,\n entries: readonly QueryIndexEventEntry[],\n): Promise<void> {\n await emitQueryIndexEvents(ctx, entries, 'upsert')\n}\n"],
5
+ "mappings": "AACA,SAAS,cAAc,gBAAgB,aAAa,uBAAuB,+BAAwD;AACnI,SAAS,eAAe,WAAW,gBAAgB;AACnD,SAAS,wBAAwB;AACjC,SAAS,uCAAuC;AAEhD,SAAS,yBAAyB,iBAAiB,yBAAyB;AAC5E,SAAS,6BAA6B;AACtC,SAAS,uBAAuB,0BAA0B;AAE1D,SAAS,oBAAoB;AAE7B,SAAS,iCAAiC;AAE1C,MAAM,SAAS,aAAa,WAAW;AACvC,SAAS,2BAAAA,0BAAyB,mBAAAC,kBAAiB,qBAAAC,0BAAyB;AAC5E,SAAS,0BAA0B;AAE5B,MAAM,oCAAoC;AAAA,EAC/C,WAAW,CAAC,iCAAiC;AAC/C;AAEO,SAAS,yBAAyB,OAA+B;AACtE,MAAI,OAAO,UAAU,SAAU,QAAO;AACtC,QAAM,UAAU,MAAM,KAAK;AAC3B,MAAI,CAAC,QAAS,QAAO;AACrB,QAAM,WAAW,sBAAsB,KAAK,OAAO;AACnD,MAAI,CAAC,SAAU,QAAO;AACtB,SAAO,IAAI,SAAS,CAAC,EAAE,YAAY,CAAC;AAC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eAAsB,2BACpB,KACA,SACe;AACf,QAAM,qBAAqB,KAAK,SAAS,QAAQ;AACnD;",
6
6
  "names": ["ensureOrganizationScope", "ensureSameScope", "ensureTenantScope"]
7
7
  }
@@ -516,7 +516,8 @@ async function applyDocumentUpdate({
516
516
  kind,
517
517
  entity,
518
518
  input,
519
- em
519
+ em,
520
+ ignoreMissingTags
520
521
  }) {
521
522
  const organizationId = entity.organizationId;
522
523
  const tenantId = entity.tenantId;
@@ -875,7 +876,8 @@ async function applyDocumentUpdate({
875
876
  kind,
876
877
  organizationId,
877
878
  tenantId,
878
- tagIds: input.tags
879
+ tagIds: input.tags,
880
+ ignoreMissing: ignoreMissingTags
879
881
  });
880
882
  }
881
883
  if (input.customFieldSetId !== void 0) {
@@ -2720,15 +2722,13 @@ function buildDocumentUpdateChangeKeys(kind, input) {
2720
2722
  }
2721
2723
  async function syncSalesDocumentTags(em, params) {
2722
2724
  if (params.tagIds === void 0) return;
2723
- const tagIds = normalizeTagIds(params.tagIds);
2725
+ const tagIds = normalizeTagIds(
2726
+ params.ignoreMissing ? params.tagIds?.map((id) => id?.toLowerCase()) : params.tagIds
2727
+ );
2724
2728
  const byId = /* @__PURE__ */ new Map();
2725
2729
  if (tagIds.length > 0) {
2726
- const tagsInScope = await em.find(SalesDocumentTag, {
2727
- id: { $in: tagIds },
2728
- organizationId: params.organizationId,
2729
- tenantId: params.tenantId
2730
- });
2731
- if (tagsInScope.length !== tagIds.length) {
2730
+ const tagsInScope = await findScopedDocumentTags(em, tagIds, params);
2731
+ if (!params.ignoreMissing && tagsInScope.length !== tagIds.length) {
2732
2732
  throw new CrudHttpError(400, {
2733
2733
  error: "One or more tags not found for this scope"
2734
2734
  });
@@ -2744,7 +2744,7 @@ async function syncSalesDocumentTags(em, params) {
2744
2744
  const tagId = readAssignmentTagId(assignment);
2745
2745
  if (tagId) existingByTagId.set(tagId, assignment);
2746
2746
  });
2747
- const wanted = new Set(tagIds);
2747
+ const wanted = new Set(params.ignoreMissing ? byId.keys() : tagIds);
2748
2748
  const toRemove = existing.filter((assignment) => {
2749
2749
  const tagId = readAssignmentTagId(assignment);
2750
2750
  return tagId === null || !wanted.has(tagId);
@@ -2767,6 +2767,20 @@ async function syncSalesDocumentTags(em, params) {
2767
2767
  em.persist(assignment);
2768
2768
  }
2769
2769
  }
2770
+ function findScopedDocumentTags(em, tagIds, { organizationId, tenantId }) {
2771
+ return em.find(SalesDocumentTag, {
2772
+ id: { $in: tagIds },
2773
+ organizationId,
2774
+ tenantId
2775
+ });
2776
+ }
2777
+ async function survivingTagAssignments(em, assignments, scope) {
2778
+ if (!Array.isArray(assignments) || !assignments.length) return [];
2779
+ const tagIds = normalizeTagIds(assignments.map(({ tagId }) => tagId));
2780
+ const tags = await findScopedDocumentTags(em, tagIds, scope);
2781
+ const availableIds = new Set(tags.map(({ id }) => id));
2782
+ return assignments.filter(({ tagId }) => availableIds.has(tagId));
2783
+ }
2770
2784
  function applyQuoteSnapshot(quote, snapshot) {
2771
2785
  quote.organizationId = snapshot.organizationId;
2772
2786
  quote.tenantId = snapshot.tenantId;
@@ -2863,7 +2877,7 @@ function applyOrderSnapshot(order, snapshot) {
2863
2877
  }
2864
2878
  async function assertQuoteGraphUndoCurrent(em, quoteId, expected) {
2865
2879
  const current = await loadQuoteSnapshot(em, quoteId);
2866
- const unchanged = !!current && sameIds(current.lines, expected.lines) && sameIds(current.adjustments, expected.adjustments) && sameRecords(current.notes, expected.notes) && sameRecords(current.tags, expected.tags) && sameRecords(current.addresses, expected.addresses);
2880
+ const unchanged = !!current && sameIds(current.lines, expected.lines) && sameIds(current.adjustments, expected.adjustments) && sameRecords(current.notes, expected.notes) && sameRecords(current.addresses, expected.addresses) && (sameRecords(current.tags, expected.tags) || sameRecords(current.tags, await survivingTagAssignments(em, expected.tags, expected.quote)));
2867
2881
  if (!unchanged) return throwDocumentUndoStale("quote");
2868
2882
  }
2869
2883
  async function undoQuoteGraph(ctx, before, after) {
@@ -2986,7 +3000,7 @@ async function restoreQuoteGraph(em, snapshot, verified = null) {
2986
3000
  }
2987
3001
  const addressSnapshots = Array.isArray(snapshot.addresses) ? snapshot.addresses : [];
2988
3002
  const noteSnapshots = Array.isArray(snapshot.notes) ? snapshot.notes : [];
2989
- const tagSnapshots = Array.isArray(snapshot.tags) ? snapshot.tags : [];
3003
+ const tagSnapshots = await survivingTagAssignments(em, snapshot.tags, quote);
2990
3004
  const verifiedIds = (entries) => verified ? { id: { $in: (entries ?? []).map((entry) => entry.id) } } : {};
2991
3005
  await em.nativeDelete(SalesDocumentAddress, {
2992
3006
  documentId: quote.id,
@@ -3237,7 +3251,7 @@ async function assertOrderGraphUndoCurrent(em, orderId, expected) {
3237
3251
  if (returnCount > 0 || invoiceLineCount > 0 || creditMemoLineCount > 0) {
3238
3252
  return throwDocumentUndoStale("order");
3239
3253
  }
3240
- const unchanged = sameLineProgress(current.lines, expected.lines) && sameIds(current.adjustments, expected.adjustments) && sameRecords(current.shipments, expected.shipments) && sameRecords(withoutAllocationIds(current.payments), withoutAllocationIds(expected.payments)) && sameRecords(current.notes, expected.notes) && sameRecords(current.tags, expected.tags) && sameRecords(current.addresses, expected.addresses);
3254
+ const unchanged = sameLineProgress(current.lines, expected.lines) && sameIds(current.adjustments, expected.adjustments) && sameRecords(current.shipments, expected.shipments) && sameRecords(withoutAllocationIds(current.payments), withoutAllocationIds(expected.payments)) && sameRecords(current.notes, expected.notes) && sameRecords(current.addresses, expected.addresses) && (sameRecords(current.tags, expected.tags) || sameRecords(current.tags, await survivingTagAssignments(em, expected.tags, expected.order)));
3241
3255
  if (!unchanged) return throwDocumentUndoStale("order");
3242
3256
  }
3243
3257
  async function lockOrderForUndo(em, orderId, scope) {
@@ -3412,7 +3426,7 @@ async function restoreOrderGraph(em, snapshot, verified = null) {
3412
3426
  }
3413
3427
  const addressSnapshots = Array.isArray(snapshot.addresses) ? snapshot.addresses : [];
3414
3428
  const noteSnapshots = Array.isArray(snapshot.notes) ? snapshot.notes : [];
3415
- const tagSnapshots = Array.isArray(snapshot.tags) ? snapshot.tags : [];
3429
+ const tagSnapshots = await survivingTagAssignments(em, snapshot.tags, order);
3416
3430
  const shipmentSnapshots = Array.isArray(snapshot.shipments) ? snapshot.shipments : [];
3417
3431
  const paymentSnapshots = Array.isArray(snapshot.payments) ? snapshot.payments : [];
3418
3432
  const existingShipments = await em.find(SalesShipment, { order: order.id });
@@ -3619,7 +3633,7 @@ async function restoreOrderGraph(em, snapshot, verified = null) {
3619
3633
  }
3620
3634
  const createQuoteCommand = {
3621
3635
  id: "sales.quotes.create",
3622
- async execute(rawInput, ctx) {
3636
+ async execute(rawInput, ctx, ignoreMissingTags = false) {
3623
3637
  const generator = ctx.container.resolve(
3624
3638
  "salesDocumentNumberGenerator"
3625
3639
  );
@@ -3837,7 +3851,8 @@ const createQuoteCommand = {
3837
3851
  kind: "quote",
3838
3852
  organizationId: quote.organizationId,
3839
3853
  tenantId: quote.tenantId,
3840
- tagIds: parsed.tags
3854
+ tagIds: parsed.tags,
3855
+ ignoreMissing: ignoreMissingTags
3841
3856
  });
3842
3857
  await setDocumentCustomFieldsIfSupplied(em, {
3843
3858
  entityId: E.sales.sales_quote,
@@ -3954,6 +3969,9 @@ const createQuoteCommand = {
3954
3969
  tx.remove(quote);
3955
3970
  await tx.flush();
3956
3971
  });
3972
+ },
3973
+ redo({ input, ctx }) {
3974
+ return createQuoteCommand.execute(input, ctx, true);
3957
3975
  }
3958
3976
  };
3959
3977
  const deleteQuoteCommand = {
@@ -4248,7 +4266,7 @@ const updateQuoteCommand = {
4248
4266
  }
4249
4267
  return snapshot ? { before: snapshot } : {};
4250
4268
  },
4251
- async execute(rawInput, ctx) {
4269
+ async execute(rawInput, ctx, ignoreMissingTags = false) {
4252
4270
  const parsed = withExactAmounts(
4253
4271
  documentUpdateSchema.parse(rawInput ?? {}),
4254
4272
  rawInput,
@@ -4269,7 +4287,8 @@ const updateQuoteCommand = {
4269
4287
  kind: "quote",
4270
4288
  entity: quote,
4271
4289
  input: parsed,
4272
- em
4290
+ em,
4291
+ ignoreMissingTags
4273
4292
  });
4274
4293
  if (shouldInvalidateSentToken) {
4275
4294
  quote.acceptanceToken = null;
@@ -4439,6 +4458,9 @@ const updateQuoteCommand = {
4439
4458
  const before = payload?.before;
4440
4459
  if (!before) return;
4441
4460
  await undoQuoteGraph(ctx, before, payload?.after);
4461
+ },
4462
+ redo({ input, ctx }) {
4463
+ return updateQuoteCommand.execute(input, ctx, true);
4442
4464
  }
4443
4465
  };
4444
4466
  const orderEntityOutputSchema = z.object({
@@ -4485,7 +4507,7 @@ const updateOrderCommand = {
4485
4507
  }
4486
4508
  return snapshot ? { before: snapshot } : {};
4487
4509
  },
4488
- async execute(rawInput, ctx) {
4510
+ async execute(rawInput, ctx, ignoreMissingTags = false) {
4489
4511
  const parsed = withExactAmounts(
4490
4512
  documentUpdateSchema.parse(rawInput ?? {}),
4491
4513
  rawInput,
@@ -4532,7 +4554,8 @@ const updateOrderCommand = {
4532
4554
  kind: "order",
4533
4555
  entity: order,
4534
4556
  input: parsed,
4535
- em
4557
+ em,
4558
+ ignoreMissingTags
4536
4559
  });
4537
4560
  },
4538
4561
  // Scalar mutations above are persisted by withAtomicFlush's per-phase
@@ -4728,12 +4751,15 @@ const updateOrderCommand = {
4728
4751
  const before = payload?.before;
4729
4752
  if (!before) return;
4730
4753
  await undoOrderGraph(ctx, before, payload?.after);
4754
+ },
4755
+ redo({ input, ctx }) {
4756
+ return updateOrderCommand.execute(input, ctx, true);
4731
4757
  }
4732
4758
  };
4733
4759
  const createOrderCommand = {
4734
4760
  id: "sales.orders.create",
4735
4761
  outputSchema: orderIdOutputSchema,
4736
- async execute(rawInput, ctx) {
4762
+ async execute(rawInput, ctx, ignoreMissingTags = false) {
4737
4763
  const generator = ctx.container.resolve(
4738
4764
  "salesDocumentNumberGenerator"
4739
4765
  );
@@ -5001,7 +5027,8 @@ const createOrderCommand = {
5001
5027
  kind: "order",
5002
5028
  organizationId: order.organizationId,
5003
5029
  tenantId: order.tenantId,
5004
- tagIds: parsed.tags
5030
+ tagIds: parsed.tags,
5031
+ ignoreMissing: ignoreMissingTags
5005
5032
  });
5006
5033
  await setDocumentCustomFieldsIfSupplied(em, {
5007
5034
  entityId: E.sales.sales_order,
@@ -5140,6 +5167,9 @@ const createOrderCommand = {
5140
5167
  await tx.flush();
5141
5168
  }
5142
5169
  );
5170
+ },
5171
+ redo({ input, ctx }) {
5172
+ return createOrderCommand.execute(input, ctx, true);
5143
5173
  }
5144
5174
  };
5145
5175
  const deleteOrderCommand = {