@open-mercato/core 0.10.1-develop.7974.1.c98f9304d9 → 0.10.1-develop.7976.1.c0ee1c7c28

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.
@@ -13,6 +13,16 @@
13
13
  "auth.acl.deps.orphaned.restore": "Restaurar \"{dependency}\"",
14
14
  "auth.acl.deps.orphaned.title": "Eliminando un permiso que otros permisos otorgados necesitan:",
15
15
  "auth.acl.deps.unknown.title": "Algunas dependencias declaradas no coinciden con ningún permiso conocido:",
16
+ "auth.acl.errors.aclGrantTenantRequired": "Se requiere un contexto de tenant para conceder permisos ACL.",
17
+ "auth.acl.errors.actorRequired": "No tienes autorización para conceder privilegios ACL.",
18
+ "auth.acl.errors.featureGrantDenied": "No se puede conceder el permiso {feature}.",
19
+ "auth.acl.errors.featureWildcardGrantDenied": "No se puede conceder el permiso comodín {feature}.",
20
+ "auth.acl.errors.globalWildcardGrantDenied": "Solo los superadministradores pueden conceder acceso comodín global.",
21
+ "auth.acl.errors.organizationOutsideScope": "No se puede conceder acceso a organizaciones fuera de su ámbito de acceso.",
22
+ "auth.acl.errors.roleGrantTenantRequired": "Se requiere un contexto de tenant para conceder roles.",
23
+ "auth.acl.errors.roleOutsideTargetTenant": "No se puede conceder un rol fuera del tenant de destino.",
24
+ "auth.acl.errors.superAdminGrantDenied": "Solo los superadministradores pueden conceder acceso de superadministrador.",
25
+ "auth.acl.errors.unrestrictedOrganizationsGrantDenied": "No se puede conceder acceso ilimitado a organizaciones.",
16
26
  "auth.acl.features.agent_orchestrator.agents.manage": "Manage agent presentation settings",
17
27
  "auth.acl.features.agent_orchestrator.agents.run": "Run agents directly (Playground, evals, diagnostics)",
18
28
  "auth.acl.features.agent_orchestrator.agents.view": "View agents and runs",
@@ -615,6 +625,9 @@
615
625
  "auth.roles.admin": "Administrador",
616
626
  "auth.roles.employee": "Empleado",
617
627
  "auth.roles.errors.nameExists": "Ya existe un rol con este nombre",
628
+ "auth.roles.errors.notFound": "Rol no encontrado",
629
+ "auth.roles.errors.rolesNotFound": "Rol(es) no encontrado(s): {roles}",
630
+ "auth.roles.errors.superAdminTargetProtected": "Solo los superadministradores pueden modificar roles de superadministrador.",
618
631
  "auth.roles.flash.created": "Rol creado",
619
632
  "auth.roles.flash.deleted": "Rol eliminado",
620
633
  "auth.roles.flash.updated": "Rol guardado",
@@ -667,8 +680,11 @@
667
680
  "auth.users.errors.emailExists": "El correo ya está en uso",
668
681
  "auth.users.errors.invalidRoleAssignment": "El usuario tiene una asignación de rol no válida.",
669
682
  "auth.users.errors.lastHolderOfCriticalRole": "No se puede eliminar al último titular activo del rol \"{roleName}\"",
683
+ "auth.users.errors.notFound": "Usuario no encontrado",
670
684
  "auth.users.errors.organizationNotFound": "Organización no encontrada",
671
685
  "auth.users.errors.roleOutsideDestinationTenant": "No se puede conservar ni asignar un rol fuera del tenant de destino.",
686
+ "auth.users.errors.superAdminTargetProtected": "Solo los superadministradores pueden modificar cuentas de superadministrador.",
687
+ "auth.users.errors.targetAccessDenied": "No tienes autorización para acceder a este usuario.",
672
688
  "auth.users.flash.created": "Usuario creado",
673
689
  "auth.users.flash.createdEmailFailed": "Usuario creado pero no se pudo enviar el correo de invitación. Puede reenviarlo desde la página del usuario.",
674
690
  "auth.users.flash.createdWithInvite": "Usuario creado e invitación enviada",
@@ -13,6 +13,16 @@
13
13
  "auth.acl.deps.orphaned.restore": "\"{dependency}\" 복원",
14
14
  "auth.acl.deps.orphaned.title": "다른 부여된 권한에 필요한 권한을 제거하고 있습니다:",
15
15
  "auth.acl.deps.unknown.title": "일부 선언된 종속성이 알려진 권한과 일치하지 않습니다:",
16
+ "auth.acl.errors.aclGrantTenantRequired": "ACL 권한을 부여하려면 테넌트 컨텍스트가 필요합니다.",
17
+ "auth.acl.errors.actorRequired": "ACL 권한을 부여할 권한이 없습니다.",
18
+ "auth.acl.errors.featureGrantDenied": "{feature} 권한을 부여할 수 없습니다.",
19
+ "auth.acl.errors.featureWildcardGrantDenied": "와일드카드 권한 {feature}을(를) 부여할 수 없습니다.",
20
+ "auth.acl.errors.globalWildcardGrantDenied": "전역 와일드카드 접근 권한은 슈퍼 관리자만 부여할 수 있습니다.",
21
+ "auth.acl.errors.organizationOutsideScope": "접근 범위를 벗어난 조직에 대한 접근 권한을 부여할 수 없습니다.",
22
+ "auth.acl.errors.roleGrantTenantRequired": "역할을 부여하려면 테넌트 컨텍스트가 필요합니다.",
23
+ "auth.acl.errors.roleOutsideTargetTenant": "대상 테넌트 외부의 역할을 부여할 수 없습니다.",
24
+ "auth.acl.errors.superAdminGrantDenied": "슈퍼 관리자 접근 권한은 슈퍼 관리자만 부여할 수 있습니다.",
25
+ "auth.acl.errors.unrestrictedOrganizationsGrantDenied": "모든 조직에 대한 무제한 접근 권한을 부여할 수 없습니다.",
16
26
  "auth.acl.features.agent_orchestrator.agents.manage": "Manage agent presentation settings",
17
27
  "auth.acl.features.agent_orchestrator.agents.run": "Run agents directly (Playground, evals, diagnostics)",
18
28
  "auth.acl.features.agent_orchestrator.agents.view": "View agents and runs",
@@ -615,6 +625,9 @@
615
625
  "auth.roles.admin": "관리자",
616
626
  "auth.roles.employee": "직원",
617
627
  "auth.roles.errors.nameExists": "이 이름의 역할이 이미 존재합니다",
628
+ "auth.roles.errors.notFound": "역할을 찾을 수 없습니다",
629
+ "auth.roles.errors.rolesNotFound": "역할을 찾을 수 없습니다: {roles}",
630
+ "auth.roles.errors.superAdminTargetProtected": "슈퍼 관리자 역할은 슈퍼 관리자만 수정할 수 있습니다.",
618
631
  "auth.roles.flash.created": "역할이 생성되었습니다",
619
632
  "auth.roles.flash.deleted": "역할이 삭제되었습니다",
620
633
  "auth.roles.flash.updated": "역할이 저장되었습니다",
@@ -667,8 +680,11 @@
667
680
  "auth.users.errors.emailExists": "이미 사용 중인 이메일입니다",
668
681
  "auth.users.errors.invalidRoleAssignment": "사용자에게 잘못된 역할이 할당되어 있습니다.",
669
682
  "auth.users.errors.lastHolderOfCriticalRole": "\"{roleName}\" 역할의 마지막 활성 보유자는 제거할 수 없습니다",
683
+ "auth.users.errors.notFound": "사용자를 찾을 수 없습니다",
670
684
  "auth.users.errors.organizationNotFound": "조직을 찾을 수 없습니다",
671
685
  "auth.users.errors.roleOutsideDestinationTenant": "대상 테넌트 외부의 역할을 유지하거나 할당할 수 없습니다.",
686
+ "auth.users.errors.superAdminTargetProtected": "슈퍼 관리자 계정은 슈퍼 관리자만 수정할 수 있습니다.",
687
+ "auth.users.errors.targetAccessDenied": "이 사용자에 접근할 권한이 없습니다.",
672
688
  "auth.users.flash.created": "사용자가 생성되었습니다",
673
689
  "auth.users.flash.createdEmailFailed": "사용자가 생성되었지만 초대 이메일을 보낼 수 없었습니다. 사용자 페이지에서 다시 보낼 수 있습니다.",
674
690
  "auth.users.flash.createdWithInvite": "사용자가 생성되고 초대가 전송되었습니다",
@@ -13,6 +13,16 @@
13
13
  "auth.acl.deps.orphaned.restore": "Przywróć \"{dependency}\"",
14
14
  "auth.acl.deps.orphaned.title": "Usuwasz uprawnienie wymagane przez inne przyznane uprawnienia:",
15
15
  "auth.acl.deps.unknown.title": "Niektóre zadeklarowane zależności nie pasują do żadnego znanego uprawnienia:",
16
+ "auth.acl.errors.aclGrantTenantRequired": "Do nadania uprawnień ACL wymagany jest kontekst najemcy.",
17
+ "auth.acl.errors.actorRequired": "Brak uprawnień do nadawania uprawnień ACL.",
18
+ "auth.acl.errors.featureGrantDenied": "Nie można nadać uprawnienia {feature}.",
19
+ "auth.acl.errors.featureWildcardGrantDenied": "Nie można nadać uprawnień z symbolem wieloznacznym {feature}.",
20
+ "auth.acl.errors.globalWildcardGrantDenied": "Tylko superadministratorzy mogą nadać pełny dostęp do wszystkich uprawnień.",
21
+ "auth.acl.errors.organizationOutsideScope": "Nie można nadać dostępu do organizacji spoza Twojego zakresu dostępu.",
22
+ "auth.acl.errors.roleGrantTenantRequired": "Do nadania ról wymagany jest kontekst najemcy.",
23
+ "auth.acl.errors.roleOutsideTargetTenant": "Nie można nadać roli spoza docelowego najemcy.",
24
+ "auth.acl.errors.superAdminGrantDenied": "Tylko superadministratorzy mogą nadać uprawnienia superadministratora.",
25
+ "auth.acl.errors.unrestrictedOrganizationsGrantDenied": "Nie można nadać nieograniczonego dostępu do organizacji.",
16
26
  "auth.acl.features.agent_orchestrator.agents.manage": "Zarządzaj ustawieniami prezentacji agentów",
17
27
  "auth.acl.features.agent_orchestrator.agents.run": "Uruchamiaj agentów bezpośrednio (Playground, ewaluacje, diagnostyka)",
18
28
  "auth.acl.features.agent_orchestrator.agents.view": "Wyświetl agentów i uruchomienia",
@@ -615,6 +625,9 @@
615
625
  "auth.roles.admin": "Administrator",
616
626
  "auth.roles.employee": "Pracownik",
617
627
  "auth.roles.errors.nameExists": "Rola o tej nazwie już istnieje",
628
+ "auth.roles.errors.notFound": "Nie znaleziono roli",
629
+ "auth.roles.errors.rolesNotFound": "Nie znaleziono ról: {roles}",
630
+ "auth.roles.errors.superAdminTargetProtected": "Tylko superadministratorzy mogą modyfikować role superadministratora.",
618
631
  "auth.roles.flash.created": "Rola utworzona",
619
632
  "auth.roles.flash.deleted": "Rola usunięta",
620
633
  "auth.roles.flash.updated": "Rola zapisana",
@@ -667,8 +680,11 @@
667
680
  "auth.users.errors.emailExists": "Adres e-mail jest już używany",
668
681
  "auth.users.errors.invalidRoleAssignment": "Użytkownik ma nieprawidłowo przypisaną rolę.",
669
682
  "auth.users.errors.lastHolderOfCriticalRole": "Nie można usunąć ostatniego aktywnego posiadacza roli \"{roleName}\"",
683
+ "auth.users.errors.notFound": "Nie znaleziono użytkownika",
670
684
  "auth.users.errors.organizationNotFound": "Nie znaleziono organizacji",
671
685
  "auth.users.errors.roleOutsideDestinationTenant": "Nie można zachować ani przypisać roli spoza docelowego tenantu.",
686
+ "auth.users.errors.superAdminTargetProtected": "Tylko superadministratorzy mogą modyfikować konta superadministratorów.",
687
+ "auth.users.errors.targetAccessDenied": "Brak uprawnień do dostępu do tego użytkownika.",
672
688
  "auth.users.flash.created": "Użytkownik utworzony",
673
689
  "auth.users.flash.createdEmailFailed": "Użytkownik utworzony, ale nie udało się wysłać e-maila z zaproszeniem. Możesz wysłać go ponownie ze strony użytkownika.",
674
690
  "auth.users.flash.createdWithInvite": "Użytkownik utworzony i zaproszenie wysłane",
@@ -3,6 +3,7 @@ import { badRequest, CrudHttpError, forbidden } from '@open-mercato/shared/lib/c
3
3
  import { hasFeature } from '@open-mercato/shared/security/features'
4
4
  import { findOneWithDecryption, findWithDecryption } from '@open-mercato/shared/lib/encryption/find'
5
5
  import { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'
6
+ import type { TranslateParams } from '@open-mercato/shared/lib/i18n/context'
6
7
  import { Role, RoleAcl, User, UserAcl, UserRole } from '@open-mercato/core/modules/auth/data/entities'
7
8
  import type { RbacService } from '@open-mercato/core/modules/auth/services/rbacService'
8
9
  import type { OrganizationScope } from '@open-mercato/core/modules/directory/utils/organizationScope'
@@ -177,13 +178,19 @@ export async function assertActorCanGrantRoles(input: RoleGrantCheckInput): Prom
177
178
  if (actorAcl.isSuperAdmin) return
178
179
 
179
180
  if (!tenantId) {
180
- throw forbidden('Tenant context is required to grant roles.')
181
+ throw forbidden(await translateAuthError(
182
+ 'auth.acl.errors.roleGrantTenantRequired',
183
+ 'Tenant context is required to grant roles.',
184
+ ))
181
185
  }
182
186
 
183
187
  for (const role of input.roles) {
184
188
  const roleTenantId = normalizeNullableString(role.tenantId)
185
189
  if (roleTenantId !== tenantId) {
186
- throw forbidden('Cannot grant a role outside the target tenant.')
190
+ throw forbidden(await translateAuthError(
191
+ 'auth.acl.errors.roleOutsideTargetTenant',
192
+ 'Cannot grant a role outside the target tenant.',
193
+ ))
187
194
  }
188
195
 
189
196
  const acl = await findOneWithDecryption(
@@ -195,7 +202,7 @@ export async function assertActorCanGrantRoles(input: RoleGrantCheckInput): Prom
195
202
  )
196
203
  if (!acl) continue
197
204
 
198
- assertActorCanGrantAclSnapshot(actorAcl, {
205
+ await assertActorCanGrantAclSnapshot(actorAcl, {
199
206
  isSuperAdmin: !!acl.isSuperAdmin,
200
207
  features: normalizeStringList(acl.featuresJson),
201
208
  organizations: normalizeOrganizationList(acl.organizationsJson),
@@ -209,10 +216,13 @@ export async function assertActorCanGrantAcl(input: FeatureGrantCheckInput): Pro
209
216
 
210
217
  const tenantId = normalizeNullableString(input.tenantId)
211
218
  if (!tenantId) {
212
- throw forbidden('Tenant context is required to grant ACL features.')
219
+ throw forbidden(await translateAuthError(
220
+ 'auth.acl.errors.aclGrantTenantRequired',
221
+ 'Tenant context is required to grant ACL features.',
222
+ ))
213
223
  }
214
224
 
215
- assertActorCanGrantAclSnapshot(actorAcl, {
225
+ await assertActorCanGrantAclSnapshot(actorAcl, {
216
226
  isSuperAdmin: !!input.isSuperAdmin,
217
227
  features: normalizeStringList(input.features),
218
228
  organizations: input.organizations === undefined ? undefined : normalizeOrganizationList(input.organizations),
@@ -228,7 +238,10 @@ export async function assertActorCanModifySuperAdminUserTarget(input: SuperAdmin
228
238
  if (actorIsSuperAdmin) return
229
239
  const targetIsSuperAdmin = await isUserEffectivelySuperAdmin(input.em, input.targetUserId)
230
240
  if (targetIsSuperAdmin) {
231
- throw forbidden('Only super administrators can modify super administrator accounts.')
241
+ throw forbidden(await translateAuthError(
242
+ 'auth.users.errors.superAdminTargetProtected',
243
+ 'Only super administrators can modify super administrator accounts.',
244
+ ))
232
245
  }
233
246
  }
234
247
 
@@ -237,7 +250,10 @@ export async function assertActorCanModifySuperAdminRoleTarget(input: SuperAdmin
237
250
  if (actorIsSuperAdmin) return
238
251
  const targetIsSuperAdmin = await isRoleEffectivelySuperAdmin(input.em, input.targetRoleId)
239
252
  if (targetIsSuperAdmin) {
240
- throw forbidden('Only super administrators can modify super administrator roles.')
253
+ throw forbidden(await translateAuthError(
254
+ 'auth.roles.errors.superAdminTargetProtected',
255
+ 'Only super administrators can modify super administrator roles.',
256
+ ))
241
257
  }
242
258
  }
243
259
 
@@ -268,13 +284,16 @@ export async function assertActorCanAccessUserTarget(input: UserTargetAccessInpu
268
284
  const actorTenantId = normalizeNullableString(input.tenantId)
269
285
  const targetTenantId = normalizeNullableString((target as { tenantId?: string | null }).tenantId)
270
286
  if (!targetTenantId || targetTenantId !== actorTenantId) {
271
- throw new CrudHttpError(404, { error: 'User not found' })
287
+ throw new CrudHttpError(404, { error: await translateAuthError('auth.users.errors.notFound', 'User not found') })
272
288
  }
273
289
 
274
290
  if (input.organizationScope.allowedIds !== null) {
275
291
  const targetOrganizationId = normalizeNullableString((target as { organizationId?: string | null }).organizationId)
276
292
  if (!targetOrganizationId || !input.organizationScope.allowedIds.includes(targetOrganizationId)) {
277
- throw forbidden('Not authorized to access this user.')
293
+ throw forbidden(await translateAuthError(
294
+ 'auth.users.errors.targetAccessDenied',
295
+ 'Not authorized to access this user.',
296
+ ))
278
297
  }
279
298
  }
280
299
  }
@@ -296,7 +315,7 @@ export async function assertActorCanAccessRoleTarget(input: SuperAdminRoleTarget
296
315
  const actorTenantId = normalizeNullableString(input.tenantId)
297
316
  const targetTenantId = normalizeNullableString((target as { tenantId?: string | null }).tenantId)
298
317
  if (!targetTenantId || targetTenantId !== actorTenantId) {
299
- throw new CrudHttpError(404, { error: 'Role not found' })
318
+ throw new CrudHttpError(404, { error: await translateAuthError('auth.roles.errors.notFound', 'Role not found') })
300
319
  }
301
320
  }
302
321
 
@@ -492,7 +511,12 @@ export async function listSuperAdminUserIds(em: EntityManager, tenantId: string
492
511
 
493
512
  async function loadActorAcl(input: GrantCheckContext): Promise<ActorAcl> {
494
513
  const actorUserId = normalizeNullableString(input.actorUserId)
495
- if (!actorUserId) throw forbidden('Not authorized to grant ACL privileges.')
514
+ if (!actorUserId) {
515
+ throw forbidden(await translateAuthError(
516
+ 'auth.acl.errors.actorRequired',
517
+ 'Not authorized to grant ACL privileges.',
518
+ ))
519
+ }
496
520
 
497
521
  const scope = {
498
522
  tenantId: normalizeNullableString(input.tenantId),
@@ -532,7 +556,9 @@ async function resolveRolesForGrant(
532
556
 
533
557
  if (missingRoles.length) {
534
558
  const labels = missingRoles.map((role) => `"${role}"`).join(', ')
535
- throw new CrudHttpError(400, { error: `Role(s) not found: ${labels}` })
559
+ throw new CrudHttpError(400, {
560
+ error: await translateAuthError('auth.roles.errors.rolesNotFound', 'Role(s) not found: {roles}', { roles: labels }),
561
+ })
536
562
  }
537
563
 
538
564
  return roles
@@ -556,52 +582,72 @@ async function resolveRoleForGrant(
556
582
  )
557
583
  }
558
584
 
559
- function assertActorCanGrantAclSnapshot(
585
+ async function assertActorCanGrantAclSnapshot(
560
586
  actorAcl: ActorAcl,
561
587
  requested: {
562
588
  isSuperAdmin: boolean
563
589
  features: string[]
564
590
  organizations?: string[] | null
565
591
  },
566
- ): void {
592
+ ): Promise<void> {
567
593
  if (requested.isSuperAdmin) {
568
- throw forbidden('Only super administrators can grant super admin access.')
594
+ throw forbidden(await translateAuthError(
595
+ 'auth.acl.errors.superAdminGrantDenied',
596
+ 'Only super administrators can grant super admin access.',
597
+ ))
569
598
  }
570
599
 
571
600
  const actorGrantableFeatures = actorAcl.features.filter((grant) => grant !== '*')
572
601
  for (const feature of requested.features) {
573
602
  if (feature === '*') {
574
- throw forbidden('Only super administrators can grant global wildcard access.')
603
+ throw forbidden(await translateAuthError(
604
+ 'auth.acl.errors.globalWildcardGrantDenied',
605
+ 'Only super administrators can grant global wildcard access.',
606
+ ))
575
607
  }
576
608
  if (isWildcardFeature(feature)) {
577
609
  if (!hasFeature(actorGrantableFeatures, feature)) {
578
- throw forbidden(`Cannot grant feature wildcard ${feature}.`)
610
+ throw forbidden(await translateAuthError(
611
+ 'auth.acl.errors.featureWildcardGrantDenied',
612
+ 'Cannot grant feature wildcard {feature}.',
613
+ { feature },
614
+ ))
579
615
  }
580
616
  continue
581
617
  }
582
618
  if (!hasFeature(actorGrantableFeatures, feature)) {
583
- throw forbidden(`Cannot grant feature ${feature}.`)
619
+ throw forbidden(await translateAuthError(
620
+ 'auth.acl.errors.featureGrantDenied',
621
+ 'Cannot grant feature {feature}.',
622
+ { feature },
623
+ ))
584
624
  }
585
625
  }
586
626
 
587
627
  if (requested.organizations !== undefined) {
588
- assertActorCanGrantOrganizations(actorAcl.organizations, requested.organizations)
628
+ await assertActorCanGrantOrganizations(actorAcl.organizations, requested.organizations)
589
629
  }
590
630
  }
591
631
 
592
- function assertActorCanGrantOrganizations(
632
+ async function assertActorCanGrantOrganizations(
593
633
  actorOrganizations: string[] | null,
594
634
  requestedOrganizations: string[] | null,
595
- ): void {
635
+ ): Promise<void> {
596
636
  if (actorOrganizations === null || actorOrganizations.includes('__all__')) return
597
637
 
598
638
  if (requestedOrganizations === null || requestedOrganizations.includes('__all__')) {
599
- throw forbidden('Cannot grant unrestricted organization access.')
639
+ throw forbidden(await translateAuthError(
640
+ 'auth.acl.errors.unrestrictedOrganizationsGrantDenied',
641
+ 'Cannot grant unrestricted organization access.',
642
+ ))
600
643
  }
601
644
 
602
645
  for (const organizationId of requestedOrganizations) {
603
646
  if (!actorOrganizations.includes(organizationId)) {
604
- throw forbidden('Cannot grant organization access outside actor scope.')
647
+ throw forbidden(await translateAuthError(
648
+ 'auth.acl.errors.organizationOutsideScope',
649
+ 'Cannot grant organization access outside actor scope.',
650
+ ))
605
651
  }
606
652
  }
607
653
  }
@@ -631,7 +677,7 @@ function isWildcardFeature(feature: string): boolean {
631
677
  return feature.endsWith('.*')
632
678
  }
633
679
 
634
- async function translateAuthError(key: string, fallback: string): Promise<string> {
680
+ async function translateAuthError(key: string, fallback: string, params?: TranslateParams): Promise<string> {
635
681
  const { translate } = await resolveTranslations()
636
- return translate(key, fallback)
682
+ return translate(key, fallback, params)
637
683
  }
@@ -59,6 +59,21 @@ type PersonCompanyLinkSnapshot = {
59
59
  type PersonCompanyLinkUndoPayload = {
60
60
  before?: PersonCompanyLinkSnapshot | null
61
61
  after?: PersonCompanyLinkSnapshot | null
62
+ createBefore?: PersonCompanyLinkCreateBefore
63
+ }
64
+
65
+ type PersonCompanyLinkCreateBefore = {
66
+ link: PersonCompanyLinkSnapshot | null
67
+ primaryLinkIds: string[]
68
+ profileCompanyId: string | null
69
+ }
70
+
71
+ type PersonCompanyLinkCreateResult = {
72
+ linkId: string
73
+ created: boolean
74
+ undeleted: boolean
75
+ changed: boolean
76
+ createBefore: PersonCompanyLinkCreateBefore
62
77
  }
63
78
 
64
79
  /**
@@ -171,6 +186,10 @@ async function loadPersonCompanyLinkSnapshot(
171
186
  },
172
187
  )
173
188
  if (!link) return null
189
+ return snapshotPersonCompanyLink(link)
190
+ }
191
+
192
+ function snapshotPersonCompanyLink(link: CustomerPersonCompanyLink): PersonCompanyLinkSnapshot {
174
193
  const personId = typeof link.person === 'string' ? link.person : link.person.id
175
194
  const companyId = typeof link.company === 'string' ? link.company : link.company.id
176
195
  return {
@@ -247,8 +266,88 @@ async function clearPrimaryFlagsForPerson(em: EntityManager, person: CustomerEnt
247
266
  )
248
267
  }
249
268
 
250
- const createPersonCompanyLinkCommand: CommandHandler<PersonCompanyLinkCreateInput, { linkId: string; created: boolean; undeleted: boolean }> = {
269
+ async function restoreCreatePersonCompanyLink(
270
+ ctx: CommandRuntimeContext,
271
+ after: PersonCompanyLinkSnapshot,
272
+ before: PersonCompanyLinkCreateBefore,
273
+ ): Promise<void> {
274
+ const em = (ctx.container.resolve('em') as EntityManager).fork()
275
+ const scope = { tenantId: after.tenantId, organizationId: after.organizationId }
276
+ const link = await findOneWithDecryption(
277
+ em,
278
+ CustomerPersonCompanyLink,
279
+ { id: after.id, ...scope },
280
+ undefined,
281
+ scope,
282
+ )
283
+ if (!link) return
284
+ const person = await requirePersonEntity(em, after.personEntityId, after.tenantId, after.organizationId)
285
+ const profile = await requirePersonProfile(em, person)
286
+ const profileCompanyId = typeof profile.company === 'string' ? profile.company : profile.company?.id ?? null
287
+ const restorePrimaryAssignment = after.isPrimary && link.isPrimary && profileCompanyId === after.companyEntityId
288
+ const company = restorePrimaryAssignment && before.profileCompanyId
289
+ ? await requireCompanyEntity(em, before.profileCompanyId, after.tenantId, after.organizationId)
290
+ : null
291
+ const primaryLinkIds = before.primaryLinkIds.filter((id) => id !== link.id)
292
+
293
+ await withAtomicFlush(em, [
294
+ async () => {
295
+ if (restorePrimaryAssignment) {
296
+ await em.nativeUpdate(
297
+ CustomerPersonCompanyLink,
298
+ { person, ...scope, id: { $ne: link.id }, deletedAt: null, isPrimary: true },
299
+ { isPrimary: false },
300
+ )
301
+ if (primaryLinkIds.length) {
302
+ await em.nativeUpdate(
303
+ CustomerPersonCompanyLink,
304
+ { person, ...scope, id: { $in: primaryLinkIds }, deletedAt: null },
305
+ { isPrimary: true },
306
+ )
307
+ }
308
+ profile.company = company
309
+ }
310
+ link.isPrimary = before.link?.isPrimary ?? false
311
+ link.deletedAt = before.link
312
+ ? before.link.deletedAt ? new Date(before.link.deletedAt) : null
313
+ : new Date()
314
+ },
315
+ ], { transaction: true })
316
+
317
+ const dataEngine = ctx.container.resolve('dataEngine') as DataEngine
318
+ await emitCrudUndoSideEffects({
319
+ dataEngine,
320
+ action: link.deletedAt ? 'deleted' : 'updated',
321
+ entity: link,
322
+ identifiers: getLinkIdentifiers(link),
323
+ syncOrigin: ctx.syncOrigin,
324
+ events: personCompanyLinkCrudEvents,
325
+ indexer: { entityType: 'customers:customer_person_company_link' },
326
+ })
327
+ }
328
+
329
+ const createPersonCompanyLinkCommand: CommandHandler<PersonCompanyLinkCreateInput, PersonCompanyLinkCreateResult> = {
251
330
  id: 'customers.personCompanyLinks.create',
331
+ async prepare(rawInput, ctx) {
332
+ const parsed = personCompanyLinkCreateSchema.parse(rawInput)
333
+ ensureTenantScope(ctx, parsed.tenantId)
334
+ ensureOrganizationScope(ctx, parsed.organizationId)
335
+ const em = (ctx.container.resolve('em') as EntityManager).fork()
336
+ const person = await requirePersonEntity(em, parsed.personEntityId, parsed.tenantId, parsed.organizationId)
337
+ const company = await requireCompanyEntity(em, parsed.companyEntityId, parsed.tenantId, parsed.organizationId)
338
+ const profile = await requirePersonProfile(em, person)
339
+ const links = await loadPersonCompanyLinks(em, person)
340
+ const link = links.find((entry) =>
341
+ (typeof entry.company === 'string' ? entry.company : entry.company.id) === company.id,
342
+ ) ?? await findDeletedPersonCompanyLink(em, person, company)
343
+ return {
344
+ before: {
345
+ link: link ? await loadPersonCompanyLinkSnapshot(em, link.id, parsed) : null,
346
+ primaryLinkIds: links.filter((entry) => entry.isPrimary).map((entry) => entry.id),
347
+ profileCompanyId: typeof profile.company === 'string' ? profile.company : profile.company?.id ?? null,
348
+ } satisfies PersonCompanyLinkCreateBefore,
349
+ }
350
+ },
252
351
  async execute(rawInput, ctx) {
253
352
  const parsed = personCompanyLinkCreateSchema.parse(rawInput)
254
353
  ensureTenantScope(ctx, parsed.tenantId)
@@ -263,9 +362,17 @@ const createPersonCompanyLinkCommand: CommandHandler<PersonCompanyLinkCreateInpu
263
362
  const makePrimary = Boolean(parsed.isPrimary) || existingLinks.length === 0
264
363
  const existingLive =
265
364
  existingLinks.find((link) => (typeof link.company === 'string' ? link.company : link.company.id) === company.id) ?? null
365
+ // This state must come from execute's decision, not prepare's earlier read: another
366
+ // request may have created the link between prepare and execute.
367
+ const createBefore: PersonCompanyLinkCreateBefore = {
368
+ link: existingLive ? snapshotPersonCompanyLink(existingLive) : null,
369
+ primaryLinkIds: existingLinks.filter((link) => link.isPrimary).map((link) => link.id),
370
+ profileCompanyId: typeof profile.company === 'string' ? profile.company : profile.company?.id ?? null,
371
+ }
266
372
 
267
373
  if (existingLive) {
268
- if (makePrimary && !existingLive.isPrimary) {
374
+ const changed = makePrimary && !existingLive.isPrimary
375
+ if (changed) {
269
376
  await withAtomicFlush(em, [
270
377
  () => clearPrimaryFlagsForPerson(em, person),
271
378
  () => {
@@ -274,7 +381,7 @@ const createPersonCompanyLinkCommand: CommandHandler<PersonCompanyLinkCreateInpu
274
381
  },
275
382
  ], { transaction: true })
276
383
  }
277
- return { linkId: existingLive.id, created: false, undeleted: false }
384
+ return { linkId: existingLive.id, created: false, undeleted: false, changed, createBefore }
278
385
  }
279
386
 
280
387
  let link!: CustomerPersonCompanyLink
@@ -282,6 +389,7 @@ const createPersonCompanyLinkCommand: CommandHandler<PersonCompanyLinkCreateInpu
282
389
  await withAtomicFlush(em, [
283
390
  async () => {
284
391
  const deletedLink = await findDeletedPersonCompanyLink(em, person, company)
392
+ if (deletedLink) createBefore.link = snapshotPersonCompanyLink(deletedLink)
285
393
  if (makePrimary) {
286
394
  await clearPrimaryFlagsForPerson(em, person)
287
395
  }
@@ -323,18 +431,22 @@ const createPersonCompanyLinkCommand: CommandHandler<PersonCompanyLinkCreateInpu
323
431
  indexer: { entityType: 'customers:customer_person_company_link' },
324
432
  })
325
433
 
326
- return { linkId: link.id, created: !undeleted, undeleted }
434
+ return { linkId: link.id, created: !undeleted, undeleted, changed: true, createBefore }
327
435
  },
328
436
  captureAfter: async (_input, result, ctx) => {
329
- const em = ctx.container.resolve('em') as EntityManager
437
+ const em = (ctx.container.resolve('em') as EntityManager).fork()
330
438
  return loadPersonCompanyLinkSnapshot(em, result.linkId, {
331
439
  tenantId: ctx.auth?.tenantId ?? null,
332
440
  organizationId: ctx.selectedOrganizationId ?? ctx.auth?.orgId ?? null,
333
441
  })
334
442
  },
335
443
  buildLog: async ({ result, snapshots }) => {
336
- const { translate } = await resolveTranslations()
444
+ const before = result.createBefore
337
445
  const after = snapshots.after as PersonCompanyLinkSnapshot | undefined
446
+ if (!result.changed) {
447
+ return { skipLog: true }
448
+ }
449
+ const { translate } = await resolveTranslations()
338
450
  return {
339
451
  actionLabel: translate('customers.audit.personCompanyLinks.create', 'Link company to person'),
340
452
  resourceKind: 'customers.personCompanyLink',
@@ -343,10 +455,12 @@ const createPersonCompanyLinkCommand: CommandHandler<PersonCompanyLinkCreateInpu
343
455
  parentResourceId: after?.personEntityId ?? null,
344
456
  tenantId: after?.tenantId ?? null,
345
457
  organizationId: after?.organizationId ?? null,
458
+ snapshotBefore: before?.link ?? null,
346
459
  snapshotAfter: after ?? null,
347
460
  payload: {
348
461
  undo: {
349
462
  after: after ?? null,
463
+ ...(before ? { createBefore: before } : {}),
350
464
  ...(result.undeleted ? { before: null } : {}),
351
465
  } satisfies PersonCompanyLinkUndoPayload,
352
466
  },
@@ -357,6 +471,11 @@ const createPersonCompanyLinkCommand: CommandHandler<PersonCompanyLinkCreateInpu
357
471
  const after = payload?.after
358
472
  if (!after) return
359
473
 
474
+ if (payload.createBefore) {
475
+ await restoreCreatePersonCompanyLink(ctx, after, payload.createBefore)
476
+ return
477
+ }
478
+
360
479
  const em = (ctx.container.resolve('em') as EntityManager).fork()
361
480
  const link = await findOneWithDecryption(
362
481
  em,
@@ -431,6 +550,12 @@ const createPersonCompanyLinkCommand: CommandHandler<PersonCompanyLinkCreateInpu
431
550
  undefined,
432
551
  { tenantId: after.tenantId, organizationId: after.organizationId },
433
552
  )
553
+ const existingLinks = await loadPersonCompanyLinks(em, person)
554
+ const createBefore: PersonCompanyLinkCreateBefore = {
555
+ link: link ? snapshotPersonCompanyLink(link) : null,
556
+ primaryLinkIds: existingLinks.filter((entry) => entry.isPrimary).map((entry) => entry.id),
557
+ profileCompanyId: typeof profile.company === 'string' ? profile.company : profile.company?.id ?? null,
558
+ }
434
559
 
435
560
  await withAtomicFlush(em, [
436
561
  async () => {
@@ -471,7 +596,7 @@ const createPersonCompanyLinkCommand: CommandHandler<PersonCompanyLinkCreateInpu
471
596
  indexer: { entityType: 'customers:customer_person_company_link' },
472
597
  })
473
598
 
474
- return { linkId: link!.id, created: true, undeleted: false }
599
+ return { linkId: link!.id, created: true, undeleted: false, changed: true, createBefore }
475
600
  },
476
601
  }
477
602