@open-mercato/core 0.4.6-develop-9ff1d4a9a2 → 0.4.6-develop-219dae16c5

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 (107) hide show
  1. package/dist/modules/currencies/backend/exchange-rates/[id]/page.js +17 -154
  2. package/dist/modules/currencies/backend/exchange-rates/[id]/page.js.map +3 -3
  3. package/dist/modules/currencies/backend/exchange-rates/create/page.js +14 -152
  4. package/dist/modules/currencies/backend/exchange-rates/create/page.js.map +2 -2
  5. package/dist/modules/currencies/lib/exchangeRateFormConfig.js +167 -0
  6. package/dist/modules/currencies/lib/exchangeRateFormConfig.js.map +7 -0
  7. package/dist/modules/customers/api/dashboard/widgets/utils.js +1 -34
  8. package/dist/modules/customers/api/dashboard/widgets/utils.js.map +2 -2
  9. package/dist/modules/customers/commands/activities.js +3 -8
  10. package/dist/modules/customers/commands/activities.js.map +2 -2
  11. package/dist/modules/customers/commands/comments.js +2 -8
  12. package/dist/modules/customers/commands/comments.js.map +2 -2
  13. package/dist/modules/dashboards/lib/widgetScope.js +38 -0
  14. package/dist/modules/dashboards/lib/widgetScope.js.map +7 -0
  15. package/dist/modules/entities/lib/makeActivityRoute.js +265 -0
  16. package/dist/modules/entities/lib/makeActivityRoute.js.map +7 -0
  17. package/dist/modules/resources/api/activities.js +24 -232
  18. package/dist/modules/resources/api/activities.js.map +2 -2
  19. package/dist/modules/resources/commands/activities.js +3 -8
  20. package/dist/modules/resources/commands/activities.js.map +2 -2
  21. package/dist/modules/resources/commands/comments.js +2 -8
  22. package/dist/modules/resources/commands/comments.js.map +2 -2
  23. package/dist/modules/sales/api/dashboard/widgets/new-orders/route.js +27 -182
  24. package/dist/modules/sales/api/dashboard/widgets/new-orders/route.js.map +2 -2
  25. package/dist/modules/sales/api/dashboard/widgets/new-quotes/route.js +28 -183
  26. package/dist/modules/sales/api/dashboard/widgets/new-quotes/route.js.map +2 -2
  27. package/dist/modules/sales/api/order-line-statuses/route.js +15 -194
  28. package/dist/modules/sales/api/order-line-statuses/route.js.map +2 -2
  29. package/dist/modules/sales/api/order-lines/route.js +15 -281
  30. package/dist/modules/sales/api/order-lines/route.js.map +2 -2
  31. package/dist/modules/sales/api/order-statuses/route.js +15 -194
  32. package/dist/modules/sales/api/order-statuses/route.js.map +2 -2
  33. package/dist/modules/sales/api/payment-statuses/route.js +15 -194
  34. package/dist/modules/sales/api/payment-statuses/route.js.map +2 -2
  35. package/dist/modules/sales/api/quote-lines/route.js +15 -279
  36. package/dist/modules/sales/api/quote-lines/route.js.map +2 -2
  37. package/dist/modules/sales/api/shipment-statuses/route.js +15 -194
  38. package/dist/modules/sales/api/shipment-statuses/route.js.map +2 -2
  39. package/dist/modules/sales/components/PaymentMethodsSettings.js +3 -84
  40. package/dist/modules/sales/components/PaymentMethodsSettings.js.map +2 -2
  41. package/dist/modules/sales/components/ProviderFieldInput.js +86 -0
  42. package/dist/modules/sales/components/ProviderFieldInput.js.map +7 -0
  43. package/dist/modules/sales/components/ShippingMethodsSettings.js +3 -82
  44. package/dist/modules/sales/components/ShippingMethodsSettings.js.map +2 -2
  45. package/dist/modules/sales/lib/makeSalesLineRoute.js +308 -0
  46. package/dist/modules/sales/lib/makeSalesLineRoute.js.map +7 -0
  47. package/dist/modules/sales/lib/makeStatusDictionaryRoute.js +206 -0
  48. package/dist/modules/sales/lib/makeStatusDictionaryRoute.js.map +7 -0
  49. package/dist/modules/sales/widgets/dashboard/makeDashboardWidgetRoute.js +178 -0
  50. package/dist/modules/sales/widgets/dashboard/makeDashboardWidgetRoute.js.map +7 -0
  51. package/dist/modules/sales/widgets/dashboard/new-orders/widget.client.js +1 -39
  52. package/dist/modules/sales/widgets/dashboard/new-orders/widget.client.js.map +2 -2
  53. package/dist/modules/sales/widgets/dashboard/new-quotes/widget.client.js +1 -39
  54. package/dist/modules/sales/widgets/dashboard/new-quotes/widget.client.js.map +2 -2
  55. package/dist/modules/sales/widgets/dashboard/shared.js +46 -0
  56. package/dist/modules/sales/widgets/dashboard/shared.js.map +7 -0
  57. package/dist/modules/staff/api/activities.js +24 -232
  58. package/dist/modules/staff/api/activities.js.map +2 -2
  59. package/dist/modules/staff/backend/staff/leave-requests/[id]/page.js +14 -34
  60. package/dist/modules/staff/backend/staff/leave-requests/[id]/page.js.map +2 -2
  61. package/dist/modules/staff/backend/staff/my-leave-requests/[id]/page.js +15 -34
  62. package/dist/modules/staff/backend/staff/my-leave-requests/[id]/page.js.map +2 -2
  63. package/dist/modules/staff/commands/activities.js +3 -8
  64. package/dist/modules/staff/commands/activities.js.map +2 -2
  65. package/dist/modules/staff/commands/comments.js +2 -8
  66. package/dist/modules/staff/commands/comments.js.map +2 -2
  67. package/dist/modules/staff/lib/leaveRequestHelpers.js +41 -0
  68. package/dist/modules/staff/lib/leaveRequestHelpers.js.map +7 -0
  69. package/package.json +2 -2
  70. package/src/modules/currencies/backend/exchange-rates/[id]/page.tsx +20 -180
  71. package/src/modules/currencies/backend/exchange-rates/create/page.tsx +16 -175
  72. package/src/modules/currencies/lib/exchangeRateFormConfig.ts +200 -0
  73. package/src/modules/customers/api/dashboard/widgets/utils.ts +1 -53
  74. package/src/modules/customers/commands/activities.ts +2 -8
  75. package/src/modules/customers/commands/comments.ts +2 -8
  76. package/src/modules/dashboards/i18n/de.json +3 -0
  77. package/src/modules/dashboards/i18n/en.json +3 -0
  78. package/src/modules/dashboards/i18n/es.json +3 -0
  79. package/src/modules/dashboards/i18n/pl.json +3 -0
  80. package/src/modules/dashboards/lib/widgetScope.ts +53 -0
  81. package/src/modules/entities/lib/makeActivityRoute.ts +327 -0
  82. package/src/modules/resources/api/activities.ts +25 -269
  83. package/src/modules/resources/commands/activities.ts +2 -7
  84. package/src/modules/resources/commands/comments.ts +2 -8
  85. package/src/modules/sales/api/dashboard/widgets/new-orders/route.ts +29 -244
  86. package/src/modules/sales/api/dashboard/widgets/new-quotes/route.ts +30 -245
  87. package/src/modules/sales/api/order-line-statuses/route.ts +16 -209
  88. package/src/modules/sales/api/order-lines/route.ts +16 -300
  89. package/src/modules/sales/api/order-statuses/route.ts +16 -209
  90. package/src/modules/sales/api/payment-statuses/route.ts +16 -209
  91. package/src/modules/sales/api/quote-lines/route.ts +16 -298
  92. package/src/modules/sales/api/shipment-statuses/route.ts +16 -209
  93. package/src/modules/sales/components/PaymentMethodsSettings.tsx +3 -88
  94. package/src/modules/sales/components/ProviderFieldInput.tsx +85 -0
  95. package/src/modules/sales/components/ShippingMethodsSettings.tsx +3 -86
  96. package/src/modules/sales/lib/makeSalesLineRoute.ts +345 -0
  97. package/src/modules/sales/lib/makeStatusDictionaryRoute.ts +229 -0
  98. package/src/modules/sales/widgets/dashboard/makeDashboardWidgetRoute.ts +247 -0
  99. package/src/modules/sales/widgets/dashboard/new-orders/widget.client.tsx +7 -50
  100. package/src/modules/sales/widgets/dashboard/new-quotes/widget.client.tsx +7 -49
  101. package/src/modules/sales/widgets/dashboard/shared.ts +44 -0
  102. package/src/modules/staff/api/activities.ts +25 -269
  103. package/src/modules/staff/backend/staff/leave-requests/[id]/page.tsx +15 -69
  104. package/src/modules/staff/backend/staff/my-leave-requests/[id]/page.tsx +16 -65
  105. package/src/modules/staff/commands/activities.ts +2 -7
  106. package/src/modules/staff/commands/comments.ts +2 -8
  107. package/src/modules/staff/lib/leaveRequestHelpers.ts +78 -0
@@ -0,0 +1,345 @@
1
+ import { z } from 'zod'
2
+ import { makeCrudRoute, type CrudCtx } from '@open-mercato/shared/lib/crud/factory'
3
+ import { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'
4
+ import { CrudHttpError } from '@open-mercato/shared/lib/crud/errors'
5
+ import {
6
+ buildCustomFieldFiltersFromQuery,
7
+ extractAllCustomFieldEntries,
8
+ } from '@open-mercato/shared/lib/crud/custom-fields'
9
+ import {
10
+ canonicalizeUnitCode,
11
+ REFERENCE_UNIT_CODES,
12
+ } from '@open-mercato/shared/lib/units/unitCodes'
13
+ import {
14
+ createPagedListResponseSchema,
15
+ createSalesCrudOpenApi,
16
+ defaultOkResponseSchema,
17
+ } from '../api/openapi'
18
+ import { withScopedPayload } from '../api/utils'
19
+
20
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any -- MikroORM entity class constructor
21
+ type EntityClass = new (...args: any[]) => unknown
22
+
23
+ interface SalesLineRouteConfig {
24
+ entity: EntityClass
25
+ entityId: string
26
+ fieldConstants: Record<string, string>
27
+ parentFkColumn: string
28
+ parentFkParam: string
29
+ createSchema: z.ZodObject<z.ZodRawShape>
30
+ features: { view: string; manage: string }
31
+ commandPrefix: string
32
+ openApi: {
33
+ resourceName: string
34
+ description: string
35
+ }
36
+ }
37
+
38
+ const rawBodySchema = z.object({}).passthrough()
39
+
40
+ function resolveRawBody(raw: unknown): Record<string, unknown> {
41
+ if (!raw || typeof raw !== 'object') return {}
42
+ if ('body' in raw) {
43
+ const payload = raw as { body?: unknown }
44
+ if (payload.body && typeof payload.body === 'object') {
45
+ return payload.body as Record<string, unknown>
46
+ }
47
+ }
48
+ return raw as Record<string, unknown>
49
+ }
50
+
51
+ function transformItem(item: Record<string, unknown> | null | undefined) {
52
+ if (!item) return item
53
+ const normalized = { ...item }
54
+ const cfEntries = extractAllCustomFieldEntries(item)
55
+ for (const key of Object.keys(normalized)) {
56
+ if (key.startsWith('cf:')) delete normalized[key]
57
+ }
58
+ const quantityUnit = canonicalizeUnitCode(
59
+ normalized['quantity_unit'] ?? normalized['quantityUnit'],
60
+ )
61
+ const normalizedUnit =
62
+ canonicalizeUnitCode(
63
+ normalized['normalized_unit'] ?? normalized['normalizedUnit'],
64
+ ) ?? quantityUnit
65
+ return {
66
+ ...normalized,
67
+ quantity_unit: quantityUnit,
68
+ normalized_unit: normalizedUnit,
69
+ ...cfEntries,
70
+ }
71
+ }
72
+
73
+ const uomSnapshotOpenApiSchema = z
74
+ .object({
75
+ version: z.literal(1),
76
+ productId: z.string().nullable(),
77
+ productVariantId: z.string().nullable(),
78
+ baseUnitCode: z.string().nullable(),
79
+ enteredUnitCode: z.string().nullable(),
80
+ enteredQuantity: z.string(),
81
+ toBaseFactor: z.string(),
82
+ normalizedQuantity: z.string(),
83
+ rounding: z.object({
84
+ mode: z.enum(['half_up', 'down', 'up']),
85
+ scale: z.number().int(),
86
+ }),
87
+ source: z.object({
88
+ conversionId: z.string().nullable(),
89
+ resolvedAt: z.string(),
90
+ }),
91
+ unitPriceReference: z
92
+ .object({
93
+ enabled: z.boolean(),
94
+ referenceUnitCode: z.enum(REFERENCE_UNIT_CODES).nullable(),
95
+ baseQuantity: z.string().nullable(),
96
+ grossPerReference: z.string().nullable().optional(),
97
+ netPerReference: z.string().nullable().optional(),
98
+ })
99
+ .optional(),
100
+ })
101
+ .nullable()
102
+ .optional()
103
+
104
+ export function makeSalesLineRoute(config: SalesLineRouteConfig) {
105
+ const {
106
+ entity,
107
+ entityId,
108
+ fieldConstants: F,
109
+ parentFkColumn,
110
+ parentFkParam,
111
+ createSchema,
112
+ features,
113
+ commandPrefix,
114
+ } = config
115
+
116
+ const listSchema = z
117
+ .object({
118
+ page: z.coerce.number().min(1).default(1),
119
+ pageSize: z.coerce.number().min(1).max(100).default(50),
120
+ id: z.string().uuid().optional(),
121
+ [parentFkParam]: z.string().uuid().optional(),
122
+ sortField: z.string().optional(),
123
+ sortDir: z.enum(['asc', 'desc']).optional(),
124
+ })
125
+ .passthrough()
126
+
127
+ const upsertSchema = createSchema.extend({
128
+ id: z.string().uuid().optional(),
129
+ })
130
+
131
+ const deleteSchema = z.object({
132
+ id: z.string().uuid(),
133
+ [parentFkParam]: z.string().uuid(),
134
+ })
135
+
136
+ const routeMetadata = {
137
+ GET: { requireAuth: true, requireFeatures: [features.view] },
138
+ POST: { requireAuth: true, requireFeatures: [features.manage] },
139
+ PUT: { requireAuth: true, requireFeatures: [features.manage] },
140
+ DELETE: { requireAuth: true, requireFeatures: [features.manage] },
141
+ }
142
+
143
+ const crud = makeCrudRoute({
144
+ metadata: routeMetadata,
145
+ orm: {
146
+ entity,
147
+ idField: 'id',
148
+ orgField: 'organizationId',
149
+ tenantField: 'tenantId',
150
+ softDeleteField: 'deletedAt',
151
+ },
152
+ indexer: {
153
+ entityType: entityId,
154
+ },
155
+ list: {
156
+ schema: listSchema,
157
+ entityId,
158
+ fields: [
159
+ F.id,
160
+ parentFkColumn,
161
+ F.line_number,
162
+ F.kind,
163
+ F.status_entry_id,
164
+ F.status,
165
+ F.product_id,
166
+ F.product_variant_id,
167
+ F.catalog_snapshot,
168
+ F.name,
169
+ F.description,
170
+ F.comment,
171
+ F.organization_id,
172
+ F.tenant_id,
173
+ F.quantity,
174
+ F.quantity_unit,
175
+ F.normalized_quantity,
176
+ F.normalized_unit,
177
+ F.uom_snapshot,
178
+ F.currency_code,
179
+ F.unit_price_net,
180
+ F.unit_price_gross,
181
+ F.discount_amount,
182
+ F.discount_percent,
183
+ F.tax_rate,
184
+ F.tax_amount,
185
+ F.total_net_amount,
186
+ F.total_gross_amount,
187
+ F.configuration,
188
+ F.promotion_code,
189
+ F.promotion_snapshot,
190
+ F.metadata,
191
+ F.custom_field_set_id,
192
+ F.created_at,
193
+ F.updated_at,
194
+ ],
195
+ sortFieldMap: {
196
+ createdAt: F.created_at,
197
+ updatedAt: F.updated_at,
198
+ lineNumber: F.line_number,
199
+ },
200
+ buildFilters: async (query: Record<string, unknown>, ctx: CrudCtx) => {
201
+ const filters: Record<string, unknown> = {}
202
+ if (query.id) filters.id = { $eq: query.id }
203
+ if (query[parentFkParam]) filters[parentFkColumn] = { $eq: query[parentFkParam] }
204
+ try {
205
+ const em = ctx.container.resolve('em')
206
+ const cfFilters = await buildCustomFieldFiltersFromQuery({
207
+ entityId,
208
+ query,
209
+ em,
210
+ tenantId: ctx.auth?.tenantId ?? null,
211
+ })
212
+ Object.assign(filters, cfFilters)
213
+ } catch {
214
+ // ignore
215
+ }
216
+ return filters
217
+ },
218
+ transformItem,
219
+ },
220
+ actions: {
221
+ create: {
222
+ commandId: `${commandPrefix}.upsert`,
223
+ schema: rawBodySchema,
224
+ mapInput: async ({ raw, ctx }: { raw: unknown; ctx: CrudCtx }) => {
225
+ const { translate } = await resolveTranslations()
226
+ const payload = upsertSchema.parse(
227
+ withScopedPayload(resolveRawBody(raw) ?? {}, ctx, translate),
228
+ )
229
+ return { body: payload }
230
+ },
231
+ response: ({ result }: { result: Record<string, unknown> | null }) => ({
232
+ id: result?.lineId ?? null,
233
+ [parentFkParam]: result?.[parentFkParam] ?? null,
234
+ }),
235
+ status: 201,
236
+ },
237
+ update: {
238
+ commandId: `${commandPrefix}.upsert`,
239
+ schema: rawBodySchema,
240
+ mapInput: async ({ raw, ctx }: { raw: unknown; ctx: CrudCtx }) => {
241
+ const { translate } = await resolveTranslations()
242
+ const payload = upsertSchema.parse(
243
+ withScopedPayload(resolveRawBody(raw) ?? {}, ctx, translate),
244
+ )
245
+ return { body: payload }
246
+ },
247
+ response: ({ result }: { result: Record<string, unknown> | null }) => ({
248
+ id: result?.lineId ?? null,
249
+ [parentFkParam]: result?.[parentFkParam] ?? null,
250
+ }),
251
+ },
252
+ delete: {
253
+ commandId: `${commandPrefix}.delete`,
254
+ schema: rawBodySchema,
255
+ mapInput: async ({ raw, ctx }: { raw: unknown; ctx: CrudCtx }) => {
256
+ const { translate } = await resolveTranslations()
257
+ const payload = deleteSchema.parse(
258
+ withScopedPayload(resolveRawBody(raw) ?? {}, ctx, translate),
259
+ )
260
+ if (!payload.id || !payload[parentFkParam]) {
261
+ throw new CrudHttpError(400, {
262
+ error: translate(
263
+ 'sales.documents.detail.error',
264
+ 'Document not found or inaccessible.',
265
+ ),
266
+ })
267
+ }
268
+ return { body: payload }
269
+ },
270
+ response: () => ({ ok: true }),
271
+ },
272
+ },
273
+ })
274
+
275
+ const lineItemSchema = z.object({
276
+ id: z.string().uuid(),
277
+ [parentFkColumn]: z.string().uuid(),
278
+ line_number: z.number(),
279
+ kind: z.string(),
280
+ status_entry_id: z.string().uuid().nullable().optional(),
281
+ status: z.string().nullable().optional(),
282
+ product_id: z.string().uuid().nullable().optional(),
283
+ product_variant_id: z.string().uuid().nullable().optional(),
284
+ catalog_snapshot: z.record(z.string(), z.unknown()).nullable().optional(),
285
+ name: z.string().nullable().optional(),
286
+ description: z.string().nullable().optional(),
287
+ comment: z.string().nullable().optional(),
288
+ quantity: z.number(),
289
+ quantity_unit: z.string().nullable().optional(),
290
+ normalized_quantity: z.number(),
291
+ normalized_unit: z.string().nullable().optional(),
292
+ uom_snapshot: uomSnapshotOpenApiSchema,
293
+ currency_code: z.string(),
294
+ unit_price_net: z.number(),
295
+ unit_price_gross: z.number(),
296
+ discount_amount: z.number(),
297
+ discount_percent: z.number(),
298
+ tax_rate: z.number(),
299
+ tax_amount: z.number(),
300
+ total_net_amount: z.number(),
301
+ total_gross_amount: z.number(),
302
+ configuration: z.record(z.string(), z.unknown()).nullable().optional(),
303
+ promotion_code: z.string().nullable().optional(),
304
+ promotion_snapshot: z.record(z.string(), z.unknown()).nullable().optional(),
305
+ metadata: z.record(z.string(), z.unknown()).nullable().optional(),
306
+ custom_field_set_id: z.string().uuid().nullable().optional(),
307
+ created_at: z.string(),
308
+ updated_at: z.string(),
309
+ })
310
+
311
+ const upsertResponseSchema = z.object({
312
+ id: z.string().uuid().nullable(),
313
+ [parentFkParam]: z.string().uuid().nullable(),
314
+ })
315
+
316
+ const openApi = createSalesCrudOpenApi({
317
+ resourceName: config.openApi.resourceName,
318
+ querySchema: listSchema,
319
+ listResponseSchema: createPagedListResponseSchema(lineItemSchema),
320
+ create: {
321
+ schema: upsertSchema,
322
+ responseSchema: upsertResponseSchema,
323
+ description: `Creates ${config.openApi.description}.`,
324
+ },
325
+ update: {
326
+ schema: upsertSchema,
327
+ responseSchema: upsertResponseSchema,
328
+ description: `Updates ${config.openApi.description}.`,
329
+ },
330
+ del: {
331
+ schema: deleteSchema,
332
+ responseSchema: defaultOkResponseSchema,
333
+ description: `Deletes ${config.openApi.description}.`,
334
+ },
335
+ })
336
+
337
+ return {
338
+ metadata: routeMetadata,
339
+ openApi,
340
+ GET: crud.GET,
341
+ POST: crud.POST,
342
+ PUT: crud.PUT,
343
+ DELETE: crud.DELETE,
344
+ }
345
+ }
@@ -0,0 +1,229 @@
1
+ import { z } from 'zod'
2
+ import { makeCrudRoute, type CrudCtx } from '@open-mercato/shared/lib/crud/factory'
3
+ import type { EntityManager } from '@mikro-orm/postgresql'
4
+ import { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'
5
+ import { CrudHttpError } from '@open-mercato/shared/lib/crud/errors'
6
+ import { Dictionary, DictionaryEntry } from '@open-mercato/core/modules/dictionaries/data/entities'
7
+ import { statusDictionaryCreateSchema, statusDictionaryUpdateSchema } from '../data/validators'
8
+ import { getSalesDictionaryDefinition, ensureSalesDictionary, type SalesDictionaryKind } from './dictionaries'
9
+ import { parseScopedCommandInput, resolveCrudRecordId } from '../api/utils'
10
+ import {
11
+ createPagedListResponseSchema,
12
+ createSalesCrudOpenApi,
13
+ defaultDeleteRequestSchema,
14
+ } from '../api/openapi'
15
+ import { escapeLikePattern } from '@open-mercato/shared/lib/db/escapeLikePattern'
16
+
17
+ interface StatusDictionaryRouteConfig {
18
+ kind: SalesDictionaryKind
19
+ entityId: string
20
+ fieldConstants: Record<string, string>
21
+ openApi: {
22
+ resourceName: string
23
+ pluralName: string
24
+ description: string
25
+ }
26
+ }
27
+
28
+ export function makeStatusDictionaryRoute(config: StatusDictionaryRouteConfig) {
29
+ const { kind, entityId, fieldConstants: F } = config
30
+ const definition = getSalesDictionaryDefinition(kind)
31
+
32
+ const rawBodySchema = z.object({}).passthrough()
33
+
34
+ const listSchema = z
35
+ .object({
36
+ page: z.coerce.number().min(1).default(1),
37
+ pageSize: z.coerce.number().min(1).max(100).default(50),
38
+ search: z.string().optional(),
39
+ sortField: z.string().optional(),
40
+ sortDir: z.enum(['asc', 'desc']).optional(),
41
+ })
42
+ .passthrough()
43
+
44
+ const metadata = {
45
+ GET: { requireAuth: true, requireFeatures: ['sales.settings.manage'] },
46
+ POST: { requireAuth: true, requireFeatures: ['sales.settings.manage'] },
47
+ PUT: { requireAuth: true, requireFeatures: ['sales.settings.manage'] },
48
+ DELETE: { requireAuth: true, requireFeatures: ['sales.settings.manage'] },
49
+ }
50
+
51
+ const dictionaryItemSchema = z.object({
52
+ id: z.string().uuid(),
53
+ value: z.string(),
54
+ label: z.string().nullable(),
55
+ color: z.string().nullable(),
56
+ icon: z.string().nullable(),
57
+ organizationId: z.string().uuid().nullable(),
58
+ tenantId: z.string().uuid().nullable(),
59
+ createdAt: z.string(),
60
+ updatedAt: z.string(),
61
+ })
62
+
63
+ const dictionaryListResponseSchema = createPagedListResponseSchema(dictionaryItemSchema)
64
+
65
+ const normalizeId = (value: unknown): string | null => {
66
+ if (typeof value !== 'string') return null
67
+ const trimmed = value.trim()
68
+ return trimmed.length > 0 ? trimmed : null
69
+ }
70
+
71
+ async function resolveDictionaryContext(ctx: CrudCtx): Promise<{ dictionaryId: string; organizationId: string | null }> {
72
+ if (!ctx.auth || !ctx.auth.tenantId) {
73
+ throw new CrudHttpError(401, { error: 'Tenant context is required.' })
74
+ }
75
+ const em = ctx.container.resolve('em') as EntityManager
76
+ const tenantId: string = ctx.auth.tenantId
77
+ const candidateOrgIds = new Set<string>()
78
+ const pushCandidate = (value: unknown) => {
79
+ const normalized = normalizeId(value)
80
+ if (normalized) candidateOrgIds.add(normalized)
81
+ }
82
+ pushCandidate(ctx.selectedOrganizationId)
83
+ pushCandidate(ctx.auth.orgId ?? null)
84
+ const scope = ctx.organizationScope
85
+ if (scope) {
86
+ if (Array.isArray(scope.filterIds)) {
87
+ for (const id of scope.filterIds) pushCandidate(id)
88
+ }
89
+ if (Array.isArray(scope.allowedIds)) {
90
+ for (const id of scope.allowedIds) pushCandidate(id)
91
+ }
92
+ }
93
+
94
+ for (const orgId of candidateOrgIds) {
95
+ const dictionary = await ensureSalesDictionary({
96
+ em,
97
+ tenantId,
98
+ organizationId: orgId,
99
+ kind,
100
+ })
101
+ if (dictionary) {
102
+ return { dictionaryId: dictionary.id, organizationId: orgId }
103
+ }
104
+ }
105
+
106
+ const fallback = await em.findOne(
107
+ Dictionary,
108
+ {
109
+ tenantId,
110
+ key: definition.key,
111
+ deletedAt: null,
112
+ },
113
+ { orderBy: { createdAt: 'asc' } },
114
+ )
115
+ if (fallback) {
116
+ return { dictionaryId: fallback.id, organizationId: fallback.organizationId }
117
+ }
118
+ throw new CrudHttpError(400, { error: 'Organization context is required.' })
119
+ }
120
+
121
+ const crud = makeCrudRoute({
122
+ metadata,
123
+ orm: {
124
+ entity: DictionaryEntry,
125
+ idField: 'id',
126
+ orgField: 'organizationId',
127
+ tenantField: 'tenantId',
128
+ softDeleteField: null,
129
+ },
130
+ list: {
131
+ schema: listSchema,
132
+ entityId,
133
+ fields: [
134
+ F.id,
135
+ F.value,
136
+ F.label,
137
+ F.color,
138
+ F.icon,
139
+ F.organization_id,
140
+ F.tenant_id,
141
+ F.created_at,
142
+ F.updated_at,
143
+ ],
144
+ sortFieldMap: {
145
+ id: F.id,
146
+ value: F.value,
147
+ label: F.label,
148
+ createdAt: F.created_at,
149
+ updatedAt: F.updated_at,
150
+ },
151
+ buildFilters: async (query, ctx) => {
152
+ const { dictionaryId } = await resolveDictionaryContext(ctx)
153
+ const filters: Record<string, unknown> = {
154
+ dictionary_id: dictionaryId,
155
+ }
156
+ if (query.search && query.search.trim().length > 0) {
157
+ const term = `%${escapeLikePattern(query.search.trim())}%`
158
+ filters.$or = [
159
+ { [F.value]: { $ilike: term } },
160
+ { [F.label]: { $ilike: term } },
161
+ ]
162
+ }
163
+ return filters
164
+ },
165
+ transformItem: (item: Record<string, unknown>) => ({
166
+ id: item.id,
167
+ value: item.value,
168
+ label: item.label,
169
+ color: item.color ?? null,
170
+ icon: item.icon ?? null,
171
+ organizationId: item.organization_id ?? null,
172
+ tenantId: item.tenant_id ?? null,
173
+ createdAt: item.created_at,
174
+ updatedAt: item.updated_at,
175
+ }),
176
+ },
177
+ actions: {
178
+ create: {
179
+ commandId: `${definition.commandPrefix}.create`,
180
+ schema: rawBodySchema,
181
+ mapInput: async ({ raw, ctx }) => {
182
+ const { translate } = await resolveTranslations()
183
+ return parseScopedCommandInput(statusDictionaryCreateSchema, raw ?? {}, ctx, translate)
184
+ },
185
+ response: ({ result }) => ({ id: result?.entryId ?? null }),
186
+ status: 201,
187
+ },
188
+ update: {
189
+ commandId: `${definition.commandPrefix}.update`,
190
+ schema: rawBodySchema,
191
+ mapInput: async ({ raw, ctx }) => {
192
+ const { translate } = await resolveTranslations()
193
+ return parseScopedCommandInput(statusDictionaryUpdateSchema, raw ?? {}, ctx, translate)
194
+ },
195
+ response: () => ({ ok: true }),
196
+ },
197
+ delete: {
198
+ commandId: `${definition.commandPrefix}.delete`,
199
+ schema: rawBodySchema,
200
+ mapInput: async ({ parsed, ctx }) => {
201
+ const { translate } = await resolveTranslations()
202
+ const id = resolveCrudRecordId(parsed, ctx, translate)
203
+ return { id }
204
+ },
205
+ response: () => ({ ok: true }),
206
+ },
207
+ },
208
+ })
209
+
210
+ const openApi = createSalesCrudOpenApi({
211
+ resourceName: config.openApi.resourceName,
212
+ pluralName: config.openApi.pluralName,
213
+ description: config.openApi.description,
214
+ querySchema: listSchema,
215
+ listResponseSchema: dictionaryListResponseSchema,
216
+ create: { schema: statusDictionaryCreateSchema },
217
+ update: { schema: statusDictionaryUpdateSchema },
218
+ del: { schema: defaultDeleteRequestSchema },
219
+ })
220
+
221
+ return {
222
+ metadata,
223
+ openApi,
224
+ GET: crud.GET,
225
+ POST: crud.POST,
226
+ PUT: crud.PUT,
227
+ DELETE: crud.DELETE,
228
+ }
229
+ }