Blame view

美国版/Food Labeling Management Platform/src/components/locations/LocationsView.tsx 38.7 KB
de8956f8   杨鑫   平台端 门店,菜单,角色
1
  import React, { useEffect, useMemo, useRef, useState } from "react";
3af4878d   杨鑫   产品 标签 关联
2
  import { Edit, MapPin, MoreHorizontal, Trash2 } from "lucide-react";
884054fb   “wangming”   项目初始化
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
  import { Button } from "../ui/button";
  import { Input } from "../ui/input";
  import {
    Table,
    TableBody,
    TableCell,
    TableHead,
    TableHeader,
    TableRow,
  } from "../ui/table";
  import {
    Dialog,
    DialogContent,
    DialogDescription,
    DialogFooter,
    DialogHeader,
    DialogTitle,
  } from "../ui/dialog";
  import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
  } from "../ui/select";
  import { Label } from "../ui/label";
  import { Badge } from "../ui/badge";
  import { Switch } from "../ui/switch";
de8956f8   杨鑫   平台端 门店,菜单,角色
31
  import { toast } from "sonner";
143afd59   杨鑫   打印,标签
32
  import { skipCountForPage } from "../../lib/paginationQuery";
de8956f8   杨鑫   平台端 门店,菜单,角色
33
34
35
36
37
38
39
40
41
42
43
44
  import { Tooltip, TooltipContent, TooltipTrigger } from "../ui/tooltip";
  import { Popover, PopoverContent, PopoverTrigger } from "../ui/popover";
  import {
    Pagination,
    PaginationContent,
    PaginationItem,
    PaginationLink,
    PaginationNext,
    PaginationPrevious,
  } from "../ui/pagination";
  import { createLocation, deleteLocation, getLocations, updateLocation } from "../../services/locationService";
  import type { LocationCreateInput, LocationDto } from "../../types/location";
884054fb   “wangming”   项目初始化
45
  
de8956f8   杨鑫   平台端 门店,菜单,角色
46
47
48
49
50
51
52
53
54
55
  function toDisplay(v: string | null | undefined): string {
    const s = (v ?? "").trim();
    return s ? s : "N/A";
  }
  
  function formatGps(lat: number | null | undefined, lng: number | null | undefined): string {
    if (lat === null || lat === undefined || lng === null || lng === undefined) return "N/A";
    if (!Number.isFinite(lat) || !Number.isFinite(lng)) return "N/A";
    return `${lat}, ${lng}`;
  }
884054fb   “wangming”   项目初始化
56
  
3d4c10ac   杨鑫   对接,标签产品
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
  /**
   * 红框区域:Location ID / Name、地址、联系方式、GPS(Partner、Group、Active 不要求)
   * 仅校验是否填写,不校验邮箱/电话格式。
   */
  function getLocationRedBoxValidationErrors(form: LocationCreateInput): string[] {
    const errs: string[] = [];
    if (!form.locationCode.trim()) errs.push("Location ID");
    if (!form.locationName.trim()) errs.push("Location Name");
    if (!(form.street ?? "").trim()) errs.push("Street");
    if (!(form.city ?? "").trim()) errs.push("City");
    if (!(form.stateCode ?? "").trim()) errs.push("State");
    if (!(form.country ?? "").trim()) errs.push("Country");
    if (!(form.zipCode ?? "").trim()) errs.push("Zip Code");
    if (!(form.phone ?? "").trim()) errs.push("Phone Number");
    if (!(form.email ?? "").trim()) errs.push("Email");
  
    const lat = form.latitude;
    const lng = form.longitude;
    if (lat === null || lat === undefined || !Number.isFinite(lat)) errs.push("Latitude");
    if (lng === null || lng === undefined || !Number.isFinite(lng)) errs.push("Longitude");
    return errs;
  }
  
884054fb   “wangming”   项目初始化
80
81
  export function LocationsView() {
    const [isCreateDialogOpen, setIsCreateDialogOpen] = useState(false);
de8956f8   杨鑫   平台端 门店,菜单,角色
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
    const [isEditDialogOpen, setIsEditDialogOpen] = useState(false);
    const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false);
    const [editingLocation, setEditingLocation] = useState<LocationDto | null>(null);
    const [deletingLocation, setDeletingLocation] = useState<LocationDto | null>(null);
    const [locations, setLocations] = useState<LocationDto[]>([]);
    const [loading, setLoading] = useState(false);
    const [total, setTotal] = useState(0);
    const [refreshSeq, setRefreshSeq] = useState(0);
    const [actionsOpenForId, setActionsOpenForId] = useState<string | null>(null);
  
    const [keyword, setKeyword] = useState("");
    const [partner, setPartner] = useState<string>("all");
    const [groupName, setGroupName] = useState<string>("all");
    const [locationPick, setLocationPick] = useState<string>("all");
  
    const [pageIndex, setPageIndex] = useState(1);
    const [pageSize, setPageSize] = useState(10);
  
    const abortRef = useRef<AbortController | null>(null);
    const keywordTimerRef = useRef<number | null>(null);
    const [debouncedKeyword, setDebouncedKeyword] = useState("");
  
    useEffect(() => {
      if (keywordTimerRef.current) window.clearTimeout(keywordTimerRef.current);
      keywordTimerRef.current = window.setTimeout(() => setDebouncedKeyword(keyword.trim()), 300);
      return () => {
        if (keywordTimerRef.current) window.clearTimeout(keywordTimerRef.current);
      };
    }, [keyword]);
  
    // Options derived from current result set (no dedicated endpoints provided in doc).
    const partnerOptions = useMemo(() => {
      const s = new Set<string>();
      for (const x of locations) {
        const v = (x.partner ?? "").trim();
        if (v) s.add(v);
      }
      return ["all", ...Array.from(s).sort((a, b) => a.localeCompare(b))];
    }, [locations]);
  
    const groupOptions = useMemo(() => {
      const s = new Set<string>();
      for (const x of locations) {
        const v = (x.groupName ?? "").trim();
        if (v) s.add(v);
      }
      return ["all", ...Array.from(s).sort((a, b) => a.localeCompare(b))];
    }, [locations]);
  
    const locationOptions = useMemo(() => {
      const s = new Set<string>();
      for (const x of locations) {
        const v = (x.locationCode ?? "").trim();
        if (v) s.add(v);
      }
      return ["all", ...Array.from(s).sort((a, b) => a.localeCompare(b))];
    }, [locations]);
  
    const totalPages = Math.max(1, Math.ceil(total / pageSize));
  
    useEffect(() => {
      // When filter changes, reset to first page.
      setPageIndex(1);
      // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [debouncedKeyword, partner, groupName, locationPick, pageSize]);
  
    useEffect(() => {
      const run = async () => {
        abortRef.current?.abort();
        const ac = new AbortController();
        abortRef.current = ac;
  
        setLoading(true);
        try {
143afd59   杨鑫   打印,标签
156
          const skipCount = skipCountForPage(pageIndex);
de8956f8   杨鑫   平台端 门店,菜单,角色
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
          const effectiveKeyword = locationPick !== "all" ? locationPick : debouncedKeyword;
          const res = await getLocations(
            {
              skipCount,
              maxResultCount: pageSize,
              keyword: effectiveKeyword || undefined,
              partner: partner !== "all" ? partner : undefined,
              groupName: groupName !== "all" ? groupName : undefined,
            },
            ac.signal,
          );
  
          setLocations(res.items ?? []);
          setTotal(res.totalCount ?? 0);
        } catch (e: any) {
          if (e?.name === "AbortError") return;
          toast.error("Failed to load locations.", {
            description: e?.message ? String(e.message) : "Please try again.",
          });
          setLocations([]);
          setTotal(0);
        } finally {
          setLoading(false);
        }
      };
  
      run();
      return () => abortRef.current?.abort();
    }, [debouncedKeyword, partner, groupName, locationPick, pageIndex, pageSize, refreshSeq]);
  
    const refreshList = () => setRefreshSeq((x) => x + 1);
  
    const openEdit = (loc: LocationDto) => {
      setActionsOpenForId(null);
      setEditingLocation(loc);
      setIsEditDialogOpen(true);
    };
  
    const openDelete = (loc: LocationDto) => {
      setActionsOpenForId(null);
      setDeletingLocation(loc);
      setIsDeleteDialogOpen(true);
    };
884054fb   “wangming”   项目初始化
200
201
202
203
204
205
206
207
208
209
  
    return (
      <div className="h-full flex flex-col">
        {/* Toolbar - no white background; spacing matches Labels (main p-8 only) */}
        <div className="pb-4">
          <div className="flex flex-col gap-4">
            {/* Toolbar: Search + Filters + Actions in one row, no "Search" label */}
            <div className="flex flex-nowrap items-center gap-3">
              <Input
                placeholder="Search"
de8956f8   杨鑫   平台端 门店,菜单,角色
210
211
                value={keyword}
                onChange={(e) => setKeyword(e.target.value)}
884054fb   “wangming”   项目初始化
212
213
214
                style={{ height: 40, boxSizing: 'border-box' }}
                className="border border-gray-300 rounded-md w-40 shrink-0 bg-white placeholder:text-gray-500"
              />
de8956f8   杨鑫   平台端 门店,菜单,角色
215
              <Select value={partner} onValueChange={setPartner}>
884054fb   “wangming”   项目初始化
216
217
218
219
                <SelectTrigger className="w-[140px] h-10 rounded-md border border-gray-300 bg-white font-medium text-gray-900 shrink-0" style={{ height: 40, boxSizing: 'border-box' }}>
                  <SelectValue placeholder="Partner" />
                </SelectTrigger>
                <SelectContent>
de8956f8   杨鑫   平台端 门店,菜单,角色
220
221
222
223
224
                  {partnerOptions.map((p) => (
                    <SelectItem key={p} value={p}>
                      {p === "all" ? "Partner (All)" : p}
                    </SelectItem>
                  ))}
884054fb   “wangming”   项目初始化
225
226
                </SelectContent>
              </Select>
de8956f8   杨鑫   平台端 门店,菜单,角色
227
              <Select value={groupName} onValueChange={setGroupName}>
884054fb   “wangming”   项目初始化
228
229
230
231
                <SelectTrigger className="w-[140px] h-10 rounded-md border border-gray-300 bg-white font-medium text-gray-900 shrink-0" style={{ height: 40, boxSizing: 'border-box' }}>
                  <SelectValue placeholder="Group" />
                </SelectTrigger>
                <SelectContent>
de8956f8   杨鑫   平台端 门店,菜单,角色
232
233
234
235
236
                  {groupOptions.map((g) => (
                    <SelectItem key={g} value={g}>
                      {g === "all" ? "Group (All)" : g}
                    </SelectItem>
                  ))}
884054fb   “wangming”   项目初始化
237
238
                </SelectContent>
              </Select>
de8956f8   杨鑫   平台端 门店,菜单,角色
239
              <Select value={locationPick} onValueChange={setLocationPick}>
884054fb   “wangming”   项目初始化
240
241
242
243
                <SelectTrigger className="w-[140px] h-10 rounded-md border border-gray-300 bg-white font-medium text-gray-900 shrink-0" style={{ height: 40, boxSizing: 'border-box' }}>
                  <SelectValue placeholder="Location" />
                </SelectTrigger>
                <SelectContent>
de8956f8   杨鑫   平台端 门店,菜单,角色
244
245
246
247
248
                  {locationOptions.map((x) => (
                    <SelectItem key={x} value={x}>
                      {x === "all" ? "All Locations" : x}
                    </SelectItem>
                  ))}
884054fb   “wangming”   项目初始化
249
250
251
                </SelectContent>
              </Select>
              <div className="flex-1" />
de8956f8   杨鑫   平台端 门店,菜单,角色
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
              <Tooltip>
                <TooltipTrigger asChild>
                  <span>
                    <Button disabled variant="outline" className="h-10 border border-gray-300 rounded-md text-gray-900 px-4 bg-white hover:bg-gray-50 shrink-0">
                      Bulk Import
                    </Button>
                  </span>
                </TooltipTrigger>
                <TooltipContent>Not supported yet</TooltipContent>
              </Tooltip>
              <Tooltip>
                <TooltipTrigger asChild>
                  <span>
                    <Button disabled variant="outline" className="h-10 border border-gray-300 rounded-md text-gray-900 px-4 bg-white hover:bg-gray-50 shrink-0">
                      Bulk Export
                    </Button>
                  </span>
                </TooltipTrigger>
                <TooltipContent>Not supported yet</TooltipContent>
              </Tooltip>
              <Tooltip>
                <TooltipTrigger asChild>
                  <span>
                    <Button disabled variant="outline" className="h-10 border border-gray-300 rounded-md text-gray-900 px-4 bg-white hover:bg-gray-50 shrink-0">
                      Bulk Edit
                    </Button>
                  </span>
                </TooltipTrigger>
                <TooltipContent>Not supported yet</TooltipContent>
              </Tooltip>
884054fb   “wangming”   项目初始化
282
283
284
285
              <Button
                className="h-10 bg-blue-600 hover:bg-blue-700 text-white rounded-md px-6 font-medium shrink-0"
                onClick={() => setIsCreateDialogOpen(true)}
              >
de8956f8   杨鑫   平台端 门店,菜单,角色
286
                New
884054fb   “wangming”   项目初始化
287
288
289
290
291
292
293
294
295
296
297
              </Button>
            </div>
          </div>
        </div>
  
        {/* Content Area - same padding as Labels (relies on main p-8) */}
        <div className="flex-1 overflow-auto pt-6">
          <div className="bg-white border border-gray-200 shadow-sm rounded-md overflow-hidden">
            <Table>
              <TableHeader>
                <TableRow className="bg-gray-100 hover:bg-gray-100">
de8956f8   杨鑫   平台端 门店,菜单,角色
298
299
                  <TableHead className="text-gray-900 font-bold border-r">Partner</TableHead>
                  <TableHead className="text-gray-900 font-bold border-r">Group</TableHead>
884054fb   “wangming”   项目初始化
300
301
302
303
304
305
306
307
308
309
                  <TableHead className="text-gray-900 font-bold border-r">Location ID</TableHead>
                  <TableHead className="text-gray-900 font-bold border-r">Location Name</TableHead>
                  <TableHead className="text-gray-900 font-bold border-r">Street</TableHead>
                  <TableHead className="text-gray-900 font-bold border-r">City</TableHead>
                  <TableHead className="text-gray-900 font-bold border-r">State</TableHead>
                  <TableHead className="text-gray-900 font-bold border-r">Country</TableHead>
                  <TableHead className="text-gray-900 font-bold border-r">Zip Code</TableHead>
                  <TableHead className="text-gray-900 font-bold border-r">Phone</TableHead>
                  <TableHead className="text-gray-900 font-bold border-r">Email</TableHead>
                  <TableHead className="text-gray-900 font-bold border-r">GPS</TableHead>
de8956f8   杨鑫   平台端 门店,菜单,角色
310
                  <TableHead className="text-gray-900 font-bold border-r">Active</TableHead>
884054fb   “wangming”   项目初始化
311
312
313
314
                  <TableHead className="text-gray-900 font-bold text-center">Actions</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
de8956f8   杨鑫   平台端 门店,菜单,角色
315
316
317
318
319
320
321
322
323
324
                {loading ? (
                  <TableRow>
                    <TableCell colSpan={14} className="text-center text-sm text-gray-500 py-10">
                      Loading...
                    </TableCell>
                  </TableRow>
                ) : locations.length === 0 ? (
                  <TableRow>
                    <TableCell colSpan={14} className="text-center text-sm text-gray-500 py-10">
                      No results.
884054fb   “wangming”   项目初始化
325
326
                    </TableCell>
                  </TableRow>
de8956f8   杨鑫   平台端 门店,菜单,角色
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
                ) : (
                  locations.map((loc) => (
                    <TableRow key={loc.id}>
                      <TableCell className="border-r text-gray-600 max-w-[140px] truncate">{toDisplay(loc.partner)}</TableCell>
                      <TableCell className="border-r text-gray-600 max-w-[140px] truncate">{toDisplay(loc.groupName)}</TableCell>
                      <TableCell className="border-r font-numeric text-gray-600">{toDisplay(loc.locationCode ?? loc.id)}</TableCell>
                      <TableCell className="border-r font-medium text-black">{toDisplay(loc.locationName)}</TableCell>
                      <TableCell className="border-r text-gray-600 max-w-[140px] truncate">{toDisplay(loc.street)}</TableCell>
                      <TableCell className="border-r text-gray-600">{toDisplay(loc.city)}</TableCell>
                      <TableCell className="border-r text-gray-600">{toDisplay(loc.stateCode)}</TableCell>
                      <TableCell className="border-r text-gray-600">{toDisplay(loc.country)}</TableCell>
                      <TableCell className="border-r text-gray-600 font-numeric">{toDisplay(loc.zipCode)}</TableCell>
                      <TableCell className="border-r text-gray-600 whitespace-nowrap">{toDisplay(loc.phone)}</TableCell>
                      <TableCell className="border-r text-gray-600 text-sm max-w-[180px] truncate">{toDisplay(loc.email)}</TableCell>
                      <TableCell className="border-r text-gray-500 font-numeric text-xs">{formatGps(loc.latitude, loc.longitude)}</TableCell>
                      <TableCell className="border-r">
                        <Badge className={loc.state ? "bg-green-600" : "bg-gray-400"}>
                          {loc.state ? "Yes" : "No"}
                        </Badge>
                      </TableCell>
                      <TableCell className="text-center">
                        <Popover
                          open={actionsOpenForId === loc.id}
                          onOpenChange={(open) => setActionsOpenForId(open ? loc.id : null)}
                        >
                          <PopoverTrigger asChild>
                            <Button
                              type="button"
                              variant="ghost"
                              size="icon"
                              className="h-8 w-8"
                              aria-label="Row actions"
                            >
                              <MoreHorizontal className="h-4 w-4 text-gray-500" />
                            </Button>
                          </PopoverTrigger>
                          <PopoverContent align="end" className="w-40 p-1">
                            <Button
                              type="button"
                              variant="ghost"
                              className="w-full justify-start gap-2 h-9 px-2 font-normal"
                              onClick={() => openEdit(loc)}
                            >
                              <Edit className="w-4 h-4" />
                              Edit
                            </Button>
                            <Button
                              type="button"
                              variant="ghost"
3af4878d   杨鑫   产品 标签 关联
376
                              className="w-full justify-start gap-2 h-9 px-2 font-normal text-red-600 hover:text-red-700 hover:bg-red-50"
de8956f8   杨鑫   平台端 门店,菜单,角色
377
378
                              onClick={() => openDelete(loc)}
                            >
3af4878d   杨鑫   产品 标签 关联
379
                              <Trash2 className="w-4 h-4 shrink-0" />
de8956f8   杨鑫   平台端 门店,菜单,角色
380
381
382
383
384
385
386
387
                              Delete
                            </Button>
                          </PopoverContent>
                        </Popover>
                      </TableCell>
                    </TableRow>
                  ))
                )}
884054fb   “wangming”   项目初始化
388
389
390
391
392
              </TableBody>
            </Table>
          </div>
        </div>
  
de8956f8   杨鑫   平台端 门店,菜单,角色
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
        <div className="pt-4">
          <div className="flex items-center justify-between text-sm text-gray-600">
            <div>
              Showing {total === 0 ? 0 : (pageIndex - 1) * pageSize + 1}-
              {Math.min(pageIndex * pageSize, total)} of {total}
            </div>
            <div className="flex items-center gap-3">
              <Select value={String(pageSize)} onValueChange={(v) => setPageSize(Number(v))}>
                <SelectTrigger className="w-[110px] h-9 rounded-md border border-gray-300 bg-white text-gray-900">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  {[10, 20, 50].map((n) => (
                    <SelectItem key={n} value={String(n)}>
                      {n} / page
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
              <Pagination className="mx-0 w-auto justify-end">
                <PaginationContent>
                  <PaginationItem>
                    <PaginationPrevious
                      href="#"
                      size="default"
                      onClick={(e) => {
                        e.preventDefault();
                        setPageIndex((p) => Math.max(1, p - 1));
                      }}
                      aria-disabled={pageIndex <= 1}
                      className={pageIndex <= 1 ? "pointer-events-none opacity-50" : ""}
                    />
                  </PaginationItem>
                  <PaginationItem>
                    <PaginationLink
                      href="#"
                      isActive
                      size="default"
                      onClick={(e) => e.preventDefault()}
                    >
                      Page {pageIndex} / {totalPages}
                    </PaginationLink>
                  </PaginationItem>
                  <PaginationItem>
                    <PaginationNext
                      href="#"
                      size="default"
                      onClick={(e) => {
                        e.preventDefault();
                        setPageIndex((p) => Math.min(totalPages, p + 1));
                      }}
                      aria-disabled={pageIndex >= totalPages}
                      className={pageIndex >= totalPages ? "pointer-events-none opacity-50" : ""}
                    />
                  </PaginationItem>
                </PaginationContent>
              </Pagination>
            </div>
          </div>
        </div>
  
        <CreateLocationDialog
          open={isCreateDialogOpen}
          onOpenChange={setIsCreateDialogOpen}
          onCreated={() => {
            // 新增后强制刷新一次列表;如果当前已在第一页也能刷新。
            setPageIndex(1);
            refreshList();
          }}
        />
  
        <EditLocationDialog
          open={isEditDialogOpen}
          location={editingLocation}
          onOpenChange={(open) => {
            setIsEditDialogOpen(open);
            if (!open) setEditingLocation(null);
          }}
          onUpdated={() => {
            // 编辑后强制刷新一次列表
            refreshList();
          }}
        />
  
        <DeleteLocationDialog
          open={isDeleteDialogOpen}
          location={deletingLocation}
          onOpenChange={(open) => {
            setIsDeleteDialogOpen(open);
            if (!open) setDeletingLocation(null);
          }}
          onDeleted={() => {
            refreshList();
          }}
        />
884054fb   “wangming”   项目初始化
488
489
490
491
492
493
      </div>
    );
  }
  
  // --- Sub-components ---
  
de8956f8   杨鑫   平台端 门店,菜单,角色
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
  function CreateLocationDialog({
    open,
    onOpenChange,
    onCreated,
  }: {
    open: boolean;
    onOpenChange: (open: boolean) => void;
    onCreated: () => void;
  }) {
    const [submitting, setSubmitting] = useState(false);
    const [form, setForm] = useState<LocationCreateInput>({
      partner: "",
      groupName: "",
      locationCode: "",
      locationName: "",
      street: "",
      city: "",
      stateCode: "",
      country: "",
      zipCode: "",
      phone: "",
      email: "",
      latitude: null,
      longitude: null,
      state: true,
    });
  
    const resetForm = () => {
      setForm({
        partner: "",
        groupName: "",
        locationCode: "",
        locationName: "",
        street: "",
        city: "",
        stateCode: "",
        country: "",
        zipCode: "",
        phone: "",
        email: "",
        latitude: null,
        longitude: null,
        state: true,
      });
    };
  
    useEffect(() => {
      if (!open) {
        resetForm();
        setSubmitting(false);
      }
    }, [open]);
  
de8956f8   杨鑫   平台端 门店,菜单,角色
547
    const submit = async () => {
3d4c10ac   杨鑫   对接,标签产品
548
549
      const errs = getLocationRedBoxValidationErrors(form);
      if (errs.length) {
de8956f8   杨鑫   平台端 门店,菜单,角色
550
        toast.error("Please fill in required fields.", {
3d4c10ac   杨鑫   对接,标签产品
551
          description: `Missing: ${errs.join(", ")}.`,
de8956f8   杨鑫   平台端 门店,菜单,角色
552
553
554
555
556
557
558
559
560
561
562
        });
        return;
      }
      setSubmitting(true);
      try {
        await createLocation({
          ...form,
          locationCode: form.locationCode.trim(),
          locationName: form.locationName.trim(),
          partner: form.partner?.trim() ? form.partner.trim() : null,
          groupName: form.groupName?.trim() ? form.groupName.trim() : null,
3d4c10ac   杨鑫   对接,标签产品
563
564
565
566
567
568
569
570
571
          street: (form.street ?? "").trim(),
          city: (form.city ?? "").trim(),
          stateCode: (form.stateCode ?? "").trim(),
          country: (form.country ?? "").trim(),
          zipCode: (form.zipCode ?? "").trim(),
          phone: (form.phone ?? "").trim(),
          email: (form.email ?? "").trim(),
          latitude: form.latitude!,
          longitude: form.longitude!,
de8956f8   杨鑫   平台端 门店,菜单,角色
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
        });
        toast.success("Location created.", {
          description: "The location has been added successfully.",
        });
        onOpenChange(false);
        onCreated();
      } catch (e: any) {
        toast.error("Failed to create location.", {
          description: e?.message ? String(e.message) : "Please try again.",
        });
      } finally {
        setSubmitting(false);
      }
    };
  
884054fb   “wangming”   项目初始化
587
588
589
590
591
592
593
594
595
596
597
598
599
600
    return (
      <Dialog open={open} onOpenChange={onOpenChange}>
        <DialogContent className="sm:max-w-[600px]">
          <DialogHeader>
            <DialogTitle>Add New Location</DialogTitle>
            <DialogDescription>
              Enter the details for the new store location.
            </DialogDescription>
          </DialogHeader>
          
          <div className="grid gap-4 py-4">
            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label>Partner</Label>
de8956f8   杨鑫   平台端 门店,菜单,角色
601
602
603
604
605
                <Input
                  placeholder="e.g. Global Foods Inc."
                  value={form.partner ?? ""}
                  onChange={(e) => setForm((p) => ({ ...p, partner: e.target.value }))}
                />
884054fb   “wangming”   项目初始化
606
607
608
              </div>
              <div className="space-y-2">
                <Label>Group</Label>
de8956f8   杨鑫   平台端 门店,菜单,角色
609
610
611
612
613
                <Input
                  placeholder="e.g. East Coast Region"
                  value={form.groupName ?? ""}
                  onChange={(e) => setForm((p) => ({ ...p, groupName: e.target.value }))}
                />
884054fb   “wangming”   项目初始化
614
615
616
617
618
              </div>
            </div>
  
            <div className="grid grid-cols-3 gap-4">
               <div className="space-y-2 col-span-1">
3d4c10ac   杨鑫   对接,标签产品
619
                <Label>Location ID *</Label>
de8956f8   杨鑫   平台端 门店,菜单,角色
620
621
622
623
624
                <Input
                  placeholder="e.g. 12345"
                  value={form.locationCode}
                  onChange={(e) => setForm((p) => ({ ...p, locationCode: e.target.value }))}
                />
884054fb   “wangming”   项目初始化
625
626
              </div>
              <div className="space-y-2 col-span-2">
3d4c10ac   杨鑫   对接,标签产品
627
                <Label>Location Name *</Label>
de8956f8   杨鑫   平台端 门店,菜单,角色
628
629
630
631
632
                <Input
                  placeholder="e.g. Downtown Store"
                  value={form.locationName}
                  onChange={(e) => setForm((p) => ({ ...p, locationName: e.target.value }))}
                />
884054fb   “wangming”   项目初始化
633
634
635
636
              </div>
            </div>
  
            <div className="space-y-2">
3d4c10ac   杨鑫   对接,标签产品
637
              <Label>Street *</Label>
de8956f8   杨鑫   平台端 门店,菜单,角色
638
639
640
641
642
              <Input
                placeholder="e.g. 123 Main St"
                value={form.street ?? ""}
                onChange={(e) => setForm((p) => ({ ...p, street: e.target.value }))}
              />
884054fb   “wangming”   项目初始化
643
644
645
646
            </div>
  
            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2">
3d4c10ac   杨鑫   对接,标签产品
647
                <Label>City *</Label>
de8956f8   杨鑫   平台端 门店,菜单,角色
648
649
650
651
652
                <Input
                  placeholder="e.g. New York"
                  value={form.city ?? ""}
                  onChange={(e) => setForm((p) => ({ ...p, city: e.target.value }))}
                />
884054fb   “wangming”   项目初始化
653
654
              </div>
              <div className="space-y-2">
3d4c10ac   杨鑫   对接,标签产品
655
                <Label>State *</Label>
de8956f8   杨鑫   平台端 门店,菜单,角色
656
657
658
659
660
                <Input
                  placeholder="e.g. NY"
                  value={form.stateCode ?? ""}
                  onChange={(e) => setForm((p) => ({ ...p, stateCode: e.target.value }))}
                />
884054fb   “wangming”   项目初始化
661
662
663
664
665
              </div>
            </div>
  
            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2">
3d4c10ac   杨鑫   对接,标签产品
666
                <Label>Country *</Label>
de8956f8   杨鑫   平台端 门店,菜单,角色
667
668
669
670
671
                <Input
                  placeholder="e.g. USA"
                  value={form.country ?? ""}
                  onChange={(e) => setForm((p) => ({ ...p, country: e.target.value }))}
                />
884054fb   “wangming”   项目初始化
672
673
              </div>
              <div className="space-y-2">
3d4c10ac   杨鑫   对接,标签产品
674
                <Label>Zip Code *</Label>
de8956f8   杨鑫   平台端 门店,菜单,角色
675
676
677
678
679
                <Input
                  placeholder="e.g. 10001"
                  value={form.zipCode ?? ""}
                  onChange={(e) => setForm((p) => ({ ...p, zipCode: e.target.value }))}
                />
884054fb   “wangming”   项目初始化
680
681
682
683
684
              </div>
            </div>
  
            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2">
3d4c10ac   杨鑫   对接,标签产品
685
                <Label>Phone Number *</Label>
de8956f8   杨鑫   平台端 门店,菜单,角色
686
687
688
689
690
                <Input
                  placeholder="+1 (555) 000-0000"
                  value={form.phone ?? ""}
                  onChange={(e) => setForm((p) => ({ ...p, phone: e.target.value }))}
                />
884054fb   “wangming”   项目初始化
691
692
              </div>
              <div className="space-y-2">
3d4c10ac   杨鑫   对接,标签产品
693
                <Label>Email *</Label>
de8956f8   杨鑫   平台端 门店,菜单,角色
694
695
696
697
698
                <Input
                  placeholder="store@example.com"
                  value={form.email ?? ""}
                  onChange={(e) => setForm((p) => ({ ...p, email: e.target.value }))}
                />
884054fb   “wangming”   项目初始化
699
700
701
702
703
              </div>
            </div>
  
            <div className="space-y-2">
              <Label className="flex items-center gap-2">
3d4c10ac   杨鑫   对接,标签产品
704
                <MapPin className="w-4 h-4" /> GPS Coordinates *
884054fb   “wangming”   项目初始化
705
706
              </Label>
              <div className="grid grid-cols-2 gap-4">
de8956f8   杨鑫   平台端 门店,菜单,角色
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
                <Input
                  placeholder="Latitude (e.g. 40.7128)"
                  value={form.latitude === null || form.latitude === undefined ? "" : String(form.latitude)}
                  onChange={(e) => {
                    const raw = e.target.value.trim();
                    setForm((p) => ({ ...p, latitude: raw ? Number(raw) : null }));
                  }}
                />
                <Input
                  placeholder="Longitude (e.g. -74.0060)"
                  value={form.longitude === null || form.longitude === undefined ? "" : String(form.longitude)}
                  onChange={(e) => {
                    const raw = e.target.value.trim();
                    setForm((p) => ({ ...p, longitude: raw ? Number(raw) : null }));
                  }}
                />
884054fb   “wangming”   项目初始化
723
724
725
726
              </div>
            </div>
  
             <div className="flex items-center gap-2 pt-2">
de8956f8   杨鑫   平台端 门店,菜单,角色
727
728
729
730
731
              <Switch
                id="loc-status"
                checked={!!form.state}
                onCheckedChange={(v) => setForm((p) => ({ ...p, state: v }))}
              />
884054fb   “wangming”   项目初始化
732
733
734
735
736
737
738
              <Label htmlFor="loc-status">Active Location</Label>
            </div>
  
          </div>
  
          <DialogFooter>
            <Button variant="outline" onClick={() => onOpenChange(false)}>Cancel</Button>
de8956f8   杨鑫   平台端 门店,菜单,角色
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
            <Button
              disabled={submitting}
              onClick={submit}
              className="bg-blue-600 text-white hover:bg-blue-700"
            >
              {submitting ? "Creating..." : "Create Location"}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    );
  }
  
  function fromDtoToForm(loc: LocationDto): LocationCreateInput {
    return {
      partner: loc.partner ?? "",
      groupName: loc.groupName ?? "",
      locationCode: loc.locationCode ?? "",
      locationName: loc.locationName ?? "",
      street: loc.street ?? "",
      city: loc.city ?? "",
      stateCode: loc.stateCode ?? "",
      country: loc.country ?? "",
      zipCode: loc.zipCode ?? "",
      phone: loc.phone ?? "",
      email: loc.email ?? "",
      latitude: loc.latitude ?? null,
      longitude: loc.longitude ?? null,
      state: !!loc.state,
    };
  }
  
  function EditLocationDialog({
    open,
    location,
    onOpenChange,
    onUpdated,
  }: {
    open: boolean;
    location: LocationDto | null;
    onOpenChange: (open: boolean) => void;
    onUpdated: () => void;
  }) {
    const [submitting, setSubmitting] = useState(false);
    const [form, setForm] = useState<LocationCreateInput>({
      partner: "",
      groupName: "",
      locationCode: "",
      locationName: "",
      street: "",
      city: "",
      stateCode: "",
      country: "",
      zipCode: "",
      phone: "",
      email: "",
      latitude: null,
      longitude: null,
      state: true,
    });
  
    useEffect(() => {
      if (open && location) {
        setForm(fromDtoToForm(location));
        setSubmitting(false);
      }
      if (!open) setSubmitting(false);
    }, [open, location]);
  
de8956f8   杨鑫   平台端 门店,菜单,角色
808
809
    const submit = async () => {
      if (!location?.id) return;
3d4c10ac   杨鑫   对接,标签产品
810
811
      const errs = getLocationRedBoxValidationErrors(form);
      if (errs.length) {
de8956f8   杨鑫   平台端 门店,菜单,角色
812
        toast.error("Please fill in required fields.", {
3d4c10ac   杨鑫   对接,标签产品
813
          description: `Missing: ${errs.join(", ")}.`,
de8956f8   杨鑫   平台端 门店,菜单,角色
814
815
816
817
818
819
820
821
822
823
824
825
        });
        return;
      }
  
      setSubmitting(true);
      try {
        await updateLocation(location.id, {
          ...form,
          locationCode: form.locationCode.trim(),
          locationName: form.locationName.trim(),
          partner: form.partner?.trim() ? form.partner.trim() : null,
          groupName: form.groupName?.trim() ? form.groupName.trim() : null,
3d4c10ac   杨鑫   对接,标签产品
826
827
828
829
830
831
832
833
834
          street: (form.street ?? "").trim(),
          city: (form.city ?? "").trim(),
          stateCode: (form.stateCode ?? "").trim(),
          country: (form.country ?? "").trim(),
          zipCode: (form.zipCode ?? "").trim(),
          phone: (form.phone ?? "").trim(),
          email: (form.email ?? "").trim(),
          latitude: form.latitude!,
          longitude: form.longitude!,
de8956f8   杨鑫   平台端 门店,菜单,角色
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
        });
  
        toast.success("Location updated.", {
          description: "The changes have been saved successfully.",
        });
        onOpenChange(false);
        onUpdated();
      } catch (e: any) {
        toast.error("Failed to update location.", {
          description: e?.message ? String(e.message) : "Please try again.",
        });
      } finally {
        setSubmitting(false);
      }
    };
  
    return (
      <Dialog open={open} onOpenChange={onOpenChange}>
        <DialogContent className="sm:max-w-[600px]">
          <DialogHeader>
            <DialogTitle>Edit Location</DialogTitle>
            <DialogDescription>
              Update the details for this store location.
            </DialogDescription>
          </DialogHeader>
  
          <div className="grid gap-4 py-4">
            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label>Partner</Label>
                <Input
                  placeholder="e.g. Global Foods Inc."
                  value={form.partner ?? ""}
                  onChange={(e) => setForm((p) => ({ ...p, partner: e.target.value }))}
                />
              </div>
              <div className="space-y-2">
                <Label>Group</Label>
                <Input
                  placeholder="e.g. East Coast Region"
                  value={form.groupName ?? ""}
                  onChange={(e) => setForm((p) => ({ ...p, groupName: e.target.value }))}
                />
              </div>
            </div>
  
            <div className="grid grid-cols-3 gap-4">
              <div className="space-y-2 col-span-1">
3d4c10ac   杨鑫   对接,标签产品
883
                <Label>Location ID *</Label>
de8956f8   杨鑫   平台端 门店,菜单,角色
884
885
886
887
888
889
890
                <Input
                  placeholder="e.g. 12345"
                  value={form.locationCode}
                  onChange={(e) => setForm((p) => ({ ...p, locationCode: e.target.value }))}
                />
              </div>
              <div className="space-y-2 col-span-2">
3d4c10ac   杨鑫   对接,标签产品
891
                <Label>Location Name *</Label>
de8956f8   杨鑫   平台端 门店,菜单,角色
892
893
894
895
896
897
898
899
900
                <Input
                  placeholder="e.g. Downtown Store"
                  value={form.locationName}
                  onChange={(e) => setForm((p) => ({ ...p, locationName: e.target.value }))}
                />
              </div>
            </div>
  
            <div className="space-y-2">
3d4c10ac   杨鑫   对接,标签产品
901
              <Label>Street *</Label>
de8956f8   杨鑫   平台端 门店,菜单,角色
902
903
904
905
906
907
908
909
910
              <Input
                placeholder="e.g. 123 Main St"
                value={form.street ?? ""}
                onChange={(e) => setForm((p) => ({ ...p, street: e.target.value }))}
              />
            </div>
  
            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2">
3d4c10ac   杨鑫   对接,标签产品
911
                <Label>City *</Label>
de8956f8   杨鑫   平台端 门店,菜单,角色
912
913
914
915
916
917
918
                <Input
                  placeholder="e.g. New York"
                  value={form.city ?? ""}
                  onChange={(e) => setForm((p) => ({ ...p, city: e.target.value }))}
                />
              </div>
              <div className="space-y-2">
3d4c10ac   杨鑫   对接,标签产品
919
                <Label>State *</Label>
de8956f8   杨鑫   平台端 门店,菜单,角色
920
921
922
923
924
925
926
927
928
929
                <Input
                  placeholder="e.g. NY"
                  value={form.stateCode ?? ""}
                  onChange={(e) => setForm((p) => ({ ...p, stateCode: e.target.value }))}
                />
              </div>
            </div>
  
            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2">
3d4c10ac   杨鑫   对接,标签产品
930
                <Label>Country *</Label>
de8956f8   杨鑫   平台端 门店,菜单,角色
931
932
933
934
935
936
937
                <Input
                  placeholder="e.g. USA"
                  value={form.country ?? ""}
                  onChange={(e) => setForm((p) => ({ ...p, country: e.target.value }))}
                />
              </div>
              <div className="space-y-2">
3d4c10ac   杨鑫   对接,标签产品
938
                <Label>Zip Code *</Label>
de8956f8   杨鑫   平台端 门店,菜单,角色
939
940
941
942
943
944
945
946
947
948
                <Input
                  placeholder="e.g. 10001"
                  value={form.zipCode ?? ""}
                  onChange={(e) => setForm((p) => ({ ...p, zipCode: e.target.value }))}
                />
              </div>
            </div>
  
            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2">
3d4c10ac   杨鑫   对接,标签产品
949
                <Label>Phone Number *</Label>
de8956f8   杨鑫   平台端 门店,菜单,角色
950
951
952
953
954
955
956
                <Input
                  placeholder="+1 (555) 000-0000"
                  value={form.phone ?? ""}
                  onChange={(e) => setForm((p) => ({ ...p, phone: e.target.value }))}
                />
              </div>
              <div className="space-y-2">
3d4c10ac   杨鑫   对接,标签产品
957
                <Label>Email *</Label>
de8956f8   杨鑫   平台端 门店,菜单,角色
958
959
960
961
962
963
964
965
966
967
                <Input
                  placeholder="store@example.com"
                  value={form.email ?? ""}
                  onChange={(e) => setForm((p) => ({ ...p, email: e.target.value }))}
                />
              </div>
            </div>
  
            <div className="space-y-2">
              <Label className="flex items-center gap-2">
3d4c10ac   杨鑫   对接,标签产品
968
                <MapPin className="w-4 h-4" /> GPS Coordinates *
de8956f8   杨鑫   平台端 门店,菜单,角色
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
              </Label>
              <div className="grid grid-cols-2 gap-4">
                <Input
                  placeholder="Latitude (e.g. 40.7128)"
                  value={form.latitude === null || form.latitude === undefined ? "" : String(form.latitude)}
                  onChange={(e) => {
                    const raw = e.target.value.trim();
                    setForm((p) => ({ ...p, latitude: raw ? Number(raw) : null }));
                  }}
                />
                <Input
                  placeholder="Longitude (e.g. -74.0060)"
                  value={form.longitude === null || form.longitude === undefined ? "" : String(form.longitude)}
                  onChange={(e) => {
                    const raw = e.target.value.trim();
                    setForm((p) => ({ ...p, longitude: raw ? Number(raw) : null }));
                  }}
                />
              </div>
            </div>
  
            <div className="flex items-center gap-2 pt-2">
              <Switch
                id="loc-status-edit"
                checked={!!form.state}
                onCheckedChange={(v) => setForm((p) => ({ ...p, state: v }))}
              />
              <Label htmlFor="loc-status-edit">Active Location</Label>
            </div>
          </div>
  
          <DialogFooter>
            <Button variant="outline" onClick={() => onOpenChange(false)}>Cancel</Button>
            <Button
              disabled={submitting}
              onClick={submit}
              className="bg-blue-600 text-white hover:bg-blue-700"
            >
              {submitting ? "Saving..." : "Save Changes"}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    );
  }
  
  function DeleteLocationDialog({
    open,
    location,
    onOpenChange,
    onDeleted,
  }: {
    open: boolean;
    location: LocationDto | null;
    onOpenChange: (open: boolean) => void;
    onDeleted: () => void;
  }) {
    const [submitting, setSubmitting] = useState(false);
  
    const name = useMemo(() => {
      const code = (location?.locationCode ?? "").trim();
      const n = (location?.locationName ?? "").trim();
      if (code && n) return `${code} - ${n}`;
      return code || n || "this location";
    }, [location?.locationCode, location?.locationName]);
  
    const submit = async () => {
      if (!location?.id) return;
      setSubmitting(true);
      try {
        await deleteLocation(location.id);
        toast.success("Location deleted.", {
          description: "The location has been removed successfully.",
        });
        onOpenChange(false);
        onDeleted();
      } catch (e: any) {
        toast.error("Failed to delete location.", {
          description: e?.message ? String(e.message) : "Please try again.",
        });
      } finally {
        setSubmitting(false);
      }
    };
  
    return (
      <Dialog open={open} onOpenChange={onOpenChange}>
        <DialogContent className="sm:max-w-none" style={{ width: "30%" }}>
          <DialogHeader>
            <DialogTitle>Delete Location</DialogTitle>
            <DialogDescription>
              This action cannot be undone.
            </DialogDescription>
          </DialogHeader>
  
          <div className="text-sm text-gray-700">
            Are you sure you want to delete <span className="font-medium">{name}</span>?
          </div>
  
          <DialogFooter className="flex-row flex-wrap justify-end">
            <Button className="min-w-24" variant="outline" onClick={() => onOpenChange(false)}>Cancel</Button>
            <Button
3af4878d   杨鑫   产品 标签 关联
1071
              className="min-w-24 gap-2"
de8956f8   杨鑫   平台端 门店,菜单,角色
1072
1073
1074
1075
              variant="destructive"
              disabled={submitting}
              onClick={submit}
            >
3af4878d   杨鑫   产品 标签 关联
1076
              <Trash2 className="h-4 w-4 shrink-0" />
de8956f8   杨鑫   平台端 门店,菜单,角色
1077
1078
              {submitting ? "Deleting..." : "Delete"}
            </Button>
884054fb   “wangming”   项目初始化
1079
1080
1081
1082
1083
          </DialogFooter>
        </DialogContent>
      </Dialog>
    );
  }