@open-mercato/core 0.6.6-develop.6543.1.49fadb4c31 → 0.6.6

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 (166) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/dist/modules/api_keys/api/keys/route.js +9 -23
  3. package/dist/modules/api_keys/api/keys/route.js.map +2 -2
  4. package/dist/modules/api_keys/cli.js +1 -2
  5. package/dist/modules/api_keys/cli.js.map +2 -2
  6. package/dist/modules/attachments/api/file/[id]/route.js +7 -9
  7. package/dist/modules/attachments/api/file/[id]/route.js.map +2 -2
  8. package/dist/modules/attachments/api/image/[id]/[[...slug]]/route.js +7 -9
  9. package/dist/modules/attachments/api/image/[id]/[[...slug]]/route.js.map +2 -2
  10. package/dist/modules/attachments/api/route.js +17 -21
  11. package/dist/modules/attachments/api/route.js.map +2 -2
  12. package/dist/modules/auth/api/users/route.js +2 -6
  13. package/dist/modules/auth/api/users/route.js.map +2 -2
  14. package/dist/modules/auth/cli.js +2 -3
  15. package/dist/modules/auth/cli.js.map +2 -2
  16. package/dist/modules/configs/lib/upgrade-actions.js +0 -22
  17. package/dist/modules/configs/lib/upgrade-actions.js.map +2 -2
  18. package/dist/modules/customer_accounts/widgets/injection-table.js +2 -0
  19. package/dist/modules/customer_accounts/widgets/injection-table.js.map +2 -2
  20. package/dist/modules/customers/backend/customers/companies-v2/[id]/page.js +1 -7
  21. package/dist/modules/customers/backend/customers/companies-v2/[id]/page.js.map +2 -2
  22. package/dist/modules/customers/components/detail/CompanyDetailTabs.js +7 -11
  23. package/dist/modules/customers/components/detail/CompanyDetailTabs.js.map +2 -2
  24. package/dist/modules/dashboards/api/roles/widgets/route.js +3 -22
  25. package/dist/modules/dashboards/api/roles/widgets/route.js.map +2 -2
  26. package/dist/modules/dashboards/api/users/widgets/route.js +3 -22
  27. package/dist/modules/dashboards/api/users/widgets/route.js.map +2 -2
  28. package/dist/modules/dashboards/cli.js +3 -4
  29. package/dist/modules/dashboards/cli.js.map +2 -2
  30. package/dist/modules/dashboards/lib/widgetAssignmentScope.js +1 -9
  31. package/dist/modules/dashboards/lib/widgetAssignmentScope.js.map +2 -2
  32. package/dist/modules/dictionaries/commands/entries.js +14 -7
  33. package/dist/modules/dictionaries/commands/entries.js.map +2 -2
  34. package/dist/modules/dictionaries/commands/entry-operations.js +16 -7
  35. package/dist/modules/dictionaries/commands/entry-operations.js.map +2 -2
  36. package/dist/modules/dictionaries/commands/factory.js +3 -9
  37. package/dist/modules/dictionaries/commands/factory.js.map +2 -2
  38. package/dist/modules/dictionaries/fields/dictionary.js +41 -56
  39. package/dist/modules/dictionaries/fields/dictionary.js.map +2 -2
  40. package/dist/modules/directory/utils/organizationScope.js +3 -10
  41. package/dist/modules/directory/utils/organizationScope.js.map +2 -2
  42. package/dist/modules/entities/api/records.js +4 -5
  43. package/dist/modules/entities/api/records.js.map +2 -2
  44. package/dist/modules/entities/backend/entities/system/[entityId]/page.meta.js +0 -1
  45. package/dist/modules/entities/backend/entities/system/[entityId]/page.meta.js.map +2 -2
  46. package/dist/modules/entities/backend/entities/user/[entityId]/page.js +49 -49
  47. package/dist/modules/entities/backend/entities/user/[entityId]/page.js.map +2 -2
  48. package/dist/modules/entities/backend/entities/user/[entityId]/page.meta.js +0 -1
  49. package/dist/modules/entities/backend/entities/user/[entityId]/page.meta.js.map +2 -2
  50. package/dist/modules/entities/cli.js +1 -2
  51. package/dist/modules/entities/cli.js.map +2 -2
  52. package/dist/modules/query_index/api/status.js +8 -2
  53. package/dist/modules/query_index/api/status.js.map +2 -2
  54. package/dist/modules/sales/commands/documents.js +0 -44
  55. package/dist/modules/sales/commands/documents.js.map +2 -2
  56. package/dist/modules/sales/commands/returns.js +27 -2
  57. package/dist/modules/sales/commands/returns.js.map +2 -2
  58. package/dist/modules/sales/components/documents/AddressesSection.js +2 -6
  59. package/dist/modules/sales/components/documents/AddressesSection.js.map +2 -2
  60. package/dist/modules/sales/components/documents/ItemsSection.js +0 -1
  61. package/dist/modules/sales/components/documents/ItemsSection.js.map +2 -2
  62. package/dist/modules/sales/components/documents/LineItemDialog.js +0 -9
  63. package/dist/modules/sales/components/documents/LineItemDialog.js.map +2 -2
  64. package/dist/modules/sales/components/documents/SalesDocumentForm.js +0 -44
  65. package/dist/modules/sales/components/documents/SalesDocumentForm.js.map +2 -2
  66. package/dist/modules/sales/components/documents/ShipmentDialog.js +38 -59
  67. package/dist/modules/sales/components/documents/ShipmentDialog.js.map +2 -2
  68. package/dist/modules/sales/lib/shipments/snapshots.js +1 -27
  69. package/dist/modules/sales/lib/shipments/snapshots.js.map +2 -2
  70. package/dist/modules/workflows/frontend/checkout-demo/page.js +8 -1
  71. package/dist/modules/workflows/frontend/checkout-demo/page.js.map +2 -2
  72. package/dist/modules/workflows/lib/activity-executor.js +1 -1
  73. package/dist/modules/workflows/lib/activity-executor.js.map +2 -2
  74. package/dist/modules/workflows/lib/find-definition.js +18 -2
  75. package/dist/modules/workflows/lib/find-definition.js.map +2 -2
  76. package/dist/modules/workflows/lib/signal-handler.js +3 -2
  77. package/dist/modules/workflows/lib/signal-handler.js.map +2 -2
  78. package/dist/modules/workflows/lib/step-handler.js +4 -8
  79. package/dist/modules/workflows/lib/step-handler.js.map +2 -2
  80. package/dist/modules/workflows/lib/task-handler.js +3 -5
  81. package/dist/modules/workflows/lib/task-handler.js.map +2 -2
  82. package/dist/modules/workflows/lib/timer-handler.js +2 -1
  83. package/dist/modules/workflows/lib/timer-handler.js.map +2 -2
  84. package/dist/modules/workflows/lib/transition-handler.js +5 -13
  85. package/dist/modules/workflows/lib/transition-handler.js.map +2 -2
  86. package/dist/modules/workflows/lib/workflow-executor.js +11 -9
  87. package/dist/modules/workflows/lib/workflow-executor.js.map +2 -2
  88. package/dist/modules/workflows/migrations/Migration20260715120000.js +68 -0
  89. package/dist/modules/workflows/migrations/Migration20260715120000.js.map +7 -0
  90. package/dist/modules/workflows/migrations/Migration20260716120000.js +24 -0
  91. package/dist/modules/workflows/migrations/Migration20260716120000.js.map +7 -0
  92. package/dist/modules/workflows/workflows.js +2 -0
  93. package/dist/modules/workflows/workflows.js.map +2 -2
  94. package/package.json +8 -9
  95. package/src/modules/api_keys/api/keys/route.ts +9 -27
  96. package/src/modules/api_keys/cli.ts +3 -2
  97. package/src/modules/attachments/api/file/[id]/route.ts +7 -11
  98. package/src/modules/attachments/api/image/[id]/[[...slug]]/route.ts +7 -11
  99. package/src/modules/attachments/api/route.ts +21 -26
  100. package/src/modules/auth/api/users/route.ts +2 -11
  101. package/src/modules/auth/cli.ts +2 -3
  102. package/src/modules/configs/i18n/de.json +1 -5
  103. package/src/modules/configs/i18n/en.json +1 -5
  104. package/src/modules/configs/i18n/es.json +1 -5
  105. package/src/modules/configs/i18n/pl.json +1 -5
  106. package/src/modules/configs/lib/upgrade-actions.ts +0 -24
  107. package/src/modules/customer_accounts/AGENTS.md +6 -8
  108. package/src/modules/customer_accounts/widgets/injection-table.ts +2 -0
  109. package/src/modules/customers/backend/customers/companies-v2/[id]/page.tsx +1 -11
  110. package/src/modules/customers/components/detail/CompanyDetailTabs.tsx +7 -13
  111. package/src/modules/dashboards/api/roles/widgets/route.ts +3 -22
  112. package/src/modules/dashboards/api/users/widgets/route.ts +3 -22
  113. package/src/modules/dashboards/cli.ts +9 -4
  114. package/src/modules/dashboards/lib/widgetAssignmentScope.ts +0 -18
  115. package/src/modules/dictionaries/commands/entries.ts +16 -7
  116. package/src/modules/dictionaries/commands/entry-operations.ts +18 -8
  117. package/src/modules/dictionaries/commands/factory.ts +2 -8
  118. package/src/modules/dictionaries/fields/dictionary.tsx +32 -55
  119. package/src/modules/dictionaries/i18n/de.json +0 -2
  120. package/src/modules/dictionaries/i18n/en.json +0 -2
  121. package/src/modules/dictionaries/i18n/es.json +0 -2
  122. package/src/modules/dictionaries/i18n/pl.json +0 -2
  123. package/src/modules/directory/utils/organizationScope.ts +2 -36
  124. package/src/modules/entities/api/records.ts +7 -5
  125. package/src/modules/entities/backend/entities/system/[entityId]/page.meta.ts +0 -1
  126. package/src/modules/entities/backend/entities/user/[entityId]/page.meta.ts +0 -1
  127. package/src/modules/entities/backend/entities/user/[entityId]/page.tsx +49 -51
  128. package/src/modules/entities/cli.ts +1 -2
  129. package/src/modules/entities/i18n/de.json +0 -34
  130. package/src/modules/entities/i18n/en.json +0 -34
  131. package/src/modules/entities/i18n/es.json +0 -34
  132. package/src/modules/entities/i18n/pl.json +0 -34
  133. package/src/modules/query_index/api/status.ts +8 -2
  134. package/src/modules/sales/commands/documents.ts +0 -65
  135. package/src/modules/sales/commands/returns.ts +32 -2
  136. package/src/modules/sales/components/documents/AddressesSection.tsx +2 -6
  137. package/src/modules/sales/components/documents/ItemsSection.tsx +0 -5
  138. package/src/modules/sales/components/documents/LineItemDialog.tsx +0 -10
  139. package/src/modules/sales/components/documents/SalesDocumentForm.tsx +0 -46
  140. package/src/modules/sales/components/documents/ShipmentDialog.tsx +40 -65
  141. package/src/modules/sales/i18n/de.json +0 -4
  142. package/src/modules/sales/i18n/en.json +0 -4
  143. package/src/modules/sales/i18n/es.json +0 -4
  144. package/src/modules/sales/i18n/pl.json +0 -4
  145. package/src/modules/sales/lib/shipments/snapshots.ts +0 -30
  146. package/src/modules/workflows/frontend/checkout-demo/page.tsx +12 -1
  147. package/src/modules/workflows/lib/activity-executor.ts +22 -2
  148. package/src/modules/workflows/lib/find-definition.ts +53 -1
  149. package/src/modules/workflows/lib/signal-handler.ts +5 -4
  150. package/src/modules/workflows/lib/step-handler.ts +4 -8
  151. package/src/modules/workflows/lib/task-handler.ts +2 -4
  152. package/src/modules/workflows/lib/timer-handler.ts +3 -2
  153. package/src/modules/workflows/lib/transition-handler.ts +5 -13
  154. package/src/modules/workflows/lib/workflow-executor.ts +11 -8
  155. package/src/modules/workflows/migrations/Migration20260715120000.ts +114 -0
  156. package/src/modules/workflows/migrations/Migration20260716120000.ts +57 -0
  157. package/src/modules/workflows/workflows.ts +2 -0
  158. package/dist/modules/attachments/lib/reconcileOrganization.js +0 -110
  159. package/dist/modules/attachments/lib/reconcileOrganization.js.map +0 -7
  160. package/dist/modules/attachments/lib/requestScope.js +0 -10
  161. package/dist/modules/attachments/lib/requestScope.js.map +0 -7
  162. package/dist/modules/customers/components/detail/useDealsAccess.js +0 -16
  163. package/dist/modules/customers/components/detail/useDealsAccess.js.map +0 -7
  164. package/src/modules/attachments/lib/reconcileOrganization.ts +0 -188
  165. package/src/modules/attachments/lib/requestScope.ts +0 -27
  166. package/src/modules/customers/components/detail/useDealsAccess.ts +0 -19
@@ -4,7 +4,6 @@ import { Role } from "@open-mercato/core/modules/auth/data/entities";
4
4
  import { loadAllWidgets } from "@open-mercato/core/modules/dashboards/lib/widgets";
5
5
  import { appendWidgetsToRoles, resolveAnalyticsWidgetIds } from "@open-mercato/core/modules/dashboards/lib/role-widgets";
6
6
  import { seedAnalyticsData } from "./seed/analytics.js";
7
- import { parseCommaSeparatedList } from "@open-mercato/shared/lib/string";
8
7
  function parseArgs(rest) {
9
8
  const args = {};
10
9
  for (let i = 0; i < rest.length; i += 2) {
@@ -85,7 +84,7 @@ const seedDefaults = {
85
84
  console.error("Usage: mercato dashboards seed-defaults --tenant <tenantId> [--roles superadmin,admin,employee] [--widgets id1,id2]");
86
85
  return;
87
86
  }
88
- const roleNames = parseCommaSeparatedList(roleCsv);
87
+ const roleNames = roleCsv.split(",").map((name) => name.trim()).filter(Boolean);
89
88
  if (!roleNames.length) {
90
89
  console.log("No roles provided, nothing to seed.");
91
90
  return;
@@ -96,7 +95,7 @@ const seedDefaults = {
96
95
  tenantId,
97
96
  organizationId,
98
97
  roleNames,
99
- widgetIds: widgetCsv ? parseCommaSeparatedList(widgetCsv) : void 0,
98
+ widgetIds: widgetCsv ? widgetCsv.split(",").map((id) => id.trim()).filter(Boolean) : void 0,
100
99
  logger: (message) => console.log(message)
101
100
  });
102
101
  }
@@ -112,7 +111,7 @@ const enableAnalyticsWidgets = {
112
111
  console.error("Usage: mercato dashboards enable-analytics-widgets --tenant <tenantId> [--org <orgId>] [--roles admin,employee]");
113
112
  return;
114
113
  }
115
- const roleNames = parseCommaSeparatedList(roleCsv);
114
+ const roleNames = roleCsv.split(",").map((name) => name.trim()).filter(Boolean);
116
115
  if (!roleNames.length) {
117
116
  console.log("No roles provided, nothing to update.");
118
117
  return;
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/modules/dashboards/cli.ts"],
4
- "sourcesContent": ["import type { ModuleCli } from '@open-mercato/shared/modules/registry'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport { DashboardRoleWidgets } from '@open-mercato/core/modules/dashboards/data/entities'\nimport { Role } from '@open-mercato/core/modules/auth/data/entities'\nimport { loadAllWidgets } from '@open-mercato/core/modules/dashboards/lib/widgets'\nimport { appendWidgetsToRoles, resolveAnalyticsWidgetIds } from '@open-mercato/core/modules/dashboards/lib/role-widgets'\nimport { seedAnalyticsData } from './seed/analytics'\nimport { parseCommaSeparatedList } from '@open-mercato/shared/lib/string'\n\ntype Args = Record<string, string>\n\nfunction parseArgs(rest: string[]): Args {\n const args: Args = {}\n for (let i = 0; i < rest.length; i += 2) {\n const key = rest[i]?.replace(/^--/, '')\n const value = rest[i + 1]\n if (key) args[key] = value ?? ''\n }\n return args\n}\n\nexport async function seedDashboardDefaultsForTenant(\n em: EntityManager,\n {\n tenantId,\n organizationId = null,\n roleNames = ['superadmin', 'admin', 'employee'],\n widgetIds,\n logger,\n }: {\n tenantId: string\n organizationId?: string | null\n roleNames?: string[]\n widgetIds?: string[]\n logger?: (message: string) => void\n },\n): Promise<boolean> {\n if (!tenantId) throw new Error('tenantId is required')\n const log = logger ?? (() => {})\n\n const widgets = await loadAllWidgets()\n const widgetMap = new Map(widgets.map((widget) => [widget.metadata.id, widget]))\n const resolvedWidgetIds = widgetIds && widgetIds.length\n ? widgetIds.filter((id) => widgetMap.has(id))\n : null\n const defaultWidgetIds = widgets\n .filter((widget) => widget.metadata.defaultEnabled)\n .map((widget) => widget.metadata.id)\n const allWidgetIds = widgets.map((widget) => widget.metadata.id)\n\n if (resolvedWidgetIds && resolvedWidgetIds.length === 0) {\n log('No widgets resolved for dashboard seeding.')\n return false\n }\n\n await em.transactional(async (tem) => {\n for (const roleName of roleNames) {\n const isAdminRole = roleName === 'admin' || roleName === 'superadmin'\n const roleWidgetIds = resolvedWidgetIds ?? (isAdminRole ? allWidgetIds : defaultWidgetIds)\n if (!roleWidgetIds.length) {\n log(`No widgets resolved for role \"${roleName}\".`)\n continue\n }\n const role = await tem.findOne(Role, { name: roleName })\n if (!role) {\n log(`Skipping role \"${roleName}\" (not found)`)\n continue\n }\n const existing = await tem.findOne(DashboardRoleWidgets, {\n roleId: String(role.id),\n tenantId,\n organizationId,\n deletedAt: null,\n })\n if (existing) {\n existing.widgetIdsJson = roleWidgetIds\n tem.persist(existing)\n log(`Updated dashboard widgets for role \"${roleName}\"`)\n } else {\n const record = tem.create(DashboardRoleWidgets, {\n roleId: String(role.id),\n tenantId,\n organizationId,\n widgetIdsJson: roleWidgetIds,\n createdAt: new Date(),\n updatedAt: null,\n deletedAt: null,\n })\n tem.persist(record)\n log(`Created dashboard widgets for role \"${roleName}\"`)\n }\n }\n })\n\n return true\n}\n\nconst seedDefaults: ModuleCli = {\n command: 'seed-defaults',\n async run(rest) {\n const args = parseArgs(rest)\n const tenantId = args.tenant || args.tenantId || null\n const organizationId = args.organization || args.organizationId || null\n const roleCsv = args.roles || 'superadmin,admin,employee'\n const widgetCsv = args.widgets || ''\n if (!tenantId) {\n console.error('Usage: mercato dashboards seed-defaults --tenant <tenantId> [--roles superadmin,admin,employee] [--widgets id1,id2]')\n return\n }\n\n const roleNames = parseCommaSeparatedList(roleCsv)\n\n if (!roleNames.length) {\n console.log('No roles provided, nothing to seed.')\n return\n }\n\n const { resolve } = await createRequestContainer()\n const em = resolve('em') as any\n\n await seedDashboardDefaultsForTenant(em as EntityManager, {\n tenantId,\n organizationId,\n roleNames,\n widgetIds: widgetCsv ? parseCommaSeparatedList(widgetCsv) : undefined,\n logger: (message) => console.log(message),\n })\n },\n}\n\nconst enableAnalyticsWidgets: ModuleCli = {\n command: 'enable-analytics-widgets',\n async run(rest) {\n const args = parseArgs(rest)\n const tenantId = args.tenant || args.tenantId || null\n const organizationId = args.organization || args.organizationId || args.org || null\n const roleCsv = args.roles || 'admin,employee'\n if (!tenantId) {\n console.error('Usage: mercato dashboards enable-analytics-widgets --tenant <tenantId> [--org <orgId>] [--roles admin,employee]')\n return\n }\n\n const roleNames = parseCommaSeparatedList(roleCsv)\n\n if (!roleNames.length) {\n console.log('No roles provided, nothing to update.')\n return\n }\n\n const { resolve } = await createRequestContainer()\n const em = resolve('em') as EntityManager\n const widgetIds = await resolveAnalyticsWidgetIds()\n\n const updated = await appendWidgetsToRoles(em, {\n tenantId,\n organizationId,\n roleNames,\n widgetIds,\n })\n\n if (!updated) {\n console.log('No dashboard role widgets updated.')\n }\n },\n}\n\nconst seedAnalytics: ModuleCli = {\n command: 'seed-analytics',\n async run(rest) {\n const args = parseArgs(rest)\n const tenantId = args.tenant || args.tenantId || null\n const organizationId = args.organization || args.organizationId || args.org || null\n const months = args.months ? parseInt(args.months, 10) : 6\n const ordersPerMonth = args.ordersPerMonth ? parseInt(args.ordersPerMonth, 10) : 50\n\n if (!tenantId || !organizationId) {\n console.error('Usage: mercato dashboards seed-analytics --tenant <tenantId> --organization <organizationId> [--months 6] [--ordersPerMonth 50]')\n return\n }\n\n const { resolve } = await createRequestContainer()\n const em = resolve('em') as EntityManager\n\n console.log(`Seeding analytics data for ${months} months with ~${ordersPerMonth} orders/month...`)\n\n try {\n const result = await em.transactional(async (tem) =>\n seedAnalyticsData(tem, { tenantId, organizationId }, { months, ordersPerMonth })\n )\n\n if (result.orders === 0) {\n console.log('Analytics data already exists. Skipping seed.')\n } else {\n console.log(`Seeded analytics data:`)\n console.log(` - Orders: ${result.orders}`)\n console.log(` - Customers: ${result.customers}`)\n console.log(` - Products: ${result.products}`)\n console.log(` - Deals: ${result.deals}`)\n }\n } catch (error) {\n console.error('Failed to seed analytics data:', error)\n }\n },\n}\n\nconst debugAnalytics: ModuleCli = {\n command: 'debug-analytics',\n async run(rest) {\n const args = parseArgs(rest)\n const tenantId = args.tenant || args.tenantId || null\n const organizationId = args.organization || args.organizationId || args.org || null\n\n if (!tenantId) {\n console.error('Usage: mercato dashboards debug-analytics --tenant <tenantId> [--organization <organizationId>]')\n return\n }\n\n const { resolve } = await createRequestContainer()\n const em = resolve('em') as EntityManager\n const conn = em.getConnection()\n\n console.log('Checking analytics data...\\n')\n\n const ordersResult = await conn.execute(\n `SELECT COUNT(*) as total, MIN(placed_at) as earliest, MAX(placed_at) as latest\n FROM sales_orders\n WHERE tenant_id = ? AND order_number LIKE 'SO-ANALYTICS-%'`,\n [tenantId]\n )\n console.log('Orders summary:', ordersResult[0])\n\n const recentOrders = await conn.execute(\n `SELECT order_number, placed_at, status, grand_total_gross_amount::numeric as total\n FROM sales_orders\n WHERE tenant_id = ? AND order_number LIKE 'SO-ANALYTICS-%'\n ORDER BY placed_at DESC LIMIT 5`,\n [tenantId]\n )\n console.log('\\nRecent orders:', recentOrders)\n\n const januaryOrders = await conn.execute(\n `SELECT COUNT(*) as count, SUM(grand_total_gross_amount::numeric) as total\n FROM sales_orders\n WHERE tenant_id = ?\n AND order_number LIKE 'SO-ANALYTICS-%'\n AND placed_at >= '2026-01-01'\n AND placed_at <= '2026-01-31 23:59:59'`,\n [tenantId]\n )\n console.log('\\nJanuary 2026 orders:', januaryOrders[0])\n\n const allOrders = await conn.execute(\n `SELECT COUNT(*) as count\n FROM sales_orders\n WHERE tenant_id = ?`,\n [tenantId]\n )\n console.log('\\nTotal orders in tenant:', allOrders[0])\n\n const orgCheck = await conn.execute(\n `SELECT organization_id, COUNT(*) as count\n FROM sales_orders\n WHERE tenant_id = ? AND order_number LIKE 'SO-ANALYTICS-%'\n GROUP BY organization_id`,\n [tenantId]\n )\n console.log('\\nOrders by organization:', orgCheck)\n\n if (organizationId) {\n const orgOrders = await conn.execute(\n `SELECT COUNT(*) as count, SUM(grand_total_gross_amount::numeric) as total\n FROM sales_orders\n WHERE tenant_id = ?\n AND organization_id = ?\n AND placed_at >= '2026-01-01'\n AND placed_at <= '2026-01-31 23:59:59'`,\n [tenantId, organizationId]\n )\n console.log(`\\nJanuary orders for org ${organizationId}:`, orgOrders[0])\n }\n\n // Check for NULL placed_at\n const nullPlacedAt = await conn.execute(\n `SELECT COUNT(*) as count\n FROM sales_orders\n WHERE tenant_id = ? AND placed_at IS NULL`,\n [tenantId]\n )\n console.log('\\nOrders with NULL placed_at:', nullPlacedAt[0])\n\n // Check non-analytics orders\n const nonAnalytics = await conn.execute(\n `SELECT order_number, placed_at, status, organization_id, grand_total_gross_amount::numeric as total\n FROM sales_orders\n WHERE tenant_id = ? AND order_number NOT LIKE 'SO-ANALYTICS-%'\n ORDER BY placed_at DESC NULLS LAST LIMIT 10`,\n [tenantId]\n )\n console.log('\\nNon-analytics orders:', nonAnalytics)\n\n // Simulate widget query\n console.log('\\n--- Simulating widget query for this_month ---')\n const widgetQuery = await conn.execute(\n `SELECT COALESCE(SUM(grand_total_gross_amount::numeric), 0) AS value\n FROM sales_orders\n WHERE tenant_id = ?\n AND organization_id = ANY(?::uuid[])\n AND deleted_at IS NULL\n AND placed_at >= '2026-01-01'\n AND placed_at <= '2026-01-31 23:59:59'`,\n [tenantId, `{${organizationId}}`]\n )\n console.log('Widget query result (revenue sum):', widgetQuery[0])\n\n const widgetCountQuery = await conn.execute(\n `SELECT COUNT(*) AS value\n FROM sales_orders\n WHERE tenant_id = ?\n AND organization_id = ANY(?::uuid[])\n AND deleted_at IS NULL\n AND placed_at >= '2026-01-01'\n AND placed_at <= '2026-01-31 23:59:59'`,\n [tenantId, `{${organizationId}}`]\n )\n console.log('Widget query result (order count):', widgetCountQuery[0])\n },\n}\n\nexport default [seedDefaults, enableAnalyticsWidgets, seedAnalytics, debugAnalytics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9D,UAAM,cAAc,MAAM,KAAK;AAAA,MAC7B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,MAOA,CAAC,UAAU,IAAI,cAAc,GAAG;AAAA,IAClC;AACA,YAAQ,IAAI,sCAAsC,YAAY,CAAC,CAAC;AAEhE,UAAM,mBAAmB,MAAM,KAAK;AAAA,MAClC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,MAOA,CAAC,UAAU,IAAI,cAAc,GAAG;AAAA,IAClC;AACA,YAAQ,IAAI,sCAAsC,iBAAiB,CAAC,CAAC;AAAA,EACvE;AACF;AAEA,IAAO,cAAQ,CAAC,cAAc,wBAAwB,eAAe,cAAc;",
4
+ "sourcesContent": ["import type { ModuleCli } from '@open-mercato/shared/modules/registry'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport { DashboardRoleWidgets } from '@open-mercato/core/modules/dashboards/data/entities'\nimport { Role } from '@open-mercato/core/modules/auth/data/entities'\nimport { loadAllWidgets } from '@open-mercato/core/modules/dashboards/lib/widgets'\nimport { appendWidgetsToRoles, resolveAnalyticsWidgetIds } from '@open-mercato/core/modules/dashboards/lib/role-widgets'\nimport { seedAnalyticsData } from './seed/analytics'\n\ntype Args = Record<string, string>\n\nfunction parseArgs(rest: string[]): Args {\n const args: Args = {}\n for (let i = 0; i < rest.length; i += 2) {\n const key = rest[i]?.replace(/^--/, '')\n const value = rest[i + 1]\n if (key) args[key] = value ?? ''\n }\n return args\n}\n\nexport async function seedDashboardDefaultsForTenant(\n em: EntityManager,\n {\n tenantId,\n organizationId = null,\n roleNames = ['superadmin', 'admin', 'employee'],\n widgetIds,\n logger,\n }: {\n tenantId: string\n organizationId?: string | null\n roleNames?: string[]\n widgetIds?: string[]\n logger?: (message: string) => void\n },\n): Promise<boolean> {\n if (!tenantId) throw new Error('tenantId is required')\n const log = logger ?? (() => {})\n\n const widgets = await loadAllWidgets()\n const widgetMap = new Map(widgets.map((widget) => [widget.metadata.id, widget]))\n const resolvedWidgetIds = widgetIds && widgetIds.length\n ? widgetIds.filter((id) => widgetMap.has(id))\n : null\n const defaultWidgetIds = widgets\n .filter((widget) => widget.metadata.defaultEnabled)\n .map((widget) => widget.metadata.id)\n const allWidgetIds = widgets.map((widget) => widget.metadata.id)\n\n if (resolvedWidgetIds && resolvedWidgetIds.length === 0) {\n log('No widgets resolved for dashboard seeding.')\n return false\n }\n\n await em.transactional(async (tem) => {\n for (const roleName of roleNames) {\n const isAdminRole = roleName === 'admin' || roleName === 'superadmin'\n const roleWidgetIds = resolvedWidgetIds ?? (isAdminRole ? allWidgetIds : defaultWidgetIds)\n if (!roleWidgetIds.length) {\n log(`No widgets resolved for role \"${roleName}\".`)\n continue\n }\n const role = await tem.findOne(Role, { name: roleName })\n if (!role) {\n log(`Skipping role \"${roleName}\" (not found)`)\n continue\n }\n const existing = await tem.findOne(DashboardRoleWidgets, {\n roleId: String(role.id),\n tenantId,\n organizationId,\n deletedAt: null,\n })\n if (existing) {\n existing.widgetIdsJson = roleWidgetIds\n tem.persist(existing)\n log(`Updated dashboard widgets for role \"${roleName}\"`)\n } else {\n const record = tem.create(DashboardRoleWidgets, {\n roleId: String(role.id),\n tenantId,\n organizationId,\n widgetIdsJson: roleWidgetIds,\n createdAt: new Date(),\n updatedAt: null,\n deletedAt: null,\n })\n tem.persist(record)\n log(`Created dashboard widgets for role \"${roleName}\"`)\n }\n }\n })\n\n return true\n}\n\nconst seedDefaults: ModuleCli = {\n command: 'seed-defaults',\n async run(rest) {\n const args = parseArgs(rest)\n const tenantId = args.tenant || args.tenantId || null\n const organizationId = args.organization || args.organizationId || null\n const roleCsv = args.roles || 'superadmin,admin,employee'\n const widgetCsv = args.widgets || ''\n if (!tenantId) {\n console.error('Usage: mercato dashboards seed-defaults --tenant <tenantId> [--roles superadmin,admin,employee] [--widgets id1,id2]')\n return\n }\n\n const roleNames = roleCsv\n .split(',')\n .map((name) => name.trim())\n .filter(Boolean)\n\n if (!roleNames.length) {\n console.log('No roles provided, nothing to seed.')\n return\n }\n\n const { resolve } = await createRequestContainer()\n const em = resolve('em') as any\n\n await seedDashboardDefaultsForTenant(em as EntityManager, {\n tenantId,\n organizationId,\n roleNames,\n widgetIds: widgetCsv ? widgetCsv.split(',').map((id) => id.trim()).filter(Boolean) : undefined,\n logger: (message) => console.log(message),\n })\n },\n}\n\nconst enableAnalyticsWidgets: ModuleCli = {\n command: 'enable-analytics-widgets',\n async run(rest) {\n const args = parseArgs(rest)\n const tenantId = args.tenant || args.tenantId || null\n const organizationId = args.organization || args.organizationId || args.org || null\n const roleCsv = args.roles || 'admin,employee'\n if (!tenantId) {\n console.error('Usage: mercato dashboards enable-analytics-widgets --tenant <tenantId> [--org <orgId>] [--roles admin,employee]')\n return\n }\n\n const roleNames = roleCsv\n .split(',')\n .map((name) => name.trim())\n .filter(Boolean)\n\n if (!roleNames.length) {\n console.log('No roles provided, nothing to update.')\n return\n }\n\n const { resolve } = await createRequestContainer()\n const em = resolve('em') as EntityManager\n const widgetIds = await resolveAnalyticsWidgetIds()\n\n const updated = await appendWidgetsToRoles(em, {\n tenantId,\n organizationId,\n roleNames,\n widgetIds,\n })\n\n if (!updated) {\n console.log('No dashboard role widgets updated.')\n }\n },\n}\n\nconst seedAnalytics: ModuleCli = {\n command: 'seed-analytics',\n async run(rest) {\n const args = parseArgs(rest)\n const tenantId = args.tenant || args.tenantId || null\n const organizationId = args.organization || args.organizationId || args.org || null\n const months = args.months ? parseInt(args.months, 10) : 6\n const ordersPerMonth = args.ordersPerMonth ? parseInt(args.ordersPerMonth, 10) : 50\n\n if (!tenantId || !organizationId) {\n console.error('Usage: mercato dashboards seed-analytics --tenant <tenantId> --organization <organizationId> [--months 6] [--ordersPerMonth 50]')\n return\n }\n\n const { resolve } = await createRequestContainer()\n const em = resolve('em') as EntityManager\n\n console.log(`Seeding analytics data for ${months} months with ~${ordersPerMonth} orders/month...`)\n\n try {\n const result = await em.transactional(async (tem) =>\n seedAnalyticsData(tem, { tenantId, organizationId }, { months, ordersPerMonth })\n )\n\n if (result.orders === 0) {\n console.log('Analytics data already exists. Skipping seed.')\n } else {\n console.log(`Seeded analytics data:`)\n console.log(` - Orders: ${result.orders}`)\n console.log(` - Customers: ${result.customers}`)\n console.log(` - Products: ${result.products}`)\n console.log(` - Deals: ${result.deals}`)\n }\n } catch (error) {\n console.error('Failed to seed analytics data:', error)\n }\n },\n}\n\nconst debugAnalytics: ModuleCli = {\n command: 'debug-analytics',\n async run(rest) {\n const args = parseArgs(rest)\n const tenantId = args.tenant || args.tenantId || null\n const organizationId = args.organization || args.organizationId || args.org || null\n\n if (!tenantId) {\n console.error('Usage: mercato dashboards debug-analytics --tenant <tenantId> [--organization <organizationId>]')\n return\n }\n\n const { resolve } = await createRequestContainer()\n const em = resolve('em') as EntityManager\n const conn = em.getConnection()\n\n console.log('Checking analytics data...\\n')\n\n const ordersResult = await conn.execute(\n `SELECT COUNT(*) as total, MIN(placed_at) as earliest, MAX(placed_at) as latest\n FROM sales_orders\n WHERE tenant_id = ? AND order_number LIKE 'SO-ANALYTICS-%'`,\n [tenantId]\n )\n console.log('Orders summary:', ordersResult[0])\n\n const recentOrders = await conn.execute(\n `SELECT order_number, placed_at, status, grand_total_gross_amount::numeric as total\n FROM sales_orders\n WHERE tenant_id = ? AND order_number LIKE 'SO-ANALYTICS-%'\n ORDER BY placed_at DESC LIMIT 5`,\n [tenantId]\n )\n console.log('\\nRecent orders:', recentOrders)\n\n const januaryOrders = await conn.execute(\n `SELECT COUNT(*) as count, SUM(grand_total_gross_amount::numeric) as total\n FROM sales_orders\n WHERE tenant_id = ?\n AND order_number LIKE 'SO-ANALYTICS-%'\n AND placed_at >= '2026-01-01'\n AND placed_at <= '2026-01-31 23:59:59'`,\n [tenantId]\n )\n console.log('\\nJanuary 2026 orders:', januaryOrders[0])\n\n const allOrders = await conn.execute(\n `SELECT COUNT(*) as count\n FROM sales_orders\n WHERE tenant_id = ?`,\n [tenantId]\n )\n console.log('\\nTotal orders in tenant:', allOrders[0])\n\n const orgCheck = await conn.execute(\n `SELECT organization_id, COUNT(*) as count\n FROM sales_orders\n WHERE tenant_id = ? AND order_number LIKE 'SO-ANALYTICS-%'\n GROUP BY organization_id`,\n [tenantId]\n )\n console.log('\\nOrders by organization:', orgCheck)\n\n if (organizationId) {\n const orgOrders = await conn.execute(\n `SELECT COUNT(*) as count, SUM(grand_total_gross_amount::numeric) as total\n FROM sales_orders\n WHERE tenant_id = ?\n AND organization_id = ?\n AND placed_at >= '2026-01-01'\n AND placed_at <= '2026-01-31 23:59:59'`,\n [tenantId, organizationId]\n )\n console.log(`\\nJanuary orders for org ${organizationId}:`, orgOrders[0])\n }\n\n // Check for NULL placed_at\n const nullPlacedAt = await conn.execute(\n `SELECT COUNT(*) as count\n FROM sales_orders\n WHERE tenant_id = ? AND placed_at IS NULL`,\n [tenantId]\n )\n console.log('\\nOrders with NULL placed_at:', nullPlacedAt[0])\n\n // Check non-analytics orders\n const nonAnalytics = await conn.execute(\n `SELECT order_number, placed_at, status, organization_id, grand_total_gross_amount::numeric as total\n FROM sales_orders\n WHERE tenant_id = ? AND order_number NOT LIKE 'SO-ANALYTICS-%'\n ORDER BY placed_at DESC NULLS LAST LIMIT 10`,\n [tenantId]\n )\n console.log('\\nNon-analytics orders:', nonAnalytics)\n\n // Simulate widget query\n console.log('\\n--- Simulating widget query for this_month ---')\n const widgetQuery = await conn.execute(\n `SELECT COALESCE(SUM(grand_total_gross_amount::numeric), 0) AS value\n FROM sales_orders\n WHERE tenant_id = ?\n AND organization_id = ANY(?::uuid[])\n AND deleted_at IS NULL\n AND placed_at >= '2026-01-01'\n AND placed_at <= '2026-01-31 23:59:59'`,\n [tenantId, `{${organizationId}}`]\n )\n console.log('Widget query result (revenue sum):', widgetQuery[0])\n\n const widgetCountQuery = await conn.execute(\n `SELECT COUNT(*) AS value\n FROM sales_orders\n WHERE tenant_id = ?\n AND organization_id = ANY(?::uuid[])\n AND deleted_at IS NULL\n AND placed_at >= '2026-01-01'\n AND placed_at <= '2026-01-31 23:59:59'`,\n [tenantId, `{${organizationId}}`]\n )\n console.log('Widget query result (order count):', widgetCountQuery[0])\n },\n}\n\nexport default [seedDefaults, enableAnalyticsWidgets, seedAnalytics, debugAnalytics]\n"],
5
+ "mappings": "AACA,SAAS,8BAA8B;AAEvC,SAAS,4BAA4B;AACrC,SAAS,YAAY;AACrB,SAAS,sBAAsB;AAC/B,SAAS,sBAAsB,iCAAiC;AAChE,SAAS,yBAAyB;AAIlC,SAAS,UAAU,MAAsB;AACvC,QAAM,OAAa,CAAC;AACpB,WAAS,IAAI,GAAG,IAAI,KAAK,QAAQ,KAAK,GAAG;AACvC,UAAM,MAAM,KAAK,CAAC,GAAG,QAAQ,OAAO,EAAE;AACtC,UAAM,QAAQ,KAAK,IAAI,CAAC;AACxB,QAAI,IAAK,MAAK,GAAG,IAAI,SAAS;AAAA,EAChC;AACA,SAAO;AACT;AAEA,eAAsB,+BACpB,IACA;AAAA,EACE;AAAA,EACA,iBAAiB;AAAA,EACjB,YAAY,CAAC,cAAc,SAAS,UAAU;AAAA,EAC9C;AAAA,EACA;AACF,GAOkB;AAClB,MAAI,CAAC,SAAU,OAAM,IAAI,MAAM,sBAAsB;AACrD,QAAM,MAAM,WAAW,MAAM;AAAA,EAAC;AAE9B,QAAM,UAAU,MAAM,eAAe;AACrC,QAAM,YAAY,IAAI,IAAI,QAAQ,IAAI,CAAC,WAAW,CAAC,OAAO,SAAS,IAAI,MAAM,CAAC,CAAC;AAC/E,QAAM,oBAAoB,aAAa,UAAU,SAC7C,UAAU,OAAO,CAAC,OAAO,UAAU,IAAI,EAAE,CAAC,IAC1C;AACJ,QAAM,mBAAmB,QACtB,OAAO,CAAC,WAAW,OAAO,SAAS,cAAc,EACjD,IAAI,CAAC,WAAW,OAAO,SAAS,EAAE;AACrC,QAAM,eAAe,QAAQ,IAAI,CAAC,WAAW,OAAO,SAAS,EAAE;AAE/D,MAAI,qBAAqB,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cAAc,KAAK,UAAU,CAAC,CAAC;AAAA,IACzE;AAGA,UAAM,eAAe,MAAM,KAAK;AAAA,MAC9B;AAAA;AAAA;AAAA,MAGA,CAAC,QAAQ;AAAA,IACX;AACA,YAAQ,IAAI,iCAAiC,aAAa,CAAC,CAAC;AAG5D,UAAM,eAAe,MAAM,KAAK;AAAA,MAC9B;AAAA;AAAA;AAAA;AAAA,MAIA,CAAC,QAAQ;AAAA,IACX;AACA,YAAQ,IAAI,2BAA2B,YAAY;AAGnD,YAAQ,IAAI,kDAAkD;AAC9D,UAAM,cAAc,MAAM,KAAK;AAAA,MAC7B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,MAOA,CAAC,UAAU,IAAI,cAAc,GAAG;AAAA,IAClC;AACA,YAAQ,IAAI,sCAAsC,YAAY,CAAC,CAAC;AAEhE,UAAM,mBAAmB,MAAM,KAAK;AAAA,MAClC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,MAOA,CAAC,UAAU,IAAI,cAAc,GAAG;AAAA,IAClC;AACA,YAAQ,IAAI,sCAAsC,iBAAiB,CAAC,CAAC;AAAA,EACvE;AACF;AAEA,IAAO,cAAQ,CAAC,cAAc,wBAAwB,eAAe,cAAc;",
6
6
  "names": []
7
7
  }
@@ -1,10 +1,3 @@
1
- function resolveWidgetAssignmentTargetAccess(params) {
2
- const { isSuperAdmin, scopeTenantId, target } = params;
3
- if (!isSuperAdmin && !scopeTenantId) return "forbidden";
4
- if (!target) return "not-found";
5
- if (scopeTenantId && (target.tenantId ?? null) !== scopeTenantId) return "not-found";
6
- return "allowed";
7
- }
8
1
  function resolveWidgetAssignmentReadScope(params) {
9
2
  const { auth, isSuperAdmin, queryTenantId, queryOrganizationId } = params;
10
3
  if (isSuperAdmin) {
@@ -19,7 +12,6 @@ function resolveWidgetAssignmentReadScope(params) {
19
12
  };
20
13
  }
21
14
  export {
22
- resolveWidgetAssignmentReadScope,
23
- resolveWidgetAssignmentTargetAccess
15
+ resolveWidgetAssignmentReadScope
24
16
  };
25
17
  //# sourceMappingURL=widgetAssignmentScope.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/dashboards/lib/widgetAssignmentScope.ts"],
4
- "sourcesContent": ["export type AuthScopeInput = {\n tenantId?: string | null\n orgId?: string | null\n}\n\nexport type ResolvedAssignmentScope = {\n tenantId: string | null\n organizationId: string | null\n}\n\nexport type WidgetAssignmentTarget = {\n tenantId?: string | null\n}\n\nexport type WidgetAssignmentTargetAccess = 'allowed' | 'forbidden' | 'not-found'\n\nexport function resolveWidgetAssignmentTargetAccess(params: {\n isSuperAdmin: boolean\n scopeTenantId: string | null\n target: WidgetAssignmentTarget | null | undefined\n}): WidgetAssignmentTargetAccess {\n const { isSuperAdmin, scopeTenantId, target } = params\n if (!isSuperAdmin && !scopeTenantId) return 'forbidden'\n if (!target) return 'not-found'\n if (scopeTenantId && (target.tenantId ?? null) !== scopeTenantId) return 'not-found'\n return 'allowed'\n}\n\nexport function resolveWidgetAssignmentReadScope(params: {\n auth: AuthScopeInput\n isSuperAdmin: boolean\n queryTenantId?: string | null\n queryOrganizationId?: string | null\n}): ResolvedAssignmentScope {\n const { auth, isSuperAdmin, queryTenantId, queryOrganizationId } = params\n if (isSuperAdmin) {\n return {\n tenantId: (queryTenantId && queryTenantId.length ? queryTenantId : auth.tenantId) ?? null,\n organizationId:\n (queryOrganizationId && queryOrganizationId.length ? queryOrganizationId : auth.orgId) ?? null,\n }\n }\n return {\n tenantId: auth.tenantId ?? null,\n organizationId: auth.orgId ?? null,\n }\n}\n"],
5
- "mappings": "AAgBO,SAAS,oCAAoC,QAInB;AAC/B,QAAM,EAAE,cAAc,eAAe,OAAO,IAAI;AAChD,MAAI,CAAC,gBAAgB,CAAC,cAAe,QAAO;AAC5C,MAAI,CAAC,OAAQ,QAAO;AACpB,MAAI,kBAAkB,OAAO,YAAY,UAAU,cAAe,QAAO;AACzE,SAAO;AACT;AAEO,SAAS,iCAAiC,QAKrB;AAC1B,QAAM,EAAE,MAAM,cAAc,eAAe,oBAAoB,IAAI;AACnE,MAAI,cAAc;AAChB,WAAO;AAAA,MACL,WAAW,iBAAiB,cAAc,SAAS,gBAAgB,KAAK,aAAa;AAAA,MACrF,iBACG,uBAAuB,oBAAoB,SAAS,sBAAsB,KAAK,UAAU;AAAA,IAC9F;AAAA,EACF;AACA,SAAO;AAAA,IACL,UAAU,KAAK,YAAY;AAAA,IAC3B,gBAAgB,KAAK,SAAS;AAAA,EAChC;AACF;",
4
+ "sourcesContent": ["export type AuthScopeInput = {\n tenantId?: string | null\n orgId?: string | null\n}\n\nexport type ResolvedAssignmentScope = {\n tenantId: string | null\n organizationId: string | null\n}\n\nexport function resolveWidgetAssignmentReadScope(params: {\n auth: AuthScopeInput\n isSuperAdmin: boolean\n queryTenantId?: string | null\n queryOrganizationId?: string | null\n}): ResolvedAssignmentScope {\n const { auth, isSuperAdmin, queryTenantId, queryOrganizationId } = params\n if (isSuperAdmin) {\n return {\n tenantId: (queryTenantId && queryTenantId.length ? queryTenantId : auth.tenantId) ?? null,\n organizationId:\n (queryOrganizationId && queryOrganizationId.length ? queryOrganizationId : auth.orgId) ?? null,\n }\n }\n return {\n tenantId: auth.tenantId ?? null,\n organizationId: auth.orgId ?? null,\n }\n}\n"],
5
+ "mappings": "AAUO,SAAS,iCAAiC,QAKrB;AAC1B,QAAM,EAAE,MAAM,cAAc,eAAe,oBAAoB,IAAI;AACnE,MAAI,cAAc;AAChB,WAAO;AAAA,MACL,WAAW,iBAAiB,cAAc,SAAS,gBAAgB,KAAK,aAAa;AAAA,MACrF,iBACG,uBAAuB,oBAAoB,SAAS,sBAAsB,KAAK,UAAU;AAAA,IAC9F;AAAA,EACF;AACA,SAAO;AAAA,IACL,UAAU,KAAK,YAAY;AAAA,IAC3B,gBAAgB,KAAK,SAAS;AAAA,EAChC;AACF;",
6
6
  "names": []
7
7
  }
@@ -3,12 +3,19 @@ import {
3
3
  dictionaryEntryCommandCreateSchema,
4
4
  dictionaryEntryCommandUpdateSchema
5
5
  } from "@open-mercato/core/modules/dictionaries/data/validators";
6
- import {
7
- ensureDictionaryEntryScope,
8
- registerDictionaryEntryCommands
9
- } from "@open-mercato/core/modules/dictionaries/commands/factory";
6
+ import { registerDictionaryEntryCommands } from "@open-mercato/core/modules/dictionaries/commands/factory";
10
7
  import { CrudHttpError } from "@open-mercato/shared/lib/crud/errors";
11
8
  import { findOneWithDecryption } from "@open-mercato/shared/lib/encryption/find";
9
+ function ensureScope(ctx, scope) {
10
+ const tenantId = ctx.auth?.tenantId ?? null;
11
+ if (tenantId && tenantId !== scope.tenantId) {
12
+ throw new CrudHttpError(403, { error: "Forbidden" });
13
+ }
14
+ const organizationId = ctx.selectedOrganizationId ?? ctx.auth?.orgId ?? null;
15
+ if (organizationId && organizationId !== scope.organizationId) {
16
+ throw new CrudHttpError(403, { error: "Forbidden" });
17
+ }
18
+ }
12
19
  async function ensureDictionary(em, id) {
13
20
  const dictionary = await em.findOne(Dictionary, {
14
21
  id,
@@ -25,12 +32,12 @@ registerDictionaryEntryCommands({
25
32
  translationKeyPrefix: "dictionaries.entries",
26
33
  createSchema: dictionaryEntryCommandCreateSchema,
27
34
  updateSchema: dictionaryEntryCommandUpdateSchema,
28
- ensureScope: ensureDictionaryEntryScope,
35
+ ensureScope,
29
36
  duplicateError: "An entry with this value already exists.",
30
37
  resolveDictionaryForCreate: async ({ em, ctx, parsed }) => {
31
38
  const dictionary = await ensureDictionary(em, parsed.dictionaryId);
32
39
  const scope = { tenantId: dictionary.tenantId, organizationId: dictionary.organizationId };
33
- ensureDictionaryEntryScope(ctx, scope);
40
+ ensureScope(ctx, scope);
34
41
  return { dictionary, scope };
35
42
  },
36
43
  resolveEntry: async ({ em, ctx, id }) => {
@@ -42,7 +49,7 @@ registerDictionaryEntryCommands({
42
49
  throw new CrudHttpError(404, { error: "Dictionary not found" });
43
50
  }
44
51
  const scope = { tenantId: entry.tenantId, organizationId: entry.organizationId };
45
- ensureDictionaryEntryScope(ctx, scope);
52
+ ensureScope(ctx, scope);
46
53
  return { entry, dictionary: entry.dictionary, scope };
47
54
  },
48
55
  ensureDictionaryForUndo: async ({ em, snapshot }) => {
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/dictionaries/commands/entries.ts"],
4
- "sourcesContent": ["import type { EntityManager } from '@mikro-orm/postgresql'\nimport { Dictionary, DictionaryEntry } from '@open-mercato/core/modules/dictionaries/data/entities'\nimport {\n dictionaryEntryCommandCreateSchema,\n dictionaryEntryCommandUpdateSchema,\n} from '@open-mercato/core/modules/dictionaries/data/validators'\nimport {\n ensureDictionaryEntryScope,\n registerDictionaryEntryCommands,\n} from '@open-mercato/core/modules/dictionaries/commands/factory'\nimport { CrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\n\nasync function ensureDictionary(em: EntityManager, id: string): Promise<Dictionary> {\n const dictionary = await em.findOne(Dictionary, {\n id,\n deletedAt: null,\n })\n if (!dictionary) {\n throw new CrudHttpError(404, { error: 'Dictionary not found' })\n }\n return dictionary\n}\n\nregisterDictionaryEntryCommands({\n commandPrefix: 'dictionaries.entries',\n resourceKind: 'dictionaries.entry',\n translationKeyPrefix: 'dictionaries.entries',\n createSchema: dictionaryEntryCommandCreateSchema,\n updateSchema: dictionaryEntryCommandUpdateSchema,\n ensureScope: ensureDictionaryEntryScope,\n duplicateError: 'An entry with this value already exists.',\n resolveDictionaryForCreate: async ({ em, ctx, parsed }) => {\n const dictionary = await ensureDictionary(em, parsed.dictionaryId)\n const scope = { tenantId: dictionary.tenantId, organizationId: dictionary.organizationId }\n ensureDictionaryEntryScope(ctx, scope)\n return { dictionary, scope }\n },\n resolveEntry: async ({ em, ctx, id }) => {\n const entry = await findOneWithDecryption(em, DictionaryEntry, id, { populate: ['dictionary'] })\n if (!entry) {\n throw new CrudHttpError(404, { error: 'Dictionary entry not found' })\n }\n if (entry.dictionary.deletedAt) {\n throw new CrudHttpError(404, { error: 'Dictionary not found' })\n }\n const scope = { tenantId: entry.tenantId, organizationId: entry.organizationId }\n ensureDictionaryEntryScope(ctx, scope)\n return { entry, dictionary: entry.dictionary, scope }\n },\n ensureDictionaryForUndo: async ({ em, snapshot }) => {\n return em.findOne(Dictionary, snapshot.dictionaryId, { filters: false })\n },\n})\n"],
5
- "mappings": "AACA,SAAS,YAAY,uBAAuB;AAC5C;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP,SAAS,qBAAqB;AAC9B,SAAS,6BAA6B;AAEtC,eAAe,iBAAiB,IAAmB,IAAiC;AAClF,QAAM,aAAa,MAAM,GAAG,QAAQ,YAAY;AAAA,IAC9C;AAAA,IACA,WAAW;AAAA,EACb,CAAC;AACD,MAAI,CAAC,YAAY;AACf,UAAM,IAAI,cAAc,KAAK,EAAE,OAAO,uBAAuB,CAAC;AAAA,EAChE;AACA,SAAO;AACT;AAEA,gCAAgC;AAAA,EAC9B,eAAe;AAAA,EACf,cAAc;AAAA,EACd,sBAAsB;AAAA,EACtB,cAAc;AAAA,EACd,cAAc;AAAA,EACd,aAAa;AAAA,EACb,gBAAgB;AAAA,EAChB,4BAA4B,OAAO,EAAE,IAAI,KAAK,OAAO,MAAM;AACzD,UAAM,aAAa,MAAM,iBAAiB,IAAI,OAAO,YAAY;AACjE,UAAM,QAAQ,EAAE,UAAU,WAAW,UAAU,gBAAgB,WAAW,eAAe;AACzF,+BAA2B,KAAK,KAAK;AACrC,WAAO,EAAE,YAAY,MAAM;AAAA,EAC7B;AAAA,EACA,cAAc,OAAO,EAAE,IAAI,KAAK,GAAG,MAAM;AACvC,UAAM,QAAQ,MAAM,sBAAsB,IAAI,iBAAiB,IAAI,EAAE,UAAU,CAAC,YAAY,EAAE,CAAC;AAC/F,QAAI,CAAC,OAAO;AACV,YAAM,IAAI,cAAc,KAAK,EAAE,OAAO,6BAA6B,CAAC;AAAA,IACtE;AACA,QAAI,MAAM,WAAW,WAAW;AAC9B,YAAM,IAAI,cAAc,KAAK,EAAE,OAAO,uBAAuB,CAAC;AAAA,IAChE;AACA,UAAM,QAAQ,EAAE,UAAU,MAAM,UAAU,gBAAgB,MAAM,eAAe;AAC/E,+BAA2B,KAAK,KAAK;AACrC,WAAO,EAAE,OAAO,YAAY,MAAM,YAAY,MAAM;AAAA,EACtD;AAAA,EACA,yBAAyB,OAAO,EAAE,IAAI,SAAS,MAAM;AACnD,WAAO,GAAG,QAAQ,YAAY,SAAS,cAAc,EAAE,SAAS,MAAM,CAAC;AAAA,EACzE;AACF,CAAC;",
4
+ "sourcesContent": ["import type { EntityManager } from '@mikro-orm/postgresql'\nimport { Dictionary, DictionaryEntry } from '@open-mercato/core/modules/dictionaries/data/entities'\nimport {\n dictionaryEntryCommandCreateSchema,\n dictionaryEntryCommandUpdateSchema,\n} from '@open-mercato/core/modules/dictionaries/data/validators'\nimport { registerDictionaryEntryCommands } from '@open-mercato/core/modules/dictionaries/commands/factory'\nimport type { CommandRuntimeContext } from '@open-mercato/shared/lib/commands'\nimport { CrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\n\nfunction ensureScope(ctx: CommandRuntimeContext, scope: { tenantId: string; organizationId: string }): void {\n const tenantId = ctx.auth?.tenantId ?? null\n if (tenantId && tenantId !== scope.tenantId) {\n throw new CrudHttpError(403, { error: 'Forbidden' })\n }\n const organizationId = ctx.selectedOrganizationId ?? ctx.auth?.orgId ?? null\n if (organizationId && organizationId !== scope.organizationId) {\n throw new CrudHttpError(403, { error: 'Forbidden' })\n }\n}\n\nasync function ensureDictionary(em: EntityManager, id: string): Promise<Dictionary> {\n const dictionary = await em.findOne(Dictionary, {\n id,\n deletedAt: null,\n })\n if (!dictionary) {\n throw new CrudHttpError(404, { error: 'Dictionary not found' })\n }\n return dictionary\n}\n\nregisterDictionaryEntryCommands({\n commandPrefix: 'dictionaries.entries',\n resourceKind: 'dictionaries.entry',\n translationKeyPrefix: 'dictionaries.entries',\n createSchema: dictionaryEntryCommandCreateSchema,\n updateSchema: dictionaryEntryCommandUpdateSchema,\n ensureScope,\n duplicateError: 'An entry with this value already exists.',\n resolveDictionaryForCreate: async ({ em, ctx, parsed }) => {\n const dictionary = await ensureDictionary(em, parsed.dictionaryId)\n const scope = { tenantId: dictionary.tenantId, organizationId: dictionary.organizationId }\n ensureScope(ctx, scope)\n return { dictionary, scope }\n },\n resolveEntry: async ({ em, ctx, id }) => {\n const entry = await findOneWithDecryption(em, DictionaryEntry, id, { populate: ['dictionary'] })\n if (!entry) {\n throw new CrudHttpError(404, { error: 'Dictionary entry not found' })\n }\n if (entry.dictionary.deletedAt) {\n throw new CrudHttpError(404, { error: 'Dictionary not found' })\n }\n const scope = { tenantId: entry.tenantId, organizationId: entry.organizationId }\n ensureScope(ctx, scope)\n return { entry, dictionary: entry.dictionary, scope }\n },\n ensureDictionaryForUndo: async ({ em, snapshot }) => {\n return em.findOne(Dictionary, snapshot.dictionaryId, { filters: false })\n },\n})\n"],
5
+ "mappings": "AACA,SAAS,YAAY,uBAAuB;AAC5C;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP,SAAS,uCAAuC;AAEhD,SAAS,qBAAqB;AAC9B,SAAS,6BAA6B;AAEtC,SAAS,YAAY,KAA4B,OAA2D;AAC1G,QAAM,WAAW,IAAI,MAAM,YAAY;AACvC,MAAI,YAAY,aAAa,MAAM,UAAU;AAC3C,UAAM,IAAI,cAAc,KAAK,EAAE,OAAO,YAAY,CAAC;AAAA,EACrD;AACA,QAAM,iBAAiB,IAAI,0BAA0B,IAAI,MAAM,SAAS;AACxE,MAAI,kBAAkB,mBAAmB,MAAM,gBAAgB;AAC7D,UAAM,IAAI,cAAc,KAAK,EAAE,OAAO,YAAY,CAAC;AAAA,EACrD;AACF;AAEA,eAAe,iBAAiB,IAAmB,IAAiC;AAClF,QAA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3
  reorderDictionaryEntriesCommandSchema,
4
4
  setDefaultDictionaryEntryCommandSchema
5
5
  } from "@open-mercato/core/modules/dictionaries/data/validators";
6
- import { ensureDictionaryEntryScope } from "@open-mercato/core/modules/dictionaries/commands/factory";
7
6
  import { registerCommand } from "@open-mercato/shared/lib/commands";
8
7
  import { extractUndoPayload } from "@open-mercato/shared/lib/commands/undo";
9
8
  import { withAtomicFlush } from "@open-mercato/shared/lib/commands/flush";
@@ -24,6 +23,16 @@ const dictionaryCrudEvents = {
24
23
  ...ctx.syncOrigin ? { syncOrigin: ctx.syncOrigin } : {}
25
24
  })
26
25
  };
26
+ function ensureScope(ctx, scope) {
27
+ const tenantId = ctx.auth?.tenantId ?? null;
28
+ if (tenantId && tenantId !== scope.tenantId) {
29
+ throw new CrudHttpError(403, { error: "Forbidden" });
30
+ }
31
+ const organizationId = ctx.selectedOrganizationId ?? ctx.auth?.orgId ?? null;
32
+ if (organizationId && organizationId !== scope.organizationId) {
33
+ throw new CrudHttpError(403, { error: "Forbidden" });
34
+ }
35
+ }
27
36
  async function requireDictionary(em, id, scope) {
28
37
  const dictionary = await findOneWithDecryption(
29
38
  em,
@@ -42,7 +51,7 @@ const reorderDictionaryEntriesCommand = {
42
51
  async prepare(rawInput, ctx) {
43
52
  const parsed = reorderDictionaryEntriesCommandSchema.parse(rawInput);
44
53
  const scope = { tenantId: parsed.tenantId, organizationId: parsed.organizationId };
45
- ensureDictionaryEntryScope(ctx, scope);
54
+ ensureScope(ctx, scope);
46
55
  const em = ctx.container.resolve("em").fork();
47
56
  const ids = parsed.entries.map((e) => e.id);
48
57
  const existing = await findWithDecryption(
@@ -66,7 +75,7 @@ const reorderDictionaryEntriesCommand = {
66
75
  async execute(rawInput, ctx) {
67
76
  const parsed = reorderDictionaryEntriesCommandSchema.parse(rawInput);
68
77
  const scope = { tenantId: parsed.tenantId, organizationId: parsed.organizationId };
69
- ensureDictionaryEntryScope(ctx, scope);
78
+ ensureScope(ctx, scope);
70
79
  const em = ctx.container.resolve("em").fork();
71
80
  const dictionary = await requireDictionary(em, parsed.dictionaryId, scope);
72
81
  const ids = parsed.entries.map((e) => e.id);
@@ -155,7 +164,7 @@ const reorderDictionaryEntriesCommand = {
155
164
  const undo = extractUndoPayload(logEntry);
156
165
  const before = undo?.before ?? logEntry?.snapshotBefore ?? null;
157
166
  if (!before) return;
158
- ensureDictionaryEntryScope(ctx, before.scope);
167
+ ensureScope(ctx, before.scope);
159
168
  const em = ctx.container.resolve("em").fork();
160
169
  const ids = before.positions.map((p) => p.id);
161
170
  const entries = await findWithDecryption(
@@ -200,7 +209,7 @@ const setDefaultDictionaryEntryCommand = {
200
209
  async prepare(rawInput, ctx) {
201
210
  const parsed = setDefaultDictionaryEntryCommandSchema.parse(rawInput);
202
211
  const scope = { tenantId: parsed.tenantId, organizationId: parsed.organizationId };
203
- ensureDictionaryEntryScope(ctx, scope);
212
+ ensureScope(ctx, scope);
204
213
  const em = ctx.container.resolve("em").fork();
205
214
  const dictionary = await requireDictionary(em, parsed.dictionaryId, scope);
206
215
  const previousDefaults = await findWithDecryption(
@@ -226,7 +235,7 @@ const setDefaultDictionaryEntryCommand = {
226
235
  async execute(rawInput, ctx) {
227
236
  const parsed = setDefaultDictionaryEntryCommandSchema.parse(rawInput);
228
237
  const scope = { tenantId: parsed.tenantId, organizationId: parsed.organizationId };
229
- ensureDictionaryEntryScope(ctx, scope);
238
+ ensureScope(ctx, scope);
230
239
  const em = ctx.container.resolve("em").fork();
231
240
  const dictionary = await requireDictionary(em, parsed.dictionaryId, scope);
232
241
  const targetEntry = await findOneWithDecryption(
@@ -321,7 +330,7 @@ const setDefaultDictionaryEntryCommand = {
321
330
  const undo = extractUndoPayload(logEntry);
322
331
  const before = undo?.before ?? logEntry?.snapshotBefore ?? null;
323
332
  if (!before) return;
324
- ensureDictionaryEntryScope(ctx, before.scope);
333
+ ensureScope(ctx, before.scope);
325
334
  const em = ctx.container.resolve("em").fork();
326
335
  const dictionary = await requireDictionary(em, before.dictionaryId, before.scope);
327
336
  const newDefault = before.newDefaultId ? await findOneWithDecryption(
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/dictionaries/commands/entry-operations.ts"],
4
- "sourcesContent": ["import type { EntityManager, FilterQuery } from '@mikro-orm/postgresql'\nimport { Dictionary, DictionaryEntry } from '@open-mercato/core/modules/dictionaries/data/entities'\nimport {\n reorderDictionaryEntriesCommandSchema,\n setDefaultDictionaryEntryCommandSchema,\n type ReorderDictionaryEntriesCommandInput,\n type SetDefaultDictionaryEntryCommandInput,\n} from '@open-mercato/core/modules/dictionaries/data/validators'\nimport { ensureDictionaryEntryScope } from '@open-mercato/core/modules/dictionaries/commands/factory'\nimport { registerCommand, type CommandHandler } from '@open-mercato/shared/lib/commands'\nimport { extractUndoPayload } from '@open-mercato/shared/lib/commands/undo'\nimport { withAtomicFlush } from '@open-mercato/shared/lib/commands/flush'\nimport { emitCrudSideEffects, emitCrudUndoSideEffects } from '@open-mercato/shared/lib/commands/helpers'\nimport type { CrudEventsConfig } from '@open-mercato/shared/lib/crud/types'\nimport { CrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport type { DataEngine } from '@open-mercato/shared/lib/data/engine'\nimport { findOneWithDecryption, findWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\n\nconst RESOURCE_KIND = 'dictionaries.dictionary'\nconst INDEXER_ENTITY_TYPE = 'dictionaries:entry'\n\ntype DictionaryScope = {\n tenantId: string\n organizationId: string\n}\n\nconst dictionaryCrudEvents: CrudEventsConfig = {\n module: 'dictionaries',\n entity: 'entry',\n persistent: true,\n buildPayload: (ctx) => ({\n id: ctx.identifiers.id,\n organizationId: ctx.identifiers.organizationId,\n tenantId: ctx.identifiers.tenantId,\n ...(ctx.syncOrigin ? { syncOrigin: ctx.syncOrigin } : {}),\n }),\n}\n\nasync function requireDictionary(\n em: EntityManager,\n id: string,\n scope: DictionaryScope,\n): Promise<Dictionary> {\n const dictionary = await findOneWithDecryption(\n em,\n Dictionary,\n { id, tenantId: scope.tenantId, organizationId: scope.organizationId, deletedAt: null },\n undefined,\n scope,\n )\n if (!dictionary) {\n throw new CrudHttpError(404, { error: 'Dictionary not found' })\n }\n return dictionary\n}\n\ntype ReorderSnapshot = {\n dictionaryId: string\n scope: DictionaryScope\n positions: Array<{ id: string; position: number }>\n}\n\ntype ReorderUndoPayload = {\n before?: ReorderSnapshot | null\n after?: ReorderSnapshot | null\n}\n\nconst reorderDictionaryEntriesCommand: CommandHandler<\n ReorderDictionaryEntriesCommandInput,\n { dictionaryId: string; updatedIds: string[] }\n> = {\n id: 'dictionaries.entries.reorder',\n async prepare(rawInput, ctx) {\n const parsed = reorderDictionaryEntriesCommandSchema.parse(rawInput)\n const scope: DictionaryScope = { tenantId: parsed.tenantId, organizationId: parsed.organizationId }\n ensureDictionaryEntryScope(ctx, scope)\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const ids = parsed.entries.map((e) => e.id)\n const existing = await findWithDecryption(\n em,\n DictionaryEntry,\n {\n id: { $in: ids },\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n } as FilterQuery<DictionaryEntry>,\n undefined,\n scope,\n )\n const before: ReorderSnapshot = {\n dictionaryId: parsed.dictionaryId,\n scope,\n positions: existing.map((entry) => ({ id: entry.id, position: entry.position ?? 0 })),\n }\n return { before }\n },\n async execute(rawInput, ctx) {\n const parsed = reorderDictionaryEntriesCommandSchema.parse(rawInput)\n const scope: DictionaryScope = { tenantId: parsed.tenantId, organizationId: parsed.organizationId }\n ensureDictionaryEntryScope(ctx, scope)\n\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const dictionary = await requireDictionary(em, parsed.dictionaryId, scope)\n const ids = parsed.entries.map((e) => e.id)\n const entries = await findWithDecryption(\n em,\n DictionaryEntry,\n {\n id: { $in: ids },\n dictionary,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n } as FilterQuery<DictionaryEntry>,\n undefined,\n scope,\n )\n const entryMap = new Map<string, DictionaryEntry>()\n for (const entry of entries) entryMap.set(entry.id, entry)\n\n const updatedIds: string[] = []\n await withAtomicFlush(em, [\n () => {\n for (const { id, position } of parsed.entries) {\n const entry = entryMap.get(id)\n if (!entry) continue\n entry.position = position\n entry.updatedAt = new Date()\n updatedIds.push(id)\n }\n },\n ], { transaction: true })\n\n const dataEngine = ctx.container.resolve('dataEngine') as DataEngine\n for (const entry of entries) {\n await emitCrudSideEffects({\n dataEngine,\n action: 'updated',\n entity: entry,\n identifiers: { id: entry.id, tenantId: entry.tenantId, organizationId: entry.organizationId },\n syncOrigin: ctx.syncOrigin,\n events: dictionaryCrudEvents,\n indexer: { entityType: INDEXER_ENTITY_TYPE },\n })\n }\n\n return { dictionaryId: parsed.dictionaryId, updatedIds }\n },\n captureAfter: async (rawInput, _result, ctx) => {\n const parsed = reorderDictionaryEntriesCommandSchema.parse(rawInput)\n const em = ctx.container.resolve('em') as EntityManager\n const scope: DictionaryScope = { tenantId: parsed.tenantId, organizationId: parsed.organizationId }\n const ids = parsed.entries.map((e) => e.id)\n const current = await findWithDecryption(\n em,\n DictionaryEntry,\n {\n id: { $in: ids },\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n } as FilterQuery<DictionaryEntry>,\n undefined,\n scope,\n )\n const after: ReorderSnapshot = {\n dictionaryId: parsed.dictionaryId,\n scope,\n positions: current.map((entry) => ({ id: entry.id, position: entry.position ?? 0 })),\n }\n return after\n },\n buildLog: async ({ snapshots, result }) => {\n const { translate } = await resolveTranslations()\n const before = snapshots.before as ReorderSnapshot | undefined\n const after = snapshots.after as ReorderSnapshot | undefined\n if (!before || !after) return null\n return {\n actionLabel: translate('dictionaries.entries.audit.reorder', 'Reorder dictionary entries'),\n resourceKind: RESOURCE_KIND,\n resourceId: result.dictionaryId,\n tenantId: before.scope.tenantId,\n organizationId: before.scope.organizationId,\n snapshotBefore: before,\n snapshotAfter: after,\n payload: {\n undo: { before, after } satisfies ReorderUndoPayload,\n },\n }\n },\n undo: async ({ logEntry, ctx }) => {\n const undo = extractUndoPayload<ReorderUndoPayload>(logEntry)\n const before = undo?.before ?? (logEntry?.snapshotBefore as ReorderSnapshot | null | undefined) ?? null\n if (!before) return\n ensureDictionaryEntryScope(ctx, before.scope)\n\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const ids = before.positions.map((p) => p.id)\n const entries = await findWithDecryption(\n em,\n DictionaryEntry,\n {\n id: { $in: ids },\n tenantId: before.scope.tenantId,\n organizationId: before.scope.organizationId,\n } as FilterQuery<DictionaryEntry>,\n undefined,\n before.scope,\n )\n const entryMap = new Map<string, DictionaryEntry>()\n for (const entry of entries) entryMap.set(entry.id, entry)\n\n await withAtomicFlush(em, [\n () => {\n for (const { id, position } of before.positions) {\n const entry = entryMap.get(id)\n if (!entry) continue\n entry.position = position\n entry.updatedAt = new Date()\n }\n },\n ], { transaction: true })\n\n const dataEngine = ctx.container.resolve('dataEngine') as DataEngine\n for (const entry of entries) {\n await emitCrudUndoSideEffects({\n dataEngine,\n action: 'updated',\n entity: entry,\n identifiers: { id: entry.id, tenantId: entry.tenantId, organizationId: entry.organizationId },\n syncOrigin: ctx.syncOrigin,\n events: dictionaryCrudEvents,\n indexer: { entityType: INDEXER_ENTITY_TYPE },\n })\n }\n },\n}\n\ntype DefaultSnapshot = {\n dictionaryId: string\n scope: DictionaryScope\n previousDefaultIds: string[]\n newDefaultId: string\n}\n\ntype DefaultUndoPayload = {\n before?: DefaultSnapshot | null\n after?: DefaultSnapshot | null\n}\n\nconst setDefaultDictionaryEntryCommand: CommandHandler<\n SetDefaultDictionaryEntryCommandInput,\n { dictionaryId: string; entryId: string; clearedIds: string[] }\n> = {\n id: 'dictionaries.entries.set_default',\n async prepare(rawInput, ctx) {\n const parsed = setDefaultDictionaryEntryCommandSchema.parse(rawInput)\n const scope: DictionaryScope = { tenantId: parsed.tenantId, organizationId: parsed.organizationId }\n ensureDictionaryEntryScope(ctx, scope)\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const dictionary = await requireDictionary(em, parsed.dictionaryId, scope)\n const previousDefaults = await findWithDecryption(\n em,\n DictionaryEntry,\n {\n dictionary,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n isDefault: true,\n } as FilterQuery<DictionaryEntry>,\n undefined,\n scope,\n )\n const before: DefaultSnapshot = {\n dictionaryId: parsed.dictionaryId,\n scope,\n previousDefaultIds: previousDefaults.map((entry) => entry.id),\n newDefaultId: parsed.entryId,\n }\n return { before }\n },\n async execute(rawInput, ctx) {\n const parsed = setDefaultDictionaryEntryCommandSchema.parse(rawInput)\n const scope: DictionaryScope = { tenantId: parsed.tenantId, organizationId: parsed.organizationId }\n ensureDictionaryEntryScope(ctx, scope)\n\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const dictionary = await requireDictionary(em, parsed.dictionaryId, scope)\n const targetEntry = await findOneWithDecryption(\n em,\n DictionaryEntry,\n {\n id: parsed.entryId,\n dictionary,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n } as FilterQuery<DictionaryEntry>,\n undefined,\n scope,\n )\n if (!targetEntry) {\n throw new CrudHttpError(404, { error: 'Dictionary entry not found' })\n }\n\n const existingDefaults = await findWithDecryption(\n em,\n DictionaryEntry,\n {\n dictionary,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n isDefault: true,\n } as FilterQuery<DictionaryEntry>,\n undefined,\n scope,\n )\n const clearedIds: string[] = []\n\n // The partial unique index `dictionary_entries_one_default_per_dict`\n // (dictionary_id, organization_id, tenant_id) WHERE is_default = true forbids\n // two default entries in the same dictionary. PostgreSQL checks partial unique\n // indexes per-statement (no deferral) and MikroORM does not guarantee that the\n // is_default=false UPDATEs run before the is_default=true UPDATE within a single\n // flush, so clearing and setting in one flush races to a 23505. Clear the prior\n // default(s) in their own flush first, then set the new default in a second\n // flush, so Postgres never observes two default rows at once.\n await withAtomicFlush(em, [\n () => {\n for (const entry of existingDefaults) {\n if (entry.id === targetEntry.id) continue\n entry.isDefault = false\n entry.updatedAt = new Date()\n clearedIds.push(entry.id)\n }\n },\n ], { transaction: true })\n await withAtomicFlush(em, [\n () => {\n targetEntry.isDefault = true\n targetEntry.updatedAt = new Date()\n },\n ], { transaction: true })\n\n const dataEngine = ctx.container.resolve('dataEngine') as DataEngine\n const touched = [targetEntry, ...existingDefaults.filter((entry) => entry.id !== targetEntry.id)]\n for (const entry of touched) {\n await emitCrudSideEffects({\n dataEngine,\n action: 'updated',\n entity: entry,\n identifiers: { id: entry.id, tenantId: entry.tenantId, organizationId: entry.organizationId },\n syncOrigin: ctx.syncOrigin,\n events: dictionaryCrudEvents,\n indexer: { entityType: INDEXER_ENTITY_TYPE },\n })\n }\n\n return { dictionaryId: parsed.dictionaryId, entryId: targetEntry.id, clearedIds }\n },\n captureAfter: async (rawInput, result, _ctx) => {\n const parsed = setDefaultDictionaryEntryCommandSchema.parse(rawInput)\n const scope: DictionaryScope = { tenantId: parsed.tenantId, organizationId: parsed.organizationId }\n const after: DefaultSnapshot = {\n dictionaryId: parsed.dictionaryId,\n scope,\n previousDefaultIds: result.clearedIds,\n newDefaultId: result.entryId,\n }\n return after\n },\n buildLog: async ({ snapshots, result }) => {\n const { translate } = await resolveTranslations()\n const before = snapshots.before as DefaultSnapshot | undefined\n const after = snapshots.after as DefaultSnapshot | undefined\n if (!before || !after) return null\n return {\n actionLabel: translate('dictionaries.entries.audit.set_default', 'Set default dictionary entry'),\n resourceKind: RESOURCE_KIND,\n resourceId: result.dictionaryId,\n tenantId: before.scope.tenantId,\n organizationId: before.scope.organizationId,\n snapshotBefore: before,\n snapshotAfter: after,\n payload: {\n undo: { before, after } satisfies DefaultUndoPayload,\n },\n }\n },\n undo: async ({ logEntry, ctx }) => {\n const undo = extractUndoPayload<DefaultUndoPayload>(logEntry)\n const before = undo?.before ?? (logEntry?.snapshotBefore as DefaultSnapshot | null | undefined) ?? null\n if (!before) return\n ensureDictionaryEntryScope(ctx, before.scope)\n\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const dictionary = await requireDictionary(em, before.dictionaryId, before.scope)\n\n const newDefault = before.newDefaultId\n ? await findOneWithDecryption(\n em,\n DictionaryEntry,\n {\n id: before.newDefaultId,\n dictionary,\n tenantId: before.scope.tenantId,\n organizationId: before.scope.organizationId,\n } as FilterQuery<DictionaryEntry>,\n undefined,\n before.scope,\n )\n : null\n const previousDefaults = before.previousDefaultIds.length > 0\n ? await findWithDecryption(\n em,\n DictionaryEntry,\n {\n id: { $in: before.previousDefaultIds },\n dictionary,\n tenantId: before.scope.tenantId,\n organizationId: before.scope.organizationId,\n } as FilterQuery<DictionaryEntry>,\n undefined,\n before.scope,\n )\n : []\n\n // Same partial-unique-index ordering constraint as `execute`: clear the\n // current default in its own flush before restoring the previous default(s),\n // so Postgres never sees two is_default=true rows in the dictionary at once.\n await withAtomicFlush(em, [\n () => {\n if (newDefault) {\n newDefault.isDefault = false\n newDefault.updatedAt = new Date()\n }\n },\n ], { transaction: true })\n await withAtomicFlush(em, [\n () => {\n for (const entry of previousDefaults) {\n entry.isDefault = true\n entry.updatedAt = new Date()\n }\n },\n ], { transaction: true })\n\n const dataEngine = ctx.container.resolve('dataEngine') as DataEngine\n const touched = [\n ...(newDefault ? [newDefault] : []),\n ...previousDefaults,\n ]\n for (const entry of touched) {\n await emitCrudUndoSideEffects({\n dataEngine,\n action: 'updated',\n entity: entry,\n identifiers: { id: entry.id, tenantId: entry.tenantId, organizationId: entry.organizationId },\n syncOrigin: ctx.syncOrigin,\n events: dictionaryCrudEvents,\n indexer: { entityType: INDEXER_ENTITY_TYPE },\n })\n }\n },\n}\n\nregisterCommand(reorderDictionaryEntriesCommand)\nregisterCommand(setDefaultDictionaryEntryCommand)\n"],
5
- "mappings": "AACA,SAAS,YAAY,uBAAuB;AAC5C;AAAA,EACE;AAAA,EACA;AAAA,OAGK;AACP,SAAS,kCAAkC;AAC3C,SAAS,uBAA4C;AACrD,SAAS,0BAA0B;AACn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cesContent": ["import type { EntityManager, FilterQuery } from '@mikro-orm/postgresql'\nimport { Dictionary, DictionaryEntry } from '@open-mercato/core/modules/dictionaries/data/entities'\nimport {\n reorderDictionaryEntriesCommandSchema,\n setDefaultDictionaryEntryCommandSchema,\n type ReorderDictionaryEntriesCommandInput,\n type SetDefaultDictionaryEntryCommandInput,\n} from '@open-mercato/core/modules/dictionaries/data/validators'\nimport { registerCommand, type CommandHandler, type CommandRuntimeContext } from '@open-mercato/shared/lib/commands'\nimport { extractUndoPayload } from '@open-mercato/shared/lib/commands/undo'\nimport { withAtomicFlush } from '@open-mercato/shared/lib/commands/flush'\nimport { emitCrudSideEffects, emitCrudUndoSideEffects } from '@open-mercato/shared/lib/commands/helpers'\nimport type { CrudEventsConfig } from '@open-mercato/shared/lib/crud/types'\nimport { CrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport type { DataEngine } from '@open-mercato/shared/lib/data/engine'\nimport { findOneWithDecryption, findWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\n\nconst RESOURCE_KIND = 'dictionaries.dictionary'\nconst INDEXER_ENTITY_TYPE = 'dictionaries:entry'\n\ntype DictionaryScope = {\n tenantId: string\n organizationId: string\n}\n\nconst dictionaryCrudEvents: CrudEventsConfig = {\n module: 'dictionaries',\n entity: 'entry',\n persistent: true,\n buildPayload: (ctx) => ({\n id: ctx.identifiers.id,\n organizationId: ctx.identifiers.organizationId,\n tenantId: ctx.identifiers.tenantId,\n ...(ctx.syncOrigin ? { syncOrigin: ctx.syncOrigin } : {}),\n }),\n}\n\nfunction ensureScope(ctx: CommandRuntimeContext, scope: DictionaryScope): void {\n const tenantId = ctx.auth?.tenantId ?? null\n if (tenantId && tenantId !== scope.tenantId) {\n throw new CrudHttpError(403, { error: 'Forbidden' })\n }\n const organizationId = ctx.selectedOrganizationId ?? ctx.auth?.orgId ?? null\n if (organizationId && organizationId !== scope.organizationId) {\n throw new CrudHttpError(403, { error: 'Forbidden' })\n }\n}\n\nasync function requireDictionary(\n em: EntityManager,\n id: string,\n scope: DictionaryScope,\n): Promise<Dictionary> {\n const dictionary = await findOneWithDecryption(\n em,\n Dictionary,\n { id, tenantId: scope.tenantId, organizationId: scope.organizationId, deletedAt: null },\n undefined,\n scope,\n )\n if (!dictionary) {\n throw new CrudHttpError(404, { error: 'Dictionary not found' })\n }\n return dictionary\n}\n\ntype ReorderSnapshot = {\n dictionaryId: string\n scope: DictionaryScope\n positions: Array<{ id: string; position: number }>\n}\n\ntype ReorderUndoPayload = {\n before?: ReorderSnapshot | null\n after?: ReorderSnapshot | null\n}\n\nconst reorderDictionaryEntriesCommand: CommandHandler<\n ReorderDictionaryEntriesCommandInput,\n { dictionaryId: string; updatedIds: string[] }\n> = {\n id: 'dictionaries.entries.reorder',\n async prepare(rawInput, ctx) {\n const parsed = reorderDictionaryEntriesCommandSchema.parse(rawInput)\n const scope: DictionaryScope = { tenantId: parsed.tenantId, organizationId: parsed.organizationId }\n ensureScope(ctx, scope)\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const ids = parsed.entries.map((e) => e.id)\n const existing = await findWithDecryption(\n em,\n DictionaryEntry,\n {\n id: { $in: ids },\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n } as FilterQuery<DictionaryEntry>,\n undefined,\n scope,\n )\n const before: ReorderSnapshot = {\n dictionaryId: parsed.dictionaryId,\n scope,\n positions: existing.map((entry) => ({ id: entry.id, position: entry.position ?? 0 })),\n }\n return { before }\n },\n async execute(rawInput, ctx) {\n const parsed = reorderDictionaryEntriesCommandSchema.parse(rawInput)\n const scope: DictionaryScope = { tenantId: parsed.tenantId, organizationId: parsed.organizationId }\n ensureScope(ctx, scope)\n\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const dictionary = await requireDictionary(em, parsed.dictionaryId, scope)\n const ids = parsed.entries.map((e) => e.id)\n const entries = await findWithDecryption(\n em,\n DictionaryEntry,\n {\n id: { $in: ids },\n dictionary,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n } as FilterQuery<DictionaryEntry>,\n undefined,\n scope,\n )\n const entryMap = new Map<string, DictionaryEntry>()\n for (const entry of entries) entryMap.set(entry.id, entry)\n\n const updatedIds: string[] = []\n await withAtomicFlush(em, [\n () => {\n for (const { id, position } of parsed.entries) {\n const entry = entryMap.get(id)\n if (!entry) continue\n entry.position = position\n entry.updatedAt = new Date()\n updatedIds.push(id)\n }\n },\n ], { transaction: true })\n\n const dataEngine = ctx.container.resolve('dataEngine') as DataEngine\n for (const entry of entries) {\n await emitCrudSideEffects({\n dataEngine,\n action: 'updated',\n entity: entry,\n identifiers: { id: entry.id, tenantId: entry.tenantId, organizationId: entry.organizationId },\n syncOrigin: ctx.syncOrigin,\n events: dictionaryCrudEvents,\n indexer: { entityType: INDEXER_ENTITY_TYPE },\n })\n }\n\n return { dictionaryId: parsed.dictionaryId, updatedIds }\n },\n captureAfter: async (rawInput, _result, ctx) => {\n const parsed = reorderDictionaryEntriesCommandSchema.parse(rawInput)\n const em = ctx.container.resolve('em') as EntityManager\n const scope: DictionaryScope = { tenantId: parsed.tenantId, organizationId: parsed.organizationId }\n const ids = parsed.entries.map((e) => e.id)\n const current = await findWithDecryption(\n em,\n DictionaryEntry,\n {\n id: { $in: ids },\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n } as FilterQuery<DictionaryEntry>,\n undefined,\n scope,\n )\n const after: ReorderSnapshot = {\n dictionaryId: parsed.dictionaryId,\n scope,\n positions: current.map((entry) => ({ id: entry.id, position: entry.position ?? 0 })),\n }\n return after\n },\n buildLog: async ({ snapshots, result }) => {\n const { translate } = await resolveTranslations()\n const before = snapshots.before as ReorderSnapshot | undefined\n const after = snapshots.after as ReorderSnapshot | undefined\n if (!before || !after) return null\n return {\n actionLabel: translate('dictionaries.entries.audit.reorder', 'Reorder dictionary entries'),\n resourceKind: RESOURCE_KIND,\n resourceId: result.dictionaryId,\n tenantId: before.scope.tenantId,\n organizationId: before.scope.organizationId,\n snapshotBefore: before,\n snapshotAfter: after,\n payload: {\n undo: { before, after } satisfies ReorderUndoPayload,\n },\n }\n },\n undo: async ({ logEntry, ctx }) => {\n const undo = extractUndoPayload<ReorderUndoPayload>(logEntry)\n const before = undo?.before ?? (logEntry?.snapshotBefore as ReorderSnapshot | null | undefined) ?? null\n if (!before) return\n ensureScope(ctx, before.scope)\n\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const ids = before.positions.map((p) => p.id)\n const entries = await findWithDecryption(\n em,\n DictionaryEntry,\n {\n id: { $in: ids },\n tenantId: before.scope.tenantId,\n organizationId: before.scope.organizationId,\n } as FilterQuery<DictionaryEntry>,\n undefined,\n before.scope,\n )\n const entryMap = new Map<string, DictionaryEntry>()\n for (const entry of entries) entryMap.set(entry.id, entry)\n\n await withAtomicFlush(em, [\n () => {\n for (const { id, position } of before.positions) {\n const entry = entryMap.get(id)\n if (!entry) continue\n entry.position = position\n entry.updatedAt = new Date()\n }\n },\n ], { transaction: true })\n\n const dataEngine = ctx.container.resolve('dataEngine') as DataEngine\n for (const entry of entries) {\n await emitCrudUndoSideEffects({\n dataEngine,\n action: 'updated',\n entity: entry,\n identifiers: { id: entry.id, tenantId: entry.tenantId, organizationId: entry.organizationId },\n syncOrigin: ctx.syncOrigin,\n events: dictionaryCrudEvents,\n indexer: { entityType: INDEXER_ENTITY_TYPE },\n })\n }\n },\n}\n\ntype DefaultSnapshot = {\n dictionaryId: string\n scope: DictionaryScope\n previousDefaultIds: string[]\n newDefaultId: string\n}\n\ntype DefaultUndoPayload = {\n before?: DefaultSnapshot | null\n after?: DefaultSnapshot | null\n}\n\nconst setDefaultDictionaryEntryCommand: CommandHandler<\n SetDefaultDictionaryEntryCommandInput,\n { dictionaryId: string; entryId: string; clearedIds: string[] }\n> = {\n id: 'dictionaries.entries.set_default',\n async prepare(rawInput, ctx) {\n const parsed = setDefaultDictionaryEntryCommandSchema.parse(rawInput)\n const scope: DictionaryScope = { tenantId: parsed.tenantId, organizationId: parsed.organizationId }\n ensureScope(ctx, scope)\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const dictionary = await requireDictionary(em, parsed.dictionaryId, scope)\n const previousDefaults = await findWithDecryption(\n em,\n DictionaryEntry,\n {\n dictionary,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n isDefault: true,\n } as FilterQuery<DictionaryEntry>,\n undefined,\n scope,\n )\n const before: DefaultSnapshot = {\n dictionaryId: parsed.dictionaryId,\n scope,\n previousDefaultIds: previousDefaults.map((entry) => entry.id),\n newDefaultId: parsed.entryId,\n }\n return { before }\n },\n async execute(rawInput, ctx) {\n const parsed = setDefaultDictionaryEntryCommandSchema.parse(rawInput)\n const scope: DictionaryScope = { tenantId: parsed.tenantId, organizationId: parsed.organizationId }\n ensureScope(ctx, scope)\n\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const dictionary = await requireDictionary(em, parsed.dictionaryId, scope)\n const targetEntry = await findOneWithDecryption(\n em,\n DictionaryEntry,\n {\n id: parsed.entryId,\n dictionary,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n } as FilterQuery<DictionaryEntry>,\n undefined,\n scope,\n )\n if (!targetEntry) {\n throw new CrudHttpError(404, { error: 'Dictionary entry not found' })\n }\n\n const existingDefaults = await findWithDecryption(\n em,\n DictionaryEntry,\n {\n dictionary,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n isDefault: true,\n } as FilterQuery<DictionaryEntry>,\n undefined,\n scope,\n )\n const clearedIds: string[] = []\n\n // The partial unique index `dictionary_entries_one_default_per_dict`\n // (dictionary_id, organization_id, tenant_id) WHERE is_default = true forbids\n // two default entries in the same dictionary. PostgreSQL checks partial unique\n // indexes per-statement (no deferral) and MikroORM does not guarantee that the\n // is_default=false UPDATEs run before the is_default=true UPDATE within a single\n // flush, so clearing and setting in one flush races to a 23505. Clear the prior\n // default(s) in their own flush first, then set the new default in a second\n // flush, so Postgres never observes two default rows at once.\n await withAtomicFlush(em, [\n () => {\n for (const entry of existingDefaults) {\n if (entry.id === targetEntry.id) continue\n entry.isDefault = false\n entry.updatedAt = new Date()\n clearedIds.push(entry.id)\n }\n },\n ], { transaction: true })\n await withAtomicFlush(em, [\n () => {\n targetEntry.isDefault = true\n targetEntry.updatedAt = new Date()\n },\n ], { transaction: true })\n\n const dataEngine = ctx.container.resolve('dataEngine') as DataEngine\n const touched = [targetEntry, ...existingDefaults.filter((entry) => entry.id !== targetEntry.id)]\n for (const entry of touched) {\n await emitCrudSideEffects({\n dataEngine,\n action: 'updated',\n entity: entry,\n identifiers: { id: entry.id, tenantId: entry.tenantId, organizationId: entry.organizationId },\n syncOrigin: ctx.syncOrigin,\n events: dictionaryCrudEvents,\n indexer: { entityType: INDEXER_ENTITY_TYPE },\n })\n }\n\n return { dictionaryId: parsed.dictionaryId, entryId: targetEntry.id, clearedIds }\n },\n captureAfter: async (rawInput, result, _ctx) => {\n const parsed = setDefaultDictionaryEntryCommandSchema.parse(rawInput)\n const scope: DictionaryScope = { tenantId: parsed.tenantId, organizationId: parsed.organizationId }\n const after: DefaultSnapshot = {\n dictionaryId: parsed.dictionaryId,\n scope,\n previousDefaultIds: result.clearedIds,\n newDefaultId: result.entryId,\n }\n return after\n },\n buildLog: async ({ snapshots, result }) => {\n const { translate } = await resolveTranslations()\n const before = snapshots.before as DefaultSnapshot | undefined\n const after = snapshots.after as DefaultSnapshot | undefined\n if (!before || !after) return null\n return {\n actionLabel: translate('dictionaries.entries.audit.set_default', 'Set default dictionary entry'),\n resourceKind: RESOURCE_KIND,\n resourceId: result.dictionaryId,\n tenantId: before.scope.tenantId,\n organizationId: before.scope.organizationId,\n snapshotBefore: before,\n snapshotAfter: after,\n payload: {\n undo: { before, after } satisfies DefaultUndoPayload,\n },\n }\n },\n undo: async ({ logEntry, ctx }) => {\n const undo = extractUndoPayload<DefaultUndoPayload>(logEntry)\n const before = undo?.before ?? (logEntry?.snapshotBefore as DefaultSnapshot | null | undefined) ?? null\n if (!before) return\n ensureScope(ctx, before.scope)\n\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const dictionary = await requireDictionary(em, before.dictionaryId, before.scope)\n\n const newDefault = before.newDefaultId\n ? await findOneWithDecryption(\n em,\n DictionaryEntry,\n {\n id: before.newDefaultId,\n dictionary,\n tenantId: before.scope.tenantId,\n organizationId: before.scope.organizationId,\n } as FilterQuery<DictionaryEntry>,\n undefined,\n before.scope,\n )\n : null\n const previousDefaults = before.previousDefaultIds.length > 0\n ? await findWithDecryption(\n em,\n DictionaryEntry,\n {\n id: { $in: before.previousDefaultIds },\n dictionary,\n tenantId: before.scope.tenantId,\n organizationId: before.scope.organizationId,\n } as FilterQuery<DictionaryEntry>,\n undefined,\n before.scope,\n )\n : []\n\n // Same partial-unique-index ordering constraint as `execute`: clear the\n // current default in its own flush before restoring the previous default(s),\n // so Postgres never sees two is_default=true rows in the dictionary at once.\n await withAtomicFlush(em, [\n () => {\n if (newDefault) {\n newDefault.isDefault = false\n newDefault.updatedAt = new Date()\n }\n },\n ], { transaction: true })\n await withAtomicFlush(em, [\n () => {\n for (const entry of previousDefaults) {\n entry.isDefault = true\n entry.updatedAt = new Date()\n }\n },\n ], { transaction: true })\n\n const dataEngine = ctx.container.resolve('dataEngine') as DataEngine\n const touched = [\n ...(newDefault ? [newDefault] : []),\n ...previousDefaults,\n ]\n for (const entry of touched) {\n await emitCrudUndoSideEffects({\n dataEngine,\n action: 'updated',\n entity: entry,\n identifiers: { id: entry.id, tenantId: entry.tenantId, organizationId: entry.organizationId },\n syncOrigin: ctx.syncOrigin,\n events: dictionaryCrudEvents,\n indexer: { entityType: INDEXER_ENTITY_TYPE },\n })\n }\n },\n}\n\nregisterCommand(reorderDictionaryEntriesCommand)\nregisterCommand(setDefaultDictionaryEntryCommand)\n"],
5
+ "mappings": "AACA,SAAS,YAAY,uBAAuB;AAC5C;AAAA,EACE;AAAA,EACA;AAAA,OAGK;AACP,SAAS,uBAAwE;AACjF,SAAS,0BAA0B;AACnC,SAAS,uB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M,wBAAwB;AAAA,QAC5B;AAAA,QACA,QAAQ;AAAA,QACR,QAAQ;AAAA,QACR,aAAa,EAAE,IAAI,MAAM,IAAI,UAAU,MAAM,UAAU,gBAAgB,MAAM,eAAe;AAAA,QAC5F,YAAY,IAAI;AAAA,QAChB,QAAQ;AAAA,QACR,SAAS,EAAE,YAAY,oBAAoB;AAAA,MAC7C,CAAC;AAAA,IACH;AAAA,EACF;AACF;AAEA,gBAAgB,+BAA+B;AAC/C,gBAAgB,gCAAgC;",
6
6
  "names": []
7
7
  }
@@ -9,17 +9,13 @@ import {
9
9
  } from "@open-mercato/shared/lib/commands";
10
10
  import { extractUndoPayload } from "@open-mercato/shared/lib/commands/undo";
11
11
  import { buildChanges, requireId } from "@open-mercato/shared/lib/commands/helpers";
12
- import { ensureOrganizationScope, ensureTenantScope } from "@open-mercato/shared/lib/commands/scope";
13
12
  import { CrudHttpError } from "@open-mercato/shared/lib/crud/errors";
14
13
  import { resolveTranslations } from "@open-mercato/shared/lib/i18n/server";
15
14
  import { findOneWithDecryption } from "@open-mercato/shared/lib/encryption/find";
16
- function ensureDictionaryEntryScope(ctx, scope) {
17
- ensureTenantScope(ctx, scope.tenantId);
18
- ensureOrganizationScope(ctx, scope.organizationId);
19
- }
20
15
  const ENTRY_CHANGE_KEYS = ["value", "label", "color", "icon", "position", "isDefault"];
21
16
  function toScopeEnsurer(fn) {
22
- return typeof fn === "function" ? fn : ensureDictionaryEntryScope;
17
+ return typeof fn === "function" ? fn : () => {
18
+ };
23
19
  }
24
20
  async function loadSnapshot(em, id) {
25
21
  const entry = await findOneWithDecryption(em, DictionaryEntry, id, { populate: ["dictionary"] });
@@ -369,8 +365,6 @@ function registerDictionaryEntryCommands(config) {
369
365
  registerCommand(deleteCommand);
370
366
  }
371
367
  export {
372
- ensureDictionaryEntryScope,
373
- registerDictionaryEntryCommands,
374
- toScopeEnsurer
368
+ registerDictionaryEntryCommands
375
369
  };
376
370
  //# sourceMappingURL=factory.js.map