@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
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { LockMode } from '@mikro-orm/core'
|
|
2
|
+
import type { EntityManager } from '@mikro-orm/postgresql'
|
|
3
|
+
import { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'
|
|
4
|
+
import { CustomerUser } from '../data/entities'
|
|
5
|
+
import { emitCustomerAccountsEvent } from '@open-mercato/core/modules/customer_accounts/events'
|
|
6
|
+
import type { CustomerSessionService } from '../services/customerSessionService'
|
|
7
|
+
import type { CustomerUserService } from '../services/customerUserService'
|
|
8
|
+
import { signupExpiryCutoff } from './pendingSignup'
|
|
9
|
+
|
|
10
|
+
export async function verifyCustomerEmail(
|
|
11
|
+
em: EntityManager,
|
|
12
|
+
identity: { userId: string; tenantId: string; organizationId?: string },
|
|
13
|
+
sessions: CustomerSessionService,
|
|
14
|
+
options?: { password: string; users: CustomerUserService; reset?: boolean },
|
|
15
|
+
): Promise<{ user: CustomerUser; newlyVerified: boolean } | null> {
|
|
16
|
+
const { userId, tenantId, organizationId } = identity
|
|
17
|
+
const user = await findOneWithDecryption(
|
|
18
|
+
em,
|
|
19
|
+
CustomerUser,
|
|
20
|
+
{ id: userId, tenantId, ...(organizationId ? { organizationId } : {}), deletedAt: null },
|
|
21
|
+
{ lockMode: LockMode.PESSIMISTIC_WRITE, refresh: true },
|
|
22
|
+
{ tenantId, organizationId },
|
|
23
|
+
)
|
|
24
|
+
if (!user?.isActive) return null
|
|
25
|
+
|
|
26
|
+
const now = new Date()
|
|
27
|
+
const newlyVerified = !user.emailVerifiedAt
|
|
28
|
+
if (newlyVerified && !user.lastLoginAt && user.createdAt <= signupExpiryCutoff(now)) return null
|
|
29
|
+
if (!newlyVerified && !options) return { user, newlyVerified }
|
|
30
|
+
if (!newlyVerified && !options?.reset && user.passwordHash) {
|
|
31
|
+
return null
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
const scope = { id: user.id, tenantId, organizationId: user.organizationId }
|
|
35
|
+
if (options) {
|
|
36
|
+
await options.users.updatePassword(user, options.password, em)
|
|
37
|
+
}
|
|
38
|
+
if (newlyVerified) {
|
|
39
|
+
await em.nativeUpdate(CustomerUser, scope, {
|
|
40
|
+
emailVerifiedAt: now,
|
|
41
|
+
...(options ? {} : { passwordHash: null }),
|
|
42
|
+
})
|
|
43
|
+
}
|
|
44
|
+
await sessions.revokeAllUserSessions(user.id, em)
|
|
45
|
+
return { user, newlyVerified }
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export function emitCustomerEmailVerified(user: CustomerUser, verifiedBy?: string): void {
|
|
49
|
+
void emitCustomerAccountsEvent('customer_accounts.email.verified', {
|
|
50
|
+
id: user.id,
|
|
51
|
+
userId: user.id,
|
|
52
|
+
recipientUserId: user.id,
|
|
53
|
+
tenantId: user.tenantId,
|
|
54
|
+
organizationId: user.organizationId,
|
|
55
|
+
...(verifiedBy ? { email: user.email, verifiedBy } : {}),
|
|
56
|
+
}).catch(() => undefined)
|
|
57
|
+
}
|
|
@@ -5,12 +5,14 @@ import {
|
|
|
5
5
|
CustomerUser,
|
|
6
6
|
CustomerUserInvitation,
|
|
7
7
|
CustomerUserRole,
|
|
8
|
+
CustomerUserSession,
|
|
8
9
|
CustomerRole,
|
|
9
10
|
} from '@open-mercato/core/modules/customer_accounts/data/entities'
|
|
10
11
|
import { generateSecureToken, hashToken } from '@open-mercato/core/modules/customer_accounts/lib/tokenGenerator'
|
|
11
12
|
import { hashForLookup, lookupHashCandidates } from '@open-mercato/shared/lib/encryption/aes'
|
|
12
13
|
import { findOneWithDecryption, findWithDecryption } from '@open-mercato/shared/lib/encryption/find'
|
|
13
14
|
import { isCustomerTenantActive } from '@open-mercato/core/modules/customer_accounts/lib/tenantEligibility'
|
|
15
|
+
import { pendingSignup } from '../lib/pendingSignup'
|
|
14
16
|
|
|
15
17
|
const BCRYPT_COST = 10
|
|
16
18
|
const INVITATION_TTL_MS = 72 * 60 * 60 * 1000 // 72 hours
|
|
@@ -270,7 +272,20 @@ export class CustomerInvitationService {
|
|
|
270
272
|
scope,
|
|
271
273
|
)
|
|
272
274
|
if (existingActiveUser) {
|
|
273
|
-
|
|
275
|
+
if (existingActiveUser.organizationId !== scope.organizationId
|
|
276
|
+
|| !existingActiveUser.isActive || existingActiveUser.emailVerifiedAt || existingActiveUser.lastLoginAt) {
|
|
277
|
+
throw new CustomerInvitationEmailConflictError(invitation.email)
|
|
278
|
+
}
|
|
279
|
+
const retired = await transactionEm.nativeUpdate(CustomerUser, {
|
|
280
|
+
id: existingActiveUser.id,
|
|
281
|
+
...scope,
|
|
282
|
+
...pendingSignup,
|
|
283
|
+
}, { deletedAt: acceptedAt, isActive: false, passwordHash: null, sessionsRevokedAt: acceptedAt })
|
|
284
|
+
if (retired !== 1) throw new CustomerInvitationEmailConflictError(invitation.email)
|
|
285
|
+
await transactionEm.nativeUpdate(CustomerUserSession, {
|
|
286
|
+
user: existingActiveUser.id,
|
|
287
|
+
deletedAt: null,
|
|
288
|
+
}, { deletedAt: acceptedAt })
|
|
274
289
|
}
|
|
275
290
|
|
|
276
291
|
const user = transactionEm.create(CustomerUser, {
|
|
@@ -7,30 +7,30 @@ import {
|
|
|
7
7
|
} from '@open-mercato/core/modules/customer_accounts/data/entities'
|
|
8
8
|
import { generateSecureToken, hashToken } from '@open-mercato/core/modules/customer_accounts/lib/tokenGenerator'
|
|
9
9
|
import { isCustomerTenantActive } from '@open-mercato/core/modules/customer_accounts/lib/tenantEligibility'
|
|
10
|
+
import { EMAIL_VERIFICATION_TTL_MS } from '../lib/pendingSignup'
|
|
10
11
|
|
|
11
12
|
function getKysely(em: EntityManager): Kysely<any> {
|
|
12
13
|
return (em as unknown as { getKysely: () => Kysely<any> }).getKysely()
|
|
13
14
|
}
|
|
14
15
|
|
|
15
|
-
const EMAIL_VERIFICATION_TTL_MS = 24 * 60 * 60 * 1000 // 24 hours
|
|
16
16
|
const MAGIC_LINK_TTL_MS = 15 * 60 * 1000 // 15 minutes
|
|
17
17
|
const PASSWORD_RESET_TTL_MS = 60 * 60 * 1000 // 60 minutes
|
|
18
18
|
|
|
19
19
|
export class CustomerTokenService {
|
|
20
20
|
constructor(private em: EntityManager) {}
|
|
21
21
|
|
|
22
|
-
async createEmailVerification(userId: string, tenantId: string): Promise<string> {
|
|
22
|
+
async createEmailVerification(userId: string, tenantId: string, createdAt = new Date(), em = this.em): Promise<string> {
|
|
23
23
|
const rawToken = generateSecureToken()
|
|
24
24
|
const tokenHashed = hashToken(rawToken)
|
|
25
|
-
const expiresAt = new Date(
|
|
26
|
-
const record =
|
|
25
|
+
const expiresAt = new Date(createdAt.getTime() + EMAIL_VERIFICATION_TTL_MS)
|
|
26
|
+
const record = em.create(CustomerUserEmailVerification, {
|
|
27
27
|
user: userId as any,
|
|
28
28
|
token: tokenHashed,
|
|
29
29
|
purpose: 'email_verification',
|
|
30
30
|
expiresAt,
|
|
31
|
-
createdAt
|
|
31
|
+
createdAt,
|
|
32
32
|
} as any)
|
|
33
|
-
await
|
|
33
|
+
await em.persist(record).flush()
|
|
34
34
|
return rawToken
|
|
35
35
|
}
|
|
36
36
|
|
|
@@ -63,9 +63,9 @@ export class CustomerTokenService {
|
|
|
63
63
|
return rawToken
|
|
64
64
|
}
|
|
65
65
|
|
|
66
|
-
async verifyEmailToken(token: string, purpose: string, tenantId?: string): Promise<{ userId: string; tenantId: string } | null> {
|
|
66
|
+
async verifyEmailToken(token: string, purpose: string, tenantId?: string, em = this.em): Promise<{ userId: string; tenantId: string } | null> {
|
|
67
67
|
const tokenHashed = hashToken(token)
|
|
68
|
-
const record = await
|
|
68
|
+
const record = await em.findOne(CustomerUserEmailVerification, {
|
|
69
69
|
token: tokenHashed,
|
|
70
70
|
purpose,
|
|
71
71
|
}, { populate: ['user'] })
|
|
@@ -75,9 +75,9 @@ export class CustomerTokenService {
|
|
|
75
75
|
|
|
76
76
|
const user = record.user as CustomerUser
|
|
77
77
|
if (tenantId && user?.tenantId !== tenantId) return null
|
|
78
|
-
if (purpose === 'magic_link' && !(await isCustomerTenantActive(
|
|
78
|
+
if (purpose === 'magic_link' && !(await isCustomerTenantActive(em, user?.tenantId))) return null
|
|
79
79
|
|
|
80
|
-
const db = getKysely(
|
|
80
|
+
const db = getKysely(em)
|
|
81
81
|
const updateResult = await db
|
|
82
82
|
.updateTable('customer_user_email_verifications' as any)
|
|
83
83
|
.set({ used_at: new Date() } as any)
|
|
@@ -93,9 +93,9 @@ export class CustomerTokenService {
|
|
|
93
93
|
return { userId: resolvedUserId, tenantId: resolvedTenantId }
|
|
94
94
|
}
|
|
95
95
|
|
|
96
|
-
async verifyPasswordResetToken(token: string, tenantId?: string): Promise<{ userId: string; tenantId: string } | null> {
|
|
96
|
+
async verifyPasswordResetToken(token: string, tenantId?: string, em = this.em): Promise<{ userId: string; tenantId: string } | null> {
|
|
97
97
|
const tokenHashed = hashToken(token)
|
|
98
|
-
const record = await
|
|
98
|
+
const record = await em.findOne(CustomerUserPasswordReset, {
|
|
99
99
|
token: tokenHashed,
|
|
100
100
|
}, { populate: ['user'] })
|
|
101
101
|
if (!record) return null
|
|
@@ -105,7 +105,7 @@ export class CustomerTokenService {
|
|
|
105
105
|
const user = record.user as CustomerUser
|
|
106
106
|
if (tenantId && user?.tenantId !== tenantId) return null
|
|
107
107
|
|
|
108
|
-
const db = getKysely(
|
|
108
|
+
const db = getKysely(em)
|
|
109
109
|
const updateResult = await db
|
|
110
110
|
.updateTable('customer_user_password_resets' as any)
|
|
111
111
|
.set({ used_at: new Date() } as any)
|
|
@@ -21,11 +21,11 @@ export class CustomerUserService {
|
|
|
21
21
|
|
|
22
22
|
async createUser(
|
|
23
23
|
email: string,
|
|
24
|
-
password: string,
|
|
24
|
+
password: string | null,
|
|
25
25
|
displayName: string,
|
|
26
26
|
scope: { tenantId: string; organizationId: string },
|
|
27
27
|
): Promise<CustomerUser> {
|
|
28
|
-
const passwordHash = await hash(password, BCRYPT_COST)
|
|
28
|
+
const passwordHash = password === null ? null : await hash(password, BCRYPT_COST)
|
|
29
29
|
const emailHash = hashForLookup(email)
|
|
30
30
|
const user = this.em.create(CustomerUser, {
|
|
31
31
|
email: email.toLowerCase().trim(),
|
|
@@ -3,6 +3,7 @@ import { CustomerUser } from '@open-mercato/core/modules/customer_accounts/data/
|
|
|
3
3
|
import { findWithDecryption, findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'
|
|
4
4
|
import { resolveOwnedCompanyForPerson } from '@open-mercato/core/modules/customer_accounts/lib/customerEntityOwnership'
|
|
5
5
|
import { createLogger } from '@open-mercato/shared/lib/logger'
|
|
6
|
+
import { getTelemetryRuntime } from '@open-mercato/shared/lib/telemetry/runtime'
|
|
6
7
|
|
|
7
8
|
const logger = createLogger('customer_accounts').child({ component: 'auto-link-crm' })
|
|
8
9
|
|
|
@@ -17,7 +18,7 @@ export default async function handle(
|
|
|
17
18
|
ctx: { resolve: <T = unknown>(name: string) => T; eventName?: string },
|
|
18
19
|
): Promise<void> {
|
|
19
20
|
const data = payload as Record<string, unknown>
|
|
20
|
-
const userId = data?.id as string
|
|
21
|
+
const userId = (data?.userId ?? data?.id) as string
|
|
21
22
|
const tenantId = data?.tenantId as string
|
|
22
23
|
const organizationId = data?.organizationId as string | undefined
|
|
23
24
|
if (!userId || !tenantId) return
|
|
@@ -25,8 +26,14 @@ export default async function handle(
|
|
|
25
26
|
const em = ctx.resolve<EntityManager>('em')
|
|
26
27
|
|
|
27
28
|
try {
|
|
28
|
-
const user = await findOneWithDecryption(em, CustomerUser, {
|
|
29
|
+
const user = await findOneWithDecryption(em, CustomerUser, {
|
|
30
|
+
id: userId,
|
|
31
|
+
tenantId,
|
|
32
|
+
...(organizationId ? { organizationId } : {}),
|
|
33
|
+
deletedAt: null,
|
|
34
|
+
}, undefined, { tenantId, organizationId })
|
|
29
35
|
if (!user) return
|
|
36
|
+
if (!user.emailVerifiedAt || !user.isActive) return
|
|
30
37
|
|
|
31
38
|
const { CustomerEntity } = await import('@open-mercato/core/modules/customers/data/entities')
|
|
32
39
|
|
|
@@ -36,95 +43,56 @@ export default async function handle(
|
|
|
36
43
|
// widen the user's portal access instead of repairing it.
|
|
37
44
|
const ownScope = { tenantId, organizationId: user.organizationId }
|
|
38
45
|
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
// could poison it with a person entity id, which then breaks every later user
|
|
43
|
-
// edit ("Company not found"). If the linked entity is a person (not a company)
|
|
44
|
-
// or sits outside the user's org, drop it — or recover the person's real company
|
|
45
|
-
// from their profile. Correct company links are left untouched. Rows created
|
|
46
|
-
// before this change keep their bad FK; see #4473 for the backfill.
|
|
47
|
-
if (user.customerEntityId) {
|
|
46
|
+
let personEntityId = user.personEntityId ?? null
|
|
47
|
+
let customerEntityId = user.customerEntityId ?? null
|
|
48
|
+
if (customerEntityId) {
|
|
48
49
|
const linked = await findOneWithDecryption(
|
|
49
50
|
em,
|
|
50
51
|
CustomerEntity,
|
|
51
|
-
{ id:
|
|
52
|
+
{ id: customerEntityId, ...ownScope, deletedAt: null },
|
|
52
53
|
undefined,
|
|
53
|
-
|
|
54
|
-
)
|
|
55
|
-
if (!linked)
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
await em.nativeUpdate(
|
|
59
|
-
CustomerUser,
|
|
60
|
-
{ id: userId, tenantId, organizationId: user.organizationId },
|
|
61
|
-
{ customerEntityId: null },
|
|
62
|
-
)
|
|
63
|
-
user.customerEntityId = null
|
|
64
|
-
} else if (linked.kind === 'person') {
|
|
65
|
-
// Only adopt a recovered company that is itself in the user's org.
|
|
66
|
-
const replacement = await resolveOwnedCompanyForPerson(em, user.customerEntityId, ownScope)
|
|
67
|
-
await em.nativeUpdate(
|
|
68
|
-
CustomerUser,
|
|
69
|
-
{ id: userId, tenantId, organizationId: user.organizationId },
|
|
70
|
-
{ customerEntityId: replacement },
|
|
71
|
-
)
|
|
72
|
-
user.customerEntityId = replacement
|
|
54
|
+
ownScope,
|
|
55
|
+
)
|
|
56
|
+
if (!linked) customerEntityId = null
|
|
57
|
+
else if (linked.kind === 'person') {
|
|
58
|
+
customerEntityId = await resolveOwnedCompanyForPerson(em, linked.id, ownScope)
|
|
73
59
|
}
|
|
74
60
|
}
|
|
75
61
|
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
await em.nativeUpdate(
|
|
86
|
-
CustomerUser,
|
|
87
|
-
{ id: userId, tenantId, organizationId: user.organizationId },
|
|
88
|
-
{ customerEntityId: recovered },
|
|
62
|
+
if (!personEntityId) {
|
|
63
|
+
const email = user.email?.toLowerCase().trim()
|
|
64
|
+
if (email) {
|
|
65
|
+
const personEntities = await findWithDecryption(
|
|
66
|
+
em,
|
|
67
|
+
CustomerEntity,
|
|
68
|
+
{ ...ownScope, kind: 'person', deletedAt: null },
|
|
69
|
+
{ limit: 500 },
|
|
70
|
+
ownScope,
|
|
89
71
|
)
|
|
72
|
+
personEntityId = personEntities.find((person) => person.primaryEmail?.toLowerCase().trim() === email)?.id ?? null
|
|
90
73
|
}
|
|
91
|
-
return
|
|
92
74
|
}
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
if (!email) return
|
|
96
|
-
|
|
97
|
-
// Scope the candidate lookup to the user's own org. The fifth argument is a
|
|
98
|
-
// decryption scope, not a filter, so without organizationId in the `where`
|
|
99
|
-
// this matches people across every org in the tenant and writes a cross-org
|
|
100
|
-
// link that the normalization block above just cleared.
|
|
101
|
-
const personEntities = await findWithDecryption(
|
|
102
|
-
em,
|
|
103
|
-
CustomerEntity,
|
|
104
|
-
{ tenantId, organizationId: user.organizationId, kind: 'person', deletedAt: null } as any,
|
|
105
|
-
{ limit: 500 } as any,
|
|
106
|
-
{ tenantId, organizationId },
|
|
107
|
-
)
|
|
108
|
-
|
|
109
|
-
const matchingEntity = personEntities.find(
|
|
110
|
-
(e: any) => e.primaryEmail && e.primaryEmail.toLowerCase().trim() === email,
|
|
111
|
-
) as any
|
|
112
|
-
|
|
113
|
-
if (!matchingEntity) return
|
|
114
|
-
|
|
115
|
-
const companyEntityId = await resolveOwnedCompanyForPerson(em, matchingEntity.id, ownScope)
|
|
116
|
-
|
|
117
|
-
const updates: Record<string, unknown> = { personEntityId: matchingEntity.id }
|
|
118
|
-
if (companyEntityId) {
|
|
119
|
-
updates.customerEntityId = companyEntityId
|
|
75
|
+
if (personEntityId && !customerEntityId) {
|
|
76
|
+
customerEntityId = await resolveOwnedCompanyForPerson(em, personEntityId, ownScope)
|
|
120
77
|
}
|
|
121
78
|
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
79
|
+
const updates: Partial<CustomerUser> = {}
|
|
80
|
+
if (personEntityId !== (user.personEntityId ?? null)) updates.personEntityId = personEntityId
|
|
81
|
+
if (customerEntityId !== (user.customerEntityId ?? null)) updates.customerEntityId = customerEntityId
|
|
82
|
+
if (!Object.keys(updates).length) return
|
|
83
|
+
|
|
84
|
+
await em.nativeUpdate(CustomerUser, {
|
|
85
|
+
id: userId,
|
|
86
|
+
...ownScope,
|
|
87
|
+
emailHash: user.emailHash,
|
|
88
|
+
emailVerifiedAt: { $ne: null },
|
|
89
|
+
deletedAt: null,
|
|
90
|
+
isActive: true,
|
|
91
|
+
personEntityId: user.personEntityId ?? null,
|
|
92
|
+
customerEntityId: user.customerEntityId ?? null,
|
|
93
|
+
}, updates)
|
|
127
94
|
} catch (err) {
|
|
128
95
|
logger.error('Failed to link customer user to CRM person', { err })
|
|
96
|
+
getTelemetryRuntime()?.reportError(err, { module: 'customer_accounts', code: 'customer_accounts.crm_link_failed' })
|
|
129
97
|
}
|
|
130
98
|
}
|
|
@@ -72,11 +72,13 @@ export default async function handle(
|
|
|
72
72
|
emailHash: { $in: emailHashes },
|
|
73
73
|
...ownScope,
|
|
74
74
|
deletedAt: null,
|
|
75
|
+
emailVerifiedAt: { $ne: null },
|
|
76
|
+
isActive: true,
|
|
75
77
|
personEntityId: null,
|
|
76
78
|
}
|
|
77
79
|
const customerUser = await findOneWithDecryption(em, CustomerUser, userWhere, undefined, ownScope)
|
|
78
80
|
|
|
79
|
-
if (customerUser) {
|
|
81
|
+
if (customerUser?.emailVerifiedAt && customerUser.isActive) {
|
|
80
82
|
const updates: Partial<CustomerUser> = { personEntityId: entity.id, updatedAt: new Date() }
|
|
81
83
|
if (!customerUser.customerEntityId) {
|
|
82
84
|
const companyEntityId = await resolveOwnedCompanyForPerson(em, entity.id, ownScope)
|
|
@@ -1,10 +1,12 @@
|
|
|
1
1
|
import type { JobContext, QueuedJob, WorkerMeta } from '@open-mercato/queue'
|
|
2
2
|
import type { EntityManager } from '@mikro-orm/postgresql'
|
|
3
3
|
import {
|
|
4
|
+
CustomerUser,
|
|
4
5
|
CustomerUserEmailVerification,
|
|
5
6
|
CustomerUserPasswordReset,
|
|
6
7
|
CustomerUserInvitation,
|
|
7
8
|
} from '@open-mercato/core/modules/customer_accounts/data/entities'
|
|
9
|
+
import { pendingSignup, signupExpiryCutoff } from '../lib/pendingSignup'
|
|
8
10
|
|
|
9
11
|
export const metadata: WorkerMeta = {
|
|
10
12
|
queue: 'customer-accounts-cleanup-tokens',
|
|
@@ -20,6 +22,11 @@ export default async function handle(job: QueuedJob, ctx: HandlerContext): Promi
|
|
|
20
22
|
const em = ctx.resolve<EntityManager>('em')
|
|
21
23
|
const now = new Date()
|
|
22
24
|
|
|
25
|
+
await em.nativeUpdate(CustomerUser, {
|
|
26
|
+
...pendingSignup,
|
|
27
|
+
createdAt: { $lte: signupExpiryCutoff(now) },
|
|
28
|
+
}, { deletedAt: now, isActive: false, passwordHash: null, sessionsRevokedAt: now })
|
|
29
|
+
|
|
23
30
|
// Cleanup expired email verifications
|
|
24
31
|
await em.nativeDelete(CustomerUserEmailVerification, {
|
|
25
32
|
$or: [
|
|
@@ -476,10 +476,11 @@ async function setCompanyCustomFields(
|
|
|
476
476
|
profileId: string,
|
|
477
477
|
organizationId: string,
|
|
478
478
|
tenantId: string,
|
|
479
|
-
values: Record<string, unknown
|
|
479
|
+
values: Record<string, unknown>,
|
|
480
|
+
transactionalEm?: EntityManager,
|
|
480
481
|
) {
|
|
481
482
|
if (!values || !Object.keys(values).length) return
|
|
482
|
-
const em = (ctx.container.resolve('em') as EntityManager)
|
|
483
|
+
const em = transactionalEm ?? (ctx.container.resolve('em') as EntityManager)
|
|
483
484
|
const routing = await resolveCompanyCustomFieldRouting(em, tenantId, organizationId)
|
|
484
485
|
const entityScoped: Record<string, unknown> = {}
|
|
485
486
|
const profileScoped: Record<string, unknown> = {}
|
|
@@ -498,6 +499,7 @@ async function setCompanyCustomFields(
|
|
|
498
499
|
organizationId,
|
|
499
500
|
tenantId,
|
|
500
501
|
values: entityScoped,
|
|
502
|
+
transactionalEm,
|
|
501
503
|
notify: false,
|
|
502
504
|
})
|
|
503
505
|
}
|
|
@@ -509,6 +511,7 @@ async function setCompanyCustomFields(
|
|
|
509
511
|
organizationId,
|
|
510
512
|
tenantId,
|
|
511
513
|
values: profileScoped,
|
|
514
|
+
transactionalEm,
|
|
512
515
|
notify: false,
|
|
513
516
|
})
|
|
514
517
|
}
|
|
@@ -594,8 +597,8 @@ const createCompanyCommand: CommandHandler<CompanyCreateInput, { entityId: strin
|
|
|
594
597
|
em.persist(profile)
|
|
595
598
|
},
|
|
596
599
|
() => syncEntityTags(em, entity, parsed.tags),
|
|
600
|
+
() => setCompanyCustomFields(ctx, entity.id, profile.id, entity.organizationId, entity.tenantId, custom, em),
|
|
597
601
|
], { transaction: true })
|
|
598
|
-
await setCompanyCustomFields(ctx, entity.id, profile.id, entity.organizationId, entity.tenantId, custom)
|
|
599
602
|
|
|
600
603
|
const de = (ctx.container.resolve('dataEngine') as DataEngine)
|
|
601
604
|
await emitCrudSideEffects({
|
|
@@ -878,10 +881,9 @@ const updateCompanyCommand = {
|
|
|
878
881
|
}
|
|
879
882
|
},
|
|
880
883
|
() => syncEntityTags(em, record, parsed.tags, { ignoreMissing: ignoreMissingTags }),
|
|
884
|
+
() => setCompanyCustomFields(ctx, record.id, profile.id, record.organizationId, record.tenantId, custom, em),
|
|
881
885
|
], { transaction: true })
|
|
882
886
|
|
|
883
|
-
await setCompanyCustomFields(ctx, record.id, profile.id, record.organizationId, record.tenantId, custom)
|
|
884
|
-
|
|
885
887
|
const de = (ctx.container.resolve('dataEngine') as DataEngine)
|
|
886
888
|
await emitCrudSideEffects({
|
|
887
889
|
dataEngine: de,
|
|
@@ -602,6 +602,7 @@ const createDealCommand: CommandHandler<DealCreateInput, { dealId: string }> = {
|
|
|
602
602
|
let resolvedPipelineStageLabel: string | null = null
|
|
603
603
|
let stageDefaultProbability: number | null = null
|
|
604
604
|
const createdDictionaryKinds = new Set<string>()
|
|
605
|
+
const de = ctx.container.resolve<DataEngine>('dataEngine')
|
|
605
606
|
await withAtomicFlush(em, [
|
|
606
607
|
async () => {
|
|
607
608
|
stageSnapshot = parsed.pipelineStageId
|
|
@@ -667,20 +668,19 @@ const createDealCommand: CommandHandler<DealCreateInput, { dealId: string }> = {
|
|
|
667
668
|
},
|
|
668
669
|
() => syncDealPeople(em, deal, parsed.personIds ?? [], parsed.primaryPersonEntityId, { stampLockToken: false }),
|
|
669
670
|
() => syncDealCompanies(em, deal, parsed.companyIds ?? [], { stampLockToken: false }),
|
|
671
|
+
() => setCustomFieldsIfAny({
|
|
672
|
+
dataEngine: de,
|
|
673
|
+
transactionalEm: em,
|
|
674
|
+
entityId: DEAL_ENTITY_ID,
|
|
675
|
+
recordId: deal.id,
|
|
676
|
+
organizationId: deal.organizationId,
|
|
677
|
+
tenantId: deal.tenantId,
|
|
678
|
+
values: custom,
|
|
679
|
+
notify: false,
|
|
680
|
+
}),
|
|
670
681
|
], { transaction: true })
|
|
671
682
|
await invalidateDictionaryKindCaches(ctx, { tenantId: parsed.tenantId, organizationId: parsed.organizationId }, createdDictionaryKinds)
|
|
672
683
|
|
|
673
|
-
const de = (ctx.container.resolve('dataEngine') as DataEngine)
|
|
674
|
-
await setCustomFieldsIfAny({
|
|
675
|
-
dataEngine: de,
|
|
676
|
-
entityId: DEAL_ENTITY_ID,
|
|
677
|
-
recordId: deal.id,
|
|
678
|
-
organizationId: deal.organizationId,
|
|
679
|
-
tenantId: deal.tenantId,
|
|
680
|
-
values: custom,
|
|
681
|
-
notify: false,
|
|
682
|
-
})
|
|
683
|
-
|
|
684
684
|
await emitCrudSideEffects({
|
|
685
685
|
dataEngine: de,
|
|
686
686
|
action: 'created',
|
|
@@ -839,13 +839,14 @@ const updateDealCommand: CommandHandler<DealUpdateInput, { dealId: string }> = {
|
|
|
839
839
|
let requestedClosureOutcome: DealClosureOutcome | null = null
|
|
840
840
|
const createdDictionaryKinds = new Set<string>()
|
|
841
841
|
|
|
842
|
+
const de = ctx.container.resolve<DataEngine>('dataEngine')
|
|
842
843
|
await runCrudCommandWrite({
|
|
843
844
|
ctx,
|
|
845
|
+
dataEngine: de,
|
|
844
846
|
em,
|
|
845
847
|
entityId: DEAL_ENTITY_ID,
|
|
846
848
|
action: 'updated',
|
|
847
849
|
scope: { tenantId: record.tenantId, organizationId: record.organizationId },
|
|
848
|
-
customFields: custom,
|
|
849
850
|
events: dealCrudEvents,
|
|
850
851
|
indexer: dealCrudIndexer,
|
|
851
852
|
sideEffect: () => ({
|
|
@@ -995,6 +996,15 @@ const updateDealCommand: CommandHandler<DealUpdateInput, { dealId: string }> = {
|
|
|
995
996
|
},
|
|
996
997
|
() => syncDealPeople(em, record, parsed.personIds, parsed.primaryPersonEntityId),
|
|
997
998
|
() => syncDealCompanies(em, record, parsed.companyIds),
|
|
999
|
+
() => setCustomFieldsIfAny({
|
|
1000
|
+
dataEngine: de,
|
|
1001
|
+
transactionalEm: em,
|
|
1002
|
+
entityId: DEAL_ENTITY_ID,
|
|
1003
|
+
recordId: record.id,
|
|
1004
|
+
organizationId: record.organizationId,
|
|
1005
|
+
tenantId: record.tenantId,
|
|
1006
|
+
values: custom,
|
|
1007
|
+
}),
|
|
998
1008
|
],
|
|
999
1009
|
})
|
|
1000
1010
|
await invalidateDictionaryKindCaches(ctx, record, createdDictionaryKinds)
|
|
@@ -562,10 +562,11 @@ async function setCustomFieldsForPerson(
|
|
|
562
562
|
profileId: string,
|
|
563
563
|
organizationId: string,
|
|
564
564
|
tenantId: string,
|
|
565
|
-
values: Record<string, unknown
|
|
565
|
+
values: Record<string, unknown>,
|
|
566
|
+
transactionalEm?: EntityManager,
|
|
566
567
|
): Promise<void> {
|
|
567
568
|
if (!values || !Object.keys(values).length) return
|
|
568
|
-
const em = (ctx.container.resolve('em') as EntityManager)
|
|
569
|
+
const em = transactionalEm ?? (ctx.container.resolve('em') as EntityManager)
|
|
569
570
|
const routing = await resolvePersonCustomFieldRouting(em, tenantId, organizationId)
|
|
570
571
|
const entityScoped: Record<string, unknown> = {}
|
|
571
572
|
const profileScoped: Record<string, unknown> = {}
|
|
@@ -584,6 +585,7 @@ async function setCustomFieldsForPerson(
|
|
|
584
585
|
organizationId,
|
|
585
586
|
tenantId,
|
|
586
587
|
values: entityScoped,
|
|
588
|
+
transactionalEm,
|
|
587
589
|
notify: true,
|
|
588
590
|
})
|
|
589
591
|
}
|
|
@@ -595,6 +597,7 @@ async function setCustomFieldsForPerson(
|
|
|
595
597
|
organizationId,
|
|
596
598
|
tenantId,
|
|
597
599
|
values: profileScoped,
|
|
600
|
+
transactionalEm,
|
|
598
601
|
notify: true,
|
|
599
602
|
})
|
|
600
603
|
}
|
|
@@ -781,12 +784,12 @@ const createPersonCommand: CommandHandler<PersonCreateInput, { entityId: string;
|
|
|
781
784
|
},
|
|
782
785
|
() => syncLegacyPrimaryCompanyLink(em, entity, profile, parsed.companyEntityId ?? null),
|
|
783
786
|
() => syncEntityTags(em, entity, parsed.tags),
|
|
787
|
+
() => setCustomFieldsForPerson(ctx, entity.id, profile.id, entity.organizationId, entity.tenantId, custom, em),
|
|
784
788
|
], { transaction: true })
|
|
785
789
|
|
|
786
790
|
const tenantId = entity.tenantId
|
|
787
791
|
const organizationId = entity.organizationId
|
|
788
792
|
await invalidateDictionaryKindCaches(ctx, { tenantId, organizationId }, createdDictionaryKinds)
|
|
789
|
-
await setCustomFieldsForPerson(ctx, entity.id, profile.id, organizationId, tenantId, custom)
|
|
790
793
|
|
|
791
794
|
const de = (ctx.container.resolve('dataEngine') as DataEngine)
|
|
792
795
|
await emitCrudSideEffects({
|
|
@@ -1140,10 +1143,10 @@ const updatePersonCommand = {
|
|
|
1140
1143
|
}
|
|
1141
1144
|
},
|
|
1142
1145
|
() => syncEntityTags(em, record, parsed.tags, { ignoreMissing: ignoreMissingTags }),
|
|
1146
|
+
() => setCustomFieldsForPerson(ctx, record.id, profile.id, record.organizationId, record.tenantId, custom, em),
|
|
1143
1147
|
], { transaction: true })
|
|
1144
1148
|
|
|
1145
1149
|
await invalidateDictionaryKindCaches(ctx, record, createdDictionaryKinds)
|
|
1146
|
-
await setCustomFieldsForPerson(ctx, record.id, profile.id, record.organizationId, record.tenantId, custom)
|
|
1147
1150
|
|
|
1148
1151
|
const de = (ctx.container.resolve('dataEngine') as DataEngine)
|
|
1149
1152
|
await emitCrudSideEffects({
|
|
@@ -252,11 +252,17 @@ export async function setRecordCustomFields(
|
|
|
252
252
|
let cf = existingRows.find((row) => !row.deletedAt
|
|
253
253
|
&& (row.organizationId ?? null) === organizationId
|
|
254
254
|
&& (row.tenantId ?? null) === tenantId) ?? null
|
|
255
|
+
const currentValue = collapseToSingle && raw.some((candidate) => candidate != null) && cf
|
|
256
|
+
? await decryptCustomFieldValue(valueFromRow(cf), tenantId, encrypted ? getEncryptionService() : null, encryptionCache, {
|
|
257
|
+
kind: def?.kind ?? null,
|
|
258
|
+
writeContext: encrypted ? { entityId, fieldKey } : undefined,
|
|
259
|
+
})
|
|
260
|
+
: undefined
|
|
255
261
|
const value: Primitive = collapseToSingle
|
|
256
|
-
? pickSingleValue(raw as Primitive[],
|
|
262
|
+
? pickSingleValue(raw as Primitive[], currentValue)
|
|
257
263
|
: raw as Primitive
|
|
258
264
|
const column: keyof CustomFieldValue = encrypted ? 'valueText' : def ? columnFromKind(def.kind) : columnFromJsValue(value)
|
|
259
|
-
const storedValue = encrypted
|
|
265
|
+
const storedValue = encrypted && value != null
|
|
260
266
|
? await encryptCustomFieldValue(value, tenantId, getEncryptionService(), encryptionCache, { entityId, fieldKey })
|
|
261
267
|
: value
|
|
262
268
|
const staleIds = existingRows.filter((row) => row !== cf).map((row) => row.id)
|