Raw
1 import { useMemo } from "react"
2 import { useForm } from "react-hook-form"
3 import { zodResolver } from "@hookform/resolvers/zod"
4 import { z } from "zod"
5 import { Button, toast } from "@medusajs/ui"
6 import { useTranslation } from "react-i18next"
7 import { HttpTypes } from "@medusajs/types"
8 import { ColumnDef } from "@tanstack/react-table"
9
10 import { RouteFocusModal, useRouteModal } from "../../../components/modals"
11 import { KeyboundForm } from "../../../components/utilities/keybound-form"
12 import { useBatchPropertyLabels } from "../../../hooks/api/property-labels"
13 import { DataGrid, createDataGridHelper } from "../../../components/data-grid"
14 import { VisuallyHidden } from "../../../components/utilities/visually-hidden"
15
16 interface PropertyFieldRow {
17 field: string
18 }
19
20 interface PropertyLabelsEditFormProps {
21 entity: string
22 columns: HttpTypes.AdminColumn[]
23 propertyLabels: HttpTypes.AdminPropertyLabel[]
24 }
25
26 const isLeafNode = (obj: any): boolean => {
27 if (typeof obj !== "object" || obj === null) return false
28 const keys = Object.keys(obj)
29 return (
30 keys.length > 0 &&
31 keys.every((key) => key === "label" || key === "description")
32 )
33 }
34
35 const propertyLabelValueSchema = z.object({
36 label: z.string().optional(),
37 description: z.string().optional(),
38 })
39
40 type PropertyLabelValue = z.infer<typeof propertyLabelValueSchema>
41
42 interface PropertyLabelSchema {
43 [key: string]: PropertyLabelValue | PropertyLabelSchema
44 }
45
46 // The input type is pinned to the output type so the schema satisfies the
47 // resolver's `FieldValues` constraint; it defaults to `unknown` otherwise.
48 const propertyLabelSchema: z.ZodType<PropertyLabelSchema, PropertyLabelSchema> =
49 z.lazy(() =>
50 z.record(z.string(), z.any()).superRefine((obj, ctx) => {
51 Object.entries(obj).forEach(([key, value]) => {
52 if (isLeafNode(value)) {
53 const result = propertyLabelValueSchema.safeParse(value)
54 if (!result.success) {
55 result.error.issues.forEach((issue) => {
56 ctx.addIssue({
57 ...issue,
58 path: [key, ...issue.path],
59 })
60 })
61 }
62
63 const typedValue = value as PropertyLabelValue
64 if (typedValue.description && typedValue.description.trim() !== "") {
65 if (!typedValue.label || typedValue.label.trim() === "") {
66 ctx.addIssue({
67 code: "custom",
68 message: "Label is required when description is provided",
69 path: [key, "label"],
70 })
71 }
72 }
73 } else if (typeof value === "object" && value !== null) {
74 const result = propertyLabelSchema.safeParse(value)
75 if (!result.success) {
76 result.error.issues.forEach((issue) => {
77 ctx.addIssue({
78 ...issue,
79 path: [key, ...issue.path],
80 })
81 })
82 }
83 }
84 })
85 })
86 )
87
88 const columnHelper = createDataGridHelper<
89 PropertyFieldRow,
90 PropertyLabelSchema
91 >()
92
93 export const PropertyLabelsEditForm = ({
94 entity,
95 columns,
96 propertyLabels,
97 }: PropertyLabelsEditFormProps) => {
98 const { t } = useTranslation()
99 const { handleSuccess } = useRouteModal()
100 const batchMutation = useBatchPropertyLabels()
101
102 const buildNestedInitialData = (
103 labels: HttpTypes.AdminPropertyLabel[]
104 ): PropertyLabelSchema => {
105 const result: any = {}
106
107 labels.forEach((label) => {
108 const parts = label.property.split(".")
109 let current = result
110
111 parts.forEach((part, index) => {
112 if (index === parts.length - 1) {
113 current[part] = {
114 label: label.label,
115 description: label.description || "",
116 }
117 } else {
118 if (!current[part]) {
119 current[part] = {}
120 }
121 current = current[part]
122 }
123 })
124 })
125
126 return result
127 }
128
129 const initialData = buildNestedInitialData(propertyLabels)
130
131 const form = useForm<PropertyLabelSchema>({
132 resolver: zodResolver(propertyLabelSchema),
133 defaultValues: initialData,
134 })
135
136 const rows: PropertyFieldRow[] = useMemo(() => {
137 return columns.map((column) => ({
138 field: column.field,
139 }))
140 }, [columns])
141
142 const gridColumns: ColumnDef<PropertyFieldRow>[] = useMemo(() => {
143 return [
144 columnHelper.column({
145 id: "field",
146 name: "field",
147 header: t("fields.field", "Field"),
148 cell: (context) => {
149 const row = context.row.original
150 return (
151 <DataGrid.ReadonlyCell context={context}>
152 {row.field}
153 </DataGrid.ReadonlyCell>
154 )
155 },
156 disableHiding: true,
157 minSize: 250,
158 }),
159 columnHelper.column({
160 id: "label",
161 name: "label",
162 header: t("propertyLabels.customLabel", "Custom Label"),
163 type: "text",
164 field: (context) => {
165 const row = context.row.original
166 return `${row.field}.label`
167 },
168 cell: (context) => {
169 return <DataGrid.TextCell context={context} />
170 },
171 disableHiding: true,
172 minSize: 250,
173 }),
174 columnHelper.column({
175 id: "description",
176 name: "description",
177 header: t("fields.description", "Description"),
178 type: "multiline-text",
179 field: (context) => {
180 const row = context.row.original
181 return `${row.field}.description`
182 },
183 cell: (context) => {
184 return <DataGrid.MultilineCell context={context} />
185 },
186 minSize: 400,
187 }),
188 ]
189 }, [t])
190
191 const flattenData = (
192 obj: any,
193 prefix = ""
194 ): Array<[string, PropertyLabelValue]> => {
195 const results: Array<[string, PropertyLabelValue]> = []
196
197 Object.entries(obj).forEach(([key, value]) => {
198 const fullPath = prefix ? `${prefix}.${key}` : key
199
200 if (value && typeof value === "object") {
201 const keys = Object.keys(value)
202 const isLeaf = keys.every((k) => k === "label" || k === "description")
203
204 if (isLeaf) {
205 results.push([fullPath, value as PropertyLabelValue])
206 } else {
207 results.push(...flattenData(value, fullPath))
208 }
209 }
210 })
211
212 return results
213 }
214
215 const handleSubmit = form.handleSubmit(async (data) => {
216 const create: HttpTypes.AdminCreatePropertyLabel[] = []
217 const update: NonNullable<HttpTypes.AdminBatchPropertyLabels["update"]> = []
218 const deleteIds: string[] = []
219
220 const labelMap = new Map<string, HttpTypes.AdminPropertyLabel>()
221 propertyLabels?.forEach((label) => {
222 labelMap.set(label.property, label)
223 })
224
225 const flatEntries = flattenData(data)
226
227 flatEntries.forEach(([property, values]) => {
228 const existingLabel = labelMap.get(property)
229 const newLabel = values.label?.trim()
230 const newDescription = values.description?.trim()
231
232 if (newLabel) {
233 if (existingLabel) {
234 if (
235 existingLabel.label !== newLabel ||
236 (existingLabel.description || "") !== (newDescription || "")
237 ) {
238 update.push({
239 id: existingLabel.id,
240 label: newLabel,
241 description: newDescription ?? null,
242 })
243 }
244 } else {
245 create.push({
246 entity,
247 property,
248 label: newLabel,
249 description: newDescription || undefined,
250 })
251 }
252 } else if (existingLabel) {
253 deleteIds.push(existingLabel.id)
254 }
255 })
256
257 if (!create.length && !update.length && !deleteIds.length) {
258 return
259 }
260
261 await batchMutation.mutateAsync(
262 {
263 create: create.length > 0 ? create : undefined,
264 update: update.length > 0 ? update : undefined,
265 delete: deleteIds.length > 0 ? deleteIds : undefined,
266 },
267 {
268 onSuccess: () => {
269 toast.success(
270 t(
271 "propertyLabels.updateSuccess",
272 "Property labels updated successfully"
273 )
274 )
275 handleSuccess()
276 },
277 onError: (error) => {
278 toast.error(error.message)
279 },
280 }
281 )
282 })
283
284 return (
285 <RouteFocusModal.Form form={form}>
286 <KeyboundForm
287 onSubmit={handleSubmit}
288 className="flex size-full flex-col overflow-hidden"
289 >
290 <RouteFocusModal.Header>
291 <RouteFocusModal.Title asChild>
292 <VisuallyHidden>
293 {t("propertyLabels.editTitle", "Edit Property Labels")}
294 </VisuallyHidden>
295 </RouteFocusModal.Title>
296 <RouteFocusModal.Description asChild>
297 <VisuallyHidden>
298 {t(
299 "propertyLabels.editDescription",
300 "Customize how property names are displayed for {{entity}}",
301 { entity }
302 )}
303 </VisuallyHidden>
304 </RouteFocusModal.Description>
305 </RouteFocusModal.Header>
306 <RouteFocusModal.Body className="overflow-hidden">
307 <DataGrid columns={gridColumns} data={rows} state={form} />
308 </RouteFocusModal.Body>
309 <RouteFocusModal.Footer>
310 <div className="flex items-center justify-end gap-2">
311 <RouteFocusModal.Close asChild>
312 <Button variant="secondary" type="button">
313 {t("actions.cancel", "Cancel")}
314 </Button>
315 </RouteFocusModal.Close>
316 <Button
317 type="submit"
318 isLoading={batchMutation.isPending}
319 disabled={!form.formState.isDirty}
320 >
321 {t("actions.save", "Save")}
322 </Button>
323 </div>
324 </RouteFocusModal.Footer>
325 </KeyboundForm>
326 </RouteFocusModal.Form>
327 )
328 }