@open-mercato/core 0.6.6-develop.6542.1.fee3e68aa6 → 0.6.6-develop.6551.1.1511bfa890
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.turbo/turbo-build.log +2 -2
- package/dist/generated/entities/gateway_session_initialization/index.js +23 -0
- package/dist/generated/entities/gateway_session_initialization/index.js.map +7 -0
- package/dist/generated/entities.ids.generated.js +1 -0
- package/dist/generated/entities.ids.generated.js.map +2 -2
- package/dist/generated/entity-fields-registry.js +12 -0
- package/dist/generated/entity-fields-registry.js.map +2 -2
- package/dist/modules/api_keys/api/keys/route.js +7 -4
- package/dist/modules/api_keys/api/keys/route.js.map +2 -2
- package/dist/modules/attachments/components/AttachmentContentPreview.js +6 -35
- package/dist/modules/attachments/components/AttachmentContentPreview.js.map +2 -2
- package/dist/modules/audit_logs/backend/audit-logs/page.js +14 -24
- package/dist/modules/audit_logs/backend/audit-logs/page.js.map +2 -2
- package/dist/modules/auth/api/autologin.js +85 -0
- package/dist/modules/auth/api/autologin.js.map +7 -0
- package/dist/modules/auth/lib/autologin.js +19 -0
- package/dist/modules/auth/lib/autologin.js.map +7 -0
- package/dist/modules/customer_accounts/api/admin/roles/[id]/acl.js +1 -0
- package/dist/modules/customer_accounts/api/admin/roles/[id]/acl.js.map +2 -2
- package/dist/modules/customer_accounts/api/admin/roles/[id].js +17 -3
- package/dist/modules/customer_accounts/api/admin/roles/[id].js.map +2 -2
- package/dist/modules/customer_accounts/api/portal/users/[id]/roles.js +6 -1
- package/dist/modules/customer_accounts/api/portal/users/[id]/roles.js.map +2 -2
- package/dist/modules/customer_accounts/api/portal/users-invite.js +6 -1
- package/dist/modules/customer_accounts/api/portal/users-invite.js.map +2 -2
- package/dist/modules/customer_accounts/services/customerInvitationService.js +1 -0
- package/dist/modules/customer_accounts/services/customerInvitationService.js.map +2 -2
- package/dist/modules/customer_accounts/services/customerRbacService.js +6 -1
- package/dist/modules/customer_accounts/services/customerRbacService.js.map +2 -2
- package/dist/modules/customers/backend/customers/deals/pipeline/components/ViewTabsRow.js +2 -2
- package/dist/modules/customers/backend/customers/deals/pipeline/components/ViewTabsRow.js.map +2 -2
- package/dist/modules/customers/components/detail/CompanyDetailTabs.js +27 -37
- package/dist/modules/customers/components/detail/CompanyDetailTabs.js.map +2 -2
- package/dist/modules/customers/components/detail/DealDetailTabs.js +23 -35
- package/dist/modules/customers/components/detail/DealDetailTabs.js.map +2 -2
- package/dist/modules/customers/components/detail/DetailTabsLayout.js +6 -21
- package/dist/modules/customers/components/detail/DetailTabsLayout.js.map +2 -2
- package/dist/modules/customers/components/detail/MobilePersonDetail.js +26 -32
- package/dist/modules/customers/components/detail/MobilePersonDetail.js.map +2 -2
- package/dist/modules/customers/components/detail/PersonDetailTabs.js +29 -39
- package/dist/modules/customers/components/detail/PersonDetailTabs.js.map +2 -2
- package/dist/modules/dictionaries/commands/entries.js +7 -14
- package/dist/modules/dictionaries/commands/entries.js.map +2 -2
- package/dist/modules/dictionaries/commands/entry-operations.js +7 -16
- package/dist/modules/dictionaries/commands/entry-operations.js.map +2 -2
- package/dist/modules/dictionaries/commands/factory.js +9 -3
- package/dist/modules/dictionaries/commands/factory.js.map +2 -2
- package/dist/modules/feature_toggles/api/check/boolean/route.js +0 -14
- package/dist/modules/feature_toggles/api/check/boolean/route.js.map +2 -2
- package/dist/modules/feature_toggles/defaults.json +8 -0
- package/dist/modules/integrations/backend/integrations/[id]/page.js +9 -80
- package/dist/modules/integrations/backend/integrations/[id]/page.js.map +2 -2
- package/dist/modules/payment_gateways/data/entities.js +45 -0
- package/dist/modules/payment_gateways/data/entities.js.map +2 -2
- package/dist/modules/payment_gateways/lib/gateway-service.js +173 -38
- package/dist/modules/payment_gateways/lib/gateway-service.js.map +3 -3
- package/dist/modules/payment_gateways/lib/session-idempotency.js +104 -0
- package/dist/modules/payment_gateways/lib/session-idempotency.js.map +7 -0
- package/dist/modules/payment_gateways/migrations/Migration20260709220938_payment_gateways.js +11 -0
- package/dist/modules/payment_gateways/migrations/Migration20260709220938_payment_gateways.js.map +7 -0
- package/dist/modules/planner/backend/planner/availability-rulesets/[id]/page.js +16 -14
- package/dist/modules/planner/backend/planner/availability-rulesets/[id]/page.js.map +2 -2
- package/dist/modules/planner/components/AvailabilityRulesEditor.js +18 -30
- package/dist/modules/planner/components/AvailabilityRulesEditor.js.map +2 -2
- package/dist/modules/resources/backend/resources/resources/[id]/page.js +24 -24
- package/dist/modules/resources/backend/resources/resources/[id]/page.js.map +2 -2
- package/dist/modules/sales/backend/sales/channels/create/page.js +6 -0
- package/dist/modules/sales/backend/sales/channels/create/page.js.map +2 -2
- package/dist/modules/sales/backend/sales/channels/create/page.meta.js +2 -0
- package/dist/modules/sales/backend/sales/channels/create/page.meta.js.map +2 -2
- package/dist/modules/sales/backend/sales/channels/offers/page.js +6 -0
- package/dist/modules/sales/backend/sales/channels/offers/page.js.map +2 -2
- package/dist/modules/sales/backend/sales/channels/offers/page.meta.js +2 -0
- package/dist/modules/sales/backend/sales/channels/offers/page.meta.js.map +2 -2
- package/dist/modules/sales/backend/sales/channels/page.js +6 -0
- package/dist/modules/sales/backend/sales/channels/page.js.map +2 -2
- package/dist/modules/sales/backend/sales/channels/page.meta.js +2 -0
- package/dist/modules/sales/backend/sales/channels/page.meta.js.map +2 -2
- package/dist/modules/sales/backend/sales/documents/[id]/page.js +6 -4
- package/dist/modules/sales/backend/sales/documents/[id]/page.js.map +2 -2
- package/dist/modules/sales/components/SalesChannelsDisabledNotice.js +15 -0
- package/dist/modules/sales/components/SalesChannelsDisabledNotice.js.map +7 -0
- package/dist/modules/sales/components/documents/SalesDocumentForm.js +7 -3
- package/dist/modules/sales/components/documents/SalesDocumentForm.js.map +2 -2
- package/dist/modules/sales/components/documents/SalesDocumentsTable.js +10 -8
- package/dist/modules/sales/components/documents/SalesDocumentsTable.js.map +2 -2
- package/dist/modules/sales/components/useSalesChannelsEnabled.js +44 -0
- package/dist/modules/sales/components/useSalesChannelsEnabled.js.map +7 -0
- package/dist/modules/sales/lib/salesChannelsToggle.js +18 -0
- package/dist/modules/sales/lib/salesChannelsToggle.js.map +7 -0
- package/dist/modules/sales/lib/salesChannelsToggleId.js +5 -0
- package/dist/modules/sales/lib/salesChannelsToggleId.js.map +7 -0
- package/dist/modules/staff/backend/staff/team-members/[id]/page.js +22 -25
- package/dist/modules/staff/backend/staff/team-members/[id]/page.js.map +2 -2
- package/dist/modules/staff/backend/staff/teams/[id]/edit/page.js +12 -14
- package/dist/modules/staff/backend/staff/teams/[id]/edit/page.js.map +2 -2
- package/dist/modules/staff/lib/timesheets-projects-ui/SavedViewTabs.js +10 -29
- package/dist/modules/staff/lib/timesheets-projects-ui/SavedViewTabs.js.map +2 -2
- package/dist/modules/sync_excel/lib/adapters/customers.js +19 -20
- package/dist/modules/sync_excel/lib/adapters/customers.js.map +2 -2
- package/dist/modules/sync_excel/lib/parser.js +185 -0
- package/dist/modules/sync_excel/lib/parser.js.map +2 -2
- package/dist/modules/sync_excel/lib/upload-storage.js +20 -1
- package/dist/modules/sync_excel/lib/upload-storage.js.map +2 -2
- package/generated/entities/gateway_session_initialization/index.ts +10 -0
- package/generated/entities.ids.generated.ts +1 -0
- package/generated/entity-fields-registry.ts +12 -0
- package/package.json +7 -7
- package/src/modules/api_keys/api/keys/route.ts +9 -4
- package/src/modules/attachments/components/AttachmentContentPreview.tsx +9 -44
- package/src/modules/audit_logs/backend/audit-logs/page.tsx +12 -22
- package/src/modules/auth/api/autologin.ts +100 -0
- package/src/modules/auth/lib/autologin.ts +36 -0
- package/src/modules/customer_accounts/api/admin/roles/[id]/acl.ts +1 -0
- package/src/modules/customer_accounts/api/admin/roles/[id].ts +17 -3
- package/src/modules/customer_accounts/api/portal/users/[id]/roles.ts +6 -1
- package/src/modules/customer_accounts/api/portal/users-invite.ts +6 -1
- package/src/modules/customer_accounts/services/customerInvitationService.ts +1 -0
- package/src/modules/customer_accounts/services/customerRbacService.ts +9 -2
- package/src/modules/customers/backend/customers/deals/pipeline/components/ViewTabsRow.tsx +6 -2
- package/src/modules/customers/components/detail/CompanyDetailTabs.tsx +27 -49
- package/src/modules/customers/components/detail/DealDetailTabs.tsx +24 -49
- package/src/modules/customers/components/detail/DetailTabsLayout.tsx +13 -24
- package/src/modules/customers/components/detail/MobilePersonDetail.tsx +25 -31
- package/src/modules/customers/components/detail/PersonDetailTabs.tsx +29 -50
- package/src/modules/dictionaries/commands/entries.ts +7 -16
- package/src/modules/dictionaries/commands/entry-operations.ts +8 -18
- package/src/modules/dictionaries/commands/factory.ts +8 -2
- package/src/modules/feature_toggles/api/check/boolean/route.ts +0 -15
- package/src/modules/feature_toggles/defaults.json +8 -0
- package/src/modules/integrations/backend/integrations/[id]/page.tsx +16 -59
- package/src/modules/payment_gateways/data/entities.ts +39 -0
- package/src/modules/payment_gateways/lib/gateway-service.ts +211 -40
- package/src/modules/payment_gateways/lib/session-idempotency.ts +142 -0
- package/src/modules/payment_gateways/migrations/.snapshot-open-mercato.json +236 -0
- package/src/modules/payment_gateways/migrations/Migration20260709220938_payment_gateways.ts +10 -0
- package/src/modules/planner/backend/planner/availability-rulesets/[id]/page.tsx +14 -20
- package/src/modules/planner/components/AvailabilityRulesEditor.tsx +16 -34
- package/src/modules/resources/backend/resources/resources/[id]/page.tsx +27 -37
- package/src/modules/sales/backend/sales/channels/create/page.meta.ts +3 -0
- package/src/modules/sales/backend/sales/channels/create/page.tsx +7 -0
- package/src/modules/sales/backend/sales/channels/offers/page.meta.ts +3 -0
- package/src/modules/sales/backend/sales/channels/offers/page.tsx +7 -0
- package/src/modules/sales/backend/sales/channels/page.meta.ts +4 -0
- package/src/modules/sales/backend/sales/channels/page.tsx +7 -0
- package/src/modules/sales/backend/sales/documents/[id]/page.tsx +7 -5
- package/src/modules/sales/components/SalesChannelsDisabledNotice.tsx +21 -0
- package/src/modules/sales/components/documents/SalesDocumentForm.tsx +7 -3
- package/src/modules/sales/components/documents/SalesDocumentsTable.tsx +10 -8
- package/src/modules/sales/components/useSalesChannelsEnabled.ts +59 -0
- package/src/modules/sales/i18n/de.json +1 -0
- package/src/modules/sales/i18n/en.json +1 -0
- package/src/modules/sales/i18n/es.json +1 -0
- package/src/modules/sales/i18n/pl.json +1 -0
- package/src/modules/sales/lib/salesChannelsToggle.ts +26 -0
- package/src/modules/sales/lib/salesChannelsToggleId.ts +1 -0
- package/src/modules/staff/backend/staff/team-members/[id]/page.tsx +25 -34
- package/src/modules/staff/backend/staff/teams/[id]/edit/page.tsx +11 -17
- package/src/modules/staff/lib/timesheets-projects-ui/SavedViewTabs.tsx +11 -28
- package/src/modules/sync_excel/lib/adapters/customers.ts +20 -22
- package/src/modules/sync_excel/lib/parser.ts +245 -0
- package/src/modules/sync_excel/lib/upload-storage.ts +23 -1
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../../../../src/modules/customer_accounts/api/admin/roles/%5Bid%5D/acl.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 { CustomerRole, CustomerRoleAcl } from '@open-mercato/core/modules/customer_accounts/data/entities'\nimport { CustomerRbacService } from '@open-mercato/core/modules/customer_accounts/services/customerRbacService'\nimport { updateRoleAclSchema } from '@open-mercato/core/modules/customer_accounts/data/validators'\nimport { enforceCommandOptimisticLock } from '@open-mercato/shared/lib/crud/optimistic-lock-command'\nimport { isCrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport {\n runCrudMutationGuardAfterSuccess,\n validateCrudMutationGuard,\n} from '@open-mercato/shared/lib/crud/mutation-guard'\n\nexport const metadata = {}\n\nconst ROLE_RESOURCE_KIND = 'customer_accounts.role'\n\nexport async function PUT(req: Request, { params }: { params: { id: string } }) {\n const auth = await getAuthFromRequest(req)\n if (!auth || !auth.tenantId) {\n return NextResponse.json({ ok: false, error: 'Authentication required' }, { status: 401 })\n }\n const tenantId = auth.tenantId\n\n const container = await createRequestContainer()\n const rbacService = container.resolve('rbacService') as RbacService\n const hasAccess = await rbacService.userHasAllFeatures(auth.sub, ['customer_accounts.roles.manage'], { 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 = updateRoleAclSchema.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 role = await em.findOne(CustomerRole, {\n id: params.id,\n tenantId,\n deletedAt: null,\n })\n if (!role) {\n return NextResponse.json({ ok: false, error: 'Role not found' }, { status: 404 })\n }\n\n // The ACL is part of the role aggregate: the role-edit screen loads and saves\n // the role and its permissions together. Guard the write against the parent\n // role's `updatedAt` so two admins editing the same role cannot silently\n // overwrite each other's permission changes (#3194). Strictly additive \u2014 when\n // the client sends no expected-version header the helper is a no-op.\n try {\n enforceCommandOptimisticLock({\n resourceKind: ROLE_RESOURCE_KIND,\n resourceId: role.id,\n current: role.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 guardResult = await validateCrudMutationGuard(container, {\n tenantId,\n organizationId: auth.orgId,\n userId: auth.sub,\n resourceKind: ROLE_RESOURCE_KIND,\n resourceId: role.id,\n operation: 'update',\n requestMethod: req.method,\n requestHeaders: req.headers,\n mutationPayload: parsed.data,\n })\n if (guardResult && !guardResult.ok) {\n return NextResponse.json(guardResult.body, { status: guardResult.status })\n }\n\n const acl = await em.findOne(CustomerRoleAcl, {\n role: role.id as any,\n tenantId,\n })\n\n if (acl) {\n await em.nativeUpdate(CustomerRoleAcl, { id: acl.id }, {\n featuresJson: parsed.data.features,\n isPortalAdmin: parsed.data.isPortalAdmin ?? acl.isPortalAdmin,\n })\n } else {\n const newAcl = em.create(CustomerRoleAcl, {\n role,\n tenantId,\n featuresJson: parsed.data.features,\n isPortalAdmin: parsed.data.isPortalAdmin ?? false,\n createdAt: new Date(),\n } as any)\n em.persist(newAcl)\n await em.flush()\n }\n\n // Bump the aggregate version so a stale role-edit screen (which holds the role's\n // pre-edit `updatedAt`) cannot save old permission arrays afterwards. `nativeUpdate`\n // bypasses MikroORM's `onUpdate` hook, so set it explicitly.\n const nextUpdatedAt = new Date()\n await em.nativeUpdate(CustomerRole, { id: role.id }, { updatedAt: nextUpdatedAt })\n\n const customerRbacService = container.resolve('customerRbacService') as CustomerRbacService\n await customerRbacService.invalidateRoleCache(role.id)\n\n if (guardResult?.ok && guardResult.shouldRunAfterSuccess) {\n await runCrudMutationGuardAfterSuccess(container, {\n tenantId,\n organizationId: auth.orgId,\n userId: auth.sub,\n resourceKind: ROLE_RESOURCE_KIND,\n resourceId: role.id,\n operation: 'update',\n requestMethod: req.method,\n requestHeaders: req.headers,\n metadata: guardResult.metadata ?? null,\n })\n }\n\n return NextResponse.json({ ok: true, updatedAt: nextUpdatedAt.toISOString() })\n}\n\nconst successSchema = z.object({ ok: z.literal(true), updatedAt: z.string().datetime() })\nconst errorSchema = z.object({ ok: z.literal(false), error: z.string() })\n\nconst methodDoc: OpenApiMethodDoc = {\n summary: 'Update customer role ACL (admin)',\n description: 'Updates the ACL (features and portal admin flag) for a customer role. Invalidates RBAC cache after update.',\n tags: ['Customer Accounts Admin'],\n requestBody: { schema: updateRoleAclSchema },\n responses: [{ status: 200, description: 'ACL updated', schema: successSchema }],\n errors: [\n { status: 400, description: 'Validation failed', schema: errorSchema },\n { status: 401, description: 'Not authenticated', schema: errorSchema },\n { status: 403, description: 'Insufficient permissions', schema: errorSchema },\n { status: 404, description: 'Role not found', schema: errorSchema },\n { status: 409, description: 'Stale ACL write (optimistic-lock conflict)', schema: errorSchema },\n ],\n}\n\nexport const openApi: OpenApiRouteDoc = {\n summary: 'Update customer role ACL (admin)',\n pathParams: z.object({ id: z.string().uuid() }),\n methods: { PUT: methodDoc },\n}\n"],
|
|
5
|
-
"mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAElB,SAAS,0BAA0B;AACnC,SAAS,8BAA8B;AAEvC,SAAS,cAAc,uBAAuB;AAE9C,SAAS,2BAA2B;AACpC,SAAS,oCAAoC;AAC7C,SAAS,uBAAuB;AAChC;AAAA,EACE;AAAA,EACA;AAAA,OACK;AAEA,MAAM,WAAW,CAAC;AAEzB,MAAM,qBAAqB;AAE3B,eAAsB,IAAI,KAAc,EAAE,OAAO,GAA+B;AAC9E,QAAM,OAAO,MAAM,mBAAmB,GAAG;AACzC,MAAI,CAAC,QAAQ,CAAC,KAAK,UAAU;AAC3B,WAAO,aAAa,KAAK,EAAE,IAAI,OAAO,OAAO,0BAA0B,GAAG,EAAE,QAAQ,IAAI,CAAC;AAAA,EAC3F;AACA,QAAM,WAAW,KAAK;AAEtB,QAAM,YAAY,MAAM,uBAAuB;AAC/C,QAAM,cAAc,UAAU,QAAQ,aAAa;AACnD,QAAM,YAAY,MAAM,YAAY,mBAAmB,KAAK,KAAK,CAAC,gCAAgC,GAAG,EAAE,UAAU,gBAAgB,KAAK,MAAM,CAAC;AAC7I,MAAI,CAAC,WAAW;AACd,WAAO,aAAa,KAAK,EAAE,IAAI,OAAO,OAAO,2BAA2B,GAAG,EAAE,QAAQ,IAAI,CAAC;AAAA,EAC5F;AAEA,MAAI;AACJ,MAAI;AACF,WAAO,MAAM,IAAI,KAAK;AAAA,EACxB,QAAQ;AACN,WAAO,aAAa,KAAK,EAAE,IAAI,OAAO,OAAO,uBAAuB,G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O,EAAE,CAAC;AAExE,MAAM,YAA8B;AAAA,EAClC,SAAS;AAAA,EACT,aAAa;AAAA,EACb,MAAM,CAAC,yBAAyB;AAAA,EAChC,aAAa,EAAE,QAAQ,oBAAoB;AAAA,EAC3C,WAAW,CAAC,EAAE,QAAQ,KAAK,aAAa,eAAe,QAAQ,cAAc,CAAC;AAAA,EAC9E,QAAQ;AAAA,IACN,EAAE,QAAQ,KAAK,aAAa,qBAAqB,QAAQ,YAAY;AAAA,IACrE,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,IAClE,EAAE,QAAQ,KAAK,aAAa,8CAA8C,QAAQ,YAAY;AAAA,EAChG;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 { 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 { CustomerRole, CustomerRoleAcl } from '@open-mercato/core/modules/customer_accounts/data/entities'\nimport { CustomerRbacService } from '@open-mercato/core/modules/customer_accounts/services/customerRbacService'\nimport { updateRoleAclSchema } from '@open-mercato/core/modules/customer_accounts/data/validators'\nimport { enforceCommandOptimisticLock } from '@open-mercato/shared/lib/crud/optimistic-lock-command'\nimport { isCrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport {\n runCrudMutationGuardAfterSuccess,\n validateCrudMutationGuard,\n} from '@open-mercato/shared/lib/crud/mutation-guard'\n\nexport const metadata = {}\n\nconst ROLE_RESOURCE_KIND = 'customer_accounts.role'\n\nexport async function PUT(req: Request, { params }: { params: { id: string } }) {\n const auth = await getAuthFromRequest(req)\n if (!auth || !auth.tenantId) {\n return NextResponse.json({ ok: false, error: 'Authentication required' }, { status: 401 })\n }\n const tenantId = auth.tenantId\n\n const container = await createRequestContainer()\n const rbacService = container.resolve('rbacService') as RbacService\n const hasAccess = await rbacService.userHasAllFeatures(auth.sub, ['customer_accounts.roles.manage'], { 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 = updateRoleAclSchema.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 role = await em.findOne(CustomerRole, {\n id: params.id,\n tenantId,\n organizationId: auth.orgId,\n deletedAt: null,\n })\n if (!role) {\n return NextResponse.json({ ok: false, error: 'Role not found' }, { status: 404 })\n }\n\n // The ACL is part of the role aggregate: the role-edit screen loads and saves\n // the role and its permissions together. Guard the write against the parent\n // role's `updatedAt` so two admins editing the same role cannot silently\n // overwrite each other's permission changes (#3194). Strictly additive \u2014 when\n // the client sends no expected-version header the helper is a no-op.\n try {\n enforceCommandOptimisticLock({\n resourceKind: ROLE_RESOURCE_KIND,\n resourceId: role.id,\n current: role.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 guardResult = await validateCrudMutationGuard(container, {\n tenantId,\n organizationId: auth.orgId,\n userId: auth.sub,\n resourceKind: ROLE_RESOURCE_KIND,\n resourceId: role.id,\n operation: 'update',\n requestMethod: req.method,\n requestHeaders: req.headers,\n mutationPayload: parsed.data,\n })\n if (guardResult && !guardResult.ok) {\n return NextResponse.json(guardResult.body, { status: guardResult.status })\n }\n\n const acl = await em.findOne(CustomerRoleAcl, {\n role: role.id as any,\n tenantId,\n })\n\n if (acl) {\n await em.nativeUpdate(CustomerRoleAcl, { id: acl.id }, {\n featuresJson: parsed.data.features,\n isPortalAdmin: parsed.data.isPortalAdmin ?? acl.isPortalAdmin,\n })\n } else {\n const newAcl = em.create(CustomerRoleAcl, {\n role,\n tenantId,\n featuresJson: parsed.data.features,\n isPortalAdmin: parsed.data.isPortalAdmin ?? false,\n createdAt: new Date(),\n } as any)\n em.persist(newAcl)\n await em.flush()\n }\n\n // Bump the aggregate version so a stale role-edit screen (which holds the role's\n // pre-edit `updatedAt`) cannot save old permission arrays afterwards. `nativeUpdate`\n // bypasses MikroORM's `onUpdate` hook, so set it explicitly.\n const nextUpdatedAt = new Date()\n await em.nativeUpdate(CustomerRole, { id: role.id }, { updatedAt: nextUpdatedAt })\n\n const customerRbacService = container.resolve('customerRbacService') as CustomerRbacService\n await customerRbacService.invalidateRoleCache(role.id)\n\n if (guardResult?.ok && guardResult.shouldRunAfterSuccess) {\n await runCrudMutationGuardAfterSuccess(container, {\n tenantId,\n organizationId: auth.orgId,\n userId: auth.sub,\n resourceKind: ROLE_RESOURCE_KIND,\n resourceId: role.id,\n operation: 'update',\n requestMethod: req.method,\n requestHeaders: req.headers,\n metadata: guardResult.metadata ?? null,\n })\n }\n\n return NextResponse.json({ ok: true, updatedAt: nextUpdatedAt.toISOString() })\n}\n\nconst successSchema = z.object({ ok: z.literal(true), updatedAt: z.string().datetime() })\nconst errorSchema = z.object({ ok: z.literal(false), error: z.string() })\n\nconst methodDoc: OpenApiMethodDoc = {\n summary: 'Update customer role ACL (admin)',\n description: 'Updates the ACL (features and portal admin flag) for a customer role. Invalidates RBAC cache after update.',\n tags: ['Customer Accounts Admin'],\n requestBody: { schema: updateRoleAclSchema },\n responses: [{ status: 200, description: 'ACL updated', schema: successSchema }],\n errors: [\n { status: 400, description: 'Validation failed', schema: errorSchema },\n { status: 401, description: 'Not authenticated', schema: errorSchema },\n { status: 403, description: 'Insufficient permissions', schema: errorSchema },\n { status: 404, description: 'Role not found', schema: errorSchema },\n { status: 409, description: 'Stale ACL write (optimistic-lock conflict)', schema: errorSchema },\n ],\n}\n\nexport const openApi: OpenApiRouteDoc = {\n summary: 'Update customer role ACL (admin)',\n pathParams: z.object({ id: z.string().uuid() }),\n methods: { PUT: methodDoc },\n}\n"],
|
|
5
|
+
"mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAElB,SAAS,0BAA0B;AACnC,SAAS,8BAA8B;AAEvC,SAAS,cAAc,uBAAuB;AAE9C,SAAS,2BAA2B;AACpC,SAAS,oCAAoC;AAC7C,SAAS,uBAAuB;AAChC;AAAA,EACE;AAAA,EACA;AAAA,OACK;AAEA,MAAM,WAAW,CAAC;AAEzB,MAAM,qBAAqB;AAE3B,eAAsB,IAAI,KAAc,EAAE,OAAO,GAA+B;AAC9E,QAAM,OAAO,MAAM,mBAAmB,GAAG;AACzC,MAAI,CAAC,QAAQ,CAAC,KAAK,UAAU;AAC3B,WAAO,aAAa,KAAK,EAAE,IAAI,OAAO,OAAO,0BAA0B,GAAG,EAAE,QAAQ,IAAI,CAAC;AAAA,EAC3F;AACA,QAAM,WAAW,KAAK;AAEtB,QAAM,YAAY,MAAM,uBAAuB;AAC/C,QAAM,cAAc,UAAU,QAAQ,aAAa;AACnD,QAAM,YAAY,MAAM,YAAY,mBAAmB,KAAK,KAAK,CAAC,gCAAgC,GAAG,EAAE,UAAU,gBAAgB,KAAK,MAAM,CAAC;AAC7I,MAAI,CAAC,WAAW;AACd,WAAO,aAAa,KAAK,EAAE,IAAI,OAAO,OAAO,2BAA2B,GAAG,EAAE,QAAQ,IAAI,CAAC;AAAA,EAC5F;AAEA,MAAI;A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AQ,IAAI,GAAG,WAAW,EAAE,OAAO,EAAE,SAAS,EAAE,CAAC;AACxF,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,yBAAyB;AAAA,EAChC,aAAa,EAAE,QAAQ,oBAAoB;AAAA,EAC3C,WAAW,CAAC,EAAE,QAAQ,KAAK,aAAa,eAAe,QAAQ,cAAc,CAAC;AAAA,EAC9E,QAAQ;AAAA,IACN,EAAE,QAAQ,KAAK,aAAa,qBAAqB,QAAQ,YAAY;AAAA,IACrE,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,IAClE,EAAE,QAAQ,KAAK,aAAa,8CAA8C,QAAQ,YAAY;AAAA,EAChG;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
|
}
|
|
@@ -27,6 +27,7 @@ async function GET(req, { params }) {
|
|
|
27
27
|
const role = await em.findOne(CustomerRole, {
|
|
28
28
|
id: params.id,
|
|
29
29
|
tenantId: auth.tenantId,
|
|
30
|
+
organizationId: auth.orgId,
|
|
30
31
|
deletedAt: null
|
|
31
32
|
});
|
|
32
33
|
if (!role) {
|
|
@@ -76,6 +77,7 @@ async function PUT(req, { params }) {
|
|
|
76
77
|
const role = await em.findOne(CustomerRole, {
|
|
77
78
|
id: params.id,
|
|
78
79
|
tenantId: auth.tenantId,
|
|
80
|
+
organizationId: auth.orgId,
|
|
79
81
|
deletedAt: null
|
|
80
82
|
});
|
|
81
83
|
if (!role) {
|
|
@@ -101,7 +103,11 @@ async function PUT(req, { params }) {
|
|
|
101
103
|
if (parsed.data.description !== void 0) updates.description = parsed.data.description;
|
|
102
104
|
if (parsed.data.isDefault !== void 0) updates.isDefault = parsed.data.isDefault;
|
|
103
105
|
if (parsed.data.customerAssignable !== void 0) updates.customerAssignable = parsed.data.customerAssignable;
|
|
104
|
-
await em.nativeUpdate(CustomerRole, {
|
|
106
|
+
await em.nativeUpdate(CustomerRole, {
|
|
107
|
+
id: role.id,
|
|
108
|
+
tenantId: auth.tenantId,
|
|
109
|
+
organizationId: auth.orgId
|
|
110
|
+
}, updates);
|
|
105
111
|
void emitCustomerAccountsEvent("customer_accounts.role.updated", {
|
|
106
112
|
id: role.id,
|
|
107
113
|
name: updates.name || role.name,
|
|
@@ -125,6 +131,7 @@ async function DELETE(req, { params }) {
|
|
|
125
131
|
const role = await em.findOne(CustomerRole, {
|
|
126
132
|
id: params.id,
|
|
127
133
|
tenantId: auth.tenantId,
|
|
134
|
+
organizationId: auth.orgId,
|
|
128
135
|
deletedAt: null
|
|
129
136
|
});
|
|
130
137
|
if (!role) {
|
|
@@ -151,8 +158,15 @@ async function DELETE(req, { params }) {
|
|
|
151
158
|
if (assignedUsersCount > 0) {
|
|
152
159
|
return NextResponse.json({ ok: false, error: `Cannot delete role with ${assignedUsersCount} assigned user(s). Reassign users first.` }, { status: 400 });
|
|
153
160
|
}
|
|
154
|
-
await em.nativeUpdate(CustomerRole, {
|
|
155
|
-
|
|
161
|
+
await em.nativeUpdate(CustomerRole, {
|
|
162
|
+
id: role.id,
|
|
163
|
+
tenantId: auth.tenantId,
|
|
164
|
+
organizationId: auth.orgId
|
|
165
|
+
}, { deletedAt: /* @__PURE__ */ new Date() });
|
|
166
|
+
await em.nativeUpdate(CustomerRoleAcl, {
|
|
167
|
+
role: role.id,
|
|
168
|
+
tenantId: auth.tenantId
|
|
169
|
+
}, { deletedAt: /* @__PURE__ */ new Date() });
|
|
156
170
|
void emitCustomerAccountsEvent("customer_accounts.role.deleted", {
|
|
157
171
|
id: role.id,
|
|
158
172
|
name: role.name,
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../../../src/modules/customer_accounts/api/admin/roles/%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 { CustomerRole, CustomerRoleAcl, CustomerUserRole } from '@open-mercato/core/modules/customer_accounts/data/entities'\nimport { updateRoleSchema } from '@open-mercato/core/modules/customer_accounts/data/validators'\nimport { emitCustomerAccountsEvent } from '@open-mercato/core/modules/customer_accounts/events'\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 role 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 role = await em.findOne(CustomerRole, {\n id: params.id,\n tenantId: auth.tenantId,\n deletedAt: null,\n })\n if (!role) {\n return NextResponse.json({ ok: false, error: 'Role not found' }, { status: 404 })\n }\n\n const acl = await em.findOne(CustomerRoleAcl, {\n role: role.id as any,\n tenantId: auth.tenantId,\n })\n\n const features = acl && Array.isArray(acl.featuresJson) ? acl.featuresJson : []\n\n return NextResponse.json({\n ok: true,\n id: role.id,\n name: role.name,\n slug: role.slug,\n description: role.description || null,\n isDefault: role.isDefault,\n isSystem: role.isSystem,\n customerAssignable: role.customerAssignable,\n createdAt: role.createdAt,\n updatedAt: role.updatedAt || null,\n features,\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.roles.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 = updateRoleSchema.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 role = await em.findOne(CustomerRole, {\n id: params.id,\n tenantId: auth.tenantId,\n deletedAt: null,\n })\n if (!role) {\n return NextResponse.json({ ok: false, error: 'Role not found' }, { status: 404 })\n }\n\n if (role.isSystem && parsed.data.name !== undefined && parsed.data.name !== role.name) {\n return NextResponse.json({ ok: false, error: 'Cannot change name of a system role' }, { status: 400 })\n }\n\n // Optimistic lock: refuse a stale overwrite so two admins editing the same role\n // in parallel cannot silently clobber each other (#2055). Strictly additive.\n try {\n await enforceCommandOptimisticLockWithGuards(container, {\n resourceKind: 'customer_accounts.role',\n resourceId: role.id,\n current: role.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 // Always bump updated_at so the lock version advances on every save \u2014 `nativeUpdate`\n // bypasses MikroORM's `onUpdate` hook, so set it explicitly.\n const nextUpdatedAt = new Date()\n const updates: Record<string, unknown> = { updatedAt: nextUpdatedAt }\n if (parsed.data.name !== undefined) updates.name = parsed.data.name\n if (parsed.data.description !== undefined) updates.description = parsed.data.description\n if (parsed.data.isDefault !== undefined) updates.isDefault = parsed.data.isDefault\n if (parsed.data.customerAssignable !== undefined) updates.customerAssignable = parsed.data.customerAssignable\n\n await em.nativeUpdate(CustomerRole, { id: role.id }, updates)\n\n void emitCustomerAccountsEvent('customer_accounts.role.updated', {\n id: role.id,\n name: updates.name as string || role.name,\n tenantId: auth.tenantId,\n organizationId: auth.orgId,\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.roles.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 role = await em.findOne(CustomerRole, {\n id: params.id,\n tenantId: auth.tenantId,\n deletedAt: null,\n })\n if (!role) {\n return NextResponse.json({ ok: false, error: 'Role not found' }, { status: 404 })\n }\n\n // System roles are seed-provided defaults but may still be removed once they are no\n // longer needed (#3556). Only the default role is hard-protected here because signup\n // auto-assigns it to new portal users \u2014 reassign the default first, then delete.\n if (role.isDefault) {\n return NextResponse.json({ ok: false, error: 'Cannot delete the default role. Set another role as default first.' }, { status: 400 })\n }\n\n // Optimistic lock: refuse a stale delete. Strictly additive.\n try {\n await enforceCommandOptimisticLockWithGuards(container, {\n resourceKind: 'customer_accounts.role',\n resourceId: role.id,\n current: role.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 assignedUsersCount = await em.count(CustomerUserRole, {\n role: role.id as any,\n deletedAt: null,\n })\n if (assignedUsersCount > 0) {\n return NextResponse.json({ ok: false, error: `Cannot delete role with ${assignedUsersCount} assigned user(s). Reassign users first.` }, { status: 400 })\n }\n\n await em.nativeUpdate(CustomerRole, { id: role.id }, { deletedAt: new Date() })\n await em.nativeUpdate(CustomerRoleAcl, { role: role.id as any }, { deletedAt: new Date() })\n\n void emitCustomerAccountsEvent('customer_accounts.role.deleted', {\n id: role.id,\n name: role.name,\n slug: role.slug,\n tenantId: auth.tenantId,\n organizationId: auth.orgId,\n }).catch(() => undefined)\n\n return NextResponse.json({ ok: true })\n}\n\nconst aclSchema = z.object({\n features: z.array(z.string()),\n isPortalAdmin: z.boolean(),\n})\nconst roleDetailSchema = z.object({\n id: z.string().uuid(),\n name: z.string(),\n slug: z.string(),\n description: z.string().nullable(),\n isDefault: z.boolean(),\n isSystem: z.boolean(),\n customerAssignable: z.boolean(),\n createdAt: z.string().datetime(),\n updatedAt: z.string().datetime().nullable(),\n acl: aclSchema,\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 role detail (admin)',\n description: 'Returns full customer role details including ACL features.',\n tags: ['Customer Accounts Admin'],\n responses: [{\n status: 200,\n description: 'Role detail with ACL',\n schema: z.object({ ok: z.literal(true), role: roleDetailSchema }),\n }],\n errors: [\n { status: 401, description: 'Not authenticated', schema: errorSchema },\n { status: 403, description: 'Insufficient permissions', schema: errorSchema },\n { status: 404, description: 'Role not found', schema: errorSchema },\n ],\n}\n\nconst putMethodDoc: OpenApiMethodDoc = {\n summary: 'Update customer role (admin)',\n description: 'Updates a customer role. System roles are protected from name changes.',\n tags: ['Customer Accounts Admin'],\n requestBody: { schema: updateRoleSchema },\n responses: [{ status: 200, description: 'Role updated', schema: successSchema }],\n errors: [\n { status: 400, description: 'Validation failed or system role restriction', schema: errorSchema },\n { status: 401, description: 'Not authenticated', schema: errorSchema },\n { status: 403, description: 'Insufficient permissions', schema: errorSchema },\n { status: 404, description: 'Role not found', schema: errorSchema },\n ],\n}\n\nconst deleteMethodDoc: OpenApiMethodDoc = {\n summary: 'Delete customer role (admin)',\n description: 'Soft deletes a customer role and its ACL. The default role (auto-assigned to new portal users) and roles with assigned users cannot be deleted.',\n tags: ['Customer Accounts Admin'],\n responses: [{ status: 200, description: 'Role deleted', schema: successSchema }],\n errors: [\n { status: 400, description: 'Default role or has assigned users', schema: errorSchema },\n { status: 401, description: 'Not authenticated', schema: errorSchema },\n { status: 403, description: 'Insufficient permissions', schema: errorSchema },\n { status: 404, description: 'Role not found', schema: errorSchema },\n ],\n}\n\nexport const openApi: OpenApiRouteDoc = {\n summary: 'Customer role 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,iBAAiB,wBAAwB;AAChE,SAAS,wBAAwB;AACjC,SAAS,iCAAi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AU,QAAQ,IAAI;AAEjC,QAAM,OAAO,MAAM,GAAG,QAAQ,cAAc;AAAA,IAC1C,IAAI,OAAO;AAAA,IACX,UAAU,KAAK;AAAA,IACf,WAAW;AAAA,EACb,CAAC;AACD,MAAI,CAAC,MAAM;AACT,WAAO,aAAa,KAAK,EAAE,IAAI,OAAO,OAAO,iBAAiB,GAAG,EAAE,QAAQ,IAAI,CAAC;AAAA,EAClF;AAEA,MAAI,KAAK,YAAY,OAAO,KAAK,SAAS,UAAa,OAAO,KAAK,SAAS,KAAK,MAAM;AACrF,WAAO,aAAa,KAAK,EAAE,IAAI,OAAO,OAAO,sCAAsC,GAAG,EAAE,QAAQ,IAAI,CAAC;AAAA,EACvG;AAIA,MAAI;AACF,UAAM,uCAAuC,WAAW;AAAA,MACtD,cAAc;AAAA,MACd,YAAY,KAAK;AAAA,MACjB,SAAS,KAAK,aAAa;AAAA,MAC3B,SAAS;AAAA,IACX,CAAC;AAAA,EACH,SAAS,KAAK;AACZ,QAAI,gBAAgB,GAAG,EAAG,QAAO,aAAa,KAAK,IAAI,MAAM,EAAE,QAAQ,IAAI,OAAO,CAAC;AACnF,UAAM;AAAA,EACR;AAIA,QAAM,gBAAgB,oBAAI,KAAK;AAC/B,QAAM,UAAmC,EAAE,WAAW,cAAc;AACpE,MAAI,OAAO,KAAK,SAAS,OAAW,SAAQ,OAAO,OAAO,KAAK;AAC/D,MAAI,OAAO,KAAK,gBAAgB,OAAW,SAAQ,cAAc,OAAO,KAAK;AAC7E,MAAI,OAAO,KAAK,cAAc,OAAW,SAAQ,YAAY,OAAO,KAAK;AACzE,MAAI,OAAO,KAAK,uBAAuB,OAAW,SAAQ,qBAAqB,OAAO,KAAK;AAE3F,QAAM,GAAG,aAAa,cAAc,
|
|
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 { CustomerRole, CustomerRoleAcl, CustomerUserRole } from '@open-mercato/core/modules/customer_accounts/data/entities'\nimport { updateRoleSchema } from '@open-mercato/core/modules/customer_accounts/data/validators'\nimport { emitCustomerAccountsEvent } from '@open-mercato/core/modules/customer_accounts/events'\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 role 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 role = await em.findOne(CustomerRole, {\n id: params.id,\n tenantId: auth.tenantId,\n organizationId: auth.orgId,\n deletedAt: null,\n })\n if (!role) {\n return NextResponse.json({ ok: false, error: 'Role not found' }, { status: 404 })\n }\n\n const acl = await em.findOne(CustomerRoleAcl, {\n role: role.id as any,\n tenantId: auth.tenantId,\n })\n\n const features = acl && Array.isArray(acl.featuresJson) ? acl.featuresJson : []\n\n return NextResponse.json({\n ok: true,\n id: role.id,\n name: role.name,\n slug: role.slug,\n description: role.description || null,\n isDefault: role.isDefault,\n isSystem: role.isSystem,\n customerAssignable: role.customerAssignable,\n createdAt: role.createdAt,\n updatedAt: role.updatedAt || null,\n features,\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.roles.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 = updateRoleSchema.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 role = await em.findOne(CustomerRole, {\n id: params.id,\n tenantId: auth.tenantId,\n organizationId: auth.orgId,\n deletedAt: null,\n })\n if (!role) {\n return NextResponse.json({ ok: false, error: 'Role not found' }, { status: 404 })\n }\n\n if (role.isSystem && parsed.data.name !== undefined && parsed.data.name !== role.name) {\n return NextResponse.json({ ok: false, error: 'Cannot change name of a system role' }, { status: 400 })\n }\n\n // Optimistic lock: refuse a stale overwrite so two admins editing the same role\n // in parallel cannot silently clobber each other (#2055). Strictly additive.\n try {\n await enforceCommandOptimisticLockWithGuards(container, {\n resourceKind: 'customer_accounts.role',\n resourceId: role.id,\n current: role.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 // Always bump updated_at so the lock version advances on every save \u2014 `nativeUpdate`\n // bypasses MikroORM's `onUpdate` hook, so set it explicitly.\n const nextUpdatedAt = new Date()\n const updates: Record<string, unknown> = { updatedAt: nextUpdatedAt }\n if (parsed.data.name !== undefined) updates.name = parsed.data.name\n if (parsed.data.description !== undefined) updates.description = parsed.data.description\n if (parsed.data.isDefault !== undefined) updates.isDefault = parsed.data.isDefault\n if (parsed.data.customerAssignable !== undefined) updates.customerAssignable = parsed.data.customerAssignable\n\n await em.nativeUpdate(CustomerRole, {\n id: role.id,\n tenantId: auth.tenantId,\n organizationId: auth.orgId,\n }, updates)\n\n void emitCustomerAccountsEvent('customer_accounts.role.updated', {\n id: role.id,\n name: updates.name as string || role.name,\n tenantId: auth.tenantId,\n organizationId: auth.orgId,\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.roles.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 role = await em.findOne(CustomerRole, {\n id: params.id,\n tenantId: auth.tenantId,\n organizationId: auth.orgId,\n deletedAt: null,\n })\n if (!role) {\n return NextResponse.json({ ok: false, error: 'Role not found' }, { status: 404 })\n }\n\n // System roles are seed-provided defaults but may still be removed once they are no\n // longer needed (#3556). Only the default role is hard-protected here because signup\n // auto-assigns it to new portal users \u2014 reassign the default first, then delete.\n if (role.isDefault) {\n return NextResponse.json({ ok: false, error: 'Cannot delete the default role. Set another role as default first.' }, { status: 400 })\n }\n\n // Optimistic lock: refuse a stale delete. Strictly additive.\n try {\n await enforceCommandOptimisticLockWithGuards(container, {\n resourceKind: 'customer_accounts.role',\n resourceId: role.id,\n current: role.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 assignedUsersCount = await em.count(CustomerUserRole, {\n role: role.id as any,\n deletedAt: null,\n })\n if (assignedUsersCount > 0) {\n return NextResponse.json({ ok: false, error: `Cannot delete role with ${assignedUsersCount} assigned user(s). Reassign users first.` }, { status: 400 })\n }\n\n await em.nativeUpdate(CustomerRole, {\n id: role.id,\n tenantId: auth.tenantId,\n organizationId: auth.orgId,\n }, { deletedAt: new Date() })\n await em.nativeUpdate(CustomerRoleAcl, {\n role: role.id as any,\n tenantId: auth.tenantId,\n }, { deletedAt: new Date() })\n\n void emitCustomerAccountsEvent('customer_accounts.role.deleted', {\n id: role.id,\n name: role.name,\n slug: role.slug,\n tenantId: auth.tenantId,\n organizationId: auth.orgId,\n }).catch(() => undefined)\n\n return NextResponse.json({ ok: true })\n}\n\nconst aclSchema = z.object({\n features: z.array(z.string()),\n isPortalAdmin: z.boolean(),\n})\nconst roleDetailSchema = z.object({\n id: z.string().uuid(),\n name: z.string(),\n slug: z.string(),\n description: z.string().nullable(),\n isDefault: z.boolean(),\n isSystem: z.boolean(),\n customerAssignable: z.boolean(),\n createdAt: z.string().datetime(),\n updatedAt: z.string().datetime().nullable(),\n acl: aclSchema,\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 role detail (admin)',\n description: 'Returns full customer role details including ACL features.',\n tags: ['Customer Accounts Admin'],\n responses: [{\n status: 200,\n description: 'Role detail with ACL',\n schema: z.object({ ok: z.literal(true), role: roleDetailSchema }),\n }],\n errors: [\n { status: 401, description: 'Not authenticated', schema: errorSchema },\n { status: 403, description: 'Insufficient permissions', schema: errorSchema },\n { status: 404, description: 'Role not found', schema: errorSchema },\n ],\n}\n\nconst putMethodDoc: OpenApiMethodDoc = {\n summary: 'Update customer role (admin)',\n description: 'Updates a customer role. System roles are protected from name changes.',\n tags: ['Customer Accounts Admin'],\n requestBody: { schema: updateRoleSchema },\n responses: [{ status: 200, description: 'Role updated', schema: successSchema }],\n errors: [\n { status: 400, description: 'Validation failed or system role restriction', schema: errorSchema },\n { status: 401, description: 'Not authenticated', schema: errorSchema },\n { status: 403, description: 'Insufficient permissions', schema: errorSchema },\n { status: 404, description: 'Role not found', schema: errorSchema },\n ],\n}\n\nconst deleteMethodDoc: OpenApiMethodDoc = {\n summary: 'Delete customer role (admin)',\n description: 'Soft deletes a customer role and its ACL. The default role (auto-assigned to new portal users) and roles with assigned users cannot be deleted.',\n tags: ['Customer Accounts Admin'],\n responses: [{ status: 200, description: 'Role deleted', schema: successSchema }],\n errors: [\n { status: 400, description: 'Default role or has assigned users', schema: errorSchema },\n { status: 401, description: 'Not authenticated', schema: errorSchema },\n { status: 403, description: 'Insufficient permissions', schema: errorSchema },\n { status: 404, description: 'Role not found', schema: errorSchema },\n ],\n}\n\nexport const openApi: OpenApiRouteDoc = {\n summary: 'Customer role 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,iBAAiB,wBAAwB;AAChE,SAAS,wBAAwB;AACjC,SAAS,iCAAiC;AAC1C,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,GAAG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AAoC;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,sCAAsC,QAAQ,YAAY;AAAA,IACtF,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
|
}
|
|
@@ -45,7 +45,12 @@ async function PUT(req, { params }) {
|
|
|
45
45
|
const fetchedRoles = requestedRoleIds.length > 0 ? await findWithDecryption(
|
|
46
46
|
em,
|
|
47
47
|
CustomerRole,
|
|
48
|
-
{
|
|
48
|
+
{
|
|
49
|
+
id: { $in: requestedRoleIds },
|
|
50
|
+
tenantId: auth.tenantId,
|
|
51
|
+
organizationId: auth.orgId,
|
|
52
|
+
deletedAt: null
|
|
53
|
+
},
|
|
49
54
|
void 0,
|
|
50
55
|
{ tenantId: auth.tenantId, organizationId: auth.orgId }
|
|
51
56
|
) : [];
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../../../../src/modules/customer_accounts/api/portal/users/%5Bid%5D/roles.ts"],
|
|
4
|
-
"sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport type { OpenApiRouteDoc, OpenApiMethodDoc } from '@open-mercato/shared/lib/openapi'\nimport { getCustomerAuthFromRequest, requireCustomerFeature } from '@open-mercato/core/modules/customer_accounts/lib/customerAuth'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { CustomerUser, CustomerUserRole, CustomerRole } from '@open-mercato/core/modules/customer_accounts/data/entities'\nimport { CustomerRbacService } from '@open-mercato/core/modules/customer_accounts/services/customerRbacService'\nimport { assignRolesSchema } from '@open-mercato/core/modules/customer_accounts/data/validators'\nimport { findOneWithDecryption, findWithDecryption } from '@open-mercato/shared/lib/encryption/find'\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 customerRbacService = container.resolve('customerRbacService') as CustomerRbacService\n\n try {\n await requireCustomerFeature(auth, ['portal.users.roles.manage'], customerRbacService)\n } catch (response) {\n return response as NextResponse\n }\n\n if (!auth.customerEntityId) {\n return NextResponse.json({ ok: false, error: 'No company association' }, { 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 = assignRolesSchema.safeParse(body)\n if (!parsed.success) {\n return NextResponse.json({ ok: false, error: 'Validation failed' }, { status: 400 })\n }\n\n const em = container.resolve('em') as import('@mikro-orm/postgresql').EntityManager\n\n // Verify target user belongs to same company\n const targetUser = await findOneWithDecryption(em, CustomerUser, {\n id: params.id,\n customerEntityId: auth.customerEntityId,\n tenantId: auth.tenantId,\n deletedAt: null,\n }, undefined, { tenantId: auth.tenantId, organizationId: auth.orgId })\n if (!targetUser) {\n return NextResponse.json({ ok: false, error: 'User not found' }, { status: 404 })\n }\n\n // Validate all roles are customer_assignable and collect for assignment\n const requestedRoleIds = parsed.data.role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AAM,sBAAsB,IAAI,cAAc;AAAA,IAC/D,IAAI,OAAO;AAAA,IACX,kBAAkB,KAAK;AAAA,IACvB,UAAU,KAAK;AAAA,IACf,WAAW;AAAA,EACb,GAAG,QAAW,EAAE,UAAU,KAAK,UAAU,gBAAgB,KAAK,MAAM,CAAC;AACrE,MAAI,CAAC,YAAY;AACf,WAAO,aAAa,KAAK,EAAE,IAAI,OAAO,OAAO,iBAAiB,GAAG,EAAE,QAAQ,IAAI,CAAC;AAAA,EAClF;AAGA,QAAM,mBAAmB,OAAO,KAAK;AACrC,QAAM,eAAe,iBAAiB,SAAS,IAC3C,MAAM;AAAA,IACJ;AAAA,IACA;AAAA,IACA,
|
|
4
|
+
"sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport type { OpenApiRouteDoc, OpenApiMethodDoc } from '@open-mercato/shared/lib/openapi'\nimport { getCustomerAuthFromRequest, requireCustomerFeature } from '@open-mercato/core/modules/customer_accounts/lib/customerAuth'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { CustomerUser, CustomerUserRole, CustomerRole } from '@open-mercato/core/modules/customer_accounts/data/entities'\nimport { CustomerRbacService } from '@open-mercato/core/modules/customer_accounts/services/customerRbacService'\nimport { assignRolesSchema } from '@open-mercato/core/modules/customer_accounts/data/validators'\nimport { findOneWithDecryption, findWithDecryption } from '@open-mercato/shared/lib/encryption/find'\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 customerRbacService = container.resolve('customerRbacService') as CustomerRbacService\n\n try {\n await requireCustomerFeature(auth, ['portal.users.roles.manage'], customerRbacService)\n } catch (response) {\n return response as NextResponse\n }\n\n if (!auth.customerEntityId) {\n return NextResponse.json({ ok: false, error: 'No company association' }, { 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 = assignRolesSchema.safeParse(body)\n if (!parsed.success) {\n return NextResponse.json({ ok: false, error: 'Validation failed' }, { status: 400 })\n }\n\n const em = container.resolve('em') as import('@mikro-orm/postgresql').EntityManager\n\n // Verify target user belongs to same company\n const targetUser = await findOneWithDecryption(em, CustomerUser, {\n id: params.id,\n customerEntityId: auth.customerEntityId,\n tenantId: auth.tenantId,\n deletedAt: null,\n }, undefined, { tenantId: auth.tenantId, organizationId: auth.orgId })\n if (!targetUser) {\n return NextResponse.json({ ok: false, error: 'User not found' }, { status: 404 })\n }\n\n // Validate all roles are customer_assignable and collect for assignment\n const requestedRoleIds = parsed.data.roleIds\n const fetchedRoles = requestedRoleIds.length > 0\n ? await findWithDecryption(\n em,\n CustomerRole,\n {\n id: { $in: requestedRoleIds },\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 const fetchedRolesById = new Map(fetchedRoles.map((role) => [role.id, role]))\n const validatedRoles: InstanceType<typeof CustomerRole>[] = []\n for (const roleId of requestedRoleIds) {\n const role = fetchedRolesById.get(roleId)\n if (!role || !role.customerAssignable) {\n return NextResponse.json({ ok: false, error: 'Role not found or not assignable' }, { status: 400 })\n }\n validatedRoles.push(role)\n }\n\n // Replace the role set atomically: deleting the old roles and inserting the new\n // ones in one transaction prevents a flush failure from leaving the user with\n // zero roles (portal lockout / privilege loss) (#2337).\n await em.transactional(async (tx) => {\n await tx.nativeDelete(CustomerUserRole, { user: targetUser.id as any })\n for (const role of validatedRoles) {\n const userRole = tx.create(CustomerUserRole, {\n user: targetUser,\n role,\n createdAt: new Date(),\n } as any)\n tx.persist(userRole)\n }\n })\n\n await customerRbacService.invalidateUserCache(targetUser.id)\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: 'Update portal user roles',\n description: 'Assigns new roles to a company portal user.',\n tags: ['Customer Portal'],\n requestBody: { schema: assignRolesSchema },\n responses: [{ status: 200, description: 'Roles updated', schema: successSchema }],\n errors: [\n { status: 400, description: 'Validation failed', 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\nexport const openApi: OpenApiRouteDoc = {\n summary: 'Update portal user roles',\n pathParams: z.object({ id: z.string().uuid() }),\n methods: { PUT: methodDoc },\n}\n"],
|
|
5
|
+
"mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAElB,SAAS,4BAA4B,8BAA8B;AACnE,SAAS,8BAA8B;AACvC,SAAS,cAAc,kBAAkB,oBAAoB;AAE7D,SAAS,yBAAyB;AAClC,SAAS,uBAAuB,0BAA0B;AAEnD,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,sBAAsB,UAAU,QAAQ,qBAAqB;AAEnE,MAAI;AACF,UAAM,uBAAuB,MAAM,CAAC,2BAA2B,GAAG,mBAAmB;AAAA,EACvF,SAAS,UAAU;AACjB,WAAO;AAAA,EACT;AAEA,MAAI,CAAC,KAAK,kBAAkB;AAC1B,WAAO,aAAa,KAAK,EAAE,IAAI,OAAO,OAAO,yBAAyB,GAAG,EAAE,QAAQ,IAAI,CAAC;AAAA,E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AAA,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
|
}
|
|
@@ -52,7 +52,12 @@ async function POST(req) {
|
|
|
52
52
|
const roles = requestedRoleIds.length > 0 ? await findWithDecryption(
|
|
53
53
|
em,
|
|
54
54
|
CustomerRole,
|
|
55
|
-
{
|
|
55
|
+
{
|
|
56
|
+
id: { $in: requestedRoleIds },
|
|
57
|
+
tenantId: auth.tenantId,
|
|
58
|
+
organizationId: auth.orgId,
|
|
59
|
+
deletedAt: null
|
|
60
|
+
},
|
|
56
61
|
void 0,
|
|
57
62
|
{ tenantId: auth.tenantId, organizationId: auth.orgId }
|
|
58
63
|
) : [];
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../../src/modules/customer_accounts/api/portal/users-invite.ts"],
|
|
4
|
-
"sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport type { OpenApiRouteDoc, OpenApiMethodDoc } from '@open-mercato/shared/lib/openapi'\nimport { getCustomerAuthFromRequest, requireCustomerFeature } from '@open-mercato/core/modules/customer_accounts/lib/customerAuth'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { CustomerInvitationService } from '@open-mercato/core/modules/customer_accounts/services/customerInvitationService'\nimport { emitCustomerAccountsEvent } from '@open-mercato/core/modules/customer_accounts/events'\nimport { CustomerRbacService } from '@open-mercato/core/modules/customer_accounts/services/customerRbacService'\nimport { CustomerRole } from '@open-mercato/core/modules/customer_accounts/data/entities'\nimport { inviteUserSchema } from '@open-mercato/core/modules/customer_accounts/data/validators'\nimport { findWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { rateLimitErrorSchema } from '@open-mercato/shared/lib/ratelimit/helpers'\nimport {\n checkAuthRateLimit,\n customerInviteRateLimitConfig,\n customerInviteIpRateLimitConfig,\n} from '@open-mercato/core/modules/customer_accounts/lib/rateLimiter'\nimport { readNormalizedEmailFromJsonRequest } from '@open-mercato/core/modules/customer_accounts/lib/rateLimitIdentifier'\n\nexport const metadata: { path?: string; requireAuth?: boolean } = { requireAuth: false }\n\nexport async function POST(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 rateLimitEmail = await readNormalizedEmailFromJsonRequest(req)\n const { error: rateLimitError } = await checkAuthRateLimit({\n req,\n ipConfig: customerInviteIpRateLimitConfig,\n compoundConfig: customerInviteRateLimitConfig,\n compoundIdentifier: rateLimitEmail,\n })\n if (rateLimitError) return rateLimitError\n\n const container = await createRequestContainer()\n const customerRbacService = container.resolve('customerRbacService') as CustomerRbacService\n\n try {\n await requireCustomerFeature(auth, ['portal.users.manage'], customerRbacService)\n } catch (response) {\n return response as NextResponse\n }\n\n if (!auth.customerEntityId) {\n return NextResponse.json({ ok: false, error: 'No company association' }, { 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 = inviteUserSchema.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 // Validate all roles are customer_assignable\n const requestedRoleIds = parsed.data.roleIds\n const roles = requestedRoleIds.length > 0\n ? await findWithDecryption(\n em,\n CustomerRole,\n {
|
|
5
|
-
"mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAElB,SAAS,4BAA4B,8BAA8B;AACnE,SAAS,8BAA8B;AAEvC,SAAS,iCAAiC;AAE1C,SAAS,oBAAoB;AAC7B,SAAS,wBAAwB;AACjC,SAAS,0BAA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QAAM,KAAK,UAAU,QAAQ,IAAI;AAGjC,QAAM,mBAAmB,OAAO,KAAK;AACrC,QAAM,QAAQ,iBAAiB,SAAS,IACpC,MAAM;AAAA,IACJ;AAAA,IACA;AAAA,IACA,
|
|
4
|
+
"sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport type { OpenApiRouteDoc, OpenApiMethodDoc } from '@open-mercato/shared/lib/openapi'\nimport { getCustomerAuthFromRequest, requireCustomerFeature } from '@open-mercato/core/modules/customer_accounts/lib/customerAuth'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { CustomerInvitationService } from '@open-mercato/core/modules/customer_accounts/services/customerInvitationService'\nimport { emitCustomerAccountsEvent } from '@open-mercato/core/modules/customer_accounts/events'\nimport { CustomerRbacService } from '@open-mercato/core/modules/customer_accounts/services/customerRbacService'\nimport { CustomerRole } from '@open-mercato/core/modules/customer_accounts/data/entities'\nimport { inviteUserSchema } from '@open-mercato/core/modules/customer_accounts/data/validators'\nimport { findWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { rateLimitErrorSchema } from '@open-mercato/shared/lib/ratelimit/helpers'\nimport {\n checkAuthRateLimit,\n customerInviteRateLimitConfig,\n customerInviteIpRateLimitConfig,\n} from '@open-mercato/core/modules/customer_accounts/lib/rateLimiter'\nimport { readNormalizedEmailFromJsonRequest } from '@open-mercato/core/modules/customer_accounts/lib/rateLimitIdentifier'\n\nexport const metadata: { path?: string; requireAuth?: boolean } = { requireAuth: false }\n\nexport async function POST(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 rateLimitEmail = await readNormalizedEmailFromJsonRequest(req)\n const { error: rateLimitError } = await checkAuthRateLimit({\n req,\n ipConfig: customerInviteIpRateLimitConfig,\n compoundConfig: customerInviteRateLimitConfig,\n compoundIdentifier: rateLimitEmail,\n })\n if (rateLimitError) return rateLimitError\n\n const container = await createRequestContainer()\n const customerRbacService = container.resolve('customerRbacService') as CustomerRbacService\n\n try {\n await requireCustomerFeature(auth, ['portal.users.manage'], customerRbacService)\n } catch (response) {\n return response as NextResponse\n }\n\n if (!auth.customerEntityId) {\n return NextResponse.json({ ok: false, error: 'No company association' }, { 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 = inviteUserSchema.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 // Validate all roles are customer_assignable\n const requestedRoleIds = parsed.data.roleIds\n const roles = requestedRoleIds.length > 0\n ? await findWithDecryption(\n em,\n CustomerRole,\n {\n id: { $in: requestedRoleIds },\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 const rolesById = new Map(roles.map((role) => [role.id, role]))\n for (const roleId of requestedRoleIds) {\n const role = rolesById.get(roleId)\n if (!role) {\n return NextResponse.json({ ok: false, error: `Role ${roleId} not found` }, { status: 400 })\n }\n if (!role.customerAssignable) {\n return NextResponse.json({ ok: false, error: `Role \"${role.name}\" cannot be assigned by portal users` }, { status: 403 })\n }\n }\n\n const customerInvitationService = container.resolve('customerInvitationService') as CustomerInvitationService\n\n const { invitation } = await customerInvitationService.createInvitation(\n parsed.data.email,\n { tenantId: auth.tenantId, organizationId: auth.orgId },\n {\n customerEntityId: auth.customerEntityId,\n roleIds: parsed.data.roleIds,\n invitedByCustomerUserId: auth.sub,\n displayName: parsed.data.displayName || null,\n },\n )\n\n void emitCustomerAccountsEvent('customer_accounts.user.invited', {\n invitationId: invitation.id,\n email: invitation.email,\n customerEntityId: invitation.customerEntityId || null,\n invitedByType: 'portal',\n tenantId: auth.tenantId,\n organizationId: auth.orgId,\n }).catch(() => undefined)\n\n return NextResponse.json({\n ok: true,\n invitation: {\n id: invitation.id,\n email: invitation.email,\n expiresAt: invitation.expiresAt,\n },\n }, { status: 201 })\n}\n\nconst successSchema = z.object({\n ok: z.literal(true),\n invitation: z.object({\n id: z.string().uuid(),\n email: z.string(),\n expiresAt: z.string().datetime(),\n }),\n})\nconst errorSchema = z.object({ ok: z.literal(false), error: z.string() })\n\nconst methodDoc: OpenApiMethodDoc = {\n summary: 'Invite a user to the company portal',\n description: 'Creates an invitation for a new user to join the company portal.',\n tags: ['Customer Portal'],\n requestBody: { schema: inviteUserSchema },\n responses: [{ status: 201, description: 'Invitation created', schema: successSchema }],\n errors: [\n { status: 400, description: 'Validation failed', schema: errorSchema },\n { status: 401, description: 'Not authenticated', schema: errorSchema },\n { status: 403, description: 'Insufficient permissions or non-assignable role', schema: errorSchema },\n { status: 429, description: 'Too many invitation requests', schema: rateLimitErrorSchema },\n ],\n}\n\nexport const openApi: OpenApiRouteDoc = {\n summary: 'Invite portal user',\n methods: { POST: methodDoc },\n}\n"],
|
|
5
|
+
"mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAElB,SAAS,4BAA4B,8BAA8B;AACnE,SAAS,8BAA8B;AAEvC,SAAS,iCAAiC;AAE1C,SAAS,oBAAoB;AAC7B,SAAS,wBAAwB;AACjC,SAAS,0BAA0B;AACnC,SAAS,4BAA4B;AACrC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,0CAA0C;AAE5C,MAAM,WAAqD,EAAE,aAAa,MAAM;AAEvF,eAAsB,KAAK,KAAc;AACvC,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,iBAAiB,MAAM,mCAAmC,GAAG;AACn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Q,IAAI;AAAA,EAClB,YAAY,EAAE,OAAO;AAAA,IACnB,IAAI,EAAE,OAAO,EAAE,KAAK;AAAA,IACpB,OAAO,EAAE,OAAO;AAAA,IAChB,WAAW,EAAE,OAAO,EAAE,SAAS;AAAA,EACjC,CAAC;AACH,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,aAAa,EAAE,QAAQ,iBAAiB;AAAA,EACxC,WAAW,CAAC,EAAE,QAAQ,KAAK,aAAa,sBAAsB,QAAQ,cAAc,CAAC;AAAA,EACrF,QAAQ;AAAA,IACN,EAAE,QAAQ,KAAK,aAAa,qBAAqB,QAAQ,YAAY;AAAA,IACrE,EAAE,QAAQ,KAAK,aAAa,qBAAqB,QAAQ,YAAY;AAAA,IACrE,EAAE,QAAQ,KAAK,aAAa,mDAAmD,QAAQ,YAAY;AAAA,IACnG,EAAE,QAAQ,KAAK,aAAa,gCAAgC,QAAQ,qBAAqB;AAAA,EAC3F;AACF;AAEO,MAAM,UAA2B;AAAA,EACtC,SAAS;AAAA,EACT,SAAS,EAAE,MAAM,UAAU;AAC7B;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/modules/customer_accounts/services/customerInvitationService.ts"],
|
|
4
|
-
"sourcesContent": ["import { EntityManager } from '@mikro-orm/postgresql'\nimport { hash } from 'bcryptjs'\nimport {\n CustomerUser,\n CustomerUserInvitation,\n CustomerUserRole,\n CustomerRole,\n} from '@open-mercato/core/modules/customer_accounts/data/entities'\nimport { generateSecureToken, hashToken } from '@open-mercato/core/modules/customer_accounts/lib/tokenGenerator'\nimport { hashForLookup } from '@open-mercato/shared/lib/encryption/aes'\nimport { findOneWithDecryption, findWithDecryption } from '@open-mercato/shared/lib/encryption/find'\n\nconst BCRYPT_COST = 10\nconst INVITATION_TTL_MS = 72 * 60 * 60 * 1000 // 72 hours\n\nexport class CustomerInvitationService {\n constructor(private em: EntityManager) {}\n\n async createInvitation(\n email: string,\n scope: { tenantId: string; organizationId: string },\n options: {\n customerEntityId?: string | null\n roleIds: string[]\n invitedByUserId?: string | null\n invitedByCustomerUserId?: string | null\n displayName?: string | null\n },\n ): Promise<{ invitation: CustomerUserInvitation; rawToken: string }> {\n const token = generateSecureToken()\n const emailHash = hashForLookup(email)\n const normalizedEmail = email.toLowerCase().trim()\n const expiresAt = new Date(Date.now() + INVITATION_TTL_MS)\n const tokenHashed = hashToken(token)\n\n // Dedupe: reuse an existing pending (not accepted, not cancelled, unexpired)\n // invitation for the same recipient instead of inserting a new row. This caps\n // row/token growth and keeps a single live token per concurrently-pending\n // (tenant, organization, email) tuple.\n const existing = await findOneWithDecryption(\n this.em,\n CustomerUserInvitation,\n {\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n emailHash,\n acceptedAt: null,\n cancelledAt: null,\n expiresAt: { $gt: new Date() },\n } as any,\n undefined,\n { tenantId: scope.tenantId, organizationId: scope.organizationId },\n )\n\n if (existing) {\n existing.email = normalizedEmail\n existing.token = tokenHashed\n existing.customerEntityId = options.customerEntityId || null\n existing.roleIdsJson = options.roleIds\n existing.invitedByUserId = options.invitedByUserId || null\n existing.invitedByCustomerUserId = options.invitedByCustomerUserId || null\n existing.displayName = options.displayName || null\n existing.expiresAt = expiresAt\n await this.em.flush()\n return { invitation: existing, rawToken: token }\n }\n\n const invitation = this.em.create(CustomerUserInvitation, {\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n email: normalizedEmail,\n emailHash,\n token: tokenHashed,\n customerEntityId: options.customerEntityId || null,\n roleIdsJson: options.roleIds,\n invitedByUserId: options.invitedByUserId || null,\n invitedByCustomerUserId: options.invitedByCustomerUserId || null,\n displayName: options.displayName || null,\n expiresAt,\n createdAt: new Date(),\n } as any) as CustomerUserInvitation\n await this.em.persist(invitation).flush()\n return { invitation, rawToken: token }\n }\n\n async findByToken(token: string): Promise<CustomerUserInvitation | null> {\n const tokenHashed = hashToken(token)\n const invitation = await findOneWithDecryption(\n this.em,\n CustomerUserInvitation,\n { token: tokenHashed } as any,\n )\n if (!invitation) return null\n if (invitation.acceptedAt) return null\n if (invitation.cancelledAt) return null\n if (invitation.expiresAt.getTime() < Date.now()) return null\n return invitation\n }\n\n async acceptInvitation(\n token: string,\n password: string,\n displayName: string,\n ): Promise<{ user: CustomerUser; invitation: CustomerUserInvitation } | null> {\n const invitation = await this.findByToken(token)\n if (!invitation) return null\n\n const passwordHash = await hash(password, BCRYPT_COST)\n const emailHash = hashForLookup(invitation.email)\n\n // Create user\n const user = this.em.create(CustomerUser, {\n email: invitation.email,\n emailHash,\n passwordHash,\n displayName: displayName || invitation.displayName || invitation.email,\n tenantId: invitation.tenantId,\n organizationId: invitation.organizationId,\n customerEntityId: invitation.customerEntityId || null,\n isActive: true,\n emailVerifiedAt: new Date(), // Invitation implicitly verifies email\n failedLoginAttempts: 0,\n createdAt: new Date(),\n } as any) as CustomerUser\n this.em.persist(user)\n\n // Assign roles\n const roleIds = Array.isArray(invitation.roleIdsJson) ? invitation.roleIdsJson : []\n const roles = roleIds.length > 0\n ? await findWithDecryption(\n this.em,\n CustomerRole,\n {\n id: { $in: roleIds } as any,\n tenantId: invitation.tenantId,\n deletedAt: null,\n } as any,\n undefined,\n { tenantId: invitation.tenantId, organizationId: invitation.organizationId },\n )\n : []\n for (const role of roles) {\n const userRole = this.em.create(CustomerUserRole, {\n user,\n role,\n createdAt: new Date(),\n } as any)\n this.em.persist(userRole)\n }\n\n // Mark invitation as accepted\n invitation.acceptedAt = new Date()\n\n await this.em.flush()\n return { user, invitation }\n }\n}\n"],
|
|
5
|
-
"mappings": "AACA,SAAS,YAAY;AACrB;AAAA,EACE;AA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AAI;AAGpB,UAAM,UAAU,MAAM,QAAQ,WAAW,WAAW,IAAI,WAAW,cAAc,CAAC;AAClF,UAAM,QAAQ,QAAQ,SAAS,IAC3B,MAAM;AAAA,MACJ,KAAK;AAAA,MACL;AAAA,MACA;AAAA,QACE,IAAI,EAAE,KAAK,QAAQ;AAAA,QACnB,UAAU,WAAW;AAAA,QACrB,WAAW;AAAA,MACb;AAAA,MACA;AAAA,MACA,EAAE,UAAU,WAAW,UAAU,gBAAgB,WAAW,eAAe;AAAA,IAC7E,IACA,CAAC;AACL,eAAW,QAAQ,OAAO;AACxB,YAAM,WAAW,KAAK,GAAG,OAAO,kBAAkB;AAAA,QAChD;AAAA,QACA;AAAA,QACA,WAAW,oBAAI,KAAK;AAAA,MACtB,CAAQ;AACR,WAAK,GAAG,QAAQ,QAAQ;AAAA,IAC1B;AAGA,eAAW,aAAa,oBAAI,KAAK;AAEjC,UAAM,KAAK,GAAG,MAAM;AACpB,WAAO,EAAE,MAAM,WAAW;AAAA,EAC5B;AACF;",
|
|
4
|
+
"sourcesContent": ["import { EntityManager } from '@mikro-orm/postgresql'\nimport { hash } from 'bcryptjs'\nimport {\n CustomerUser,\n CustomerUserInvitation,\n CustomerUserRole,\n CustomerRole,\n} from '@open-mercato/core/modules/customer_accounts/data/entities'\nimport { generateSecureToken, hashToken } from '@open-mercato/core/modules/customer_accounts/lib/tokenGenerator'\nimport { hashForLookup } from '@open-mercato/shared/lib/encryption/aes'\nimport { findOneWithDecryption, findWithDecryption } from '@open-mercato/shared/lib/encryption/find'\n\nconst BCRYPT_COST = 10\nconst INVITATION_TTL_MS = 72 * 60 * 60 * 1000 // 72 hours\n\nexport class CustomerInvitationService {\n constructor(private em: EntityManager) {}\n\n async createInvitation(\n email: string,\n scope: { tenantId: string; organizationId: string },\n options: {\n customerEntityId?: string | null\n roleIds: string[]\n invitedByUserId?: string | null\n invitedByCustomerUserId?: string | null\n displayName?: string | null\n },\n ): Promise<{ invitation: CustomerUserInvitation; rawToken: string }> {\n const token = generateSecureToken()\n const emailHash = hashForLookup(email)\n const normalizedEmail = email.toLowerCase().trim()\n const expiresAt = new Date(Date.now() + INVITATION_TTL_MS)\n const tokenHashed = hashToken(token)\n\n // Dedupe: reuse an existing pending (not accepted, not cancelled, unexpired)\n // invitation for the same recipient instead of inserting a new row. This caps\n // row/token growth and keeps a single live token per concurrently-pending\n // (tenant, organization, email) tuple.\n const existing = await findOneWithDecryption(\n this.em,\n CustomerUserInvitation,\n {\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n emailHash,\n acceptedAt: null,\n cancelledAt: null,\n expiresAt: { $gt: new Date() },\n } as any,\n undefined,\n { tenantId: scope.tenantId, organizationId: scope.organizationId },\n )\n\n if (existing) {\n existing.email = normalizedEmail\n existing.token = tokenHashed\n existing.customerEntityId = options.customerEntityId || null\n existing.roleIdsJson = options.roleIds\n existing.invitedByUserId = options.invitedByUserId || null\n existing.invitedByCustomerUserId = options.invitedByCustomerUserId || null\n existing.displayName = options.displayName || null\n existing.expiresAt = expiresAt\n await this.em.flush()\n return { invitation: existing, rawToken: token }\n }\n\n const invitation = this.em.create(CustomerUserInvitation, {\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n email: normalizedEmail,\n emailHash,\n token: tokenHashed,\n customerEntityId: options.customerEntityId || null,\n roleIdsJson: options.roleIds,\n invitedByUserId: options.invitedByUserId || null,\n invitedByCustomerUserId: options.invitedByCustomerUserId || null,\n displayName: options.displayName || null,\n expiresAt,\n createdAt: new Date(),\n } as any) as CustomerUserInvitation\n await this.em.persist(invitation).flush()\n return { invitation, rawToken: token }\n }\n\n async findByToken(token: string): Promise<CustomerUserInvitation | null> {\n const tokenHashed = hashToken(token)\n const invitation = await findOneWithDecryption(\n this.em,\n CustomerUserInvitation,\n { token: tokenHashed } as any,\n )\n if (!invitation) return null\n if (invitation.acceptedAt) return null\n if (invitation.cancelledAt) return null\n if (invitation.expiresAt.getTime() < Date.now()) return null\n return invitation\n }\n\n async acceptInvitation(\n token: string,\n password: string,\n displayName: string,\n ): Promise<{ user: CustomerUser; invitation: CustomerUserInvitation } | null> {\n const invitation = await this.findByToken(token)\n if (!invitation) return null\n\n const passwordHash = await hash(password, BCRYPT_COST)\n const emailHash = hashForLookup(invitation.email)\n\n // Create user\n const user = this.em.create(CustomerUser, {\n email: invitation.email,\n emailHash,\n passwordHash,\n displayName: displayName || invitation.displayName || invitation.email,\n tenantId: invitation.tenantId,\n organizationId: invitation.organizationId,\n customerEntityId: invitation.customerEntityId || null,\n isActive: true,\n emailVerifiedAt: new Date(), // Invitation implicitly verifies email\n failedLoginAttempts: 0,\n createdAt: new Date(),\n } as any) as CustomerUser\n this.em.persist(user)\n\n // Assign roles\n const roleIds = Array.isArray(invitation.roleIdsJson) ? invitation.roleIdsJson : []\n const roles = roleIds.length > 0\n ? await findWithDecryption(\n this.em,\n CustomerRole,\n {\n id: { $in: roleIds } as any,\n tenantId: invitation.tenantId,\n organizationId: invitation.organizationId,\n deletedAt: null,\n } as any,\n undefined,\n { tenantId: invitation.tenantId, organizationId: invitation.organizationId },\n )\n : []\n for (const role of roles) {\n const userRole = this.em.create(CustomerUserRole, {\n user,\n role,\n createdAt: new Date(),\n } as any)\n this.em.persist(userRole)\n }\n\n // Mark invitation as accepted\n invitation.acceptedAt = new Date()\n\n await this.em.flush()\n return { user, invitation }\n }\n}\n"],
|
|
5
|
+
"mappings": "AACA,SAAS,YAAY;AACrB;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,qBAAqB,iBAAiB;AAC/C,SAAS,qBAAqB;AAC9B,SAAS,uBAAuB,0BAA0B;AAE1D,MAAM,cAAc;AACpB,MAAM,oBAAoB,KAAK,KAAK,KAAK;AAElC,MAAM,0BAA0B;AAAA,EACrC,YAAoB,IAAmB;AAAnB;AAAA,EAAoB;AAAA,EAExC,MAAM,iBACJ,OACA,OACA,SAOmE;AACnE,UAAM,QAAQ,oBAAoB;AAClC,UAAM,YAAY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AW,eAAe;AAAA,IAC7E,IACA,CAAC;AACL,eAAW,QAAQ,OAAO;AACxB,YAAM,WAAW,KAAK,GAAG,OAAO,kBAAkB;AAAA,QAChD;AAAA,QACA;AAAA,QACA,WAAW,oBAAI,KAAK;AAAA,MACtB,CAAQ;AACR,WAAK,GAAG,QAAQ,QAAQ;AAAA,IAC1B;AAGA,eAAW,aAAa,oBAAI,KAAK;AAEjC,UAAM,KAAK,GAAG,MAAM;AACpB,WAAO,EAAE,MAAM,WAAW;AAAA,EAC5B;AACF;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -19,7 +19,7 @@ class CustomerRbacService {
|
|
|
19
19
|
this.cache = cache || null;
|
|
20
20
|
}
|
|
21
21
|
getCacheKey(userId, scope) {
|
|
22
|
-
return `customer_rbac:${userId}:${scope.tenantId}:${scope.organizationId}`;
|
|
22
|
+
return `customer_rbac:v2:${userId}:${scope.tenantId}:${scope.organizationId}`;
|
|
23
23
|
}
|
|
24
24
|
getUserTag(userId) {
|
|
25
25
|
return `customer_rbac:user:${userId}`;
|
|
@@ -61,6 +61,11 @@ class CustomerRbacService {
|
|
|
61
61
|
}
|
|
62
62
|
const links = await em.find(CustomerUserRole, {
|
|
63
63
|
user: userId,
|
|
64
|
+
role: {
|
|
65
|
+
tenantId: scope.tenantId,
|
|
66
|
+
organizationId: scope.organizationId,
|
|
67
|
+
deletedAt: null
|
|
68
|
+
},
|
|
64
69
|
deletedAt: null
|
|
65
70
|
}, { populate: ["role"] });
|
|
66
71
|
const roleIds = links.map((l) => l.role?.id).filter(Boolean);
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/modules/customer_accounts/services/customerRbacService.ts"],
|
|
4
|
-
"sourcesContent": ["import { EntityManager } from '@mikro-orm/postgresql'\nimport type { CacheStrategy } from '@open-mercato/cache'\nimport {\n CustomerUserAcl,\n CustomerRoleAcl,\n CustomerUserRole,\n} from '@open-mercato/core/modules/customer_accounts/data/entities'\nimport { hasAllFeatures } from '@open-mercato/shared/lib/auth/featureMatch'\n\ninterface CustomerAclData {\n isPortalAdmin: boolean\n features: string[]\n}\n\nfunction isCustomerAclData(value: unknown): value is CustomerAclData {\n if (typeof value !== 'object' || value === null) return false\n const record = value as Partial<CustomerAclData>\n if (typeof record.isPortalAdmin !== 'boolean') return false\n if (!Array.isArray(record.features) || record.features.some((f) => typeof f !== 'string')) return false\n return true\n}\n\nexport class CustomerRbacService {\n private cacheTtlMs: number = 5 * 60 * 1000\n private cache: CacheStrategy | null = null\n\n constructor(private em: EntityManager, cache?: CacheStrategy) {\n this.cache = cache || null\n }\n\n private getCacheKey(userId: string, scope: { tenantId: string; organizationId: string }): string {\n return `customer_rbac:${userId}:${scope.tenantId}:${scope.organizationId}`\n }\n\n private getUserTag(userId: string): string {\n return `customer_rbac:user:${userId}`\n }\n\n private getTenantTag(tenantId: string): string {\n return `customer_rbac:tenant:${tenantId}`\n }\n\n private async getFromCache(cacheKey: string): Promise<CustomerAclData | null> {\n if (!this.cache) return null\n const cached = await this.cache.get(cacheKey)\n if (!cached) return null\n return isCustomerAclData(cached) ? cached : null\n }\n\n private async setCache(\n cacheKey: string,\n data: CustomerAclData,\n userId: string,\n scope: { tenantId: string; organizationId: string },\n ): Promise<void> {\n if (!this.cache) return\n const tags = [\n this.getUserTag(userId),\n this.getTenantTag(scope.tenantId),\n 'customer_rbac:all',\n ]\n await this.cache.set(cacheKey, data, { ttl: this.cacheTtlMs, tags })\n }\n\n async loadAcl(\n userId: string,\n scope: { tenantId: string; organizationId: string },\n ): Promise<CustomerAclData> {\n const cacheKey = this.getCacheKey(userId, scope)\n const cached = await this.getFromCache(cacheKey)\n if (cached) return cached\n\n const em = this.em.fork()\n\n // Per-user ACL first\n const userAcl = await em.findOne(CustomerUserAcl, {\n user: userId as any,\n tenantId: scope.tenantId,\n })\n if (userAcl) {\n const result: CustomerAclData = {\n isPortalAdmin: !!userAcl.isPortalAdmin,\n features: Array.isArray(userAcl.featuresJson) ? userAcl.featuresJson : [],\n }\n await this.setCache(cacheKey, result, userId, scope)\n return result\n }\n\n // Aggregate role ACLs\n const links = await em.find(CustomerUserRole, {\n user: userId as any,\n deletedAt: null,\n }, { populate: ['role'] })\n const roleIds = links.map((l) => (l.role as any)?.id).filter(Boolean)\n\n let isPortalAdmin = false\n const features: string[] = []\n if (roleIds.length) {\n const roleAcls = await em.find(CustomerRoleAcl, {\n tenantId: scope.tenantId,\n role: { $in: roleIds as any },\n } as any)\n for (const acl of roleAcls) {\n isPortalAdmin = isPortalAdmin || !!acl.isPortalAdmin\n if (Array.isArray(acl.featuresJson)) {\n for (const f of acl.featuresJson) {\n if (!features.includes(f)) features.push(f)\n }\n }\n }\n }\n\n const result: CustomerAclData = { isPortalAdmin, features }\n await this.setCache(cacheKey, result, userId, scope)\n return result\n }\n\n async userHasAllFeatures(\n userId: string,\n required: string[],\n scope: { tenantId: string; organizationId: string },\n ): Promise<boolean> {\n if (!required.length) return true\n const acl = await this.loadAcl(userId, scope)\n if (acl.isPortalAdmin) return true\n return hasAllFeatures(required, acl.features)\n }\n\n async invalidateUserCache(userId: string): Promise<void> {\n if (!this.cache) return\n await this.cache.deleteByTags([this.getUserTag(userId)])\n }\n\n async invalidateRoleCache(roleId: string): Promise<void> {\n if (!this.cache) return\n // When a role changes, invalidate all customer RBAC caches since we don't track role\u2192user mappings\n await this.cache.deleteByTags(['customer_rbac:all'])\n }\n\n async invalidateTenantCache(tenantId: string): Promise<void> {\n if (!this.cache) return\n await this.cache.deleteByTags([this.getTenantTag(tenantId)])\n }\n}\n"],
|
|
5
|
-
"mappings": "AAEA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,sBAAsB;AAO/B,SAAS,kBAAkB,OAA0C;AACnE,MAAI,OAAO,UAAU,YAAY,UAAU,KAAM,QAAO;AACxD,QAAM,SAAS;AACf,MAAI,OAAO,OAAO,kBAAkB,UAAW,QAAO;AACtD,MAAI,CAAC,MAAM,QAAQ,OAAO,QAAQ,KAAK,OAAO,SAAS,KAAK,CAAC,MAAM,OAAO,MAAM,QAAQ,EAAG,QAAO;AAClG,SAAO;AACT;AAEO,MAAM,oBAAoB;AAAA,EAI/B,YAAoB,IAAmB,OAAuB;AAA1C;AAHpB,SAAQ,aAAqB,IAAI,KAAK;AACtC,SAAQ,QAA8B;AAGpC,SAAK,QAAQ,SAAS;AAAA,EACxB;AAAA,EAEQ,YAAY,QAAgB,OAA6D;
|
|
4
|
+
"sourcesContent": ["import { EntityManager } from '@mikro-orm/postgresql'\nimport type { CacheStrategy } from '@open-mercato/cache'\nimport {\n CustomerUserAcl,\n CustomerRoleAcl,\n CustomerUserRole,\n} from '@open-mercato/core/modules/customer_accounts/data/entities'\nimport { hasAllFeatures } from '@open-mercato/shared/lib/auth/featureMatch'\n\ninterface CustomerAclData {\n isPortalAdmin: boolean\n features: string[]\n}\n\nfunction isCustomerAclData(value: unknown): value is CustomerAclData {\n if (typeof value !== 'object' || value === null) return false\n const record = value as Partial<CustomerAclData>\n if (typeof record.isPortalAdmin !== 'boolean') return false\n if (!Array.isArray(record.features) || record.features.some((f) => typeof f !== 'string')) return false\n return true\n}\n\nexport class CustomerRbacService {\n private cacheTtlMs: number = 5 * 60 * 1000\n private cache: CacheStrategy | null = null\n\n constructor(private em: EntityManager, cache?: CacheStrategy) {\n this.cache = cache || null\n }\n\n private getCacheKey(userId: string, scope: { tenantId: string; organizationId: string }): string {\n // Keep the authorization query versioned in the key so cache entries created\n // before scope hardening cannot preserve grants that are no longer valid.\n return `customer_rbac:v2:${userId}:${scope.tenantId}:${scope.organizationId}`\n }\n\n private getUserTag(userId: string): string {\n return `customer_rbac:user:${userId}`\n }\n\n private getTenantTag(tenantId: string): string {\n return `customer_rbac:tenant:${tenantId}`\n }\n\n private async getFromCache(cacheKey: string): Promise<CustomerAclData | null> {\n if (!this.cache) return null\n const cached = await this.cache.get(cacheKey)\n if (!cached) return null\n return isCustomerAclData(cached) ? cached : null\n }\n\n private async setCache(\n cacheKey: string,\n data: CustomerAclData,\n userId: string,\n scope: { tenantId: string; organizationId: string },\n ): Promise<void> {\n if (!this.cache) return\n const tags = [\n this.getUserTag(userId),\n this.getTenantTag(scope.tenantId),\n 'customer_rbac:all',\n ]\n await this.cache.set(cacheKey, data, { ttl: this.cacheTtlMs, tags })\n }\n\n async loadAcl(\n userId: string,\n scope: { tenantId: string; organizationId: string },\n ): Promise<CustomerAclData> {\n const cacheKey = this.getCacheKey(userId, scope)\n const cached = await this.getFromCache(cacheKey)\n if (cached) return cached\n\n const em = this.em.fork()\n\n // Per-user ACL first\n const userAcl = await em.findOne(CustomerUserAcl, {\n user: userId as any,\n tenantId: scope.tenantId,\n })\n if (userAcl) {\n const result: CustomerAclData = {\n isPortalAdmin: !!userAcl.isPortalAdmin,\n features: Array.isArray(userAcl.featuresJson) ? userAcl.featuresJson : [],\n }\n await this.setCache(cacheKey, result, userId, scope)\n return result\n }\n\n // Aggregate role ACLs\n const links = await em.find(CustomerUserRole, {\n user: userId as any,\n role: {\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n deletedAt: null,\n },\n deletedAt: null,\n } as any, { populate: ['role'] })\n const roleIds = links.map((l) => (l.role as any)?.id).filter(Boolean)\n\n let isPortalAdmin = false\n const features: string[] = []\n if (roleIds.length) {\n const roleAcls = await em.find(CustomerRoleAcl, {\n tenantId: scope.tenantId,\n role: { $in: roleIds as any },\n } as any)\n for (const acl of roleAcls) {\n isPortalAdmin = isPortalAdmin || !!acl.isPortalAdmin\n if (Array.isArray(acl.featuresJson)) {\n for (const f of acl.featuresJson) {\n if (!features.includes(f)) features.push(f)\n }\n }\n }\n }\n\n const result: CustomerAclData = { isPortalAdmin, features }\n await this.setCache(cacheKey, result, userId, scope)\n return result\n }\n\n async userHasAllFeatures(\n userId: string,\n required: string[],\n scope: { tenantId: string; organizationId: string },\n ): Promise<boolean> {\n if (!required.length) return true\n const acl = await this.loadAcl(userId, scope)\n if (acl.isPortalAdmin) return true\n return hasAllFeatures(required, acl.features)\n }\n\n async invalidateUserCache(userId: string): Promise<void> {\n if (!this.cache) return\n await this.cache.deleteByTags([this.getUserTag(userId)])\n }\n\n async invalidateRoleCache(roleId: string): Promise<void> {\n if (!this.cache) return\n // When a role changes, invalidate all customer RBAC caches since we don't track role\u2192user mappings\n await this.cache.deleteByTags(['customer_rbac:all'])\n }\n\n async invalidateTenantCache(tenantId: string): Promise<void> {\n if (!this.cache) return\n await this.cache.deleteByTags([this.getTenantTag(tenantId)])\n }\n}\n"],
|
|
5
|
+
"mappings": "AAEA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,sBAAsB;AAO/B,SAAS,kBAAkB,OAA0C;AACnE,MAAI,OAAO,UAAU,YAAY,UAAU,KAAM,QAAO;AACxD,QAAM,SAAS;AACf,MAAI,OAAO,OAAO,kBAAkB,UAAW,QAAO;AACtD,MAAI,CAAC,MAAM,QAAQ,OAAO,QAAQ,KAAK,OAAO,SAAS,KAAK,CAAC,MAAM,OAAO,MAAM,QAAQ,EAAG,QAAO;AAClG,SAAO;AACT;AAEO,MAAM,oBAAoB;AAAA,EAI/B,YAAoB,IAAmB,OAAuB;AAA1C;AAHpB,SAAQ,aAAqB,IAAI,KAAK;AACtC,SAAQ,QAA8B;AAGpC,SAAK,QAAQ,SAAS;AAAA,EACxB;AAAA,EAEQ,YAAY,QAAgB,OAA6D;AAG/F,WAAO,oBAAoB,MAAM,IAAI,MAAM,QAAQ,IAAI,MAAM,cAAc;AAAA,EAC7E;AAAA,EAEQ,WAAW,QAAwB;AACzC,WAAO,sBAAsB,MAAM;AAAA,EACrC;AAAA,EAEQ,aAAa,UAA0B;AAC7C,WAAO,wBAAwB,QAAQ;AAAA,EACzC;AAAA,EAEA,MAAc,aAAa,UAAmD;AAC5E,QAAI,CAAC,KAAK,MAAO,QAAO;AACxB,UAAM,SAAS,MAAM,KAAK,MAAM,IAAI,QAAQ;AAC5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
|
|
13
13
|
list: translateWithFallback(t, "customers.deals.kanban.view.list", "List"),
|
|
14
14
|
map: translateWithFallback(t, "customers.deals.kanban.view.map", "Map")
|
|
15
15
|
};
|
|
16
|
-
const baseTab = "inline-flex items-center px-3.5 py-2.5 text-sm leading-normal transition-colors focus-visible:outline-none focus-visible:
|
|
17
|
-
const activeTab = "border-b-2 border-
|
|
16
|
+
const baseTab = "inline-flex items-center px-3.5 py-2.5 text-sm leading-normal transition-colors focus-visible:outline-none focus-visible:shadow-focus";
|
|
17
|
+
const activeTab = "border-b-2 border-accent-indigo font-semibold text-foreground";
|
|
18
18
|
const inactiveTab = "border-b-2 border-transparent font-normal text-muted-foreground hover:text-foreground";
|
|
19
19
|
const isKanbanActive = active === "kanban";
|
|
20
20
|
const isListActive = active === "list";
|
package/dist/modules/customers/backend/customers/deals/pipeline/components/ViewTabsRow.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../../../../../src/modules/customers/backend/customers/deals/pipeline/components/ViewTabsRow.tsx"],
|
|
4
|
-
"sourcesContent": ["\"use client\"\n\nimport * as React from 'react'\nimport Link from 'next/link'\nimport { useT } from '@open-mercato/shared/lib/i18n/context'\nimport { translateWithFallback } from '@open-mercato/shared/lib/i18n/translate'\n\nexport type KanbanView = 'kanban' | 'list' | 'map'\n\ntype ViewTabsRowProps = {\n active: KanbanView\n className?: string\n}\n\nconst VIEW_KANBAN_HREF = '/backend/customers/deals/pipeline'\nconst VIEW_LIST_HREF = '/backend/customers/deals'\nconst VIEW_MAP_HREF = '/backend/customers/deals/map'\n\nexport function ViewTabsRow({ active, className }: ViewTabsRowProps): React.ReactElement {\n const t = useT()\n const labels = {\n kanban: translateWithFallback(t, 'customers.deals.kanban.view.kanban', 'Kanban'),\n list: translateWithFallback(t, 'customers.deals.kanban.view.list', 'List'),\n map: translateWithFallback(t, 'customers.deals.kanban.view.map', 'Map'),\n }\n\n const baseTab =\n 'inline-flex items-center px-3.5 py-2.5 text-sm leading-normal transition-colors focus-visible:outline-none focus-visible:
|
|
5
|
-
"mappings": ";
|
|
4
|
+
"sourcesContent": ["\"use client\"\n\nimport * as React from 'react'\nimport Link from 'next/link'\nimport { useT } from '@open-mercato/shared/lib/i18n/context'\nimport { translateWithFallback } from '@open-mercato/shared/lib/i18n/translate'\n\nexport type KanbanView = 'kanban' | 'list' | 'map'\n\ntype ViewTabsRowProps = {\n active: KanbanView\n className?: string\n}\n\nconst VIEW_KANBAN_HREF = '/backend/customers/deals/pipeline'\nconst VIEW_LIST_HREF = '/backend/customers/deals'\nconst VIEW_MAP_HREF = '/backend/customers/deals/map'\n\nexport function ViewTabsRow({ active, className }: ViewTabsRowProps): React.ReactElement {\n const t = useT()\n const labels = {\n kanban: translateWithFallback(t, 'customers.deals.kanban.view.kanban', 'Kanban'),\n list: translateWithFallback(t, 'customers.deals.kanban.view.list', 'List'),\n map: translateWithFallback(t, 'customers.deals.kanban.view.map', 'Map'),\n }\n\n // Link-based tab row (two routes), so the Tabs primitive (state-driven,\n // onValueChange) does not fit \u2014 real <Link> semantics must stay. Classes\n // mirror the Tabs underline variant: accent-indigo active border,\n // shadow-focus halo.\n const baseTab =\n 'inline-flex items-center px-3.5 py-2.5 text-sm leading-normal transition-colors focus-visible:outline-none focus-visible:shadow-focus'\n const activeTab = 'border-b-2 border-accent-indigo font-semibold text-foreground'\n const inactiveTab = 'border-b-2 border-transparent font-normal text-muted-foreground hover:text-foreground'\n\n // Renders the active tab as a non-navigating `<span>` and the inactive tab as a `<Link>`,\n // so the user can always round-trip between kanban and list from either page. Previously\n // the kanban tab was a hardcoded `<span>` because the row was only rendered on the kanban\n // page \u2014 adding it to the list page (item 7 of the SPEC-048 UX review) requires it to\n // navigate back to /pipeline.\n const isKanbanActive = active === 'kanban'\n const isListActive = active === 'list'\n const isMapActive = active === 'map'\n\n return (\n <div\n role=\"tablist\"\n aria-label={translateWithFallback(t, 'customers.deals.kanban.view.tablistLabel', 'Deals views')}\n className={`flex items-end gap-1 border-b border-border ${className ?? ''}`.trim()}\n >\n {isKanbanActive ? (\n <span\n role=\"tab\"\n aria-selected={true}\n className={`${baseTab} ${activeTab}`}\n >\n {labels.kanban}\n </span>\n ) : (\n <Link\n href={VIEW_KANBAN_HREF}\n role=\"tab\"\n aria-selected={false}\n className={`${baseTab} ${inactiveTab}`}\n >\n {labels.kanban}\n </Link>\n )}\n {isListActive ? (\n <span\n role=\"tab\"\n aria-selected={true}\n className={`${baseTab} ${activeTab}`}\n >\n {labels.list}\n </span>\n ) : (\n <Link\n href={VIEW_LIST_HREF}\n role=\"tab\"\n aria-selected={false}\n className={`${baseTab} ${inactiveTab}`}\n >\n {labels.list}\n </Link>\n )}\n {isMapActive ? (\n <span\n role=\"tab\"\n aria-selected={true}\n className={`${baseTab} ${activeTab}`}\n >\n {labels.map}\n </span>\n ) : (\n <Link\n href={VIEW_MAP_HREF}\n role=\"tab\"\n aria-selected={false}\n className={`${baseTab} ${inactiveTab}`}\n >\n {labels.map}\n </Link>\n )}\n </div>\n )\n}\n\nexport default ViewTabsRow\n"],
|
|
5
|
+
"mappings": ";AA6CI,SAMI,KANJ;AA1CJ,OAAO,UAAU;AACjB,SAAS,YAAY;AACrB,SAAS,6BAA6B;AAStC,MAAM,mBAAmB;AACzB,MAAM,iBAAiB;AACvB,MAAM,gBAAgB;AAEf,SAAS,YAAY,EAAE,QAAQ,UAAU,GAAyC;AACvF,QAAM,IAAI,KAAK;AACf,QAAM,SAAS;AAAA,IACb,QAAQ,sBAAsB,GAAG,sCAAsC,QAAQ;AAAA,IAC/E,MAAM,sBAAsB,GAAG,oCAAoC,MAAM;AAAA,IACzE,KAAK,sBAAsB,GAAG,mCAAmC,KAAK;AAAA,EACxE;AAMA,QAAM,UACJ;AACF,QAAM,YAAY;AAClB,QAAM,cAAc;AAOpB,QAAM,iBAAiB,WAAW;AAClC,QAAM,eAAe,WAAW;AAChC,QAAM,cAAc,WAAW;AA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