@open-mercato/core 0.11.1-develop.8538.1.78ea48b6e6 → 0.11.1-develop.8545.1.dd603570fd

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/dist/modules/customer_accounts/api/admin/users/[id].js +10 -9
  3. package/dist/modules/customer_accounts/api/admin/users/[id].js.map +2 -2
  4. package/dist/modules/customer_accounts/api/portal/notifications/[id]/dismiss.js +3 -2
  5. package/dist/modules/customer_accounts/api/portal/notifications/[id]/dismiss.js.map +2 -2
  6. package/dist/modules/customer_accounts/api/portal/notifications/[id]/read.js +3 -2
  7. package/dist/modules/customer_accounts/api/portal/notifications/[id]/read.js.map +2 -2
  8. package/dist/modules/customer_accounts/api/portal/notifications/mark-all-read.js +4 -0
  9. package/dist/modules/customer_accounts/api/portal/notifications/mark-all-read.js.map +2 -2
  10. package/dist/modules/customer_accounts/api/portal/notifications/unread-count.js +4 -0
  11. package/dist/modules/customer_accounts/api/portal/notifications/unread-count.js.map +2 -2
  12. package/dist/modules/customer_accounts/api/portal/notifications.js +4 -0
  13. package/dist/modules/customer_accounts/api/portal/notifications.js.map +2 -2
  14. package/dist/modules/customer_accounts/lib/customerEntityOwnership.js +12 -1
  15. package/dist/modules/customer_accounts/lib/customerEntityOwnership.js.map +2 -2
  16. package/dist/modules/customer_accounts/lib/moduleEntityRegistration.js +8 -0
  17. package/dist/modules/customer_accounts/lib/moduleEntityRegistration.js.map +7 -0
  18. package/dist/modules/customer_accounts/lib/portalNotificationsAvailability.js +9 -0
  19. package/dist/modules/customer_accounts/lib/portalNotificationsAvailability.js.map +7 -0
  20. package/dist/modules/directory/utils/organizationScope.js +3 -2
  21. package/dist/modules/directory/utils/organizationScope.js.map +2 -2
  22. package/dist/modules/entities/api/records.js +4 -3
  23. package/dist/modules/entities/api/records.js.map +2 -2
  24. package/dist/modules/entities/backend/entities/user/[entityId]/records/page.js +22 -38
  25. package/dist/modules/entities/backend/entities/user/[entityId]/records/page.js.map +2 -2
  26. package/dist/modules/progress/api/active/route.js +11 -3
  27. package/dist/modules/progress/api/active/route.js.map +2 -2
  28. package/dist/modules/progress/api/jobPermissions.js +42 -0
  29. package/dist/modules/progress/api/jobPermissions.js.map +7 -0
  30. package/dist/modules/progress/api/jobs/[id]/route.js +6 -11
  31. package/dist/modules/progress/api/jobs/[id]/route.js.map +2 -2
  32. package/dist/modules/wms/index.js +1 -1
  33. package/dist/modules/wms/index.js.map +2 -2
  34. package/dist/modules/wms/setup.js +4 -1
  35. package/dist/modules/wms/setup.js.map +2 -2
  36. package/dist/modules/workflows/api/events/route.js +1 -1
  37. package/dist/modules/workflows/api/events/route.js.map +2 -2
  38. package/dist/modules/workflows/api/instances/[id]/events/route.js +1 -1
  39. package/dist/modules/workflows/api/instances/[id]/events/route.js.map +2 -2
  40. package/dist/modules/workflows/api/instances/[id]/steps/route.js +1 -1
  41. package/dist/modules/workflows/api/instances/[id]/steps/route.js.map +2 -2
  42. package/dist/modules/workflows/api/instances/failure-queue/route.js +1 -1
  43. package/dist/modules/workflows/api/instances/failure-queue/route.js.map +2 -2
  44. package/dist/modules/workflows/lib/event-logger.js +1 -1
  45. package/dist/modules/workflows/lib/event-logger.js.map +2 -2
  46. package/dist/modules/workflows/lib/work-inbox/user-task-source.js +1 -1
  47. package/dist/modules/workflows/lib/work-inbox/user-task-source.js.map +2 -2
  48. package/package.json +7 -7
  49. package/src/modules/customer_accounts/api/admin/users/[id].ts +10 -9
  50. package/src/modules/customer_accounts/api/portal/notifications/[id]/dismiss.ts +8 -5
  51. package/src/modules/customer_accounts/api/portal/notifications/[id]/read.ts +8 -5
  52. package/src/modules/customer_accounts/api/portal/notifications/mark-all-read.ts +4 -0
  53. package/src/modules/customer_accounts/api/portal/notifications/unread-count.ts +4 -0
  54. package/src/modules/customer_accounts/api/portal/notifications.ts +4 -0
  55. package/src/modules/customer_accounts/lib/customerEntityOwnership.ts +13 -1
  56. package/src/modules/customer_accounts/lib/moduleEntityRegistration.ts +12 -0
  57. package/src/modules/customer_accounts/lib/portalNotificationsAvailability.ts +7 -0
  58. package/src/modules/directory/utils/organizationScope.ts +3 -2
  59. package/src/modules/entities/api/records.ts +4 -3
  60. package/src/modules/entities/backend/entities/user/[entityId]/records/page.tsx +25 -31
  61. package/src/modules/entities/i18n/de.json +20 -1
  62. package/src/modules/entities/i18n/en.json +20 -1
  63. package/src/modules/entities/i18n/es.json +20 -1
  64. package/src/modules/entities/i18n/ko.json +20 -1
  65. package/src/modules/entities/i18n/pl.json +20 -1
  66. package/src/modules/progress/api/active/route.ts +18 -3
  67. package/src/modules/progress/api/jobPermissions.ts +50 -0
  68. package/src/modules/progress/api/jobs/[id]/route.ts +7 -20
  69. package/src/modules/wms/index.ts +1 -1
  70. package/src/modules/wms/setup.ts +4 -1
  71. package/src/modules/workflows/api/events/route.ts +1 -1
  72. package/src/modules/workflows/api/instances/[id]/events/route.ts +1 -1
  73. package/src/modules/workflows/api/instances/[id]/steps/route.ts +3 -2
  74. package/src/modules/workflows/api/instances/failure-queue/route.ts +1 -1
  75. package/src/modules/workflows/lib/event-logger.ts +1 -1
  76. package/src/modules/workflows/lib/work-inbox/user-task-source.ts +3 -2
@@ -1,4 +1,4 @@
1
- [build:core] found 6667 entry points
1
+ [build:core] found 6673 entry points
2
2
  [build:core] built successfully
3
3
  [build:core:generated] found 276 entry points
4
4
  [build:core:generated] built successfully
@@ -6,7 +6,7 @@ import { CustomerUser, CustomerUserRole, CustomerRole, CustomerUserSession } fro
6
6
  import { adminUpdateUserSchema } from "@open-mercato/core/modules/customer_accounts/data/validators";
7
7
  import { emitCustomerAccountsEvent } from "@open-mercato/core/modules/customer_accounts/events";
8
8
  import { findOneWithDecryption, findWithDecryption } from "@open-mercato/shared/lib/encryption/find";
9
- import { isOwnedCompanyEntity, isOwnedPersonEntity } from "@open-mercato/core/modules/customer_accounts/lib/customerEntityOwnership";
9
+ import { isCustomerEntityRegistered, isOwnedCompanyEntity, isOwnedPersonEntity } from "@open-mercato/core/modules/customer_accounts/lib/customerEntityOwnership";
10
10
  import { enforceCommandOptimisticLockWithGuards } from "@open-mercato/shared/lib/crud/optimistic-lock-command";
11
11
  import { isCrudHttpError } from "@open-mercato/shared/lib/crud/errors";
12
12
  const metadata = {};
@@ -127,21 +127,22 @@ async function PUT(req, { params }) {
127
127
  if (isCrudHttpError(err)) return NextResponse.json(err.body, { status: err.status });
128
128
  throw err;
129
129
  }
130
- if (parsed.data.customerEntityId) {
131
- const owned = await isOwnedCompanyEntity(em, parsed.data.customerEntityId, {
130
+ const { customerEntityId, personEntityId } = parsed.data;
131
+ if (customerEntityId) {
132
+ const owned = await isOwnedCompanyEntity(em, customerEntityId, {
132
133
  tenantId: auth.tenantId,
133
134
  organizationId: auth.orgId
134
135
  });
135
- if (!owned) {
136
+ if (!owned && (customerEntityId !== user.customerEntityId || await isCustomerEntityRegistered(em))) {
136
137
  return NextResponse.json({ ok: false, error: "Company not found" }, { status: 400 });
137
138
  }
138
139
  }
139
- if (parsed.data.personEntityId) {
140
- const owned = await isOwnedPersonEntity(em, parsed.data.personEntityId, {
140
+ if (personEntityId) {
141
+ const owned = await isOwnedPersonEntity(em, personEntityId, {
141
142
  tenantId: auth.tenantId,
142
143
  organizationId: auth.orgId
143
144
  });
144
- if (!owned) {
145
+ if (!owned && (personEntityId !== user.personEntityId || await isCustomerEntityRegistered(em))) {
145
146
  return NextResponse.json({ ok: false, error: "Person not found" }, { status: 400 });
146
147
  }
147
148
  }
@@ -153,8 +154,8 @@ async function PUT(req, { params }) {
153
154
  const updates = { updatedAt: nextUpdatedAt };
154
155
  if (parsed.data.isActive !== void 0) updates.isActive = parsed.data.isActive;
155
156
  if (parsed.data.lockedUntil !== void 0) updates.lockedUntil = parsed.data.lockedUntil ? new Date(parsed.data.lockedUntil) : null;
156
- if (parsed.data.personEntityId !== void 0) updates.personEntityId = parsed.data.personEntityId;
157
- if (parsed.data.customerEntityId !== void 0) updates.customerEntityId = parsed.data.customerEntityId;
157
+ if (personEntityId !== void 0 && personEntityId !== user.personEntityId) updates.personEntityId = personEntityId;
158
+ if (customerEntityId !== void 0 && customerEntityId !== user.customerEntityId) updates.customerEntityId = customerEntityId;
158
159
  await em.nativeUpdate(CustomerUser, {
159
160
  id: user.id,
160
161
  tenantId: user.tenantId,
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../../src/modules/customer_accounts/api/admin/users/%5Bid%5D.ts"],
4
- "sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport type { OpenApiRouteDoc, OpenApiMethodDoc } from '@open-mercato/shared/lib/openapi'\nimport { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { RbacService } from '@open-mercato/core/modules/auth/services/rbacService'\nimport { CustomerUser, CustomerUserRole, CustomerRole, CustomerUserSession } from '@open-mercato/core/modules/customer_accounts/data/entities'\nimport { CustomerUserService } from '@open-mercato/core/modules/customer_accounts/services/customerUserService'\nimport { CustomerSessionService } from '@open-mercato/core/modules/customer_accounts/services/customerSessionService'\nimport { CustomerRbacService } from '@open-mercato/core/modules/customer_accounts/services/customerRbacService'\nimport { adminUpdateUserSchema } from '@open-mercato/core/modules/customer_accounts/data/validators'\nimport { emitCustomerAccountsEvent } from '@open-mercato/core/modules/customer_accounts/events'\nimport { findOneWithDecryption, findWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { isOwnedCompanyEntity, isOwnedPersonEntity } from '@open-mercato/core/modules/customer_accounts/lib/customerEntityOwnership'\nimport { enforceCommandOptimisticLockWithGuards } from '@open-mercato/shared/lib/crud/optimistic-lock-command'\nimport { isCrudHttpError } from '@open-mercato/shared/lib/crud/errors'\n\nexport const metadata = {}\n\nconst UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i\n\nexport async function GET(req: Request, { params }: { params: { id: string } }) {\n if (!UUID_RE.test(params.id)) {\n return NextResponse.json({ ok: false, error: 'Invalid user ID' }, { status: 400 })\n }\n\n const auth = await getAuthFromRequest(req)\n if (!auth) {\n return NextResponse.json({ ok: false, error: 'Authentication required' }, { status: 401 })\n }\n\n const container = await createRequestContainer()\n const rbacService = container.resolve('rbacService') as RbacService\n const hasAccess = await rbacService.userHasAllFeatures(auth.sub, ['customer_accounts.view'], { tenantId: auth.tenantId, organizationId: auth.orgId })\n if (!hasAccess) {\n return NextResponse.json({ ok: false, error: 'Insufficient permissions' }, { status: 403 })\n }\n\n const em = container.resolve('em') as import('@mikro-orm/postgresql').EntityManager\n\n const user = await findOneWithDecryption(\n em,\n CustomerUser,\n { id: params.id, tenantId: auth.tenantId, organizationId: auth.orgId, deletedAt: null } as any,\n undefined,\n { tenantId: auth.tenantId, organizationId: auth.orgId },\n )\n if (!user) {\n return NextResponse.json({ ok: false, error: 'User not found' }, { status: 404 })\n }\n\n const userRoles = await findWithDecryption(\n em,\n CustomerUserRole,\n { user: user.id as any, deletedAt: null } as any,\n { populate: ['role'] },\n { tenantId: auth.tenantId, organizationId: auth.orgId },\n )\n const roles = userRoles.map((ur) => ({\n id: (ur.role as any).id,\n name: (ur.role as any).name,\n slug: (ur.role as any).slug,\n }))\n\n const activeSessions = await findWithDecryption(\n em,\n CustomerUserSession,\n {\n user: user.id as any,\n deletedAt: null,\n expiresAt: { $gt: new Date() },\n } as any,\n { orderBy: { lastUsedAt: 'DESC' } },\n { tenantId: auth.tenantId, organizationId: auth.orgId },\n )\n\n const sessions = activeSessions.map((session) => ({\n id: session.id,\n ipAddress: (session as any).ipAddress || null,\n userAgent: (session as any).userAgent || null,\n lastUsedAt: (session as any).lastUsedAt || null,\n createdAt: session.createdAt,\n expiresAt: session.expiresAt,\n }))\n\n return NextResponse.json({\n ok: true,\n id: user.id,\n email: user.email,\n displayName: user.displayName,\n emailVerifiedAt: user.emailVerifiedAt || null,\n isActive: user.isActive,\n lockedUntil: user.lockedUntil || null,\n lastLoginAt: user.lastLoginAt || null,\n customerEntityId: user.customerEntityId || null,\n personEntityId: user.personEntityId || null,\n createdAt: user.createdAt,\n updatedAt: user.updatedAt || null,\n roles,\n sessions,\n })\n}\n\nexport async function PUT(req: Request, { params }: { params: { id: string } }) {\n const auth = await getAuthFromRequest(req)\n if (!auth) {\n return NextResponse.json({ ok: false, error: 'Authentication required' }, { status: 401 })\n }\n\n const container = await createRequestContainer()\n const rbacService = container.resolve('rbacService') as RbacService\n const hasAccess = await rbacService.userHasAllFeatures(auth.sub, ['customer_accounts.manage'], { tenantId: auth.tenantId, organizationId: auth.orgId })\n if (!hasAccess) {\n return NextResponse.json({ ok: false, error: 'Insufficient permissions' }, { status: 403 })\n }\n\n let body: unknown\n try {\n body = await req.json()\n } catch {\n return NextResponse.json({ ok: false, error: 'Invalid request body' }, { status: 400 })\n }\n\n const parsed = adminUpdateUserSchema.safeParse(body)\n if (!parsed.success) {\n return NextResponse.json({ ok: false, error: 'Validation failed', details: parsed.error.flatten().fieldErrors }, { status: 400 })\n }\n\n const em = container.resolve('em') as import('@mikro-orm/postgresql').EntityManager\n\n const user = await findOneWithDecryption(\n em,\n CustomerUser,\n { id: params.id, tenantId: auth.tenantId, organizationId: auth.orgId, deletedAt: null } as any,\n undefined,\n { tenantId: auth.tenantId, organizationId: auth.orgId },\n )\n if (!user) {\n return NextResponse.json({ ok: false, error: 'User not found' }, { status: 404 })\n }\n\n // Optimistic lock: refuse a stale overwrite so two admins editing the same\n // customer user in parallel cannot silently clobber each other (#2055). The\n // check is strictly additive \u2014 a no-op when the client sends no expected-version header.\n try {\n await enforceCommandOptimisticLockWithGuards(container, {\n resourceKind: 'customer_accounts.user',\n resourceId: user.id,\n current: user.updatedAt ?? null,\n request: req,\n })\n } catch (err) {\n if (isCrudHttpError(err)) return NextResponse.json(err.body, { status: err.status })\n throw err\n }\n\n // Reject a customerEntityId the caller does not own before persisting it.\n // Without this check a mislinked company FK cross-links the user into another\n // org/company's portal context and persists indefinitely (#2693). A null value\n // (unlink) needs no ownership check.\n if (parsed.data.customerEntityId) {\n const owned = await isOwnedCompanyEntity(em, parsed.data.customerEntityId, {\n tenantId: auth.tenantId,\n organizationId: auth.orgId,\n })\n if (!owned) {\n return NextResponse.json({ ok: false, error: 'Company not found' }, { status: 400 })\n }\n }\n\n // Same guard for the person FK. Without it the invite-side check is trivially\n // bypassable: create the user normally, then PUT an unowned personEntityId.\n // It persists (autoLinkCrm short-circuits on any non-null value) and leaks\n // account status into the other org's people list via the account-status\n // enricher. A null value (unlink) needs no ownership check.\n if (parsed.data.personEntityId) {\n const owned = await isOwnedPersonEntity(em, parsed.data.personEntityId, {\n tenantId: auth.tenantId,\n organizationId: auth.orgId,\n })\n if (!owned) {\n return NextResponse.json({ ok: false, error: 'Person not found' }, { status: 400 })\n }\n }\n\n // `display_name` is encrypted at rest, and `nativeUpdate` skips the flush hooks the\n // tenant-encryption subscriber relies on, so persisting it below would write plaintext PII\n // into a ciphertext column (#3837). Route it through the service, which writes it via the\n // managed entity. Runs before the `nativeUpdate` so the explicit `updated_at` below stays\n // the value this response reports back as the optimistic-lock version.\n if (parsed.data.displayName !== undefined) {\n const customerUserService = container.resolve('customerUserService') as CustomerUserService\n await customerUserService.updateProfile(user, { displayName: parsed.data.displayName })\n }\n\n // Always bump updated_at so the optimistic-lock version advances on every save.\n // `nativeUpdate` bypasses MikroORM's `onUpdate` hook, so set it explicitly \u2014 without\n // this the version never changes and concurrent edits cannot be detected (#2055).\n const nextUpdatedAt = new Date()\n const updates: Record<string, unknown> = { updatedAt: nextUpdatedAt }\n if (parsed.data.isActive !== undefined) updates.isActive = parsed.data.isActive\n if (parsed.data.lockedUntil !== undefined) updates.lockedUntil = parsed.data.lockedUntil ? new Date(parsed.data.lockedUntil) : null\n if (parsed.data.personEntityId !== undefined) updates.personEntityId = parsed.data.personEntityId\n if (parsed.data.customerEntityId !== undefined) updates.customerEntityId = parsed.data.customerEntityId\n\n await em.nativeUpdate(CustomerUser, {\n id: user.id,\n tenantId: user.tenantId,\n organizationId: user.organizationId,\n }, updates)\n\n let rolesChanged = false\n if (parsed.data.roleIds !== undefined) {\n const requestedRoleIds = parsed.data.roleIds\n // Scope role resolution to the caller's organization too \u2014 CustomerRole is\n // org-scoped, so a tenant-only filter would let an admin link roles from\n // another org in the same tenant (#2693).\n const validRoles = requestedRoleIds.length > 0\n ? await findWithDecryption(\n em,\n CustomerRole,\n {\n id: { $in: requestedRoleIds } as any,\n tenantId: auth.tenantId,\n organizationId: auth.orgId,\n deletedAt: null,\n } as any,\n undefined,\n { tenantId: auth.tenantId, organizationId: auth.orgId },\n )\n : []\n if (validRoles.length !== requestedRoleIds.length) {\n const foundIds = new Set(validRoles.map((role) => role.id))\n const missingId = requestedRoleIds.find((roleId) => !foundIds.has(roleId))\n return NextResponse.json({ ok: false, error: `Role ${missingId} not found` }, { status: 400 })\n }\n\n await em.nativeDelete(CustomerUserRole, { user: user.id } as Record<string, unknown>)\n\n for (const role of validRoles) {\n const userRole = em.create(CustomerUserRole, {\n user,\n role,\n createdAt: new Date(),\n } as any)\n em.persist(userRole)\n }\n await em.flush()\n rolesChanged = true\n }\n\n if (rolesChanged) {\n const customerRbacService = container.resolve('customerRbacService') as CustomerRbacService\n await customerRbacService.invalidateUserCache(user.id)\n }\n\n void emitCustomerAccountsEvent('customer_accounts.user.updated', {\n id: user.id,\n recipientUserId: user.id,\n email: user.email,\n tenantId: user.tenantId,\n organizationId: user.organizationId,\n updatedBy: auth.sub,\n }).catch(() => undefined)\n\n return NextResponse.json({ ok: true, updatedAt: nextUpdatedAt.toISOString() })\n}\n\nexport async function DELETE(req: Request, { params }: { params: { id: string } }) {\n const auth = await getAuthFromRequest(req)\n if (!auth) {\n return NextResponse.json({ ok: false, error: 'Authentication required' }, { status: 401 })\n }\n\n const container = await createRequestContainer()\n const rbacService = container.resolve('rbacService') as RbacService\n const hasAccess = await rbacService.userHasAllFeatures(auth.sub, ['customer_accounts.manage'], { tenantId: auth.tenantId, organizationId: auth.orgId })\n if (!hasAccess) {\n return NextResponse.json({ ok: false, error: 'Insufficient permissions' }, { status: 403 })\n }\n\n const em = container.resolve('em') as import('@mikro-orm/postgresql').EntityManager\n\n const user = await findOneWithDecryption(\n em,\n CustomerUser,\n { id: params.id, tenantId: auth.tenantId, organizationId: auth.orgId, deletedAt: null } as any,\n undefined,\n { tenantId: auth.tenantId, organizationId: auth.orgId },\n )\n if (!user) {\n return NextResponse.json({ ok: false, error: 'User not found' }, { status: 404 })\n }\n\n // Optimistic lock: refuse a stale delete (e.g. deleting a record another admin\n // already modified). Strictly additive \u2014 a no-op without the expected-version header.\n try {\n await enforceCommandOptimisticLockWithGuards(container, {\n resourceKind: 'customer_accounts.user',\n resourceId: user.id,\n current: user.updatedAt ?? null,\n request: req,\n })\n } catch (err) {\n if (isCrudHttpError(err)) return NextResponse.json(err.body, { status: err.status })\n throw err\n }\n\n const customerUserService = container.resolve('customerUserService') as CustomerUserService\n const customerSessionService = container.resolve('customerSessionService') as CustomerSessionService\n\n await customerUserService.softDelete(user.id, {\n tenantId: user.tenantId,\n organizationId: user.organizationId,\n })\n await customerSessionService.revokeAllUserSessions(user.id)\n\n void emitCustomerAccountsEvent('customer_accounts.user.deleted', {\n id: user.id,\n email: user.email,\n tenantId: user.tenantId,\n organizationId: user.organizationId,\n deletedBy: auth.sub,\n }).catch(() => undefined)\n\n return NextResponse.json({ ok: true })\n}\n\nconst roleSchema = z.object({ id: z.string().uuid(), name: z.string(), slug: z.string() })\nconst userDetailSchema = z.object({\n id: z.string().uuid(),\n email: z.string(),\n displayName: z.string(),\n emailVerified: z.boolean(),\n isActive: z.boolean(),\n lockedUntil: z.string().datetime().nullable(),\n lastLoginAt: z.string().datetime().nullable(),\n failedLoginAttempts: z.number(),\n customerEntityId: z.string().uuid().nullable(),\n personEntityId: z.string().uuid().nullable(),\n createdAt: z.string().datetime(),\n updatedAt: z.string().datetime().nullable(),\n roles: z.array(roleSchema),\n activeSessionCount: z.number(),\n})\n\nconst successSchema = z.object({ ok: z.literal(true) })\nconst errorSchema = z.object({ ok: z.literal(false), error: z.string() })\n\nconst getMethodDoc: OpenApiMethodDoc = {\n summary: 'Get customer user detail (admin)',\n description: 'Returns full customer user details including CRM links, roles, and active session count.',\n tags: ['Customer Accounts Admin'],\n responses: [{\n status: 200,\n description: 'User detail',\n schema: z.object({ ok: z.literal(true), user: userDetailSchema }),\n }],\n errors: [\n { status: 401, description: 'Not authenticated', schema: errorSchema },\n { status: 403, description: 'Insufficient permissions', schema: errorSchema },\n { status: 404, description: 'User not found', schema: errorSchema },\n ],\n}\n\nconst putMethodDoc: OpenApiMethodDoc = {\n summary: 'Update customer user (admin)',\n description: 'Updates a customer user. Staff can update status, lock, CRM links, and roles. Role assignment bypasses customer_assignable check.',\n tags: ['Customer Accounts Admin'],\n requestBody: { schema: adminUpdateUserSchema },\n responses: [{ status: 200, description: 'User updated', schema: successSchema }],\n errors: [\n { status: 400, description: 'Validation failed or role not found', schema: errorSchema },\n { status: 401, description: 'Not authenticated', schema: errorSchema },\n { status: 403, description: 'Insufficient permissions', schema: errorSchema },\n { status: 404, description: 'User not found', schema: errorSchema },\n ],\n}\n\nconst deleteMethodDoc: OpenApiMethodDoc = {\n summary: 'Delete customer user (admin)',\n description: 'Soft deletes a customer user and revokes all their active sessions.',\n tags: ['Customer Accounts Admin'],\n responses: [{ status: 200, description: 'User deleted', schema: successSchema }],\n errors: [\n { status: 401, description: 'Not authenticated', schema: errorSchema },\n { status: 403, description: 'Insufficient permissions', schema: errorSchema },\n { status: 404, description: 'User not found', schema: errorSchema },\n ],\n}\n\nexport const openApi: OpenApiRouteDoc = {\n summary: 'Customer user detail management (admin)',\n pathParams: z.object({ id: z.string().uuid() }),\n methods: {\n GET: getMethodDoc,\n PUT: putMethodDoc,\n DELETE: deleteMethodDoc,\n },\n}\n"],
5
- "mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAElB,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A,EACT,aAAa;AAAA,EACb,MAAM,CAAC,yBAAyB;AAAA,EAChC,aAAa,EAAE,QAAQ,sBAAsB;AAAA,EAC7C,WAAW,CAAC,EAAE,QAAQ,KAAK,aAAa,gBAAgB,QAAQ,cAAc,CAAC;AAAA,EAC/E,QAAQ;AAAA,IACN,EAAE,QAAQ,KAAK,aAAa,uCAAuC,QAAQ,YAAY;AAAA,IACvF,EAAE,QAAQ,KAAK,aAAa,qBAAqB,QAAQ,YAAY;AAAA,IACrE,EAAE,QAAQ,KAAK,aAAa,4BAA4B,QAAQ,YAAY;AAAA,IAC5E,EAAE,QAAQ,KAAK,aAAa,kBAAkB,QAAQ,YAAY;AAAA,EACpE;AACF;AAEA,MAAM,kBAAoC;AAAA,EACxC,SAAS;AAAA,EACT,aAAa;AAAA,EACb,MAAM,CAAC,yBAAyB;AAAA,EAChC,WAAW,CAAC,EAAE,QAAQ,KAAK,aAAa,gBAAgB,QAAQ,cAAc,CAAC;AAAA,EAC/E,QAAQ;AAAA,IACN,EAAE,QAAQ,KAAK,aAAa,qBAAqB,QAAQ,YAAY;AAAA,IACrE,EAAE,QAAQ,KAAK,aAAa,4BAA4B,QAAQ,YAAY;AAAA,IAC5E,EAAE,QAAQ,KAAK,aAAa,kBAAkB,QAAQ,YAAY;AAAA,EACpE;AACF;AAEO,MAAM,UAA2B;AAAA,EACtC,SAAS;AAAA,EACT,YAAY,EAAE,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC;AAAA,EAC9C,SAAS;AAAA,IACP,KAAK;AAAA,IACL,KAAK;AAAA,IACL,QAAQ;AAAA,EACV;AACF;",
4
+ "sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport type { OpenApiRouteDoc, OpenApiMethodDoc } from '@open-mercato/shared/lib/openapi'\nimport { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { RbacService } from '@open-mercato/core/modules/auth/services/rbacService'\nimport { CustomerUser, CustomerUserRole, CustomerRole, CustomerUserSession } from '@open-mercato/core/modules/customer_accounts/data/entities'\nimport { CustomerUserService } from '@open-mercato/core/modules/customer_accounts/services/customerUserService'\nimport { CustomerSessionService } from '@open-mercato/core/modules/customer_accounts/services/customerSessionService'\nimport { CustomerRbacService } from '@open-mercato/core/modules/customer_accounts/services/customerRbacService'\nimport { adminUpdateUserSchema } from '@open-mercato/core/modules/customer_accounts/data/validators'\nimport { emitCustomerAccountsEvent } from '@open-mercato/core/modules/customer_accounts/events'\nimport { findOneWithDecryption, findWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { isCustomerEntityRegistered, isOwnedCompanyEntity, isOwnedPersonEntity } from '@open-mercato/core/modules/customer_accounts/lib/customerEntityOwnership'\nimport { enforceCommandOptimisticLockWithGuards } from '@open-mercato/shared/lib/crud/optimistic-lock-command'\nimport { isCrudHttpError } from '@open-mercato/shared/lib/crud/errors'\n\nexport const metadata = {}\n\nconst UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i\n\nexport async function GET(req: Request, { params }: { params: { id: string } }) {\n if (!UUID_RE.test(params.id)) {\n return NextResponse.json({ ok: false, error: 'Invalid user ID' }, { status: 400 })\n }\n\n const auth = await getAuthFromRequest(req)\n if (!auth) {\n return NextResponse.json({ ok: false, error: 'Authentication required' }, { status: 401 })\n }\n\n const container = await createRequestContainer()\n const rbacService = container.resolve('rbacService') as RbacService\n const hasAccess = await rbacService.userHasAllFeatures(auth.sub, ['customer_accounts.view'], { tenantId: auth.tenantId, organizationId: auth.orgId })\n if (!hasAccess) {\n return NextResponse.json({ ok: false, error: 'Insufficient permissions' }, { status: 403 })\n }\n\n const em = container.resolve('em') as import('@mikro-orm/postgresql').EntityManager\n\n const user = await findOneWithDecryption(\n em,\n CustomerUser,\n { id: params.id, tenantId: auth.tenantId, organizationId: auth.orgId, deletedAt: null } as any,\n undefined,\n { tenantId: auth.tenantId, organizationId: auth.orgId },\n )\n if (!user) {\n return NextResponse.json({ ok: false, error: 'User not found' }, { status: 404 })\n }\n\n const userRoles = await findWithDecryption(\n em,\n CustomerUserRole,\n { user: user.id as any, deletedAt: null } as any,\n { populate: ['role'] },\n { tenantId: auth.tenantId, organizationId: auth.orgId },\n )\n const roles = userRoles.map((ur) => ({\n id: (ur.role as any).id,\n name: (ur.role as any).name,\n slug: (ur.role as any).slug,\n }))\n\n const activeSessions = await findWithDecryption(\n em,\n CustomerUserSession,\n {\n user: user.id as any,\n deletedAt: null,\n expiresAt: { $gt: new Date() },\n } as any,\n { orderBy: { lastUsedAt: 'DESC' } },\n { tenantId: auth.tenantId, organizationId: auth.orgId },\n )\n\n const sessions = activeSessions.map((session) => ({\n id: session.id,\n ipAddress: (session as any).ipAddress || null,\n userAgent: (session as any).userAgent || null,\n lastUsedAt: (session as any).lastUsedAt || null,\n createdAt: session.createdAt,\n expiresAt: session.expiresAt,\n }))\n\n return NextResponse.json({\n ok: true,\n id: user.id,\n email: user.email,\n displayName: user.displayName,\n emailVerifiedAt: user.emailVerifiedAt || null,\n isActive: user.isActive,\n lockedUntil: user.lockedUntil || null,\n lastLoginAt: user.lastLoginAt || null,\n customerEntityId: user.customerEntityId || null,\n personEntityId: user.personEntityId || null,\n createdAt: user.createdAt,\n updatedAt: user.updatedAt || null,\n roles,\n sessions,\n })\n}\n\nexport async function PUT(req: Request, { params }: { params: { id: string } }) {\n const auth = await getAuthFromRequest(req)\n if (!auth) {\n return NextResponse.json({ ok: false, error: 'Authentication required' }, { status: 401 })\n }\n\n const container = await createRequestContainer()\n const rbacService = container.resolve('rbacService') as RbacService\n const hasAccess = await rbacService.userHasAllFeatures(auth.sub, ['customer_accounts.manage'], { tenantId: auth.tenantId, organizationId: auth.orgId })\n if (!hasAccess) {\n return NextResponse.json({ ok: false, error: 'Insufficient permissions' }, { status: 403 })\n }\n\n let body: unknown\n try {\n body = await req.json()\n } catch {\n return NextResponse.json({ ok: false, error: 'Invalid request body' }, { status: 400 })\n }\n\n const parsed = adminUpdateUserSchema.safeParse(body)\n if (!parsed.success) {\n return NextResponse.json({ ok: false, error: 'Validation failed', details: parsed.error.flatten().fieldErrors }, { status: 400 })\n }\n\n const em = container.resolve('em') as import('@mikro-orm/postgresql').EntityManager\n\n const user = await findOneWithDecryption(\n em,\n CustomerUser,\n { id: params.id, tenantId: auth.tenantId, organizationId: auth.orgId, deletedAt: null } as any,\n undefined,\n { tenantId: auth.tenantId, organizationId: auth.orgId },\n )\n if (!user) {\n return NextResponse.json({ ok: false, error: 'User not found' }, { status: 404 })\n }\n\n // Optimistic lock: refuse a stale overwrite so two admins editing the same\n // customer user in parallel cannot silently clobber each other (#2055). The\n // check is strictly additive \u2014 a no-op when the client sends no expected-version header.\n try {\n await enforceCommandOptimisticLockWithGuards(container, {\n resourceKind: 'customer_accounts.user',\n resourceId: user.id,\n current: user.updatedAt ?? null,\n request: req,\n })\n } catch (err) {\n if (isCrudHttpError(err)) return NextResponse.json(err.body, { status: err.status })\n throw err\n }\n\n // Reject a customerEntityId the caller does not own before persisting it.\n // Without this check a mislinked company FK cross-links the user into another\n // org/company's portal context and persists indefinitely (#2693). A null value\n // (unlink) needs no ownership check.\n const { customerEntityId, personEntityId } = parsed.data\n if (customerEntityId) {\n const owned = await isOwnedCompanyEntity(em, customerEntityId, {\n tenantId: auth.tenantId,\n organizationId: auth.orgId,\n })\n if (!owned && (customerEntityId !== user.customerEntityId || await isCustomerEntityRegistered(em))) {\n return NextResponse.json({ ok: false, error: 'Company not found' }, { status: 400 })\n }\n }\n\n // Same guard for the person FK. Without it the invite-side check is trivially\n // bypassable: create the user normally, then PUT an unowned personEntityId.\n // It persists (autoLinkCrm short-circuits on any non-null value) and leaks\n // account status into the other org's people list via the account-status\n // enricher. A null value (unlink) needs no ownership check.\n if (personEntityId) {\n const owned = await isOwnedPersonEntity(em, personEntityId, {\n tenantId: auth.tenantId,\n organizationId: auth.orgId,\n })\n if (!owned && (personEntityId !== user.personEntityId || await isCustomerEntityRegistered(em))) {\n return NextResponse.json({ ok: false, error: 'Person not found' }, { status: 400 })\n }\n }\n\n // `display_name` is encrypted at rest, and `nativeUpdate` skips the flush hooks the\n // tenant-encryption subscriber relies on, so persisting it below would write plaintext PII\n // into a ciphertext column (#3837). Route it through the service, which writes it via the\n // managed entity. Runs before the `nativeUpdate` so the explicit `updated_at` below stays\n // the value this response reports back as the optimistic-lock version.\n if (parsed.data.displayName !== undefined) {\n const customerUserService = container.resolve('customerUserService') as CustomerUserService\n await customerUserService.updateProfile(user, { displayName: parsed.data.displayName })\n }\n\n // Always bump updated_at so the optimistic-lock version advances on every save.\n // `nativeUpdate` bypasses MikroORM's `onUpdate` hook, so set it explicitly \u2014 without\n // this the version never changes and concurrent edits cannot be detected (#2055).\n const nextUpdatedAt = new Date()\n const updates: Record<string, unknown> = { updatedAt: nextUpdatedAt }\n if (parsed.data.isActive !== undefined) updates.isActive = parsed.data.isActive\n if (parsed.data.lockedUntil !== undefined) updates.lockedUntil = parsed.data.lockedUntil ? new Date(parsed.data.lockedUntil) : null\n if (personEntityId !== undefined && personEntityId !== user.personEntityId) updates.personEntityId = personEntityId\n if (customerEntityId !== undefined && customerEntityId !== user.customerEntityId) updates.customerEntityId = customerEntityId\n\n await em.nativeUpdate(CustomerUser, {\n id: user.id,\n tenantId: user.tenantId,\n organizationId: user.organizationId,\n }, updates)\n\n let rolesChanged = false\n if (parsed.data.roleIds !== undefined) {\n const requestedRoleIds = parsed.data.roleIds\n // Scope role resolution to the caller's organization too \u2014 CustomerRole is\n // org-scoped, so a tenant-only filter would let an admin link roles from\n // another org in the same tenant (#2693).\n const validRoles = requestedRoleIds.length > 0\n ? await findWithDecryption(\n em,\n CustomerRole,\n {\n id: { $in: requestedRoleIds } as any,\n tenantId: auth.tenantId,\n organizationId: auth.orgId,\n deletedAt: null,\n } as any,\n undefined,\n { tenantId: auth.tenantId, organizationId: auth.orgId },\n )\n : []\n if (validRoles.length !== requestedRoleIds.length) {\n const foundIds = new Set(validRoles.map((role) => role.id))\n const missingId = requestedRoleIds.find((roleId) => !foundIds.has(roleId))\n return NextResponse.json({ ok: false, error: `Role ${missingId} not found` }, { status: 400 })\n }\n\n await em.nativeDelete(CustomerUserRole, { user: user.id } as Record<string, unknown>)\n\n for (const role of validRoles) {\n const userRole = em.create(CustomerUserRole, {\n user,\n role,\n createdAt: new Date(),\n } as any)\n em.persist(userRole)\n }\n await em.flush()\n rolesChanged = true\n }\n\n if (rolesChanged) {\n const customerRbacService = container.resolve('customerRbacService') as CustomerRbacService\n await customerRbacService.invalidateUserCache(user.id)\n }\n\n void emitCustomerAccountsEvent('customer_accounts.user.updated', {\n id: user.id,\n recipientUserId: user.id,\n email: user.email,\n tenantId: user.tenantId,\n organizationId: user.organizationId,\n updatedBy: auth.sub,\n }).catch(() => undefined)\n\n return NextResponse.json({ ok: true, updatedAt: nextUpdatedAt.toISOString() })\n}\n\nexport async function DELETE(req: Request, { params }: { params: { id: string } }) {\n const auth = await getAuthFromRequest(req)\n if (!auth) {\n return NextResponse.json({ ok: false, error: 'Authentication required' }, { status: 401 })\n }\n\n const container = await createRequestContainer()\n const rbacService = container.resolve('rbacService') as RbacService\n const hasAccess = await rbacService.userHasAllFeatures(auth.sub, ['customer_accounts.manage'], { tenantId: auth.tenantId, organizationId: auth.orgId })\n if (!hasAccess) {\n return NextResponse.json({ ok: false, error: 'Insufficient permissions' }, { status: 403 })\n }\n\n const em = container.resolve('em') as import('@mikro-orm/postgresql').EntityManager\n\n const user = await findOneWithDecryption(\n em,\n CustomerUser,\n { id: params.id, tenantId: auth.tenantId, organizationId: auth.orgId, deletedAt: null } as any,\n undefined,\n { tenantId: auth.tenantId, organizationId: auth.orgId },\n )\n if (!user) {\n return NextResponse.json({ ok: false, error: 'User not found' }, { status: 404 })\n }\n\n // Optimistic lock: refuse a stale delete (e.g. deleting a record another admin\n // already modified). Strictly additive \u2014 a no-op without the expected-version header.\n try {\n await enforceCommandOptimisticLockWithGuards(container, {\n resourceKind: 'customer_accounts.user',\n resourceId: user.id,\n current: user.updatedAt ?? null,\n request: req,\n })\n } catch (err) {\n if (isCrudHttpError(err)) return NextResponse.json(err.body, { status: err.status })\n throw err\n }\n\n const customerUserService = container.resolve('customerUserService') as CustomerUserService\n const customerSessionService = container.resolve('customerSessionService') as CustomerSessionService\n\n await customerUserService.softDelete(user.id, {\n tenantId: user.tenantId,\n organizationId: user.organizationId,\n })\n await customerSessionService.revokeAllUserSessions(user.id)\n\n void emitCustomerAccountsEvent('customer_accounts.user.deleted', {\n id: user.id,\n email: user.email,\n tenantId: user.tenantId,\n organizationId: user.organizationId,\n deletedBy: auth.sub,\n }).catch(() => undefined)\n\n return NextResponse.json({ ok: true })\n}\n\nconst roleSchema = z.object({ id: z.string().uuid(), name: z.string(), slug: z.string() })\nconst userDetailSchema = z.object({\n id: z.string().uuid(),\n email: z.string(),\n displayName: z.string(),\n emailVerified: z.boolean(),\n isActive: z.boolean(),\n lockedUntil: z.string().datetime().nullable(),\n lastLoginAt: z.string().datetime().nullable(),\n failedLoginAttempts: z.number(),\n customerEntityId: z.string().uuid().nullable(),\n personEntityId: z.string().uuid().nullable(),\n createdAt: z.string().datetime(),\n updatedAt: z.string().datetime().nullable(),\n roles: z.array(roleSchema),\n activeSessionCount: z.number(),\n})\n\nconst successSchema = z.object({ ok: z.literal(true) })\nconst errorSchema = z.object({ ok: z.literal(false), error: z.string() })\n\nconst getMethodDoc: OpenApiMethodDoc = {\n summary: 'Get customer user detail (admin)',\n description: 'Returns full customer user details including CRM links, roles, and active session count.',\n tags: ['Customer Accounts Admin'],\n responses: [{\n status: 200,\n description: 'User detail',\n schema: z.object({ ok: z.literal(true), user: userDetailSchema }),\n }],\n errors: [\n { status: 401, description: 'Not authenticated', schema: errorSchema },\n { status: 403, description: 'Insufficient permissions', schema: errorSchema },\n { status: 404, description: 'User not found', schema: errorSchema },\n ],\n}\n\nconst putMethodDoc: OpenApiMethodDoc = {\n summary: 'Update customer user (admin)',\n description: 'Updates a customer user. Staff can update status, lock, CRM links, and roles. Role assignment bypasses customer_assignable check.',\n tags: ['Customer Accounts Admin'],\n requestBody: { schema: adminUpdateUserSchema },\n responses: [{ status: 200, description: 'User updated', schema: successSchema }],\n errors: [\n { status: 400, description: 'Validation failed or role not found', schema: errorSchema },\n { status: 401, description: 'Not authenticated', schema: errorSchema },\n { status: 403, description: 'Insufficient permissions', schema: errorSchema },\n { status: 404, description: 'User not found', schema: errorSchema },\n ],\n}\n\nconst deleteMethodDoc: OpenApiMethodDoc = {\n summary: 'Delete customer user (admin)',\n description: 'Soft deletes a customer user and revokes all their active sessions.',\n tags: ['Customer Accounts Admin'],\n responses: [{ status: 200, description: 'User deleted', schema: successSchema }],\n errors: [\n { status: 401, description: 'Not authenticated', schema: errorSchema },\n { status: 403, description: 'Insufficient permissions', schema: errorSchema },\n { status: 404, description: 'User not found', schema: errorSchema },\n ],\n}\n\nexport const openApi: OpenApiRouteDoc = {\n summary: 'Customer user detail management (admin)',\n pathParams: z.object({ id: z.string().uuid() }),\n methods: {\n GET: getMethodDoc,\n PUT: putMethodDoc,\n DELETE: deleteMethodDoc,\n },\n}\n"],
5
+ "mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAElB,SAAS,0BAA0B;AACnC,SAAS,8BAA8B;AAEvC,SAAS,cAAc,kBAAkB,cAAc,2BAA2B;AAIlF,SAAS,6BAA6B;AACtC,SAAS,iCAAiC;AAC1C,SAAS,uBAAuB,0BAA0B;AAC1D,SAAS,4BAA4B,sBAAsB,2BAA2B;AACtF,SAAS,8CAA8C;AACvD,SAAS,uBAAuB;AAEzB,MAAM,WAAW,CAAC;AAEzB,MAAM,UAAU;AAEhB,eAAsB,IAAI,KAAc,EAAE,OAAO,GAA+B;AAC9E,MAAI,CAAC,QAAQ,KAAK,OAAO,EAAE,GAAG;AAC5B,WAAO,aAAa,KAAK,EAAE,IAAI,OAAO,OAAO,kBAAkB,GAA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AK,aAAa,4BAA4B,QAAQ,YAAY;AAAA,IAC5E,EAAE,QAAQ,KAAK,aAAa,kBAAkB,QAAQ,YAAY;AAAA,EACpE;AACF;AAEA,MAAM,kBAAoC;AAAA,EACxC,SAAS;AAAA,EACT,aAAa;AAAA,EACb,MAAM,CAAC,yBAAyB;AAAA,EAChC,WAAW,CAAC,EAAE,QAAQ,KAAK,aAAa,gBAAgB,QAAQ,cAAc,CAAC;AAAA,EAC/E,QAAQ;AAAA,IACN,EAAE,QAAQ,KAAK,aAAa,qBAAqB,QAAQ,YAAY;AAAA,IACrE,EAAE,QAAQ,KAAK,aAAa,4BAA4B,QAAQ,YAAY;AAAA,IAC5E,EAAE,QAAQ,KAAK,aAAa,kBAAkB,QAAQ,YAAY;AAAA,EACpE;AACF;AAEO,MAAM,UAA2B;AAAA,EACtC,SAAS;AAAA,EACT,YAAY,EAAE,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC;AAAA,EAC9C,SAAS;AAAA,IACP,KAAK;AAAA,IACL,KAAK;AAAA,IACL,QAAQ;AAAA,EACV;AACF;",
6
6
  "names": []
7
7
  }
@@ -1,6 +1,7 @@
1
1
  import { NextResponse } from "next/server";
2
2
  import { z } from "zod";
3
3
  import { getCustomerAuthFromRequest } from "@open-mercato/core/modules/customer_accounts/lib/customerAuth";
4
+ import { arePortalNotificationsAvailable } from "@open-mercato/core/modules/customer_accounts/lib/portalNotificationsAvailability";
4
5
  import { createRequestContainer } from "@open-mercato/shared/lib/di/container";
5
6
  import { Notification } from "@open-mercato/core/modules/notifications/data/entities";
6
7
  const metadata = { requireAuth: false };
@@ -11,11 +12,11 @@ async function PUT(req, { params }) {
11
12
  }
12
13
  const container = await createRequestContainer();
13
14
  const em = container.resolve("em");
14
- const notification = await em.findOne(Notification, {
15
+ const notification = arePortalNotificationsAvailable(em) ? await em.findOne(Notification, {
15
16
  id: params.id,
16
17
  recipientUserId: auth.sub,
17
18
  tenantId: auth.tenantId
18
- });
19
+ }) : null;
19
20
  if (!notification) {
20
21
  return NextResponse.json({ ok: false, error: "Notification not found" }, { status: 404 });
21
22
  }
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../../../src/modules/customer_accounts/api/portal/notifications/%5Bid%5D/dismiss.ts"],
4
- "sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport type { OpenApiRouteDoc, OpenApiMethodDoc } from '@open-mercato/shared/lib/openapi'\nimport { getCustomerAuthFromRequest } from '@open-mercato/core/modules/customer_accounts/lib/customerAuth'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { Notification } from '@open-mercato/core/modules/notifications/data/entities'\n\nexport const metadata: { path?: string; requireAuth?: boolean } = { requireAuth: false }\n\nexport async function PUT(req: Request, { params }: { params: { id: string } }) {\n const auth = await getCustomerAuthFromRequest(req)\n if (!auth) {\n return NextResponse.json({ ok: false, error: 'Authentication required' }, { status: 401 })\n }\n\n const container = await createRequestContainer()\n const em = container.resolve('em') as import('@mikro-orm/postgresql').EntityManager\n\n const notification = await em.findOne(Notification, {\n id: params.id,\n recipientUserId: auth.sub,\n tenantId: auth.tenantId,\n })\n\n if (!notification) {\n return NextResponse.json({ ok: false, error: 'Notification not found' }, { status: 404 })\n }\n\n notification.status = 'dismissed'\n notification.dismissedAt = new Date()\n await em.flush()\n\n return NextResponse.json({ ok: true })\n}\n\nconst successSchema = z.object({ ok: z.literal(true) })\nconst errorSchema = z.object({ ok: z.literal(false), error: z.string() })\n\nconst methodDoc: OpenApiMethodDoc = {\n summary: 'Dismiss notification',\n description: 'Dismisses a single notification for the authenticated customer user.',\n tags: ['Customer Portal'],\n responses: [{ status: 200, description: 'Notification dismissed', schema: successSchema }],\n errors: [\n { status: 401, description: 'Not authenticated', schema: errorSchema },\n { status: 404, description: 'Notification not found', schema: errorSchema },\n ],\n}\n\nexport const openApi: OpenApiRouteDoc = {\n summary: 'Dismiss customer notification',\n pathParams: z.object({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AE,QAAQ,KAAK,aAAa,qBAAqB,QAAQ,YAAY;AAAA,IACrE,EAAE,QAAQ,KAAK,aAAa,0BAA0B,QAAQ,YAAY;AAAA,EAC5E;AACF;AAEO,MAAM,UAA2B;AAAA,EACtC,SAAS;AAAA,EACT,YAAY,EAAE,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC;AAAA,EAC9C,SAAS,EAAE,KAAK,UAAU;AAC5B;",
4
+ "sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport type { OpenApiRouteDoc, OpenApiMethodDoc } from '@open-mercato/shared/lib/openapi'\nimport { getCustomerAuthFromRequest } from '@open-mercato/core/modules/customer_accounts/lib/customerAuth'\nimport { arePortalNotificationsAvailable } from '@open-mercato/core/modules/customer_accounts/lib/portalNotificationsAvailability'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { Notification } from '@open-mercato/core/modules/notifications/data/entities'\n\nexport const metadata: { path?: string; requireAuth?: boolean } = { requireAuth: false }\n\nexport async function PUT(req: Request, { params }: { params: { id: string } }) {\n const auth = await getCustomerAuthFromRequest(req)\n if (!auth) {\n return NextResponse.json({ ok: false, error: 'Authentication required' }, { status: 401 })\n }\n\n const container = await createRequestContainer()\n const em = container.resolve('em') as import('@mikro-orm/postgresql').EntityManager\n\n const notification = arePortalNotificationsAvailable(em)\n ? await em.findOne(Notification, {\n id: params.id,\n recipientUserId: auth.sub,\n tenantId: auth.tenantId,\n })\n : null\n\n if (!notification) {\n return NextResponse.json({ ok: false, error: 'Notification not found' }, { status: 404 })\n }\n\n notification.status = 'dismissed'\n notification.dismissedAt = new Date()\n await em.flush()\n\n return NextResponse.json({ ok: true })\n}\n\nconst successSchema = z.object({ ok: z.literal(true) })\nconst errorSchema = z.object({ ok: z.literal(false), error: z.string() })\n\nconst methodDoc: OpenApiMethodDoc = {\n summary: 'Dismiss notification',\n description: 'Dismisses a single notification for the authenticated customer user.',\n tags: ['Customer Portal'],\n responses: [{ status: 200, description: 'Notification dismissed', schema: successSchema }],\n errors: [\n { status: 401, description: 'Not authenticated', schema: errorSchema },\n { status: 404, description: 'Notification not found', schema: errorSchema },\n ],\n}\n\nexport const openApi: OpenApiRouteDoc = {\n summary: 'Dismiss customer notification',\n pathParams: z.object({ id: z.string().uuid() }),\n methods: { PUT: methodDoc },\n}\n"],
5
+ "mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAElB,SAAS,kCAAkC;AAC3C,SAAS,uCAAuC;AAChD,SAAS,8BAA8B;AACvC,SAAS,oBAAoB;AAEtB,MAAM,WAAqD,EAAE,aAAa,MAAM;AAEvF,eAAsB,IAAI,KAAc,EAAE,OAAO,GAA+B;AAC9E,QAAM,OAAO,MAAM,2BAA2B,GAAG;AACjD,MAAI,CAAC,MAAM;AACT,WAAO,aAAa,KAAK,EAAE,IAAI,OAAO,OAAO,0BAA0B,GAAG,EAAE,QAAQ,IAAI,CAAC;AAAA,EAC3F;AAEA,QAAM,YAAY,MAAM,uBAAuB;AAC/C,QAAM,KAAK,UAAU,QAAQ,IAAI;AAEjC,QAAM,eAAe,gCAAgC,EAAE,IACnD,MAAM,GAAG,QAAQ,cAAc;AAAA,IAC7B,IAAI,OAAO;AAAA,IACX,iBAAiB,KAAK;AAAA,IACtB,UAAU,KAAK;AAAA,EACjB,CAAC,IACD;AAEJ,MAAI,CAAC,cAAc;AACjB,WAAO,aAAa,KAAK,EAAE,IAAI,OAAO,OAAO,yBAAyB,GAAG,EAAE,QAAQ,IAAI,CAAC;AAAA,EAC1F;AAEA,eAAa,SAAS;AACtB,eAAa,cAAc,oBAAI,KAAK;AACpC,QAAM,GAAG,MAAM;AAEf,SAAO,aAAa,KAAK,EAAE,IAAI,KAAK,CAAC;AACvC;AAEA,MAAM,gBAAgB,EAAE,OAAO,EAAE,IAAI,EAAE,QAAQ,IAAI,EAAE,CAAC;AACtD,MAAM,cAAc,EAAE,OAAO,EAAE,IAAI,EAAE,QAAQ,KAAK,GAAG,OAAO,EAAE,OAAO,EAAE,CAAC;AAExE,MAAM,YAA8B;AAAA,EAClC,SAAS;AAAA,EACT,aAAa;AAAA,EACb,MAAM,CAAC,iBAAiB;AAAA,EACxB,WAAW,CAAC,EAAE,QAAQ,KAAK,aAAa,0BAA0B,QAAQ,cAAc,CAAC;AAAA,EACzF,QAAQ;AAAA,IACN,EAAE,QAAQ,KAAK,aAAa,qBAAqB,QAAQ,YAAY;AAAA,IACrE,EAAE,QAAQ,KAAK,aAAa,0BAA0B,QAAQ,YAAY;AAAA,EAC5E;AACF;AAEO,MAAM,UAA2B;AAAA,EACtC,SAAS;AAAA,EACT,YAAY,EAAE,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC;AAAA,EAC9C,SAAS,EAAE,KAAK,UAAU;AAC5B;",
6
6
  "names": []
7
7
  }
@@ -1,6 +1,7 @@
1
1
  import { NextResponse } from "next/server";
2
2
  import { z } from "zod";
3
3
  import { getCustomerAuthFromRequest } from "@open-mercato/core/modules/customer_accounts/lib/customerAuth";
4
+ import { arePortalNotificationsAvailable } from "@open-mercato/core/modules/customer_accounts/lib/portalNotificationsAvailability";
4
5
  import { createRequestContainer } from "@open-mercato/shared/lib/di/container";
5
6
  import { Notification } from "@open-mercato/core/modules/notifications/data/entities";
6
7
  const metadata = { requireAuth: false };
@@ -11,11 +12,11 @@ async function PUT(req, { params }) {
11
12
  }
12
13
  const container = await createRequestContainer();
13
14
  const em = container.resolve("em");
14
- const notification = await em.findOne(Notification, {
15
+ const notification = arePortalNotificationsAvailable(em) ? await em.findOne(Notification, {
15
16
  id: params.id,
16
17
  recipientUserId: auth.sub,
17
18
  tenantId: auth.tenantId
18
- });
19
+ }) : null;
19
20
  if (!notification) {
20
21
  return NextResponse.json({ ok: false, error: "Notification not found" }, { status: 404 });
21
22
  }
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../../../src/modules/customer_accounts/api/portal/notifications/%5Bid%5D/read.ts"],
4
- "sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport type { OpenApiRouteDoc, OpenApiMethodDoc } from '@open-mercato/shared/lib/openapi'\nimport { getCustomerAuthFromRequest } from '@open-mercato/core/modules/customer_accounts/lib/customerAuth'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { Notification } from '@open-mercato/core/modules/notifications/data/entities'\n\nexport const metadata: { path?: string; requireAuth?: boolean } = { requireAuth: false }\n\nexport async function PUT(req: Request, { params }: { params: { id: string } }) {\n const auth = await getCustomerAuthFromRequest(req)\n if (!auth) {\n return NextResponse.json({ ok: false, error: 'Authentication required' }, { status: 401 })\n }\n\n const container = await createRequestContainer()\n const em = container.resolve('em') as import('@mikro-orm/postgresql').EntityManager\n\n const notification = await em.findOne(Notification, {\n id: params.id,\n recipientUserId: auth.sub,\n tenantId: auth.tenantId,\n })\n\n if (!notification) {\n return NextResponse.json({ ok: false, error: 'Notification not found' }, { status: 404 })\n }\n\n notification.status = 'read'\n notification.readAt = new Date()\n await em.flush()\n\n return NextResponse.json({ ok: true })\n}\n\nconst successSchema = z.object({ ok: z.literal(true) })\nconst errorSchema = z.object({ ok: z.literal(false), error: z.string() })\n\nconst methodDoc: OpenApiMethodDoc = {\n summary: 'Mark notification as read',\n description: 'Marks a single notification as read for the authenticated customer user.',\n tags: ['Customer Portal'],\n responses: [{ status: 200, description: 'Notification marked as read', schema: successSchema }],\n errors: [\n { status: 401, description: 'Not authenticated', schema: errorSchema },\n { status: 404, description: 'Notification not found', schema: errorSchema },\n ],\n}\n\nexport const openApi: OpenApiRouteDoc = {\n summary: 'Mark notification as read',\n pathParams: z.object({ id: z.string().uuid() }),\n methods: { PUT: methodDoc },\n}\n"],
5
- "mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAElB,SAAS,kCAAkC;AAC3C,SAAS,8BAA8B;AACvC,SAAS,oBAAoB;AAEtB,MAAM,WAAqD,EAAE,aA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AO,EAAE,IAAI,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC;AAAA,EAC9C,SAAS,EAAE,KAAK,UAAU;AAC5B;",
4
+ "sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport type { OpenApiRouteDoc, OpenApiMethodDoc } from '@open-mercato/shared/lib/openapi'\nimport { getCustomerAuthFromRequest } from '@open-mercato/core/modules/customer_accounts/lib/customerAuth'\nimport { arePortalNotificationsAvailable } from '@open-mercato/core/modules/customer_accounts/lib/portalNotificationsAvailability'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { Notification } from '@open-mercato/core/modules/notifications/data/entities'\n\nexport const metadata: { path?: string; requireAuth?: boolean } = { requireAuth: false }\n\nexport async function PUT(req: Request, { params }: { params: { id: string } }) {\n const auth = await getCustomerAuthFromRequest(req)\n if (!auth) {\n return NextResponse.json({ ok: false, error: 'Authentication required' }, { status: 401 })\n }\n\n const container = await createRequestContainer()\n const em = container.resolve('em') as import('@mikro-orm/postgresql').EntityManager\n\n const notification = arePortalNotificationsAvailable(em)\n ? await em.findOne(Notification, {\n id: params.id,\n recipientUserId: auth.sub,\n tenantId: auth.tenantId,\n })\n : null\n\n if (!notification) {\n return NextResponse.json({ ok: false, error: 'Notification not found' }, { status: 404 })\n }\n\n notification.status = 'read'\n notification.readAt = new Date()\n await em.flush()\n\n return NextResponse.json({ ok: true })\n}\n\nconst successSchema = z.object({ ok: z.literal(true) })\nconst errorSchema = z.object({ ok: z.literal(false), error: z.string() })\n\nconst methodDoc: OpenApiMethodDoc = {\n summary: 'Mark notification as read',\n description: 'Marks a single notification as read for the authenticated customer user.',\n tags: ['Customer Portal'],\n responses: [{ status: 200, description: 'Notification marked as read', schema: successSchema }],\n errors: [\n { status: 401, description: 'Not authenticated', schema: errorSchema },\n { status: 404, description: 'Notification not found', schema: errorSchema },\n ],\n}\n\nexport const openApi: OpenApiRouteDoc = {\n summary: 'Mark notification as read',\n pathParams: z.object({ id: z.string().uu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c,CAAC;AAAA,EAC9F,QAAQ;AAAA,IACN,EAAE,QAAQ,KAAK,aAAa,qBAAqB,QAAQ,YAAY;AAAA,IACrE,EAAE,QAAQ,KAAK,aAAa,0BAA0B,QAAQ,YAAY;AAAA,EAC5E;AACF;AAEO,MAAM,UAA2B;AAAA,EACtC,SAAS;AAAA,EACT,YAAY,EAAE,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC;AAAA,EAC9C,SAAS,EAAE,KAAK,UAAU;AAC5B;",
6
6
  "names": []
7
7
  }
@@ -1,6 +1,7 @@
1
1
  import { NextResponse } from "next/server";
2
2
  import { z } from "zod";
3
3
  import { getCustomerAuthFromRequest } from "@open-mercato/core/modules/customer_accounts/lib/customerAuth";
4
+ import { arePortalNotificationsAvailable } from "@open-mercato/core/modules/customer_accounts/lib/portalNotificationsAvailability";
4
5
  import { createRequestContainer } from "@open-mercato/shared/lib/di/container";
5
6
  import { Notification } from "@open-mercato/core/modules/notifications/data/entities";
6
7
  const metadata = { requireAuth: false };
@@ -11,6 +12,9 @@ async function PUT(req) {
11
12
  }
12
13
  const container = await createRequestContainer();
13
14
  const em = container.resolve("em");
15
+ if (!arePortalNotificationsAvailable(em)) {
16
+ return NextResponse.json({ ok: true, count: 0 });
17
+ }
14
18
  const now = /* @__PURE__ */ new Date();
15
19
  const count = await em.nativeUpdate(Notification, {
16
20
  recipientUserId: auth.sub,
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../../src/modules/customer_accounts/api/portal/notifications/mark-all-read.ts"],
4
- "sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport type { OpenApiRouteDoc, OpenApiMethodDoc } from '@open-mercato/shared/lib/openapi'\nimport { getCustomerAuthFromRequest } from '@open-mercato/core/modules/customer_accounts/lib/customerAuth'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { Notification } from '@open-mercato/core/modules/notifications/data/entities'\n\nexport const metadata: { path?: string; requireAuth?: boolean } = { requireAuth: false }\n\nexport async function PUT(req: Request) {\n const auth = await getCustomerAuthFromRequest(req)\n if (!auth) {\n return NextResponse.json({ ok: false, error: 'Authentication required' }, { status: 401 })\n }\n\n const container = await createRequestContainer()\n const em = container.resolve('em') as import('@mikro-orm/postgresql').EntityManager\n\n const now = new Date()\n const count = await em.nativeUpdate(Notification, {\n recipientUserId: auth.sub,\n tenantId: auth.tenantId,\n status: 'unread',\n }, {\n status: 'read',\n readAt: now,\n })\n\n return NextResponse.json({ ok: true, count })\n}\n\nconst successSchema = z.object({\n ok: z.literal(true),\n count: z.number(),\n})\nconst errorSchema = z.object({ ok: z.literal(false), error: z.string() })\n\nconst methodDoc: OpenApiMethodDoc = {\n summary: 'Mark all notifications as read',\n description: 'Marks all unread notifications as read for the authenticated customer user.',\n tags: ['Customer Portal'],\n responses: [{ status: 200, description: 'All notifications marked as read', schema: successSchema }],\n errors: [{ status: 401, description: 'Not authenticated', schema: errorSchema }],\n}\n\nexport const openApi: OpenApiRouteDoc = {\n summary: 'Mark all customer notifications as read',\n methods: { PUT: methodDoc },\n}\n"],
5
- "mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAElB,SAAS,kCAAkC;AAC3C,SAAS,8BAA8B;AACvC,SAAS,oBAAoB;AAEtB,MAAM,WAAqD,EAAE,aAAa,MAAM;AAEvF,eAAsB,IAAI,KAAc;AACtC,QAAM,OAAO,MAAM,2BAA2B,GAAG;AACjD,MAAI,CAAC,MAAM;AACT,WAAO,aAAa,KAAK,EAAE,IAAI,OAAO,OAAO,0BAA0B,GAAG,EAAE,QAAQ,IAAI,CAAC;AAAA,EAC3F;AAEA,QAAM,YAAY,MAAM,uBAAuB;AAC/C,QAAM,KAAK,UAAU,QAAQ,IAAI;AAEjC,QAAM,MAAM,oBAAI,KAAK;AACrB,QAAM,QAAQ,MAAM,GAAG,aAAa,cAAc;AAAA,IAChD,iBAAiB,KAAK;AAAA,IACtB,UAAU,KAAK;AAAA,IACf,QAAQ;AAAA,EACV,GAAG;AAAA,IACD,QAAQ;AAAA,IACR,QAAQ;AAAA,EACV,CAAC;AAED,SAAO,aAAa,KAAK,EAAE,IAAI,MAAM,MAAM,CAAC;AAC9C;AAEA,MAAM,gBAAgB,EAAE,OAAO;AAAA,EAC7B,IAAI,EAAE,QAAQ,IAAI;AAAA,EAClB,OAAO,EAAE,OAAO;AAClB,CAAC;AACD,MAAM,cAAc,EAAE,OAAO,EAAE,IAAI,EAAE,QAAQ,KAAK,GAAG,OAAO,EAAE,OAAO,EAAE,CAAC;AAExE,MAAM,YAA8B;AAAA,EAClC,SAAS;AAAA,EACT,aAAa;AAAA,EACb,MAAM,CAAC,iBAAiB;AAAA,EACxB,WAAW,CAAC,EAAE,QAAQ,KAAK,aAAa,oCAAoC,QAAQ,cAAc,CAAC;AAAA,EACnG,QAAQ,CAAC,EAAE,QAAQ,KAAK,aAAa,qBAAqB,QAAQ,YAAY,CAAC;AACjF;AAEO,MAAM,UAA2B;AAAA,EACtC,SAAS;AAAA,EACT,SAAS,EAAE,KAAK,UAAU;AAC5B;",
4
+ "sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport type { OpenApiRouteDoc, OpenApiMethodDoc } from '@open-mercato/shared/lib/openapi'\nimport { getCustomerAuthFromRequest } from '@open-mercato/core/modules/customer_accounts/lib/customerAuth'\nimport { arePortalNotificationsAvailable } from '@open-mercato/core/modules/customer_accounts/lib/portalNotificationsAvailability'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { Notification } from '@open-mercato/core/modules/notifications/data/entities'\n\nexport const metadata: { path?: string; requireAuth?: boolean } = { requireAuth: false }\n\nexport async function PUT(req: Request) {\n const auth = await getCustomerAuthFromRequest(req)\n if (!auth) {\n return NextResponse.json({ ok: false, error: 'Authentication required' }, { status: 401 })\n }\n\n const container = await createRequestContainer()\n const em = container.resolve('em') as import('@mikro-orm/postgresql').EntityManager\n if (!arePortalNotificationsAvailable(em)) {\n return NextResponse.json({ ok: true, count: 0 })\n }\n\n const now = new Date()\n const count = await em.nativeUpdate(Notification, {\n recipientUserId: auth.sub,\n tenantId: auth.tenantId,\n status: 'unread',\n }, {\n status: 'read',\n readAt: now,\n })\n\n return NextResponse.json({ ok: true, count })\n}\n\nconst successSchema = z.object({\n ok: z.literal(true),\n count: z.number(),\n})\nconst errorSchema = z.object({ ok: z.literal(false), error: z.string() })\n\nconst methodDoc: OpenApiMethodDoc = {\n summary: 'Mark all notifications as read',\n description: 'Marks all unread notifications as read for the authenticated customer user.',\n tags: ['Customer Portal'],\n responses: [{ status: 200, description: 'All notifications marked as read', schema: successSchema }],\n errors: [{ status: 401, description: 'Not authenticated', schema: errorSchema }],\n}\n\nexport const openApi: OpenApiRouteDoc = {\n summary: 'Mark all customer notifications as read',\n methods: { PUT: methodDoc },\n}\n"],
5
+ "mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAElB,SAAS,kCAAkC;AAC3C,SAAS,uCAAuC;AAChD,SAAS,8BAA8B;AACvC,SAAS,oBAAoB;AAEtB,MAAM,WAAqD,EAAE,aAAa,MAAM;AAEvF,eAAsB,IAAI,KAAc;AACtC,QAAM,OAAO,MAAM,2BAA2B,GAAG;AACjD,MAAI,CAAC,MAAM;AACT,WAAO,aAAa,KAAK,EAAE,IAAI,OAAO,OAAO,0BAA0B,GAAG,EAAE,QAAQ,IAAI,CAAC;AAAA,EAC3F;AAEA,QAAM,YAAY,MAAM,uBAAuB;AAC/C,QAAM,KAAK,UAAU,QAAQ,IAAI;AACjC,MAAI,CAAC,gCAAgC,EAAE,GAAG;AACxC,WAAO,aAAa,KAAK,EAAE,IAAI,MAAM,OAAO,EAAE,CAAC;AAAA,EACjD;AAEA,QAAM,MAAM,oBAAI,KAAK;AACrB,QAAM,QAAQ,MAAM,GAAG,aAAa,cAAc;AAAA,IAChD,iBAAiB,KAAK;AAAA,IACtB,UAAU,KAAK;AAAA,IACf,QAAQ;AAAA,EACV,GAAG;AAAA,IACD,QAAQ;AAAA,IACR,QAAQ;AAAA,EACV,CAAC;AAED,SAAO,aAAa,KAAK,EAAE,IAAI,MAAM,MAAM,CAAC;AAC9C;AAEA,MAAM,gBAAgB,EAAE,OAAO;AAAA,EAC7B,IAAI,EAAE,QAAQ,IAAI;AAAA,EAClB,OAAO,EAAE,OAAO;AAClB,CAAC;AACD,MAAM,cAAc,EAAE,OAAO,EAAE,IAAI,EAAE,QAAQ,KAAK,GAAG,OAAO,EAAE,OAAO,EAAE,CAAC;AAExE,MAAM,YAA8B;AAAA,EAClC,SAAS;AAAA,EACT,aAAa;AAAA,EACb,MAAM,CAAC,iBAAiB;AAAA,EACxB,WAAW,CAAC,EAAE,QAAQ,KAAK,aAAa,oCAAoC,QAAQ,cAAc,CAAC;AAAA,EACnG,QAAQ,CAAC,EAAE,QAAQ,KAAK,aAAa,qBAAqB,QAAQ,YAAY,CAAC;AACjF;AAEO,MAAM,UAA2B;AAAA,EACtC,SAAS;AAAA,EACT,SAAS,EAAE,KAAK,UAAU;AAC5B;",
6
6
  "names": []
7
7
  }
@@ -1,6 +1,7 @@
1
1
  import { NextResponse } from "next/server";
2
2
  import { z } from "zod";
3
3
  import { getCustomerAuthFromRequest } from "@open-mercato/core/modules/customer_accounts/lib/customerAuth";
4
+ import { arePortalNotificationsAvailable } from "@open-mercato/core/modules/customer_accounts/lib/portalNotificationsAvailability";
4
5
  import { createRequestContainer } from "@open-mercato/shared/lib/di/container";
5
6
  import { Notification } from "@open-mercato/core/modules/notifications/data/entities";
6
7
  const metadata = { requireAuth: false };
@@ -11,6 +12,9 @@ async function GET(req) {
11
12
  }
12
13
  const container = await createRequestContainer();
13
14
  const em = container.resolve("em");
15
+ if (!arePortalNotificationsAvailable(em)) {
16
+ return NextResponse.json({ ok: true, unreadCount: 0 });
17
+ }
14
18
  const unreadCount = await em.count(Notification, {
15
19
  recipientUserId: auth.sub,
16
20
  tenantId: auth.tenantId,
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../../src/modules/customer_accounts/api/portal/notifications/unread-count.ts"],
4
- "sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport type { OpenApiRouteDoc, OpenApiMethodDoc } from '@open-mercato/shared/lib/openapi'\nimport { getCustomerAuthFromRequest } from '@open-mercato/core/modules/customer_accounts/lib/customerAuth'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { Notification } from '@open-mercato/core/modules/notifications/data/entities'\n\nexport const metadata: { path?: string; requireAuth?: boolean } = { requireAuth: false }\n\nexport async function GET(req: Request) {\n const auth = await getCustomerAuthFromRequest(req)\n if (!auth) {\n return NextResponse.json({ ok: false, error: 'Authentication required' }, { status: 401 })\n }\n\n const container = await createRequestContainer()\n const em = container.resolve('em') as import('@mikro-orm/postgresql').EntityManager\n\n const unreadCount = await em.count(Notification, {\n recipientUserId: auth.sub,\n tenantId: auth.tenantId,\n status: 'unread',\n })\n\n return NextResponse.json({ ok: true, unreadCount })\n}\n\nconst successSchema = z.object({\n ok: z.literal(true),\n unreadCount: z.number(),\n})\nconst errorSchema = z.object({ ok: z.literal(false), error: z.string() })\n\nconst methodDoc: OpenApiMethodDoc = {\n summary: 'Get unread notification count',\n description: 'Returns the number of unread notifications for the authenticated customer user.',\n tags: ['Customer Portal'],\n responses: [{ status: 200, description: 'Unread count', schema: successSchema }],\n errors: [{ status: 401, description: 'Not authenticated', schema: errorSchema }],\n}\n\nexport const openApi: OpenApiRouteDoc = {\n summary: 'Customer unread notification count',\n methods: { GET: methodDoc },\n}\n"],
5
- "mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAElB,SAAS,kCAAkC;AAC3C,SAAS,8BAA8B;AACvC,SAAS,oBAAoB;AAEtB,MAAM,WAAqD,EAAE,aAAa,MAAM;AAEvF,eAAsB,IAAI,KAAc;AACtC,QAAM,OAAO,MAAM,2BAA2B,GAAG;AACjD,MAAI,CAAC,MAAM;AACT,WAAO,aAAa,KAAK,EAAE,IAAI,OAAO,OAAO,0BAA0B,GAAG,EAAE,QAAQ,IAAI,CAAC;AAAA,EAC3F;AAEA,QAAM,YAAY,MAAM,uBAAuB;AAC/C,QAAM,KAAK,UAAU,QAAQ,IAAI;AAEjC,QAAM,cAAc,MAAM,GAAG,MAAM,cAAc;AAAA,IAC/C,iBAAiB,KAAK;AAAA,IACtB,UAAU,KAAK;AAAA,IACf,QAAQ;AAAA,EACV,CAAC;AAED,SAAO,aAAa,KAAK,EAAE,IAAI,MAAM,YAAY,CAAC;AACpD;AAEA,MAAM,gBAAgB,EAAE,OAAO;AAAA,EAC7B,IAAI,EAAE,QAAQ,IAAI;AAAA,EAClB,aAAa,EAAE,OAAO;AACxB,CAAC;AACD,MAAM,cAAc,EAAE,OAAO,EAAE,IAAI,EAAE,QAAQ,KAAK,GAAG,OAAO,EAAE,OAAO,EAAE,CAAC;AAExE,MAAM,YAA8B;AAAA,EAClC,SAAS;AAAA,EACT,aAAa;AAAA,EACb,MAAM,CAAC,iBAAiB;AAAA,EACxB,WAAW,CAAC,EAAE,QAAQ,KAAK,aAAa,gBAAgB,QAAQ,cAAc,CAAC;AAAA,EAC/E,QAAQ,CAAC,EAAE,QAAQ,KAAK,aAAa,qBAAqB,QAAQ,YAAY,CAAC;AACjF;AAEO,MAAM,UAA2B;AAAA,EACtC,SAAS;AAAA,EACT,SAAS,EAAE,KAAK,UAAU;AAC5B;",
4
+ "sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport type { OpenApiRouteDoc, OpenApiMethodDoc } from '@open-mercato/shared/lib/openapi'\nimport { getCustomerAuthFromRequest } from '@open-mercato/core/modules/customer_accounts/lib/customerAuth'\nimport { arePortalNotificationsAvailable } from '@open-mercato/core/modules/customer_accounts/lib/portalNotificationsAvailability'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { Notification } from '@open-mercato/core/modules/notifications/data/entities'\n\nexport const metadata: { path?: string; requireAuth?: boolean } = { requireAuth: false }\n\nexport async function GET(req: Request) {\n const auth = await getCustomerAuthFromRequest(req)\n if (!auth) {\n return NextResponse.json({ ok: false, error: 'Authentication required' }, { status: 401 })\n }\n\n const container = await createRequestContainer()\n const em = container.resolve('em') as import('@mikro-orm/postgresql').EntityManager\n if (!arePortalNotificationsAvailable(em)) {\n return NextResponse.json({ ok: true, unreadCount: 0 })\n }\n\n const unreadCount = await em.count(Notification, {\n recipientUserId: auth.sub,\n tenantId: auth.tenantId,\n status: 'unread',\n })\n\n return NextResponse.json({ ok: true, unreadCount })\n}\n\nconst successSchema = z.object({\n ok: z.literal(true),\n unreadCount: z.number(),\n})\nconst errorSchema = z.object({ ok: z.literal(false), error: z.string() })\n\nconst methodDoc: OpenApiMethodDoc = {\n summary: 'Get unread notification count',\n description: 'Returns the number of unread notifications for the authenticated customer user.',\n tags: ['Customer Portal'],\n responses: [{ status: 200, description: 'Unread count', schema: successSchema }],\n errors: [{ status: 401, description: 'Not authenticated', schema: errorSchema }],\n}\n\nexport const openApi: OpenApiRouteDoc = {\n summary: 'Customer unread notification count',\n methods: { GET: methodDoc },\n}\n"],
5
+ "mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAElB,SAAS,kCAAkC;AAC3C,SAAS,uCAAuC;AAChD,SAAS,8BAA8B;AACvC,SAAS,oBAAoB;AAEtB,MAAM,WAAqD,EAAE,aAAa,MAAM;AAEvF,eAAsB,IAAI,KAAc;AACtC,QAAM,OAAO,MAAM,2BAA2B,GAAG;AACjD,MAAI,CAAC,MAAM;AACT,WAAO,aAAa,KAAK,EAAE,IAAI,OAAO,OAAO,0BAA0B,GAAG,EAAE,QAAQ,IAAI,CAAC;AAAA,EAC3F;AAEA,QAAM,YAAY,MAAM,uBAAuB;AAC/C,QAAM,KAAK,UAAU,QAAQ,IAAI;AACjC,MAAI,CAAC,gCAAgC,EAAE,GAAG;AACxC,WAAO,aAAa,KAAK,EAAE,IAAI,MAAM,aAAa,EAAE,CAAC;AAAA,EACvD;AAEA,QAAM,cAAc,MAAM,GAAG,MAAM,cAAc;AAAA,IAC/C,iBAAiB,KAAK;AAAA,IACtB,UAAU,KAAK;AAAA,IACf,QAAQ;AAAA,EACV,CAAC;AAED,SAAO,aAAa,KAAK,EAAE,IAAI,MAAM,YAAY,CAAC;AACpD;AAEA,MAAM,gBAAgB,EAAE,OAAO;AAAA,EAC7B,IAAI,EAAE,QAAQ,IAAI;AAAA,EAClB,aAAa,EAAE,OAAO;AACxB,CAAC;AACD,MAAM,cAAc,EAAE,OAAO,EAAE,IAAI,EAAE,QAAQ,KAAK,GAAG,OAAO,EAAE,OAAO,EAAE,CAAC;AAExE,MAAM,YAA8B;AAAA,EAClC,SAAS;AAAA,EACT,aAAa;AAAA,EACb,MAAM,CAAC,iBAAiB;AAAA,EACxB,WAAW,CAAC,EAAE,QAAQ,KAAK,aAAa,gBAAgB,QAAQ,cAAc,CAAC;AAAA,EAC/E,QAAQ,CAAC,EAAE,QAAQ,KAAK,aAAa,qBAAqB,QAAQ,YAAY,CAAC;AACjF;AAEO,MAAM,UAA2B;AAAA,EACtC,SAAS;AAAA,EACT,SAAS,EAAE,KAAK,UAAU;AAC5B;",
6
6
  "names": []
7
7
  }
@@ -1,6 +1,7 @@
1
1
  import { NextResponse } from "next/server";
2
2
  import { z } from "zod";
3
3
  import { getCustomerAuthFromRequest } from "@open-mercato/core/modules/customer_accounts/lib/customerAuth";
4
+ import { arePortalNotificationsAvailable } from "@open-mercato/core/modules/customer_accounts/lib/portalNotificationsAvailability";
4
5
  import { createRequestContainer } from "@open-mercato/shared/lib/di/container";
5
6
  import { Notification } from "@open-mercato/core/modules/notifications/data/entities";
6
7
  import { toNotificationDto } from "@open-mercato/core/modules/notifications/lib/notificationMapper";
@@ -18,6 +19,9 @@ async function GET(req) {
18
19
  const since = url.searchParams.get("since") || void 0;
19
20
  const container = await createRequestContainer();
20
21
  const em = container.resolve("em");
22
+ if (!arePortalNotificationsAvailable(em)) {
23
+ return NextResponse.json({ ok: true, items: [], total: 0, page, pageSize });
24
+ }
21
25
  const where = {
22
26
  recipientUserId: auth.sub,
23
27
  tenantId: auth.tenantId
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../src/modules/customer_accounts/api/portal/notifications.ts"],
4
- "sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport type { OpenApiRouteDoc, OpenApiMethodDoc } from '@open-mercato/shared/lib/openapi'\nimport { getCustomerAuthFromRequest } from '@open-mercato/core/modules/customer_accounts/lib/customerAuth'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { Notification } from '@open-mercato/core/modules/notifications/data/entities'\nimport { toNotificationDto } from '@open-mercato/core/modules/notifications/lib/notificationMapper'\n\nexport const metadata: { path?: string; requireAuth?: boolean } = { requireAuth: false }\n\nexport async function GET(req: Request) {\n const auth = await getCustomerAuthFromRequest(req)\n if (!auth) {\n return NextResponse.json({ ok: false, error: 'Authentication required' }, { status: 401 })\n }\n\n const url = new URL(req.url)\n const page = Math.max(1, parseInt(url.searchParams.get('page') || '1', 10) || 1)\n const rawPageSize = parseInt(url.searchParams.get('pageSize') || '50', 10) || 50\n const pageSize = Math.min(Math.max(1, rawPageSize), 100)\n const status = url.searchParams.get('status') || undefined\n const since = url.searchParams.get('since') || undefined\n\n const container = await createRequestContainer()\n const em = container.resolve('em') as import('@mikro-orm/postgresql').EntityManager\n\n const where: Record<string, unknown> = {\n recipientUserId: auth.sub,\n tenantId: auth.tenantId,\n }\n\n if (status) {\n where.status = status\n } else {\n where.status = { $ne: 'dismissed' }\n }\n\n if (since) {\n const sinceDate = new Date(since)\n if (!isNaN(sinceDate.getTime())) {\n where.createdAt = { $gte: sinceDate }\n }\n }\n\n const offset = (page - 1) * pageSize\n\n const [items, total] = await Promise.all([\n em.find(Notification, where, {\n orderBy: { createdAt: 'DESC' },\n limit: pageSize,\n offset,\n }),\n em.count(Notification, where),\n ])\n\n return NextResponse.json({\n ok: true,\n items: items.map(toNotificationDto),\n total,\n page,\n pageSize,\n })\n}\n\nconst notificationDtoSchema = z.object({\n id: z.string().uuid(),\n type: z.string(),\n title: z.string(),\n body: z.string().nullable().optional(),\n titleKey: z.string().nullable().optional(),\n bodyKey: z.string().nullable().optional(),\n titleVariables: z.record(z.string(), z.string()).nullable().optional(),\n bodyVariables: z.record(z.string(), z.string()).nullable().optional(),\n icon: z.string().nullable().optional(),\n severity: z.enum(['info', 'warning', 'success', 'error']),\n status: z.enum(['unread', 'read', 'actioned', 'dismissed']),\n actions: z.array(z.object({\n id: z.string(),\n label: z.string(),\n labelKey: z.string().optional(),\n variant: z.string().optional(),\n icon: z.string().optional(),\n })),\n primaryActionId: z.string().optional(),\n sourceModule: z.string().nullable().optional(),\n sourceEntityType: z.string().nullable().optional(),\n sourceEntityId: z.string().nullable().optional(),\n linkHref: z.string().nullable().optional(),\n createdAt: z.string().datetime(),\n readAt: z.string().datetime().nullable(),\n actionTaken: z.string().nullable().optional(),\n})\n\nconst listResponseSchema = z.object({\n ok: z.literal(true),\n items: z.array(notificationDtoSchema),\n total: z.number(),\n page: z.number(),\n pageSize: z.number(),\n})\n\nconst errorSchema = z.object({ ok: z.literal(false), error: z.string() })\n\nconst methodDoc: OpenApiMethodDoc = {\n summary: 'List customer notifications',\n description: 'Returns paginated notifications for the authenticated customer user. Dismissed notifications are excluded by default unless ?status=dismissed is specified.',\n tags: ['Customer Portal'],\n responses: [{ status: 200, description: 'Notification list', schema: listResponseSchema }],\n errors: [{ status: 401, description: 'Not authenticated', schema: errorSchema }],\n}\n\nexport const openApi: OpenApiRouteDoc = {\n summary: 'Customer notifications',\n methods: { GET: methodDoc },\n}\n"],
5
- "mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAElB,SAAS,kCAAkC;AAC3C,SAAS,8BAA8B;AACvC,SAAS,oBAAoB;AAC7B,SAAS,yBAAyB;AAE3B,MAAM,WAAqD,EAA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,EAAE,SAAS;AAAA,EACjD,gBAAgB,EAAE,OAAO,EAAE,SAAS,EAAE,SAAS;AAAA,EAC/C,UAAU,EAAE,OAAO,EAAE,SAAS,EAAE,SAAS;AAAA,EACzC,WAAW,EAAE,OAAO,EAAE,SAAS;AAAA,EAC/B,QAAQ,EAAE,OAAO,EAAE,SAAS,EAAE,SAAS;AAAA,EACvC,aAAa,EAAE,OAAO,EAAE,SAAS,EAAE,SAAS;AAC9C,CAAC;AAED,MAAM,qBAAqB,EAAE,OAAO;AAAA,EAClC,IAAI,EAAE,QAAQ,IAAI;AAAA,EAClB,OAAO,EAAE,MAAM,qBAAqB;AAAA,EACpC,OAAO,EAAE,OAAO;AAAA,EAChB,MAAM,EAAE,OAAO;AAAA,EACf,UAAU,EAAE,OAAO;AACrB,CAAC;AAED,MAAM,cAAc,EAAE,OAAO,EAAE,IAAI,EAAE,QAAQ,KAAK,GAAG,OAAO,EAAE,OAAO,EAAE,CAAC;AAExE,MAAM,YAA8B;AAAA,EAClC,SAAS;AAAA,EACT,aAAa;AAAA,EACb,MAAM,CAAC,iBAAiB;AAAA,EACxB,WAAW,CAAC,EAAE,QAAQ,KAAK,aAAa,qBAAqB,QAAQ,mBAAmB,CAAC;AAAA,EACzF,QAAQ,CAAC,EAAE,QAAQ,KAAK,aAAa,qBAAqB,QAAQ,YAAY,CAAC;AACjF;AAEO,MAAM,UAA2B;AAAA,EACtC,SAAS;AAAA,EACT,SAAS,EAAE,KAAK,UAAU;AAC5B;",
4
+ "sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport type { OpenApiRouteDoc, OpenApiMethodDoc } from '@open-mercato/shared/lib/openapi'\nimport { getCustomerAuthFromRequest } from '@open-mercato/core/modules/customer_accounts/lib/customerAuth'\nimport { arePortalNotificationsAvailable } from '@open-mercato/core/modules/customer_accounts/lib/portalNotificationsAvailability'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { Notification } from '@open-mercato/core/modules/notifications/data/entities'\nimport { toNotificationDto } from '@open-mercato/core/modules/notifications/lib/notificationMapper'\n\nexport const metadata: { path?: string; requireAuth?: boolean } = { requireAuth: false }\n\nexport async function GET(req: Request) {\n const auth = await getCustomerAuthFromRequest(req)\n if (!auth) {\n return NextResponse.json({ ok: false, error: 'Authentication required' }, { status: 401 })\n }\n\n const url = new URL(req.url)\n const page = Math.max(1, parseInt(url.searchParams.get('page') || '1', 10) || 1)\n const rawPageSize = parseInt(url.searchParams.get('pageSize') || '50', 10) || 50\n const pageSize = Math.min(Math.max(1, rawPageSize), 100)\n const status = url.searchParams.get('status') || undefined\n const since = url.searchParams.get('since') || undefined\n\n const container = await createRequestContainer()\n const em = container.resolve('em') as import('@mikro-orm/postgresql').EntityManager\n if (!arePortalNotificationsAvailable(em)) {\n return NextResponse.json({ ok: true, items: [], total: 0, page, pageSize })\n }\n\n const where: Record<string, unknown> = {\n recipientUserId: auth.sub,\n tenantId: auth.tenantId,\n }\n\n if (status) {\n where.status = status\n } else {\n where.status = { $ne: 'dismissed' }\n }\n\n if (since) {\n const sinceDate = new Date(since)\n if (!isNaN(sinceDate.getTime())) {\n where.createdAt = { $gte: sinceDate }\n }\n }\n\n const offset = (page - 1) * pageSize\n\n const [items, total] = await Promise.all([\n em.find(Notification, where, {\n orderBy: { createdAt: 'DESC' },\n limit: pageSize,\n offset,\n }),\n em.count(Notification, where),\n ])\n\n return NextResponse.json({\n ok: true,\n items: items.map(toNotificationDto),\n total,\n page,\n pageSize,\n })\n}\n\nconst notificationDtoSchema = z.object({\n id: z.string().uuid(),\n type: z.string(),\n title: z.string(),\n body: z.string().nullable().optional(),\n titleKey: z.string().nullable().optional(),\n bodyKey: z.string().nullable().optional(),\n titleVariables: z.record(z.string(), z.string()).nullable().optional(),\n bodyVariables: z.record(z.string(), z.string()).nullable().optional(),\n icon: z.string().nullable().optional(),\n severity: z.enum(['info', 'warning', 'success', 'error']),\n status: z.enum(['unread', 'read', 'actioned', 'dismissed']),\n actions: z.array(z.object({\n id: z.string(),\n label: z.string(),\n labelKey: z.string().optional(),\n variant: z.string().optional(),\n icon: z.string().optional(),\n })),\n primaryActionId: z.string().optional(),\n sourceModule: z.string().nullable().optional(),\n sourceEntityType: z.string().nullable().optional(),\n sourceEntityId: z.string().nullable().optional(),\n linkHref: z.string().nullable().optional(),\n createdAt: z.string().datetime(),\n readAt: z.string().datetime().nullable(),\n actionTaken: z.string().nullable().optional(),\n})\n\nconst listResponseSchema = z.object({\n ok: z.literal(true),\n items: z.array(notificationDtoSchema),\n total: z.number(),\n page: z.number(),\n pageSize: z.number(),\n})\n\nconst errorSchema = z.object({ ok: z.literal(false), error: z.string() })\n\nconst methodDoc: OpenApiMethodDoc = {\n summary: 'List customer notifications',\n description: 'Returns paginated notifications for the authenticated customer user. Dismissed notifications are excluded by default unless ?status=dismissed is specified.',\n tags: ['Customer Portal'],\n responses: [{ status: 200, description: 'Notification list', schema: listResponseSchema }],\n errors: [{ status: 401, description: 'Not authenticated', schema: errorSchema }],\n}\n\nexport const openApi: OpenApiRouteDoc = {\n summary: 'Customer notifications',\n methods: { GET: methodDoc },\n}\n"],
5
+ "mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAElB,SAAS,kCAAkC;AAC3C,SAAS,uCAAuC;AAChD,SAAS,8BAA8B;AACvC,SAAS,oBAAoB;AAC7B,SAAS,yBAAyB;AAE3B,MAAM,WAAqD,EAAE,aAAa,MAAM;AAEvF,eAAsB,IAAI,KAAc;AACtC,QAAM,OAAO,MAAM,2BAA2B,GAAG;AACjD,MAAI,CAAC,MAAM;AACT,WAAO,aAAa,KAAK,EAAE,IAAI,OAAO,OAAO,0BAA0B,GAAG,EAAE,QAAQ,IAAI,CAAC;AAAA,EAC3F;AAEA,QAAM,MAAM,IAAI,IAAI,IAAI,GAAG;AAC3B,QAAM,OAAO,KAAK,IAAI,GAAG,SAAS,IAAI,aAAa,IAAI,MAAM,KAAK,KAAK,EAAE,KAAK,CAAC;AAC/E,QAAM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AE,SAAS;AAAA,EACvC,aAAa,EAAE,OAAO,EAAE,SAAS,EAAE,SAAS;AAC9C,CAAC;AAED,MAAM,qBAAqB,EAAE,OAAO;AAAA,EAClC,IAAI,EAAE,QAAQ,IAAI;AAAA,EAClB,OAAO,EAAE,MAAM,qBAAqB;AAAA,EACpC,OAAO,EAAE,OAAO;AAAA,EAChB,MAAM,EAAE,OAAO;AAAA,EACf,UAAU,EAAE,OAAO;AACrB,CAAC;AAED,MAAM,cAAc,EAAE,OAAO,EAAE,IAAI,EAAE,QAAQ,KAAK,GAAG,OAAO,EAAE,OAAO,EAAE,CAAC;AAExE,MAAM,YAA8B;AAAA,EAClC,SAAS;AAAA,EACT,aAAa;AAAA,EACb,MAAM,CAAC,iBAAiB;AAAA,EACxB,WAAW,CAAC,EAAE,QAAQ,KAAK,aAAa,qBAAqB,QAAQ,mBAAmB,CAAC;AAAA,EACzF,QAAQ,CAAC,EAAE,QAAQ,KAAK,aAAa,qBAAqB,QAAQ,YAAY,CAAC;AACjF;AAEO,MAAM,UAA2B;AAAA,EACtC,SAAS;AAAA,EACT,SAAS,EAAE,KAAK,UAAU;AAC5B;",
6
6
  "names": []
7
7
  }
@@ -1,4 +1,12 @@
1
1
  import { findOneWithDecryption } from "@open-mercato/shared/lib/encryption/find";
2
+ import { isRegisteredModuleEntity } from "./moduleEntityRegistration.js";
3
+ async function getRegisteredCustomerEntity(em) {
4
+ const { CustomerEntity } = await import("@open-mercato/core/modules/customers/data/entities");
5
+ return isRegisteredModuleEntity(em, CustomerEntity, "customers.CustomerEntity") ? CustomerEntity : null;
6
+ }
7
+ async function isCustomerEntityRegistered(em) {
8
+ return await getRegisteredCustomerEntity(em) !== null;
9
+ }
2
10
  async function isOwnedCompanyEntity(em, customerEntityId, scope) {
3
11
  return isOwnedEntityOfKind(em, customerEntityId, "company", scope);
4
12
  }
@@ -7,6 +15,7 @@ async function isOwnedPersonEntity(em, personEntityId, scope) {
7
15
  }
8
16
  async function resolveOwnedCompanyForPerson(em, personEntityId, scope) {
9
17
  const { CustomerPersonProfile } = await import("@open-mercato/core/modules/customers/data/entities");
18
+ if (!isRegisteredModuleEntity(em, CustomerPersonProfile, "customers.CustomerPersonProfile")) return null;
10
19
  const profile = await em.findOne(CustomerPersonProfile, {
11
20
  entity: personEntityId,
12
21
  tenantId: scope.tenantId,
@@ -24,7 +33,8 @@ function readCompanyEntityId(profile) {
24
33
  return typeof id === "string" ? id : null;
25
34
  }
26
35
  async function isOwnedEntityOfKind(em, entityId, kind, scope) {
27
- const { CustomerEntity } = await import("@open-mercato/core/modules/customers/data/entities");
36
+ const CustomerEntity = await getRegisteredCustomerEntity(em);
37
+ if (!CustomerEntity) return false;
28
38
  const entity = await findOneWithDecryption(
29
39
  em,
30
40
  CustomerEntity,
@@ -41,6 +51,7 @@ async function isOwnedEntityOfKind(em, entityId, kind, scope) {
41
51
  return !!entity;
42
52
  }
43
53
  export {
54
+ isCustomerEntityRegistered,
44
55
  isOwnedCompanyEntity,
45
56
  isOwnedPersonEntity,
46
57
  resolveOwnedCompanyForPerson
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/customer_accounts/lib/customerEntityOwnership.ts"],
4
- "sourcesContent": ["import type { EntityManager } from '@mikro-orm/postgresql'\nimport { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\n\nexport type CustomerEntityScope = {\n tenantId: string | null | undefined\n organizationId: string | null | undefined\n}\n\n/**\n * Confirms that a caller-supplied `customerEntityId` (the CRM company FK linked\n * onto a customer user) exists, is a company, is not soft-deleted, and belongs\n * to the caller's tenant and organization.\n *\n * Without this check an admin in org A could pass a company UUID from org B in\n * the same tenant and cross-link a customer user into another org's portal\n * context (#2693). The lookup is org-scoped to match how `CustomerEntity` rows\n * are created and listed.\n */\nexport async function isOwnedCompanyEntity(\n em: EntityManager,\n customerEntityId: string,\n scope: CustomerEntityScope,\n): Promise<boolean> {\n return isOwnedEntityOfKind(em, customerEntityId, 'company', scope)\n}\n\n/**\n * Confirms that a caller-supplied `personEntityId` (the CRM person FK linked\n * onto a customer user) exists, is a person, is not soft-deleted, and belongs\n * to the caller's tenant and organization.\n *\n * This is the symmetric guard to {@link isOwnedCompanyEntity}: the person FK is\n * copied onto the customer user on accept and short-circuits CRM auto-linking,\n * so an unvalidated id would permanently cross-link a portal user to another\n * org's person (the #4362/#2693 class of bug, on the person side).\n */\nexport async function isOwnedPersonEntity(\n em: EntityManager,\n personEntityId: string,\n scope: CustomerEntityScope,\n): Promise<boolean> {\n return isOwnedEntityOfKind(em, personEntityId, 'person', scope)\n}\n\n/**\n * Resolves the CRM company a person belongs to, but only when both the profile\n * lookup and the company itself stay inside the given tenant/organization scope.\n * Returns null when the person has no company or that company is out of scope.\n *\n * Both the invite route and the CRM auto-link subscriber need this answer, and\n * both write the result into `customerEntityId` \u2014 the portal company scope key \u2014\n * so they must agree on what counts as an in-scope company.\n */\nexport async function resolveOwnedCompanyForPerson(\n em: EntityManager,\n personEntityId: string,\n scope: CustomerEntityScope,\n): Promise<string | null> {\n const { CustomerPersonProfile } = await import('@open-mercato/core/modules/customers/data/entities')\n const profile = await em.findOne(CustomerPersonProfile as any, {\n entity: personEntityId,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n } as any)\n const candidate = readCompanyEntityId(profile)\n if (!candidate) return null\n return (await isOwnedCompanyEntity(em, candidate, scope)) ? candidate : null\n}\n\n/**\n * `CustomerPersonProfile.company` is a relation on `company_entity_id`, not a\n * scalar \u2014 MikroORM hands back either the raw id or an entity reference, never a\n * `companyEntityId` property. Reading the wrong one silently yields undefined and\n * turns every company recovery into a clear.\n */\nfunction readCompanyEntityId(profile: unknown): string | null {\n const company = (profile as { company?: unknown } | null | undefined)?.company\n if (!company) return null\n if (typeof company === 'string') return company\n const id = (company as { id?: unknown }).id\n return typeof id === 'string' ? id : null\n}\n\nasync function isOwnedEntityOfKind(\n em: EntityManager,\n entityId: string,\n kind: 'company' | 'person',\n scope: CustomerEntityScope,\n): Promise<boolean> {\n const { CustomerEntity } = await import('@open-mercato/core/modules/customers/data/entities')\n const entity = await findOneWithDecryption(\n em,\n CustomerEntity,\n {\n id: entityId,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n kind,\n deletedAt: null,\n } as any,\n undefined,\n { tenantId: scope.tenantId, organizationId: scope.organizationId },\n )\n return !!entity\n}\n"],
5
- "mappings": "AACA,SAAS,6BAA6B;AAiBtC,eAAsB,qBACpB,IACA,kBACA,OACkB;AAClB,SAAO,oBAAoB,IAAI,kBAAkB,WAAW,KAAK;AACnE;AAYA,eAAsB,oBACpB,IACA,gBACA,OACkB;AAClB,SAAO,oBAAoB,IAAI,gBAAgB,UAAU,KAAK;AAChE;AAWA,eAAsB,6BACpB,IACA,gBACA,OACwB;AACxB,QAAM,EAAE,sBAAsB,IAAI,MAAM,OAAO,oDAAoD;AACnG,QAAM,UAAU,MAAM,GAAG,QAAQ,uBAA8B;AAAA,IAC7D,QAAQ;AAAA,IACR,UAAU,MAAM;AAAA,IAChB,gBAAgB,MAAM;AAAA,EACxB,CAAQ;AACR,QAAM,YAAY,oBAAoB,OAAO;AAC7C,MAAI,CAAC,UAAW,QAAO;AACvB,SAAQ,MAAM,qBAAqB,IAAI,WAAW,KAAK,IAAK,YAAY;AAC1E;AAQA,SAAS,oBAAoB,SAAiC;AAC5D,QAAM,UAAW,SAAsD;AACvE,MAAI,CAAC,QAAS,QAAO;AACrB,MAAI,OAAO,YAAY,SAAU,QAAO;AACxC,QAAM,KAAM,QAA6B;AACzC,SAAO,OAAO,OAAO,WAAW,KAAK;AACvC;AAEA,eAAe,oBACb,IACA,UACA,MACA,OACkB;AAClB,QAAM,EAAE,eAAe,IAAI,MAAM,OAAO,oDAAoD;AAC5F,QAAM,SAAS,MAAM;AAAA,IACnB;AAAA,IACA;AAAA,IACA;AAAA,MACE,IAAI;AAAA,MACJ,UAAU,MAAM;AAAA,MAChB,gBAAgB,MAAM;AAAA,MACtB;AAAA,MACA,WAAW;AAAA,IACb;AAAA,IACA;AAAA,IACA,EAAE,UAAU,MAAM,UAAU,gBAAgB,MAAM,eAAe;AAAA,EACnE;AACA,SAAO,CAAC,CAAC;AACX;",
4
+ "sourcesContent": ["import type { EntityManager } from '@mikro-orm/postgresql'\nimport { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { isRegisteredModuleEntity } from './moduleEntityRegistration'\n\nexport type CustomerEntityScope = {\n tenantId: string | null | undefined\n organizationId: string | null | undefined\n}\n\nasync function getRegisteredCustomerEntity(em: EntityManager) {\n const { CustomerEntity } = await import('@open-mercato/core/modules/customers/data/entities')\n return isRegisteredModuleEntity(em, CustomerEntity, 'customers.CustomerEntity') ? CustomerEntity : null\n}\n\nexport async function isCustomerEntityRegistered(em: EntityManager): Promise<boolean> {\n return (await getRegisteredCustomerEntity(em)) !== null\n}\n\n/**\n * Confirms that a caller-supplied `customerEntityId` (the CRM company FK linked\n * onto a customer user) exists, is a company, is not soft-deleted, and belongs\n * to the caller's tenant and organization.\n *\n * Without this check an admin in org A could pass a company UUID from org B in\n * the same tenant and cross-link a customer user into another org's portal\n * context (#2693). The lookup is org-scoped to match how `CustomerEntity` rows\n * are created and listed.\n */\nexport async function isOwnedCompanyEntity(\n em: EntityManager,\n customerEntityId: string,\n scope: CustomerEntityScope,\n): Promise<boolean> {\n return isOwnedEntityOfKind(em, customerEntityId, 'company', scope)\n}\n\n/**\n * Confirms that a caller-supplied `personEntityId` (the CRM person FK linked\n * onto a customer user) exists, is a person, is not soft-deleted, and belongs\n * to the caller's tenant and organization.\n *\n * This is the symmetric guard to {@link isOwnedCompanyEntity}: the person FK is\n * copied onto the customer user on accept and short-circuits CRM auto-linking,\n * so an unvalidated id would permanently cross-link a portal user to another\n * org's person (the #4362/#2693 class of bug, on the person side).\n */\nexport async function isOwnedPersonEntity(\n em: EntityManager,\n personEntityId: string,\n scope: CustomerEntityScope,\n): Promise<boolean> {\n return isOwnedEntityOfKind(em, personEntityId, 'person', scope)\n}\n\n/**\n * Resolves the CRM company a person belongs to, but only when both the profile\n * lookup and the company itself stay inside the given tenant/organization scope.\n * Returns null when the person has no company or that company is out of scope.\n *\n * Both the invite route and the CRM auto-link subscriber need this answer, and\n * both write the result into `customerEntityId` \u2014 the portal company scope key \u2014\n * so they must agree on what counts as an in-scope company.\n */\nexport async function resolveOwnedCompanyForPerson(\n em: EntityManager,\n personEntityId: string,\n scope: CustomerEntityScope,\n): Promise<string | null> {\n const { CustomerPersonProfile } = await import('@open-mercato/core/modules/customers/data/entities')\n if (!isRegisteredModuleEntity(em, CustomerPersonProfile, 'customers.CustomerPersonProfile')) return null\n const profile = await em.findOne(CustomerPersonProfile as any, {\n entity: personEntityId,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n } as any)\n const candidate = readCompanyEntityId(profile)\n if (!candidate) return null\n return (await isOwnedCompanyEntity(em, candidate, scope)) ? candidate : null\n}\n\n/**\n * `CustomerPersonProfile.company` is a relation on `company_entity_id`, not a\n * scalar \u2014 MikroORM hands back either the raw id or an entity reference, never a\n * `companyEntityId` property. Reading the wrong one silently yields undefined and\n * turns every company recovery into a clear.\n */\nfunction readCompanyEntityId(profile: unknown): string | null {\n const company = (profile as { company?: unknown } | null | undefined)?.company\n if (!company) return null\n if (typeof company === 'string') return company\n const id = (company as { id?: unknown }).id\n return typeof id === 'string' ? id : null\n}\n\nasync function isOwnedEntityOfKind(\n em: EntityManager,\n entityId: string,\n kind: 'company' | 'person',\n scope: CustomerEntityScope,\n): Promise<boolean> {\n const CustomerEntity = await getRegisteredCustomerEntity(em)\n if (!CustomerEntity) return false\n const entity = await findOneWithDecryption(\n em,\n CustomerEntity,\n {\n id: entityId,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n kind,\n deletedAt: null,\n } as any,\n undefined,\n { tenantId: scope.tenantId, organizationId: scope.organizationId },\n )\n return !!entity\n}\n"],
5
+ "mappings": "AACA,SAAS,6BAA6B;AACtC,SAAS,gCAAgC;AAOzC,eAA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AA,MACtB;AAAA,MACA,WAAW;AAAA,IACb;AAAA,IACA;AAAA,IACA,EAAE,UAAU,MAAM,UAAU,gBAAgB,MAAM,eAAe;AAAA,EACnE;AACA,SAAO,CAAC,CAAC;AACX;",
6
6
  "names": []
7
7
  }
@@ -0,0 +1,8 @@
1
+ function isRegisteredModuleEntity(em, entity, qualifiedName) {
2
+ const registeredClass = em.getMetadata().find(entity)?.class;
3
+ return registeredClass === entity || registeredClass?.entityName === qualifiedName;
4
+ }
5
+ export {
6
+ isRegisteredModuleEntity
7
+ };
8
+ //# sourceMappingURL=moduleEntityRegistration.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../../src/modules/customer_accounts/lib/moduleEntityRegistration.ts"],
4
+ "sourcesContent": ["import type { EntityCtor } from '@mikro-orm/core'\nimport type { EntityManager } from '@mikro-orm/postgresql'\n\nexport function isRegisteredModuleEntity<Entity>(\n em: EntityManager,\n entity: EntityCtor<Entity>,\n qualifiedName: string,\n): boolean {\n const registeredClass: (EntityCtor<Entity> & { entityName?: string }) | undefined =\n em.getMetadata().find(entity)?.class\n return registeredClass === entity || registeredClass?.entityName === qualifiedName\n}\n"],
5
+ "mappings": "AAGO,SAAS,yBACd,IACA,QACA,eACS;AACT,QAAM,kBACJ,GAAG,YAAY,EAAE,KAAK,MAAM,GAAG;AACjC,SAAO,oBAAoB,UAAU,iBAAiB,eAAe;AACvE;",
6
+ "names": []
7
+ }
@@ -0,0 +1,9 @@
1
+ import { Notification } from "@open-mercato/core/modules/notifications/data/entities";
2
+ import { isRegisteredModuleEntity } from "./moduleEntityRegistration.js";
3
+ function arePortalNotificationsAvailable(em) {
4
+ return isRegisteredModuleEntity(em, Notification, "notifications.Notification");
5
+ }
6
+ export {
7
+ arePortalNotificationsAvailable
8
+ };
9
+ //# sourceMappingURL=portalNotificationsAvailability.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../../src/modules/customer_accounts/lib/portalNotificationsAvailability.ts"],
4
+ "sourcesContent": ["import type { EntityManager } from '@mikro-orm/postgresql'\nimport { Notification } from '@open-mercato/core/modules/notifications/data/entities'\nimport { isRegisteredModuleEntity } from './moduleEntityRegistration'\n\nexport function arePortalNotificationsAvailable(em: EntityManager): boolean {\n return isRegisteredModuleEntity(em, Notification, 'notifications.Notification')\n}\n"],
5
+ "mappings": "AACA,SAAS,oBAAoB;AAC7B,SAAS,gCAAgC;AAElC,SAAS,gCAAgC,IAA4B;AAC1E,SAAO,yBAAyB,IAAI,cAAc,4BAA4B;AAChF;",
6
+ "names": []
7
+ }
@@ -397,7 +397,7 @@ async function resolveFeatureCheckContext({
397
397
  }) {
398
398
  const boundFeatureScope = auth?.sub && selectedId === void 0 ? getFeatureScopeForRequest(request, auth.sub, tenantId) : null;
399
399
  let scope = boundFeatureScope ? boundFeatureScope.scope : await resolveOrganizationScopeForRequest({ container, auth, request, selectedId, tenantId });
400
- const organizationId = boundFeatureScope ? boundFeatureScope.organizationId : resolveFeatureCheckOrganizationId(scope, auth);
400
+ let organizationId = boundFeatureScope ? boundFeatureScope.organizationId : resolveFeatureCheckOrganizationId(scope, auth);
401
401
  if (auth?.sub && request && scope.selectedId === null && scope.tenantId && Array.isArray(requiredFeatures) && requiredFeatures.length > 0) {
402
402
  const em = container.resolve("em");
403
403
  const rbac = container.resolve("rbacService");
@@ -426,7 +426,7 @@ async function resolveFeatureCheckContext({
426
426
  );
427
427
  const approvedOrganizationIds = Array.from(new Set(
428
428
  featureOrganizationIds.filter((featureOrganizationId) => candidateOrganizationIds.has(featureOrganizationId))
429
- ));
429
+ )).sort((left, right) => left.localeCompare(right));
430
430
  scope = {
431
431
  ...scope,
432
432
  selectedId: null,
@@ -434,6 +434,7 @@ async function resolveFeatureCheckContext({
434
434
  allowedIds: approvedOrganizationIds,
435
435
  tenantId: scope.tenantId
436
436
  };
437
+ if (!organizationId) organizationId = resolveFeatureCheckOrganizationId(scope, auth);
437
438
  }
438
439
  bindFeatureScopeToRequest(request, { userId: auth.sub, scope, organizationId });
439
440
  }