Blame view

美国版/Food Labeling Management Platform/src/components/labels/MultipleOptionsView.tsx 48.9 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
  import { getPartners } from "../../services/partnerService";
  import {
1b68006d   李曜臣   20260708
54
    buildEntityScopeSaveFromForm,
91821909   杨鑫   最新
55
    hydrateCategoryScopeFromLocationIds,
1b68006d   李曜臣   20260708
56
    hydrateEntityScopeFromDto,
91821909   杨鑫   最新
57
58
59
  } from "../../lib/categoryScopeForm";
  import { CategoryScopeFields } from "../shared/category-scope-fields";
  import { useCategoryScopeAuth } from "../../hooks/useCategoryScopeAuth";
0e27ddc8   杨鑫   标签
60
61
62
63
64
  import type {
    LabelMultipleOptionDto,
    LabelMultipleOptionCreateInput,
    LabelMultipleOptionUpdateInput,
  } from "../../types/labelMultipleOption";
ef6b3255   杨鑫   修改BUG
65
66
  import type { LocationDto } from "../../types/location";
  import type { GroupListItem } from "../../types/group";
91821909   杨鑫   最新
67
  import type { PartnerListItem } from "../../types/partner";
540ac0e3   杨鑫   前端修改bug
68
69
70
71
72
73
74
  import {
    filterGroupsByCompany,
    filterLocationsByCompanyAndRegion,
    matchesCompanyByLocationIds,
    matchesRegionByLocationIds,
    resolveScopedLocationIdsForToolbar,
  } from "../../lib/labelingToolbarScope";
ef6b3255   杨鑫   修改BUG
75
  import { cn } from "../ui/utils";
0e27ddc8   杨鑫   标签
76
77
78
79
80
  
  function toDisplay(v: string | null | undefined): string {
    const s = (v ?? "").trim();
    return s ? s : "None";
  }
884054fb   “wangming”   项目初始化
81
  
91821909   杨鑫   最新
82
83
84
85
86
87
88
89
90
91
92
  /** 新增时由名称生成编码(界面不再手填 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
93
94
95
96
97
  /** 列表行单元格统一字体(与 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";
  
ef6b3255   杨鑫   修改BUG
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
  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));
  }
  
540ac0e3   杨鑫   前端修改bug
149
150
151
152
153
154
155
156
157
158
  function optionMatchesCompanyFilter(
    opt: LabelMultipleOptionDto,
    companyFilterId: string,
    catalog: LocationDto[],
    partners: PartnerListItem[],
  ): boolean {
    const lids = (opt.locationIds ?? []).map((x) => String(x).trim()).filter(Boolean);
    return matchesCompanyByLocationIds(lids, companyFilterId, catalog, partners);
  }
  
ef6b3255   杨鑫   修改BUG
159
160
161
162
163
164
  function optionMatchesRegionFilter(
    opt: LabelMultipleOptionDto,
    regionFilterId: string,
    catalog: LocationDto[],
    groups: GroupListItem[],
  ): boolean {
540ac0e3   杨鑫   前端修改bug
165
166
    const lids = (opt.locationIds ?? []).map((x) => String(x).trim()).filter(Boolean);
    return matchesRegionByLocationIds(lids, regionFilterId, catalog, groups);
ef6b3255   杨鑫   修改BUG
167
168
169
170
171
172
173
174
175
176
177
  }
  
  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
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
  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
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
  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”   项目初始化
234
  export function MultipleOptionsView() {
91821909   杨鑫   最新
235
    const scopeAuth = useCategoryScopeAuth();
0e27ddc8   杨鑫   标签
236
237
238
239
240
241
242
243
244
245
246
247
    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("");
540ac0e3   杨鑫   前端修改bug
248
    const [companyFilter, setCompanyFilter] = useState("all");
ef6b3255   杨鑫   修改BUG
249
250
    const [regionFilter, setRegionFilter] = useState("all");
    const [locationFilter, setLocationFilter] = useState("all");
0e27ddc8   杨鑫   标签
251
252
253
254
255
    const [stateFilter, setStateFilter] = useState<string>("all");
  
    const [pageIndex, setPageIndex] = useState(1);
    const [pageSize, setPageSize] = useState(10);
  
ef6b3255   杨鑫   修改BUG
256
257
    const [locationCatalog, setLocationCatalog] = useState<LocationDto[]>([]);
    const [filterGroups, setFilterGroups] = useState<GroupListItem[]>([]);
91821909   杨鑫   最新
258
    const [filterPartners, setFilterPartners] = useState<PartnerListItem[]>([]);
ef6b3255   杨鑫   修改BUG
259
  
0e27ddc8   杨鑫   标签
260
261
262
263
    const abortRef = useRef<AbortController | null>(null);
    const keywordTimerRef = useRef<number | null>(null);
    const [debouncedKeyword, setDebouncedKeyword] = useState("");
  
540ac0e3   杨鑫   前端修改bug
264
265
266
267
268
269
270
271
272
273
    const companySelectOptions = useMemo(
      () =>
        [...filterPartners]
          .filter((p) => (p.partnerName ?? "").trim())
          .sort((a, b) =>
            (a.partnerName ?? "").localeCompare(b.partnerName ?? "", undefined, { sensitivity: "base" }),
          ),
      [filterPartners],
    );
  
ef6b3255   杨鑫   修改BUG
274
    const regionSelectOptions = useMemo(() => {
540ac0e3   杨鑫   前端修改bug
275
      const list = filterGroupsByCompany(filterGroups, companyFilter);
ef6b3255   杨鑫   修改BUG
276
      const m = new Map<string, GroupListItem>();
540ac0e3   杨鑫   前端修改bug
277
      for (const g of list) {
ef6b3255   杨鑫   修改BUG
278
279
280
281
282
283
        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" }),
      );
540ac0e3   杨鑫   前端修改bug
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
    }, [filterGroups, companyFilter]);
  
    const locationsForToolbarFilter = useMemo(
      () =>
        filterLocationsByCompanyAndRegion(
          locationCatalog,
          filterPartners,
          companyFilter,
          regionFilter,
          filterGroups,
        ),
      [locationCatalog, filterPartners, companyFilter, regionFilter, filterGroups],
    );
  
    useEffect(() => {
      setRegionFilter("all");
      setLocationFilter("all");
    }, [companyFilter]);
ef6b3255   杨鑫   修改BUG
302
303
304
305
306
307
  
    useEffect(() => {
      setLocationFilter("all");
    }, [regionFilter]);
  
    useEffect(() => {
540ac0e3   杨鑫   前端修改bug
308
309
310
311
312
313
314
315
316
317
      if (companyFilter === "all") return;
      if (!companySelectOptions.some((p) => p.id === companyFilter)) setCompanyFilter("all");
    }, [companyFilter, companySelectOptions]);
  
    useEffect(() => {
      if (regionFilter === "all") return;
      if (!regionSelectOptions.some((g) => g.id === regionFilter)) setRegionFilter("all");
    }, [companyFilter, regionSelectOptions, regionFilter]);
  
    useEffect(() => {
ef6b3255   杨鑫   修改BUG
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
      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   杨鑫   最新
340
341
342
343
          const [grpRes, partnerRes] = await Promise.all([
            getGroups({ skipCount: 1, maxResultCount: 500 }),
            getPartners({ skipCount: 1, maxResultCount: 500, state: true }),
          ]);
ef6b3255   杨鑫   修改BUG
344
345
346
          if (cancelled) return;
          setLocationCatalog(out);
          setFilterGroups(grpRes.items ?? []);
91821909   杨鑫   最新
347
          setFilterPartners(partnerRes.items ?? []);
ef6b3255   杨鑫   修改BUG
348
349
350
351
        } catch {
          if (!cancelled) {
            setLocationCatalog([]);
            setFilterGroups([]);
91821909   杨鑫   最新
352
            setFilterPartners([]);
ef6b3255   杨鑫   修改BUG
353
354
355
356
357
358
359
360
          }
        }
      })();
      return () => {
        cancelled = true;
      };
    }, []);
  
0e27ddc8   杨鑫   标签
361
362
363
364
365
366
367
368
369
370
371
372
    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);
540ac0e3   杨鑫   前端修改bug
373
    }, [debouncedKeyword, companyFilter, regionFilter, locationFilter, stateFilter, pageSize]);
0e27ddc8   杨鑫   标签
374
375
376
377
378
379
380
381
382
  
    useEffect(() => {
      const run = async () => {
        abortRef.current?.abort();
        const ac = new AbortController();
        abortRef.current = ac;
  
        setLoading(true);
        try {
143afd59   杨鑫   打印,标签
383
          const skipCount = skipCountForPage(pageIndex);
ef6b3255   杨鑫   修改BUG
384
385
          const stateBool = stateFilter === "all" ? undefined : stateFilter === "true";
          const kw = debouncedKeyword || undefined;
540ac0e3   杨鑫   前端修改bug
386
387
388
389
          const needsClientFilter =
            companyFilter !== "all" || regionFilter !== "all" || locationFilter !== "all";
          const scopeLocationIds = resolveScopedLocationIdsForToolbar(
            companyFilter,
ef6b3255   杨鑫   修改BUG
390
391
392
393
            regionFilter,
            locationFilter,
            locationCatalog,
            filterGroups,
540ac0e3   杨鑫   前端修改bug
394
            filterPartners,
0e27ddc8   杨鑫   标签
395
          );
540ac0e3   杨鑫   前端修改bug
396
397
          const canUseServerScope =
            companyFilter === "all" && (regionFilter !== "all" || locationFilter !== "all");
0e27ddc8   杨鑫   标签
398
  
ef6b3255   杨鑫   修改BUG
399
400
401
402
403
404
405
          if (!needsClientFilter) {
            const res = await getLabelMultipleOptions(
              {
                skipCount,
                maxResultCount: pageSize,
                keyword: kw,
                state: stateBool,
540ac0e3   杨鑫   前端修改bug
406
407
408
409
410
411
412
413
414
415
416
417
418
              },
              ac.signal,
            );
  
            setOptions(res.items ?? []);
            setTotal(res.totalCount ?? 0);
          } else if (canUseServerScope) {
            const res = await getLabelMultipleOptions(
              {
                skipCount,
                maxResultCount: pageSize,
                keyword: kw,
                state: stateBool,
ef6b3255   杨鑫   修改BUG
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
                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 (
540ac0e3   杨鑫   前端修改bug
436
                  optionMatchesCompanyFilter(opt, companyFilter, locationCatalog, filterPartners) &&
ef6b3255   杨鑫   修改BUG
437
438
439
440
441
442
443
444
445
446
                  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   杨鑫   标签
447
448
449
450
451
452
453
454
455
456
457
458
459
460
        } 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
461
462
    }, [
      debouncedKeyword,
540ac0e3   杨鑫   前端修改bug
463
      companyFilter,
ef6b3255   杨鑫   修改BUG
464
465
466
467
468
469
470
471
      regionFilter,
      locationFilter,
      stateFilter,
      pageIndex,
      pageSize,
      refreshSeq,
      locationCatalog,
      filterGroups,
540ac0e3   杨鑫   前端修改bug
472
      filterPartners,
ef6b3255   杨鑫   修改BUG
473
    ]);
0e27ddc8   杨鑫   标签
474
475
476
477
478
479
480
481
482
483
484
485
486
487
  
    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”   项目初始化
488
489
  
    return (
0e27ddc8   杨鑫   标签
490
491
492
493
494
495
496
497
498
499
500
      <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"
              />
540ac0e3   杨鑫   前端修改bug
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
              {scopeAuth.requireCompanySelection ? (
                <Select value={companyFilter} onValueChange={setCompanyFilter}>
                  <SelectTrigger
                    className="bg-white border border-gray-300 rounded-md w-[150px] shrink-0"
                    style={{ height: 40, boxSizing: "border-box" }}
                  >
                    <SelectValue placeholder="Company" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="all">All Companies</SelectItem>
                    {companySelectOptions.map((p) => (
                      <SelectItem key={p.id} value={p.id}>
                        {toDisplay(p.partnerName)}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              ) : null}
ef6b3255   杨鑫   修改BUG
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
547
548
549
550
551
552
553
554
555
              <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   杨鑫   标签
556
557
              <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
558
                  <SelectValue placeholder="Status" />
0e27ddc8   杨鑫   标签
559
560
                </SelectTrigger>
                <SelectContent>
ef6b3255   杨鑫   修改BUG
561
                  <SelectItem value="all">Status</SelectItem>
0e27ddc8   杨鑫   标签
562
563
564
565
566
567
568
569
570
                  <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
571
                New Multiple Option Set <Plus className="ml-1 h-4 w-4" />
0e27ddc8   杨鑫   标签
572
573
574
              </Button>
            </div>
          </div>
884054fb   “wangming”   项目初始化
575
576
        </div>
  
0e27ddc8   杨鑫   标签
577
578
        <div className="flex-1 overflow-auto pt-6">
          <div className="rounded-md border bg-white shadow-sm">
ef6b3255   杨鑫   修改BUG
579
            <Table className="font-sans">
0e27ddc8   杨鑫   标签
580
581
              <TableHeader>
                <TableRow className="bg-gray-50 hover:bg-gray-50">
ef6b3255   杨鑫   修改BUG
582
583
584
585
586
587
                  <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”   项目初始化
588
                </TableRow>
0e27ddc8   杨鑫   标签
589
590
591
592
              </TableHeader>
              <TableBody>
                {loading ? (
                  <TableRow>
ef6b3255   杨鑫   修改BUG
593
                    <TableCell colSpan={6} className={`text-center ${LIST_ROW_CELL} py-10`}>
0e27ddc8   杨鑫   标签
594
595
596
597
598
                      Loading...
                    </TableCell>
                  </TableRow>
                ) : options.length === 0 ? (
                  <TableRow>
ef6b3255   杨鑫   修改BUG
599
                    <TableCell colSpan={6} className={`text-center ${LIST_ROW_CELL} py-10`}>
0e27ddc8   杨鑫   标签
600
601
602
603
                      No results.
                    </TableCell>
                  </TableRow>
                ) : (
ef6b3255   杨鑫   修改BUG
604
605
606
607
608
609
                  options.map((item) => {
                    const contentsText =
                      item.optionValuesJson && item.optionValuesJson.length > 0
                        ? item.optionValuesJson.join("; ")
                        : "None";
                    return (
0e27ddc8   杨鑫   标签
610
                    <TableRow key={item.id} className="hover:bg-gray-50">
ef6b3255   杨鑫   修改BUG
611
612
613
614
615
616
617
                      <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   杨鑫   标签
618
                      </TableCell>
ef6b3255   杨鑫   修改BUG
619
620
621
622
623
624
625
626
627
                      <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   杨鑫   标签
628
629
                        </Badge>
                      </TableCell>
ef6b3255   杨鑫   修改BUG
630
631
                      <TableCell className={LIST_ROW_CELL_NOWRAP}>
                        {item.orderNum != null && Number.isFinite(item.orderNum) ? item.orderNum : "—"}
0e27ddc8   杨鑫   标签
632
                      </TableCell>
ef6b3255   杨鑫   修改BUG
633
634
635
636
                      <TableCell className={LIST_ROW_CELL_NOWRAP}>
                        {toDisplay(item.lastEdited)}
                      </TableCell>
                      <TableCell className={`text-center ${LIST_ROW_CELL_NOWRAP}`}>
0e27ddc8   杨鑫   标签
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
                        <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   杨鑫   产品 标签 关联
665
                              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   杨鑫   标签
666
667
                              onClick={() => openDelete(item)}
                            >
3af4878d   杨鑫   产品 标签 关联
668
                              <Trash2 className="w-4 h-4 shrink-0" />
0e27ddc8   杨鑫   标签
669
670
671
672
673
674
                              Delete
                            </Button>
                          </PopoverContent>
                        </Popover>
                      </TableCell>
                    </TableRow>
ef6b3255   杨鑫   修改BUG
675
676
                    );
                  })
0e27ddc8   杨鑫   标签
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
                )}
              </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”   项目初始化
742
        </div>
0e27ddc8   杨鑫   标签
743
744
745
  
        <CreateMultipleOptionDialog
          open={isCreateDialogOpen}
ef6b3255   杨鑫   修改BUG
746
          locations={locationCatalog}
91821909   杨鑫   最新
747
          partners={filterPartners}
ef6b3255   杨鑫   修改BUG
748
          groups={filterGroups}
91821909   杨鑫   最新
749
750
          requireCompanySelection={scopeAuth.requireCompanySelection}
          fixedPartnerId={scopeAuth.fixedPartnerId}
0e27ddc8   杨鑫   标签
751
752
753
754
755
756
757
758
759
760
          onOpenChange={setIsCreateDialogOpen}
          onCreated={() => {
            setPageIndex(1);
            refreshList();
          }}
        />
  
        <EditMultipleOptionDialog
          open={isEditDialogOpen}
          option={editingOption}
ef6b3255   杨鑫   修改BUG
761
          locations={locationCatalog}
91821909   杨鑫   最新
762
          partners={filterPartners}
ef6b3255   杨鑫   修改BUG
763
          groups={filterGroups}
91821909   杨鑫   最新
764
765
          requireCompanySelection={scopeAuth.requireCompanySelection}
          fixedPartnerId={scopeAuth.fixedPartnerId}
0e27ddc8   杨鑫   标签
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
          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”   项目初始化
782
783
784
      </div>
    );
  }
0e27ddc8   杨鑫   标签
785
786
787
  
  function CreateMultipleOptionDialog({
    open,
ef6b3255   杨鑫   修改BUG
788
    locations,
91821909   杨鑫   最新
789
    partners,
ef6b3255   杨鑫   修改BUG
790
    groups,
91821909   杨鑫   最新
791
792
    requireCompanySelection,
    fixedPartnerId,
0e27ddc8   杨鑫   标签
793
794
795
796
    onOpenChange,
    onCreated,
  }: {
    open: boolean;
ef6b3255   杨鑫   修改BUG
797
    locations: LocationDto[];
91821909   杨鑫   最新
798
    partners: PartnerListItem[];
ef6b3255   杨鑫   修改BUG
799
    groups: GroupListItem[];
91821909   杨鑫   最新
800
801
    requireCompanySelection: boolean;
    fixedPartnerId: string;
0e27ddc8   杨鑫   标签
802
803
804
805
    onOpenChange: (open: boolean) => void;
    onCreated: () => void;
  }) {
    const [submitting, setSubmitting] = useState(false);
91821909   杨鑫   最新
806
    const [selectedPartnerId, setSelectedPartnerId] = useState("");
c9bc327f   杨鑫   修改前端
807
    const [selectedPartnerIds, setSelectedPartnerIds] = useState<string[]>([]);
ef6b3255   杨鑫   修改BUG
808
    const [selectedRegionNames, setSelectedRegionNames] = useState<string[]>([]);
c9bc327f   杨鑫   修改前端
809
    const [selectedRegionIds, setSelectedRegionIds] = useState<string[]>([]);
ef6b3255   杨鑫   修改BUG
810
    const [selectedLocationIds, setSelectedLocationIds] = useState<string[]>([]);
0e27ddc8   杨鑫   标签
811
    const [form, setForm] = useState<LabelMultipleOptionCreateInput>({
0e27ddc8   杨鑫   标签
812
813
814
815
816
817
818
819
      optionName: "",
      optionValuesJson: [],
      state: true,
      orderNum: null,
    });
    const [newValue, setNewValue] = useState("");
  
    const resetForm = () => {
91821909   杨鑫   最新
820
      setSelectedPartnerId("");
1b68006d   李曜臣   20260708
821
      setSelectedPartnerIds([]);
ef6b3255   杨鑫   修改BUG
822
      setSelectedRegionNames([]);
1b68006d   李曜臣   20260708
823
      setSelectedRegionIds([]);
ef6b3255   杨鑫   修改BUG
824
      setSelectedLocationIds([]);
0e27ddc8   杨鑫   标签
825
      setForm({
0e27ddc8   杨鑫   标签
826
827
828
829
830
831
832
833
834
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
        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   杨鑫   完善打印逻辑
864
      if (!form.optionName.trim()) {
0e27ddc8   杨鑫   标签
865
        toast.error("Validation failed", {
699ea6e8   杨鑫   完善打印逻辑
866
          description: "Option Name is required.",
0e27ddc8   杨鑫   标签
867
868
869
870
871
872
873
874
875
        });
        return;
      }
      if (form.optionValuesJson.length === 0) {
        toast.error("Validation failed", {
          description: "At least one option value is required.",
        });
        return;
      }
3d4c10ac   杨鑫   对接,标签产品
876
877
878
879
      if (form.orderNum === null || form.orderNum === undefined || !Number.isFinite(form.orderNum)) {
        toast.error("Validation failed", { description: "Order is required." });
        return;
      }
0e27ddc8   杨鑫   标签
880
  
1b68006d   李曜臣   20260708
881
      const scopePayload = buildEntityScopeSaveFromForm({
91821909   杨鑫   最新
882
883
        requireCompanySelection,
        selectedPartnerId,
c9bc327f   杨鑫   修改前端
884
        selectedPartnerIds,
ef6b3255   杨鑫   修改BUG
885
        selectedRegionNames,
c9bc327f   杨鑫   修改前端
886
        selectedRegionIds,
ef6b3255   杨鑫   修改BUG
887
        selectedLocationIds,
91821909   杨鑫   最新
888
        fixedPartnerId,
ef6b3255   杨鑫   修改BUG
889
        locations,
c9bc327f   杨鑫   修改前端
890
891
        partners,
        groups,
c9bc327f   杨鑫   修改前端
892
893
894
      });
      if (!scopePayload.ok) {
        toast.error("Validation failed", { description: scopePayload.message });
ef6b3255   杨鑫   修改BUG
895
896
897
        return;
      }
  
0e27ddc8   杨鑫   标签
898
899
      setSubmitting(true);
      try {
ef6b3255   杨鑫   修改BUG
900
901
        await createLabelMultipleOption({
          ...form,
91821909   杨鑫   最新
902
          optionCode: optionCodeFromName(form.optionName),
1b68006d   李曜臣   20260708
903
          ...scopePayload.body,
ef6b3255   杨鑫   修改BUG
904
        });
0e27ddc8   杨鑫   标签
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
        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   杨鑫   最新
930
931
932
933
934
935
936
            <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   杨鑫   标签
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
            </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   杨鑫   对接,标签产品
977
                <Label>Order *</Label>
0e27ddc8   杨鑫   标签
978
979
980
981
982
983
984
985
986
987
988
989
                <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
990
  
91821909   杨鑫   最新
991
992
993
            <CategoryScopeFields
              partners={partners}
              groups={groups}
ef6b3255   杨鑫   修改BUG
994
              locations={locations}
91821909   杨鑫   最新
995
996
              selectedPartnerId={selectedPartnerId}
              onPartnerChange={setSelectedPartnerId}
c9bc327f   杨鑫   修改前端
997
998
              selectedPartnerIds={selectedPartnerIds}
              onPartnerIdsChange={setSelectedPartnerIds}
ef6b3255   杨鑫   修改BUG
999
              selectedRegionNames={selectedRegionNames}
ef6b3255   杨鑫   修改BUG
1000
              onRegionChange={setSelectedRegionNames}
c9bc327f   杨鑫   修改前端
1001
1002
              selectedRegionIds={selectedRegionIds}
              onRegionIdsChange={setSelectedRegionIds}
91821909   杨鑫   最新
1003
              selectedLocationIds={selectedLocationIds}
ef6b3255   杨鑫   修改BUG
1004
              onLocationChange={setSelectedLocationIds}
91821909   杨鑫   最新
1005
1006
              requireCompanySelection={requireCompanySelection}
              fixedPartnerId={fixedPartnerId}
c9bc327f   杨鑫   修改前端
1007
              templateScopeMode={requireCompanySelection}
1b68006d   李曜臣   20260708
1008
1009
1010
1011
              selectedPartnerIds={selectedPartnerIds}
              onPartnerIdsChange={setSelectedPartnerIds}
              selectedRegionIds={selectedRegionIds}
              onRegionIdsChange={setSelectedRegionIds}
ef6b3255   杨鑫   修改BUG
1012
            />
0e27ddc8   杨鑫   标签
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
          </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
1031
    locations,
91821909   杨鑫   最新
1032
    partners,
ef6b3255   杨鑫   修改BUG
1033
    groups,
91821909   杨鑫   最新
1034
1035
    requireCompanySelection,
    fixedPartnerId,
0e27ddc8   杨鑫   标签
1036
1037
1038
1039
1040
    onOpenChange,
    onUpdated,
  }: {
    open: boolean;
    option: LabelMultipleOptionDto | null;
ef6b3255   杨鑫   修改BUG
1041
    locations: LocationDto[];
91821909   杨鑫   最新
1042
    partners: PartnerListItem[];
ef6b3255   杨鑫   修改BUG
1043
    groups: GroupListItem[];
91821909   杨鑫   最新
1044
1045
    requireCompanySelection: boolean;
    fixedPartnerId: string;
0e27ddc8   杨鑫   标签
1046
1047
1048
1049
    onOpenChange: (open: boolean) => void;
    onUpdated: () => void;
  }) {
    const [submitting, setSubmitting] = useState(false);
ef6b3255   杨鑫   修改BUG
1050
    const [loadingDetail, setLoadingDetail] = useState(false);
91821909   杨鑫   最新
1051
    const [selectedPartnerId, setSelectedPartnerId] = useState("");
c9bc327f   杨鑫   修改前端
1052
    const [selectedPartnerIds, setSelectedPartnerIds] = useState<string[]>([]);
ef6b3255   杨鑫   修改BUG
1053
    const [selectedRegionNames, setSelectedRegionNames] = useState<string[]>([]);
c9bc327f   杨鑫   修改前端
1054
    const [selectedRegionIds, setSelectedRegionIds] = useState<string[]>([]);
ef6b3255   杨鑫   修改BUG
1055
    const [selectedLocationIds, setSelectedLocationIds] = useState<string[]>([]);
0e27ddc8   杨鑫   标签
1056
    const [form, setForm] = useState<LabelMultipleOptionUpdateInput>({
0e27ddc8   杨鑫   标签
1057
1058
1059
1060
1061
1062
1063
1064
      optionName: "",
      optionValuesJson: [],
      state: true,
      orderNum: null,
    });
    const [newValue, setNewValue] = useState("");
  
    useEffect(() => {
ef6b3255   杨鑫   修改BUG
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
      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
1076
1077
1078
1079
1080
1081
1082
            optionName: detail.optionName ?? option.optionName ?? "",
            optionValuesJson: detail.optionValuesJson ?? option.optionValuesJson ?? [],
            state: detail.state ?? option.state ?? true,
            orderNum: detail.orderNum ?? option.orderNum ?? null,
          });
          setNewValue("");
  
1b68006d   李曜臣   20260708
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
          if (requireCompanySelection) {
            const scope = hydrateEntityScopeFromDto(detail, locations, partners, groups);
            setSelectedPartnerIds(scope.partnerIds);
            setSelectedRegionIds(scope.regionIds);
            setSelectedLocationIds(scope.locationIds);
            setSelectedPartnerId("");
            setSelectedRegionNames([]);
            return;
          }
  
ef6b3255   杨鑫   修改BUG
1093
1094
          const lids = (detail.locationIds ?? []).map((x) => String(x).trim()).filter(Boolean);
          if (lids.length > 0) {
91821909   杨鑫   最新
1095
1096
            const scope = hydrateCategoryScopeFromLocationIds(lids, locations, partners, groups);
            setSelectedPartnerId(scope.partnerId);
ef6b3255   杨鑫   修改BUG
1097
1098
            setSelectedRegionNames(scope.regionNames);
            setSelectedLocationIds(scope.locationIds);
1b68006d   李曜臣   20260708
1099
1100
            setSelectedPartnerIds([]);
            setSelectedRegionIds([]);
ef6b3255   杨鑫   修改BUG
1101
1102
1103
1104
1105
1106
1107
            return;
          }
  
          const gids = [...(detail.groupIds ?? []), ...(detail.regionIds ?? [])]
            .map((x) => String(x).trim())
            .filter(Boolean);
          if (gids.length > 0) {
91821909   杨鑫   最新
1108
            const matchedGroups = groups.filter((g) => gids.includes(g.id));
91821909   杨鑫   最新
1109
            const pid = matchedGroups[0]?.partnerId ?? "";
ef6b3255   杨鑫   修改BUG
1110
            const names = [
91821909   杨鑫   最新
1111
              ...new Set(matchedGroups.map((g) => (g.groupName ?? "").trim()).filter(Boolean)),
ef6b3255   杨鑫   修改BUG
1112
            ];
91821909   杨鑫   最新
1113
            setSelectedPartnerId(pid);
ef6b3255   杨鑫   修改BUG
1114
1115
            setSelectedRegionNames(names);
            setSelectedLocationIds([]);
1b68006d   李曜臣   20260708
1116
1117
            setSelectedPartnerIds([]);
            setSelectedRegionIds([]);
ef6b3255   杨鑫   修改BUG
1118
1119
1120
1121
1122
1123
            return;
          }
  
          const fromLabels = await fetchLocationIdsForMultipleOption(option.id, ac.signal);
          if (ac.signal.aborted) return;
          if (fromLabels.length > 0) {
c9bc327f   杨鑫   修改前端
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
            if (requireCompanySelection) {
              const scope = hydrateLabelingScopeFromLocationIds(fromLabels, locations, partners, groups);
              setSelectedPartnerIds(scope.partnerIds);
              setSelectedRegionIds(scope.regionIds);
              setSelectedLocationIds(scope.locationIds);
              setSelectedPartnerId("");
              setSelectedRegionNames([]);
            } else {
              const scope = hydrateCategoryScopeFromLocationIds(fromLabels, locations, partners, groups);
              setSelectedPartnerId(scope.partnerId);
              setSelectedRegionNames(scope.regionNames);
              setSelectedLocationIds(scope.locationIds);
              setSelectedPartnerIds([]);
              setSelectedRegionIds([]);
            }
ef6b3255   杨鑫   修改BUG
1139
          } else {
91821909   杨鑫   最新
1140
            setSelectedPartnerId("");
c9bc327f   杨鑫   修改前端
1141
            setSelectedPartnerIds([]);
ef6b3255   杨鑫   修改BUG
1142
            setSelectedRegionNames([]);
c9bc327f   杨鑫   修改前端
1143
            setSelectedRegionIds([]);
ef6b3255   杨鑫   修改BUG
1144
1145
            setSelectedLocationIds([]);
          }
1b68006d   李曜臣   20260708
1146
1147
          setSelectedPartnerIds([]);
          setSelectedRegionIds([]);
ef6b3255   杨鑫   修改BUG
1148
1149
1150
        } catch {
          if (ac.signal.aborted) return;
          setForm({
ef6b3255   杨鑫   修改BUG
1151
1152
1153
1154
1155
            optionName: option.optionName ?? "",
            optionValuesJson: option.optionValuesJson ?? [],
            state: option.state ?? true,
            orderNum: option.orderNum ?? null,
          });
91821909   杨鑫   最新
1156
          setSelectedPartnerId("");
1b68006d   李曜臣   20260708
1157
          setSelectedPartnerIds([]);
ef6b3255   杨鑫   修改BUG
1158
          setSelectedRegionNames([]);
1b68006d   李曜臣   20260708
1159
          setSelectedRegionIds([]);
ef6b3255   杨鑫   修改BUG
1160
1161
1162
1163
1164
1165
1166
1167
          setSelectedLocationIds([]);
          setNewValue("");
        } finally {
          if (!ac.signal.aborted) setLoadingDetail(false);
        }
      })();
  
      return () => ac.abort();
c9bc327f   杨鑫   修改前端
1168
    }, [open, option, locations, partners, groups, requireCompanySelection]);
0e27ddc8   杨鑫   标签
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
  
    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   杨鑫   完善打印逻辑
1195
      if (!form.optionName.trim()) {
0e27ddc8   杨鑫   标签
1196
        toast.error("Validation failed", {
699ea6e8   杨鑫   完善打印逻辑
1197
          description: "Option Name is required.",
0e27ddc8   杨鑫   标签
1198
1199
1200
1201
1202
1203
1204
1205
1206
        });
        return;
      }
      if (form.optionValuesJson.length === 0) {
        toast.error("Validation failed", {
          description: "At least one option value is required.",
        });
        return;
      }
3d4c10ac   杨鑫   对接,标签产品
1207
1208
1209
1210
      if (form.orderNum === null || form.orderNum === undefined || !Number.isFinite(form.orderNum)) {
        toast.error("Validation failed", { description: "Order is required." });
        return;
      }
0e27ddc8   杨鑫   标签
1211
  
1b68006d   李曜臣   20260708
1212
      const scopePayload = buildEntityScopeSaveFromForm({
91821909   杨鑫   最新
1213
1214
        requireCompanySelection,
        selectedPartnerId,
c9bc327f   杨鑫   修改前端
1215
        selectedPartnerIds,
ef6b3255   杨鑫   修改BUG
1216
        selectedRegionNames,
c9bc327f   杨鑫   修改前端
1217
        selectedRegionIds,
ef6b3255   杨鑫   修改BUG
1218
        selectedLocationIds,
91821909   杨鑫   最新
1219
        fixedPartnerId,
ef6b3255   杨鑫   修改BUG
1220
        locations,
c9bc327f   杨鑫   修改前端
1221
1222
        partners,
        groups,
c9bc327f   杨鑫   修改前端
1223
1224
1225
      });
      if (!scopePayload.ok) {
        toast.error("Validation failed", { description: scopePayload.message });
ef6b3255   杨鑫   修改BUG
1226
1227
1228
        return;
      }
  
0e27ddc8   杨鑫   标签
1229
1230
      setSubmitting(true);
      try {
ef6b3255   杨鑫   修改BUG
1231
1232
        await updateLabelMultipleOption(option.id, {
          ...form,
91821909   杨鑫   最新
1233
          optionCode: option.optionCode ?? "",
1b68006d   李曜臣   20260708
1234
          ...scopePayload.body,
ef6b3255   杨鑫   修改BUG
1235
        });
0e27ddc8   杨鑫   标签
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
        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   杨鑫   最新
1261
1262
1263
1264
1265
1266
1267
            <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   杨鑫   标签
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
            </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   杨鑫   对接,标签产品
1308
                <Label>Order *</Label>
0e27ddc8   杨鑫   标签
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
                <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
1321
1322
  
            {loadingDetail ? (
91821909   杨鑫   最新
1323
              <p className="text-sm text-gray-500">Loading company, region and location…</p>
ef6b3255   杨鑫   修改BUG
1324
            ) : (
91821909   杨鑫   最新
1325
1326
1327
              <CategoryScopeFields
                partners={partners}
                groups={groups}
ef6b3255   杨鑫   修改BUG
1328
                locations={locations}
91821909   杨鑫   最新
1329
1330
                selectedPartnerId={selectedPartnerId}
                onPartnerChange={setSelectedPartnerId}
c9bc327f   杨鑫   修改前端
1331
1332
                selectedPartnerIds={selectedPartnerIds}
                onPartnerIdsChange={setSelectedPartnerIds}
ef6b3255   杨鑫   修改BUG
1333
                selectedRegionNames={selectedRegionNames}
ef6b3255   杨鑫   修改BUG
1334
                onRegionChange={setSelectedRegionNames}
c9bc327f   杨鑫   修改前端
1335
1336
                selectedRegionIds={selectedRegionIds}
                onRegionIdsChange={setSelectedRegionIds}
91821909   杨鑫   最新
1337
                selectedLocationIds={selectedLocationIds}
ef6b3255   杨鑫   修改BUG
1338
                onLocationChange={setSelectedLocationIds}
91821909   杨鑫   最新
1339
1340
                requireCompanySelection={requireCompanySelection}
                fixedPartnerId={fixedPartnerId}
c9bc327f   杨鑫   修改前端
1341
                templateScopeMode={requireCompanySelection}
1b68006d   李曜臣   20260708
1342
1343
1344
1345
                selectedPartnerIds={selectedPartnerIds}
                onPartnerIdsChange={setSelectedPartnerIds}
                selectedRegionIds={selectedRegionIds}
                onRegionIdsChange={setSelectedRegionIds}
ef6b3255   杨鑫   修改BUG
1346
1347
              />
            )}
0e27ddc8   杨鑫   标签
1348
1349
1350
1351
1352
1353
          </div>
  
          <DialogFooter>
            <Button variant="outline" onClick={() => onOpenChange(false)}>
              Cancel
            </Button>
ef6b3255   杨鑫   修改BUG
1354
            <Button disabled={submitting || loadingDetail} onClick={submit}>
0e27ddc8   杨鑫   标签
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
              {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   杨鑫   产品 标签 关联
1417
              className="min-w-24 gap-2"
0e27ddc8   杨鑫   标签
1418
1419
1420
1421
              variant="destructive"
              disabled={submitting}
              onClick={submit}
            >
3af4878d   杨鑫   产品 标签 关联
1422
              <Trash2 className="h-4 w-4 shrink-0" />
0e27ddc8   杨鑫   标签
1423
1424
1425
1426
1427
1428
1429
              {submitting ? "Deleting..." : "Delete"}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    );
  }