@open-mercato/core 0.6.6-develop.6384.1.f06fc0b42c → 0.6.6-develop.6386.1.391a1afb9e

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 (42) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/dist/bootstrap.js +6 -1
  3. package/dist/bootstrap.js.map +2 -2
  4. package/dist/modules/attachments/lib/scope.js +26 -0
  5. package/dist/modules/attachments/lib/scope.js.map +7 -0
  6. package/dist/modules/catalog/commands/variants.js +4 -2
  7. package/dist/modules/catalog/commands/variants.js.map +2 -2
  8. package/dist/modules/configs/api/module-telemetry/route.js +75 -0
  9. package/dist/modules/configs/api/module-telemetry/route.js.map +7 -0
  10. package/dist/modules/configs/api/openapi.js +110 -0
  11. package/dist/modules/configs/api/openapi.js.map +2 -2
  12. package/dist/modules/configs/backend/config/cache/page.meta.js +1 -1
  13. package/dist/modules/configs/backend/config/cache/page.meta.js.map +1 -1
  14. package/dist/modules/configs/backend/config/module-telemetry/page.js +10 -0
  15. package/dist/modules/configs/backend/config/module-telemetry/page.js.map +7 -0
  16. package/dist/modules/configs/backend/config/module-telemetry/page.meta.js +36 -0
  17. package/dist/modules/configs/backend/config/module-telemetry/page.meta.js.map +7 -0
  18. package/dist/modules/configs/components/ModuleTelemetryPanel.js +801 -0
  19. package/dist/modules/configs/components/ModuleTelemetryPanel.js.map +7 -0
  20. package/dist/modules/messages/commands/messages.js +0 -1
  21. package/dist/modules/messages/commands/messages.js.map +2 -2
  22. package/dist/modules/messages/lib/attachments.js +13 -7
  23. package/dist/modules/messages/lib/attachments.js.map +2 -2
  24. package/dist/modules/query_index/di.js +3 -3
  25. package/dist/modules/query_index/di.js.map +2 -2
  26. package/package.json +7 -7
  27. package/src/bootstrap.ts +7 -1
  28. package/src/modules/attachments/lib/scope.ts +42 -0
  29. package/src/modules/catalog/commands/variants.ts +7 -2
  30. package/src/modules/configs/api/module-telemetry/route.ts +77 -0
  31. package/src/modules/configs/api/openapi.ts +117 -0
  32. package/src/modules/configs/backend/config/cache/page.meta.ts +1 -1
  33. package/src/modules/configs/backend/config/module-telemetry/page.meta.ts +34 -0
  34. package/src/modules/configs/backend/config/module-telemetry/page.tsx +12 -0
  35. package/src/modules/configs/components/ModuleTelemetryPanel.tsx +1109 -0
  36. package/src/modules/configs/i18n/de.json +72 -0
  37. package/src/modules/configs/i18n/en.json +72 -0
  38. package/src/modules/configs/i18n/es.json +72 -0
  39. package/src/modules/configs/i18n/pl.json +72 -0
  40. package/src/modules/messages/commands/messages.ts +0 -1
  41. package/src/modules/messages/lib/attachments.ts +15 -7
  42. package/src/modules/query_index/di.ts +3 -3
@@ -1,4 +1,4 @@
1
- [build:core] found 3433 entry points
1
+ [build:core] found 3438 entry points
2
2
  [build:core] built successfully
3
3
  [build:core:generated] found 186 entry points
4
4
  [build:core:generated] built successfully
package/dist/bootstrap.js CHANGED
@@ -119,7 +119,12 @@ async function bootstrap(container) {
119
119
  loadedModules = getModules();
120
120
  } catch {
121
121
  }
122
- const subs = loadedModules.flatMap((m) => m.subscribers || []);
122
+ const subs = loadedModules.flatMap(
123
+ (m) => (m.subscribers || []).map((subscriber) => ({
124
+ ...subscriber,
125
+ moduleId: subscriber.moduleId ?? m.id
126
+ }))
127
+ );
123
128
  if (subs.length) container.resolve("eventBus").registerModuleSubscribers(subs);
124
129
  const syncSubs = subs.filter((s) => s.sync === true);
125
130
  if (syncSubs.length) {
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../src/bootstrap.ts"],
4
- "sourcesContent": ["import type { AwilixContainer } from 'awilix'\nimport { asValue } from 'awilix'\nimport { createEventBus } from '@open-mercato/events/index'\nimport { setGlobalEventBus } from '@open-mercato/shared/modules/events'\nimport { createCacheService } from '@open-mercato/cache'\nimport type { CacheStrategy } from '@open-mercato/cache'\nimport { createKmsService } from '@open-mercato/shared/lib/encryption/kms'\nimport { TenantDataEncryptionService } from '@open-mercato/shared/lib/encryption/tenantDataEncryptionService'\nimport { registerTenantEncryptionSubscriber } from '@open-mercato/shared/lib/encryption/subscriber'\nimport { isTenantDataEncryptionEnabled } from '@open-mercato/shared/lib/encryption/toggles'\nimport { getSearchModuleConfigs } from '@open-mercato/shared/modules/search'\nimport {\n registerSearchModule,\n createSearchDeleteSubscriber,\n searchDeleteMetadata,\n} from '@open-mercato/search'\nimport { RateLimiterService } from '@open-mercato/shared/lib/ratelimit/service'\nimport { readRateLimitConfig } from '@open-mercato/shared/lib/ratelimit/config'\nimport type { EntityManager } from '@mikro-orm/postgresql'\n\n// Use globalThis to survive tsx/webpack module duplication (same pattern as container.ts DI registrars)\nconst RL_GLOBAL_KEY = '__openMercatoRateLimiterService__'\nconst RL_SHUTDOWN_KEY = '__openMercatoRateLimiterShutdown__'\n\nconst CACHE_GLOBAL_KEY = '__openMercatoCacheService__'\nconst CACHE_SHUTDOWN_KEY = '__openMercatoCacheShutdown__'\n\n// Escape hatch: set OM_CACHE_SINGLETON=off to fall back to the legacy\n// per-request cache instance (e.g. to isolate a regression). Default ON.\nfunction isCacheSingletonEnabled(): boolean {\n const raw = process.env.OM_CACHE_SINGLETON\n if (raw === undefined) return true\n const normalized = raw.trim().toLowerCase()\n if (!normalized.length) return true\n return !(normalized === '0' || normalized === 'off' || normalized === 'false' || normalized === 'no')\n}\n\n/**\n * Process-wide cache service singleton, mirroring getCachedRateLimiterService.\n *\n * bootstrap() previously built a fresh cache per request container, so under\n * the default memory strategy every cross-request cache was a no-op (each\n * instance is process-local) and under sqlite each request leaked a native\n * handle. Reusing one instance is safe by construction: tenant scope resolves\n * per-call via AsyncLocalStorage (packages/cache/src/tenantContext.ts), so the\n * service holds no request-bound state.\n *\n * Returns null when disabled via the escape hatch or when creation fails, so\n * the caller falls back to a per-request instance.\n */\nexport function getCachedCacheService(): CacheStrategy | null {\n if (!isCacheSingletonEnabled()) return null\n let service = (globalThis as any)[CACHE_GLOBAL_KEY] as CacheStrategy | null ?? null\n if (!service) {\n try {\n try {\n service = createCacheService()\n } catch (err) {\n console.warn('Cache service initialization failed; falling back to memory strategy:', (err as Error)?.message || err)\n service = createCacheService({ strategy: 'memory' })\n }\n ;(globalThis as any)[CACHE_GLOBAL_KEY] = service\n\n // Register shutdown hook once to close persistent handles (sqlite/redis) on process exit\n if (!(globalThis as any)[CACHE_SHUTDOWN_KEY]) {\n const shutdown = () => { service?.close?.().catch(() => {}) }\n process.once('SIGTERM', shutdown)\n process.once('SIGINT', shutdown)\n ;(globalThis as any)[CACHE_SHUTDOWN_KEY] = true\n }\n } catch (err) {\n console.warn('[cache] Failed to create cache service:', (err as Error)?.message || err)\n }\n }\n return service\n}\n\nexport function getCachedRateLimiterService(): RateLimiterService | null {\n let service = (globalThis as any)[RL_GLOBAL_KEY] as RateLimiterService | null ?? null\n if (!service) {\n try {\n const rateLimitConfig = readRateLimitConfig()\n service = new RateLimiterService(rateLimitConfig)\n // Fire-and-forget async init (only needed for Redis strategy;\n // memory strategy works synchronously, and Redis has an in-memory\n // insurance limiter so the first few requests are still protected)\n service.initialize().catch((err) => {\n console.warn('[ratelimit] Async initialization failed:', (err as Error)?.message || err)\n })\n ;(globalThis as any)[RL_GLOBAL_KEY] = service\n\n // Register shutdown hook once to disconnect Redis on process exit\n if (!(globalThis as any)[RL_SHUTDOWN_KEY]) {\n const shutdown = () => { service?.destroy().catch(() => {}) }\n process.once('SIGTERM', shutdown)\n process.once('SIGINT', shutdown)\n ;(globalThis as any)[RL_SHUTDOWN_KEY] = true\n }\n } catch (err) {\n console.warn('[ratelimit] Failed to create rate limiter service:', (err as Error)?.message || err)\n }\n }\n return service\n}\n\nexport async function bootstrap(container: AwilixContainer) {\n // Register the cache service. Prefer the process-wide singleton so caches\n // survive across request containers; fall back to a per-request instance\n // when the singleton is disabled or fails to build.\n let cache: any = getCachedCacheService()\n if (!cache) {\n try {\n cache = createCacheService()\n } catch (err: any) {\n console.warn('Cache service initialization failed; falling back to memory strategy:', err?.message || err)\n cache = createCacheService({ strategy: 'memory' })\n }\n }\n container.register({ cache: asValue(cache) })\n\n // Create and register the DI-aware event bus\n let eventBus: any\n try {\n // Support both QUEUE_STRATEGY and legacy EVENTS_STRATEGY env vars\n const strategyEnv = process.env.QUEUE_STRATEGY || process.env.EVENTS_STRATEGY\n const queueStrategy = strategyEnv === 'async' || strategyEnv === 'redis' ? 'async' : 'local'\n eventBus = createEventBus({ resolve: container.resolve.bind(container) as any, queueStrategy })\n } catch (err: any) {\n // Fall back to local strategy to avoid breaking the app on misconfiguration\n console.warn('Event bus initialization failed; falling back to local strategy:', err?.message || err)\n try {\n eventBus = createEventBus({ resolve: container.resolve.bind(container) as any, queueStrategy: 'local' })\n } catch {\n // In extreme cases, provide a no-op bus to avoid crashes\n eventBus = {\n emit: async () => {},\n on: () => {},\n registerModuleSubscribers: () => {},\n clearQueue: async () => ({ removed: 0 }),\n }\n }\n }\n container.register({ eventBus: asValue(eventBus) })\n // Wire the global event bus so createModuleEvents().emit works outside DI context\n setGlobalEventBus(eventBus)\n // Auto-register discovered module subscribers\n try {\n let loadedModules: any[] = []\n try {\n const { getModules } = await import('@open-mercato/shared/lib/i18n/server')\n loadedModules = getModules()\n } catch {}\n const subs = loadedModules.flatMap((m) => m.subscribers || [])\n if (subs.length) (container.resolve as any)('eventBus').registerModuleSubscribers(subs)\n\n // Extract sync subscribers and register in the sync-subscriber-store\n const syncSubs = subs.filter((s: any) => s.sync === true)\n if (syncSubs.length) {\n try {\n const { registerSyncSubscribers } = await import('@open-mercato/shared/lib/crud/sync-subscriber-store')\n registerSyncSubscribers(\n syncSubs.map((s: any) => ({\n metadata: { event: s.event, sync: true as const, priority: s.priority, id: s.id },\n handler: s.handler,\n })),\n )\n } catch {\n // sync-subscriber-store may not be available\n }\n }\n } catch (err) {\n console.error(\"Failed to register module subscribers:\", err);\n }\n\n // KMS + tenant encryption\n const kmsService = createKmsService()\n container.register({ kmsService: asValue(kmsService) })\n try {\n const em = container.resolve('em') as EntityManager\n const cacheService = (() => {\n try { return container.resolve('cache') as any } catch { return null }\n })()\n const tenantEncryptionService = new TenantDataEncryptionService(em, { cache: cacheService, kms: kmsService })\n container.register({ tenantEncryptionService: asValue(tenantEncryptionService) })\n if (isTenantDataEncryptionEnabled() && kmsService.isHealthy()) {\n try {\n registerTenantEncryptionSubscriber(em, tenantEncryptionService)\n } catch (err) {\n console.warn('[encryption] Failed to register MikroORM encryption subscriber:', (err as Error)?.message || err)\n }\n } else if (isTenantDataEncryptionEnabled() && !kmsService.isHealthy()) {\n console.warn('[encryption] Vault/KMS unhealthy - tenant data encryption is disabled until recovery')\n }\n } catch (err) {\n console.warn('[encryption] Failed to initialize tenant encryption service:', (err as Error)?.message || err)\n }\n\n // Register rate limiter service (singleton via globalThis \u2014 reused across request containers)\n // getCachedRateLimiterService() never throws; returns null on failure\n const rateLimiterService = getCachedRateLimiterService()\n if (rateLimiterService) {\n container.register({ rateLimiterService: asValue(rateLimiterService) })\n }\n\n // Register search module\n try {\n // Get configs from global registry (registered during app bootstrap)\n const searchModuleConfigs = getSearchModuleConfigs()\n registerSearchModule(container as any, { moduleConfigs: searchModuleConfigs })\n\n // Register searchModuleConfigs in container so status API can access vector-enabled entities\n container.register({\n searchModuleConfigs: asValue(searchModuleConfigs),\n })\n\n // Register search delete event subscriber\n // Note: search.index_record is now handled by auto-discovered fulltext_upsert.ts subscriber\n try {\n const searchIndexer = container.resolve('searchIndexer') as any\n if (searchIndexer && eventBus) {\n eventBus.registerModuleSubscribers([\n {\n event: searchDeleteMetadata.event,\n persistent: searchDeleteMetadata.persistent,\n handler: createSearchDeleteSubscriber(searchIndexer),\n },\n ])\n }\n } catch {\n // searchIndexer may not be available\n }\n } catch (err) {\n console.warn('[search] Failed to register search module:', (err as Error)?.message || err)\n }\n}\n"],
5
- "mappings": "AACA,SAAS,eAAe;AACxB,SAAS,sBAAsB;AAC/B,SAAS,yBAAyB;AAClC,SAAS,0BAA0B;AAEnC,SAAS,wBAAwB;AACjC,SAAS,mCAAmC;A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ilixContainer } from 'awilix'\nimport { asValue } from 'awilix'\nimport type { ModuleSubscriber } from '@open-mercato/shared/modules/registry'\nimport { createEventBus } from '@open-mercato/events/index'\nimport { setGlobalEventBus } from '@open-mercato/shared/modules/events'\nimport { createCacheService } from '@open-mercato/cache'\nimport type { CacheStrategy } from '@open-mercato/cache'\nimport { createKmsService } from '@open-mercato/shared/lib/encryption/kms'\nimport { TenantDataEncryptionService } from '@open-mercato/shared/lib/encryption/tenantDataEncryptionService'\nimport { registerTenantEncryptionSubscriber } from '@open-mercato/shared/lib/encryption/subscriber'\nimport { isTenantDataEncryptionEnabled } from '@open-mercato/shared/lib/encryption/toggles'\nimport { getSearchModuleConfigs } from '@open-mercato/shared/modules/search'\nimport {\n registerSearchModule,\n createSearchDeleteSubscriber,\n searchDeleteMetadata,\n} from '@open-mercato/search'\nimport { RateLimiterService } from '@open-mercato/shared/lib/ratelimit/service'\nimport { readRateLimitConfig } from '@open-mercato/shared/lib/ratelimit/config'\nimport type { EntityManager } from '@mikro-orm/postgresql'\n\n// Use globalThis to survive tsx/webpack module duplication (same pattern as container.ts DI registrars)\nconst RL_GLOBAL_KEY = '__openMercatoRateLimiterService__'\nconst RL_SHUTDOWN_KEY = '__openMercatoRateLimiterShutdown__'\n\nconst CACHE_GLOBAL_KEY = '__openMercatoCacheService__'\nconst CACHE_SHUTDOWN_KEY = '__openMercatoCacheShutdown__'\n\n// Escape hatch: set OM_CACHE_SINGLETON=off to fall back to the legacy\n// per-request cache instance (e.g. to isolate a regression). Default ON.\nfunction isCacheSingletonEnabled(): boolean {\n const raw = process.env.OM_CACHE_SINGLETON\n if (raw === undefined) return true\n const normalized = raw.trim().toLowerCase()\n if (!normalized.length) return true\n return !(normalized === '0' || normalized === 'off' || normalized === 'false' || normalized === 'no')\n}\n\n/**\n * Process-wide cache service singleton, mirroring getCachedRateLimiterService.\n *\n * bootstrap() previously built a fresh cache per request container, so under\n * the default memory strategy every cross-request cache was a no-op (each\n * instance is process-local) and under sqlite each request leaked a native\n * handle. Reusing one instance is safe by construction: tenant scope resolves\n * per-call via AsyncLocalStorage (packages/cache/src/tenantContext.ts), so the\n * service holds no request-bound state.\n *\n * Returns null when disabled via the escape hatch or when creation fails, so\n * the caller falls back to a per-request instance.\n */\nexport function getCachedCacheService(): CacheStrategy | null {\n if (!isCacheSingletonEnabled()) return null\n let service = (globalThis as any)[CACHE_GLOBAL_KEY] as CacheStrategy | null ?? null\n if (!service) {\n try {\n try {\n service = createCacheService()\n } catch (err) {\n console.warn('Cache service initialization failed; falling back to memory strategy:', (err as Error)?.message || err)\n service = createCacheService({ strategy: 'memory' })\n }\n ;(globalThis as any)[CACHE_GLOBAL_KEY] = service\n\n // Register shutdown hook once to close persistent handles (sqlite/redis) on process exit\n if (!(globalThis as any)[CACHE_SHUTDOWN_KEY]) {\n const shutdown = () => { service?.close?.().catch(() => {}) }\n process.once('SIGTERM', shutdown)\n process.once('SIGINT', shutdown)\n ;(globalThis as any)[CACHE_SHUTDOWN_KEY] = true\n }\n } catch (err) {\n console.warn('[cache] Failed to create cache service:', (err as Error)?.message || err)\n }\n }\n return service\n}\n\nexport function getCachedRateLimiterService(): RateLimiterService | null {\n let service = (globalThis as any)[RL_GLOBAL_KEY] as RateLimiterService | null ?? null\n if (!service) {\n try {\n const rateLimitConfig = readRateLimitConfig()\n service = new RateLimiterService(rateLimitConfig)\n // Fire-and-forget async init (only needed for Redis strategy;\n // memory strategy works synchronously, and Redis has an in-memory\n // insurance limiter so the first few requests are still protected)\n service.initialize().catch((err) => {\n console.warn('[ratelimit] Async initialization failed:', (err as Error)?.message || err)\n })\n ;(globalThis as any)[RL_GLOBAL_KEY] = service\n\n // Register shutdown hook once to disconnect Redis on process exit\n if (!(globalThis as any)[RL_SHUTDOWN_KEY]) {\n const shutdown = () => { service?.destroy().catch(() => {}) }\n process.once('SIGTERM', shutdown)\n process.once('SIGINT', shutdown)\n ;(globalThis as any)[RL_SHUTDOWN_KEY] = true\n }\n } catch (err) {\n console.warn('[ratelimit] Failed to create rate limiter service:', (err as Error)?.message || err)\n }\n }\n return service\n}\n\nexport async function bootstrap(container: AwilixContainer) {\n // Register the cache service. Prefer the process-wide singleton so caches\n // survive across request containers; fall back to a per-request instance\n // when the singleton is disabled or fails to build.\n let cache: any = getCachedCacheService()\n if (!cache) {\n try {\n cache = createCacheService()\n } catch (err: any) {\n console.warn('Cache service initialization failed; falling back to memory strategy:', err?.message || err)\n cache = createCacheService({ strategy: 'memory' })\n }\n }\n container.register({ cache: asValue(cache) })\n\n // Create and register the DI-aware event bus\n let eventBus: any\n try {\n // Support both QUEUE_STRATEGY and legacy EVENTS_STRATEGY env vars\n const strategyEnv = process.env.QUEUE_STRATEGY || process.env.EVENTS_STRATEGY\n const queueStrategy = strategyEnv === 'async' || strategyEnv === 'redis' ? 'async' : 'local'\n eventBus = createEventBus({ resolve: container.resolve.bind(container) as any, queueStrategy })\n } catch (err: any) {\n // Fall back to local strategy to avoid breaking the app on misconfiguration\n console.warn('Event bus initialization failed; falling back to local strategy:', err?.message || err)\n try {\n eventBus = createEventBus({ resolve: container.resolve.bind(container) as any, queueStrategy: 'local' })\n } catch {\n // In extreme cases, provide a no-op bus to avoid crashes\n eventBus = {\n emit: async () => {},\n on: () => {},\n registerModuleSubscribers: () => {},\n clearQueue: async () => ({ removed: 0 }),\n }\n }\n }\n container.register({ eventBus: asValue(eventBus) })\n // Wire the global event bus so createModuleEvents().emit works outside DI context\n setGlobalEventBus(eventBus)\n // Auto-register discovered module subscribers\n try {\n let loadedModules: any[] = []\n try {\n const { getModules } = await import('@open-mercato/shared/lib/i18n/server')\n loadedModules = getModules()\n } catch {}\n const subs = loadedModules.flatMap((m) =>\n (m.subscribers || []).map((subscriber: ModuleSubscriber) => ({\n ...subscriber,\n moduleId: subscriber.moduleId ?? m.id,\n })),\n )\n if (subs.length) (container.resolve as any)('eventBus').registerModuleSubscribers(subs)\n\n // Extract sync subscribers and register in the sync-subscriber-store\n const syncSubs = subs.filter((s: any) => s.sync === true)\n if (syncSubs.length) {\n try {\n const { registerSyncSubscribers } = await import('@open-mercato/shared/lib/crud/sync-subscriber-store')\n registerSyncSubscribers(\n syncSubs.map((s: any) => ({\n metadata: { event: s.event, sync: true as const, priority: s.priority, id: s.id },\n handler: s.handler,\n })),\n )\n } catch {\n // sync-subscriber-store may not be available\n }\n }\n } catch (err) {\n console.error(\"Failed to register module subscribers:\", err);\n }\n\n // KMS + tenant encryption\n const kmsService = createKmsService()\n container.register({ kmsService: asValue(kmsService) })\n try {\n const em = container.resolve('em') as EntityManager\n const cacheService = (() => {\n try { return container.resolve('cache') as any } catch { return null }\n })()\n const tenantEncryptionService = new TenantDataEncryptionService(em, { cache: cacheService, kms: kmsService })\n container.register({ tenantEncryptionService: asValue(tenantEncryptionService) })\n if (isTenantDataEncryptionEnabled() && kmsService.isHealthy()) {\n try {\n registerTenantEncryptionSubscriber(em, tenantEncryptionService)\n } catch (err) {\n console.warn('[encryption] Failed to register MikroORM encryption subscriber:', (err as Error)?.message || err)\n }\n } else if (isTenantDataEncryptionEnabled() && !kmsService.isHealthy()) {\n console.warn('[encryption] Vault/KMS unhealthy - tenant data encryption is disabled until recovery')\n }\n } catch (err) {\n console.warn('[encryption] Failed to initialize tenant encryption service:', (err as Error)?.message || err)\n }\n\n // Register rate limiter service (singleton via globalThis \u2014 reused across request containers)\n // getCachedRateLimiterService() never throws; returns null on failure\n const rateLimiterService = getCachedRateLimiterService()\n if (rateLimiterService) {\n container.register({ rateLimiterService: asValue(rateLimiterService) })\n }\n\n // Register search module\n try {\n // Get configs from global registry (registered during app bootstrap)\n const searchModuleConfigs = getSearchModuleConfigs()\n registerSearchModule(container as any, { moduleConfigs: searchModuleConfigs })\n\n // Register searchModuleConfigs in container so status API can access vector-enabled entities\n container.register({\n searchModuleConfigs: asValue(searchModuleConfigs),\n })\n\n // Register search delete event subscriber\n // Note: search.index_record is now handled by auto-discovered fulltext_upsert.ts subscriber\n try {\n const searchIndexer = container.resolve('searchIndexer') as any\n if (searchIndexer && eventBus) {\n eventBus.registerModuleSubscribers([\n {\n event: searchDeleteMetadata.event,\n persistent: searchDeleteMetadata.persistent,\n handler: createSearchDeleteSubscriber(searchIndexer),\n },\n ])\n }\n } catch {\n // searchIndexer may not be available\n }\n } catch (err) {\n console.warn('[search] Failed to register search module:', (err as Error)?.message || err)\n }\n}\n"],
5
+ "mappings": "AACA,SAAS,eAAe;AAExB,SAAS,sBAAsB;AAC/B,SAAS,yBAAyB;AAClC,SAAS,0BAA0B;AAEnC,SAAS,wBAAwB;AACjC,SAAS,mCAAmC;AAC5C,SAAS,0CAA0C;AACnD,SAAS,qCAAqC;AAC9C,SAAS,8BAA8B;AACvC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,0BAA0B;AACnC,SAAS,2BAA2B;AAIpC,MAAM,gBAAgB;AACtB,MAAM,kBAAkB;AAExB,MAAM,mBAAmB;AACzB,MAAM,qBAAqB;AAI3B,SAAS,0BAAmC;AAC1C,QAAM,MAAM,QAAQ,IAAI;AACxB,MAAI,QAAQ,OAAW,QAAO;AAC9B,QAAM,aAAa,IAAI,KAAK,EAAE,YAAY;AAC1C,MAAI,CAAC,WAAW,OAAQ,QAAO;AAC/B,SAAO,EAAE,eAAe,OAAO,eAAe,SAAS,eAAe,WAAW,eAAe;AAClG;AAeO,SAAS,wBAA8C;AAC5D,MAAI,CAAC,wBAAwB,EAAG,QAAO;AACvC,MAAI,UAAW,WAAmB,gBAAgB,KAA6B;AAC/E,MAAI,CAAC,SAAS;AACZ,QAAI;AACF,UAAI;AACF,kBAAU,mBAAmB;AAAA,MAC/B,SAAS,KAAK;AACZ,gBAAQ,KAAK,yEAA0E,KAAe,WAAW,GAAG;AACpH,kBAAU,mBAAmB,EAAE,UAAU,SAAS,CAAC;AAAA,MACrD;AACA;AAAC,MAAC,WAAmB,gBAAgB,IAAI;AAGzC,UAAI,CAAE,WAAmB,kBAAkB,GAAG;AAC5C,cAAM,WAAW,MAAM;AAAE,m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oB,CAAC;AAG7E,cAAU,SAAS;AAAA,MACjB,qBAAqB,QAAQ,mBAAmB;AAAA,IAClD,CAAC;AAID,QAAI;AACF,YAAM,gBAAgB,UAAU,QAAQ,eAAe;AACvD,UAAI,iBAAiB,UAAU;AAC7B,iBAAS,0BAA0B;AAAA,UACjC;AAAA,YACE,OAAO,qBAAqB;AAAA,YAC5B,YAAY,qBAAqB;AAAA,YACjC,SAAS,6BAA6B,aAAa;AAAA,UACrD;AAAA,QACF,CAAC;AAAA,MACH;AAAA,IACF,QAAQ;AAAA,IAER;AAAA,EACF,SAAS,KAAK;AACZ,YAAQ,KAAK,8CAA+C,KAAe,WAAW,GAAG;AAAA,EAC3F;AACF;",
6
6
  "names": []
7
7
  }
@@ -0,0 +1,26 @@
1
+ function normalizeScopeValue(value) {
2
+ if (typeof value !== "string") return value ?? null;
3
+ const trimmed = value.trim();
4
+ return trimmed.length > 0 ? trimmed : null;
5
+ }
6
+ function isValidAttachmentScopePair(candidate) {
7
+ const organizationId = normalizeScopeValue(candidate.organizationId);
8
+ const tenantId = normalizeScopeValue(candidate.tenantId);
9
+ return organizationId === null === (tenantId === null);
10
+ }
11
+ function resolveAttachmentScopePair(...candidates) {
12
+ for (const candidate of candidates) {
13
+ if (!candidate) continue;
14
+ const organizationId = normalizeScopeValue(candidate.organizationId);
15
+ const tenantId = normalizeScopeValue(candidate.tenantId);
16
+ if (organizationId === null === (tenantId === null)) {
17
+ return { organizationId, tenantId };
18
+ }
19
+ }
20
+ return null;
21
+ }
22
+ export {
23
+ isValidAttachmentScopePair,
24
+ resolveAttachmentScopePair
25
+ };
26
+ //# sourceMappingURL=scope.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../../src/modules/attachments/lib/scope.ts"],
4
+ "sourcesContent": ["export type AttachmentScopePair = {\n organizationId: string | null\n tenantId: string | null\n}\n\nexport type AttachmentScopeCandidate = {\n organizationId?: string | null\n tenantId?: string | null\n}\n\nfunction normalizeScopeValue(value: string | null | undefined): string | null {\n if (typeof value !== 'string') return value ?? null\n const trimmed = value.trim()\n return trimmed.length > 0 ? trimmed : null\n}\n\nexport function isValidAttachmentScopePair(candidate: AttachmentScopeCandidate): boolean {\n const organizationId = normalizeScopeValue(candidate.organizationId)\n const tenantId = normalizeScopeValue(candidate.tenantId)\n return (organizationId === null) === (tenantId === null)\n}\n\n/**\n * Returns the first candidate whose tenant/organization columns form a valid\n * \"both set or both null\" scope pair (blank/whitespace treated as null), or\n * `null` when no candidate satisfies the invariant. Copy/clone sites use this\n * to carry a scope pair across as a unit instead of coalescing the two columns\n * independently, which is what allows a partial-null row to be constructed.\n */\nexport function resolveAttachmentScopePair(\n ...candidates: Array<AttachmentScopeCandidate | null | undefined>\n): AttachmentScopePair | null {\n for (const candidate of candidates) {\n if (!candidate) continue\n const organizationId = normalizeScopeValue(candidate.organizationId)\n const tenantId = normalizeScopeValue(candidate.tenantId)\n if ((organizationId === null) === (tenantId === null)) {\n return { organizationId, tenantId }\n }\n }\n return null\n}\n"],
5
+ "mappings": "AAUA,SAAS,oBAAoB,OAAiD;AAC5E,MAAI,OAAO,UAAU,SAAU,QAAO,SAAS;AAC/C,QAAM,UAAU,MAAM,KAAK;AAC3B,SAAO,QAAQ,SAAS,IAAI,UAAU;AACxC;AAEO,SAAS,2BAA2B,WAA8C;AACvF,QAAM,iBAAiB,oBAAoB,UAAU,cAAc;AACnE,QAAM,WAAW,oBAAoB,UAAU,QAAQ;AACvD,SAAQ,mBAAmB,UAAW,aAAa;AACrD;AASO,SAAS,8BACX,YACyB;AAC5B,aAAW,aAAa,YAAY;AAClC,QAAI,CAAC,UAAW;AAChB,UAAM,iBAAiB,oBAAoB,UAAU,cAAc;AACnE,UAAM,WAAW,oBAAoB,UAAU,QAAQ;AACvD,QAAK,mBAAmB,UAAW,aAAa,OAAO;AACrD,aAAO,EAAE,gBAAgB,SAAS;AAAA,IACpC;AAAA,EACF;AACA,SAAO;AACT;",
6
+ "names": []
7
+ }
@@ -16,6 +16,7 @@ import {
16
16
  CatalogPriceKind
17
17
  } from "../data/entities.js";
18
18
  import { Attachment } from "@open-mercato/core/modules/attachments/data/entities";
19
+ import { resolveAttachmentScopePair } from "@open-mercato/core/modules/attachments/lib/scope";
19
20
  import {
20
21
  variantCreateSchema,
21
22
  variantUpdateSchema
@@ -411,11 +412,12 @@ async function aggregateVariantMediaToProduct(em, variant) {
411
412
  for (const source of attachments) {
412
413
  const key = buildKey(source);
413
414
  if (existingKeys.has(key)) continue;
415
+ const scope = resolveAttachmentScopePair(source, variant) ?? { organizationId: null, tenantId: null };
414
416
  const clone = em.create(Attachment, {
415
417
  entityId: E.catalog.catalog_product,
416
418
  recordId: productId,
417
- organizationId: source.organizationId ?? variant.organizationId ?? null,
418
- tenantId: source.tenantId ?? variant.tenantId ?? null,
419
+ organizationId: scope.organizationId,
420
+ tenantId: scope.tenantId,
419
421
  partitionCode: source.partitionCode,
420
422
  fileName: source.fileName,
421
423
  mimeType: source.mimeType,
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/catalog/commands/variants.ts"],
4
- "sourcesContent": ["import { registerCommand } from '@open-mercato/shared/lib/commands'\nimport type { CommandHandler } from '@open-mercato/shared/lib/commands'\nimport { buildChanges, requireId, parseWithCustomFields, setCustomFieldsIfAny, emitCrudSideEffects } from '@open-mercato/shared/lib/commands/helpers'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport { UniqueConstraintViolationException } from '@mikro-orm/core'\nimport { CrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport { loadCustomFieldSnapshot, buildCustomFieldResetMap } from '@open-mercato/shared/lib/commands/customFieldSnapshots'\nimport { withAtomicFlush } from '@open-mercato/shared/lib/commands/flush'\nimport { resolveRedoSnapshot, restoreCreatedRow } from '@open-mercato/shared/lib/commands/redo'\nimport { E } from '#generated/entities.ids.generated'\nimport { findWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport {\n CatalogProductVariant,\n CatalogProductPrice,\n CatalogProduct,\n CatalogOffer,\n CatalogPriceKind,\n} from '../data/entities'\nimport type { DataEngine } from '@open-mercato/shared/lib/data/engine'\nimport { Attachment } from '@open-mercato/core/modules/attachments/data/entities'\nimport {\n variantCreateSchema,\n variantUpdateSchema,\n type VariantCreateInput,\n type VariantUpdateInput,\n} from '../data/validators'\nimport { isValidGtin, normalizeGtinValue } from '../lib/gtin'\nimport type { CatalogGtinType } from '../data/types'\nimport {\n cloneJson,\n commandActorScope,\n ensureOrganizationScope,\n ensureTenantScope,\n emitCatalogQueryIndexEvent,\n extractUndoPayload,\n requireProduct,\n toNumericString,\n getErrorConstraint,\n getErrorMessage,\n} from './shared'\nimport { SalesTaxRate } from '@open-mercato/core/modules/sales/data/entities'\nimport type { CrudEventsConfig } from '@open-mercato/shared/lib/crud/types'\n\nconst variantCrudEvents: CrudEventsConfig = {\n module: 'catalog',\n entity: 'variant',\n persistent: true,\n buildPayload: (ctx) => ({\n id: ctx.identifiers.id,\n organizationId: ctx.identifiers.organizationId,\n tenantId: ctx.identifiers.tenantId,\n }),\n}\n\ntype VariantSnapshot = {\n id: string\n productId: string\n organizationId: string\n tenantId: string\n name: string | null\n sku: string | null\n barcode: string | null\n gtinType: CatalogGtinType | null\n hsCode: string | null\n statusEntryId: string | null\n isDefault: boolean\n isActive: boolean\n weightValue: string | null\n weightUnit: string | null\n taxRateId: string | null\n taxRate: string | null\n dimensions: Record<string, unknown> | null\n metadata: Record<string, unknown> | null\n optionValues: Record<string, string> | null\n customFieldsetCode: string | null\n createdAt: string\n updatedAt: string\n custom: Record<string, unknown> | null\n prices?: VariantPriceSnapshot[] | null\n}\n\ntype VariantUndoPayload = {\n before?: VariantSnapshot | null\n after?: VariantSnapshot | null\n previousDefaultVariantId?: string | null\n}\n\nconst VARIANT_CHANGE_KEYS = [\n 'name',\n 'sku',\n 'barcode',\n 'gtinType',\n 'hsCode',\n 'statusEntryId',\n 'isDefault',\n 'isActive',\n 'weightValue',\n 'weightUnit',\n 'taxRateId',\n 'taxRate',\n 'dimensions',\n 'optionValues',\n 'customFieldsetCode',\n 'metadata',\n] as const satisfies readonly string[]\n\nasync function loadVariantSnapshot(\n em: EntityManager,\n id: string,\n options: { includePrices?: boolean } = {}\n): Promise<VariantSnapshot | null> {\n const record = await em.findOne(CatalogProductVariant, { id, deletedAt: null })\n if (!record) return null\n const prices = options.includePrices\n ? await loadVariantPriceSnapshots(em, record.id, {\n tenantId: record.tenantId,\n organizationId: record.organizationId,\n })\n : null\n const custom = await loadCustomFieldSnapshot(em, {\n entityId: E.catalog.catalog_product_variant,\n recordId: record.id,\n tenantId: record.tenantId,\n organizationId: record.organizationId,\n })\n const productId = typeof record.product === 'string' ? record.product : record.product.id\n return {\n id: record.id,\n productId,\n organizationId: record.organizationId,\n tenantId: record.tenantId,\n name: record.name ?? null,\n sku: record.sku ?? null,\n barcode: record.barcode ?? null,\n gtinType: record.gtinType ?? null,\n hsCode: record.hsCode ?? null,\n statusEntryId: record.statusEntryId ?? null,\n isDefault: record.isDefault,\n isActive: record.isActive,\n weightValue: record.weightValue ?? null,\n weightUnit: record.weightUnit ?? null,\n taxRateId: record.taxRateId ?? null,\n taxRate: record.taxRate ?? null,\n dimensions: record.dimensions ? cloneJson(record.dimensions) : null,\n metadata: record.metadata ? cloneJson(record.metadata) : null,\n optionValues: record.optionValues ? cloneJson(record.optionValues) : null,\n customFieldsetCode: record.customFieldsetCode ?? null,\n createdAt: record.createdAt.toISOString(),\n updatedAt: record.updatedAt.toISOString(),\n custom: Object.keys(custom).length ? custom : null,\n prices: prices && prices.length ? prices : null,\n }\n}\n\nfunction variantSeedFromSnapshot(snapshot: VariantSnapshot): Record<string, unknown> {\n return {\n id: snapshot.id,\n product: snapshot.productId,\n organizationId: snapshot.organizationId,\n tenantId: snapshot.tenantId,\n name: snapshot.name ?? null,\n sku: snapshot.sku ?? null,\n barcode: snapshot.barcode ?? null,\n gtinType: snapshot.gtinType ?? null,\n hsCode: snapshot.hsCode ?? null,\n statusEntryId: snapshot.statusEntryId ?? null,\n isDefault: snapshot.isDefault,\n isActive: snapshot.isActive,\n weightValue: snapshot.weightValue ?? null,\n weightUnit: snapshot.weightUnit ?? null,\n taxRateId: snapshot.taxRateId ?? null,\n taxRate: snapshot.taxRate ?? null,\n dimensions: snapshot.dimensions ? cloneJson(snapshot.dimensions) : null,\n metadata: snapshot.metadata ? cloneJson(snapshot.metadata) : null,\n optionValues: snapshot.optionValues ? cloneJson(snapshot.optionValues) : null,\n customFieldsetCode: snapshot.customFieldsetCode ?? null,\n createdAt: new Date(snapshot.createdAt),\n updatedAt: new Date(snapshot.updatedAt),\n }\n}\n\nfunction applyVariantSnapshot(record: CatalogProductVariant, snapshot: VariantSnapshot): void {\n record.organizationId = snapshot.organizationId\n record.tenantId = snapshot.tenantId\n record.name = snapshot.name ?? null\n record.sku = snapshot.sku ?? null\n record.barcode = snapshot.barcode ?? null\n record.gtinType = snapshot.gtinType ?? null\n record.hsCode = snapshot.hsCode ?? null\n record.statusEntryId = snapshot.statusEntryId ?? null\n record.isDefault = snapshot.isDefault\n record.isActive = snapshot.isActive\n record.weightValue = snapshot.weightValue ?? null\n record.weightUnit = snapshot.weightUnit ?? null\n record.taxRateId = snapshot.taxRateId ?? null\n record.taxRate = snapshot.taxRate ?? null\n record.dimensions = snapshot.dimensions ? cloneJson(snapshot.dimensions) : null\n record.metadata = snapshot.metadata ? cloneJson(snapshot.metadata) : null\n record.optionValues = snapshot.optionValues ? cloneJson(snapshot.optionValues) : null\n record.customFieldsetCode = snapshot.customFieldsetCode ?? null\n record.createdAt = new Date(snapshot.createdAt)\n record.updatedAt = new Date(snapshot.updatedAt)\n}\n\nasync function resolveVariantTaxRate(\n em: EntityManager,\n product: CatalogProduct,\n taxRateIdInput: string | null | undefined,\n taxRateInput: number | string | null | undefined\n): Promise<{ taxRateId: string | null; taxRate: string | null }> {\n const organizationId = product.organizationId\n const tenantId = product.tenantId\n const normalizedRate =\n taxRateInput === null || taxRateInput === undefined\n ? null\n : (() => {\n const numeric = typeof taxRateInput === 'string' ? Number(taxRateInput) : taxRateInput\n return Number.isFinite(numeric) ? toNumericString(numeric) : null\n })()\n if (taxRateIdInput === null) {\n return { taxRateId: product.taxRateId ?? null, taxRate: product.taxRate ?? null }\n }\n if (!taxRateIdInput) {\n return { taxRateId: product.taxRateId ?? null, taxRate: product.taxRate ?? normalizedRate }\n }\n const record = await em.findOne(SalesTaxRate, {\n id: taxRateIdInput,\n organizationId,\n tenantId,\n deletedAt: null,\n })\n if (!record) {\n throw new CrudHttpError(400, { error: 'Tax class not found' })\n }\n return { taxRateId: taxRateIdInput, taxRate: record.rate ?? normalizedRate }\n}\n\ntype VariantPriceSnapshot = {\n id: string\n variantId: string | null\n productId: string | null\n offerId: string | null\n organizationId: string\n tenantId: string\n priceKindId: string\n priceKindCode: string\n currencyCode: string\n kind: string\n minQuantity: number\n maxQuantity: number | null\n unitPriceNet: string | null\n unitPriceGross: string | null\n taxRate: string | null\n taxAmount: string | null\n channelId: string | null\n userId: string | null\n userGroupId: string | null\n customerId: string | null\n customerGroupId: string | null\n metadata: Record<string, unknown> | null\n startsAt: string | null\n endsAt: string | null\n createdAt: string\n updatedAt: string\n custom: Record<string, unknown> | null\n}\n\nasync function loadVariantPriceSnapshots(\n em: EntityManager,\n variantId: string,\n scope: { tenantId: string; organizationId: string }\n): Promise<VariantPriceSnapshot[]> {\n const prices = await findWithDecryption(\n em,\n CatalogProductPrice,\n { variant: variantId, tenantId: scope.tenantId, organizationId: scope.organizationId },\n { populate: ['priceKind', 'product', 'offer'] },\n { tenantId: scope.tenantId, organizationId: scope.organizationId },\n )\n const snapshots: VariantPriceSnapshot[] = []\n for (const price of prices) {\n const variantRef = price.variant\n const variantIdValue =\n typeof variantRef === 'string'\n ? variantRef\n : variantRef\n ? variantRef.id\n : null\n const productRef = price.product\n ? price.product\n : typeof price.variant === 'object' && price.variant\n ? price.variant.product\n : null\n const productId =\n typeof productRef === 'string'\n ? productRef\n : productRef\n ? productRef.id\n : null\n const priceKindRef = price.priceKind\n const priceKindId =\n typeof priceKindRef === 'string'\n ? priceKindRef\n : priceKindRef\n ? priceKindRef.id\n : null\n if (!priceKindId) {\n throw new CrudHttpError(400, { error: 'Price is missing price kind metadata.' })\n }\n const priceKindCode =\n typeof priceKindRef === 'object' && priceKindRef ? priceKindRef.code : price.kind\n const custom = await loadCustomFieldSnapshot(em, {\n entityId: E.catalog.catalog_product_price,\n recordId: price.id,\n tenantId: price.tenantId,\n organizationId: price.organizationId,\n })\n snapshots.push({\n id: price.id,\n variantId: variantIdValue,\n productId,\n offerId: typeof price.offer === 'string' ? price.offer : price.offer ? price.offer.id : null,\n organizationId: price.organizationId,\n tenantId: price.tenantId,\n priceKindId,\n priceKindCode,\n currencyCode: price.currencyCode,\n kind: price.kind,\n minQuantity: price.minQuantity,\n maxQuantity: price.maxQuantity ?? null,\n unitPriceNet: price.unitPriceNet ?? null,\n unitPriceGross: price.unitPriceGross ?? null,\n taxRate: price.taxRate ?? null,\n taxAmount: price.taxAmount ?? null,\n channelId: price.channelId ?? null,\n userId: price.userId ?? null,\n userGroupId: price.userGroupId ?? null,\n customerId: price.customerId ?? null,\n customerGroupId: price.customerGroupId ?? null,\n metadata: price.metadata ? cloneJson(price.metadata) : null,\n startsAt: price.startsAt ? price.startsAt.toISOString() : null,\n endsAt: price.endsAt ? price.endsAt.toISOString() : null,\n createdAt: price.createdAt.toISOString(),\n updatedAt: price.updatedAt.toISOString(),\n custom: Object.keys(custom).length ? custom : null,\n })\n }\n return snapshots\n}\n\nasync function restoreVariantPricesFromSnapshots(\n em: EntityManager,\n variant: CatalogProductVariant,\n snapshots: VariantPriceSnapshot[],\n dataEngine: DataEngine\n): Promise<void> {\n if (!snapshots.length) return\n const productRef =\n typeof variant.product === 'string'\n ? await requireProduct(em, variant.product, {\n tenantId: variant.tenantId,\n organizationId: variant.organizationId,\n })\n : variant.product\n for (const snapshot of snapshots) {\n const product =\n snapshot.productId && snapshot.productId !== productRef.id\n ? em.getReference(CatalogProduct, snapshot.productId)\n : productRef\n const offer = snapshot.offerId ? em.getReference(CatalogOffer, snapshot.offerId) : null\n const priceKind = em.getReference(CatalogPriceKind, snapshot.priceKindId)\n let record = await em.findOne(CatalogProductPrice, { id: snapshot.id })\n if (!record) {\n record = em.create(CatalogProductPrice, {\n id: snapshot.id,\n variant,\n product,\n offer,\n organizationId: snapshot.organizationId,\n tenantId: snapshot.tenantId,\n currencyCode: snapshot.currencyCode,\n priceKind,\n kind: snapshot.priceKindCode || snapshot.kind,\n minQuantity: snapshot.minQuantity,\n maxQuantity: snapshot.maxQuantity ?? null,\n unitPriceNet: snapshot.unitPriceNet ?? null,\n unitPriceGross: snapshot.unitPriceGross ?? null,\n taxRate: snapshot.taxRate ?? null,\n taxAmount: snapshot.taxAmount ?? null,\n channelId: snapshot.channelId ?? null,\n userId: snapshot.userId ?? null,\n userGroupId: snapshot.userGroupId ?? null,\n customerId: snapshot.customerId ?? null,\n customerGroupId: snapshot.customerGroupId ?? null,\n metadata: snapshot.metadata ? cloneJson(snapshot.metadata) : null,\n startsAt: snapshot.startsAt ? new Date(snapshot.startsAt) : null,\n endsAt: snapshot.endsAt ? new Date(snapshot.endsAt) : null,\n createdAt: new Date(snapshot.createdAt),\n updatedAt: new Date(snapshot.updatedAt),\n })\n em.persist(record)\n } else {\n record.variant = variant\n record.product = product\n record.offer = offer\n record.priceKind = priceKind\n record.organizationId = snapshot.organizationId\n record.tenantId = snapshot.tenantId\n record.currencyCode = snapshot.currencyCode\n record.kind = snapshot.priceKindCode || snapshot.kind\n record.minQuantity = snapshot.minQuantity\n record.maxQuantity = snapshot.maxQuantity ?? null\n record.unitPriceNet = snapshot.unitPriceNet ?? null\n record.unitPriceGross = snapshot.unitPriceGross ?? null\n record.taxRate = snapshot.taxRate ?? null\n record.taxAmount = snapshot.taxAmount ?? null\n record.channelId = snapshot.channelId ?? null\n record.userId = snapshot.userId ?? null\n record.userGroupId = snapshot.userGroupId ?? null\n record.customerId = snapshot.customerId ?? null\n record.customerGroupId = snapshot.customerGroupId ?? null\n record.metadata = snapshot.metadata ? cloneJson(snapshot.metadata) : null\n record.startsAt = snapshot.startsAt ? new Date(snapshot.startsAt) : null\n record.endsAt = snapshot.endsAt ? new Date(snapshot.endsAt) : null\n record.createdAt = new Date(snapshot.createdAt)\n record.updatedAt = new Date(snapshot.updatedAt)\n }\n }\n await em.flush()\n for (const snapshot of snapshots) {\n if (!snapshot.custom || !Object.keys(snapshot.custom).length) continue\n await setCustomFieldsIfAny({\n dataEngine,\n entityId: E.catalog.catalog_product_price,\n recordId: snapshot.id,\n organizationId: snapshot.organizationId,\n tenantId: snapshot.tenantId,\n values: snapshot.custom,\n })\n }\n}\n\ntype MetadataSplitResult = {\n metadata: Record<string, unknown> | null\n optionValues: Record<string, string> | null\n hadOptionValues: boolean\n}\n\nfunction splitOptionValuesFromMetadata(\n metadata?: Record<string, unknown> | null\n): MetadataSplitResult {\n if (!metadata || typeof metadata !== 'object' || Array.isArray(metadata)) {\n return {\n metadata: metadata ? cloneJson(metadata) : null,\n optionValues: null,\n hadOptionValues: false,\n }\n }\n const { optionValues, ...rest } = metadata as Record<string, unknown> & {\n optionValues?: unknown\n }\n const normalizedMetadata = Object.keys(rest).length ? cloneJson(rest) : null\n return {\n metadata: normalizedMetadata,\n optionValues: normalizeOptionValues(optionValues),\n hadOptionValues: optionValues !== undefined,\n }\n}\n\nfunction normalizeOptionValues(input: unknown): Record<string, string> | null {\n if (!input || typeof input !== 'object' || Array.isArray(input)) return null\n const normalized: Record<string, string> = {}\n for (const [rawKey, rawValue] of Object.entries(input)) {\n if (typeof rawValue !== 'string') continue\n const key = rawKey.trim()\n const value = rawValue.trim()\n if (!key || !value) continue\n normalized[key] = value\n }\n return Object.keys(normalized).length ? normalized : null\n}\n\nfunction resolveProductId(record: CatalogProductVariant): string {\n return typeof record.product === 'string' ? record.product : record.product.id\n}\n\nasync function enforceSingleDefaultVariant(\n em: EntityManager,\n variant: CatalogProductVariant\n): Promise<string | null> {\n if (!variant.isDefault) return null\n const productId = resolveProductId(variant)\n const existingDefault = await em.findOne(\n CatalogProductVariant,\n { product: productId, isDefault: true, deletedAt: null, id: { $ne: variant.id } },\n { fields: ['id', 'isDefault'] }\n )\n if (existingDefault) {\n existingDefault.isDefault = false\n return existingDefault.id\n }\n return null\n}\n\nasync function aggregateVariantMediaToProduct(\n em: EntityManager,\n variant: CatalogProductVariant\n): Promise<void> {\n const productId = resolveProductId(variant)\n const buildKey = (\n attachment: Pick<Attachment, 'fileName' | 'fileSize' | 'storageDriver' | 'partitionCode' | 'storagePath'>\n ) =>\n [\n attachment.fileName?.trim() ?? '',\n attachment.fileSize ?? '',\n attachment.storageDriver ?? '',\n attachment.partitionCode ?? '',\n ].join('|')\n const attachments = await em.find(\n Attachment,\n {\n entityId: E.catalog.catalog_product_variant,\n recordId: variant.id,\n organizationId: variant.organizationId ?? undefined,\n tenantId: variant.tenantId ?? undefined,\n },\n {\n fields: [\n 'id',\n 'partitionCode',\n 'fileName',\n 'mimeType',\n 'fileSize',\n 'storageDriver',\n 'storagePath',\n 'storageMetadata',\n 'url',\n 'organizationId',\n 'tenantId',\n 'fileSize',\n 'storageDriver',\n 'partitionCode',\n ],\n }\n )\n if (!attachments.length) return\n const existing = await em.find(\n Attachment,\n {\n entityId: E.catalog.catalog_product,\n recordId: productId,\n organizationId: variant.organizationId ?? undefined,\n tenantId: variant.tenantId ?? undefined,\n },\n {\n fields: ['storagePath', 'fileName', 'fileSize', 'storageDriver', 'partitionCode'],\n }\n )\n const existingKeys = new Set(existing.map((item) => buildKey(item)))\n let created = 0\n for (const source of attachments) {\n const key = buildKey(source)\n if (existingKeys.has(key)) continue\n const clone = em.create(Attachment, {\n entityId: E.catalog.catalog_product,\n recordId: productId,\n organizationId: source.organizationId ?? variant.organizationId ?? null,\n tenantId: source.tenantId ?? variant.tenantId ?? null,\n partitionCode: source.partitionCode,\n fileName: source.fileName,\n mimeType: source.mimeType,\n fileSize: source.fileSize,\n storageDriver: source.storageDriver,\n storagePath: source.storagePath,\n storageMetadata: source.storageMetadata ? cloneJson(source.storageMetadata) : null,\n url: source.url,\n })\n em.persist(clone)\n existingKeys.add(key)\n created += 1\n }\n if (created > 0) {\n await em.flush()\n }\n}\n\nconst createVariantCommand: CommandHandler<VariantCreateInput, { variantId: string; previousDefaultVariantId?: string | null }> = {\n id: 'catalog.variants.create',\n async execute(rawInput, ctx) {\n const { parsed, custom } = parseWithCustomFields(variantCreateSchema, rawInput)\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const product = await requireProduct(em, parsed.productId, commandActorScope(ctx))\n ensureTenantScope(ctx, product.tenantId)\n ensureOrganizationScope(ctx, product.organizationId)\n const { taxRateId, taxRate } = await resolveVariantTaxRate(\n em,\n product,\n parsed.taxRateId ?? null,\n parsed.taxRate\n )\n\n const metadataSplit = splitOptionValuesFromMetadata(parsed.metadata)\n const resolvedOptionValues =\n parsed.optionValues ?? (metadataSplit.hadOptionValues ? metadataSplit.optionValues : null)\n\n const gtinType = parsed.gtinType ?? null\n const barcode =\n gtinType && parsed.barcode\n ? normalizeGtinValue(gtinType, parsed.barcode)\n : (parsed.barcode ?? null)\n\n const now = new Date()\n const record = em.create(CatalogProductVariant, {\n organizationId: product.organizationId,\n tenantId: product.tenantId,\n product,\n name: parsed.name ?? null,\n sku: parsed.sku ?? null,\n barcode,\n gtinType,\n hsCode: parsed.hsCode ?? null,\n statusEntryId: parsed.statusEntryId ?? null,\n isDefault: parsed.isDefault ?? false,\n isActive: parsed.isActive ?? true,\n weightValue: toNumericString(parsed.weightValue),\n weightUnit: parsed.weightUnit ?? null,\n taxRateId,\n taxRate,\n dimensions: parsed.dimensions ? cloneJson(parsed.dimensions) : null,\n metadata: metadataSplit.metadata,\n optionValues: resolvedOptionValues ? cloneJson(resolvedOptionValues) : null,\n customFieldsetCode: parsed.customFieldsetCode ?? null,\n createdAt: now,\n updatedAt: now,\n })\n em.persist(record)\n let previousDefaultVariantId: string | null = null\n try {\n await withAtomicFlush(\n em,\n [\n () => em.flush(),\n async () => {\n if (record.isDefault) {\n previousDefaultVariantId = await enforceSingleDefaultVariant(em, record)\n await em.flush()\n }\n },\n () => aggregateVariantMediaToProduct(em, record),\n ],\n { transaction: true }\n )\n } catch (error) {\n await rethrowVariantUniqueConstraint(error)\n }\n await setCustomFieldsIfAny({\n dataEngine: ctx.container.resolve('dataEngine'),\n entityId: E.catalog.catalog_product_variant,\n recordId: record.id,\n organizationId: record.organizationId,\n tenantId: record.tenantId,\n values: custom,\n })\n await emitCatalogQueryIndexEvent(ctx, {\n entityType: E.catalog.catalog_product_variant,\n recordId: record.id,\n organizationId: record.organizationId,\n tenantId: record.tenantId,\n action: 'created',\n })\n await emitCrudSideEffects({\n dataEngine: ctx.container.resolve('dataEngine') as DataEngine,\n action: 'created',\n entity: record,\n identifiers: {\n id: record.id,\n organizationId: record.organizationId,\n tenantId: record.tenantId,\n },\n events: variantCrudEvents,\n })\n return { variantId: record.id, previousDefaultVariantId }\n },\n captureAfter: async (_input, result, ctx) => {\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n return loadVariantSnapshot(em, result.variantId)\n },\n buildLog: async ({ result, snapshots }) => {\n const after = snapshots.after as VariantSnapshot | undefined\n if (!after) return null\n const { translate } = await resolveTranslations()\n return {\n actionLabel: translate('catalog.audit.variants.create', 'Create product variant'),\n resourceKind: 'catalog.variant',\n resourceId: result.variantId,\n parentResourceKind: 'catalog.product',\n parentResourceId: after.productId ?? null,\n tenantId: after.tenantId,\n organizationId: after.organizationId,\n snapshotAfter: after,\n payload: {\n undo: {\n after,\n previousDefaultVariantId: (result as { previousDefaultVariantId?: string | null })?.previousDefaultVariantId ?? null,\n } satisfies VariantUndoPayload,\n },\n }\n },\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<VariantUndoPayload>(logEntry)\n const after = payload?.after\n if (!after) return\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const record = await em.findOne(CatalogProductVariant, { id: after.id })\n if (!record) return\n ensureTenantScope(ctx, record.tenantId)\n ensureOrganizationScope(ctx, record.organizationId)\n em.remove(record)\n await em.flush()\n if (payload?.previousDefaultVariantId) {\n const previousDefault = await em.findOne(CatalogProductVariant, { id: payload.previousDefaultVariantId })\n if (previousDefault) {\n ensureTenantScope(ctx, previousDefault.tenantId)\n ensureOrganizationScope(ctx, previousDefault.organizationId)\n previousDefault.isDefault = true\n await em.flush()\n }\n }\n const resetValues = buildCustomFieldResetMap(undefined, after.custom ?? undefined)\n if (Object.keys(resetValues).length) {\n await setCustomFieldsIfAny({\n dataEngine: ctx.container.resolve('dataEngine'),\n entityId: E.catalog.catalog_product_variant,\n recordId: after.id,\n organizationId: after.organizationId,\n tenantId: after.tenantId,\n values: resetValues,\n })\n }\n },\n redo: async ({ ctx, logEntry }) => {\n const after = resolveRedoSnapshot<VariantSnapshot>(logEntry)\n if (!after) throw new CrudHttpError(400, { error: '[internal] redo snapshot unavailable for variant create' })\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const record = await restoreCreatedRow(\n em,\n CatalogProductVariant,\n after.id,\n () => variantSeedFromSnapshot(after),\n )\n applyVariantSnapshot(record, after)\n let previousDefaultVariantId: string | null = null\n try {\n await withAtomicFlush(\n em,\n [\n () => em.flush(),\n async () => {\n if (record.isDefault) {\n previousDefaultVariantId = await enforceSingleDefaultVariant(em, record)\n await em.flush()\n }\n },\n () => aggregateVariantMediaToProduct(em, record),\n ],\n { transaction: true }\n )\n } catch (error) {\n await rethrowVariantUniqueConstraint(error)\n }\n if (after.custom && Object.keys(after.custom).length) {\n await setCustomFieldsIfAny({\n dataEngine: ctx.container.resolve('dataEngine'),\n entityId: E.catalog.catalog_product_variant,\n recordId: record.id,\n organizationId: record.organizationId,\n tenantId: record.tenantId,\n values: after.custom,\n })\n }\n await emitCatalogQueryIndexEvent(ctx, {\n entityType: E.catalog.catalog_product_variant,\n recordId: record.id,\n organizationId: record.organizationId,\n tenantId: record.tenantId,\n action: 'created',\n })\n await emitCrudSideEffects({\n dataEngine: ctx.container.resolve('dataEngine') as DataEngine,\n action: 'created',\n entity: record,\n identifiers: {\n id: record.id,\n organizationId: record.organizationId,\n tenantId: record.tenantId,\n },\n events: variantCrudEvents,\n })\n return { variantId: record.id, previousDefaultVariantId }\n },\n}\n\nconst updateVariantCommand: CommandHandler<VariantUpdateInput, { variantId: string; previousDefaultVariantId?: string | null }> = {\n id: 'catalog.variants.update',\n async prepare(input, ctx) {\n const id = requireId(input, 'Variant id is required')\n const em = (ctx.container.resolve('em') as EntityManager)\n const snapshot = await loadVariantSnapshot(em, id)\n if (snapshot) {\n ensureTenantScope(ctx, snapshot.tenantId)\n ensureOrganizationScope(ctx, snapshot.organizationId)\n }\n return snapshot ? { before: snapshot } : {}\n },\n async execute(rawInput, ctx) {\n const { parsed, custom } = parseWithCustomFields(variantUpdateSchema, rawInput)\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const record = await em.findOne(CatalogProductVariant, { id: parsed.id, deletedAt: null })\n if (!record) throw new CrudHttpError(404, { error: 'Catalog variant not found' })\n ensureTenantScope(ctx, record.tenantId)\n ensureOrganizationScope(ctx, record.organizationId)\n const product = await requireProduct(em, record.product.id, {\n tenantId: record.tenantId,\n organizationId: record.organizationId,\n })\n\n if (!product) throw new CrudHttpError(400, { error: 'Variant product missing' })\n\n const taxRateProvided = parsed.taxRateId !== undefined || parsed.taxRate !== undefined\n const resolvedTaxRate = taxRateProvided\n ? await resolveVariantTaxRate(em, product, parsed.taxRateId ?? null, parsed.taxRate)\n : null\n\n // Re-validate GTIN against the merged record state: a partial update may\n // carry only one of (gtinType, barcode) while the other half is stored.\n let normalizedGtinBarcode: string | null = null\n if (parsed.gtinType !== undefined || parsed.barcode !== undefined) {\n const effectiveGtinType =\n parsed.gtinType !== undefined ? (parsed.gtinType ?? null) : (record.gtinType ?? null)\n if (effectiveGtinType) {\n const effectiveBarcode =\n parsed.barcode !== undefined ? (parsed.barcode ?? null) : (record.barcode ?? null)\n if (!effectiveBarcode || !effectiveBarcode.trim().length) {\n await throwGtinBarcodeRequiredError()\n } else {\n const normalized = normalizeGtinValue(effectiveGtinType, effectiveBarcode)\n if (!isValidGtin(effectiveGtinType, normalized)) {\n await throwInvalidGtinError()\n }\n normalizedGtinBarcode = normalized\n }\n }\n }\n\n let previousDefaultVariantId: string | null = null\n try {\n await withAtomicFlush(\n em,\n [\n () => {\n if (parsed.name !== undefined) record.name = parsed.name ?? null\n if (parsed.sku !== undefined) record.sku = parsed.sku ?? null\n if (parsed.barcode !== undefined) record.barcode = parsed.barcode ?? null\n if (parsed.gtinType !== undefined) record.gtinType = parsed.gtinType ?? null\n if (parsed.hsCode !== undefined) record.hsCode = parsed.hsCode ?? null\n if (normalizedGtinBarcode !== null) record.barcode = normalizedGtinBarcode\n if (parsed.statusEntryId !== undefined) record.statusEntryId = parsed.statusEntryId ?? null\n if (parsed.isDefault !== undefined) record.isDefault = parsed.isDefault\n if (parsed.isActive !== undefined) record.isActive = parsed.isActive\n if (Object.prototype.hasOwnProperty.call(parsed, 'weightValue')) {\n record.weightValue = toNumericString(parsed.weightValue)\n }\n if (parsed.weightUnit !== undefined) record.weightUnit = parsed.weightUnit ?? null\n if (parsed.dimensions !== undefined) {\n record.dimensions = parsed.dimensions ? cloneJson(parsed.dimensions) : null\n }\n let metadataSplit: MetadataSplitResult | null = null\n if (parsed.metadata !== undefined) {\n metadataSplit = splitOptionValuesFromMetadata(parsed.metadata)\n record.metadata = metadataSplit.metadata\n }\n if (parsed.optionValues !== undefined) {\n record.optionValues = parsed.optionValues ? cloneJson(parsed.optionValues) : null\n } else if (metadataSplit?.hadOptionValues) {\n record.optionValues = metadataSplit.optionValues ? cloneJson(metadataSplit.optionValues) : null\n }\n if (taxRateProvided) {\n record.taxRateId = resolvedTaxRate?.taxRateId ?? null\n record.taxRate = resolvedTaxRate?.taxRate ?? null\n }\n if (parsed.customFieldsetCode !== undefined) {\n record.customFieldsetCode = parsed.customFieldsetCode ?? null\n }\n },\n async () => {\n if (parsed.isDefault === true) {\n previousDefaultVariantId = await enforceSingleDefaultVariant(em, record)\n }\n },\n () => aggregateVariantMediaToProduct(em, record),\n ],\n { transaction: true }\n )\n } catch (error) {\n await rethrowVariantUniqueConstraint(error)\n }\n if (custom && Object.keys(custom).length) {\n await setCustomFieldsIfAny({\n dataEngine: ctx.container.resolve('dataEngine'),\n entityId: E.catalog.catalog_product_variant,\n recordId: record.id,\n organizationId: record.organizationId,\n tenantId: record.tenantId,\n values: custom,\n })\n }\n await emitCatalogQueryIndexEvent(ctx, {\n entityType: E.catalog.catalog_product_variant,\n recordId: record.id,\n organizationId: record.organizationId,\n tenantId: record.tenantId,\n action: 'updated',\n })\n await emitCrudSideEffects({\n dataEngine: ctx.container.resolve('dataEngine') as DataEngine,\n action: 'updated',\n entity: record,\n identifiers: {\n id: record.id,\n organizationId: record.organizationId,\n tenantId: record.tenantId,\n },\n events: variantCrudEvents,\n })\n return { variantId: record.id, previousDefaultVariantId }\n },\n captureAfter: async (_input, result, ctx) => {\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n return loadVariantSnapshot(em, result.variantId)\n },\n buildLog: async ({ result, snapshots }) => {\n const before = snapshots.before as VariantSnapshot | undefined\n const after = snapshots.after as VariantSnapshot | undefined\n if (!before || !after) return null\n const { translate } = await resolveTranslations()\n return {\n actionLabel: translate('catalog.audit.variants.update', 'Update product variant'),\n resourceKind: 'catalog.variant',\n resourceId: before.id,\n parentResourceKind: 'catalog.product',\n parentResourceId: before.productId ?? null,\n tenantId: before.tenantId,\n organizationId: before.organizationId,\n snapshotBefore: before,\n snapshotAfter: after,\n changes: buildChanges(\n before as Record<string, unknown>,\n after as Record<string, unknown>,\n VARIANT_CHANGE_KEYS\n ),\n payload: {\n undo: {\n before,\n after,\n previousDefaultVariantId:\n (result as { previousDefaultVariantId?: string | null })?.previousDefaultVariantId ?? null,\n } satisfies VariantUndoPayload,\n },\n }\n },\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<VariantUndoPayload>(logEntry)\n const before = payload?.before\n if (!before) return\n const after = payload?.after\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n let record = await em.findOne(CatalogProductVariant, { id: before.id })\n if (!record) {\n const product = await requireProduct(em, before.productId, {\n tenantId: before.tenantId,\n organizationId: before.organizationId,\n })\n record = em.create(CatalogProductVariant, {\n id: before.id,\n product,\n organizationId: before.organizationId,\n tenantId: before.tenantId,\n name: before.name ?? null,\n sku: before.sku ?? null,\n barcode: before.barcode ?? null,\n statusEntryId: before.statusEntryId ?? null,\n isDefault: before.isDefault,\n isActive: before.isActive,\n weightValue: before.weightValue ?? null,\n weightUnit: before.weightUnit ?? null,\n dimensions: before.dimensions ? cloneJson(before.dimensions) : null,\n metadata: before.metadata ? cloneJson(before.metadata) : null,\n optionValues: before.optionValues ? cloneJson(before.optionValues) : null,\n customFieldsetCode: before.customFieldsetCode ?? null,\n createdAt: new Date(before.createdAt),\n updatedAt: new Date(before.updatedAt),\n })\n em.persist(record)\n }\n ensureTenantScope(ctx, before.tenantId)\n ensureOrganizationScope(ctx, before.organizationId)\n applyVariantSnapshot(record, before)\n await em.flush()\n const previousDefaultId = payload?.previousDefaultVariantId\n if (previousDefaultId) {\n const previousDefault = await em.findOne(CatalogProductVariant, { id: previousDefaultId })\n if (previousDefault) {\n ensureTenantScope(ctx, previousDefault.tenantId)\n ensureOrganizationScope(ctx, previousDefault.organizationId)\n previousDefault.isDefault = true\n await em.flush()\n }\n }\n const resetValues = buildCustomFieldResetMap(\n before.custom ?? undefined,\n after?.custom ?? undefined\n )\n if (Object.keys(resetValues).length) {\n await setCustomFieldsIfAny({\n dataEngine: ctx.container.resolve('dataEngine'),\n entityId: E.catalog.catalog_product_variant,\n recordId: before.id,\n organizationId: before.organizationId,\n tenantId: before.tenantId,\n values: resetValues,\n })\n }\n },\n}\n\nconst deleteVariantCommand: CommandHandler<\n { body?: Record<string, unknown>; query?: Record<string, unknown> },\n { variantId: string }\n> = {\n id: 'catalog.variants.delete',\n async prepare(input, ctx) {\n const id = requireId(input, 'Variant id is required')\n const em = (ctx.container.resolve('em') as EntityManager)\n const snapshot = await loadVariantSnapshot(em, id, { includePrices: true })\n if (snapshot) {\n ensureTenantScope(ctx, snapshot.tenantId)\n ensureOrganizationScope(ctx, snapshot.organizationId)\n }\n return snapshot ? { before: snapshot } : {}\n },\n async execute(input, ctx) {\n const id = requireId(input, 'Variant id is required')\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const record = await em.findOne(CatalogProductVariant, { id })\n if (!record) throw new CrudHttpError(404, { error: 'Catalog variant not found' })\n ensureTenantScope(ctx, record.tenantId)\n ensureOrganizationScope(ctx, record.organizationId)\n\n const baseEm = (ctx.container.resolve('em') as EntityManager)\n const snapshot = await loadVariantSnapshot(baseEm, id, { includePrices: true })\n const dataEngine = ctx.container.resolve('dataEngine') as DataEngine\n const priceSnapshots =\n snapshot?.prices && snapshot.prices.length\n ? snapshot.prices\n : await loadVariantPriceSnapshots(baseEm, id, {\n tenantId: record.tenantId,\n organizationId: record.organizationId,\n })\n\n if (priceSnapshots.length) {\n await em.nativeDelete(CatalogProductPrice, { id: { $in: priceSnapshots.map((price) => price.id) } })\n } else {\n await em.nativeDelete(CatalogProductPrice, { variant: record })\n }\n em.remove(record)\n await em.flush()\n for (const priceSnapshot of priceSnapshots) {\n const resetValues = buildCustomFieldResetMap(priceSnapshot.custom ?? undefined, undefined)\n if (!Object.keys(resetValues).length) continue\n await setCustomFieldsIfAny({\n dataEngine,\n entityId: E.catalog.catalog_product_price,\n recordId: priceSnapshot.id,\n organizationId: priceSnapshot.organizationId,\n tenantId: priceSnapshot.tenantId,\n values: resetValues,\n })\n }\n if (snapshot?.custom && Object.keys(snapshot.custom).length) {\n const resetValues = buildCustomFieldResetMap(snapshot.custom, undefined)\n if (Object.keys(resetValues).length) {\n await setCustomFieldsIfAny({\n dataEngine,\n entityId: E.catalog.catalog_product_variant,\n recordId: id,\n organizationId: snapshot.organizationId,\n tenantId: snapshot.tenantId,\n values: resetValues,\n })\n }\n }\n await emitCatalogQueryIndexEvent(ctx, {\n entityType: E.catalog.catalog_product_variant,\n recordId: id,\n organizationId: snapshot?.organizationId ?? record.organizationId,\n tenantId: snapshot?.tenantId ?? record.tenantId,\n action: 'deleted',\n })\n await emitCrudSideEffects({\n dataEngine: ctx.container.resolve('dataEngine') as DataEngine,\n action: 'deleted',\n entity: record,\n identifiers: {\n id,\n organizationId: snapshot?.organizationId ?? record.organizationId,\n tenantId: snapshot?.tenantId ?? record.tenantId,\n },\n events: variantCrudEvents,\n })\n return { variantId: id }\n },\n buildLog: async ({ snapshots }) => {\n const before = snapshots.before as VariantSnapshot | undefined\n if (!before) return null\n const { translate } = await resolveTranslations()\n return {\n actionLabel: translate('catalog.audit.variants.delete', 'Delete product variant'),\n resourceKind: 'catalog.variant',\n resourceId: before.id,\n parentResourceKind: 'catalog.product',\n parentResourceId: before.productId ?? null,\n tenantId: before.tenantId,\n organizationId: before.organizationId,\n snapshotBefore: before,\n payload: {\n undo: {\n before,\n } satisfies VariantUndoPayload,\n },\n }\n },\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<VariantUndoPayload>(logEntry)\n const before = payload?.before\n if (!before) return\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n let record = await em.findOne(CatalogProductVariant, { id: before.id })\n if (!record) {\n const product = await requireProduct(em, before.productId, {\n tenantId: before.tenantId,\n organizationId: before.organizationId,\n })\n record = em.create(CatalogProductVariant, {\n id: before.id,\n product,\n organizationId: before.organizationId,\n tenantId: before.tenantId,\n name: before.name ?? null,\n sku: before.sku ?? null,\n barcode: before.barcode ?? null,\n statusEntryId: before.statusEntryId ?? null,\n isDefault: before.isDefault,\n isActive: before.isActive,\n weightValue: before.weightValue ?? null,\n weightUnit: before.weightUnit ?? null,\n dimensions: before.dimensions ? cloneJson(before.dimensions) : null,\n metadata: before.metadata ? cloneJson(before.metadata) : null,\n customFieldsetCode: before.customFieldsetCode ?? null,\n createdAt: new Date(before.createdAt),\n updatedAt: new Date(before.updatedAt),\n })\n em.persist(record)\n }\n ensureTenantScope(ctx, before.tenantId)\n ensureOrganizationScope(ctx, before.organizationId)\n applyVariantSnapshot(record, before)\n if (before.prices?.length) {\n const dataEngine = ctx.container.resolve('dataEngine') as DataEngine\n await restoreVariantPricesFromSnapshots(em, record, before.prices, dataEngine)\n }\n await em.flush()\n if (before.custom && Object.keys(before.custom).length) {\n await setCustomFieldsIfAny({\n dataEngine: ctx.container.resolve('dataEngine'),\n entityId: E.catalog.catalog_product_variant,\n recordId: before.id,\n organizationId: before.organizationId,\n tenantId: before.tenantId,\n values: before.custom,\n })\n }\n },\n}\n\nasync function throwDuplicateVariantSkuError(): Promise<never> {\n const { translate } = await resolveTranslations()\n const message = translate('catalog.variants.errors.skuExists', 'SKU already in use.')\n throw new CrudHttpError(400, {\n error: message,\n fieldErrors: { sku: message },\n details: [{ path: ['sku'], message, code: 'duplicate', origin: 'validation' }],\n })\n}\n\nasync function throwDuplicateVariantGtinError(): Promise<never> {\n const { translate } = await resolveTranslations()\n const message = translate(\n 'catalog.variants.errors.gtinExists',\n 'Another variant already uses this identifier.',\n )\n throw new CrudHttpError(400, {\n error: message,\n fieldErrors: { barcode: message },\n details: [{ path: ['barcode'], message, code: 'duplicate', origin: 'validation' }],\n })\n}\n\nasync function throwGtinBarcodeRequiredError(): Promise<never> {\n const { translate } = await resolveTranslations()\n const message = translate(\n 'catalog.variants.validation.gtinBarcodeRequired',\n 'A barcode value is required when an identifier type is set.',\n )\n throw new CrudHttpError(400, {\n error: message,\n fieldErrors: { barcode: message },\n details: [{ path: ['barcode'], message, code: 'invalid', origin: 'validation' }],\n })\n}\n\nasync function throwInvalidGtinError(): Promise<never> {\n const { translate } = await resolveTranslations()\n const message = translate(\n 'catalog.variants.validation.gtinChecksum',\n 'The barcode does not match the selected identifier type.',\n )\n throw new CrudHttpError(400, {\n error: message,\n fieldErrors: { barcode: message },\n details: [{ path: ['barcode'], message, code: 'invalid', origin: 'validation' }],\n })\n}\n\nasync function rethrowVariantUniqueConstraint(error: unknown): Promise<never> {\n if (error instanceof UniqueConstraintViolationException) {\n const constraint = getErrorConstraint(error)\n const message = getErrorMessage(error).toLowerCase()\n if (\n constraint === 'catalog_product_variants_sku_unique' ||\n message.includes('catalog_product_variants_sku_unique')\n ) {\n await throwDuplicateVariantSkuError()\n }\n if (\n constraint === 'catalog_product_variants_gtin_scope_unique' ||\n message.includes('catalog_product_variants_gtin_scope_unique')\n ) {\n await throwDuplicateVariantGtinError()\n }\n }\n throw error\n}\n\nregisterCommand(createVariantCommand)\nregisterCommand(updateVariantCommand)\nregisterCommand(deleteVariantCommand)\n"],
5
- "mappings": "AAAA,SAAS,uBAAuB;AAEhC,SAAS,cAAc,WAAW,uBAAuB,sBAAsB,2BAA2B;AAE1G,SAAS,0CAA0C;AACnD,SAAS,qBAAqB;AAC9B,SAAS,2BAA2B;AACpC,SAAS,yBAAyB,gCAAgC;AAClE,SAAS,uBAAuB;AAChC,SAAS,qBAAqB,yBAAyB;AACvD,SAAS,SAAS;AAClB,SAAS,0BAA0B;AACnC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEP,SAAS,kBAAkB;AAC3B;AAAA,EACE;AAAA,EACA;AAAA,OAGK;AACP,SAAS,aAAa,0BAA0B;AAEhD;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,oBAAoB;AAG7B,MAAM,oBAAsC;AAAA,EAC1C,QAAQ;AAAA,EACR,QAAQ;AAAA,EACR,YAAY;AAAA,EACZ,cAAc,CAAC,SAAS;AAAA,IACtB,IAAI,IAAI,YAAY;AAAA,IACpB,gBAAgB,IAAI,YAAY;AAAA,IAChC,UAAU,IAAI,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B,oBAAoB;",
4
+ "sourcesContent": ["import { registerCommand } from '@open-mercato/shared/lib/commands'\nimport type { CommandHandler } from '@open-mercato/shared/lib/commands'\nimport { buildChanges, requireId, parseWithCustomFields, setCustomFieldsIfAny, emitCrudSideEffects } from '@open-mercato/shared/lib/commands/helpers'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport { UniqueConstraintViolationException } from '@mikro-orm/core'\nimport { CrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport { loadCustomFieldSnapshot, buildCustomFieldResetMap } from '@open-mercato/shared/lib/commands/customFieldSnapshots'\nimport { withAtomicFlush } from '@open-mercato/shared/lib/commands/flush'\nimport { resolveRedoSnapshot, restoreCreatedRow } from '@open-mercato/shared/lib/commands/redo'\nimport { E } from '#generated/entities.ids.generated'\nimport { findWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport {\n CatalogProductVariant,\n CatalogProductPrice,\n CatalogProduct,\n CatalogOffer,\n CatalogPriceKind,\n} from '../data/entities'\nimport type { DataEngine } from '@open-mercato/shared/lib/data/engine'\nimport { Attachment } from '@open-mercato/core/modules/attachments/data/entities'\nimport { resolveAttachmentScopePair } from '@open-mercato/core/modules/attachments/lib/scope'\nimport {\n variantCreateSchema,\n variantUpdateSchema,\n type VariantCreateInput,\n type VariantUpdateInput,\n} from '../data/validators'\nimport { isValidGtin, normalizeGtinValue } from '../lib/gtin'\nimport type { CatalogGtinType } from '../data/types'\nimport {\n cloneJson,\n commandActorScope,\n ensureOrganizationScope,\n ensureTenantScope,\n emitCatalogQueryIndexEvent,\n extractUndoPayload,\n requireProduct,\n toNumericString,\n getErrorConstraint,\n getErrorMessage,\n} from './shared'\nimport { SalesTaxRate } from '@open-mercato/core/modules/sales/data/entities'\nimport type { CrudEventsConfig } from '@open-mercato/shared/lib/crud/types'\n\nconst variantCrudEvents: CrudEventsConfig = {\n module: 'catalog',\n entity: 'variant',\n persistent: true,\n buildPayload: (ctx) => ({\n id: ctx.identifiers.id,\n organizationId: ctx.identifiers.organizationId,\n tenantId: ctx.identifiers.tenantId,\n }),\n}\n\ntype VariantSnapshot = {\n id: string\n productId: string\n organizationId: string\n tenantId: string\n name: string | null\n sku: string | null\n barcode: string | null\n gtinType: CatalogGtinType | null\n hsCode: string | null\n statusEntryId: string | null\n isDefault: boolean\n isActive: boolean\n weightValue: string | null\n weightUnit: string | null\n taxRateId: string | null\n taxRate: string | null\n dimensions: Record<string, unknown> | null\n metadata: Record<string, unknown> | null\n optionValues: Record<string, string> | null\n customFieldsetCode: string | null\n createdAt: string\n updatedAt: string\n custom: Record<string, unknown> | null\n prices?: VariantPriceSnapshot[] | null\n}\n\ntype VariantUndoPayload = {\n before?: VariantSnapshot | null\n after?: VariantSnapshot | null\n previousDefaultVariantId?: string | null\n}\n\nconst VARIANT_CHANGE_KEYS = [\n 'name',\n 'sku',\n 'barcode',\n 'gtinType',\n 'hsCode',\n 'statusEntryId',\n 'isDefault',\n 'isActive',\n 'weightValue',\n 'weightUnit',\n 'taxRateId',\n 'taxRate',\n 'dimensions',\n 'optionValues',\n 'customFieldsetCode',\n 'metadata',\n] as const satisfies readonly string[]\n\nasync function loadVariantSnapshot(\n em: EntityManager,\n id: string,\n options: { includePrices?: boolean } = {}\n): Promise<VariantSnapshot | null> {\n const record = await em.findOne(CatalogProductVariant, { id, deletedAt: null })\n if (!record) return null\n const prices = options.includePrices\n ? await loadVariantPriceSnapshots(em, record.id, {\n tenantId: record.tenantId,\n organizationId: record.organizationId,\n })\n : null\n const custom = await loadCustomFieldSnapshot(em, {\n entityId: E.catalog.catalog_product_variant,\n recordId: record.id,\n tenantId: record.tenantId,\n organizationId: record.organizationId,\n })\n const productId = typeof record.product === 'string' ? record.product : record.product.id\n return {\n id: record.id,\n productId,\n organizationId: record.organizationId,\n tenantId: record.tenantId,\n name: record.name ?? null,\n sku: record.sku ?? null,\n barcode: record.barcode ?? null,\n gtinType: record.gtinType ?? null,\n hsCode: record.hsCode ?? null,\n statusEntryId: record.statusEntryId ?? null,\n isDefault: record.isDefault,\n isActive: record.isActive,\n weightValue: record.weightValue ?? null,\n weightUnit: record.weightUnit ?? null,\n taxRateId: record.taxRateId ?? null,\n taxRate: record.taxRate ?? null,\n dimensions: record.dimensions ? cloneJson(record.dimensions) : null,\n metadata: record.metadata ? cloneJson(record.metadata) : null,\n optionValues: record.optionValues ? cloneJson(record.optionValues) : null,\n customFieldsetCode: record.customFieldsetCode ?? null,\n createdAt: record.createdAt.toISOString(),\n updatedAt: record.updatedAt.toISOString(),\n custom: Object.keys(custom).length ? custom : null,\n prices: prices && prices.length ? prices : null,\n }\n}\n\nfunction variantSeedFromSnapshot(snapshot: VariantSnapshot): Record<string, unknown> {\n return {\n id: snapshot.id,\n product: snapshot.productId,\n organizationId: snapshot.organizationId,\n tenantId: snapshot.tenantId,\n name: snapshot.name ?? null,\n sku: snapshot.sku ?? null,\n barcode: snapshot.barcode ?? null,\n gtinType: snapshot.gtinType ?? null,\n hsCode: snapshot.hsCode ?? null,\n statusEntryId: snapshot.statusEntryId ?? null,\n isDefault: snapshot.isDefault,\n isActive: snapshot.isActive,\n weightValue: snapshot.weightValue ?? null,\n weightUnit: snapshot.weightUnit ?? null,\n taxRateId: snapshot.taxRateId ?? null,\n taxRate: snapshot.taxRate ?? null,\n dimensions: snapshot.dimensions ? cloneJson(snapshot.dimensions) : null,\n metadata: snapshot.metadata ? cloneJson(snapshot.metadata) : null,\n optionValues: snapshot.optionValues ? cloneJson(snapshot.optionValues) : null,\n customFieldsetCode: snapshot.customFieldsetCode ?? null,\n createdAt: new Date(snapshot.createdAt),\n updatedAt: new Date(snapshot.updatedAt),\n }\n}\n\nfunction applyVariantSnapshot(record: CatalogProductVariant, snapshot: VariantSnapshot): void {\n record.organizationId = snapshot.organizationId\n record.tenantId = snapshot.tenantId\n record.name = snapshot.name ?? null\n record.sku = snapshot.sku ?? null\n record.barcode = snapshot.barcode ?? null\n record.gtinType = snapshot.gtinType ?? null\n record.hsCode = snapshot.hsCode ?? null\n record.statusEntryId = snapshot.statusEntryId ?? null\n record.isDefault = snapshot.isDefault\n record.isActive = snapshot.isActive\n record.weightValue = snapshot.weightValue ?? null\n record.weightUnit = snapshot.weightUnit ?? null\n record.taxRateId = snapshot.taxRateId ?? null\n record.taxRate = snapshot.taxRate ?? null\n record.dimensions = snapshot.dimensions ? cloneJson(snapshot.dimensions) : null\n record.metadata = snapshot.metadata ? cloneJson(snapshot.metadata) : null\n record.optionValues = snapshot.optionValues ? cloneJson(snapshot.optionValues) : null\n record.customFieldsetCode = snapshot.customFieldsetCode ?? null\n record.createdAt = new Date(snapshot.createdAt)\n record.updatedAt = new Date(snapshot.updatedAt)\n}\n\nasync function resolveVariantTaxRate(\n em: EntityManager,\n product: CatalogProduct,\n taxRateIdInput: string | null | undefined,\n taxRateInput: number | string | null | undefined\n): Promise<{ taxRateId: string | null; taxRate: string | null }> {\n const organizationId = product.organizationId\n const tenantId = product.tenantId\n const normalizedRate =\n taxRateInput === null || taxRateInput === undefined\n ? null\n : (() => {\n const numeric = typeof taxRateInput === 'string' ? Number(taxRateInput) : taxRateInput\n return Number.isFinite(numeric) ? toNumericString(numeric) : null\n })()\n if (taxRateIdInput === null) {\n return { taxRateId: product.taxRateId ?? null, taxRate: product.taxRate ?? null }\n }\n if (!taxRateIdInput) {\n return { taxRateId: product.taxRateId ?? null, taxRate: product.taxRate ?? normalizedRate }\n }\n const record = await em.findOne(SalesTaxRate, {\n id: taxRateIdInput,\n organizationId,\n tenantId,\n deletedAt: null,\n })\n if (!record) {\n throw new CrudHttpError(400, { error: 'Tax class not found' })\n }\n return { taxRateId: taxRateIdInput, taxRate: record.rate ?? normalizedRate }\n}\n\ntype VariantPriceSnapshot = {\n id: string\n variantId: string | null\n productId: string | null\n offerId: string | null\n organizationId: string\n tenantId: string\n priceKindId: string\n priceKindCode: string\n currencyCode: string\n kind: string\n minQuantity: number\n maxQuantity: number | null\n unitPriceNet: string | null\n unitPriceGross: string | null\n taxRate: string | null\n taxAmount: string | null\n channelId: string | null\n userId: string | null\n userGroupId: string | null\n customerId: string | null\n customerGroupId: string | null\n metadata: Record<string, unknown> | null\n startsAt: string | null\n endsAt: string | null\n createdAt: string\n updatedAt: string\n custom: Record<string, unknown> | null\n}\n\nasync function loadVariantPriceSnapshots(\n em: EntityManager,\n variantId: string,\n scope: { tenantId: string; organizationId: string }\n): Promise<VariantPriceSnapshot[]> {\n const prices = await findWithDecryption(\n em,\n CatalogProductPrice,\n { variant: variantId, tenantId: scope.tenantId, organizationId: scope.organizationId },\n { populate: ['priceKind', 'product', 'offer'] },\n { tenantId: scope.tenantId, organizationId: scope.organizationId },\n )\n const snapshots: VariantPriceSnapshot[] = []\n for (const price of prices) {\n const variantRef = price.variant\n const variantIdValue =\n typeof variantRef === 'string'\n ? variantRef\n : variantRef\n ? variantRef.id\n : null\n const productRef = price.product\n ? price.product\n : typeof price.variant === 'object' && price.variant\n ? price.variant.product\n : null\n const productId =\n typeof productRef === 'string'\n ? productRef\n : productRef\n ? productRef.id\n : null\n const priceKindRef = price.priceKind\n const priceKindId =\n typeof priceKindRef === 'string'\n ? priceKindRef\n : priceKindRef\n ? priceKindRef.id\n : null\n if (!priceKindId) {\n throw new CrudHttpError(400, { error: 'Price is missing price kind metadata.' })\n }\n const priceKindCode =\n typeof priceKindRef === 'object' && priceKindRef ? priceKindRef.code : price.kind\n const custom = await loadCustomFieldSnapshot(em, {\n entityId: E.catalog.catalog_product_price,\n recordId: price.id,\n tenantId: price.tenantId,\n organizationId: price.organizationId,\n })\n snapshots.push({\n id: price.id,\n variantId: variantIdValue,\n productId,\n offerId: typeof price.offer === 'string' ? price.offer : price.offer ? price.offer.id : null,\n organizationId: price.organizationId,\n tenantId: price.tenantId,\n priceKindId,\n priceKindCode,\n currencyCode: price.currencyCode,\n kind: price.kind,\n minQuantity: price.minQuantity,\n maxQuantity: price.maxQuantity ?? null,\n unitPriceNet: price.unitPriceNet ?? null,\n unitPriceGross: price.unitPriceGross ?? null,\n taxRate: price.taxRate ?? null,\n taxAmount: price.taxAmount ?? null,\n channelId: price.channelId ?? null,\n userId: price.userId ?? null,\n userGroupId: price.userGroupId ?? null,\n customerId: price.customerId ?? null,\n customerGroupId: price.customerGroupId ?? null,\n metadata: price.metadata ? cloneJson(price.metadata) : null,\n startsAt: price.startsAt ? price.startsAt.toISOString() : null,\n endsAt: price.endsAt ? price.endsAt.toISOString() : null,\n createdAt: price.createdAt.toISOString(),\n updatedAt: price.updatedAt.toISOString(),\n custom: Object.keys(custom).length ? custom : null,\n })\n }\n return snapshots\n}\n\nasync function restoreVariantPricesFromSnapshots(\n em: EntityManager,\n variant: CatalogProductVariant,\n snapshots: VariantPriceSnapshot[],\n dataEngine: DataEngine\n): Promise<void> {\n if (!snapshots.length) return\n const productRef =\n typeof variant.product === 'string'\n ? await requireProduct(em, variant.product, {\n tenantId: variant.tenantId,\n organizationId: variant.organizationId,\n })\n : variant.product\n for (const snapshot of snapshots) {\n const product =\n snapshot.productId && snapshot.productId !== productRef.id\n ? em.getReference(CatalogProduct, snapshot.productId)\n : productRef\n const offer = snapshot.offerId ? em.getReference(CatalogOffer, snapshot.offerId) : null\n const priceKind = em.getReference(CatalogPriceKind, snapshot.priceKindId)\n let record = await em.findOne(CatalogProductPrice, { id: snapshot.id })\n if (!record) {\n record = em.create(CatalogProductPrice, {\n id: snapshot.id,\n variant,\n product,\n offer,\n organizationId: snapshot.organizationId,\n tenantId: snapshot.tenantId,\n currencyCode: snapshot.currencyCode,\n priceKind,\n kind: snapshot.priceKindCode || snapshot.kind,\n minQuantity: snapshot.minQuantity,\n maxQuantity: snapshot.maxQuantity ?? null,\n unitPriceNet: snapshot.unitPriceNet ?? null,\n unitPriceGross: snapshot.unitPriceGross ?? null,\n taxRate: snapshot.taxRate ?? null,\n taxAmount: snapshot.taxAmount ?? null,\n channelId: snapshot.channelId ?? null,\n userId: snapshot.userId ?? null,\n userGroupId: snapshot.userGroupId ?? null,\n customerId: snapshot.customerId ?? null,\n customerGroupId: snapshot.customerGroupId ?? null,\n metadata: snapshot.metadata ? cloneJson(snapshot.metadata) : null,\n startsAt: snapshot.startsAt ? new Date(snapshot.startsAt) : null,\n endsAt: snapshot.endsAt ? new Date(snapshot.endsAt) : null,\n createdAt: new Date(snapshot.createdAt),\n updatedAt: new Date(snapshot.updatedAt),\n })\n em.persist(record)\n } else {\n record.variant = variant\n record.product = product\n record.offer = offer\n record.priceKind = priceKind\n record.organizationId = snapshot.organizationId\n record.tenantId = snapshot.tenantId\n record.currencyCode = snapshot.currencyCode\n record.kind = snapshot.priceKindCode || snapshot.kind\n record.minQuantity = snapshot.minQuantity\n record.maxQuantity = snapshot.maxQuantity ?? null\n record.unitPriceNet = snapshot.unitPriceNet ?? null\n record.unitPriceGross = snapshot.unitPriceGross ?? null\n record.taxRate = snapshot.taxRate ?? null\n record.taxAmount = snapshot.taxAmount ?? null\n record.channelId = snapshot.channelId ?? null\n record.userId = snapshot.userId ?? null\n record.userGroupId = snapshot.userGroupId ?? null\n record.customerId = snapshot.customerId ?? null\n record.customerGroupId = snapshot.customerGroupId ?? null\n record.metadata = snapshot.metadata ? cloneJson(snapshot.metadata) : null\n record.startsAt = snapshot.startsAt ? new Date(snapshot.startsAt) : null\n record.endsAt = snapshot.endsAt ? new Date(snapshot.endsAt) : null\n record.createdAt = new Date(snapshot.createdAt)\n record.updatedAt = new Date(snapshot.updatedAt)\n }\n }\n await em.flush()\n for (const snapshot of snapshots) {\n if (!snapshot.custom || !Object.keys(snapshot.custom).length) continue\n await setCustomFieldsIfAny({\n dataEngine,\n entityId: E.catalog.catalog_product_price,\n recordId: snapshot.id,\n organizationId: snapshot.organizationId,\n tenantId: snapshot.tenantId,\n values: snapshot.custom,\n })\n }\n}\n\ntype MetadataSplitResult = {\n metadata: Record<string, unknown> | null\n optionValues: Record<string, string> | null\n hadOptionValues: boolean\n}\n\nfunction splitOptionValuesFromMetadata(\n metadata?: Record<string, unknown> | null\n): MetadataSplitResult {\n if (!metadata || typeof metadata !== 'object' || Array.isArray(metadata)) {\n return {\n metadata: metadata ? cloneJson(metadata) : null,\n optionValues: null,\n hadOptionValues: false,\n }\n }\n const { optionValues, ...rest } = metadata as Record<string, unknown> & {\n optionValues?: unknown\n }\n const normalizedMetadata = Object.keys(rest).length ? cloneJson(rest) : null\n return {\n metadata: normalizedMetadata,\n optionValues: normalizeOptionValues(optionValues),\n hadOptionValues: optionValues !== undefined,\n }\n}\n\nfunction normalizeOptionValues(input: unknown): Record<string, string> | null {\n if (!input || typeof input !== 'object' || Array.isArray(input)) return null\n const normalized: Record<string, string> = {}\n for (const [rawKey, rawValue] of Object.entries(input)) {\n if (typeof rawValue !== 'string') continue\n const key = rawKey.trim()\n const value = rawValue.trim()\n if (!key || !value) continue\n normalized[key] = value\n }\n return Object.keys(normalized).length ? normalized : null\n}\n\nfunction resolveProductId(record: CatalogProductVariant): string {\n return typeof record.product === 'string' ? record.product : record.product.id\n}\n\nasync function enforceSingleDefaultVariant(\n em: EntityManager,\n variant: CatalogProductVariant\n): Promise<string | null> {\n if (!variant.isDefault) return null\n const productId = resolveProductId(variant)\n const existingDefault = await em.findOne(\n CatalogProductVariant,\n { product: productId, isDefault: true, deletedAt: null, id: { $ne: variant.id } },\n { fields: ['id', 'isDefault'] }\n )\n if (existingDefault) {\n existingDefault.isDefault = false\n return existingDefault.id\n }\n return null\n}\n\nasync function aggregateVariantMediaToProduct(\n em: EntityManager,\n variant: CatalogProductVariant\n): Promise<void> {\n const productId = resolveProductId(variant)\n const buildKey = (\n attachment: Pick<Attachment, 'fileName' | 'fileSize' | 'storageDriver' | 'partitionCode' | 'storagePath'>\n ) =>\n [\n attachment.fileName?.trim() ?? '',\n attachment.fileSize ?? '',\n attachment.storageDriver ?? '',\n attachment.partitionCode ?? '',\n ].join('|')\n const attachments = await em.find(\n Attachment,\n {\n entityId: E.catalog.catalog_product_variant,\n recordId: variant.id,\n organizationId: variant.organizationId ?? undefined,\n tenantId: variant.tenantId ?? undefined,\n },\n {\n fields: [\n 'id',\n 'partitionCode',\n 'fileName',\n 'mimeType',\n 'fileSize',\n 'storageDriver',\n 'storagePath',\n 'storageMetadata',\n 'url',\n 'organizationId',\n 'tenantId',\n 'fileSize',\n 'storageDriver',\n 'partitionCode',\n ],\n }\n )\n if (!attachments.length) return\n const existing = await em.find(\n Attachment,\n {\n entityId: E.catalog.catalog_product,\n recordId: productId,\n organizationId: variant.organizationId ?? undefined,\n tenantId: variant.tenantId ?? undefined,\n },\n {\n fields: ['storagePath', 'fileName', 'fileSize', 'storageDriver', 'partitionCode'],\n }\n )\n const existingKeys = new Set(existing.map((item) => buildKey(item)))\n let created = 0\n for (const source of attachments) {\n const key = buildKey(source)\n if (existingKeys.has(key)) continue\n // Carry a scope pair across as a unit (source row first, else the variant\n // scope, else global) so independent `??` coalescing can't produce a\n // partial-null attachment row.\n const scope = resolveAttachmentScopePair(source, variant) ?? { organizationId: null, tenantId: null }\n const clone = em.create(Attachment, {\n entityId: E.catalog.catalog_product,\n recordId: productId,\n organizationId: scope.organizationId,\n tenantId: scope.tenantId,\n partitionCode: source.partitionCode,\n fileName: source.fileName,\n mimeType: source.mimeType,\n fileSize: source.fileSize,\n storageDriver: source.storageDriver,\n storagePath: source.storagePath,\n storageMetadata: source.storageMetadata ? cloneJson(source.storageMetadata) : null,\n url: source.url,\n })\n em.persist(clone)\n existingKeys.add(key)\n created += 1\n }\n if (created > 0) {\n await em.flush()\n }\n}\n\nconst createVariantCommand: CommandHandler<VariantCreateInput, { variantId: string; previousDefaultVariantId?: string | null }> = {\n id: 'catalog.variants.create',\n async execute(rawInput, ctx) {\n const { parsed, custom } = parseWithCustomFields(variantCreateSchema, rawInput)\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const product = await requireProduct(em, parsed.productId, commandActorScope(ctx))\n ensureTenantScope(ctx, product.tenantId)\n ensureOrganizationScope(ctx, product.organizationId)\n const { taxRateId, taxRate } = await resolveVariantTaxRate(\n em,\n product,\n parsed.taxRateId ?? null,\n parsed.taxRate\n )\n\n const metadataSplit = splitOptionValuesFromMetadata(parsed.metadata)\n const resolvedOptionValues =\n parsed.optionValues ?? (metadataSplit.hadOptionValues ? metadataSplit.optionValues : null)\n\n const gtinType = parsed.gtinType ?? null\n const barcode =\n gtinType && parsed.barcode\n ? normalizeGtinValue(gtinType, parsed.barcode)\n : (parsed.barcode ?? null)\n\n const now = new Date()\n const record = em.create(CatalogProductVariant, {\n organizationId: product.organizationId,\n tenantId: product.tenantId,\n product,\n name: parsed.name ?? null,\n sku: parsed.sku ?? null,\n barcode,\n gtinType,\n hsCode: parsed.hsCode ?? null,\n statusEntryId: parsed.statusEntryId ?? null,\n isDefault: parsed.isDefault ?? false,\n isActive: parsed.isActive ?? true,\n weightValue: toNumericString(parsed.weightValue),\n weightUnit: parsed.weightUnit ?? null,\n taxRateId,\n taxRate,\n dimensions: parsed.dimensions ? cloneJson(parsed.dimensions) : null,\n metadata: metadataSplit.metadata,\n optionValues: resolvedOptionValues ? cloneJson(resolvedOptionValues) : null,\n customFieldsetCode: parsed.customFieldsetCode ?? null,\n createdAt: now,\n updatedAt: now,\n })\n em.persist(record)\n let previousDefaultVariantId: string | null = null\n try {\n await withAtomicFlush(\n em,\n [\n () => em.flush(),\n async () => {\n if (record.isDefault) {\n previousDefaultVariantId = await enforceSingleDefaultVariant(em, record)\n await em.flush()\n }\n },\n () => aggregateVariantMediaToProduct(em, record),\n ],\n { transaction: true }\n )\n } catch (error) {\n await rethrowVariantUniqueConstraint(error)\n }\n await setCustomFieldsIfAny({\n dataEngine: ctx.container.resolve('dataEngine'),\n entityId: E.catalog.catalog_product_variant,\n recordId: record.id,\n organizationId: record.organizationId,\n tenantId: record.tenantId,\n values: custom,\n })\n await emitCatalogQueryIndexEvent(ctx, {\n entityType: E.catalog.catalog_product_variant,\n recordId: record.id,\n organizationId: record.organizationId,\n tenantId: record.tenantId,\n action: 'created',\n })\n await emitCrudSideEffects({\n dataEngine: ctx.container.resolve('dataEngine') as DataEngine,\n action: 'created',\n entity: record,\n identifiers: {\n id: record.id,\n organizationId: record.organizationId,\n tenantId: record.tenantId,\n },\n events: variantCrudEvents,\n })\n return { variantId: record.id, previousDefaultVariantId }\n },\n captureAfter: async (_input, result, ctx) => {\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n return loadVariantSnapshot(em, result.variantId)\n },\n buildLog: async ({ result, snapshots }) => {\n const after = snapshots.after as VariantSnapshot | undefined\n if (!after) return null\n const { translate } = await resolveTranslations()\n return {\n actionLabel: translate('catalog.audit.variants.create', 'Create product variant'),\n resourceKind: 'catalog.variant',\n resourceId: result.variantId,\n parentResourceKind: 'catalog.product',\n parentResourceId: after.productId ?? null,\n tenantId: after.tenantId,\n organizationId: after.organizationId,\n snapshotAfter: after,\n payload: {\n undo: {\n after,\n previousDefaultVariantId: (result as { previousDefaultVariantId?: string | null })?.previousDefaultVariantId ?? null,\n } satisfies VariantUndoPayload,\n },\n }\n },\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<VariantUndoPayload>(logEntry)\n const after = payload?.after\n if (!after) return\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const record = await em.findOne(CatalogProductVariant, { id: after.id })\n if (!record) return\n ensureTenantScope(ctx, record.tenantId)\n ensureOrganizationScope(ctx, record.organizationId)\n em.remove(record)\n await em.flush()\n if (payload?.previousDefaultVariantId) {\n const previousDefault = await em.findOne(CatalogProductVariant, { id: payload.previousDefaultVariantId })\n if (previousDefault) {\n ensureTenantScope(ctx, previousDefault.tenantId)\n ensureOrganizationScope(ctx, previousDefault.organizationId)\n previousDefault.isDefault = true\n await em.flush()\n }\n }\n const resetValues = buildCustomFieldResetMap(undefined, after.custom ?? undefined)\n if (Object.keys(resetValues).length) {\n await setCustomFieldsIfAny({\n dataEngine: ctx.container.resolve('dataEngine'),\n entityId: E.catalog.catalog_product_variant,\n recordId: after.id,\n organizationId: after.organizationId,\n tenantId: after.tenantId,\n values: resetValues,\n })\n }\n },\n redo: async ({ ctx, logEntry }) => {\n const after = resolveRedoSnapshot<VariantSnapshot>(logEntry)\n if (!after) throw new CrudHttpError(400, { error: '[internal] redo snapshot unavailable for variant create' })\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const record = await restoreCreatedRow(\n em,\n CatalogProductVariant,\n after.id,\n () => variantSeedFromSnapshot(after),\n )\n applyVariantSnapshot(record, after)\n let previousDefaultVariantId: string | null = null\n try {\n await withAtomicFlush(\n em,\n [\n () => em.flush(),\n async () => {\n if (record.isDefault) {\n previousDefaultVariantId = await enforceSingleDefaultVariant(em, record)\n await em.flush()\n }\n },\n () => aggregateVariantMediaToProduct(em, record),\n ],\n { transaction: true }\n )\n } catch (error) {\n await rethrowVariantUniqueConstraint(error)\n }\n if (after.custom && Object.keys(after.custom).length) {\n await setCustomFieldsIfAny({\n dataEngine: ctx.container.resolve('dataEngine'),\n entityId: E.catalog.catalog_product_variant,\n recordId: record.id,\n organizationId: record.organizationId,\n tenantId: record.tenantId,\n values: after.custom,\n })\n }\n await emitCatalogQueryIndexEvent(ctx, {\n entityType: E.catalog.catalog_product_variant,\n recordId: record.id,\n organizationId: record.organizationId,\n tenantId: record.tenantId,\n action: 'created',\n })\n await emitCrudSideEffects({\n dataEngine: ctx.container.resolve('dataEngine') as DataEngine,\n action: 'created',\n entity: record,\n identifiers: {\n id: record.id,\n organizationId: record.organizationId,\n tenantId: record.tenantId,\n },\n events: variantCrudEvents,\n })\n return { variantId: record.id, previousDefaultVariantId }\n },\n}\n\nconst updateVariantCommand: CommandHandler<VariantUpdateInput, { variantId: string; previousDefaultVariantId?: string | null }> = {\n id: 'catalog.variants.update',\n async prepare(input, ctx) {\n const id = requireId(input, 'Variant id is required')\n const em = (ctx.container.resolve('em') as EntityManager)\n const snapshot = await loadVariantSnapshot(em, id)\n if (snapshot) {\n ensureTenantScope(ctx, snapshot.tenantId)\n ensureOrganizationScope(ctx, snapshot.organizationId)\n }\n return snapshot ? { before: snapshot } : {}\n },\n async execute(rawInput, ctx) {\n const { parsed, custom } = parseWithCustomFields(variantUpdateSchema, rawInput)\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const record = await em.findOne(CatalogProductVariant, { id: parsed.id, deletedAt: null })\n if (!record) throw new CrudHttpError(404, { error: 'Catalog variant not found' })\n ensureTenantScope(ctx, record.tenantId)\n ensureOrganizationScope(ctx, record.organizationId)\n const product = await requireProduct(em, record.product.id, {\n tenantId: record.tenantId,\n organizationId: record.organizationId,\n })\n\n if (!product) throw new CrudHttpError(400, { error: 'Variant product missing' })\n\n const taxRateProvided = parsed.taxRateId !== undefined || parsed.taxRate !== undefined\n const resolvedTaxRate = taxRateProvided\n ? await resolveVariantTaxRate(em, product, parsed.taxRateId ?? null, parsed.taxRate)\n : null\n\n // Re-validate GTIN against the merged record state: a partial update may\n // carry only one of (gtinType, barcode) while the other half is stored.\n let normalizedGtinBarcode: string | null = null\n if (parsed.gtinType !== undefined || parsed.barcode !== undefined) {\n const effectiveGtinType =\n parsed.gtinType !== undefined ? (parsed.gtinType ?? null) : (record.gtinType ?? null)\n if (effectiveGtinType) {\n const effectiveBarcode =\n parsed.barcode !== undefined ? (parsed.barcode ?? null) : (record.barcode ?? null)\n if (!effectiveBarcode || !effectiveBarcode.trim().length) {\n await throwGtinBarcodeRequiredError()\n } else {\n const normalized = normalizeGtinValue(effectiveGtinType, effectiveBarcode)\n if (!isValidGtin(effectiveGtinType, normalized)) {\n await throwInvalidGtinError()\n }\n normalizedGtinBarcode = normalized\n }\n }\n }\n\n let previousDefaultVariantId: string | null = null\n try {\n await withAtomicFlush(\n em,\n [\n () => {\n if (parsed.name !== undefined) record.name = parsed.name ?? null\n if (parsed.sku !== undefined) record.sku = parsed.sku ?? null\n if (parsed.barcode !== undefined) record.barcode = parsed.barcode ?? null\n if (parsed.gtinType !== undefined) record.gtinType = parsed.gtinType ?? null\n if (parsed.hsCode !== undefined) record.hsCode = parsed.hsCode ?? null\n if (normalizedGtinBarcode !== null) record.barcode = normalizedGtinBarcode\n if (parsed.statusEntryId !== undefined) record.statusEntryId = parsed.statusEntryId ?? null\n if (parsed.isDefault !== undefined) record.isDefault = parsed.isDefault\n if (parsed.isActive !== undefined) record.isActive = parsed.isActive\n if (Object.prototype.hasOwnProperty.call(parsed, 'weightValue')) {\n record.weightValue = toNumericString(parsed.weightValue)\n }\n if (parsed.weightUnit !== undefined) record.weightUnit = parsed.weightUnit ?? null\n if (parsed.dimensions !== undefined) {\n record.dimensions = parsed.dimensions ? cloneJson(parsed.dimensions) : null\n }\n let metadataSplit: MetadataSplitResult | null = null\n if (parsed.metadata !== undefined) {\n metadataSplit = splitOptionValuesFromMetadata(parsed.metadata)\n record.metadata = metadataSplit.metadata\n }\n if (parsed.optionValues !== undefined) {\n record.optionValues = parsed.optionValues ? cloneJson(parsed.optionValues) : null\n } else if (metadataSplit?.hadOptionValues) {\n record.optionValues = metadataSplit.optionValues ? cloneJson(metadataSplit.optionValues) : null\n }\n if (taxRateProvided) {\n record.taxRateId = resolvedTaxRate?.taxRateId ?? null\n record.taxRate = resolvedTaxRate?.taxRate ?? null\n }\n if (parsed.customFieldsetCode !== undefined) {\n record.customFieldsetCode = parsed.customFieldsetCode ?? null\n }\n },\n async () => {\n if (parsed.isDefault === true) {\n previousDefaultVariantId = await enforceSingleDefaultVariant(em, record)\n }\n },\n () => aggregateVariantMediaToProduct(em, record),\n ],\n { transaction: true }\n )\n } catch (error) {\n await rethrowVariantUniqueConstraint(error)\n }\n if (custom && Object.keys(custom).length) {\n await setCustomFieldsIfAny({\n dataEngine: ctx.container.resolve('dataEngine'),\n entityId: E.catalog.catalog_product_variant,\n recordId: record.id,\n organizationId: record.organizationId,\n tenantId: record.tenantId,\n values: custom,\n })\n }\n await emitCatalogQueryIndexEvent(ctx, {\n entityType: E.catalog.catalog_product_variant,\n recordId: record.id,\n organizationId: record.organizationId,\n tenantId: record.tenantId,\n action: 'updated',\n })\n await emitCrudSideEffects({\n dataEngine: ctx.container.resolve('dataEngine') as DataEngine,\n action: 'updated',\n entity: record,\n identifiers: {\n id: record.id,\n organizationId: record.organizationId,\n tenantId: record.tenantId,\n },\n events: variantCrudEvents,\n })\n return { variantId: record.id, previousDefaultVariantId }\n },\n captureAfter: async (_input, result, ctx) => {\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n return loadVariantSnapshot(em, result.variantId)\n },\n buildLog: async ({ result, snapshots }) => {\n const before = snapshots.before as VariantSnapshot | undefined\n const after = snapshots.after as VariantSnapshot | undefined\n if (!before || !after) return null\n const { translate } = await resolveTranslations()\n return {\n actionLabel: translate('catalog.audit.variants.update', 'Update product variant'),\n resourceKind: 'catalog.variant',\n resourceId: before.id,\n parentResourceKind: 'catalog.product',\n parentResourceId: before.productId ?? null,\n tenantId: before.tenantId,\n organizationId: before.organizationId,\n snapshotBefore: before,\n snapshotAfter: after,\n changes: buildChanges(\n before as Record<string, unknown>,\n after as Record<string, unknown>,\n VARIANT_CHANGE_KEYS\n ),\n payload: {\n undo: {\n before,\n after,\n previousDefaultVariantId:\n (result as { previousDefaultVariantId?: string | null })?.previousDefaultVariantId ?? null,\n } satisfies VariantUndoPayload,\n },\n }\n },\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<VariantUndoPayload>(logEntry)\n const before = payload?.before\n if (!before) return\n const after = payload?.after\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n let record = await em.findOne(CatalogProductVariant, { id: before.id })\n if (!record) {\n const product = await requireProduct(em, before.productId, {\n tenantId: before.tenantId,\n organizationId: before.organizationId,\n })\n record = em.create(CatalogProductVariant, {\n id: before.id,\n product,\n organizationId: before.organizationId,\n tenantId: before.tenantId,\n name: before.name ?? null,\n sku: before.sku ?? null,\n barcode: before.barcode ?? null,\n statusEntryId: before.statusEntryId ?? null,\n isDefault: before.isDefault,\n isActive: before.isActive,\n weightValue: before.weightValue ?? null,\n weightUnit: before.weightUnit ?? null,\n dimensions: before.dimensions ? cloneJson(before.dimensions) : null,\n metadata: before.metadata ? cloneJson(before.metadata) : null,\n optionValues: before.optionValues ? cloneJson(before.optionValues) : null,\n customFieldsetCode: before.customFieldsetCode ?? null,\n createdAt: new Date(before.createdAt),\n updatedAt: new Date(before.updatedAt),\n })\n em.persist(record)\n }\n ensureTenantScope(ctx, before.tenantId)\n ensureOrganizationScope(ctx, before.organizationId)\n applyVariantSnapshot(record, before)\n await em.flush()\n const previousDefaultId = payload?.previousDefaultVariantId\n if (previousDefaultId) {\n const previousDefault = await em.findOne(CatalogProductVariant, { id: previousDefaultId })\n if (previousDefault) {\n ensureTenantScope(ctx, previousDefault.tenantId)\n ensureOrganizationScope(ctx, previousDefault.organizationId)\n previousDefault.isDefault = true\n await em.flush()\n }\n }\n const resetValues = buildCustomFieldResetMap(\n before.custom ?? undefined,\n after?.custom ?? undefined\n )\n if (Object.keys(resetValues).length) {\n await setCustomFieldsIfAny({\n dataEngine: ctx.container.resolve('dataEngine'),\n entityId: E.catalog.catalog_product_variant,\n recordId: before.id,\n organizationId: before.organizationId,\n tenantId: before.tenantId,\n values: resetValues,\n })\n }\n },\n}\n\nconst deleteVariantCommand: CommandHandler<\n { body?: Record<string, unknown>; query?: Record<string, unknown> },\n { variantId: string }\n> = {\n id: 'catalog.variants.delete',\n async prepare(input, ctx) {\n const id = requireId(input, 'Variant id is required')\n const em = (ctx.container.resolve('em') as EntityManager)\n const snapshot = await loadVariantSnapshot(em, id, { includePrices: true })\n if (snapshot) {\n ensureTenantScope(ctx, snapshot.tenantId)\n ensureOrganizationScope(ctx, snapshot.organizationId)\n }\n return snapshot ? { before: snapshot } : {}\n },\n async execute(input, ctx) {\n const id = requireId(input, 'Variant id is required')\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const record = await em.findOne(CatalogProductVariant, { id })\n if (!record) throw new CrudHttpError(404, { error: 'Catalog variant not found' })\n ensureTenantScope(ctx, record.tenantId)\n ensureOrganizationScope(ctx, record.organizationId)\n\n const baseEm = (ctx.container.resolve('em') as EntityManager)\n const snapshot = await loadVariantSnapshot(baseEm, id, { includePrices: true })\n const dataEngine = ctx.container.resolve('dataEngine') as DataEngine\n const priceSnapshots =\n snapshot?.prices && snapshot.prices.length\n ? snapshot.prices\n : await loadVariantPriceSnapshots(baseEm, id, {\n tenantId: record.tenantId,\n organizationId: record.organizationId,\n })\n\n if (priceSnapshots.length) {\n await em.nativeDelete(CatalogProductPrice, { id: { $in: priceSnapshots.map((price) => price.id) } })\n } else {\n await em.nativeDelete(CatalogProductPrice, { variant: record })\n }\n em.remove(record)\n await em.flush()\n for (const priceSnapshot of priceSnapshots) {\n const resetValues = buildCustomFieldResetMap(priceSnapshot.custom ?? undefined, undefined)\n if (!Object.keys(resetValues).length) continue\n await setCustomFieldsIfAny({\n dataEngine,\n entityId: E.catalog.catalog_product_price,\n recordId: priceSnapshot.id,\n organizationId: priceSnapshot.organizationId,\n tenantId: priceSnapshot.tenantId,\n values: resetValues,\n })\n }\n if (snapshot?.custom && Object.keys(snapshot.custom).length) {\n const resetValues = buildCustomFieldResetMap(snapshot.custom, undefined)\n if (Object.keys(resetValues).length) {\n await setCustomFieldsIfAny({\n dataEngine,\n entityId: E.catalog.catalog_product_variant,\n recordId: id,\n organizationId: snapshot.organizationId,\n tenantId: snapshot.tenantId,\n values: resetValues,\n })\n }\n }\n await emitCatalogQueryIndexEvent(ctx, {\n entityType: E.catalog.catalog_product_variant,\n recordId: id,\n organizationId: snapshot?.organizationId ?? record.organizationId,\n tenantId: snapshot?.tenantId ?? record.tenantId,\n action: 'deleted',\n })\n await emitCrudSideEffects({\n dataEngine: ctx.container.resolve('dataEngine') as DataEngine,\n action: 'deleted',\n entity: record,\n identifiers: {\n id,\n organizationId: snapshot?.organizationId ?? record.organizationId,\n tenantId: snapshot?.tenantId ?? record.tenantId,\n },\n events: variantCrudEvents,\n })\n return { variantId: id }\n },\n buildLog: async ({ snapshots }) => {\n const before = snapshots.before as VariantSnapshot | undefined\n if (!before) return null\n const { translate } = await resolveTranslations()\n return {\n actionLabel: translate('catalog.audit.variants.delete', 'Delete product variant'),\n resourceKind: 'catalog.variant',\n resourceId: before.id,\n parentResourceKind: 'catalog.product',\n parentResourceId: before.productId ?? null,\n tenantId: before.tenantId,\n organizationId: before.organizationId,\n snapshotBefore: before,\n payload: {\n undo: {\n before,\n } satisfies VariantUndoPayload,\n },\n }\n },\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<VariantUndoPayload>(logEntry)\n const before = payload?.before\n if (!before) return\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n let record = await em.findOne(CatalogProductVariant, { id: before.id })\n if (!record) {\n const product = await requireProduct(em, before.productId, {\n tenantId: before.tenantId,\n organizationId: before.organizationId,\n })\n record = em.create(CatalogProductVariant, {\n id: before.id,\n product,\n organizationId: before.organizationId,\n tenantId: before.tenantId,\n name: before.name ?? null,\n sku: before.sku ?? null,\n barcode: before.barcode ?? null,\n statusEntryId: before.statusEntryId ?? null,\n isDefault: before.isDefault,\n isActive: before.isActive,\n weightValue: before.weightValue ?? null,\n weightUnit: before.weightUnit ?? null,\n dimensions: before.dimensions ? cloneJson(before.dimensions) : null,\n metadata: before.metadata ? cloneJson(before.metadata) : null,\n customFieldsetCode: before.customFieldsetCode ?? null,\n createdAt: new Date(before.createdAt),\n updatedAt: new Date(before.updatedAt),\n })\n em.persist(record)\n }\n ensureTenantScope(ctx, before.tenantId)\n ensureOrganizationScope(ctx, before.organizationId)\n applyVariantSnapshot(record, before)\n if (before.prices?.length) {\n const dataEngine = ctx.container.resolve('dataEngine') as DataEngine\n await restoreVariantPricesFromSnapshots(em, record, before.prices, dataEngine)\n }\n await em.flush()\n if (before.custom && Object.keys(before.custom).length) {\n await setCustomFieldsIfAny({\n dataEngine: ctx.container.resolve('dataEngine'),\n entityId: E.catalog.catalog_product_variant,\n recordId: before.id,\n organizationId: before.organizationId,\n tenantId: before.tenantId,\n values: before.custom,\n })\n }\n },\n}\n\nasync function throwDuplicateVariantSkuError(): Promise<never> {\n const { translate } = await resolveTranslations()\n const message = translate('catalog.variants.errors.skuExists', 'SKU already in use.')\n throw new CrudHttpError(400, {\n error: message,\n fieldErrors: { sku: message },\n details: [{ path: ['sku'], message, code: 'duplicate', origin: 'validation' }],\n })\n}\n\nasync function throwDuplicateVariantGtinError(): Promise<never> {\n const { translate } = await resolveTranslations()\n const message = translate(\n 'catalog.variants.errors.gtinExists',\n 'Another variant already uses this identifier.',\n )\n throw new CrudHttpError(400, {\n error: message,\n fieldErrors: { barcode: message },\n details: [{ path: ['barcode'], message, code: 'duplicate', origin: 'validation' }],\n })\n}\n\nasync function throwGtinBarcodeRequiredError(): Promise<never> {\n const { translate } = await resolveTranslations()\n const message = translate(\n 'catalog.variants.validation.gtinBarcodeRequired',\n 'A barcode value is required when an identifier type is set.',\n )\n throw new CrudHttpError(400, {\n error: message,\n fieldErrors: { barcode: message },\n details: [{ path: ['barcode'], message, code: 'invalid', origin: 'validation' }],\n })\n}\n\nasync function throwInvalidGtinError(): Promise<never> {\n const { translate } = await resolveTranslations()\n const message = translate(\n 'catalog.variants.validation.gtinChecksum',\n 'The barcode does not match the selected identifier type.',\n )\n throw new CrudHttpError(400, {\n error: message,\n fieldErrors: { barcode: message },\n details: [{ path: ['barcode'], message, code: 'invalid', origin: 'validation' }],\n })\n}\n\nasync function rethrowVariantUniqueConstraint(error: unknown): Promise<never> {\n if (error instanceof UniqueConstraintViolationException) {\n const constraint = getErrorConstraint(error)\n const message = getErrorMessage(error).toLowerCase()\n if (\n constraint === 'catalog_product_variants_sku_unique' ||\n message.includes('catalog_product_variants_sku_unique')\n ) {\n await throwDuplicateVariantSkuError()\n }\n if (\n constraint === 'catalog_product_variants_gtin_scope_unique' ||\n message.includes('catalog_product_variants_gtin_scope_unique')\n ) {\n await throwDuplicateVariantGtinError()\n }\n }\n throw error\n}\n\nregisterCommand(createVariantCommand)\nregisterCommand(updateVariantCommand)\nregisterCommand(deleteVariantCommand)\n"],
5
+ "mappings": "AAAA,SAAS,uBAAuB;AAEhC,SAAS,cAAc,WAAW,uBAAuB,sBAAsB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AAW,QAAQ,aAAa,CAAC;AAAA,EACjF,CAAC;AACH;AAEA,eAAe,wBAAwC;AACrD,QAAM,EAAE,UAAU,IAAI,MAAM,oBAAoB;AAChD,QAAM,UAAU;AAAA,IACd;AAAA,IACA;AAAA,EACF;AACA,QAAM,IAAI,cAAc,KAAK;AAAA,IAC3B,OAAO;AAAA,IACP,aAAa,EAAE,SAAS,QAAQ;AAAA,IAChC,SAAS,CAAC,EAAE,MAAM,CAAC,SAAS,GAAG,SAAS,MAAM,WAAW,QAAQ,aAAa,CAAC;AAAA,EACjF,CAAC;AACH;AAEA,eAAe,+BAA+B,OAAgC;AAC5E,MAAI,iBAAiB,oCAAoC;AACvD,UAAM,aAAa,mBAAmB,KAAK;AAC3C,UAAM,UAAU,gBAAgB,KAAK,EAAE,YAAY;AACnD,QACE,eAAe,yCACf,QAAQ,SAAS,qCAAqC,GACtD;AACA,YAAM,8BAA8B;AAAA,IACtC;AACA,QACE,eAAe,gDACf,QAAQ,SAAS,4CAA4C,GAC7D;AACA,YAAM,+BAA+B;AAAA,IACvC;AAAA,EACF;AACA,QAAM;AACR;AAEA,gBAAgB,oBAAoB;AACpC,gBAAgB,oBAAoB;AACpC,gBAAgB,oBAAoB;",
6
6
  "names": []
7
7
  }
@@ -0,0 +1,75 @@
1
+ import { NextResponse } from "next/server";
2
+ import { getAuthFromRequest } from "@open-mercato/shared/lib/auth/server";
3
+ import {
4
+ clearModuleResourceUsageData,
5
+ getModuleResourceUsageReport
6
+ } from "@open-mercato/shared/lib/modules/resource-usage";
7
+ import {
8
+ configErrorSchema,
9
+ configsTag,
10
+ moduleTelemetryClearResponseSchema,
11
+ moduleTelemetryResponseSchema
12
+ } from "../openapi.js";
13
+ const metadata = {
14
+ GET: { requireAuth: true, requireFeatures: ["configs.system_status.view"] },
15
+ // Clearing telemetry shouldn't itself perturb the very telemetry it just cleared.
16
+ DELETE: { requireAuth: true, requireFeatures: ["configs.manage"], skipModuleResourceUsageTracking: true }
17
+ };
18
+ function canClearModuleTelemetry() {
19
+ return process.env.NODE_ENV === "development";
20
+ }
21
+ async function GET(req) {
22
+ const auth = await getAuthFromRequest(req);
23
+ if (!auth?.sub) {
24
+ return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
25
+ }
26
+ return NextResponse.json({
27
+ ...getModuleResourceUsageReport(),
28
+ canClearTelemetry: canClearModuleTelemetry()
29
+ });
30
+ }
31
+ async function DELETE(req) {
32
+ const auth = await getAuthFromRequest(req);
33
+ if (!auth?.sub) {
34
+ return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
35
+ }
36
+ if (!canClearModuleTelemetry()) {
37
+ return NextResponse.json({ error: "Clearing module telemetry is only available in development mode." }, { status: 403 });
38
+ }
39
+ clearModuleResourceUsageData();
40
+ return NextResponse.json({ cleared: true });
41
+ }
42
+ const openApi = {
43
+ tag: configsTag,
44
+ summary: "Module telemetry usage",
45
+ methods: {
46
+ GET: {
47
+ summary: "Get module resource usage telemetry",
48
+ description: "Returns in-process module resource attribution for API routes, event subscribers, and queue workers.",
49
+ responses: [
50
+ { status: 200, description: "Module resource usage report", schema: moduleTelemetryResponseSchema }
51
+ ],
52
+ errors: [
53
+ { status: 401, description: "Unauthorized", schema: configErrorSchema }
54
+ ]
55
+ },
56
+ DELETE: {
57
+ summary: "Clear module telemetry data",
58
+ description: "Development-only endpoint that clears in-memory module telemetry and local process telemetry files.",
59
+ responses: [
60
+ { status: 200, description: "Module telemetry cleared", schema: moduleTelemetryClearResponseSchema }
61
+ ],
62
+ errors: [
63
+ { status: 401, description: "Unauthorized", schema: configErrorSchema },
64
+ { status: 403, description: "Forbidden outside development mode", schema: configErrorSchema }
65
+ ]
66
+ }
67
+ }
68
+ };
69
+ export {
70
+ DELETE,
71
+ GET,
72
+ metadata,
73
+ openApi
74
+ };
75
+ //# sourceMappingURL=route.js.map