Raw
1 import { Badge, StatusBadge, Tooltip } from "@medusajs/ui"
2 import ReactCountryFlag from "react-country-flag"
3 import { getCountryByIso2 } from "./data/countries"
4 import { getStylizedAmount } from "./money-amount-helpers"
5
6 // Helper function to get nested value from object using dot notation
7 const getNestedValue = (obj: any, path: string) => {
8 return path.split(".").reduce((current, key) => current?.[key], obj)
9 }
10
11 // Helper function to format date
12 const formatDate = (
13 date: string | Date,
14 format: "short" | "long" | "relative" = "short"
15 ) => {
16 const dateObj = new Date(date)
17
18 switch (format) {
19 case "short":
20 return dateObj.toLocaleDateString("en-GB", {
21 day: "numeric",
22 month: "short",
23 year: "numeric",
24 })
25 case "long":
26 return dateObj.toLocaleDateString("en-GB", {
27 day: "numeric",
28 month: "long",
29 year: "numeric",
30 hour: "2-digit",
31 minute: "2-digit",
32 })
33 case "relative": {
34 const now = new Date()
35 const diffInMs = now.getTime() - dateObj.getTime()
36 const diffInDays = Math.floor(diffInMs / (1000 * 60 * 60 * 24))
37
38 if (diffInDays === 0) {
39 return "Today"
40 }
41 if (diffInDays === 1) {
42 return "Yesterday"
43 }
44 if (diffInDays < 7) {
45 return `${diffInDays} days ago`
46 }
47
48 return dateObj.toLocaleDateString("en-GB", {
49 day: "numeric",
50 month: "short",
51 })
52 }
53 default:
54 return dateObj.toLocaleDateString()
55 }
56 }
57
58 // Payment status display
59 const PaymentStatusBadge = ({ status }: { status: string }) => {
60 const getStatusColor = (status: string) => {
61 switch (status?.toLowerCase()) {
62 case "paid":
63 case "captured":
64 return "green"
65 case "pending":
66 case "awaiting":
67 return "orange"
68 case "failed":
69 case "canceled":
70 return "red"
71 default:
72 return "grey"
73 }
74 }
75
76 return <StatusBadge color={getStatusColor(status)}>{status}</StatusBadge>
77 }
78
79 // Fulfillment status display
80 const FulfillmentStatusBadge = ({ status }: { status: string }) => {
81 const getStatusColor = (status: string) => {
82 switch (status?.toLowerCase()) {
83 case "fulfilled":
84 case "shipped":
85 return "green"
86 case "partially_fulfilled":
87 case "preparing":
88 return "orange"
89 case "canceled":
90 case "returned":
91 return "red"
92 case "pending":
93 case "not_fulfilled":
94 return "grey"
95 default:
96 return "grey"
97 }
98 }
99
100 return <StatusBadge color={getStatusColor(status)}>{status}</StatusBadge>
101 }
102
103 // Generic status badge
104 const GenericStatusBadge = ({ status }: { status: string }) => {
105 return (
106 <Badge color="grey" className="capitalize">
107 {status}
108 </Badge>
109 )
110 }
111
112 // Display strategies registry
113 export const DISPLAY_STRATEGIES = {
114 // Known semantic types with pixel-perfect display
115 status: {
116 payment: (value: any) => <PaymentStatusBadge status={value} />,
117 fulfillment: (value: any) => <FulfillmentStatusBadge status={value} />,
118 default: (value: any) => <GenericStatusBadge status={value} />,
119 },
120
121 currency: {
122 default: (value: any, row: any) => {
123 if (value === null || value === undefined) {
124 return "-"
125 }
126 const currencyCode = row.currency_code || "USD"
127 const formatted = getStylizedAmount(value, currencyCode)
128
129 return (
130 <div className="flex h-full w-full items-center justify-end text-right">
131 <span className="truncate">{formatted}</span>
132 </div>
133 )
134 },
135 },
136
137 timestamp: {
138 creation: (value: any) => {
139 return value ? formatDate(value, "short") : "-"
140 },
141 update: (value: any) => {
142 return value ? formatDate(value, "relative") : "-"
143 },
144 default: (value: any) => {
145 return value ? formatDate(value, "short") : "-"
146 },
147 },
148
149 identifier: {
150 order: (value: any) => `#${value}`,
151 default: (value: any) => value,
152 },
153
154 email: {
155 default: (value: any) => value || "-",
156 },
157
158 // Generic fallbacks for custom fields
159 enum: {
160 default: (value: any) => <GenericStatusBadge status={value} />,
161 },
162
163 // Base type fallbacks
164 string: {
165 default: (value: any) => value || "-",
166 },
167
168 number: {
169 default: (value: any) => value?.toLocaleString() || "0",
170 },
171
172 boolean: {
173 default: (value: any) => (
174 <Badge color={value ? "green" : "grey"}>{value ? "Yes" : "No"}</Badge>
175 ),
176 },
177
178 object: {
179 relationship: (value: any) => {
180 if (!value || typeof value !== "object") {
181 return "-"
182 }
183
184 // Try common display fields
185 if (value.name) {
186 return value.name
187 }
188 if (value.title) {
189 return value.title
190 }
191 if (value.email) {
192 return value.email
193 }
194 if (value.display_name) {
195 return value.display_name
196 }
197
198 return JSON.stringify(value)
199 },
200 default: (value: any) => {
201 if (!value || typeof value !== "object") {
202 return "-"
203 }
204
205 // Try common display fields
206 if (value.name) {
207 return value.name
208 }
209 if (value.title) {
210 return value.title
211 }
212 if (value.email) {
213 return value.email
214 }
215
216 return JSON.stringify(value)
217 },
218 },
219
220 // Date types (in addition to timestamp)
221 date: {
222 default: (value: any) => {
223 return value ? formatDate(value, "short") : "-"
224 },
225 },
226
227 datetime: {
228 default: (value: any) => {
229 return value ? formatDate(value, "long") : "-"
230 },
231 },
232
233 // Computed columns
234 computed: {
235 display: (value: any) => value || "-",
236 default: (value: any) => value || "-",
237 },
238 }
239
240 // Strategy selection function
241 export const getDisplayStrategy = (column: any) => {
242 const semanticStrategies =
243 DISPLAY_STRATEGIES[column.semantic_type as keyof typeof DISPLAY_STRATEGIES]
244 if (semanticStrategies) {
245 const contextStrategy =
246 semanticStrategies[column.context as keyof typeof semanticStrategies]
247 if (contextStrategy) {
248 return contextStrategy
249 }
250
251 const defaultStrategy = semanticStrategies.default
252 if (defaultStrategy) {
253 return defaultStrategy
254 }
255 }
256
257 // Fallback to data type
258 // Map 'text' data type to 'string' strategy
259 const dataType = column.data_type === "text" ? "string" : column.data_type
260 const dataTypeStrategies =
261 DISPLAY_STRATEGIES[dataType as keyof typeof DISPLAY_STRATEGIES]
262 if (dataTypeStrategies) {
263 const defaultStrategy = dataTypeStrategies.default
264 if (defaultStrategy) {
265 return defaultStrategy
266 }
267 }
268
269 // Final fallback
270 return (value: any) => String(value || "-")
271 }
272
273 // Computed column computation functions
274 export const COMPUTED_COLUMN_FUNCTIONS = {
275 customer_name: (row: any) => {
276 // Try customer object first
277 if (row.customer?.first_name || row.customer?.last_name) {
278 const fullName = `${row.customer.first_name || ""} ${
279 row.customer.last_name || ""
280 }`.trim()
281 if (fullName) {
282 return fullName
283 }
284 }
285
286 // Fall back to email
287 if (row.customer?.email) {
288 return row.customer.email
289 }
290
291 // Fall back to phone
292 if (row.customer?.phone) {
293 return row.customer.phone
294 }
295
296 return "Guest"
297 },
298
299 address_summary: (row: any, column?: any) => {
300 // Determine which address to use based on the column field
301 let address: Record<string, string> | null = null
302 if (column?.field === "shipping_address_display") {
303 address = row.shipping_address
304 } else if (column?.field === "billing_address_display") {
305 address = row.billing_address
306 } else {
307 // Fallback to shipping address if no specific field
308 address = row.shipping_address || row.billing_address
309 }
310
311 if (!address) {
312 return "-"
313 }
314
315 // Build address parts in a meaningful order
316 const parts: string[] = []
317
318 // Include street address if available
319 if (address.address_1) {
320 parts.push(address.address_1)
321 }
322
323 // City, Province/State, Postal Code
324 const locationParts: string[] = []
325 if (address.city) {
326 locationParts.push(address.city)
327 }
328 if (address.province) {
329 locationParts.push(address.province)
330 }
331 if (address.postal_code) {
332 locationParts.push(address.postal_code)
333 }
334
335 if (locationParts.length > 0) {
336 parts.push(locationParts.join(", "))
337 }
338
339 // Country
340 if (address.country_code) {
341 parts.push(address.country_code.toUpperCase())
342 }
343
344 return parts.join(" • ") || "-"
345 },
346
347 country_code: (row: any) => {
348 // Get country code from shipping address
349 const countryCode = row.shipping_address?.country_code
350
351 if (!countryCode) {
352 return <div className="flex w-full justify-center">-</div>
353 }
354
355 // Get country information
356 const country = getCountryByIso2(countryCode)
357 const displayName = country?.display_name || countryCode.toUpperCase()
358
359 // Display country flag with tooltip - centered in the cell
360 return (
361 <div className="flex w-full items-center justify-center">
362 <Tooltip content={displayName}>
363 <div className="flex size-4 items-center justify-center overflow-hidden rounded-sm">
364 <ReactCountryFlag
365 countryCode={countryCode.toUpperCase()}
366 svg
367 style={{
368 width: "16px",
369 height: "16px",
370 }}
371 aria-label={displayName}
372 />
373 </div>
374 </Tooltip>
375 </div>
376 )
377 },
378 }
379
380 // Entity-specific column overrides
381 export const ENTITY_COLUMN_OVERRIDES = {
382 orders: {
383 // Override for customer column that combines multiple fields
384 customer: {
385 accessor: (row: any) => {
386 // Complex logic for combining fields
387 const shipping = row.shipping_address
388 const customer = row.customer
389
390 if (shipping?.first_name || shipping?.last_name) {
391 return `${shipping.first_name || ""} ${
392 shipping.last_name || ""
393 }`.trim()
394 }
395 if (customer?.first_name || customer?.last_name) {
396 return `${customer.first_name || ""} ${
397 customer.last_name || ""
398 }`.trim()
399 }
400 return customer?.email || "Guest"
401 },
402 },
403 },
404 }
405
406 // Helper function to get entity-specific accessor
407 export const getEntityAccessor = (
408 entity: string,
409 fieldName: string,
410 column?: any
411 ) => {
412 // Check if this is a computed column
413 if (column?.computed) {
414 const computationFn =
415 COMPUTED_COLUMN_FUNCTIONS[
416 column.computed.type as keyof typeof COMPUTED_COLUMN_FUNCTIONS
417 ]
418 if (computationFn) {
419 // Return a wrapper function that passes the column info
420 return (row: any) => computationFn(row, column)
421 }
422 }
423
424 const entityOverrides =
425 ENTITY_COLUMN_OVERRIDES[entity as keyof typeof ENTITY_COLUMN_OVERRIDES]
426 if (entityOverrides) {
427 const fieldOverride =
428 entityOverrides[fieldName as keyof typeof entityOverrides]
429 if (fieldOverride?.accessor) {
430 return fieldOverride.accessor
431 }
432 }
433
434 // Default accessor using dot notation
435 return (row: any) => getNestedValue(row, fieldName)
436 }