@open-mercato/core 0.10.1-develop.7833.1.d6cbf0e3ab → 0.10.1-develop.7841.1.af87ac614d

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (136) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/dist/modules/cart/api/current/lines/bulk/route.js +1 -1
  3. package/dist/modules/cart/api/current/lines/bulk/route.js.map +2 -2
  4. package/dist/modules/cart/api/current/lines/route.js +1 -1
  5. package/dist/modules/cart/api/current/lines/route.js.map +2 -2
  6. package/dist/modules/cart/commands/lines.js +5 -10
  7. package/dist/modules/cart/commands/lines.js.map +2 -2
  8. package/dist/modules/cart/lib/currentCartRoute.js +8 -0
  9. package/dist/modules/cart/lib/currentCartRoute.js.map +3 -3
  10. package/dist/modules/cart/lib/lineMutationLock.js +52 -0
  11. package/dist/modules/cart/lib/lineMutationLock.js.map +7 -0
  12. package/dist/modules/customer_accounts/api/admin/roles.js +25 -2
  13. package/dist/modules/customer_accounts/api/admin/roles.js.map +2 -2
  14. package/dist/modules/customer_accounts/api/admin/users.js +24 -7
  15. package/dist/modules/customer_accounts/api/admin/users.js.map +2 -2
  16. package/dist/modules/customer_accounts/backend/customer_accounts/users/PortalUsersPageClient.js +77 -15
  17. package/dist/modules/customer_accounts/backend/customer_accounts/users/PortalUsersPageClient.js.map +2 -2
  18. package/dist/modules/customer_accounts/backend/customer_accounts/users/page.js +12 -1
  19. package/dist/modules/customer_accounts/backend/customer_accounts/users/page.js.map +2 -2
  20. package/dist/modules/customer_accounts/data/validators.js +2 -1
  21. package/dist/modules/customer_accounts/data/validators.js.map +2 -2
  22. package/dist/modules/customer_accounts/lib/adminOrganizationScope.js +46 -0
  23. package/dist/modules/customer_accounts/lib/adminOrganizationScope.js.map +7 -0
  24. package/dist/modules/customers/api/customer-dictionary-entries/route.js +86 -0
  25. package/dist/modules/customers/api/customer-dictionary-entries/route.js.map +7 -0
  26. package/dist/modules/customers/api/dictionaries/[kind]/route.js +29 -7
  27. package/dist/modules/customers/api/dictionaries/[kind]/route.js.map +2 -2
  28. package/dist/modules/customers/cli.js +28 -110
  29. package/dist/modules/customers/cli.js.map +3 -3
  30. package/dist/modules/customers/components/DictionarySettings.js +1 -1
  31. package/dist/modules/customers/components/DictionarySettings.js.map +1 -1
  32. package/dist/modules/customers/components/detail/ManageTagsDialog.js +1 -1
  33. package/dist/modules/customers/components/detail/ManageTagsDialog.js.map +2 -2
  34. package/dist/modules/customers/components/detail/TaskDialog.js +14 -1
  35. package/dist/modules/customers/components/detail/TaskDialog.js.map +2 -2
  36. package/dist/modules/customers/components/detail/TaskForm.js +1 -16
  37. package/dist/modules/customers/components/detail/TaskForm.js.map +2 -2
  38. package/dist/modules/customers/components/detail/TasksSection.js +38 -10
  39. package/dist/modules/customers/components/detail/TasksSection.js.map +2 -2
  40. package/dist/modules/customers/components/detail/hooks/useCustomerDictionary.js +12 -5
  41. package/dist/modules/customers/components/detail/hooks/useCustomerDictionary.js.map +2 -2
  42. package/dist/modules/customers/components/detail/hooks/useInteractions.js +3 -13
  43. package/dist/modules/customers/components/detail/hooks/useInteractions.js.map +2 -2
  44. package/dist/modules/customers/lib/dictionaryDefaults.js +134 -0
  45. package/dist/modules/customers/lib/dictionaryDefaults.js.map +7 -0
  46. package/dist/modules/customers/lib/dictionaryLabels.js +59 -0
  47. package/dist/modules/customers/lib/dictionaryLabels.js.map +7 -0
  48. package/dist/modules/customers/lib/interactionCompatibility.js +1 -0
  49. package/dist/modules/customers/lib/interactionCompatibility.js.map +2 -2
  50. package/dist/modules/customers/translations.js +9 -0
  51. package/dist/modules/customers/translations.js.map +7 -0
  52. package/dist/modules/eudr/index.js +13 -0
  53. package/dist/modules/eudr/index.js.map +2 -2
  54. package/dist/modules/sales/commands/documents.js +3 -3
  55. package/dist/modules/sales/commands/documents.js.map +2 -2
  56. package/dist/modules/sales/components/documents/ItemsSection.js +75 -21
  57. package/dist/modules/sales/components/documents/ItemsSection.js.map +2 -2
  58. package/dist/modules/sales/components/documents/lineItemUtils.js +2 -2
  59. package/dist/modules/sales/components/documents/lineItemUtils.js.map +2 -2
  60. package/dist/modules/staff/api/timesheets/access-requests/route.js +11 -5
  61. package/dist/modules/staff/api/timesheets/access-requests/route.js.map +2 -2
  62. package/dist/modules/staff/api/timesheets/time-projects/route.js +19 -12
  63. package/dist/modules/staff/api/timesheets/time-projects/route.js.map +2 -2
  64. package/dist/modules/staff/backend/staff/time-tracking/projects/[id]/edit/page.js +21 -12
  65. package/dist/modules/staff/backend/staff/time-tracking/projects/[id]/edit/page.js.map +2 -2
  66. package/dist/modules/staff/backend/staff/time-tracking/projects/[id]/page.js +14 -9
  67. package/dist/modules/staff/backend/staff/time-tracking/projects/[id]/page.js.map +2 -2
  68. package/dist/modules/staff/lib/time-tracking-ui/NoProjectAccess.js +31 -10
  69. package/dist/modules/staff/lib/time-tracking-ui/NoProjectAccess.js.map +2 -2
  70. package/dist/modules/staff/lib/time-tracking-ui/projectAccessScope.js +64 -0
  71. package/dist/modules/staff/lib/time-tracking-ui/projectAccessScope.js.map +7 -0
  72. package/dist/modules/staff/lib/time-tracking-ui/projectAccessScopeHeaders.js +13 -0
  73. package/dist/modules/staff/lib/time-tracking-ui/projectAccessScopeHeaders.js.map +7 -0
  74. package/dist/modules/sync_excel/index.js +11 -1
  75. package/dist/modules/sync_excel/index.js.map +2 -2
  76. package/dist/modules/translations/di.js +2 -0
  77. package/dist/modules/translations/di.js.map +2 -2
  78. package/package.json +7 -7
  79. package/src/modules/cart/api/current/lines/bulk/route.ts +1 -1
  80. package/src/modules/cart/api/current/lines/route.ts +1 -1
  81. package/src/modules/cart/commands/lines.ts +5 -10
  82. package/src/modules/cart/i18n/de.json +1 -0
  83. package/src/modules/cart/i18n/en.json +1 -0
  84. package/src/modules/cart/i18n/es.json +1 -0
  85. package/src/modules/cart/i18n/ko.json +1 -0
  86. package/src/modules/cart/i18n/pl.json +1 -0
  87. package/src/modules/cart/lib/currentCartRoute.ts +8 -0
  88. package/src/modules/cart/lib/lineMutationLock.ts +59 -0
  89. package/src/modules/customer_accounts/api/admin/roles.ts +26 -2
  90. package/src/modules/customer_accounts/api/admin/users.ts +26 -7
  91. package/src/modules/customer_accounts/backend/customer_accounts/users/PortalUsersPageClient.tsx +96 -13
  92. package/src/modules/customer_accounts/backend/customer_accounts/users/page.tsx +9 -1
  93. package/src/modules/customer_accounts/data/validators.ts +1 -0
  94. package/src/modules/customer_accounts/i18n/de.json +10 -0
  95. package/src/modules/customer_accounts/i18n/en.json +10 -0
  96. package/src/modules/customer_accounts/i18n/es.json +10 -0
  97. package/src/modules/customer_accounts/i18n/ko.json +10 -0
  98. package/src/modules/customer_accounts/i18n/pl.json +10 -0
  99. package/src/modules/customer_accounts/lib/adminOrganizationScope.ts +71 -0
  100. package/src/modules/customers/api/customer-dictionary-entries/route.ts +82 -0
  101. package/src/modules/customers/api/dictionaries/[kind]/route.ts +29 -6
  102. package/src/modules/customers/cli.ts +23 -124
  103. package/src/modules/customers/components/DictionarySettings.tsx +1 -1
  104. package/src/modules/customers/components/detail/ManageTagsDialog.tsx +1 -1
  105. package/src/modules/customers/components/detail/TaskDialog.tsx +15 -1
  106. package/src/modules/customers/components/detail/TaskForm.tsx +1 -17
  107. package/src/modules/customers/components/detail/TasksSection.tsx +44 -14
  108. package/src/modules/customers/components/detail/hooks/useCustomerDictionary.ts +14 -8
  109. package/src/modules/customers/components/detail/hooks/useInteractions.ts +3 -4
  110. package/src/modules/customers/i18n/de.json +81 -0
  111. package/src/modules/customers/i18n/en.json +81 -0
  112. package/src/modules/customers/i18n/es.json +81 -0
  113. package/src/modules/customers/i18n/ko.json +81 -0
  114. package/src/modules/customers/i18n/pl.json +81 -0
  115. package/src/modules/customers/lib/dictionaryDefaults.ts +137 -0
  116. package/src/modules/customers/lib/dictionaryLabels.ts +73 -0
  117. package/src/modules/customers/lib/interactionCompatibility.ts +1 -0
  118. package/src/modules/customers/translations.ts +5 -0
  119. package/src/modules/eudr/index.ts +13 -0
  120. package/src/modules/sales/commands/documents.ts +3 -3
  121. package/src/modules/sales/components/documents/ItemsSection.tsx +82 -23
  122. package/src/modules/sales/components/documents/lineItemUtils.ts +2 -2
  123. package/src/modules/sales/i18n/de.json +1 -0
  124. package/src/modules/sales/i18n/en.json +1 -0
  125. package/src/modules/sales/i18n/es.json +1 -0
  126. package/src/modules/sales/i18n/ko.json +1 -0
  127. package/src/modules/sales/i18n/pl.json +1 -0
  128. package/src/modules/staff/api/timesheets/access-requests/route.ts +13 -14
  129. package/src/modules/staff/api/timesheets/time-projects/route.ts +22 -13
  130. package/src/modules/staff/backend/staff/time-tracking/projects/[id]/edit/page.tsx +25 -14
  131. package/src/modules/staff/backend/staff/time-tracking/projects/[id]/page.tsx +14 -13
  132. package/src/modules/staff/lib/time-tracking-ui/NoProjectAccess.tsx +30 -8
  133. package/src/modules/staff/lib/time-tracking-ui/projectAccessScope.ts +102 -0
  134. package/src/modules/staff/lib/time-tracking-ui/projectAccessScopeHeaders.ts +15 -0
  135. package/src/modules/sync_excel/index.ts +10 -0
  136. package/src/modules/translations/di.ts +2 -0
@@ -0,0 +1,86 @@
1
+ import { NextResponse } from "next/server";
2
+ import { z } from "zod";
3
+ import { findWithDecryption } from "@open-mercato/shared/lib/encryption/find";
4
+ import { escapeLikePattern } from "@open-mercato/shared/lib/db/escapeLikePattern";
5
+ import { isCrudHttpError } from "@open-mercato/shared/lib/crud/errors";
6
+ import { resolveTranslations } from "@open-mercato/shared/lib/i18n/server";
7
+ import { CustomerDictionaryEntry } from "../../data/entities.js";
8
+ import { resolveDictionaryRouteContext } from "../dictionaries/context.js";
9
+ import { createPagedListResponseSchema } from "../openapi.js";
10
+ const querySchema = z.object({
11
+ page: z.coerce.number().int().min(1).default(1),
12
+ pageSize: z.coerce.number().int().min(1).max(100).default(20),
13
+ search: z.string().trim().max(150).optional(),
14
+ id: z.string().uuid().optional()
15
+ });
16
+ const metadata = {
17
+ GET: { requireAuth: true, requireFeatures: ["customers.settings.manage", "translations.view"] }
18
+ };
19
+ async function GET(req) {
20
+ try {
21
+ const url = new URL(req.url);
22
+ const query = querySchema.parse({
23
+ page: url.searchParams.get("page") ?? void 0,
24
+ pageSize: url.searchParams.get("pageSize") ?? void 0,
25
+ search: url.searchParams.get("search") ?? void 0,
26
+ id: url.searchParams.get("id") ?? void 0
27
+ });
28
+ const { em, tenantId, organizationId, translate } = await resolveDictionaryRouteContext(req);
29
+ if (!organizationId) {
30
+ return NextResponse.json({ error: translate("customers.errors.organization_required", "Organization context is required") }, { status: 400 });
31
+ }
32
+ const where = {
33
+ tenantId,
34
+ organizationId,
35
+ ...query.id ? { id: query.id } : {},
36
+ ...query.search ? { label: { $ilike: `%${escapeLikePattern(query.search)}%` } } : {}
37
+ };
38
+ const total = await em.count(CustomerDictionaryEntry, where);
39
+ const entries = await findWithDecryption(em, CustomerDictionaryEntry, where, {
40
+ orderBy: { kind: "asc", label: "asc", id: "asc" },
41
+ limit: query.pageSize,
42
+ offset: (query.page - 1) * query.pageSize
43
+ }, { tenantId, organizationId });
44
+ return NextResponse.json({
45
+ items: entries.map(({ id, kind, value, label, updatedAt }) => ({ id, kind, value, label, updatedAt })),
46
+ total,
47
+ page: query.page,
48
+ pageSize: query.pageSize,
49
+ totalPages: Math.ceil(total / query.pageSize)
50
+ });
51
+ } catch (error) {
52
+ if (isCrudHttpError(error)) return NextResponse.json(error.body, { status: error.status });
53
+ if (error instanceof z.ZodError) {
54
+ const { translate } = await resolveTranslations();
55
+ return NextResponse.json({ error: translate("customers.errors.invalid_query", "Invalid query parameters") }, { status: 400 });
56
+ }
57
+ throw error;
58
+ }
59
+ }
60
+ const openApi = {
61
+ tag: "Customers",
62
+ summary: "Customer dictionary translation records",
63
+ methods: {
64
+ GET: {
65
+ summary: "List base labels for translation management",
66
+ query: querySchema,
67
+ responses: [{
68
+ status: 200,
69
+ description: "Dictionary entries in the selected organization with their stored base labels",
70
+ schema: createPagedListResponseSchema(z.object({
71
+ id: z.string().uuid(),
72
+ kind: z.string(),
73
+ value: z.string(),
74
+ label: z.string(),
75
+ updatedAt: z.string()
76
+ }))
77
+ }]
78
+ }
79
+ }
80
+ };
81
+ export {
82
+ GET,
83
+ metadata,
84
+ openApi
85
+ };
86
+ //# sourceMappingURL=route.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../../../src/modules/customers/api/customer-dictionary-entries/route.ts"],
4
+ "sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport type { FilterQuery } from '@mikro-orm/core'\nimport type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport { findWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { escapeLikePattern } from '@open-mercato/shared/lib/db/escapeLikePattern'\nimport { isCrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport { CustomerDictionaryEntry } from '../../data/entities'\nimport { resolveDictionaryRouteContext } from '../dictionaries/context'\nimport { createPagedListResponseSchema } from '../openapi'\n\nconst querySchema = z.object({\n page: z.coerce.number().int().min(1).default(1),\n pageSize: z.coerce.number().int().min(1).max(100).default(20),\n search: z.string().trim().max(150).optional(),\n id: z.string().uuid().optional(),\n})\n\nexport const metadata = {\n GET: { requireAuth: true, requireFeatures: ['customers.settings.manage', 'translations.view'] },\n}\n\nexport async function GET(req: Request) {\n try {\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 id: url.searchParams.get('id') ?? undefined,\n })\n const { em, tenantId, organizationId, translate } = await resolveDictionaryRouteContext(req)\n if (!organizationId) {\n return NextResponse.json({ error: translate('customers.errors.organization_required', 'Organization context is required') }, { status: 400 })\n }\n const where: FilterQuery<CustomerDictionaryEntry> = {\n tenantId,\n organizationId,\n ...(query.id ? { id: query.id } : {}),\n ...(query.search ? { label: { $ilike: `%${escapeLikePattern(query.search)}%` } } : {}),\n }\n const total = await em.count(CustomerDictionaryEntry, where)\n const entries = await findWithDecryption(em, CustomerDictionaryEntry, where, {\n orderBy: { kind: 'asc', label: 'asc', id: 'asc' },\n limit: query.pageSize,\n offset: (query.page - 1) * query.pageSize,\n }, { tenantId, organizationId })\n return NextResponse.json({\n items: entries.map(({ id, kind, value, label, updatedAt }) => ({ id, kind, value, label, updatedAt })),\n total,\n page: query.page,\n pageSize: query.pageSize,\n totalPages: Math.ceil(total / query.pageSize),\n })\n } catch (error) {\n if (isCrudHttpError(error)) return NextResponse.json(error.body, { status: error.status })\n if (error instanceof z.ZodError) {\n const { translate } = await resolveTranslations()\n return NextResponse.json({ error: translate('customers.errors.invalid_query', 'Invalid query parameters') }, { status: 400 })\n }\n throw error\n }\n}\n\nexport const openApi: OpenApiRouteDoc = {\n tag: 'Customers',\n summary: 'Customer dictionary translation records',\n methods: {\n GET: {\n summary: 'List base labels for translation management',\n query: querySchema,\n responses: [{\n status: 200,\n description: 'Dictionary entries in the selected organization with their stored base labels',\n schema: createPagedListResponseSchema(z.object({\n id: z.string().uuid(), kind: z.string(), value: z.string(), label: z.string(), updatedAt: z.string(),\n })),\n }],\n },\n },\n}\n"],
5
+ "mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAGlB,SAAS,0BAA0B;AACnC,SAAS,yBAAyB;AAClC,SAAS,uBAAuB;AAChC,SAAS,2BAA2B;AACpC,SAAS,+BAA+B;AACxC,SAAS,qCAAqC;AAC9C,SAAS,qCAAqC;AAE9C,MAAM,cAAc,EAAE,OAAO;AAAA,EAC3B,MAAM,EAAE,OAAO,OAAO,EAAE,IAAI,EAAE,IAAI,CAAC,EAAE,QAAQ,CAAC;AAAA,EAC9C,UAAU,EAAE,OAAO,OAAO,EAAE,IAAI,EAAE,IAAI,CAAC,EAAE,IAAI,GAAG,EAAE,QAAQ,EAAE;AAAA,EAC5D,QAAQ,EAAE,OAAO,EA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Ae,CAAC;AAC/B,WAAO,aAAa,KAAK;AAAA,MACvB,OAAO,QAAQ,IAAI,CAAC,EAAE,IAAI,MAAM,OAAO,OAAO,UAAU,OAAO,EAAE,IAAI,MAAM,OAAO,OAAO,UAAU,EAAE;AAAA,MACrG;AAAA,MACA,MAAM,MAAM;AAAA,MACZ,UAAU,MAAM;AAAA,MAChB,YAAY,KAAK,KAAK,QAAQ,MAAM,QAAQ;AAAA,IAC9C,CAAC;AAAA,EACH,SAAS,OAAO;AACd,QAAI,gBAAgB,KAAK,EAAG,QAAO,aAAa,KAAK,MAAM,MAAM,EAAE,QAAQ,MAAM,OAAO,CAAC;AACzF,QAAI,iBAAiB,EAAE,UAAU;AAC/B,YAAM,EAAE,UAAU,IAAI,MAAM,oBAAoB;AAChD,aAAO,aAAa,KAAK,EAAE,OAAO,UAAU,kCAAkC,0BAA0B,EAAE,GAAG,EAAE,QAAQ,IAAI,CAAC;AAAA,IAC9H;AACA,UAAM;AAAA,EACR;AACF;AAEO,MAAM,UAA2B;AAAA,EACtC,KAAK;AAAA,EACL,SAAS;AAAA,EACT,SAAS;AAAA,IACP,KAAK;AAAA,MACH,SAAS;AAAA,MACT,OAAO;AAAA,MACP,WAAW,CAAC;AAAA,QACV,QAAQ;AAAA,QACR,aAAa;AAAA,QACb,QAAQ,8BAA8B,EAAE,OAAO;AAAA,UAC7C,IAAI,EAAE,OAAO,EAAE,KAAK;AAAA,UAAG,MAAM,EAAE,OAAO;AAAA,UAAG,OAAO,EAAE,OAAO;AAAA,UAAG,OAAO,EAAE,OAAO;AAAA,UAAG,WAAW,EAAE,OAAO;AAAA,QACrG,CAAC,CAAC;AAAA,MACJ,CAAC;AAAA,IACH;AAAA,EACF;AACF;",
6
+ "names": []
7
+ }
@@ -21,6 +21,8 @@ import { readJsonSafe } from "@open-mercato/shared/lib/http/readJsonSafe";
21
21
  import { createLogger } from "@open-mercato/shared/lib/logger";
22
22
  import { CUSTOMER_DICTIONARY_ORGANIZATION_REQUIRED_CODE } from "../../../lib/dictionaries.js";
23
23
  import { getCommandInterceptorHttpRejection } from "@open-mercato/shared/lib/commands/errors";
24
+ import { getTranslationOverlayPlugin } from "@open-mercato/shared/lib/localization/overlay-plugin";
25
+ import { localizeCustomerDictionaryEntries } from "../../../lib/dictionaryLabels.js";
24
26
  import { calendarEventTypeBehaviorSchema } from "../../../calendar-event-types.js";
25
27
  const logger = createLogger("customers");
26
28
  const colorSchema = z.string().trim().regex(/^#([0-9A-Fa-f]{6})$/, "Invalid color hex");
@@ -33,7 +35,10 @@ const postSchema = z.object({
33
35
  behavior: calendarEventTypeBehaviorSchema.nullable().optional()
34
36
  });
35
37
  const querySchema = z.object({
36
- organizationId: z.string().uuid().optional()
38
+ organizationId: z.string().uuid().optional(),
39
+ labels: z.enum(["localized", "base"]).optional().describe(
40
+ "Label projection. `localized` (default) resolves labels for the request locale; `base` returns the stored labels that management screens edit."
41
+ )
37
42
  });
38
43
  const metadata = {
39
44
  GET: { requireAuth: true, requireFeatures: ["customers.people.view"] },
@@ -43,12 +48,25 @@ async function GET(req, ctx) {
43
48
  try {
44
49
  const url = new URL(req.url);
45
50
  const query = querySchema.parse({
46
- organizationId: url.searchParams.get("organizationId") ?? void 0
51
+ organizationId: url.searchParams.get("organizationId") ?? void 0,
52
+ labels: url.searchParams.get("labels") ?? void 0
47
53
  });
48
54
  const { translate, em, organizationId, readableOrganizationIds, tenantId, cache, container } = await resolveDictionaryRouteContext(req, {
49
55
  selectedId: query.organizationId ?? void 0
50
56
  });
51
57
  const { kind, mappedKind } = mapDictionaryKind(ctx.params?.kind);
58
+ const localizeResponse = async (body) => {
59
+ if (query.labels === "base") return body;
60
+ const { resolveLocale } = getTranslationOverlayPlugin();
61
+ const locale = resolveLocale?.(req) ?? (await resolveTranslations()).locale ?? "en";
62
+ return {
63
+ ...body,
64
+ items: sortDictionaryEntries(
65
+ await localizeCustomerDictionaryEntries(body.items, { kind: mappedKind, locale, tenantId, container }),
66
+ resolveDictionaryEntrySortMode(body.sortMode)
67
+ )
68
+ };
69
+ };
52
70
  if (!organizationId) {
53
71
  throw new CrudHttpError(400, {
54
72
  error: translate("customers.errors.organization_required", "Organization context is required"),
@@ -76,9 +94,9 @@ async function GET(req, ctx) {
76
94
  sortMode,
77
95
  readableOrganizationIds: scopedOrganizationIds
78
96
  });
79
- const cached = await cache.get(cacheKey);
80
- if (cached) {
81
- return NextResponse.json(cached);
97
+ const cached = dictionaryCacheResponseSchema.safeParse(await cache.get(cacheKey));
98
+ if (cached.success) {
99
+ return NextResponse.json(await localizeResponse(cached.data));
82
100
  }
83
101
  }
84
102
  const entries = await findWithDecryption(
@@ -148,7 +166,7 @@ async function GET(req, ctx) {
148
166
  logger.warn("Failed to set cache entry", { component: "dictionaries.cache", err });
149
167
  }
150
168
  }
151
- return NextResponse.json(responseBody);
169
+ return NextResponse.json(await localizeResponse(responseBody));
152
170
  } catch (err) {
153
171
  if (isCrudHttpError(err)) {
154
172
  return NextResponse.json(err.body, { status: err.status });
@@ -275,6 +293,9 @@ const dictionaryListResponseSchema = z.object({
275
293
  sortMode: z.string().optional(),
276
294
  items: z.array(dictionaryEntrySchema)
277
295
  });
296
+ const dictionaryCacheResponseSchema = dictionaryListResponseSchema.extend({
297
+ items: z.array(dictionaryEntrySchema.extend({ label: z.string(), organizationId: z.string() }).passthrough())
298
+ });
278
299
  const dictionaryErrorSchema = z.object({
279
300
  error: z.string(),
280
301
  code: z.string().optional()
@@ -285,7 +306,8 @@ const openApi = {
285
306
  methods: {
286
307
  GET: {
287
308
  summary: "List dictionary entries",
288
- description: "Returns dictionary entries for the requested kind within the currently selected organization.",
309
+ description: "Returns dictionary entries for the requested kind within the currently selected organization. Labels are localized for the request locale unless `labels=base` is passed.",
310
+ query: querySchema,
289
311
  responses: [
290
312
  { status: 200, description: "Dictionary entries", schema: dictionaryListResponseSchema },
291
313
  { status: 401, description: "Unauthorized", schema: dictionaryErrorSchema },
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../../src/modules/customers/api/dictionaries/%5Bkind%5D/route.ts"],
4
- "sourcesContent": ["import { NextResponse } from 'next/server'\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 type { CommandExecuteResult } from '@open-mercato/shared/lib/commands/types'\nimport { serializeOperationMetadata } from '@open-mercato/shared/lib/commands/operationMetadata'\nimport { CustomerDictionaryEntry } from '../../../data/entities'\nimport { mapDictionaryKind, resolveDictionaryActorId, resolveDictionaryRouteContext } from '../context'\nimport { createDictionaryCacheKey, createDictionaryCacheTags, invalidateDictionaryCache, DICTIONARY_CACHE_TTL_MS } from '../cache'\nimport { loadCustomerSettings } from '../../../commands/settings'\nimport {\n resolveDictionaryEntrySortMode,\n sortDictionaryEntries,\n} from '@open-mercato/core/modules/dictionaries/lib/entrySort'\nimport { z } from 'zod'\nimport type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport { loadRoleTypeUsageMap, resolveRoleTypeUsageKey } from '../../../lib/roleTypeUsage'\nimport {\n runCrudMutationGuardAfterSuccess,\n validateCrudMutationGuard,\n} from '@open-mercato/shared/lib/crud/mutation-guard'\nimport { findWithDecryption, findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { readJsonSafe } from '@open-mercato/shared/lib/http/readJsonSafe'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\nimport { CUSTOMER_DICTIONARY_ORGANIZATION_REQUIRED_CODE } from '../../../lib/dictionaries'\nimport { getCommandInterceptorHttpRejection } from '@open-mercato/shared/lib/commands/errors'\nimport { calendarEventTypeBehaviorSchema } from '../../../calendar-event-types'\nimport type { OrganizationHierarchyService } from '@open-mercato/shared/lib/auth/principal-service'\n\nconst logger = createLogger('customers')\n\nconst colorSchema = z.string().trim().regex(/^#([0-9A-Fa-f]{6})$/, 'Invalid color hex')\nconst iconSchema = z.string().trim().min(1).max(48)\n\nconst postSchema = z.object({\n value: z.string().trim().min(1).max(150),\n label: z.string().trim().max(150).optional(),\n color: colorSchema.or(z.null()).optional(),\n icon: iconSchema.or(z.null()).optional(),\n behavior: calendarEventTypeBehaviorSchema.nullable().optional(),\n})\n\nconst querySchema = z.object({\n organizationId: z.string().uuid().optional(),\n})\n\nexport const metadata = {\n GET: { requireAuth: true, requireFeatures: ['customers.people.view'] },\n POST: { requireAuth: true, requireFeatures: ['customers.settings.manage'] },\n}\n\nexport async function GET(req: Request, ctx: { params?: { kind?: string } }) {\n try {\n const url = new URL(req.url)\n const query = querySchema.parse({\n organizationId: url.searchParams.get('organizationId') ?? undefined,\n })\n const { translate, em, organizationId, readableOrganizationIds, tenantId, cache, container } = await resolveDictionaryRouteContext(req, {\n selectedId: query.organizationId ?? undefined,\n })\n const { kind, mappedKind } = mapDictionaryKind(ctx.params?.kind)\n if (!organizationId) {\n throw new CrudHttpError(400, {\n error: translate('customers.errors.organization_required', 'Organization context is required'),\n code: CUSTOMER_DICTIONARY_ORGANIZATION_REQUIRED_CODE,\n })\n }\n const settings = await loadCustomerSettings(em, { tenantId, organizationId })\n const sortMode = resolveDictionaryEntrySortMode(settings?.dictionarySortModes?.[kind])\n let scopedOrganizationIds = readableOrganizationIds.length > 0 ? readableOrganizationIds : [organizationId]\n if (mappedKind === 'activity_type') {\n const hierarchy = container.resolve('organizationHierarchyService') as OrganizationHierarchyService\n const ancestors = await hierarchy.resolveAncestorIds({ tenantId, organizationId })\n if (ancestors === null) {\n throw new CrudHttpError(403, { error: translate('customers.errors.organization_forbidden', 'Organization not accessible') })\n }\n scopedOrganizationIds = Array.from(new Set([organizationId, ...ancestors.slice().reverse()]))\n }\n const canUseCache = Boolean(cache) && mappedKind !== 'person_company_role'\n\n let cacheKey: string | null = null\n if (canUseCache && cache) {\n cacheKey = createDictionaryCacheKey({\n tenantId,\n organizationId,\n mappedKind,\n sortMode,\n readableOrganizationIds: scopedOrganizationIds,\n })\n const cached = await cache.get(cacheKey)\n if (cached) {\n return NextResponse.json(cached)\n }\n }\n\n const entries = await findWithDecryption(\n em,\n CustomerDictionaryEntry,\n { tenantId, kind: mappedKind, organizationId: { $in: scopedOrganizationIds } } as any,\n { orderBy: { label: 'asc' } },\n { tenantId, organizationId },\n )\n\n const inheritedPriority = new Map(scopedOrganizationIds.map((id, index) => [id, index]))\n const sortByLabel = (left: CustomerDictionaryEntry, right: CustomerDictionaryEntry) =>\n left.label.localeCompare(right.label, undefined, { sensitivity: 'base' })\n\n const localEntries = entries\n .filter((entry) => entry.organizationId === organizationId)\n .sort(sortByLabel)\n const inheritedEntries = entries\n .filter((entry) => entry.organizationId !== organizationId)\n .sort((left, right) => {\n const leftPriority = inheritedPriority.get(left.organizationId) ?? Number.MAX_SAFE_INTEGER\n const rightPriority = inheritedPriority.get(right.organizationId) ?? Number.MAX_SAFE_INTEGER\n if (leftPriority !== rightPriority) return leftPriority - rightPriority\n return sortByLabel(left, right)\n })\n\n const preferredEntries = new Map<string, CustomerDictionaryEntry>()\n for (const entry of [...localEntries, ...inheritedEntries]) {\n const normalizedValue = entry.normalizedValue?.trim() || entry.value.trim().toLowerCase()\n if (!normalizedValue || preferredEntries.has(normalizedValue)) continue\n preferredEntries.set(normalizedValue, entry)\n }\n\n const preferredEntryList = Array.from(preferredEntries.values())\n const usageByEntryKey =\n mappedKind === 'person_company_role'\n ? await loadRoleTypeUsageMap(em, {\n tenantId,\n entries: preferredEntryList.map((entry) => ({\n organizationId: entry.organizationId,\n value: entry.value,\n })),\n })\n : new Map()\n\n const items = sortDictionaryEntries(\n preferredEntryList\n .map((entry) => ({\n id: entry.id,\n value: entry.value,\n label: entry.label,\n color: entry.color,\n icon: entry.icon,\n ...(mappedKind === 'activity_type' ? { behavior: entry.activityTypeBehavior ?? null } : {}),\n organizationId: entry.organizationId,\n isInherited: entry.organizationId !== organizationId,\n createdAt: entry.createdAt,\n updatedAt: entry.updatedAt,\n ...(mappedKind === 'person_company_role'\n ? {\n usageCount:\n usageByEntryKey.get(resolveRoleTypeUsageKey(entry.organizationId, entry.value))?.total ?? 0,\n }\n : {}),\n })),\n sortMode,\n )\n\n const responseBody = {\n sortMode,\n items,\n }\n\n if (canUseCache && cache && cacheKey) {\n const tags = createDictionaryCacheTags({\n tenantId,\n mappedKind,\n organizationIds: scopedOrganizationIds,\n })\n try {\n await cache.set(cacheKey, responseBody, {\n ttl: DICTIONARY_CACHE_TTL_MS,\n tags,\n })\n } catch (err) {\n logger.warn('Failed to set cache entry', { component: 'dictionaries.cache', err })\n }\n }\n\n return NextResponse.json(responseBody)\n } catch (err) {\n if (isCrudHttpError(err)) {\n return NextResponse.json(err.body, { status: err.status })\n }\n const { translate } = await resolveTranslations()\n logger.error('customers.dictionaries.list failed', { err })\n return NextResponse.json({ error: translate('customers.errors.lookup_failed', 'Failed to load dictionary entries') }, { status: 400 })\n }\n}\n\nexport async function POST(req: Request, ctx: { params?: { kind?: string } }) {\n try {\n const context = await resolveDictionaryRouteContext(req)\n if (!context.organizationId) {\n throw new CrudHttpError(400, { error: context.translate('customers.errors.organization_required', 'Organization context is required') })\n }\n const { mappedKind } = mapDictionaryKind(ctx.params?.kind)\n const body = postSchema.parse(await readJsonSafe(req, {}))\n const guardUserId = resolveDictionaryActorId(context.auth)\n const guardResult = await validateCrudMutationGuard(context.container, {\n tenantId: context.tenantId,\n organizationId: context.organizationId,\n userId: guardUserId,\n resourceKind: 'customers.dictionary_entry',\n resourceId: '',\n operation: 'create',\n requestMethod: req.method,\n requestHeaders: req.headers,\n mutationPayload: body,\n })\n if (guardResult && !guardResult.ok) {\n return NextResponse.json(guardResult.body, { status: guardResult.status })\n }\n const commandBus = (context.container.resolve('commandBus') as CommandBus)\n const { result, logEntry } =\n (await commandBus.execute('customers.dictionaryEntries.create', {\n input: {\n tenantId: context.tenantId,\n organizationId: context.organizationId,\n kind: mappedKind,\n value: body.value,\n label: body.label,\n color: body.color,\n icon: body.icon,\n behavior: body.behavior,\n },\n ctx: context.ctx,\n })) as CommandExecuteResult<{ entryId: string; mode: 'created' | 'updated' | 'unchanged' }>\n const entry = await findOneWithDecryption(context.em.fork(), CustomerDictionaryEntry, result.entryId, {}, { tenantId: context.tenantId, organizationId: context.organizationId })\n if (!entry) {\n throw new CrudHttpError(400, { error: context.translate('customers.errors.lookup_failed', 'Failed to save dictionary entry') })\n }\n\n await invalidateDictionaryCache(context.cache, {\n tenantId: context.tenantId,\n mappedKind,\n organizationIds: [entry.organizationId],\n })\n\n if (guardResult?.ok && guardResult.shouldRunAfterSuccess) {\n await runCrudMutationGuardAfterSuccess(context.container, {\n tenantId: context.tenantId,\n organizationId: context.organizationId,\n userId: guardUserId,\n resourceKind: 'customers.dictionary_entry',\n resourceId: entry.id,\n operation: 'create',\n requestMethod: req.method,\n requestHeaders: req.headers,\n metadata: guardResult.metadata ?? null,\n })\n }\n\n const response = NextResponse.json(\n {\n id: entry.id,\n value: entry.value,\n label: entry.label,\n color: entry.color,\n icon: entry.icon,\n ...(mappedKind === 'activity_type' ? { behavior: entry.activityTypeBehavior ?? null } : {}),\n organizationId: entry.organizationId,\n isInherited: false,\n updatedAt: entry.updatedAt,\n },\n { status: result.mode === 'created' ? 201 : 200 }\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 return response\n } catch (err) {\n if (isCrudHttpError(err)) {\n return NextResponse.json(err.body, { status: err.status })\n }\n const interceptorRejection = getCommandInterceptorHttpRejection(err)\n if (interceptorRejection) {\n return NextResponse.json(interceptorRejection.body, { status: interceptorRejection.status })\n }\n const { translate } = await resolveTranslations()\n logger.error('customers.dictionaries.create failed', { err })\n return NextResponse.json({ error: translate('customers.errors.lookup_failed', 'Failed to save 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 behavior: calendarEventTypeBehaviorSchema.nullable().optional(),\n organizationId: z.string().uuid().nullable().optional(),\n isInherited: z.boolean().optional(),\n createdAt: z.date().or(z.string()).optional(),\n updatedAt: z.date().or(z.string()).optional(),\n})\n\nconst dictionaryListResponseSchema = z.object({\n sortMode: z.string().optional(),\n items: z.array(dictionaryEntrySchema),\n})\n\nconst dictionaryErrorSchema = z.object({\n error: z.string(),\n code: z.string().optional(),\n})\n\nexport const openApi: OpenApiRouteDoc = {\n tag: 'Customers',\n summary: 'Customer dictionary entries',\n methods: {\n GET: {\n summary: 'List dictionary entries',\n description: 'Returns dictionary entries for the requested kind within the currently selected organization.',\n responses: [\n { status: 200, description: 'Dictionary entries', schema: dictionaryListResponseSchema },\n { status: 401, description: 'Unauthorized', schema: dictionaryErrorSchema },\n { status: 400, description: 'Failed to resolve dictionary context', schema: dictionaryErrorSchema },\n ],\n },\n POST: {\n summary: 'Create or override dictionary entry',\n description: 'Creates a dictionary entry (or updates the existing entry for the same value) within the current organization scope.',\n requestBody: {\n contentType: 'application/json',\n schema: postSchema,\n },\n responses: [\n { status: 201, description: 'Dictionary entry created', schema: dictionaryEntrySchema },\n { status: 200, description: 'Dictionary entry updated', schema: dictionaryEntrySchema },\n ],\n errors: [\n { status: 400, description: 'Invalid payload', schema: dictionaryErrorSchema },\n { status: 401, description: 'Unauthorized', schema: dictionaryErrorSchema },\n { status: 409, description: 'Duplicate value conflict', schema: dictionaryErrorSchema },\n ],\n },\n },\n}\n"],
5
- "mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,2BAA2B;AACpC,SAAS,eAAe,uBAAuB;AAG/C,SAAS,kCAAkC;AAC3C,SAAS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F;",
4
+ "sourcesContent": ["import { NextResponse } from 'next/server'\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 type { CommandExecuteResult } from '@open-mercato/shared/lib/commands/types'\nimport { serializeOperationMetadata } from '@open-mercato/shared/lib/commands/operationMetadata'\nimport { CustomerDictionaryEntry } from '../../../data/entities'\nimport { mapDictionaryKind, resolveDictionaryActorId, resolveDictionaryRouteContext } from '../context'\nimport { createDictionaryCacheKey, createDictionaryCacheTags, invalidateDictionaryCache, DICTIONARY_CACHE_TTL_MS } from '../cache'\nimport { loadCustomerSettings } from '../../../commands/settings'\nimport {\n resolveDictionaryEntrySortMode,\n sortDictionaryEntries,\n} from '@open-mercato/core/modules/dictionaries/lib/entrySort'\nimport { z } from 'zod'\nimport type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport { loadRoleTypeUsageMap, resolveRoleTypeUsageKey } from '../../../lib/roleTypeUsage'\nimport {\n runCrudMutationGuardAfterSuccess,\n validateCrudMutationGuard,\n} from '@open-mercato/shared/lib/crud/mutation-guard'\nimport { findWithDecryption, findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { readJsonSafe } from '@open-mercato/shared/lib/http/readJsonSafe'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\nimport { CUSTOMER_DICTIONARY_ORGANIZATION_REQUIRED_CODE } from '../../../lib/dictionaries'\nimport { getCommandInterceptorHttpRejection } from '@open-mercato/shared/lib/commands/errors'\nimport { getTranslationOverlayPlugin } from '@open-mercato/shared/lib/localization/overlay-plugin'\nimport { localizeCustomerDictionaryEntries } from '../../../lib/dictionaryLabels'\nimport { calendarEventTypeBehaviorSchema } from '../../../calendar-event-types'\nimport type { OrganizationHierarchyService } from '@open-mercato/shared/lib/auth/principal-service'\n\nconst logger = createLogger('customers')\n\nconst colorSchema = z.string().trim().regex(/^#([0-9A-Fa-f]{6})$/, 'Invalid color hex')\nconst iconSchema = z.string().trim().min(1).max(48)\n\nconst postSchema = z.object({\n value: z.string().trim().min(1).max(150),\n label: z.string().trim().max(150).optional(),\n color: colorSchema.or(z.null()).optional(),\n icon: iconSchema.or(z.null()).optional(),\n behavior: calendarEventTypeBehaviorSchema.nullable().optional(),\n})\n\nconst querySchema = z.object({\n organizationId: z.string().uuid().optional(),\n labels: z.enum(['localized', 'base']).optional().describe(\n 'Label projection. `localized` (default) resolves labels for the request locale; `base` returns the stored labels that management screens edit.',\n ),\n})\n\nexport const metadata = {\n GET: { requireAuth: true, requireFeatures: ['customers.people.view'] },\n POST: { requireAuth: true, requireFeatures: ['customers.settings.manage'] },\n}\n\nexport async function GET(req: Request, ctx: { params?: { kind?: string } }) {\n try {\n const url = new URL(req.url)\n const query = querySchema.parse({\n organizationId: url.searchParams.get('organizationId') ?? undefined,\n labels: url.searchParams.get('labels') ?? undefined,\n })\n const { translate, em, organizationId, readableOrganizationIds, tenantId, cache, container } = await resolveDictionaryRouteContext(req, {\n selectedId: query.organizationId ?? undefined,\n })\n const { kind, mappedKind } = mapDictionaryKind(ctx.params?.kind)\n const localizeResponse = async (body: z.infer<typeof dictionaryCacheResponseSchema>) => {\n if (query.labels === 'base') return body\n const { resolveLocale } = getTranslationOverlayPlugin()\n const locale = resolveLocale?.(req) ?? (await resolveTranslations()).locale ?? 'en'\n return {\n ...body,\n items: sortDictionaryEntries(\n await localizeCustomerDictionaryEntries(body.items, { kind: mappedKind, locale, tenantId, container }),\n resolveDictionaryEntrySortMode(body.sortMode),\n ),\n }\n }\n if (!organizationId) {\n throw new CrudHttpError(400, {\n error: translate('customers.errors.organization_required', 'Organization context is required'),\n code: CUSTOMER_DICTIONARY_ORGANIZATION_REQUIRED_CODE,\n })\n }\n const settings = await loadCustomerSettings(em, { tenantId, organizationId })\n const sortMode = resolveDictionaryEntrySortMode(settings?.dictionarySortModes?.[kind])\n let scopedOrganizationIds = readableOrganizationIds.length > 0 ? readableOrganizationIds : [organizationId]\n if (mappedKind === 'activity_type') {\n const hierarchy = container.resolve('organizationHierarchyService') as OrganizationHierarchyService\n const ancestors = await hierarchy.resolveAncestorIds({ tenantId, organizationId })\n if (ancestors === null) {\n throw new CrudHttpError(403, { error: translate('customers.errors.organization_forbidden', 'Organization not accessible') })\n }\n scopedOrganizationIds = Array.from(new Set([organizationId, ...ancestors.slice().reverse()]))\n }\n const canUseCache = Boolean(cache) && mappedKind !== 'person_company_role'\n\n let cacheKey: string | null = null\n if (canUseCache && cache) {\n cacheKey = createDictionaryCacheKey({\n tenantId,\n organizationId,\n mappedKind,\n sortMode,\n readableOrganizationIds: scopedOrganizationIds,\n })\n const cached = dictionaryCacheResponseSchema.safeParse(await cache.get(cacheKey))\n if (cached.success) {\n return NextResponse.json(await localizeResponse(cached.data))\n }\n }\n\n const entries = await findWithDecryption(\n em,\n CustomerDictionaryEntry,\n { tenantId, kind: mappedKind, organizationId: { $in: scopedOrganizationIds } },\n { orderBy: { label: 'asc' } },\n { tenantId, organizationId },\n )\n\n const inheritedPriority = new Map(scopedOrganizationIds.map((id, index) => [id, index]))\n const sortByLabel = (left: CustomerDictionaryEntry, right: CustomerDictionaryEntry) =>\n left.label.localeCompare(right.label, undefined, { sensitivity: 'base' })\n\n const localEntries = entries\n .filter((entry) => entry.organizationId === organizationId)\n .sort(sortByLabel)\n const inheritedEntries = entries\n .filter((entry) => entry.organizationId !== organizationId)\n .sort((left, right) => {\n const leftPriority = inheritedPriority.get(left.organizationId) ?? Number.MAX_SAFE_INTEGER\n const rightPriority = inheritedPriority.get(right.organizationId) ?? Number.MAX_SAFE_INTEGER\n if (leftPriority !== rightPriority) return leftPriority - rightPriority\n return sortByLabel(left, right)\n })\n\n const preferredEntries = new Map<string, CustomerDictionaryEntry>()\n for (const entry of [...localEntries, ...inheritedEntries]) {\n const normalizedValue = entry.normalizedValue?.trim() || entry.value.trim().toLowerCase()\n if (!normalizedValue || preferredEntries.has(normalizedValue)) continue\n preferredEntries.set(normalizedValue, entry)\n }\n\n const preferredEntryList = Array.from(preferredEntries.values())\n const usageByEntryKey =\n mappedKind === 'person_company_role'\n ? await loadRoleTypeUsageMap(em, {\n tenantId,\n entries: preferredEntryList.map((entry) => ({\n organizationId: entry.organizationId,\n value: entry.value,\n })),\n })\n : new Map()\n\n const items = sortDictionaryEntries(\n preferredEntryList\n .map((entry) => ({\n id: entry.id,\n value: entry.value,\n label: entry.label,\n color: entry.color,\n icon: entry.icon,\n ...(mappedKind === 'activity_type' ? { behavior: entry.activityTypeBehavior ?? null } : {}),\n organizationId: entry.organizationId,\n isInherited: entry.organizationId !== organizationId,\n createdAt: entry.createdAt,\n updatedAt: entry.updatedAt,\n ...(mappedKind === 'person_company_role'\n ? {\n usageCount:\n usageByEntryKey.get(resolveRoleTypeUsageKey(entry.organizationId, entry.value))?.total ?? 0,\n }\n : {}),\n })),\n sortMode,\n )\n\n const responseBody = {\n sortMode,\n items,\n }\n\n if (canUseCache && cache && cacheKey) {\n const tags = createDictionaryCacheTags({\n tenantId,\n mappedKind,\n organizationIds: scopedOrganizationIds,\n })\n try {\n await cache.set(cacheKey, responseBody, {\n ttl: DICTIONARY_CACHE_TTL_MS,\n tags,\n })\n } catch (err) {\n logger.warn('Failed to set cache entry', { component: 'dictionaries.cache', err })\n }\n }\n\n return NextResponse.json(await localizeResponse(responseBody))\n } catch (err) {\n if (isCrudHttpError(err)) {\n return NextResponse.json(err.body, { status: err.status })\n }\n const { translate } = await resolveTranslations()\n logger.error('customers.dictionaries.list failed', { err })\n return NextResponse.json({ error: translate('customers.errors.lookup_failed', 'Failed to load dictionary entries') }, { status: 400 })\n }\n}\n\nexport async function POST(req: Request, ctx: { params?: { kind?: string } }) {\n try {\n const context = await resolveDictionaryRouteContext(req)\n if (!context.organizationId) {\n throw new CrudHttpError(400, { error: context.translate('customers.errors.organization_required', 'Organization context is required') })\n }\n const { mappedKind } = mapDictionaryKind(ctx.params?.kind)\n const body = postSchema.parse(await readJsonSafe(req, {}))\n const guardUserId = resolveDictionaryActorId(context.auth)\n const guardResult = await validateCrudMutationGuard(context.container, {\n tenantId: context.tenantId,\n organizationId: context.organizationId,\n userId: guardUserId,\n resourceKind: 'customers.dictionary_entry',\n resourceId: '',\n operation: 'create',\n requestMethod: req.method,\n requestHeaders: req.headers,\n mutationPayload: body,\n })\n if (guardResult && !guardResult.ok) {\n return NextResponse.json(guardResult.body, { status: guardResult.status })\n }\n const commandBus = (context.container.resolve('commandBus') as CommandBus)\n const { result, logEntry } =\n (await commandBus.execute('customers.dictionaryEntries.create', {\n input: {\n tenantId: context.tenantId,\n organizationId: context.organizationId,\n kind: mappedKind,\n value: body.value,\n label: body.label,\n color: body.color,\n icon: body.icon,\n behavior: body.behavior,\n },\n ctx: context.ctx,\n })) as CommandExecuteResult<{ entryId: string; mode: 'created' | 'updated' | 'unchanged' }>\n const entry = await findOneWithDecryption(context.em.fork(), CustomerDictionaryEntry, result.entryId, {}, { tenantId: context.tenantId, organizationId: context.organizationId })\n if (!entry) {\n throw new CrudHttpError(400, { error: context.translate('customers.errors.lookup_failed', 'Failed to save dictionary entry') })\n }\n\n await invalidateDictionaryCache(context.cache, {\n tenantId: context.tenantId,\n mappedKind,\n organizationIds: [entry.organizationId],\n })\n\n if (guardResult?.ok && guardResult.shouldRunAfterSuccess) {\n await runCrudMutationGuardAfterSuccess(context.container, {\n tenantId: context.tenantId,\n organizationId: context.organizationId,\n userId: guardUserId,\n resourceKind: 'customers.dictionary_entry',\n resourceId: entry.id,\n operation: 'create',\n requestMethod: req.method,\n requestHeaders: req.headers,\n metadata: guardResult.metadata ?? null,\n })\n }\n\n const response = NextResponse.json(\n {\n id: entry.id,\n value: entry.value,\n label: entry.label,\n color: entry.color,\n icon: entry.icon,\n ...(mappedKind === 'activity_type' ? { behavior: entry.activityTypeBehavior ?? null } : {}),\n organizationId: entry.organizationId,\n isInherited: false,\n updatedAt: entry.updatedAt,\n },\n { status: result.mode === 'created' ? 201 : 200 }\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 return response\n } catch (err) {\n if (isCrudHttpError(err)) {\n return NextResponse.json(err.body, { status: err.status })\n }\n const interceptorRejection = getCommandInterceptorHttpRejection(err)\n if (interceptorRejection) {\n return NextResponse.json(interceptorRejection.body, { status: interceptorRejection.status })\n }\n const { translate } = await resolveTranslations()\n logger.error('customers.dictionaries.create failed', { err })\n return NextResponse.json({ error: translate('customers.errors.lookup_failed', 'Failed to save 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 behavior: calendarEventTypeBehaviorSchema.nullable().optional(),\n organizationId: z.string().uuid().nullable().optional(),\n isInherited: z.boolean().optional(),\n createdAt: z.date().or(z.string()).optional(),\n updatedAt: z.date().or(z.string()).optional(),\n})\n\nconst dictionaryListResponseSchema = z.object({\n sortMode: z.string().optional(),\n items: z.array(dictionaryEntrySchema),\n})\n\nconst dictionaryCacheResponseSchema = dictionaryListResponseSchema.extend({\n items: z.array(dictionaryEntrySchema.extend({ label: z.string(), organizationId: z.string() }).passthrough()),\n})\n\nconst dictionaryErrorSchema = z.object({\n error: z.string(),\n code: z.string().optional(),\n})\n\nexport const openApi: OpenApiRouteDoc = {\n tag: 'Customers',\n summary: 'Customer dictionary entries',\n methods: {\n GET: {\n summary: 'List dictionary entries',\n description: 'Returns dictionary entries for the requested kind within the currently selected organization. Labels are localized for the request locale unless `labels=base` is passed.',\n query: querySchema,\n responses: [\n { status: 200, description: 'Dictionary entries', schema: dictionaryListResponseSchema },\n { status: 401, description: 'Unauthorized', schema: dictionaryErrorSchema },\n { status: 400, description: 'Failed to resolve dictionary context', schema: dictionaryErrorSchema },\n ],\n },\n POST: {\n summary: 'Create or override dictionary entry',\n description: 'Creates a dictionary entry (or updates the existing entry for the same value) within the current organization scope.',\n requestBody: {\n contentType: 'application/json',\n schema: postSchema,\n },\n responses: [\n { status: 201, description: 'Dictionary entry created', schema: dictionaryEntrySchema },\n { status: 200, description: 'Dictionary entry updated', schema: dictionaryEntrySchema },\n ],\n errors: [\n { status: 400, description: 'Invalid payload', schema: dictionaryErrorSchema },\n { status: 401, description: 'Unauthorized', schema: dictionaryErrorSchema },\n { status: 409, description: 'Duplicate value conflict', schema: dictionaryErrorSchema },\n ],\n },\n },\n}\n"],
5
+ "mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,2BAA2B;AACpC,SAAS,eAAe,uBAAuB;AAG/C,SAAS,kCAAkC;AAC3C,SAAS,+BAA+B;AACxC,SAAS,mBAAmB,0BAA0B,qCAAqC;AAC3F,SAAS,0BAA0B,2BAA2B,2BAA2B,+BAA+B;AACxH,SAAS,4BAA4B;AACrC;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP,SAAS,SAAS;AAElB,SAAS,sBAAsB,+BAA+B;AAC9D;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP,SAAS,oBAAoB,6BAA6B;AAC1D,SAAS,oBAAoB;AAC7B,SAAS,oBAAoB;AAC7B,SAAS,sDAAsD;AAC/D,SAAS,0CAA0C;AACnD,SAAS,mCAAmC;AAC5C,SAAS,yCAAyC;AAClD,SAAS,uCAAuC;AAGhD,MAAM,SAAS,aAAa,WAAW;AAEvC,MAAM,cAAc,EAAE,OAAO,EAAE,KAAK,EAAE,MAAM,uBAAuB,mBAAmB;AACtF,MAAM,aAAa,EAAE,OAAO,EAAE,KAAK,EAAE,IAAI,CAAC,EAAE,IAAI,EAAE;AAElD,MA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AA,QACN,EAAE,QAAQ,KAAK,aAAa,mBAAmB,QAAQ,sBAAsB;AAAA,QAC7E,EAAE,QAAQ,KAAK,aAAa,gBAAgB,QAAQ,sBAAsB;AAAA,QAC1E,EAAE,QAAQ,KAAK,aAAa,4BAA4B,QAAQ,sBAAsB;AAAA,MACxF;AAAA,IACF;AAAA,EACF;AACF;",
6
6
  "names": []
7
7
  }
@@ -32,102 +32,28 @@ import {
32
32
  CUSTOMER_INTERACTION_TODO_ADAPTER_SOURCE
33
33
  } from "./lib/interactionCompatibility.js";
34
34
  import { CUSTOMER_CUSTOM_FIELD_SETS } from "./customFieldDefaults.js";
35
- const DEAL_STATUS_DEFAULTS = [
36
- { value: "open", label: "Open", color: "#2563eb", icon: "lucide:circle" },
37
- { value: "closed", label: "Closed", color: "#6b7280", icon: "lucide:check-circle" },
38
- { value: "win", label: "Win", color: "#22c55e", icon: "lucide:trophy" },
39
- { value: "lost", label: "Lost", color: "#ef4444", icon: "lucide:flag" },
40
- { value: "in_progress", label: "In progress", color: "#f59e0b", icon: "lucide:activity" }
41
- ];
42
- const PIPELINE_STAGE_DEFAULTS = [
43
- { value: "opportunity", label: "Opportunity", color: "#38bdf8", icon: "lucide:target" },
44
- { value: "marketing_qualified_lead", label: "Marketing Qualified Lead", color: "#a855f7", icon: "lucide:sparkles" },
45
- { value: "sales_qualified_lead", label: "Sales Qualified Lead", color: "#f97316", icon: "lucide:users" },
46
- { value: "offering", label: "Offering", color: "#22c55e", icon: "lucide:package" },
47
- { value: "negotiations", label: "Negotiations", color: "#facc15", icon: "lucide:handshake" },
48
- { value: "win", label: "Win", color: "#16a34a", icon: "lucide:award" },
49
- { value: "lost", label: "Lost", color: "#ef4444", icon: "lucide:flag" },
50
- { value: "stalled", label: "Stalled", color: "#6b7280", icon: "lucide:alert-circle" }
51
- ];
52
- const ENTITY_STATUS_DEFAULTS = [
53
- { value: "active", label: "Active", color: "#22c55e", icon: "lucide:user-check" },
54
- { value: "inactive", label: "Inactive", color: "#94a3b8", icon: "lucide:pause-circle" },
55
- { value: "pending", label: "Pending", color: "#f59e0b", icon: "lucide:clock" },
56
- { value: "archived", label: "Archived", color: "#64748b", icon: "lucide:archive" }
57
- ];
58
- const ENTITY_LIFECYCLE_STAGE_DEFAULTS = [
59
- { value: "lead", label: "Lead", color: "#3b82f6", icon: "lucide:sparkles" },
60
- { value: "prospect", label: "Prospect", color: "#8b5cf6", icon: "lucide:eye" },
61
- { value: "customer", label: "Customer", color: "#22c55e", icon: "lucide:handshake" },
62
- { value: "subscriber", label: "Subscriber", color: "#10b981", icon: "lucide:bell" },
63
- { value: "churned", label: "Churned", color: "#ef4444", icon: "lucide:user-x" },
64
- { value: "other", label: "Other", color: "#94a3b8", icon: "lucide:circle" }
65
- ];
66
- const ENTITY_SOURCE_DEFAULTS = [
67
- { value: "linkedin", label: "LinkedIn", color: "#0a66c2", icon: "lucide:linkedin" },
68
- { value: "email", label: "Email", color: "#3b82f6", icon: "lucide:mail" },
69
- { value: "web_form", label: "Web form", color: "#22c55e", icon: "lucide:globe" },
70
- { value: "referral", label: "Referral", color: "#8b5cf6", icon: "lucide:users" },
71
- { value: "customer_referral", label: "Customer referral", color: "#22c55e", icon: "lucide:thumbs-up" },
72
- { value: "partner_referral", label: "Partner referral", color: "#3b82f6", icon: "lucide:handshake" },
73
- { value: "event", label: "Conference / Event", color: "#f59e0b", icon: "lucide:calendar" },
74
- { value: "cold_outreach", label: "Cold outreach", color: "#94a3b8", icon: "lucide:phone" },
75
- { value: "facebook", label: "Facebook", color: "#1877f2", icon: "lucide:facebook" },
76
- { value: "typeform", label: "Typeform", color: "#262627", icon: "lucide:file-text" },
77
- { value: "other", label: "Other", color: "#64748b", icon: "lucide:circle" }
78
- ];
79
- const ADDRESS_TYPE_DEFAULTS = [
80
- { value: "office", label: "Office", color: "#3b82f6", icon: "lucide:building" },
81
- { value: "work", label: "Work", color: "#6366f1", icon: "lucide:briefcase" },
82
- { value: "billing", label: "Billing", color: "#f97316", icon: "lucide:wallet" },
83
- { value: "shipping", label: "Shipping", color: "#22c55e", icon: "lucide:truck" },
84
- { value: "home", label: "Home", color: "#10b981", icon: "lucide:map-pin" }
85
- ];
86
- const ACTIVITY_TYPE_DEFAULTS = [
87
- { value: "call", label: "Call", color: "#2563eb", icon: "lucide:phone-call" },
88
- { value: "email", label: "Email", color: "#16a34a", icon: "lucide:mail" },
89
- { value: "event", label: "Event", color: "#6366f1", icon: "lucide:calendar" },
90
- { value: "meeting", label: "Meeting", color: "#f59e0b", icon: "lucide:users" },
91
- { value: "note", label: "Note", color: "#a855f7", icon: "lucide:notebook" },
92
- { value: "task", label: "Task", color: "#ef4444", icon: "lucide:check-square" }
93
- ];
94
- const INTERACTION_STATUS_DEFAULTS = [
95
- { value: "planned", label: "Planned", color: "#2563eb", icon: "lucide:circle" },
96
- { value: "in_progress", label: "In progress", color: "#f59e0b", icon: "lucide:activity" },
97
- { value: "waiting", label: "Waiting / blocked", color: "#a855f7", icon: "lucide:pause-circle" },
98
- { value: "done", label: "Done", color: "#22c55e", icon: "lucide:check-circle" },
99
- { value: "canceled", label: "Canceled", color: "#6b7280", icon: "lucide:x-circle" }
100
- ];
101
- const JOB_TITLE_DEFAULTS = [
102
- { value: "Director of Operations", label: "Director of Operations", color: "#f97316", icon: "lucide:settings" },
103
- { value: "VP of Partnerships", label: "VP of Partnerships", color: "#6366f1", icon: "lucide:users" },
104
- { value: "Founder & Principal", label: "Founder & Principal", color: "#ec4899", icon: "lucide:star" },
105
- { value: "Senior Project Manager", label: "Senior Project Manager", color: "#0ea5e9", icon: "lucide:clipboard-list" },
106
- { value: "Chief Revenue Officer", label: "Chief Revenue Officer", color: "#8b5cf6", icon: "lucide:bar-chart-3" },
107
- { value: "Director of Retail Partnerships", label: "Director of Retail Partnerships", color: "#f59e0b", icon: "lucide:shopping-bag" }
108
- ];
109
- const INDUSTRY_DEFAULTS = [
110
- { value: "Renewable Energy", label: "Renewable Energy" },
111
- { value: "Software", label: "Software" },
112
- { value: "Interior Design", label: "Interior Design" },
113
- { value: "SaaS", label: "SaaS" },
114
- { value: "E-commerce", label: "E-commerce" },
115
- { value: "Healthcare", label: "Healthcare" },
116
- { value: "Manufacturing", label: "Manufacturing" },
117
- { value: "Logistics", label: "Logistics" },
118
- { value: "Financial Services", label: "Financial Services" },
119
- { value: "Retail", label: "Retail" },
120
- { value: "Hospitality", label: "Hospitality" },
121
- { value: "Energy", label: "Energy" },
122
- { value: "Media", label: "Media" }
123
- ];
124
- const TEMPERATURE_DEFAULTS = [
125
- { value: "hot", label: "Hot", color: "#ef4444", icon: "lucide:flame" },
126
- { value: "high", label: "High", color: "#f59e0b", icon: "lucide:trending-up" },
127
- { value: "medium", label: "Medium", color: "#8b5cf6", icon: "lucide:sparkles" },
128
- { value: "low", label: "Low", color: "#64748b", icon: "lucide:clock" },
129
- { value: "cold", label: "Cold", color: "#94a3b8", icon: "lucide:snowflake" }
130
- ];
35
+ import {
36
+ ENTITY_STATUS_DEFAULTS,
37
+ ENTITY_SOURCE_DEFAULTS,
38
+ ENTITY_LIFECYCLE_STAGE_DEFAULTS,
39
+ ADDRESS_TYPE_DEFAULTS,
40
+ ACTIVITY_TYPE_DEFAULTS,
41
+ INTERACTION_STATUS_DEFAULTS,
42
+ JOB_TITLE_DEFAULTS,
43
+ DEAL_STATUS_DEFAULTS,
44
+ PIPELINE_STAGE_DEFAULTS,
45
+ INDUSTRY_DEFAULTS,
46
+ TEMPERATURE_DEFAULTS,
47
+ PERSON_COMPANY_ROLE_DEFAULTS
48
+ } from "./lib/dictionaryDefaults.js";
49
+ import {
50
+ DEAL_STATUS_DEFAULTS as DEAL_STATUS_DEFAULTS2,
51
+ PIPELINE_STAGE_DEFAULTS as PIPELINE_STAGE_DEFAULTS2,
52
+ ENTITY_STATUS_DEFAULTS as ENTITY_STATUS_DEFAULTS2,
53
+ ENTITY_LIFECYCLE_STAGE_DEFAULTS as ENTITY_LIFECYCLE_STAGE_DEFAULTS2,
54
+ ENTITY_SOURCE_DEFAULTS as ENTITY_SOURCE_DEFAULTS2,
55
+ INTERACTION_STATUS_DEFAULTS as INTERACTION_STATUS_DEFAULTS2
56
+ } from "./lib/dictionaryDefaults.js";
131
57
  const CUSTOM_TAG_SEED_DEFAULTS = [
132
58
  { value: "architecture", label: "architecture" },
133
59
  { value: "hospitality", label: "hospitality" },
@@ -144,14 +70,6 @@ const CUSTOM_TAG_SEED_DEFAULTS = [
144
70
  { value: "reference-customer", label: "reference-customer" },
145
71
  { value: "case-study-candidate", label: "case-study-candidate" }
146
72
  ];
147
- const PERSON_COMPANY_ROLE_DEFAULTS = [
148
- { value: "decision_maker", label: "Decision maker", color: "#f59e0b", icon: "lucide:crown" },
149
- { value: "influencer", label: "Influencer", color: "#8b5cf6", icon: "lucide:sparkles" },
150
- { value: "budget_holder", label: "Budget holder", color: "#3b82f6", icon: "lucide:wallet" },
151
- { value: "technical_evaluator", label: "Technical evaluator", color: "#22c55e", icon: "lucide:wrench" },
152
- { value: "primary_contact", label: "Primary contact", color: "#0ea5e9", icon: "lucide:star" },
153
- { value: "end_user", label: "End user", color: "#64748b", icon: "lucide:user" }
154
- ];
155
73
  const PRIORITY_CURRENCIES = ["EUR", "USD", "GBP", "PLN"];
156
74
  const NOW = /* @__PURE__ */ new Date();
157
75
  function isoDaysFromNow(days, options) {
@@ -2684,12 +2602,12 @@ async function ensureCustomerCustomFieldDefinitions(em, tenantId) {
2684
2602
  }
2685
2603
  export {
2686
2604
  CUSTOMER_EXAMPLES,
2687
- DEAL_STATUS_DEFAULTS,
2688
- ENTITY_LIFECYCLE_STAGE_DEFAULTS,
2689
- ENTITY_SOURCE_DEFAULTS,
2690
- ENTITY_STATUS_DEFAULTS,
2691
- INTERACTION_STATUS_DEFAULTS,
2692
- PIPELINE_STAGE_DEFAULTS,
2605
+ DEAL_STATUS_DEFAULTS2 as DEAL_STATUS_DEFAULTS,
2606
+ ENTITY_LIFECYCLE_STAGE_DEFAULTS2 as ENTITY_LIFECYCLE_STAGE_DEFAULTS,
2607
+ ENTITY_SOURCE_DEFAULTS2 as ENTITY_SOURCE_DEFAULTS,
2608
+ ENTITY_STATUS_DEFAULTS2 as ENTITY_STATUS_DEFAULTS,
2609
+ INTERACTION_STATUS_DEFAULTS2 as INTERACTION_STATUS_DEFAULTS,
2610
+ PIPELINE_STAGE_DEFAULTS2 as PIPELINE_STAGE_DEFAULTS,
2693
2611
  cli_default as default,
2694
2612
  ensureCustomerCustomFieldDefinitions,
2695
2613
  seedCurrencyDictionary,