@haus-tech/product-import-export-plugin 3.3.10-next.1 → 3.3.10-next.2

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.
@@ -1,418 +0,0 @@
1
- import {
2
- Accordion,
3
- AccordionContent,
4
- AccordionItem,
5
- AccordionTrigger,
6
- Checkbox,
7
- Input,
8
- Label,
9
- Popover,
10
- PopoverContent,
11
- PopoverTrigger,
12
- RadioGroup,
13
- RadioGroupItem,
14
- toast,
15
- } from '@vendure/dashboard'
16
- import { ChevronRight, InfoIcon } from 'lucide-react'
17
- import {
18
- useCallback,
19
- useEffect,
20
- useImperativeHandle,
21
- useMemo,
22
- forwardRef,
23
- useState,
24
- } from 'react'
25
- import {
26
- getServerLocation,
27
- getChannelHeader,
28
- type PluginInitOptions,
29
- type ExportFields,
30
- type ProductFields,
31
- type VariantFields,
32
- } from './utils'
33
-
34
- const MANDATORY_OPTION_FIELDS: Array<ProductFields | VariantFields> = [
35
- 'optionGroups',
36
- 'optionValues',
37
- ]
38
-
39
- const AVAILABLE_EXPORT_FIELDS: ExportFields = [
40
- 'name',
41
- 'slug',
42
- 'description',
43
- 'assets',
44
- 'facets',
45
- 'optionGroups',
46
- 'sku',
47
- 'optionValues',
48
- 'price',
49
- 'taxCategory',
50
- 'stockOnHand',
51
- 'trackInventory',
52
- 'variantAssets',
53
- 'variantFacets',
54
- 'enabled',
55
- ]
56
-
57
- export type ExportConfigurationPanelProps = {
58
- /** Selected product IDs for scoped export; omit when `isExportAll` (treated as empty). */
59
- productIds?: string[]
60
- isExportAll: boolean
61
- /** Fetch config + fields only while true (e.g. dialog `open`) */
62
- active: boolean
63
- /** Prefix for input/checkbox ids so modal vs page never collide */
64
- idPrefix?: string
65
- /** Expand “Select fields to export” on first paint (e.g. modal); inline page keeps it collapsed */
66
- fieldsAccordionDefaultOpen?: boolean
67
- onExportSuccess?: () => void
68
- }
69
-
70
- export type ExportConfigurationPanelHandle = {
71
- submitExport: () => Promise<void>
72
- }
73
-
74
- export const ExportConfigurationPanel = forwardRef<
75
- ExportConfigurationPanelHandle,
76
- ExportConfigurationPanelProps
77
- >(function ExportConfigurationPanel(
78
- {
79
- productIds,
80
- isExportAll,
81
- active,
82
- idPrefix = 'export-config',
83
- fieldsAccordionDefaultOpen = false,
84
- onExportSuccess,
85
- },
86
- ref,
87
- ) {
88
- const resolvedProductIds = productIds ?? []
89
-
90
- const [config, setConfig] = useState<PluginInitOptions['exportOptions'] | null>(null)
91
-
92
- const [fileName, setFileName] = useState('')
93
- const [customFieldNames, setCustomFieldNames] = useState<string[]>([])
94
- const [selectedCustomFields, setSelectedCustomFields] = useState<string[]>([])
95
- const [exportAssetsAs, setExportAssetsAs] = useState<'url' | 'json'>('url')
96
- const [selectedExportFields, setSelectedExportFields] = useState<ExportFields>([])
97
- const [toggleAllChecked, setToggleAllChecked] = useState(false)
98
-
99
- /** Stable primitive so effects / callbacks don’t churn on fresh array references with the same IDs. */
100
- const productIdsFetchKey = resolvedProductIds.join(',')
101
-
102
- useEffect(() => {
103
- if (!active) return
104
-
105
- const fetchInitial = async () => {
106
- try {
107
- const serverPath = getServerLocation()
108
- const [configRes, customFieldsRes] = await Promise.all([
109
- fetch(`${serverPath}/product-import-export/config`, {
110
- method: 'GET',
111
- headers: {
112
- 'Content-Type': 'application/json',
113
- ...getChannelHeader(),
114
- },
115
- credentials: 'include',
116
- }),
117
- fetch(`${serverPath}/product-export/custom-fields`, {
118
- method: 'POST',
119
- headers: {
120
- 'Content-Type': 'application/json',
121
- ...getChannelHeader(),
122
- },
123
- credentials: 'include',
124
- body: JSON.stringify(
125
- resolvedProductIds.length > 0 ? resolvedProductIds : [],
126
- ),
127
- }),
128
- ])
129
-
130
- const configData = await configRes.json()
131
- const customFieldsData = await customFieldsRes.json()
132
-
133
- setConfig(configData.exportOptions)
134
-
135
- const names = customFieldsData.map((field: { name: string }) => field.name)
136
- setCustomFieldNames(names)
137
- setSelectedCustomFields([...names])
138
-
139
- const defaultAssets =
140
- configData.exportOptions?.defaultExportAssetsAs ||
141
- configData.exportOptions?.exportAssetsAsOptions?.[0] ||
142
- 'url'
143
- setExportAssetsAs(defaultAssets)
144
-
145
- const initialExportFields = Array.from(
146
- new Set([
147
- ...(configData.exportOptions?.defaultExportFields || []),
148
- ...(configData.exportOptions?.requiredExportFields || []),
149
- ...MANDATORY_OPTION_FIELDS,
150
- ]),
151
- ) as ExportFields
152
-
153
- setSelectedExportFields(initialExportFields)
154
- } catch (error) {
155
- console.error('Failed to fetch export config:', error)
156
- }
157
- }
158
-
159
- fetchInitial()
160
- }, [active, productIdsFetchKey])
161
-
162
- const derivedToggleAll = useMemo(() => {
163
- const allStandard = AVAILABLE_EXPORT_FIELDS.every((f) => selectedExportFields.includes(f))
164
- const allCustom =
165
- customFieldNames.length === 0 ||
166
- customFieldNames.every((f) => selectedCustomFields.includes(f))
167
- return allStandard && allCustom
168
- }, [selectedExportFields, selectedCustomFields, customFieldNames])
169
-
170
- useEffect(() => {
171
- setToggleAllChecked(derivedToggleAll)
172
- }, [derivedToggleAll])
173
-
174
- const toggleCustomField = (fieldName: string) => {
175
- setSelectedCustomFields((prev) =>
176
- prev.includes(fieldName) ? prev.filter((f) => f !== fieldName) : [...prev, fieldName],
177
- )
178
- }
179
-
180
- const toggleExportField = (fieldName: ProductFields | VariantFields) => {
181
- if (MANDATORY_OPTION_FIELDS.includes(fieldName)) return
182
- setSelectedExportFields((prev) =>
183
- prev.includes(fieldName)
184
- ? prev.filter((f) => f !== fieldName)
185
- : [...prev, fieldName],
186
- )
187
- }
188
-
189
- const toggleSelectAll = (checked: boolean) => {
190
- setToggleAllChecked(checked)
191
- if (checked) {
192
- setSelectedExportFields([...AVAILABLE_EXPORT_FIELDS])
193
- setSelectedCustomFields([...customFieldNames])
194
- } else {
195
- setSelectedExportFields([
196
- ...(config?.requiredExportFields || []),
197
- ...MANDATORY_OPTION_FIELDS,
198
- ])
199
- setSelectedCustomFields([])
200
- }
201
- }
202
-
203
- const bothAssetModes =
204
- config?.exportAssetsAsOptions?.includes('url') &&
205
- config?.exportAssetsAsOptions?.includes('json')
206
-
207
- const submitExport = useCallback(async () => {
208
- try {
209
- const serverPath = getServerLocation()
210
- const trimmed = fileName.trim()
211
- const finalFileName = trimmed || config?.defaultFileName || 'products_export.csv'
212
- const endpoint = isExportAll ? 'export-all' : 'export'
213
- const body = isExportAll ? undefined : JSON.stringify(resolvedProductIds)
214
-
215
- const res = await fetch(
216
- `${serverPath}/product-export/${endpoint}?fileName=${encodeURIComponent(
217
- finalFileName,
218
- )}&customFields=${encodeURIComponent(
219
- selectedCustomFields.join(','),
220
- )}&exportAssetsAs=${exportAssetsAs}&selectedExportFields=${encodeURIComponent(
221
- selectedExportFields.join(','),
222
- )}`,
223
- {
224
- method: 'POST',
225
- headers: {
226
- 'Content-Type': 'application/json',
227
- ...getChannelHeader(),
228
- },
229
- credentials: 'include',
230
- ...(body && { body }),
231
- },
232
- )
233
-
234
- if (!res.ok) {
235
- const json = await res.json().catch(() => ({}))
236
- throw new Error(json?.message || 'Export failed')
237
- }
238
-
239
- toast.success(
240
- isExportAll
241
- ? 'Export queued. You will receive an email when the file is ready.'
242
- : `Export job queued successfully. ${resolvedProductIds.length} products will be exported.`,
243
- )
244
- onExportSuccess?.()
245
- } catch (error: unknown) {
246
- console.error(error)
247
- toast.error((error as Error)?.message || 'Failed to queue export')
248
- }
249
- }, [
250
- fileName,
251
- config?.defaultFileName,
252
- isExportAll,
253
- productIdsFetchKey,
254
- selectedCustomFields,
255
- exportAssetsAs,
256
- selectedExportFields,
257
- onExportSuccess,
258
- ])
259
-
260
- useImperativeHandle(ref, () => ({ submitExport }), [submitExport])
261
-
262
- if (!active) {
263
- return null
264
- }
265
-
266
- return (
267
- <div className="space-y-4">
268
- <div>
269
- <Label htmlFor={`${idPrefix}-file-name`}>File name (optional)</Label>
270
- <p className="text-xs text-muted-foreground mt-1">
271
- A timestamp is added automatically for uniqueness.
272
- </p>
273
- <Input
274
- id={`${idPrefix}-file-name`}
275
- value={fileName}
276
- onChange={(e) => setFileName(e.target.value)}
277
- placeholder={config?.defaultFileName || 'products_export.csv'}
278
- className="mt-2"
279
- />
280
- </div>
281
-
282
- <Accordion
283
- className="border rounded-lg px-3"
284
- defaultValue={
285
- fieldsAccordionDefaultOpen ? ['select-fields'] : ([] as string[])
286
- }
287
- >
288
- <AccordionItem value="select-fields" className="border-0">
289
- <AccordionTrigger className="group/trigger flex w-full items-center gap-3 py-3 text-sm hover:no-underline [&>svg:last-child]:size-4 [&>svg:last-child]:shrink-0 [&>svg:last-child]:self-center">
290
- <ChevronRight className="text-primary size-4 shrink-0 self-center transition-transform duration-200 group-data-[state=open]/trigger:rotate-90" />
291
- <span className="flex min-w-0 flex-1 flex-wrap items-center gap-x-1 self-center text-left leading-snug">
292
- <span className="font-medium text-foreground">Configure fields to export</span>
293
- </span>
294
- </AccordionTrigger>
295
- <AccordionContent className="space-y-4 pb-4 pt-4 border-t border-border">
296
- <div className="flex items-center space-x-2 pt-2">
297
- <Checkbox
298
- id={`${idPrefix}-select-all`}
299
- checked={toggleAllChecked}
300
- onCheckedChange={(checked) => toggleSelectAll(checked === true)}
301
- />
302
- <Label htmlFor={`${idPrefix}-select-all`} className="font-normal">
303
- Select all fields
304
- </Label>
305
- </div>
306
-
307
- <div className="grid grid-cols-1 sm:grid-cols-2 gap-2">
308
- {AVAILABLE_EXPORT_FIELDS.map((field) => (
309
- <div key={field} className="flex items-center space-x-2">
310
- <Checkbox
311
- id={`${idPrefix}-field-${field}`}
312
- checked={selectedExportFields.includes(field)}
313
- onCheckedChange={() => toggleExportField(field)}
314
- disabled={
315
- config?.requiredExportFields?.includes(field) ||
316
- MANDATORY_OPTION_FIELDS.includes(field)
317
- }
318
- />
319
- <Label htmlFor={`${idPrefix}-field-${field}`} className="font-normal">
320
- {field}
321
- </Label>
322
- </div>
323
- ))}
324
- </div>
325
-
326
- {customFieldNames.length > 0 && (
327
- <div className="space-y-2 pt-4 border-t">
328
- <Label className="text-muted-foreground pb-2">Custom fields</Label>
329
- <div className="grid grid-cols-1 sm:grid-cols-2 gap-2">
330
- {customFieldNames.map((field) => (
331
- <div key={field} className="flex items-center space-x-2">
332
- <Checkbox
333
- id={`${idPrefix}-custom-${field}`}
334
- checked={selectedCustomFields.includes(field)}
335
- onCheckedChange={() => toggleCustomField(field)}
336
- />
337
- <Label htmlFor={`${idPrefix}-custom-${field}`} className="font-normal">
338
- {field}
339
- </Label>
340
- </div>
341
- ))}
342
- </div>
343
- </div>
344
- )}
345
- </AccordionContent>
346
- </AccordionItem>
347
- </Accordion>
348
-
349
- {bothAssetModes ? (
350
- <Accordion className="border rounded-lg px-3" defaultValue={[]}>
351
- <AccordionItem value="advanced-settings" className="border-0">
352
- <AccordionTrigger className="group/trigger flex w-full items-center gap-3 py-3 text-sm hover:no-underline [&>svg:last-child]:size-4 [&>svg:last-child]:shrink-0 [&>svg:last-child]:self-center">
353
- <ChevronRight className="text-primary size-4 shrink-0 self-center transition-transform duration-200 group-data-[state=open]/trigger:rotate-90" />
354
- <span className="flex min-w-0 flex-1 flex-wrap items-center gap-x-1 self-center text-left leading-snug">
355
- <span className="font-medium text-foreground">Advanced settings</span>
356
- </span>
357
- </AccordionTrigger>
358
- <AccordionContent className="space-y-4 pb-4 pt-4 border-t border-border">
359
- <div className="flex flex-row flex-wrap items-center gap-x-6 gap-y-2 pt-2">
360
- <div className="flex shrink-0 items-center gap-1">
361
- <Label className="font-medium">Export assets as</Label>
362
- <Popover>
363
- <PopoverTrigger
364
- type="button"
365
- className="inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-md text-muted-foreground outline-none transition-colors hover:bg-accent hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring"
366
- aria-label="What does export assets as mean?"
367
- >
368
- <InfoIcon className="h-4 w-4" />
369
- </PopoverTrigger>
370
- <PopoverContent className="w-80 text-sm" align="start" side="top">
371
- <p className="font-medium text-foreground">Asset columns in the CSV</p>
372
- <p className="mt-2 text-muted-foreground">
373
- Controls how product and variant asset fields are serialized in the export.
374
- </p>
375
- <ul className="mt-3 list-disc space-y-2 pl-4 text-muted-foreground">
376
- <li>
377
- <span className="font-medium text-foreground">URL only</span> — each cell
378
- lists asset file URLs separated by{' '}
379
- <span className="font-mono text-xs">|</span>.
380
- </li>
381
- <li>
382
- <span className="font-medium text-foreground">Full JSON</span> — each cell
383
- contains JSON with <span className="font-mono text-xs">id</span>,{' '}
384
- <span className="font-mono text-xs">name</span>, and{' '}
385
- <span className="font-mono text-xs">url</span> per asset.
386
- </li>
387
- </ul>
388
- </PopoverContent>
389
- </Popover>
390
- </div>
391
- <RadioGroup
392
- value={exportAssetsAs}
393
- onValueChange={(val) => setExportAssetsAs(val as 'url' | 'json')}
394
- className="flex flex-row flex-wrap gap-6"
395
- >
396
- <div className="flex items-center space-x-2">
397
- <RadioGroupItem value="url" id={`${idPrefix}-assets-url`} />
398
- <Label htmlFor={`${idPrefix}-assets-url`} className="font-normal">
399
- URL only
400
- </Label>
401
- </div>
402
- <div className="flex items-center space-x-2">
403
- <RadioGroupItem value="json" id={`${idPrefix}-assets-json`} />
404
- <Label htmlFor={`${idPrefix}-assets-json`} className="font-normal">
405
- Full JSON
406
- </Label>
407
- </div>
408
- </RadioGroup>
409
- </div>
410
- </AccordionContent>
411
- </AccordionItem>
412
- </Accordion>
413
- ) : null}
414
- </div>
415
- )
416
- })
417
-
418
- ExportConfigurationPanel.displayName = 'ExportConfigurationPanel'