@open-mercato/core 0.6.1-develop.3139.9fc38487c8 → 0.6.1-develop.3144.b39fb4dfa6
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/dist/modules/catalog/api/dictionaries/[key]/route.js +2 -2
- package/dist/modules/catalog/api/dictionaries/[key]/route.js.map +2 -2
- package/dist/modules/customers/api/activities/route.js +5 -5
- package/dist/modules/customers/api/activities/route.js.map +2 -2
- package/dist/modules/customers/api/assignable-staff/route.js +2 -2
- package/dist/modules/customers/api/assignable-staff/route.js.map +2 -2
- package/dist/modules/customers/api/companies/[id]/people/route.js +2 -2
- package/dist/modules/customers/api/companies/[id]/people/route.js.map +2 -2
- package/dist/modules/customers/api/dashboard/widgets/customer-todos/route.js +2 -2
- package/dist/modules/customers/api/dashboard/widgets/customer-todos/route.js.map +2 -2
- package/dist/modules/customers/api/dashboard/widgets/new-customers/route.js +2 -2
- package/dist/modules/customers/api/dashboard/widgets/new-customers/route.js.map +2 -2
- package/dist/modules/customers/api/dashboard/widgets/new-deals/route.js +2 -2
- package/dist/modules/customers/api/dashboard/widgets/new-deals/route.js.map +2 -2
- package/dist/modules/customers/api/dashboard/widgets/next-interactions/route.js +2 -2
- package/dist/modules/customers/api/dashboard/widgets/next-interactions/route.js.map +2 -2
- package/dist/modules/customers/api/deals/[id]/companies/route.js +2 -2
- package/dist/modules/customers/api/deals/[id]/companies/route.js.map +2 -2
- package/dist/modules/customers/api/deals/[id]/people/route.js +2 -2
- package/dist/modules/customers/api/deals/[id]/people/route.js.map +2 -2
- package/dist/modules/customers/api/dictionaries/[kind]/[id]/route.js +6 -6
- package/dist/modules/customers/api/dictionaries/[kind]/[id]/route.js.map +2 -2
- package/dist/modules/customers/api/dictionaries/[kind]/route.js +3 -3
- package/dist/modules/customers/api/dictionaries/[kind]/route.js.map +2 -2
- package/dist/modules/customers/api/dictionaries/currency/route.js +2 -2
- package/dist/modules/customers/api/dictionaries/currency/route.js.map +2 -2
- package/dist/modules/customers/api/dictionaries/kind-settings/route.js +3 -3
- package/dist/modules/customers/api/dictionaries/kind-settings/route.js.map +2 -2
- package/dist/modules/customers/api/entity-roles-factory.js +5 -5
- package/dist/modules/customers/api/entity-roles-factory.js.map +2 -2
- package/dist/modules/customers/api/interactions/cancel/route.js +2 -2
- package/dist/modules/customers/api/interactions/cancel/route.js.map +2 -2
- package/dist/modules/customers/api/interactions/complete/route.js +2 -2
- package/dist/modules/customers/api/interactions/complete/route.js.map +2 -2
- package/dist/modules/customers/api/interactions/conflicts/route.js +2 -2
- package/dist/modules/customers/api/interactions/conflicts/route.js.map +2 -2
- package/dist/modules/customers/api/interactions/counts/route.js +2 -2
- package/dist/modules/customers/api/interactions/counts/route.js.map +2 -2
- package/dist/modules/customers/api/interactions/route.js +2 -2
- package/dist/modules/customers/api/interactions/route.js.map +2 -2
- package/dist/modules/customers/api/interactions/tasks/route.js +2 -2
- package/dist/modules/customers/api/interactions/tasks/route.js.map +2 -2
- package/dist/modules/customers/api/labels/assign/route.js +2 -2
- package/dist/modules/customers/api/labels/assign/route.js.map +2 -2
- package/dist/modules/customers/api/labels/route.js +3 -3
- package/dist/modules/customers/api/labels/route.js.map +2 -2
- package/dist/modules/customers/api/labels/unassign/route.js +2 -2
- package/dist/modules/customers/api/labels/unassign/route.js.map +2 -2
- package/dist/modules/customers/api/people/[id]/companies/[linkId]/route.js +3 -3
- package/dist/modules/customers/api/people/[id]/companies/[linkId]/route.js.map +2 -2
- package/dist/modules/customers/api/people/[id]/companies/enriched/route.js +2 -2
- package/dist/modules/customers/api/people/[id]/companies/enriched/route.js.map +2 -2
- package/dist/modules/customers/api/people/[id]/companies/route.js +3 -3
- package/dist/modules/customers/api/people/[id]/companies/route.js.map +2 -2
- package/dist/modules/customers/api/pipeline-stages/reorder/route.js +2 -2
- package/dist/modules/customers/api/pipeline-stages/reorder/route.js.map +2 -2
- package/dist/modules/customers/api/pipeline-stages/route.js +5 -5
- package/dist/modules/customers/api/pipeline-stages/route.js.map +2 -2
- package/dist/modules/customers/api/pipelines/route.js +5 -5
- package/dist/modules/customers/api/pipelines/route.js.map +2 -2
- package/dist/modules/customers/api/settings/address-format/route.js +3 -3
- package/dist/modules/customers/api/settings/address-format/route.js.map +2 -2
- package/dist/modules/customers/api/tags/assign/route.js +2 -2
- package/dist/modules/customers/api/tags/assign/route.js.map +2 -2
- package/dist/modules/customers/api/tags/unassign/route.js +2 -2
- package/dist/modules/customers/api/tags/unassign/route.js.map +2 -2
- package/dist/modules/customers/api/todos/route.js +5 -5
- package/dist/modules/customers/api/todos/route.js.map +2 -2
- package/dist/modules/dictionaries/api/[dictionaryId]/entries/[entryId]/route.js +3 -3
- package/dist/modules/dictionaries/api/[dictionaryId]/entries/[entryId]/route.js.map +2 -2
- package/dist/modules/dictionaries/api/[dictionaryId]/entries/reorder/route.js +2 -2
- package/dist/modules/dictionaries/api/[dictionaryId]/entries/reorder/route.js.map +2 -2
- package/dist/modules/dictionaries/api/[dictionaryId]/entries/route.js +3 -3
- package/dist/modules/dictionaries/api/[dictionaryId]/entries/route.js.map +2 -2
- package/dist/modules/dictionaries/api/[dictionaryId]/entries/set-default/route.js +2 -2
- package/dist/modules/dictionaries/api/[dictionaryId]/entries/set-default/route.js.map +2 -2
- package/dist/modules/dictionaries/api/[dictionaryId]/route.js +4 -4
- package/dist/modules/dictionaries/api/[dictionaryId]/route.js.map +2 -2
- package/dist/modules/dictionaries/api/route.js +3 -3
- package/dist/modules/dictionaries/api/route.js.map +2 -2
- package/dist/modules/feature_toggles/api/overrides/route.js +2 -2
- package/dist/modules/feature_toggles/api/overrides/route.js.map +2 -2
- package/dist/modules/planner/api/availability-date-specific.js +2 -2
- package/dist/modules/planner/api/availability-date-specific.js.map +2 -2
- package/dist/modules/planner/api/availability-weekly.js +2 -2
- package/dist/modules/planner/api/availability-weekly.js.map +2 -2
- package/dist/modules/resources/api/resources/tags/assign/route.js +2 -2
- package/dist/modules/resources/api/resources/tags/assign/route.js.map +2 -2
- package/dist/modules/resources/api/resources/tags/unassign/route.js +2 -2
- package/dist/modules/resources/api/resources/tags/unassign/route.js.map +2 -2
- package/dist/modules/sales/api/document-history/route.js +2 -2
- package/dist/modules/sales/api/document-history/route.js.map +2 -2
- package/dist/modules/sales/api/document-numbers/route.js +2 -2
- package/dist/modules/sales/api/document-numbers/route.js.map +2 -2
- package/dist/modules/sales/api/quotes/accept/route.js +2 -2
- package/dist/modules/sales/api/quotes/accept/route.js.map +2 -2
- package/dist/modules/sales/api/quotes/convert/route.js +2 -2
- package/dist/modules/sales/api/quotes/convert/route.js.map +2 -2
- package/dist/modules/sales/api/quotes/public/[token]/route.js +2 -2
- package/dist/modules/sales/api/quotes/public/[token]/route.js.map +2 -2
- package/dist/modules/sales/api/quotes/send/route.js +2 -2
- package/dist/modules/sales/api/quotes/send/route.js.map +2 -2
- package/dist/modules/sales/api/returns/[id]/route.js +2 -2
- package/dist/modules/sales/api/returns/[id]/route.js.map +2 -2
- package/dist/modules/sales/api/settings/document-numbers/route.js +3 -3
- package/dist/modules/sales/api/settings/document-numbers/route.js.map +2 -2
- package/dist/modules/sales/api/settings/order-editing/route.js +3 -3
- package/dist/modules/sales/api/settings/order-editing/route.js.map +2 -2
- package/dist/modules/sales/widgets/dashboard/makeDashboardWidgetRoute.js +2 -2
- package/dist/modules/sales/widgets/dashboard/makeDashboardWidgetRoute.js.map +2 -2
- package/dist/modules/staff/api/leave-requests/accept/route.js +2 -2
- package/dist/modules/staff/api/leave-requests/accept/route.js.map +2 -2
- package/dist/modules/staff/api/leave-requests/reject/route.js +2 -2
- package/dist/modules/staff/api/leave-requests/reject/route.js.map +2 -2
- package/dist/modules/staff/api/team-members/self/route.js +3 -3
- package/dist/modules/staff/api/team-members/self/route.js.map +2 -2
- package/dist/modules/staff/api/team-members/tags/assign/route.js +2 -2
- package/dist/modules/staff/api/team-members/tags/assign/route.js.map +2 -2
- package/dist/modules/staff/api/team-members/tags/unassign/route.js +2 -2
- package/dist/modules/staff/api/team-members/tags/unassign/route.js.map +2 -2
- package/dist/modules/translations/api/[entityType]/[entityId]/route.js +4 -4
- package/dist/modules/translations/api/[entityType]/[entityId]/route.js.map +2 -2
- package/dist/modules/translations/api/get/locales.js +2 -2
- package/dist/modules/translations/api/get/locales.js.map +2 -2
- package/dist/modules/translations/api/put/locales.js +2 -2
- package/dist/modules/translations/api/put/locales.js.map +2 -2
- package/package.json +5 -5
- package/src/modules/catalog/api/dictionaries/[key]/route.ts +2 -2
- package/src/modules/customers/api/activities/route.ts +5 -5
- package/src/modules/customers/api/assignable-staff/route.ts +2 -2
- package/src/modules/customers/api/companies/[id]/people/route.ts +2 -2
- package/src/modules/customers/api/dashboard/widgets/customer-todos/route.ts +2 -2
- package/src/modules/customers/api/dashboard/widgets/new-customers/route.ts +2 -2
- package/src/modules/customers/api/dashboard/widgets/new-deals/route.ts +2 -2
- package/src/modules/customers/api/dashboard/widgets/next-interactions/route.ts +2 -2
- package/src/modules/customers/api/deals/[id]/companies/route.ts +2 -2
- package/src/modules/customers/api/deals/[id]/people/route.ts +2 -2
- package/src/modules/customers/api/dictionaries/[kind]/[id]/route.ts +6 -6
- package/src/modules/customers/api/dictionaries/[kind]/route.ts +3 -3
- package/src/modules/customers/api/dictionaries/currency/route.ts +2 -2
- package/src/modules/customers/api/dictionaries/kind-settings/route.ts +3 -3
- package/src/modules/customers/api/entity-roles-factory.ts +5 -5
- package/src/modules/customers/api/interactions/cancel/route.ts +2 -2
- package/src/modules/customers/api/interactions/complete/route.ts +2 -2
- package/src/modules/customers/api/interactions/conflicts/route.ts +2 -2
- package/src/modules/customers/api/interactions/counts/route.ts +2 -2
- package/src/modules/customers/api/interactions/route.ts +2 -2
- package/src/modules/customers/api/interactions/tasks/route.ts +2 -2
- package/src/modules/customers/api/labels/assign/route.ts +2 -2
- package/src/modules/customers/api/labels/route.ts +3 -3
- package/src/modules/customers/api/labels/unassign/route.ts +2 -2
- package/src/modules/customers/api/people/[id]/companies/[linkId]/route.ts +3 -3
- package/src/modules/customers/api/people/[id]/companies/enriched/route.ts +2 -2
- package/src/modules/customers/api/people/[id]/companies/route.ts +3 -3
- package/src/modules/customers/api/pipeline-stages/reorder/route.ts +2 -2
- package/src/modules/customers/api/pipeline-stages/route.ts +5 -5
- package/src/modules/customers/api/pipelines/route.ts +5 -5
- package/src/modules/customers/api/settings/address-format/route.ts +3 -3
- package/src/modules/customers/api/tags/assign/route.ts +2 -2
- package/src/modules/customers/api/tags/unassign/route.ts +2 -2
- package/src/modules/customers/api/todos/route.ts +5 -5
- package/src/modules/dictionaries/api/[dictionaryId]/entries/[entryId]/route.ts +3 -3
- package/src/modules/dictionaries/api/[dictionaryId]/entries/reorder/route.ts +2 -2
- package/src/modules/dictionaries/api/[dictionaryId]/entries/route.ts +3 -3
- package/src/modules/dictionaries/api/[dictionaryId]/entries/set-default/route.ts +2 -2
- package/src/modules/dictionaries/api/[dictionaryId]/route.ts +4 -4
- package/src/modules/dictionaries/api/route.ts +3 -3
- package/src/modules/feature_toggles/api/overrides/route.ts +2 -2
- package/src/modules/planner/api/availability-date-specific.ts +2 -2
- package/src/modules/planner/api/availability-weekly.ts +2 -2
- package/src/modules/resources/api/resources/tags/assign/route.ts +2 -2
- package/src/modules/resources/api/resources/tags/unassign/route.ts +2 -2
- package/src/modules/sales/api/document-history/route.ts +2 -2
- package/src/modules/sales/api/document-numbers/route.ts +2 -2
- package/src/modules/sales/api/quotes/accept/route.ts +2 -2
- package/src/modules/sales/api/quotes/convert/route.ts +2 -2
- package/src/modules/sales/api/quotes/public/[token]/route.ts +2 -2
- package/src/modules/sales/api/quotes/send/route.ts +2 -2
- package/src/modules/sales/api/returns/[id]/route.ts +2 -2
- package/src/modules/sales/api/settings/document-numbers/route.ts +3 -3
- package/src/modules/sales/api/settings/order-editing/route.ts +3 -3
- package/src/modules/sales/widgets/dashboard/makeDashboardWidgetRoute.ts +2 -2
- package/src/modules/staff/api/leave-requests/accept/route.ts +2 -2
- package/src/modules/staff/api/leave-requests/reject/route.ts +2 -2
- package/src/modules/staff/api/team-members/self/route.ts +3 -3
- package/src/modules/staff/api/team-members/tags/assign/route.ts +2 -2
- package/src/modules/staff/api/team-members/tags/unassign/route.ts +2 -2
- package/src/modules/translations/api/[entityType]/[entityId]/route.ts +4 -4
- package/src/modules/translations/api/get/locales.ts +2 -2
- package/src/modules/translations/api/put/locales.ts +2 -2
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../../../../src/modules/customers/api/dashboard/widgets/new-customers/route.ts"],
|
|
4
|
-
"sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport { CrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport { CustomerEntity, type CustomerEntityKind } from '../../../../data/entities'\nimport { resolveWidgetScope, type WidgetScopeContext } from '../utils'\nimport type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport type { FilterQuery } from '@mikro-orm/core'\n\nconst querySchema = z.object({\n limit: z.coerce.number().min(1).max(20).default(5),\n tenantId: z.string().uuid().optional(),\n organizationId: z.string().uuid().optional(),\n kind: z.enum(['person', 'company']).optional(),\n})\n\nexport const metadata = {\n GET: { requireAuth: true, requireFeatures: ['dashboards.view', 'customers.widgets.new-customers'] },\n}\n\ntype WidgetContext = WidgetScopeContext & {\n limit: number\n kind: CustomerEntityKind | null\n}\n\nasync function resolveContext(req: Request, translate: (key: string, fallback?: string) => string): Promise<WidgetContext> {\n const url = new URL(req.url)\n const rawQuery: Record<string, string> = {}\n for (const [key, value] of url.searchParams.entries()) {\n rawQuery[key] = value\n }\n const parsed = querySchema.safeParse(rawQuery)\n if (!parsed.success) {\n throw new CrudHttpError(400, { error: translate('customers.errors.invalid_query', 'Invalid query parameters') })\n }\n\n const { container, em, tenantId, organizationIds } = await resolveWidgetScope(req, translate, {\n tenantId: parsed.data.tenantId ?? null,\n organizationId: parsed.data.organizationId ?? null,\n })\n\n return {\n container,\n em,\n tenantId,\n organizationIds,\n limit: parsed.data.limit,\n kind: parsed.data.kind ?? null,\n }\n}\n\nexport async function GET(req: Request) {\n const { translate } = await resolveTranslations()\n try {\n const { em, tenantId, organizationIds, limit, kind } = await resolveContext(req, translate)\n\n const where: FilterQuery<CustomerEntity> = {\n tenantId,\n deletedAt: null,\n }\n if (Array.isArray(organizationIds)) {\n where.organizationId =\n organizationIds.length === 1 ? organizationIds[0] : { $in: Array.from(new Set(organizationIds)) }\n }\n if (kind) where.kind = kind\n\n const entities = await em.find(CustomerEntity, where, {\n limit,\n orderBy: { createdAt: 'desc' as const },\n })\n\n const items = entities.map((entity) => ({\n id: entity.id,\n displayName: entity.displayName,\n kind: entity.kind,\n organizationId: entity.organizationId,\n createdAt: entity.createdAt.toISOString(),\n ownerUserId: entity.ownerUserId ?? null,\n }))\n\n return NextResponse.json({ items })\n } catch (err) {\n if (err
|
|
5
|
-
"mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAClB,SAAS,2BAA2B;AACpC,SAAS,
|
|
4
|
+
"sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport { CrudHttpError, isCrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport { CustomerEntity, type CustomerEntityKind } from '../../../../data/entities'\nimport { resolveWidgetScope, type WidgetScopeContext } from '../utils'\nimport type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport type { FilterQuery } from '@mikro-orm/core'\n\nconst querySchema = z.object({\n limit: z.coerce.number().min(1).max(20).default(5),\n tenantId: z.string().uuid().optional(),\n organizationId: z.string().uuid().optional(),\n kind: z.enum(['person', 'company']).optional(),\n})\n\nexport const metadata = {\n GET: { requireAuth: true, requireFeatures: ['dashboards.view', 'customers.widgets.new-customers'] },\n}\n\ntype WidgetContext = WidgetScopeContext & {\n limit: number\n kind: CustomerEntityKind | null\n}\n\nasync function resolveContext(req: Request, translate: (key: string, fallback?: string) => string): Promise<WidgetContext> {\n const url = new URL(req.url)\n const rawQuery: Record<string, string> = {}\n for (const [key, value] of url.searchParams.entries()) {\n rawQuery[key] = value\n }\n const parsed = querySchema.safeParse(rawQuery)\n if (!parsed.success) {\n throw new CrudHttpError(400, { error: translate('customers.errors.invalid_query', 'Invalid query parameters') })\n }\n\n const { container, em, tenantId, organizationIds } = await resolveWidgetScope(req, translate, {\n tenantId: parsed.data.tenantId ?? null,\n organizationId: parsed.data.organizationId ?? null,\n })\n\n return {\n container,\n em,\n tenantId,\n organizationIds,\n limit: parsed.data.limit,\n kind: parsed.data.kind ?? null,\n }\n}\n\nexport async function GET(req: Request) {\n const { translate } = await resolveTranslations()\n try {\n const { em, tenantId, organizationIds, limit, kind } = await resolveContext(req, translate)\n\n const where: FilterQuery<CustomerEntity> = {\n tenantId,\n deletedAt: null,\n }\n if (Array.isArray(organizationIds)) {\n where.organizationId =\n organizationIds.length === 1 ? organizationIds[0] : { $in: Array.from(new Set(organizationIds)) }\n }\n if (kind) where.kind = kind\n\n const entities = await em.find(CustomerEntity, where, {\n limit,\n orderBy: { createdAt: 'desc' as const },\n })\n\n const items = entities.map((entity) => ({\n id: entity.id,\n displayName: entity.displayName,\n kind: entity.kind,\n organizationId: entity.organizationId,\n createdAt: entity.createdAt.toISOString(),\n ownerUserId: entity.ownerUserId ?? null,\n }))\n\n return NextResponse.json({ items })\n } catch (err) {\n if (isCrudHttpError(err)) {\n return NextResponse.json(err.body, { status: err.status })\n }\n console.error('customers.widgets.newCustomers failed', err)\n return NextResponse.json(\n { error: translate('customers.widgets.newCustomers.error', 'Failed to load recently added customers') },\n { status: 500 }\n )\n }\n}\n\nconst newCustomersItemSchema = z.object({\n id: z.string().uuid(),\n displayName: z.string().nullable().optional(),\n kind: z.string().nullable().optional(),\n organizationId: z.string().uuid().nullable().optional(),\n createdAt: z.string(),\n ownerUserId: z.string().uuid().nullable().optional(),\n})\n\nconst newCustomersResponseSchema = z.object({\n items: z.array(newCustomersItemSchema),\n})\n\nconst widgetErrorSchema = z.object({\n error: z.string(),\n})\n\nexport const openApi: OpenApiRouteDoc = {\n tag: 'Customers',\n summary: 'New customers widget',\n methods: {\n GET: {\n summary: 'Fetch recently created customers',\n description: 'Returns the latest customers created within the scoped tenant/organization for dashboard display.',\n query: querySchema,\n responses: [\n { status: 200, description: 'Widget payload', schema: newCustomersResponseSchema },\n ],\n errors: [\n { status: 400, description: 'Invalid query parameters', schema: widgetErrorSchema },\n { status: 401, description: 'Unauthorized', schema: widgetErrorSchema },\n { status: 500, description: 'Widget failed to load', schema: widgetErrorSchema },\n ],\n },\n },\n}\n"],
|
|
5
|
+
"mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAClB,SAAS,2BAA2B;AACpC,SAAS,eAAe,uBAAuB;AAC/C,SAAS,sBAA+C;AACxD,SAAS,0BAAmD;AAI5D,MAAM,cAAc,EAAE,OAAO;AAAA,EAC3B,OAAO,EAAE,OAAO,OAAO,EAAE,IAAI,CAAC,EAAE,IAAI,EAAE,EAAE,QAAQ,CAAC;AAAA,EACjD,UAAU,EAAE,OAAO,EAAE,KAAK,EAAE,SAAS;AAAA,EACrC,gBAAgB,EAAE,OAAO,EAAE,KAAK,EAAE,SAAS;AAAA,EAC3C,MAAM,EAAE,KAAK,CAAC,UAAU,SAAS,CAAC,EAAE,SAAS;AAC/C,CAAC;AAEM,MAAM,WAAW;AAAA,EACtB,KAAK,EAAE,aAAa,MAAM,iBAAiB,CAAC,mBAAmB,iCAAiC,EAAE;AACpG;AAOA,eAAe,eAAe,KAAc,WAA+E;AACzH,QAAM,MAAM,IAAI,IAAI,IAAI,GAAG;AAC3B,QAAM,WAAmC,CAAC;AAC1C,aAAW,CAAC,KAAK,KAAK,KAAK,IAAI,aAAa,QAAQ,GAAG;AACrD,aAAS,GAAG,IAAI;AAAA,EAClB;AACA,QAAM,SAAS,YAAY,UAAU,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,QAAQ,kBAAkB;AAAA,MACjF;AAAA,IACF;AAAA,EACF;AACF;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { NextResponse } from "next/server";
|
|
2
2
|
import { z } from "zod";
|
|
3
3
|
import { resolveTranslations } from "@open-mercato/shared/lib/i18n/server";
|
|
4
|
-
import { CrudHttpError } from "@open-mercato/shared/lib/crud/errors";
|
|
4
|
+
import { CrudHttpError, isCrudHttpError } from "@open-mercato/shared/lib/crud/errors";
|
|
5
5
|
import { CustomerDeal } from "../../../../data/entities.js";
|
|
6
6
|
import { resolveWidgetScope } from "../utils.js";
|
|
7
7
|
const querySchema = z.object({
|
|
@@ -59,7 +59,7 @@ async function GET(req) {
|
|
|
59
59
|
}));
|
|
60
60
|
return NextResponse.json({ items });
|
|
61
61
|
} catch (err) {
|
|
62
|
-
if (err
|
|
62
|
+
if (isCrudHttpError(err)) {
|
|
63
63
|
return NextResponse.json(err.body, { status: err.status });
|
|
64
64
|
}
|
|
65
65
|
console.error("customers.widgets.newDeals failed", err);
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../../../../src/modules/customers/api/dashboard/widgets/new-deals/route.ts"],
|
|
4
|
-
"sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport { CrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport { CustomerDeal } from '../../../../data/entities'\nimport { resolveWidgetScope, type WidgetScopeContext } from '../utils'\nimport type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport type { FilterQuery } from '@mikro-orm/core'\n\nconst querySchema = z.object({\n limit: z.coerce.number().min(1).max(20).default(5),\n tenantId: z.string().uuid().optional(),\n organizationId: z.string().uuid().optional(),\n})\n\nexport const metadata = {\n GET: { requireAuth: true, requireFeatures: ['dashboards.view', 'customers.widgets.new-deals'] },\n}\n\ntype WidgetContext = WidgetScopeContext & {\n limit: number\n}\n\nasync function resolveContext(req: Request, translate: (key: string, fallback?: string) => string): Promise<WidgetContext> {\n const url = new URL(req.url)\n const rawQuery: Record<string, string> = {}\n for (const [key, value] of url.searchParams.entries()) rawQuery[key] = value\n const parsed = querySchema.safeParse(rawQuery)\n if (!parsed.success) {\n throw new CrudHttpError(400, { error: translate('customers.errors.invalid_query', 'Invalid query parameters') })\n }\n\n const { container, em, tenantId, organizationIds } = await resolveWidgetScope(req, translate, {\n tenantId: parsed.data.tenantId ?? null,\n organizationId: parsed.data.organizationId ?? null,\n })\n\n return {\n container,\n em,\n tenantId,\n organizationIds,\n limit: parsed.data.limit,\n }\n}\n\nexport async function GET(req: Request) {\n const { translate } = await resolveTranslations()\n try {\n const { em, tenantId, organizationIds, limit } = await resolveContext(req, translate)\n\n const where: FilterQuery<CustomerDeal> = {\n tenantId,\n deletedAt: null,\n }\n if (Array.isArray(organizationIds)) {\n where.organizationId = organizationIds.length === 1 ? organizationIds[0] : { $in: Array.from(new Set(organizationIds)) }\n }\n\n const deals = await em.find(CustomerDeal, where, {\n limit,\n orderBy: { createdAt: 'desc' as const },\n })\n\n const items = deals.map((deal) => ({\n id: deal.id,\n title: deal.title,\n status: deal.status,\n organizationId: deal.organizationId,\n createdAt: deal.createdAt.toISOString(),\n ownerUserId: deal.ownerUserId ?? null,\n valueAmount: deal.valueAmount ?? null,\n valueCurrency: deal.valueCurrency ?? null,\n }))\n\n return NextResponse.json({ items })\n } catch (err) {\n if (err
|
|
5
|
-
"mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAClB,SAAS,2BAA2B;AACpC,SAAS,
|
|
4
|
+
"sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport { CrudHttpError, isCrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport { CustomerDeal } from '../../../../data/entities'\nimport { resolveWidgetScope, type WidgetScopeContext } from '../utils'\nimport type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport type { FilterQuery } from '@mikro-orm/core'\n\nconst querySchema = z.object({\n limit: z.coerce.number().min(1).max(20).default(5),\n tenantId: z.string().uuid().optional(),\n organizationId: z.string().uuid().optional(),\n})\n\nexport const metadata = {\n GET: { requireAuth: true, requireFeatures: ['dashboards.view', 'customers.widgets.new-deals'] },\n}\n\ntype WidgetContext = WidgetScopeContext & {\n limit: number\n}\n\nasync function resolveContext(req: Request, translate: (key: string, fallback?: string) => string): Promise<WidgetContext> {\n const url = new URL(req.url)\n const rawQuery: Record<string, string> = {}\n for (const [key, value] of url.searchParams.entries()) rawQuery[key] = value\n const parsed = querySchema.safeParse(rawQuery)\n if (!parsed.success) {\n throw new CrudHttpError(400, { error: translate('customers.errors.invalid_query', 'Invalid query parameters') })\n }\n\n const { container, em, tenantId, organizationIds } = await resolveWidgetScope(req, translate, {\n tenantId: parsed.data.tenantId ?? null,\n organizationId: parsed.data.organizationId ?? null,\n })\n\n return {\n container,\n em,\n tenantId,\n organizationIds,\n limit: parsed.data.limit,\n }\n}\n\nexport async function GET(req: Request) {\n const { translate } = await resolveTranslations()\n try {\n const { em, tenantId, organizationIds, limit } = await resolveContext(req, translate)\n\n const where: FilterQuery<CustomerDeal> = {\n tenantId,\n deletedAt: null,\n }\n if (Array.isArray(organizationIds)) {\n where.organizationId = organizationIds.length === 1 ? organizationIds[0] : { $in: Array.from(new Set(organizationIds)) }\n }\n\n const deals = await em.find(CustomerDeal, where, {\n limit,\n orderBy: { createdAt: 'desc' as const },\n })\n\n const items = deals.map((deal) => ({\n id: deal.id,\n title: deal.title,\n status: deal.status,\n organizationId: deal.organizationId,\n createdAt: deal.createdAt.toISOString(),\n ownerUserId: deal.ownerUserId ?? null,\n valueAmount: deal.valueAmount ?? null,\n valueCurrency: deal.valueCurrency ?? null,\n }))\n\n return NextResponse.json({ items })\n } catch (err) {\n if (isCrudHttpError(err)) {\n return NextResponse.json(err.body, { status: err.status })\n }\n console.error('customers.widgets.newDeals failed', err)\n return NextResponse.json(\n { error: translate('customers.widgets.newDeals.error', 'Failed to load recently created deals') },\n { status: 500 },\n )\n }\n}\n\nconst newDealsItemSchema = z.object({\n id: z.string().uuid(),\n title: z.string().nullable().optional(),\n status: z.string().nullable().optional(),\n organizationId: z.string().uuid().nullable().optional(),\n createdAt: z.string(),\n ownerUserId: z.string().uuid().nullable().optional(),\n valueAmount: z.string().nullable().optional(),\n valueCurrency: z.string().nullable().optional(),\n})\n\nconst newDealsResponseSchema = z.object({\n items: z.array(newDealsItemSchema),\n})\n\nconst widgetErrorSchema = z.object({ error: z.string() })\n\nexport const openApi: OpenApiRouteDoc = {\n tag: 'Customers',\n summary: 'New deals widget',\n methods: {\n GET: {\n summary: 'Fetch recently created deals',\n description: 'Returns the latest deals created within the scoped tenant/organization for dashboard display.',\n query: querySchema,\n responses: [{ status: 200, description: 'Widget payload', schema: newDealsResponseSchema }],\n errors: [\n { status: 400, description: 'Invalid query parameters', schema: widgetErrorSchema },\n { status: 401, description: 'Unauthorized', schema: widgetErrorSchema },\n { status: 500, description: 'Widget failed to load', schema: widgetErrorSchema },\n ],\n },\n },\n}\n"],
|
|
5
|
+
"mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAClB,SAAS,2BAA2B;AACpC,SAAS,eAAe,uBAAuB;AAC/C,SAAS,oBAAoB;AAC7B,SAAS,0BAAmD;AAI5D,MAAM,cAAc,EAAE,OAAO;AAAA,EAC3B,OAAO,EAAE,OAAO,OAAO,EAAE,IAAI,CAAC,EAAE,IAAI,EAAE,EAAE,QAAQ,CAAC;AAAA,EACjD,UAAU,EAAE,OAAO,EAAE,KAAK,EAAE,SAAS;AAAA,EACrC,gBAAgB,EAAE,OAAO,EAAE,KAAK,EAAE,SAAS;AAC7C,CAAC;AAEM,MAAM,WAAW;AAAA,EACtB,KAAK,EAAE,aAAa,MA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ACT,SAAS;AAAA,IACP,KAAK;AAAA,MACH,SAAS;AAAA,MACT,aAAa;AAAA,MACb,OAAO;AAAA,MACP,WAAW,CAAC,EAAE,QAAQ,KAAK,aAAa,kBAAkB,QAAQ,uBAAuB,CAAC;AAAA,MAC1F,QAAQ;AAAA,QACN,EAAE,QAAQ,KAAK,aAAa,4BAA4B,QAAQ,kBAAkB;AAAA,QAClF,EAAE,QAAQ,KAAK,aAAa,gBAAgB,QAAQ,kBAAkB;AAAA,QACtE,EAAE,QAAQ,KAAK,aAAa,yBAAyB,QAAQ,kBAAkB;AAAA,MACjF;AAAA,IACF;AAAA,EACF;AACF;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { NextResponse } from "next/server";
|
|
2
2
|
import { z } from "zod";
|
|
3
3
|
import { resolveTranslations } from "@open-mercato/shared/lib/i18n/server";
|
|
4
|
-
import { CrudHttpError } from "@open-mercato/shared/lib/crud/errors";
|
|
4
|
+
import { CrudHttpError, isCrudHttpError } from "@open-mercato/shared/lib/crud/errors";
|
|
5
5
|
import { CustomerEntity } from "../../../../data/entities.js";
|
|
6
6
|
import { resolveWidgetScope } from "../utils.js";
|
|
7
7
|
import { parseBooleanToken } from "@open-mercato/shared/lib/boolean";
|
|
@@ -66,7 +66,7 @@ async function GET(req) {
|
|
|
66
66
|
}));
|
|
67
67
|
return NextResponse.json({ items, now: now.toISOString() });
|
|
68
68
|
} catch (err) {
|
|
69
|
-
if (err
|
|
69
|
+
if (isCrudHttpError(err)) {
|
|
70
70
|
return NextResponse.json(err.body, { status: err.status });
|
|
71
71
|
}
|
|
72
72
|
console.error("customers.widgets.nextInteractions failed", err);
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../../../../src/modules/customers/api/dashboard/widgets/next-interactions/route.ts"],
|
|
4
|
-
"sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport { CrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport { CustomerEntity } from '../../../../data/entities'\nimport type { FilterQuery } from '@mikro-orm/core'\nimport { resolveWidgetScope, type WidgetScopeContext } from '../utils'\nimport type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport { parseBooleanToken } from '@open-mercato/shared/lib/boolean'\n\nconst querySchema = z.object({\n limit: z.coerce.number().min(1).max(20).default(5),\n tenantId: z.string().uuid().optional(),\n organizationId: z.string().uuid().optional(),\n includePast: z.enum(['true', 'false']).optional(),\n})\n\nexport const metadata = {\n GET: { requireAuth: true, requireFeatures: ['dashboards.view', 'customers.widgets.next-interactions'] },\n}\n\ntype WidgetContext = WidgetScopeContext & {\n limit: number\n includePast: boolean\n}\n\nasync function resolveContext(req: Request, translate: (key: string, fallback?: string) => string): Promise<WidgetContext> {\n const url = new URL(req.url)\n const rawQuery: Record<string, string> = {}\n for (const [key, value] of url.searchParams.entries()) {\n rawQuery[key] = value\n }\n const parsed = querySchema.safeParse(rawQuery)\n if (!parsed.success) {\n throw new CrudHttpError(400, { error: translate('customers.errors.invalid_query', 'Invalid query parameters') })\n }\n\n const { container, em, tenantId, organizationIds } = await resolveWidgetScope(req, translate, {\n tenantId: parsed.data.tenantId ?? null,\n organizationId: parsed.data.organizationId ?? null,\n })\n\n return {\n container,\n em,\n tenantId,\n organizationIds,\n limit: parsed.data.limit,\n includePast: parseBooleanToken(parsed.data.includePast) === true,\n }\n}\n\nexport async function GET(req: Request) {\n const { translate } = await resolveTranslations()\n try {\n const { em, tenantId, organizationIds, limit, includePast } = await resolveContext(req, translate)\n const organizationFilter =\n Array.isArray(organizationIds)\n ? organizationIds.length === 1\n ? organizationIds[0]\n : { $in: Array.from(new Set(organizationIds)) }\n : null\n\n const now = new Date()\n\n const filters: FilterQuery<CustomerEntity> = {\n tenantId,\n deletedAt: null,\n nextInteractionAt: includePast ? { $ne: null } : { $gte: now },\n }\n if (organizationFilter) filters.organizationId = organizationFilter\n\n const entities = await em.find(CustomerEntity, filters, {\n limit,\n orderBy: { nextInteractionAt: 'asc' as const },\n })\n\n const items = entities.map((entity) => ({\n id: entity.id,\n displayName: entity.displayName,\n kind: entity.kind,\n organizationId: entity.organizationId,\n nextInteractionAt: entity.nextInteractionAt ? entity.nextInteractionAt.toISOString() : null,\n nextInteractionName: entity.nextInteractionName ?? null,\n nextInteractionIcon: entity.nextInteractionIcon ?? null,\n nextInteractionColor: entity.nextInteractionColor ?? null,\n ownerUserId: entity.ownerUserId ?? null,\n }))\n\n return NextResponse.json({ items, now: now.toISOString() })\n } catch (err) {\n if (err
|
|
5
|
-
"mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAClB,SAAS,2BAA2B;AACpC,SAAS,
|
|
4
|
+
"sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport { CrudHttpError, isCrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport { CustomerEntity } from '../../../../data/entities'\nimport type { FilterQuery } from '@mikro-orm/core'\nimport { resolveWidgetScope, type WidgetScopeContext } from '../utils'\nimport type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport { parseBooleanToken } from '@open-mercato/shared/lib/boolean'\n\nconst querySchema = z.object({\n limit: z.coerce.number().min(1).max(20).default(5),\n tenantId: z.string().uuid().optional(),\n organizationId: z.string().uuid().optional(),\n includePast: z.enum(['true', 'false']).optional(),\n})\n\nexport const metadata = {\n GET: { requireAuth: true, requireFeatures: ['dashboards.view', 'customers.widgets.next-interactions'] },\n}\n\ntype WidgetContext = WidgetScopeContext & {\n limit: number\n includePast: boolean\n}\n\nasync function resolveContext(req: Request, translate: (key: string, fallback?: string) => string): Promise<WidgetContext> {\n const url = new URL(req.url)\n const rawQuery: Record<string, string> = {}\n for (const [key, value] of url.searchParams.entries()) {\n rawQuery[key] = value\n }\n const parsed = querySchema.safeParse(rawQuery)\n if (!parsed.success) {\n throw new CrudHttpError(400, { error: translate('customers.errors.invalid_query', 'Invalid query parameters') })\n }\n\n const { container, em, tenantId, organizationIds } = await resolveWidgetScope(req, translate, {\n tenantId: parsed.data.tenantId ?? null,\n organizationId: parsed.data.organizationId ?? null,\n })\n\n return {\n container,\n em,\n tenantId,\n organizationIds,\n limit: parsed.data.limit,\n includePast: parseBooleanToken(parsed.data.includePast) === true,\n }\n}\n\nexport async function GET(req: Request) {\n const { translate } = await resolveTranslations()\n try {\n const { em, tenantId, organizationIds, limit, includePast } = await resolveContext(req, translate)\n const organizationFilter =\n Array.isArray(organizationIds)\n ? organizationIds.length === 1\n ? organizationIds[0]\n : { $in: Array.from(new Set(organizationIds)) }\n : null\n\n const now = new Date()\n\n const filters: FilterQuery<CustomerEntity> = {\n tenantId,\n deletedAt: null,\n nextInteractionAt: includePast ? { $ne: null } : { $gte: now },\n }\n if (organizationFilter) filters.organizationId = organizationFilter\n\n const entities = await em.find(CustomerEntity, filters, {\n limit,\n orderBy: { nextInteractionAt: 'asc' as const },\n })\n\n const items = entities.map((entity) => ({\n id: entity.id,\n displayName: entity.displayName,\n kind: entity.kind,\n organizationId: entity.organizationId,\n nextInteractionAt: entity.nextInteractionAt ? entity.nextInteractionAt.toISOString() : null,\n nextInteractionName: entity.nextInteractionName ?? null,\n nextInteractionIcon: entity.nextInteractionIcon ?? null,\n nextInteractionColor: entity.nextInteractionColor ?? null,\n ownerUserId: entity.ownerUserId ?? null,\n }))\n\n return NextResponse.json({ items, now: now.toISOString() })\n } catch (err) {\n if (isCrudHttpError(err)) {\n return NextResponse.json(err.body, { status: err.status })\n }\n console.error('customers.widgets.nextInteractions failed', err)\n return NextResponse.json(\n { error: translate('customers.widgets.nextInteractions.error', 'Failed to load upcoming interactions') },\n { status: 500 }\n )\n }\n}\n\nconst nextInteractionItemSchema = z.object({\n id: z.string().uuid(),\n displayName: z.string().nullable().optional(),\n kind: z.string().nullable().optional(),\n organizationId: z.string().uuid().nullable().optional(),\n nextInteractionAt: z.string().nullable(),\n nextInteractionName: z.string().nullable().optional(),\n nextInteractionIcon: z.string().nullable().optional(),\n nextInteractionColor: z.string().nullable().optional(),\n ownerUserId: z.string().uuid().nullable().optional(),\n})\n\nconst nextInteractionResponseSchema = z.object({\n items: z.array(nextInteractionItemSchema),\n now: z.string(),\n})\n\nconst widgetErrorSchema = z.object({\n error: z.string(),\n})\n\nexport const openApi: OpenApiRouteDoc = {\n tag: 'Customers',\n summary: 'Next interactions widget',\n methods: {\n GET: {\n summary: 'Fetch upcoming customer interactions',\n description: 'Lists upcoming (or optionally past) customer interaction reminders ordered by interaction date.',\n query: querySchema,\n responses: [\n { status: 200, description: 'Widget payload', schema: nextInteractionResponseSchema },\n ],\n errors: [\n { status: 400, description: 'Invalid query parameters', schema: widgetErrorSchema },\n { status: 401, description: 'Unauthorized', schema: widgetErrorSchema },\n { status: 500, description: 'Widget failed to load', schema: widgetErrorSchema },\n ],\n },\n },\n}\n"],
|
|
5
|
+
"mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAClB,SAAS,2BAA2B;AACpC,SAAS,eAAe,uBAAuB;AAC/C,SAAS,sBAAsB;AAE/B,SAAS,0BAAmD;AAE5D,SAAS,yBAAyB;AAElC,MAAM,cAAc,EAAE,OAAO;AAAA,EAC3B,OAAO,EAAE,OAAO,OAAO,EAAE,IAAI,CAAC,EAAE,IAAI,EAAE,EAAE,QAAQ,CAAC;AAAA,EACjD,UAAU,EAAE,OAAO,EAAE,KAAK,EAAE,SAAS;AAAA,EACrC,gBAAgB,EAAE,OAAO,EAAE,KAAK,EAAE,SAAS;AAAA,EAC3C,aAAa,EAAE,KAAK,CAAC,QAAQ,OAAO,CAAC,EAAE,SAAS;AAClD,CAAC;AAEM,MAAM,WAAW;AAAA,EACtB,KAAK,EAAE,aAAa,MAAM,iBAAiB,CAAC,mBAAmB,qCAAqC,EAAE;AACxG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AAO,EAAE,SAAS,EAAE,SAAS;AAAA,EACrD,aAAa,EAAE,OAAO,EAAE,KAAK,EAAE,SAAS,EAAE,SAAS;AACrD,CAAC;AAED,MAAM,gCAAgC,EAAE,OAAO;AAAA,EAC7C,OAAO,EAAE,MAAM,yBAAyB;AAAA,EACxC,KAAK,EAAE,OAAO;AAChB,CAAC;AAED,MAAM,oBAAoB,EAAE,OAAO;AAAA,EACjC,OAAO,EAAE,OAAO;AAClB,CAAC;AAEM,MAAM,UAA2B;AAAA,EACtC,KAAK;AAAA,EACL,SAAS;AAAA,EACT,SAAS;AAAA,IACP,KAAK;AAAA,MACH,SAAS;AAAA,MACT,aAAa;AAAA,MACb,OAAO;AAAA,MACP,WAAW;AAAA,QACT,EAAE,QAAQ,KAAK,aAAa,kBAAkB,QAAQ,8BAA8B;AAAA,MACtF;AAAA,MACA,QAAQ;AAAA,QACN,EAAE,QAAQ,KAAK,aAAa,4BAA4B,QAAQ,kBAAkB;AAAA,QAClF,EAAE,QAAQ,KAAK,aAAa,gBAAgB,QAAQ,kBAAkB;AAAA,QACtE,EAAE,QAAQ,KAAK,aAAa,yBAAyB,QAAQ,kBAAkB;AAAA,MACjF;AAAA,IACF;AAAA,EACF;AACF;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { NextResponse } from "next/server";
|
|
2
2
|
import { z } from "zod";
|
|
3
|
-
import { CrudHttpError } from "@open-mercato/shared/lib/crud/errors";
|
|
3
|
+
import { CrudHttpError, isCrudHttpError } from "@open-mercato/shared/lib/crud/errors";
|
|
4
4
|
import { createRequestContainer } from "@open-mercato/shared/lib/di/container";
|
|
5
5
|
import { getAuthFromRequest } from "@open-mercato/shared/lib/auth/server";
|
|
6
6
|
import { resolveOrganizationScopeForRequest } from "@open-mercato/core/modules/directory/utils/organizationScope";
|
|
@@ -127,7 +127,7 @@ async function GET(req, ctx) {
|
|
|
127
127
|
totalPages
|
|
128
128
|
});
|
|
129
129
|
} catch (error) {
|
|
130
|
-
if (error
|
|
130
|
+
if (isCrudHttpError(error)) {
|
|
131
131
|
return NextResponse.json(error.body, { status: error.status });
|
|
132
132
|
}
|
|
133
133
|
console.error("[customers.deals.companies.GET]", error);
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../../../../src/modules/customers/api/deals/%5Bid%5D/companies/route.ts"],
|
|
4
|
-
"sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport { CrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'\nimport { resolveOrganizationScopeForRequest } from '@open-mercato/core/modules/directory/utils/organizationScope'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport { findOneWithDecryption, findWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { CustomerCompanyProfile, CustomerDeal, CustomerDealCompanyLink, CustomerEntity } from '../../../../data/entities'\n\nconst paramsSchema = z.object({\n id: z.string().uuid(),\n})\n\nconst querySchema = z.object({\n page: z.coerce.number().min(1).default(1),\n pageSize: z.coerce.number().min(1).max(100).default(20),\n search: z.string().optional(),\n sort: z.enum(['label-asc', 'label-desc', 'name-asc', 'name-desc', 'recent']).default('label-asc'),\n})\n\ntype DealLinkedEntitySort = 'label-asc' | 'label-desc' | 'recent'\n\nfunction normalizeSort(sort: z.infer<typeof querySchema>['sort']): DealLinkedEntitySort {\n if (sort === 'name-asc') return 'label-asc'\n if (sort === 'name-desc') return 'label-desc'\n return sort\n}\n\ntype DealCompanyItem = {\n id: string\n label: string\n subtitle: string | null\n kind: 'company'\n linkedAt: string\n}\n\nfunction matchesSearch(item: DealCompanyItem, query: string): boolean {\n const normalized = query.trim().toLowerCase()\n if (!normalized.length) return true\n return [item.label, item.subtitle]\n .filter((value): value is string => typeof value === 'string' && value.length > 0)\n .some((value) => value.toLowerCase().includes(normalized))\n}\n\nfunction sortItems(items: DealCompanyItem[], sort: 'label-asc' | 'label-desc' | 'recent'): DealCompanyItem[] {\n if (sort === 'recent') {\n return [...items].sort((left, right) => {\n const compare = new Date(right.linkedAt).getTime() - new Date(left.linkedAt).getTime()\n if (compare !== 0) return compare\n return left.label.localeCompare(right.label, undefined, { sensitivity: 'base' })\n })\n }\n return [...items].sort((left, right) => {\n const compare = left.label.localeCompare(right.label, undefined, { sensitivity: 'base' })\n return sort === 'label-asc' ? compare : -compare\n })\n}\n\nexport const metadata = {\n GET: { requireAuth: true, requireFeatures: ['customers.deals.view'] },\n}\n\nexport async function GET(req: Request, ctx: { params?: { id?: string } }) {\n const { translate } = await resolveTranslations()\n try {\n const { id } = paramsSchema.parse({ id: ctx.params?.id })\n const auth = await getAuthFromRequest(req)\n if (!auth?.tenantId) throw new CrudHttpError(401, { error: 'Unauthorized' })\n\n const url = new URL(req.url)\n const query = querySchema.parse({\n page: url.searchParams.get('page') ?? undefined,\n pageSize: url.searchParams.get('pageSize') ?? undefined,\n search: url.searchParams.get('search') ?? undefined,\n sort: url.searchParams.get('sort') ?? undefined,\n })\n\n const container = await createRequestContainer()\n const scope = await resolveOrganizationScopeForRequest({ container, auth, request: req })\n const em = (container.resolve('em') as EntityManager).fork()\n const decryptionScope = {\n tenantId: auth.tenantId,\n organizationId: scope?.selectedId ?? auth.orgId ?? null,\n }\n\n const deal = await findOneWithDecryption(\n em,\n CustomerDeal,\n { id, tenantId: auth.tenantId, deletedAt: null },\n {},\n decryptionScope,\n )\n if (!deal) {\n throw new CrudHttpError(404, { error: translate('customers.errors.deal_not_found', 'Deal not found') })\n }\n\n const allowedOrgIds = new Set<string>()\n if (scope?.filterIds?.length) scope.filterIds.forEach((entry) => allowedOrgIds.add(entry))\n else if (auth.orgId) allowedOrgIds.add(auth.orgId)\n if (allowedOrgIds.size > 0 && deal.organizationId && !allowedOrgIds.has(deal.organizationId)) {\n throw new CrudHttpError(403, { error: translate('customers.errors.access_denied', 'Access denied') })\n }\n\n const entityScope = { tenantId: deal.tenantId, organizationId: deal.organizationId }\n const links = await findWithDecryption(\n em,\n CustomerDealCompanyLink,\n { deal: deal.id },\n { populate: ['company'] },\n entityScope,\n )\n\n const companyIds = links\n .map((link) => link.company?.id)\n .filter((companyId): companyId is string => typeof companyId === 'string' && companyId.length > 0)\n const profiles = companyIds.length > 0\n ? await findWithDecryption(\n em,\n CustomerCompanyProfile,\n {\n entity: { $in: companyIds },\n tenantId: deal.tenantId,\n organizationId: deal.organizationId,\n },\n {},\n entityScope,\n )\n : []\n const profileByCompanyId = new Map(\n profiles.map((profile) => [(profile.entity as { id: string }).id, profile]),\n )\n\n const items = links\n .map((link) => {\n const company = link.company as CustomerEntity | null\n if (!company?.id) return null\n const profile = profileByCompanyId.get(company.id) ?? null\n return {\n id: company.id,\n label: company.displayName ?? profile?.domain ?? company.id,\n subtitle: profile?.domain ?? company.primaryEmail ?? company.primaryPhone ?? null,\n kind: 'company',\n linkedAt: link.createdAt.toISOString(),\n } satisfies DealCompanyItem\n })\n .filter((item): item is DealCompanyItem => item !== null)\n\n const filtered = query.search?.trim().length ? items.filter((item) => matchesSearch(item, query.search ?? '')) : items\n const sorted = sortItems(filtered, normalizeSort(query.sort))\n const total = sorted.length\n const totalPages = Math.max(1, Math.ceil(total / query.pageSize))\n const page = Math.min(query.page, totalPages)\n const start = (page - 1) * query.pageSize\n\n return NextResponse.json({\n items: sorted.slice(start, start + query.pageSize),\n total,\n page,\n pageSize: query.pageSize,\n totalPages,\n })\n } catch (error) {\n if (error
|
|
5
|
-
"mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAElB,SAAS,
|
|
4
|
+
"sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport { CrudHttpError, isCrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'\nimport { resolveOrganizationScopeForRequest } from '@open-mercato/core/modules/directory/utils/organizationScope'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport { findOneWithDecryption, findWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { CustomerCompanyProfile, CustomerDeal, CustomerDealCompanyLink, CustomerEntity } from '../../../../data/entities'\n\nconst paramsSchema = z.object({\n id: z.string().uuid(),\n})\n\nconst querySchema = z.object({\n page: z.coerce.number().min(1).default(1),\n pageSize: z.coerce.number().min(1).max(100).default(20),\n search: z.string().optional(),\n sort: z.enum(['label-asc', 'label-desc', 'name-asc', 'name-desc', 'recent']).default('label-asc'),\n})\n\ntype DealLinkedEntitySort = 'label-asc' | 'label-desc' | 'recent'\n\nfunction normalizeSort(sort: z.infer<typeof querySchema>['sort']): DealLinkedEntitySort {\n if (sort === 'name-asc') return 'label-asc'\n if (sort === 'name-desc') return 'label-desc'\n return sort\n}\n\ntype DealCompanyItem = {\n id: string\n label: string\n subtitle: string | null\n kind: 'company'\n linkedAt: string\n}\n\nfunction matchesSearch(item: DealCompanyItem, query: string): boolean {\n const normalized = query.trim().toLowerCase()\n if (!normalized.length) return true\n return [item.label, item.subtitle]\n .filter((value): value is string => typeof value === 'string' && value.length > 0)\n .some((value) => value.toLowerCase().includes(normalized))\n}\n\nfunction sortItems(items: DealCompanyItem[], sort: 'label-asc' | 'label-desc' | 'recent'): DealCompanyItem[] {\n if (sort === 'recent') {\n return [...items].sort((left, right) => {\n const compare = new Date(right.linkedAt).getTime() - new Date(left.linkedAt).getTime()\n if (compare !== 0) return compare\n return left.label.localeCompare(right.label, undefined, { sensitivity: 'base' })\n })\n }\n return [...items].sort((left, right) => {\n const compare = left.label.localeCompare(right.label, undefined, { sensitivity: 'base' })\n return sort === 'label-asc' ? compare : -compare\n })\n}\n\nexport const metadata = {\n GET: { requireAuth: true, requireFeatures: ['customers.deals.view'] },\n}\n\nexport async function GET(req: Request, ctx: { params?: { id?: string } }) {\n const { translate } = await resolveTranslations()\n try {\n const { id } = paramsSchema.parse({ id: ctx.params?.id })\n const auth = await getAuthFromRequest(req)\n if (!auth?.tenantId) throw new CrudHttpError(401, { error: 'Unauthorized' })\n\n const url = new URL(req.url)\n const query = querySchema.parse({\n page: url.searchParams.get('page') ?? undefined,\n pageSize: url.searchParams.get('pageSize') ?? undefined,\n search: url.searchParams.get('search') ?? undefined,\n sort: url.searchParams.get('sort') ?? undefined,\n })\n\n const container = await createRequestContainer()\n const scope = await resolveOrganizationScopeForRequest({ container, auth, request: req })\n const em = (container.resolve('em') as EntityManager).fork()\n const decryptionScope = {\n tenantId: auth.tenantId,\n organizationId: scope?.selectedId ?? auth.orgId ?? null,\n }\n\n const deal = await findOneWithDecryption(\n em,\n CustomerDeal,\n { id, tenantId: auth.tenantId, deletedAt: null },\n {},\n decryptionScope,\n )\n if (!deal) {\n throw new CrudHttpError(404, { error: translate('customers.errors.deal_not_found', 'Deal not found') })\n }\n\n const allowedOrgIds = new Set<string>()\n if (scope?.filterIds?.length) scope.filterIds.forEach((entry) => allowedOrgIds.add(entry))\n else if (auth.orgId) allowedOrgIds.add(auth.orgId)\n if (allowedOrgIds.size > 0 && deal.organizationId && !allowedOrgIds.has(deal.organizationId)) {\n throw new CrudHttpError(403, { error: translate('customers.errors.access_denied', 'Access denied') })\n }\n\n const entityScope = { tenantId: deal.tenantId, organizationId: deal.organizationId }\n const links = await findWithDecryption(\n em,\n CustomerDealCompanyLink,\n { deal: deal.id },\n { populate: ['company'] },\n entityScope,\n )\n\n const companyIds = links\n .map((link) => link.company?.id)\n .filter((companyId): companyId is string => typeof companyId === 'string' && companyId.length > 0)\n const profiles = companyIds.length > 0\n ? await findWithDecryption(\n em,\n CustomerCompanyProfile,\n {\n entity: { $in: companyIds },\n tenantId: deal.tenantId,\n organizationId: deal.organizationId,\n },\n {},\n entityScope,\n )\n : []\n const profileByCompanyId = new Map(\n profiles.map((profile) => [(profile.entity as { id: string }).id, profile]),\n )\n\n const items = links\n .map((link) => {\n const company = link.company as CustomerEntity | null\n if (!company?.id) return null\n const profile = profileByCompanyId.get(company.id) ?? null\n return {\n id: company.id,\n label: company.displayName ?? profile?.domain ?? company.id,\n subtitle: profile?.domain ?? company.primaryEmail ?? company.primaryPhone ?? null,\n kind: 'company',\n linkedAt: link.createdAt.toISOString(),\n } satisfies DealCompanyItem\n })\n .filter((item): item is DealCompanyItem => item !== null)\n\n const filtered = query.search?.trim().length ? items.filter((item) => matchesSearch(item, query.search ?? '')) : items\n const sorted = sortItems(filtered, normalizeSort(query.sort))\n const total = sorted.length\n const totalPages = Math.max(1, Math.ceil(total / query.pageSize))\n const page = Math.min(query.page, totalPages)\n const start = (page - 1) * query.pageSize\n\n return NextResponse.json({\n items: sorted.slice(start, start + query.pageSize),\n total,\n page,\n pageSize: query.pageSize,\n totalPages,\n })\n } catch (error) {\n if (isCrudHttpError(error)) {\n return NextResponse.json(error.body, { status: error.status })\n }\n console.error('[customers.deals.companies.GET]', error)\n return NextResponse.json({ error: translate('customers.errors.deal_companies_load_failed', 'Failed to load linked companies') }, { status: 500 })\n }\n}\n\nexport const openApi: OpenApiRouteDoc = {\n tag: 'Customers',\n methods: {\n GET: {\n summary: 'List linked companies for a deal',\n query: querySchema,\n responses: [\n {\n status: 200,\n description: 'Paginated linked companies',\n schema: z.object({\n items: z.array(\n z.object({\n id: z.string().uuid(),\n label: z.string(),\n subtitle: z.string().nullable(),\n kind: z.literal('company'),\n linkedAt: z.string(),\n }),\n ),\n total: z.number().int().nonnegative(),\n page: z.number().int().min(1),\n pageSize: z.number().int().min(1),\n totalPages: z.number().int().min(1),\n }),\n },\n ],\n },\n },\n}\n"],
|
|
5
|
+
"mappings": "AAAA,SAAS,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,QAAQ,IAAI,CAAC;AAAA,EAClJ;AACF;AAEO,MAAM,UAA2B;AAAA,EACtC,KAAK;AAAA,EACL,SAAS;AAAA,IACP,KAAK;AAAA,MACH,SAAS;AAAA,MACT,OAAO;AAAA,MACP,WAAW;AAAA,QACT;AAAA,UACE,QAAQ;AAAA,UACR,aAAa;AAAA,UACb,QAAQ,EAAE,OAAO;AAAA,YACf,OAAO,EAAE;AAAA,cACP,EAAE,OAAO;AAAA,gBACP,IAAI,EAAE,OAAO,EAAE,KAAK;AAAA,gBACpB,OAAO,EAAE,OAAO;AAAA,gBAChB,UAAU,EAAE,OAAO,EAAE,SAAS;AAAA,gBAC9B,MAAM,EAAE,QAAQ,SAAS;AAAA,gBACzB,UAAU,EAAE,OAAO;AAAA,cACrB,CAAC;AAAA,YACH;AAAA,YACA,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,YAAY;AAAA,YACpC,MAAM,EAAE,OAAO,EAAE,IAAI,EAAE,IAAI,CAAC;AAAA,YAC5B,UAAU,EAAE,OAAO,EAAE,IAAI,EAAE,IAAI,CAAC;AAAA,YAChC,YAAY,EAAE,OAAO,EAAE,IAAI,EAAE,IAAI,CAAC;AAAA,UACpC,CAAC;AAAA,QACH;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { NextResponse } from "next/server";
|
|
2
2
|
import { z } from "zod";
|
|
3
|
-
import { CrudHttpError } from "@open-mercato/shared/lib/crud/errors";
|
|
3
|
+
import { CrudHttpError, isCrudHttpError } from "@open-mercato/shared/lib/crud/errors";
|
|
4
4
|
import { createRequestContainer } from "@open-mercato/shared/lib/di/container";
|
|
5
5
|
import { getAuthFromRequest } from "@open-mercato/shared/lib/auth/server";
|
|
6
6
|
import { resolveOrganizationScopeForRequest } from "@open-mercato/core/modules/directory/utils/organizationScope";
|
|
@@ -111,7 +111,7 @@ async function GET(req, ctx) {
|
|
|
111
111
|
totalPages
|
|
112
112
|
});
|
|
113
113
|
} catch (error) {
|
|
114
|
-
if (error
|
|
114
|
+
if (isCrudHttpError(error)) {
|
|
115
115
|
return NextResponse.json(error.body, { status: error.status });
|
|
116
116
|
}
|
|
117
117
|
console.error("[customers.deals.people.GET]", error);
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../../../../src/modules/customers/api/deals/%5Bid%5D/people/route.ts"],
|
|
4
|
-
"sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport { CrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'\nimport { resolveOrganizationScopeForRequest } from '@open-mercato/core/modules/directory/utils/organizationScope'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport { findOneWithDecryption, findWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { CustomerDeal, CustomerDealPersonLink, CustomerEntity } from '../../../../data/entities'\n\nconst paramsSchema = z.object({\n id: z.string().uuid(),\n})\n\nconst querySchema = z.object({\n page: z.coerce.number().min(1).default(1),\n pageSize: z.coerce.number().min(1).max(100).default(20),\n search: z.string().optional(),\n sort: z.enum(['label-asc', 'label-desc', 'name-asc', 'name-desc', 'recent']).default('label-asc'),\n})\n\ntype DealLinkedEntitySort = 'label-asc' | 'label-desc' | 'recent'\n\nfunction normalizeSort(sort: z.infer<typeof querySchema>['sort']): DealLinkedEntitySort {\n if (sort === 'name-asc') return 'label-asc'\n if (sort === 'name-desc') return 'label-desc'\n return sort\n}\n\ntype DealPersonItem = {\n id: string\n label: string\n subtitle: string | null\n kind: 'person'\n linkedAt: string\n}\n\nfunction matchesSearch(item: DealPersonItem, query: string): boolean {\n const normalized = query.trim().toLowerCase()\n if (!normalized.length) return true\n return [item.label, item.subtitle]\n .filter((value): value is string => typeof value === 'string' && value.length > 0)\n .some((value) => value.toLowerCase().includes(normalized))\n}\n\nfunction sortItems(items: DealPersonItem[], sort: 'label-asc' | 'label-desc' | 'recent'): DealPersonItem[] {\n if (sort === 'recent') {\n return [...items].sort((left, right) => {\n const compare = new Date(right.linkedAt).getTime() - new Date(left.linkedAt).getTime()\n if (compare !== 0) return compare\n return left.label.localeCompare(right.label, undefined, { sensitivity: 'base' })\n })\n }\n return [...items].sort((left, right) => {\n const compare = left.label.localeCompare(right.label, undefined, { sensitivity: 'base' })\n return sort === 'label-asc' ? compare : -compare\n })\n}\n\nexport const metadata = {\n GET: { requireAuth: true, requireFeatures: ['customers.deals.view'] },\n}\n\nexport async function GET(req: Request, ctx: { params?: { id?: string } }) {\n const { translate } = await resolveTranslations()\n try {\n const { id } = paramsSchema.parse({ id: ctx.params?.id })\n const auth = await getAuthFromRequest(req)\n if (!auth?.tenantId) throw new CrudHttpError(401, { error: 'Unauthorized' })\n\n const url = new URL(req.url)\n const query = querySchema.parse({\n page: url.searchParams.get('page') ?? undefined,\n pageSize: url.searchParams.get('pageSize') ?? undefined,\n search: url.searchParams.get('search') ?? undefined,\n sort: url.searchParams.get('sort') ?? undefined,\n })\n\n const container = await createRequestContainer()\n const scope = await resolveOrganizationScopeForRequest({ container, auth, request: req })\n const em = (container.resolve('em') as EntityManager).fork()\n const decryptionScope = {\n tenantId: auth.tenantId,\n organizationId: scope?.selectedId ?? auth.orgId ?? null,\n }\n\n const deal = await findOneWithDecryption(\n em,\n CustomerDeal,\n { id, tenantId: auth.tenantId, deletedAt: null },\n {},\n decryptionScope,\n )\n if (!deal) {\n throw new CrudHttpError(404, { error: translate('customers.errors.deal_not_found', 'Deal not found') })\n }\n\n const allowedOrgIds = new Set<string>()\n if (scope?.filterIds?.length) scope.filterIds.forEach((entry) => allowedOrgIds.add(entry))\n else if (auth.orgId) allowedOrgIds.add(auth.orgId)\n if (allowedOrgIds.size > 0 && deal.organizationId && !allowedOrgIds.has(deal.organizationId)) {\n throw new CrudHttpError(403, { error: translate('customers.errors.access_denied', 'Access denied') })\n }\n\n const entityScope = { tenantId: deal.tenantId, organizationId: deal.organizationId }\n const links = await findWithDecryption(\n em,\n CustomerDealPersonLink,\n { deal: deal.id },\n { populate: ['person'] },\n entityScope,\n )\n\n const items = links\n .map((link) => {\n const person = link.person as CustomerEntity | null\n if (!person?.id) return null\n return {\n id: person.id,\n label: person.displayName ?? person.primaryEmail ?? person.id,\n subtitle: person.primaryEmail ?? person.primaryPhone ?? null,\n kind: 'person',\n linkedAt: link.createdAt.toISOString(),\n } satisfies DealPersonItem\n })\n .filter((item): item is DealPersonItem => item !== null)\n\n const filtered = query.search?.trim().length ? items.filter((item) => matchesSearch(item, query.search ?? '')) : items\n const sorted = sortItems(filtered, normalizeSort(query.sort))\n const total = sorted.length\n const totalPages = Math.max(1, Math.ceil(total / query.pageSize))\n const page = Math.min(query.page, totalPages)\n const start = (page - 1) * query.pageSize\n\n return NextResponse.json({\n items: sorted.slice(start, start + query.pageSize),\n total,\n page,\n pageSize: query.pageSize,\n totalPages,\n })\n } catch (error) {\n if (error
|
|
5
|
-
"mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAElB,SAAS,
|
|
4
|
+
"sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport { CrudHttpError, isCrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'\nimport { resolveOrganizationScopeForRequest } from '@open-mercato/core/modules/directory/utils/organizationScope'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport { findOneWithDecryption, findWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { CustomerDeal, CustomerDealPersonLink, CustomerEntity } from '../../../../data/entities'\n\nconst paramsSchema = z.object({\n id: z.string().uuid(),\n})\n\nconst querySchema = z.object({\n page: z.coerce.number().min(1).default(1),\n pageSize: z.coerce.number().min(1).max(100).default(20),\n search: z.string().optional(),\n sort: z.enum(['label-asc', 'label-desc', 'name-asc', 'name-desc', 'recent']).default('label-asc'),\n})\n\ntype DealLinkedEntitySort = 'label-asc' | 'label-desc' | 'recent'\n\nfunction normalizeSort(sort: z.infer<typeof querySchema>['sort']): DealLinkedEntitySort {\n if (sort === 'name-asc') return 'label-asc'\n if (sort === 'name-desc') return 'label-desc'\n return sort\n}\n\ntype DealPersonItem = {\n id: string\n label: string\n subtitle: string | null\n kind: 'person'\n linkedAt: string\n}\n\nfunction matchesSearch(item: DealPersonItem, query: string): boolean {\n const normalized = query.trim().toLowerCase()\n if (!normalized.length) return true\n return [item.label, item.subtitle]\n .filter((value): value is string => typeof value === 'string' && value.length > 0)\n .some((value) => value.toLowerCase().includes(normalized))\n}\n\nfunction sortItems(items: DealPersonItem[], sort: 'label-asc' | 'label-desc' | 'recent'): DealPersonItem[] {\n if (sort === 'recent') {\n return [...items].sort((left, right) => {\n const compare = new Date(right.linkedAt).getTime() - new Date(left.linkedAt).getTime()\n if (compare !== 0) return compare\n return left.label.localeCompare(right.label, undefined, { sensitivity: 'base' })\n })\n }\n return [...items].sort((left, right) => {\n const compare = left.label.localeCompare(right.label, undefined, { sensitivity: 'base' })\n return sort === 'label-asc' ? compare : -compare\n })\n}\n\nexport const metadata = {\n GET: { requireAuth: true, requireFeatures: ['customers.deals.view'] },\n}\n\nexport async function GET(req: Request, ctx: { params?: { id?: string } }) {\n const { translate } = await resolveTranslations()\n try {\n const { id } = paramsSchema.parse({ id: ctx.params?.id })\n const auth = await getAuthFromRequest(req)\n if (!auth?.tenantId) throw new CrudHttpError(401, { error: 'Unauthorized' })\n\n const url = new URL(req.url)\n const query = querySchema.parse({\n page: url.searchParams.get('page') ?? undefined,\n pageSize: url.searchParams.get('pageSize') ?? undefined,\n search: url.searchParams.get('search') ?? undefined,\n sort: url.searchParams.get('sort') ?? undefined,\n })\n\n const container = await createRequestContainer()\n const scope = await resolveOrganizationScopeForRequest({ container, auth, request: req })\n const em = (container.resolve('em') as EntityManager).fork()\n const decryptionScope = {\n tenantId: auth.tenantId,\n organizationId: scope?.selectedId ?? auth.orgId ?? null,\n }\n\n const deal = await findOneWithDecryption(\n em,\n CustomerDeal,\n { id, tenantId: auth.tenantId, deletedAt: null },\n {},\n decryptionScope,\n )\n if (!deal) {\n throw new CrudHttpError(404, { error: translate('customers.errors.deal_not_found', 'Deal not found') })\n }\n\n const allowedOrgIds = new Set<string>()\n if (scope?.filterIds?.length) scope.filterIds.forEach((entry) => allowedOrgIds.add(entry))\n else if (auth.orgId) allowedOrgIds.add(auth.orgId)\n if (allowedOrgIds.size > 0 && deal.organizationId && !allowedOrgIds.has(deal.organizationId)) {\n throw new CrudHttpError(403, { error: translate('customers.errors.access_denied', 'Access denied') })\n }\n\n const entityScope = { tenantId: deal.tenantId, organizationId: deal.organizationId }\n const links = await findWithDecryption(\n em,\n CustomerDealPersonLink,\n { deal: deal.id },\n { populate: ['person'] },\n entityScope,\n )\n\n const items = links\n .map((link) => {\n const person = link.person as CustomerEntity | null\n if (!person?.id) return null\n return {\n id: person.id,\n label: person.displayName ?? person.primaryEmail ?? person.id,\n subtitle: person.primaryEmail ?? person.primaryPhone ?? null,\n kind: 'person',\n linkedAt: link.createdAt.toISOString(),\n } satisfies DealPersonItem\n })\n .filter((item): item is DealPersonItem => item !== null)\n\n const filtered = query.search?.trim().length ? items.filter((item) => matchesSearch(item, query.search ?? '')) : items\n const sorted = sortItems(filtered, normalizeSort(query.sort))\n const total = sorted.length\n const totalPages = Math.max(1, Math.ceil(total / query.pageSize))\n const page = Math.min(query.page, totalPages)\n const start = (page - 1) * query.pageSize\n\n return NextResponse.json({\n items: sorted.slice(start, start + query.pageSize),\n total,\n page,\n pageSize: query.pageSize,\n totalPages,\n })\n } catch (error) {\n if (isCrudHttpError(error)) {\n return NextResponse.json(error.body, { status: error.status })\n }\n console.error('[customers.deals.people.GET]', error)\n return NextResponse.json({ error: translate('customers.errors.deal_people_load_failed', 'Failed to load linked people') }, { status: 500 })\n }\n}\n\nexport const openApi: OpenApiRouteDoc = {\n tag: 'Customers',\n methods: {\n GET: {\n summary: 'List linked people for a deal',\n query: querySchema,\n responses: [\n {\n status: 200,\n description: 'Paginated linked people',\n schema: z.object({\n items: z.array(\n z.object({\n id: z.string().uuid(),\n label: z.string(),\n subtitle: z.string().nullable(),\n kind: z.literal('person'),\n linkedAt: z.string(),\n }),\n ),\n total: z.number().int().nonnegative(),\n page: z.number().int().min(1),\n pageSize: z.number().int().min(1),\n totalPages: z.number().int().min(1),\n }),\n },\n ],\n },\n },\n}\n"],
|
|
5
|
+
"mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAElB,SAAS,eAAe,uBAAuB;AAC/C,SAAS,8BAA8B;AACvC,SAAS,0BAA0B;AACnC,SAAS,0CAA0C;AACnD,SAAS,2BAA2B;AAEpC,SAAS,uBAAuB,0BAA0B;AAC1D,SAAS,cAAc,8BAA8C;AAErE,MAAM,eAAe,EAAE,OAAO;AAAA,EAC5B,IAAI,EAAE,OAAO,EAAE,KAAK;AACtB,CAAC;AAED,MAAM,cAAc,EAAE,OAAO;AAAA,EAC3B,MAAM,EAAE,OAAO,OAAO,EAAE,IAAI,CAAC,EAAE,QAAQ,CAAC;AAAA,EACxC,UAAU,EAAE,OAAO,OAAO,EAAE,IAAI,CAAC,EAAE,IAAI,GAAG,EAAE,QAAQ,EAAE;AAAA,EACtD,QAAQ,EAAE,OAAO,EAAE,SAAS;AAAA,EAC5B,MAAM,EAAE,KAAK,CAAC,aAAa,cAAc,YAAY,aAAa,QAAQ,CAAC,EAAE,QAAQ,WAAW;AAClG,CAAC;AAID,SAAS,cAAc,MAAi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E,OAAO,UAAU,4CAA4C,8BAA8B,EAAE,GAAG,EAAE,QAAQ,IAAI,CAAC;AAAA,EAC5I;AACF;AAEO,MAAM,UAA2B;AAAA,EACtC,KAAK;AAAA,EACL,SAAS;AAAA,IACP,KAAK;AAAA,MACH,SAAS;AAAA,MACT,OAAO;AAAA,MACP,WAAW;AAAA,QACT;AAAA,UACE,QAAQ;AAAA,UACR,aAAa;AAAA,UACb,QAAQ,EAAE,OAAO;AAAA,YACf,OAAO,EAAE;AAAA,cACP,EAAE,OAAO;AAAA,gBACP,IAAI,EAAE,OAAO,EAAE,KAAK;AAAA,gBACpB,OAAO,EAAE,OAAO;AAAA,gBAChB,UAAU,EAAE,OAAO,EAAE,SAAS;AAAA,gBAC9B,MAAM,EAAE,QAAQ,QAAQ;AAAA,gBACxB,UAAU,EAAE,OAAO;AAAA,cACrB,CAAC;AAAA,YACH;AAAA,YACA,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,YAAY;AAAA,YACpC,MAAM,EAAE,OAAO,EAAE,IAAI,EAAE,IAAI,CAAC;AAAA,YAC5B,UAAU,EAAE,OAAO,EAAE,IAAI,EAAE,IAAI,CAAC;AAAA,YAChC,YAAY,EAAE,OAAO,EAAE,IAAI,EAAE,IAAI,CAAC;AAAA,UACpC,CAAC;AAAA,QACH;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { NextResponse } from "next/server";
|
|
2
2
|
import { z } from "zod";
|
|
3
3
|
import { resolveTranslations } from "@open-mercato/shared/lib/i18n/server";
|
|
4
|
-
import { CrudHttpError } from "@open-mercato/shared/lib/crud/errors";
|
|
4
|
+
import { CrudHttpError, isCrudHttpError } from "@open-mercato/shared/lib/crud/errors";
|
|
5
5
|
import { serializeOperationMetadata } from "@open-mercato/shared/lib/commands/operationMetadata";
|
|
6
6
|
import { CustomerDictionaryEntry } from "../../../../data/entities.js";
|
|
7
7
|
import { mapDictionaryKind, resolveDictionaryActorId, resolveDictionaryRouteContext } from "../../context.js";
|
|
@@ -71,7 +71,7 @@ async function PATCH(req, ctx) {
|
|
|
71
71
|
ctx: routeContext.ctx
|
|
72
72
|
});
|
|
73
73
|
} catch (err) {
|
|
74
|
-
if (err
|
|
74
|
+
if (isCrudHttpError(err)) {
|
|
75
75
|
if (err.status === 404) {
|
|
76
76
|
throw new CrudHttpError(404, { error: routeContext.translate("customers.errors.lookup_failed", "Dictionary entry not found") });
|
|
77
77
|
}
|
|
@@ -156,7 +156,7 @@ async function PATCH(req, ctx) {
|
|
|
156
156
|
}
|
|
157
157
|
return response;
|
|
158
158
|
} catch (err) {
|
|
159
|
-
if (err
|
|
159
|
+
if (isCrudHttpError(err)) {
|
|
160
160
|
return NextResponse.json(err.body, { status: err.status });
|
|
161
161
|
}
|
|
162
162
|
const { translate } = await resolveTranslations();
|
|
@@ -200,10 +200,10 @@ async function DELETE(req, ctx) {
|
|
|
200
200
|
ctx: routeContext.ctx
|
|
201
201
|
});
|
|
202
202
|
} catch (err) {
|
|
203
|
-
if (err
|
|
203
|
+
if (isCrudHttpError(err) && err.status === 404) {
|
|
204
204
|
throw new CrudHttpError(404, { error: routeContext.translate("customers.errors.lookup_failed", "Dictionary entry not found") });
|
|
205
205
|
}
|
|
206
|
-
if (err
|
|
206
|
+
if (isCrudHttpError(err) && err.status === 409 && err.body?.code === "role_type_in_use") {
|
|
207
207
|
const usageCount = Number(err.body?.usageCount ?? 0);
|
|
208
208
|
throw new CrudHttpError(409, {
|
|
209
209
|
...err.body,
|
|
@@ -254,7 +254,7 @@ async function DELETE(req, ctx) {
|
|
|
254
254
|
}
|
|
255
255
|
return response;
|
|
256
256
|
} catch (err) {
|
|
257
|
-
if (err
|
|
257
|
+
if (isCrudHttpError(err)) {
|
|
258
258
|
return NextResponse.json(err.body, { status: err.status });
|
|
259
259
|
}
|
|
260
260
|
const { translate } = await resolveTranslations();
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../../../../src/modules/customers/api/dictionaries/%5Bkind%5D/%5Bid%5D/route.ts"],
|
|
4
|
-
"sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport { CrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport type { CommandBus } from '@open-mercato/shared/lib/commands'\nimport { serializeOperationMetadata } from '@open-mercato/shared/lib/commands/operationMetadata'\nimport type { CommandExecuteResult } from '@open-mercato/shared/lib/commands/types'\nimport { CustomerDictionaryEntry } from '../../../../data/entities'\nimport { mapDictionaryKind, resolveDictionaryActorId, resolveDictionaryRouteContext } from '../../context'\nimport { invalidateDictionaryCache } from '../../cache'\nimport type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport { readJsonSafe } from '@open-mercato/shared/lib/http/readJsonSafe'\nimport { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport {\n runCrudMutationGuardAfterSuccess,\n validateCrudMutationGuard,\n} from '@open-mercato/shared/lib/crud/mutation-guard'\n\nconst paramsSchema = z.object({\n id: z.string().uuid(),\n})\n\nconst patchSchema = z\n .object({\n value: z.string().trim().min(1).max(150).optional(),\n label: z.string().trim().max(150).optional(),\n color: z.union([z.string().trim(), z.null()]).optional(),\n icon: z.union([z.string().trim(), z.null()]).optional(),\n })\n .refine((input) => input.value !== undefined || input.label !== undefined || input.color !== undefined || input.icon !== undefined, {\n message: 'No changes provided',\n })\n\nexport const metadata = {\n PATCH: { requireAuth: true, requireFeatures: ['customers.settings.manage'] },\n DELETE: { requireAuth: true, requireFeatures: ['customers.settings.manage'] },\n}\n\nfunction formatCountMessage(template: string, count: number) {\n return template.replace('{{count}}', String(count))\n}\n\nexport async function PATCH(req: Request, ctx: { params?: { kind?: string; id?: string } }) {\n try {\n const routeContext = await resolveDictionaryRouteContext(req)\n if (!routeContext.organizationId) {\n throw new CrudHttpError(400, { error: routeContext.translate('customers.errors.organization_required', 'Organization context is required') })\n }\n const { mappedKind } = mapDictionaryKind(ctx.params?.kind)\n const { id } = paramsSchema.parse({ id: ctx.params?.id })\n const payload = patchSchema.parse(await readJsonSafe(req, {}))\n const guardUserId = resolveDictionaryActorId(routeContext.auth)\n const guardResult = await validateCrudMutationGuard(routeContext.container, {\n tenantId: routeContext.tenantId,\n organizationId: routeContext.organizationId,\n userId: guardUserId,\n resourceKind: 'customers.dictionary_entry',\n resourceId: id,\n operation: 'update',\n requestMethod: req.method,\n requestHeaders: req.headers,\n mutationPayload: payload,\n })\n if (guardResult && !guardResult.ok) {\n return NextResponse.json(guardResult.body, { status: guardResult.status })\n }\n const commandBus = (routeContext.container.resolve('commandBus') as CommandBus)\n let commandResult: CommandExecuteResult<{ entryId: string; changed: boolean }>\n try {\n commandResult = (await commandBus.execute('customers.dictionaryEntries.update', {\n input: {\n id,\n tenantId: routeContext.tenantId,\n organizationId: routeContext.organizationId,\n kind: mappedKind,\n value: payload.value,\n label: payload.label,\n color: payload.color,\n icon: payload.icon,\n },\n ctx: routeContext.ctx,\n })) as CommandExecuteResult<{ entryId: string; changed: boolean }>\n } catch (err) {\n if (err instanceof CrudHttpError) {\n if (err.status === 404) {\n throw new CrudHttpError(404, { error: routeContext.translate('customers.errors.lookup_failed', 'Dictionary entry not found') })\n }\n if (err.status === 409) {\n if ((err.body as Record<string, unknown> | undefined)?.code === 'role_type_in_use') {\n const usageCount = Number((err.body as Record<string, unknown> | undefined)?.usageCount ?? 0)\n throw new CrudHttpError(409, {\n ...(err.body as Record<string, unknown> | undefined),\n error: formatCountMessage(\n routeContext.translate(\n 'customers.config.dictionaries.errors.roleTypeValueInUse',\n 'This role type is assigned to {{count}} records. Remove or replace those assignments before changing its value.',\n ),\n usageCount,\n ),\n })\n }\n throw new CrudHttpError(409, { error: routeContext.translate('customers.config.dictionaries.errors.duplicate', 'An entry with this value already exists') })\n }\n if (err.status === 400) {\n throw new CrudHttpError(400, { error: routeContext.translate('customers.errors.lookup_failed', 'Failed to save dictionary entry') })\n }\n }\n throw err\n }\n const { result, logEntry } = commandResult\n\n const entry = await findOneWithDecryption(\n routeContext.em.fork(),\n CustomerDictionaryEntry,\n { id },\n {},\n {\n tenantId: routeContext.tenantId,\n organizationId: routeContext.organizationId,\n },\n )\n if (!entry) {\n throw new CrudHttpError(404, { error: routeContext.translate('customers.errors.lookup_failed', 'Dictionary entry not found') })\n }\n\n if (result.changed) {\n await invalidateDictionaryCache(routeContext.cache, {\n tenantId: routeContext.tenantId,\n mappedKind,\n organizationIds: [routeContext.organizationId],\n })\n }\n\n const response = NextResponse.json({\n id: entry.id,\n value: entry.value,\n label: entry.label,\n color: entry.color,\n icon: entry.icon,\n organizationId: entry.organizationId,\n isInherited: false,\n })\n if (logEntry?.undoToken && logEntry?.id && logEntry?.commandId) {\n response.headers.set(\n 'x-om-operation',\n serializeOperationMetadata({\n id: logEntry.id,\n undoToken: logEntry.undoToken,\n commandId: logEntry.commandId,\n actionLabel: logEntry.actionLabel ?? null,\n resourceKind: logEntry.resourceKind ?? 'customers.dictionary_entry',\n resourceId: entry.id,\n executedAt: logEntry.createdAt instanceof Date ? logEntry.createdAt.toISOString() : undefined,\n })\n )\n }\n if (guardResult?.ok && guardResult.shouldRunAfterSuccess) {\n await runCrudMutationGuardAfterSuccess(routeContext.container, {\n tenantId: routeContext.tenantId,\n organizationId: routeContext.organizationId,\n userId: guardUserId,\n resourceKind: 'customers.dictionary_entry',\n resourceId: entry.id,\n operation: 'update',\n requestMethod: req.method,\n requestHeaders: req.headers,\n metadata: guardResult.metadata ?? null,\n })\n }\n return response\n } catch (err) {\n if (err instanceof CrudHttpError) {\n return NextResponse.json(err.body, { status: err.status })\n }\n const { translate } = await resolveTranslations()\n console.error('customers.dictionaries.update failed', err)\n return NextResponse.json({ error: translate('customers.errors.lookup_failed', 'Failed to save dictionary entry') }, { status: 400 })\n }\n}\n\nexport async function DELETE(req: Request, ctx: { params?: { kind?: string; id?: string } }) {\n try {\n const routeContext = await resolveDictionaryRouteContext(req)\n if (!routeContext.organizationId) {\n throw new CrudHttpError(400, { error: routeContext.translate('customers.errors.organization_required', 'Organization context is required') })\n }\n const { mappedKind } = mapDictionaryKind(ctx.params?.kind)\n const { id } = paramsSchema.parse({ id: ctx.params?.id })\n const guardUserId = resolveDictionaryActorId(routeContext.auth)\n const guardResult = await validateCrudMutationGuard(routeContext.container, {\n tenantId: routeContext.tenantId,\n organizationId: routeContext.organizationId,\n userId: guardUserId,\n resourceKind: 'customers.dictionary_entry',\n resourceId: id,\n operation: 'delete',\n requestMethod: req.method,\n requestHeaders: req.headers,\n mutationPayload: null,\n })\n if (guardResult && !guardResult.ok) {\n return NextResponse.json(guardResult.body, { status: guardResult.status })\n }\n const commandBus = (routeContext.container.resolve('commandBus') as CommandBus)\n let deleteResult: CommandExecuteResult<{ entryId: string }>\n try {\n deleteResult = (await commandBus.execute('customers.dictionaryEntries.delete', {\n input: {\n id,\n tenantId: routeContext.tenantId,\n organizationId: routeContext.organizationId,\n kind: mappedKind,\n },\n ctx: routeContext.ctx,\n })) as CommandExecuteResult<{ entryId: string }>\n } catch (err) {\n if (err instanceof CrudHttpError && err.status === 404) {\n throw new CrudHttpError(404, { error: routeContext.translate('customers.errors.lookup_failed', 'Dictionary entry not found') })\n }\n if (err instanceof CrudHttpError && err.status === 409 && (err.body as Record<string, unknown> | undefined)?.code === 'role_type_in_use') {\n const usageCount = Number((err.body as Record<string, unknown> | undefined)?.usageCount ?? 0)\n throw new CrudHttpError(409, {\n ...(err.body as Record<string, unknown> | undefined),\n error: formatCountMessage(\n routeContext.translate(\n 'customers.config.dictionaries.errors.roleTypeDeleteInUse',\n 'This role type is assigned to {{count}} records. Remove or replace those assignments before deleting it.',\n ),\n usageCount,\n ),\n })\n }\n throw err\n }\n const { logEntry } = deleteResult\n\n await invalidateDictionaryCache(routeContext.cache, {\n tenantId: routeContext.tenantId,\n mappedKind,\n organizationIds: [routeContext.organizationId],\n })\n\n const response = NextResponse.json({ success: true })\n if (logEntry?.undoToken && logEntry?.id && logEntry?.commandId) {\n response.headers.set(\n 'x-om-operation',\n serializeOperationMetadata({\n id: logEntry.id,\n undoToken: logEntry.undoToken,\n commandId: logEntry.commandId,\n actionLabel: logEntry.actionLabel ?? null,\n resourceKind: logEntry.resourceKind ?? 'customers.dictionary_entry',\n resourceId: id,\n executedAt: logEntry.createdAt instanceof Date ? logEntry.createdAt.toISOString() : undefined,\n })\n )\n }\n if (guardResult?.ok && guardResult.shouldRunAfterSuccess) {\n await runCrudMutationGuardAfterSuccess(routeContext.container, {\n tenantId: routeContext.tenantId,\n organizationId: routeContext.organizationId,\n userId: guardUserId,\n resourceKind: 'customers.dictionary_entry',\n resourceId: id,\n operation: 'delete',\n requestMethod: req.method,\n requestHeaders: req.headers,\n metadata: guardResult.metadata ?? null,\n })\n }\n return response\n } catch (err) {\n if (err instanceof CrudHttpError) {\n return NextResponse.json(err.body, { status: err.status })\n }\n const { translate } = await resolveTranslations()\n console.error('customers.dictionaries.delete failed', err)\n return NextResponse.json({ error: translate('customers.errors.lookup_failed', 'Failed to delete dictionary entry') }, { status: 400 })\n }\n}\n\nconst dictionaryEntrySchema = z.object({\n id: z.string().uuid(),\n value: z.string(),\n label: z.string().nullable().optional(),\n color: z.string().nullable().optional(),\n icon: z.string().nullable().optional(),\n organizationId: z.string().uuid().nullable().optional(),\n isInherited: z.boolean().optional(),\n})\n\nconst dictionaryDeleteResponseSchema = z.object({\n success: z.literal(true),\n})\n\nconst dictionaryErrorSchema = z.object({\n error: z.string(),\n})\n\nexport const openApi: OpenApiRouteDoc = {\n tag: 'Customers',\n summary: 'Customer dictionary entry',\n methods: {\n PATCH: {\n summary: 'Update dictionary entry',\n description: 'Updates value, label, color, or icon for an existing customer dictionary entry.',\n requestBody: {\n contentType: 'application/json',\n schema: patchSchema,\n },\n responses: [\n { status: 200, description: 'Updated dictionary entry', schema: dictionaryEntrySchema },\n ],\n errors: [\n { status: 400, description: 'Invalid payload', schema: dictionaryErrorSchema },\n { status: 401, description: 'Unauthorized', schema: dictionaryErrorSchema },\n { status: 404, description: 'Entry not found', schema: dictionaryErrorSchema },\n { status: 409, description: 'Duplicate value conflict', schema: dictionaryErrorSchema },\n ],\n },\n DELETE: {\n summary: 'Delete dictionary entry',\n description: 'Removes a customer dictionary entry by identifier.',\n responses: [\n { status: 200, description: 'Entry deleted', schema: dictionaryDeleteResponseSchema },\n ],\n errors: [\n { status: 401, description: 'Unauthorized', schema: dictionaryErrorSchema },\n { status: 404, description: 'Entry not found', schema: dictionaryErrorSchema },\n { status: 409, description: 'Entry is in use and cannot be deleted', schema: dictionaryErrorSchema },\n ],\n },\n },\n}\n"],
|
|
5
|
-
"mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAClB,SAAS,2BAA2B;AACpC,SAAS,
|
|
4
|
+
"sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport { CrudHttpError, isCrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport type { CommandBus } from '@open-mercato/shared/lib/commands'\nimport { serializeOperationMetadata } from '@open-mercato/shared/lib/commands/operationMetadata'\nimport type { CommandExecuteResult } from '@open-mercato/shared/lib/commands/types'\nimport { CustomerDictionaryEntry } from '../../../../data/entities'\nimport { mapDictionaryKind, resolveDictionaryActorId, resolveDictionaryRouteContext } from '../../context'\nimport { invalidateDictionaryCache } from '../../cache'\nimport type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport { readJsonSafe } from '@open-mercato/shared/lib/http/readJsonSafe'\nimport { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport {\n runCrudMutationGuardAfterSuccess,\n validateCrudMutationGuard,\n} from '@open-mercato/shared/lib/crud/mutation-guard'\n\nconst paramsSchema = z.object({\n id: z.string().uuid(),\n})\n\nconst patchSchema = z\n .object({\n value: z.string().trim().min(1).max(150).optional(),\n label: z.string().trim().max(150).optional(),\n color: z.union([z.string().trim(), z.null()]).optional(),\n icon: z.union([z.string().trim(), z.null()]).optional(),\n })\n .refine((input) => input.value !== undefined || input.label !== undefined || input.color !== undefined || input.icon !== undefined, {\n message: 'No changes provided',\n })\n\nexport const metadata = {\n PATCH: { requireAuth: true, requireFeatures: ['customers.settings.manage'] },\n DELETE: { requireAuth: true, requireFeatures: ['customers.settings.manage'] },\n}\n\nfunction formatCountMessage(template: string, count: number) {\n return template.replace('{{count}}', String(count))\n}\n\nexport async function PATCH(req: Request, ctx: { params?: { kind?: string; id?: string } }) {\n try {\n const routeContext = await resolveDictionaryRouteContext(req)\n if (!routeContext.organizationId) {\n throw new CrudHttpError(400, { error: routeContext.translate('customers.errors.organization_required', 'Organization context is required') })\n }\n const { mappedKind } = mapDictionaryKind(ctx.params?.kind)\n const { id } = paramsSchema.parse({ id: ctx.params?.id })\n const payload = patchSchema.parse(await readJsonSafe(req, {}))\n const guardUserId = resolveDictionaryActorId(routeContext.auth)\n const guardResult = await validateCrudMutationGuard(routeContext.container, {\n tenantId: routeContext.tenantId,\n organizationId: routeContext.organizationId,\n userId: guardUserId,\n resourceKind: 'customers.dictionary_entry',\n resourceId: id,\n operation: 'update',\n requestMethod: req.method,\n requestHeaders: req.headers,\n mutationPayload: payload,\n })\n if (guardResult && !guardResult.ok) {\n return NextResponse.json(guardResult.body, { status: guardResult.status })\n }\n const commandBus = (routeContext.container.resolve('commandBus') as CommandBus)\n let commandResult: CommandExecuteResult<{ entryId: string; changed: boolean }>\n try {\n commandResult = (await commandBus.execute('customers.dictionaryEntries.update', {\n input: {\n id,\n tenantId: routeContext.tenantId,\n organizationId: routeContext.organizationId,\n kind: mappedKind,\n value: payload.value,\n label: payload.label,\n color: payload.color,\n icon: payload.icon,\n },\n ctx: routeContext.ctx,\n })) as CommandExecuteResult<{ entryId: string; changed: boolean }>\n } catch (err) {\n if (isCrudHttpError(err)) {\n if (err.status === 404) {\n throw new CrudHttpError(404, { error: routeContext.translate('customers.errors.lookup_failed', 'Dictionary entry not found') })\n }\n if (err.status === 409) {\n if ((err.body as Record<string, unknown> | undefined)?.code === 'role_type_in_use') {\n const usageCount = Number((err.body as Record<string, unknown> | undefined)?.usageCount ?? 0)\n throw new CrudHttpError(409, {\n ...(err.body as Record<string, unknown> | undefined),\n error: formatCountMessage(\n routeContext.translate(\n 'customers.config.dictionaries.errors.roleTypeValueInUse',\n 'This role type is assigned to {{count}} records. Remove or replace those assignments before changing its value.',\n ),\n usageCount,\n ),\n })\n }\n throw new CrudHttpError(409, { error: routeContext.translate('customers.config.dictionaries.errors.duplicate', 'An entry with this value already exists') })\n }\n if (err.status === 400) {\n throw new CrudHttpError(400, { error: routeContext.translate('customers.errors.lookup_failed', 'Failed to save dictionary entry') })\n }\n }\n throw err\n }\n const { result, logEntry } = commandResult\n\n const entry = await findOneWithDecryption(\n routeContext.em.fork(),\n CustomerDictionaryEntry,\n { id },\n {},\n {\n tenantId: routeContext.tenantId,\n organizationId: routeContext.organizationId,\n },\n )\n if (!entry) {\n throw new CrudHttpError(404, { error: routeContext.translate('customers.errors.lookup_failed', 'Dictionary entry not found') })\n }\n\n if (result.changed) {\n await invalidateDictionaryCache(routeContext.cache, {\n tenantId: routeContext.tenantId,\n mappedKind,\n organizationIds: [routeContext.organizationId],\n })\n }\n\n const response = NextResponse.json({\n id: entry.id,\n value: entry.value,\n label: entry.label,\n color: entry.color,\n icon: entry.icon,\n organizationId: entry.organizationId,\n isInherited: false,\n })\n if (logEntry?.undoToken && logEntry?.id && logEntry?.commandId) {\n response.headers.set(\n 'x-om-operation',\n serializeOperationMetadata({\n id: logEntry.id,\n undoToken: logEntry.undoToken,\n commandId: logEntry.commandId,\n actionLabel: logEntry.actionLabel ?? null,\n resourceKind: logEntry.resourceKind ?? 'customers.dictionary_entry',\n resourceId: entry.id,\n executedAt: logEntry.createdAt instanceof Date ? logEntry.createdAt.toISOString() : undefined,\n })\n )\n }\n if (guardResult?.ok && guardResult.shouldRunAfterSuccess) {\n await runCrudMutationGuardAfterSuccess(routeContext.container, {\n tenantId: routeContext.tenantId,\n organizationId: routeContext.organizationId,\n userId: guardUserId,\n resourceKind: 'customers.dictionary_entry',\n resourceId: entry.id,\n operation: 'update',\n requestMethod: req.method,\n requestHeaders: req.headers,\n metadata: guardResult.metadata ?? null,\n })\n }\n return response\n } catch (err) {\n if (isCrudHttpError(err)) {\n return NextResponse.json(err.body, { status: err.status })\n }\n const { translate } = await resolveTranslations()\n console.error('customers.dictionaries.update failed', err)\n return NextResponse.json({ error: translate('customers.errors.lookup_failed', 'Failed to save dictionary entry') }, { status: 400 })\n }\n}\n\nexport async function DELETE(req: Request, ctx: { params?: { kind?: string; id?: string } }) {\n try {\n const routeContext = await resolveDictionaryRouteContext(req)\n if (!routeContext.organizationId) {\n throw new CrudHttpError(400, { error: routeContext.translate('customers.errors.organization_required', 'Organization context is required') })\n }\n const { mappedKind } = mapDictionaryKind(ctx.params?.kind)\n const { id } = paramsSchema.parse({ id: ctx.params?.id })\n const guardUserId = resolveDictionaryActorId(routeContext.auth)\n const guardResult = await validateCrudMutationGuard(routeContext.container, {\n tenantId: routeContext.tenantId,\n organizationId: routeContext.organizationId,\n userId: guardUserId,\n resourceKind: 'customers.dictionary_entry',\n resourceId: id,\n operation: 'delete',\n requestMethod: req.method,\n requestHeaders: req.headers,\n mutationPayload: null,\n })\n if (guardResult && !guardResult.ok) {\n return NextResponse.json(guardResult.body, { status: guardResult.status })\n }\n const commandBus = (routeContext.container.resolve('commandBus') as CommandBus)\n let deleteResult: CommandExecuteResult<{ entryId: string }>\n try {\n deleteResult = (await commandBus.execute('customers.dictionaryEntries.delete', {\n input: {\n id,\n tenantId: routeContext.tenantId,\n organizationId: routeContext.organizationId,\n kind: mappedKind,\n },\n ctx: routeContext.ctx,\n })) as CommandExecuteResult<{ entryId: string }>\n } catch (err) {\n if (isCrudHttpError(err) && err.status === 404) {\n throw new CrudHttpError(404, { error: routeContext.translate('customers.errors.lookup_failed', 'Dictionary entry not found') })\n }\n if (isCrudHttpError(err) && err.status === 409 && (err.body as Record<string, unknown> | undefined)?.code === 'role_type_in_use') {\n const usageCount = Number((err.body as Record<string, unknown> | undefined)?.usageCount ?? 0)\n throw new CrudHttpError(409, {\n ...(err.body as Record<string, unknown> | undefined),\n error: formatCountMessage(\n routeContext.translate(\n 'customers.config.dictionaries.errors.roleTypeDeleteInUse',\n 'This role type is assigned to {{count}} records. Remove or replace those assignments before deleting it.',\n ),\n usageCount,\n ),\n })\n }\n throw err\n }\n const { logEntry } = deleteResult\n\n await invalidateDictionaryCache(routeContext.cache, {\n tenantId: routeContext.tenantId,\n mappedKind,\n organizationIds: [routeContext.organizationId],\n })\n\n const response = NextResponse.json({ success: true })\n if (logEntry?.undoToken && logEntry?.id && logEntry?.commandId) {\n response.headers.set(\n 'x-om-operation',\n serializeOperationMetadata({\n id: logEntry.id,\n undoToken: logEntry.undoToken,\n commandId: logEntry.commandId,\n actionLabel: logEntry.actionLabel ?? null,\n resourceKind: logEntry.resourceKind ?? 'customers.dictionary_entry',\n resourceId: id,\n executedAt: logEntry.createdAt instanceof Date ? logEntry.createdAt.toISOString() : undefined,\n })\n )\n }\n if (guardResult?.ok && guardResult.shouldRunAfterSuccess) {\n await runCrudMutationGuardAfterSuccess(routeContext.container, {\n tenantId: routeContext.tenantId,\n organizationId: routeContext.organizationId,\n userId: guardUserId,\n resourceKind: 'customers.dictionary_entry',\n resourceId: id,\n operation: 'delete',\n requestMethod: req.method,\n requestHeaders: req.headers,\n metadata: guardResult.metadata ?? null,\n })\n }\n return response\n } catch (err) {\n if (isCrudHttpError(err)) {\n return NextResponse.json(err.body, { status: err.status })\n }\n const { translate } = await resolveTranslations()\n console.error('customers.dictionaries.delete failed', err)\n return NextResponse.json({ error: translate('customers.errors.lookup_failed', 'Failed to delete dictionary entry') }, { status: 400 })\n }\n}\n\nconst dictionaryEntrySchema = z.object({\n id: z.string().uuid(),\n value: z.string(),\n label: z.string().nullable().optional(),\n color: z.string().nullable().optional(),\n icon: z.string().nullable().optional(),\n organizationId: z.string().uuid().nullable().optional(),\n isInherited: z.boolean().optional(),\n})\n\nconst dictionaryDeleteResponseSchema = z.object({\n success: z.literal(true),\n})\n\nconst dictionaryErrorSchema = z.object({\n error: z.string(),\n})\n\nexport const openApi: OpenApiRouteDoc = {\n tag: 'Customers',\n summary: 'Customer dictionary entry',\n methods: {\n PATCH: {\n summary: 'Update dictionary entry',\n description: 'Updates value, label, color, or icon for an existing customer dictionary entry.',\n requestBody: {\n contentType: 'application/json',\n schema: patchSchema,\n },\n responses: [\n { status: 200, description: 'Updated dictionary entry', schema: dictionaryEntrySchema },\n ],\n errors: [\n { status: 400, description: 'Invalid payload', schema: dictionaryErrorSchema },\n { status: 401, description: 'Unauthorized', schema: dictionaryErrorSchema },\n { status: 404, description: 'Entry not found', schema: dictionaryErrorSchema },\n { status: 409, description: 'Duplicate value conflict', schema: dictionaryErrorSchema },\n ],\n },\n DELETE: {\n summary: 'Delete dictionary entry',\n description: 'Removes a customer dictionary entry by identifier.',\n responses: [\n { status: 200, description: 'Entry deleted', schema: dictionaryDeleteResponseSchema },\n ],\n errors: [\n { status: 401, description: 'Unauthorized', schema: dictionaryErrorSchema },\n { status: 404, description: 'Entry not found', schema: dictionaryErrorSchema },\n { status: 409, description: 'Entry is in use and cannot be deleted', schema: dictionaryErrorSchema },\n ],\n },\n },\n}\n"],
|
|
5
|
+
"mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAClB,SAAS,2BAA2B;AACpC,SAAS,eAAe,uBAAuB;AAE/C,SAAS,kCAAkC;AAE3C,SAAS,+BAA+B;AACxC,SAAS,mBAAmB,0BAA0B,qCAAqC;AAC3F,SAAS,iCAAiC;AAE1C,SAAS,oBAAoB;AAC7B,SAAS,6BAA6B;AACtC;AAAA,EACE;AAAA,EACA;AAAA,OACK;AAEP,MAAM,eAAe,EAAE,OAAO;AAAA,EAC5B,IAAI,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AAA,IACF;AAAA,EACF;AACF;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { NextResponse } from "next/server";
|
|
2
2
|
import { resolveTranslations } from "@open-mercato/shared/lib/i18n/server";
|
|
3
|
-
import { CrudHttpError } from "@open-mercato/shared/lib/crud/errors";
|
|
3
|
+
import { CrudHttpError, isCrudHttpError } from "@open-mercato/shared/lib/crud/errors";
|
|
4
4
|
import { serializeOperationMetadata } from "@open-mercato/shared/lib/commands/operationMetadata";
|
|
5
5
|
import { CustomerDictionaryEntry, CustomerPipelineStage } from "../../../data/entities.js";
|
|
6
6
|
import { ensureDictionaryEntry } from "../../../commands/shared.js";
|
|
@@ -151,7 +151,7 @@ async function GET(req, ctx) {
|
|
|
151
151
|
}
|
|
152
152
|
return NextResponse.json(responseBody);
|
|
153
153
|
} catch (err) {
|
|
154
|
-
if (err
|
|
154
|
+
if (isCrudHttpError(err)) {
|
|
155
155
|
return NextResponse.json(err.body, { status: err.status });
|
|
156
156
|
}
|
|
157
157
|
const { translate } = await resolveTranslations();
|
|
@@ -245,7 +245,7 @@ async function POST(req, ctx) {
|
|
|
245
245
|
}
|
|
246
246
|
return response;
|
|
247
247
|
} catch (err) {
|
|
248
|
-
if (err
|
|
248
|
+
if (isCrudHttpError(err)) {
|
|
249
249
|
return NextResponse.json(err.body, { status: err.status });
|
|
250
250
|
}
|
|
251
251
|
const { translate } = await resolveTranslations();
|