From 3b969879b6b34a5e6b2c357472b20ddcb1156de2 Mon Sep 17 00:00:00 2001 From: jokerxue <2509699647@qq.com> Date: Thu, 9 Jul 2026 16:17:03 +0800 Subject: [PATCH] 修改bug --- 美国版/Food Labeling Management App UniApp/src/pages/labels/preview.vue | 32 +++++++++++++++++++++++++++----- 美国版/Food Labeling Management App UniApp/src/utils/print/manager/printerManager.ts | 32 +++++++++++++++++++++++++++++--- 美国版/Food Labeling Management App UniApp/src/utils/print/printerConnection.ts | 116 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++------------------------------------------- 美国版/Food Labeling Management App UniApp/src/utils/printFromPrintDataList.ts | 1 - 美国版/Food Labeling Management Platform/src/components/labels/LabelTemplateEditor/index.tsx | 15 ++++++++++++--- 美国版/Food Labeling Management Platform/src/components/labels/LabelsList.tsx | 887 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-------------- 美国版/Food Labeling Management Platform/src/components/shared/category-scope-fields.tsx | 57 +++++++++++++++++++++++++++++++++++++++++++++++++++------ 美国版/Food Labeling Management Platform/src/lib/categoryScopeForm.ts | 106 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----------------------- 美国版/Food Labeling Management Platform/src/lib/labelEntityScopeApi.ts | 124 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 美国版/Food Labeling Management Platform/src/services/labelCategoryService.ts | 46 ++++++++-------------------------------------- 美国版/Food Labeling Management Platform/src/services/labelMultipleOptionService.ts | 53 ++++++++--------------------------------------------- 美国版/Food Labeling Management Platform/src/services/labelTemplateService.ts | 65 ++++++++++------------------------------------------------------- 美国版/Food Labeling Management Platform/src/services/labelTypeService.ts | 48 ++++++++---------------------------------------- 美国版/Food Labeling Management Platform/src/types/labelTemplate.ts | 40 ++++++++++++++++++++++++---------------- 14 files changed, 1330 insertions(+), 292 deletions(-) create mode 100644 美国版/Food Labeling Management Platform/src/lib/labelEntityScopeApi.ts diff --git a/美国版/Food Labeling Management App UniApp/src/pages/labels/preview.vue b/美国版/Food Labeling Management App UniApp/src/pages/labels/preview.vue index cb6baf3..bdcfc97 100644 --- a/美国版/Food Labeling Management App UniApp/src/pages/labels/preview.vue +++ b/美国版/Food Labeling Management App UniApp/src/pages/labels/preview.vue @@ -1446,6 +1446,29 @@ async function loadPreview() { } return '' } + const readTemplateName = (...sources: Array): string => { + for (const source of sources) { + if (source == null || typeof source !== 'object' || Array.isArray(source)) continue + const obj = source as Record + const direct = + obj.name ?? + obj.Name ?? + obj.templateName ?? + obj.TemplateName + if (direct != null && String(direct).trim()) return String(direct).trim() + const nestedTemplate = obj.template ?? obj.Template + if (nestedTemplate != null && typeof nestedTemplate === 'object' && !Array.isArray(nestedTemplate)) { + const t = nestedTemplate as Record + const nestedName = + t.name ?? + t.Name ?? + t.templateName ?? + t.TemplateName + if (nestedName != null && String(nestedName).trim()) return String(nestedName).trim() + } + } + return '' + } const leStr = readLastEdited(root) || readLastEdited(inner) lastEdited.value = leStr || '—' @@ -1468,6 +1491,10 @@ async function loadPreview() { previewLoading.value = false return } + const templateNameFromApi = readTemplateName(inner, root, tmplRaw) + if (templateNameFromApi) { + templateName.value = templateNameFromApi + } const lstRaw = root.labelSizeText ?? root.LabelSizeText ?? @@ -1717,13 +1744,8 @@ const handlePrint = async () => { */ const tmplForNativeJob = normalizeTemplateForNativeFastJob(tmpl, printInputJson as any, printBaseTime) const printSummary = getCurrentPrinterSummary() - const printConn = getBluetoothConnection() - const isVirtualBtActive = - printSummary.type === 'bluetooth' - && isVirtualBtPrinterDeviceName(printConn?.deviceName) const mustUseCanvasRasterPrint = printSummary.type === 'builtin' - || isVirtualBtActive || templateRequiresCanvasStyleFidelity(tmpl) || templateHasDateTimeElements(tmpl) const currentDriver = getCurrentPrinterDriver() diff --git a/美国版/Food Labeling Management App UniApp/src/utils/print/manager/printerManager.ts b/美国版/Food Labeling Management App UniApp/src/utils/print/manager/printerManager.ts index 7bbacf2..652455a 100644 --- a/美国版/Food Labeling Management App UniApp/src/utils/print/manager/printerManager.ts +++ b/美国版/Food Labeling Management App UniApp/src/utils/print/manager/printerManager.ts @@ -860,6 +860,7 @@ export async function printImageForCurrentPrinter ( } } else { try { + const sendStageMs = isVirtualBtBluetoothConnection() ? 600000 : 180000 await withStageTimeout( sendToPrinter(data, (p) => { lastExternalProgressAt = Date.now() @@ -868,7 +869,7 @@ export async function printImageForCurrentPrinter ( printRunDiag('printImage_send_progress', { p }) } }), - 180000, + sendStageMs, 'sendToPrinter' ) } finally { @@ -897,11 +898,36 @@ export async function printImageDataForCurrentPrinter ( const rasterDriver = resolveRasterPrintDriver(driver) let raster = rasterizeImageData(imageData, options) raster = finalizeRasterForPrint(raster, rasterDriver.protocol, options) - if (onProgress) onProgress(5) + if (onProgress) onProgress(18) const data = rasterDriver.protocol === 'esc' ? buildEscPosImageData(raster, options) : buildTscImageData(raster, options, rasterDriver.imageDpi || 203) - await sendToPrinter(data, onProgress) + let sendVisual = 22 + let lastExternalAt = Date.now() + const reportSend = (p: number) => { + if (!onProgress) return + const mapped = 22 + Math.round((Math.min(100, Math.max(0, p)) / 100) * 78) + if (mapped > sendVisual) { + sendVisual = mapped + onProgress(sendVisual) + } else { + lastExternalAt = Date.now() + } + } + const keepAlive = onProgress + ? setInterval(() => { + if (Date.now() - lastExternalAt < 1200) return + if (sendVisual >= 96) return + sendVisual += sendVisual < 80 ? 2 : 1 + onProgress(sendVisual) + }, 800) + : null + try { + await sendToPrinter(data, reportSend) + } finally { + if (keepAlive) clearInterval(keepAlive) + } + if (onProgress) onProgress(100) return driver } diff --git a/美国版/Food Labeling Management App UniApp/src/utils/print/printerConnection.ts b/美国版/Food Labeling Management App UniApp/src/utils/print/printerConnection.ts index 92e77af..a60175a 100644 --- a/美国版/Food Labeling Management App UniApp/src/utils/print/printerConnection.ts +++ b/美国版/Food Labeling Management App UniApp/src/utils/print/printerConnection.ts @@ -595,15 +595,12 @@ export function resolvePrintSendChannelHint (): string { const conn = getBluetoothConnection() const uposSupported = isNativeUposPrintSupported() const uposPrefer = getUposOptionsFromStorage().prefer || 'builtin' - if (virtualBt && isD320faxAioDevice()) { + if (virtualBt) { if (conn?.transportMode === 'native-plugin' && isNativePrintCommandBytesSupported()) { return 'Gprinter SDK TSC (Virtual BT)' } return 'Bluetooth classic TSC (Virtual BT)' } - if (virtualBt && uposSupported && !isD320faxAioDevice()) { - return `UPOS/${uposPrefer} (Virtual BT redirect)` - } if (type === 'builtin') { if (uposSupported) return `UPOS/${uposPrefer}` if (isBuiltinPrinterAvailable()) return 'TCP localhost' @@ -633,16 +630,14 @@ export function preferBuiltinPrinterOnAioDevice (): boolean { restoreD320faxVirtualBtBluetoothMode() if (getPrinterType() === 'builtin') { - if (isD320faxAioDevice() && isVirtualBtBluetoothConnection()) return false + if (isVirtualBtBluetoothConnection()) return false return true } if (!isAioBuiltinPrintCapable()) return false - /** D320FAX:佳博 SDK + Virtual BT + TSC 光栅,保持 bluetooth 模式 */ + /** 一体机已连 Virtual BT:保持 Bluetooth + 佳博 TSC,勿切 Built-in/UPOS */ if (isVirtualBtBluetoothConnection()) { - if (isD320faxAioDevice()) return false - setBuiltinPrinter(getCurrentPrinterDriverKey() || 'generic-tsc') - return true + return false } if (!isBuiltinPrinterEnabledByDeviceModel()) return false @@ -694,17 +689,9 @@ export function sendToPrinter ( const type = getPrinterType() printRunDiag('sendToPrinter', { type, dataBytes: data?.length || 0 }) - /** D320FAX Virtual BT:佳博 SDK 为 TSC 模式,禁止走 UPOS(串口全失败) */ - if (isVirtualBtBluetoothConnection() && isD320faxAioDevice()) { - return sendViaD320faxVirtualBt(data, onProgress) - } - - /** rk3568 等 UPOS 可用机型:Virtual BT 光栅改走 UPOS 内置物理通道 */ - if (isVirtualBtBluetoothConnection() && isNativeUposPrintSupported()) { - printRunDiag('sendToPrinter_virtual_bt_upos_redirect', { dataBytes: data?.length || 0 }) - return sendViaBuiltin(data).then(() => { - if (onProgress) onProgress(100) - }) + /** Virtual BT:TSC 光栅必须走佳博 SDK / 经典蓝牙 SPP,禁止误投 UPOS(TSC 字节 UPOS 不认会卡死) */ + if (isVirtualBtBluetoothConnection()) { + return sendViaVirtualBtTsc(data, onProgress) } if (type === 'bluetooth') { @@ -1142,23 +1129,49 @@ function numberArrayToBase64 (data: number[]): string { } /** - * D320FAX + Virtual BT:Canvas 光栅 → TSC 指令 → 佳博 SDK printCommandBytes。 + * Virtual BT(含 D320FAX / AOA 一体机):Canvas 光栅 TSC 指令 → 佳博 SDK printCommandBytes 或经典蓝牙 SPP。 */ -async function sendViaD320faxVirtualBt ( +async function sendViaVirtualBtTsc ( data: number[], onProgress?: (percent: number) => void, ): Promise { - printRunDiag('sendToPrinter_d320fax_virtual_bt', { dataBytes: data?.length || 0 }) + printRunDiag('sendToPrinter_virtual_bt_tsc', { dataBytes: data?.length || 0 }) await ensureNativeClassicTransportIfPossible() const conn = getBluetoothConnection() if (conn?.transportMode === 'native-plugin' && isNativePrintCommandBytesSupported()) { - return sendViaNativeClassicPlugin(data, onProgress) + const nativeWaitMs = Math.min( + 600000, + Math.max(60000, estimateClassicSendTimeoutMs(data.length)), + ) + try { + await sendViaNativeClassicPlugin(data, onProgress, { writeTimeoutMs: nativeWaitMs }) + return + } catch (e) { + printRunDiag('virtual_bt_native_bytes_fallback_js', { + err: String((e as Error)?.message || e), + dataBytes: data.length, + }) + try { + if (classicBluetooth?.ensureConnection) { + classicBluetooth.ensureConnection(conn.deviceId) + } + } catch (_) {} + return sendViaClassic(data, onProgress) + } } if (conn?.deviceType === 'classic') { - printRunDiag('sendToPrinter_d320fax_classic_js', { dataBytes: data?.length || 0 }) + printRunDiag('sendToPrinter_virtual_bt_classic_js', { dataBytes: data?.length || 0 }) return sendViaClassic(data, onProgress) } - return Promise.reject(new Error('D320FAX Virtual BT printer not connected.')) + return Promise.reject(new Error('Virtual BT printer not connected.')) +} + +/** @deprecated 使用 sendViaVirtualBtTsc;保留别名兼容旧诊断关键字 */ +async function sendViaD320faxVirtualBt ( + data: number[], + onProgress?: (percent: number) => void, +): Promise { + return sendViaVirtualBtTsc(data, onProgress) } /** @@ -1166,7 +1179,8 @@ async function sendViaD320faxVirtualBt ( */ function sendViaNativeClassicPlugin ( data: number[], - onProgress?: (percent: number) => void + onProgress?: (percent: number) => void, + options: { writeTimeoutMs?: number } = {}, ): Promise { const conn = getBluetoothConnection() if (!conn || conn.deviceType !== 'classic' || conn.transportMode !== 'native-plugin') { @@ -1179,23 +1193,40 @@ function sendViaNativeClassicPlugin ( if (!base64) { return Promise.reject(new Error('BASE64_ENCODE_FAILED')) } - const writeTimeoutMs = Math.min(600000, Math.max(45000, estimateClassicSendTimeoutMs(data.length))) + const writeTimeoutMs = options.writeTimeoutMs + ?? Math.min(600000, Math.max(45000, estimateClassicSendTimeoutMs(data.length))) if (onProgress) onProgress(5) + let waitVisual = 5 + const waitKeepAlive = onProgress + ? setInterval(() => { + if (waitVisual >= 95) return + waitVisual = Math.min(95, waitVisual + 1) + onProgress(waitVisual) + }, 1200) + : null return printNativeCommandBytes({ deviceId: conn.deviceId, deviceName: conn.deviceName, base64, }).then(async () => { printRunDiag('native_printCommandBytes_queued', { dataBytes: data.length }) - const verified = await waitForNativeCommandBytesWriteComplete(writeTimeoutMs, (waitPct) => { - if (onProgress) onProgress(8 + Math.round(waitPct * 0.9)) - }) - printRunDiag('native_printCommandBytes_verified', { - writeMs: verified.writeMs, - commandBytes: verified.commandBytes, - stage: verified.stage, - }) - if (onProgress) onProgress(100) + try { + const verified = await waitForNativeCommandBytesWriteComplete(writeTimeoutMs, (waitPct) => { + if (onProgress) { + const p = Math.max(waitVisual, 8 + Math.round(waitPct * 0.9)) + waitVisual = p + onProgress(p) + } + }) + printRunDiag('native_printCommandBytes_verified', { + writeMs: verified.writeMs, + commandBytes: verified.commandBytes, + stage: verified.stage, + }) + if (onProgress) onProgress(100) + } finally { + if (waitKeepAlive) clearInterval(waitKeepAlive) + } }) } @@ -1402,8 +1433,7 @@ function sendViaBuiltin (data: number[]): Promise { const shouldTryUpos = uposSupported && ( uposOptions.force || (matchesKeywords && !isD320faxDevice) - || (virtualBtLinked && !isD320faxDevice) - || (getPrinterType() === 'builtin' && !isD320faxDevice) + || (getPrinterType() === 'builtin' && !isD320faxDevice && !virtualBtLinked) ) const shouldPreferTcpFirst = (matchesKeywords || isD320faxDevice) && !uposOptions.force @@ -1493,13 +1523,13 @@ function sendViaBuiltin (data: number[]): Promise { const msg = e instanceof Error ? e.message : String(e || 'UPOS_PRINT_FAILED') printRunDiag('builtin_upos_fail_fallback', { err: msg.slice(0, 240), waitMs: Date.now() - tUpos }) - if (isVirtualBtBluetoothConnection() && isD320faxAioDevice()) { + if (isVirtualBtBluetoothConnection()) { try { - await sendViaD320faxVirtualBt(data, onProgress) + await sendViaVirtualBtTsc(data, onProgress) return } catch (gErr: any) { - const gMsg = gErr instanceof Error ? gErr.message : String(gErr || 'GPRINTER_SDK_FAILED') - throw new Error(`UPOS failed (${msg}); Gprinter SDK failed (${gMsg})`) + const gMsg = gErr instanceof Error ? gErr.message : String(gErr || 'VIRTUAL_BT_TSC_FAILED') + throw new Error(`UPOS failed (${msg}); Virtual BT TSC failed (${gMsg})`) } } diff --git a/美国版/Food Labeling Management App UniApp/src/utils/printFromPrintDataList.ts b/美国版/Food Labeling Management App UniApp/src/utils/printFromPrintDataList.ts index 548cbb1..c284a58 100644 --- a/美国版/Food Labeling Management App UniApp/src/utils/printFromPrintDataList.ts +++ b/美国版/Food Labeling Management App UniApp/src/utils/printFromPrintDataList.ts @@ -453,7 +453,6 @@ async function printReprintTemplateWithPreviewStrategy ( const conn = getBluetoothConnection() const mustUseCanvasRaster = summary.type === 'builtin' - || (summary.type === 'bluetooth' && isVirtualBtPrinterDeviceName(conn?.deviceName)) || templateRequiresCanvasStyleFidelity(tmplSized) || templateHasDateTimeElements(tmplSized) const useNative = diff --git a/美国版/Food Labeling Management Platform/src/components/labels/LabelTemplateEditor/index.tsx b/美国版/Food Labeling Management Platform/src/components/labels/LabelTemplateEditor/index.tsx index cae5a70..8dd2cb8 100644 --- a/美国版/Food Labeling Management Platform/src/components/labels/LabelTemplateEditor/index.tsx +++ b/美国版/Food Labeling Management Platform/src/components/labels/LabelTemplateEditor/index.tsx @@ -61,6 +61,7 @@ import { getGroups } from '../../../services/groupService'; import { getPartners } from '../../../services/partnerService'; import { skipCountForPage } from '../../../lib/paginationQuery'; import { + filterScopeIdsForPartners, hydrateLabelTemplateScopeFromDto, locationsScopedForTemplateScope, regionOptionsForPartners, @@ -636,6 +637,14 @@ export function LabelTemplateEditor({ const availablePartnerIds = scopeAuth.requireCompanySelection ? filterPartners.map((p) => p.id).filter(Boolean) : effectivePartnerIds; + const sanitizedScope = filterScopeIdsForPartners({ + partners: filterPartners, + groups: filterGroups, + locations: locationCatalog, + partnerIds: effectivePartnerIds, + regionIds: scopeRegionIds, + locationIds: scopeLocationIds, + }); const availableRegionIds = regionOptionsForPartners( filterGroups, effectivePartnerIds.length > 0 ? effectivePartnerIds : availablePartnerIds, @@ -645,14 +654,14 @@ export function LabelTemplateEditor({ filterPartners, filterGroups, effectivePartnerIds, - scopeRegionIds, + sanitizedScope.regionIds, ); const availableLocationIds = scopedLocations.map((l) => l.id); const scopePayload = buildLabelTemplateScopePayload({ selectedPartnerIds: effectivePartnerIds, - selectedRegionIds: scopeRegionIds, - selectedLocationIds: scopeLocationIds, + selectedRegionIds: sanitizedScope.regionIds, + selectedLocationIds: sanitizedScope.locationIds, availablePartnerIds, availableRegionIds, availableLocationIds, diff --git a/美国版/Food Labeling Management Platform/src/components/labels/LabelsList.tsx b/美国版/Food Labeling Management Platform/src/components/labels/LabelsList.tsx index a933cc3..1c28634 100755 --- a/美国版/Food Labeling Management Platform/src/components/labels/LabelsList.tsx +++ b/美国版/Food Labeling Management Platform/src/components/labels/LabelsList.tsx @@ -27,7 +27,7 @@ import { import { Label } from "../ui/label"; import { Switch } from "../ui/switch"; import { Badge } from "../ui/badge"; -import { Plus, Edit, MoreHorizontal, Trash2 } from "lucide-react"; +import { ArrowLeft, Plus, Edit, MoreHorizontal, Trash2 } from "lucide-react"; import { toast } from "sonner"; import { skipCountForPage } from "../../lib/paginationQuery"; import { preventDialogDismissOnOverlay } from "../../lib/formDialogLayout"; @@ -67,7 +67,6 @@ import type { ProductDto } from "../../types/product"; import type { ProductCategoryDto } from "../../types/productCategory"; import type { ProductLocationLinkDto } from "../../types/productLocation"; import { getProductLocations } from "../../services/productLocationService"; -import { LabelTemplateDataEntryView } from "./LabelTemplateDataEntryView"; import { NutritionManualEntryForm } from "./NutritionManualEntryForm"; import { LabelPreviewOnly } from "./LabelTemplateEditor/LabelCanvas"; import { @@ -298,6 +297,17 @@ function labelCategoryMatchesRegion(c: LabelCategoryDto, allowedLocIds: Set allowedLocIds.has(lid)); } +function labelTypeMatchesRegion(t: LabelTypeDto, allowedLocIds: Set): boolean { + const at = String(t.availabilityType ?? "ALL").trim().toUpperCase(); + if (at !== "SPECIFIED") return true; + const lids = (t.locationIds ?? []).map((x) => String(x).trim()).filter(Boolean); + return lids.some((lid) => allowedLocIds.has(lid)); +} + +type TemplateInputColumn = + | { kind: "element"; el: LabelElement } + | { kind: "nutrition"; parent: LabelElement; spec: NutritionManualFieldSpec }; + function templateAppliesToRegion(tpl: LabelTemplateDto, allowedLocIds: Set): boolean { const mode = appliedLocationToEditor(tpl); if (mode === "ALL") return true; @@ -959,8 +969,8 @@ type LabelsListProps = { }; export function LabelsList({ openCreateSeq = 0, onOpenCreateIntentConsumed }: LabelsListProps = {}) { - const [dataEntryTemplateCode, setDataEntryTemplateCode] = useState(null); - const [dataEntryContextHint, setDataEntryContextHint] = useState(undefined); + const [bulkAddTemplateCode, setBulkAddTemplateCode] = useState(null); + const [bulkAddContextHint, setBulkAddContextHint] = useState(undefined); const [isBulkAddDialogOpen, setIsBulkAddDialogOpen] = useState(false); const [bulkLoadingTemplates, setBulkLoadingTemplates] = useState(false); const [bulkLoadingPreview, setBulkLoadingPreview] = useState(false); @@ -1311,8 +1321,8 @@ export function LabelsList({ openCreateSeq = 0, onOpenCreateIntentConsumed }: La } const tpl = bulkTemplates.find((x) => templateListCode(x) === bulkTemplateCode); const title = tpl ? templateListLabel(tpl) : bulkTemplateCode; - setDataEntryContextHint(`Bulk Add template: ${title}`); - setDataEntryTemplateCode(bulkTemplateCode); + setBulkAddContextHint(`Template: ${title}`); + setBulkAddTemplateCode(bulkTemplateCode); setIsBulkAddDialogOpen(false); }; @@ -1324,19 +1334,19 @@ export function LabelsList({ openCreateSeq = 0, onOpenCreateIntentConsumed }: La } }; - const closeDataEntry = () => { - setDataEntryTemplateCode(null); - setDataEntryContextHint(undefined); + const closeBulkAddPage = () => { + setBulkAddTemplateCode(null); + setBulkAddContextHint(undefined); refreshList(); }; - if (dataEntryTemplateCode) { + if (bulkAddTemplateCode) { return (
-
); @@ -1719,6 +1729,855 @@ export function LabelsList({ openCreateSeq = 0, onOpenCreateIntentConsumed }: La ); } +type BulkAddRow = { + id: string; + partnerId: string; + regionIds: string[]; + productCategoryId: string; + productId: string; + labelName: string; + locationIds: string[]; + labelCategoryId: string; + labelTypeId: string; + state: boolean; + templateDataValues: Record; + templateDateOffsets: Record; + nutritionByElementId: Record>; +}; + +function createEmptyBulkAddRow(scopeAuth: ReturnType): BulkAddRow { + return { + id: `row-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`, + partnerId: scopeAuth.requireCompanySelection ? "" : scopeAuth.fixedPartnerId.trim(), + regionIds: [], + productCategoryId: "", + productId: "", + labelName: "", + locationIds: [], + labelCategoryId: "", + labelTypeId: "", + state: true, + templateDataValues: {}, + templateDateOffsets: {}, + nutritionByElementId: {}, + }; +} + +function LabelBulkAddPage({ + templateCode, + onBack, + contextHint, +}: { + templateCode: string; + onBack: () => void; + contextHint?: string; +}) { + const scopeAuth = useCategoryScopeAuth(); + const { + loading, + templates, + locations, + groups, + partners, + categories, + types, + products, + productCategories, + productLocationMap, + } = useLabelFormReferenceData(true, null); + const [rows, setRows] = useState(() => [createEmptyBulkAddRow(scopeAuth)]); + const [saving, setSaving] = useState(false); + const [bulkTemplateDetail, setBulkTemplateDetail] = useState(null); + const [bulkTemplateDetailLoading, setBulkTemplateDetailLoading] = useState(false); + + useEffect(() => { + if (scopeAuth.requireCompanySelection) return; + const fixed = scopeAuth.fixedPartnerId.trim(); + if (!fixed) return; + setRows((prev) => + prev.map((row) => (row.partnerId === fixed ? row : { ...row, partnerId: fixed })), + ); + }, [scopeAuth.requireCompanySelection, scopeAuth.fixedPartnerId]); + + useEffect(() => { + const code = templateCode.trim(); + if (!code) { + setBulkTemplateDetail(null); + return; + } + let cancelled = false; + (async () => { + setBulkTemplateDetailLoading(true); + try { + const tpl = await getLabelTemplate(code); + if (!cancelled) setBulkTemplateDetail(tpl); + } catch (e: any) { + if (!cancelled) { + setBulkTemplateDetail(null); + toast.error("Failed to load template fields.", { + description: e?.message ? String(e.message) : "Please try again.", + }); + } + } finally { + if (!cancelled) setBulkTemplateDetailLoading(false); + } + })(); + return () => { + cancelled = true; + }; + }, [templateCode]); + + const templateFromList = useMemo( + () => templates.find((t) => templateListCode(t) === templateCode) ?? null, + [templates, templateCode], + ); + + const selectedTemplate = bulkTemplateDetail ?? templateFromList; + + const selectedTemplateLabel = selectedTemplate ? templateListLabel(selectedTemplate) : templateCode; + + const bulkDataEntryElements = useMemo( + () => getCreateLabelTemplateInputElements(selectedTemplate), + [selectedTemplate], + ); + + const bulkNutritionElements = useMemo( + () => listNutritionElements(((selectedTemplate?.elements ?? []) as LabelElement[])), + [selectedTemplate], + ); + + const bulkTemplateInputColumns = useMemo(() => { + const cols: TemplateInputColumn[] = bulkDataEntryElements.map((el) => ({ kind: "element", el })); + for (const nel of bulkNutritionElements) { + for (const spec of listNutritionManualFieldSpecs(nel)) { + cols.push({ kind: "nutrition", parent: nel, spec }); + } + } + return cols; + }, [bulkDataEntryElements, bulkNutritionElements]); + + const showTemplateInputColumns = bulkTemplateInputColumns.length > 0; + + useEffect(() => { + if (!selectedTemplate) return; + const empty = emptyLabelFormTemplateInputState(selectedTemplate); + setRows((prev) => + prev.map((row) => ({ + ...row, + templateDataValues: { ...empty.textValues, ...row.templateDataValues }, + templateDateOffsets: { ...empty.dateOffsets, ...row.templateDateOffsets }, + nutritionByElementId: { + ...empty.nutritionByElementId, + ...row.nutritionByElementId, + }, + })), + ); + }, [selectedTemplate]); + + const companyOptions = useMemo( + () => + [...partners] + .filter((p) => (p.id ?? "").trim()) + .sort((a, b) => + (a.partnerName ?? "").localeCompare(b.partnerName ?? "", undefined, { sensitivity: "base" }), + ) + .map((p) => ({ + value: (p.id ?? "").trim(), + label: toDisplay(p.partnerName), + })), + [partners], + ); + + const updateRow = (rowId: string, patch: Partial) => { + setRows((prev) => prev.map((row) => (row.id === rowId ? { ...row, ...patch } : row))); + }; + + const updateRowTemplateText = (rowId: string, elementId: string, value: string) => { + setRows((prev) => + prev.map((row) => + row.id === rowId + ? { + ...row, + templateDataValues: { + ...row.templateDataValues, + [elementId]: value, + }, + } + : row, + ), + ); + }; + + const updateRowTemplateDateOffset = ( + rowId: string, + elementId: string, + patch: Partial<{ unit: string; value: string }>, + ) => { + setRows((prev) => + prev.map((row) => { + if (row.id !== rowId) return row; + const cur = row.templateDateOffsets[elementId] ?? { unit: "Days", value: "" }; + return { + ...row, + templateDateOffsets: { + ...row.templateDateOffsets, + [elementId]: { ...cur, ...patch }, + }, + }; + }), + ); + }; + + const updateRowNutritionValue = ( + rowId: string, + elementId: string, + subKey: string, + value: string, + ) => { + setRows((prev) => + prev.map((row) => + row.id === rowId + ? { + ...row, + nutritionByElementId: { + ...row.nutritionByElementId, + [elementId]: { + ...(row.nutritionByElementId[elementId] ?? {}), + [subKey]: value, + }, + }, + } + : row, + ), + ); + }; + + const updateRowPartner = (rowId: string, partnerId: string) => { + updateRow(rowId, { + partnerId, + regionIds: [], + productCategoryId: "", + productId: "", + locationIds: [], + labelCategoryId: "", + labelTypeId: "", + }); + }; + + const updateRowProduct = (row: BulkAddRow, productId: string, productOptionsSource: ProductDto[]) => { + if (!selectedTemplate) { + updateRow(row.id, { productId }); + return; + } + const productCodeValue = (() => { + const p = productOptionsSource.find((x) => x.id === productId); + return (p?.codeValue ?? "").trim(); + })(); + updateRow(row.id, { + productId, + templateDataValues: { + ...row.templateDataValues, + ...buildTemplateBarcodeQrDefaultsFromCodeValue( + (selectedTemplate.elements ?? []) as LabelElement[], + productCodeValue, + ), + }, + }); + }; + + const updateRowLabelName = (row: BulkAddRow, labelName: string) => { + if (!selectedTemplate) { + updateRow(row.id, { labelName }); + return; + } + updateRow(row.id, { + labelName, + templateDataValues: mergeLabelBindingsIntoTextValues( + row.templateDataValues, + (selectedTemplate.elements ?? []) as LabelElement[], + { labelName }, + ), + }); + }; + + const updateRowLabelType = (row: BulkAddRow, labelTypeId: string, labelTypeOptionsSource: LabelTypeDto[]) => { + if (!selectedTemplate) { + updateRow(row.id, { labelTypeId }); + return; + } + const labelType = labelTypeOptionsSource.find((x) => x.id === labelTypeId); + updateRow(row.id, { + labelTypeId, + templateDataValues: mergeLabelBindingsIntoTextValues( + row.templateDataValues, + (selectedTemplate.elements ?? []) as LabelElement[], + { labelTypeName: labelType?.typeName ?? labelType?.typeCode }, + ), + }); + }; + + const updateRowRegions = (rowId: string, regionIds: string[]) => { + updateRow(rowId, { + regionIds, + productCategoryId: "", + productId: "", + locationIds: [], + labelCategoryId: "", + labelTypeId: "", + }); + }; + + const addRow = () => setRows((prev) => [...prev, createEmptyBulkAddRow(scopeAuth)]); + const removeRow = (rowId: string) => + setRows((prev) => (prev.length <= 1 ? prev : prev.filter((row) => row.id !== rowId))); + + const validateAndBuildInput = (row: BulkAddRow, index: number): LabelCreateInput | null => { + const rowName = `Row ${index + 1}`; + const effectivePartnerId = effectiveScopePartnerId( + scopeAuth.requireCompanySelection, + row.partnerId, + scopeAuth.fixedPartnerId, + ); + const partnerErr = scopePartnerValidationMessage( + scopeAuth.requireCompanySelection, + effectivePartnerId, + ); + if (partnerErr) { + toast.error(`${rowName}: validation failed`, { description: partnerErr }); + return null; + } + const regionPayload = buildLabelRegionScopePayload(row.regionIds, groups, effectivePartnerId); + if (regionPayload.appliedRegionType === "SPECIFIED" && !regionPayload.regionIds.length) { + toast.error(`${rowName}: validation failed`, { + description: "Select company and applicable region(s).", + }); + return null; + } + const locPayload = buildSpecifiedLocationPayload( + locations, + partners, + groups, + effectivePartnerId, + row.regionIds, + row.locationIds, + ); + if (!locPayload.ok) { + toast.error(`${rowName}: validation failed`, { description: locPayload.message }); + return null; + } + if (selectedTemplate) { + const allowedLocIds = new Set( + locationsForRegionGroups( + locations, + groups, + regionNamesToGroupIds(row.regionIds, groups, effectivePartnerId), + ).map((l) => l.id), + ); + if (!templateAppliesToRegion(selectedTemplate, allowedLocIds)) { + toast.error(`${rowName}: validation failed`, { + description: "The selected template is not available in this row's region.", + }); + return null; + } + } + if (!row.productCategoryId.trim() || !row.productId.trim()) { + toast.error(`${rowName}: validation failed`, { + description: "Select a product category and product.", + }); + return null; + } + if (!row.labelName.trim() || !row.labelCategoryId.trim() || !row.labelTypeId.trim()) { + toast.error(`${rowName}: validation failed`, { + description: "Fill label name, label category, and label type.", + }); + return null; + } + return { + labelName: row.labelName.trim(), + templateCode, + locationIds: locPayload.locationIds, + labelCategoryId: row.labelCategoryId.trim(), + labelTypeId: row.labelTypeId.trim(), + productIds: [row.productId.trim()], + labelInfoJson: null, + state: row.state, + appliedRegionType: regionPayload.appliedRegionType, + regionIds: regionPayload.regionIds, + groupIds: regionPayload.regionIds, + }; + }; + + const saveTemplateDefaultsAfterLabels = async (validRows: BulkAddRow[]) => { + if (!selectedTemplate) return; + const code = templateCode.trim(); + if (!code) return; + const latest = await getLabelTemplate(code); + const dataEls = getDataEntryElements(latest); + const hasNutritionRows = listNutritionElements((latest.elements ?? []) as LabelElement[]).length > 0; + if (dataEls.length === 0 && !hasNutritionRows) return; + + const defaultsMap = buildTemplateDefaultsMap(latest); + for (const row of validRows) { + const productId = row.productId.trim(); + const labelTypeId = row.labelTypeId.trim(); + if (!productId || !labelTypeId) continue; + const product = products.find((x) => x.id === productId); + const labelType = types.find((x) => x.id === labelTypeId); + const productCodeValue = (product?.codeValue ?? "").trim(); + const inputDefaultValues = collectTemplateDefaultValuesForSave( + latest, + row.templateDataValues, + row.templateDateOffsets, + row.nutritionByElementId, + productCodeValue, + { + labelName: row.labelName, + labelTypeName: labelType?.typeName ?? labelType?.typeCode, + }, + ); + defaultsMap.set(`${productId}::${labelTypeId}`, { + productId, + labelTypeId, + defaultValues: { ...inputDefaultValues }, + orderNum: defaultsMap.size + 1, + }); + } + + const mergedDefaults = Array.from(defaultsMap.values()).map((row, idx) => ({ + ...row, + orderNum: idx + 1, + })); + const elements = sortTemplateElementsForDisplay((latest.elements ?? []) as LabelElement[]); + await updateLabelTemplate(code, { + id: latest.id, + name: (latest.name ?? latest.templateName ?? "").trim() || latest.id, + labelType: (latest.labelType ?? "PRICE") as any, + unit: (latest.unit ?? "inch") as any, + width: Number(latest.width ?? 2), + height: Number(latest.height ?? 2), + appliedLocation: appliedLocationToEditor(latest), + showRuler: latest.showRuler ?? true, + showGrid: latest.showGrid ?? true, + state: latest.state ?? true, + elements: labelElementsToApiPayload(elements), + contents: buildTemplateContentsFromElements(elements), + appliedLocationIds: + appliedLocationToEditor(latest) === "ALL" ? [] : (latest.appliedLocationIds ?? []), + templateProductDefaults: mergedDefaults, + }); + }; + + const submit = async () => { + const inputs: LabelCreateInput[] = []; + const validRows: BulkAddRow[] = []; + for (let i = 0; i < rows.length; i += 1) { + const input = validateAndBuildInput(rows[i], i); + if (!input) return; + inputs.push(input); + validRows.push(rows[i]); + } + + setSaving(true); + try { + for (const input of inputs) { + await createLabel(input); + } + try { + await saveTemplateDefaultsAfterLabels(validRows); + } catch (e: any) { + toast.warning("Labels created, template data failed.", { + description: e?.message ? String(e.message) : "Please edit template data manually.", + }); + } + toast.success("Labels created.", { + description: `${inputs.length} label(s) have been created successfully.`, + }); + onBack(); + } catch (e: any) { + toast.error("Failed to create labels.", { + description: e?.message ? String(e.message) : "Please check the rows and try again.", + }); + } finally { + setSaving(false); + } + }; + + return ( +
+
+ +
+
Bulk Add Labels
+
{selectedTemplateLabel}
+ {contextHint ?
{contextHint}
: null} +
+ + +
+ +
+ {loading || bulkTemplateDetailLoading ? ( +
Loading options...
+ ) : ( +
+ + + + # + {scopeAuth.requireCompanySelection ? ( + Company * + ) : null} + Applicable Region * + Product category * + Product * + Label Name * + Location * + Label Category * + Label Type * + {bulkTemplateInputColumns.map((col) => ( + + {col.kind === "element" + ? dataEntryColumnLabel( + col.el, + (selectedTemplate?.elements ?? []) as LabelElement[], + ) + : col.spec.columnLabel} + + ))} + Enabled + Actions + + + + {rows.map((row, index) => { + const effectivePartnerId = effectiveScopePartnerId( + scopeAuth.requireCompanySelection, + row.partnerId, + scopeAuth.fixedPartnerId, + ); + const regionOptions = regionOptionsForPartner(groups, effectivePartnerId); + const groupIds = regionNamesToGroupIds(row.regionIds, groups, effectivePartnerId); + const regionReady = !!(effectivePartnerId && row.regionIds.length && groupIds.length); + const locationsInScope = regionReady + ? locationsForRegionGroups(locations, groups, groupIds) + : []; + const allowedLocIds = new Set(locationsInScope.map((l) => l.id).filter(Boolean)); + const templateAllowed = selectedTemplate + ? templateAppliesToRegion(selectedTemplate, allowedLocIds) + : true; + const productCategoryOptions = productCategories + .filter((c) => productCategoryMatchesRegion(c, allowedLocIds)) + .map((c) => ({ + value: (c.id ?? "").trim(), + label: toDisplay(c.categoryName ?? c.categoryCode ?? c.id), + })) + .filter((o) => o.value); + const productOptions = products + .filter((p) => { + if ((p.categoryId ?? "").trim() !== row.productCategoryId.trim()) return false; + const linkedLocIds = productLocationMap.get(p.id) ?? p.locationIds ?? []; + if (linkedLocIds.length) { + return linkedLocIds.some((lid) => allowedLocIds.has(String(lid).trim())); + } + const productPartnerId = (p.partnerId ?? "").trim(); + if (productPartnerId && productPartnerId !== effectivePartnerId) return false; + const productGroupIds = (p.groupIds ?? []).map((gid) => String(gid).trim()).filter(Boolean); + if (productGroupIds.length) return productGroupIds.some((gid) => groupIds.includes(gid)); + return true; + }) + .map((p) => ({ + value: p.id, + label: toDisplay(p.productName ?? p.productCode ?? p.id), + })); + const locationOptions = locationsInScope.map((loc) => ({ + value: loc.id, + label: toDisplay(loc.locationName ?? loc.locationCode ?? loc.id), + })); + const labelCategoryOptions = categories + .filter((c) => labelCategoryMatchesRegion(c, allowedLocIds)) + .map((c) => ({ + value: c.id, + label: toDisplay(c.categoryName ?? c.categoryCode ?? c.id), + })); + const labelTypeOptions = types + .filter((t) => labelTypeMatchesRegion(t, allowedLocIds)) + .map((t) => ({ + value: t.id, + label: toDisplay(t.typeName ?? t.typeCode ?? t.id), + })); + const gateHint = scopeAuth.requireCompanySelection + ? "Select company and region first" + : "Select region first"; + + return ( + + + {index + 1} + + {scopeAuth.requireCompanySelection ? ( + + updateRowPartner(row.id, v)} + options={companyOptions} + placeholder="Select company" + searchPlaceholder="Search company..." + emptyText="No companies available." + disabled={saving} + /> + + ) : null} + + updateRowRegions(row.id, v)} + options={regionOptions} + placeholder={effectivePartnerId ? "Select region(s)" : "Select company first"} + searchPlaceholder="Search regions..." + selectAllRowLabel="Select All" + emptyText={effectivePartnerId ? "No regions for this company." : "Select company first."} + disabled={saving || !effectivePartnerId} + /> + {!templateAllowed && regionReady ? ( +
Template is not available in this region.
+ ) : null} +
+ + updateRow(row.id, { productCategoryId: v, productId: "" })} + options={productCategoryOptions} + placeholder={regionReady ? "Select category" : gateHint} + searchPlaceholder="Search product category..." + emptyText={regionReady ? "No product categories." : gateHint} + disabled={saving || !regionReady} + /> + + + updateRowProduct(row, v, products)} + options={productOptions} + placeholder={ + regionReady + ? row.productCategoryId.trim() + ? "Select product" + : "Select category first" + : gateHint + } + searchPlaceholder="Search products..." + emptyText={ + regionReady + ? row.productCategoryId.trim() + ? "No products in this category." + : "Select a product category." + : gateHint + } + disabled={saving || !regionReady || !row.productCategoryId.trim()} + /> + + + updateRowLabelName(row, e.target.value)} + placeholder="e.g. Breakfast label" + disabled={saving} + /> + + + updateRow(row.id, { locationIds: v })} + options={locationOptions} + placeholder={regionReady ? "Select location(s)" : gateHint} + searchPlaceholder="Search location..." + selectAllRowLabel="Select All" + emptyText={regionReady ? "No locations in this region." : gateHint} + disabled={saving || !regionReady} + /> + + + updateRow(row.id, { labelCategoryId: v })} + options={labelCategoryOptions} + placeholder={regionReady ? "Select category" : gateHint} + searchPlaceholder="Search category..." + emptyText={regionReady ? "No label categories." : gateHint} + disabled={saving || !regionReady} + /> + + + updateRowLabelType(row, v, types)} + options={labelTypeOptions} + placeholder={regionReady ? "Select type" : gateHint} + searchPlaceholder="Search type..." + emptyText={regionReady ? "No label types." : gateHint} + disabled={saving || !regionReady} + /> + + {bulkTemplateInputColumns.map((col) => { + if (col.kind === "nutrition") { + const value = row.nutritionByElementId[col.parent.id]?.[col.spec.subKey] ?? ""; + return ( + + {col.spec.inputType === "checkbox" ? ( + + updateRowNutritionValue( + row.id, + col.parent.id, + col.spec.subKey, + checked ? "true" : "false", + ) + } + disabled={saving} + /> + ) : ( + + updateRowNutritionValue( + row.id, + col.parent.id, + col.spec.subKey, + e.target.value, + ) + } + placeholder={col.spec.columnLabel} + disabled={saving} + /> + )} + + ); + } + + const el = col.el; + const templateScanLocked = isTemplateSectionBarcodeOrQrElement(el); + const label = dataEntryColumnLabel( + el, + (selectedTemplate?.elements ?? []) as LabelElement[], + ); + return ( + + {templateScanLocked ? ( + + ) : isDateTimeDataEntryField(el) ? ( +
+ + + updateRowTemplateDateOffset(row.id, el.id, { + value: e.target.value, + }) + } + placeholder="Value" + disabled={saving} + /> +
+ ) : ( + updateRowTemplateText(row.id, el.id, e.target.value)} + placeholder={`Enter ${label}`} + disabled={saving} + /> + )} +
+ ); + })} + + updateRow(row.id, { state: checked })} + disabled={saving} + /> + + + + +
+ ); + })} +
+
+
+ )} +
+
+ ); +} + function CreateLabelDialog({ open, onOpenChange, diff --git a/美国版/Food Labeling Management Platform/src/components/shared/category-scope-fields.tsx b/美国版/Food Labeling Management Platform/src/components/shared/category-scope-fields.tsx index 8bf3835..0e153df 100644 --- a/美国版/Food Labeling Management Platform/src/components/shared/category-scope-fields.tsx +++ b/美国版/Food Labeling Management Platform/src/components/shared/category-scope-fields.tsx @@ -7,6 +7,8 @@ import { locationsScopedForCategoryForm, locationsScopedForTemplateScope, regionOptionsForPartner, + filterScopeIdsForPartners, + partnerIdsScopeKey, regionOptionsForPartners, regionSelectionToGroupNames, } from "../../lib/categoryScopeForm"; @@ -159,15 +161,55 @@ export function CategoryScopeFields({ [scopedLocations], ); + const clearRegionAndLocation = useCallback(() => { + onRegionIdsChange?.([]); + onRegionChange([]); + onLocationChange([]); + }, [onRegionIdsChange, onRegionChange, onLocationChange]); + const onCompaniesChange = useCallback( (nextIds: string[]) => { + const prevKey = partnerIdsScopeKey(selectedPartnerIds); + const nextKey = partnerIdsScopeKey(nextIds); onPartnerIdsChange?.(nextIds); - onRegionIdsChange?.([]); - onLocationChange([]); + if (prevKey !== nextKey) { + clearRegionAndLocation(); + } }, - [onPartnerIdsChange, onRegionIdsChange, onLocationChange], + [selectedPartnerIds, onPartnerIdsChange, clearRegionAndLocation], ); + /** 剔除不属于当前 Company 的 Region / Location 选中项(防止 UI 仍显示旧标签) */ + useEffect(() => { + if (!templateScopeMode) return; + const { regionIds, locationIds } = filterScopeIdsForPartners({ + partners, + groups, + locations, + partnerIds: effectivePartnerIds, + regionIds: selectedRegionIds, + locationIds: selectedLocationIds, + }); + const regionChanged = + regionIds.length !== selectedRegionIds.length + || regionIds.some((id, i) => id !== selectedRegionIds[i]); + const locationChanged = + locationIds.length !== selectedLocationIds.length + || locationIds.some((id, i) => id !== selectedLocationIds[i]); + if (regionChanged) onRegionIdsChange?.(regionIds); + if (locationChanged) onLocationChange(locationIds); + }, [ + templateScopeMode, + partners, + groups, + locations, + effectivePartnerIds, + selectedRegionIds, + selectedLocationIds, + onRegionIdsChange, + onLocationChange, + ]); + const onRegionIdsMultiChange = useCallback( (nextRegionIds: string[]) => { onRegionIdsChange?.(nextRegionIds); @@ -192,11 +234,14 @@ export function CategoryScopeFields({ const onCompanyChange = useCallback( (nextId: string) => { + const prev = selectedPartnerId.trim(); + const next = nextId.trim(); onPartnerChange(nextId); - onRegionChange([]); - onLocationChange([]); + if (prev !== next) { + clearRegionAndLocation(); + } }, - [onPartnerChange, onRegionChange, onLocationChange], + [selectedPartnerId, onPartnerChange, clearRegionAndLocation], ); const onRegionMultiChange = useCallback( diff --git a/美国版/Food Labeling Management Platform/src/lib/categoryScopeForm.ts b/美国版/Food Labeling Management Platform/src/lib/categoryScopeForm.ts index d2e41f8..1a60609 100644 --- a/美国版/Food Labeling Management Platform/src/lib/categoryScopeForm.ts +++ b/美国版/Food Labeling Management Platform/src/lib/categoryScopeForm.ts @@ -47,6 +47,43 @@ export function effectiveScopePartnerIds( return pid ? [pid] : []; } +/** 比较 Company 多选是否变化(忽略顺序) */ +export function partnerIdsScopeKey(partnerIds: string[]): string { + return [...new Set(partnerIds.map((x) => x.trim()).filter(Boolean))].sort().join("|"); +} + +/** + * 按当前选中的 Company / Region 过滤 Region、Location Id,剔除已不属于当前公司的旧值。 + */ +export function filterScopeIdsForPartners(input: { + partners: PartnerListItem[]; + groups: GroupListItem[]; + locations: LocationDto[]; + partnerIds: string[]; + regionIds: string[]; + locationIds: string[]; +}): { regionIds: string[]; locationIds: string[] } { + const availablePartnerIds = input.partners + .map((p) => String(p.id ?? "").trim()) + .filter(Boolean); + const effectivePartnerIds = + input.partnerIds.length > 0 ? input.partnerIds : availablePartnerIds; + const availableRegionIdSet = new Set( + regionOptionsForPartners(input.groups, effectivePartnerIds).map((r) => r.value), + ); + const regionIds = input.regionIds.filter((id) => availableRegionIdSet.has(id)); + const scopedLocs = locationsScopedForTemplateScope( + input.locations, + input.partners, + input.groups, + effectivePartnerIds, + regionIds, + ); + const locationIdSet = new Set(scopedLocs.map((l) => l.id)); + const locationIds = input.locationIds.filter((id) => locationIdSet.has(id)); + return { regionIds, locationIds }; +} + export type LabelingScopeSaveBody = { availabilityType: "ALL" | "SPECIFIED"; appliedPartnerType?: AppliedScopeType; @@ -85,6 +122,14 @@ export function buildLabelingScopeSaveBody(input: { const partnerErr = scopePartnersValidationMessage(true, effectivePartnerIds); if (partnerErr) return { ok: false, message: partnerErr }; + const sanitized = filterScopeIdsForPartners({ + partners: input.partners, + groups: input.groups, + locations: input.locations, + partnerIds: effectivePartnerIds, + regionIds: input.selectedRegionIds, + locationIds: input.selectedLocationIds, + }); const partnerIdsForFilter = effectivePartnerIds.length > 0 ? effectivePartnerIds : availablePartnerIds; const availableRegionIds = regionOptionsForPartners(input.groups, partnerIdsForFilter).map( @@ -95,14 +140,14 @@ export function buildLabelingScopeSaveBody(input: { input.partners, input.groups, partnerIdsForFilter, - input.selectedRegionIds, + sanitized.regionIds, ); const availableLocationIds = scopedLocs.map((l) => l.id); const scope = buildLabelTemplateScopePayload({ selectedPartnerIds: effectivePartnerIds, - selectedRegionIds: input.selectedRegionIds, - selectedLocationIds: input.selectedLocationIds, + selectedRegionIds: sanitized.regionIds, + selectedLocationIds: sanitized.locationIds, availablePartnerIds, availableRegionIds, availableLocationIds, @@ -619,12 +664,13 @@ function resolveScopeDimensionForSave( available: string[], ): { type: AppliedScopeType; ids: string[] } { const avail = dedupeIds(available); - const sel = dedupeIds(selected).filter((id) => !avail.length || avail.includes(id)); - if (!avail.length || !sel.length) { + if (!avail.length) { return { type: "ALL", ids: [] }; } - if (sel.length >= avail.length && avail.every((id) => sel.includes(id))) { - return { type: "ALL", ids: [] }; + const sel = dedupeIds(selected).filter((id) => avail.includes(id)); + // 空选或全选当前可选项 → 展开为全部 Id,接口需显式传入 companyIds/regionIds/locationIds + if (!sel.length || (sel.length >= avail.length && avail.every((id) => sel.includes(id)))) { + return { type: "SPECIFIED", ids: avail }; } return { type: "SPECIFIED", ids: sel }; } @@ -669,7 +715,7 @@ export type EntityScopePayloadBody = { /** * 标签类型 / 分类 / 多选项保存:Company + Region + Location 三维适用范围。 - * 空选或全选当前可选项 → 该维度 ALL;部分选中 → SPECIFIED + Id 数组。 + * 空选或全选当前可选项 → 展开为全部 Id;部分选中 → 对应 Id 数组。 */ export function buildEntityPartnerScopePayload(input: { selectedPartnerIds: string[]; @@ -692,14 +738,19 @@ export function buildEntityPartnerScopePayload(input: { input.availableLocationIds, ); - const locationSpecified = - regionDim.type === "SPECIFIED" || locationDim.type === "SPECIFIED"; - const availabilityType: "ALL" | "SPECIFIED" = locationSpecified ? "SPECIFIED" : "ALL"; + const partnerIds = partnerDim.ids; + const regionIds = regionDim.ids; + const locationIds = locationDim.ids; + + const appliedPartnerType: AppliedScopeType = + partnerIds.length > 0 ? "SPECIFIED" : "ALL"; + const availabilityType: "ALL" | "SPECIFIED" = + regionIds.length > 0 || locationIds.length > 0 ? "SPECIFIED" : "ALL"; const anySpecified = - partnerDim.type === "SPECIFIED" || locationSpecified; + appliedPartnerType === "SPECIFIED" || availabilityType === "SPECIFIED"; const effectiveLocationIds = - locationDim.type === "SPECIFIED" ? locationDim.ids : input.availableLocationIds; + locationIds.length > 0 ? locationIds : input.availableLocationIds; if (anySpecified && effectiveLocationIds.length === 0) { return { @@ -708,14 +759,10 @@ export function buildEntityPartnerScopePayload(input: { }; } - const partnerIds = partnerDim.type === "SPECIFIED" ? partnerDim.ids : []; - const regionIds = regionDim.type === "SPECIFIED" ? regionDim.ids : []; - const locationIds = locationDim.type === "SPECIFIED" ? locationDim.ids : []; - return { ok: true, body: { - appliedPartnerType: partnerDim.type, + appliedPartnerType, partnerIds, companyIds: partnerIds, regionIds, @@ -740,18 +787,31 @@ export function buildEntityScopeSaveFromForm(input: { groups: GroupListItem[]; }): { ok: true; body: EntityScopePayloadBody } | { ok: false; message: string } { if (input.requireCompanySelection) { + const effectivePartnerIds = effectiveScopePartnerIds( + true, + input.selectedPartnerIds, + "", + ); + const sanitized = filterScopeIdsForPartners({ + partners: input.partners, + groups: input.groups, + locations: input.locations, + partnerIds: effectivePartnerIds, + regionIds: input.selectedRegionIds, + locationIds: input.selectedLocationIds, + }); const { availablePartnerIds, availableRegionIds, availableLocationIds } = computeTemplateScopeAvailableIds( input.partners, input.groups, input.locations, - input.selectedPartnerIds, - input.selectedRegionIds, + effectivePartnerIds, + sanitized.regionIds, ); return buildEntityPartnerScopePayload({ - selectedPartnerIds: input.selectedPartnerIds, - selectedRegionIds: input.selectedRegionIds, - selectedLocationIds: input.selectedLocationIds, + selectedPartnerIds: effectivePartnerIds, + selectedRegionIds: sanitized.regionIds, + selectedLocationIds: sanitized.locationIds, availablePartnerIds, availableRegionIds, availableLocationIds, diff --git a/美国版/Food Labeling Management Platform/src/lib/labelEntityScopeApi.ts b/美国版/Food Labeling Management Platform/src/lib/labelEntityScopeApi.ts new file mode 100644 index 0000000..ffcc188 --- /dev/null +++ b/美国版/Food Labeling Management Platform/src/lib/labelEntityScopeApi.ts @@ -0,0 +1,124 @@ +/** 解析接口返回的 Company Id 列表(优先 companyIds) */ +export function parseCompanyIdsFromApi(raw: Record): string[] { + const parse = (v: unknown): string[] => { + if (!Array.isArray(v)) return []; + return [...new Set(v.map((x) => String(x).trim()).filter(Boolean))]; + }; + const fromCompany = parse(raw.companyIds ?? raw.CompanyIds); + if (fromCompany.length) return fromCompany; + return parse(raw.partnerIds ?? raw.PartnerIds); +} + +export type LabelEntityScopeInput = { + appliedPartnerType?: string | null; + partnerIds?: string[] | null; + companyIds?: string[] | null; + availabilityType?: string | null; + regionIds?: string[] | null; + groupIds?: string[] | null; + locationIds?: string[] | null; +}; + +/** + * 分类 / 类型 / 多选项 保存:公司范围以 companyIds 数组为主字段,partnerIds 同步兼容。 + */ +export function buildLabelEntityScopeApiBody(input: LabelEntityScopeInput): Record { + const companyIds = [ + ...new Set( + [...(input.companyIds ?? []), ...(input.partnerIds ?? [])] + .map((x) => String(x).trim()) + .filter(Boolean), + ), + ]; + const groupIds = [ + ...new Set( + [...(input.groupIds ?? []), ...(input.regionIds ?? [])] + .map((x) => String(x).trim()) + .filter(Boolean), + ), + ]; + const locationIds = [ + ...new Set((input.locationIds ?? []).map((x) => String(x).trim()).filter(Boolean)), + ]; + + const appliedPartnerTypeRaw = String(input.appliedPartnerType ?? "").trim().toUpperCase(); + const appliedPartnerType = + appliedPartnerTypeRaw === "ALL" || appliedPartnerTypeRaw === "SPECIFIED" + ? appliedPartnerTypeRaw + : companyIds.length + ? "SPECIFIED" + : "ALL"; + + const body: Record = { + appliedPartnerType, + companyIds, + partnerIds: companyIds, + }; + + const availabilityTypeRaw = String(input.availabilityType ?? "ALL").trim().toUpperCase(); + body.availabilityType = + availabilityTypeRaw === "SPECIFIED" || groupIds.length > 0 || locationIds.length > 0 + ? "SPECIFIED" + : "ALL"; + + body.groupIds = groupIds; + body.regionIds = groupIds; + body.locationIds = locationIds; + + return body; +} + +export type LabelTemplateScopeInput = LabelEntityScopeInput & { + appliedRegionType?: string | null; + appliedLocation?: string | null; + appliedLocationIds?: string[] | null; +}; + +/** 标签模板保存:Company / Region / Location 三维 + companyIds 数组 */ +export function buildLabelTemplateScopeApiBody( + input: LabelTemplateScopeInput, +): Record { + const companyIds = [ + ...new Set( + [...(input.companyIds ?? []), ...(input.partnerIds ?? [])] + .map((x) => String(x).trim()) + .filter(Boolean), + ), + ]; + const regionIds = [ + ...new Set( + [...(input.regionIds ?? []), ...(input.groupIds ?? [])] + .map((x) => String(x).trim()) + .filter(Boolean), + ), + ]; + const locationIds = [ + ...new Set( + [...(input.locationIds ?? []), ...(input.appliedLocationIds ?? [])] + .map((x) => String(x).trim()) + .filter(Boolean), + ), + ]; + + const appliedPartnerType = + String(input.appliedPartnerType ?? "").trim().toUpperCase() + || (companyIds.length ? "SPECIFIED" : "ALL"); + const appliedRegionType = + String(input.appliedRegionType ?? "").trim().toUpperCase() + || (regionIds.length ? "SPECIFIED" : "ALL"); + const appliedLocation = + String(input.appliedLocation ?? "").trim().toUpperCase() + || (locationIds.length ? "SPECIFIED" : "ALL"); + + return { + appliedPartnerType, + companyIds, + partnerIds: companyIds, + appliedRegionType, + regionIds, + groupIds: regionIds, + appliedLocation, + locationIds, + appliedLocationIds: locationIds, + }; +} diff --git a/美国版/Food Labeling Management Platform/src/services/labelCategoryService.ts b/美国版/Food Labeling Management Platform/src/services/labelCategoryService.ts index 6c6dbfd..64149d2 100644 --- a/美国版/Food Labeling Management Platform/src/services/labelCategoryService.ts +++ b/美国版/Food Labeling Management Platform/src/services/labelCategoryService.ts @@ -1,5 +1,9 @@ import { createApiClient } from "../lib/apiClient"; import { serializeButtonAppearanceForApi } from "../lib/categoryButtonAppearance"; +import { + buildLabelEntityScopeApiBody, + parseCompanyIdsFromApi, +} from "../lib/labelEntityScopeApi"; import type { LabelCategoryCreateInput, LabelCategoryDto, @@ -28,7 +32,8 @@ function normalizeLabelCategoryDto(raw: unknown): LabelCategoryDto { }; const groupIds = parseIds(r.groupIds ?? r.GroupIds ?? r.regionIds ?? r.RegionIds); const locationIds = parseIds(r.locationIds ?? r.LocationIds); - const partnerIds = parseIds(r.partnerIds ?? r.PartnerIds ?? r.companyIds ?? r.CompanyIds); + const companyIds = parseCompanyIdsFromApi(r); + const partnerIds = companyIds; const noRaw = r.noOfLabels ?? r.NoOfLabels; const noOfLabels = typeof noRaw === "number" && Number.isFinite(noRaw) @@ -49,7 +54,7 @@ function normalizeLabelCategoryDto(raw: unknown): LabelCategoryDto { id: String(r.id ?? r.Id ?? ""), appliedPartnerType: String(r.appliedPartnerType ?? r.AppliedPartnerType ?? "").trim() || undefined, partnerIds, - companyIds: partnerIds, + companyIds, availabilityType: String(r.availabilityType ?? r.AvailabilityType ?? "").trim() || undefined, groupIds, regionIds: groupIds, @@ -61,42 +66,7 @@ function normalizeLabelCategoryDto(raw: unknown): LabelCategoryDto { } function scopeBodyFromInput(input: LabelCategoryCreateInput): Record { - const groupIds = [ - ...new Set( - [...(input.groupIds ?? []), ...(input.regionIds ?? [])] - .map((x) => String(x).trim()) - .filter(Boolean), - ), - ]; - const locationIds = [ - ...new Set((input.locationIds ?? []).map((x) => String(x).trim()).filter(Boolean)), - ]; - const partnerIds = [ - ...new Set( - [...(input.partnerIds ?? []), ...(input.companyIds ?? [])] - .map((x) => String(x).trim()) - .filter(Boolean), - ), - ]; - const body: Record = {}; - const appliedPartnerType = String(input.appliedPartnerType ?? "").trim().toUpperCase(); - if (appliedPartnerType === "ALL" || appliedPartnerType === "SPECIFIED") { - body.appliedPartnerType = appliedPartnerType; - } - if (partnerIds.length) { - body.partnerIds = partnerIds; - body.companyIds = partnerIds; - } - const availabilityType = String(input.availabilityType ?? "ALL").trim().toUpperCase() || "ALL"; - body.availabilityType = availabilityType; - if (groupIds.length) { - body.groupIds = groupIds; - body.regionIds = groupIds; - } - if (locationIds.length) { - body.locationIds = locationIds; - } - return body; + return buildLabelEntityScopeApiBody(input); } export async function getLabelCategories(input: LabelCategoryGetListInput, signal?: AbortSignal): Promise> { diff --git a/美国版/Food Labeling Management Platform/src/services/labelMultipleOptionService.ts b/美国版/Food Labeling Management Platform/src/services/labelMultipleOptionService.ts index 15da9ad..39b0a28 100644 --- a/美国版/Food Labeling Management Platform/src/services/labelMultipleOptionService.ts +++ b/美国版/Food Labeling Management Platform/src/services/labelMultipleOptionService.ts @@ -1,4 +1,8 @@ import { createApiClient } from "../lib/apiClient"; +import { + buildLabelEntityScopeApiBody, + parseCompanyIdsFromApi, +} from "../lib/labelEntityScopeApi"; import type { LabelMultipleOptionCreateInput, LabelMultipleOptionDto, @@ -63,12 +67,8 @@ function normalizeLabelMultipleOptionDto(item: LabelMultipleOptionDto): LabelMul const locationIds = parseIds( (raw as Record).locationIds ?? (raw as Record).LocationIds, ); - const partnerIds = parseIds( - (raw as Record).partnerIds ?? - (raw as Record).PartnerIds ?? - (raw as Record).companyIds ?? - (raw as Record).CompanyIds, - ); + const partnerIds = parseCompanyIdsFromApi(raw as Record); + const companyIds = partnerIds; const companyRaw = (raw as Record).company ?? (raw as Record).Company; return { ...item, @@ -81,7 +81,7 @@ function normalizeLabelMultipleOptionDto(item: LabelMultipleOptionDto): LabelMul "", ).trim() || undefined, partnerIds, - companyIds: partnerIds, + companyIds, availabilityType: String( (raw as Record).availabilityType ?? @@ -108,44 +108,7 @@ function optionValuesJsonToApiBody(values: string[]): string { } function scopeBodyFromInput(input: LabelMultipleOptionCreateInput): Record { - const groupIds = [ - ...new Set( - [...(input.groupIds ?? []), ...(input.regionIds ?? [])] - .map((x) => String(x).trim()) - .filter(Boolean), - ), - ]; - const locationIds = [ - ...new Set((input.locationIds ?? []).map((x) => String(x).trim()).filter(Boolean)), - ]; - const partnerIds = [ - ...new Set( - [...(input.partnerIds ?? []), ...(input.companyIds ?? [])] - .map((x) => String(x).trim()) - .filter(Boolean), - ), - ]; - const body: Record = {}; - const appliedPartnerType = String(input.appliedPartnerType ?? "").trim().toUpperCase(); - if (appliedPartnerType === "ALL" || appliedPartnerType === "SPECIFIED") { - body.appliedPartnerType = appliedPartnerType; - } - if (partnerIds.length) { - body.partnerIds = partnerIds; - body.companyIds = partnerIds; - } - const availabilityType = String(input.availabilityType ?? "").trim().toUpperCase(); - if (availabilityType === "ALL" || availabilityType === "SPECIFIED") { - body.availabilityType = availabilityType; - } - if (groupIds.length) { - body.groupIds = groupIds; - body.regionIds = groupIds; - } - if (locationIds.length) { - body.locationIds = locationIds; - } - return body; + return buildLabelEntityScopeApiBody(input); } export async function getLabelMultipleOptions(input: LabelMultipleOptionGetListInput, signal?: AbortSignal): Promise> { diff --git a/美国版/Food Labeling Management Platform/src/services/labelTemplateService.ts b/美国版/Food Labeling Management Platform/src/services/labelTemplateService.ts index d7eecde..41e0760 100644 --- a/美国版/Food Labeling Management Platform/src/services/labelTemplateService.ts +++ b/美国版/Food Labeling Management Platform/src/services/labelTemplateService.ts @@ -1,5 +1,9 @@ import { createApiClient } from "../lib/apiClient"; import { + buildLabelTemplateScopeApiBody, + parseCompanyIdsFromApi, +} from "../lib/labelEntityScopeApi"; +import { stripLabelConfigPrefixes, normalizeTemplateBorder, normalizePrintOrientation, @@ -166,12 +170,13 @@ function normalizeLabelTemplateDto(raw: unknown): LabelTemplateDto { const regionIds = parseIdList(r.regionIds ?? r.RegionIds); const groupIds = parseIdList(r.groupIds ?? r.GroupIds); const locationIds = parseIdList(r.locationIds ?? r.LocationIds); - const partnerIds = parseIdList(r.partnerIds ?? r.PartnerIds ?? r.companyIds ?? r.CompanyIds); + const partnerIds = parseCompanyIdsFromApi(r); + const mergedPartnerIds = partnerIds; + const companyIds = partnerIds; const mergedRegionIds = [...new Set([...regionIds, ...groupIds])]; const mergedLocationIds = [ ...new Set([...locationIds, ...appliedLocationIds]), ]; - const mergedPartnerIds = partnerIds; const appliedPartnerTypeRaw = r.appliedPartnerType ?? r.AppliedPartnerType; const appliedRegionTypeRaw = r.appliedRegionType ?? r.AppliedRegionType; const appliedLocationTypeRaw = @@ -230,7 +235,7 @@ function normalizeLabelTemplateDto(raw: unknown): LabelTemplateDto { lastEdited: (typeof lastEditedVo === "string" ? lastEditedVo : null) ?? (r.lastEdited as string | null), appliedLocationIds: mergedLocationIds.length ? mergedLocationIds : appliedLocationIds, partnerIds: mergedPartnerIds, - companyIds: mergedPartnerIds, + companyIds, regionIds: mergedRegionIds, groupIds: mergedRegionIds, locationIds: mergedLocationIds, @@ -274,31 +279,7 @@ export async function getLabelTemplate(templateCode: string, signal?: AbortSigna } function buildLabelTemplateScopeBody(input: LabelTemplateCreateInput): Record { - const partnerIds = [ - ...new Set( - [...(input.partnerIds ?? []), ...(input.companyIds ?? [])] - .map((x) => String(x).trim()) - .filter(Boolean), - ), - ]; - const regionIds = [ - ...new Set( - [...(input.regionIds ?? []), ...(input.groupIds ?? [])] - .map((x) => String(x).trim()) - .filter(Boolean), - ), - ]; - const locationIds = [ - ...new Set( - [...(input.locationIds ?? []), ...(input.appliedLocationIds ?? [])] - .map((x) => String(x).trim()) - .filter(Boolean), - ), - ]; - const appliedPartnerType = String(input.appliedPartnerType ?? "").trim().toUpperCase() || (partnerIds.length ? "SPECIFIED" : "ALL"); - const appliedRegionType = String(input.appliedRegionType ?? "").trim().toUpperCase() || (regionIds.length ? "SPECIFIED" : "ALL"); - const appliedLocation = String(input.appliedLocation ?? "").trim().toUpperCase() || (locationIds.length ? "SPECIFIED" : "ALL"); - + const scope = buildLabelTemplateScopeApiBody(input); const body: Record = { id: input.id, name: input.name, @@ -306,9 +287,7 @@ function buildLabelTemplateScopeBody(input: LabelTemplateCreateInput): Record { - const groupIds = [ - ...new Set( - [...(input.groupIds ?? []), ...(input.regionIds ?? [])] - .map((x) => String(x).trim()) - .filter(Boolean), - ), - ]; - const locationIds = [ - ...new Set((input.locationIds ?? []).map((x) => String(x).trim()).filter(Boolean)), - ]; - const partnerIds = [ - ...new Set( - [...(input.partnerIds ?? []), ...(input.companyIds ?? [])] - .map((x) => String(x).trim()) - .filter(Boolean), - ), - ]; - const body: Record = {}; - const appliedPartnerType = String(input.appliedPartnerType ?? "").trim().toUpperCase(); - if (appliedPartnerType === "ALL" || appliedPartnerType === "SPECIFIED") { - body.appliedPartnerType = appliedPartnerType; - } - if (partnerIds.length) { - body.partnerIds = partnerIds; - body.companyIds = partnerIds; - } - const availabilityType = String(input.availabilityType ?? "").trim().toUpperCase(); - if (availabilityType === "ALL" || availabilityType === "SPECIFIED") { - body.availabilityType = availabilityType; - } - if (groupIds.length) { - body.groupIds = groupIds; - body.regionIds = groupIds; - } - if (locationIds.length) { - body.locationIds = locationIds; - } - return body; + return buildLabelEntityScopeApiBody(input); } export async function getLabelTypes(input: LabelTypeGetListInput, signal?: AbortSignal): Promise> { diff --git a/美国版/Food Labeling Management Platform/src/types/labelTemplate.ts b/美国版/Food Labeling Management Platform/src/types/labelTemplate.ts index 8f4a768..74efde3 100644 --- a/美国版/Food Labeling Management Platform/src/types/labelTemplate.ts +++ b/美国版/Food Labeling Management Platform/src/types/labelTemplate.ts @@ -1025,19 +1025,20 @@ function resolveScopeDimensionForSave( available: string[], ): { type: AppliedScopeType; ids: string[] } { const avail = dedupeIdList(available); - const sel = dedupeIdList(selected).filter((id) => !avail.length || avail.includes(id)); - if (!avail.length || !sel.length) { + if (!avail.length) { return { type: 'ALL', ids: [] }; } - if (sel.length >= avail.length && avail.every((id) => sel.includes(id))) { - return { type: 'ALL', ids: [] }; + const sel = dedupeIdList(selected).filter((id) => avail.includes(id)); + // 空选或全选当前可选项 → 展开为全部 Id + if (!sel.length || (sel.length >= avail.length && avail.every((id) => sel.includes(id)))) { + return { type: 'SPECIFIED', ids: avail }; } return { type: 'SPECIFIED', ids: sel }; } /** * 6-4:模板保存 Body 中的 Company / Region / Location 三维适用范围。 - * 空选或全选当前可选项 → 该维度 ALL + 空数组;部分选中 → SPECIFIED + Id 数组。 + * 空选或全选当前可选项 → 展开为全部 Id;部分选中 → 对应 Id 数组。 */ export function buildLabelTemplateScopePayload(input: { selectedPartnerIds: string[]; @@ -1060,12 +1061,23 @@ export function buildLabelTemplateScopePayload(input: { input.availableLocationIds, ); + const partnerIds = partnerDim.ids; + const regionIds = regionDim.ids; + const locationIds = locationDim.ids; + + const appliedPartnerType: AppliedScopeType = + partnerIds.length > 0 ? 'SPECIFIED' : 'ALL'; + const appliedRegionType: AppliedScopeType = + regionIds.length > 0 ? 'SPECIFIED' : 'ALL'; + const appliedLocation: AppliedLocation = + locationIds.length > 0 ? 'SPECIFIED' : 'ALL'; + const anySpecified = - partnerDim.type === 'SPECIFIED' - || regionDim.type === 'SPECIFIED' - || locationDim.type === 'SPECIFIED'; + appliedPartnerType === 'SPECIFIED' + || appliedRegionType === 'SPECIFIED' + || appliedLocation === 'SPECIFIED'; const effectiveLocationIds = - locationDim.type === 'SPECIFIED' ? locationDim.ids : input.availableLocationIds; + locationIds.length > 0 ? locationIds : input.availableLocationIds; if (anySpecified && effectiveLocationIds.length === 0) { return { @@ -1074,20 +1086,16 @@ export function buildLabelTemplateScopePayload(input: { }; } - const partnerIds = partnerDim.type === 'SPECIFIED' ? partnerDim.ids : []; - const regionIds = regionDim.type === 'SPECIFIED' ? regionDim.ids : []; - const locationIds = locationDim.type === 'SPECIFIED' ? locationDim.ids : []; - return { ok: true, body: { - appliedPartnerType: partnerDim.type, + appliedPartnerType, partnerIds, companyIds: partnerIds, - appliedRegionType: regionDim.type, + appliedRegionType, regionIds, groupIds: regionIds, - appliedLocation: locationDim.type, + appliedLocation, locationIds, appliedLocationIds: locationIds, }, -- libgit2 0.21.4