@open-mercato/core 0.10.1-develop.8004.1.a8a79ee43f → 0.10.1-develop.8022.1.b6753de892

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.
Files changed (59) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/dist/modules/audit_logs/components/AuditLogsActions.js +80 -50
  3. package/dist/modules/audit_logs/components/AuditLogsActions.js.map +3 -3
  4. package/dist/modules/audit_logs/lib/rowPresentation.js +82 -0
  5. package/dist/modules/audit_logs/lib/rowPresentation.js.map +7 -0
  6. package/dist/modules/catalog/commands/variants.js +89 -16
  7. package/dist/modules/catalog/commands/variants.js.map +2 -2
  8. package/dist/modules/catalog/seed/examples.js +7 -0
  9. package/dist/modules/catalog/seed/examples.js.map +2 -2
  10. package/dist/modules/customers/api/interactions/route.js +2 -2
  11. package/dist/modules/customers/api/interactions/route.js.map +2 -2
  12. package/dist/modules/customers/components/detail/AssignRoleDialog.js +10 -21
  13. package/dist/modules/customers/components/detail/AssignRoleDialog.js.map +2 -2
  14. package/dist/modules/customers/migrations/Migration20260825140000_customers.js +17 -10
  15. package/dist/modules/customers/migrations/Migration20260825140000_customers.js.map +2 -2
  16. package/dist/modules/entities/cli.js +138 -66
  17. package/dist/modules/entities/cli.js.map +3 -3
  18. package/dist/modules/promotions/commands/codes.js +18 -3
  19. package/dist/modules/promotions/commands/codes.js.map +2 -2
  20. package/dist/modules/query_index/cli.js +17 -1
  21. package/dist/modules/query_index/cli.js.map +2 -2
  22. package/dist/modules/query_index/lib/reindexer.js +23 -5
  23. package/dist/modules/query_index/lib/reindexer.js.map +2 -2
  24. package/dist/modules/sales/commands/configuration.js +30 -16
  25. package/dist/modules/sales/commands/configuration.js.map +2 -2
  26. package/dist/modules/sales/components/documents/AddressesSection.js +36 -15
  27. package/dist/modules/sales/components/documents/AddressesSection.js.map +2 -2
  28. package/dist/modules/sales/seed/examples.js +35 -6
  29. package/dist/modules/sales/seed/examples.js.map +2 -2
  30. package/package.json +7 -7
  31. package/src/modules/audit_logs/components/AuditLogsActions.tsx +85 -48
  32. package/src/modules/audit_logs/i18n/de.json +16 -0
  33. package/src/modules/audit_logs/i18n/en.json +16 -0
  34. package/src/modules/audit_logs/i18n/es.json +16 -0
  35. package/src/modules/audit_logs/i18n/ko.json +16 -0
  36. package/src/modules/audit_logs/i18n/pl.json +16 -0
  37. package/src/modules/audit_logs/lib/rowPresentation.ts +92 -0
  38. package/src/modules/catalog/commands/variants.ts +96 -17
  39. package/src/modules/catalog/seed/examples.ts +7 -0
  40. package/src/modules/customers/api/interactions/route.ts +2 -2
  41. package/src/modules/customers/components/detail/AssignRoleDialog.tsx +9 -12
  42. package/src/modules/customers/i18n/de.json +2 -1
  43. package/src/modules/customers/i18n/en.json +2 -1
  44. package/src/modules/customers/i18n/es.json +2 -1
  45. package/src/modules/customers/i18n/ko.json +2 -1
  46. package/src/modules/customers/i18n/pl.json +2 -1
  47. package/src/modules/customers/migrations/Migration20260825140000_customers.ts +21 -10
  48. package/src/modules/entities/cli.ts +144 -65
  49. package/src/modules/promotions/commands/codes.ts +19 -4
  50. package/src/modules/query_index/cli.ts +17 -1
  51. package/src/modules/query_index/lib/reindexer.ts +55 -6
  52. package/src/modules/sales/commands/configuration.ts +35 -16
  53. package/src/modules/sales/components/documents/AddressesSection.tsx +51 -20
  54. package/src/modules/sales/i18n/de.json +3 -0
  55. package/src/modules/sales/i18n/en.json +3 -0
  56. package/src/modules/sales/i18n/es.json +3 -0
  57. package/src/modules/sales/i18n/ko.json +3 -0
  58. package/src/modules/sales/i18n/pl.json +4 -1
  59. package/src/modules/sales/seed/examples.ts +41 -6
@@ -326,15 +326,15 @@ export function AssignRoleDialog({
326
326
  {selectedUser.teamName ? <span>{selectedUser.teamName}</span> : null}
327
327
  </div>
328
328
  {selectedUserConflict?.length ? (
329
- <div className="mt-2 flex flex-wrap items-center gap-2">
330
- <Badge
331
- variant="outline"
332
- className="rounded-full border-status-error-border bg-status-error-bg px-2 py-0.5 text-xs font-semibold text-status-error-text"
333
- >
334
- {t('customers.roles.dialog.conflict', 'Conflict: {{roles}}', {
329
+ <div className="mt-2 space-y-1.5">
330
+ <Badge variant="info">
331
+ {t('customers.roles.dialog.alreadyAssigned', 'Already assigned: {{roles}}', {
335
332
  roles: selectedUserConflict.join(', '),
336
333
  })}
337
334
  </Badge>
335
+ <p className="text-xs text-muted-foreground">
336
+ {t('customers.roles.dialog.multipleRolesHint', 'One person can hold several roles on this record.')}
337
+ </p>
338
338
  </div>
339
339
  ) : null}
340
340
  </div>
@@ -560,7 +560,7 @@ export function AssignRoleDialog({
560
560
  type="button"
561
561
  variant="ghost"
562
562
  onClick={() => setSelectedUser(user)}
563
- className={`h-auto flex w-full items-center gap-3 rounded-lg border px-4 py-3 text-left transition-colors ${
563
+ className={`h-auto flex w-full items-center gap-3 whitespace-normal break-words rounded-lg border px-4 py-3 text-left transition-colors ${
564
564
  isSelected
565
565
  ? 'border-foreground bg-background shadow-sm'
566
566
  : 'border-border/70 bg-background hover:bg-accent/40'
@@ -581,11 +581,8 @@ export function AssignRoleDialog({
581
581
  </Badge>
582
582
  ) : null}
583
583
  {userConflicts.length ? (
584
- <Badge
585
- variant="outline"
586
- className="rounded-full border-status-error-border bg-status-error-bg px-2 py-0.5 text-xs font-semibold text-status-error-text"
587
- >
588
- {t('customers.roles.dialog.conflict', 'Conflict: {{roles}}', {
584
+ <Badge variant="info">
585
+ {t('customers.roles.dialog.alreadyAssigned', 'Already assigned: {{roles}}', {
589
586
  roles: userConflicts.join(', '),
590
587
  })}
591
588
  </Badge>
@@ -2743,9 +2743,9 @@
2743
2743
  "customers.roles.configureRoleTypes": "Rollentypen konfigurieren",
2744
2744
  "customers.roles.defaultEntityName.company": "dieses Unternehmen",
2745
2745
  "customers.roles.defaultEntityName.person": "diese Person",
2746
+ "customers.roles.dialog.alreadyAssigned": "Bereits zugewiesen: {{roles}}",
2746
2747
  "customers.roles.dialog.assign": "Assign role",
2747
2748
  "customers.roles.dialog.change": "Change",
2748
- "customers.roles.dialog.conflict": "Conflict: {{roles}}",
2749
2749
  "customers.roles.dialog.constraint": "One person per role. The assignment can be changed at any time.",
2750
2750
  "customers.roles.dialog.defaultEntity.company": "this company",
2751
2751
  "customers.roles.dialog.defaultEntity.person": "this person",
@@ -2753,6 +2753,7 @@
2753
2753
  "customers.roles.dialog.loadMore": "Mehr laden",
2754
2754
  "customers.roles.dialog.loadingMore": "Wird geladen...",
2755
2755
  "customers.roles.dialog.manageRoleTypes": "Rollentypen verwalten",
2756
+ "customers.roles.dialog.multipleRolesHint": "Eine Person kann in diesem Datensatz mehrere Rollen haben.",
2756
2757
  "customers.roles.dialog.next": "Next",
2757
2758
  "customers.roles.dialog.noAvailableRoles": "All available role types are already assigned.",
2758
2759
  "customers.roles.dialog.noResults": "No matching team members found.",
@@ -2743,9 +2743,9 @@
2743
2743
  "customers.roles.configureRoleTypes": "Configure role types",
2744
2744
  "customers.roles.defaultEntityName.company": "this company",
2745
2745
  "customers.roles.defaultEntityName.person": "this person",
2746
+ "customers.roles.dialog.alreadyAssigned": "Already assigned: {{roles}}",
2746
2747
  "customers.roles.dialog.assign": "Assign role",
2747
2748
  "customers.roles.dialog.change": "Change",
2748
- "customers.roles.dialog.conflict": "Conflict: {{roles}}",
2749
2749
  "customers.roles.dialog.constraint": "One person per role. The assignment can be changed at any time.",
2750
2750
  "customers.roles.dialog.defaultEntity.company": "this company",
2751
2751
  "customers.roles.dialog.defaultEntity.person": "this person",
@@ -2753,6 +2753,7 @@
2753
2753
  "customers.roles.dialog.loadMore": "Load more",
2754
2754
  "customers.roles.dialog.loadingMore": "Loading more...",
2755
2755
  "customers.roles.dialog.manageRoleTypes": "Manage role types",
2756
+ "customers.roles.dialog.multipleRolesHint": "One person can hold several roles on this record.",
2756
2757
  "customers.roles.dialog.next": "Next",
2757
2758
  "customers.roles.dialog.noAvailableRoles": "All available role types are already assigned.",
2758
2759
  "customers.roles.dialog.noResults": "No matching team members found.",
@@ -2743,9 +2743,9 @@
2743
2743
  "customers.roles.configureRoleTypes": "Configurar tipos de rol",
2744
2744
  "customers.roles.defaultEntityName.company": "esta empresa",
2745
2745
  "customers.roles.defaultEntityName.person": "esta persona",
2746
+ "customers.roles.dialog.alreadyAssigned": "Ya asignado: {{roles}}",
2746
2747
  "customers.roles.dialog.assign": "Assign role",
2747
2748
  "customers.roles.dialog.change": "Change",
2748
- "customers.roles.dialog.conflict": "Conflict: {{roles}}",
2749
2749
  "customers.roles.dialog.constraint": "One person per role. The assignment can be changed at any time.",
2750
2750
  "customers.roles.dialog.defaultEntity.company": "this company",
2751
2751
  "customers.roles.dialog.defaultEntity.person": "this person",
@@ -2753,6 +2753,7 @@
2753
2753
  "customers.roles.dialog.loadMore": "Cargar más",
2754
2754
  "customers.roles.dialog.loadingMore": "Cargando más...",
2755
2755
  "customers.roles.dialog.manageRoleTypes": "Gestionar tipos de rol",
2756
+ "customers.roles.dialog.multipleRolesHint": "Una persona puede tener varios roles en este registro.",
2756
2757
  "customers.roles.dialog.next": "Next",
2757
2758
  "customers.roles.dialog.noAvailableRoles": "All available role types are already assigned.",
2758
2759
  "customers.roles.dialog.noResults": "No matching team members found.",
@@ -2743,9 +2743,9 @@
2743
2743
  "customers.roles.configureRoleTypes": "역할 유형 설정",
2744
2744
  "customers.roles.defaultEntityName.company": "이 회사",
2745
2745
  "customers.roles.defaultEntityName.person": "이 연락처",
2746
+ "customers.roles.dialog.alreadyAssigned": "이미 배정됨: {{roles}}",
2746
2747
  "customers.roles.dialog.assign": "역할 배정",
2747
2748
  "customers.roles.dialog.change": "변경",
2748
- "customers.roles.dialog.conflict": "충돌: {{roles}}",
2749
2749
  "customers.roles.dialog.constraint": "역할당 한 명만 배정할 수 있습니다. 배정은 언제든지 변경할 수 있습니다.",
2750
2750
  "customers.roles.dialog.defaultEntity.company": "이 회사",
2751
2751
  "customers.roles.dialog.defaultEntity.person": "이 연락처",
@@ -2753,6 +2753,7 @@
2753
2753
  "customers.roles.dialog.loadMore": "더 보기",
2754
2754
  "customers.roles.dialog.loadingMore": "더 불러오는 중...",
2755
2755
  "customers.roles.dialog.manageRoleTypes": "역할 유형 관리",
2756
+ "customers.roles.dialog.multipleRolesHint": "한 사람이 이 레코드에서 여러 역할을 가질 수 있습니다.",
2756
2757
  "customers.roles.dialog.next": "다음",
2757
2758
  "customers.roles.dialog.noAvailableRoles": "사용 가능한 모든 역할 유형이 이미 배정되었습니다.",
2758
2759
  "customers.roles.dialog.noResults": "일치하는 팀원을 찾을 수 없습니다.",
@@ -2743,9 +2743,9 @@
2743
2743
  "customers.roles.configureRoleTypes": "Skonfiguruj typy ról",
2744
2744
  "customers.roles.defaultEntityName.company": "tej firmie",
2745
2745
  "customers.roles.defaultEntityName.person": "tej osobie",
2746
+ "customers.roles.dialog.alreadyAssigned": "Ma już rolę: {{roles}}",
2746
2747
  "customers.roles.dialog.assign": "Przypisz rolę",
2747
2748
  "customers.roles.dialog.change": "Zmień",
2748
- "customers.roles.dialog.conflict": "Konflikt: {{roles}}",
2749
2749
  "customers.roles.dialog.constraint": "Jedna osoba na rolę. Przypisanie można zmienić w dowolnym momencie.",
2750
2750
  "customers.roles.dialog.defaultEntity.company": "tej firmy",
2751
2751
  "customers.roles.dialog.defaultEntity.person": "tej osoby",
@@ -2753,6 +2753,7 @@
2753
2753
  "customers.roles.dialog.loadMore": "Załaduj więcej",
2754
2754
  "customers.roles.dialog.loadingMore": "Ładowanie...",
2755
2755
  "customers.roles.dialog.manageRoleTypes": "Zarządzaj typami ról",
2756
+ "customers.roles.dialog.multipleRolesHint": "Jedna osoba może mieć kilka ról w tym rekordzie.",
2756
2757
  "customers.roles.dialog.next": "Dalej",
2757
2758
  "customers.roles.dialog.noAvailableRoles": "Wszystkie dostępne typy ról są już przypisane.",
2758
2759
  "customers.roles.dialog.noResults": "Nie znaleziono pasujących członków zespołu.",
@@ -17,17 +17,28 @@ export class Migration20260825140000_customers extends Migration {
17
17
  // predicate treats as "not shared" (fail closed). Scoped by tenant on both
18
18
  // joins so a backfill can never attribute an interaction to another tenant's
19
19
  // channel.
20
+ //
21
+ // Both source tables belong to the optional communication_channels module. Apps
22
+ // that do not enable it (e.g. the wms starter preset) have neither table and no
23
+ // email rows to backfill, so the backfill runs only when both tables exist.
20
24
  this.addSql(`
21
- update "customer_interactions" ci
22
- set "channel_id" = ec."channel_id"
23
- from "message_channel_links" mcl
24
- join "external_conversations" ec
25
- on ec."id" = mcl."external_conversation_id"
26
- and ec."tenant_id" = mcl."tenant_id"
27
- where ci."external_message_id" = mcl."id"
28
- and ci."tenant_id" = mcl."tenant_id"
29
- and ci."interaction_type" = 'email'
30
- and ci."channel_id" is null;
25
+ do $$
26
+ begin
27
+ if to_regclass('message_channel_links') is not null
28
+ and to_regclass('external_conversations') is not null then
29
+ update "customer_interactions" ci
30
+ set "channel_id" = ec."channel_id"
31
+ from "message_channel_links" mcl
32
+ join "external_conversations" ec
33
+ on ec."id" = mcl."external_conversation_id"
34
+ and ec."tenant_id" = mcl."tenant_id"
35
+ where ci."external_message_id" = mcl."id"
36
+ and ci."tenant_id" = mcl."tenant_id"
37
+ and ci."interaction_type" = 'email'
38
+ and ci."channel_id" is null;
39
+ end if;
40
+ end
41
+ $$;
31
42
  `);
32
43
 
33
44
  this.addSql(`create index "customer_interactions_email_channel_idx" on "customer_interactions" ("channel_id", "entity_id") where "interaction_type" = 'email' and "channel_id" is not null and "deleted_at" is null;`);
@@ -501,6 +501,26 @@ function formatValueForColumn(prop: any, value: unknown): unknown {
501
501
  return JSON.stringify(value)
502
502
  }
503
503
 
504
+ async function updateEncryptionColumns(
505
+ connection: { execute: (query: string, parameters: unknown[]) => Promise<unknown> },
506
+ table: string,
507
+ primaryKey: string,
508
+ row: Record<string, unknown>,
509
+ updates: Record<string, unknown>,
510
+ scope: { tenantId: string; organizationId: string | null },
511
+ ): Promise<void> {
512
+ const columns = Object.keys(updates)
513
+ const assignments = columns.map((column) => `"${column}" = ?`).join(', ')
514
+ const unchanged = columns.map((column) => `"${column}" IS NOT DISTINCT FROM ?`).join(' AND ')
515
+ const result = await connection.execute(
516
+ `UPDATE ${table} SET ${assignments} WHERE "${primaryKey}" = ? AND tenant_id = ? AND organization_id IS NOT DISTINCT FROM ? AND ${unchanged} RETURNING "${primaryKey}"`,
517
+ [...Object.values(updates), row[primaryKey], scope.tenantId, scope.organizationId, ...columns.map((column) => row[column])],
518
+ )
519
+ if (!Array.isArray(result) || result.length !== 1) {
520
+ failCli('[internal] A row changed concurrently during encryption maintenance. No stale values were written; retry after stopping writers.')
521
+ }
522
+ }
523
+
504
524
  const rotateEncryptionKey: ModuleCli = {
505
525
  command: 'rotate-encryption-key',
506
526
  async run(rest) {
@@ -518,6 +538,9 @@ const rotateEncryptionKey: ModuleCli = {
518
538
  ) {
519
539
  failCli(`--old-key and ${OLD_ENCRYPTION_KEY_ENV} contain different values. Remove --old-key and retry.`)
520
540
  }
541
+ if (oldKeyArgument && parseBooleanToken(String(args['allow-unsafe-old-key'])) !== true) {
542
+ failCli(`--old-key is deprecated because process listings expose it. Use ${OLD_ENCRYPTION_KEY_ENV}; the compatibility bridge requires --allow-unsafe-old-key.`)
543
+ }
521
544
  if (oldKeyArgument) {
522
545
  console.warn(
523
546
  `Passing key material through --old-key can expose it in shell history and process listings. Set ${OLD_ENCRYPTION_KEY_ENV} through your secret manager instead.`,
@@ -751,11 +774,7 @@ const rotateEncryptionKey: ModuleCli = {
751
774
  }
752
775
  if (!Object.keys(updates).length) continue
753
776
  if (!dryRun) {
754
- const setSql = Object.keys(updates).map((col) => `"${col}" = ?`).join(', ')
755
- await conn.execute(
756
- `update ${qualifiedTable} set ${setSql} where "${pk}" = ?`,
757
- [...Object.values(updates), row[pk]],
758
- )
777
+ await updateEncryptionColumns(conn, qualifiedTable, pk, row, updates, scope)
759
778
  }
760
779
  updated += 1
761
780
  }
@@ -830,6 +849,10 @@ const decryptDatabase: ModuleCli = {
830
849
  }
831
850
  }
832
851
 
852
+ if (deactivateMaps && !dryRun && args['confirm-offline-maintenance'] !== tenantIdArg) {
853
+ failCli('--deactivate-maps requires all application and worker writers stopped. Confirm offline maintenance with --confirm-offline-maintenance <tenantUuid>; restart every replica before resuming writes.')
854
+ }
855
+
833
856
  const { resolve } = await createRequestContainer()
834
857
  const em = resolve('em') as any
835
858
  const conn: any = em?.getConnection?.()
@@ -843,27 +866,10 @@ const decryptDatabase: ModuleCli = {
843
866
 
844
867
  const metaByEntityId = buildEntityMetaRegistry(em)
845
868
 
846
- const resolveDecryptScopes = async (
847
- tenantId: string,
848
- organizationId: string | null,
849
- ): Promise<Array<{ tenantId: string; organizationId: string | null }>> => {
850
- if (organizationId) return [{ tenantId, organizationId }]
851
- const rows = await conn.execute(
852
- `SELECT DISTINCT organization_id FROM encryption_maps WHERE tenant_id = ? AND deleted_at IS NULL`,
853
- [tenantId],
854
- )
855
- const orgIds = new Set<string | null>()
856
- for (const row of Array.isArray(rows) ? rows : []) {
857
- orgIds.add(row.organization_id ?? null)
858
- }
859
- orgIds.add(null)
860
- return Array.from(orgIds).map((orgId) => ({ tenantId, organizationId: orgId }))
861
- }
862
-
863
869
  const mapWhere: any = { tenantId: tenantIdArg, deletedAt: null, isActive: true }
864
- if (organizationIdArg) mapWhere.organizationId = organizationIdArg
870
+ if (organizationIdArg) mapWhere.$or = [{ organizationId: organizationIdArg }, { organizationId: null }]
865
871
  if (entityIdArg) mapWhere.entityId = entityIdArg
866
- const allMaps = await em.find(EncryptionMap, mapWhere)
872
+ const allMaps = await em.find(EncryptionMap, mapWhere, { orderBy: { organizationId: 'asc', createdAt: 'asc', id: 'asc' } })
867
873
  const systemScopedEntityIds = await getSystemScopedEntityIds()
868
874
  const maps = allMaps.filter((map: EncryptionMap) => {
869
875
  if (!systemScopedEntityIds.has(String(map.entityId))) return true
@@ -878,6 +884,41 @@ const decryptDatabase: ModuleCli = {
878
884
  return
879
885
  }
880
886
  const resolvedMaps = resolveMapsOrFail(maps, metaByEntityId)
887
+ const resolveProcessingMaps = async (
888
+ executeQuery: (query: string, parameters: unknown[]) => Promise<unknown> = (query, parameters) => conn.execute(query, parameters),
889
+ ) => {
890
+ const groups = new Map<string, typeof resolvedMaps>()
891
+ for (const entry of resolvedMaps) {
892
+ const key = JSON.stringify([entry.mapMeta.tenantId, entry.mapMeta.entityId])
893
+ groups.set(key, [...(groups.get(key) ?? []), entry])
894
+ }
895
+ const result: Array<{ mapMeta: EncryptionMapMeta; scope: { tenantId: string; organizationId: string | null } }> = []
896
+ for (const entries of groups.values()) {
897
+ const template = entries[0]!
898
+ const { entityId, tenantId, meta } = template.mapMeta
899
+ const table = meta.schema ? `"${meta.schema}"."${meta.tableName}"` : `"${meta.tableName}"`
900
+ const scopes = new Set<string | null>(organizationIdArg ? [organizationIdArg] : [null])
901
+ if (!organizationIdArg) {
902
+ const rows = await executeQuery(`SELECT DISTINCT organization_id FROM ${table} WHERE tenant_id = ?`, [tenantId])
903
+ for (const row of Array.isArray(rows) ? rows : []) scopes.add(row.organization_id ?? null)
904
+ }
905
+ for (const organizationId of scopes) {
906
+ const hasExactPolicy = organizationId !== null && allMaps.some((map: EncryptionMap) => map.entityId === entityId && map.tenantId === tenantId && map.organizationId === organizationId)
907
+ const applicable = organizationId === null ? [...entries].sort((left, right) => Number(Boolean(left.map.organizationId)) - Number(Boolean(right.map.organizationId))) : entries.filter(({ map }) => hasExactPolicy ? map.organizationId === organizationId : !map.organizationId)
908
+ const fields = new Map<string, EncryptionMapMeta['fields'][number]>()
909
+ for (const entry of applicable) {
910
+ for (const field of entry.mapMeta.fields) {
911
+ const existing = fields.get(field.field)
912
+ fields.set(field.field, existing ? { ...existing, hashField: existing.hashField ?? field.hashField } : field)
913
+ }
914
+ }
915
+ if (fields.size) result.push({ mapMeta: { ...template.mapMeta, fields: [...fields.values()] }, scope: { tenantId, organizationId } })
916
+ }
917
+ }
918
+ return result
919
+ }
920
+ const processingMaps = await resolveProcessingMaps()
921
+
881
922
 
882
923
  const kms = createKmsService()
883
924
  const dekCache = new Map<string, TenantDek | null>()
@@ -899,7 +940,7 @@ const decryptDatabase: ModuleCli = {
899
940
  // rest, and let the closing gate below make the incomplete run exit non-zero.
900
941
  const uninspectableEntityIds: string[] = []
901
942
  const failedSampleScopes: string[] = []
902
- for (const { map, mapMeta } of resolvedMaps) {
943
+ for (const { mapMeta, scope } of processingMaps) {
903
944
  const { entityId, meta, fields, tenantId } = mapMeta
904
945
  const dek = await getDek(tenantId).catch(() => null)
905
946
  if (!dek) {
@@ -907,15 +948,15 @@ const decryptDatabase: ModuleCli = {
907
948
  uninspectableEntityIds.push(entityId)
908
949
  continue
909
950
  }
910
- const scopes = await resolveDecryptScopes(tenantId, map.organizationId ? String(map.organizationId) : null)
911
951
  const pk = Array.isArray(meta?.primaryKeys) && meta.primaryKeys.length ? meta.primaryKeys[0] : 'id'
912
952
  const tableName = meta.tableName
913
953
  const schema = meta?.schema
914
954
  const qualifiedTable = schema ? `"${schema}"."${tableName}"` : `"${tableName}"`
915
- const fieldCols = fields.flatMap((f: any) => {
916
- const r = resolveProperty(meta, f.field)
917
- return r.columnName ? [r.columnName] : []
918
- })
955
+ const scopes = [scope]
956
+ const fieldCols = fields.flatMap((field) => [
957
+ resolveProperty(meta, field.field).columnName,
958
+ field.hashField ? resolveProperty(meta, field.hashField).columnName : null,
959
+ ].filter((column): column is string => Boolean(column)))
919
960
  const colList = Array.from(new Set([pk, ...fieldCols]))
920
961
  for (const scope of scopes) {
921
962
  let sampleRows: unknown
@@ -942,8 +983,9 @@ const decryptDatabase: ModuleCli = {
942
983
  try {
943
984
  decryptWithAesGcmStrict(String(rawValue), dek.key)
944
985
  rowHasEncrypted = true
945
- } catch (e: any) {
946
- if (e instanceof TenantDataEncryptionError && e.code === TenantDataEncryptionErrorCode.MALFORMED_PAYLOAD) {
986
+ } catch (error: unknown) {
987
+ if (isEncryptedPayloadShape(rawValue)) throw error
988
+ if (error instanceof TenantDataEncryptionError && error.code === TenantDataEncryptionErrorCode.MALFORMED_PAYLOAD) {
947
989
  malformedPayloadCountSampled++
948
990
  }
949
991
  }
@@ -992,21 +1034,21 @@ const decryptDatabase: ModuleCli = {
992
1034
  deksByTenantId.set(mapMeta.tenantId, dek)
993
1035
  }
994
1036
 
995
- for (const { map, mapMeta } of resolvedMaps) {
1037
+ for (const { mapMeta, scope } of processingMaps) {
996
1038
  const { entityId, meta, fields, tenantId } = mapMeta
997
1039
  const dek = deksByTenantId.get(tenantId)!
998
1040
  const pk = Array.isArray(meta?.primaryKeys) && meta.primaryKeys.length ? meta.primaryKeys[0] : 'id'
999
1041
  const tableName = meta.tableName
1000
1042
  const schema = meta?.schema
1001
1043
  const qualifiedTable = schema ? `"${schema}"."${tableName}"` : `"${tableName}"`
1002
- const fieldCols = fields.flatMap((f: any) => {
1003
- const r = resolveProperty(meta, f.field)
1004
- return r.columnName ? [r.columnName] : []
1005
- })
1044
+ const fieldCols = fields.flatMap((field) => [
1045
+ resolveProperty(meta, field.field).columnName,
1046
+ field.hashField ? resolveProperty(meta, field.hashField).columnName : null,
1047
+ ].filter((column): column is string => Boolean(column)))
1006
1048
  const colList = Array.from(new Set([pk, ...fieldCols]))
1007
1049
  totalEntitiesProcessed++
1008
1050
 
1009
- const scopes = await resolveDecryptScopes(tenantId, map.organizationId ? String(map.organizationId) : null)
1051
+ const scopes = [scope]
1010
1052
 
1011
1053
  for (const scope of scopes) {
1012
1054
  let lastId: string | null = null
@@ -1054,20 +1096,20 @@ const decryptDatabase: ModuleCli = {
1054
1096
  }
1055
1097
  updates[col] = valueToWrite
1056
1098
  rowDecrypted = true
1057
- } catch (e: any) {
1058
- if (e instanceof TenantDataEncryptionError) {
1059
- if (e.code === TenantDataEncryptionErrorCode.AUTH_FAILED) {
1060
- // Value is plaintext — skip silently
1061
- } else if (e.code === TenantDataEncryptionErrorCode.MALFORMED_PAYLOAD) {
1099
+ } catch (error: unknown) {
1100
+ if (error instanceof TenantDataEncryptionError) {
1101
+ if (error.code === TenantDataEncryptionErrorCode.AUTH_FAILED) {
1102
+ if (isEncryptedPayloadShape(rawValue)) throw error
1103
+ } else if (error.code === TenantDataEncryptionErrorCode.MALFORMED_PAYLOAD) {
1062
1104
  scopeMalformedCount++
1063
1105
  const locationKey = `${tableName}:${col}`
1064
1106
  malformedByLocation.set(locationKey, (malformedByLocation.get(locationKey) ?? 0) + 1)
1065
1107
  console.warn(`⚠ MALFORMED_PAYLOAD for ${entityId} field "${col}" row ${row[pk]}; skipping field.`)
1066
1108
  } else {
1067
- throw e
1109
+ throw error
1068
1110
  }
1069
1111
  } else {
1070
- throw e
1112
+ throw error
1071
1113
  }
1072
1114
  }
1073
1115
  }
@@ -1092,11 +1134,7 @@ const decryptDatabase: ModuleCli = {
1092
1134
 
1093
1135
  if (Object.keys(updates).length > 0) {
1094
1136
  if (!dryRun) {
1095
- const setSql = Object.keys(updates).map((col) => `"${col}" = ?`).join(', ')
1096
- await conn.execute(
1097
- `UPDATE ${qualifiedTable} SET ${setSql} WHERE "${pk}" = ?`,
1098
- [...Object.values(updates), row[pk]],
1099
- )
1137
+ await updateEncryptionColumns(conn, qualifiedTable, pk, row, updates, scope)
1100
1138
  }
1101
1139
  totalRowsUpdated++
1102
1140
  }
@@ -1156,29 +1194,70 @@ const decryptDatabase: ModuleCli = {
1156
1194
  )
1157
1195
  }
1158
1196
 
1197
+ const retiring = resolvedMaps.filter(({ map }) => !organizationIdArg || Boolean(map.organizationId))
1159
1198
  if (deactivateMaps && !dryRun) {
1160
- let deactivateSql = `UPDATE encryption_maps SET is_active = false, deleted_at = now() WHERE tenant_id = ? AND deleted_at IS NULL`
1161
- const deactivateParams: unknown[] = [tenantIdArg]
1162
- if (organizationIdArg) {
1163
- deactivateSql += ` AND (organization_id = ? OR organization_id IS NULL)`
1164
- deactivateParams.push(organizationIdArg)
1165
- }
1166
- if (entityIdArg) {
1167
- deactivateSql += ` AND entity_id = ?`
1168
- deactivateParams.push(entityIdArg)
1199
+ if (retiring.length) {
1200
+ const policySignature = (policies: EncryptionMap[]) => JSON.stringify(policies.map((map) => [map.id, map.entityId, map.tenantId, map.organizationId, map.fieldsJson]).sort((left, right) => String(left[0]).localeCompare(String(right[0]))))
1201
+ const selectedPolicySignature = policySignature(allMaps)
1202
+ await (em as EntityManager).transactional(async (transaction) => {
1203
+ const executeProtected = (query: string, parameters: unknown[] = []) =>
1204
+ transaction.getConnection().execute(query, parameters, 'all', transaction.getTransactionContext())
1205
+ const tables = Array.from(new Set(resolvedMaps.map(({ mapMeta }) => {
1206
+ const { meta } = mapMeta
1207
+ return meta.schema ? `"${meta.schema}"."${meta.tableName}"` : `"${meta.tableName}"`
1208
+ }))).sort((left, right) => left.localeCompare(right))
1209
+ await executeProtected(`LOCK TABLE encryption_maps, ${tables.join(', ')} IN SHARE ROW EXCLUSIVE MODE`)
1210
+ const lockedPolicies = await transaction.find(EncryptionMap, mapWhere, { refresh: true })
1211
+ if (policySignature(lockedPolicies) !== selectedPolicySignature) {
1212
+ failCli('[internal] Encryption policies changed during maintenance. Maps remain active; retry against the current policies.')
1213
+ }
1214
+ for (const { mapMeta, scope } of await resolveProcessingMaps(executeProtected)) {
1215
+ const { meta, fields, entityId, tenantId } = mapMeta
1216
+ const table = meta.schema ? `"${meta.schema}"."${meta.tableName}"` : `"${meta.tableName}"`
1217
+ const columns = fields.map((field) => resolveProperty(meta, field.field).columnName).filter((column): column is string => Boolean(column))
1218
+ const scopes = [scope]
1219
+ for (const scope of scopes) {
1220
+ const primaryKey = meta.primaryKeys?.[0] ?? 'id'
1221
+ const selectedColumns = [...new Set([primaryKey, ...columns])]
1222
+ let lastVerifiedId: string | null = null
1223
+ while (true) {
1224
+ let query = `SELECT ${selectedColumns.map((column) => `"${column}"`).join(', ')} FROM ${table} WHERE tenant_id = ? AND organization_id IS NOT DISTINCT FROM ?`
1225
+ const parameters: unknown[] = [scope.tenantId, scope.organizationId]
1226
+ if (lastVerifiedId !== null) {
1227
+ query += ` AND "${primaryKey}" > ?`
1228
+ parameters.push(lastVerifiedId)
1229
+ }
1230
+ query += ` ORDER BY "${primaryKey}" LIMIT ?`
1231
+ parameters.push(batchSize)
1232
+ const rows = await executeProtected(query, parameters)
1233
+ const batch = Array.isArray(rows) ? rows : []
1234
+ if (!batch.length) break
1235
+ if (batch.some((row) => columns.some((column) => isEncryptedPayloadShape(row[column])))) {
1236
+ failCli('[internal] Encrypted values remain during the protected final sweep. Encryption maps remain active; stop writers and retry.')
1237
+ }
1238
+ lastVerifiedId = String(batch[batch.length - 1]![primaryKey])
1239
+ }
1240
+ }
1241
+ }
1242
+ const ids = retiring.map(({ map }) => map.id)
1243
+ if (ids.some((id) => typeof id !== 'string' || !id)) failCli('[internal] Cannot retire an encryption map without its identifier.')
1244
+ await executeProtected(`UPDATE encryption_maps SET is_active = false, deleted_at = now() WHERE tenant_id = ? AND id IN (${ids.map(() => '?').join(', ')}) AND deleted_at IS NULL`, [tenantIdArg, ...ids])
1245
+ })
1246
+ console.warn('⚠ Restart all application replicas before resuming writes — in-process map caches may still be active.')
1169
1247
  }
1170
- await conn.execute(deactivateSql, deactivateParams)
1171
- console.warn('⚠ Restart all application replicas — in-process map caches may still be active.')
1172
- if (isTenantDataEncryptionEnabled()) {
1173
- console.warn('⚠ Env TENANT_DATA_ENCRYPTION is still true — new writes will be re-encrypted until env is updated and replicas restarted.')
1248
+ if (organizationIdArg && resolvedMaps.some(({ map }) => !map.organizationId)) {
1249
+ console.warn('⚠ Tenant-wide fallback encryption maps remain active after organization-only decryption. Run a complete tenant sweep before retiring them.')
1174
1250
  }
1175
1251
  }
1176
1252
 
1177
1253
  if (deactivateMaps && dryRun) {
1178
- console.log(`[dry-run] Would deactivate ${maps.length} EncryptionMap record(s).`)
1254
+ console.log(`[dry-run] Would deactivate ${retiring.length} EncryptionMap record(s).`)
1179
1255
  }
1180
1256
 
1181
- if (!dryRun) {
1257
+ if (!dryRun && organizationIdArg) {
1258
+ console.log(`\n✅ Organization-scoped decryption complete. Keep tenant encryption enabled; tenant-wide fallback policies may still protect other organizations. Restart replicas before resuming writes.`)
1259
+ }
1260
+ if (!dryRun && !organizationIdArg) {
1182
1261
  console.log(`\n✅ Decryption complete. Required next steps:`)
1183
1262
  console.log(` 1. Set TENANT_DATA_ENCRYPTION=false in your environment / secrets`)
1184
1263
  console.log(` 2. Restart all application replicas`)
@@ -11,6 +11,7 @@ import { CrudHttpError, notFound } from '@open-mercato/shared/lib/crud/errors'
11
11
  import type { CrudEventsConfig, CrudIndexerConfig } from '@open-mercato/shared/lib/crud/types'
12
12
  import { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'
13
13
  import { createLogger } from '@open-mercato/shared/lib/logger'
14
+ import { LockMode } from '@mikro-orm/core'
14
15
  import type { EntityManager } from '@mikro-orm/postgresql'
15
16
  import { E } from '#generated/entities.ids.generated'
16
17
  import {
@@ -31,7 +32,7 @@ import {
31
32
  type PromotionCodeUpdateInput,
32
33
  type PromotionCodeDeleteInput,
33
34
  } from '../data/validators'
34
- import { PromotionCodeService, type PromotionsCodeScope } from '../lib/code-service'
35
+ import { PromotionCodeService, hasRemainingGlobalUses, type PromotionsCodeScope } from '../lib/code-service'
35
36
  import type { PromotionCodeGenerationService } from '../services/code-generation'
36
37
  import type { CodeReservationResult, CodeUseResult } from '../lib/types'
37
38
 
@@ -203,6 +204,12 @@ async function loadCode(em: EntityManager, id: string): Promise<Code | null> {
203
204
  return em.findOne(Code, { id, deletedAt: null })
204
205
  }
205
206
 
207
+ function resolveUndoActiveFlag(code: Code, before: CodeSnapshot): boolean {
208
+ if (!before.active || code.type !== 'static') return before.active
209
+ const redeemedSinceUpdate = code.used > before.used
210
+ return !redeemedSinceUpdate || hasRemainingGlobalUses(code)
211
+ }
212
+
206
213
  // Mirrors `commands/promotions.ts`'s `resolveActorScope` — a new code's scope is always
207
214
  // the caller's own actor scope, never a client-supplied value.
208
215
  function resolveCodeActorScope(ctx: CommandRuntimeContext): PromotionsCodeScope {
@@ -391,13 +398,20 @@ const updateCodeCommand: CommandHandler<PromotionCodeUpdateInput, { codeId: stri
391
398
  const before = payload?.before
392
399
  if (!before) return
393
400
  const em = (ctx.container.resolve('em') as EntityManager).fork()
394
- const code = await em.findOne(Code, { id: before.id })
395
- if (!code) return
401
+ let code = null as Code | null
396
402
 
397
403
  await withAtomicFlush(
398
404
  em,
399
405
  [
406
+ async () => {
407
+ code = await em.findOne(
408
+ Code,
409
+ { id: before.id, tenantId: before.tenantId, organizationId: before.organizationId },
410
+ { lockMode: LockMode.PESSIMISTIC_WRITE },
411
+ )
412
+ },
400
413
  () => {
414
+ if (!code) return
401
415
  code.name = before.name
402
416
  code.type = before.type
403
417
  code.code = before.code
@@ -408,11 +422,12 @@ const updateCodeCommand: CommandHandler<PromotionCodeUpdateInput, { codeId: stri
408
422
  code.usage = before.usage
409
423
  code.usageAmount = before.usageAmount
410
424
  code.usagePerCustomer = before.usagePerCustomer
411
- code.active = before.active
425
+ code.active = resolveUndoActiveFlag(code, before)
412
426
  },
413
427
  ],
414
428
  { transaction: true, label: 'promotions.code.update.undo' },
415
429
  )
430
+ if (!code) return
416
431
 
417
432
  const dataEngine = ctx.container.resolve('dataEngine') as DataEngine
418
433
  await emitCrudUndoSideEffects({
@@ -21,7 +21,7 @@ import {
21
21
  mergeUpsertIndexBatchResults,
22
22
  type AnyRow,
23
23
  } from './lib/batch'
24
- import { reindexEntity, DEFAULT_REINDEX_PARTITIONS } from './lib/reindexer'
24
+ import { reindexEntity, isTenantlessReindexTarget, DEFAULT_REINDEX_PARTITIONS } from './lib/reindexer'
25
25
  import type { ReindexJobResult } from './lib/reindexer'
26
26
 
27
27
  /**
@@ -948,6 +948,22 @@ const reindex: ModuleCli = {
948
948
  console.log(`[${idx + 1}/${entityIds.length}] Purging existing index rows for ${id}...`)
949
949
  await purgeIndexScope(baseEm, { entityType: id, organizationId: orgId, tenantId })
950
950
  }
951
+ if (tenantId != null && await isTenantlessReindexTarget(baseEm, id)) {
952
+ console.log(`[${idx + 1}/${entityIds.length}] Skipping ${id}: its table has no tenant_id column, so it is not tenant-scoped`)
953
+ await recordIndexerLog(
954
+ { em: baseEm },
955
+ {
956
+ source: 'query_index',
957
+ handler: 'cli:query_index.reindex',
958
+ message: `Reindex skipped for ${id}: not tenant-scoped`,
959
+ entityType: id,
960
+ tenantId,
961
+ organizationId: orgId ?? null,
962
+ details: { skipped: 'no-tenant-column' },
963
+ },
964
+ ).catch(() => undefined)
965
+ continue
966
+ }
951
967
  console.log(
952
968
  `[${idx + 1}/${entityIds.length}] Reindexing ${id}${force ? ' (forced)' : ''} in ${partitionTargets.length} partition(s)...`,
953
969
  )