1 import { HttpTypes } from "@medusajs/types"
2
3 /**
4 * The path a quantity column reads its unit of measure from. The unit does not
5 * always live on the row itself — on a reservation it hangs off the related
6 * inventory item — so a column can point at it with a `unit_of_measure_path`
7 * metadata entry.
8 *
9 * Shared with the cell renderer so the field that is requested is the field
10 * that is read.
11 */
12 export function getUnitOfMeasurePath(column?: {
13 metadata?: Record<string, any> | null
14 }): string {
15 return column?.metadata?.unit_of_measure_path ?? "unit_of_measure"
16 }
17
18 /**
19 * Calculate required fields based on visible columns from API definitions.
20 */
21 export function calculateRequiredFields(
22 apiColumns: HttpTypes.AdminColumn[],
23 visibleColumns: Record<string, boolean>
24 ): string {
25 // Get all visible columns
26 const visibleColumnObjects = apiColumns.filter((column) => {
27 // If visibleColumns has data, use it; otherwise use default_visible
28 if (Object.keys(visibleColumns).length > 0) {
29 return visibleColumns[column.field] === true
30 }
31 return column.default_visible
32 })
33
34 // Collect all required fields from visible columns
35 const requiredFieldsSet = new Set<string>()
36
37 visibleColumnObjects.forEach((column) => {
38 // Virtual columns (selection, actions) have no backing data field and must
39 // not be requested from the API.
40 if (column.render_mode === "select" || column.render_mode === "actions") {
41 return
42 }
43
44 // A quantity is rendered with its unit of measure, which the user has not
45 // necessarily added as a column of its own.
46 if (column.render_mode === "quantity") {
47 requiredFieldsSet.add(getUnitOfMeasurePath(column))
48 }
49
50 if (column.computed) {
51 // For computed columns, add all required and optional fields
52 column.computed.required_fields?.forEach((field: string) =>
53 requiredFieldsSet.add(field)
54 )
55 column.computed.optional_fields?.forEach((field: string) =>
56 requiredFieldsSet.add(field)
57 )
58 } else {
59 // Relationship field
60 requiredFieldsSet.add(column.field)
61 }
62 })
63
64 // Currency columns (e.g. "total") render their amount using the entity's
65 // own currency, not a fixed one, so `currency_code` must be fetched
66 // whenever such a column is visible, even if the user hasn't added it as a
67 // column itself.
68 const hasVisibleCurrencyColumn = visibleColumnObjects.some(
69 (column) => column.data_type === "currency"
70 )
71 const entityHasCurrencyCode = apiColumns.some(
72 (column) => column.field === "currency_code"
73 )
74 if (hasVisibleCurrencyColumn && entityHasCurrencyCode) {
75 requiredFieldsSet.add("currency_code")
76 }
77
78 return Array.from(requiredFieldsSet).join(",")
79 }