1 import { SettingsTypes } from "@medusajs/framework/types"
2 import {
3 GraphQLEnumType,
4 GraphQLObjectType,
5 isEnumType,
6 isScalarType,
7 Kind,
8 } from "@medusajs/framework/utils"
9 import { getComputedColumnRegistry } from "./computed-columns"
10 import {
11 DiscoveredEntity,
12 EntityDiscoveryService,
13 getUnderlyingType,
14 isArrayField,
15 isSingleRelationship,
16 SchemaTypeMap,
17 } from "./entity-discovery"
18 import {
19 EntityOverride,
20 getAdditionalTypes,
21 getDefaultVisibleFields,
22 getEntityOverride,
23 getFieldFilterRules,
24 getFieldMetadata,
25 getFieldOrdering,
26 getFieldRenderModes,
27 getNonFilterableFields,
28 getNonSortableFields,
29 } from "./entity-overrides"
30 import {
31 buildFilterConfig,
32 FieldFilterRules,
33 shouldExcludeField,
34 } from "./filter-rules"
35 import { getRelationshipFilterConfig } from "./relationship-filters"
36 import {
37 inferDataType,
38 inferRenderMode,
39 RenderMode,
40 } from "./render-mode-mapper"
41
42 // Re-export the AdminColumn type from types for convenience
43 export type ViewConfigurationColumn = SettingsTypes.ViewConfigurationColumnDTO
44
45 /**
46 * Property label data for customizing column names.
47 */
48 export interface PropertyLabel {
49 id: string
50 entity: string
51 property: string
52 label: string
53 description?: string | null
54 }
55
56 /**
57 * Resolve the real (stored) values of a GraphQL enum.
58 *
59 * DML-generated enums uppercase the member name and keep the real stored value
60 * in an `@enumValue(value: "...")` directive (e.g. `STANDARD @enumValue(value:
61 * "standard")`). Honor that directive so filters use the value the DB actually
62 * stores; fall back to the member value for enums declared without it.
63 */
64 function getEnumValues(enumType: GraphQLEnumType): string[] {
65 return enumType.getValues().map((value) => {
66 const directive = value.astNode?.directives?.find(
67 (d) => d.name.value === "enumValue"
68 )
69 const arg = directive?.arguments?.find((a) => a.name.value === "value")
70 if (arg?.value.kind === Kind.STRING) {
71 return arg.value.value
72 }
73 return String(value.value)
74 })
75 }
76
77 /**
78 * Format a field name to display name.
79 */
80 function formatFieldName(fieldName: string): string {
81 return fieldName
82 .replace(/_/g, " ")
83 .replace(/([A-Z])/g, " $1")
84 .replace(/^\s+/, "")
85 .split(" ")
86 .map((word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())
87 .join(" ")
88 }
89
90 /**
91 * Map semantic type to a valid column category.
92 */
93 function semanticTypeToCategory(
94 semanticType: string | undefined
95 ): ViewConfigurationColumn["category"] {
96 switch (semanticType) {
97 case "identifier":
98 return "identifier"
99 case "timestamp":
100 return "timestamp"
101 case "status":
102 return "status"
103 case "currency":
104 case "count":
105 return "metric"
106 default:
107 return "field"
108 }
109 }
110
111 /**
112 * Generate columns for an entity using the entity discovery service.
113 */
114 export function generateEntityColumns(
115 entityDiscovery: EntityDiscoveryService,
116 entityKey: string,
117 propertyLabels?: Map<string, PropertyLabel>,
118 customOverride?: EntityOverride
119 ): ViewConfigurationColumn[] | null {
120 if (!entityDiscovery.isInitialized()) {
121 return null
122 }
123
124 const entity = entityDiscovery.getEntity(entityKey)
125 if (!entity) {
126 return null
127 }
128
129 const override = customOverride || getEntityOverride(entity.name)
130 const filterRules = getFieldFilterRules(entity.name, override)
131 const defaultVisibleFields = getDefaultVisibleFields(entity.name, override)
132 const defaultFieldOrdering = getFieldOrdering(entity.name, override)
133 const fieldRenderModes = getFieldRenderModes(entity.name, override)
134 const fieldMetadata = getFieldMetadata(entity.name, override)
135 const additionalTypes = getAdditionalTypes(entity.name, override)
136 const nonFilterableFields = getNonFilterableFields(entity.name, override)
137 const nonSortableFields = getNonSortableFields(entity.name, override)
138
139 const schemaTypeMap = entityDiscovery.getSchemaTypeMap()
140 const columns: ViewConfigurationColumn[] = []
141 const processedFields = new Set<string>()
142
143 // Process main entity type
144 processEntityType(
145 schemaTypeMap,
146 entity.graphqlType,
147 entity,
148 columns,
149 processedFields,
150 filterRules,
151 defaultVisibleFields,
152 defaultFieldOrdering,
153 fieldRenderModes,
154 fieldMetadata,
155 nonFilterableFields,
156 nonSortableFields,
157 propertyLabels
158 )
159
160 // Process additional types (e.g., OrderDetail for Order)
161 for (const additionalType of additionalTypes) {
162 const type = schemaTypeMap[additionalType] as GraphQLObjectType | undefined
163 if (type) {
164 processEntityType(
165 schemaTypeMap,
166 additionalType,
167 entity,
168 columns,
169 processedFields,
170 filterRules,
171 defaultVisibleFields,
172 defaultFieldOrdering,
173 fieldRenderModes,
174 fieldMetadata,
175 nonFilterableFields,
176 nonSortableFields,
177 propertyLabels
178 )
179 }
180 }
181
182 // Add computed columns
183 const computedColumnRegistry = getComputedColumnRegistry()
184 const computedColumns = computedColumnRegistry.get(entity.name)
185
186 for (const computed of computedColumns) {
187 const columnId = computed.id
188 if (processedFields.has(columnId)) {
189 continue
190 }
191
192 const label = propertyLabels?.get(columnId)
193 const hasCustomLabel = !!label
194
195 columns.push({
196 id: columnId,
197 name: label?.label || computed.name,
198 description: label?.description || computed.description,
199 field: columnId,
200 sortable: computed.sortable ?? false,
201 hideable: true,
202 default_visible:
203 computed.defaultVisible || defaultVisibleFields.includes(columnId),
204 data_type: (computed.dataType ??
205 "string") as ViewConfigurationColumn["data_type"],
206 semantic_type: computed.renderMode ? "computed" : "relationship",
207 context: computed.context ?? "display",
208 // Only display columns carry a compute (render + required fields);
209 // filter-only injected columns omit it.
210 computed: computed.renderMode
211 ? {
212 type: computed.renderMode,
213 required_fields: computed.requiredFields ?? [],
214 optional_fields: computed.optionalFields || [],
215 }
216 : undefined,
217 metadata: computed.metadata,
218 render_mode: computed.renderMode,
219 default_order: defaultFieldOrdering[columnId] || 850,
220 category:
221 (computed.category as ViewConfigurationColumn["category"]) ||
222 "computed",
223 filter: computed.filter ?? { enabled: false },
224 source: { module: entity.module, entity: entity.name },
225 custom_label: hasCustomLabel,
226 label_id: label?.id,
227 })
228 }
229
230 // Sort columns by default_order
231 columns.sort((a, b) => (a.default_order || 1000) - (b.default_order || 1000))
232
233 return columns
234 }
235
236 /**
237 * Process a GraphQL type and add columns.
238 */
239 function processEntityType(
240 schemaTypeMap: SchemaTypeMap,
241 typeName: string,
242 entity: DiscoveredEntity,
243 columns: ViewConfigurationColumn[],
244 processedFields: Set<string>,
245 filterRules: FieldFilterRules,
246 defaultVisibleFields: string[],
247 defaultFieldOrdering: Record<string, number>,
248 fieldRenderModes: Record<string, RenderMode>,
249 fieldMetadata: Record<string, Record<string, any>>,
250 nonFilterableFields: string[],
251 nonSortableFields: string[],
252 propertyLabels?: Map<string, PropertyLabel>,
253 parentPath: string = ""
254 ): void {
255 const type = schemaTypeMap[typeName] as GraphQLObjectType | undefined
256 if (!type || !type.getFields) {
257 return
258 }
259
260 const fields = type.getFields()
261
262 // Foreign keys made redundant by a single relationship of the same name
263 // (e.g. collection_id -> collection.id). The relationship's `.id` column
264 // covers both filtering and display, so drop the raw FK to avoid duplicates.
265 const redundantForeignKeys = new Set<string>()
266 if (!parentPath) {
267 for (const [fieldName, fieldDef] of Object.entries(fields)) {
268 const fieldType = (fieldDef as any).type
269 if (
270 isSingleRelationship(fieldType) &&
271 getUnderlyingType(fieldType) instanceof GraphQLObjectType
272 ) {
273 redundantForeignKeys.add(`${fieldName}_id`)
274 }
275 }
276 }
277
278 for (const [fieldName, fieldDef] of Object.entries(fields)) {
279 const fullPath = parentPath ? `${parentPath}.${fieldName}` : fieldName
280
281 // Skip if already processed
282 if (processedFields.has(fullPath)) {
283 continue
284 }
285
286 // Skip excluded fields
287 if (shouldExcludeField(fieldName, filterRules)) {
288 continue
289 }
290
291 // Skip FKs covered by their relationship's `.id` column
292 if (redundantForeignKeys.has(fullPath)) {
293 continue
294 }
295
296 const fieldType = (fieldDef as any).type
297 const underlyingType = getUnderlyingType(fieldType)
298 const isArray = isArrayField(fieldType)
299
300 // Handle scalar and enum types
301 if (isScalarType(underlyingType) || isEnumType(underlyingType)) {
302 const dataType = inferDataType(underlyingType, fieldName)
303 const { renderMode: inferredRenderMode, semanticType } = inferRenderMode(
304 fieldName,
305 underlyingType
306 )
307 const renderMode = fieldRenderModes[fullPath] ?? inferredRenderMode
308
309 const label = propertyLabels?.get(fullPath)
310 const hasCustomLabel = !!label
311
312 processedFields.add(fullPath)
313
314 const filter = nonFilterableFields.includes(fullPath)
315 ? { enabled: false }
316 : buildFilterConfig(
317 fieldName,
318 dataType,
319 false,
320 semanticType,
321 isEnumType(underlyingType)
322 ? getEnumValues(underlyingType)
323 : undefined
324 )
325
326 columns.push({
327 id: fullPath,
328 name: label?.label || formatFieldName(fieldName),
329 description: label?.description || undefined,
330 field: fullPath,
331 sortable:
332 !parentPath &&
333 dataType !== "object" &&
334 !nonSortableFields.includes(fullPath), // Only top-level fields are sortable
335 hideable: true,
336 default_visible: defaultVisibleFields.includes(fullPath),
337 data_type: dataType,
338 semantic_type: semanticType,
339 context: "both",
340 render_mode: renderMode,
341 metadata: fieldMetadata[fullPath],
342 default_order: defaultFieldOrdering[fullPath] || 900,
343 category: parentPath
344 ? "relationship"
345 : semanticTypeToCategory(semanticType),
346 filter,
347 source: { module: entity.module, entity: entity.name },
348 custom_label: hasCustomLabel,
349 label_id: label?.id,
350 })
351 }
352 // Handle single relationships (many-to-one, one-to-one)
353 else if (
354 isSingleRelationship(fieldType) &&
355 underlyingType instanceof GraphQLObjectType
356 ) {
357 // Process nested fields with dot notation (one level deep)
358 if (!parentPath) {
359 const relatedTypeName = underlyingType.name
360 const shouldIncludeRelationship = true
361
362 // Get scalar fields from the related entity
363 const relatedFields = underlyingType.getFields()
364
365 // Process all scalar fields of the relationship
366 for (const [relatedFieldName, relatedFieldDef] of Object.entries(
367 relatedFields
368 )) {
369 const nestedPath = `${fieldName}.${relatedFieldName}`
370 const nestedFieldType = (relatedFieldDef as any).type
371 const nestedUnderlyingType = getUnderlyingType(nestedFieldType)
372
373 // Only include scalar fields (not nested objects or arrays)
374 if (
375 isScalarType(nestedUnderlyingType) &&
376 !processedFields.has(nestedPath)
377 ) {
378 const dataType = inferDataType(
379 nestedUnderlyingType,
380 relatedFieldName
381 )
382 const { renderMode: inferredRenderMode, semanticType } =
383 inferRenderMode(relatedFieldName, nestedUnderlyingType)
384 const renderMode =
385 fieldRenderModes[nestedPath] ?? inferredRenderMode
386
387 const label = propertyLabels?.get(nestedPath)
388 const hasCustomLabel = !!label
389
390 processedFields.add(nestedPath)
391
392 const filter = nonFilterableFields.includes(nestedPath)
393 ? { enabled: false }
394 : buildFilterConfig(
395 relatedFieldName,
396 dataType,
397 false,
398 semanticType,
399 isEnumType(nestedUnderlyingType)
400 ? getEnumValues(nestedUnderlyingType)
401 : undefined
402 )
403
404 // Note: nested .id paths in nonFilterableFields produce
405 // { enabled: false, relationship: {...} }; not currently reachable.
406 if (shouldIncludeRelationship && relatedFieldName === "id") {
407 const relationshipFilter = getRelationshipFilterConfig(
408 entity.name,
409 fieldName,
410 relatedTypeName,
411 false,
412 schemaTypeMap
413 )
414 if (relationshipFilter) {
415 filter.relationship = relationshipFilter
416 }
417 }
418
419 columns.push({
420 id: nestedPath,
421 name:
422 label?.label ||
423 `${formatFieldName(fieldName)} ${formatFieldName(
424 relatedFieldName
425 )}`,
426 description: label?.description || undefined,
427 field: nestedPath,
428 sortable: false,
429 hideable: true,
430 default_visible: defaultVisibleFields.includes(nestedPath),
431 data_type: dataType,
432 semantic_type: semanticType,
433 context: "both",
434 render_mode: renderMode,
435 metadata: fieldMetadata[nestedPath],
436 default_order: defaultFieldOrdering[nestedPath] || 950,
437 category: "relationship",
438 filter,
439 source: { module: entity.module, entity: entity.name },
440 custom_label: hasCustomLabel,
441 label_id: label?.id,
442 })
443 }
444 }
445 }
446 }
447 // Handle array relationships for relationship filter dropdowns
448 else if (isArray && underlyingType instanceof GraphQLObjectType) {
449 const relatedTypeName = underlyingType.name
450
451 // Add a relationship filter if this is a filterable entity
452 if (!parentPath) {
453 const relationshipFilter = getRelationshipFilterConfig(
454 entity.name,
455 fieldName,
456 relatedTypeName,
457 true,
458 schemaTypeMap
459 )
460
461 if (relationshipFilter) {
462 const label = propertyLabels?.get(fieldName)
463 const hasCustomLabel = !!label
464
465 // Add as a virtual filterable column
466 columns.push({
467 id: `${fieldName}_filter`,
468 name: label?.label || formatFieldName(fieldName),
469 description: label?.description || undefined,
470 field: `${fieldName}.id`,
471 sortable: false,
472 hideable: true,
473 default_visible: false,
474 data_type: "string",
475 semantic_type: "relationship",
476 context: "filter",
477 render_mode: "text",
478 default_order: 980,
479 category: "relationship",
480 filter: {
481 enabled: true,
482 operators: ["in"],
483 relationship: relationshipFilter,
484 },
485 source: { module: entity.module, entity: entity.name },
486 custom_label: hasCustomLabel,
487 label_id: label?.id,
488 })
489 }
490 }
491 }
492 }
493 }