@open-mercato/core 0.7.1-develop.7195.1.b5efd1d51a → 0.7.1-develop.7200.1.8ba2d93d3f

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.
@@ -331,6 +331,7 @@ async function setupInitialTenant(em, options) {
331
331
  await mod.setup.onTenantCreated({ em, tenantId, organizationId });
332
332
  }
333
333
  }
334
+ await ensureCustomRoleAcls(em, tenantId, resolvedModules);
334
335
  return {
335
336
  tenantId,
336
337
  organizationId,
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/auth/lib/setup-app.ts"],
4
- "sourcesContent": ["import { hash } from 'bcryptjs'\nimport { randomBytes } from 'node:crypto'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport { Role, RoleAcl, User, UserRole } from '@open-mercato/core/modules/auth/data/entities'\nimport { Tenant, Organization } from '@open-mercato/core/modules/directory/data/entities'\nimport { rebuildHierarchyForTenant } from '@open-mercato/core/modules/directory/lib/hierarchy'\nimport { normalizeTenantId } from './tenantAccess'\nimport { computeEmailHash, emailHashLookupValues } from '@open-mercato/core/modules/auth/lib/emailHash'\nimport { getDefaultEncryptionMaps, type Module } from '@open-mercato/shared/modules/registry'\nimport { isEncryptionDebugEnabled, isTenantDataEncryptionEnabled } from '@open-mercato/shared/lib/encryption/toggles'\nimport { EncryptionMap } from '@open-mercato/core/modules/entities/data/entities'\nimport { createKmsService } from '@open-mercato/shared/lib/encryption/kms'\nimport { TenantDataEncryptionService } from '@open-mercato/shared/lib/encryption/tenantDataEncryptionService'\nimport { findOneWithDecryption, findWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { parseBooleanToken } from '@open-mercato/shared/lib/boolean'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('auth').child({ component: 'setup' })\n\nconst DEFAULT_ROLE_NAMES = ['employee', 'admin', 'superadmin'] as const\nconst DEMO_SUPERADMIN_EMAIL = 'superadmin@acme.com'\nconst DEFAULT_DERIVED_EMAIL_DOMAIN = DEMO_SUPERADMIN_EMAIL.split('@')[1] ?? 'acme.com'\n\nexport type EnsureRolesOptions = {\n roleNames?: string[]\n tenantId?: string\n}\n\nasync function ensureRolesInContext(\n em: EntityManager,\n roleNames: string[],\n tenantId: string,\n) {\n for (const name of roleNames) {\n const existing = await findOneWithDecryption(em, Role, { name, tenantId }, {}, { tenantId, organizationId: null })\n if (existing) continue\n em.persist(em.create(Role, { name, tenantId, minActiveHolders: name === 'admin' ? 1 : 0, createdAt: new Date() }))\n }\n}\n\nexport async function ensureRoles(em: EntityManager, options: EnsureRolesOptions = {}) {\n const roleNames = options.roleNames ?? [...DEFAULT_ROLE_NAMES]\n const tenantId = normalizeTenantId(options.tenantId ?? null)\n if (!tenantId) {\n throw new Error('ensureRoles requires a tenantId \u2014 global roles are not supported')\n }\n await em.transactional(async (tem) => {\n await ensureRolesInContext(tem, roleNames, tenantId)\n await tem.flush()\n })\n}\n\nasync function findRoleByName(\n em: EntityManager,\n name: string,\n tenantId: string | null,\n): Promise<Role | null> {\n const normalizedTenant = normalizeTenantId(tenantId ?? null) ?? null\n return findOneWithDecryption(em, Role, { name, tenantId: normalizedTenant }, {}, { tenantId: normalizedTenant, organizationId: null })\n}\n\nasync function findRoleByNameOrFail(\n em: EntityManager,\n name: string,\n tenantId: string | null,\n): Promise<Role> {\n const role = await findRoleByName(em, name, tenantId)\n if (!role) throw new Error(`ROLE_NOT_FOUND:${name}`)\n return role\n}\n\ntype PrimaryUserInput = {\n email: string\n password?: string\n hashedPassword?: string | null\n firstName?: string | null\n lastName?: string | null\n displayName?: string | null\n confirm?: boolean\n}\n\nconst DERIVED_EMAIL_ENV = {\n admin: 'OM_INIT_ADMIN_EMAIL',\n employee: 'OM_INIT_EMPLOYEE_EMAIL',\n} as const\n\nexport type DemoUserRole = 'superadmin' | 'admin' | 'employee'\nexport type DemoUserEmail = { role: DemoUserRole; email: string }\n\n/**\n * Returns the canonical list of demo user emails the setup path may have\n * seeded. Honors OM_INIT_ADMIN_EMAIL / OM_INIT_EMPLOYEE_EMAIL exactly the\n * same way the derived-user seeding branch does, so the deactivation loop\n * never drifts from the seeding loop.\n *\n * Pure function \u2014 no side effects, safe to unit-test in isolation.\n *\n * @internal Exported for tests; not part of the public auth API.\n */\nexport function resolveDemoUserEmails(): DemoUserEmail[] {\n const adminEmail = readEnvValue(DERIVED_EMAIL_ENV.admin) ?? `admin@${DEFAULT_DERIVED_EMAIL_DOMAIN}`\n const employeeEmail = readEnvValue(DERIVED_EMAIL_ENV.employee) ?? `employee@${DEFAULT_DERIVED_EMAIL_DOMAIN}`\n return [\n { role: 'superadmin', email: DEMO_SUPERADMIN_EMAIL },\n { role: 'admin', email: adminEmail },\n { role: 'employee', email: employeeEmail },\n ]\n}\n\nexport type SetupInitialTenantOptions = {\n orgName: string\n primaryUser: PrimaryUserInput\n roleNames?: string[]\n includeDerivedUsers?: boolean\n failIfUserExists?: boolean\n primaryUserRoles?: string[]\n includeSuperadminRole?: boolean\n /** Optional list of enabled modules. When provided, module setup hooks are called. */\n modules?: Module[]\n /**\n * Optional global slug to persist on the new Organization. When set, a\n * pre-flight uniqueness check across all tenants throws OrgSlugExistsError\n * on collision so scriptable callers can fail loudly instead of silently\n * reusing or clobbering an existing organization.\n */\n orgSlug?: string\n /**\n * Opt-in flag that allows seeding the derived admin/employee accounts when\n * the OM_INIT_ADMIN_PASSWORD / OM_INIT_EMPLOYEE_PASSWORD env vars are unset.\n *\n * - In non-production (`NODE_ENV !== 'production'`): the demo accounts are\n * seeded with the well-known `'secret'` password so local dev workflows\n * (e.g. `mercato init`) stay predictable for developers.\n * - In production: the fallback uses a randomly generated 96-bit password\n * (printed once by the CLI) so an operator who deliberately opts in still\n * avoids the historical hardcoded credential. When this flag is false/unset\n * in production and the env vars are missing, `DerivedUserPasswordRequiredError`\n * is thrown instead of silently seeding any account.\n */\n allowDemoDerivedPasswords?: boolean\n}\n\nexport class OrgSlugExistsError extends Error {\n constructor(public readonly slug: string) {\n super(`ORG_SLUG_EXISTS: an organization with slug \"${slug}\" already exists`)\n this.name = 'OrgSlugExistsError'\n }\n}\n\nexport class DerivedUserPasswordRequiredError extends Error {\n constructor(public readonly missing: string[]) {\n super(\n `DERIVED_USER_PASSWORD_REQUIRED: missing ${missing.join(', ')} (set the env vars, pass allowDemoDerivedPasswords: true / --include-demo-users in non-production, or disable derived user seeding)`,\n )\n this.name = 'DerivedUserPasswordRequiredError'\n }\n}\n\nexport type SetupInitialTenantResult = {\n tenantId: string\n organizationId: string\n users: Array<{ user: User; roles: string[]; created: boolean; generatedPassword?: string | null }>\n reusedExistingUser: boolean\n}\n\nexport async function setupInitialTenant(\n em: EntityManager,\n options: SetupInitialTenantOptions,\n): Promise<SetupInitialTenantResult> {\n const {\n primaryUser,\n includeDerivedUsers = true,\n failIfUserExists = false,\n primaryUserRoles,\n includeSuperadminRole = true,\n } = options\n const primaryRolesInput = primaryUserRoles && primaryUserRoles.length ? primaryUserRoles : ['superadmin']\n const primaryRoles = includeSuperadminRole\n ? primaryRolesInput\n : primaryRolesInput.filter((role) => role !== 'superadmin')\n if (primaryRoles.length === 0) {\n throw new Error('PRIMARY_ROLES_REQUIRED')\n }\n const defaultRoleNames = options.roleNames ?? [...DEFAULT_ROLE_NAMES]\n const resolvedRoleNames = includeSuperadminRole\n ? defaultRoleNames\n : defaultRoleNames.filter((role) => role !== 'superadmin')\n const roleNames = Array.from(new Set([...resolvedRoleNames, ...primaryRoles]))\n const resolvedModules = options.modules ?? tryGetModules()\n const defaultEncryptionMaps = getDefaultEncryptionMaps(resolvedModules)\n\n const mainEmail = primaryUser.email\n const existingUserByHash = await findOneWithDecryption(\n em,\n User,\n { emailHash: { $in: emailHashLookupValues(mainEmail) }, deletedAt: null },\n {},\n { tenantId: null, organizationId: null },\n )\n const existingUser = existingUserByHash ?? await findOneWithDecryption(\n em,\n User,\n { email: mainEmail, deletedAt: null },\n {},\n { tenantId: null, organizationId: null },\n )\n if (existingUser && failIfUserExists) {\n throw new Error('USER_EXISTS')\n }\n\n if (options.orgSlug) {\n const slugConflict = await findOneWithDecryption(\n em,\n Organization,\n { slug: options.orgSlug },\n {},\n { tenantId: null, organizationId: null },\n )\n if (slugConflict) {\n throw new OrgSlugExistsError(options.orgSlug)\n }\n }\n\n let tenantId: string | undefined\n let organizationId: string | undefined\n let reusedExistingUser = false\n const userSnapshots: Array<{ user: User; roles: string[]; created: boolean; generatedPassword?: string | null }> = []\n\n await em.transactional(async (tem) => {\n if (!existingUser) return\n reusedExistingUser = true\n tenantId = existingUser.tenantId ? String(existingUser.tenantId) : undefined\n organizationId = existingUser.organizationId ? String(existingUser.organizationId) : undefined\n const roleTenantId = normalizeTenantId(existingUser.tenantId ?? null) ?? null\n if (!roleTenantId) {\n throw new Error('Cannot reuse a user without a tenantId \u2014 global roles are not supported')\n }\n\n await ensureRolesInContext(tem, roleNames, roleTenantId)\n await tem.flush()\n\n const requiredRoleSet = new Set([...roleNames, ...primaryRoles])\n const links = await findWithDecryption(\n tem,\n UserRole,\n { user: existingUser },\n { populate: ['role'] },\n { tenantId: roleTenantId, organizationId: null },\n )\n const currentRoles = new Set(links.map((link) => link.role.name))\n for (const roleName of requiredRoleSet) {\n if (!currentRoles.has(roleName)) {\n const role = await findRoleByNameOrFail(tem, roleName, roleTenantId)\n tem.persist(tem.create(UserRole, { user: existingUser, role, createdAt: new Date() }))\n }\n }\n await tem.flush()\n const roles = Array.from(new Set([...currentRoles, ...roleNames]))\n userSnapshots.push({ user: existingUser, roles, created: false })\n })\n\n if (!existingUser) {\n const baseUsers: Array<{\n email: string\n roles: string[]\n name?: string | null\n passwordHash?: string | null\n generatedPassword?: string | null\n }> = [\n { email: primaryUser.email, roles: primaryRoles, name: resolvePrimaryName(primaryUser) },\n ]\n if (includeDerivedUsers) {\n const adminOverride = readEnvValue(DERIVED_EMAIL_ENV.admin)\n const employeeOverride = readEnvValue(DERIVED_EMAIL_ENV.employee)\n const adminEmail = adminOverride ?? `admin@${DEFAULT_DERIVED_EMAIL_DOMAIN}`\n const employeeEmail = employeeOverride ?? `employee@${DEFAULT_DERIVED_EMAIL_DOMAIN}`\n const envAdminPwd = readEnvValue('OM_INIT_ADMIN_PASSWORD')\n const envEmployeePwd = readEnvValue('OM_INIT_EMPLOYEE_PASSWORD')\n const isProduction = process.env.NODE_ENV === 'production'\n const allowDemo = options.allowDemoDerivedPasswords === true\n if (isProduction && !allowDemo) {\n const missing: string[] = []\n if (!envAdminPwd) missing.push('OM_INIT_ADMIN_PASSWORD')\n if (!envEmployeePwd) missing.push('OM_INIT_EMPLOYEE_PASSWORD')\n if (missing.length) {\n throw new DerivedUserPasswordRequiredError(missing)\n }\n }\n // In non-production, fall back to the well-known DEMO_DERIVED_PASSWORD so\n // local dev workflows stay predictable (admin@/employee@ login with the\n // documented demo password). In production we either have env-supplied\n // values, or \u2014 for opt-in --include-demo-users flows \u2014 we generate a\n // random one-time password and surface it via `generatedPassword` so the\n // operator can capture it. Production callers without env vars and\n // without the opt-in already threw above.\n const fallbackAdminPwd = isProduction ? generateDerivedPassword() : DEMO_DERIVED_PASSWORD\n const fallbackEmployeePwd = isProduction ? generateDerivedPassword() : DEMO_DERIVED_PASSWORD\n const adminPasswordPlain = envAdminPwd ?? fallbackAdminPwd\n const employeePasswordPlain = envEmployeePwd ?? fallbackEmployeePwd\n const adminPasswordHash = await hash(adminPasswordPlain, 10)\n const employeePasswordHash = await hash(employeePasswordPlain, 10)\n addUniqueBaseUser(baseUsers, {\n email: adminEmail,\n roles: ['admin'],\n passwordHash: adminPasswordHash,\n generatedPassword: envAdminPwd ? null : adminPasswordPlain,\n })\n addUniqueBaseUser(baseUsers, {\n email: employeeEmail,\n roles: ['employee'],\n passwordHash: employeePasswordHash,\n generatedPassword: envEmployeePwd ? null : employeePasswordPlain,\n })\n }\n const passwordHash = await resolvePasswordHash(primaryUser)\n\n await em.transactional(async (tem) => {\n const tenant = tem.create(Tenant, {\n name: options.orgName,\n isActive: true,\n createdAt: new Date(),\n updatedAt: new Date(),\n })\n tem.persist(tenant)\n await tem.flush()\n\n const organization = tem.create(Organization, {\n name: options.orgName,\n slug: options.orgSlug ?? null,\n tenant,\n isActive: true,\n depth: 0,\n ancestorIds: [],\n childIds: [],\n descendantIds: [],\n logoPreserveAspectRatio: false,\n createdAt: new Date(),\n updatedAt: new Date(),\n })\n tem.persist(organization)\n await tem.flush()\n\n tenantId = String(tenant.id)\n organizationId = String(organization.id)\n const roleTenantId = tenantId\n\n if (isTenantDataEncryptionEnabled()) {\n try {\n const kms = createKmsService()\n if (kms.isHealthy()) {\n if (isEncryptionDebugEnabled()) {\n logger.info('Provisioning tenant DEK', { tenantId: String(tenant.id) })\n }\n await kms.createTenantDek(String(tenant.id))\n if (isEncryptionDebugEnabled()) {\n logger.info('Created tenant DEK during setup', { tenantId: String(tenant.id) })\n }\n } else {\n if (isEncryptionDebugEnabled()) {\n logger.warn('KMS not healthy, skipping tenant DEK creation', { tenantId: String(tenant.id) })\n }\n }\n } catch (err) {\n if (isEncryptionDebugEnabled()) {\n logger.warn('Failed to create tenant DEK', { err })\n }\n }\n }\n\n await ensureRolesInContext(tem, roleNames, roleTenantId)\n await tem.flush()\n\n if (isTenantDataEncryptionEnabled()) {\n // System-scoped maps are resolved from module code, never from a tenant row.\n // Persisting one here would make the tenant-scoped encryption CLIs believe they\n // own that entity and re-wrap its `system:<entityId>` ciphertext under the tenant\n // DEK, which runtime decryption can no longer read.\n for (const spec of defaultEncryptionMaps) {\n if (spec.keyScope === 'system') continue\n const existing = await findOneWithDecryption(tem, EncryptionMap, { entityId: spec.entityId, tenantId: tenant.id, organizationId: organization.id, deletedAt: null }, {}, { tenantId: String(tenant.id), organizationId: String(organization.id) })\n if (!existing) {\n tem.persist(tem.create(EncryptionMap, {\n entityId: spec.entityId,\n tenantId: tenant.id,\n organizationId: organization.id,\n fieldsJson: spec.fields,\n isActive: true,\n createdAt: new Date(),\n updatedAt: new Date(),\n }))\n } else {\n existing.fieldsJson = spec.fields\n existing.isActive = true\n }\n }\n await tem.flush()\n }\n })\n\n await em.transactional(async (tem) => {\n if (!tenantId || !organizationId) return\n const roleTenantId = tenantId\n const encryptionService = isTenantDataEncryptionEnabled()\n ? new TenantDataEncryptionService(tem as any, { kms: createKmsService() })\n : null\n if (encryptionService) {\n await encryptionService.invalidateMap('auth:user', String(tenantId), String(organizationId))\n await encryptionService.invalidateMap('auth:user', String(tenantId), null)\n }\n\n for (const base of baseUsers) {\n const resolvedPasswordHash = base.passwordHash ?? passwordHash\n let user = await findOneWithDecryption(tem, User, { email: base.email }, {}, { tenantId: tenantId ?? null, organizationId: organizationId ?? null })\n const confirm = primaryUser.confirm ?? true\n const encryptedPayload = encryptionService\n ? await encryptionService.encryptEntityPayload('auth:user', { email: base.email }, tenantId, organizationId)\n : { email: base.email, emailHash: computeEmailHash(base.email) }\n if (user) {\n user.passwordHash = resolvedPasswordHash\n user.organizationId = organizationId\n user.tenantId = tenantId\n if (isTenantDataEncryptionEnabled()) {\n user.email = encryptedPayload.email as any\n user.emailHash = (encryptedPayload as any).emailHash ?? computeEmailHash(base.email)\n }\n if (base.name) user.name = base.name\n if (confirm) user.isConfirmed = true\n tem.persist(user)\n userSnapshots.push({ user, roles: base.roles, created: false, generatedPassword: base.generatedPassword ?? null })\n } else {\n user = tem.create(User, {\n email: (encryptedPayload as any).email ?? base.email,\n emailHash: isTenantDataEncryptionEnabled() ? (encryptedPayload as any).emailHash ?? computeEmailHash(base.email) : undefined,\n passwordHash: resolvedPasswordHash,\n organizationId,\n tenantId,\n name: base.name ?? undefined,\n isConfirmed: confirm,\n createdAt: new Date(),\n })\n tem.persist(user)\n userSnapshots.push({ user, roles: base.roles, created: true, generatedPassword: base.generatedPassword ?? null })\n }\n await tem.flush()\n for (const roleName of base.roles) {\n const role = await findRoleByNameOrFail(tem, roleName, roleTenantId)\n const existingLink = await findOneWithDecryption(tem, UserRole, { user, role }, {}, { tenantId: tenantId ?? null, organizationId: null })\n if (!existingLink) tem.persist(tem.create(UserRole, { user, role, createdAt: new Date() }))\n }\n await tem.flush()\n }\n })\n }\n\n if (!tenantId || !organizationId) {\n throw new Error('SETUP_FAILED')\n }\n\n if (!reusedExistingUser) {\n await rebuildHierarchyForTenant(em, tenantId)\n }\n\n await ensureDefaultRoleAcls(em, tenantId, resolvedModules, { includeSuperadminRole })\n await deactivateDemoUsersIfSelfOnboardingEnabled(em)\n\n // Call module onTenantCreated hooks\n for (const mod of resolvedModules) {\n if (mod.setup?.onTenantCreated) {\n await mod.setup.onTenantCreated({ em, tenantId, organizationId })\n }\n }\n\n return {\n tenantId,\n organizationId,\n users: userSnapshots,\n reusedExistingUser,\n }\n}\n\nfunction resolvePrimaryName(input: PrimaryUserInput): string | null {\n if (input.displayName && input.displayName.trim()) return input.displayName.trim()\n const parts = [input.firstName, input.lastName].map((value) => value?.trim()).filter(Boolean)\n if (parts.length) return parts.join(' ')\n return null\n}\n\nfunction readEnvValue(key: string): string | undefined {\n const value = process.env[key]\n if (typeof value !== 'string') return undefined\n const trimmed = value.trim()\n return trimmed.length > 0 ? trimmed : undefined\n}\n\nfunction addUniqueBaseUser(\n baseUsers: Array<{ email: string; roles: string[]; name?: string | null; passwordHash?: string | null; generatedPassword?: string | null }>,\n entry: { email: string; roles: string[]; name?: string | null; passwordHash?: string | null; generatedPassword?: string | null },\n) {\n if (!entry.email) return\n const normalized = entry.email.toLowerCase()\n if (baseUsers.some((user) => user.email.toLowerCase() === normalized)) return\n baseUsers.push(entry)\n}\n\n/**\n * Well-known demo password seeded for derived admin@/employee@ accounts in\n * non-production (`NODE_ENV !== 'production'`) when no env override is set.\n * Keeps the documented `yarn dev` / `mercato init` DX predictable. Never used\n * in production: the production branch either consumes env-supplied values or\n * falls back to `generateDerivedPassword()` so credentials remain non-guessable.\n */\nconst DEMO_DERIVED_PASSWORD = 'secret'\n\n/**\n * Generate a 16-character base64url password (96 bits of entropy) for a derived\n * demo user in production when no env override is provided AND the caller\n * explicitly opted in via `allowDemoDerivedPasswords`. Surfaced via the\n * `users[].generatedPassword` snapshot so CLI callers can print it to the\n * operator \u2014 there is no other recovery path for these credentials.\n */\nfunction generateDerivedPassword(): string {\n return randomBytes(12).toString('base64url')\n}\n\nfunction isDemoModeEnabled(): boolean {\n const parsed = parseBooleanToken(process.env.DEMO_MODE ?? '')\n return parsed === false ? false : true\n}\n\nfunction shouldKeepDemoSuperadminDuringInit(): boolean {\n if (process.env.OM_INIT_FLOW !== 'true') return false\n if (!readEnvValue('OM_INIT_SUPERADMIN_EMAIL')) return false\n return isDemoModeEnabled()\n}\n\nasync function resolvePasswordHash(input: PrimaryUserInput): Promise<string | null> {\n if (typeof input.hashedPassword === 'string') return input.hashedPassword\n if (input.password) return hash(input.password, 10)\n return null\n}\n\nexport async function ensureDefaultRoleAcls(\n em: EntityManager,\n tenantId: string,\n modules: Module[],\n options: { includeSuperadminRole?: boolean } = {},\n) {\n const includeSuperadminRole = options.includeSuperadminRole ?? true\n const roleTenantId = normalizeTenantId(tenantId) ?? null\n const superadminRole = includeSuperadminRole ? await findRoleByName(em, 'superadmin', roleTenantId) : null\n const adminRole = await findRoleByName(em, 'admin', roleTenantId)\n const employeeRole = await findRoleByName(em, 'employee', roleTenantId)\n\n // Merge features from all enabled modules' setup configs\n const builtInRoles = ['superadmin', 'admin', 'employee'] as const\n const superadminFeatures: string[] = []\n const adminFeatures: string[] = []\n const employeeFeatures: string[] = []\n const customRoleFeatures = new Map<string, string[]>()\n\n for (const mod of modules) {\n const roleFeatures = mod.setup?.defaultRoleFeatures\n if (!roleFeatures) continue\n if (roleFeatures.superadmin) superadminFeatures.push(...roleFeatures.superadmin)\n if (roleFeatures.admin) adminFeatures.push(...roleFeatures.admin)\n if (roleFeatures.employee) employeeFeatures.push(...roleFeatures.employee)\n\n // Collect features for custom roles (any key not in builtInRoles)\n for (const [roleName, features] of Object.entries(roleFeatures)) {\n if ((builtInRoles as readonly string[]).includes(roleName)) continue\n if (!Array.isArray(features)) continue\n const existing = customRoleFeatures.get(roleName) ?? []\n existing.push(...features)\n customRoleFeatures.set(roleName, existing)\n }\n }\n\n logger.info('Seeded default role features', {\n superadmin: superadminFeatures,\n admin: adminFeatures,\n employee: employeeFeatures,\n ...(customRoleFeatures.size > 0\n ? Object.fromEntries(customRoleFeatures)\n : {}),\n })\n\n if (includeSuperadminRole && superadminRole) {\n await ensureRoleAclFor(em, superadminRole, tenantId, superadminFeatures, { isSuperAdmin: true })\n }\n if (adminRole) {\n await ensureRoleAclFor(em, adminRole, tenantId, adminFeatures)\n }\n if (employeeRole) {\n await ensureRoleAclFor(em, employeeRole, tenantId, employeeFeatures)\n }\n\n // Seed ACLs for custom roles defined by app modules.\n // NOTE: Custom roles may not exist yet if they are created in seedDefaults\n // (which runs after this function). In that case, use ensureCustomRoleAcls()\n // after seedDefaults to pick them up.\n for (const [roleName, features] of customRoleFeatures) {\n const role = await findRoleByName(em, roleName, roleTenantId)\n if (role) {\n await ensureRoleAclFor(em, role, tenantId, features)\n }\n }\n}\n\n/**\n * Seed ACLs for custom roles defined in module defaultRoleFeatures.\n * Call this AFTER seedDefaults to pick up roles created by app modules.\n * Safe to call multiple times \u2014 ensureRoleAclFor merges features idempotently.\n */\nexport async function ensureCustomRoleAcls(\n em: EntityManager,\n tenantId: string,\n modules?: Module[],\n): Promise<void> {\n const resolvedModules = modules ?? tryGetModules()\n const roleTenantId = normalizeTenantId(tenantId) ?? null\n const builtInRoles = ['superadmin', 'admin', 'employee']\n const customRoleFeatures = new Map<string, string[]>()\n\n for (const mod of resolvedModules) {\n const roleFeatures = mod.setup?.defaultRoleFeatures\n if (!roleFeatures) continue\n for (const [roleName, features] of Object.entries(roleFeatures)) {\n if (builtInRoles.includes(roleName)) continue\n if (!Array.isArray(features)) continue\n const existing = customRoleFeatures.get(roleName) ?? []\n existing.push(...features)\n customRoleFeatures.set(roleName, existing)\n }\n }\n\n if (customRoleFeatures.size === 0) return\n\n let seeded = 0\n for (const [roleName, features] of customRoleFeatures) {\n const role = await findRoleByName(em, roleName, roleTenantId)\n if (role) {\n await ensureRoleAclFor(em, role, tenantId, features)\n seeded++\n }\n }\n if (seeded > 0) {\n logger.info('Seeded custom role ACLs', { seeded })\n }\n}\n\nasync function ensureRoleAclFor(\n em: EntityManager,\n role: Role,\n tenantId: string,\n features: string[],\n options: { isSuperAdmin?: boolean } = {},\n) {\n // Deduplicated on the create path too, not only on merge. `ensureDefaultRoleAcls` concatenates\n // every enabled module's declared features, and two modules legitimately declare the same\n // grant (the example module asks for `payment_gateways.view`, and so does that module itself),\n // so a first init used to store the string twice while the second run silently collapsed it.\n // Same list, two shapes, depending only on how many times setup had run.\n const uniqueFeatures = Array.from(new Set(features))\n const existing = await findOneWithDecryption(em, RoleAcl, { role, tenantId }, {}, { tenantId, organizationId: null })\n if (!existing) {\n const acl = em.create(RoleAcl, {\n role,\n tenantId,\n featuresJson: uniqueFeatures,\n isSuperAdmin: !!options.isSuperAdmin,\n createdAt: new Date(),\n })\n await em.persist(acl).flush()\n return\n }\n const currentFeatures = Array.isArray(existing.featuresJson) ? existing.featuresJson : []\n const merged = Array.from(new Set([...currentFeatures, ...uniqueFeatures]))\n const changed =\n merged.length !== currentFeatures.length ||\n merged.some((value, index) => value !== currentFeatures[index])\n if (changed) existing.featuresJson = merged\n if (options.isSuperAdmin && !existing.isSuperAdmin) {\n existing.isSuperAdmin = true\n }\n if (changed || options.isSuperAdmin) {\n await em.persist(existing).flush()\n }\n}\n\n/**\n * Neutralizes every demo account the setup path may have seeded\n * (superadmin, admin, employee \u2014 honoring OM_INIT_*_EMAIL overrides)\n * when SELF_SERVICE_ONBOARDING_ENABLED is on and the operator did not\n * opt in to keeping demo credentials via shouldKeepDemoSuperadminDuringInit.\n *\n * Each user is processed in its own try/catch so a single failure (e.g.\n * decryption error on a legacy row) does not skip the remaining accounts.\n *\n * @internal Exported for tests; not part of the public auth API.\n */\nexport async function deactivateDemoUsersIfSelfOnboardingEnabled(em: EntityManager) {\n if (process.env.SELF_SERVICE_ONBOARDING_ENABLED !== 'true') return\n if (shouldKeepDemoSuperadminDuringInit()) return\n for (const { role, email } of resolveDemoUserEmails()) {\n try {\n const user = await findOneWithDecryption(\n em,\n User,\n { email },\n {},\n { tenantId: null, organizationId: null },\n )\n if (!user) continue\n let dirty = false\n if (user.passwordHash) {\n user.passwordHash = null\n dirty = true\n }\n if (user.isConfirmed !== false) {\n user.isConfirmed = false\n dirty = true\n }\n if (dirty) {\n await em.persist(user).flush()\n }\n } catch (error) {\n logger.error('Failed to deactivate demo user', { role, email, err: error })\n }\n }\n}\n\n/**\n * @deprecated Renamed to {@link deactivateDemoUsersIfSelfOnboardingEnabled}\n * because the helper now neutralizes admin/employee demo accounts in addition\n * to superadmin (security tracker finding #5). Kept as an internal alias to\n * avoid breaking any out-of-tree caller that imported the old name; will be\n * removed in a future major.\n */\nconst deactivateDemoSuperAdminIfSelfOnboardingEnabled = deactivateDemoUsersIfSelfOnboardingEnabled\n\n/** Try to get modules from runtime registry; returns empty array if not yet registered. */\nfunction tryGetModules(): Module[] {\n try {\n const { getModules } = require('@open-mercato/shared/lib/modules/registry')\n return getModules()\n } catch {\n return []\n }\n}\n"],
5
- "mappings": "AAAA,SAAS,YAAY;AACrB,SAAS,mBAAmB;AAE5B,SAAS,MAAM,SAAS,MAAM,gBAAgB;AAC9C,SAAS,QAAQ,oBAAoB;AACrC,SAAS,iCAAiC;AAC1C,SAAS,yBAAyB;AAClC,SAAS,kBAAkB,6BAA6B;AACxD,SAAS,gCAA6C;AACtD,SAAS,0BAA0B,qCAAqC;AACxE,SAAS,qBAAqB;AAC9B,SAAS,wBAAwB;AACjC,SAAS,mCAAmC;AAC5C,SAAS,uBAAuB,0BAA0B;AAC1D,SAAS,yBAAyB;AAClC,SAAS,oBAAoB;AAE7B,MAAM,SAAS,aAAa,MAAM,EAAE,MAAM,EAAE,WAAW,QAAQ,CAAC;AAEhE,MAAM,qBAAqB,CAAC,YAAY,SAAS,YAAY;AAC7D,MAAM,wBAAwB;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;AACrD,QAAI;AACF,YAAM,OAAO,MAAM;AAAA,QACjB;AAAA,QACA;AAAA,QACA,EAAE,MAAM;AAAA,QACR,CAAC;AAAA,QACD,EAAE,UAAU,MAAM,gBAAgB,KAAK;AAAA,MACzC;AACA,UAAI,CAAC,KAAM;AACX,UAAI,QAAQ;AACZ,UAAI,KAAK,cAAc;AACrB,aAAK,eAAe;AACpB,gBAAQ;AAAA,MACV;AACA,UAAI,KAAK,gBAAgB,OAAO;AAC9B,aAAK,cAAc;AACnB,gBAAQ;AAAA,MACV;AACA,UAAI,OAAO;AACT,cAAM,GAAG,QAAQ,IAAI,EAAE,MAAM;AAAA,MAC/B;AAAA,IACF,SAAS,OAAO;AACd,aAAO,MAAM,kCAAkC,EAAE,MAAM,OAAO,KAAK,MAAM,CAAC;AAAA,IAC5E;AAAA,EACF;AACF;AASA,MAAM,kDAAkD;AAGxD,SAAS,gBAA0B;AACjC,MAAI;AACF,UAAM,EAAE,WAAW,IAAI,QAAQ,2CAA2C;AAC1E,WAAO,WAAW;AAAA,EACpB,QAAQ;AACN,WAAO,CAAC;AAAA,EACV;AACF;",
4
+ "sourcesContent": ["import { hash } from 'bcryptjs'\nimport { randomBytes } from 'node:crypto'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport { Role, RoleAcl, User, UserRole } from '@open-mercato/core/modules/auth/data/entities'\nimport { Tenant, Organization } from '@open-mercato/core/modules/directory/data/entities'\nimport { rebuildHierarchyForTenant } from '@open-mercato/core/modules/directory/lib/hierarchy'\nimport { normalizeTenantId } from './tenantAccess'\nimport { computeEmailHash, emailHashLookupValues } from '@open-mercato/core/modules/auth/lib/emailHash'\nimport { getDefaultEncryptionMaps, type Module } from '@open-mercato/shared/modules/registry'\nimport { isEncryptionDebugEnabled, isTenantDataEncryptionEnabled } from '@open-mercato/shared/lib/encryption/toggles'\nimport { EncryptionMap } from '@open-mercato/core/modules/entities/data/entities'\nimport { createKmsService } from '@open-mercato/shared/lib/encryption/kms'\nimport { TenantDataEncryptionService } from '@open-mercato/shared/lib/encryption/tenantDataEncryptionService'\nimport { findOneWithDecryption, findWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { parseBooleanToken } from '@open-mercato/shared/lib/boolean'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('auth').child({ component: 'setup' })\n\nconst DEFAULT_ROLE_NAMES = ['employee', 'admin', 'superadmin'] as const\nconst DEMO_SUPERADMIN_EMAIL = 'superadmin@acme.com'\nconst DEFAULT_DERIVED_EMAIL_DOMAIN = DEMO_SUPERADMIN_EMAIL.split('@')[1] ?? 'acme.com'\n\nexport type EnsureRolesOptions = {\n roleNames?: string[]\n tenantId?: string\n}\n\nasync function ensureRolesInContext(\n em: EntityManager,\n roleNames: string[],\n tenantId: string,\n) {\n for (const name of roleNames) {\n const existing = await findOneWithDecryption(em, Role, { name, tenantId }, {}, { tenantId, organizationId: null })\n if (existing) continue\n em.persist(em.create(Role, { name, tenantId, minActiveHolders: name === 'admin' ? 1 : 0, createdAt: new Date() }))\n }\n}\n\nexport async function ensureRoles(em: EntityManager, options: EnsureRolesOptions = {}) {\n const roleNames = options.roleNames ?? [...DEFAULT_ROLE_NAMES]\n const tenantId = normalizeTenantId(options.tenantId ?? null)\n if (!tenantId) {\n throw new Error('ensureRoles requires a tenantId \u2014 global roles are not supported')\n }\n await em.transactional(async (tem) => {\n await ensureRolesInContext(tem, roleNames, tenantId)\n await tem.flush()\n })\n}\n\nasync function findRoleByName(\n em: EntityManager,\n name: string,\n tenantId: string | null,\n): Promise<Role | null> {\n const normalizedTenant = normalizeTenantId(tenantId ?? null) ?? null\n return findOneWithDecryption(em, Role, { name, tenantId: normalizedTenant }, {}, { tenantId: normalizedTenant, organizationId: null })\n}\n\nasync function findRoleByNameOrFail(\n em: EntityManager,\n name: string,\n tenantId: string | null,\n): Promise<Role> {\n const role = await findRoleByName(em, name, tenantId)\n if (!role) throw new Error(`ROLE_NOT_FOUND:${name}`)\n return role\n}\n\ntype PrimaryUserInput = {\n email: string\n password?: string\n hashedPassword?: string | null\n firstName?: string | null\n lastName?: string | null\n displayName?: string | null\n confirm?: boolean\n}\n\nconst DERIVED_EMAIL_ENV = {\n admin: 'OM_INIT_ADMIN_EMAIL',\n employee: 'OM_INIT_EMPLOYEE_EMAIL',\n} as const\n\nexport type DemoUserRole = 'superadmin' | 'admin' | 'employee'\nexport type DemoUserEmail = { role: DemoUserRole; email: string }\n\n/**\n * Returns the canonical list of demo user emails the setup path may have\n * seeded. Honors OM_INIT_ADMIN_EMAIL / OM_INIT_EMPLOYEE_EMAIL exactly the\n * same way the derived-user seeding branch does, so the deactivation loop\n * never drifts from the seeding loop.\n *\n * Pure function \u2014 no side effects, safe to unit-test in isolation.\n *\n * @internal Exported for tests; not part of the public auth API.\n */\nexport function resolveDemoUserEmails(): DemoUserEmail[] {\n const adminEmail = readEnvValue(DERIVED_EMAIL_ENV.admin) ?? `admin@${DEFAULT_DERIVED_EMAIL_DOMAIN}`\n const employeeEmail = readEnvValue(DERIVED_EMAIL_ENV.employee) ?? `employee@${DEFAULT_DERIVED_EMAIL_DOMAIN}`\n return [\n { role: 'superadmin', email: DEMO_SUPERADMIN_EMAIL },\n { role: 'admin', email: adminEmail },\n { role: 'employee', email: employeeEmail },\n ]\n}\n\nexport type SetupInitialTenantOptions = {\n orgName: string\n primaryUser: PrimaryUserInput\n roleNames?: string[]\n includeDerivedUsers?: boolean\n failIfUserExists?: boolean\n primaryUserRoles?: string[]\n includeSuperadminRole?: boolean\n /** Optional list of enabled modules. When provided, module setup hooks are called. */\n modules?: Module[]\n /**\n * Optional global slug to persist on the new Organization. When set, a\n * pre-flight uniqueness check across all tenants throws OrgSlugExistsError\n * on collision so scriptable callers can fail loudly instead of silently\n * reusing or clobbering an existing organization.\n */\n orgSlug?: string\n /**\n * Opt-in flag that allows seeding the derived admin/employee accounts when\n * the OM_INIT_ADMIN_PASSWORD / OM_INIT_EMPLOYEE_PASSWORD env vars are unset.\n *\n * - In non-production (`NODE_ENV !== 'production'`): the demo accounts are\n * seeded with the well-known `'secret'` password so local dev workflows\n * (e.g. `mercato init`) stay predictable for developers.\n * - In production: the fallback uses a randomly generated 96-bit password\n * (printed once by the CLI) so an operator who deliberately opts in still\n * avoids the historical hardcoded credential. When this flag is false/unset\n * in production and the env vars are missing, `DerivedUserPasswordRequiredError`\n * is thrown instead of silently seeding any account.\n */\n allowDemoDerivedPasswords?: boolean\n}\n\nexport class OrgSlugExistsError extends Error {\n constructor(public readonly slug: string) {\n super(`ORG_SLUG_EXISTS: an organization with slug \"${slug}\" already exists`)\n this.name = 'OrgSlugExistsError'\n }\n}\n\nexport class DerivedUserPasswordRequiredError extends Error {\n constructor(public readonly missing: string[]) {\n super(\n `DERIVED_USER_PASSWORD_REQUIRED: missing ${missing.join(', ')} (set the env vars, pass allowDemoDerivedPasswords: true / --include-demo-users in non-production, or disable derived user seeding)`,\n )\n this.name = 'DerivedUserPasswordRequiredError'\n }\n}\n\nexport type SetupInitialTenantResult = {\n tenantId: string\n organizationId: string\n users: Array<{ user: User; roles: string[]; created: boolean; generatedPassword?: string | null }>\n reusedExistingUser: boolean\n}\n\nexport async function setupInitialTenant(\n em: EntityManager,\n options: SetupInitialTenantOptions,\n): Promise<SetupInitialTenantResult> {\n const {\n primaryUser,\n includeDerivedUsers = true,\n failIfUserExists = false,\n primaryUserRoles,\n includeSuperadminRole = true,\n } = options\n const primaryRolesInput = primaryUserRoles && primaryUserRoles.length ? primaryUserRoles : ['superadmin']\n const primaryRoles = includeSuperadminRole\n ? primaryRolesInput\n : primaryRolesInput.filter((role) => role !== 'superadmin')\n if (primaryRoles.length === 0) {\n throw new Error('PRIMARY_ROLES_REQUIRED')\n }\n const defaultRoleNames = options.roleNames ?? [...DEFAULT_ROLE_NAMES]\n const resolvedRoleNames = includeSuperadminRole\n ? defaultRoleNames\n : defaultRoleNames.filter((role) => role !== 'superadmin')\n const roleNames = Array.from(new Set([...resolvedRoleNames, ...primaryRoles]))\n const resolvedModules = options.modules ?? tryGetModules()\n const defaultEncryptionMaps = getDefaultEncryptionMaps(resolvedModules)\n\n const mainEmail = primaryUser.email\n const existingUserByHash = await findOneWithDecryption(\n em,\n User,\n { emailHash: { $in: emailHashLookupValues(mainEmail) }, deletedAt: null },\n {},\n { tenantId: null, organizationId: null },\n )\n const existingUser = existingUserByHash ?? await findOneWithDecryption(\n em,\n User,\n { email: mainEmail, deletedAt: null },\n {},\n { tenantId: null, organizationId: null },\n )\n if (existingUser && failIfUserExists) {\n throw new Error('USER_EXISTS')\n }\n\n if (options.orgSlug) {\n const slugConflict = await findOneWithDecryption(\n em,\n Organization,\n { slug: options.orgSlug },\n {},\n { tenantId: null, organizationId: null },\n )\n if (slugConflict) {\n throw new OrgSlugExistsError(options.orgSlug)\n }\n }\n\n let tenantId: string | undefined\n let organizationId: string | undefined\n let reusedExistingUser = false\n const userSnapshots: Array<{ user: User; roles: string[]; created: boolean; generatedPassword?: string | null }> = []\n\n await em.transactional(async (tem) => {\n if (!existingUser) return\n reusedExistingUser = true\n tenantId = existingUser.tenantId ? String(existingUser.tenantId) : undefined\n organizationId = existingUser.organizationId ? String(existingUser.organizationId) : undefined\n const roleTenantId = normalizeTenantId(existingUser.tenantId ?? null) ?? null\n if (!roleTenantId) {\n throw new Error('Cannot reuse a user without a tenantId \u2014 global roles are not supported')\n }\n\n await ensureRolesInContext(tem, roleNames, roleTenantId)\n await tem.flush()\n\n const requiredRoleSet = new Set([...roleNames, ...primaryRoles])\n const links = await findWithDecryption(\n tem,\n UserRole,\n { user: existingUser },\n { populate: ['role'] },\n { tenantId: roleTenantId, organizationId: null },\n )\n const currentRoles = new Set(links.map((link) => link.role.name))\n for (const roleName of requiredRoleSet) {\n if (!currentRoles.has(roleName)) {\n const role = await findRoleByNameOrFail(tem, roleName, roleTenantId)\n tem.persist(tem.create(UserRole, { user: existingUser, role, createdAt: new Date() }))\n }\n }\n await tem.flush()\n const roles = Array.from(new Set([...currentRoles, ...roleNames]))\n userSnapshots.push({ user: existingUser, roles, created: false })\n })\n\n if (!existingUser) {\n const baseUsers: Array<{\n email: string\n roles: string[]\n name?: string | null\n passwordHash?: string | null\n generatedPassword?: string | null\n }> = [\n { email: primaryUser.email, roles: primaryRoles, name: resolvePrimaryName(primaryUser) },\n ]\n if (includeDerivedUsers) {\n const adminOverride = readEnvValue(DERIVED_EMAIL_ENV.admin)\n const employeeOverride = readEnvValue(DERIVED_EMAIL_ENV.employee)\n const adminEmail = adminOverride ?? `admin@${DEFAULT_DERIVED_EMAIL_DOMAIN}`\n const employeeEmail = employeeOverride ?? `employee@${DEFAULT_DERIVED_EMAIL_DOMAIN}`\n const envAdminPwd = readEnvValue('OM_INIT_ADMIN_PASSWORD')\n const envEmployeePwd = readEnvValue('OM_INIT_EMPLOYEE_PASSWORD')\n const isProduction = process.env.NODE_ENV === 'production'\n const allowDemo = options.allowDemoDerivedPasswords === true\n if (isProduction && !allowDemo) {\n const missing: string[] = []\n if (!envAdminPwd) missing.push('OM_INIT_ADMIN_PASSWORD')\n if (!envEmployeePwd) missing.push('OM_INIT_EMPLOYEE_PASSWORD')\n if (missing.length) {\n throw new DerivedUserPasswordRequiredError(missing)\n }\n }\n // In non-production, fall back to the well-known DEMO_DERIVED_PASSWORD so\n // local dev workflows stay predictable (admin@/employee@ login with the\n // documented demo password). In production we either have env-supplied\n // values, or \u2014 for opt-in --include-demo-users flows \u2014 we generate a\n // random one-time password and surface it via `generatedPassword` so the\n // operator can capture it. Production callers without env vars and\n // without the opt-in already threw above.\n const fallbackAdminPwd = isProduction ? generateDerivedPassword() : DEMO_DERIVED_PASSWORD\n const fallbackEmployeePwd = isProduction ? generateDerivedPassword() : DEMO_DERIVED_PASSWORD\n const adminPasswordPlain = envAdminPwd ?? fallbackAdminPwd\n const employeePasswordPlain = envEmployeePwd ?? fallbackEmployeePwd\n const adminPasswordHash = await hash(adminPasswordPlain, 10)\n const employeePasswordHash = await hash(employeePasswordPlain, 10)\n addUniqueBaseUser(baseUsers, {\n email: adminEmail,\n roles: ['admin'],\n passwordHash: adminPasswordHash,\n generatedPassword: envAdminPwd ? null : adminPasswordPlain,\n })\n addUniqueBaseUser(baseUsers, {\n email: employeeEmail,\n roles: ['employee'],\n passwordHash: employeePasswordHash,\n generatedPassword: envEmployeePwd ? null : employeePasswordPlain,\n })\n }\n const passwordHash = await resolvePasswordHash(primaryUser)\n\n await em.transactional(async (tem) => {\n const tenant = tem.create(Tenant, {\n name: options.orgName,\n isActive: true,\n createdAt: new Date(),\n updatedAt: new Date(),\n })\n tem.persist(tenant)\n await tem.flush()\n\n const organization = tem.create(Organization, {\n name: options.orgName,\n slug: options.orgSlug ?? null,\n tenant,\n isActive: true,\n depth: 0,\n ancestorIds: [],\n childIds: [],\n descendantIds: [],\n logoPreserveAspectRatio: false,\n createdAt: new Date(),\n updatedAt: new Date(),\n })\n tem.persist(organization)\n await tem.flush()\n\n tenantId = String(tenant.id)\n organizationId = String(organization.id)\n const roleTenantId = tenantId\n\n if (isTenantDataEncryptionEnabled()) {\n try {\n const kms = createKmsService()\n if (kms.isHealthy()) {\n if (isEncryptionDebugEnabled()) {\n logger.info('Provisioning tenant DEK', { tenantId: String(tenant.id) })\n }\n await kms.createTenantDek(String(tenant.id))\n if (isEncryptionDebugEnabled()) {\n logger.info('Created tenant DEK during setup', { tenantId: String(tenant.id) })\n }\n } else {\n if (isEncryptionDebugEnabled()) {\n logger.warn('KMS not healthy, skipping tenant DEK creation', { tenantId: String(tenant.id) })\n }\n }\n } catch (err) {\n if (isEncryptionDebugEnabled()) {\n logger.warn('Failed to create tenant DEK', { err })\n }\n }\n }\n\n await ensureRolesInContext(tem, roleNames, roleTenantId)\n await tem.flush()\n\n if (isTenantDataEncryptionEnabled()) {\n // System-scoped maps are resolved from module code, never from a tenant row.\n // Persisting one here would make the tenant-scoped encryption CLIs believe they\n // own that entity and re-wrap its `system:<entityId>` ciphertext under the tenant\n // DEK, which runtime decryption can no longer read.\n for (const spec of defaultEncryptionMaps) {\n if (spec.keyScope === 'system') continue\n const existing = await findOneWithDecryption(tem, EncryptionMap, { entityId: spec.entityId, tenantId: tenant.id, organizationId: organization.id, deletedAt: null }, {}, { tenantId: String(tenant.id), organizationId: String(organization.id) })\n if (!existing) {\n tem.persist(tem.create(EncryptionMap, {\n entityId: spec.entityId,\n tenantId: tenant.id,\n organizationId: organization.id,\n fieldsJson: spec.fields,\n isActive: true,\n createdAt: new Date(),\n updatedAt: new Date(),\n }))\n } else {\n existing.fieldsJson = spec.fields\n existing.isActive = true\n }\n }\n await tem.flush()\n }\n })\n\n await em.transactional(async (tem) => {\n if (!tenantId || !organizationId) return\n const roleTenantId = tenantId\n const encryptionService = isTenantDataEncryptionEnabled()\n ? new TenantDataEncryptionService(tem as any, { kms: createKmsService() })\n : null\n if (encryptionService) {\n await encryptionService.invalidateMap('auth:user', String(tenantId), String(organizationId))\n await encryptionService.invalidateMap('auth:user', String(tenantId), null)\n }\n\n for (const base of baseUsers) {\n const resolvedPasswordHash = base.passwordHash ?? passwordHash\n let user = await findOneWithDecryption(tem, User, { email: base.email }, {}, { tenantId: tenantId ?? null, organizationId: organizationId ?? null })\n const confirm = primaryUser.confirm ?? true\n const encryptedPayload = encryptionService\n ? await encryptionService.encryptEntityPayload('auth:user', { email: base.email }, tenantId, organizationId)\n : { email: base.email, emailHash: computeEmailHash(base.email) }\n if (user) {\n user.passwordHash = resolvedPasswordHash\n user.organizationId = organizationId\n user.tenantId = tenantId\n if (isTenantDataEncryptionEnabled()) {\n user.email = encryptedPayload.email as any\n user.emailHash = (encryptedPayload as any).emailHash ?? computeEmailHash(base.email)\n }\n if (base.name) user.name = base.name\n if (confirm) user.isConfirmed = true\n tem.persist(user)\n userSnapshots.push({ user, roles: base.roles, created: false, generatedPassword: base.generatedPassword ?? null })\n } else {\n user = tem.create(User, {\n email: (encryptedPayload as any).email ?? base.email,\n emailHash: isTenantDataEncryptionEnabled() ? (encryptedPayload as any).emailHash ?? computeEmailHash(base.email) : undefined,\n passwordHash: resolvedPasswordHash,\n organizationId,\n tenantId,\n name: base.name ?? undefined,\n isConfirmed: confirm,\n createdAt: new Date(),\n })\n tem.persist(user)\n userSnapshots.push({ user, roles: base.roles, created: true, generatedPassword: base.generatedPassword ?? null })\n }\n await tem.flush()\n for (const roleName of base.roles) {\n const role = await findRoleByNameOrFail(tem, roleName, roleTenantId)\n const existingLink = await findOneWithDecryption(tem, UserRole, { user, role }, {}, { tenantId: tenantId ?? null, organizationId: null })\n if (!existingLink) tem.persist(tem.create(UserRole, { user, role, createdAt: new Date() }))\n }\n await tem.flush()\n }\n })\n }\n\n if (!tenantId || !organizationId) {\n throw new Error('SETUP_FAILED')\n }\n\n if (!reusedExistingUser) {\n await rebuildHierarchyForTenant(em, tenantId)\n }\n\n await ensureDefaultRoleAcls(em, tenantId, resolvedModules, { includeSuperadminRole })\n await deactivateDemoUsersIfSelfOnboardingEnabled(em)\n\n // Call module onTenantCreated hooks\n for (const mod of resolvedModules) {\n if (mod.setup?.onTenantCreated) {\n await mod.setup.onTenantCreated({ em, tenantId, organizationId })\n }\n }\n\n // Custom roles are often created inside onTenantCreated hooks, so they did not\n // exist yet when ensureDefaultRoleAcls ran above and were skipped there. Sync\n // again now that the hooks have had a chance to create them \u2014 idempotent, same\n // pattern as the `mercato auth sync-role-acls` CLI command.\n await ensureCustomRoleAcls(em, tenantId, resolvedModules)\n\n return {\n tenantId,\n organizationId,\n users: userSnapshots,\n reusedExistingUser,\n }\n}\n\nfunction resolvePrimaryName(input: PrimaryUserInput): string | null {\n if (input.displayName && input.displayName.trim()) return input.displayName.trim()\n const parts = [input.firstName, input.lastName].map((value) => value?.trim()).filter(Boolean)\n if (parts.length) return parts.join(' ')\n return null\n}\n\nfunction readEnvValue(key: string): string | undefined {\n const value = process.env[key]\n if (typeof value !== 'string') return undefined\n const trimmed = value.trim()\n return trimmed.length > 0 ? trimmed : undefined\n}\n\nfunction addUniqueBaseUser(\n baseUsers: Array<{ email: string; roles: string[]; name?: string | null; passwordHash?: string | null; generatedPassword?: string | null }>,\n entry: { email: string; roles: string[]; name?: string | null; passwordHash?: string | null; generatedPassword?: string | null },\n) {\n if (!entry.email) return\n const normalized = entry.email.toLowerCase()\n if (baseUsers.some((user) => user.email.toLowerCase() === normalized)) return\n baseUsers.push(entry)\n}\n\n/**\n * Well-known demo password seeded for derived admin@/employee@ accounts in\n * non-production (`NODE_ENV !== 'production'`) when no env override is set.\n * Keeps the documented `yarn dev` / `mercato init` DX predictable. Never used\n * in production: the production branch either consumes env-supplied values or\n * falls back to `generateDerivedPassword()` so credentials remain non-guessable.\n */\nconst DEMO_DERIVED_PASSWORD = 'secret'\n\n/**\n * Generate a 16-character base64url password (96 bits of entropy) for a derived\n * demo user in production when no env override is provided AND the caller\n * explicitly opted in via `allowDemoDerivedPasswords`. Surfaced via the\n * `users[].generatedPassword` snapshot so CLI callers can print it to the\n * operator \u2014 there is no other recovery path for these credentials.\n */\nfunction generateDerivedPassword(): string {\n return randomBytes(12).toString('base64url')\n}\n\nfunction isDemoModeEnabled(): boolean {\n const parsed = parseBooleanToken(process.env.DEMO_MODE ?? '')\n return parsed === false ? false : true\n}\n\nfunction shouldKeepDemoSuperadminDuringInit(): boolean {\n if (process.env.OM_INIT_FLOW !== 'true') return false\n if (!readEnvValue('OM_INIT_SUPERADMIN_EMAIL')) return false\n return isDemoModeEnabled()\n}\n\nasync function resolvePasswordHash(input: PrimaryUserInput): Promise<string | null> {\n if (typeof input.hashedPassword === 'string') return input.hashedPassword\n if (input.password) return hash(input.password, 10)\n return null\n}\n\nexport async function ensureDefaultRoleAcls(\n em: EntityManager,\n tenantId: string,\n modules: Module[],\n options: { includeSuperadminRole?: boolean } = {},\n) {\n const includeSuperadminRole = options.includeSuperadminRole ?? true\n const roleTenantId = normalizeTenantId(tenantId) ?? null\n const superadminRole = includeSuperadminRole ? await findRoleByName(em, 'superadmin', roleTenantId) : null\n const adminRole = await findRoleByName(em, 'admin', roleTenantId)\n const employeeRole = await findRoleByName(em, 'employee', roleTenantId)\n\n // Merge features from all enabled modules' setup configs\n const builtInRoles = ['superadmin', 'admin', 'employee'] as const\n const superadminFeatures: string[] = []\n const adminFeatures: string[] = []\n const employeeFeatures: string[] = []\n const customRoleFeatures = new Map<string, string[]>()\n\n for (const mod of modules) {\n const roleFeatures = mod.setup?.defaultRoleFeatures\n if (!roleFeatures) continue\n if (roleFeatures.superadmin) superadminFeatures.push(...roleFeatures.superadmin)\n if (roleFeatures.admin) adminFeatures.push(...roleFeatures.admin)\n if (roleFeatures.employee) employeeFeatures.push(...roleFeatures.employee)\n\n // Collect features for custom roles (any key not in builtInRoles)\n for (const [roleName, features] of Object.entries(roleFeatures)) {\n if ((builtInRoles as readonly string[]).includes(roleName)) continue\n if (!Array.isArray(features)) continue\n const existing = customRoleFeatures.get(roleName) ?? []\n existing.push(...features)\n customRoleFeatures.set(roleName, existing)\n }\n }\n\n logger.info('Seeded default role features', {\n superadmin: superadminFeatures,\n admin: adminFeatures,\n employee: employeeFeatures,\n ...(customRoleFeatures.size > 0\n ? Object.fromEntries(customRoleFeatures)\n : {}),\n })\n\n if (includeSuperadminRole && superadminRole) {\n await ensureRoleAclFor(em, superadminRole, tenantId, superadminFeatures, { isSuperAdmin: true })\n }\n if (adminRole) {\n await ensureRoleAclFor(em, adminRole, tenantId, adminFeatures)\n }\n if (employeeRole) {\n await ensureRoleAclFor(em, employeeRole, tenantId, employeeFeatures)\n }\n\n // Seed ACLs for custom roles defined by app modules.\n // NOTE: Custom roles may not exist yet if they are created in seedDefaults\n // (which runs after this function). In that case, use ensureCustomRoleAcls()\n // after seedDefaults to pick them up.\n for (const [roleName, features] of customRoleFeatures) {\n const role = await findRoleByName(em, roleName, roleTenantId)\n if (role) {\n await ensureRoleAclFor(em, role, tenantId, features)\n }\n }\n}\n\n/**\n * Seed ACLs for custom roles defined in module defaultRoleFeatures.\n * Call this AFTER seedDefaults to pick up roles created by app modules.\n * Safe to call multiple times \u2014 ensureRoleAclFor merges features idempotently.\n */\nexport async function ensureCustomRoleAcls(\n em: EntityManager,\n tenantId: string,\n modules?: Module[],\n): Promise<void> {\n const resolvedModules = modules ?? tryGetModules()\n const roleTenantId = normalizeTenantId(tenantId) ?? null\n const builtInRoles = ['superadmin', 'admin', 'employee']\n const customRoleFeatures = new Map<string, string[]>()\n\n for (const mod of resolvedModules) {\n const roleFeatures = mod.setup?.defaultRoleFeatures\n if (!roleFeatures) continue\n for (const [roleName, features] of Object.entries(roleFeatures)) {\n if (builtInRoles.includes(roleName)) continue\n if (!Array.isArray(features)) continue\n const existing = customRoleFeatures.get(roleName) ?? []\n existing.push(...features)\n customRoleFeatures.set(roleName, existing)\n }\n }\n\n if (customRoleFeatures.size === 0) return\n\n let seeded = 0\n for (const [roleName, features] of customRoleFeatures) {\n const role = await findRoleByName(em, roleName, roleTenantId)\n if (role) {\n await ensureRoleAclFor(em, role, tenantId, features)\n seeded++\n }\n }\n if (seeded > 0) {\n logger.info('Seeded custom role ACLs', { seeded })\n }\n}\n\nasync function ensureRoleAclFor(\n em: EntityManager,\n role: Role,\n tenantId: string,\n features: string[],\n options: { isSuperAdmin?: boolean } = {},\n) {\n // Deduplicated on the create path too, not only on merge. `ensureDefaultRoleAcls` concatenates\n // every enabled module's declared features, and two modules legitimately declare the same\n // grant (the example module asks for `payment_gateways.view`, and so does that module itself),\n // so a first init used to store the string twice while the second run silently collapsed it.\n // Same list, two shapes, depending only on how many times setup had run.\n const uniqueFeatures = Array.from(new Set(features))\n const existing = await findOneWithDecryption(em, RoleAcl, { role, tenantId }, {}, { tenantId, organizationId: null })\n if (!existing) {\n const acl = em.create(RoleAcl, {\n role,\n tenantId,\n featuresJson: uniqueFeatures,\n isSuperAdmin: !!options.isSuperAdmin,\n createdAt: new Date(),\n })\n await em.persist(acl).flush()\n return\n }\n const currentFeatures = Array.isArray(existing.featuresJson) ? existing.featuresJson : []\n const merged = Array.from(new Set([...currentFeatures, ...uniqueFeatures]))\n const changed =\n merged.length !== currentFeatures.length ||\n merged.some((value, index) => value !== currentFeatures[index])\n if (changed) existing.featuresJson = merged\n if (options.isSuperAdmin && !existing.isSuperAdmin) {\n existing.isSuperAdmin = true\n }\n if (changed || options.isSuperAdmin) {\n await em.persist(existing).flush()\n }\n}\n\n/**\n * Neutralizes every demo account the setup path may have seeded\n * (superadmin, admin, employee \u2014 honoring OM_INIT_*_EMAIL overrides)\n * when SELF_SERVICE_ONBOARDING_ENABLED is on and the operator did not\n * opt in to keeping demo credentials via shouldKeepDemoSuperadminDuringInit.\n *\n * Each user is processed in its own try/catch so a single failure (e.g.\n * decryption error on a legacy row) does not skip the remaining accounts.\n *\n * @internal Exported for tests; not part of the public auth API.\n */\nexport async function deactivateDemoUsersIfSelfOnboardingEnabled(em: EntityManager) {\n if (process.env.SELF_SERVICE_ONBOARDING_ENABLED !== 'true') return\n if (shouldKeepDemoSuperadminDuringInit()) return\n for (const { role, email } of resolveDemoUserEmails()) {\n try {\n const user = await findOneWithDecryption(\n em,\n User,\n { email },\n {},\n { tenantId: null, organizationId: null },\n )\n if (!user) continue\n let dirty = false\n if (user.passwordHash) {\n user.passwordHash = null\n dirty = true\n }\n if (user.isConfirmed !== false) {\n user.isConfirmed = false\n dirty = true\n }\n if (dirty) {\n await em.persist(user).flush()\n }\n } catch (error) {\n logger.error('Failed to deactivate demo user', { role, email, err: error })\n }\n }\n}\n\n/**\n * @deprecated Renamed to {@link deactivateDemoUsersIfSelfOnboardingEnabled}\n * because the helper now neutralizes admin/employee demo accounts in addition\n * to superadmin (security tracker finding #5). Kept as an internal alias to\n * avoid breaking any out-of-tree caller that imported the old name; will be\n * removed in a future major.\n */\nconst deactivateDemoSuperAdminIfSelfOnboardingEnabled = deactivateDemoUsersIfSelfOnboardingEnabled\n\n/** Try to get modules from runtime registry; returns empty array if not yet registered. */\nfunction tryGetModules(): Module[] {\n try {\n const { getModules } = require('@open-mercato/shared/lib/modules/registry')\n return getModules()\n } catch {\n return []\n }\n}\n"],
5
+ "mappings": "AAAA,SAAS,YAAY;AACrB,SAAS,m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,7 @@ const CONFIG_PASSTHROUGH_KEYS = [
14
14
  "formEditable",
15
15
  "listVisible",
16
16
  "indexed",
17
+ "encrypted",
17
18
  "priority",
18
19
  "editor",
19
20
  "input",
@@ -38,6 +39,11 @@ function normalizeValue(value) {
38
39
  function configEquals(a, b) {
39
40
  return JSON.stringify(normalizeValue(a ?? null)) === JSON.stringify(normalizeValue(b ?? null));
40
41
  }
42
+ function hasEncryptionEnabled(definition) {
43
+ const config = definition?.configJson;
44
+ if (!config || typeof config !== "object") return false;
45
+ return config.encrypted === true;
46
+ }
41
47
  async function ensureCustomFieldDefinitions(em, sets, scope) {
42
48
  let created = 0;
43
49
  let updated = 0;
@@ -65,6 +71,9 @@ async function ensureCustomFieldDefinitions(em, sets, scope) {
65
71
  const value = field[key];
66
72
  if (value !== void 0) configJson[key] = value;
67
73
  }
74
+ if (configJson.encrypted === void 0 && hasEncryptionEnabled(existing)) {
75
+ configJson.encrypted = true;
76
+ }
68
77
  if (!existing) {
69
78
  if (!scope.dryRun) {
70
79
  const createdDef = em.create(CustomFieldDef, {
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/entities/lib/field-definitions.ts"],
4
- "sourcesContent": ["import type { EntityManager } from '@mikro-orm/postgresql'\nimport { CustomFieldDef } from '../data/entities'\nimport type { CustomFieldDefinition } from '@open-mercato/shared/modules/entities'\n\nexport type FieldSetInput = {\n entity: string\n fields: CustomFieldDefinition[]\n source?: string\n}\n\nexport type EnsureFieldDefinitionsOptions = {\n organizationId: string | null\n tenantId: string | null\n dryRun?: boolean\n createOnly?: boolean\n}\n\nexport type EnsureFieldDefinitionsResult = {\n created: number\n updated: number\n unchanged: number\n}\n\nconst CONFIG_PASSTHROUGH_KEYS: Array<keyof CustomFieldDefinition> = [\n 'label',\n 'description',\n 'fieldset',\n 'fieldsets',\n 'group',\n 'options',\n 'optionsUrl',\n 'defaultValue',\n 'required',\n 'multi',\n 'filterable',\n 'formEditable',\n 'listVisible',\n 'indexed',\n 'priority',\n 'editor',\n 'input',\n 'relatedEntityId',\n 'dictionaryId',\n 'dictionaryInlineCreate',\n 'validation',\n 'maxAttachmentSizeMb',\n 'acceptExtensions',\n 'sourceMetadata',\n]\n\nfunction normalizeValue(value: unknown): unknown {\n if (Array.isArray(value)) return value.map((item) => normalizeValue(item))\n if (value && typeof value === 'object') {\n return Object.keys(value as Record<string, unknown>)\n .sort((a, b) => a.localeCompare(b))\n .reduce<Record<string, unknown>>((acc, key) => {\n acc[key] = normalizeValue((value as Record<string, unknown>)[key])\n return acc\n }, {})\n }\n return value\n}\n\nfunction configEquals(a: unknown, b: unknown): boolean {\n return JSON.stringify(normalizeValue(a ?? null)) === JSON.stringify(normalizeValue(b ?? null))\n}\n\nexport async function ensureCustomFieldDefinitions(\n em: EntityManager,\n sets: FieldSetInput[],\n scope: EnsureFieldDefinitionsOptions\n): Promise<EnsureFieldDefinitionsResult> {\n let created = 0\n let updated = 0\n let unchanged = 0\n\n // Prefetch every existing definition the batch could touch in a single query,\n // then index by composite key so the nested loop never issues per-field lookups.\n const entityIds = Array.from(new Set(sets.map((set) => set.entity)))\n const fieldKeys = Array.from(new Set(sets.flatMap((set) => set.fields.map((field) => field.key))))\n const existingByKey = new Map<string, CustomFieldDef>()\n if (entityIds.length > 0 && fieldKeys.length > 0) {\n const existingDefs = await em.find(CustomFieldDef, {\n entityId: { $in: entityIds },\n organizationId: scope.organizationId,\n tenantId: scope.tenantId,\n key: { $in: fieldKeys },\n })\n for (const def of existingDefs) {\n existingByKey.set(`${def.entityId}|${def.key}`, def)\n }\n }\n\n let dirty = false\n\n for (const set of sets) {\n for (const field of set.fields) {\n const existing = existingByKey.get(`${set.entity}|${field.key}`) ?? null\n const configJson: Record<string, unknown> = {}\n\n for (const key of CONFIG_PASSTHROUGH_KEYS) {\n const value = field[key]\n if (value !== undefined) configJson[key] = value as unknown\n }\n\n if (!existing) {\n if (!scope.dryRun) {\n const createdDef = em.create(CustomFieldDef, {\n entityId: set.entity,\n organizationId: scope.organizationId,\n tenantId: scope.tenantId,\n key: field.key,\n kind: field.kind,\n configJson,\n isActive: true,\n createdAt: new Date(),\n updatedAt: new Date(),\n })\n em.persist(createdDef)\n // Track so duplicate (entity, key) pairs within the batch update in memory instead of double-inserting.\n existingByKey.set(`${set.entity}|${field.key}`, createdDef)\n dirty = true\n }\n created++\n continue\n }\n\n const kindChanged = existing.kind !== field.kind\n const configChanged = !configEquals(existing.configJson ?? null, configJson)\n const needsActivation = existing.isActive !== true || existing.deletedAt != null\n if (scope.createOnly) {\n unchanged++\n continue\n }\n if (!kindChanged && !configChanged && !needsActivation) {\n unchanged++\n continue\n }\n\n if (!scope.dryRun) {\n existing.kind = field.kind\n ;(existing as any).configJson = configJson\n existing.isActive = true\n existing.updatedAt = new Date()\n if (existing.deletedAt) existing.deletedAt = null\n em.persist(existing)\n dirty = true\n }\n updated++\n }\n }\n\n if (dirty) {\n // Single flush for the whole batch instead of one round trip per field.\n await em.flush()\n }\n\n return { created, updated, unchanged }\n}\n"],
5
- "mappings": "AACA,SAAS,sBAAsB;AAsB/B,MAAM,0BAA8D;AAAA,EAClE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAEA,SAAS,eAAe,OAAyB;AAC/C,MAAI,MAAM,QAAQ,KAAK,EAAG,QAAO,MAAM,IAAI,CAAC,SAAS,eAAe,IAAI,CAAC;AACzE,MAAI,SAAS,OAAO,UAAU,UAAU;AACtC,WAAO,OAAO,KAAK,KAAgC,EAChD,KAAK,CAAC,GAAG,MAAM,EAAE,cAAc,CAAC,CAAC,EACjC,OAAgC,CAAC,KAAK,QAAQ;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AC7C;AAEA,UAAI,CAAC,UAAU;AACb,YAAI,CAAC,MAAM,QAAQ;AACjB,gBAAM,aAAa,GAAG,OAAO,gBAAgB;AAAA,YAC3C,UAAU,IAAI;AAAA,YACd,gBAAgB,MAAM;AAAA,YACtB,UAAU,MAAM;AAAA,YAChB,KAAK,MAAM;AAAA,YACX,MAAM,MAAM;AAAA,YACZ;AAAA,YACA,UAAU;AAAA,YACV,WAAW,oBAAI,KAAK;AAAA,YACpB,WAAW,oBAAI,KAAK;AAAA,UACtB,CAAC;AACD,aAAG,QAAQ,UAAU;AAErB,wBAAc,IAAI,GAAG,IAAI,MAAM,IAAI,MAAM,GAAG,IAAI,UAAU;AAC1D,kBAAQ;AAAA,QACV;AACA;AACA;AAAA,MACF;AAEA,YAAM,cAAc,SAAS,SAAS,MAAM;AAC5C,YAAM,gBAAgB,CAAC,aAAa,SAAS,cAAc,MAAM,UAAU;AAC3E,YAAM,kBAAkB,SAAS,aAAa,QAAQ,SAAS,aAAa;AAC5E,UAAI,MAAM,YAAY;AACpB;AACA;AAAA,MACF;AACA,UAAI,CAAC,eAAe,CAAC,iBAAiB,CAAC,iBAAiB;AACtD;AACA;AAAA,MACF;AAEA,UAAI,CAAC,MAAM,QAAQ;AACjB,iBAAS,OAAO,MAAM;AACrB,QAAC,SAAiB,aAAa;AAChC,iBAAS,WAAW;AACpB,iBAAS,YAAY,oBAAI,KAAK;AAC9B,YAAI,SAAS,UAAW,UAAS,YAAY;AAC7C,WAAG,QAAQ,QAAQ;AACnB,gBAAQ;AAAA,MACV;AACA;AAAA,IACF;AAAA,EACF;AAEA,MAAI,OAAO;AAET,UAAM,GAAG,MAAM;AAAA,EACjB;AAEA,SAAO,EAAE,SAAS,SAAS,UAAU;AACvC;",
4
+ "sourcesContent": ["import type { EntityManager } from '@mikro-orm/postgresql'\nimport { CustomFieldDef } from '../data/entities'\nimport type { CustomFieldDefinition } from '@open-mercato/shared/modules/entities'\n\nexport type FieldSetInput = {\n entity: string\n fields: CustomFieldDefinition[]\n source?: string\n}\n\nexport type EnsureFieldDefinitionsOptions = {\n organizationId: string | null\n tenantId: string | null\n dryRun?: boolean\n createOnly?: boolean\n}\n\nexport type EnsureFieldDefinitionsResult = {\n created: number\n updated: number\n unchanged: number\n}\n\nconst CONFIG_PASSTHROUGH_KEYS: Array<keyof CustomFieldDefinition> = [\n 'label',\n 'description',\n 'fieldset',\n 'fieldsets',\n 'group',\n 'options',\n 'optionsUrl',\n 'defaultValue',\n 'required',\n 'multi',\n 'filterable',\n 'formEditable',\n 'listVisible',\n 'indexed',\n 'encrypted',\n 'priority',\n 'editor',\n 'input',\n 'relatedEntityId',\n 'dictionaryId',\n 'dictionaryInlineCreate',\n 'validation',\n 'maxAttachmentSizeMb',\n 'acceptExtensions',\n 'sourceMetadata',\n]\n\nfunction normalizeValue(value: unknown): unknown {\n if (Array.isArray(value)) return value.map((item) => normalizeValue(item))\n if (value && typeof value === 'object') {\n return Object.keys(value as Record<string, unknown>)\n .sort((a, b) => a.localeCompare(b))\n .reduce<Record<string, unknown>>((acc, key) => {\n acc[key] = normalizeValue((value as Record<string, unknown>)[key])\n return acc\n }, {})\n }\n return value\n}\n\nfunction configEquals(a: unknown, b: unknown): boolean {\n return JSON.stringify(normalizeValue(a ?? null)) === JSON.stringify(normalizeValue(b ?? null))\n}\n\nfunction hasEncryptionEnabled(definition: CustomFieldDef | null): boolean {\n const config = definition?.configJson\n if (!config || typeof config !== 'object') return false\n return (config as Record<string, unknown>).encrypted === true\n}\n\nexport async function ensureCustomFieldDefinitions(\n em: EntityManager,\n sets: FieldSetInput[],\n scope: EnsureFieldDefinitionsOptions\n): Promise<EnsureFieldDefinitionsResult> {\n let created = 0\n let updated = 0\n let unchanged = 0\n\n // Prefetch every existing definition the batch could touch in a single query,\n // then index by composite key so the nested loop never issues per-field lookups.\n const entityIds = Array.from(new Set(sets.map((set) => set.entity)))\n const fieldKeys = Array.from(new Set(sets.flatMap((set) => set.fields.map((field) => field.key))))\n const existingByKey = new Map<string, CustomFieldDef>()\n if (entityIds.length > 0 && fieldKeys.length > 0) {\n const existingDefs = await em.find(CustomFieldDef, {\n entityId: { $in: entityIds },\n organizationId: scope.organizationId,\n tenantId: scope.tenantId,\n key: { $in: fieldKeys },\n })\n for (const def of existingDefs) {\n existingByKey.set(`${def.entityId}|${def.key}`, def)\n }\n }\n\n let dirty = false\n\n for (const set of sets) {\n for (const field of set.fields) {\n const existing = existingByKey.get(`${set.entity}|${field.key}`) ?? null\n const configJson: Record<string, unknown> = {}\n\n for (const key of CONFIG_PASSTHROUGH_KEYS) {\n const value = field[key]\n if (value !== undefined) configJson[key] = value as unknown\n }\n\n // configJson is rebuilt from the declaration, so a field encrypted through the\n // definitions API would lose the flag on the next install while its stored\n // values stay ciphertext the read path no longer decrypts. Keep an enabled flag\n // unless the declaration turns it off with an explicit `encrypted: false`.\n if (configJson.encrypted === undefined && hasEncryptionEnabled(existing)) {\n configJson.encrypted = true\n }\n\n if (!existing) {\n if (!scope.dryRun) {\n const createdDef = em.create(CustomFieldDef, {\n entityId: set.entity,\n organizationId: scope.organizationId,\n tenantId: scope.tenantId,\n key: field.key,\n kind: field.kind,\n configJson,\n isActive: true,\n createdAt: new Date(),\n updatedAt: new Date(),\n })\n em.persist(createdDef)\n // Track so duplicate (entity, key) pairs within the batch update in memory instead of double-inserting.\n existingByKey.set(`${set.entity}|${field.key}`, createdDef)\n dirty = true\n }\n created++\n continue\n }\n\n const kindChanged = existing.kind !== field.kind\n const configChanged = !configEquals(existing.configJson ?? null, configJson)\n const needsActivation = existing.isActive !== true || existing.deletedAt != null\n if (scope.createOnly) {\n unchanged++\n continue\n }\n if (!kindChanged && !configChanged && !needsActivation) {\n unchanged++\n continue\n }\n\n if (!scope.dryRun) {\n existing.kind = field.kind\n ;(existing as any).configJson = configJson\n existing.isActive = true\n existing.updatedAt = new Date()\n if (existing.deletedAt) existing.deletedAt = null\n em.persist(existing)\n dirty = true\n }\n updated++\n }\n }\n\n if (dirty) {\n // Single flush for the whole batch instead of one round trip per field.\n await em.flush()\n }\n\n return { created, updated, unchanged }\n}\n"],
5
+ "mappings": "AACA,SAAS,sBAAsB;AAsB/B,MAAM,0BAA8D;AAAA,EAClE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAEA,SAAS,eAAe,OAAyB;AAC/C,MAAI,MAAM,QAAQ,KAAK,EAAG,QAAO,MAAM,IAAI,CAAC,SAAS,eAAe,IAAI,CAAC;AACzE,MAAI,SAAS,OAAO,UAAU,UAAU;AACtC,WAAO,OAAO,KAAK,KAAgC,EAChD,KAAK,CAAC,GAAG,MAAM,EAAE,cAAc,CAAC,CAAC,EACjC,OAAgC,CAAC,KAAK,QAAQ;AAC7C,UAAI,GAAG,IAAI,eAAgB,MAAkC,GAAG,CAAC;AACjE,aAAO;AAAA,IACT,GAAG,CAAC,CAAC;AAAA,EACT;AACA,SAAO;AACT;AAEA,SAAS,aAAa,GAAY,GAAqB;AACrD,SAAO,KAAK,UAAU,eAAe,KAAK,IAAI,CAAC,MAAM,KAAK,UAAU,eAAe,KAAK,IAAI,CAAC;AAC/F;AAEA,SAAS,qBAAqB,YAA4C;AACxE,QAAM,SAAS,YAAY;AAC3B,MAAI,CAAC,UAAU,OAAO,WAAW,SAAU,QAAO;AAClD,SAAQ,OAAmC,cAAc;AAC3D;AAEA,eAAsB,6BACpB,IACA,MACA,OACuC;AACvC,MAAI,UAAU;AACd,MAAI,UAAU;AACd,MAAI,YAAY;AAIhB,QAAM,YAAY,MAAM,KAAK,IAAI,IAAI,KAAK,IAAI,CAAC,QAAQ,IAAI,MAAM,CAAC,CAAC;AACnE,QAA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AErB,wBAAc,IAAI,GAAG,IAAI,MAAM,IAAI,MAAM,GAAG,IAAI,UAAU;AAC1D,kBAAQ;AAAA,QACV;AACA;AACA;AAAA,MACF;AAEA,YAAM,cAAc,SAAS,SAAS,MAAM;AAC5C,YAAM,gBAAgB,CAAC,aAAa,SAAS,cAAc,MAAM,UAAU;AAC3E,YAAM,kBAAkB,SAAS,aAAa,QAAQ,SAAS,aAAa;AAC5E,UAAI,MAAM,YAAY;AACpB;AACA;AAAA,MACF;AACA,UAAI,CAAC,eAAe,CAAC,iBAAiB,CAAC,iBAAiB;AACtD;AACA;AAAA,MACF;AAEA,UAAI,CAAC,MAAM,QAAQ;AACjB,iBAAS,OAAO,MAAM;AACrB,QAAC,SAAiB,aAAa;AAChC,iBAAS,WAAW;AACpB,iBAAS,YAAY,oBAAI,KAAK;AAC9B,YAAI,SAAS,UAAW,UAAS,YAAY;AAC7C,WAAG,QAAQ,QAAQ;AACnB,gBAAQ;AAAA,MACV;AACA;AAAA,IACF;AAAA,EACF;AAEA,MAAI,OAAO;AAET,UAAM,GAAG,MAAM;AAAA,EACjB;AAEA,SAAO,EAAE,SAAS,SAAS,UAAU;AACvC;",
6
6
  "names": []
7
7
  }
@@ -17,6 +17,7 @@ const FIELD_DETAIL_KEYS = [
17
17
  "formEditable",
18
18
  "listVisible",
19
19
  "indexed",
20
+ "encrypted",
20
21
  "priority",
21
22
  "editor",
22
23
  "input",
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/entities/lib/install-from-ce.ts"],
4
- "sourcesContent": ["import crypto from 'node:crypto'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport type { CacheStrategy } from '@open-mercato/cache/types'\nimport type { CustomFieldDefinition, CustomFieldSet, CustomEntitySpec } from '@open-mercato/shared/modules/entities'\nimport { Tenant } from '@open-mercato/core/modules/directory/data/entities'\nimport { getModules } from '@open-mercato/shared/lib/i18n/server'\nimport { getEntityIds } from '@open-mercato/shared/lib/encryption/entityIds'\nimport { ensureCustomFieldDefinitions } from './field-definitions'\nimport { upsertCustomEntity, type UpsertCustomEntityResult } from './register'\nimport { invalidateDefinitionsCache } from '../api/definitions.cache'\n\ntype InstallScope = {\n tenantId: string | null\n}\n\nexport type InstallEntitiesOptions = {\n tenantIds?: string[]\n entityIds?: string[]\n includeGlobal?: boolean\n dryRun?: boolean\n createOnly?: boolean\n force?: boolean\n logger?: (message: string) => void\n}\n\nexport type InstallEntitiesResult = {\n processed: number\n synchronized: number\n skipped: number\n fieldChanges: number\n}\n\nexport type AggregatedEntityConfig = {\n entityId: string\n moduleIds: Set<string>\n spec?: CustomEntitySpec\n fieldSets: CustomFieldSet[]\n}\n\nconst FIELD_DETAIL_KEYS: Array<keyof CustomFieldDefinition> = [\n 'label',\n 'description',\n 'options',\n 'optionsUrl',\n 'defaultValue',\n 'required',\n 'multi',\n 'filterable',\n 'formEditable',\n 'listVisible',\n 'indexed',\n 'priority',\n 'editor',\n 'input',\n 'relatedEntityId',\n 'validation',\n 'maxAttachmentSizeMb',\n 'acceptExtensions',\n]\n\nfunction normalizeValue(value: unknown): unknown {\n if (Array.isArray(value)) return value.map((item) => normalizeValue(item))\n if (value && typeof value === 'object') {\n return Object.keys(value as Record<string, unknown>)\n .sort((a, b) => a.localeCompare(b))\n .reduce<Record<string, unknown>>((acc, key) => {\n acc[key] = normalizeValue((value as Record<string, unknown>)[key])\n return acc\n }, {})\n }\n return value\n}\n\nfunction computeChecksum(payload: unknown): string {\n return crypto.createHash('md5').update(JSON.stringify(normalizeValue(payload))).digest('hex')\n}\n\nfunction systemEntityIds(): Set<string> {\n const ids = new Set<string>()\n const GeneratedEntities = getEntityIds()\n for (const moduleEntities of Object.values(GeneratedEntities)) {\n for (const id of Object.values(moduleEntities as Record<string, string>)) {\n ids.add(id)\n }\n }\n return ids\n}\n\nfunction buildAggregatedConfigs(): AggregatedEntityConfig[] {\n const map = new Map<string, AggregatedEntityConfig>()\n const modules = getModules()\n for (const mod of modules) {\n const moduleId = mod.id\n const entitySpecs = ((mod as any).customEntities as CustomEntitySpec[] | undefined) ?? []\n for (const spec of entitySpecs) {\n const existing = map.get(spec.id) ?? { entityId: spec.id, moduleIds: new Set<string>(), spec: undefined, fieldSets: [] }\n existing.moduleIds.add(moduleId)\n if (!existing.spec) existing.spec = spec\n map.set(spec.id, existing)\n }\n const fieldSets = ((mod as any).customFieldSets as CustomFieldSet[] | undefined) ?? []\n for (const set of fieldSets) {\n const existing = map.get(set.entity) ?? { entityId: set.entity, moduleIds: new Set<string>(), spec: undefined, fieldSets: [] }\n existing.moduleIds.add(moduleId)\n existing.fieldSets.push(set)\n map.set(set.entity, existing)\n }\n }\n return Array.from(map.values())\n}\n\nexport function resolveFields(fieldSets: CustomFieldSet[]): CustomFieldDefinition[] {\n const byKey = new Map<string, CustomFieldDefinition>()\n const declarationOrder = new Map<string, number>()\n for (const set of fieldSets) {\n for (const field of set.fields ?? []) {\n if (!declarationOrder.has(field.key)) declarationOrder.set(field.key, declarationOrder.size)\n byKey.set(field.key, { ...field })\n }\n }\n // Declaration order is the author's intent, so it drives `priority` (and the\n // resulting render order) unless a field states its own. Sorting alphabetically\n // by key here would silently discard that intent (#4378).\n const resolved = Array.from(byKey.values()).map((field) => (\n typeof field.priority === 'number'\n ? field\n : { ...field, priority: declarationOrder.get(field.key) ?? 0 }\n ))\n return resolved.sort((a, b) => {\n const byPriority = (a.priority ?? 0) - (b.priority ?? 0)\n if (byPriority !== 0) return byPriority\n return (declarationOrder.get(a.key) ?? 0) - (declarationOrder.get(b.key) ?? 0)\n })\n}\n\nfunction normalizeField(field: CustomFieldDefinition) {\n const payload: Record<string, unknown> = {\n key: field.key,\n kind: field.kind,\n }\n for (const key of FIELD_DETAIL_KEYS) {\n const value = field[key]\n if (value !== undefined) payload[key] = value as unknown\n }\n if (field.id) payload.id = field.id\n return payload\n}\n\nfunction buildChecksumPayload(params: {\n entityId: string\n scope: InstallScope\n spec: CustomEntitySpec | undefined\n global: boolean\n fields: CustomFieldDefinition[]\n}) {\n const { entityId, scope, spec, global, fields } = params\n return {\n entityId,\n scope,\n global,\n label: spec?.label ?? null,\n description: spec?.description ?? null,\n labelField: spec?.labelField ?? null,\n defaultEditor: spec?.defaultEditor ?? null,\n showInSidebar: spec?.showInSidebar ?? false,\n accessRestricted: spec?.accessRestricted ?? false,\n fields: fields.map((f) => normalizeField(f)),\n }\n}\n\nexport async function installCustomEntitiesFromModules(\n em: EntityManager,\n cache: CacheStrategy | null | undefined,\n options: InstallEntitiesOptions = {}\n): Promise<InstallEntitiesResult> {\n const requestedEntityIds = options.entityIds\n ? new Set(options.entityIds.filter((id): id is string => typeof id === 'string' && id.length > 0))\n : null\n const aggregated = buildAggregatedConfigs().filter((entry) => {\n if (!requestedEntityIds) return true\n return requestedEntityIds.has(entry.entityId)\n })\n const systemIds = systemEntityIds()\n const includeGlobal = options.includeGlobal !== false\n const dryRun = options.dryRun === true\n const createOnly = options.createOnly === true\n const force = options.force === true\n const logger = options.logger\n\n let tenantIds: string[] | undefined\n if (options.tenantIds !== undefined) {\n tenantIds = Array.from(new Set(options.tenantIds.filter((id): id is string => typeof id === 'string' && id.length > 0)))\n }\n\n const ensureTenantIds = async (): Promise<string[]> => {\n if (tenantIds !== undefined) return tenantIds\n const rows = await em.find(Tenant, { deletedAt: null } as any, { fields: ['id'] as any })\n tenantIds = rows.map((row) => row.id)\n return tenantIds ?? []\n }\n\n let processed = 0\n let synchronized = 0\n let skipped = 0\n let fieldChanges = 0\n\n for (const entry of aggregated) {\n const { entityId } = entry\n const spec = entry.spec\n const fields = resolveFields(entry.fieldSets)\n const isSystem = systemIds.has(entityId)\n const registerEntity = !isSystem && !!spec\n const isGlobal = spec?.global === true\n\n const scopes: InstallScope[] = []\n if (isGlobal) {\n if (includeGlobal) scopes.push({ tenantId: null })\n } else {\n const ids = await ensureTenantIds()\n if (!ids.length) {\n skipped++\n continue\n }\n for (const tenantId of ids) scopes.push({ tenantId })\n }\n\n if (!scopes.length && fields.length === 0 && !registerEntity) {\n skipped++\n continue\n }\n\n for (const scope of scopes) {\n processed++\n const scopeKey = scope.tenantId ? `tenant:${scope.tenantId}` : 'global'\n const checksumPayload = buildChecksumPayload({\n entityId,\n scope,\n spec,\n global: isGlobal,\n fields,\n })\n const checksum = computeChecksum(checksumPayload)\n const cacheKey = `custom-entities:v1:${scopeKey}:${entityId}`\n\n if (!dryRun && !force && cache) {\n try {\n const cached = await cache.get(cacheKey)\n if (typeof cached === 'string' && cached === checksum) {\n skipped++\n continue\n }\n } catch {}\n }\n\n let entityResult: UpsertCustomEntityResult = 'unchanged'\n if (registerEntity) {\n entityResult = await upsertCustomEntity(em, entityId, {\n label: spec?.label ?? entityId,\n description: spec?.description ?? null,\n organizationId: null,\n tenantId: scope.tenantId,\n showInSidebar: spec?.showInSidebar ?? false,\n accessRestricted: spec?.accessRestricted ?? false,\n labelField: spec?.labelField ?? null,\n defaultEditor: spec?.defaultEditor ?? null,\n isActive: true,\n dryRun,\n createOnly,\n })\n }\n\n let fieldResult = { created: 0, updated: 0, unchanged: 0 }\n if (fields.length) {\n fieldResult = await ensureCustomFieldDefinitions(\n em,\n [{ entity: entityId, fields }],\n { organizationId: null, tenantId: scope.tenantId, dryRun, createOnly }\n )\n }\n\n const changed = (entityResult !== 'unchanged') || fieldResult.created > 0 || fieldResult.updated > 0\n const shouldInvalidateDefinitions = !dryRun && (changed || force)\n if (shouldInvalidateDefinitions) {\n await invalidateDefinitionsCache(cache ?? undefined, {\n tenantId: scope.tenantId,\n organizationId: null,\n entityIds: [entityId],\n })\n }\n\n if (changed) {\n synchronized++\n fieldChanges += fieldResult.created + fieldResult.updated\n if (!dryRun && cache) {\n try {\n await cache.set(cacheKey, checksum, { tags: [`custom-entity:${entityId}`, `custom-entity-scope:${scopeKey}`] })\n } catch {}\n }\n if (logger) {\n const parts: string[] = []\n if (entityResult !== 'unchanged') parts.push(`entity ${entityResult}`)\n if (fieldResult.created || fieldResult.updated) {\n parts.push(`fields +${fieldResult.created} / ~${fieldResult.updated}`)\n }\n logger(`Synced ${entityId} for ${scopeKey}${parts.length ? ` (${parts.join(', ')})` : ''}`)\n }\n } else {\n skipped++\n if (!dryRun && cache) {\n try {\n await cache.set(cacheKey, checksum, { tags: [`custom-entity:${entityId}`, `custom-entity-scope:${scopeKey}`] })\n } catch {}\n }\n }\n }\n }\n\n return { processed, synchronized, skipped, fieldChanges }\n}\n\nexport function listCustomEntityIds(): string[] {\n return buildAggregatedConfigs().map((entry) => entry.entityId)\n}\n\nexport function getAggregatedCustomEntityConfigs(): AggregatedEntityConfig[] {\n return buildAggregatedConfigs()\n}\n"],
5
- "mappings": "AAAA,OAAO,YAAY;AAInB,SAAS,cAAc;AACvB,SAAS,kBAAkB;AAC3B,SAAS,oBAAoB;AAC7B,SAAS,oCAAoC;AAC7C,SAAS,0BAAyD;AAClE,SAAS,kCAAkC;AA8B3C,MAAM,oBAAwD;AAAA,EAC5D;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAEA,SAAS,eAAe,OAAyB;AAC/C,MAAI,MAAM,QAAQ,KAAK,EAAG,QAAO,MAAM,IAAI,CAAC,SAAS,eAAe,IAAI,CAAC;AACzE,MAAI,SAAS,OAAO,UAAU,UAAU;AACtC,WAAO,OAAO,KAAK,KAAgC,EAChD,KAAK,CAAC,GAAG,MAAM,EAAE,cAAc,CAAC,CAAC,EACjC,OAAgC,CAAC,KAAK,QAAQ;AAC7C,UAAI,GAAG,IAAI,eAAgB,MAAkC,GAAG,CAAC;AACjE,aAAO;AAAA,IACT,GAAG,CAAC,CAAC;AAAA,EACT;AACA,SAAO;AACT;AAEA,SAAS,gBAAgB,SAA0B;AACjD,SAAO,OAAO,WAAW,KAAK,EAAE,OAAO,KAAK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B,QAAQ,IAAI,uBAAuB,QAAQ,EAAE,EAAE,CAAC;AAAA,UAChH,QAAQ;AAAA,UAAC;AAAA,QACX;AAAA,MACF;AAAA,IACF;AAAA,EACF;AAEA,SAAO,EAAE,WAAW,cAAc,SAAS,aAAa;AAC1D;AAEO,SAAS,sBAAgC;AAC9C,SAAO,uBAAuB,EAAE,IAAI,CAAC,UAAU,MAAM,QAAQ;AAC/D;AAEO,SAAS,mCAA6D;AAC3E,SAAO,uBAAuB;AAChC;",
4
+ "sourcesContent": ["import crypto from 'node:crypto'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport type { CacheStrategy } from '@open-mercato/cache/types'\nimport type { CustomFieldDefinition, CustomFieldSet, CustomEntitySpec } from '@open-mercato/shared/modules/entities'\nimport { Tenant } from '@open-mercato/core/modules/directory/data/entities'\nimport { getModules } from '@open-mercato/shared/lib/i18n/server'\nimport { getEntityIds } from '@open-mercato/shared/lib/encryption/entityIds'\nimport { ensureCustomFieldDefinitions } from './field-definitions'\nimport { upsertCustomEntity, type UpsertCustomEntityResult } from './register'\nimport { invalidateDefinitionsCache } from '../api/definitions.cache'\n\ntype InstallScope = {\n tenantId: string | null\n}\n\nexport type InstallEntitiesOptions = {\n tenantIds?: string[]\n entityIds?: string[]\n includeGlobal?: boolean\n dryRun?: boolean\n createOnly?: boolean\n force?: boolean\n logger?: (message: string) => void\n}\n\nexport type InstallEntitiesResult = {\n processed: number\n synchronized: number\n skipped: number\n fieldChanges: number\n}\n\nexport type AggregatedEntityConfig = {\n entityId: string\n moduleIds: Set<string>\n spec?: CustomEntitySpec\n fieldSets: CustomFieldSet[]\n}\n\nconst FIELD_DETAIL_KEYS: Array<keyof CustomFieldDefinition> = [\n 'label',\n 'description',\n 'options',\n 'optionsUrl',\n 'defaultValue',\n 'required',\n 'multi',\n 'filterable',\n 'formEditable',\n 'listVisible',\n 'indexed',\n 'encrypted',\n 'priority',\n 'editor',\n 'input',\n 'relatedEntityId',\n 'validation',\n 'maxAttachmentSizeMb',\n 'acceptExtensions',\n]\n\nfunction normalizeValue(value: unknown): unknown {\n if (Array.isArray(value)) return value.map((item) => normalizeValue(item))\n if (value && typeof value === 'object') {\n return Object.keys(value as Record<string, unknown>)\n .sort((a, b) => a.localeCompare(b))\n .reduce<Record<string, unknown>>((acc, key) => {\n acc[key] = normalizeValue((value as Record<string, unknown>)[key])\n return acc\n }, {})\n }\n return value\n}\n\nfunction computeChecksum(payload: unknown): string {\n return crypto.createHash('md5').update(JSON.stringify(normalizeValue(payload))).digest('hex')\n}\n\nfunction systemEntityIds(): Set<string> {\n const ids = new Set<string>()\n const GeneratedEntities = getEntityIds()\n for (const moduleEntities of Object.values(GeneratedEntities)) {\n for (const id of Object.values(moduleEntities as Record<string, string>)) {\n ids.add(id)\n }\n }\n return ids\n}\n\nfunction buildAggregatedConfigs(): AggregatedEntityConfig[] {\n const map = new Map<string, AggregatedEntityConfig>()\n const modules = getModules()\n for (const mod of modules) {\n const moduleId = mod.id\n const entitySpecs = ((mod as any).customEntities as CustomEntitySpec[] | undefined) ?? []\n for (const spec of entitySpecs) {\n const existing = map.get(spec.id) ?? { entityId: spec.id, moduleIds: new Set<string>(), spec: undefined, fieldSets: [] }\n existing.moduleIds.add(moduleId)\n if (!existing.spec) existing.spec = spec\n map.set(spec.id, existing)\n }\n const fieldSets = ((mod as any).customFieldSets as CustomFieldSet[] | undefined) ?? []\n for (const set of fieldSets) {\n const existing = map.get(set.entity) ?? { entityId: set.entity, moduleIds: new Set<string>(), spec: undefined, fieldSets: [] }\n existing.moduleIds.add(moduleId)\n existing.fieldSets.push(set)\n map.set(set.entity, existing)\n }\n }\n return Array.from(map.values())\n}\n\nexport function resolveFields(fieldSets: CustomFieldSet[]): CustomFieldDefinition[] {\n const byKey = new Map<string, CustomFieldDefinition>()\n const declarationOrder = new Map<string, number>()\n for (const set of fieldSets) {\n for (const field of set.fields ?? []) {\n if (!declarationOrder.has(field.key)) declarationOrder.set(field.key, declarationOrder.size)\n byKey.set(field.key, { ...field })\n }\n }\n // Declaration order is the author's intent, so it drives `priority` (and the\n // resulting render order) unless a field states its own. Sorting alphabetically\n // by key here would silently discard that intent (#4378).\n const resolved = Array.from(byKey.values()).map((field) => (\n typeof field.priority === 'number'\n ? field\n : { ...field, priority: declarationOrder.get(field.key) ?? 0 }\n ))\n return resolved.sort((a, b) => {\n const byPriority = (a.priority ?? 0) - (b.priority ?? 0)\n if (byPriority !== 0) return byPriority\n return (declarationOrder.get(a.key) ?? 0) - (declarationOrder.get(b.key) ?? 0)\n })\n}\n\nfunction normalizeField(field: CustomFieldDefinition) {\n const payload: Record<string, unknown> = {\n key: field.key,\n kind: field.kind,\n }\n for (const key of FIELD_DETAIL_KEYS) {\n const value = field[key]\n if (value !== undefined) payload[key] = value as unknown\n }\n if (field.id) payload.id = field.id\n return payload\n}\n\nfunction buildChecksumPayload(params: {\n entityId: string\n scope: InstallScope\n spec: CustomEntitySpec | undefined\n global: boolean\n fields: CustomFieldDefinition[]\n}) {\n const { entityId, scope, spec, global, fields } = params\n return {\n entityId,\n scope,\n global,\n label: spec?.label ?? null,\n description: spec?.description ?? null,\n labelField: spec?.labelField ?? null,\n defaultEditor: spec?.defaultEditor ?? null,\n showInSidebar: spec?.showInSidebar ?? false,\n accessRestricted: spec?.accessRestricted ?? false,\n fields: fields.map((f) => normalizeField(f)),\n }\n}\n\nexport async function installCustomEntitiesFromModules(\n em: EntityManager,\n cache: CacheStrategy | null | undefined,\n options: InstallEntitiesOptions = {}\n): Promise<InstallEntitiesResult> {\n const requestedEntityIds = options.entityIds\n ? new Set(options.entityIds.filter((id): id is string => typeof id === 'string' && id.length > 0))\n : null\n const aggregated = buildAggregatedConfigs().filter((entry) => {\n if (!requestedEntityIds) return true\n return requestedEntityIds.has(entry.entityId)\n })\n const systemIds = systemEntityIds()\n const includeGlobal = options.includeGlobal !== false\n const dryRun = options.dryRun === true\n const createOnly = options.createOnly === true\n const force = options.force === true\n const logger = options.logger\n\n let tenantIds: string[] | undefined\n if (options.tenantIds !== undefined) {\n tenantIds = Array.from(new Set(options.tenantIds.filter((id): id is string => typeof id === 'string' && id.length > 0)))\n }\n\n const ensureTenantIds = async (): Promise<string[]> => {\n if (tenantIds !== undefined) return tenantIds\n const rows = await em.find(Tenant, { deletedAt: null } as any, { fields: ['id'] as any })\n tenantIds = rows.map((row) => row.id)\n return tenantIds ?? []\n }\n\n let processed = 0\n let synchronized = 0\n let skipped = 0\n let fieldChanges = 0\n\n for (const entry of aggregated) {\n const { entityId } = entry\n const spec = entry.spec\n const fields = resolveFields(entry.fieldSets)\n const isSystem = systemIds.has(entityId)\n const registerEntity = !isSystem && !!spec\n const isGlobal = spec?.global === true\n\n const scopes: InstallScope[] = []\n if (isGlobal) {\n if (includeGlobal) scopes.push({ tenantId: null })\n } else {\n const ids = await ensureTenantIds()\n if (!ids.length) {\n skipped++\n continue\n }\n for (const tenantId of ids) scopes.push({ tenantId })\n }\n\n if (!scopes.length && fields.length === 0 && !registerEntity) {\n skipped++\n continue\n }\n\n for (const scope of scopes) {\n processed++\n const scopeKey = scope.tenantId ? `tenant:${scope.tenantId}` : 'global'\n const checksumPayload = buildChecksumPayload({\n entityId,\n scope,\n spec,\n global: isGlobal,\n fields,\n })\n const checksum = computeChecksum(checksumPayload)\n const cacheKey = `custom-entities:v1:${scopeKey}:${entityId}`\n\n if (!dryRun && !force && cache) {\n try {\n const cached = await cache.get(cacheKey)\n if (typeof cached === 'string' && cached === checksum) {\n skipped++\n continue\n }\n } catch {}\n }\n\n let entityResult: UpsertCustomEntityResult = 'unchanged'\n if (registerEntity) {\n entityResult = await upsertCustomEntity(em, entityId, {\n label: spec?.label ?? entityId,\n description: spec?.description ?? null,\n organizationId: null,\n tenantId: scope.tenantId,\n showInSidebar: spec?.showInSidebar ?? false,\n accessRestricted: spec?.accessRestricted ?? false,\n labelField: spec?.labelField ?? null,\n defaultEditor: spec?.defaultEditor ?? null,\n isActive: true,\n dryRun,\n createOnly,\n })\n }\n\n let fieldResult = { created: 0, updated: 0, unchanged: 0 }\n if (fields.length) {\n fieldResult = await ensureCustomFieldDefinitions(\n em,\n [{ entity: entityId, fields }],\n { organizationId: null, tenantId: scope.tenantId, dryRun, createOnly }\n )\n }\n\n const changed = (entityResult !== 'unchanged') || fieldResult.created > 0 || fieldResult.updated > 0\n const shouldInvalidateDefinitions = !dryRun && (changed || force)\n if (shouldInvalidateDefinitions) {\n await invalidateDefinitionsCache(cache ?? undefined, {\n tenantId: scope.tenantId,\n organizationId: null,\n entityIds: [entityId],\n })\n }\n\n if (changed) {\n synchronized++\n fieldChanges += fieldResult.created + fieldResult.updated\n if (!dryRun && cache) {\n try {\n await cache.set(cacheKey, checksum, { tags: [`custom-entity:${entityId}`, `custom-entity-scope:${scopeKey}`] })\n } catch {}\n }\n if (logger) {\n const parts: string[] = []\n if (entityResult !== 'unchanged') parts.push(`entity ${entityResult}`)\n if (fieldResult.created || fieldResult.updated) {\n parts.push(`fields +${fieldResult.created} / ~${fieldResult.updated}`)\n }\n logger(`Synced ${entityId} for ${scopeKey}${parts.length ? ` (${parts.join(', ')})` : ''}`)\n }\n } else {\n skipped++\n if (!dryRun && cache) {\n try {\n await cache.set(cacheKey, checksum, { tags: [`custom-entity:${entityId}`, `custom-entity-scope:${scopeKey}`] })\n } catch {}\n }\n }\n }\n }\n\n return { processed, synchronized, skipped, fieldChanges }\n}\n\nexport function listCustomEntityIds(): string[] {\n return buildAggregatedConfigs().map((entry) => entry.entityId)\n}\n\nexport function getAggregatedCustomEntityConfigs(): AggregatedEntityConfig[] {\n return buildAggregatedConfigs()\n}\n"],
5
+ "mappings": "AAAA,OAAO,YAAY;AAInB,SAAS,cAAc;AACvB,SAAS,kBAAkB;AAC3B,SAAS,oBAAoB;AAC7B,SAAS,oCAAoC;AAC7C,SAAS,0BAAyD;AAClE,SAAS,kCAAkC;AA8B3C,MAAM,oBAAwD;AAAA,EAC5D;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,E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BAAM,MAAM,IAAI,UAAU,UAAU,EAAE,MAAM,CAAC,iBAAiB,QAAQ,IAAI,uBAAuB,QAAQ,EAAE,EAAE,CAAC;AAAA,UAChH,QAAQ;AAAA,UAAC;AAAA,QACX;AACA,YAAI,QAAQ;AACV,gBAAM,QAAkB,CAAC;AACzB,cAAI,iBAAiB,YAAa,OAAM,KAAK,UAAU,YAAY,EAAE;AACrE,cAAI,YAAY,WAAW,YAAY,SAAS;AAC9C,kBAAM,KAAK,WAAW,YAAY,OAAO,OAAO,YAAY,OAAO,EAAE;AAAA,UACvE;AACA,iBAAO,UAAU,QAAQ,QAAQ,QAAQ,GAAG,MAAM,SAAS,KAAK,MAAM,KAAK,IAAI,CAAC,MAAM,EAAE,EAAE;AAAA,QAC5F;AAAA,MACF,OAAO;AACL;AACA,YAAI,CAAC,UAAU,OAAO;AACpB,cAAI;AACF,kBAAM,MAAM,IAAI,UAAU,UAAU,EAAE,MAAM,CAAC,iBAAiB,QAAQ,IAAI,uBAAuB,QAAQ,EAAE,EAAE,CAAC;AAAA,UAChH,QAAQ;AAAA,UAAC;AAAA,QACX;AAAA,MACF;AAAA,IACF;AAAA,EACF;AAEA,SAAO,EAAE,WAAW,cAAc,SAAS,aAAa;AAC1D;AAEO,SAAS,sBAAgC;AAC9C,SAAO,uBAAuB,EAAE,IAAI,CAAC,UAAU,MAAM,QAAQ;AAC/D;AAEO,SAAS,mCAA6D;AAC3E,SAAO,uBAAuB;AAChC;",
6
6
  "names": []
7
7
  }
@@ -69,22 +69,20 @@ function resolveSupplierName(record) {
69
69
  return readObjectText(snapshot, "display_name", "displayName", "name");
70
70
  }
71
71
  function buildStatementPresenter(translate, record) {
72
- const label = translate("eudr.search.badge.statement", "DDS statement");
73
72
  const title = readRecordText(record, "title") ?? translate("eudr.common.recordUnavailable");
74
73
  const subtitle = formatSubtitle(
75
74
  readRecordText(record, "reference_number", "referenceNumber"),
76
75
  translateToken(translate, "eudr.commodity", readRecordText(record, "commodity"))
77
76
  );
78
- return { title, subtitle, icon: "file-check", badge: label };
77
+ return { title, subtitle, icon: "file-check" };
79
78
  }
80
79
  function buildPlotPresenter(translate, record) {
81
- const label = translate("eudr.search.badge.plot", "Plot");
82
80
  const title = readRecordText(record, "name") ?? translate("eudr.common.recordUnavailable");
83
81
  const subtitle = formatSubtitle(
84
82
  readRecordText(record, "origin_country", "originCountry"),
85
83
  translateToken(translate, "eudr.plotType", readRecordText(record, "plot_type", "plotType"))
86
84
  );
87
- return { title, subtitle, icon: "map-pin", badge: label };
85
+ return { title, subtitle, icon: "map-pin" };
88
86
  }
89
87
  function buildSubmissionPresenter(translate, record) {
90
88
  const label = translate("eudr.search.badge.submission", "Evidence submission");
@@ -95,7 +93,7 @@ function buildSubmissionPresenter(translate, record) {
95
93
  supplierName,
96
94
  translateToken(translate, "eudr.submissionStatus", readRecordText(record, "status"))
97
95
  );
98
- return { title, subtitle, icon: "package", badge: label };
96
+ return { title, subtitle, icon: "package" };
99
97
  }
100
98
  const searchConfig = {
101
99
  entities: [
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/modules/eudr/search.ts"],
4
- "sourcesContent": ["import type { SearchBuildContext, SearchIndexSource, SearchModuleConfig, SearchResultPresenter } from '@open-mercato/shared/modules/search'\nimport type { TranslateFn } from '@open-mercato/shared/lib/i18n/context'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\n\nconst EUDR_STATEMENTS_URL = '/backend/eudr/statements'\nconst EUDR_PLOTS_URL = '/backend/eudr/plots'\nconst EUDR_EVIDENCE_SUBMISSIONS_URL = '/backend/eudr/evidence-submissions'\n\nfunction assertTenantContext(ctx: SearchBuildContext): void {\n if (typeof ctx.tenantId !== 'string' || ctx.tenantId.length === 0) {\n throw new Error('[internal] [search.eudr] Missing tenantId in search build context')\n }\n}\n\nfunction normalizeText(value: unknown): string | null {\n if (value === null || value === undefined) return null\n if (typeof value === 'string') {\n const trimmed = value.trim()\n return trimmed.length > 0 ? trimmed : null\n }\n if (value instanceof Date) return value.toISOString()\n if (typeof value === 'number' || typeof value === 'boolean') return String(value)\n return null\n}\n\nfunction readRecordText(record: Record<string, unknown>, ...keys: string[]): string | null {\n for (const key of keys) {\n const text = normalizeText(record[key])\n if (text) return text\n }\n return null\n}\n\nfunction readObjectText(source: unknown, ...keys: string[]): string | null {\n if (!source || typeof source !== 'object') return null\n return readRecordText(source as Record<string, unknown>, ...keys)\n}\n\nfunction formatSubtitle(...parts: Array<unknown>): string | undefined {\n const text = parts\n .map((part) => normalizeText(part))\n .filter((value): value is string => Boolean(value))\n if (!text.length) return undefined\n return text.join(' \u00B7 ')\n}\n\nfunction appendLine(lines: string[], label: string, value: unknown) {\n const text = normalizeText(value)\n if (!text) return\n lines.push(`${label}: ${text}`)\n}\n\nfunction friendlyLabel(input: string): string {\n return input\n .replace(/^cf:/, '')\n .replace(/_/g, ' ')\n .replace(/([a-z])([A-Z])/g, (_match, firstChar, secondChar) => `${firstChar} ${secondChar}`)\n .replace(/\\b\\w/g, (character) => character.toUpperCase())\n}\n\nfunction appendCustomFieldLines(lines: string[], customFields: Record<string, unknown>) {\n for (const [key, value] of Object.entries(customFields)) {\n if (value === null || value === undefined) continue\n appendLine(lines, friendlyLabel(key), value)\n }\n}\n\nfunction buildIndexSource(\n ctx: SearchBuildContext,\n presenter: SearchResultPresenter,\n lines: string[],\n): SearchIndexSource | null {\n appendCustomFieldLines(lines, ctx.customFields)\n if (!lines.length) return null\n return {\n text: lines,\n presenter,\n checksumSource: { record: ctx.record, customFields: ctx.customFields },\n }\n}\n\nfunction buildRecordUrl(baseUrl: string, record: Record<string, unknown>): string | null {\n const recordId = readRecordText(record, 'id')\n return recordId ? `${baseUrl}/${encodeURIComponent(recordId)}` : null\n}\n\nfunction translateToken(translate: TranslateFn, prefix: string, value: string | null): string | null {\n if (!value) return null\n return translate(`${prefix}.${value}`, value)\n}\n\nfunction resolveSupplierName(record: Record<string, unknown>): string | null {\n const snapshot = record.supplier_snapshot ?? record.supplierSnapshot\n return readObjectText(snapshot, 'display_name', 'displayName', 'name')\n}\n\nfunction buildStatementPresenter(translate: TranslateFn, record: Record<string, unknown>): SearchResultPresenter {\n const label = translate('eudr.search.badge.statement', 'DDS statement')\n const title = readRecordText(record, 'title') ?? translate('eudr.common.recordUnavailable')\n const subtitle = formatSubtitle(\n readRecordText(record, 'reference_number', 'referenceNumber'),\n translateToken(translate, 'eudr.commodity', readRecordText(record, 'commodity')),\n )\n return { title, subtitle, icon: 'file-check', badge: label }\n}\n\nfunction buildPlotPresenter(translate: TranslateFn, record: Record<string, unknown>): SearchResultPresenter {\n const label = translate('eudr.search.badge.plot', 'Plot')\n const title = readRecordText(record, 'name') ?? translate('eudr.common.recordUnavailable')\n const subtitle = formatSubtitle(\n readRecordText(record, 'origin_country', 'originCountry'),\n translateToken(translate, 'eudr.plotType', readRecordText(record, 'plot_type', 'plotType')),\n )\n return { title, subtitle, icon: 'map-pin', badge: label }\n}\n\nfunction buildSubmissionPresenter(translate: TranslateFn, record: Record<string, unknown>): SearchResultPresenter {\n const label = translate('eudr.search.badge.submission', 'Evidence submission')\n const batchNumber = readRecordText(record, 'batch_number', 'batchNumber')\n const supplierName = resolveSupplierName(record)\n const title = batchNumber\n ? `${label} ${batchNumber}`\n : supplierName ?? translate('eudr.common.recordUnavailable')\n const subtitle = formatSubtitle(\n supplierName,\n translateToken(translate, 'eudr.submissionStatus', readRecordText(record, 'status')),\n )\n return { title, subtitle, icon: 'package', badge: label }\n}\n\nexport const searchConfig: SearchModuleConfig = {\n entities: [\n {\n entityId: 'eudr:eudr_due_diligence_statement',\n enabled: true,\n priority: 8,\n fieldPolicy: {\n searchable: ['title', 'reference_number', 'commodity'],\n excluded: ['notes'],\n },\n buildSource: async (ctx) => {\n assertTenantContext(ctx)\n const { t: translate } = await resolveTranslations()\n const record = ctx.record\n const lines: string[] = []\n appendLine(lines, 'Title', record.title)\n appendLine(lines, 'Reference number', record.reference_number ?? record.referenceNumber)\n appendLine(lines, 'Commodity', record.commodity)\n return buildIndexSource(ctx, buildStatementPresenter(translate, record), lines)\n },\n formatResult: async (ctx) => {\n const { t: translate } = await resolveTranslations()\n return buildStatementPresenter(translate, ctx.record)\n },\n resolveUrl: async (ctx) => buildRecordUrl(EUDR_STATEMENTS_URL, ctx.record),\n aclFeatures: ['eudr.statements.view'],\n },\n {\n entityId: 'eudr:eudr_plot',\n enabled: true,\n priority: 7,\n fieldPolicy: {\n searchable: ['name', 'external_id', 'origin_country'],\n excluded: ['producer_name'],\n },\n buildSource: async (ctx) => {\n assertTenantContext(ctx)\n const { t: translate } = await resolveTranslations()\n const record = ctx.record\n const lines: string[] = []\n appendLine(lines, 'Name', record.name)\n appendLine(lines, 'External ID', record.external_id ?? record.externalId)\n appendLine(lines, 'Origin country', record.origin_country ?? record.originCountry)\n return buildIndexSource(ctx, buildPlotPresenter(translate, record), lines)\n },\n formatResult: async (ctx) => {\n const { t: translate } = await resolveTranslations()\n return buildPlotPresenter(translate, ctx.record)\n },\n resolveUrl: async (ctx) => buildRecordUrl(EUDR_PLOTS_URL, ctx.record),\n aclFeatures: ['eudr.plots.view'],\n },\n {\n entityId: 'eudr:eudr_evidence_submission',\n enabled: true,\n priority: 6,\n fieldPolicy: {\n searchable: ['batch_number', 'commodity'],\n excluded: ['producer_name', 'notes'],\n },\n buildSource: async (ctx) => {\n assertTenantContext(ctx)\n const { t: translate } = await resolveTranslations()\n const record = ctx.record\n const lines: string[] = []\n appendLine(lines, 'Batch number', record.batch_number ?? record.batchNumber)\n appendLine(lines, 'Commodity', record.commodity)\n appendLine(lines, 'Supplier', resolveSupplierName(record))\n return buildIndexSource(ctx, buildSubmissionPresenter(translate, record), lines)\n },\n formatResult: async (ctx) => {\n const { t: translate } = await resolveTranslations()\n return buildSubmissionPresenter(translate, ctx.record)\n },\n resolveUrl: async (ctx) => buildRecordUrl(EUDR_EVIDENCE_SUBMISSIONS_URL, ctx.record),\n aclFeatures: ['eudr.submissions.view'],\n },\n ],\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QACX,YAAY,CAAC,gBAAgB,WAAW;AAAA,QACxC,UAAU,CAAC,iBAAiB,OAAO;AAAA,MACrC;AAAA,MACA,aAAa,OAAO,QAAQ;AAC1B,4BAAoB,GAAG;AACvB,cAAM,EAAE,GAAG,UAAU,IAAI,MAAM,oBAAoB;AACnD,cAAM,SAAS,IAAI;AACnB,cAAM,QAAkB,CAAC;AACzB,mBAAW,OAAO,gBAAgB,OAAO,gBAAgB,OAAO,WAAW;AAC3E,mBAAW,OAAO,aAAa,OAAO,SAAS;AAC/C,mBAAW,OAAO,YAAY,oBAAoB,MAAM,CAAC;AACzD,eAAO,iBAAiB,KAAK,yBAAyB,WAAW,MAAM,GAAG,KAAK;AAAA,MACjF;AAAA,MACA,cAAc,OAAO,QAAQ;AAC3B,cAAM,EAAE,GAAG,UAAU,IAAI,MAAM,oBAAoB;AACnD,eAAO,yBAAyB,WAAW,IAAI,MAAM;AAAA,MACvD;AAAA,MACA,YAAY,OAAO,QAAQ,eAAe,+BAA+B,IAAI,MAAM;AAAA,MACnF,aAAa,CAAC,uBAAuB;AAAA,IACvC;AAAA,EACF;AACF;AAEA,IAAO,iBAAQ;AACR,MAAM,SAAS;",
4
+ "sourcesContent": ["import type { SearchBuildContext, SearchIndexSource, SearchModuleConfig, SearchResultPresenter } from '@open-mercato/shared/modules/search'\nimport type { TranslateFn } from '@open-mercato/shared/lib/i18n/context'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\n\nconst EUDR_STATEMENTS_URL = '/backend/eudr/statements'\nconst EUDR_PLOTS_URL = '/backend/eudr/plots'\nconst EUDR_EVIDENCE_SUBMISSIONS_URL = '/backend/eudr/evidence-submissions'\n\nfunction assertTenantContext(ctx: SearchBuildContext): void {\n if (typeof ctx.tenantId !== 'string' || ctx.tenantId.length === 0) {\n throw new Error('[internal] [search.eudr] Missing tenantId in search build context')\n }\n}\n\nfunction normalizeText(value: unknown): string | null {\n if (value === null || value === undefined) return null\n if (typeof value === 'string') {\n const trimmed = value.trim()\n return trimmed.length > 0 ? trimmed : null\n }\n if (value instanceof Date) return value.toISOString()\n if (typeof value === 'number' || typeof value === 'boolean') return String(value)\n return null\n}\n\nfunction readRecordText(record: Record<string, unknown>, ...keys: string[]): string | null {\n for (const key of keys) {\n const text = normalizeText(record[key])\n if (text) return text\n }\n return null\n}\n\nfunction readObjectText(source: unknown, ...keys: string[]): string | null {\n if (!source || typeof source !== 'object') return null\n return readRecordText(source as Record<string, unknown>, ...keys)\n}\n\nfunction formatSubtitle(...parts: Array<unknown>): string | undefined {\n const text = parts\n .map((part) => normalizeText(part))\n .filter((value): value is string => Boolean(value))\n if (!text.length) return undefined\n return text.join(' \u00B7 ')\n}\n\nfunction appendLine(lines: string[], label: string, value: unknown) {\n const text = normalizeText(value)\n if (!text) return\n lines.push(`${label}: ${text}`)\n}\n\nfunction friendlyLabel(input: string): string {\n return input\n .replace(/^cf:/, '')\n .replace(/_/g, ' ')\n .replace(/([a-z])([A-Z])/g, (_match, firstChar, secondChar) => `${firstChar} ${secondChar}`)\n .replace(/\\b\\w/g, (character) => character.toUpperCase())\n}\n\nfunction appendCustomFieldLines(lines: string[], customFields: Record<string, unknown>) {\n for (const [key, value] of Object.entries(customFields)) {\n if (value === null || value === undefined) continue\n appendLine(lines, friendlyLabel(key), value)\n }\n}\n\nfunction buildIndexSource(\n ctx: SearchBuildContext,\n presenter: SearchResultPresenter,\n lines: string[],\n): SearchIndexSource | null {\n appendCustomFieldLines(lines, ctx.customFields)\n if (!lines.length) return null\n return {\n text: lines,\n presenter,\n checksumSource: { record: ctx.record, customFields: ctx.customFields },\n }\n}\n\nfunction buildRecordUrl(baseUrl: string, record: Record<string, unknown>): string | null {\n const recordId = readRecordText(record, 'id')\n return recordId ? `${baseUrl}/${encodeURIComponent(recordId)}` : null\n}\n\nfunction translateToken(translate: TranslateFn, prefix: string, value: string | null): string | null {\n if (!value) return null\n return translate(`${prefix}.${value}`, value)\n}\n\nfunction resolveSupplierName(record: Record<string, unknown>): string | null {\n const snapshot = record.supplier_snapshot ?? record.supplierSnapshot\n return readObjectText(snapshot, 'display_name', 'displayName', 'name')\n}\n\nfunction buildStatementPresenter(translate: TranslateFn, record: Record<string, unknown>): SearchResultPresenter {\n const title = readRecordText(record, 'title') ?? translate('eudr.common.recordUnavailable')\n const subtitle = formatSubtitle(\n readRecordText(record, 'reference_number', 'referenceNumber'),\n translateToken(translate, 'eudr.commodity', readRecordText(record, 'commodity')),\n )\n return { title, subtitle, icon: 'file-check' }\n}\n\nfunction buildPlotPresenter(translate: TranslateFn, record: Record<string, unknown>): SearchResultPresenter {\n const title = readRecordText(record, 'name') ?? translate('eudr.common.recordUnavailable')\n const subtitle = formatSubtitle(\n readRecordText(record, 'origin_country', 'originCountry'),\n translateToken(translate, 'eudr.plotType', readRecordText(record, 'plot_type', 'plotType')),\n )\n return { title, subtitle, icon: 'map-pin' }\n}\n\nfunction buildSubmissionPresenter(translate: TranslateFn, record: Record<string, unknown>): SearchResultPresenter {\n const label = translate('eudr.search.badge.submission', 'Evidence submission')\n const batchNumber = readRecordText(record, 'batch_number', 'batchNumber')\n const supplierName = resolveSupplierName(record)\n const title = batchNumber\n ? `${label} ${batchNumber}`\n : supplierName ?? translate('eudr.common.recordUnavailable')\n const subtitle = formatSubtitle(\n supplierName,\n translateToken(translate, 'eudr.submissionStatus', readRecordText(record, 'status')),\n )\n return { title, subtitle, icon: 'package' }\n}\n\nexport const searchConfig: SearchModuleConfig = {\n entities: [\n {\n entityId: 'eudr:eudr_due_diligence_statement',\n enabled: true,\n priority: 8,\n fieldPolicy: {\n searchable: ['title', 'reference_number', 'commodity'],\n excluded: ['notes'],\n },\n buildSource: async (ctx) => {\n assertTenantContext(ctx)\n const { t: translate } = await resolveTranslations()\n const record = ctx.record\n const lines: string[] = []\n appendLine(lines, 'Title', record.title)\n appendLine(lines, 'Reference number', record.reference_number ?? record.referenceNumber)\n appendLine(lines, 'Commodity', record.commodity)\n return buildIndexSource(ctx, buildStatementPresenter(translate, record), lines)\n },\n formatResult: async (ctx) => {\n const { t: translate } = await resolveTranslations()\n return buildStatementPresenter(translate, ctx.record)\n },\n resolveUrl: async (ctx) => buildRecordUrl(EUDR_STATEMENTS_URL, ctx.record),\n aclFeatures: ['eudr.statements.view'],\n },\n {\n entityId: 'eudr:eudr_plot',\n enabled: true,\n priority: 7,\n fieldPolicy: {\n searchable: ['name', 'external_id', 'origin_country'],\n excluded: ['producer_name'],\n },\n buildSource: async (ctx) => {\n assertTenantContext(ctx)\n const { t: translate } = await resolveTranslations()\n const record = ctx.record\n const lines: string[] = []\n appendLine(lines, 'Name', record.name)\n appendLine(lines, 'External ID', record.external_id ?? record.externalId)\n appendLine(lines, 'Origin country', record.origin_country ?? record.originCountry)\n return buildIndexSource(ctx, buildPlotPresenter(translate, record), lines)\n },\n formatResult: async (ctx) => {\n const { t: translate } = await resolveTranslations()\n return buildPlotPresenter(translate, ctx.record)\n },\n resolveUrl: async (ctx) => buildRecordUrl(EUDR_PLOTS_URL, ctx.record),\n aclFeatures: ['eudr.plots.view'],\n },\n {\n entityId: 'eudr:eudr_evidence_submission',\n enabled: true,\n priority: 6,\n fieldPolicy: {\n searchable: ['batch_number', 'commodity'],\n excluded: ['producer_name', 'notes'],\n },\n buildSource: async (ctx) => {\n assertTenantContext(ctx)\n const { t: translate } = await resolveTranslations()\n const record = ctx.record\n const lines: string[] = []\n appendLine(lines, 'Batch number', record.batch_number ?? record.batchNumber)\n appendLine(lines, 'Commodity', record.commodity)\n appendLine(lines, 'Supplier', resolveSupplierName(record))\n return buildIndexSource(ctx, buildSubmissionPresenter(translate, record), lines)\n },\n formatResult: async (ctx) => {\n const { t: translate } = await resolveTranslations()\n return buildSubmissionPresenter(translate, ctx.record)\n },\n resolveUrl: async (ctx) => buildRecordUrl(EUDR_EVIDENCE_SUBMISSIONS_URL, ctx.record),\n aclFeatures: ['eudr.submissions.view'],\n },\n ],\n}\n\nexport default searchConfig\nexport const config = searchConfig\n"],
5
+ "mappings": "AAEA,SA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AM,oBAAoB;AACnD,cAAM,SAAS,IAAI;AACnB,cAAM,QAAkB,CAAC;AACzB,mBAAW,OAAO,gBAAgB,OAAO,gBAAgB,OAAO,WAAW;AAC3E,mBAAW,OAAO,aAAa,OAAO,SAAS;AAC/C,mBAAW,OAAO,YAAY,oBAAoB,MAAM,CAAC;AACzD,eAAO,iBAAiB,KAAK,yBAAyB,WAAW,MAAM,GAAG,KAAK;AAAA,MACjF;AAAA,MACA,cAAc,OAAO,QAAQ;AAC3B,cAAM,EAAE,GAAG,UAAU,IAAI,MAAM,oBAAoB;AACnD,eAAO,yBAAyB,WAAW,IAAI,MAAM;AAAA,MACvD;AAAA,MACA,YAAY,OAAO,QAAQ,eAAe,+BAA+B,IAAI,MAAM;AAAA,MACnF,aAAa,CAAC,uBAAuB;AAAA,IACvC;AAAA,EACF;AACF;AAEA,IAAO,iBAAQ;AACR,MAAM,SAAS;",
6
6
  "names": []
7
7
  }
@@ -10,6 +10,9 @@ function toNumeric(value) {
10
10
  function mapPersistedLine(line) {
11
11
  return {
12
12
  id: line.id,
13
+ statusEntryId: line.statusEntryId ?? null,
14
+ catalogSnapshot: line.catalogSnapshot ? cloneJson(line.catalogSnapshot) : null,
15
+ promotionSnapshot: line.promotionSnapshot ? cloneJson(line.promotionSnapshot) : null,
13
16
  lineNumber: line.lineNumber,
14
17
  kind: line.kind,
15
18
  productId: line.productId ?? null,
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/sales/lib/lineSnapshots.ts"],
4
- "sourcesContent": ["import type { SalesOrderLine, SalesQuoteLine } from '../data/entities'\nimport { cloneJson } from './json'\nimport type { SalesLineDiscountBasis, SalesLineSnapshot } from './types'\n\nfunction toNumeric(value: unknown): number {\n if (typeof value === 'number' && Number.isFinite(value)) return value\n if (typeof value === 'string' && value.trim().length) {\n const parsed = Number(value)\n if (Number.isFinite(parsed)) return parsed\n }\n return 0\n}\n\nfunction mapPersistedLine(line: SalesOrderLine | SalesQuoteLine): SalesLineSnapshot {\n return {\n id: line.id,\n lineNumber: line.lineNumber,\n kind: line.kind,\n productId: line.productId ?? null,\n productVariantId: line.productVariantId ?? null,\n name: line.name ?? null,\n description: line.description ?? null,\n comment: line.comment ?? null,\n quantity: toNumeric(line.quantity),\n quantityUnit: line.quantityUnit ?? null,\n normalizedQuantity: toNumeric(line.normalizedQuantity ?? line.quantity),\n normalizedUnit: line.normalizedUnit ?? line.quantityUnit ?? null,\n uomSnapshot: line.uomSnapshot ? cloneJson(line.uomSnapshot) : null,\n currencyCode: line.currencyCode,\n unitPriceNet: toNumeric(line.unitPriceNet),\n unitPriceGross: toNumeric(line.unitPriceGross),\n discountAmount: toNumeric(line.discountAmount),\n // The persisted column holds the discount for the whole line, so the\n // calculation engine must not multiply it out by quantity again. This flag\n // is the only thing standing between a round trip and a compounding\n // re-inflation, and it is why mappers must never set `discountAmountBasis`\n // instead \u2014 that one means \"a caller asserted this\".\n discountAmountFromStoredRow: true,\n discountPercent: toNumeric(line.discountPercent),\n taxRate: toNumeric(line.taxRate),\n taxAmount: toNumeric(line.taxAmount),\n // The totals below are the engine's own previous output read back off the\n // row, not something a caller asserted, so they are not reconciled against\n // the recomputed net (#5644) \u2014 on a legacy row that divergence is the\n // discount contract healing itself, not a caller mistake.\n totalsFromStoredRow: true,\n totalNetAmount: toNumeric(line.totalNetAmount),\n totalGrossAmount: toNumeric(line.totalGrossAmount),\n configuration: line.configuration ? cloneJson(line.configuration) : null,\n promotionCode: line.promotionCode ?? null,\n metadata: line.metadata ? cloneJson(line.metadata) : null,\n customFieldSetId: line.customFieldSetId ?? null,\n }\n}\n\n/**\n * Rebuild a calculation snapshot from a persisted order line.\n *\n * Shared by `commands/documents.ts` and `commands/returns.ts` on purpose: the\n * two files used to carry byte-identical copies, and that duplication is why\n * the return flows kept the discount defect after the order flows were fixed.\n */\nexport function mapOrderLineEntityToSnapshot(line: SalesOrderLine): SalesLineSnapshot {\n return mapPersistedLine(line)\n}\n\nexport function mapQuoteLineEntityToSnapshot(line: SalesQuoteLine): SalesLineSnapshot {\n return mapPersistedLine(line)\n}\n\ntype UpsertDiscountFields = Pick<\n SalesLineSnapshot,\n 'discountAmount' | 'discountAmountBasis' | 'discountAmountFromStoredRow'\n>\n\n/**\n * Decide the discount fields of an upsert payload one operand at a time.\n *\n * A line upsert can source its amount from two places with opposite meanings: a\n * caller value, which is per unit unless the caller says otherwise, and the\n * stored row, which is always a line total. Collapsing them into a single\n * `caller ?? stored` expression means whichever origin the merged result is\n * tagged with is wrong half the time \u2014 and the half that breaks is the\n * upsert-existing path, which then re-inflates by a further factor of quantity\n * while looking perfectly correct.\n *\n * Keeping `null` rather than `0` for \"nothing supplied\" is deliberate too: the\n * column cannot represent that distinction, but the payload can, and the\n * calculation engine needs it to tell a suppressing zero from an absent value.\n */\nexport function resolveUpsertDiscountFields(\n callerAmount: number | null | undefined,\n callerBasis: SalesLineDiscountBasis | null | undefined,\n existingSnapshot: Pick<SalesLineSnapshot, 'discountAmount'> | null | undefined,\n): UpsertDiscountFields {\n if (callerAmount !== null && callerAmount !== undefined) {\n return { discountAmount: callerAmount, discountAmountBasis: callerBasis ?? 'unit' }\n }\n return {\n discountAmount: existingSnapshot?.discountAmount ?? null,\n discountAmountFromStoredRow: existingSnapshot != null,\n }\n}\n\n/**\n * Decide whether the `totalNetAmount` an upsert payload ends up carrying is a\n * caller assertion or a value that came back off the stored row.\n *\n * The upsert merges caller input over the existing snapshot, so the merged\n * total has two possible origins and only the caller one is worth reconciling\n * against the recomputed net (#5644): a value read back off the row is what the\n * engine itself wrote last time, and on a legacy row it is exactly what\n * recalculation is supposed to heal.\n */\nexport function resolveUpsertTotalsOrigin(\n callerTotalNetAmount: number | null | undefined,\n existingSnapshot: Pick<SalesLineSnapshot, 'totalNetAmount'> | null | undefined,\n): Pick<SalesLineSnapshot, 'totalsFromStoredRow'> {\n if (callerTotalNetAmount !== null && callerTotalNetAmount !== undefined) return {}\n return existingSnapshot != null ? { totalsF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ACjD,eAAe,KAAK,gBAAgB,UAAU,KAAK,aAAa,IAAI;AAAA,IACpE,eAAe,KAAK,iBAAiB;AAAA,IACrC,UAAU,KAAK,WAAW,UAAU,KAAK,QAAQ,IAAI;AAAA,IACrD,kBAAkB,KAAK,oBAAoB;AAAA,EAC7C;AACF;AASO,SAAS,6BAA6B,MAAyC;AACpF,SAAO,iBAAiB,IAAI;AAC9B;AAEO,SAAS,6BAA6B,MAAyC;AACpF,SAAO,iBAAiB,IAAI;AAC9B;AAsBO,SAAS,4BACd,cACA,aACA,kBACsB;AACtB,MAAI,iBAAiB,QAAQ,iBAAiB,QAAW;AACvD,WAAO,EAAE,gBAAgB,cAAc,qBAAqB,eAAe,OAAO;AAAA,EACpF;AACA,SAAO;AAAA,IACL,gBAAgB,kBAAkB,kBAAkB;AAAA,IACpD,6BAA6B,oBAAoB;AAAA,EACnD;AACF;AAYO,SAAS,0BACd,sBACA,kBACgD;AAChD,MAAI,yBAAyB,QAAQ,yBAAyB,OAAW,QAAO,CAAC;AACjF,SAAO,oBAAoB,OAAO,EAAE,qBAAqB,KAAK,IAAI,CAAC;AACrE;",
4
+ "sourcesContent": ["import type { SalesOrderLine, SalesQuoteLine } from '../data/entities'\nimport { cloneJson } from './json'\nimport type { SalesLineDiscountBasis, SalesLineSnapshot } from './types'\n\nfunction toNumeric(value: unknown): number {\n if (typeof value === 'number' && Number.isFinite(value)) return value\n if (typeof value === 'string' && value.trim().length) {\n const parsed = Number(value)\n if (Number.isFinite(parsed)) return parsed\n }\n return 0\n}\n\n/**\n * A snapshot rebuilt from a persisted row, plus the columns the calculation\n * engine never reads but the write paths must carry back to the row.\n *\n * The line upsert, line delete and adjustment write paths all rebuild *every*\n * line of the document from these snapshots and then `Object.assign` the result\n * onto the existing entities. Anything the mapper drops is therefore not merely\n * absent from the calculation \u2014 it is written back as `null` over the stored\n * value of lines the caller never touched (#5911).\n */\nexport type SalesPersistedLineSnapshot = SalesLineSnapshot & {\n statusEntryId: string | null\n catalogSnapshot: Record<string, unknown> | null\n promotionSnapshot: Record<string, unknown> | null\n}\n\nfunction mapPersistedLine(line: SalesOrderLine | SalesQuoteLine): SalesPersistedLineSnapshot {\n return {\n id: line.id,\n statusEntryId: line.statusEntryId ?? null,\n catalogSnapshot: line.catalogSnapshot ? cloneJson(line.catalogSnapshot) : null,\n promotionSnapshot: line.promotionSnapshot ? cloneJson(line.promotionSnapshot) : null,\n lineNumber: line.lineNumber,\n kind: line.kind,\n productId: line.productId ?? null,\n productVariantId: line.productVariantId ?? null,\n name: line.name ?? null,\n description: line.description ?? null,\n comment: line.comment ?? null,\n quantity: toNumeric(line.quantity),\n quantityUnit: line.quantityUnit ?? null,\n normalizedQuantity: toNumeric(line.normalizedQuantity ?? line.quantity),\n normalizedUnit: line.normalizedUnit ?? line.quantityUnit ?? null,\n uomSnapshot: line.uomSnapshot ? cloneJson(line.uomSnapshot) : null,\n currencyCode: line.currencyCode,\n unitPriceNet: toNumeric(line.unitPriceNet),\n unitPriceGross: toNumeric(line.unitPriceGross),\n discountAmount: toNumeric(line.discountAmount),\n // The persisted column holds the discount for the whole line, so the\n // calculation engine must not multiply it out by quantity again. This flag\n // is the only thing standing between a round trip and a compounding\n // re-inflation, and it is why mappers must never set `discountAmountBasis`\n // instead \u2014 that one means \"a caller asserted this\".\n discountAmountFromStoredRow: true,\n discountPercent: toNumeric(line.discountPercent),\n taxRate: toNumeric(line.taxRate),\n taxAmount: toNumeric(line.taxAmount),\n // The totals below are the engine's own previous output read back off the\n // row, not something a caller asserted, so they are not reconciled against\n // the recomputed net (#5644) \u2014 on a legacy row that divergence is the\n // discount contract healing itself, not a caller mistake.\n totalsFromStoredRow: true,\n totalNetAmount: toNumeric(line.totalNetAmount),\n totalGrossAmount: toNumeric(line.totalGrossAmount),\n configuration: line.configuration ? cloneJson(line.configuration) : null,\n promotionCode: line.promotionCode ?? null,\n metadata: line.metadata ? cloneJson(line.metadata) : null,\n customFieldSetId: line.customFieldSetId ?? null,\n }\n}\n\n/**\n * Rebuild a calculation snapshot from a persisted order line.\n *\n * Shared by `commands/documents.ts` and `commands/returns.ts` on purpose: the\n * two files used to carry byte-identical copies, and that duplication is why\n * the return flows kept the discount defect after the order flows were fixed.\n */\nexport function mapOrderLineEntityToSnapshot(line: SalesOrderLine): SalesPersistedLineSnapshot {\n return mapPersistedLine(line)\n}\n\nexport function mapQuoteLineEntityToSnapshot(line: SalesQuoteLine): SalesPersistedLineSnapshot {\n return mapPersistedLine(line)\n}\n\ntype UpsertDiscountFields = Pick<\n SalesLineSnapshot,\n 'discountAmount' | 'discountAmountBasis' | 'discountAmountFromStoredRow'\n>\n\n/**\n * Decide the discount fields of an upsert payload one operand at a time.\n *\n * A line upsert can source its amount from two places with opposite meanings: a\n * caller value, which is per unit unless the caller says otherwise, and the\n * stored row, which is always a line total. Collapsing them into a single\n * `caller ?? stored` expression means whichever origin the merged result is\n * tagged with is wrong half the time \u2014 and the half that breaks is the\n * upsert-existing path, which then re-inflates by a further factor of quantity\n * while looking perfectly correct.\n *\n * Keeping `null` rather than `0` for \"nothing supplied\" is deliberate too: the\n * column cannot represent that distinction, but the payload can, and the\n * calculation engine needs it to tell a suppressing zero from an absent value.\n */\nexport function resolveUpsertDiscountFields(\n callerAmount: number | null | undefined,\n callerBasis: SalesLineDiscountBasis | null | undefined,\n existingSnapshot: Pick<SalesLineSnapshot, 'discountAmount'> | null | undefined,\n): UpsertDiscountFields {\n if (callerAmount !== null && callerAmount !== undefined) {\n return { discountAmount: callerAmount, discountAmountBasis: callerBasis ?? 'unit' }\n }\n return {\n discountAmount: existingSnapshot?.discountAmount ?? null,\n discountAmountFromStoredRow: existingSnapshot != null,\n }\n}\n\n/**\n * Decide whether the `totalNetAmount` an upsert payload ends up carrying is a\n * caller assertion or a value that came back off the stored row.\n *\n * The upsert merges caller input over the existing snapshot, so the merged\n * total has two possible origins and only the caller one is worth reconciling\n * against the recomputed net (#5644): a value read back off the row is what the\n * engine itself wrote last time, and on a legacy row it is exactly what\n * recalculation is supposed to heal.\n */\nexport function resolveUpsertTotalsOrigin(\n callerTotalNetAmount: number | null | undefined,\n existingSnapshot: Pick<SalesLineSnapshot, 'totalNetAmount'> | null | undefined,\n): Pick<SalesLineSnapshot, 'totalsFromStoredRow'> {\n if (callerTotalNetAmount !== null && callerTotalNetAmount !== undefined) return {}\n return existingSnapshot != null ? { totalsFromStoredRow: true } : {}\n}\n"],
5
+ "mappings": "AACA,SAAS,iBAAiB;AAG1B,SAAS,UAAU,OAAwB;AACzC,MAAI,OAAO,UAAU,YAAY,OAAO,SAAS,KAAK,EAAG,QAAO;AAChE,MAAI,OAAO,UAAU,YAAY,MAAM,KAAK,EAAE,QAAQ;AACpD,UAAM,SAAS,OAAO,KAAK;AAC3B,QAAI,OAAO,SAAS,MAAM,EAAG,QAAO;AAAA,EACtC;AACA,SAAO;AACT;AAkBA,SAAS,iBAAiB,MAAmE;AAC3F,SAAO;AAAA,IACL,IAAI,KAAK;AAAA,IACT,eAAe,KAAK,iBAAiB;AAAA,IACrC,iBAAiB,KAAK,kBAAkB,UAAU,KAAK,eAAe,IAAI;AAAA,IAC1E,mBAAmB,KAAK,oBAAoB,UAAU,KAAK,iBAAiB,IAAI;AAAA,IAChF,YAAY,KAAK;AAAA,IACjB,MAAM,KAAK;AAAA,IACX,WAAW,KAAK,aAAa;AAAA,IAC7B,kBAAkB,KAAK,oBAAoB;AAAA,IAC3C,MAAM,KAAK,QAAQ;AAAA,IACnB,aAAa,KAAK,eAAe;AAAA,IACjC,SAAS,KAAK,WAAW;AAAA,IACzB,UAAU,UAAU,KAAK,QAAQ;AAAA,IACjC,cAAc,KAAK,gBAAgB;AAAA,IACnC,oBAAoB,UAAU,KAAK,sBAAsB,KAAK,QAAQ;AAAA,IACtE,gBAAgB,KAAK,kBAAkB,KAAK,gBAAgB;AAAA,IAC5D,aAAa,KAAK,cAAc,UAAU,KAAK,WAAW,IAAI;AAAA,IAC9D,cAAc,KAAK;AAAA,IACnB,cAAc,UAAU,KAAK,YAAY;AAAA,IACzC,gBAAgB,UAAU,KAAK,cAAc;AAAA,IAC7C,gBAAgB,UAAU,KAAK,cAAc;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAM7C,6BAA6B;AAAA,IAC7B,iBAAiB,UAAU,KAAK,eAAe;AAAA,IAC/C,SAAS,UAAU,KAAK,OAAO;AAAA,IAC/B,WAAW,UAAU,KAAK,SAAS;AAAA;AAAA;AAAA;AAAA;AAAA,IAKnC,qBAAqB;AAAA,IACrB,gBAAgB,UAAU,KAAK,cAAc;AAAA,IAC7C,kBAAkB,UAAU,KAAK,gBAAgB;AAAA,IACjD,eAAe,KAAK,gBAAgB,UAAU,KAAK,aAAa,IAAI;AAAA,IACpE,eAAe,KAAK,iBAAiB;AAAA,IACrC,UAAU,KAAK,WAAW,UAAU,KAAK,QAAQ,IAAI;AAAA,IACrD,kBAAkB,KAAK,oBAAoB;AAAA,EAC7C;AACF;AASO,SAAS,6BAA6B,MAAkD;AAC7F,SAAO,iBAAiB,IAAI;AAC9B;AAEO,SAAS,6BAA6B,MAAkD;AAC7F,SAAO,iBAAiB,IAAI;AAC9B;AAsBO,SAAS,4BACd,cACA,aACA,kBACsB;AACtB,MAAI,iBAAiB,QAAQ,iBAAiB,QAAW;AACvD,WAAO,EAAE,gBAAgB,cAAc,qBAAqB,eAAe,OAAO;AAAA,EACpF;AACA,SAAO;AAAA,IACL,gBAAgB,kBAAkB,kBAAkB;AAAA,IACpD,6BAA6B,oBAAoB;AAAA,EACnD;AACF;AAYO,SAAS,0BACd,sBACA,kBACgD;AAChD,MAAI,yBAAyB,QAAQ,yBAAyB,OAAW,QAAO,CAAC;AACjF,SAAO,oBAAoB,OAAO,EAAE,qBAAqB,KAAK,IAAI,CAAC;AACrE;",
6
6
  "names": []
7
7
  }
@@ -37,13 +37,13 @@ function buildWarehousePresenter(t, record) {
37
37
  const label = t("wms.search.badge.warehouse", "Warehouse");
38
38
  const title = pickString(record.name, record.code, record.id) ?? label;
39
39
  const subtitle = formatSubtitle(record.code, record.city, record.country);
40
- return { title, subtitle, icon: "warehouse", badge: label };
40
+ return { title, subtitle, icon: "warehouse" };
41
41
  }
42
42
  function buildLocationPresenter(t, record) {
43
43
  const label = t("wms.search.badge.location", "Location");
44
44
  const title = pickString(record.code, record.id) ?? label;
45
45
  const subtitle = formatSubtitle(record.type, record.warehouse_id ?? record.warehouseId);
46
- return { title, subtitle, icon: "map-pinned", badge: label };
46
+ return { title, subtitle, icon: "map-pinned" };
47
47
  }
48
48
  function buildInventoryProfilePresenter(t, record) {
49
49
  const label = t("wms.search.badge.inventoryProfile", "Inventory profile");
@@ -55,13 +55,13 @@ function buildInventoryProfilePresenter(t, record) {
55
55
  record.default_uom ?? record.defaultUom,
56
56
  variantId ? t("wms.search.profile.variantScoped", "Variant-scoped") : t("wms.search.profile.productScoped", "Product-scoped")
57
57
  );
58
- return { title, subtitle, icon: "boxes", badge: label };
58
+ return { title, subtitle, icon: "boxes" };
59
59
  }
60
60
  function buildLotPresenter(t, record) {
61
61
  const label = t("wms.search.badge.lot", "Inventory lot");
62
62
  const title = pickString(record.lot_number, record.lotNumber, record.batch_number, record.batchNumber, record.id) ?? label;
63
63
  const subtitle = formatSubtitle(record.catalog_variant_id ?? record.catalogVariantId, record.status, record.expires_at ?? record.expiresAt);
64
- return { title, subtitle, icon: "package-search", badge: label };
64
+ return { title, subtitle, icon: "package-search" };
65
65
  }
66
66
  const searchConfig = {
67
67
  entities: [
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/modules/wms/search.ts"],
4
- "sourcesContent": ["import type {\n SearchBuildContext,\n SearchIndexSource,\n SearchModuleConfig,\n SearchResultPresenter,\n} from '@open-mercato/shared/modules/search'\nimport type { TranslateFn } from '@open-mercato/shared/lib/i18n/context'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport { E } from '#generated/entities.ids.generated'\n\nconst WMS_ROOT_URL = '/backend/wms'\nconst WMS_INVENTORY_URL = '/backend/wms/inventory'\nconst WMS_CONFIG_URL = '/backend/config/wms'\n\nfunction pickString(...candidates: Array<unknown>): string | null {\n for (const candidate of candidates) {\n if (typeof candidate !== 'string') continue\n const trimmed = candidate.trim()\n if (trimmed.length > 0) return trimmed\n }\n return null\n}\n\nfunction appendLine(lines: string[], label: string, value: unknown) {\n if (value === null || value === undefined) return\n const text = Array.isArray(value)\n ? value.map((item) => (item == null ? '' : String(item))).filter(Boolean).join(', ')\n : typeof value === 'object'\n ? JSON.stringify(value)\n : String(value)\n if (!text.trim()) return\n lines.push(`${label}: ${text}`)\n}\n\nfunction formatSubtitle(...parts: Array<unknown>): string | undefined {\n const values = parts\n .map((part) => (part == null ? '' : String(part)).trim())\n .filter(Boolean)\n if (!values.length) return undefined\n return values.join(' \u00B7 ')\n}\n\nfunction buildIndexSource(\n ctx: SearchBuildContext,\n presenter: SearchResultPresenter,\n lines: string[],\n): SearchIndexSource | null {\n for (const [key, value] of Object.entries(ctx.customFields)) {\n appendLine(lines, key.replace(/^cf:/, ''), value)\n }\n if (!lines.length) return null\n return {\n text: lines,\n presenter,\n checksumSource: { record: ctx.record, customFields: ctx.customFields },\n }\n}\n\nfunction buildWarehousePresenter(\n t: TranslateFn,\n record: Record<string, unknown>,\n): SearchResultPresenter {\n const label = t('wms.search.badge.warehouse', 'Warehouse')\n const title = pickString(record.name, record.code, record.id) ?? label\n const subtitle = formatSubtitle(record.code, record.city, record.country)\n return { title, subtitle, icon: 'warehouse', badge: label }\n}\n\nfunction buildLocationPresenter(\n t: TranslateFn,\n record: Record<string, unknown>,\n): SearchResultPresenter {\n const label = t('wms.search.badge.location', 'Location')\n const title = pickString(record.code, record.id) ?? label\n const subtitle = formatSubtitle(record.type, record.warehouse_id ?? record.warehouseId)\n return { title, subtitle, icon: 'map-pinned', badge: label }\n}\n\nfunction buildInventoryProfilePresenter(\n t: TranslateFn,\n record: Record<string, unknown>,\n): SearchResultPresenter {\n const label = t('wms.search.badge.inventoryProfile', 'Inventory profile')\n const productId = pickString(record.catalog_product_id, record.catalogProductId)\n const variantId = pickString(record.catalog_variant_id, record.catalogVariantId)\n const title = variantId || productId || pickString(record.id) || label\n const subtitle = formatSubtitle(\n record.default_strategy ?? record.defaultStrategy,\n record.default_uom ?? record.defaultUom,\n variantId ? t('wms.search.profile.variantScoped', 'Variant-scoped') : t('wms.search.profile.productScoped', 'Product-scoped'),\n )\n return { title, subtitle, icon: 'boxes', badge: label }\n}\n\nfunction buildLotPresenter(\n t: TranslateFn,\n record: Record<string, unknown>,\n): SearchResultPresenter {\n const label = t('wms.search.badge.lot', 'Inventory lot')\n const title = pickString(record.lot_number, record.lotNumber, record.batch_number, record.batchNumber, record.id) ?? label\n const subtitle = formatSubtitle(record.catalog_variant_id ?? record.catalogVariantId, record.status, record.expires_at ?? record.expiresAt)\n return { title, subtitle, icon: 'package-search', badge: label }\n}\n\nexport const searchConfig: SearchModuleConfig = {\n entities: [\n {\n entityId: E.wms.warehouse,\n aclFeatures: ['wms.view'],\n enabled: true,\n priority: 8,\n buildSource: async (ctx) => {\n const { t } = await resolveTranslations()\n const record = ctx.record\n const lines: string[] = []\n appendLine(lines, 'Name', record.name)\n appendLine(lines, 'Code', record.code)\n appendLine(lines, 'City', record.city)\n appendLine(lines, 'Country', record.country)\n appendLine(lines, 'Timezone', record.timezone)\n return buildIndexSource(ctx, buildWarehousePresenter(t, record), lines)\n },\n formatResult: async (ctx) => {\n const { t } = await resolveTranslations()\n return buildWarehousePresenter(t, ctx.record)\n },\n resolveUrl: async () => WMS_CONFIG_URL,\n fieldPolicy: {\n searchable: ['name', 'code', 'city', 'country', 'timezone'],\n },\n },\n {\n entityId: E.wms.warehouse_location,\n aclFeatures: ['wms.view'],\n enabled: true,\n priority: 7,\n buildSource: async (ctx) => {\n const { t } = await resolveTranslations()\n const record = ctx.record\n const lines: string[] = []\n appendLine(lines, 'Code', record.code)\n appendLine(lines, 'Type', record.type)\n appendLine(lines, 'Warehouse', record.warehouse_id ?? record.warehouseId)\n appendLine(lines, 'Parent', record.parent_id ?? record.parentId)\n appendLine(lines, 'Capacity units', record.capacity_units ?? record.capacityUnits)\n appendLine(lines, 'Capacity weight', record.capacity_weight ?? record.capacityWeight)\n return buildIndexSource(ctx, buildLocationPresenter(t, record), lines)\n },\n formatResult: async (ctx) => {\n const { t } = await resolveTranslations()\n return buildLocationPresenter(t, ctx.record)\n },\n resolveUrl: async () => WMS_CONFIG_URL,\n fieldPolicy: {\n searchable: ['code', 'type', 'warehouse_id', 'parent_id', 'capacity_units', 'capacity_weight'],\n },\n },\n {\n entityId: E.wms.product_inventory_profile,\n aclFeatures: ['wms.view'],\n enabled: true,\n priority: 8,\n buildSource: async (ctx) => {\n const { t } = await resolveTranslations()\n const record = ctx.record\n const lines: string[] = []\n appendLine(lines, 'Product', record.catalog_product_id ?? record.catalogProductId)\n appendLine(lines, 'Variant', record.catalog_variant_id ?? record.catalogVariantId)\n appendLine(lines, 'Default UOM', record.default_uom ?? record.defaultUom)\n appendLine(lines, 'Strategy', record.default_strategy ?? record.defaultStrategy)\n appendLine(lines, 'Reorder point', record.reorder_point ?? record.reorderPoint)\n appendLine(lines, 'Safety stock', record.safety_stock ?? record.safetyStock)\n appendLine(lines, 'Track lot', record.track_lot ?? record.trackLot)\n appendLine(lines, 'Track serial', record.track_serial ?? record.trackSerial)\n appendLine(lines, 'Track expiration', record.track_expiration ?? record.trackExpiration)\n return buildIndexSource(ctx, buildInventoryProfilePresenter(t, record), lines)\n },\n formatResult: async (ctx) => {\n const { t } = await resolveTranslations()\n return buildInventoryProfilePresenter(t, ctx.record)\n },\n resolveUrl: async (ctx) => {\n const variantId = pickString(ctx.record.catalog_variant_id, ctx.record.catalogVariantId)\n if (variantId) return `${WMS_ROOT_URL}/sku/${variantId}`\n return WMS_CONFIG_URL\n },\n resolveLinks: async () => [{ href: WMS_INVENTORY_URL, label: 'Inventory console', kind: 'secondary' }],\n fieldPolicy: {\n searchable: [\n 'catalog_product_id',\n 'catalog_variant_id',\n 'default_uom',\n 'default_strategy',\n 'reorder_point',\n 'safety_stock',\n ],\n },\n },\n {\n entityId: E.wms.inventory_lot,\n aclFeatures: ['wms.view'],\n enabled: true,\n priority: 6,\n buildSource: async (ctx) => {\n const { t } = await resolveTranslations()\n const record = ctx.record\n const lines: string[] = []\n appendLine(lines, 'Lot number', record.lot_number ?? record.lotNumber)\n appendLine(lines, 'Batch number', record.batch_number ?? record.batchNumber)\n appendLine(lines, 'SKU', record.sku)\n appendLine(lines, 'Variant', record.catalog_variant_id ?? record.catalogVariantId)\n appendLine(lines, 'Status', record.status)\n appendLine(lines, 'Expires at', record.expires_at ?? record.expiresAt)\n return buildIndexSource(ctx, buildLotPresenter(t, record), lines)\n },\n formatResult: async (ctx) => {\n const { t } = await resolveTranslations()\n return buildLotPresenter(t, ctx.record)\n },\n resolveUrl: async (ctx) => {\n const id = pickString(ctx.record.id)\n if (id) return `${WMS_ROOT_URL}/lot/${id}`\n return WMS_ROOT_URL\n },\n resolveLinks: async () => [{ href: WMS_CONFIG_URL, label: 'WMS configuration', kind: 'secondary' }],\n fieldPolicy: {\n searchable: ['lot_number', 'batch_number', 'sku', 'catalog_variant_id', 'status', 'expires_at'],\n },\n },\n ],\n}\n\nexport default searchConfig\nexport const config = searchConfig\n"],
5
- "mappings": "AAOA,SAAS,2BAA2B;AACpC,SAAS,SAAS;AAElB,MAAM,eAAe;AACrB,MAAM,oBAAoB;AAC1B,MAAM,iBAAiB;AAEvB,SAAS,cAAc,YAA2C;AAChE,aAAW,aAAa,YAAY;AAClC,QAAI,OAAO,cAAc,SAAU;AACnC,UAAM,UAAU,UAAU,KAAK;AAC/B,QAAI,QAAQ,SAAS,EAAG,QAAO;AAAA,EACjC;AACA,SAAO;AACT;AAEA,SAAS,WAAW,OAAiB,OAAe,OAAgB;AAClE,MAAI,UAAU,QAAQ,UAAU,OAAW;AAC3C,QAAM,OAAO,MAAM,QAAQ,KAAK,IAC5B,MAAM,IAAI,CAAC,SAAU,QAAQ,OA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A,QACF;AAAA,MACF;AAAA,IACF;AAAA,IACA;AAAA,MACE,UAAU,EAAE,IAAI;AAAA,MAChB,aAAa,CAAC,UAAU;AAAA,MACxB,SAAS;AAAA,MACT,UAAU;AAAA,MACV,aAAa,OAAO,QAAQ;AAC1B,cAAM,EAAE,EAAE,IAAI,MAAM,oBAAoB;AACxC,cAAM,SAAS,IAAI;AACnB,cAAM,QAAkB,CAAC;AACzB,mBAAW,OAAO,cAAc,OAAO,cAAc,OAAO,SAAS;AACrE,mBAAW,OAAO,gBAAgB,OAAO,gBAAgB,OAAO,WAAW;AAC3E,mBAAW,OAAO,OAAO,OAAO,GAAG;AACnC,mBAAW,OAAO,WAAW,OAAO,sBAAsB,OAAO,gBAAgB;AACjF,mBAAW,OAAO,UAAU,OAAO,MAAM;AACzC,mBAAW,OAAO,cAAc,OAAO,cAAc,OAAO,SAAS;AACrE,eAAO,iBAAiB,KAAK,kBAAkB,GAAG,MAAM,GAAG,KAAK;AAAA,MAClE;AAAA,MACA,cAAc,OAAO,QAAQ;AAC3B,cAAM,EAAE,EAAE,IAAI,MAAM,oBAAoB;AACxC,eAAO,kBAAkB,GAAG,IAAI,MAAM;AAAA,MACxC;AAAA,MACA,YAAY,OAAO,QAAQ;AACzB,cAAM,KAAK,WAAW,IAAI,OAAO,EAAE;AACnC,YAAI,GAAI,QAAO,GAAG,YAAY,QAAQ,EAAE;AACxC,eAAO;AAAA,MACT;AAAA,MACA,cAAc,YAAY,CAAC,EAAE,MAAM,gBAAgB,OAAO,qBAAqB,MAAM,YAAY,CAAC;AAAA,MAClG,aAAa;AAAA,QACX,YAAY,CAAC,cAAc,gBAAgB,OAAO,sBAAsB,UAAU,YAAY;AAAA,MAChG;AAAA,IACF;AAAA,EACF;AACF;AAEA,IAAO,iBAAQ;AACR,MAAM,SAAS;",
4
+ "sourcesContent": ["import type {\n SearchBuildContext,\n SearchIndexSource,\n SearchModuleConfig,\n SearchResultPresenter,\n} from '@open-mercato/shared/modules/search'\nimport type { TranslateFn } from '@open-mercato/shared/lib/i18n/context'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport { E } from '#generated/entities.ids.generated'\n\nconst WMS_ROOT_URL = '/backend/wms'\nconst WMS_INVENTORY_URL = '/backend/wms/inventory'\nconst WMS_CONFIG_URL = '/backend/config/wms'\n\nfunction pickString(...candidates: Array<unknown>): string | null {\n for (const candidate of candidates) {\n if (typeof candidate !== 'string') continue\n const trimmed = candidate.trim()\n if (trimmed.length > 0) return trimmed\n }\n return null\n}\n\nfunction appendLine(lines: string[], label: string, value: unknown) {\n if (value === null || value === undefined) return\n const text = Array.isArray(value)\n ? value.map((item) => (item == null ? '' : String(item))).filter(Boolean).join(', ')\n : typeof value === 'object'\n ? JSON.stringify(value)\n : String(value)\n if (!text.trim()) return\n lines.push(`${label}: ${text}`)\n}\n\nfunction formatSubtitle(...parts: Array<unknown>): string | undefined {\n const values = parts\n .map((part) => (part == null ? '' : String(part)).trim())\n .filter(Boolean)\n if (!values.length) return undefined\n return values.join(' \u00B7 ')\n}\n\nfunction buildIndexSource(\n ctx: SearchBuildContext,\n presenter: SearchResultPresenter,\n lines: string[],\n): SearchIndexSource | null {\n for (const [key, value] of Object.entries(ctx.customFields)) {\n appendLine(lines, key.replace(/^cf:/, ''), value)\n }\n if (!lines.length) return null\n return {\n text: lines,\n presenter,\n checksumSource: { record: ctx.record, customFields: ctx.customFields },\n }\n}\n\nfunction buildWarehousePresenter(\n t: TranslateFn,\n record: Record<string, unknown>,\n): SearchResultPresenter {\n const label = t('wms.search.badge.warehouse', 'Warehouse')\n const title = pickString(record.name, record.code, record.id) ?? label\n const subtitle = formatSubtitle(record.code, record.city, record.country)\n return { title, subtitle, icon: 'warehouse' }\n}\n\nfunction buildLocationPresenter(\n t: TranslateFn,\n record: Record<string, unknown>,\n): SearchResultPresenter {\n const label = t('wms.search.badge.location', 'Location')\n const title = pickString(record.code, record.id) ?? label\n const subtitle = formatSubtitle(record.type, record.warehouse_id ?? record.warehouseId)\n return { title, subtitle, icon: 'map-pinned' }\n}\n\nfunction buildInventoryProfilePresenter(\n t: TranslateFn,\n record: Record<string, unknown>,\n): SearchResultPresenter {\n const label = t('wms.search.badge.inventoryProfile', 'Inventory profile')\n const productId = pickString(record.catalog_product_id, record.catalogProductId)\n const variantId = pickString(record.catalog_variant_id, record.catalogVariantId)\n const title = variantId || productId || pickString(record.id) || label\n const subtitle = formatSubtitle(\n record.default_strategy ?? record.defaultStrategy,\n record.default_uom ?? record.defaultUom,\n variantId ? t('wms.search.profile.variantScoped', 'Variant-scoped') : t('wms.search.profile.productScoped', 'Product-scoped'),\n )\n return { title, subtitle, icon: 'boxes' }\n}\n\nfunction buildLotPresenter(\n t: TranslateFn,\n record: Record<string, unknown>,\n): SearchResultPresenter {\n const label = t('wms.search.badge.lot', 'Inventory lot')\n const title = pickString(record.lot_number, record.lotNumber, record.batch_number, record.batchNumber, record.id) ?? label\n const subtitle = formatSubtitle(record.catalog_variant_id ?? record.catalogVariantId, record.status, record.expires_at ?? record.expiresAt)\n return { title, subtitle, icon: 'package-search' }\n}\n\nexport const searchConfig: SearchModuleConfig = {\n entities: [\n {\n entityId: E.wms.warehouse,\n aclFeatures: ['wms.view'],\n enabled: true,\n priority: 8,\n buildSource: async (ctx) => {\n const { t } = await resolveTranslations()\n const record = ctx.record\n const lines: string[] = []\n appendLine(lines, 'Name', record.name)\n appendLine(lines, 'Code', record.code)\n appendLine(lines, 'City', record.city)\n appendLine(lines, 'Country', record.country)\n appendLine(lines, 'Timezone', record.timezone)\n return buildIndexSource(ctx, buildWarehousePresenter(t, record), lines)\n },\n formatResult: async (ctx) => {\n const { t } = await resolveTranslations()\n return buildWarehousePresenter(t, ctx.record)\n },\n resolveUrl: async () => WMS_CONFIG_URL,\n fieldPolicy: {\n searchable: ['name', 'code', 'city', 'country', 'timezone'],\n },\n },\n {\n entityId: E.wms.warehouse_location,\n aclFeatures: ['wms.view'],\n enabled: true,\n priority: 7,\n buildSource: async (ctx) => {\n const { t } = await resolveTranslations()\n const record = ctx.record\n const lines: string[] = []\n appendLine(lines, 'Code', record.code)\n appendLine(lines, 'Type', record.type)\n appendLine(lines, 'Warehouse', record.warehouse_id ?? record.warehouseId)\n appendLine(lines, 'Parent', record.parent_id ?? record.parentId)\n appendLine(lines, 'Capacity units', record.capacity_units ?? record.capacityUnits)\n appendLine(lines, 'Capacity weight', record.capacity_weight ?? record.capacityWeight)\n return buildIndexSource(ctx, buildLocationPresenter(t, record), lines)\n },\n formatResult: async (ctx) => {\n const { t } = await resolveTranslations()\n return buildLocationPresenter(t, ctx.record)\n },\n resolveUrl: async () => WMS_CONFIG_URL,\n fieldPolicy: {\n searchable: ['code', 'type', 'warehouse_id', 'parent_id', 'capacity_units', 'capacity_weight'],\n },\n },\n {\n entityId: E.wms.product_inventory_profile,\n aclFeatures: ['wms.view'],\n enabled: true,\n priority: 8,\n buildSource: async (ctx) => {\n const { t } = await resolveTranslations()\n const record = ctx.record\n const lines: string[] = []\n appendLine(lines, 'Product', record.catalog_product_id ?? record.catalogProductId)\n appendLine(lines, 'Variant', record.catalog_variant_id ?? record.catalogVariantId)\n appendLine(lines, 'Default UOM', record.default_uom ?? record.defaultUom)\n appendLine(lines, 'Strategy', record.default_strategy ?? record.defaultStrategy)\n appendLine(lines, 'Reorder point', record.reorder_point ?? record.reorderPoint)\n appendLine(lines, 'Safety stock', record.safety_stock ?? record.safetyStock)\n appendLine(lines, 'Track lot', record.track_lot ?? record.trackLot)\n appendLine(lines, 'Track serial', record.track_serial ?? record.trackSerial)\n appendLine(lines, 'Track expiration', record.track_expiration ?? record.trackExpiration)\n return buildIndexSource(ctx, buildInventoryProfilePresenter(t, record), lines)\n },\n formatResult: async (ctx) => {\n const { t } = await resolveTranslations()\n return buildInventoryProfilePresenter(t, ctx.record)\n },\n resolveUrl: async (ctx) => {\n const variantId = pickString(ctx.record.catalog_variant_id, ctx.record.catalogVariantId)\n if (variantId) return `${WMS_ROOT_URL}/sku/${variantId}`\n return WMS_CONFIG_URL\n },\n resolveLinks: async () => [{ href: WMS_INVENTORY_URL, label: 'Inventory console', kind: 'secondary' }],\n fieldPolicy: {\n searchable: [\n 'catalog_product_id',\n 'catalog_variant_id',\n 'default_uom',\n 'default_strategy',\n 'reorder_point',\n 'safety_stock',\n ],\n },\n },\n {\n entityId: E.wms.inventory_lot,\n aclFeatures: ['wms.view'],\n enabled: true,\n priority: 6,\n buildSource: async (ctx) => {\n const { t } = await resolveTranslations()\n const record = ctx.record\n const lines: string[] = []\n appendLine(lines, 'Lot number', record.lot_number ?? record.lotNumber)\n appendLine(lines, 'Batch number', record.batch_number ?? record.batchNumber)\n appendLine(lines, 'SKU', record.sku)\n appendLine(lines, 'Variant', record.catalog_variant_id ?? record.catalogVariantId)\n appendLine(lines, 'Status', record.status)\n appendLine(lines, 'Expires at', record.expires_at ?? record.expiresAt)\n return buildIndexSource(ctx, buildLotPresenter(t, record), lines)\n },\n formatResult: async (ctx) => {\n const { t } = await resolveTranslations()\n return buildLotPresenter(t, ctx.record)\n },\n resolveUrl: async (ctx) => {\n const id = pickString(ctx.record.id)\n if (id) return `${WMS_ROOT_URL}/lot/${id}`\n return WMS_ROOT_URL\n },\n resolveLinks: async () => [{ href: WMS_CONFIG_URL, label: 'WMS configuration', kind: 'secondary' }],\n fieldPolicy: {\n searchable: ['lot_number', 'batch_number', 'sku', 'catalog_variant_id', 'status', 'expires_at'],\n },\n },\n ],\n}\n\nexport default searchConfig\nexport const config = searchConfig\n"],
5
+ "mappings": "AAOA,SAAS,2BAA2B;AACpC,SAAS,SAAS;AAElB,MAAM,eAAe;AACrB,MAAM,oBAAoB;AAC1B,MAAM,iBAAiB;AAEvB,SAAS,cAAc,YAA2C;AAChE,aAAW,aAAa,YAAY;AAClC,QAAI,OAAO,cAAc,SAAU;AACnC,UAAM,UAAU,UAAU,KAAK;AAC/B,QAAI,QAAQ,SAAS,EAAG,QAAO;AAAA,EACjC;AACA,SAAO;AACT;AAEA,SAAS,WAAW,OAAiB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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@open-mercato/core",
3
- "version": "0.7.1-develop.7195.1.b5efd1d51a",
3
+ "version": "0.7.1-develop.7200.1.8ba2d93d3f",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -253,16 +253,16 @@
253
253
  "zod": "^4.4.3"
254
254
  },
255
255
  "peerDependencies": {
256
- "@open-mercato/ai-assistant": "0.7.1-develop.7195.1.b5efd1d51a",
257
- "@open-mercato/shared": "0.7.1-develop.7195.1.b5efd1d51a",
258
- "@open-mercato/ui": "0.7.1-develop.7195.1.b5efd1d51a",
256
+ "@open-mercato/ai-assistant": "0.7.1-develop.7200.1.8ba2d93d3f",
257
+ "@open-mercato/shared": "0.7.1-develop.7200.1.8ba2d93d3f",
258
+ "@open-mercato/ui": "0.7.1-develop.7200.1.8ba2d93d3f",
259
259
  "react": "^19.0.0",
260
260
  "react-dom": "^19.0.0"
261
261
  },
262
262
  "devDependencies": {
263
- "@open-mercato/ai-assistant": "0.7.1-develop.7195.1.b5efd1d51a",
264
- "@open-mercato/shared": "0.7.1-develop.7195.1.b5efd1d51a",
265
- "@open-mercato/ui": "0.7.1-develop.7195.1.b5efd1d51a",
263
+ "@open-mercato/ai-assistant": "0.7.1-develop.7200.1.8ba2d93d3f",
264
+ "@open-mercato/shared": "0.7.1-develop.7200.1.8ba2d93d3f",
265
+ "@open-mercato/ui": "0.7.1-develop.7200.1.8ba2d93d3f",
266
266
  "@testing-library/dom": "^10.4.1",
267
267
  "@testing-library/jest-dom": "^7.0.1",
268
268
  "@testing-library/react": "^16.3.3",
@@ -470,6 +470,12 @@ export async function setupInitialTenant(
470
470
  }
471
471
  }
472
472
 
473
+ // Custom roles are often created inside onTenantCreated hooks, so they did not
474
+ // exist yet when ensureDefaultRoleAcls ran above and were skipped there. Sync
475
+ // again now that the hooks have had a chance to create them — idempotent, same
476
+ // pattern as the `mercato auth sync-role-acls` CLI command.
477
+ await ensureCustomRoleAcls(em, tenantId, resolvedModules)
478
+
473
479
  return {
474
480
  tenantId,
475
481
  organizationId,
@@ -36,6 +36,7 @@ const CONFIG_PASSTHROUGH_KEYS: Array<keyof CustomFieldDefinition> = [
36
36
  'formEditable',
37
37
  'listVisible',
38
38
  'indexed',
39
+ 'encrypted',
39
40
  'priority',
40
41
  'editor',
41
42
  'input',
@@ -65,6 +66,12 @@ function configEquals(a: unknown, b: unknown): boolean {
65
66
  return JSON.stringify(normalizeValue(a ?? null)) === JSON.stringify(normalizeValue(b ?? null))
66
67
  }
67
68
 
69
+ function hasEncryptionEnabled(definition: CustomFieldDef | null): boolean {
70
+ const config = definition?.configJson
71
+ if (!config || typeof config !== 'object') return false
72
+ return (config as Record<string, unknown>).encrypted === true
73
+ }
74
+
68
75
  export async function ensureCustomFieldDefinitions(
69
76
  em: EntityManager,
70
77
  sets: FieldSetInput[],
@@ -103,6 +110,14 @@ export async function ensureCustomFieldDefinitions(
103
110
  if (value !== undefined) configJson[key] = value as unknown
104
111
  }
105
112
 
113
+ // configJson is rebuilt from the declaration, so a field encrypted through the
114
+ // definitions API would lose the flag on the next install while its stored
115
+ // values stay ciphertext the read path no longer decrypts. Keep an enabled flag
116
+ // unless the declaration turns it off with an explicit `encrypted: false`.
117
+ if (configJson.encrypted === undefined && hasEncryptionEnabled(existing)) {
118
+ configJson.encrypted = true
119
+ }
120
+
106
121
  if (!existing) {
107
122
  if (!scope.dryRun) {
108
123
  const createdDef = em.create(CustomFieldDef, {
@@ -49,6 +49,7 @@ const FIELD_DETAIL_KEYS: Array<keyof CustomFieldDefinition> = [
49
49
  'formEditable',
50
50
  'listVisible',
51
51
  'indexed',
52
+ 'encrypted',
52
53
  'priority',
53
54
  'editor',
54
55
  'input',
@@ -744,5 +744,8 @@
744
744
  "eudr.supplierPanel.viewSubmissions": "Einreichungen anzeigen",
745
745
  "eudr.supplierPanel.warnings": "Mit Warnungen",
746
746
  "eudr.warnings.harvestBeforeCutoff": "Ernte vor dem EUDR-Stichtag",
747
- "eudr.warnings.speciesMissing": "Bei einer verknüpften Holz-Zuordnung fehlt der wissenschaftliche oder gebräuchliche Artname"
747
+ "eudr.warnings.speciesMissing": "Bei einer verknüpften Holz-Zuordnung fehlt der wissenschaftliche oder gebräuchliche Artname",
748
+ "search.entityType.eudr.eudr_due_diligence_statement": "DDS-Erklärung",
749
+ "search.entityType.eudr.eudr_evidence_submission": "Nachweiseinreichung",
750
+ "search.entityType.eudr.eudr_plot": "Parzelle"
748
751
  }
@@ -744,5 +744,8 @@
744
744
  "eudr.supplierPanel.viewSubmissions": "View submissions",
745
745
  "eudr.supplierPanel.warnings": "With warnings",
746
746
  "eudr.warnings.harvestBeforeCutoff": "Harvest before EUDR cutoff",
747
- "eudr.warnings.speciesMissing": "A linked wood mapping is missing a scientific or common species name"
747
+ "eudr.warnings.speciesMissing": "A linked wood mapping is missing a scientific or common species name",
748
+ "search.entityType.eudr.eudr_due_diligence_statement": "DDS statement",
749
+ "search.entityType.eudr.eudr_evidence_submission": "Evidence submission",
750
+ "search.entityType.eudr.eudr_plot": "Plot"
748
751
  }
@@ -744,5 +744,8 @@
744
744
  "eudr.supplierPanel.viewSubmissions": "Ver presentaciones",
745
745
  "eudr.supplierPanel.warnings": "Con advertencias",
746
746
  "eudr.warnings.harvestBeforeCutoff": "Cosecha anterior a la fecha de corte EUDR",
747
- "eudr.warnings.speciesMissing": "A una asignación de madera vinculada le falta el nombre científico o común de la especie"
747
+ "eudr.warnings.speciesMissing": "A una asignación de madera vinculada le falta el nombre científico o común de la especie",
748
+ "search.entityType.eudr.eudr_due_diligence_statement": "Declaración DDS",
749
+ "search.entityType.eudr.eudr_evidence_submission": "Envío de evidencia",
750
+ "search.entityType.eudr.eudr_plot": "Parcela"
748
751
  }
@@ -744,5 +744,8 @@
744
744
  "eudr.supplierPanel.viewSubmissions": "제출물 보기",
745
745
  "eudr.supplierPanel.warnings": "경고 있음",
746
746
  "eudr.warnings.harvestBeforeCutoff": "EUDR 기준일 이전 수확",
747
- "eudr.warnings.speciesMissing": "연결된 목재 매핑에 학명 또는 일반명이 누락되었습니다"
747
+ "eudr.warnings.speciesMissing": "연결된 목재 매핑에 학명 또는 일반명이 누락되었습니다",
748
+ "search.entityType.eudr.eudr_due_diligence_statement": "DDS 진술서",
749
+ "search.entityType.eudr.eudr_evidence_submission": "증거 제출물",
750
+ "search.entityType.eudr.eudr_plot": "구획"
748
751
  }
@@ -744,5 +744,8 @@
744
744
  "eudr.supplierPanel.viewSubmissions": "Zobacz zgłoszenia",
745
745
  "eudr.supplierPanel.warnings": "Z ostrzeżeniami",
746
746
  "eudr.warnings.harvestBeforeCutoff": "Zbiory przed datą graniczną EUDR",
747
- "eudr.warnings.speciesMissing": "W powiązanym mapowaniu drewna brakuje naukowej lub zwyczajowej nazwy gatunku"
747
+ "eudr.warnings.speciesMissing": "W powiązanym mapowaniu drewna brakuje naukowej lub zwyczajowej nazwy gatunku",
748
+ "search.entityType.eudr.eudr_due_diligence_statement": "Oświadczenie DDS",
749
+ "search.entityType.eudr.eudr_evidence_submission": "Zgłoszenie dowodów",
750
+ "search.entityType.eudr.eudr_plot": "Działka"
748
751
  }
@@ -95,23 +95,21 @@ function resolveSupplierName(record: Record<string, unknown>): string | null {
95
95
  }
96
96
 
97
97
  function buildStatementPresenter(translate: TranslateFn, record: Record<string, unknown>): SearchResultPresenter {
98
- const label = translate('eudr.search.badge.statement', 'DDS statement')
99
98
  const title = readRecordText(record, 'title') ?? translate('eudr.common.recordUnavailable')
100
99
  const subtitle = formatSubtitle(
101
100
  readRecordText(record, 'reference_number', 'referenceNumber'),
102
101
  translateToken(translate, 'eudr.commodity', readRecordText(record, 'commodity')),
103
102
  )
104
- return { title, subtitle, icon: 'file-check', badge: label }
103
+ return { title, subtitle, icon: 'file-check' }
105
104
  }
106
105
 
107
106
  function buildPlotPresenter(translate: TranslateFn, record: Record<string, unknown>): SearchResultPresenter {
108
- const label = translate('eudr.search.badge.plot', 'Plot')
109
107
  const title = readRecordText(record, 'name') ?? translate('eudr.common.recordUnavailable')
110
108
  const subtitle = formatSubtitle(
111
109
  readRecordText(record, 'origin_country', 'originCountry'),
112
110
  translateToken(translate, 'eudr.plotType', readRecordText(record, 'plot_type', 'plotType')),
113
111
  )
114
- return { title, subtitle, icon: 'map-pin', badge: label }
112
+ return { title, subtitle, icon: 'map-pin' }
115
113
  }
116
114
 
117
115
  function buildSubmissionPresenter(translate: TranslateFn, record: Record<string, unknown>): SearchResultPresenter {
@@ -125,7 +123,7 @@ function buildSubmissionPresenter(translate: TranslateFn, record: Record<string,
125
123
  supplierName,
126
124
  translateToken(translate, 'eudr.submissionStatus', readRecordText(record, 'status')),
127
125
  )
128
- return { title, subtitle, icon: 'package', badge: label }
126
+ return { title, subtitle, icon: 'package' }
129
127
  }
130
128
 
131
129
  export const searchConfig: SearchModuleConfig = {
@@ -11,9 +11,28 @@ function toNumeric(value: unknown): number {
11
11
  return 0
12
12
  }
13
13
 
14
- function mapPersistedLine(line: SalesOrderLine | SalesQuoteLine): SalesLineSnapshot {
14
+ /**
15
+ * A snapshot rebuilt from a persisted row, plus the columns the calculation
16
+ * engine never reads but the write paths must carry back to the row.
17
+ *
18
+ * The line upsert, line delete and adjustment write paths all rebuild *every*
19
+ * line of the document from these snapshots and then `Object.assign` the result
20
+ * onto the existing entities. Anything the mapper drops is therefore not merely
21
+ * absent from the calculation — it is written back as `null` over the stored
22
+ * value of lines the caller never touched (#5911).
23
+ */
24
+ export type SalesPersistedLineSnapshot = SalesLineSnapshot & {
25
+ statusEntryId: string | null
26
+ catalogSnapshot: Record<string, unknown> | null
27
+ promotionSnapshot: Record<string, unknown> | null
28
+ }
29
+
30
+ function mapPersistedLine(line: SalesOrderLine | SalesQuoteLine): SalesPersistedLineSnapshot {
15
31
  return {
16
32
  id: line.id,
33
+ statusEntryId: line.statusEntryId ?? null,
34
+ catalogSnapshot: line.catalogSnapshot ? cloneJson(line.catalogSnapshot) : null,
35
+ promotionSnapshot: line.promotionSnapshot ? cloneJson(line.promotionSnapshot) : null,
17
36
  lineNumber: line.lineNumber,
18
37
  kind: line.kind,
19
38
  productId: line.productId ?? null,
@@ -60,11 +79,11 @@ function mapPersistedLine(line: SalesOrderLine | SalesQuoteLine): SalesLineSnaps
60
79
  * two files used to carry byte-identical copies, and that duplication is why
61
80
  * the return flows kept the discount defect after the order flows were fixed.
62
81
  */
63
- export function mapOrderLineEntityToSnapshot(line: SalesOrderLine): SalesLineSnapshot {
82
+ export function mapOrderLineEntityToSnapshot(line: SalesOrderLine): SalesPersistedLineSnapshot {
64
83
  return mapPersistedLine(line)
65
84
  }
66
85
 
67
- export function mapQuoteLineEntityToSnapshot(line: SalesQuoteLine): SalesLineSnapshot {
86
+ export function mapQuoteLineEntityToSnapshot(line: SalesQuoteLine): SalesPersistedLineSnapshot {
68
87
  return mapPersistedLine(line)
69
88
  }
70
89
 
@@ -1,4 +1,8 @@
1
1
  {
2
+ "search.entityType.wms.inventory_lot": "Lagerbestand",
3
+ "search.entityType.wms.product_inventory_profile": "Bestandsprofil",
4
+ "search.entityType.wms.warehouse": "Lager",
5
+ "search.entityType.wms.warehouse_location": "Lagerort",
2
6
  "wms.audit.inventory.receive": "Wareneingang buchen",
3
7
  "wms.audit.salesOrder.assignWarehouse": "Lager dem Auftrag zuweisen",
4
8
  "wms.audit.salesOrder.reRunReservation": "Reservierung für Auftrag erneut ausführen",
@@ -1,4 +1,8 @@
1
1
  {
2
+ "search.entityType.wms.inventory_lot": "Inventory lot",
3
+ "search.entityType.wms.product_inventory_profile": "Inventory profile",
4
+ "search.entityType.wms.warehouse": "Warehouse",
5
+ "search.entityType.wms.warehouse_location": "Location",
2
6
  "wms.audit.inventory.receive": "Receive inventory",
3
7
  "wms.audit.salesOrder.assignWarehouse": "Assign warehouse to order",
4
8
  "wms.audit.salesOrder.reRunReservation": "Re-run reservation for order",
@@ -1,4 +1,8 @@
1
1
  {
2
+ "search.entityType.wms.inventory_lot": "Lote de inventario",
3
+ "search.entityType.wms.product_inventory_profile": "Perfil de inventario",
4
+ "search.entityType.wms.warehouse": "Almacén",
5
+ "search.entityType.wms.warehouse_location": "Ubicación",
2
6
  "wms.audit.inventory.receive": "Recibir inventario",
3
7
  "wms.audit.salesOrder.assignWarehouse": "Asignar almacén al pedido",
4
8
  "wms.audit.salesOrder.reRunReservation": "Volver a ejecutar la reserva del pedido",
@@ -1,4 +1,8 @@
1
1
  {
2
+ "search.entityType.wms.inventory_lot": "재고 로트",
3
+ "search.entityType.wms.product_inventory_profile": "재고 프로필",
4
+ "search.entityType.wms.warehouse": "창고",
5
+ "search.entityType.wms.warehouse_location": "위치",
2
6
  "wms.audit.inventory.receive": "재고 수령",
3
7
  "wms.audit.salesOrder.assignWarehouse": "주문할 창고 지정",
4
8
  "wms.audit.salesOrder.reRunReservation": "주문 예약 재실행",
@@ -1,4 +1,8 @@
1
1
  {
2
+ "search.entityType.wms.inventory_lot": "Partia zapasu",
3
+ "search.entityType.wms.product_inventory_profile": "Profil zapasu",
4
+ "search.entityType.wms.warehouse": "Magazyn",
5
+ "search.entityType.wms.warehouse_location": "Lokalizacja",
2
6
  "wms.audit.inventory.receive": "Przyjmij zapas",
3
7
  "wms.audit.salesOrder.assignWarehouse": "Przypisz magazyn do zamówienia",
4
8
  "wms.audit.salesOrder.reRunReservation": "Ponów rezerwację dla zamówienia",
@@ -63,7 +63,7 @@ function buildWarehousePresenter(
63
63
  const label = t('wms.search.badge.warehouse', 'Warehouse')
64
64
  const title = pickString(record.name, record.code, record.id) ?? label
65
65
  const subtitle = formatSubtitle(record.code, record.city, record.country)
66
- return { title, subtitle, icon: 'warehouse', badge: label }
66
+ return { title, subtitle, icon: 'warehouse' }
67
67
  }
68
68
 
69
69
  function buildLocationPresenter(
@@ -73,7 +73,7 @@ function buildLocationPresenter(
73
73
  const label = t('wms.search.badge.location', 'Location')
74
74
  const title = pickString(record.code, record.id) ?? label
75
75
  const subtitle = formatSubtitle(record.type, record.warehouse_id ?? record.warehouseId)
76
- return { title, subtitle, icon: 'map-pinned', badge: label }
76
+ return { title, subtitle, icon: 'map-pinned' }
77
77
  }
78
78
 
79
79
  function buildInventoryProfilePresenter(
@@ -89,7 +89,7 @@ function buildInventoryProfilePresenter(
89
89
  record.default_uom ?? record.defaultUom,
90
90
  variantId ? t('wms.search.profile.variantScoped', 'Variant-scoped') : t('wms.search.profile.productScoped', 'Product-scoped'),
91
91
  )
92
- return { title, subtitle, icon: 'boxes', badge: label }
92
+ return { title, subtitle, icon: 'boxes' }
93
93
  }
94
94
 
95
95
  function buildLotPresenter(
@@ -99,7 +99,7 @@ function buildLotPresenter(
99
99
  const label = t('wms.search.badge.lot', 'Inventory lot')
100
100
  const title = pickString(record.lot_number, record.lotNumber, record.batch_number, record.batchNumber, record.id) ?? label
101
101
  const subtitle = formatSubtitle(record.catalog_variant_id ?? record.catalogVariantId, record.status, record.expires_at ?? record.expiresAt)
102
- return { title, subtitle, icon: 'package-search', badge: label }
102
+ return { title, subtitle, icon: 'package-search' }
103
103
  }
104
104
 
105
105
  export const searchConfig: SearchModuleConfig = {