@open-mercato/core 0.6.7-develop.6726.1.983ae8a07e → 0.6.7-develop.6744.1.0483b18565

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 (147) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/dist/generated/entities/resources_resource/index.js +2 -0
  3. package/dist/generated/entities/resources_resource/index.js.map +2 -2
  4. package/dist/generated/entity-fields-registry.js +1 -0
  5. package/dist/generated/entity-fields-registry.js.map +2 -2
  6. package/dist/helpers/integration/salesFixtures.js +31 -2
  7. package/dist/helpers/integration/salesFixtures.js.map +2 -2
  8. package/dist/helpers/integration/salesUi.js +5 -0
  9. package/dist/helpers/integration/salesUi.js.map +2 -2
  10. package/dist/modules/communication_channels/data/enrichers.js +4 -4
  11. package/dist/modules/communication_channels/data/enrichers.js.map +2 -2
  12. package/dist/modules/customers/analytics.js +1 -0
  13. package/dist/modules/customers/analytics.js.map +2 -2
  14. package/dist/modules/customers/components/detail/DealForm.js +2 -1
  15. package/dist/modules/customers/components/detail/DealForm.js.map +2 -2
  16. package/dist/modules/customers/components/detail/DealsSection.js +1 -1
  17. package/dist/modules/customers/components/detail/DealsSection.js.map +2 -2
  18. package/dist/modules/customers/data/validators.js +3 -1
  19. package/dist/modules/customers/data/validators.js.map +2 -2
  20. package/dist/modules/dashboards/widgets/dashboard/pipeline-summary/config.js +52 -2
  21. package/dist/modules/dashboards/widgets/dashboard/pipeline-summary/config.js.map +2 -2
  22. package/dist/modules/dashboards/widgets/dashboard/pipeline-summary/widget.client.js +42 -26
  23. package/dist/modules/dashboards/widgets/dashboard/pipeline-summary/widget.client.js.map +2 -2
  24. package/dist/modules/dashboards/widgets/dashboard/pipeline-summary/widget.js +2 -2
  25. package/dist/modules/dashboards/widgets/dashboard/pipeline-summary/widget.js.map +2 -2
  26. package/dist/modules/dictionaries/api/[dictionaryId]/entries/route.js +34 -12
  27. package/dist/modules/dictionaries/api/[dictionaryId]/entries/route.js.map +2 -2
  28. package/dist/modules/dictionaries/api/openapi.js +15 -2
  29. package/dist/modules/dictionaries/api/openapi.js.map +2 -2
  30. package/dist/modules/dictionaries/components/hooks/useDictionaryEntries.js +30 -29
  31. package/dist/modules/dictionaries/components/hooks/useDictionaryEntries.js.map +2 -2
  32. package/dist/modules/dictionaries/data/validators.js +7 -0
  33. package/dist/modules/dictionaries/data/validators.js.map +2 -2
  34. package/dist/modules/dictionaries/lib/clientEntries.js +4 -3
  35. package/dist/modules/dictionaries/lib/clientEntries.js.map +2 -2
  36. package/dist/modules/dictionaries/lib/fetchAllEntries.js +43 -0
  37. package/dist/modules/dictionaries/lib/fetchAllEntries.js.map +7 -0
  38. package/dist/modules/entities/api/definitions.js +51 -3
  39. package/dist/modules/entities/api/definitions.js.map +2 -2
  40. package/dist/modules/entities/api/entities.js +21 -2
  41. package/dist/modules/entities/api/entities.js.map +2 -2
  42. package/dist/modules/entities/api/records.js +3 -24
  43. package/dist/modules/entities/api/records.js.map +2 -2
  44. package/dist/modules/entities/api/sidebar-entities.js +34 -12
  45. package/dist/modules/entities/api/sidebar-entities.js.map +2 -2
  46. package/dist/modules/entities/lib/entityAcl.js +46 -0
  47. package/dist/modules/entities/lib/entityAcl.js.map +2 -2
  48. package/dist/modules/messages/api/route.js +2 -5
  49. package/dist/modules/messages/api/route.js.map +2 -2
  50. package/dist/modules/messages/lib/participantScope.js +15 -0
  51. package/dist/modules/messages/lib/participantScope.js.map +7 -0
  52. package/dist/modules/planner/components/unavailabilityReasons.js +3 -3
  53. package/dist/modules/planner/components/unavailabilityReasons.js.map +2 -2
  54. package/dist/modules/progress/lib/progressService.js +2 -0
  55. package/dist/modules/progress/lib/progressService.js.map +2 -2
  56. package/dist/modules/progress/lib/progressServiceImpl.js +322 -104
  57. package/dist/modules/progress/lib/progressServiceImpl.js.map +2 -2
  58. package/dist/modules/resources/api/resources.js +2 -0
  59. package/dist/modules/resources/api/resources.js.map +2 -2
  60. package/dist/modules/resources/backend/resources/resources/[id]/page.js +3 -2
  61. package/dist/modules/resources/backend/resources/resources/[id]/page.js.map +2 -2
  62. package/dist/modules/resources/commands/resources.js +9 -0
  63. package/dist/modules/resources/commands/resources.js.map +2 -2
  64. package/dist/modules/resources/components/detail/dictionaries.js +3 -3
  65. package/dist/modules/resources/components/detail/dictionaries.js.map +2 -2
  66. package/dist/modules/resources/data/entities.js +3 -0
  67. package/dist/modules/resources/data/entities.js.map +2 -2
  68. package/dist/modules/resources/data/validators.js +6 -2
  69. package/dist/modules/resources/data/validators.js.map +2 -2
  70. package/dist/modules/resources/lib/seeds.js +16 -9
  71. package/dist/modules/resources/lib/seeds.js.map +2 -2
  72. package/dist/modules/resources/migrations/Migration20260608231000.js +13 -0
  73. package/dist/modules/resources/migrations/Migration20260608231000.js.map +7 -0
  74. package/dist/modules/sales/backend/sales/documents/create/page.js +11 -14
  75. package/dist/modules/sales/backend/sales/documents/create/page.js.map +2 -2
  76. package/dist/modules/sales/commands/documents.js +8 -0
  77. package/dist/modules/sales/commands/documents.js.map +2 -2
  78. package/dist/modules/sales/components/documents/ItemsSection.js +18 -9
  79. package/dist/modules/sales/components/documents/ItemsSection.js.map +2 -2
  80. package/dist/modules/sales/components/documents/LineItemDialog.js +12 -5
  81. package/dist/modules/sales/components/documents/LineItemDialog.js.map +2 -2
  82. package/dist/modules/sales/components/documents/SalesDocumentForm.js +48 -2
  83. package/dist/modules/sales/components/documents/SalesDocumentForm.js.map +2 -2
  84. package/dist/modules/sales/components/documents/SalesOrderDraftLines.js +167 -0
  85. package/dist/modules/sales/components/documents/SalesOrderDraftLines.js.map +7 -0
  86. package/dist/modules/sales/data/validators.js +5 -1
  87. package/dist/modules/sales/data/validators.js.map +2 -2
  88. package/dist/modules/staff/components/detail/dictionaries.js +3 -3
  89. package/dist/modules/staff/components/detail/dictionaries.js.map +2 -2
  90. package/dist/modules/workflows/widgets/injection/order-approval/widget.client.js +11 -4
  91. package/dist/modules/workflows/widgets/injection/order-approval/widget.client.js.map +2 -2
  92. package/generated/entities/resources_resource/index.ts +1 -0
  93. package/generated/entity-fields-registry.ts +1 -0
  94. package/package.json +7 -7
  95. package/src/helpers/integration/salesFixtures.ts +34 -2
  96. package/src/helpers/integration/salesUi.ts +8 -0
  97. package/src/modules/communication_channels/data/enrichers.ts +6 -26
  98. package/src/modules/customers/analytics.ts +1 -0
  99. package/src/modules/customers/components/detail/DealForm.tsx +5 -1
  100. package/src/modules/customers/components/detail/DealsSection.tsx +1 -1
  101. package/src/modules/customers/data/validators.ts +5 -1
  102. package/src/modules/dashboards/i18n/de.json +3 -0
  103. package/src/modules/dashboards/i18n/en.json +3 -0
  104. package/src/modules/dashboards/i18n/es.json +3 -0
  105. package/src/modules/dashboards/i18n/pl.json +3 -0
  106. package/src/modules/dashboards/widgets/dashboard/pipeline-summary/config.ts +86 -0
  107. package/src/modules/dashboards/widgets/dashboard/pipeline-summary/widget.client.tsx +33 -18
  108. package/src/modules/dashboards/widgets/dashboard/pipeline-summary/widget.ts +2 -2
  109. package/src/modules/dictionaries/api/[dictionaryId]/entries/route.ts +39 -11
  110. package/src/modules/dictionaries/api/openapi.ts +19 -0
  111. package/src/modules/dictionaries/components/hooks/useDictionaryEntries.ts +35 -36
  112. package/src/modules/dictionaries/data/validators.ts +14 -0
  113. package/src/modules/dictionaries/lib/clientEntries.ts +4 -3
  114. package/src/modules/dictionaries/lib/fetchAllEntries.ts +72 -0
  115. package/src/modules/entities/api/definitions.ts +51 -3
  116. package/src/modules/entities/api/entities.ts +30 -2
  117. package/src/modules/entities/api/records.ts +3 -27
  118. package/src/modules/entities/api/sidebar-entities.ts +43 -14
  119. package/src/modules/entities/lib/entityAcl.ts +58 -0
  120. package/src/modules/messages/api/route.ts +4 -5
  121. package/src/modules/messages/lib/participantScope.ts +64 -0
  122. package/src/modules/planner/components/unavailabilityReasons.ts +3 -3
  123. package/src/modules/progress/AGENTS.md +11 -1
  124. package/src/modules/progress/lib/progressService.ts +1 -0
  125. package/src/modules/progress/lib/progressServiceImpl.ts +385 -117
  126. package/src/modules/resources/api/resources.ts +2 -0
  127. package/src/modules/resources/backend/resources/resources/[id]/page.tsx +9 -3
  128. package/src/modules/resources/commands/resources.ts +10 -0
  129. package/src/modules/resources/components/detail/dictionaries.ts +3 -3
  130. package/src/modules/resources/data/entities.ts +3 -0
  131. package/src/modules/resources/data/validators.ts +5 -0
  132. package/src/modules/resources/lib/seeds.ts +16 -9
  133. package/src/modules/resources/migrations/.snapshot-open-mercato.json +17 -1
  134. package/src/modules/resources/migrations/Migration20260608231000.ts +13 -0
  135. package/src/modules/sales/backend/sales/documents/create/page.tsx +2 -4
  136. package/src/modules/sales/commands/documents.ts +8 -0
  137. package/src/modules/sales/components/documents/ItemsSection.tsx +19 -10
  138. package/src/modules/sales/components/documents/LineItemDialog.tsx +13 -5
  139. package/src/modules/sales/components/documents/SalesDocumentForm.tsx +48 -6
  140. package/src/modules/sales/components/documents/SalesOrderDraftLines.tsx +198 -0
  141. package/src/modules/sales/data/validators.ts +7 -1
  142. package/src/modules/sales/i18n/de.json +2 -0
  143. package/src/modules/sales/i18n/en.json +2 -0
  144. package/src/modules/sales/i18n/es.json +2 -0
  145. package/src/modules/sales/i18n/pl.json +2 -0
  146. package/src/modules/staff/components/detail/dictionaries.ts +3 -3
  147. package/src/modules/workflows/widgets/injection/order-approval/widget.client.tsx +12 -5
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../src/modules/dictionaries/components/hooks/useDictionaryEntries.ts"],
4
- "sourcesContent": ["\"use client\"\n\nimport { apiCall } from '@open-mercato/ui/backend/utils/apiCall'\nimport { useQuery, type QueryClient, type UseQueryResult } from '@tanstack/react-query'\nimport {\n createDictionaryMap,\n normalizeDictionaryEntries,\n type DictionaryDisplayEntry,\n type DictionaryMap,\n} from '../dictionaryAppearance'\n\nexport type DictionaryEntryRecord = DictionaryDisplayEntry & {\n id: string\n createdAt: string | null\n updatedAt: string | null\n}\n\nexport type DictionaryEntriesQueryData = {\n entries: DictionaryDisplayEntry[]\n map: DictionaryMap\n fullEntries: DictionaryEntryRecord[]\n}\n\nconst DICTIONARY_ENTRIES_STALE_TIME = 5 * 60 * 1000\n\nconst BASE_DICTIONARY_ENTRIES_KEY = ['dictionaries', 'entries'] as const\n\nexport const dictionaryEntriesQueryKey = (dictionaryId: string, scopeVersion = 0) =>\n [...BASE_DICTIONARY_ENTRIES_KEY, dictionaryId, `scope:${scopeVersion}`] as const\n\nexport const dictionaryEntriesQueryOptions = (dictionaryId: string, scopeVersion = 0) => ({\n queryKey: dictionaryEntriesQueryKey(dictionaryId, scopeVersion),\n staleTime: DICTIONARY_ENTRIES_STALE_TIME,\n gcTime: DICTIONARY_ENTRIES_STALE_TIME,\n queryFn: async (): Promise<DictionaryEntriesQueryData> => {\n const call = await apiCall<Record<string, unknown>>(`/api/dictionaries/${dictionaryId}/entries`)\n const payload = call.result ?? {}\n if (!call.ok) {\n const message =\n typeof payload.error === 'string'\n ? payload.error\n : 'Failed to load dictionary entries.'\n throw new Error(message)\n }\n const items = Array.isArray(payload.items) ? payload.items : []\n const parsed: DictionaryEntryRecord[] = []\n for (const item of items) {\n if (!item || typeof item !== 'object') continue\n const data = item as Record<string, unknown>\n const id = typeof data.id === 'string' ? data.id : ''\n const value = typeof data.value === 'string' ? data.value.trim() : ''\n if (!id || !value) continue\n const label =\n typeof data.label === 'string' && data.label.trim().length ? data.label.trim() : value\n const color =\n typeof data.color === 'string' && /^#([0-9a-fA-F]{6})$/.test(data.color)\n ? `#${data.color.slice(1).toLowerCase()}`\n : null\n const icon = typeof data.icon === 'string' && data.icon.trim().length ? data.icon.trim() : null\n const createdAt = typeof data.createdAt === 'string' ? data.createdAt : null\n const updatedAt = typeof data.updatedAt === 'string' ? data.updatedAt : null\n parsed.push({\n id,\n value,\n label,\n color,\n icon,\n createdAt,\n updatedAt,\n })\n }\n const normalized = normalizeDictionaryEntries(\n parsed.map(({ value, label, color, icon }) => ({ value, label, color, icon })),\n { sort: false },\n )\n return {\n entries: normalized,\n map: createDictionaryMap(normalized),\n fullEntries: parsed,\n }\n },\n})\n\nexport function useDictionaryEntries(\n dictionaryId: string,\n scopeVersion = 0,\n): UseQueryResult<DictionaryEntriesQueryData> {\n return useQuery(dictionaryEntriesQueryOptions(dictionaryId, scopeVersion))\n}\n\nexport async function invalidateDictionaryEntries(queryClient: QueryClient, dictionaryId: string) {\n await queryClient.invalidateQueries({ queryKey: [...BASE_DICTIONARY_ENTRIES_KEY, dictionaryId] })\n}\n\nexport async function ensureDictionaryEntries(\n queryClient: QueryClient,\n dictionaryId: string,\n scopeVersion = 0,\n): Promise<DictionaryEntriesQueryData> {\n return queryClient.ensureQueryData(dictionaryEntriesQueryOptions(dictionaryId, scopeVersion))\n}\n"],
5
- "mappings": ";AAEA,SAAS,eAAe;AACxB,SAAS,gBAAuD;AAChE;AAAA,EACE;AAAA,EACA;AAAA,OAGK;AAcP,MAAM,gCAAgC,IAAI,KAAK;AAE/C,MAAM,8BAA8B,CAAC,gBAAgB,SAAS;AAEvD,MAAM,4BAA4B,CAAC,cAAsB,eAAe,MAC7E,CAAC,GAAG,6BAA6B,cAAc,SAAS,YAAY,EAAE;AAEjE,MAAM,gCAAgC,CAAC,cAAsB,eAAe,OAAO;AAAA,EACxF,UAAU,0BAA0B,cAAc,YAAY;AAAA,EAC9D,WAAW;AAAA,EACX,QAAQ;AAAA,EACR,SAAS,YAAiD;AACxD,UAAM,OAAO,MAAM,QAAiC,qBAAqB,YAAY,UAAU;AAC/F,UAAM,UAAU,KAAK,UAAU,CAAC;AAChC,QAAI,CAAC,KAAK,IAAI;AACZ,YAAM,UACJ,OAAO,QAAQ,UAAU,WACrB,QAAQ,QACR;AACN,YAAM,IAAI,MAAM,OAAO;AAAA,IACzB;AACA,UAAM,QAAQ,MAAM,QAAQ,QAAQ,KAAK,IAAI,QAAQ,QAAQ,CAAC;AAC9D,UAAM,SAAkC,CAAC;AACzC,eAAW,QAAQ,OAAO;AACxB,UAAI,CA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A,eAAsB,wBACpB,aACA,cACA,eAAe,GACsB;AACrC,SAAO,YAAY,gBAAgB,8BAA8B,cAAc,YAAY,CAAC;AAC9F;",
4
+ "sourcesContent": ["\"use client\"\n\nimport { useQuery, type QueryClient, type UseQueryResult } from '@tanstack/react-query'\nimport {\n createDictionaryMap,\n normalizeDictionaryEntries,\n type DictionaryDisplayEntry,\n type DictionaryMap,\n} from '../dictionaryAppearance'\nimport { fetchAllDictionaryEntries } from '../../lib/fetchAllEntries'\n\nexport type DictionaryEntryRecord = DictionaryDisplayEntry & {\n id: string\n createdAt: string | null\n updatedAt: string | null\n}\n\nexport type DictionaryEntriesQueryData = {\n entries: DictionaryDisplayEntry[]\n map: DictionaryMap\n fullEntries: DictionaryEntryRecord[]\n}\n\nconst DICTIONARY_ENTRIES_STALE_TIME = 5 * 60 * 1000\n\nconst BASE_DICTIONARY_ENTRIES_KEY = ['dictionaries', 'entries'] as const\n\nexport const dictionaryEntriesQueryKey = (dictionaryId: string, scopeVersion = 0) =>\n [...BASE_DICTIONARY_ENTRIES_KEY, dictionaryId, `scope:${scopeVersion}`] as const\n\nfunction parseDictionaryEntryItems(items: unknown[]): DictionaryEntryRecord[] {\n const parsed: DictionaryEntryRecord[] = []\n for (const item of items) {\n if (!item || typeof item !== 'object') continue\n const data = item as Record<string, unknown>\n const id = typeof data.id === 'string' ? data.id : ''\n const value = typeof data.value === 'string' ? data.value.trim() : ''\n if (!id || !value) continue\n const label =\n typeof data.label === 'string' && data.label.trim().length ? data.label.trim() : value\n const color =\n typeof data.color === 'string' && /^#([0-9a-fA-F]{6})$/.test(data.color)\n ? `#${data.color.slice(1).toLowerCase()}`\n : null\n const icon = typeof data.icon === 'string' && data.icon.trim().length ? data.icon.trim() : null\n const createdAt = typeof data.createdAt === 'string' ? data.createdAt : null\n const updatedAt = typeof data.updatedAt === 'string' ? data.updatedAt : null\n parsed.push({\n id,\n value,\n label,\n color,\n icon,\n createdAt,\n updatedAt,\n })\n }\n return parsed\n}\n\nexport const dictionaryEntriesQueryOptions = (dictionaryId: string, scopeVersion = 0) => ({\n queryKey: dictionaryEntriesQueryKey(dictionaryId, scopeVersion),\n staleTime: DICTIONARY_ENTRIES_STALE_TIME,\n gcTime: DICTIONARY_ENTRIES_STALE_TIME,\n queryFn: async (): Promise<DictionaryEntriesQueryData> => {\n const pages = await fetchAllDictionaryEntries(dictionaryId)\n if (!pages.ok) {\n throw new Error(pages.errorMessage ?? 'Failed to load dictionary entries.')\n }\n const parsed = parseDictionaryEntryItems(pages.items)\n const normalized = normalizeDictionaryEntries(\n parsed.map(({ value, label, color, icon }) => ({ value, label, color, icon })),\n { sort: false },\n )\n return {\n entries: normalized,\n map: createDictionaryMap(normalized),\n fullEntries: parsed,\n }\n },\n})\n\nexport function useDictionaryEntries(\n dictionaryId: string,\n scopeVersion = 0,\n): UseQueryResult<DictionaryEntriesQueryData> {\n return useQuery(dictionaryEntriesQueryOptions(dictionaryId, scopeVersion))\n}\n\nexport async function invalidateDictionaryEntries(queryClient: QueryClient, dictionaryId: string) {\n await queryClient.invalidateQueries({ queryKey: [...BASE_DICTIONARY_ENTRIES_KEY, dictionaryId] })\n}\n\nexport async function ensureDictionaryEntries(\n queryClient: QueryClient,\n dictionaryId: string,\n scopeVersion = 0,\n): Promise<DictionaryEntriesQueryData> {\n return queryClient.ensureQueryData(dictionaryEntriesQueryOptions(dictionaryId, scopeVersion))\n}\n"],
5
+ "mappings": ";AAEA,SAAS,gBAAuD;AAChE;AAAA,EACE;AAAA,EACA;AAAA,OAGK;AACP,SAAS,iCAAiC;AAc1C,MAAM,gCAAgC,IAAI,KAAK;AAE/C,MAAM,8BAA8B,CAAC,gBAAgB,SAAS;AAEvD,MAAM,4BAA4B,CAAC,cAAsB,eAAe,MAC7E,CAAC,GAAG,6BAA6B,cAAc,SAAS,YAAY,EAAE;AAExE,SAAS,0BAA0B,OAA2C;AAC5E,QAAM,SAAkC,CAAC;AACzC,aAAW,QAAQ,OAAO;AACxB,QAAI,CAAC,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AAA,IAChB;AACA,WAAO;AAAA,MACL,SAAS;AAAA,MACT,KAAK,oBAAoB,UAAU;AAAA,MACnC,aAAa;AAAA,IACf;AAAA,EACF;AACF;AAEO,SAAS,qBACd,cACA,eAAe,GAC6B;AAC5C,SAAO,SAAS,8BAA8B,cAAc,YAAY,CAAC;AAC3E;AAEA,eAAsB,4BAA4B,aAA0B,cAAsB;AAChG,QAAM,YAAY,kBAAkB,EAAE,UAAU,CAAC,GAAG,6BAA6B,YAAY,EAAE,CAAC;AAClG;AAEA,eAAsB,wBACpB,aACA,cACA,eAAe,GACsB;AACrC,SAAO,YAAY,gBAAgB,8BAA8B,cAAc,YAAY,CAAC;AAC9F;",
6
6
  "names": []
7
7
  }
@@ -11,6 +11,11 @@ const upsertDictionarySchema = z.object({
11
11
  isActive: z.boolean().optional(),
12
12
  entrySortMode: dictionaryEntrySortModeSchema.optional()
13
13
  });
14
+ const DICTIONARY_ENTRIES_MAX_LIMIT = 500;
15
+ const listDictionaryEntriesQuerySchema = z.object({
16
+ limit: z.coerce.number().int().positive().max(DICTIONARY_ENTRIES_MAX_LIMIT).catch(DICTIONARY_ENTRIES_MAX_LIMIT),
17
+ offset: z.coerce.number().int().min(0).catch(0)
18
+ });
14
19
  const createDictionaryEntrySchema = z.object({
15
20
  value: z.string().trim().min(1).max(150),
16
21
  label: z.string().trim().min(1).max(150).optional(),
@@ -61,10 +66,12 @@ const setDefaultDictionaryEntryCommandSchema = setDefaultDictionaryEntrySchema.e
61
66
  organizationId: z.string().uuid()
62
67
  });
63
68
  export {
69
+ DICTIONARY_ENTRIES_MAX_LIMIT,
64
70
  createDictionaryEntrySchema,
65
71
  dictionaryEntryCommandCreateSchema,
66
72
  dictionaryEntryCommandUpdateSchema,
67
73
  dictionaryKeySchema,
74
+ listDictionaryEntriesQuerySchema,
68
75
  reorderDictionaryEntriesCommandSchema,
69
76
  reorderDictionaryEntriesSchema,
70
77
  setDefaultDictionaryEntryCommandSchema,
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/dictionaries/data/validators.ts"],
4
- "sourcesContent": ["import { z } from 'zod'\nimport { dictionaryEntrySortModeSchema } from '../lib/entrySort'\n\nexport const dictionaryKeySchema = z\n .string()\n .trim()\n .min(1)\n .max(100)\n .regex(/^[a-z0-9][a-z0-9_-]*$/, 'Use lowercase letters, numbers, hyphen, or underscore.')\n\nconst hexColorSchema = z\n .string()\n .trim()\n .regex(/^#([0-9a-fA-F]{6})$/, 'Color must be a valid six-digit hex code like #3366ff')\n\nconst iconSchema = z.string().trim().min(1).max(64)\n\nexport const upsertDictionarySchema = z.object({\n key: dictionaryKeySchema,\n name: z.string().trim().min(1).max(200),\n description: z.string().trim().max(2000).optional(),\n isSystem: z.boolean().optional(),\n isActive: z.boolean().optional(),\n entrySortMode: dictionaryEntrySortModeSchema.optional(),\n})\n\nexport type UpsertDictionaryInput = z.infer<typeof upsertDictionarySchema>\n\nexport const createDictionaryEntrySchema = z.object({\n value: z.string().trim().min(1).max(150),\n label: z.string().trim().min(1).max(150).optional(),\n color: hexColorSchema.nullable().optional(),\n icon: iconSchema.nullable().optional(),\n position: z.number().int().min(0).optional(),\n})\n\nexport type CreateDictionaryEntryInput = z.infer<typeof createDictionaryEntrySchema>\n\nconst dictionaryEntryUpdateFieldsSchema = z.object({\n value: z.string().trim().min(1).max(150).optional(),\n label: z.string().trim().min(1).max(150).optional(),\n color: hexColorSchema.nullable().optional(),\n icon: iconSchema.nullable().optional(),\n position: z.number().int().min(0).optional(),\n isDefault: z.boolean().optional(),\n})\n\nconst validateDictionaryEntryUpdate = (payload: z.infer<typeof dictionaryEntryUpdateFieldsSchema>) =>\n Object.keys(payload).length > 0\n\nexport const updateDictionaryEntrySchema = dictionaryEntryUpdateFieldsSchema.refine(\n validateDictionaryEntryUpdate,\n {\n message: 'Provide at least one field to update.',\n },\n)\n\nexport type UpdateDictionaryEntryInput = z.infer<typeof updateDictionaryEntrySchema>\n\nexport const dictionaryEntryCommandCreateSchema = createDictionaryEntrySchema.extend({\n dictionaryId: z.string().uuid(),\n})\n\nexport type DictionaryEntryCommandCreateInput = z.infer<typeof dictionaryEntryCommandCreateSchema>\n\nexport const dictionaryEntryCommandUpdateSchema = z\n .object({\n id: z.string().uuid(),\n })\n .merge(dictionaryEntryUpdateFieldsSchema)\n .refine(validateDictionaryEntryUpdate, {\n message: 'Provide at least one field to update.',\n })\n\nexport type DictionaryEntryCommandUpdateInput = z.infer<typeof dictionaryEntryCommandUpdateSchema>\n\nexport const reorderDictionaryEntriesSchema = z.object({\n entries: z.array(z.object({\n id: z.string().uuid(),\n position: z.number().int().min(0),\n })).min(1),\n})\n\nexport type ReorderDictionaryEntriesInput = z.infer<typeof reorderDictionaryEntriesSchema>\n\nexport const reorderDictionaryEntriesCommandSchema = reorderDictionaryEntriesSchema.extend({\n dictionaryId: z.string().uuid(),\n tenantId: z.string().uuid(),\n organizationId: z.string().uuid(),\n})\n\nexport type ReorderDictionaryEntriesCommandInput = z.infer<typeof reorderDictionaryEntriesCommandSchema>\n\nexport const setDefaultDictionaryEntrySchema = z.object({\n entryId: z.string().uuid(),\n})\n\nexport type SetDefaultDictionaryEntryInput = z.infer<typeof setDefaultDictionaryEntrySchema>\n\nexport const setDefaultDictionaryEntryCommandSchema = setDefaultDictionaryEntrySchema.extend({\n dictionaryId: z.string().uuid(),\n tenantId: z.string().uuid(),\n organizationId: z.string().uuid(),\n})\n\nexport type SetDefaultDictionaryEntryCommandInput = z.infer<typeof setDefaultDictionaryEntryCommandSchema>\n"],
5
- "mappings": "AAAA,SAAS,SAAS;AAClB,SAAS,qCAAqC;AAEvC,MAAM,sBAAsB,EAChC,OAAO,EACP,KAAK,EACL,IAAI,CAAC,EACL,IAAI,GAAG,EACP,MAAM,yBAAyB,wDAAwD;AAE1F,MAAM,iBAAiB,EACpB,OAAO,EACP,KAAK,EACL,MAAM,uBAAuB,uDAAuD;AAEvF,MAAM,aAAa,EAAE,OAAO,EAAE,KAAK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AAEzB,MAAM,8BAA8B,kCAAkC;AAAA,EAC3E;AAAA,EACA;AAAA,IACE,SAAS;AAAA,EACX;AACF;AAIO,MAAM,qCAAqC,4BAA4B,OAAO;AAAA,EACnF,cAAc,EAAE,OAAO,EAAE,KAAK;AAChC,CAAC;AAIM,MAAM,qCAAqC,EAC/C,OAAO;AAAA,EACN,IAAI,EAAE,OAAO,EAAE,KAAK;AACtB,CAAC,EACA,MAAM,iCAAiC,EACvC,OAAO,+BAA+B;AAAA,EACrC,SAAS;AACX,CAAC;AAII,MAAM,iCAAiC,EAAE,OAAO;AAAA,EACrD,SAAS,EAAE,MAAM,EAAE,OAAO;AAAA,IACxB,IAAI,EAAE,OAAO,EAAE,KAAK;AAAA,IACpB,UAAU,EAAE,OAAO,EAAE,IAAI,EAAE,IAAI,CAAC;AAAA,EAClC,CAAC,CAAC,EAAE,IAAI,CAAC;AACX,CAAC;AAIM,MAAM,wCAAwC,+BAA+B,OAAO;AAAA,EACzF,cAAc,EAAE,OAAO,EAAE,KAAK;AAAA,EAC9B,UAAU,EAAE,OAAO,EAAE,KAAK;AAAA,EAC1B,gBAAgB,EAAE,OAAO,EAAE,KAAK;AAClC,CAAC;AAIM,MAAM,kCAAkC,EAAE,OAAO;AAAA,EACtD,SAAS,EAAE,OAAO,EAAE,KAAK;AAC3B,CAAC;AAIM,MAAM,yCAAyC,gCAAgC,OAAO;AAAA,EAC3F,cAAc,EAAE,OAAO,EAAE,KAAK;AAAA,EAC9B,UAAU,EAAE,OAAO,EAAE,KAAK;AAAA,EAC1B,gBAAgB,EAAE,OAAO,EAAE,KAAK;AAClC,CAAC;",
4
+ "sourcesContent": ["import { z } from 'zod'\nimport { dictionaryEntrySortModeSchema } from '../lib/entrySort'\n\nexport const dictionaryKeySchema = z\n .string()\n .trim()\n .min(1)\n .max(100)\n .regex(/^[a-z0-9][a-z0-9_-]*$/, 'Use lowercase letters, numbers, hyphen, or underscore.')\n\nconst hexColorSchema = z\n .string()\n .trim()\n .regex(/^#([0-9a-fA-F]{6})$/, 'Color must be a valid six-digit hex code like #3366ff')\n\nconst iconSchema = z.string().trim().min(1).max(64)\n\nexport const upsertDictionarySchema = z.object({\n key: dictionaryKeySchema,\n name: z.string().trim().min(1).max(200),\n description: z.string().trim().max(2000).optional(),\n isSystem: z.boolean().optional(),\n isActive: z.boolean().optional(),\n entrySortMode: dictionaryEntrySortModeSchema.optional(),\n})\n\nexport type UpsertDictionaryInput = z.infer<typeof upsertDictionarySchema>\n\nexport const DICTIONARY_ENTRIES_MAX_LIMIT = 500\n\nexport const listDictionaryEntriesQuerySchema = z.object({\n limit: z.coerce\n .number()\n .int()\n .positive()\n .max(DICTIONARY_ENTRIES_MAX_LIMIT)\n .catch(DICTIONARY_ENTRIES_MAX_LIMIT),\n offset: z.coerce.number().int().min(0).catch(0),\n})\n\nexport type ListDictionaryEntriesQuery = z.infer<typeof listDictionaryEntriesQuerySchema>\n\nexport const createDictionaryEntrySchema = z.object({\n value: z.string().trim().min(1).max(150),\n label: z.string().trim().min(1).max(150).optional(),\n color: hexColorSchema.nullable().optional(),\n icon: iconSchema.nullable().optional(),\n position: z.number().int().min(0).optional(),\n})\n\nexport type CreateDictionaryEntryInput = z.infer<typeof createDictionaryEntrySchema>\n\nconst dictionaryEntryUpdateFieldsSchema = z.object({\n value: z.string().trim().min(1).max(150).optional(),\n label: z.string().trim().min(1).max(150).optional(),\n color: hexColorSchema.nullable().optional(),\n icon: iconSchema.nullable().optional(),\n position: z.number().int().min(0).optional(),\n isDefault: z.boolean().optional(),\n})\n\nconst validateDictionaryEntryUpdate = (payload: z.infer<typeof dictionaryEntryUpdateFieldsSchema>) =>\n Object.keys(payload).length > 0\n\nexport const updateDictionaryEntrySchema = dictionaryEntryUpdateFieldsSchema.refine(\n validateDictionaryEntryUpdate,\n {\n message: 'Provide at least one field to update.',\n },\n)\n\nexport type UpdateDictionaryEntryInput = z.infer<typeof updateDictionaryEntrySchema>\n\nexport const dictionaryEntryCommandCreateSchema = createDictionaryEntrySchema.extend({\n dictionaryId: z.string().uuid(),\n})\n\nexport type DictionaryEntryCommandCreateInput = z.infer<typeof dictionaryEntryCommandCreateSchema>\n\nexport const dictionaryEntryCommandUpdateSchema = z\n .object({\n id: z.string().uuid(),\n })\n .merge(dictionaryEntryUpdateFieldsSchema)\n .refine(validateDictionaryEntryUpdate, {\n message: 'Provide at least one field to update.',\n })\n\nexport type DictionaryEntryCommandUpdateInput = z.infer<typeof dictionaryEntryCommandUpdateSchema>\n\nexport const reorderDictionaryEntriesSchema = z.object({\n entries: z.array(z.object({\n id: z.string().uuid(),\n position: z.number().int().min(0),\n })).min(1),\n})\n\nexport type ReorderDictionaryEntriesInput = z.infer<typeof reorderDictionaryEntriesSchema>\n\nexport const reorderDictionaryEntriesCommandSchema = reorderDictionaryEntriesSchema.extend({\n dictionaryId: z.string().uuid(),\n tenantId: z.string().uuid(),\n organizationId: z.string().uuid(),\n})\n\nexport type ReorderDictionaryEntriesCommandInput = z.infer<typeof reorderDictionaryEntriesCommandSchema>\n\nexport const setDefaultDictionaryEntrySchema = z.object({\n entryId: z.string().uuid(),\n})\n\nexport type SetDefaultDictionaryEntryInput = z.infer<typeof setDefaultDictionaryEntrySchema>\n\nexport const setDefaultDictionaryEntryCommandSchema = setDefaultDictionaryEntrySchema.extend({\n dictionaryId: z.string().uuid(),\n tenantId: z.string().uuid(),\n organizationId: z.string().uuid(),\n})\n\nexport type SetDefaultDictionaryEntryCommandInput = z.infer<typeof setDefaultDictionaryEntryCommandSchema>\n"],
5
+ "mappings": "AAAA,SAAS,SAAS;AAClB,SAAS,qCAAqC;AAEvC,MAAM,sBAAsB,EAChC,OAAO,EACP,KAAK,EACL,IAAI,CAAC,EACL,IAAI,GAAG,EACP,MAAM,yBAAyB,wDAAwD;AAE1F,MAAM,iBAAiB,EACpB,OAAO,EACP,KAAK,EACL,MAAM,uBAAuB,uDAAuD;AAEvF,MAAM,aAAa,EAAE,OAAO,EAAE,KAAK,EAAE,IAAI,CAAC,E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",
6
6
  "names": []
7
7
  }
@@ -1,5 +1,6 @@
1
1
  "use client";
2
2
  import { apiCall } from "@open-mercato/ui/backend/utils/apiCall";
3
+ import { fetchAllDictionaryEntries } from "./fetchAllEntries.js";
3
4
  function normalizeDictionaryList(items) {
4
5
  if (!Array.isArray(items)) return [];
5
6
  return items.map((item) => {
@@ -33,9 +34,9 @@ async function loadDictionaryEntriesByKey(key) {
33
34
  if (!dictionariesCall.ok) return [];
34
35
  const dictionary = normalizeDictionaryList(dictionariesCall.result?.items).find((item) => item.key === key);
35
36
  if (!dictionary) return [];
36
- const entriesCall = await apiCall(`/api/dictionaries/${dictionary.id}/entries`);
37
- if (!entriesCall.ok) return [];
38
- return normalizeDictionaryEntries(entriesCall.result?.items);
37
+ const entries = await fetchAllDictionaryEntries(dictionary.id);
38
+ if (!entries.ok) return [];
39
+ return normalizeDictionaryEntries(entries.items);
39
40
  }
40
41
  export {
41
42
  loadDictionaryEntriesByKey
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/dictionaries/lib/clientEntries.ts"],
4
- "sourcesContent": ["\"use client\"\n\nimport { apiCall } from '@open-mercato/ui/backend/utils/apiCall'\n\ntype DictionarySummary = {\n id: string\n key: string\n}\n\nexport type DictionaryEntryOption = {\n id: string\n value: string\n label: string\n color: string | null\n icon: string | null\n}\n\nfunction normalizeDictionaryList(items: unknown): DictionarySummary[] {\n if (!Array.isArray(items)) return []\n return items\n .map((item) => {\n if (!item || typeof item !== 'object') return null\n const record = item as Record<string, unknown>\n const id = typeof record.id === 'string' ? record.id : null\n const key = typeof record.key === 'string' ? record.key : null\n if (!id || !key) return null\n return { id, key }\n })\n .filter((item): item is DictionarySummary => !!item)\n}\n\nfunction normalizeDictionaryEntries(items: unknown): DictionaryEntryOption[] {\n if (!Array.isArray(items)) return []\n return items\n .map((item) => {\n if (!item || typeof item !== 'object') return null\n const record = item as Record<string, unknown>\n const id = typeof record.id === 'string' ? record.id : null\n const value = typeof record.value === 'string' ? record.value : null\n if (!id || !value) return null\n return {\n id,\n value,\n label:\n typeof record.label === 'string' && record.label.trim().length > 0\n ? record.label\n : value,\n color: typeof record.color === 'string' ? record.color : null,\n icon: typeof record.icon === 'string' ? record.icon : null,\n }\n })\n .filter((item): item is DictionaryEntryOption => !!item)\n}\n\nexport async function loadDictionaryEntriesByKey(key: string): Promise<DictionaryEntryOption[]> {\n const dictionariesCall = await apiCall<{ items?: unknown[] }>('/api/dictionaries')\n if (!dictionariesCall.ok) return []\n\n const dictionary = normalizeDictionaryList(dictionariesCall.result?.items).find((item) => item.key === key)\n if (!dictionary) return []\n\n const entriesCall = await apiCall<{ items?: unknown[] }>(`/api/dictionaries/${dictionary.id}/entries`)\n if (!entriesCall.ok) return []\n\n return normalizeDictionaryEntries(entriesCall.result?.items)\n}\n"],
5
- "mappings": ";AAEA,SAAS,eAAe;AAexB,SAAS,wBAAwB,OAAqC;AACpE,MAAI,CAAC,MAAM,QAAQ,KAAK,EAAG,QAAO,CAAC;AACnC,SAAO,MACJ,IAAI,CAAC,SAAS;AACb,QAAI,CAAC,QAAQ,OAAO,SAAS,SAAU,QAAO;AAC9C,UAAM,SAAS;AACf,UAAM,KAAK,OAAO,OAAO,OAAO,WAAW,OAAO,KAAK;AACvD,UAAM,MAAM,OAAO,OAAO,QAAQ,WAAW,OAAO,MAAM;AAC1D,QAAI,CAAC,MAAM,CAAC,IAAK,QAAO;AACxB,WAAO,EAAE,IAAI,IAAI;AAAA,EACnB,CAAC,EACA,OAAO,CAAC,SAAoC,CAAC,CAAC,IAAI;AACvD;AAEA,SAAS,2BAA2B,OAAyC;AAC3E,MAAI,CAAC,MAAM,QAAQ,KAAK,EAAG,QAAO,CAAC;AACnC,SAAO,MACJ,IAAI,CAAC,SAAS;AACb,QAAI,CAAC,QAAQ,OAAO,SAAS,SAAU,QAAO;AAC9C,UAAM,SAAS;AACf,UAAM,KAAK,OAAO,OAAO,OAAO,WAAW,OAAO,KAAK;AACvD,UAAM,QAAQ,OAAO,OAAO,UAAU,WAAW,OAAO,QAAQ;AAChE,QAAI,CAAC,MAAM,CAAC,MAAO,QAAO;AAC1B,WAAO;AAAA,MACL;AAAA,MACA;AAAA,MACA,OACE,OAAO,OAAO,UAAU,YAAY,OAAO,MAAM,KAAK,EAAE,SAAS,IAC7D,OAAO,QACP;AAAA,MACN,OAAO,OAAO,OAAO,UAAU,WAAW,OAAO,QAAQ;AAAA,MACzD,MAAM,OAAO,OAAO,SAAS,WAAW,OAAO,OAAO;AAAA,IACxD;AAAA,EACF,CAAC,EACA,OAAO,CAAC,SAAwC,CAAC,CAAC,IAAI;AAC3D;AAEA,eAAsB,2BAA2B,KAA+C;AAC9F,QAAM,mBAAmB,MAAM,QAA+B,mBAAmB;AACjF,MAAI,CAAC,iBAAiB,GAAI,QAAO,CAAC;AAElC,QAAM,aAAa,wBAAwB,iBAAiB,QAAQ,KAAK,EAAE,KAAK,CAAC,SAAS,KAAK,QAAQ,GAAG;AAC1G,MAAI,CAAC,WAAY,QAAO,CAAC;AAEzB,QAAM,cAAc,MAAM,QAA+B,qBAAqB,WAAW,EAAE,UAAU;AACrG,MAAI,CAAC,YAAY,GAAI,QAAO,CAAC;AAE7B,SAAO,2BAA2B,YAAY,QAAQ,KAAK;AAC7D;",
4
+ "sourcesContent": ["\"use client\"\n\nimport { apiCall } from '@open-mercato/ui/backend/utils/apiCall'\nimport { fetchAllDictionaryEntries } from './fetchAllEntries'\n\ntype DictionarySummary = {\n id: string\n key: string\n}\n\nexport type DictionaryEntryOption = {\n id: string\n value: string\n label: string\n color: string | null\n icon: string | null\n}\n\nfunction normalizeDictionaryList(items: unknown): DictionarySummary[] {\n if (!Array.isArray(items)) return []\n return items\n .map((item) => {\n if (!item || typeof item !== 'object') return null\n const record = item as Record<string, unknown>\n const id = typeof record.id === 'string' ? record.id : null\n const key = typeof record.key === 'string' ? record.key : null\n if (!id || !key) return null\n return { id, key }\n })\n .filter((item): item is DictionarySummary => !!item)\n}\n\nfunction normalizeDictionaryEntries(items: unknown): DictionaryEntryOption[] {\n if (!Array.isArray(items)) return []\n return items\n .map((item) => {\n if (!item || typeof item !== 'object') return null\n const record = item as Record<string, unknown>\n const id = typeof record.id === 'string' ? record.id : null\n const value = typeof record.value === 'string' ? record.value : null\n if (!id || !value) return null\n return {\n id,\n value,\n label:\n typeof record.label === 'string' && record.label.trim().length > 0\n ? record.label\n : value,\n color: typeof record.color === 'string' ? record.color : null,\n icon: typeof record.icon === 'string' ? record.icon : null,\n }\n })\n .filter((item): item is DictionaryEntryOption => !!item)\n}\n\nexport async function loadDictionaryEntriesByKey(key: string): Promise<DictionaryEntryOption[]> {\n const dictionariesCall = await apiCall<{ items?: unknown[] }>('/api/dictionaries')\n if (!dictionariesCall.ok) return []\n\n const dictionary = normalizeDictionaryList(dictionariesCall.result?.items).find((item) => item.key === key)\n if (!dictionary) return []\n\n const entries = await fetchAllDictionaryEntries(dictionary.id)\n if (!entries.ok) return []\n\n return normalizeDictionaryEntries(entries.items)\n}\n"],
5
+ "mappings": ";AAEA,SAAS,eAAe;AACxB,SAAS,iCAAiC;AAe1C,SAAS,wBAAwB,OAAqC;AACpE,MAAI,CAAC,MAAM,QAAQ,KAAK,EAAG,QAAO,CAAC;AACnC,SAAO,MACJ,IAAI,CAAC,SAAS;AACb,QAAI,CAAC,QAAQ,OAAO,SAAS,SAAU,QAAO;AAC9C,UAAM,SAAS;AACf,UAAM,KAAK,OAAO,OAAO,OAAO,WAAW,OAAO,KAAK;AACvD,UAAM,MAAM,OAAO,OAAO,QAAQ,WAAW,OAAO,MAAM;AAC1D,QAAI,CAAC,MAAM,CAAC,IAAK,QAAO;AACxB,WAAO,EAAE,IAAI,IAAI;AAAA,EACnB,CAAC,EACA,OAAO,CAAC,SAAoC,CAAC,CAAC,IAAI;AACvD;AAEA,SAAS,2BAA2B,OAAyC;AAC3E,MAAI,CAAC,MAAM,QAAQ,KAAK,EAAG,QAAO,CAAC;AACnC,SAAO,MACJ,IAAI,CAAC,SAAS;AACb,QAAI,CAAC,QAAQ,OAAO,SAAS,SAAU,QAAO;AAC9C,UAAM,SAAS;AACf,UAAM,KAAK,OAAO,OAAO,OAAO,WAAW,OAAO,KAAK;AACvD,UAAM,QAAQ,OAAO,OAAO,UAAU,WAAW,OAAO,QAAQ;AAChE,QAAI,CAAC,MAAM,CAAC,MAAO,QAAO;AAC1B,WAAO;AAAA,MACL;AAAA,MACA;AAAA,MACA,OACE,OAAO,OAAO,UAAU,YAAY,OAAO,MAAM,KAAK,EAAE,SAAS,IAC7D,OAAO,QACP;AAAA,MACN,OAAO,OAAO,OAAO,UAAU,WAAW,OAAO,QAAQ;AAAA,MACzD,MAAM,OAAO,OAAO,SAAS,WAAW,OAAO,OAAO;AAAA,IACxD;AAAA,EACF,CAAC,EACA,OAAO,CAAC,SAAwC,CAAC,CAAC,IAAI;AAC3D;AAEA,eAAsB,2BAA2B,KAA+C;AAC9F,QAAM,mBAAmB,MAAM,QAA+B,mBAAmB;AACjF,MAAI,CAAC,iBAAiB,GAAI,QAAO,CAAC;AAElC,QAAM,aAAa,wBAAwB,iBAAiB,QAAQ,KAAK,EAAE,KAAK,CAAC,SAAS,KAAK,QAAQ,GAAG;AAC1G,MAAI,CAAC,WAAY,QAAO,CAAC;AAEzB,QAAM,UAAU,MAAM,0BAA0B,WAAW,EAAE;AAC7D,MAAI,CAAC,QAAQ,GAAI,QAAO,CAAC;AAEzB,SAAO,2BAA2B,QAAQ,KAAK;AACjD;",
6
6
  "names": []
7
7
  }
@@ -0,0 +1,43 @@
1
+ "use client";
2
+ import { fetchAllOffsetPages } from "@open-mercato/ui/backend/utils/fetchAllPages";
3
+ import {
4
+ resolveDictionaryEntrySortMode,
5
+ sortDictionaryEntries
6
+ } from "./entrySort.js";
7
+ function toRecords(items) {
8
+ return items.filter((item) => !!item && typeof item === "object");
9
+ }
10
+ function toSortView(entry) {
11
+ const value = typeof entry.value === "string" ? entry.value.trim() : "";
12
+ const label = typeof entry.label === "string" ? entry.label.trim() : "";
13
+ return {
14
+ entry,
15
+ id: typeof entry.id === "string" ? entry.id : null,
16
+ value: value.length ? value : null,
17
+ label: label.length ? label : null,
18
+ createdAt: typeof entry.createdAt === "string" ? entry.createdAt : null
19
+ };
20
+ }
21
+ async function fetchAllDictionaryEntries(dictionaryId) {
22
+ const pages = await fetchAllOffsetPages(`/api/dictionaries/${dictionaryId}/entries`);
23
+ const records = toRecords(pages.items);
24
+ if (!pages.ok) {
25
+ const error = pages.errorPayload?.error;
26
+ return {
27
+ ok: false,
28
+ items: records,
29
+ pageCount: pages.pageCount,
30
+ errorMessage: typeof error === "string" ? error : null
31
+ };
32
+ }
33
+ if (pages.pageCount <= 1) {
34
+ return { ok: true, items: records, pageCount: pages.pageCount, errorMessage: null };
35
+ }
36
+ const sortMode = resolveDictionaryEntrySortMode(pages.firstPayload.sortMode);
37
+ const sorted = sortDictionaryEntries(records.map(toSortView), sortMode).map((view) => view.entry);
38
+ return { ok: true, items: sorted, pageCount: pages.pageCount, errorMessage: null };
39
+ }
40
+ export {
41
+ fetchAllDictionaryEntries
42
+ };
43
+ //# sourceMappingURL=fetchAllEntries.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../../src/modules/dictionaries/lib/fetchAllEntries.ts"],
4
+ "sourcesContent": ["\"use client\"\n\nimport { fetchAllOffsetPages } from '@open-mercato/ui/backend/utils/fetchAllPages'\nimport {\n resolveDictionaryEntrySortMode,\n sortDictionaryEntries,\n type DictionaryEntrySortItem,\n} from './entrySort'\n\nexport type DictionaryEntryItem = Record<string, unknown>\n\nexport type DictionaryEntriesResult = {\n ok: boolean\n items: DictionaryEntryItem[]\n pageCount: number\n errorMessage: string | null\n}\n\ntype DictionaryEntrySortView = DictionaryEntrySortItem & { entry: DictionaryEntryItem }\n\nfunction toRecords(items: unknown[]): DictionaryEntryItem[] {\n return items.filter((item): item is DictionaryEntryItem => !!item && typeof item === 'object')\n}\n\nfunction toSortView(entry: DictionaryEntryItem): DictionaryEntrySortView {\n const value = typeof entry.value === 'string' ? entry.value.trim() : ''\n const label = typeof entry.label === 'string' ? entry.label.trim() : ''\n return {\n entry,\n id: typeof entry.id === 'string' ? entry.id : null,\n value: value.length ? value : null,\n label: label.length ? label : null,\n createdAt: typeof entry.createdAt === 'string' ? entry.createdAt : null,\n }\n}\n\n/**\n * Load every entry of a dictionary, walking the entries route's page cap.\n *\n * The route bounds each response, so any consumer that needs the full option\n * list must page \u2014 reading `items` from a single request silently drops\n * everything past the ceiling and makes those values unselectable.\n */\nexport async function fetchAllDictionaryEntries(\n dictionaryId: string,\n): Promise<DictionaryEntriesResult> {\n const pages = await fetchAllOffsetPages(`/api/dictionaries/${dictionaryId}/entries`)\n const records = toRecords(pages.items)\n\n if (!pages.ok) {\n const error = pages.errorPayload?.error\n return {\n ok: false,\n items: records,\n pageCount: pages.pageCount,\n errorMessage: typeof error === 'string' ? error : null,\n }\n }\n\n // The route bounds each response and orders it in memory, so entries\n // assembled from several pages are only sorted within each page. Re-apply the\n // mode that produced them across the whole set. A single-page dictionary \u2014\n // every dictionary at or below the route ceiling \u2014 keeps the server ordering\n // byte-for-byte.\n if (pages.pageCount <= 1) {\n return { ok: true, items: records, pageCount: pages.pageCount, errorMessage: null }\n }\n\n const sortMode = resolveDictionaryEntrySortMode(pages.firstPayload.sortMode)\n const sorted = sortDictionaryEntries(records.map(toSortView), sortMode).map((view) => view.entry)\n return { ok: true, items: sorted, pageCount: pages.pageCount, errorMessage: null }\n}\n"],
5
+ "mappings": ";AAEA,SAAS,2BAA2B;AACpC;AAAA,EACE;AAAA,EACA;AAAA,OAEK;AAaP,SAAS,UAAU,OAAyC;AAC1D,SAAO,MAAM,OAAO,CAAC,SAAsC,CAAC,CAAC,QAAQ,OAAO,SAAS,QAAQ;AAC/F;AAEA,SAAS,WAAW,OAAqD;AACvE,QAAM,QAAQ,OAAO,MAAM,UAAU,WAAW,MAAM,MAAM,KAAK,IAAI;AACrE,QAAM,QAAQ,OAAO,MAAM,UAAU,WAAW,MAAM,MAAM,KAAK,IAAI;AACrE,SAAO;AAAA,IACL;AAAA,IACA,IAAI,OAAO,MAAM,OAAO,WAAW,MAAM,KAAK;AAAA,IAC9C,OAAO,MAAM,SAAS,QAAQ;AAAA,IAC9B,OAAO,MAAM,SAAS,QAAQ;AAAA,IAC9B,WAAW,OAAO,MAAM,cAAc,WAAW,MAAM,YAAY;AAAA,EACrE;AACF;AASA,eAAsB,0BACpB,cACkC;AAClC,QAAM,QAAQ,MAAM,oBAAoB,qBAAqB,YAAY,UAAU;AACnF,QAAM,UAAU,UAAU,MAAM,KAAK;AAErC,MAAI,CAAC,MAAM,IAAI;AACb,UAAM,QAAQ,MAAM,cAAc;AAClC,WAAO;AAAA,MACL,IAAI;AAAA,MACJ,OAAO;AAAA,MACP,WAAW,MAAM;AAAA,MACjB,cAAc,OAAO,UAAU,WAAW,QAAQ;AAAA,IACpD;AAAA,EACF;AAOA,MAAI,MAAM,aAAa,GAAG;AACxB,WAAO,EAAE,IAAI,MAAM,OAAO,SAAS,WAAW,MAAM,WAAW,cAAc,KAAK;AAAA,EACpF;AAEA,QAAM,WAAW,+BAA+B,MAAM,aAAa,QAAQ;AAC3E,QAAM,SAAS,sBAAsB,QAAQ,IAAI,UAAU,GAAG,QAAQ,EAAE,IAAI,CAAC,SAAS,KAAK,KAAK;AAChG,SAAO,EAAE,IAAI,MAAM,OAAO,QAAQ,WAAW,MAAM,WAAW,cAAc,KAAK;AACnF;",
6
+ "names": []
7
+ }
@@ -11,6 +11,7 @@ import {
11
11
  ENTITY_DEFINITIONS_CACHE_TTL_MS
12
12
  } from "./definitions.cache.js";
13
13
  import { filterSelectableSystemEntityIds, isSystemEntitySelectable } from "@open-mercato/shared/lib/entities/system-entities";
14
+ import { isOrmBackedSystemEntityId } from "@open-mercato/shared/lib/data/engine";
14
15
  import { resolveOrganizationScopeForRequest } from "@open-mercato/core/modules/directory/utils/organizationScope";
15
16
  import { loadEntityFieldsetConfigs } from "../lib/fieldsets.js";
16
17
  import { installCustomEntitiesFromModules } from "../lib/install-from-ce.js";
@@ -20,6 +21,12 @@ import {
20
21
  beginEntitiesMutationGuard,
21
22
  FIELD_DEFINITION_RESOURCE_KIND
22
23
  } from "./definitions.mutation-guard.js";
24
+ import {
25
+ canReadAllEntityMetadata,
26
+ canReadEntityMetadata,
27
+ getDeclaredCustomEntityRestriction,
28
+ resolveEntityAclRequirement
29
+ } from "../lib/entityAcl.js";
23
30
  import {
24
31
  createExactDefinitionWhere,
25
32
  createScopedDefinitionTombstone,
@@ -187,8 +194,8 @@ async function GET(req) {
187
194
  const fieldsetFilter = requestedFieldset && requestedFieldset.trim().length ? requestedFieldset.trim() : null;
188
195
  const auth = await getAuthFromRequest(req);
189
196
  if (!auth) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
190
- const entityIds = filterSelectableSystemEntityIds(requestedEntityIds);
191
- if (!entityIds.length) {
197
+ const selectableEntityIds = filterSelectableSystemEntityIds(requestedEntityIds);
198
+ if (!selectableEntityIds.length) {
192
199
  return NextResponse.json({ items: [] });
193
200
  }
194
201
  const container = await createRequestContainer();
@@ -201,6 +208,48 @@ async function GET(req) {
201
208
  const organizationId = definitionScope.organizationId;
202
209
  const { resolve } = container;
203
210
  const em = resolve("em");
211
+ const rbac = resolve("rbacService");
212
+ const acl = await rbac.loadAcl(auth.sub ?? "", {
213
+ tenantId,
214
+ organizationId
215
+ });
216
+ const designerCanRead = canReadAllEntityMetadata(acl);
217
+ const customEntityRestrictions = /* @__PURE__ */ new Map();
218
+ for (const entityId of selectableEntityIds) {
219
+ if (isOrmBackedSystemEntityId(em, entityId)) continue;
220
+ const declaredRestriction = getDeclaredCustomEntityRestriction(entityId);
221
+ if (declaredRestriction !== void 0) customEntityRestrictions.set(entityId, declaredRestriction);
222
+ }
223
+ if (!designerCanRead) {
224
+ const unresolvedEntityIds = selectableEntityIds.filter(
225
+ (entityId) => !resolveEntityAclRequirement(entityId) && !customEntityRestrictions.has(entityId)
226
+ );
227
+ if (unresolvedEntityIds.length) {
228
+ const registrations = await em.find(CustomEntity, {
229
+ entityId: { $in: unresolvedEntityIds },
230
+ isActive: true,
231
+ $and: [
232
+ { $or: [{ tenantId }, { tenantId: null }] },
233
+ { $or: [{ organizationId }, { organizationId: null }] }
234
+ ]
235
+ });
236
+ for (const registration of registrations) {
237
+ const entityId = String(registration.entityId);
238
+ if (!isOrmBackedSystemEntityId(em, entityId)) {
239
+ customEntityRestrictions.set(entityId, registration.accessRestricted === true);
240
+ }
241
+ }
242
+ }
243
+ }
244
+ const entityIds = selectableEntityIds.filter((entityId) => canReadEntityMetadata({
245
+ entityId,
246
+ isCustomEntity: customEntityRestrictions.has(entityId),
247
+ isRestricted: customEntityRestrictions.get(entityId) === true,
248
+ acl
249
+ }));
250
+ if (!entityIds.length) {
251
+ return NextResponse.json({ items: [], fieldsetsByEntity: {}, entitySettings: {} });
252
+ }
204
253
  let cache;
205
254
  try {
206
255
  cache = resolve("cache");
@@ -209,7 +258,6 @@ async function GET(req) {
209
258
  let canManageDefinitions = false;
210
259
  if (typeof auth.sub === "string" && auth.sub.length > 0) {
211
260
  try {
212
- const rbac = resolve("rbacService");
213
261
  canManageDefinitions = await rbac.userHasAllFeatures(auth.sub, ["entities.definitions.manage"], {
214
262
  tenantId,
215
263
  organizationId
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/entities/api/definitions.ts"],
4
- "sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport type { CacheStrategy } from '@open-mercato/cache'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'\nimport type { RbacService } from '@open-mercato/core/modules/auth/services/rbacService'\nimport { CustomEntity, CustomFieldDef } from '@open-mercato/core/modules/entities/data/entities'\nimport { upsertCustomFieldDefSchema, fieldsetCodeRegex } from '@open-mercato/core/modules/entities/data/validators'\nimport {\n createDefinitionsCacheKey,\n createDefinitionsCacheTags,\n invalidateDefinitionsCache,\n ENTITY_DEFINITIONS_CACHE_TTL_MS,\n} from './definitions.cache'\nimport type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport { filterSelectableSystemEntityIds, isSystemEntitySelectable } from '@open-mercato/shared/lib/entities/system-entities'\nimport { resolveOrganizationScopeForRequest } from '@open-mercato/core/modules/directory/utils/organizationScope'\nimport { loadEntityFieldsetConfigs, CustomFieldsetDefinition } from '../lib/fieldsets'\nimport { installCustomEntitiesFromModules } from '../lib/install-from-ce'\nimport { normalizeCustomFieldOptions } from '@open-mercato/shared/modules/entities/options'\nimport { CURRENCY_OPTIONS_URL } from '@open-mercato/shared/modules/entities/kinds'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport {\n beginEntitiesMutationGuard,\n FIELD_DEFINITION_RESOURCE_KIND,\n} from './definitions.mutation-guard'\nimport {\n createExactDefinitionWhere,\n createScopedDefinitionTombstone,\n createVisibleDefinitionWhere,\n markDefinitionTombstoned,\n resolveDefinitionScopeFromOrganizationScope,\n resolveDefinitionMutationScope,\n selectVisibleDefinitionWinner,\n} from '../lib/definition-scope'\nimport { resolveEntityDefinitionsVersion } from '../lib/definitions-version'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('entities').child({ component: 'definitions' })\n\n/**\n * Validate defaultValue against the field kind. Returns an error message string\n * if invalid, or null if valid. For dictionary and currency kinds, queries the\n * database to verify the token exists.\n */\nasync function validateDefaultValueByKind(\n value: unknown,\n kind: string,\n cfg: Record<string, unknown>,\n em: EntityManager,\n tenantContext: { tenantId: string | null; organizationId: string | null },\n): Promise<string | null> {\n switch (kind) {\n case 'boolean':\n if (typeof value !== 'boolean') return 'defaultValue for boolean fields must be true or false'\n return null\n case 'integer':\n if (typeof value !== 'number' || !Number.isInteger(value))\n return 'defaultValue for integer fields must be a whole number'\n return null\n case 'float':\n if (typeof value !== 'number' || !isFinite(value))\n return 'defaultValue for float fields must be a finite number'\n return null\n case 'text':\n case 'multiline':\n case 'date':\n case 'datetime':\n if (typeof value !== 'string')\n return `defaultValue for ${kind} fields must be a string`\n return null\n case 'dictionary': {\n if (typeof value !== 'string')\n return 'defaultValue for dictionary fields must be a string'\n const dictionaryId = typeof cfg.dictionaryId === 'string' ? cfg.dictionaryId.trim() : ''\n if (dictionaryId) {\n try {\n const { DictionaryEntry } = await import('@open-mercato/core/modules/dictionaries/data/entities')\n const entry = await em.findOne(DictionaryEntry, {\n dictionary: dictionaryId,\n value: value,\n ...(tenantContext.organizationId ? { organizationId: tenantContext.organizationId } : {}),\n ...(tenantContext.tenantId ? { tenantId: tenantContext.tenantId } : {}),\n })\n if (!entry) return `defaultValue \"${value}\" does not match any entry in the configured dictionary`\n } catch (err) {\n // If the dictionaries module is not available, skip entry validation\n logger.debug('Dictionary validation skipped \u2014 module not available', { err })\n }\n }\n return null\n }\n case 'currency': {\n if (typeof value !== 'string')\n return 'defaultValue for currency fields must be a string'\n try {\n const { Currency } = await import('@open-mercato/core/modules/currencies/data/entities')\n const where: Record<string, string> = { code: value as string }\n if (tenantContext.tenantId) where.tenantId = tenantContext.tenantId\n if (tenantContext.organizationId) where.organizationId = tenantContext.organizationId\n const currency = await em.findOne(Currency, where)\n if (!currency) return `defaultValue \"${value}\" does not match any available currency`\n } catch (err) {\n // If the currencies module is not available, skip currency validation\n logger.debug('Currency validation skipped \u2014 module not available', { err })\n }\n return null\n }\n case 'select': {\n if (typeof value !== 'string' && typeof value !== 'number')\n return 'defaultValue for select fields must be a string or number'\n const options = normalizeCustomFieldOptions(\n Array.isArray(cfg.options) ? cfg.options : [],\n )\n if (options.length > 0) {\n const match = options.some(\n (o) => o.value === value || String(o.value) === String(value),\n )\n if (!match) return 'defaultValue does not match any of the configured options'\n }\n return null\n }\n case 'relation':\n case 'attachment':\n return `defaultValue is not supported for ${kind} fields`\n default:\n return null\n }\n}\n\n/**\n * Normalize defaultValue to the canonical storage shape for the given kind.\n */\nfunction normalizeDefaultValueByKind(value: unknown, kind: string): unknown {\n switch (kind) {\n case 'boolean':\n return value === true\n case 'integer':\n return Math.round(Number(value))\n case 'float':\n return Number(value)\n default:\n return value\n }\n}\n\nexport const metadata = {\n // Reading definitions is needed by record forms; keep it auth-protected but accessible to all authenticated users\n GET: { requireAuth: true },\n // Mutations remain admin-only\n POST: { requireAuth: true, requireFeatures: ['entities.definitions.manage'] },\n DELETE: { requireAuth: true, requireFeatures: ['entities.definitions.manage'] },\n}\n\nfunction parseEntityIds(url: URL): string[] {\n const direct = url.searchParams.getAll('entityId').filter((id) => typeof id === 'string' && id.trim().length > 0)\n const combined = url.searchParams.get('entityIds')\n if (combined) {\n combined\n .split(',')\n .map((id) => id.trim())\n .filter((id) => id.length > 0)\n .forEach((id) => direct.push(id))\n }\n const unique: string[] = []\n const seen = new Set<string>()\n for (const id of direct) {\n if (seen.has(id)) continue\n seen.add(id)\n unique.push(id)\n }\n return unique\n}\n\nasync function resolveEntityDefaultEditor(em: any, entityId: string, tenantId: string | null | undefined): Promise<string | undefined> {\n try {\n const ent = await em.findOne(CustomEntity, {\n entityId,\n $and: [\n { $or: [ { tenantId: tenantId ?? undefined as any }, { tenantId: null } ] },\n ],\n } as any)\n if (ent && typeof (ent as any).defaultEditor === 'string') return (ent as any).defaultEditor\n } catch {}\n return undefined\n}\n\nfunction normalizeFieldGroup(raw: unknown): { code: string; title?: string; hint?: string } | undefined {\n if (!raw) return undefined\n if (typeof raw === 'string') {\n const code = raw.trim()\n return code ? { code } : undefined\n }\n if (typeof raw !== 'object') return undefined\n const entry = raw as Record<string, unknown>\n const code = typeof entry.code === 'string' ? entry.code.trim() : ''\n if (!code) return undefined\n const group: { code: string; title?: string; hint?: string } = { code }\n if (typeof entry.title === 'string' && entry.title.trim()) group.title = entry.title.trim()\n if (typeof entry.hint === 'string' && entry.hint.trim()) group.hint = entry.hint.trim()\n return group\n}\n\nfunction definitionMatchesReadScope(\n definition: { tenantId?: string | null; organizationId?: string | null },\n scope: { tenantId: string | null; organizationId: string | null },\n) {\n const definitionTenantId = definition.tenantId ?? null\n const definitionOrganizationId = definition.organizationId ?? null\n const tenantMatches = definitionTenantId === null || definitionTenantId === scope.tenantId\n const organizationMatches =\n definitionOrganizationId === null ||\n (scope.organizationId !== null && definitionOrganizationId === scope.organizationId)\n return tenantMatches && organizationMatches\n}\n\nexport async function GET(req: Request) {\n const url = new URL(req.url)\n const requestedEntityIds = parseEntityIds(url)\n if (!requestedEntityIds.length) {\n return NextResponse.json({ error: 'entityId is required' }, { status: 400 })\n }\n const requestedFieldset = url.searchParams.get('fieldset')\n const fieldsetFilter = requestedFieldset && requestedFieldset.trim().length ? requestedFieldset.trim() : null\n\n const auth = await getAuthFromRequest(req)\n if (!auth) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })\n\n const entityIds = filterSelectableSystemEntityIds(requestedEntityIds)\n if (!entityIds.length) {\n return NextResponse.json({ items: [] })\n }\n\n const container = await createRequestContainer()\n const scope = await resolveOrganizationScopeForRequest({ container, auth, request: req })\n const definitionScope = resolveDefinitionScopeFromOrganizationScope(auth, scope)\n const tenantId = definitionScope.tenantId\n if (!tenantId) {\n return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })\n }\n const organizationId = definitionScope.organizationId\n const { resolve } = container\n const em = resolve('em') as any\n let cache: CacheStrategy | undefined\n try {\n cache = resolve('cache') as CacheStrategy\n } catch {}\n\n let canManageDefinitions = false\n if (typeof auth.sub === 'string' && auth.sub.length > 0) {\n try {\n const rbac = resolve('rbacService') as RbacService\n canManageDefinitions = await rbac.userHasAllFeatures(auth.sub, ['entities.definitions.manage'], {\n tenantId,\n organizationId,\n })\n } catch {\n // RBAC service unavailable \u2014 fall back to read-only (no definition sync)\n }\n }\n\n if (canManageDefinitions) {\n try {\n await installCustomEntitiesFromModules(em, cache, {\n tenantIds: [tenantId],\n entityIds,\n includeGlobal: true,\n createOnly: true,\n })\n } catch (err) {\n logger.warn('Failed to synchronize module-backed definitions', {\n tenantId,\n entityIds,\n err,\n })\n }\n }\n\n let cacheKey: string | null = null\n if (cache && !fieldsetFilter) {\n cacheKey = createDefinitionsCacheKey({\n tenantId,\n organizationId,\n entityIds,\n })\n try {\n const cached = await cache.get(cacheKey)\n if (cached) {\n return NextResponse.json(cached)\n }\n } catch (err) {\n logger.warn('Failed to read cache', { err })\n }\n }\n\n const fieldsetConfigs = await loadEntityFieldsetConfigs(em, {\n entityIds,\n tenantId,\n organizationId,\n mode: 'public',\n })\n\n const tenantCandidates = [{ tenantId }, { tenantId: null as string | null }]\n const organizationCandidates = [{ organizationId: null as string | null }]\n if (organizationId) organizationCandidates.unshift({ organizationId })\n const readScope = { tenantId, organizationId }\n\n const whereActive = {\n entityId: { $in: entityIds as any },\n deletedAt: null,\n $and: [\n { $or: tenantCandidates },\n { $or: organizationCandidates },\n ],\n } as any\n const defs = (await em.find(CustomFieldDef, whereActive as any))\n .filter((definition: any) => definitionMatchesReadScope(definition, readScope))\n const tombstones = (await em.find(CustomFieldDef, {\n entityId: { $in: entityIds as any },\n deletedAt: { $ne: null } as any,\n $and: [\n { $or: tenantCandidates },\n { $or: organizationCandidates },\n ],\n } as any)).filter((definition: any) => definitionMatchesReadScope(definition, readScope))\n\n const tombstonedByEntity = new Map<string, Set<string>>()\n for (const entry of tombstones as any[]) {\n const eid = String(entry.entityId)\n if (!tombstonedByEntity.has(eid)) tombstonedByEntity.set(eid, new Set())\n tombstonedByEntity.get(eid)!.add(entry.key)\n }\n\n const scopeScore = (x: any) => (x.tenantId ? 2 : 0) + (x.organizationId ? 1 : 0)\n\n const definitionsByEntity = new Map<string, any[]>()\n for (const d of defs) {\n const eid = String(d.entityId)\n if (!definitionsByEntity.has(eid)) definitionsByEntity.set(eid, [])\n definitionsByEntity.get(eid)!.push(d)\n }\n\n const entityDefaultEditors = new Map<string, string | undefined>()\n for (const entityId of entityIds) {\n const editor = await resolveEntityDefaultEditor(em, entityId, tenantId ?? null)\n entityDefaultEditors.set(entityId, editor)\n }\n\n const items: any[] = []\n\n const entityOrder = new Map<string, number>()\n entityIds.forEach((id, idx) => entityOrder.set(id, idx))\n\n for (const entityId of entityIds) {\n const defsForEntity = definitionsByEntity.get(entityId) ?? []\n if (!defsForEntity.length) continue\n const tombstonedKeys = tombstonedByEntity.get(entityId) ?? new Set<string>()\n const byKey = new Map<string, any>()\n for (const d of defsForEntity) {\n const existing = byKey.get(d.key)\n if (!existing) { byKey.set(d.key, d); continue }\n const sNew = scopeScore(d)\n const sOld = scopeScore(existing)\n if (sNew > sOld) { byKey.set(d.key, d); continue }\n if (sNew < sOld) continue\n const tNew = (d.updatedAt instanceof Date) ? d.updatedAt.getTime() : new Date(d.updatedAt).getTime()\n const tOld = (existing.updatedAt instanceof Date) ? existing.updatedAt.getTime() : new Date(existing.updatedAt).getTime()\n if (tNew >= tOld) byKey.set(d.key, d)\n }\n\n const defaultEditor = entityDefaultEditors.get(entityId)\n const winning = Array.from(byKey.values()).filter((d: any) => (d.isActive !== false) && !tombstonedKeys.has(d.key))\n winning.sort((a: any, b: any) => ((a.configJson?.priority ?? 0) - (b.configJson?.priority ?? 0)))\n\n for (const d of winning) {\n const rawFieldset = typeof d.configJson?.fieldset === 'string' ? d.configJson.fieldset.trim() : ''\n const normalizedFieldset = rawFieldset.length > 0 ? rawFieldset : undefined\n const normalizedFieldsets = Array.isArray(d.configJson?.fieldsets)\n ? d.configJson.fieldsets\n .filter((entry: unknown): entry is string => typeof entry === 'string')\n .map((entry: string) => entry.trim())\n .filter((entry: string) => entry.length > 0)\n : []\n const effectiveFieldsets = normalizedFieldsets.length > 0\n ? normalizedFieldsets\n : (normalizedFieldset ? [normalizedFieldset] : [])\n if (fieldsetFilter && !effectiveFieldsets.includes(fieldsetFilter)) continue\n const groupInfo = normalizeFieldGroup(d.configJson?.group)\n const keyLower = String(d.key).toLowerCase()\n const candidateBase = {\n key: d.key,\n kind: d.kind,\n label: d.configJson?.label || d.key,\n description: d.configJson?.description || undefined,\n multi: Boolean(d.configJson?.multi),\n options: (() => {\n if (d.kind === 'currency') return undefined\n const normalizedOptions = normalizeCustomFieldOptions(d.configJson?.options)\n return normalizedOptions.length ? normalizedOptions : undefined\n })(),\n optionsUrl: (() => {\n if (d.kind === 'currency') return CURRENCY_OPTIONS_URL\n const dictionaryId = typeof d.configJson?.dictionaryId === 'string' ? d.configJson.dictionaryId : undefined\n if (dictionaryId) return `/api/dictionaries/${dictionaryId}/entries`\n return typeof d.configJson?.optionsUrl === 'string' ? d.configJson.optionsUrl : undefined\n })(),\n filterable: Boolean(d.configJson?.filterable),\n formEditable: d.configJson?.formEditable !== undefined ? Boolean(d.configJson.formEditable) : true,\n listVisible: d.configJson?.listVisible !== undefined ? Boolean(d.configJson.listVisible) : true,\n editor: typeof d.configJson?.editor === 'string'\n ? d.configJson.editor\n : (d.kind === 'multiline' ? defaultEditor : undefined),\n input: typeof d.configJson?.input === 'string' ? d.configJson.input : undefined,\n dictionaryId: typeof d.configJson?.dictionaryId === 'string' ? d.configJson.dictionaryId : undefined,\n dictionaryInlineCreate: d.configJson?.dictionaryInlineCreate !== undefined\n ? Boolean(d.configJson.dictionaryInlineCreate)\n : undefined,\n priority: typeof d.configJson?.priority === 'number' ? d.configJson.priority : 0,\n validation: Array.isArray(d.configJson?.validation) ? d.configJson.validation : undefined,\n defaultValue: d.configJson?.defaultValue !== undefined ? d.configJson.defaultValue : undefined,\n // attachments config passthrough\n maxAttachmentSizeMb: typeof d.configJson?.maxAttachmentSizeMb === 'number' ? d.configJson.maxAttachmentSizeMb : undefined,\n acceptExtensions: Array.isArray(d.configJson?.acceptExtensions) ? d.configJson.acceptExtensions : undefined,\n // phone config passthrough\n defaultCountryIso2: typeof d.configJson?.defaultCountryIso2 === 'string' ? d.configJson.defaultCountryIso2 : undefined,\n entityId,\n fieldset: normalizedFieldset ?? effectiveFieldsets[0],\n fieldsets: effectiveFieldsets.length > 0 ? effectiveFieldsets : undefined,\n group: groupInfo,\n } as any\n const metrics = computeDefinitionScore(d, candidateBase, entityOrder.get(entityId) ?? Number.MAX_SAFE_INTEGER)\n const candidate = { ...candidateBase, __score: metrics }\n const existing = (items as any[]).find((entry) => entry.key.toLowerCase() === keyLower)\n if (!existing) {\n items.push(candidate)\n continue\n }\n const existingScore = existing.__score as { base: number; penalty: number; entityIndex: number }\n const candidateScoreInfo = candidate.__score as { base: number; penalty: number; entityIndex: number }\n const better =\n candidateScoreInfo.base > existingScore.base ||\n (candidateScoreInfo.base === existingScore.base && candidateScoreInfo.penalty < existingScore.penalty) ||\n (candidateScoreInfo.base === existingScore.base && candidateScoreInfo.penalty === existingScore.penalty && candidateScoreInfo.entityIndex < existingScore.entityIndex)\n if (better) {\n const index = items.findIndex((entry) => entry.key.toLowerCase() === keyLower)\n if (index >= 0) items[index] = candidate\n }\n }\n }\n\n const sanitized = items.map((item: any) => {\n const { __score, ...rest } = item\n return rest\n })\n sanitized.sort((a: any, b: any) => ((a.priority ?? 0) - (b.priority ?? 0)))\n\n const fieldsetsByEntity: Record<string, CustomFieldsetDefinition[]> = {}\n const entitySettings: Record<string, { singleFieldsetPerRecord: boolean }> = {}\n for (const entityId of entityIds) {\n const cfg = fieldsetConfigs.get(entityId) ?? { fieldsets: [], singleFieldsetPerRecord: true }\n fieldsetsByEntity[entityId] = cfg.fieldsets\n entitySettings[entityId] = { singleFieldsetPerRecord: cfg.singleFieldsetPerRecord }\n }\n\n const responseBody = { items: sanitized, fieldsetsByEntity, entitySettings }\n\n if (cache && cacheKey && !fieldsetFilter) {\n const tags = createDefinitionsCacheTags({\n tenantId,\n organizationId,\n entityIds,\n })\n try {\n await cache.set(cacheKey, responseBody, {\n ttl: ENTITY_DEFINITIONS_CACHE_TTL_MS,\n tags,\n })\n } catch (err) {\n logger.warn('Failed to store cache entry', { err })\n }\n }\n\n return NextResponse.json(responseBody)\n}\n\nexport async function POST(req: Request) {\n const auth = await getAuthFromRequest(req)\n if (!auth || !auth.orgId) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })\n let body: any\n try { body = await req.json() } catch { return NextResponse.json({ error: 'Invalid JSON' }, { status: 400 }) }\n const parsed = upsertCustomFieldDefSchema.safeParse(body)\n if (!parsed.success) return NextResponse.json({ error: 'Validation failed', details: parsed.error.flatten() }, { status: 400 })\n const input = parsed.data\n\n if (!isSystemEntitySelectable(input.entityId)) {\n return NextResponse.json({ error: 'Custom fields are not supported for this entity' }, { status: 400 })\n }\n\n if (input.kind === 'dictionary') {\n const dictionaryId = input.configJson?.dictionaryId\n if (typeof dictionaryId !== 'string' || dictionaryId.trim().length === 0) {\n return NextResponse.json({ error: 'dictionaryId is required for dictionary custom fields' }, { status: 400 })\n }\n }\n\n const container = await createRequestContainer()\n const scope = await resolveDefinitionMutationScope({ auth, container, request: req })\n const { resolve } = container\n const em = resolve('em') as any\n let cache: CacheStrategy | undefined\n try {\n cache = resolve('cache') as CacheStrategy\n } catch {}\n\n const where: any = createExactDefinitionWhere(input.entityId, input.key, scope)\n let def = await em.findOne(CustomFieldDef, where)\n\n const guard = await beginEntitiesMutationGuard({\n container,\n auth,\n req,\n resourceKind: FIELD_DEFINITION_RESOURCE_KIND,\n resourceId: def ? def.id : `${input.entityId}:${input.key}`,\n operation: def ? 'update' : 'create',\n mutationPayload: input as unknown as Record<string, unknown>,\n })\n if (guard.blockedResponse) return guard.blockedResponse\n\n if (!def) def = em.create(CustomFieldDef, { ...where, createdAt: new Date() })\n def.kind = input.kind\n const inCfg = (input as any).configJson ?? {}\n const cfg: Record<string, any> = { ...inCfg }\n if (cfg.label == null || String(cfg.label).trim() === '') cfg.label = input.key\n if (cfg.formEditable === undefined) cfg.formEditable = true\n if (cfg.listVisible === undefined) cfg.listVisible = true\n if (input.kind === 'dictionary') {\n const dictionaryId = typeof cfg.dictionaryId === 'string' ? cfg.dictionaryId.trim() : ''\n cfg.dictionaryId = dictionaryId\n cfg.dictionaryInlineCreate = cfg.dictionaryInlineCreate !== false\n }\n if (input.kind === 'currency') {\n cfg.optionsUrl = CURRENCY_OPTIONS_URL\n if (Array.isArray(cfg.options)) delete cfg.options\n }\n if (input.kind === 'multiline' && (cfg.editor == null || String(cfg.editor).trim() === '')) {\n cfg.editor = 'markdown'\n }\n // Validate and normalize defaultValue by kind before persisting\n if (cfg.defaultValue !== undefined && cfg.defaultValue !== null) {\n const validationError = await validateDefaultValueByKind(\n cfg.defaultValue, input.kind, cfg, em,\n { tenantId: scope.tenantId, organizationId: scope.organizationId },\n )\n if (validationError) {\n return NextResponse.json({ error: validationError }, { status: 400 })\n }\n cfg.defaultValue = normalizeDefaultValueByKind(cfg.defaultValue, input.kind)\n }\n def.configJson = cfg\n def.isActive = input.isActive ?? true\n def.deletedAt = def.isActive === false ? (def.deletedAt ?? new Date()) : null\n def.updatedAt = new Date()\n em.persist(def)\n await em.flush()\n await guard.runAfterSuccess()\n await invalidateDefinitionsCache(cache, {\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n entityIds: [input.entityId],\n })\n // Changing field definitions may impact forms but not sidebar items; no nav cache touch\n return NextResponse.json({ ok: true, item: { id: def.id, key: def.key, kind: def.kind, configJson: def.configJson, isActive: def.isActive } })\n}\n\nexport async function DELETE(req: Request) {\n const auth = await getAuthFromRequest(req)\n if (!auth || !auth.orgId) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })\n let body: any\n try { body = await req.json() } catch { return NextResponse.json({ error: 'Invalid JSON' }, { status: 400 }) }\n const { entityId, key } = body || {}\n if (!entityId || !key) return NextResponse.json({ error: 'entityId and key are required' }, { status: 400 })\n\n const container = await createRequestContainer()\n const scope = await resolveDefinitionMutationScope({ auth, container, request: req })\n const { resolve } = container\n const em = resolve('em') as any\n let cache: CacheStrategy | undefined\n try {\n cache = resolve('cache') as CacheStrategy\n } catch {}\n const where: any = createExactDefinitionWhere(entityId, key, scope)\n let def = await em.findOne(CustomFieldDef, where)\n let inherited: any | null = null\n if (!def) {\n inherited = selectVisibleDefinitionWinner(await em.find(CustomFieldDef, createVisibleDefinitionWhere(\n entityId,\n key,\n scope,\n { deletedAt: null, isActive: true },\n )))\n if (!inherited) return NextResponse.json({ error: 'Not found' }, { status: 404 })\n }\n\n const guard = await beginEntitiesMutationGuard({\n container,\n auth,\n req,\n resourceKind: FIELD_DEFINITION_RESOURCE_KIND,\n resourceId: def?.id ?? inherited?.id ?? `${entityId}:${key}`,\n operation: 'delete',\n mutationPayload: { entityId, key },\n })\n if (guard.blockedResponse) return guard.blockedResponse\n\n if (!def) {\n def = createScopedDefinitionTombstone(em, inherited, scope)\n } else {\n markDefinitionTombstoned(def)\n }\n em.persist(def)\n await em.flush()\n await guard.runAfterSuccess()\n await invalidateDefinitionsCache(cache, {\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n entityIds: [entityId],\n })\n // Changing field definitions may impact forms but not sidebar items; no nav cache touch\n // Return the post-delete aggregate version so the edit form keeps its optimistic-lock\n // token in sync after removing a field out-of-band (issue #3152).\n const version = await resolveEntityDefinitionsVersion(em, {\n entityId,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n })\n return NextResponse.json({ ok: true, version })\n}\n\nconst definitionsQuerySchema = z\n .object({\n entityId: z.union([z.string(), z.array(z.string())]).optional(),\n entityIds: z.string().optional(),\n fieldset: z.string().regex(fieldsetCodeRegex).optional(),\n })\n .refine(\n (value) => {\n if (value.entityId && typeof value.entityId === 'string' && value.entityId.trim().length > 0) return true\n if (Array.isArray(value.entityId) && value.entityId.length > 0) return true\n return typeof value.entityIds === 'string' && value.entityIds.trim().length > 0\n },\n { message: 'Provide at least one entityId or an entityIds list.' }\n )\n\nconst customFieldOptionValueSchema = z.union([z.string(), z.number()])\n\nconst customFieldDefinitionSchema = z.object({\n key: z.string(),\n kind: z.string(),\n label: z.string(),\n description: z.string().optional(),\n multi: z.boolean().optional(),\n options: z.array(customFieldOptionValueSchema).optional(),\n optionsUrl: z.string().optional(),\n filterable: z.boolean().optional(),\n formEditable: z.boolean().optional(),\n listVisible: z.boolean().optional(),\n editor: z.string().optional(),\n input: z.string().optional(),\n dictionaryId: z.string().optional(),\n dictionaryInlineCreate: z.boolean().optional(),\n priority: z.number().optional(),\n validation: z.array(z.any()).optional(),\n defaultValue: z.union([z.string(), z.number(), z.boolean(), z.null()]).optional(),\n maxAttachmentSizeMb: z.number().optional(),\n acceptExtensions: z.array(z.any()).optional(),\n entityId: z.string(),\n fieldset: z.string().optional(),\n group: z\n .object({\n code: z.string(),\n title: z.string().optional(),\n hint: z.string().optional(),\n })\n .optional(),\n})\n\nconst customFieldsetGroupResponseSchema = z.object({\n code: z.string(),\n title: z.string().optional(),\n hint: z.string().optional(),\n})\n\nconst entityFieldsetResponseSchema = z.object({\n code: z.string(),\n label: z.string(),\n icon: z.string().optional(),\n description: z.string().optional(),\n groups: z.array(customFieldsetGroupResponseSchema).optional(),\n})\n\nconst definitionsResponseSchema = z.object({\n items: z.array(customFieldDefinitionSchema),\n fieldsetsByEntity: z.record(z.string(), z.array(entityFieldsetResponseSchema)).optional(),\n entitySettings: z\n .record(\n z.string(),\n z.object({\n singleFieldsetPerRecord: z.boolean().optional(),\n })\n )\n .optional(),\n})\n\nconst upsertDefinitionResponseSchema = z.object({\n ok: z.literal(true),\n item: z.object({\n id: z.string().uuid(),\n key: z.string(),\n kind: z.string(),\n configJson: z.record(z.string(), z.any()),\n isActive: z.boolean().optional(),\n }),\n})\n\nconst deleteDefinitionRequestSchema = z.object({\n entityId: z.string(),\n key: z.string(),\n})\n\nconst deleteDefinitionResponseSchema = z.object({\n ok: z.literal(true),\n version: z.string().nullable().optional(),\n})\n\nexport const openApi: OpenApiRouteDoc = {\n tag: 'Entities',\n summary: 'Manage custom field definitions',\n methods: {\n GET: {\n summary: 'List active custom field definitions',\n description: 'Returns active custom field definitions for the supplied entity ids, respecting tenant scope and tombstones.',\n query: definitionsQuerySchema,\n responses: [\n {\n status: 200,\n description: 'Definition list',\n schema: definitionsResponseSchema,\n },\n {\n status: 400,\n description: 'Missing entity id',\n schema: z.object({ error: z.string() }),\n },\n {\n status: 401,\n description: 'Missing authentication',\n schema: z.object({ error: z.string() }),\n },\n ],\n },\n POST: {\n summary: 'Upsert custom field definition',\n description: 'Creates or updates a custom field definition for the current tenant/org scope.',\n requestBody: {\n contentType: 'application/json',\n schema: upsertCustomFieldDefSchema,\n },\n responses: [\n {\n status: 200,\n description: 'Definition saved',\n schema: upsertDefinitionResponseSchema,\n },\n {\n status: 400,\n description: 'Validation failed',\n schema: z.object({\n error: z.string(),\n details: z.any().optional(),\n }),\n },\n {\n status: 401,\n description: 'Missing authentication',\n schema: z.object({ error: z.string() }),\n },\n ],\n },\n DELETE: {\n summary: 'Soft delete custom field definition',\n description: 'Marks the specified definition inactive and tombstones it for the current scope.',\n requestBody: {\n contentType: 'application/json',\n schema: deleteDefinitionRequestSchema,\n },\n responses: [\n {\n status: 200,\n description: 'Definition deleted',\n schema: deleteDefinitionResponseSchema,\n },\n {\n status: 400,\n description: 'Missing entity id or key',\n schema: z.object({ error: z.string() }),\n },\n {\n status: 401,\n description: 'Missing authentication',\n schema: z.object({ error: z.string() }),\n },\n {\n status: 404,\n description: 'Definition not found',\n schema: z.object({ error: z.string() }),\n },\n ],\n },\n },\n}\nconst computeDefinitionScore = (def: any, cfg: Record<string, any>, entityIndex: number) => {\n const listVisibleScore = cfg.listVisible === false ? 0 : 1\n const formEditableScore = cfg.formEditable === false ? 0 : 1\n const filterableScore = cfg.filterable ? 1 : 0\n const kindScore = (() => {\n switch (def.kind) {\n case 'dictionary':\n return 8\n case 'relation':\n return 6\n case 'select':\n case 'currency':\n return 4\n case 'multiline':\n return 3\n case 'boolean':\n case 'integer':\n case 'float':\n return 2\n default:\n return 1\n }\n })()\n const optionsBonus = Array.isArray(cfg.options) && cfg.options.length ? 2 : 0\n const dictionaryBonus = typeof cfg.dictionaryId === 'string' && cfg.dictionaryId.trim().length ? 5 : 0\n const base = (listVisibleScore * 16) + (formEditableScore * 8) + (filterableScore * 4) + kindScore + optionsBonus + dictionaryBonus\n const penalty = typeof cfg.priority === 'number' ? cfg.priority : 0\n return { base,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ACL,KAAK;AACH,eAAO;AAAA,MACT,KAAK;AACH,eAAO;AAAA,MACT,KAAK;AAAA,MACL,KAAK;AAAA,MACL,KAAK;AACH,eAAO;AAAA,MACT;AACE,eAAO;AAAA,IACX;AAAA,EACF,GAAG;AACH,QAAM,eAAe,MAAM,QAAQ,IAAI,OAAO,KAAK,IAAI,QAAQ,SAAS,IAAI;AAC5E,QAAM,kBAAkB,OAAO,IAAI,iBAAiB,YAAY,IAAI,aAAa,KAAK,EAAE,SAAS,IAAI;AACrG,QAAM,OAAQ,mBAAmB,KAAO,oBAAoB,IAAM,kBAAkB,IAAK,YAAY,eAAe;AACpH,QAAM,UAAU,OAAO,IAAI,aAAa,WAAW,IAAI,WAAW;AAClE,SAAO,EAAE,MAAM,SAAS,YAAY;AACtC;",
4
+ "sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport type { CacheStrategy } from '@open-mercato/cache'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'\nimport type { RbacService } from '@open-mercato/core/modules/auth/services/rbacService'\nimport { CustomEntity, CustomFieldDef } from '@open-mercato/core/modules/entities/data/entities'\nimport { upsertCustomFieldDefSchema, fieldsetCodeRegex } from '@open-mercato/core/modules/entities/data/validators'\nimport {\n createDefinitionsCacheKey,\n createDefinitionsCacheTags,\n invalidateDefinitionsCache,\n ENTITY_DEFINITIONS_CACHE_TTL_MS,\n} from './definitions.cache'\nimport type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport { filterSelectableSystemEntityIds, isSystemEntitySelectable } from '@open-mercato/shared/lib/entities/system-entities'\nimport { isOrmBackedSystemEntityId } from '@open-mercato/shared/lib/data/engine'\nimport { resolveOrganizationScopeForRequest } from '@open-mercato/core/modules/directory/utils/organizationScope'\nimport { loadEntityFieldsetConfigs, CustomFieldsetDefinition } from '../lib/fieldsets'\nimport { installCustomEntitiesFromModules } from '../lib/install-from-ce'\nimport { normalizeCustomFieldOptions } from '@open-mercato/shared/modules/entities/options'\nimport { CURRENCY_OPTIONS_URL } from '@open-mercato/shared/modules/entities/kinds'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport {\n beginEntitiesMutationGuard,\n FIELD_DEFINITION_RESOURCE_KIND,\n} from './definitions.mutation-guard'\nimport {\n canReadAllEntityMetadata,\n canReadEntityMetadata,\n getDeclaredCustomEntityRestriction,\n resolveEntityAclRequirement,\n} from '../lib/entityAcl'\nimport {\n createExactDefinitionWhere,\n createScopedDefinitionTombstone,\n createVisibleDefinitionWhere,\n markDefinitionTombstoned,\n resolveDefinitionScopeFromOrganizationScope,\n resolveDefinitionMutationScope,\n selectVisibleDefinitionWinner,\n} from '../lib/definition-scope'\nimport { resolveEntityDefinitionsVersion } from '../lib/definitions-version'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('entities').child({ component: 'definitions' })\n\n/**\n * Validate defaultValue against the field kind. Returns an error message string\n * if invalid, or null if valid. For dictionary and currency kinds, queries the\n * database to verify the token exists.\n */\nasync function validateDefaultValueByKind(\n value: unknown,\n kind: string,\n cfg: Record<string, unknown>,\n em: EntityManager,\n tenantContext: { tenantId: string | null; organizationId: string | null },\n): Promise<string | null> {\n switch (kind) {\n case 'boolean':\n if (typeof value !== 'boolean') return 'defaultValue for boolean fields must be true or false'\n return null\n case 'integer':\n if (typeof value !== 'number' || !Number.isInteger(value))\n return 'defaultValue for integer fields must be a whole number'\n return null\n case 'float':\n if (typeof value !== 'number' || !isFinite(value))\n return 'defaultValue for float fields must be a finite number'\n return null\n case 'text':\n case 'multiline':\n case 'date':\n case 'datetime':\n if (typeof value !== 'string')\n return `defaultValue for ${kind} fields must be a string`\n return null\n case 'dictionary': {\n if (typeof value !== 'string')\n return 'defaultValue for dictionary fields must be a string'\n const dictionaryId = typeof cfg.dictionaryId === 'string' ? cfg.dictionaryId.trim() : ''\n if (dictionaryId) {\n try {\n const { DictionaryEntry } = await import('@open-mercato/core/modules/dictionaries/data/entities')\n const entry = await em.findOne(DictionaryEntry, {\n dictionary: dictionaryId,\n value: value,\n ...(tenantContext.organizationId ? { organizationId: tenantContext.organizationId } : {}),\n ...(tenantContext.tenantId ? { tenantId: tenantContext.tenantId } : {}),\n })\n if (!entry) return `defaultValue \"${value}\" does not match any entry in the configured dictionary`\n } catch (err) {\n // If the dictionaries module is not available, skip entry validation\n logger.debug('Dictionary validation skipped \u2014 module not available', { err })\n }\n }\n return null\n }\n case 'currency': {\n if (typeof value !== 'string')\n return 'defaultValue for currency fields must be a string'\n try {\n const { Currency } = await import('@open-mercato/core/modules/currencies/data/entities')\n const where: Record<string, string> = { code: value as string }\n if (tenantContext.tenantId) where.tenantId = tenantContext.tenantId\n if (tenantContext.organizationId) where.organizationId = tenantContext.organizationId\n const currency = await em.findOne(Currency, where)\n if (!currency) return `defaultValue \"${value}\" does not match any available currency`\n } catch (err) {\n // If the currencies module is not available, skip currency validation\n logger.debug('Currency validation skipped \u2014 module not available', { err })\n }\n return null\n }\n case 'select': {\n if (typeof value !== 'string' && typeof value !== 'number')\n return 'defaultValue for select fields must be a string or number'\n const options = normalizeCustomFieldOptions(\n Array.isArray(cfg.options) ? cfg.options : [],\n )\n if (options.length > 0) {\n const match = options.some(\n (o) => o.value === value || String(o.value) === String(value),\n )\n if (!match) return 'defaultValue does not match any of the configured options'\n }\n return null\n }\n case 'relation':\n case 'attachment':\n return `defaultValue is not supported for ${kind} fields`\n default:\n return null\n }\n}\n\n/**\n * Normalize defaultValue to the canonical storage shape for the given kind.\n */\nfunction normalizeDefaultValueByKind(value: unknown, kind: string): unknown {\n switch (kind) {\n case 'boolean':\n return value === true\n case 'integer':\n return Math.round(Number(value))\n case 'float':\n return Number(value)\n default:\n return value\n }\n}\n\nexport const metadata = {\n // Reading definitions is needed by record forms; keep it auth-protected but accessible to all authenticated users\n GET: { requireAuth: true },\n // Mutations remain admin-only\n POST: { requireAuth: true, requireFeatures: ['entities.definitions.manage'] },\n DELETE: { requireAuth: true, requireFeatures: ['entities.definitions.manage'] },\n}\n\nfunction parseEntityIds(url: URL): string[] {\n const direct = url.searchParams.getAll('entityId').filter((id) => typeof id === 'string' && id.trim().length > 0)\n const combined = url.searchParams.get('entityIds')\n if (combined) {\n combined\n .split(',')\n .map((id) => id.trim())\n .filter((id) => id.length > 0)\n .forEach((id) => direct.push(id))\n }\n const unique: string[] = []\n const seen = new Set<string>()\n for (const id of direct) {\n if (seen.has(id)) continue\n seen.add(id)\n unique.push(id)\n }\n return unique\n}\n\nasync function resolveEntityDefaultEditor(em: any, entityId: string, tenantId: string | null | undefined): Promise<string | undefined> {\n try {\n const ent = await em.findOne(CustomEntity, {\n entityId,\n $and: [\n { $or: [ { tenantId: tenantId ?? undefined as any }, { tenantId: null } ] },\n ],\n } as any)\n if (ent && typeof (ent as any).defaultEditor === 'string') return (ent as any).defaultEditor\n } catch {}\n return undefined\n}\n\nfunction normalizeFieldGroup(raw: unknown): { code: string; title?: string; hint?: string } | undefined {\n if (!raw) return undefined\n if (typeof raw === 'string') {\n const code = raw.trim()\n return code ? { code } : undefined\n }\n if (typeof raw !== 'object') return undefined\n const entry = raw as Record<string, unknown>\n const code = typeof entry.code === 'string' ? entry.code.trim() : ''\n if (!code) return undefined\n const group: { code: string; title?: string; hint?: string } = { code }\n if (typeof entry.title === 'string' && entry.title.trim()) group.title = entry.title.trim()\n if (typeof entry.hint === 'string' && entry.hint.trim()) group.hint = entry.hint.trim()\n return group\n}\n\nfunction definitionMatchesReadScope(\n definition: { tenantId?: string | null; organizationId?: string | null },\n scope: { tenantId: string | null; organizationId: string | null },\n) {\n const definitionTenantId = definition.tenantId ?? null\n const definitionOrganizationId = definition.organizationId ?? null\n const tenantMatches = definitionTenantId === null || definitionTenantId === scope.tenantId\n const organizationMatches =\n definitionOrganizationId === null ||\n (scope.organizationId !== null && definitionOrganizationId === scope.organizationId)\n return tenantMatches && organizationMatches\n}\n\nexport async function GET(req: Request) {\n const url = new URL(req.url)\n const requestedEntityIds = parseEntityIds(url)\n if (!requestedEntityIds.length) {\n return NextResponse.json({ error: 'entityId is required' }, { status: 400 })\n }\n const requestedFieldset = url.searchParams.get('fieldset')\n const fieldsetFilter = requestedFieldset && requestedFieldset.trim().length ? requestedFieldset.trim() : null\n\n const auth = await getAuthFromRequest(req)\n if (!auth) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })\n\n const selectableEntityIds = filterSelectableSystemEntityIds(requestedEntityIds)\n if (!selectableEntityIds.length) {\n return NextResponse.json({ items: [] })\n }\n\n const container = await createRequestContainer()\n const scope = await resolveOrganizationScopeForRequest({ container, auth, request: req })\n const definitionScope = resolveDefinitionScopeFromOrganizationScope(auth, scope)\n const tenantId = definitionScope.tenantId\n if (!tenantId) {\n return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })\n }\n const organizationId = definitionScope.organizationId\n const { resolve } = container\n const em = resolve('em') as any\n const rbac = resolve('rbacService') as RbacService\n const acl = await rbac.loadAcl(auth.sub ?? '', {\n tenantId,\n organizationId,\n })\n const designerCanRead = canReadAllEntityMetadata(acl)\n const customEntityRestrictions = new Map<string, boolean>()\n for (const entityId of selectableEntityIds) {\n if (isOrmBackedSystemEntityId(em, entityId)) continue\n const declaredRestriction = getDeclaredCustomEntityRestriction(entityId)\n if (declaredRestriction !== undefined) customEntityRestrictions.set(entityId, declaredRestriction)\n }\n if (!designerCanRead) {\n const unresolvedEntityIds = selectableEntityIds.filter(\n (entityId) => !resolveEntityAclRequirement(entityId) && !customEntityRestrictions.has(entityId),\n )\n if (unresolvedEntityIds.length) {\n const registrations = await em.find(CustomEntity as any, {\n entityId: { $in: unresolvedEntityIds },\n isActive: true,\n $and: [\n { $or: [{ tenantId }, { tenantId: null }] },\n { $or: [{ organizationId }, { organizationId: null }] },\n ],\n } as any)\n for (const registration of registrations as any[]) {\n const entityId = String(registration.entityId)\n if (!isOrmBackedSystemEntityId(em, entityId)) {\n customEntityRestrictions.set(entityId, registration.accessRestricted === true)\n }\n }\n }\n }\n const entityIds = selectableEntityIds.filter((entityId) => canReadEntityMetadata({\n entityId,\n isCustomEntity: customEntityRestrictions.has(entityId),\n isRestricted: customEntityRestrictions.get(entityId) === true,\n acl,\n }))\n if (!entityIds.length) {\n return NextResponse.json({ items: [], fieldsetsByEntity: {}, entitySettings: {} })\n }\n let cache: CacheStrategy | undefined\n try {\n cache = resolve('cache') as CacheStrategy\n } catch {}\n\n let canManageDefinitions = false\n if (typeof auth.sub === 'string' && auth.sub.length > 0) {\n try {\n canManageDefinitions = await rbac.userHasAllFeatures(auth.sub, ['entities.definitions.manage'], {\n tenantId,\n organizationId,\n })\n } catch {\n // RBAC service unavailable \u2014 fall back to read-only (no definition sync)\n }\n }\n\n if (canManageDefinitions) {\n try {\n await installCustomEntitiesFromModules(em, cache, {\n tenantIds: [tenantId],\n entityIds,\n includeGlobal: true,\n createOnly: true,\n })\n } catch (err) {\n logger.warn('Failed to synchronize module-backed definitions', {\n tenantId,\n entityIds,\n err,\n })\n }\n }\n\n let cacheKey: string | null = null\n if (cache && !fieldsetFilter) {\n cacheKey = createDefinitionsCacheKey({\n tenantId,\n organizationId,\n entityIds,\n })\n try {\n const cached = await cache.get(cacheKey)\n if (cached) {\n return NextResponse.json(cached)\n }\n } catch (err) {\n logger.warn('Failed to read cache', { err })\n }\n }\n\n const fieldsetConfigs = await loadEntityFieldsetConfigs(em, {\n entityIds,\n tenantId,\n organizationId,\n mode: 'public',\n })\n\n const tenantCandidates = [{ tenantId }, { tenantId: null as string | null }]\n const organizationCandidates = [{ organizationId: null as string | null }]\n if (organizationId) organizationCandidates.unshift({ organizationId })\n const readScope = { tenantId, organizationId }\n\n const whereActive = {\n entityId: { $in: entityIds as any },\n deletedAt: null,\n $and: [\n { $or: tenantCandidates },\n { $or: organizationCandidates },\n ],\n } as any\n const defs = (await em.find(CustomFieldDef, whereActive as any))\n .filter((definition: any) => definitionMatchesReadScope(definition, readScope))\n const tombstones = (await em.find(CustomFieldDef, {\n entityId: { $in: entityIds as any },\n deletedAt: { $ne: null } as any,\n $and: [\n { $or: tenantCandidates },\n { $or: organizationCandidates },\n ],\n } as any)).filter((definition: any) => definitionMatchesReadScope(definition, readScope))\n\n const tombstonedByEntity = new Map<string, Set<string>>()\n for (const entry of tombstones as any[]) {\n const eid = String(entry.entityId)\n if (!tombstonedByEntity.has(eid)) tombstonedByEntity.set(eid, new Set())\n tombstonedByEntity.get(eid)!.add(entry.key)\n }\n\n const scopeScore = (x: any) => (x.tenantId ? 2 : 0) + (x.organizationId ? 1 : 0)\n\n const definitionsByEntity = new Map<string, any[]>()\n for (const d of defs) {\n const eid = String(d.entityId)\n if (!definitionsByEntity.has(eid)) definitionsByEntity.set(eid, [])\n definitionsByEntity.get(eid)!.push(d)\n }\n\n const entityDefaultEditors = new Map<string, string | undefined>()\n for (const entityId of entityIds) {\n const editor = await resolveEntityDefaultEditor(em, entityId, tenantId ?? null)\n entityDefaultEditors.set(entityId, editor)\n }\n\n const items: any[] = []\n\n const entityOrder = new Map<string, number>()\n entityIds.forEach((id, idx) => entityOrder.set(id, idx))\n\n for (const entityId of entityIds) {\n const defsForEntity = definitionsByEntity.get(entityId) ?? []\n if (!defsForEntity.length) continue\n const tombstonedKeys = tombstonedByEntity.get(entityId) ?? new Set<string>()\n const byKey = new Map<string, any>()\n for (const d of defsForEntity) {\n const existing = byKey.get(d.key)\n if (!existing) { byKey.set(d.key, d); continue }\n const sNew = scopeScore(d)\n const sOld = scopeScore(existing)\n if (sNew > sOld) { byKey.set(d.key, d); continue }\n if (sNew < sOld) continue\n const tNew = (d.updatedAt instanceof Date) ? d.updatedAt.getTime() : new Date(d.updatedAt).getTime()\n const tOld = (existing.updatedAt instanceof Date) ? existing.updatedAt.getTime() : new Date(existing.updatedAt).getTime()\n if (tNew >= tOld) byKey.set(d.key, d)\n }\n\n const defaultEditor = entityDefaultEditors.get(entityId)\n const winning = Array.from(byKey.values()).filter((d: any) => (d.isActive !== false) && !tombstonedKeys.has(d.key))\n winning.sort((a: any, b: any) => ((a.configJson?.priority ?? 0) - (b.configJson?.priority ?? 0)))\n\n for (const d of winning) {\n const rawFieldset = typeof d.configJson?.fieldset === 'string' ? d.configJson.fieldset.trim() : ''\n const normalizedFieldset = rawFieldset.length > 0 ? rawFieldset : undefined\n const normalizedFieldsets = Array.isArray(d.configJson?.fieldsets)\n ? d.configJson.fieldsets\n .filter((entry: unknown): entry is string => typeof entry === 'string')\n .map((entry: string) => entry.trim())\n .filter((entry: string) => entry.length > 0)\n : []\n const effectiveFieldsets = normalizedFieldsets.length > 0\n ? normalizedFieldsets\n : (normalizedFieldset ? [normalizedFieldset] : [])\n if (fieldsetFilter && !effectiveFieldsets.includes(fieldsetFilter)) continue\n const groupInfo = normalizeFieldGroup(d.configJson?.group)\n const keyLower = String(d.key).toLowerCase()\n const candidateBase = {\n key: d.key,\n kind: d.kind,\n label: d.configJson?.label || d.key,\n description: d.configJson?.description || undefined,\n multi: Boolean(d.configJson?.multi),\n options: (() => {\n if (d.kind === 'currency') return undefined\n const normalizedOptions = normalizeCustomFieldOptions(d.configJson?.options)\n return normalizedOptions.length ? normalizedOptions : undefined\n })(),\n optionsUrl: (() => {\n if (d.kind === 'currency') return CURRENCY_OPTIONS_URL\n const dictionaryId = typeof d.configJson?.dictionaryId === 'string' ? d.configJson.dictionaryId : undefined\n if (dictionaryId) return `/api/dictionaries/${dictionaryId}/entries`\n return typeof d.configJson?.optionsUrl === 'string' ? d.configJson.optionsUrl : undefined\n })(),\n filterable: Boolean(d.configJson?.filterable),\n formEditable: d.configJson?.formEditable !== undefined ? Boolean(d.configJson.formEditable) : true,\n listVisible: d.configJson?.listVisible !== undefined ? Boolean(d.configJson.listVisible) : true,\n editor: typeof d.configJson?.editor === 'string'\n ? d.configJson.editor\n : (d.kind === 'multiline' ? defaultEditor : undefined),\n input: typeof d.configJson?.input === 'string' ? d.configJson.input : undefined,\n dictionaryId: typeof d.configJson?.dictionaryId === 'string' ? d.configJson.dictionaryId : undefined,\n dictionaryInlineCreate: d.configJson?.dictionaryInlineCreate !== undefined\n ? Boolean(d.configJson.dictionaryInlineCreate)\n : undefined,\n priority: typeof d.configJson?.priority === 'number' ? d.configJson.priority : 0,\n validation: Array.isArray(d.configJson?.validation) ? d.configJson.validation : undefined,\n defaultValue: d.configJson?.defaultValue !== undefined ? d.configJson.defaultValue : undefined,\n // attachments config passthrough\n maxAttachmentSizeMb: typeof d.configJson?.maxAttachmentSizeMb === 'number' ? d.configJson.maxAttachmentSizeMb : undefined,\n acceptExtensions: Array.isArray(d.configJson?.acceptExtensions) ? d.configJson.acceptExtensions : undefined,\n // phone config passthrough\n defaultCountryIso2: typeof d.configJson?.defaultCountryIso2 === 'string' ? d.configJson.defaultCountryIso2 : undefined,\n entityId,\n fieldset: normalizedFieldset ?? effectiveFieldsets[0],\n fieldsets: effectiveFieldsets.length > 0 ? effectiveFieldsets : undefined,\n group: groupInfo,\n } as any\n const metrics = computeDefinitionScore(d, candidateBase, entityOrder.get(entityId) ?? Number.MAX_SAFE_INTEGER)\n const candidate = { ...candidateBase, __score: metrics }\n const existing = (items as any[]).find((entry) => entry.key.toLowerCase() === keyLower)\n if (!existing) {\n items.push(candidate)\n continue\n }\n const existingScore = existing.__score as { base: number; penalty: number; entityIndex: number }\n const candidateScoreInfo = candidate.__score as { base: number; penalty: number; entityIndex: number }\n const better =\n candidateScoreInfo.base > existingScore.base ||\n (candidateScoreInfo.base === existingScore.base && candidateScoreInfo.penalty < existingScore.penalty) ||\n (candidateScoreInfo.base === existingScore.base && candidateScoreInfo.penalty === existingScore.penalty && candidateScoreInfo.entityIndex < existingScore.entityIndex)\n if (better) {\n const index = items.findIndex((entry) => entry.key.toLowerCase() === keyLower)\n if (index >= 0) items[index] = candidate\n }\n }\n }\n\n const sanitized = items.map((item: any) => {\n const { __score, ...rest } = item\n return rest\n })\n sanitized.sort((a: any, b: any) => ((a.priority ?? 0) - (b.priority ?? 0)))\n\n const fieldsetsByEntity: Record<string, CustomFieldsetDefinition[]> = {}\n const entitySettings: Record<string, { singleFieldsetPerRecord: boolean }> = {}\n for (const entityId of entityIds) {\n const cfg = fieldsetConfigs.get(entityId) ?? { fieldsets: [], singleFieldsetPerRecord: true }\n fieldsetsByEntity[entityId] = cfg.fieldsets\n entitySettings[entityId] = { singleFieldsetPerRecord: cfg.singleFieldsetPerRecord }\n }\n\n const responseBody = { items: sanitized, fieldsetsByEntity, entitySettings }\n\n if (cache && cacheKey && !fieldsetFilter) {\n const tags = createDefinitionsCacheTags({\n tenantId,\n organizationId,\n entityIds,\n })\n try {\n await cache.set(cacheKey, responseBody, {\n ttl: ENTITY_DEFINITIONS_CACHE_TTL_MS,\n tags,\n })\n } catch (err) {\n logger.warn('Failed to store cache entry', { err })\n }\n }\n\n return NextResponse.json(responseBody)\n}\n\nexport async function POST(req: Request) {\n const auth = await getAuthFromRequest(req)\n if (!auth || !auth.orgId) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })\n let body: any\n try { body = await req.json() } catch { return NextResponse.json({ error: 'Invalid JSON' }, { status: 400 }) }\n const parsed = upsertCustomFieldDefSchema.safeParse(body)\n if (!parsed.success) return NextResponse.json({ error: 'Validation failed', details: parsed.error.flatten() }, { status: 400 })\n const input = parsed.data\n\n if (!isSystemEntitySelectable(input.entityId)) {\n return NextResponse.json({ error: 'Custom fields are not supported for this entity' }, { status: 400 })\n }\n\n if (input.kind === 'dictionary') {\n const dictionaryId = input.configJson?.dictionaryId\n if (typeof dictionaryId !== 'string' || dictionaryId.trim().length === 0) {\n return NextResponse.json({ error: 'dictionaryId is required for dictionary custom fields' }, { status: 400 })\n }\n }\n\n const container = await createRequestContainer()\n const scope = await resolveDefinitionMutationScope({ auth, container, request: req })\n const { resolve } = container\n const em = resolve('em') as any\n let cache: CacheStrategy | undefined\n try {\n cache = resolve('cache') as CacheStrategy\n } catch {}\n\n const where: any = createExactDefinitionWhere(input.entityId, input.key, scope)\n let def = await em.findOne(CustomFieldDef, where)\n\n const guard = await beginEntitiesMutationGuard({\n container,\n auth,\n req,\n resourceKind: FIELD_DEFINITION_RESOURCE_KIND,\n resourceId: def ? def.id : `${input.entityId}:${input.key}`,\n operation: def ? 'update' : 'create',\n mutationPayload: input as unknown as Record<string, unknown>,\n })\n if (guard.blockedResponse) return guard.blockedResponse\n\n if (!def) def = em.create(CustomFieldDef, { ...where, createdAt: new Date() })\n def.kind = input.kind\n const inCfg = (input as any).configJson ?? {}\n const cfg: Record<string, any> = { ...inCfg }\n if (cfg.label == null || String(cfg.label).trim() === '') cfg.label = input.key\n if (cfg.formEditable === undefined) cfg.formEditable = true\n if (cfg.listVisible === undefined) cfg.listVisible = true\n if (input.kind === 'dictionary') {\n const dictionaryId = typeof cfg.dictionaryId === 'string' ? cfg.dictionaryId.trim() : ''\n cfg.dictionaryId = dictionaryId\n cfg.dictionaryInlineCreate = cfg.dictionaryInlineCreate !== false\n }\n if (input.kind === 'currency') {\n cfg.optionsUrl = CURRENCY_OPTIONS_URL\n if (Array.isArray(cfg.options)) delete cfg.options\n }\n if (input.kind === 'multiline' && (cfg.editor == null || String(cfg.editor).trim() === '')) {\n cfg.editor = 'markdown'\n }\n // Validate and normalize defaultValue by kind before persisting\n if (cfg.defaultValue !== undefined && cfg.defaultValue !== null) {\n const validationError = await validateDefaultValueByKind(\n cfg.defaultValue, input.kind, cfg, em,\n { tenantId: scope.tenantId, organizationId: scope.organizationId },\n )\n if (validationError) {\n return NextResponse.json({ error: validationError }, { status: 400 })\n }\n cfg.defaultValue = normalizeDefaultValueByKind(cfg.defaultValue, input.kind)\n }\n def.configJson = cfg\n def.isActive = input.isActive ?? true\n def.deletedAt = def.isActive === false ? (def.deletedAt ?? new Date()) : null\n def.updatedAt = new Date()\n em.persist(def)\n await em.flush()\n await guard.runAfterSuccess()\n await invalidateDefinitionsCache(cache, {\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n entityIds: [input.entityId],\n })\n // Changing field definitions may impact forms but not sidebar items; no nav cache touch\n return NextResponse.json({ ok: true, item: { id: def.id, key: def.key, kind: def.kind, configJson: def.configJson, isActive: def.isActive } })\n}\n\nexport async function DELETE(req: Request) {\n const auth = await getAuthFromRequest(req)\n if (!auth || !auth.orgId) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })\n let body: any\n try { body = await req.json() } catch { return NextResponse.json({ error: 'Invalid JSON' }, { status: 400 }) }\n const { entityId, key } = body || {}\n if (!entityId || !key) return NextResponse.json({ error: 'entityId and key are required' }, { status: 400 })\n\n const container = await createRequestContainer()\n const scope = await resolveDefinitionMutationScope({ auth, container, request: req })\n const { resolve } = container\n const em = resolve('em') as any\n let cache: CacheStrategy | undefined\n try {\n cache = resolve('cache') as CacheStrategy\n } catch {}\n const where: any = createExactDefinitionWhere(entityId, key, scope)\n let def = await em.findOne(CustomFieldDef, where)\n let inherited: any | null = null\n if (!def) {\n inherited = selectVisibleDefinitionWinner(await em.find(CustomFieldDef, createVisibleDefinitionWhere(\n entityId,\n key,\n scope,\n { deletedAt: null, isActive: true },\n )))\n if (!inherited) return NextResponse.json({ error: 'Not found' }, { status: 404 })\n }\n\n const guard = await beginEntitiesMutationGuard({\n container,\n auth,\n req,\n resourceKind: FIELD_DEFINITION_RESOURCE_KIND,\n resourceId: def?.id ?? inherited?.id ?? `${entityId}:${key}`,\n operation: 'delete',\n mutationPayload: { entityId, key },\n })\n if (guard.blockedResponse) return guard.blockedResponse\n\n if (!def) {\n def = createScopedDefinitionTombstone(em, inherited, scope)\n } else {\n markDefinitionTombstoned(def)\n }\n em.persist(def)\n await em.flush()\n await guard.runAfterSuccess()\n await invalidateDefinitionsCache(cache, {\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n entityIds: [entityId],\n })\n // Changing field definitions may impact forms but not sidebar items; no nav cache touch\n // Return the post-delete aggregate version so the edit form keeps its optimistic-lock\n // token in sync after removing a field out-of-band (issue #3152).\n const version = await resolveEntityDefinitionsVersion(em, {\n entityId,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n })\n return NextResponse.json({ ok: true, version })\n}\n\nconst definitionsQuerySchema = z\n .object({\n entityId: z.union([z.string(), z.array(z.string())]).optional(),\n entityIds: z.string().optional(),\n fieldset: z.string().regex(fieldsetCodeRegex).optional(),\n })\n .refine(\n (value) => {\n if (value.entityId && typeof value.entityId === 'string' && value.entityId.trim().length > 0) return true\n if (Array.isArray(value.entityId) && value.entityId.length > 0) return true\n return typeof value.entityIds === 'string' && value.entityIds.trim().length > 0\n },\n { message: 'Provide at least one entityId or an entityIds list.' }\n )\n\nconst customFieldOptionValueSchema = z.union([z.string(), z.number()])\n\nconst customFieldDefinitionSchema = z.object({\n key: z.string(),\n kind: z.string(),\n label: z.string(),\n description: z.string().optional(),\n multi: z.boolean().optional(),\n options: z.array(customFieldOptionValueSchema).optional(),\n optionsUrl: z.string().optional(),\n filterable: z.boolean().optional(),\n formEditable: z.boolean().optional(),\n listVisible: z.boolean().optional(),\n editor: z.string().optional(),\n input: z.string().optional(),\n dictionaryId: z.string().optional(),\n dictionaryInlineCreate: z.boolean().optional(),\n priority: z.number().optional(),\n validation: z.array(z.any()).optional(),\n defaultValue: z.union([z.string(), z.number(), z.boolean(), z.null()]).optional(),\n maxAttachmentSizeMb: z.number().optional(),\n acceptExtensions: z.array(z.any()).optional(),\n entityId: z.string(),\n fieldset: z.string().optional(),\n group: z\n .object({\n code: z.string(),\n title: z.string().optional(),\n hint: z.string().optional(),\n })\n .optional(),\n})\n\nconst customFieldsetGroupResponseSchema = z.object({\n code: z.string(),\n title: z.string().optional(),\n hint: z.string().optional(),\n})\n\nconst entityFieldsetResponseSchema = z.object({\n code: z.string(),\n label: z.string(),\n icon: z.string().optional(),\n description: z.string().optional(),\n groups: z.array(customFieldsetGroupResponseSchema).optional(),\n})\n\nconst definitionsResponseSchema = z.object({\n items: z.array(customFieldDefinitionSchema),\n fieldsetsByEntity: z.record(z.string(), z.array(entityFieldsetResponseSchema)).optional(),\n entitySettings: z\n .record(\n z.string(),\n z.object({\n singleFieldsetPerRecord: z.boolean().optional(),\n })\n )\n .optional(),\n})\n\nconst upsertDefinitionResponseSchema = z.object({\n ok: z.literal(true),\n item: z.object({\n id: z.string().uuid(),\n key: z.string(),\n kind: z.string(),\n configJson: z.record(z.string(), z.any()),\n isActive: z.boolean().optional(),\n }),\n})\n\nconst deleteDefinitionRequestSchema = z.object({\n entityId: z.string(),\n key: z.string(),\n})\n\nconst deleteDefinitionResponseSchema = z.object({\n ok: z.literal(true),\n version: z.string().nullable().optional(),\n})\n\nexport const openApi: OpenApiRouteDoc = {\n tag: 'Entities',\n summary: 'Manage custom field definitions',\n methods: {\n GET: {\n summary: 'List active custom field definitions',\n description: 'Returns active custom field definitions for the supplied entity ids, respecting tenant scope and tombstones.',\n query: definitionsQuerySchema,\n responses: [\n {\n status: 200,\n description: 'Definition list',\n schema: definitionsResponseSchema,\n },\n {\n status: 400,\n description: 'Missing entity id',\n schema: z.object({ error: z.string() }),\n },\n {\n status: 401,\n description: 'Missing authentication',\n schema: z.object({ error: z.string() }),\n },\n ],\n },\n POST: {\n summary: 'Upsert custom field definition',\n description: 'Creates or updates a custom field definition for the current tenant/org scope.',\n requestBody: {\n contentType: 'application/json',\n schema: upsertCustomFieldDefSchema,\n },\n responses: [\n {\n status: 200,\n description: 'Definition saved',\n schema: upsertDefinitionResponseSchema,\n },\n {\n status: 400,\n description: 'Validation failed',\n schema: z.object({\n error: z.string(),\n details: z.any().optional(),\n }),\n },\n {\n status: 401,\n description: 'Missing authentication',\n schema: z.object({ error: z.string() }),\n },\n ],\n },\n DELETE: {\n summary: 'Soft delete custom field definition',\n description: 'Marks the specified definition inactive and tombstones it for the current scope.',\n requestBody: {\n contentType: 'application/json',\n schema: deleteDefinitionRequestSchema,\n },\n responses: [\n {\n status: 200,\n description: 'Definition deleted',\n schema: deleteDefinitionResponseSchema,\n },\n {\n status: 400,\n description: 'Missing entity id or key',\n schema: z.object({ error: z.string() }),\n },\n {\n status: 401,\n description: 'Missing authentication',\n schema: z.object({ error: z.string() }),\n },\n {\n status: 404,\n description: 'Definition not found',\n schema: z.object({ error: z.string() }),\n },\n ],\n },\n },\n}\nconst computeDefinitionScore = (def: any, cfg: Record<string, any>, entityIndex: number) => {\n const listVisibleScore = cfg.listVisible === false ? 0 : 1\n const formEditableScore = cfg.formEditable === false ? 0 : 1\n const filterableScore = cfg.filterable ? 1 : 0\n const kindScore = (() => {\n switch (def.kind) {\n case 'dictionary':\n return 8\n case 'relation':\n return 6\n case 'select':\n case 'currency':\n return 4\n case 'multiline':\n return 3\n case 'boolean':\n case 'integer':\n case 'float':\n return 2\n default:\n return 1\n }\n })()\n const optionsBonus = Array.isArray(cfg.options) && cfg.options.length ? 2 : 0\n const dictionaryBonus = typeof cfg.dictionaryId === 'string' && cfg.dictionaryId.trim().length ? 5 : 0\n const base = (listVisibleScore * 16) + (formEditableScore * 8) + (filterableScore * 4) + kindScore + optionsBonus + dictionaryBonus\n const penalty = typeof cfg.priority === 'number' ? cfg.priority : 0\n return { base, penalty, entityIndex }\n}\n"],
5
+ "mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAElB,SAAS,8BAA8B;AACvC,SAAS,0BAA0B;AAEnC,SAAS,cAAc,sBAAsB;AAC7C,SAAS,4BAA4B,yBAAyB;AAC9D;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEP,SAAS,iCAAiC,gCAAgC;AAC1E,SAAS,iCAAiC;AAC1C,SAAS,0CAA0C;AACnD,SAAS,iCAA2D;AACpE,SAAS,wCAAwC;AACjD,SAAS,mCAAmC;AAC5C,SAAS,4BAA4B;AAErC;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,uCAAuC;AAChD,SAAS,oBAAoB;AAE7B,MAAM,SAAS,aAAa,UA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