@open-mercato/core 0.11.1-develop.8545.1.dd603570fd → 0.11.1-develop.8556.1.d944a8493f
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.
- package/.turbo/turbo-build.log +1 -1
- package/dist/modules/customer_accounts/api/admin/users/[id]/verify-email.js +10 -30
- package/dist/modules/customer_accounts/api/admin/users/[id]/verify-email.js.map +2 -2
- package/dist/modules/customer_accounts/api/email/verify.js +11 -10
- package/dist/modules/customer_accounts/api/email/verify.js.map +2 -2
- package/dist/modules/customer_accounts/api/magic-link/verify.js +9 -8
- package/dist/modules/customer_accounts/api/magic-link/verify.js.map +2 -2
- package/dist/modules/customer_accounts/api/password/reset-confirm.js +13 -16
- package/dist/modules/customer_accounts/api/password/reset-confirm.js.map +2 -2
- package/dist/modules/customer_accounts/api/signup.js +33 -19
- package/dist/modules/customer_accounts/api/signup.js.map +3 -3
- package/dist/modules/customer_accounts/data/validators.js +3 -2
- package/dist/modules/customer_accounts/data/validators.js.map +2 -2
- package/dist/modules/customer_accounts/lib/customerAuth.js +11 -10
- package/dist/modules/customer_accounts/lib/customerAuth.js.map +2 -2
- package/dist/modules/customer_accounts/lib/customerAuthServer.js +7 -7
- package/dist/modules/customer_accounts/lib/customerAuthServer.js.map +2 -2
- package/dist/modules/customer_accounts/lib/pendingSignup.js +16 -0
- package/dist/modules/customer_accounts/lib/pendingSignup.js.map +7 -0
- package/dist/modules/customer_accounts/lib/verifyCustomerEmail.js +50 -0
- package/dist/modules/customer_accounts/lib/verifyCustomerEmail.js.map +7 -0
- package/dist/modules/customer_accounts/services/customerInvitationService.js +15 -1
- package/dist/modules/customer_accounts/services/customerInvitationService.js.map +2 -2
- package/dist/modules/customer_accounts/services/customerTokenService.js +13 -13
- package/dist/modules/customer_accounts/services/customerTokenService.js.map +2 -2
- package/dist/modules/customer_accounts/services/customerUserService.js +1 -1
- package/dist/modules/customer_accounts/services/customerUserService.js.map +2 -2
- package/dist/modules/customer_accounts/subscribers/autoLinkCrm.js +44 -51
- package/dist/modules/customer_accounts/subscribers/autoLinkCrm.js.map +2 -2
- package/dist/modules/customer_accounts/subscribers/autoLinkCrmOnVerification.js +12 -0
- package/dist/modules/customer_accounts/subscribers/autoLinkCrmOnVerification.js.map +7 -0
- package/dist/modules/customer_accounts/subscribers/autoLinkCrmReverse.js +3 -1
- package/dist/modules/customer_accounts/subscribers/autoLinkCrmReverse.js.map +2 -2
- package/dist/modules/customer_accounts/workers/cleanupExpiredTokens.js +6 -0
- package/dist/modules/customer_accounts/workers/cleanupExpiredTokens.js.map +2 -2
- package/dist/modules/customers/commands/companies.js +8 -6
- package/dist/modules/customers/commands/companies.js.map +2 -2
- package/dist/modules/customers/commands/deals.js +24 -13
- package/dist/modules/customers/commands/deals.js.map +2 -2
- package/dist/modules/customers/commands/people.js +8 -6
- package/dist/modules/customers/commands/people.js.map +2 -2
- package/dist/modules/entities/lib/helpers.js +6 -2
- package/dist/modules/entities/lib/helpers.js.map +2 -2
- package/dist/modules/portal/frontend/[orgSlug]/portal/PasswordForm.js +127 -0
- package/dist/modules/portal/frontend/[orgSlug]/portal/PasswordForm.js.map +7 -0
- package/dist/modules/portal/frontend/[orgSlug]/portal/reset-password/page.js +10 -122
- package/dist/modules/portal/frontend/[orgSlug]/portal/reset-password/page.js.map +2 -2
- package/dist/modules/portal/frontend/[orgSlug]/portal/signup/page.js +2 -11
- package/dist/modules/portal/frontend/[orgSlug]/portal/signup/page.js.map +2 -2
- package/dist/modules/portal/frontend/[orgSlug]/portal/verify/page.js +3 -61
- package/dist/modules/portal/frontend/[orgSlug]/portal/verify/page.js.map +2 -2
- package/package.json +8 -8
- package/src/modules/customer_accounts/api/admin/users/[id]/verify-email.ts +11 -33
- package/src/modules/customer_accounts/api/email/verify.ts +15 -11
- package/src/modules/customer_accounts/api/magic-link/verify.ts +9 -9
- package/src/modules/customer_accounts/api/password/reset-confirm.ts +13 -18
- package/src/modules/customer_accounts/api/signup.ts +36 -24
- package/src/modules/customer_accounts/data/validators.ts +2 -1
- package/src/modules/customer_accounts/lib/customerAuth.ts +12 -10
- package/src/modules/customer_accounts/lib/customerAuthServer.ts +7 -7
- package/src/modules/customer_accounts/lib/pendingSignup.ts +12 -0
- package/src/modules/customer_accounts/lib/verifyCustomerEmail.ts +57 -0
- package/src/modules/customer_accounts/services/customerInvitationService.ts +16 -1
- package/src/modules/customer_accounts/services/customerTokenService.ts +13 -13
- package/src/modules/customer_accounts/services/customerUserService.ts +2 -2
- package/src/modules/customer_accounts/subscribers/autoLinkCrm.ts +46 -78
- package/src/modules/customer_accounts/subscribers/autoLinkCrmOnVerification.ts +9 -0
- package/src/modules/customer_accounts/subscribers/autoLinkCrmReverse.ts +3 -1
- package/src/modules/customer_accounts/workers/cleanupExpiredTokens.ts +7 -0
- package/src/modules/customers/commands/companies.ts +7 -5
- package/src/modules/customers/commands/deals.ts +22 -12
- package/src/modules/customers/commands/people.ts +7 -4
- package/src/modules/entities/lib/helpers.ts +8 -2
- package/src/modules/portal/frontend/[orgSlug]/portal/PasswordForm.tsx +182 -0
- package/src/modules/portal/frontend/[orgSlug]/portal/reset-password/page.tsx +9 -165
- package/src/modules/portal/frontend/[orgSlug]/portal/signup/page.tsx +2 -12
- package/src/modules/portal/frontend/[orgSlug]/portal/verify/page.tsx +3 -89
- package/src/modules/portal/i18n/de.json +2 -1
- package/src/modules/portal/i18n/en.json +2 -1
- package/src/modules/portal/i18n/es.json +2 -1
- package/src/modules/portal/i18n/ko.json +2 -1
- package/src/modules/portal/i18n/pl.json +2 -1
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/modules/customer_accounts/services/customerTokenService.ts"],
|
|
4
|
-
"sourcesContent": ["import { EntityManager } from '@mikro-orm/postgresql'\nimport type { Kysely } from 'kysely'\nimport {\n CustomerUser,\n CustomerUserEmailVerification,\n CustomerUserPasswordReset,\n} from '@open-mercato/core/modules/customer_accounts/data/entities'\nimport { generateSecureToken, hashToken } from '@open-mercato/core/modules/customer_accounts/lib/tokenGenerator'\nimport { isCustomerTenantActive } from '@open-mercato/core/modules/customer_accounts/lib/tenantEligibility'\n\nfunction getKysely(em: EntityManager): Kysely<any> {\n return (em as unknown as { getKysely: () => Kysely<any> }).getKysely()\n}\n\nconst
|
|
5
|
-
"mappings": "AAEA;AAAA,EAEE;AAAA,EACA;AAAA,OACK;AACP,SAAS,qBAAqB,iBAAiB;AAC/C,SAAS,8BAA8B;
|
|
4
|
+
"sourcesContent": ["import { EntityManager } from '@mikro-orm/postgresql'\nimport type { Kysely } from 'kysely'\nimport {\n CustomerUser,\n CustomerUserEmailVerification,\n CustomerUserPasswordReset,\n} from '@open-mercato/core/modules/customer_accounts/data/entities'\nimport { generateSecureToken, hashToken } from '@open-mercato/core/modules/customer_accounts/lib/tokenGenerator'\nimport { isCustomerTenantActive } from '@open-mercato/core/modules/customer_accounts/lib/tenantEligibility'\nimport { EMAIL_VERIFICATION_TTL_MS } from '../lib/pendingSignup'\n\nfunction getKysely(em: EntityManager): Kysely<any> {\n return (em as unknown as { getKysely: () => Kysely<any> }).getKysely()\n}\n\nconst MAGIC_LINK_TTL_MS = 15 * 60 * 1000 // 15 minutes\nconst PASSWORD_RESET_TTL_MS = 60 * 60 * 1000 // 60 minutes\n\nexport class CustomerTokenService {\n constructor(private em: EntityManager) {}\n\n async createEmailVerification(userId: string, tenantId: string, createdAt = new Date(), em = this.em): Promise<string> {\n const rawToken = generateSecureToken()\n const tokenHashed = hashToken(rawToken)\n const expiresAt = new Date(createdAt.getTime() + EMAIL_VERIFICATION_TTL_MS)\n const record = em.create(CustomerUserEmailVerification, {\n user: userId as any,\n token: tokenHashed,\n purpose: 'email_verification',\n expiresAt,\n createdAt,\n } as any)\n await em.persist(record).flush()\n return rawToken\n }\n\n async createMagicLink(userId: string, tenantId: string): Promise<string> {\n const rawToken = generateSecureToken()\n const tokenHashed = hashToken(rawToken)\n const expiresAt = new Date(Date.now() + MAGIC_LINK_TTL_MS)\n const record = this.em.create(CustomerUserEmailVerification, {\n user: userId as any,\n token: tokenHashed,\n purpose: 'magic_link',\n expiresAt,\n createdAt: new Date(),\n } as any)\n await this.em.persist(record).flush()\n return rawToken\n }\n\n async createPasswordReset(userId: string, tenantId: string): Promise<string> {\n const rawToken = generateSecureToken()\n const tokenHashed = hashToken(rawToken)\n const expiresAt = new Date(Date.now() + PASSWORD_RESET_TTL_MS)\n const record = this.em.create(CustomerUserPasswordReset, {\n user: userId as any,\n token: tokenHashed,\n expiresAt,\n createdAt: new Date(),\n } as any)\n await this.em.persist(record).flush()\n return rawToken\n }\n\n async verifyEmailToken(token: string, purpose: string, tenantId?: string, em = this.em): Promise<{ userId: string; tenantId: string } | null> {\n const tokenHashed = hashToken(token)\n const record = await em.findOne(CustomerUserEmailVerification, {\n token: tokenHashed,\n purpose,\n }, { populate: ['user'] })\n if (!record) return null\n if (record.usedAt) return null\n if (record.expiresAt.getTime() < Date.now()) return null\n\n const user = record.user as CustomerUser\n if (tenantId && user?.tenantId !== tenantId) return null\n if (purpose === 'magic_link' && !(await isCustomerTenantActive(em, user?.tenantId))) return null\n\n const db = getKysely(em)\n const updateResult = await db\n .updateTable('customer_user_email_verifications' as any)\n .set({ used_at: new Date() } as any)\n .where('id' as any, '=', record.id)\n .where('used_at' as any, 'is', null)\n .where('expires_at' as any, '>', new Date())\n .executeTakeFirst()\n const consumed = Number(updateResult?.numUpdatedRows ?? 0)\n if (consumed === 0) return null\n\n const resolvedUserId = typeof user === 'string' ? user : user.id\n const resolvedTenantId = typeof user === 'string' ? '' : user.tenantId\n return { userId: resolvedUserId, tenantId: resolvedTenantId }\n }\n\n async verifyPasswordResetToken(token: string, tenantId?: string, em = this.em): Promise<{ userId: string; tenantId: string } | null> {\n const tokenHashed = hashToken(token)\n const record = await em.findOne(CustomerUserPasswordReset, {\n token: tokenHashed,\n }, { populate: ['user'] })\n if (!record) return null\n if (record.usedAt) return null\n if (record.expiresAt.getTime() < Date.now()) return null\n\n const user = record.user as CustomerUser\n if (tenantId && user?.tenantId !== tenantId) return null\n\n const db = getKysely(em)\n const updateResult = await db\n .updateTable('customer_user_password_resets' as any)\n .set({ used_at: new Date() } as any)\n .where('id' as any, '=', record.id)\n .where('used_at' as any, 'is', null)\n .where('expires_at' as any, '>', new Date())\n .executeTakeFirst()\n const consumed = Number(updateResult?.numUpdatedRows ?? 0)\n if (consumed === 0) return null\n\n const resolvedUserId = typeof user === 'string' ? user : user.id\n const resolvedTenantId = typeof user === 'string' ? '' : user.tenantId\n return { userId: resolvedUserId, tenantId: resolvedTenantId }\n }\n}\n"],
|
|
5
|
+
"mappings": "AAEA;AAAA,EAEE;AAAA,EACA;AAAA,OACK;AACP,SAAS,qBAAqB,iBAAiB;AAC/C,SAAS,8BAA8B;AACvC,SAAS,iCAAiC;AAE1C,SAAS,UAAU,IAAgC;AACjD,SAAQ,GAAmD,UAAU;AACvE;AAEA,MAAM,oBAAoB,KAAK,KAAK;AACpC,MAAM,wBAAwB,KAAK,KAAK;AAEjC,MAAM,qBAAqB;AAAA,EAChC,YAAoB,IAAmB;AAAnB;AAAA,EAAoB;AAAA,EAExC,MAAM,wBAAwB,QAAgB,UAAkB,YAAY,oBAAI,KAAK,GAAG,KAAK,KAAK,IAAqB;AACrH,UAAM,WAAW,oBAAoB;AACrC,UAAM,cAAc,UAAU,QAAQ;AACtC,UAAM,YAAY,IAAI,KAAK,UAAU,QAAQ,IAAI,yBAAyB;AAC1E,UAAM,SAAS,GAAG,OAAO,+BAA+B;AAAA,MACtD,MAAM;AAAA,MACN,OAAO;AAAA,MACP,SAAS;AAAA,MACT;AAAA,MACA;AAAA,IACF,CAAQ;AACR,UAAM,GAAG,QAAQ,MAAM,EAAE,MAAM;AAC/B,WAAO;AAAA,EACT;AAAA,EAEA,MAAM,gBAAgB,QAAgB,UAAmC;AACvE,UAAM,WAAW,oBAAoB;AACrC,UAAM,cAAc,UAAU,QAAQ;AACtC,UAAM,Y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C9D,WAAO,EAAE,QAAQ,gBAAgB,UAAU,iBAAiB;AAAA,EAC9D;AACF;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -10,7 +10,7 @@ class CustomerUserService {
|
|
|
10
10
|
this.em = em;
|
|
11
11
|
}
|
|
12
12
|
async createUser(email, password, displayName, scope) {
|
|
13
|
-
const passwordHash = await hash(password, BCRYPT_COST);
|
|
13
|
+
const passwordHash = password === null ? null : await hash(password, BCRYPT_COST);
|
|
14
14
|
const emailHash = hashForLookup(email);
|
|
15
15
|
const user = this.em.create(CustomerUser, {
|
|
16
16
|
email: email.toLowerCase().trim(),
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/modules/customer_accounts/services/customerUserService.ts"],
|
|
4
|
-
"sourcesContent": ["import { EntityManager } from '@mikro-orm/postgresql'\nimport { hash, compare } from 'bcryptjs'\nimport { CustomerUser } from '@open-mercato/core/modules/customer_accounts/data/entities'\nimport { hashForLookup, lookupHashCandidates } from '@open-mercato/shared/lib/encryption/aes'\nimport { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\n\nconst BCRYPT_COST = 10\nconst MAX_FAILED_ATTEMPTS = 5\nconst LOCKOUT_DURATION_MS = 15 * 60 * 1000 // 15 minutes\n\ntype CustomerUserLockoutDatabase = {\n customer_users: {\n id: string\n failed_login_attempts: number\n locked_until: Date | null\n }\n}\n\nexport class CustomerUserService {\n constructor(private em: EntityManager) {}\n\n async createUser(\n email: string,\n password: string,\n displayName: string,\n scope: { tenantId: string; organizationId: string },\n ): Promise<CustomerUser> {\n const passwordHash = await hash(password, BCRYPT_COST)\n const emailHash = hashForLookup(email)\n const user = this.em.create(CustomerUser, {\n email: email.toLowerCase().trim(),\n emailHash,\n passwordHash,\n displayName,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n isActive: true,\n failedLoginAttempts: 0,\n createdAt: new Date(),\n } as any)\n return user as CustomerUser\n }\n\n async findByEmail(email: string, tenantId: string): Promise<CustomerUser | null> {\n return findOneWithDecryption(\n this.em,\n CustomerUser,\n {\n emailHash: { $in: lookupHashCandidates(email) },\n tenantId,\n deletedAt: null,\n } as any,\n undefined,\n { tenantId },\n )\n }\n\n async findById(\n id: string,\n tenantId: string,\n organizationId?: string | null,\n ): Promise<CustomerUser | null> {\n const where: Record<string, unknown> = { id, tenantId, deletedAt: null }\n if (organizationId !== undefined) where.organizationId = organizationId\n return findOneWithDecryption(\n this.em,\n CustomerUser,\n where as any,\n undefined,\n { tenantId, organizationId },\n )\n }\n\n async verifyPassword(user: CustomerUser, password: string): Promise<boolean> {\n if (!user.passwordHash) return false\n return compare(password, user.passwordHash)\n }\n\n async updateLastLoginAt(user: CustomerUser): Promise<void> {\n const now = new Date()\n await this.em.nativeUpdate(CustomerUser, { id: user.id }, { lastLoginAt: now })\n user.lastLoginAt = now\n }\n\n checkLockout(user: CustomerUser): boolean {\n if (!user.lockedUntil) return false\n if (user.lockedUntil.getTime() > Date.now()) return true\n return false\n }\n\n async incrementFailedAttempts(user: CustomerUser): Promise<void> {\n const lockedUntil = new Date(Date.now() + LOCKOUT_DURATION_MS)\n await this.em.getKysely<CustomerUserLockoutDatabase>()\n .updateTable('customer_users')\n .set((eb) => ({\n failed_login_attempts: eb('failed_login_attempts', '+', 1),\n locked_until: eb\n .case()\n .when('failed_login_attempts', '>=', MAX_FAILED_ATTEMPTS - 1)\n .then(eb.fn<Date>('greatest', [eb.ref('locked_until'), eb.val(lockedUntil)]))\n .else(eb.ref('locked_until'))\n .end(),\n }))\n .where('id', '=', user.id)\n .execute()\n }\n\n async resetFailedAttemptsUnlessLocked(user: CustomerUser): Promise<boolean> {\n const now = new Date()\n const row = await this.em.getKysely<CustomerUserLockoutDatabase>()\n .updateTable('customer_users')\n .set({ failed_login_attempts: 0, locked_until: null })\n .where('id', '=', user.id)\n .where((eb) => eb.or([eb('locked_until', 'is', null), eb('locked_until', '<=', now)]))\n .returning('id')\n .executeTakeFirst()\n return row !== undefined\n }\n\n async resetFailedAttempts(user: CustomerUser): Promise<void> {\n await this.em.nativeUpdate(CustomerUser, { id: user.id }, {\n failedLoginAttempts: 0,\n lockedUntil: null,\n })\n }\n\n async updatePassword(user: CustomerUser, newPassword: string, em?: EntityManager): Promise<void> {\n const passwordHash = await hash(newPassword, BCRYPT_COST)\n await (em ?? this.em).nativeUpdate(CustomerUser, {\n id: user.id,\n tenantId: user.tenantId,\n organizationId: user.organizationId,\n }, { passwordHash })\n user.passwordHash = passwordHash\n }\n\n // `display_name` is encrypted at rest. `nativeUpdate` issues raw SQL and fires none of the\n // flush hooks the tenant-encryption subscriber depends on, so writing it that way persists\n // plaintext PII into a ciphertext column (#3837). Assign it on the managed entity and flush\n // so `beforeUpdate` encrypts the value on its way to the database.\n async updateProfile(user: CustomerUser, data: { displayName?: string }): Promise<void> {\n if (data.displayName === undefined) return\n const managed = await findOneWithDecryption(\n this.em,\n CustomerUser,\n { id: user.id, tenantId: user.tenantId, organizationId: user.organizationId, deletedAt: null } as any,\n undefined,\n { tenantId: user.tenantId, organizationId: user.organizationId },\n )\n if (!managed) return\n managed.displayName = data.displayName\n await this.em.flush()\n user.displayName = data.displayName\n }\n\n async softDelete(\n userId: string,\n scope?: { tenantId: string; organizationId: string | null },\n ): Promise<void> {\n const where: Record<string, unknown> = { id: userId }\n if (scope) {\n where.tenantId = scope.tenantId\n where.organizationId = scope.organizationId\n }\n await this.em.nativeUpdate(CustomerUser, where, {\n deletedAt: new Date(),\n isActive: false,\n })\n }\n}\n"],
|
|
5
|
-
"mappings": "AACA,SAAS,MAAM,eAAe;AAC9B,SAAS,oBAAoB;AAC7B,SAAS,eAAe,4BAA4B;AACpD,SAAS,6BAA6B;AAEtC,MAAM,cAAc;AACpB,MAAM,sBAAsB;AAC5B,MAAM,sBAAsB,KAAK,KAAK;AAU/B,MAAM,oBAAoB;AAAA,EAC/B,YAAoB,IAAmB;AAAnB;AAAA,EAAoB;AAAA,EAExC,MAAM,WACJ,OACA,UACA,aACA,OACuB;AACvB,UAAM,eAAe,MAAM,KAAK,UAAU,WAAW;
|
|
4
|
+
"sourcesContent": ["import { EntityManager } from '@mikro-orm/postgresql'\nimport { hash, compare } from 'bcryptjs'\nimport { CustomerUser } from '@open-mercato/core/modules/customer_accounts/data/entities'\nimport { hashForLookup, lookupHashCandidates } from '@open-mercato/shared/lib/encryption/aes'\nimport { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\n\nconst BCRYPT_COST = 10\nconst MAX_FAILED_ATTEMPTS = 5\nconst LOCKOUT_DURATION_MS = 15 * 60 * 1000 // 15 minutes\n\ntype CustomerUserLockoutDatabase = {\n customer_users: {\n id: string\n failed_login_attempts: number\n locked_until: Date | null\n }\n}\n\nexport class CustomerUserService {\n constructor(private em: EntityManager) {}\n\n async createUser(\n email: string,\n password: string | null,\n displayName: string,\n scope: { tenantId: string; organizationId: string },\n ): Promise<CustomerUser> {\n const passwordHash = password === null ? null : await hash(password, BCRYPT_COST)\n const emailHash = hashForLookup(email)\n const user = this.em.create(CustomerUser, {\n email: email.toLowerCase().trim(),\n emailHash,\n passwordHash,\n displayName,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n isActive: true,\n failedLoginAttempts: 0,\n createdAt: new Date(),\n } as any)\n return user as CustomerUser\n }\n\n async findByEmail(email: string, tenantId: string): Promise<CustomerUser | null> {\n return findOneWithDecryption(\n this.em,\n CustomerUser,\n {\n emailHash: { $in: lookupHashCandidates(email) },\n tenantId,\n deletedAt: null,\n } as any,\n undefined,\n { tenantId },\n )\n }\n\n async findById(\n id: string,\n tenantId: string,\n organizationId?: string | null,\n ): Promise<CustomerUser | null> {\n const where: Record<string, unknown> = { id, tenantId, deletedAt: null }\n if (organizationId !== undefined) where.organizationId = organizationId\n return findOneWithDecryption(\n this.em,\n CustomerUser,\n where as any,\n undefined,\n { tenantId, organizationId },\n )\n }\n\n async verifyPassword(user: CustomerUser, password: string): Promise<boolean> {\n if (!user.passwordHash) return false\n return compare(password, user.passwordHash)\n }\n\n async updateLastLoginAt(user: CustomerUser): Promise<void> {\n const now = new Date()\n await this.em.nativeUpdate(CustomerUser, { id: user.id }, { lastLoginAt: now })\n user.lastLoginAt = now\n }\n\n checkLockout(user: CustomerUser): boolean {\n if (!user.lockedUntil) return false\n if (user.lockedUntil.getTime() > Date.now()) return true\n return false\n }\n\n async incrementFailedAttempts(user: CustomerUser): Promise<void> {\n const lockedUntil = new Date(Date.now() + LOCKOUT_DURATION_MS)\n await this.em.getKysely<CustomerUserLockoutDatabase>()\n .updateTable('customer_users')\n .set((eb) => ({\n failed_login_attempts: eb('failed_login_attempts', '+', 1),\n locked_until: eb\n .case()\n .when('failed_login_attempts', '>=', MAX_FAILED_ATTEMPTS - 1)\n .then(eb.fn<Date>('greatest', [eb.ref('locked_until'), eb.val(lockedUntil)]))\n .else(eb.ref('locked_until'))\n .end(),\n }))\n .where('id', '=', user.id)\n .execute()\n }\n\n async resetFailedAttemptsUnlessLocked(user: CustomerUser): Promise<boolean> {\n const now = new Date()\n const row = await this.em.getKysely<CustomerUserLockoutDatabase>()\n .updateTable('customer_users')\n .set({ failed_login_attempts: 0, locked_until: null })\n .where('id', '=', user.id)\n .where((eb) => eb.or([eb('locked_until', 'is', null), eb('locked_until', '<=', now)]))\n .returning('id')\n .executeTakeFirst()\n return row !== undefined\n }\n\n async resetFailedAttempts(user: CustomerUser): Promise<void> {\n await this.em.nativeUpdate(CustomerUser, { id: user.id }, {\n failedLoginAttempts: 0,\n lockedUntil: null,\n })\n }\n\n async updatePassword(user: CustomerUser, newPassword: string, em?: EntityManager): Promise<void> {\n const passwordHash = await hash(newPassword, BCRYPT_COST)\n await (em ?? this.em).nativeUpdate(CustomerUser, {\n id: user.id,\n tenantId: user.tenantId,\n organizationId: user.organizationId,\n }, { passwordHash })\n user.passwordHash = passwordHash\n }\n\n // `display_name` is encrypted at rest. `nativeUpdate` issues raw SQL and fires none of the\n // flush hooks the tenant-encryption subscriber depends on, so writing it that way persists\n // plaintext PII into a ciphertext column (#3837). Assign it on the managed entity and flush\n // so `beforeUpdate` encrypts the value on its way to the database.\n async updateProfile(user: CustomerUser, data: { displayName?: string }): Promise<void> {\n if (data.displayName === undefined) return\n const managed = await findOneWithDecryption(\n this.em,\n CustomerUser,\n { id: user.id, tenantId: user.tenantId, organizationId: user.organizationId, deletedAt: null } as any,\n undefined,\n { tenantId: user.tenantId, organizationId: user.organizationId },\n )\n if (!managed) return\n managed.displayName = data.displayName\n await this.em.flush()\n user.displayName = data.displayName\n }\n\n async softDelete(\n userId: string,\n scope?: { tenantId: string; organizationId: string | null },\n ): Promise<void> {\n const where: Record<string, unknown> = { id: userId }\n if (scope) {\n where.tenantId = scope.tenantId\n where.organizationId = scope.organizationId\n }\n await this.em.nativeUpdate(CustomerUser, where, {\n deletedAt: new Date(),\n isActive: false,\n })\n }\n}\n"],
|
|
5
|
+
"mappings": "AACA,SAAS,MAAM,eAAe;AAC9B,SAAS,oBAAoB;AAC7B,SAAS,eAAe,4BAA4B;AACpD,SAAS,6BAA6B;AAEtC,MAAM,cAAc;AACpB,MAAM,sBAAsB;AAC5B,MAAM,sBAAsB,KAAK,KAAK;AAU/B,MAAM,oBAAoB;AAAA,EAC/B,YAAoB,IAAmB;AAAnB;AAAA,EAAoB;AAAA,EAExC,MAAM,WACJ,OACA,UACA,aACA,OACuB;AACvB,UAAM,eAAe,aAAa,OAAO,OAAO,MAAM,KAAK,UAAU,WAAW;AAChF,UAAM,YAAY,cAAc,KAAK;AACrC,UAAM,OAAO,KAAK,GAAG,OAAO,cAAc;AAAA,MACxC,OAAO,MAAM,YAAY,EAAE,KAAK;AAAA,MAChC;AAAA,MACA;AAAA,MACA;AAAA,MACA,UAAU,MAAM;AAAA,MAChB,gBAAgB,MAAM;AAAA,MACtB,UAAU;AAAA,MACV,qBAAqB;AAAA,MACrB,WAAW,oBAAI,KAAK;AAAA,IACtB,CAAQ;AACR,WAAO;AAAA,EACT;AAAA,EA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I,UAAU,KAAK,UAAU,gBAAgB,KAAK,gBAAgB,WAAW,KAAK;AAAA,MAC7F;AAAA,MACA,EAAE,UAAU,KAAK,UAAU,gBAAgB,KAAK,eAAe;AAAA,IACjE;AACA,QAAI,CAAC,QAAS;AACd,YAAQ,cAAc,KAAK;AAC3B,UAAM,KAAK,GAAG,MAAM;AACpB,SAAK,cAAc,KAAK;AAAA,EAC1B;AAAA,EAEA,MAAM,WACJ,QACA,OACe;AACf,UAAM,QAAiC,EAAE,IAAI,OAAO;AACpD,QAAI,OAAO;AACT,YAAM,WAAW,MAAM;AACvB,YAAM,iBAAiB,MAAM;AAAA,IAC/B;AACA,UAAM,KAAK,GAAG,aAAa,cAAc,OAAO;AAAA,MAC9C,WAAW,oBAAI,KAAK;AAAA,MACpB,UAAU;AAAA,IACZ,CAAC;AAAA,EACH;AACF;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -2,6 +2,7 @@ import { CustomerUser } from "@open-mercato/core/modules/customer_accounts/data/
|
|
|
2
2
|
import { findWithDecryption, findOneWithDecryption } from "@open-mercato/shared/lib/encryption/find";
|
|
3
3
|
import { resolveOwnedCompanyForPerson } from "@open-mercato/core/modules/customer_accounts/lib/customerEntityOwnership";
|
|
4
4
|
import { createLogger } from "@open-mercato/shared/lib/logger";
|
|
5
|
+
import { getTelemetryRuntime } from "@open-mercato/shared/lib/telemetry/runtime";
|
|
5
6
|
const logger = createLogger("customer_accounts").child({ component: "auto-link-crm" });
|
|
6
7
|
const metadata = {
|
|
7
8
|
event: "customer_accounts.user.created",
|
|
@@ -10,78 +11,70 @@ const metadata = {
|
|
|
10
11
|
};
|
|
11
12
|
async function handle(payload, ctx) {
|
|
12
13
|
const data = payload;
|
|
13
|
-
const userId = data?.id;
|
|
14
|
+
const userId = data?.userId ?? data?.id;
|
|
14
15
|
const tenantId = data?.tenantId;
|
|
15
16
|
const organizationId = data?.organizationId;
|
|
16
17
|
if (!userId || !tenantId) return;
|
|
17
18
|
const em = ctx.resolve("em");
|
|
18
19
|
try {
|
|
19
|
-
const user = await findOneWithDecryption(em, CustomerUser, {
|
|
20
|
+
const user = await findOneWithDecryption(em, CustomerUser, {
|
|
21
|
+
id: userId,
|
|
22
|
+
tenantId,
|
|
23
|
+
...organizationId ? { organizationId } : {},
|
|
24
|
+
deletedAt: null
|
|
25
|
+
}, void 0, { tenantId, organizationId });
|
|
20
26
|
if (!user) return;
|
|
27
|
+
if (!user.emailVerifiedAt || !user.isActive) return;
|
|
21
28
|
const { CustomerEntity } = await import("@open-mercato/core/modules/customers/data/entities");
|
|
22
29
|
const ownScope = { tenantId, organizationId: user.organizationId };
|
|
23
|
-
|
|
30
|
+
let personEntityId = user.personEntityId ?? null;
|
|
31
|
+
let customerEntityId = user.customerEntityId ?? null;
|
|
32
|
+
if (customerEntityId) {
|
|
24
33
|
const linked = await findOneWithDecryption(
|
|
25
34
|
em,
|
|
26
35
|
CustomerEntity,
|
|
27
|
-
{ id:
|
|
36
|
+
{ id: customerEntityId, ...ownScope, deletedAt: null },
|
|
28
37
|
void 0,
|
|
29
|
-
|
|
38
|
+
ownScope
|
|
30
39
|
);
|
|
31
|
-
if (!linked)
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
{ id: userId, tenantId, organizationId: user.organizationId },
|
|
35
|
-
{ customerEntityId: null }
|
|
36
|
-
);
|
|
37
|
-
user.customerEntityId = null;
|
|
38
|
-
} else if (linked.kind === "person") {
|
|
39
|
-
const replacement = await resolveOwnedCompanyForPerson(em, user.customerEntityId, ownScope);
|
|
40
|
-
await em.nativeUpdate(
|
|
41
|
-
CustomerUser,
|
|
42
|
-
{ id: userId, tenantId, organizationId: user.organizationId },
|
|
43
|
-
{ customerEntityId: replacement }
|
|
44
|
-
);
|
|
45
|
-
user.customerEntityId = replacement;
|
|
40
|
+
if (!linked) customerEntityId = null;
|
|
41
|
+
else if (linked.kind === "person") {
|
|
42
|
+
customerEntityId = await resolveOwnedCompanyForPerson(em, linked.id, ownScope);
|
|
46
43
|
}
|
|
47
44
|
}
|
|
48
|
-
if (
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
{
|
|
55
|
-
{
|
|
45
|
+
if (!personEntityId) {
|
|
46
|
+
const email = user.email?.toLowerCase().trim();
|
|
47
|
+
if (email) {
|
|
48
|
+
const personEntities = await findWithDecryption(
|
|
49
|
+
em,
|
|
50
|
+
CustomerEntity,
|
|
51
|
+
{ ...ownScope, kind: "person", deletedAt: null },
|
|
52
|
+
{ limit: 500 },
|
|
53
|
+
ownScope
|
|
56
54
|
);
|
|
55
|
+
personEntityId = personEntities.find((person) => person.primaryEmail?.toLowerCase().trim() === email)?.id ?? null;
|
|
57
56
|
}
|
|
58
|
-
return;
|
|
59
57
|
}
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
const personEntities = await findWithDecryption(
|
|
63
|
-
em,
|
|
64
|
-
CustomerEntity,
|
|
65
|
-
{ tenantId, organizationId: user.organizationId, kind: "person", deletedAt: null },
|
|
66
|
-
{ limit: 500 },
|
|
67
|
-
{ tenantId, organizationId }
|
|
68
|
-
);
|
|
69
|
-
const matchingEntity = personEntities.find(
|
|
70
|
-
(e) => e.primaryEmail && e.primaryEmail.toLowerCase().trim() === email
|
|
71
|
-
);
|
|
72
|
-
if (!matchingEntity) return;
|
|
73
|
-
const companyEntityId = await resolveOwnedCompanyForPerson(em, matchingEntity.id, ownScope);
|
|
74
|
-
const updates = { personEntityId: matchingEntity.id };
|
|
75
|
-
if (companyEntityId) {
|
|
76
|
-
updates.customerEntityId = companyEntityId;
|
|
58
|
+
if (personEntityId && !customerEntityId) {
|
|
59
|
+
customerEntityId = await resolveOwnedCompanyForPerson(em, personEntityId, ownScope);
|
|
77
60
|
}
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
61
|
+
const updates = {};
|
|
62
|
+
if (personEntityId !== (user.personEntityId ?? null)) updates.personEntityId = personEntityId;
|
|
63
|
+
if (customerEntityId !== (user.customerEntityId ?? null)) updates.customerEntityId = customerEntityId;
|
|
64
|
+
if (!Object.keys(updates).length) return;
|
|
65
|
+
await em.nativeUpdate(CustomerUser, {
|
|
66
|
+
id: userId,
|
|
67
|
+
...ownScope,
|
|
68
|
+
emailHash: user.emailHash,
|
|
69
|
+
emailVerifiedAt: { $ne: null },
|
|
70
|
+
deletedAt: null,
|
|
71
|
+
isActive: true,
|
|
72
|
+
personEntityId: user.personEntityId ?? null,
|
|
73
|
+
customerEntityId: user.customerEntityId ?? null
|
|
74
|
+
}, updates);
|
|
83
75
|
} catch (err) {
|
|
84
76
|
logger.error("Failed to link customer user to CRM person", { err });
|
|
77
|
+
getTelemetryRuntime()?.reportError(err, { module: "customer_accounts", code: "customer_accounts.crm_link_failed" });
|
|
85
78
|
}
|
|
86
79
|
}
|
|
87
80
|
export {
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/modules/customer_accounts/subscribers/autoLinkCrm.ts"],
|
|
4
|
-
"sourcesContent": ["import type { EntityManager } from '@mikro-orm/postgresql'\nimport { CustomerUser } from '@open-mercato/core/modules/customer_accounts/data/entities'\nimport { findWithDecryption, findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { resolveOwnedCompanyForPerson } from '@open-mercato/core/modules/customer_accounts/lib/customerEntityOwnership'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('customer_accounts').child({ component: 'auto-link-crm' })\n\nexport const metadata = {\n event: 'customer_accounts.user.created',\n persistent: true,\n id: 'customer_accounts:auto-link-crm',\n}\n\nexport default async function handle(\n payload: unknown,\n ctx: { resolve: <T = unknown>(name: string) => T; eventName?: string },\n): Promise<void> {\n const data = payload as Record<string, unknown>\n const userId = data?.id as string\n const tenantId = data?.tenantId as string\n const organizationId = data?.organizationId as string | undefined\n if (!userId || !tenantId) return\n\n const em = ctx.resolve<EntityManager>('em')\n\n try {\n const user = await findOneWithDecryption(em, CustomerUser, {
|
|
5
|
-
"mappings": "AACA,SAAS,oBAAoB;AAC7B,SAAS,oBAAoB,6BAA6B;AAC1D,SAAS,oCAAoC;AAC7C,SAAS,oBAAoB;
|
|
4
|
+
"sourcesContent": ["import type { EntityManager } from '@mikro-orm/postgresql'\nimport { CustomerUser } from '@open-mercato/core/modules/customer_accounts/data/entities'\nimport { findWithDecryption, findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { resolveOwnedCompanyForPerson } from '@open-mercato/core/modules/customer_accounts/lib/customerEntityOwnership'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\nimport { getTelemetryRuntime } from '@open-mercato/shared/lib/telemetry/runtime'\n\nconst logger = createLogger('customer_accounts').child({ component: 'auto-link-crm' })\n\nexport const metadata = {\n event: 'customer_accounts.user.created',\n persistent: true,\n id: 'customer_accounts:auto-link-crm',\n}\n\nexport default async function handle(\n payload: unknown,\n ctx: { resolve: <T = unknown>(name: string) => T; eventName?: string },\n): Promise<void> {\n const data = payload as Record<string, unknown>\n const userId = (data?.userId ?? data?.id) as string\n const tenantId = data?.tenantId as string\n const organizationId = data?.organizationId as string | undefined\n if (!userId || !tenantId) return\n\n const em = ctx.resolve<EntityManager>('em')\n\n try {\n const user = await findOneWithDecryption(em, CustomerUser, {\n id: userId,\n tenantId,\n ...(organizationId ? { organizationId } : {}),\n deletedAt: null,\n }, undefined, { tenantId, organizationId })\n if (!user) return\n if (!user.emailVerifiedAt || !user.isActive) return\n\n const { CustomerEntity } = await import('@open-mercato/core/modules/customers/data/entities')\n\n // Every lookup and write below normalizes against the user's OWN org, not just\n // the tenant: customerEntityId is the portal's company scope key (portal user\n // and invite routes filter on it), so adopting an entity from another org would\n // widen the user's portal access instead of repairing it.\n const ownScope = { tenantId, organizationId: user.organizationId }\n\n let personEntityId = user.personEntityId ?? null\n let customerEntityId = user.customerEntityId ?? null\n if (customerEntityId) {\n const linked = await findOneWithDecryption(\n em,\n CustomerEntity,\n { id: customerEntityId, ...ownScope, deletedAt: null },\n undefined,\n ownScope,\n )\n if (!linked) customerEntityId = null\n else if (linked.kind === 'person') {\n customerEntityId = await resolveOwnedCompanyForPerson(em, linked.id, ownScope)\n }\n }\n\n if (!personEntityId) {\n const email = user.email?.toLowerCase().trim()\n if (email) {\n const personEntities = await findWithDecryption(\n em,\n CustomerEntity,\n { ...ownScope, kind: 'person', deletedAt: null },\n { limit: 500 },\n ownScope,\n )\n personEntityId = personEntities.find((person) => person.primaryEmail?.toLowerCase().trim() === email)?.id ?? null\n }\n }\n if (personEntityId && !customerEntityId) {\n customerEntityId = await resolveOwnedCompanyForPerson(em, personEntityId, ownScope)\n }\n\n const updates: Partial<CustomerUser> = {}\n if (personEntityId !== (user.personEntityId ?? null)) updates.personEntityId = personEntityId\n if (customerEntityId !== (user.customerEntityId ?? null)) updates.customerEntityId = customerEntityId\n if (!Object.keys(updates).length) return\n\n await em.nativeUpdate(CustomerUser, {\n id: userId,\n ...ownScope,\n emailHash: user.emailHash,\n emailVerifiedAt: { $ne: null },\n deletedAt: null,\n isActive: true,\n personEntityId: user.personEntityId ?? null,\n customerEntityId: user.customerEntityId ?? null,\n }, updates)\n } catch (err) {\n logger.error('Failed to link customer user to CRM person', { err })\n getTelemetryRuntime()?.reportError(err, { module: 'customer_accounts', code: 'customer_accounts.crm_link_failed' })\n }\n}\n"],
|
|
5
|
+
"mappings": "AACA,SAAS,oBAAoB;AAC7B,SAAS,oBAAoB,6BAA6B;AAC1D,SAAS,oCAAoC;AAC7C,SAAS,oBAAoB;AAC7B,SAAS,2BAA2B;AAEpC,MAAM,SAAS,aAAa,mBAAmB,EAAE,MAAM,EAAE,WAAW,gBAAgB,CAAC;AAE9E,MAAM,WAAW;AAAA,EACtB,OAAO;AAAA,EACP,YAAY;AAAA,EACZ,IAAI;AACN;AAEA,eAAO,OACL,SACA,KACe;AACf,QAAM,OAAO;AACb,QAAM,SAAU,MAAM,UAAU,MAA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;AAAA,IACF;AACA,QAAI,kBAAkB,CAAC,kBAAkB;AACvC,yBAAmB,MAAM,6BAA6B,IAAI,gBAAgB,QAAQ;AAAA,IACpF;AAEA,UAAM,UAAiC,CAAC;AACxC,QAAI,oBAAoB,KAAK,kBAAkB,MAAO,SAAQ,iBAAiB;AAC/E,QAAI,sBAAsB,KAAK,oBAAoB,MAAO,SAAQ,mBAAmB;AACrF,QAAI,CAAC,OAAO,KAAK,OAAO,EAAE,OAAQ;AAElC,UAAM,GAAG,aAAa,cAAc;AAAA,MAClC,IAAI;AAAA,MACJ,GAAG;AAAA,MACH,WAAW,KAAK;AAAA,MAChB,iBAAiB,EAAE,KAAK,KAAK;AAAA,MAC7B,WAAW;AAAA,MACX,UAAU;AAAA,MACV,gBAAgB,KAAK,kBAAkB;AAAA,MACvC,kBAAkB,KAAK,oBAAoB;AAAA,IAC7C,GAAG,OAAO;AAAA,EACZ,SAAS,KAAK;AACZ,WAAO,MAAM,8CAA8C,EAAE,IAAI,CAAC;AAClE,wBAAoB,GAAG,YAAY,KAAK,EAAE,QAAQ,qBAAqB,MAAM,oCAAoC,CAAC;AAAA,EACpH;AACF;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import autoLinkCrm from "./autoLinkCrm.js";
|
|
2
|
+
const metadata = {
|
|
3
|
+
event: "customer_accounts.email.verified",
|
|
4
|
+
persistent: true,
|
|
5
|
+
id: "customer_accounts:auto-link-crm-on-verification"
|
|
6
|
+
};
|
|
7
|
+
var autoLinkCrmOnVerification_default = autoLinkCrm;
|
|
8
|
+
export {
|
|
9
|
+
autoLinkCrmOnVerification_default as default,
|
|
10
|
+
metadata
|
|
11
|
+
};
|
|
12
|
+
//# sourceMappingURL=autoLinkCrmOnVerification.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../../../src/modules/customer_accounts/subscribers/autoLinkCrmOnVerification.ts"],
|
|
4
|
+
"sourcesContent": ["import autoLinkCrm from './autoLinkCrm'\n\nexport const metadata = {\n event: 'customer_accounts.email.verified',\n persistent: true,\n id: 'customer_accounts:auto-link-crm-on-verification',\n}\n\nexport default autoLinkCrm\n"],
|
|
5
|
+
"mappings": "AAAA,OAAO,iBAAiB;AAEjB,MAAM,WAAW;AAAA,EACtB,OAAO;AAAA,EACP,YAAY;AAAA,EACZ,IAAI;AACN;AAEA,IAAO,oCAAQ;",
|
|
6
|
+
"names": []
|
|
7
|
+
}
|
|
@@ -58,10 +58,12 @@ async function handle(payload, ctx) {
|
|
|
58
58
|
emailHash: { $in: emailHashes },
|
|
59
59
|
...ownScope,
|
|
60
60
|
deletedAt: null,
|
|
61
|
+
emailVerifiedAt: { $ne: null },
|
|
62
|
+
isActive: true,
|
|
61
63
|
personEntityId: null
|
|
62
64
|
};
|
|
63
65
|
const customerUser = await findOneWithDecryption(em, CustomerUser, userWhere, void 0, ownScope);
|
|
64
|
-
if (customerUser) {
|
|
66
|
+
if (customerUser?.emailVerifiedAt && customerUser.isActive) {
|
|
65
67
|
const updates = { personEntityId: entity.id, updatedAt: /* @__PURE__ */ new Date() };
|
|
66
68
|
if (!customerUser.customerEntityId) {
|
|
67
69
|
const companyEntityId = await resolveOwnedCompanyForPerson(em, entity.id, ownScope);
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/modules/customer_accounts/subscribers/autoLinkCrmReverse.ts"],
|
|
4
|
-
"sourcesContent": ["import type { EntityManager } from '@mikro-orm/postgresql'\nimport { CustomerUser } from '@open-mercato/core/modules/customer_accounts/data/entities'\nimport { resolveOwnedCompanyForPerson } from '@open-mercato/core/modules/customer_accounts/lib/customerEntityOwnership'\nimport { lookupHashCandidates } from '@open-mercato/shared/lib/encryption/aes'\nimport { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\nimport { getTelemetryRuntime } from '@open-mercato/shared/lib/telemetry/runtime'\n\nconst logger = createLogger('customer_accounts').child({ component: 'auto-link-crm-reverse' })\n\nexport const metadata = {\n event: 'customers.person.created',\n persistent: true,\n id: 'customer_accounts:auto-link-crm-reverse',\n}\n\nexport default async function handle(\n payload: unknown,\n ctx: { resolve: <T = unknown>(name: string) => T; eventName?: string },\n): Promise<void> {\n if (!payload || typeof payload !== 'object') return\n const data = payload as Record<string, unknown>\n const eventId = typeof data.id === 'string' ? data.id : undefined\n const tenantId = typeof data.tenantId === 'string' ? data.tenantId : undefined\n const organizationId = typeof data.organizationId === 'string' ? data.organizationId : undefined\n if (!eventId || !tenantId) return\n\n const em = ctx.resolve<EntityManager>('em')\n\n try {\n const { CustomerEntity, CustomerPersonProfile } = await import('@open-mercato/core/modules/customers/data/entities')\n const eventScope = { tenantId, ...(organizationId ? { organizationId } : {}) }\n\n let entity = await findOneWithDecryption(\n em,\n CustomerEntity,\n { id: eventId, ...eventScope, kind: 'person', deletedAt: null },\n undefined,\n { tenantId, organizationId },\n )\n\n if (!entity) {\n const profile = await findOneWithDecryption(\n em,\n CustomerPersonProfile,\n { id: eventId, ...eventScope },\n undefined,\n eventScope,\n )\n const profileEntity: unknown = profile?.entity\n const personEntityId = typeof profileEntity === 'string' ? profileEntity : profile?.entity?.id\n if (personEntityId && profile?.organizationId) {\n const profileScope = { tenantId, organizationId: profile.organizationId }\n entity = await findOneWithDecryption(\n em,\n CustomerEntity,\n { id: personEntityId, ...profileScope, kind: 'person', deletedAt: null },\n undefined,\n profileScope,\n )\n }\n }\n\n if (!entity?.organizationId) return\n const ownScope = { tenantId, organizationId: entity.organizationId }\n const email = entity.primaryEmail\n if (!email) return\n\n const emailHashes = lookupHashCandidates(email.toLowerCase().trim())\n\n const userWhere = {\n emailHash: { $in: emailHashes },\n ...ownScope,\n deletedAt: null,\n personEntityId: null,\n }\n const customerUser = await findOneWithDecryption(em, CustomerUser, userWhere, undefined, ownScope)\n\n if (customerUser) {\n const updates: Partial<CustomerUser> = { personEntityId: entity.id, updatedAt: new Date() }\n if (!customerUser.customerEntityId) {\n const companyEntityId = await resolveOwnedCompanyForPerson(em, entity.id, ownScope)\n if (companyEntityId) updates.customerEntityId = companyEntityId\n }\n const affected = await em.nativeUpdate(CustomerUser, {\n id: customerUser.id,\n ...userWhere,\n customerEntityId: customerUser.customerEntityId ?? null,\n }, updates)\n if (affected === 0) return\n }\n } catch (err) {\n logger.error('Failed to link CRM person to customer user', { err })\n getTelemetryRuntime()?.reportError(err, { module: 'customer_accounts', code: 'customer_accounts.reverse_crm_link_failed' })\n }\n}\n"],
|
|
5
|
-
"mappings": "AACA,SAAS,oBAAoB;AAC7B,SAAS,oCAAoC;AAC7C,SAAS,4BAA4B;AACrC,SAAS,6BAA6B;AACtC,SAAS,oBAAoB;AAC7B,SAAS,2BAA2B;AAEpC,MAAM,SAAS,aAAa,mBAAmB,EAAE,MAAM,EAAE,WAAW,wBAAwB,CAAC;AAEtF,MAAM,WAAW;AAAA,EACtB,OAAO;AAAA,EACP,YAAY;AAAA,EACZ,IAAI;AACN;AAEA,eAAO,OACL,SACA,KACe;AACf,MAAI,CAAC,WAAW,OAAO,YAAY,SAAU;AAC7C,QAAM,OAAO;AACb,QAAM,UAAU,OAAO,KAAK,OAAO,WAAW,KAAK,KAAK;AACxD,QAAM,WAAW,OAAO,KAAK,aAAa,WAAW,KAAK,WAAW;AACrE,QAAM,iBAAiB,OAAO,KAAK,mBAAmB,WAAW,KAAK,iBAAiB;AACvF,MAAI,CAAC,WAAW,CAAC,SAAU;AAE3B,QAAM,KAAK,IAAI,QAAuB,IAAI;AAE1C,MAAI;AACF,UAAM,EAAE,gBAAgB,sBAAsB,IAAI,MAAM,OAAO,oDAAoD;AACnH,UAAM,aAAa,EAAE,UAAU,GAAI,iBAAiB,EAAE,eAAe,IAAI,CAAC,EAAG;AAE7E,QAAI,SAAS,MAAM;AAAA,MACjB;AAAA,MACA;AAAA,MACA,EAAE,IAAI,SAAS,GAAG,YAAY,MAAM,UAAU,WAAW,KAAK;AAAA,MAC9D;AAAA,MACA,EAAE,UAAU,eAAe;AAAA,IAC7B;AAEA,QAAI,CAAC,QAAQ;AACX,YAAM,UAAU,MAAM;AAAA,QACpB;AAAA,QACA;AAAA,QACA,EAAE,IAAI,SAAS,GAAG,WAAW;AAAA,QAC7B;AAAA,QACA;AAAA,MACF;AACA,YAAM,gBAAyB,SAAS;AACxC,YAAM,iBAAiB,OAAO,kBAAkB,WAAW,gBAAgB,SAAS,QAAQ;AAC5F,UAAI,kBAAkB,SAAS,gBAAgB;AAC7C,cAAM,eAAe,EAAE,UAAU,gBAAgB,QAAQ,eAAe;AACxE,iBAAS,MAAM;AAAA,UACb;AAAA,UACA;AAAA,UACA,EAAE,IAAI,gBAAgB,GAAG,cAAc,MAAM,UAAU,WAAW,KAAK;AAAA,UACvE;AAAA,UACA;AAAA,QACF;AAAA,MACF;AAAA,IACF;AAEA,QAAI,CAAC,QAAQ,eAAgB;AAC7B,UAAM,WAAW,EAAE,UAAU,gBAAgB,OAAO,eAAe;AACnE,UAAM,QAAQ,OAAO;AACrB,QAAI,CAAC,MAAO;AAEZ,UAAM,cAAc,qBAAqB,MAAM,YAAY,EAAE,KAAK,CAAC;AAEnE,UAAM,YAAY;AAAA,MAChB,WAAW,EAAE,KAAK,YAAY;AAAA,MAC9B,GAAG;AAAA,MACH,WAAW;AAAA,MACX,gBAAgB;AAAA,IAClB;AACA,UAAM,eAAe,MAAM,sBAAsB,IAAI,cAAc,WAAW,QAAW,QAAQ;AAEjG,QAAI,cAAc;
|
|
4
|
+
"sourcesContent": ["import type { EntityManager } from '@mikro-orm/postgresql'\nimport { CustomerUser } from '@open-mercato/core/modules/customer_accounts/data/entities'\nimport { resolveOwnedCompanyForPerson } from '@open-mercato/core/modules/customer_accounts/lib/customerEntityOwnership'\nimport { lookupHashCandidates } from '@open-mercato/shared/lib/encryption/aes'\nimport { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\nimport { getTelemetryRuntime } from '@open-mercato/shared/lib/telemetry/runtime'\n\nconst logger = createLogger('customer_accounts').child({ component: 'auto-link-crm-reverse' })\n\nexport const metadata = {\n event: 'customers.person.created',\n persistent: true,\n id: 'customer_accounts:auto-link-crm-reverse',\n}\n\nexport default async function handle(\n payload: unknown,\n ctx: { resolve: <T = unknown>(name: string) => T; eventName?: string },\n): Promise<void> {\n if (!payload || typeof payload !== 'object') return\n const data = payload as Record<string, unknown>\n const eventId = typeof data.id === 'string' ? data.id : undefined\n const tenantId = typeof data.tenantId === 'string' ? data.tenantId : undefined\n const organizationId = typeof data.organizationId === 'string' ? data.organizationId : undefined\n if (!eventId || !tenantId) return\n\n const em = ctx.resolve<EntityManager>('em')\n\n try {\n const { CustomerEntity, CustomerPersonProfile } = await import('@open-mercato/core/modules/customers/data/entities')\n const eventScope = { tenantId, ...(organizationId ? { organizationId } : {}) }\n\n let entity = await findOneWithDecryption(\n em,\n CustomerEntity,\n { id: eventId, ...eventScope, kind: 'person', deletedAt: null },\n undefined,\n { tenantId, organizationId },\n )\n\n if (!entity) {\n const profile = await findOneWithDecryption(\n em,\n CustomerPersonProfile,\n { id: eventId, ...eventScope },\n undefined,\n eventScope,\n )\n const profileEntity: unknown = profile?.entity\n const personEntityId = typeof profileEntity === 'string' ? profileEntity : profile?.entity?.id\n if (personEntityId && profile?.organizationId) {\n const profileScope = { tenantId, organizationId: profile.organizationId }\n entity = await findOneWithDecryption(\n em,\n CustomerEntity,\n { id: personEntityId, ...profileScope, kind: 'person', deletedAt: null },\n undefined,\n profileScope,\n )\n }\n }\n\n if (!entity?.organizationId) return\n const ownScope = { tenantId, organizationId: entity.organizationId }\n const email = entity.primaryEmail\n if (!email) return\n\n const emailHashes = lookupHashCandidates(email.toLowerCase().trim())\n\n const userWhere = {\n emailHash: { $in: emailHashes },\n ...ownScope,\n deletedAt: null,\n emailVerifiedAt: { $ne: null },\n isActive: true,\n personEntityId: null,\n }\n const customerUser = await findOneWithDecryption(em, CustomerUser, userWhere, undefined, ownScope)\n\n if (customerUser?.emailVerifiedAt && customerUser.isActive) {\n const updates: Partial<CustomerUser> = { personEntityId: entity.id, updatedAt: new Date() }\n if (!customerUser.customerEntityId) {\n const companyEntityId = await resolveOwnedCompanyForPerson(em, entity.id, ownScope)\n if (companyEntityId) updates.customerEntityId = companyEntityId\n }\n const affected = await em.nativeUpdate(CustomerUser, {\n id: customerUser.id,\n ...userWhere,\n customerEntityId: customerUser.customerEntityId ?? null,\n }, updates)\n if (affected === 0) return\n }\n } catch (err) {\n logger.error('Failed to link CRM person to customer user', { err })\n getTelemetryRuntime()?.reportError(err, { module: 'customer_accounts', code: 'customer_accounts.reverse_crm_link_failed' })\n }\n}\n"],
|
|
5
|
+
"mappings": "AACA,SAAS,oBAAoB;AAC7B,SAAS,oCAAoC;AAC7C,SAAS,4BAA4B;AACrC,SAAS,6BAA6B;AACtC,SAAS,oBAAoB;AAC7B,SAAS,2BAA2B;AAEpC,MAAM,SAAS,aAAa,mBAAmB,EAAE,MAAM,EAAE,WAAW,wBAAwB,CAAC;AAEtF,MAAM,WAAW;AAAA,EACtB,OAAO;AAAA,EACP,YAAY;AAAA,EACZ,IAAI;AACN;AAEA,eAAO,OACL,SACA,KACe;AACf,MAAI,CAAC,WAAW,OAAO,YAAY,SAAU;AAC7C,QAAM,OAAO;AACb,QAAM,UAAU,OAAO,KAAK,OAAO,WAAW,KAAK,KAAK;AACxD,QAAM,WAAW,OAAO,KAAK,aAAa,WAAW,KAAK,WAAW;AACrE,QAAM,iBAAiB,OAAO,KAAK,mBAAmB,WAAW,KAAK,iBAAiB;AACvF,MAAI,CAAC,WAAW,CAAC,SAAU;AAE3B,QAAM,KAAK,IAAI,QAAuB,IAAI;AAE1C,MAAI;AACF,UAAM,EAAE,gBAAgB,sBAAsB,IAAI,MAAM,OAAO,oDAAoD;AACnH,UAAM,aAAa,EAAE,UAAU,GAAI,i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EAAE;AAC1F,UAAI,CAAC,aAAa,kBAAkB;AAClC,cAAM,kBAAkB,MAAM,6BAA6B,IAAI,OAAO,IAAI,QAAQ;AAClF,YAAI,gBAAiB,SAAQ,mBAAmB;AAAA,MAClD;AACA,YAAM,WAAW,MAAM,GAAG,aAAa,cAAc;AAAA,QACnD,IAAI,aAAa;AAAA,QACjB,GAAG;AAAA,QACH,kBAAkB,aAAa,oBAAoB;AAAA,MACrD,GAAG,OAAO;AACV,UAAI,aAAa,EAAG;AAAA,IACtB;AAAA,EACF,SAAS,KAAK;AACZ,WAAO,MAAM,8CAA8C,EAAE,IAAI,CAAC;AAClE,wBAAoB,GAAG,YAAY,KAAK,EAAE,QAAQ,qBAAqB,MAAM,4CAA4C,CAAC;AAAA,EAC5H;AACF;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -1,8 +1,10 @@
|
|
|
1
1
|
import {
|
|
2
|
+
CustomerUser,
|
|
2
3
|
CustomerUserEmailVerification,
|
|
3
4
|
CustomerUserPasswordReset,
|
|
4
5
|
CustomerUserInvitation
|
|
5
6
|
} from "@open-mercato/core/modules/customer_accounts/data/entities";
|
|
7
|
+
import { pendingSignup, signupExpiryCutoff } from "../lib/pendingSignup.js";
|
|
6
8
|
const metadata = {
|
|
7
9
|
queue: "customer-accounts-cleanup-tokens",
|
|
8
10
|
id: "customer_accounts:cleanup-expired-tokens",
|
|
@@ -11,6 +13,10 @@ const metadata = {
|
|
|
11
13
|
async function handle(job, ctx) {
|
|
12
14
|
const em = ctx.resolve("em");
|
|
13
15
|
const now = /* @__PURE__ */ new Date();
|
|
16
|
+
await em.nativeUpdate(CustomerUser, {
|
|
17
|
+
...pendingSignup,
|
|
18
|
+
createdAt: { $lte: signupExpiryCutoff(now) }
|
|
19
|
+
}, { deletedAt: now, isActive: false, passwordHash: null, sessionsRevokedAt: now });
|
|
14
20
|
await em.nativeDelete(CustomerUserEmailVerification, {
|
|
15
21
|
$or: [
|
|
16
22
|
{ expiresAt: { $lt: now }, usedAt: null },
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/modules/customer_accounts/workers/cleanupExpiredTokens.ts"],
|
|
4
|
-
"sourcesContent": ["import type { JobContext, QueuedJob, WorkerMeta } from '@open-mercato/queue'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport {\n CustomerUserEmailVerification,\n CustomerUserPasswordReset,\n CustomerUserInvitation,\n} from '@open-mercato/core/modules/customer_accounts/data/entities'\n\nexport const metadata: WorkerMeta = {\n queue: 'customer-accounts-cleanup-tokens',\n id: 'customer_accounts:cleanup-expired-tokens',\n concurrency: 1,\n}\n\ntype HandlerContext = JobContext & {\n resolve: <T = unknown>(name: string) => T\n}\n\nexport default async function handle(job: QueuedJob, ctx: HandlerContext): Promise<void> {\n const em = ctx.resolve<EntityManager>('em')\n const now = new Date()\n\n // Cleanup expired email verifications\n await em.nativeDelete(CustomerUserEmailVerification, {\n $or: [\n { expiresAt: { $lt: now }, usedAt: null },\n { usedAt: { $ne: null } },\n ],\n } as any)\n\n // Cleanup expired password resets\n await em.nativeDelete(CustomerUserPasswordReset, {\n $or: [\n { expiresAt: { $lt: now }, usedAt: null },\n { usedAt: { $ne: null } },\n ],\n } as any)\n\n // Cleanup expired/accepted/cancelled invitations\n await em.nativeDelete(CustomerUserInvitation, {\n $or: [\n { expiresAt: { $lt: now }, acceptedAt: null, cancelledAt: null },\n { acceptedAt: { $ne: null } },\n { cancelledAt: { $ne: null } },\n ],\n } as any)\n}\n"],
|
|
5
|
-
"mappings": "AAEA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;
|
|
4
|
+
"sourcesContent": ["import type { JobContext, QueuedJob, WorkerMeta } from '@open-mercato/queue'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport {\n CustomerUser,\n CustomerUserEmailVerification,\n CustomerUserPasswordReset,\n CustomerUserInvitation,\n} from '@open-mercato/core/modules/customer_accounts/data/entities'\nimport { pendingSignup, signupExpiryCutoff } from '../lib/pendingSignup'\n\nexport const metadata: WorkerMeta = {\n queue: 'customer-accounts-cleanup-tokens',\n id: 'customer_accounts:cleanup-expired-tokens',\n concurrency: 1,\n}\n\ntype HandlerContext = JobContext & {\n resolve: <T = unknown>(name: string) => T\n}\n\nexport default async function handle(job: QueuedJob, ctx: HandlerContext): Promise<void> {\n const em = ctx.resolve<EntityManager>('em')\n const now = new Date()\n\n await em.nativeUpdate(CustomerUser, {\n ...pendingSignup,\n createdAt: { $lte: signupExpiryCutoff(now) },\n }, { deletedAt: now, isActive: false, passwordHash: null, sessionsRevokedAt: now })\n\n // Cleanup expired email verifications\n await em.nativeDelete(CustomerUserEmailVerification, {\n $or: [\n { expiresAt: { $lt: now }, usedAt: null },\n { usedAt: { $ne: null } },\n ],\n } as any)\n\n // Cleanup expired password resets\n await em.nativeDelete(CustomerUserPasswordReset, {\n $or: [\n { expiresAt: { $lt: now }, usedAt: null },\n { usedAt: { $ne: null } },\n ],\n } as any)\n\n // Cleanup expired/accepted/cancelled invitations\n await em.nativeDelete(CustomerUserInvitation, {\n $or: [\n { expiresAt: { $lt: now }, acceptedAt: null, cancelledAt: null },\n { acceptedAt: { $ne: null } },\n { cancelledAt: { $ne: null } },\n ],\n } as any)\n}\n"],
|
|
5
|
+
"mappings": "AAEA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,eAAe,0BAA0B;AAE3C,MAAM,WAAuB;AAAA,EAClC,OAAO;AAAA,EACP,IAAI;AAAA,EACJ,aAAa;AACf;AAMA,eAAO,OAA8B,KAAgB,KAAoC;AACvF,QAAM,KAAK,IAAI,QAAuB,IAAI;AAC1C,QAAM,MAAM,oBAAI,KAAK;AAErB,QAAM,GAAG,aAAa,cAAc;AAAA,IAClC,GAAG;AAAA,IACH,WAAW,EAAE,MAAM,mBAAmB,GAAG,EAAE;AAAA,EAC7C,GAAG,EAAE,WAAW,KAAK,UAAU,OAAO,cAAc,MAAM,mBAAmB,IAAI,CAAC;AAGlF,QAAM,GAAG,aAAa,+BAA+B;AAAA,IACnD,KAAK;AAAA,MACH,EAAE,WAAW,EAAE,KAAK,IAAI,GAAG,QAAQ,KAAK;AAAA,MACxC,EAAE,QAAQ,EAAE,KAAK,KAAK,EAAE;AAAA,IAC1B;AAAA,EACF,CAAQ;AAGR,QAAM,GAAG,aAAa,2BAA2B;AAAA,IAC/C,KAAK;AAAA,MACH,EAAE,WAAW,EAAE,KAAK,IAAI,GAAG,QAAQ,KAAK;AAAA,MACxC,EAAE,QAAQ,EAAE,KAAK,KAAK,EAAE;AAAA,IAC1B;AAAA,EACF,CAAQ;AAGR,QAAM,GAAG,aAAa,wBAAwB;AAAA,IAC5C,KAAK;AAAA,MACH,EAAE,WAAW,EAAE,KAAK,IAAI,GAAG,YAAY,MAAM,aAAa,KAAK;AAAA,MAC/D,EAAE,YAAY,EAAE,KAAK,KAAK,EAAE;AAAA,MAC5B,EAAE,aAAa,EAAE,KAAK,KAAK,EAAE;AAAA,IAC/B;AAAA,EACF,CAAQ;AACV;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -296,9 +296,9 @@ async function loadCompanySnapshot(em, id, ctx, options = {}) {
|
|
|
296
296
|
)
|
|
297
297
|
};
|
|
298
298
|
}
|
|
299
|
-
async function setCompanyCustomFields(ctx, entityId, profileId, organizationId, tenantId, values) {
|
|
299
|
+
async function setCompanyCustomFields(ctx, entityId, profileId, organizationId, tenantId, values, transactionalEm) {
|
|
300
300
|
if (!values || !Object.keys(values).length) return;
|
|
301
|
-
const em = ctx.container.resolve("em");
|
|
301
|
+
const em = transactionalEm ?? ctx.container.resolve("em");
|
|
302
302
|
const routing = await resolveCompanyCustomFieldRouting(em, tenantId, organizationId);
|
|
303
303
|
const entityScoped = {};
|
|
304
304
|
const profileScoped = {};
|
|
@@ -316,6 +316,7 @@ async function setCompanyCustomFields(ctx, entityId, profileId, organizationId,
|
|
|
316
316
|
organizationId,
|
|
317
317
|
tenantId,
|
|
318
318
|
values: entityScoped,
|
|
319
|
+
transactionalEm,
|
|
319
320
|
notify: false
|
|
320
321
|
});
|
|
321
322
|
}
|
|
@@ -327,6 +328,7 @@ async function setCompanyCustomFields(ctx, entityId, profileId, organizationId,
|
|
|
327
328
|
organizationId,
|
|
328
329
|
tenantId,
|
|
329
330
|
values: profileScoped,
|
|
331
|
+
transactionalEm,
|
|
330
332
|
notify: false
|
|
331
333
|
});
|
|
332
334
|
}
|
|
@@ -401,9 +403,9 @@ const createCompanyCommand = {
|
|
|
401
403
|
em.persist(entity);
|
|
402
404
|
em.persist(profile);
|
|
403
405
|
},
|
|
404
|
-
() => syncEntityTags(em, entity, parsed.tags)
|
|
406
|
+
() => syncEntityTags(em, entity, parsed.tags),
|
|
407
|
+
() => setCompanyCustomFields(ctx, entity.id, profile.id, entity.organizationId, entity.tenantId, custom, em)
|
|
405
408
|
], { transaction: true });
|
|
406
|
-
await setCompanyCustomFields(ctx, entity.id, profile.id, entity.organizationId, entity.tenantId, custom);
|
|
407
409
|
const de = ctx.container.resolve("dataEngine");
|
|
408
410
|
await emitCrudSideEffects({
|
|
409
411
|
dataEngine: de,
|
|
@@ -671,9 +673,9 @@ const updateCompanyCommand = {
|
|
|
671
673
|
record.updatedAt = /* @__PURE__ */ new Date();
|
|
672
674
|
}
|
|
673
675
|
},
|
|
674
|
-
() => syncEntityTags(em, record, parsed.tags, { ignoreMissing: ignoreMissingTags })
|
|
676
|
+
() => syncEntityTags(em, record, parsed.tags, { ignoreMissing: ignoreMissingTags }),
|
|
677
|
+
() => setCompanyCustomFields(ctx, record.id, profile.id, record.organizationId, record.tenantId, custom, em)
|
|
675
678
|
], { transaction: true });
|
|
676
|
-
await setCompanyCustomFields(ctx, record.id, profile.id, record.organizationId, record.tenantId, custom);
|
|
677
679
|
const de = ctx.container.resolve("dataEngine");
|
|
678
680
|
await emitCrudSideEffects({
|
|
679
681
|
dataEngine: de,
|