Blame view

美国版/Food Labeling Management Platform/src/components/labels/MultipleOptionsView.tsx 45.2 KB
ef6b3255   杨鑫   修改BUG
1
  import React, { useCallback, useEffect, useMemo, useRef, useState } from "react";
884054fb   “wangming”   项目初始化
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
  import {
    Table,
    TableBody,
    TableCell,
    TableHead,
    TableHeader,
    TableRow,
  } from "../ui/table";
  import { Input } from "../ui/input";
  import { Button } from "../ui/button";
  import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
  } from "../ui/select";
0e27ddc8   杨鑫   标签
19
20
21
22
23
24
25
26
27
28
29
  import {
    Dialog,
    DialogContent,
    DialogDescription,
    DialogFooter,
    DialogHeader,
    DialogTitle,
  } from "../ui/dialog";
  import { Label } from "../ui/label";
  import { Switch } from "../ui/switch";
  import { Badge } from "../ui/badge";
3af4878d   杨鑫   产品 标签 关联
30
  import { Plus, Edit, MoreHorizontal, X, Trash2 } from "lucide-react";
0e27ddc8   杨鑫   标签
31
  import { toast } from "sonner";
143afd59   杨鑫   打印,标签
32
  import { skipCountForPage } from "../../lib/paginationQuery";
0e27ddc8   杨鑫   标签
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
  import { Popover, PopoverContent, PopoverTrigger } from "../ui/popover";
  import {
    Pagination,
    PaginationContent,
    PaginationItem,
    PaginationLink,
    PaginationNext,
    PaginationPrevious,
  } from "../ui/pagination";
  import {
    getLabelMultipleOptions,
    getLabelMultipleOption,
    createLabelMultipleOption,
    updateLabelMultipleOption,
    deleteLabelMultipleOption,
  } from "../../services/labelMultipleOptionService";
ef6b3255   杨鑫   修改BUG
49
50
51
  import { getLabels } from "../../services/labelService";
  import { getLocations } from "../../services/locationService";
  import { getGroups } from "../../services/groupService";
91821909   杨鑫   最新
52
53
54
55
56
57
58
59
60
61
  import { getPartners } from "../../services/partnerService";
  import {
    buildSpecifiedLocationPayload,
    effectiveScopePartnerId,
    hydrateCategoryScopeFromLocationIds,
    regionNamesToGroupIds,
    scopePartnerValidationMessage,
  } from "../../lib/categoryScopeForm";
  import { CategoryScopeFields } from "../shared/category-scope-fields";
  import { useCategoryScopeAuth } from "../../hooks/useCategoryScopeAuth";
0e27ddc8   杨鑫   标签
62
63
64
65
66
  import type {
    LabelMultipleOptionDto,
    LabelMultipleOptionCreateInput,
    LabelMultipleOptionUpdateInput,
  } from "../../types/labelMultipleOption";
ef6b3255   杨鑫   修改BUG
67
68
  import type { LocationDto } from "../../types/location";
  import type { GroupListItem } from "../../types/group";
91821909   杨鑫   最新
69
  import type { PartnerListItem } from "../../types/partner";
ef6b3255   杨鑫   修改BUG
70
  import { cn } from "../ui/utils";
0e27ddc8   杨鑫   标签
71
72
73
74
75
  
  function toDisplay(v: string | null | undefined): string {
    const s = (v ?? "").trim();
    return s ? s : "None";
  }
884054fb   “wangming”   项目初始化
76
  
91821909   杨鑫   最新
77
78
79
80
81
82
83
84
85
86
87
  /** 新增时由名称生成编码(界面不再手填 Option Code) */
  function optionCodeFromName(name: string): string {
    const slug = name
      .trim()
      .toUpperCase()
      .replace(/[^A-Z0-9]+/g, "_")
      .replace(/^_+|_+$/g, "")
      .slice(0, 40);
    return slug ? `OPT_${slug}` : `OPT_${Date.now()}`;
  }
  
ef6b3255   杨鑫   修改BUG
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
156
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
  /** 列表行单元格统一字体(与 Label Types / Label Categories 一致) */
  const LIST_ROW_CELL = "text-sm font-normal font-sans text-gray-900";
  const LIST_ROW_CELL_NOWRAP = `${LIST_ROW_CELL} whitespace-nowrap`;
  const LIST_STATUS_BADGE = "!text-sm !font-normal font-sans normal-case border-0";
  
  function resolveScopedLocationIds(
    regionFilter: string,
    locationFilter: string,
    locationCatalog: LocationDto[],
    filterGroups: GroupListItem[],
  ): string[] | null {
    if (regionFilter === "all" && locationFilter === "all") return null;
    if (locationFilter !== "all") {
      const lid = locationFilter.trim();
      return lid ? [lid] : [];
    }
    const g = filterGroups.find((x) => x.id === regionFilter);
    if (!g) return [];
    const gn = (g.groupName ?? "").trim();
    const pn = (g.partnerName ?? "").trim();
    return locationCatalog
      .filter((l) => (l.groupName ?? "").trim() === gn && (l.partner ?? "").trim() === pn)
      .map((l) => l.id)
      .filter(Boolean);
  }
  
  function collectMultipleOptionIdsFromValue(value: unknown, out: Set<string>): void {
    if (value == null) return;
    if (Array.isArray(value)) {
      for (const v of value) collectMultipleOptionIdsFromValue(v, out);
      return;
    }
    if (typeof value === "object") {
      for (const [k, v] of Object.entries(value as Record<string, unknown>)) {
        if (k === "multipleOptionId" || k === "MultipleOptionId") {
          const id = String(v ?? "").trim();
          if (id) out.add(id);
        }
        collectMultipleOptionIdsFromValue(v, out);
      }
    }
  }
  
  async function fetchMultipleOptionIdsInLocations(
    locationIds: string[],
    signal: AbortSignal,
  ): Promise<Set<string>> {
    const optionIds = new Set<string>();
    for (const lid of locationIds) {
      let page = 1;
      for (;;) {
        const res = await getLabels(
          {
            skipCount: skipCountForPage(page),
            maxResultCount: 500,
            locationId: lid,
          },
          signal,
        );
        for (const lbl of res.items ?? []) {
          collectMultipleOptionIdsFromValue(lbl.labelInfoJson, optionIds);
        }
        if ((res.items?.length ?? 0) < 500) break;
        page += 1;
        if (page > 50) break;
      }
      if (signal.aborted) break;
    }
    return optionIds;
  }
  
  function locationsForOptionScope(opt: LabelMultipleOptionDto, catalog: LocationDto[]): LocationDto[] {
    const idSet = new Set((opt.locationIds ?? []).map((x) => String(x).trim()).filter(Boolean));
    if (!idSet.size) return [];
    return catalog.filter((l) => idSet.has(l.id));
  }
  
  function optionMatchesRegionFilter(
    opt: LabelMultipleOptionDto,
    regionFilterId: string,
    catalog: LocationDto[],
    groups: GroupListItem[],
  ): boolean {
    if (regionFilterId === "all") return true;
    const g = groups.find((x) => x.id === regionFilterId);
    if (!g) return true;
    const gn = (g.groupName ?? "").trim();
    const pn = (g.partnerName ?? "").trim();
    const matched = locationsForOptionScope(opt, catalog);
    if (!matched.length) return true;
    return matched.some(
      (l) => (l.groupName ?? "").trim() === gn && (l.partner ?? "").trim() === pn,
    );
  }
  
  function optionMatchesLocationFilter(opt: LabelMultipleOptionDto, locationFilterId: string): boolean {
    if (locationFilterId === "all") return true;
    const lid = locationFilterId.trim();
    if (!lid) return true;
    const lids = new Set((opt.locationIds ?? []).map((x) => String(x).trim()).filter(Boolean));
    if (!lids.size) return true;
    return lids.has(lid);
  }
  
ef6b3255   杨鑫   修改BUG
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
  function labelInfoJsonReferencesOptionId(value: unknown, optionId: string): boolean {
    const ids = new Set<string>();
    collectMultipleOptionIdsFromValue(value, ids);
    return ids.has(optionId);
  }
  
  async function fetchLocationIdsForMultipleOption(optionId: string, signal?: AbortSignal): Promise<string[]> {
    const lids: string[] = [];
    let page = 1;
    for (;;) {
      const res = await getLabels(
        {
          skipCount: skipCountForPage(page),
          maxResultCount: 500,
        },
        signal,
      );
      for (const lbl of res.items ?? []) {
        if (!labelInfoJsonReferencesOptionId(lbl.labelInfoJson, optionId)) continue;
        const id = (lbl.locationId ?? "").trim();
        if (id) lids.push(id);
      }
      if ((res.items?.length ?? 0) < 500) break;
      page += 1;
      if (page > 50) break;
    }
    return [...new Set(lids)];
  }
  
ef6b3255   杨鑫   修改BUG
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
  async function fetchAllLabelMultipleOptionsMatching(
    keyword: string | undefined,
    state: boolean | undefined,
    signal: AbortSignal,
  ): Promise<LabelMultipleOptionDto[]> {
    const out: LabelMultipleOptionDto[] = [];
    let page = 1;
    const size = 500;
    for (;;) {
      const res = await getLabelMultipleOptions(
        {
          skipCount: skipCountForPage(page),
          maxResultCount: size,
          keyword,
          state,
        },
        signal,
      );
      const items = res.items ?? [];
      out.push(...items);
      if (items.length < size) break;
      page += 1;
      if (page > 200) break;
    }
    return out;
  }
  
884054fb   “wangming”   项目初始化
248
  export function MultipleOptionsView() {
91821909   杨鑫   最新
249
    const scopeAuth = useCategoryScopeAuth();
0e27ddc8   杨鑫   标签
250
251
252
253
254
255
256
257
258
259
260
261
    const [isCreateDialogOpen, setIsCreateDialogOpen] = useState(false);
    const [isEditDialogOpen, setIsEditDialogOpen] = useState(false);
    const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false);
    const [editingOption, setEditingOption] = useState<LabelMultipleOptionDto | null>(null);
    const [deletingOption, setDeletingOption] = useState<LabelMultipleOptionDto | null>(null);
    const [options, setOptions] = useState<LabelMultipleOptionDto[]>([]);
    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("");
ef6b3255   杨鑫   修改BUG
262
263
    const [regionFilter, setRegionFilter] = useState("all");
    const [locationFilter, setLocationFilter] = useState("all");
0e27ddc8   杨鑫   标签
264
265
266
267
268
    const [stateFilter, setStateFilter] = useState<string>("all");
  
    const [pageIndex, setPageIndex] = useState(1);
    const [pageSize, setPageSize] = useState(10);
  
ef6b3255   杨鑫   修改BUG
269
270
    const [locationCatalog, setLocationCatalog] = useState<LocationDto[]>([]);
    const [filterGroups, setFilterGroups] = useState<GroupListItem[]>([]);
91821909   杨鑫   最新
271
    const [filterPartners, setFilterPartners] = useState<PartnerListItem[]>([]);
ef6b3255   杨鑫   修改BUG
272
  
0e27ddc8   杨鑫   标签
273
274
275
276
    const abortRef = useRef<AbortController | null>(null);
    const keywordTimerRef = useRef<number | null>(null);
    const [debouncedKeyword, setDebouncedKeyword] = useState("");
  
ef6b3255   杨鑫   修改BUG
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
    const regionSelectOptions = useMemo(() => {
      const m = new Map<string, GroupListItem>();
      for (const g of filterGroups) {
        const id = (g.id ?? "").trim();
        if (id && !m.has(id)) m.set(id, g);
      }
      return Array.from(m.values()).sort((a, b) =>
        (a.groupName ?? "").localeCompare(b.groupName ?? "", undefined, { sensitivity: "base" }),
      );
    }, [filterGroups]);
  
    const locationsForToolbarFilter = useMemo(() => {
      if (regionFilter === "all") return locationCatalog;
      const g = filterGroups.find((x) => x.id === regionFilter);
      if (!g) return locationCatalog;
      const gn = (g.groupName ?? "").trim();
      const pn = (g.partnerName ?? "").trim();
      return locationCatalog.filter(
        (l) => (l.groupName ?? "").trim() === gn && (l.partner ?? "").trim() === pn,
      );
    }, [locationCatalog, filterGroups, regionFilter]);
  
    useEffect(() => {
      setLocationFilter("all");
    }, [regionFilter]);
  
    useEffect(() => {
      if (locationFilter === "all") return;
      const allowed = new Set(locationsForToolbarFilter.map((l) => l.id));
      if (!allowed.has(locationFilter)) setLocationFilter("all");
    }, [locationsForToolbarFilter, locationFilter]);
  
    useEffect(() => {
      let cancelled = false;
      (async () => {
        try {
          const out: LocationDto[] = [];
          let locPage = 1;
          const locSize = 500;
          for (;;) {
            const res = await getLocations({
              skipCount: skipCountForPage(locPage),
              maxResultCount: locSize,
            });
            out.push(...(res.items ?? []));
            if (!res.items || res.items.length < locSize) break;
            locPage += 1;
            if (locPage > 200) break;
          }
91821909   杨鑫   最新
326
327
328
329
          const [grpRes, partnerRes] = await Promise.all([
            getGroups({ skipCount: 1, maxResultCount: 500 }),
            getPartners({ skipCount: 1, maxResultCount: 500, state: true }),
          ]);
ef6b3255   杨鑫   修改BUG
330
331
332
          if (cancelled) return;
          setLocationCatalog(out);
          setFilterGroups(grpRes.items ?? []);
91821909   杨鑫   最新
333
          setFilterPartners(partnerRes.items ?? []);
ef6b3255   杨鑫   修改BUG
334
335
336
337
        } catch {
          if (!cancelled) {
            setLocationCatalog([]);
            setFilterGroups([]);
91821909   杨鑫   最新
338
            setFilterPartners([]);
ef6b3255   杨鑫   修改BUG
339
340
341
342
343
344
345
346
          }
        }
      })();
      return () => {
        cancelled = true;
      };
    }, []);
  
0e27ddc8   杨鑫   标签
347
348
349
350
351
352
353
354
355
356
357
358
    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]);
  
    const totalPages = Math.max(1, Math.ceil(total / pageSize));
  
    useEffect(() => {
      setPageIndex(1);
ef6b3255   杨鑫   修改BUG
359
    }, [debouncedKeyword, regionFilter, locationFilter, stateFilter, pageSize]);
0e27ddc8   杨鑫   标签
360
361
362
363
364
365
366
367
368
  
    useEffect(() => {
      const run = async () => {
        abortRef.current?.abort();
        const ac = new AbortController();
        abortRef.current = ac;
  
        setLoading(true);
        try {
143afd59   杨鑫   打印,标签
369
          const skipCount = skipCountForPage(pageIndex);
ef6b3255   杨鑫   修改BUG
370
371
372
373
374
375
376
377
          const stateBool = stateFilter === "all" ? undefined : stateFilter === "true";
          const kw = debouncedKeyword || undefined;
          const needsClientFilter = regionFilter !== "all" || locationFilter !== "all";
          const scopeLocationIds = resolveScopedLocationIds(
            regionFilter,
            locationFilter,
            locationCatalog,
            filterGroups,
0e27ddc8   杨鑫   标签
378
379
          );
  
ef6b3255   杨鑫   修改BUG
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
          if (!needsClientFilter) {
            const res = await getLabelMultipleOptions(
              {
                skipCount,
                maxResultCount: pageSize,
                keyword: kw,
                state: stateBool,
                groupId: regionFilter !== "all" ? regionFilter : undefined,
                locationId: locationFilter !== "all" ? locationFilter : undefined,
              },
              ac.signal,
            );
  
            setOptions(res.items ?? []);
            setTotal(res.totalCount ?? 0);
          } else {
            const scopedOptionIds = scopeLocationIds?.length
              ? await fetchMultipleOptionIdsInLocations(scopeLocationIds, ac.signal)
              : new Set<string>();
            const all = await fetchAllLabelMultipleOptionsMatching(kw, stateBool, ac.signal);
            const filtered = all.filter((opt) => {
              const hasScope = (opt.locationIds ?? []).some((x) => String(x).trim());
              if (hasScope) {
                return (
                  optionMatchesRegionFilter(opt, regionFilter, locationCatalog, filterGroups) &&
                  optionMatchesLocationFilter(opt, locationFilter)
                );
              }
              return scopedOptionIds.has(opt.id);
            });
            setTotal(filtered.length);
            const start = (pageIndex - 1) * pageSize;
            setOptions(filtered.slice(start, start + pageSize));
          }
0e27ddc8   杨鑫   标签
414
415
416
417
418
419
420
421
422
423
424
425
426
427
        } catch (e: any) {
          if (e?.name === "AbortError") return;
          toast.error("Failed to load multiple options.", {
            description: e?.message ? String(e.message) : "Please try again.",
          });
          setOptions([]);
          setTotal(0);
        } finally {
          setLoading(false);
        }
      };
  
      run();
      return () => abortRef.current?.abort();
ef6b3255   杨鑫   修改BUG
428
429
430
431
432
433
434
435
436
437
438
    }, [
      debouncedKeyword,
      regionFilter,
      locationFilter,
      stateFilter,
      pageIndex,
      pageSize,
      refreshSeq,
      locationCatalog,
      filterGroups,
    ]);
0e27ddc8   杨鑫   标签
439
440
441
442
443
444
445
446
447
448
449
450
451
452
  
    const refreshList = () => setRefreshSeq((x) => x + 1);
  
    const openEdit = (opt: LabelMultipleOptionDto) => {
      setActionsOpenForId(null);
      setEditingOption(opt);
      setIsEditDialogOpen(true);
    };
  
    const openDelete = (opt: LabelMultipleOptionDto) => {
      setActionsOpenForId(null);
      setDeletingOption(opt);
      setIsDeleteDialogOpen(true);
    };
884054fb   “wangming”   项目初始化
453
454
  
    return (
0e27ddc8   杨鑫   标签
455
456
457
458
459
460
461
462
463
464
465
      <div className="h-full flex flex-col">
        <div className="pb-4">
          <div className="flex flex-col gap-4">
            <div className="flex flex-nowrap items-center gap-3">
              <Input
                placeholder="Search"
                value={keyword}
                onChange={(e) => setKeyword(e.target.value)}
                style={{ height: 40, boxSizing: 'border-box' }}
                className="bg-white border border-gray-300 rounded-md w-40 shrink-0 placeholder:text-gray-500"
              />
ef6b3255   杨鑫   修改BUG
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
              <Select value={regionFilter} onValueChange={setRegionFilter}>
                <SelectTrigger
                  className="bg-white border border-gray-300 rounded-md w-[150px] shrink-0"
                  style={{ height: 40, boxSizing: "border-box" }}
                >
                  <SelectValue placeholder="Region" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">All Region</SelectItem>
                  {regionSelectOptions.map((g) => (
                    <SelectItem key={g.id} value={g.id}>
                      {toDisplay(g.groupName)}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
              <Select value={locationFilter} onValueChange={setLocationFilter}>
                <SelectTrigger
                  className="bg-white border border-gray-300 rounded-md w-[170px] shrink-0"
                  style={{ height: 40, boxSizing: "border-box" }}
                >
                  <SelectValue placeholder="Location" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">All Locations</SelectItem>
                  {locationsForToolbarFilter.map((loc) => {
                    const code = (loc.locationCode ?? "").trim();
                    const name = (loc.locationName ?? "").trim();
                    const label = code && name ? `${code} - ${name}` : name || code || loc.id;
                    return (
                      <SelectItem key={loc.id} value={loc.id}>
                        {label}
                      </SelectItem>
                    );
                  })}
                </SelectContent>
              </Select>
0e27ddc8   杨鑫   标签
503
504
              <Select value={stateFilter} onValueChange={setStateFilter}>
                <SelectTrigger className="bg-white border border-gray-300 rounded-md w-[150px] shrink-0" style={{ height: 40, boxSizing: 'border-box' }}>
ef6b3255   杨鑫   修改BUG
505
                  <SelectValue placeholder="Status" />
0e27ddc8   杨鑫   标签
506
507
                </SelectTrigger>
                <SelectContent>
ef6b3255   杨鑫   修改BUG
508
                  <SelectItem value="all">Status</SelectItem>
0e27ddc8   杨鑫   标签
509
510
511
512
513
514
515
516
517
                  <SelectItem value="true">Active</SelectItem>
                  <SelectItem value="false">Inactive</SelectItem>
                </SelectContent>
              </Select>
              <div className="flex-1" />
              <Button
                className="bg-blue-600 hover:bg-blue-700 text-white font-medium rounded-md h-10 px-6 shrink-0"
                onClick={() => setIsCreateDialogOpen(true)}
              >
ef6b3255   杨鑫   修改BUG
518
                New Multiple Option Set <Plus className="ml-1 h-4 w-4" />
0e27ddc8   杨鑫   标签
519
520
521
              </Button>
            </div>
          </div>
884054fb   “wangming”   项目初始化
522
523
        </div>
  
0e27ddc8   杨鑫   标签
524
525
        <div className="flex-1 overflow-auto pt-6">
          <div className="rounded-md border bg-white shadow-sm">
ef6b3255   杨鑫   修改BUG
526
            <Table className="font-sans">
0e27ddc8   杨鑫   标签
527
528
              <TableHeader>
                <TableRow className="bg-gray-50 hover:bg-gray-50">
ef6b3255   杨鑫   修改BUG
529
530
531
532
533
534
                  <TableHead className="text-sm font-semibold font-sans text-gray-900 min-w-[200px]">Multiple Option Set Name</TableHead>
                  <TableHead className="text-sm font-semibold font-sans text-gray-900 min-w-[240px]">Contents</TableHead>
                  <TableHead className="text-sm font-semibold font-sans text-gray-900 w-[100px]">Status</TableHead>
                  <TableHead className="text-sm font-semibold font-sans text-gray-900 w-[130px]">Sequence Order</TableHead>
                  <TableHead className="text-sm font-semibold font-sans text-gray-900 min-w-[140px]">Last Edited</TableHead>
                  <TableHead className="text-sm font-semibold font-sans text-gray-900 text-center w-[100px]">Actions</TableHead>
884054fb   “wangming”   项目初始化
535
                </TableRow>
0e27ddc8   杨鑫   标签
536
537
538
539
              </TableHeader>
              <TableBody>
                {loading ? (
                  <TableRow>
ef6b3255   杨鑫   修改BUG
540
                    <TableCell colSpan={6} className={`text-center ${LIST_ROW_CELL} py-10`}>
0e27ddc8   杨鑫   标签
541
542
543
544
545
                      Loading...
                    </TableCell>
                  </TableRow>
                ) : options.length === 0 ? (
                  <TableRow>
ef6b3255   杨鑫   修改BUG
546
                    <TableCell colSpan={6} className={`text-center ${LIST_ROW_CELL} py-10`}>
0e27ddc8   杨鑫   标签
547
548
549
550
                      No results.
                    </TableCell>
                  </TableRow>
                ) : (
ef6b3255   杨鑫   修改BUG
551
552
553
554
555
556
                  options.map((item) => {
                    const contentsText =
                      item.optionValuesJson && item.optionValuesJson.length > 0
                        ? item.optionValuesJson.join("; ")
                        : "None";
                    return (
0e27ddc8   杨鑫   标签
557
                    <TableRow key={item.id} className="hover:bg-gray-50">
ef6b3255   杨鑫   修改BUG
558
559
560
561
562
563
564
                      <TableCell className={LIST_ROW_CELL_NOWRAP}>
                        {toDisplay(item.optionName)}
                      </TableCell>
                      <TableCell className={`${LIST_ROW_CELL} max-w-[360px]`}>
                        <div className="truncate whitespace-nowrap" title={contentsText}>
                          {contentsText}
                        </div>
0e27ddc8   杨鑫   标签
565
                      </TableCell>
ef6b3255   杨鑫   修改BUG
566
567
568
569
570
571
572
573
574
                      <TableCell className={LIST_ROW_CELL_NOWRAP}>
                        <Badge
                          variant={item.state !== false ? "default" : "secondary"}
                          className={cn(
                            LIST_STATUS_BADGE,
                            item.state !== false ? "bg-green-600" : "bg-gray-400",
                          )}
                        >
                          {item.state !== false ? "active" : "inactive"}
0e27ddc8   杨鑫   标签
575
576
                        </Badge>
                      </TableCell>
ef6b3255   杨鑫   修改BUG
577
578
                      <TableCell className={LIST_ROW_CELL_NOWRAP}>
                        {item.orderNum != null && Number.isFinite(item.orderNum) ? item.orderNum : "—"}
0e27ddc8   杨鑫   标签
579
                      </TableCell>
ef6b3255   杨鑫   修改BUG
580
581
582
583
                      <TableCell className={LIST_ROW_CELL_NOWRAP}>
                        {toDisplay(item.lastEdited)}
                      </TableCell>
                      <TableCell className={`text-center ${LIST_ROW_CELL_NOWRAP}`}>
0e27ddc8   杨鑫   标签
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
                        <Popover
                          open={actionsOpenForId === item.id}
                          onOpenChange={(open) => setActionsOpenForId(open ? item.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(item)}
                            >
                              <Edit className="w-4 h-4" />
                              Edit
                            </Button>
                            <Button
                              type="button"
                              variant="ghost"
3af4878d   杨鑫   产品 标签 关联
612
                              className="w-full justify-start gap-2 h-9 px-2 font-normal text-red-600 hover:text-red-700 hover:bg-red-50"
0e27ddc8   杨鑫   标签
613
614
                              onClick={() => openDelete(item)}
                            >
3af4878d   杨鑫   产品 标签 关联
615
                              <Trash2 className="w-4 h-4 shrink-0" />
0e27ddc8   杨鑫   标签
616
617
618
619
620
621
                              Delete
                            </Button>
                          </PopoverContent>
                        </Popover>
                      </TableCell>
                    </TableRow>
ef6b3255   杨鑫   修改BUG
622
623
                    );
                  })
0e27ddc8   杨鑫   标签
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
                )}
              </TableBody>
            </Table>
          </div>
        </div>
  
        <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>
884054fb   “wangming”   项目初始化
689
        </div>
0e27ddc8   杨鑫   标签
690
691
692
  
        <CreateMultipleOptionDialog
          open={isCreateDialogOpen}
ef6b3255   杨鑫   修改BUG
693
          locations={locationCatalog}
91821909   杨鑫   最新
694
          partners={filterPartners}
ef6b3255   杨鑫   修改BUG
695
          groups={filterGroups}
91821909   杨鑫   最新
696
697
          requireCompanySelection={scopeAuth.requireCompanySelection}
          fixedPartnerId={scopeAuth.fixedPartnerId}
0e27ddc8   杨鑫   标签
698
699
700
701
702
703
704
705
706
707
          onOpenChange={setIsCreateDialogOpen}
          onCreated={() => {
            setPageIndex(1);
            refreshList();
          }}
        />
  
        <EditMultipleOptionDialog
          open={isEditDialogOpen}
          option={editingOption}
ef6b3255   杨鑫   修改BUG
708
          locations={locationCatalog}
91821909   杨鑫   最新
709
          partners={filterPartners}
ef6b3255   杨鑫   修改BUG
710
          groups={filterGroups}
91821909   杨鑫   最新
711
712
          requireCompanySelection={scopeAuth.requireCompanySelection}
          fixedPartnerId={scopeAuth.fixedPartnerId}
0e27ddc8   杨鑫   标签
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
          onOpenChange={(open) => {
            setIsEditDialogOpen(open);
            if (!open) setEditingOption(null);
          }}
          onUpdated={refreshList}
        />
  
        <DeleteMultipleOptionDialog
          open={isDeleteDialogOpen}
          option={deletingOption}
          onOpenChange={(open) => {
            setIsDeleteDialogOpen(open);
            if (!open) setDeletingOption(null);
          }}
          onDeleted={refreshList}
        />
884054fb   “wangming”   项目初始化
729
730
731
      </div>
    );
  }
0e27ddc8   杨鑫   标签
732
733
734
  
  function CreateMultipleOptionDialog({
    open,
ef6b3255   杨鑫   修改BUG
735
    locations,
91821909   杨鑫   最新
736
    partners,
ef6b3255   杨鑫   修改BUG
737
    groups,
91821909   杨鑫   最新
738
739
    requireCompanySelection,
    fixedPartnerId,
0e27ddc8   杨鑫   标签
740
741
742
743
    onOpenChange,
    onCreated,
  }: {
    open: boolean;
ef6b3255   杨鑫   修改BUG
744
    locations: LocationDto[];
91821909   杨鑫   最新
745
    partners: PartnerListItem[];
ef6b3255   杨鑫   修改BUG
746
    groups: GroupListItem[];
91821909   杨鑫   最新
747
748
    requireCompanySelection: boolean;
    fixedPartnerId: string;
0e27ddc8   杨鑫   标签
749
750
751
752
    onOpenChange: (open: boolean) => void;
    onCreated: () => void;
  }) {
    const [submitting, setSubmitting] = useState(false);
91821909   杨鑫   最新
753
    const [selectedPartnerId, setSelectedPartnerId] = useState("");
ef6b3255   杨鑫   修改BUG
754
755
    const [selectedRegionNames, setSelectedRegionNames] = useState<string[]>([]);
    const [selectedLocationIds, setSelectedLocationIds] = useState<string[]>([]);
0e27ddc8   杨鑫   标签
756
    const [form, setForm] = useState<LabelMultipleOptionCreateInput>({
0e27ddc8   杨鑫   标签
757
758
759
760
761
762
763
764
      optionName: "",
      optionValuesJson: [],
      state: true,
      orderNum: null,
    });
    const [newValue, setNewValue] = useState("");
  
    const resetForm = () => {
91821909   杨鑫   最新
765
      setSelectedPartnerId("");
ef6b3255   杨鑫   修改BUG
766
767
      setSelectedRegionNames([]);
      setSelectedLocationIds([]);
0e27ddc8   杨鑫   标签
768
      setForm({
0e27ddc8   杨鑫   标签
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
        optionName: "",
        optionValuesJson: [],
        state: true,
        orderNum: null,
      });
      setNewValue("");
    };
  
    useEffect(() => {
      if (!open) {
        resetForm();
      }
    }, [open]);
  
    const addValue = () => {
      const trimmed = newValue.trim();
      if (!trimmed) return;
      if (form.optionValuesJson.includes(trimmed)) {
        toast.error("Duplicate value", {
          description: "This value already exists.",
        });
        return;
      }
      setForm((p) => ({
        ...p,
        optionValuesJson: [...p.optionValuesJson, trimmed],
      }));
      setNewValue("");
    };
  
    const removeValue = (index: number) => {
      setForm((p) => ({
        ...p,
        optionValuesJson: p.optionValuesJson.filter((_, i) => i !== index),
      }));
    };
  
    const submit = async () => {
699ea6e8   杨鑫   完善打印逻辑
807
      if (!form.optionName.trim()) {
0e27ddc8   杨鑫   标签
808
        toast.error("Validation failed", {
699ea6e8   杨鑫   完善打印逻辑
809
          description: "Option Name is required.",
0e27ddc8   杨鑫   标签
810
811
812
813
814
815
816
817
818
        });
        return;
      }
      if (form.optionValuesJson.length === 0) {
        toast.error("Validation failed", {
          description: "At least one option value is required.",
        });
        return;
      }
3d4c10ac   杨鑫   对接,标签产品
819
820
821
822
      if (form.orderNum === null || form.orderNum === undefined || !Number.isFinite(form.orderNum)) {
        toast.error("Validation failed", { description: "Order is required." });
        return;
      }
0e27ddc8   杨鑫   标签
823
  
91821909   杨鑫   最新
824
825
826
827
828
829
830
831
832
833
834
      const scopePartnerId = effectiveScopePartnerId(
        requireCompanySelection,
        selectedPartnerId,
        fixedPartnerId,
      );
      const partnerErr = scopePartnerValidationMessage(requireCompanySelection, scopePartnerId);
      if (partnerErr) {
        toast.error("Validation failed", { description: partnerErr });
        return;
      }
  
ef6b3255   杨鑫   修改BUG
835
836
      const locPayload = buildSpecifiedLocationPayload(
        locations,
91821909   杨鑫   最新
837
838
        partners,
        scopePartnerId,
ef6b3255   杨鑫   修改BUG
839
840
841
842
843
844
845
846
        selectedRegionNames,
        selectedLocationIds,
      );
      if (!locPayload.ok) {
        toast.error("Validation failed", { description: locPayload.message });
        return;
      }
  
91821909   杨鑫   最新
847
      const groupIds = regionNamesToGroupIds(selectedRegionNames, groups, scopePartnerId);
ef6b3255   杨鑫   修改BUG
848
  
0e27ddc8   杨鑫   标签
849
850
      setSubmitting(true);
      try {
ef6b3255   杨鑫   修改BUG
851
852
        await createLabelMultipleOption({
          ...form,
91821909   杨鑫   最新
853
          optionCode: optionCodeFromName(form.optionName),
ef6b3255   杨鑫   修改BUG
854
855
856
857
          groupIds,
          regionIds: groupIds,
          locationIds: locPayload.locationIds,
        });
0e27ddc8   杨鑫   标签
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("Multiple option created.", {
          description: "The multiple option has been created successfully.",
        });
        onOpenChange(false);
        onCreated();
      } catch (e: any) {
        toast.error("Failed to create multiple option.", {
          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>Add New Multiple Option</DialogTitle>
            <DialogDescription>
              Enter the details for the new multiple option.
            </DialogDescription>
          </DialogHeader>
  
          <div className="grid gap-4 py-4">
91821909   杨鑫   最新
883
884
885
886
887
888
889
            <div className="space-y-2">
              <Label>Option Name *</Label>
              <Input
                placeholder="e.g. Allergens"
                value={form.optionName}
                onChange={(e) => setForm((p) => ({ ...p, optionName: e.target.value }))}
              />
0e27ddc8   杨鑫   标签
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
            </div>
  
            <div className="space-y-2">
              <Label>Option Values *</Label>
              <div className="flex gap-2">
                <Input
                  placeholder="Enter a value and press Add"
                  value={newValue}
                  onChange={(e) => setNewValue(e.target.value)}
                  onKeyDown={(e) => {
                    if (e.key === "Enter") {
                      e.preventDefault();
                      addValue();
                    }
                  }}
                />
                <Button type="button" onClick={addValue} variant="outline">
                  Add
                </Button>
              </div>
              {form.optionValuesJson.length > 0 && (
                <div className="flex flex-wrap gap-2 mt-2">
                  {form.optionValuesJson.map((val, idx) => (
                    <Badge key={idx} variant="secondary" className="flex items-center gap-1">
                      {val}
                      <button
                        type="button"
                        onClick={() => removeValue(idx)}
                        className="ml-1 hover:text-red-600"
                      >
                        <X className="h-3 w-3" />
                      </button>
                    </Badge>
                  ))}
                </div>
              )}
            </div>
  
            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2">
3d4c10ac   杨鑫   对接,标签产品
930
                <Label>Order *</Label>
0e27ddc8   杨鑫   标签
931
932
933
934
935
936
937
938
939
940
941
942
                <Input
                  type="number"
                  placeholder="e.g. 1"
                  value={form.orderNum ?? ""}
                  onChange={(e) => setForm((p) => ({ ...p, orderNum: e.target.value ? Number(e.target.value) : null }))}
                />
              </div>
              <div className="flex items-center justify-between border border-gray-200 rounded-md px-3 bg-white" style={{ height: 40 }}>
                <div className="text-sm font-medium text-gray-900">Enabled</div>
                <Switch checked={form.state} onCheckedChange={(checked) => setForm((p) => ({ ...p, state: checked }))} />
              </div>
            </div>
ef6b3255   杨鑫   修改BUG
943
  
91821909   杨鑫   最新
944
945
946
            <CategoryScopeFields
              partners={partners}
              groups={groups}
ef6b3255   杨鑫   修改BUG
947
              locations={locations}
91821909   杨鑫   最新
948
949
              selectedPartnerId={selectedPartnerId}
              onPartnerChange={setSelectedPartnerId}
ef6b3255   杨鑫   修改BUG
950
              selectedRegionNames={selectedRegionNames}
ef6b3255   杨鑫   修改BUG
951
              onRegionChange={setSelectedRegionNames}
91821909   杨鑫   最新
952
              selectedLocationIds={selectedLocationIds}
ef6b3255   杨鑫   修改BUG
953
              onLocationChange={setSelectedLocationIds}
91821909   杨鑫   最新
954
955
              requireCompanySelection={requireCompanySelection}
              fixedPartnerId={fixedPartnerId}
ef6b3255   杨鑫   修改BUG
956
            />
0e27ddc8   杨鑫   标签
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
          </div>
  
          <DialogFooter>
            <Button variant="outline" onClick={() => onOpenChange(false)}>
              Cancel
            </Button>
            <Button disabled={submitting} onClick={submit}>
              {submitting ? "Creating..." : "Create"}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    );
  }
  
  function EditMultipleOptionDialog({
    open,
    option,
ef6b3255   杨鑫   修改BUG
975
    locations,
91821909   杨鑫   最新
976
    partners,
ef6b3255   杨鑫   修改BUG
977
    groups,
91821909   杨鑫   最新
978
979
    requireCompanySelection,
    fixedPartnerId,
0e27ddc8   杨鑫   标签
980
981
982
983
984
    onOpenChange,
    onUpdated,
  }: {
    open: boolean;
    option: LabelMultipleOptionDto | null;
ef6b3255   杨鑫   修改BUG
985
    locations: LocationDto[];
91821909   杨鑫   最新
986
    partners: PartnerListItem[];
ef6b3255   杨鑫   修改BUG
987
    groups: GroupListItem[];
91821909   杨鑫   最新
988
989
    requireCompanySelection: boolean;
    fixedPartnerId: string;
0e27ddc8   杨鑫   标签
990
991
992
993
    onOpenChange: (open: boolean) => void;
    onUpdated: () => void;
  }) {
    const [submitting, setSubmitting] = useState(false);
ef6b3255   杨鑫   修改BUG
994
    const [loadingDetail, setLoadingDetail] = useState(false);
91821909   杨鑫   最新
995
    const [selectedPartnerId, setSelectedPartnerId] = useState("");
ef6b3255   杨鑫   修改BUG
996
997
    const [selectedRegionNames, setSelectedRegionNames] = useState<string[]>([]);
    const [selectedLocationIds, setSelectedLocationIds] = useState<string[]>([]);
0e27ddc8   杨鑫   标签
998
    const [form, setForm] = useState<LabelMultipleOptionUpdateInput>({
0e27ddc8   杨鑫   标签
999
1000
1001
1002
1003
1004
1005
1006
      optionName: "",
      optionValuesJson: [],
      state: true,
      orderNum: null,
    });
    const [newValue, setNewValue] = useState("");
  
    useEffect(() => {
ef6b3255   杨鑫   修改BUG
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
      if (!open || !option?.id) return;
  
      const ac = new AbortController();
      setLoadingDetail(true);
  
      (async () => {
        try {
          const detail = await getLabelMultipleOption(option.id, ac.signal);
          if (ac.signal.aborted) return;
  
          setForm({
ef6b3255   杨鑫   修改BUG
1018
1019
1020
1021
1022
1023
1024
1025
1026
            optionName: detail.optionName ?? option.optionName ?? "",
            optionValuesJson: detail.optionValuesJson ?? option.optionValuesJson ?? [],
            state: detail.state ?? option.state ?? true,
            orderNum: detail.orderNum ?? option.orderNum ?? null,
          });
          setNewValue("");
  
          const lids = (detail.locationIds ?? []).map((x) => String(x).trim()).filter(Boolean);
          if (lids.length > 0) {
91821909   杨鑫   最新
1027
1028
            const scope = hydrateCategoryScopeFromLocationIds(lids, locations, partners, groups);
            setSelectedPartnerId(scope.partnerId);
ef6b3255   杨鑫   修改BUG
1029
1030
1031
1032
1033
1034
1035
1036
1037
            setSelectedRegionNames(scope.regionNames);
            setSelectedLocationIds(scope.locationIds);
            return;
          }
  
          const gids = [...(detail.groupIds ?? []), ...(detail.regionIds ?? [])]
            .map((x) => String(x).trim())
            .filter(Boolean);
          if (gids.length > 0) {
91821909   杨鑫   最新
1038
1039
            const matchedGroups = groups.filter((g) => gids.includes(g.id));
            const pid = matchedGroups[0]?.partnerId ?? "";
ef6b3255   杨鑫   修改BUG
1040
            const names = [
91821909   杨鑫   最新
1041
              ...new Set(matchedGroups.map((g) => (g.groupName ?? "").trim()).filter(Boolean)),
ef6b3255   杨鑫   修改BUG
1042
            ];
91821909   杨鑫   最新
1043
            setSelectedPartnerId(pid);
ef6b3255   杨鑫   修改BUG
1044
1045
1046
1047
1048
1049
1050
1051
            setSelectedRegionNames(names);
            setSelectedLocationIds([]);
            return;
          }
  
          const fromLabels = await fetchLocationIdsForMultipleOption(option.id, ac.signal);
          if (ac.signal.aborted) return;
          if (fromLabels.length > 0) {
91821909   杨鑫   最新
1052
1053
            const scope = hydrateCategoryScopeFromLocationIds(fromLabels, locations, partners, groups);
            setSelectedPartnerId(scope.partnerId);
ef6b3255   杨鑫   修改BUG
1054
1055
1056
            setSelectedRegionNames(scope.regionNames);
            setSelectedLocationIds(scope.locationIds);
          } else {
91821909   杨鑫   最新
1057
            setSelectedPartnerId("");
ef6b3255   杨鑫   修改BUG
1058
1059
1060
1061
1062
1063
            setSelectedRegionNames([]);
            setSelectedLocationIds([]);
          }
        } catch {
          if (ac.signal.aborted) return;
          setForm({
ef6b3255   杨鑫   修改BUG
1064
1065
1066
1067
1068
            optionName: option.optionName ?? "",
            optionValuesJson: option.optionValuesJson ?? [],
            state: option.state ?? true,
            orderNum: option.orderNum ?? null,
          });
91821909   杨鑫   最新
1069
          setSelectedPartnerId("");
ef6b3255   杨鑫   修改BUG
1070
1071
1072
1073
1074
1075
1076
1077
1078
          setSelectedRegionNames([]);
          setSelectedLocationIds([]);
          setNewValue("");
        } finally {
          if (!ac.signal.aborted) setLoadingDetail(false);
        }
      })();
  
      return () => ac.abort();
91821909   杨鑫   最新
1079
    }, [open, option, locations, partners, groups]);
0e27ddc8   杨鑫   标签
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
  
    const addValue = () => {
      const trimmed = newValue.trim();
      if (!trimmed) return;
      if (form.optionValuesJson.includes(trimmed)) {
        toast.error("Duplicate value", {
          description: "This value already exists.",
        });
        return;
      }
      setForm((p) => ({
        ...p,
        optionValuesJson: [...p.optionValuesJson, trimmed],
      }));
      setNewValue("");
    };
  
    const removeValue = (index: number) => {
      setForm((p) => ({
        ...p,
        optionValuesJson: p.optionValuesJson.filter((_, i) => i !== index),
      }));
    };
  
    const submit = async () => {
      if (!option?.id) return;
699ea6e8   杨鑫   完善打印逻辑
1106
      if (!form.optionName.trim()) {
0e27ddc8   杨鑫   标签
1107
        toast.error("Validation failed", {
699ea6e8   杨鑫   完善打印逻辑
1108
          description: "Option Name is required.",
0e27ddc8   杨鑫   标签
1109
1110
1111
1112
1113
1114
1115
1116
1117
        });
        return;
      }
      if (form.optionValuesJson.length === 0) {
        toast.error("Validation failed", {
          description: "At least one option value is required.",
        });
        return;
      }
3d4c10ac   杨鑫   对接,标签产品
1118
1119
1120
1121
      if (form.orderNum === null || form.orderNum === undefined || !Number.isFinite(form.orderNum)) {
        toast.error("Validation failed", { description: "Order is required." });
        return;
      }
0e27ddc8   杨鑫   标签
1122
  
91821909   杨鑫   最新
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
      const scopePartnerId = effectiveScopePartnerId(
        requireCompanySelection,
        selectedPartnerId,
        fixedPartnerId,
      );
      const partnerErr = scopePartnerValidationMessage(requireCompanySelection, scopePartnerId);
      if (partnerErr) {
        toast.error("Validation failed", { description: partnerErr });
        return;
      }
  
ef6b3255   杨鑫   修改BUG
1134
1135
      const locPayload = buildSpecifiedLocationPayload(
        locations,
91821909   杨鑫   最新
1136
1137
        partners,
        scopePartnerId,
ef6b3255   杨鑫   修改BUG
1138
1139
1140
1141
1142
1143
1144
1145
        selectedRegionNames,
        selectedLocationIds,
      );
      if (!locPayload.ok) {
        toast.error("Validation failed", { description: locPayload.message });
        return;
      }
  
91821909   杨鑫   最新
1146
      const groupIds = regionNamesToGroupIds(selectedRegionNames, groups, scopePartnerId);
ef6b3255   杨鑫   修改BUG
1147
  
0e27ddc8   杨鑫   标签
1148
1149
      setSubmitting(true);
      try {
ef6b3255   杨鑫   修改BUG
1150
1151
        await updateLabelMultipleOption(option.id, {
          ...form,
91821909   杨鑫   最新
1152
          optionCode: option.optionCode ?? "",
ef6b3255   杨鑫   修改BUG
1153
1154
1155
1156
          groupIds,
          regionIds: groupIds,
          locationIds: locPayload.locationIds,
        });
0e27ddc8   杨鑫   标签
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
        toast.success("Multiple option updated.", {
          description: "The multiple option has been updated successfully.",
        });
        onOpenChange(false);
        onUpdated();
      } catch (e: any) {
        toast.error("Failed to update multiple option.", {
          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 Multiple Option</DialogTitle>
            <DialogDescription>
              Update the multiple option details.
            </DialogDescription>
          </DialogHeader>
  
          <div className="grid gap-4 py-4">
91821909   杨鑫   最新
1182
1183
1184
1185
1186
1187
1188
            <div className="space-y-2">
              <Label>Option Name *</Label>
              <Input
                placeholder="e.g. Allergens"
                value={form.optionName}
                onChange={(e) => setForm((p) => ({ ...p, optionName: e.target.value }))}
              />
0e27ddc8   杨鑫   标签
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
            </div>
  
            <div className="space-y-2">
              <Label>Option Values *</Label>
              <div className="flex gap-2">
                <Input
                  placeholder="Enter a value and press Add"
                  value={newValue}
                  onChange={(e) => setNewValue(e.target.value)}
                  onKeyDown={(e) => {
                    if (e.key === "Enter") {
                      e.preventDefault();
                      addValue();
                    }
                  }}
                />
                <Button type="button" onClick={addValue} variant="outline">
                  Add
                </Button>
              </div>
              {form.optionValuesJson.length > 0 && (
                <div className="flex flex-wrap gap-2 mt-2">
                  {form.optionValuesJson.map((val, idx) => (
                    <Badge key={idx} variant="secondary" className="flex items-center gap-1">
                      {val}
                      <button
                        type="button"
                        onClick={() => removeValue(idx)}
                        className="ml-1 hover:text-red-600"
                      >
                        <X className="h-3 w-3" />
                      </button>
                    </Badge>
                  ))}
                </div>
              )}
            </div>
  
            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2">
3d4c10ac   杨鑫   对接,标签产品
1229
                <Label>Order *</Label>
0e27ddc8   杨鑫   标签
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
                <Input
                  type="number"
                  placeholder="e.g. 1"
                  value={form.orderNum ?? ""}
                  onChange={(e) => setForm((p) => ({ ...p, orderNum: e.target.value ? Number(e.target.value) : null }))}
                />
              </div>
              <div className="flex items-center justify-between border border-gray-200 rounded-md px-3 bg-white" style={{ height: 40 }}>
                <div className="text-sm font-medium text-gray-900">Enabled</div>
                <Switch checked={form.state} onCheckedChange={(checked) => setForm((p) => ({ ...p, state: checked }))} />
              </div>
            </div>
ef6b3255   杨鑫   修改BUG
1242
1243
  
            {loadingDetail ? (
91821909   杨鑫   最新
1244
              <p className="text-sm text-gray-500">Loading company, region and location…</p>
ef6b3255   杨鑫   修改BUG
1245
            ) : (
91821909   杨鑫   最新
1246
1247
1248
              <CategoryScopeFields
                partners={partners}
                groups={groups}
ef6b3255   杨鑫   修改BUG
1249
                locations={locations}
91821909   杨鑫   最新
1250
1251
                selectedPartnerId={selectedPartnerId}
                onPartnerChange={setSelectedPartnerId}
ef6b3255   杨鑫   修改BUG
1252
                selectedRegionNames={selectedRegionNames}
ef6b3255   杨鑫   修改BUG
1253
                onRegionChange={setSelectedRegionNames}
91821909   杨鑫   最新
1254
                selectedLocationIds={selectedLocationIds}
ef6b3255   杨鑫   修改BUG
1255
                onLocationChange={setSelectedLocationIds}
91821909   杨鑫   最新
1256
1257
                requireCompanySelection={requireCompanySelection}
                fixedPartnerId={fixedPartnerId}
ef6b3255   杨鑫   修改BUG
1258
1259
              />
            )}
0e27ddc8   杨鑫   标签
1260
1261
1262
1263
1264
1265
          </div>
  
          <DialogFooter>
            <Button variant="outline" onClick={() => onOpenChange(false)}>
              Cancel
            </Button>
ef6b3255   杨鑫   修改BUG
1266
            <Button disabled={submitting || loadingDetail} onClick={submit}>
0e27ddc8   杨鑫   标签
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
              {submitting ? "Updating..." : "Update"}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    );
  }
  
  function DeleteMultipleOptionDialog({
    open,
    option,
    onOpenChange,
    onDeleted,
  }: {
    open: boolean;
    option: LabelMultipleOptionDto | null;
    onOpenChange: (open: boolean) => void;
    onDeleted: () => void;
  }) {
    const [submitting, setSubmitting] = useState(false);
  
    const name = useMemo(() => {
      const n = (option?.optionName ?? "").trim();
      return n || option?.optionCode || "this option";
    }, [option]);
  
    const submit = async () => {
      if (!option?.id) return;
      setSubmitting(true);
      try {
        await deleteLabelMultipleOption(option.id);
        toast.success("Multiple option deleted.", {
          description: "The multiple option has been removed successfully.",
        });
        onOpenChange(false);
        onDeleted();
      } catch (e: any) {
        toast.error("Failed to delete multiple option.", {
          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 Multiple Option</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   杨鑫   产品 标签 关联
1329
              className="min-w-24 gap-2"
0e27ddc8   杨鑫   标签
1330
1331
1332
1333
              variant="destructive"
              disabled={submitting}
              onClick={submit}
            >
3af4878d   杨鑫   产品 标签 关联
1334
              <Trash2 className="h-4 w-4 shrink-0" />
0e27ddc8   杨鑫   标签
1335
1336
1337
1338
1339
1340
1341
              {submitting ? "Deleting..." : "Delete"}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    );
  }