Commit 3b969879b6b34a5e6b2c357472b20ddcb1156de2

Authored by 杨鑫
1 parent ff0f4ef5

修改bug

美国版/Food Labeling Management App UniApp/src/pages/labels/preview.vue
@@ -1446,6 +1446,29 @@ async function loadPreview() { @@ -1446,6 +1446,29 @@ async function loadPreview() {
1446 } 1446 }
1447 return '' 1447 return ''
1448 } 1448 }
  1449 + const readTemplateName = (...sources: Array<unknown>): string => {
  1450 + for (const source of sources) {
  1451 + if (source == null || typeof source !== 'object' || Array.isArray(source)) continue
  1452 + const obj = source as Record<string, unknown>
  1453 + const direct =
  1454 + obj.name ??
  1455 + obj.Name ??
  1456 + obj.templateName ??
  1457 + obj.TemplateName
  1458 + if (direct != null && String(direct).trim()) return String(direct).trim()
  1459 + const nestedTemplate = obj.template ?? obj.Template
  1460 + if (nestedTemplate != null && typeof nestedTemplate === 'object' && !Array.isArray(nestedTemplate)) {
  1461 + const t = nestedTemplate as Record<string, unknown>
  1462 + const nestedName =
  1463 + t.name ??
  1464 + t.Name ??
  1465 + t.templateName ??
  1466 + t.TemplateName
  1467 + if (nestedName != null && String(nestedName).trim()) return String(nestedName).trim()
  1468 + }
  1469 + }
  1470 + return ''
  1471 + }
1449 1472
1450 const leStr = readLastEdited(root) || readLastEdited(inner) 1473 const leStr = readLastEdited(root) || readLastEdited(inner)
1451 lastEdited.value = leStr || '—' 1474 lastEdited.value = leStr || '—'
@@ -1468,6 +1491,10 @@ async function loadPreview() { @@ -1468,6 +1491,10 @@ async function loadPreview() {
1468 previewLoading.value = false 1491 previewLoading.value = false
1469 return 1492 return
1470 } 1493 }
  1494 + const templateNameFromApi = readTemplateName(inner, root, tmplRaw)
  1495 + if (templateNameFromApi) {
  1496 + templateName.value = templateNameFromApi
  1497 + }
1471 const lstRaw = 1498 const lstRaw =
1472 root.labelSizeText ?? 1499 root.labelSizeText ??
1473 root.LabelSizeText ?? 1500 root.LabelSizeText ??
@@ -1717,13 +1744,8 @@ const handlePrint = async () =&gt; { @@ -1717,13 +1744,8 @@ const handlePrint = async () =&gt; {
1717 */ 1744 */
1718 const tmplForNativeJob = normalizeTemplateForNativeFastJob(tmpl, printInputJson as any, printBaseTime) 1745 const tmplForNativeJob = normalizeTemplateForNativeFastJob(tmpl, printInputJson as any, printBaseTime)
1719 const printSummary = getCurrentPrinterSummary() 1746 const printSummary = getCurrentPrinterSummary()
1720 - const printConn = getBluetoothConnection()  
1721 - const isVirtualBtActive =  
1722 - printSummary.type === 'bluetooth'  
1723 - && isVirtualBtPrinterDeviceName(printConn?.deviceName)  
1724 const mustUseCanvasRasterPrint = 1747 const mustUseCanvasRasterPrint =
1725 printSummary.type === 'builtin' 1748 printSummary.type === 'builtin'
1726 - || isVirtualBtActive  
1727 || templateRequiresCanvasStyleFidelity(tmpl) 1749 || templateRequiresCanvasStyleFidelity(tmpl)
1728 || templateHasDateTimeElements(tmpl) 1750 || templateHasDateTimeElements(tmpl)
1729 const currentDriver = getCurrentPrinterDriver() 1751 const currentDriver = getCurrentPrinterDriver()
美国版/Food Labeling Management App UniApp/src/utils/print/manager/printerManager.ts
@@ -860,6 +860,7 @@ export async function printImageForCurrentPrinter ( @@ -860,6 +860,7 @@ export async function printImageForCurrentPrinter (
860 } 860 }
861 } else { 861 } else {
862 try { 862 try {
  863 + const sendStageMs = isVirtualBtBluetoothConnection() ? 600000 : 180000
863 await withStageTimeout( 864 await withStageTimeout(
864 sendToPrinter(data, (p) => { 865 sendToPrinter(data, (p) => {
865 lastExternalProgressAt = Date.now() 866 lastExternalProgressAt = Date.now()
@@ -868,7 +869,7 @@ export async function printImageForCurrentPrinter ( @@ -868,7 +869,7 @@ export async function printImageForCurrentPrinter (
868 printRunDiag('printImage_send_progress', { p }) 869 printRunDiag('printImage_send_progress', { p })
869 } 870 }
870 }), 871 }),
871 - 180000, 872 + sendStageMs,
872 'sendToPrinter' 873 'sendToPrinter'
873 ) 874 )
874 } finally { 875 } finally {
@@ -897,11 +898,36 @@ export async function printImageDataForCurrentPrinter ( @@ -897,11 +898,36 @@ export async function printImageDataForCurrentPrinter (
897 const rasterDriver = resolveRasterPrintDriver(driver) 898 const rasterDriver = resolveRasterPrintDriver(driver)
898 let raster = rasterizeImageData(imageData, options) 899 let raster = rasterizeImageData(imageData, options)
899 raster = finalizeRasterForPrint(raster, rasterDriver.protocol, options) 900 raster = finalizeRasterForPrint(raster, rasterDriver.protocol, options)
900 - if (onProgress) onProgress(5) 901 + if (onProgress) onProgress(18)
901 const data = rasterDriver.protocol === 'esc' 902 const data = rasterDriver.protocol === 'esc'
902 ? buildEscPosImageData(raster, options) 903 ? buildEscPosImageData(raster, options)
903 : buildTscImageData(raster, options, rasterDriver.imageDpi || 203) 904 : buildTscImageData(raster, options, rasterDriver.imageDpi || 203)
904 - await sendToPrinter(data, onProgress) 905 + let sendVisual = 22
  906 + let lastExternalAt = Date.now()
  907 + const reportSend = (p: number) => {
  908 + if (!onProgress) return
  909 + const mapped = 22 + Math.round((Math.min(100, Math.max(0, p)) / 100) * 78)
  910 + if (mapped > sendVisual) {
  911 + sendVisual = mapped
  912 + onProgress(sendVisual)
  913 + } else {
  914 + lastExternalAt = Date.now()
  915 + }
  916 + }
  917 + const keepAlive = onProgress
  918 + ? setInterval(() => {
  919 + if (Date.now() - lastExternalAt < 1200) return
  920 + if (sendVisual >= 96) return
  921 + sendVisual += sendVisual < 80 ? 2 : 1
  922 + onProgress(sendVisual)
  923 + }, 800)
  924 + : null
  925 + try {
  926 + await sendToPrinter(data, reportSend)
  927 + } finally {
  928 + if (keepAlive) clearInterval(keepAlive)
  929 + }
  930 + if (onProgress) onProgress(100)
905 return driver 931 return driver
906 } 932 }
907 933
美国版/Food Labeling Management App UniApp/src/utils/print/printerConnection.ts
@@ -595,15 +595,12 @@ export function resolvePrintSendChannelHint (): string { @@ -595,15 +595,12 @@ export function resolvePrintSendChannelHint (): string {
595 const conn = getBluetoothConnection() 595 const conn = getBluetoothConnection()
596 const uposSupported = isNativeUposPrintSupported() 596 const uposSupported = isNativeUposPrintSupported()
597 const uposPrefer = getUposOptionsFromStorage().prefer || 'builtin' 597 const uposPrefer = getUposOptionsFromStorage().prefer || 'builtin'
598 - if (virtualBt && isD320faxAioDevice()) { 598 + if (virtualBt) {
599 if (conn?.transportMode === 'native-plugin' && isNativePrintCommandBytesSupported()) { 599 if (conn?.transportMode === 'native-plugin' && isNativePrintCommandBytesSupported()) {
600 return 'Gprinter SDK TSC (Virtual BT)' 600 return 'Gprinter SDK TSC (Virtual BT)'
601 } 601 }
602 return 'Bluetooth classic TSC (Virtual BT)' 602 return 'Bluetooth classic TSC (Virtual BT)'
603 } 603 }
604 - if (virtualBt && uposSupported && !isD320faxAioDevice()) {  
605 - return `UPOS/${uposPrefer} (Virtual BT redirect)`  
606 - }  
607 if (type === 'builtin') { 604 if (type === 'builtin') {
608 if (uposSupported) return `UPOS/${uposPrefer}` 605 if (uposSupported) return `UPOS/${uposPrefer}`
609 if (isBuiltinPrinterAvailable()) return 'TCP localhost' 606 if (isBuiltinPrinterAvailable()) return 'TCP localhost'
@@ -633,16 +630,14 @@ export function preferBuiltinPrinterOnAioDevice (): boolean { @@ -633,16 +630,14 @@ export function preferBuiltinPrinterOnAioDevice (): boolean {
633 restoreD320faxVirtualBtBluetoothMode() 630 restoreD320faxVirtualBtBluetoothMode()
634 631
635 if (getPrinterType() === 'builtin') { 632 if (getPrinterType() === 'builtin') {
636 - if (isD320faxAioDevice() && isVirtualBtBluetoothConnection()) return false 633 + if (isVirtualBtBluetoothConnection()) return false
637 return true 634 return true
638 } 635 }
639 if (!isAioBuiltinPrintCapable()) return false 636 if (!isAioBuiltinPrintCapable()) return false
640 637
641 - /** D320FAX:佳博 SDK + Virtual BT + TSC 光栅,保持 bluetooth 模式 */ 638 + /** 一体机已连 Virtual BT:保持 Bluetooth + 佳博 TSC,勿切 Built-in/UPOS */
642 if (isVirtualBtBluetoothConnection()) { 639 if (isVirtualBtBluetoothConnection()) {
643 - if (isD320faxAioDevice()) return false  
644 - setBuiltinPrinter(getCurrentPrinterDriverKey() || 'generic-tsc')  
645 - return true 640 + return false
646 } 641 }
647 642
648 if (!isBuiltinPrinterEnabledByDeviceModel()) return false 643 if (!isBuiltinPrinterEnabledByDeviceModel()) return false
@@ -694,17 +689,9 @@ export function sendToPrinter ( @@ -694,17 +689,9 @@ export function sendToPrinter (
694 const type = getPrinterType() 689 const type = getPrinterType()
695 printRunDiag('sendToPrinter', { type, dataBytes: data?.length || 0 }) 690 printRunDiag('sendToPrinter', { type, dataBytes: data?.length || 0 })
696 691
697 - /** D320FAX Virtual BT:佳博 SDK 为 TSC 模式,禁止走 UPOS(串口全失败) */  
698 - if (isVirtualBtBluetoothConnection() && isD320faxAioDevice()) {  
699 - return sendViaD320faxVirtualBt(data, onProgress)  
700 - }  
701 -  
702 - /** rk3568 等 UPOS 可用机型:Virtual BT 光栅改走 UPOS 内置物理通道 */  
703 - if (isVirtualBtBluetoothConnection() && isNativeUposPrintSupported()) {  
704 - printRunDiag('sendToPrinter_virtual_bt_upos_redirect', { dataBytes: data?.length || 0 })  
705 - return sendViaBuiltin(data).then(() => {  
706 - if (onProgress) onProgress(100)  
707 - }) 692 + /** Virtual BT:TSC 光栅必须走佳博 SDK / 经典蓝牙 SPP,禁止误投 UPOS(TSC 字节 UPOS 不认会卡死) */
  693 + if (isVirtualBtBluetoothConnection()) {
  694 + return sendViaVirtualBtTsc(data, onProgress)
708 } 695 }
709 696
710 if (type === 'bluetooth') { 697 if (type === 'bluetooth') {
@@ -1142,23 +1129,49 @@ function numberArrayToBase64 (data: number[]): string { @@ -1142,23 +1129,49 @@ function numberArrayToBase64 (data: number[]): string {
1142 } 1129 }
1143 1130
1144 /** 1131 /**
1145 - * D320FAX + Virtual BT:Canvas 光栅 → TSC 指令 → 佳博 SDK printCommandBytes。 1132 + * Virtual BT(含 D320FAX / AOA 一体机):Canvas 光栅 TSC 指令 → 佳博 SDK printCommandBytes 或经典蓝牙 SPP。
1146 */ 1133 */
1147 -async function sendViaD320faxVirtualBt ( 1134 +async function sendViaVirtualBtTsc (
1148 data: number[], 1135 data: number[],
1149 onProgress?: (percent: number) => void, 1136 onProgress?: (percent: number) => void,
1150 ): Promise<void> { 1137 ): Promise<void> {
1151 - printRunDiag('sendToPrinter_d320fax_virtual_bt', { dataBytes: data?.length || 0 }) 1138 + printRunDiag('sendToPrinter_virtual_bt_tsc', { dataBytes: data?.length || 0 })
1152 await ensureNativeClassicTransportIfPossible() 1139 await ensureNativeClassicTransportIfPossible()
1153 const conn = getBluetoothConnection() 1140 const conn = getBluetoothConnection()
1154 if (conn?.transportMode === 'native-plugin' && isNativePrintCommandBytesSupported()) { 1141 if (conn?.transportMode === 'native-plugin' && isNativePrintCommandBytesSupported()) {
1155 - return sendViaNativeClassicPlugin(data, onProgress) 1142 + const nativeWaitMs = Math.min(
  1143 + 600000,
  1144 + Math.max(60000, estimateClassicSendTimeoutMs(data.length)),
  1145 + )
  1146 + try {
  1147 + await sendViaNativeClassicPlugin(data, onProgress, { writeTimeoutMs: nativeWaitMs })
  1148 + return
  1149 + } catch (e) {
  1150 + printRunDiag('virtual_bt_native_bytes_fallback_js', {
  1151 + err: String((e as Error)?.message || e),
  1152 + dataBytes: data.length,
  1153 + })
  1154 + try {
  1155 + if (classicBluetooth?.ensureConnection) {
  1156 + classicBluetooth.ensureConnection(conn.deviceId)
  1157 + }
  1158 + } catch (_) {}
  1159 + return sendViaClassic(data, onProgress)
  1160 + }
1156 } 1161 }
1157 if (conn?.deviceType === 'classic') { 1162 if (conn?.deviceType === 'classic') {
1158 - printRunDiag('sendToPrinter_d320fax_classic_js', { dataBytes: data?.length || 0 }) 1163 + printRunDiag('sendToPrinter_virtual_bt_classic_js', { dataBytes: data?.length || 0 })
1159 return sendViaClassic(data, onProgress) 1164 return sendViaClassic(data, onProgress)
1160 } 1165 }
1161 - return Promise.reject(new Error('D320FAX Virtual BT printer not connected.')) 1166 + return Promise.reject(new Error('Virtual BT printer not connected.'))
  1167 +}
  1168 +
  1169 +/** @deprecated 使用 sendViaVirtualBtTsc;保留别名兼容旧诊断关键字 */
  1170 +async function sendViaD320faxVirtualBt (
  1171 + data: number[],
  1172 + onProgress?: (percent: number) => void,
  1173 +): Promise<void> {
  1174 + return sendViaVirtualBtTsc(data, onProgress)
1162 } 1175 }
1163 1176
1164 /** 1177 /**
@@ -1166,7 +1179,8 @@ async function sendViaD320faxVirtualBt ( @@ -1166,7 +1179,8 @@ async function sendViaD320faxVirtualBt (
1166 */ 1179 */
1167 function sendViaNativeClassicPlugin ( 1180 function sendViaNativeClassicPlugin (
1168 data: number[], 1181 data: number[],
1169 - onProgress?: (percent: number) => void 1182 + onProgress?: (percent: number) => void,
  1183 + options: { writeTimeoutMs?: number } = {},
1170 ): Promise<void> { 1184 ): Promise<void> {
1171 const conn = getBluetoothConnection() 1185 const conn = getBluetoothConnection()
1172 if (!conn || conn.deviceType !== 'classic' || conn.transportMode !== 'native-plugin') { 1186 if (!conn || conn.deviceType !== 'classic' || conn.transportMode !== 'native-plugin') {
@@ -1179,23 +1193,40 @@ function sendViaNativeClassicPlugin ( @@ -1179,23 +1193,40 @@ function sendViaNativeClassicPlugin (
1179 if (!base64) { 1193 if (!base64) {
1180 return Promise.reject(new Error('BASE64_ENCODE_FAILED')) 1194 return Promise.reject(new Error('BASE64_ENCODE_FAILED'))
1181 } 1195 }
1182 - const writeTimeoutMs = Math.min(600000, Math.max(45000, estimateClassicSendTimeoutMs(data.length))) 1196 + const writeTimeoutMs = options.writeTimeoutMs
  1197 + ?? Math.min(600000, Math.max(45000, estimateClassicSendTimeoutMs(data.length)))
1183 if (onProgress) onProgress(5) 1198 if (onProgress) onProgress(5)
  1199 + let waitVisual = 5
  1200 + const waitKeepAlive = onProgress
  1201 + ? setInterval(() => {
  1202 + if (waitVisual >= 95) return
  1203 + waitVisual = Math.min(95, waitVisual + 1)
  1204 + onProgress(waitVisual)
  1205 + }, 1200)
  1206 + : null
1184 return printNativeCommandBytes({ 1207 return printNativeCommandBytes({
1185 deviceId: conn.deviceId, 1208 deviceId: conn.deviceId,
1186 deviceName: conn.deviceName, 1209 deviceName: conn.deviceName,
1187 base64, 1210 base64,
1188 }).then(async () => { 1211 }).then(async () => {
1189 printRunDiag('native_printCommandBytes_queued', { dataBytes: data.length }) 1212 printRunDiag('native_printCommandBytes_queued', { dataBytes: data.length })
1190 - const verified = await waitForNativeCommandBytesWriteComplete(writeTimeoutMs, (waitPct) => {  
1191 - if (onProgress) onProgress(8 + Math.round(waitPct * 0.9))  
1192 - })  
1193 - printRunDiag('native_printCommandBytes_verified', {  
1194 - writeMs: verified.writeMs,  
1195 - commandBytes: verified.commandBytes,  
1196 - stage: verified.stage,  
1197 - })  
1198 - if (onProgress) onProgress(100) 1213 + try {
  1214 + const verified = await waitForNativeCommandBytesWriteComplete(writeTimeoutMs, (waitPct) => {
  1215 + if (onProgress) {
  1216 + const p = Math.max(waitVisual, 8 + Math.round(waitPct * 0.9))
  1217 + waitVisual = p
  1218 + onProgress(p)
  1219 + }
  1220 + })
  1221 + printRunDiag('native_printCommandBytes_verified', {
  1222 + writeMs: verified.writeMs,
  1223 + commandBytes: verified.commandBytes,
  1224 + stage: verified.stage,
  1225 + })
  1226 + if (onProgress) onProgress(100)
  1227 + } finally {
  1228 + if (waitKeepAlive) clearInterval(waitKeepAlive)
  1229 + }
1199 }) 1230 })
1200 } 1231 }
1201 1232
@@ -1402,8 +1433,7 @@ function sendViaBuiltin (data: number[]): Promise&lt;void&gt; { @@ -1402,8 +1433,7 @@ function sendViaBuiltin (data: number[]): Promise&lt;void&gt; {
1402 const shouldTryUpos = uposSupported && ( 1433 const shouldTryUpos = uposSupported && (
1403 uposOptions.force 1434 uposOptions.force
1404 || (matchesKeywords && !isD320faxDevice) 1435 || (matchesKeywords && !isD320faxDevice)
1405 - || (virtualBtLinked && !isD320faxDevice)  
1406 - || (getPrinterType() === 'builtin' && !isD320faxDevice) 1436 + || (getPrinterType() === 'builtin' && !isD320faxDevice && !virtualBtLinked)
1407 ) 1437 )
1408 const shouldPreferTcpFirst = (matchesKeywords || isD320faxDevice) 1438 const shouldPreferTcpFirst = (matchesKeywords || isD320faxDevice)
1409 && !uposOptions.force 1439 && !uposOptions.force
@@ -1493,13 +1523,13 @@ function sendViaBuiltin (data: number[]): Promise&lt;void&gt; { @@ -1493,13 +1523,13 @@ function sendViaBuiltin (data: number[]): Promise&lt;void&gt; {
1493 const msg = e instanceof Error ? e.message : String(e || 'UPOS_PRINT_FAILED') 1523 const msg = e instanceof Error ? e.message : String(e || 'UPOS_PRINT_FAILED')
1494 printRunDiag('builtin_upos_fail_fallback', { err: msg.slice(0, 240), waitMs: Date.now() - tUpos }) 1524 printRunDiag('builtin_upos_fail_fallback', { err: msg.slice(0, 240), waitMs: Date.now() - tUpos })
1495 1525
1496 - if (isVirtualBtBluetoothConnection() && isD320faxAioDevice()) { 1526 + if (isVirtualBtBluetoothConnection()) {
1497 try { 1527 try {
1498 - await sendViaD320faxVirtualBt(data, onProgress) 1528 + await sendViaVirtualBtTsc(data, onProgress)
1499 return 1529 return
1500 } catch (gErr: any) { 1530 } catch (gErr: any) {
1501 - const gMsg = gErr instanceof Error ? gErr.message : String(gErr || 'GPRINTER_SDK_FAILED')  
1502 - throw new Error(`UPOS failed (${msg}); Gprinter SDK failed (${gMsg})`) 1531 + const gMsg = gErr instanceof Error ? gErr.message : String(gErr || 'VIRTUAL_BT_TSC_FAILED')
  1532 + throw new Error(`UPOS failed (${msg}); Virtual BT TSC failed (${gMsg})`)
1503 } 1533 }
1504 } 1534 }
1505 1535
美国版/Food Labeling Management App UniApp/src/utils/printFromPrintDataList.ts
@@ -453,7 +453,6 @@ async function printReprintTemplateWithPreviewStrategy ( @@ -453,7 +453,6 @@ async function printReprintTemplateWithPreviewStrategy (
453 const conn = getBluetoothConnection() 453 const conn = getBluetoothConnection()
454 const mustUseCanvasRaster = 454 const mustUseCanvasRaster =
455 summary.type === 'builtin' 455 summary.type === 'builtin'
456 - || (summary.type === 'bluetooth' && isVirtualBtPrinterDeviceName(conn?.deviceName))  
457 || templateRequiresCanvasStyleFidelity(tmplSized) 456 || templateRequiresCanvasStyleFidelity(tmplSized)
458 || templateHasDateTimeElements(tmplSized) 457 || templateHasDateTimeElements(tmplSized)
459 const useNative = 458 const useNative =
美国版/Food Labeling Management Platform/src/components/labels/LabelTemplateEditor/index.tsx
@@ -61,6 +61,7 @@ import { getGroups } from &#39;../../../services/groupService&#39;; @@ -61,6 +61,7 @@ import { getGroups } from &#39;../../../services/groupService&#39;;
61 import { getPartners } from '../../../services/partnerService'; 61 import { getPartners } from '../../../services/partnerService';
62 import { skipCountForPage } from '../../../lib/paginationQuery'; 62 import { skipCountForPage } from '../../../lib/paginationQuery';
63 import { 63 import {
  64 + filterScopeIdsForPartners,
64 hydrateLabelTemplateScopeFromDto, 65 hydrateLabelTemplateScopeFromDto,
65 locationsScopedForTemplateScope, 66 locationsScopedForTemplateScope,
66 regionOptionsForPartners, 67 regionOptionsForPartners,
@@ -636,6 +637,14 @@ export function LabelTemplateEditor({ @@ -636,6 +637,14 @@ export function LabelTemplateEditor({
636 const availablePartnerIds = scopeAuth.requireCompanySelection 637 const availablePartnerIds = scopeAuth.requireCompanySelection
637 ? filterPartners.map((p) => p.id).filter(Boolean) 638 ? filterPartners.map((p) => p.id).filter(Boolean)
638 : effectivePartnerIds; 639 : effectivePartnerIds;
  640 + const sanitizedScope = filterScopeIdsForPartners({
  641 + partners: filterPartners,
  642 + groups: filterGroups,
  643 + locations: locationCatalog,
  644 + partnerIds: effectivePartnerIds,
  645 + regionIds: scopeRegionIds,
  646 + locationIds: scopeLocationIds,
  647 + });
639 const availableRegionIds = regionOptionsForPartners( 648 const availableRegionIds = regionOptionsForPartners(
640 filterGroups, 649 filterGroups,
641 effectivePartnerIds.length > 0 ? effectivePartnerIds : availablePartnerIds, 650 effectivePartnerIds.length > 0 ? effectivePartnerIds : availablePartnerIds,
@@ -645,14 +654,14 @@ export function LabelTemplateEditor({ @@ -645,14 +654,14 @@ export function LabelTemplateEditor({
645 filterPartners, 654 filterPartners,
646 filterGroups, 655 filterGroups,
647 effectivePartnerIds, 656 effectivePartnerIds,
648 - scopeRegionIds, 657 + sanitizedScope.regionIds,
649 ); 658 );
650 const availableLocationIds = scopedLocations.map((l) => l.id); 659 const availableLocationIds = scopedLocations.map((l) => l.id);
651 660
652 const scopePayload = buildLabelTemplateScopePayload({ 661 const scopePayload = buildLabelTemplateScopePayload({
653 selectedPartnerIds: effectivePartnerIds, 662 selectedPartnerIds: effectivePartnerIds,
654 - selectedRegionIds: scopeRegionIds,  
655 - selectedLocationIds: scopeLocationIds, 663 + selectedRegionIds: sanitizedScope.regionIds,
  664 + selectedLocationIds: sanitizedScope.locationIds,
656 availablePartnerIds, 665 availablePartnerIds,
657 availableRegionIds, 666 availableRegionIds,
658 availableLocationIds, 667 availableLocationIds,
美国版/Food Labeling Management Platform/src/components/labels/LabelsList.tsx
@@ -27,7 +27,7 @@ import { @@ -27,7 +27,7 @@ import {
27 import { Label } from "../ui/label"; 27 import { Label } from "../ui/label";
28 import { Switch } from "../ui/switch"; 28 import { Switch } from "../ui/switch";
29 import { Badge } from "../ui/badge"; 29 import { Badge } from "../ui/badge";
30 -import { Plus, Edit, MoreHorizontal, Trash2 } from "lucide-react"; 30 +import { ArrowLeft, Plus, Edit, MoreHorizontal, Trash2 } from "lucide-react";
31 import { toast } from "sonner"; 31 import { toast } from "sonner";
32 import { skipCountForPage } from "../../lib/paginationQuery"; 32 import { skipCountForPage } from "../../lib/paginationQuery";
33 import { preventDialogDismissOnOverlay } from "../../lib/formDialogLayout"; 33 import { preventDialogDismissOnOverlay } from "../../lib/formDialogLayout";
@@ -67,7 +67,6 @@ import type { ProductDto } from &quot;../../types/product&quot;; @@ -67,7 +67,6 @@ import type { ProductDto } from &quot;../../types/product&quot;;
67 import type { ProductCategoryDto } from "../../types/productCategory"; 67 import type { ProductCategoryDto } from "../../types/productCategory";
68 import type { ProductLocationLinkDto } from "../../types/productLocation"; 68 import type { ProductLocationLinkDto } from "../../types/productLocation";
69 import { getProductLocations } from "../../services/productLocationService"; 69 import { getProductLocations } from "../../services/productLocationService";
70 -import { LabelTemplateDataEntryView } from "./LabelTemplateDataEntryView";  
71 import { NutritionManualEntryForm } from "./NutritionManualEntryForm"; 70 import { NutritionManualEntryForm } from "./NutritionManualEntryForm";
72 import { LabelPreviewOnly } from "./LabelTemplateEditor/LabelCanvas"; 71 import { LabelPreviewOnly } from "./LabelTemplateEditor/LabelCanvas";
73 import { 72 import {
@@ -298,6 +297,17 @@ function labelCategoryMatchesRegion(c: LabelCategoryDto, allowedLocIds: Set&lt;stri @@ -298,6 +297,17 @@ function labelCategoryMatchesRegion(c: LabelCategoryDto, allowedLocIds: Set&lt;stri
298 return lids.some((lid) => allowedLocIds.has(lid)); 297 return lids.some((lid) => allowedLocIds.has(lid));
299 } 298 }
300 299
  300 +function labelTypeMatchesRegion(t: LabelTypeDto, allowedLocIds: Set<string>): boolean {
  301 + const at = String(t.availabilityType ?? "ALL").trim().toUpperCase();
  302 + if (at !== "SPECIFIED") return true;
  303 + const lids = (t.locationIds ?? []).map((x) => String(x).trim()).filter(Boolean);
  304 + return lids.some((lid) => allowedLocIds.has(lid));
  305 +}
  306 +
  307 +type TemplateInputColumn =
  308 + | { kind: "element"; el: LabelElement }
  309 + | { kind: "nutrition"; parent: LabelElement; spec: NutritionManualFieldSpec };
  310 +
301 function templateAppliesToRegion(tpl: LabelTemplateDto, allowedLocIds: Set<string>): boolean { 311 function templateAppliesToRegion(tpl: LabelTemplateDto, allowedLocIds: Set<string>): boolean {
302 const mode = appliedLocationToEditor(tpl); 312 const mode = appliedLocationToEditor(tpl);
303 if (mode === "ALL") return true; 313 if (mode === "ALL") return true;
@@ -959,8 +969,8 @@ type LabelsListProps = { @@ -959,8 +969,8 @@ type LabelsListProps = {
959 }; 969 };
960 970
961 export function LabelsList({ openCreateSeq = 0, onOpenCreateIntentConsumed }: LabelsListProps = {}) { 971 export function LabelsList({ openCreateSeq = 0, onOpenCreateIntentConsumed }: LabelsListProps = {}) {
962 - const [dataEntryTemplateCode, setDataEntryTemplateCode] = useState<string | null>(null);  
963 - const [dataEntryContextHint, setDataEntryContextHint] = useState<string | undefined>(undefined); 972 + const [bulkAddTemplateCode, setBulkAddTemplateCode] = useState<string | null>(null);
  973 + const [bulkAddContextHint, setBulkAddContextHint] = useState<string | undefined>(undefined);
964 const [isBulkAddDialogOpen, setIsBulkAddDialogOpen] = useState(false); 974 const [isBulkAddDialogOpen, setIsBulkAddDialogOpen] = useState(false);
965 const [bulkLoadingTemplates, setBulkLoadingTemplates] = useState(false); 975 const [bulkLoadingTemplates, setBulkLoadingTemplates] = useState(false);
966 const [bulkLoadingPreview, setBulkLoadingPreview] = useState(false); 976 const [bulkLoadingPreview, setBulkLoadingPreview] = useState(false);
@@ -1311,8 +1321,8 @@ export function LabelsList({ openCreateSeq = 0, onOpenCreateIntentConsumed }: La @@ -1311,8 +1321,8 @@ export function LabelsList({ openCreateSeq = 0, onOpenCreateIntentConsumed }: La
1311 } 1321 }
1312 const tpl = bulkTemplates.find((x) => templateListCode(x) === bulkTemplateCode); 1322 const tpl = bulkTemplates.find((x) => templateListCode(x) === bulkTemplateCode);
1313 const title = tpl ? templateListLabel(tpl) : bulkTemplateCode; 1323 const title = tpl ? templateListLabel(tpl) : bulkTemplateCode;
1314 - setDataEntryContextHint(`Bulk Add template: ${title}`);  
1315 - setDataEntryTemplateCode(bulkTemplateCode); 1324 + setBulkAddContextHint(`Template: ${title}`);
  1325 + setBulkAddTemplateCode(bulkTemplateCode);
1316 setIsBulkAddDialogOpen(false); 1326 setIsBulkAddDialogOpen(false);
1317 }; 1327 };
1318 1328
@@ -1324,19 +1334,19 @@ export function LabelsList({ openCreateSeq = 0, onOpenCreateIntentConsumed }: La @@ -1324,19 +1334,19 @@ export function LabelsList({ openCreateSeq = 0, onOpenCreateIntentConsumed }: La
1324 } 1334 }
1325 }; 1335 };
1326 1336
1327 - const closeDataEntry = () => {  
1328 - setDataEntryTemplateCode(null);  
1329 - setDataEntryContextHint(undefined); 1337 + const closeBulkAddPage = () => {
  1338 + setBulkAddTemplateCode(null);
  1339 + setBulkAddContextHint(undefined);
1330 refreshList(); 1340 refreshList();
1331 }; 1341 };
1332 1342
1333 - if (dataEntryTemplateCode) { 1343 + if (bulkAddTemplateCode) {
1334 return ( 1344 return (
1335 <div className="h-[calc(100vh-8rem)] min-h-[500px] flex flex-col pt-2"> 1345 <div className="h-[calc(100vh-8rem)] min-h-[500px] flex flex-col pt-2">
1336 - <LabelTemplateDataEntryView  
1337 - templateCode={dataEntryTemplateCode}  
1338 - onBack={closeDataEntry}  
1339 - contextHint={dataEntryContextHint} 1346 + <LabelBulkAddPage
  1347 + templateCode={bulkAddTemplateCode}
  1348 + onBack={closeBulkAddPage}
  1349 + contextHint={bulkAddContextHint}
1340 /> 1350 />
1341 </div> 1351 </div>
1342 ); 1352 );
@@ -1719,6 +1729,855 @@ export function LabelsList({ openCreateSeq = 0, onOpenCreateIntentConsumed }: La @@ -1719,6 +1729,855 @@ export function LabelsList({ openCreateSeq = 0, onOpenCreateIntentConsumed }: La
1719 ); 1729 );
1720 } 1730 }
1721 1731
  1732 +type BulkAddRow = {
  1733 + id: string;
  1734 + partnerId: string;
  1735 + regionIds: string[];
  1736 + productCategoryId: string;
  1737 + productId: string;
  1738 + labelName: string;
  1739 + locationIds: string[];
  1740 + labelCategoryId: string;
  1741 + labelTypeId: string;
  1742 + state: boolean;
  1743 + templateDataValues: Record<string, string>;
  1744 + templateDateOffsets: Record<string, { unit: string; value: string }>;
  1745 + nutritionByElementId: Record<string, Record<string, string>>;
  1746 +};
  1747 +
  1748 +function createEmptyBulkAddRow(scopeAuth: ReturnType<typeof useCategoryScopeAuth>): BulkAddRow {
  1749 + return {
  1750 + id: `row-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,
  1751 + partnerId: scopeAuth.requireCompanySelection ? "" : scopeAuth.fixedPartnerId.trim(),
  1752 + regionIds: [],
  1753 + productCategoryId: "",
  1754 + productId: "",
  1755 + labelName: "",
  1756 + locationIds: [],
  1757 + labelCategoryId: "",
  1758 + labelTypeId: "",
  1759 + state: true,
  1760 + templateDataValues: {},
  1761 + templateDateOffsets: {},
  1762 + nutritionByElementId: {},
  1763 + };
  1764 +}
  1765 +
  1766 +function LabelBulkAddPage({
  1767 + templateCode,
  1768 + onBack,
  1769 + contextHint,
  1770 +}: {
  1771 + templateCode: string;
  1772 + onBack: () => void;
  1773 + contextHint?: string;
  1774 +}) {
  1775 + const scopeAuth = useCategoryScopeAuth();
  1776 + const {
  1777 + loading,
  1778 + templates,
  1779 + locations,
  1780 + groups,
  1781 + partners,
  1782 + categories,
  1783 + types,
  1784 + products,
  1785 + productCategories,
  1786 + productLocationMap,
  1787 + } = useLabelFormReferenceData(true, null);
  1788 + const [rows, setRows] = useState<BulkAddRow[]>(() => [createEmptyBulkAddRow(scopeAuth)]);
  1789 + const [saving, setSaving] = useState(false);
  1790 + const [bulkTemplateDetail, setBulkTemplateDetail] = useState<LabelTemplateDto | null>(null);
  1791 + const [bulkTemplateDetailLoading, setBulkTemplateDetailLoading] = useState(false);
  1792 +
  1793 + useEffect(() => {
  1794 + if (scopeAuth.requireCompanySelection) return;
  1795 + const fixed = scopeAuth.fixedPartnerId.trim();
  1796 + if (!fixed) return;
  1797 + setRows((prev) =>
  1798 + prev.map((row) => (row.partnerId === fixed ? row : { ...row, partnerId: fixed })),
  1799 + );
  1800 + }, [scopeAuth.requireCompanySelection, scopeAuth.fixedPartnerId]);
  1801 +
  1802 + useEffect(() => {
  1803 + const code = templateCode.trim();
  1804 + if (!code) {
  1805 + setBulkTemplateDetail(null);
  1806 + return;
  1807 + }
  1808 + let cancelled = false;
  1809 + (async () => {
  1810 + setBulkTemplateDetailLoading(true);
  1811 + try {
  1812 + const tpl = await getLabelTemplate(code);
  1813 + if (!cancelled) setBulkTemplateDetail(tpl);
  1814 + } catch (e: any) {
  1815 + if (!cancelled) {
  1816 + setBulkTemplateDetail(null);
  1817 + toast.error("Failed to load template fields.", {
  1818 + description: e?.message ? String(e.message) : "Please try again.",
  1819 + });
  1820 + }
  1821 + } finally {
  1822 + if (!cancelled) setBulkTemplateDetailLoading(false);
  1823 + }
  1824 + })();
  1825 + return () => {
  1826 + cancelled = true;
  1827 + };
  1828 + }, [templateCode]);
  1829 +
  1830 + const templateFromList = useMemo(
  1831 + () => templates.find((t) => templateListCode(t) === templateCode) ?? null,
  1832 + [templates, templateCode],
  1833 + );
  1834 +
  1835 + const selectedTemplate = bulkTemplateDetail ?? templateFromList;
  1836 +
  1837 + const selectedTemplateLabel = selectedTemplate ? templateListLabel(selectedTemplate) : templateCode;
  1838 +
  1839 + const bulkDataEntryElements = useMemo(
  1840 + () => getCreateLabelTemplateInputElements(selectedTemplate),
  1841 + [selectedTemplate],
  1842 + );
  1843 +
  1844 + const bulkNutritionElements = useMemo(
  1845 + () => listNutritionElements(((selectedTemplate?.elements ?? []) as LabelElement[])),
  1846 + [selectedTemplate],
  1847 + );
  1848 +
  1849 + const bulkTemplateInputColumns = useMemo(() => {
  1850 + const cols: TemplateInputColumn[] = bulkDataEntryElements.map((el) => ({ kind: "element", el }));
  1851 + for (const nel of bulkNutritionElements) {
  1852 + for (const spec of listNutritionManualFieldSpecs(nel)) {
  1853 + cols.push({ kind: "nutrition", parent: nel, spec });
  1854 + }
  1855 + }
  1856 + return cols;
  1857 + }, [bulkDataEntryElements, bulkNutritionElements]);
  1858 +
  1859 + const showTemplateInputColumns = bulkTemplateInputColumns.length > 0;
  1860 +
  1861 + useEffect(() => {
  1862 + if (!selectedTemplate) return;
  1863 + const empty = emptyLabelFormTemplateInputState(selectedTemplate);
  1864 + setRows((prev) =>
  1865 + prev.map((row) => ({
  1866 + ...row,
  1867 + templateDataValues: { ...empty.textValues, ...row.templateDataValues },
  1868 + templateDateOffsets: { ...empty.dateOffsets, ...row.templateDateOffsets },
  1869 + nutritionByElementId: {
  1870 + ...empty.nutritionByElementId,
  1871 + ...row.nutritionByElementId,
  1872 + },
  1873 + })),
  1874 + );
  1875 + }, [selectedTemplate]);
  1876 +
  1877 + const companyOptions = useMemo(
  1878 + () =>
  1879 + [...partners]
  1880 + .filter((p) => (p.id ?? "").trim())
  1881 + .sort((a, b) =>
  1882 + (a.partnerName ?? "").localeCompare(b.partnerName ?? "", undefined, { sensitivity: "base" }),
  1883 + )
  1884 + .map((p) => ({
  1885 + value: (p.id ?? "").trim(),
  1886 + label: toDisplay(p.partnerName),
  1887 + })),
  1888 + [partners],
  1889 + );
  1890 +
  1891 + const updateRow = (rowId: string, patch: Partial<BulkAddRow>) => {
  1892 + setRows((prev) => prev.map((row) => (row.id === rowId ? { ...row, ...patch } : row)));
  1893 + };
  1894 +
  1895 + const updateRowTemplateText = (rowId: string, elementId: string, value: string) => {
  1896 + setRows((prev) =>
  1897 + prev.map((row) =>
  1898 + row.id === rowId
  1899 + ? {
  1900 + ...row,
  1901 + templateDataValues: {
  1902 + ...row.templateDataValues,
  1903 + [elementId]: value,
  1904 + },
  1905 + }
  1906 + : row,
  1907 + ),
  1908 + );
  1909 + };
  1910 +
  1911 + const updateRowTemplateDateOffset = (
  1912 + rowId: string,
  1913 + elementId: string,
  1914 + patch: Partial<{ unit: string; value: string }>,
  1915 + ) => {
  1916 + setRows((prev) =>
  1917 + prev.map((row) => {
  1918 + if (row.id !== rowId) return row;
  1919 + const cur = row.templateDateOffsets[elementId] ?? { unit: "Days", value: "" };
  1920 + return {
  1921 + ...row,
  1922 + templateDateOffsets: {
  1923 + ...row.templateDateOffsets,
  1924 + [elementId]: { ...cur, ...patch },
  1925 + },
  1926 + };
  1927 + }),
  1928 + );
  1929 + };
  1930 +
  1931 + const updateRowNutritionValue = (
  1932 + rowId: string,
  1933 + elementId: string,
  1934 + subKey: string,
  1935 + value: string,
  1936 + ) => {
  1937 + setRows((prev) =>
  1938 + prev.map((row) =>
  1939 + row.id === rowId
  1940 + ? {
  1941 + ...row,
  1942 + nutritionByElementId: {
  1943 + ...row.nutritionByElementId,
  1944 + [elementId]: {
  1945 + ...(row.nutritionByElementId[elementId] ?? {}),
  1946 + [subKey]: value,
  1947 + },
  1948 + },
  1949 + }
  1950 + : row,
  1951 + ),
  1952 + );
  1953 + };
  1954 +
  1955 + const updateRowPartner = (rowId: string, partnerId: string) => {
  1956 + updateRow(rowId, {
  1957 + partnerId,
  1958 + regionIds: [],
  1959 + productCategoryId: "",
  1960 + productId: "",
  1961 + locationIds: [],
  1962 + labelCategoryId: "",
  1963 + labelTypeId: "",
  1964 + });
  1965 + };
  1966 +
  1967 + const updateRowProduct = (row: BulkAddRow, productId: string, productOptionsSource: ProductDto[]) => {
  1968 + if (!selectedTemplate) {
  1969 + updateRow(row.id, { productId });
  1970 + return;
  1971 + }
  1972 + const productCodeValue = (() => {
  1973 + const p = productOptionsSource.find((x) => x.id === productId);
  1974 + return (p?.codeValue ?? "").trim();
  1975 + })();
  1976 + updateRow(row.id, {
  1977 + productId,
  1978 + templateDataValues: {
  1979 + ...row.templateDataValues,
  1980 + ...buildTemplateBarcodeQrDefaultsFromCodeValue(
  1981 + (selectedTemplate.elements ?? []) as LabelElement[],
  1982 + productCodeValue,
  1983 + ),
  1984 + },
  1985 + });
  1986 + };
  1987 +
  1988 + const updateRowLabelName = (row: BulkAddRow, labelName: string) => {
  1989 + if (!selectedTemplate) {
  1990 + updateRow(row.id, { labelName });
  1991 + return;
  1992 + }
  1993 + updateRow(row.id, {
  1994 + labelName,
  1995 + templateDataValues: mergeLabelBindingsIntoTextValues(
  1996 + row.templateDataValues,
  1997 + (selectedTemplate.elements ?? []) as LabelElement[],
  1998 + { labelName },
  1999 + ),
  2000 + });
  2001 + };
  2002 +
  2003 + const updateRowLabelType = (row: BulkAddRow, labelTypeId: string, labelTypeOptionsSource: LabelTypeDto[]) => {
  2004 + if (!selectedTemplate) {
  2005 + updateRow(row.id, { labelTypeId });
  2006 + return;
  2007 + }
  2008 + const labelType = labelTypeOptionsSource.find((x) => x.id === labelTypeId);
  2009 + updateRow(row.id, {
  2010 + labelTypeId,
  2011 + templateDataValues: mergeLabelBindingsIntoTextValues(
  2012 + row.templateDataValues,
  2013 + (selectedTemplate.elements ?? []) as LabelElement[],
  2014 + { labelTypeName: labelType?.typeName ?? labelType?.typeCode },
  2015 + ),
  2016 + });
  2017 + };
  2018 +
  2019 + const updateRowRegions = (rowId: string, regionIds: string[]) => {
  2020 + updateRow(rowId, {
  2021 + regionIds,
  2022 + productCategoryId: "",
  2023 + productId: "",
  2024 + locationIds: [],
  2025 + labelCategoryId: "",
  2026 + labelTypeId: "",
  2027 + });
  2028 + };
  2029 +
  2030 + const addRow = () => setRows((prev) => [...prev, createEmptyBulkAddRow(scopeAuth)]);
  2031 + const removeRow = (rowId: string) =>
  2032 + setRows((prev) => (prev.length <= 1 ? prev : prev.filter((row) => row.id !== rowId)));
  2033 +
  2034 + const validateAndBuildInput = (row: BulkAddRow, index: number): LabelCreateInput | null => {
  2035 + const rowName = `Row ${index + 1}`;
  2036 + const effectivePartnerId = effectiveScopePartnerId(
  2037 + scopeAuth.requireCompanySelection,
  2038 + row.partnerId,
  2039 + scopeAuth.fixedPartnerId,
  2040 + );
  2041 + const partnerErr = scopePartnerValidationMessage(
  2042 + scopeAuth.requireCompanySelection,
  2043 + effectivePartnerId,
  2044 + );
  2045 + if (partnerErr) {
  2046 + toast.error(`${rowName}: validation failed`, { description: partnerErr });
  2047 + return null;
  2048 + }
  2049 + const regionPayload = buildLabelRegionScopePayload(row.regionIds, groups, effectivePartnerId);
  2050 + if (regionPayload.appliedRegionType === "SPECIFIED" && !regionPayload.regionIds.length) {
  2051 + toast.error(`${rowName}: validation failed`, {
  2052 + description: "Select company and applicable region(s).",
  2053 + });
  2054 + return null;
  2055 + }
  2056 + const locPayload = buildSpecifiedLocationPayload(
  2057 + locations,
  2058 + partners,
  2059 + groups,
  2060 + effectivePartnerId,
  2061 + row.regionIds,
  2062 + row.locationIds,
  2063 + );
  2064 + if (!locPayload.ok) {
  2065 + toast.error(`${rowName}: validation failed`, { description: locPayload.message });
  2066 + return null;
  2067 + }
  2068 + if (selectedTemplate) {
  2069 + const allowedLocIds = new Set(
  2070 + locationsForRegionGroups(
  2071 + locations,
  2072 + groups,
  2073 + regionNamesToGroupIds(row.regionIds, groups, effectivePartnerId),
  2074 + ).map((l) => l.id),
  2075 + );
  2076 + if (!templateAppliesToRegion(selectedTemplate, allowedLocIds)) {
  2077 + toast.error(`${rowName}: validation failed`, {
  2078 + description: "The selected template is not available in this row's region.",
  2079 + });
  2080 + return null;
  2081 + }
  2082 + }
  2083 + if (!row.productCategoryId.trim() || !row.productId.trim()) {
  2084 + toast.error(`${rowName}: validation failed`, {
  2085 + description: "Select a product category and product.",
  2086 + });
  2087 + return null;
  2088 + }
  2089 + if (!row.labelName.trim() || !row.labelCategoryId.trim() || !row.labelTypeId.trim()) {
  2090 + toast.error(`${rowName}: validation failed`, {
  2091 + description: "Fill label name, label category, and label type.",
  2092 + });
  2093 + return null;
  2094 + }
  2095 + return {
  2096 + labelName: row.labelName.trim(),
  2097 + templateCode,
  2098 + locationIds: locPayload.locationIds,
  2099 + labelCategoryId: row.labelCategoryId.trim(),
  2100 + labelTypeId: row.labelTypeId.trim(),
  2101 + productIds: [row.productId.trim()],
  2102 + labelInfoJson: null,
  2103 + state: row.state,
  2104 + appliedRegionType: regionPayload.appliedRegionType,
  2105 + regionIds: regionPayload.regionIds,
  2106 + groupIds: regionPayload.regionIds,
  2107 + };
  2108 + };
  2109 +
  2110 + const saveTemplateDefaultsAfterLabels = async (validRows: BulkAddRow[]) => {
  2111 + if (!selectedTemplate) return;
  2112 + const code = templateCode.trim();
  2113 + if (!code) return;
  2114 + const latest = await getLabelTemplate(code);
  2115 + const dataEls = getDataEntryElements(latest);
  2116 + const hasNutritionRows = listNutritionElements((latest.elements ?? []) as LabelElement[]).length > 0;
  2117 + if (dataEls.length === 0 && !hasNutritionRows) return;
  2118 +
  2119 + const defaultsMap = buildTemplateDefaultsMap(latest);
  2120 + for (const row of validRows) {
  2121 + const productId = row.productId.trim();
  2122 + const labelTypeId = row.labelTypeId.trim();
  2123 + if (!productId || !labelTypeId) continue;
  2124 + const product = products.find((x) => x.id === productId);
  2125 + const labelType = types.find((x) => x.id === labelTypeId);
  2126 + const productCodeValue = (product?.codeValue ?? "").trim();
  2127 + const inputDefaultValues = collectTemplateDefaultValuesForSave(
  2128 + latest,
  2129 + row.templateDataValues,
  2130 + row.templateDateOffsets,
  2131 + row.nutritionByElementId,
  2132 + productCodeValue,
  2133 + {
  2134 + labelName: row.labelName,
  2135 + labelTypeName: labelType?.typeName ?? labelType?.typeCode,
  2136 + },
  2137 + );
  2138 + defaultsMap.set(`${productId}::${labelTypeId}`, {
  2139 + productId,
  2140 + labelTypeId,
  2141 + defaultValues: { ...inputDefaultValues },
  2142 + orderNum: defaultsMap.size + 1,
  2143 + });
  2144 + }
  2145 +
  2146 + const mergedDefaults = Array.from(defaultsMap.values()).map((row, idx) => ({
  2147 + ...row,
  2148 + orderNum: idx + 1,
  2149 + }));
  2150 + const elements = sortTemplateElementsForDisplay((latest.elements ?? []) as LabelElement[]);
  2151 + await updateLabelTemplate(code, {
  2152 + id: latest.id,
  2153 + name: (latest.name ?? latest.templateName ?? "").trim() || latest.id,
  2154 + labelType: (latest.labelType ?? "PRICE") as any,
  2155 + unit: (latest.unit ?? "inch") as any,
  2156 + width: Number(latest.width ?? 2),
  2157 + height: Number(latest.height ?? 2),
  2158 + appliedLocation: appliedLocationToEditor(latest),
  2159 + showRuler: latest.showRuler ?? true,
  2160 + showGrid: latest.showGrid ?? true,
  2161 + state: latest.state ?? true,
  2162 + elements: labelElementsToApiPayload(elements),
  2163 + contents: buildTemplateContentsFromElements(elements),
  2164 + appliedLocationIds:
  2165 + appliedLocationToEditor(latest) === "ALL" ? [] : (latest.appliedLocationIds ?? []),
  2166 + templateProductDefaults: mergedDefaults,
  2167 + });
  2168 + };
  2169 +
  2170 + const submit = async () => {
  2171 + const inputs: LabelCreateInput[] = [];
  2172 + const validRows: BulkAddRow[] = [];
  2173 + for (let i = 0; i < rows.length; i += 1) {
  2174 + const input = validateAndBuildInput(rows[i], i);
  2175 + if (!input) return;
  2176 + inputs.push(input);
  2177 + validRows.push(rows[i]);
  2178 + }
  2179 +
  2180 + setSaving(true);
  2181 + try {
  2182 + for (const input of inputs) {
  2183 + await createLabel(input);
  2184 + }
  2185 + try {
  2186 + await saveTemplateDefaultsAfterLabels(validRows);
  2187 + } catch (e: any) {
  2188 + toast.warning("Labels created, template data failed.", {
  2189 + description: e?.message ? String(e.message) : "Please edit template data manually.",
  2190 + });
  2191 + }
  2192 + toast.success("Labels created.", {
  2193 + description: `${inputs.length} label(s) have been created successfully.`,
  2194 + });
  2195 + onBack();
  2196 + } catch (e: any) {
  2197 + toast.error("Failed to create labels.", {
  2198 + description: e?.message ? String(e.message) : "Please check the rows and try again.",
  2199 + });
  2200 + } finally {
  2201 + setSaving(false);
  2202 + }
  2203 + };
  2204 +
  2205 + return (
  2206 + <div className="flex h-full min-h-0 flex-col">
  2207 + <div className="flex shrink-0 items-center gap-3 border-b bg-white px-4 py-3">
  2208 + <Button type="button" variant="outline" className="h-9 gap-2" onClick={onBack} disabled={saving}>
  2209 + <ArrowLeft className="h-4 w-4" />
  2210 + Back
  2211 + </Button>
  2212 + <div className="min-w-0 flex-1">
  2213 + <div className="text-xs font-semibold uppercase tracking-wide text-gray-500">Bulk Add Labels</div>
  2214 + <div className="truncate text-base font-semibold text-gray-900">{selectedTemplateLabel}</div>
  2215 + {contextHint ? <div className="truncate text-xs text-gray-500">{contextHint}</div> : null}
  2216 + </div>
  2217 + <Button type="button" variant="outline" className="h-9 gap-2" onClick={addRow} disabled={saving}>
  2218 + <Plus className="h-4 w-4" />
  2219 + Add row
  2220 + </Button>
  2221 + <Button
  2222 + type="button"
  2223 + className="h-9 bg-blue-600 px-6 text-white hover:bg-blue-700"
  2224 + onClick={submit}
  2225 + disabled={saving || loading || bulkTemplateDetailLoading}
  2226 + >
  2227 + {saving ? "Saving..." : "Save"}
  2228 + </Button>
  2229 + </div>
  2230 +
  2231 + <div className="min-h-0 flex-1 overflow-auto bg-gray-50 p-4">
  2232 + {loading || bulkTemplateDetailLoading ? (
  2233 + <div className="rounded-md border bg-white p-8 text-center text-sm text-gray-500">Loading options...</div>
  2234 + ) : (
  2235 + <div className="min-w-[1900px] rounded-md border bg-white shadow-sm">
  2236 + <Table>
  2237 + <TableHeader>
  2238 + <TableRow className="bg-gray-50 hover:bg-gray-50">
  2239 + <TableHead className="w-[64px] font-bold text-gray-900">#</TableHead>
  2240 + {scopeAuth.requireCompanySelection ? (
  2241 + <TableHead className="min-w-[180px] font-bold text-gray-900">Company *</TableHead>
  2242 + ) : null}
  2243 + <TableHead className="min-w-[220px] font-bold text-gray-900">Applicable Region *</TableHead>
  2244 + <TableHead className="min-w-[210px] font-bold text-gray-900">Product category *</TableHead>
  2245 + <TableHead className="min-w-[210px] font-bold text-gray-900">Product *</TableHead>
  2246 + <TableHead className="min-w-[220px] font-bold text-gray-900">Label Name *</TableHead>
  2247 + <TableHead className="min-w-[220px] font-bold text-gray-900">Location *</TableHead>
  2248 + <TableHead className="min-w-[210px] font-bold text-gray-900">Label Category *</TableHead>
  2249 + <TableHead className="min-w-[210px] font-bold text-gray-900">Label Type *</TableHead>
  2250 + {bulkTemplateInputColumns.map((col) => (
  2251 + <TableHead
  2252 + key={
  2253 + col.kind === "element"
  2254 + ? `template-${col.el.id}`
  2255 + : `nutrition-${col.parent.id}-${col.spec.subKey}`
  2256 + }
  2257 + className="min-w-[180px] font-bold text-gray-900"
  2258 + title={
  2259 + col.kind === "element"
  2260 + ? col.el.id
  2261 + : `${col.parent.id} / ${col.spec.subKey}`
  2262 + }
  2263 + >
  2264 + {col.kind === "element"
  2265 + ? dataEntryColumnLabel(
  2266 + col.el,
  2267 + (selectedTemplate?.elements ?? []) as LabelElement[],
  2268 + )
  2269 + : col.spec.columnLabel}
  2270 + </TableHead>
  2271 + ))}
  2272 + <TableHead className="w-[110px] font-bold text-gray-900">Enabled</TableHead>
  2273 + <TableHead className="w-[80px] text-center font-bold text-gray-900">Actions</TableHead>
  2274 + </TableRow>
  2275 + </TableHeader>
  2276 + <TableBody>
  2277 + {rows.map((row, index) => {
  2278 + const effectivePartnerId = effectiveScopePartnerId(
  2279 + scopeAuth.requireCompanySelection,
  2280 + row.partnerId,
  2281 + scopeAuth.fixedPartnerId,
  2282 + );
  2283 + const regionOptions = regionOptionsForPartner(groups, effectivePartnerId);
  2284 + const groupIds = regionNamesToGroupIds(row.regionIds, groups, effectivePartnerId);
  2285 + const regionReady = !!(effectivePartnerId && row.regionIds.length && groupIds.length);
  2286 + const locationsInScope = regionReady
  2287 + ? locationsForRegionGroups(locations, groups, groupIds)
  2288 + : [];
  2289 + const allowedLocIds = new Set(locationsInScope.map((l) => l.id).filter(Boolean));
  2290 + const templateAllowed = selectedTemplate
  2291 + ? templateAppliesToRegion(selectedTemplate, allowedLocIds)
  2292 + : true;
  2293 + const productCategoryOptions = productCategories
  2294 + .filter((c) => productCategoryMatchesRegion(c, allowedLocIds))
  2295 + .map((c) => ({
  2296 + value: (c.id ?? "").trim(),
  2297 + label: toDisplay(c.categoryName ?? c.categoryCode ?? c.id),
  2298 + }))
  2299 + .filter((o) => o.value);
  2300 + const productOptions = products
  2301 + .filter((p) => {
  2302 + if ((p.categoryId ?? "").trim() !== row.productCategoryId.trim()) return false;
  2303 + const linkedLocIds = productLocationMap.get(p.id) ?? p.locationIds ?? [];
  2304 + if (linkedLocIds.length) {
  2305 + return linkedLocIds.some((lid) => allowedLocIds.has(String(lid).trim()));
  2306 + }
  2307 + const productPartnerId = (p.partnerId ?? "").trim();
  2308 + if (productPartnerId && productPartnerId !== effectivePartnerId) return false;
  2309 + const productGroupIds = (p.groupIds ?? []).map((gid) => String(gid).trim()).filter(Boolean);
  2310 + if (productGroupIds.length) return productGroupIds.some((gid) => groupIds.includes(gid));
  2311 + return true;
  2312 + })
  2313 + .map((p) => ({
  2314 + value: p.id,
  2315 + label: toDisplay(p.productName ?? p.productCode ?? p.id),
  2316 + }));
  2317 + const locationOptions = locationsInScope.map((loc) => ({
  2318 + value: loc.id,
  2319 + label: toDisplay(loc.locationName ?? loc.locationCode ?? loc.id),
  2320 + }));
  2321 + const labelCategoryOptions = categories
  2322 + .filter((c) => labelCategoryMatchesRegion(c, allowedLocIds))
  2323 + .map((c) => ({
  2324 + value: c.id,
  2325 + label: toDisplay(c.categoryName ?? c.categoryCode ?? c.id),
  2326 + }));
  2327 + const labelTypeOptions = types
  2328 + .filter((t) => labelTypeMatchesRegion(t, allowedLocIds))
  2329 + .map((t) => ({
  2330 + value: t.id,
  2331 + label: toDisplay(t.typeName ?? t.typeCode ?? t.id),
  2332 + }));
  2333 + const gateHint = scopeAuth.requireCompanySelection
  2334 + ? "Select company and region first"
  2335 + : "Select region first";
  2336 +
  2337 + return (
  2338 + <TableRow key={row.id} className={!templateAllowed && regionReady ? "bg-red-50/50" : ""}>
  2339 + <TableCell className="align-top pt-5 text-sm font-semibold text-gray-700">
  2340 + {index + 1}
  2341 + </TableCell>
  2342 + {scopeAuth.requireCompanySelection ? (
  2343 + <TableCell className="align-top">
  2344 + <SearchableSelect
  2345 + value={row.partnerId}
  2346 + onValueChange={(v) => updateRowPartner(row.id, v)}
  2347 + options={companyOptions}
  2348 + placeholder="Select company"
  2349 + searchPlaceholder="Search company..."
  2350 + emptyText="No companies available."
  2351 + disabled={saving}
  2352 + />
  2353 + </TableCell>
  2354 + ) : null}
  2355 + <TableCell className="align-top">
  2356 + <SearchableMultiSelect
  2357 + values={row.regionIds}
  2358 + onValuesChange={(v) => updateRowRegions(row.id, v)}
  2359 + options={regionOptions}
  2360 + placeholder={effectivePartnerId ? "Select region(s)" : "Select company first"}
  2361 + searchPlaceholder="Search regions..."
  2362 + selectAllRowLabel="Select All"
  2363 + emptyText={effectivePartnerId ? "No regions for this company." : "Select company first."}
  2364 + disabled={saving || !effectivePartnerId}
  2365 + />
  2366 + {!templateAllowed && regionReady ? (
  2367 + <div className="mt-1 text-xs text-red-600">Template is not available in this region.</div>
  2368 + ) : null}
  2369 + </TableCell>
  2370 + <TableCell className="align-top">
  2371 + <SearchableSelect
  2372 + value={row.productCategoryId}
  2373 + onValueChange={(v) => updateRow(row.id, { productCategoryId: v, productId: "" })}
  2374 + options={productCategoryOptions}
  2375 + placeholder={regionReady ? "Select category" : gateHint}
  2376 + searchPlaceholder="Search product category..."
  2377 + emptyText={regionReady ? "No product categories." : gateHint}
  2378 + disabled={saving || !regionReady}
  2379 + />
  2380 + </TableCell>
  2381 + <TableCell className="align-top">
  2382 + <SearchableSelect
  2383 + value={row.productId}
  2384 + onValueChange={(v) => updateRowProduct(row, v, products)}
  2385 + options={productOptions}
  2386 + placeholder={
  2387 + regionReady
  2388 + ? row.productCategoryId.trim()
  2389 + ? "Select product"
  2390 + : "Select category first"
  2391 + : gateHint
  2392 + }
  2393 + searchPlaceholder="Search products..."
  2394 + emptyText={
  2395 + regionReady
  2396 + ? row.productCategoryId.trim()
  2397 + ? "No products in this category."
  2398 + : "Select a product category."
  2399 + : gateHint
  2400 + }
  2401 + disabled={saving || !regionReady || !row.productCategoryId.trim()}
  2402 + />
  2403 + </TableCell>
  2404 + <TableCell className="align-top">
  2405 + <Input
  2406 + className="h-10"
  2407 + value={row.labelName}
  2408 + onChange={(e) => updateRowLabelName(row, e.target.value)}
  2409 + placeholder="e.g. Breakfast label"
  2410 + disabled={saving}
  2411 + />
  2412 + </TableCell>
  2413 + <TableCell className="align-top">
  2414 + <SearchableMultiSelect
  2415 + values={row.locationIds}
  2416 + onValuesChange={(v) => updateRow(row.id, { locationIds: v })}
  2417 + options={locationOptions}
  2418 + placeholder={regionReady ? "Select location(s)" : gateHint}
  2419 + searchPlaceholder="Search location..."
  2420 + selectAllRowLabel="Select All"
  2421 + emptyText={regionReady ? "No locations in this region." : gateHint}
  2422 + disabled={saving || !regionReady}
  2423 + />
  2424 + </TableCell>
  2425 + <TableCell className="align-top">
  2426 + <SearchableSelect
  2427 + value={row.labelCategoryId}
  2428 + onValueChange={(v) => updateRow(row.id, { labelCategoryId: v })}
  2429 + options={labelCategoryOptions}
  2430 + placeholder={regionReady ? "Select category" : gateHint}
  2431 + searchPlaceholder="Search category..."
  2432 + emptyText={regionReady ? "No label categories." : gateHint}
  2433 + disabled={saving || !regionReady}
  2434 + />
  2435 + </TableCell>
  2436 + <TableCell className="align-top">
  2437 + <SearchableSelect
  2438 + value={row.labelTypeId}
  2439 + onValueChange={(v) => updateRowLabelType(row, v, types)}
  2440 + options={labelTypeOptions}
  2441 + placeholder={regionReady ? "Select type" : gateHint}
  2442 + searchPlaceholder="Search type..."
  2443 + emptyText={regionReady ? "No label types." : gateHint}
  2444 + disabled={saving || !regionReady}
  2445 + />
  2446 + </TableCell>
  2447 + {bulkTemplateInputColumns.map((col) => {
  2448 + if (col.kind === "nutrition") {
  2449 + const value = row.nutritionByElementId[col.parent.id]?.[col.spec.subKey] ?? "";
  2450 + return (
  2451 + <TableCell
  2452 + key={`nutrition-${row.id}-${col.parent.id}-${col.spec.subKey}`}
  2453 + className="align-top"
  2454 + >
  2455 + {col.spec.inputType === "checkbox" ? (
  2456 + <Switch
  2457 + checked={value === "true"}
  2458 + onCheckedChange={(checked) =>
  2459 + updateRowNutritionValue(
  2460 + row.id,
  2461 + col.parent.id,
  2462 + col.spec.subKey,
  2463 + checked ? "true" : "false",
  2464 + )
  2465 + }
  2466 + disabled={saving}
  2467 + />
  2468 + ) : (
  2469 + <Input
  2470 + className="h-10"
  2471 + value={value}
  2472 + onChange={(e) =>
  2473 + updateRowNutritionValue(
  2474 + row.id,
  2475 + col.parent.id,
  2476 + col.spec.subKey,
  2477 + e.target.value,
  2478 + )
  2479 + }
  2480 + placeholder={col.spec.columnLabel}
  2481 + disabled={saving}
  2482 + />
  2483 + )}
  2484 + </TableCell>
  2485 + );
  2486 + }
  2487 +
  2488 + const el = col.el;
  2489 + const templateScanLocked = isTemplateSectionBarcodeOrQrElement(el);
  2490 + const label = dataEntryColumnLabel(
  2491 + el,
  2492 + (selectedTemplate?.elements ?? []) as LabelElement[],
  2493 + );
  2494 + return (
  2495 + <TableCell key={`template-${row.id}-${el.id}`} className="align-top">
  2496 + {templateScanLocked ? (
  2497 + <Input
  2498 + className="h-10 bg-gray-50"
  2499 + readOnly
  2500 + disabled
  2501 + value={row.templateDataValues[el.id] ?? ""}
  2502 + placeholder="From product Code Value"
  2503 + />
  2504 + ) : isDateTimeDataEntryField(el) ? (
  2505 + <div className="flex items-center gap-2">
  2506 + <Select
  2507 + value={row.templateDateOffsets[el.id]?.unit ?? "Days"}
  2508 + onValueChange={(unit) =>
  2509 + updateRowTemplateDateOffset(row.id, el.id, { unit })
  2510 + }
  2511 + disabled={saving}
  2512 + >
  2513 + <SelectTrigger className="h-10 min-w-0 flex-1 bg-white text-sm">
  2514 + <SelectValue />
  2515 + </SelectTrigger>
  2516 + <SelectContent>
  2517 + {LABEL_FORM_OFFSET_UNITS.map((u) => (
  2518 + <SelectItem key={u} value={u} className="text-xs">
  2519 + {u}
  2520 + </SelectItem>
  2521 + ))}
  2522 + </SelectContent>
  2523 + </Select>
  2524 + <Input
  2525 + type="number"
  2526 + className="h-10 w-20 shrink-0 bg-white"
  2527 + value={row.templateDateOffsets[el.id]?.value ?? ""}
  2528 + onChange={(e) =>
  2529 + updateRowTemplateDateOffset(row.id, el.id, {
  2530 + value: e.target.value,
  2531 + })
  2532 + }
  2533 + placeholder="Value"
  2534 + disabled={saving}
  2535 + />
  2536 + </div>
  2537 + ) : (
  2538 + <Input
  2539 + className="h-10"
  2540 + value={row.templateDataValues[el.id] ?? ""}
  2541 + onChange={(e) => updateRowTemplateText(row.id, el.id, e.target.value)}
  2542 + placeholder={`Enter ${label}`}
  2543 + disabled={saving}
  2544 + />
  2545 + )}
  2546 + </TableCell>
  2547 + );
  2548 + })}
  2549 + <TableCell className="align-top pt-4">
  2550 + <Switch
  2551 + checked={row.state}
  2552 + onCheckedChange={(checked) => updateRow(row.id, { state: checked })}
  2553 + disabled={saving}
  2554 + />
  2555 + </TableCell>
  2556 + <TableCell className="align-top text-center">
  2557 + <Button
  2558 + type="button"
  2559 + variant="ghost"
  2560 + size="icon"
  2561 + className="h-9 w-9 text-red-600 hover:bg-red-50 hover:text-red-700"
  2562 + onClick={() => removeRow(row.id)}
  2563 + disabled={saving || rows.length <= 1}
  2564 + aria-label="Delete row"
  2565 + >
  2566 + <Trash2 className="h-4 w-4" />
  2567 + </Button>
  2568 + </TableCell>
  2569 + </TableRow>
  2570 + );
  2571 + })}
  2572 + </TableBody>
  2573 + </Table>
  2574 + </div>
  2575 + )}
  2576 + </div>
  2577 + </div>
  2578 + );
  2579 +}
  2580 +
1722 function CreateLabelDialog({ 2581 function CreateLabelDialog({
1723 open, 2582 open,
1724 onOpenChange, 2583 onOpenChange,
美国版/Food Labeling Management Platform/src/components/shared/category-scope-fields.tsx
@@ -7,6 +7,8 @@ import { @@ -7,6 +7,8 @@ import {
7 locationsScopedForCategoryForm, 7 locationsScopedForCategoryForm,
8 locationsScopedForTemplateScope, 8 locationsScopedForTemplateScope,
9 regionOptionsForPartner, 9 regionOptionsForPartner,
  10 + filterScopeIdsForPartners,
  11 + partnerIdsScopeKey,
10 regionOptionsForPartners, 12 regionOptionsForPartners,
11 regionSelectionToGroupNames, 13 regionSelectionToGroupNames,
12 } from "../../lib/categoryScopeForm"; 14 } from "../../lib/categoryScopeForm";
@@ -159,15 +161,55 @@ export function CategoryScopeFields({ @@ -159,15 +161,55 @@ export function CategoryScopeFields({
159 [scopedLocations], 161 [scopedLocations],
160 ); 162 );
161 163
  164 + const clearRegionAndLocation = useCallback(() => {
  165 + onRegionIdsChange?.([]);
  166 + onRegionChange([]);
  167 + onLocationChange([]);
  168 + }, [onRegionIdsChange, onRegionChange, onLocationChange]);
  169 +
162 const onCompaniesChange = useCallback( 170 const onCompaniesChange = useCallback(
163 (nextIds: string[]) => { 171 (nextIds: string[]) => {
  172 + const prevKey = partnerIdsScopeKey(selectedPartnerIds);
  173 + const nextKey = partnerIdsScopeKey(nextIds);
164 onPartnerIdsChange?.(nextIds); 174 onPartnerIdsChange?.(nextIds);
165 - onRegionIdsChange?.([]);  
166 - onLocationChange([]); 175 + if (prevKey !== nextKey) {
  176 + clearRegionAndLocation();
  177 + }
167 }, 178 },
168 - [onPartnerIdsChange, onRegionIdsChange, onLocationChange], 179 + [selectedPartnerIds, onPartnerIdsChange, clearRegionAndLocation],
169 ); 180 );
170 181
  182 + /** 剔除不属于当前 Company 的 Region / Location 选中项(防止 UI 仍显示旧标签) */
  183 + useEffect(() => {
  184 + if (!templateScopeMode) return;
  185 + const { regionIds, locationIds } = filterScopeIdsForPartners({
  186 + partners,
  187 + groups,
  188 + locations,
  189 + partnerIds: effectivePartnerIds,
  190 + regionIds: selectedRegionIds,
  191 + locationIds: selectedLocationIds,
  192 + });
  193 + const regionChanged =
  194 + regionIds.length !== selectedRegionIds.length
  195 + || regionIds.some((id, i) => id !== selectedRegionIds[i]);
  196 + const locationChanged =
  197 + locationIds.length !== selectedLocationIds.length
  198 + || locationIds.some((id, i) => id !== selectedLocationIds[i]);
  199 + if (regionChanged) onRegionIdsChange?.(regionIds);
  200 + if (locationChanged) onLocationChange(locationIds);
  201 + }, [
  202 + templateScopeMode,
  203 + partners,
  204 + groups,
  205 + locations,
  206 + effectivePartnerIds,
  207 + selectedRegionIds,
  208 + selectedLocationIds,
  209 + onRegionIdsChange,
  210 + onLocationChange,
  211 + ]);
  212 +
171 const onRegionIdsMultiChange = useCallback( 213 const onRegionIdsMultiChange = useCallback(
172 (nextRegionIds: string[]) => { 214 (nextRegionIds: string[]) => {
173 onRegionIdsChange?.(nextRegionIds); 215 onRegionIdsChange?.(nextRegionIds);
@@ -192,11 +234,14 @@ export function CategoryScopeFields({ @@ -192,11 +234,14 @@ export function CategoryScopeFields({
192 234
193 const onCompanyChange = useCallback( 235 const onCompanyChange = useCallback(
194 (nextId: string) => { 236 (nextId: string) => {
  237 + const prev = selectedPartnerId.trim();
  238 + const next = nextId.trim();
195 onPartnerChange(nextId); 239 onPartnerChange(nextId);
196 - onRegionChange([]);  
197 - onLocationChange([]); 240 + if (prev !== next) {
  241 + clearRegionAndLocation();
  242 + }
198 }, 243 },
199 - [onPartnerChange, onRegionChange, onLocationChange], 244 + [selectedPartnerId, onPartnerChange, clearRegionAndLocation],
200 ); 245 );
201 246
202 const onRegionMultiChange = useCallback( 247 const onRegionMultiChange = useCallback(
美国版/Food Labeling Management Platform/src/lib/categoryScopeForm.ts
@@ -47,6 +47,43 @@ export function effectiveScopePartnerIds( @@ -47,6 +47,43 @@ export function effectiveScopePartnerIds(
47 return pid ? [pid] : []; 47 return pid ? [pid] : [];
48 } 48 }
49 49
  50 +/** 比较 Company 多选是否变化(忽略顺序) */
  51 +export function partnerIdsScopeKey(partnerIds: string[]): string {
  52 + return [...new Set(partnerIds.map((x) => x.trim()).filter(Boolean))].sort().join("|");
  53 +}
  54 +
  55 +/**
  56 + * 按当前选中的 Company / Region 过滤 Region、Location Id,剔除已不属于当前公司的旧值。
  57 + */
  58 +export function filterScopeIdsForPartners(input: {
  59 + partners: PartnerListItem[];
  60 + groups: GroupListItem[];
  61 + locations: LocationDto[];
  62 + partnerIds: string[];
  63 + regionIds: string[];
  64 + locationIds: string[];
  65 +}): { regionIds: string[]; locationIds: string[] } {
  66 + const availablePartnerIds = input.partners
  67 + .map((p) => String(p.id ?? "").trim())
  68 + .filter(Boolean);
  69 + const effectivePartnerIds =
  70 + input.partnerIds.length > 0 ? input.partnerIds : availablePartnerIds;
  71 + const availableRegionIdSet = new Set(
  72 + regionOptionsForPartners(input.groups, effectivePartnerIds).map((r) => r.value),
  73 + );
  74 + const regionIds = input.regionIds.filter((id) => availableRegionIdSet.has(id));
  75 + const scopedLocs = locationsScopedForTemplateScope(
  76 + input.locations,
  77 + input.partners,
  78 + input.groups,
  79 + effectivePartnerIds,
  80 + regionIds,
  81 + );
  82 + const locationIdSet = new Set(scopedLocs.map((l) => l.id));
  83 + const locationIds = input.locationIds.filter((id) => locationIdSet.has(id));
  84 + return { regionIds, locationIds };
  85 +}
  86 +
50 export type LabelingScopeSaveBody = { 87 export type LabelingScopeSaveBody = {
51 availabilityType: "ALL" | "SPECIFIED"; 88 availabilityType: "ALL" | "SPECIFIED";
52 appliedPartnerType?: AppliedScopeType; 89 appliedPartnerType?: AppliedScopeType;
@@ -85,6 +122,14 @@ export function buildLabelingScopeSaveBody(input: { @@ -85,6 +122,14 @@ export function buildLabelingScopeSaveBody(input: {
85 const partnerErr = scopePartnersValidationMessage(true, effectivePartnerIds); 122 const partnerErr = scopePartnersValidationMessage(true, effectivePartnerIds);
86 if (partnerErr) return { ok: false, message: partnerErr }; 123 if (partnerErr) return { ok: false, message: partnerErr };
87 124
  125 + const sanitized = filterScopeIdsForPartners({
  126 + partners: input.partners,
  127 + groups: input.groups,
  128 + locations: input.locations,
  129 + partnerIds: effectivePartnerIds,
  130 + regionIds: input.selectedRegionIds,
  131 + locationIds: input.selectedLocationIds,
  132 + });
88 const partnerIdsForFilter = 133 const partnerIdsForFilter =
89 effectivePartnerIds.length > 0 ? effectivePartnerIds : availablePartnerIds; 134 effectivePartnerIds.length > 0 ? effectivePartnerIds : availablePartnerIds;
90 const availableRegionIds = regionOptionsForPartners(input.groups, partnerIdsForFilter).map( 135 const availableRegionIds = regionOptionsForPartners(input.groups, partnerIdsForFilter).map(
@@ -95,14 +140,14 @@ export function buildLabelingScopeSaveBody(input: { @@ -95,14 +140,14 @@ export function buildLabelingScopeSaveBody(input: {
95 input.partners, 140 input.partners,
96 input.groups, 141 input.groups,
97 partnerIdsForFilter, 142 partnerIdsForFilter,
98 - input.selectedRegionIds, 143 + sanitized.regionIds,
99 ); 144 );
100 const availableLocationIds = scopedLocs.map((l) => l.id); 145 const availableLocationIds = scopedLocs.map((l) => l.id);
101 146
102 const scope = buildLabelTemplateScopePayload({ 147 const scope = buildLabelTemplateScopePayload({
103 selectedPartnerIds: effectivePartnerIds, 148 selectedPartnerIds: effectivePartnerIds,
104 - selectedRegionIds: input.selectedRegionIds,  
105 - selectedLocationIds: input.selectedLocationIds, 149 + selectedRegionIds: sanitized.regionIds,
  150 + selectedLocationIds: sanitized.locationIds,
106 availablePartnerIds, 151 availablePartnerIds,
107 availableRegionIds, 152 availableRegionIds,
108 availableLocationIds, 153 availableLocationIds,
@@ -619,12 +664,13 @@ function resolveScopeDimensionForSave( @@ -619,12 +664,13 @@ function resolveScopeDimensionForSave(
619 available: string[], 664 available: string[],
620 ): { type: AppliedScopeType; ids: string[] } { 665 ): { type: AppliedScopeType; ids: string[] } {
621 const avail = dedupeIds(available); 666 const avail = dedupeIds(available);
622 - const sel = dedupeIds(selected).filter((id) => !avail.length || avail.includes(id));  
623 - if (!avail.length || !sel.length) { 667 + if (!avail.length) {
624 return { type: "ALL", ids: [] }; 668 return { type: "ALL", ids: [] };
625 } 669 }
626 - if (sel.length >= avail.length && avail.every((id) => sel.includes(id))) {  
627 - return { type: "ALL", ids: [] }; 670 + const sel = dedupeIds(selected).filter((id) => avail.includes(id));
  671 + // 空选或全选当前可选项 → 展开为全部 Id,接口需显式传入 companyIds/regionIds/locationIds
  672 + if (!sel.length || (sel.length >= avail.length && avail.every((id) => sel.includes(id)))) {
  673 + return { type: "SPECIFIED", ids: avail };
628 } 674 }
629 return { type: "SPECIFIED", ids: sel }; 675 return { type: "SPECIFIED", ids: sel };
630 } 676 }
@@ -669,7 +715,7 @@ export type EntityScopePayloadBody = { @@ -669,7 +715,7 @@ export type EntityScopePayloadBody = {
669 715
670 /** 716 /**
671 * 标签类型 / 分类 / 多选项保存:Company + Region + Location 三维适用范围。 717 * 标签类型 / 分类 / 多选项保存:Company + Region + Location 三维适用范围。
672 - * 空选或全选当前可选项 → 该维度 ALL;部分选中 → SPECIFIED + Id 数组。 718 + * 空选或全选当前可选项 → 展开为全部 Id;部分选中 → 对应 Id 数组。
673 */ 719 */
674 export function buildEntityPartnerScopePayload(input: { 720 export function buildEntityPartnerScopePayload(input: {
675 selectedPartnerIds: string[]; 721 selectedPartnerIds: string[];
@@ -692,14 +738,19 @@ export function buildEntityPartnerScopePayload(input: { @@ -692,14 +738,19 @@ export function buildEntityPartnerScopePayload(input: {
692 input.availableLocationIds, 738 input.availableLocationIds,
693 ); 739 );
694 740
695 - const locationSpecified =  
696 - regionDim.type === "SPECIFIED" || locationDim.type === "SPECIFIED";  
697 - const availabilityType: "ALL" | "SPECIFIED" = locationSpecified ? "SPECIFIED" : "ALL"; 741 + const partnerIds = partnerDim.ids;
  742 + const regionIds = regionDim.ids;
  743 + const locationIds = locationDim.ids;
  744 +
  745 + const appliedPartnerType: AppliedScopeType =
  746 + partnerIds.length > 0 ? "SPECIFIED" : "ALL";
  747 + const availabilityType: "ALL" | "SPECIFIED" =
  748 + regionIds.length > 0 || locationIds.length > 0 ? "SPECIFIED" : "ALL";
698 749
699 const anySpecified = 750 const anySpecified =
700 - partnerDim.type === "SPECIFIED" || locationSpecified; 751 + appliedPartnerType === "SPECIFIED" || availabilityType === "SPECIFIED";
701 const effectiveLocationIds = 752 const effectiveLocationIds =
702 - locationDim.type === "SPECIFIED" ? locationDim.ids : input.availableLocationIds; 753 + locationIds.length > 0 ? locationIds : input.availableLocationIds;
703 754
704 if (anySpecified && effectiveLocationIds.length === 0) { 755 if (anySpecified && effectiveLocationIds.length === 0) {
705 return { 756 return {
@@ -708,14 +759,10 @@ export function buildEntityPartnerScopePayload(input: { @@ -708,14 +759,10 @@ export function buildEntityPartnerScopePayload(input: {
708 }; 759 };
709 } 760 }
710 761
711 - const partnerIds = partnerDim.type === "SPECIFIED" ? partnerDim.ids : [];  
712 - const regionIds = regionDim.type === "SPECIFIED" ? regionDim.ids : [];  
713 - const locationIds = locationDim.type === "SPECIFIED" ? locationDim.ids : [];  
714 -  
715 return { 762 return {
716 ok: true, 763 ok: true,
717 body: { 764 body: {
718 - appliedPartnerType: partnerDim.type, 765 + appliedPartnerType,
719 partnerIds, 766 partnerIds,
720 companyIds: partnerIds, 767 companyIds: partnerIds,
721 regionIds, 768 regionIds,
@@ -740,18 +787,31 @@ export function buildEntityScopeSaveFromForm(input: { @@ -740,18 +787,31 @@ export function buildEntityScopeSaveFromForm(input: {
740 groups: GroupListItem[]; 787 groups: GroupListItem[];
741 }): { ok: true; body: EntityScopePayloadBody } | { ok: false; message: string } { 788 }): { ok: true; body: EntityScopePayloadBody } | { ok: false; message: string } {
742 if (input.requireCompanySelection) { 789 if (input.requireCompanySelection) {
  790 + const effectivePartnerIds = effectiveScopePartnerIds(
  791 + true,
  792 + input.selectedPartnerIds,
  793 + "",
  794 + );
  795 + const sanitized = filterScopeIdsForPartners({
  796 + partners: input.partners,
  797 + groups: input.groups,
  798 + locations: input.locations,
  799 + partnerIds: effectivePartnerIds,
  800 + regionIds: input.selectedRegionIds,
  801 + locationIds: input.selectedLocationIds,
  802 + });
743 const { availablePartnerIds, availableRegionIds, availableLocationIds } = 803 const { availablePartnerIds, availableRegionIds, availableLocationIds } =
744 computeTemplateScopeAvailableIds( 804 computeTemplateScopeAvailableIds(
745 input.partners, 805 input.partners,
746 input.groups, 806 input.groups,
747 input.locations, 807 input.locations,
748 - input.selectedPartnerIds,  
749 - input.selectedRegionIds, 808 + effectivePartnerIds,
  809 + sanitized.regionIds,
750 ); 810 );
751 return buildEntityPartnerScopePayload({ 811 return buildEntityPartnerScopePayload({
752 - selectedPartnerIds: input.selectedPartnerIds,  
753 - selectedRegionIds: input.selectedRegionIds,  
754 - selectedLocationIds: input.selectedLocationIds, 812 + selectedPartnerIds: effectivePartnerIds,
  813 + selectedRegionIds: sanitized.regionIds,
  814 + selectedLocationIds: sanitized.locationIds,
755 availablePartnerIds, 815 availablePartnerIds,
756 availableRegionIds, 816 availableRegionIds,
757 availableLocationIds, 817 availableLocationIds,
美国版/Food Labeling Management Platform/src/lib/labelEntityScopeApi.ts 0 → 100644
  1 +/** 解析接口返回的 Company Id 列表(优先 companyIds) */
  2 +export function parseCompanyIdsFromApi(raw: Record<string, unknown>): string[] {
  3 + const parse = (v: unknown): string[] => {
  4 + if (!Array.isArray(v)) return [];
  5 + return [...new Set(v.map((x) => String(x).trim()).filter(Boolean))];
  6 + };
  7 + const fromCompany = parse(raw.companyIds ?? raw.CompanyIds);
  8 + if (fromCompany.length) return fromCompany;
  9 + return parse(raw.partnerIds ?? raw.PartnerIds);
  10 +}
  11 +
  12 +export type LabelEntityScopeInput = {
  13 + appliedPartnerType?: string | null;
  14 + partnerIds?: string[] | null;
  15 + companyIds?: string[] | null;
  16 + availabilityType?: string | null;
  17 + regionIds?: string[] | null;
  18 + groupIds?: string[] | null;
  19 + locationIds?: string[] | null;
  20 +};
  21 +
  22 +/**
  23 + * 分类 / 类型 / 多选项 保存:公司范围以 companyIds 数组为主字段,partnerIds 同步兼容。
  24 + */
  25 +export function buildLabelEntityScopeApiBody(input: LabelEntityScopeInput): Record<string, unknown> {
  26 + const companyIds = [
  27 + ...new Set(
  28 + [...(input.companyIds ?? []), ...(input.partnerIds ?? [])]
  29 + .map((x) => String(x).trim())
  30 + .filter(Boolean),
  31 + ),
  32 + ];
  33 + const groupIds = [
  34 + ...new Set(
  35 + [...(input.groupIds ?? []), ...(input.regionIds ?? [])]
  36 + .map((x) => String(x).trim())
  37 + .filter(Boolean),
  38 + ),
  39 + ];
  40 + const locationIds = [
  41 + ...new Set((input.locationIds ?? []).map((x) => String(x).trim()).filter(Boolean)),
  42 + ];
  43 +
  44 + const appliedPartnerTypeRaw = String(input.appliedPartnerType ?? "").trim().toUpperCase();
  45 + const appliedPartnerType =
  46 + appliedPartnerTypeRaw === "ALL" || appliedPartnerTypeRaw === "SPECIFIED"
  47 + ? appliedPartnerTypeRaw
  48 + : companyIds.length
  49 + ? "SPECIFIED"
  50 + : "ALL";
  51 +
  52 + const body: Record<string, unknown> = {
  53 + appliedPartnerType,
  54 + companyIds,
  55 + partnerIds: companyIds,
  56 + };
  57 +
  58 + const availabilityTypeRaw = String(input.availabilityType ?? "ALL").trim().toUpperCase();
  59 + body.availabilityType =
  60 + availabilityTypeRaw === "SPECIFIED" || groupIds.length > 0 || locationIds.length > 0
  61 + ? "SPECIFIED"
  62 + : "ALL";
  63 +
  64 + body.groupIds = groupIds;
  65 + body.regionIds = groupIds;
  66 + body.locationIds = locationIds;
  67 +
  68 + return body;
  69 +}
  70 +
  71 +export type LabelTemplateScopeInput = LabelEntityScopeInput & {
  72 + appliedRegionType?: string | null;
  73 + appliedLocation?: string | null;
  74 + appliedLocationIds?: string[] | null;
  75 +};
  76 +
  77 +/** 标签模板保存:Company / Region / Location 三维 + companyIds 数组 */
  78 +export function buildLabelTemplateScopeApiBody(
  79 + input: LabelTemplateScopeInput,
  80 +): Record<string, unknown> {
  81 + const companyIds = [
  82 + ...new Set(
  83 + [...(input.companyIds ?? []), ...(input.partnerIds ?? [])]
  84 + .map((x) => String(x).trim())
  85 + .filter(Boolean),
  86 + ),
  87 + ];
  88 + const regionIds = [
  89 + ...new Set(
  90 + [...(input.regionIds ?? []), ...(input.groupIds ?? [])]
  91 + .map((x) => String(x).trim())
  92 + .filter(Boolean),
  93 + ),
  94 + ];
  95 + const locationIds = [
  96 + ...new Set(
  97 + [...(input.locationIds ?? []), ...(input.appliedLocationIds ?? [])]
  98 + .map((x) => String(x).trim())
  99 + .filter(Boolean),
  100 + ),
  101 + ];
  102 +
  103 + const appliedPartnerType =
  104 + String(input.appliedPartnerType ?? "").trim().toUpperCase()
  105 + || (companyIds.length ? "SPECIFIED" : "ALL");
  106 + const appliedRegionType =
  107 + String(input.appliedRegionType ?? "").trim().toUpperCase()
  108 + || (regionIds.length ? "SPECIFIED" : "ALL");
  109 + const appliedLocation =
  110 + String(input.appliedLocation ?? "").trim().toUpperCase()
  111 + || (locationIds.length ? "SPECIFIED" : "ALL");
  112 +
  113 + return {
  114 + appliedPartnerType,
  115 + companyIds,
  116 + partnerIds: companyIds,
  117 + appliedRegionType,
  118 + regionIds,
  119 + groupIds: regionIds,
  120 + appliedLocation,
  121 + locationIds,
  122 + appliedLocationIds: locationIds,
  123 + };
  124 +}
美国版/Food Labeling Management Platform/src/services/labelCategoryService.ts
1 import { createApiClient } from "../lib/apiClient"; 1 import { createApiClient } from "../lib/apiClient";
2 import { serializeButtonAppearanceForApi } from "../lib/categoryButtonAppearance"; 2 import { serializeButtonAppearanceForApi } from "../lib/categoryButtonAppearance";
  3 +import {
  4 + buildLabelEntityScopeApiBody,
  5 + parseCompanyIdsFromApi,
  6 +} from "../lib/labelEntityScopeApi";
3 import type { 7 import type {
4 LabelCategoryCreateInput, 8 LabelCategoryCreateInput,
5 LabelCategoryDto, 9 LabelCategoryDto,
@@ -28,7 +32,8 @@ function normalizeLabelCategoryDto(raw: unknown): LabelCategoryDto { @@ -28,7 +32,8 @@ function normalizeLabelCategoryDto(raw: unknown): LabelCategoryDto {
28 }; 32 };
29 const groupIds = parseIds(r.groupIds ?? r.GroupIds ?? r.regionIds ?? r.RegionIds); 33 const groupIds = parseIds(r.groupIds ?? r.GroupIds ?? r.regionIds ?? r.RegionIds);
30 const locationIds = parseIds(r.locationIds ?? r.LocationIds); 34 const locationIds = parseIds(r.locationIds ?? r.LocationIds);
31 - const partnerIds = parseIds(r.partnerIds ?? r.PartnerIds ?? r.companyIds ?? r.CompanyIds); 35 + const companyIds = parseCompanyIdsFromApi(r);
  36 + const partnerIds = companyIds;
32 const noRaw = r.noOfLabels ?? r.NoOfLabels; 37 const noRaw = r.noOfLabels ?? r.NoOfLabels;
33 const noOfLabels = 38 const noOfLabels =
34 typeof noRaw === "number" && Number.isFinite(noRaw) 39 typeof noRaw === "number" && Number.isFinite(noRaw)
@@ -49,7 +54,7 @@ function normalizeLabelCategoryDto(raw: unknown): LabelCategoryDto { @@ -49,7 +54,7 @@ function normalizeLabelCategoryDto(raw: unknown): LabelCategoryDto {
49 id: String(r.id ?? r.Id ?? ""), 54 id: String(r.id ?? r.Id ?? ""),
50 appliedPartnerType: String(r.appliedPartnerType ?? r.AppliedPartnerType ?? "").trim() || undefined, 55 appliedPartnerType: String(r.appliedPartnerType ?? r.AppliedPartnerType ?? "").trim() || undefined,
51 partnerIds, 56 partnerIds,
52 - companyIds: partnerIds, 57 + companyIds,
53 availabilityType: String(r.availabilityType ?? r.AvailabilityType ?? "").trim() || undefined, 58 availabilityType: String(r.availabilityType ?? r.AvailabilityType ?? "").trim() || undefined,
54 groupIds, 59 groupIds,
55 regionIds: groupIds, 60 regionIds: groupIds,
@@ -61,42 +66,7 @@ function normalizeLabelCategoryDto(raw: unknown): LabelCategoryDto { @@ -61,42 +66,7 @@ function normalizeLabelCategoryDto(raw: unknown): LabelCategoryDto {
61 } 66 }
62 67
63 function scopeBodyFromInput(input: LabelCategoryCreateInput): Record<string, unknown> { 68 function scopeBodyFromInput(input: LabelCategoryCreateInput): Record<string, unknown> {
64 - const groupIds = [  
65 - ...new Set(  
66 - [...(input.groupIds ?? []), ...(input.regionIds ?? [])]  
67 - .map((x) => String(x).trim())  
68 - .filter(Boolean),  
69 - ),  
70 - ];  
71 - const locationIds = [  
72 - ...new Set((input.locationIds ?? []).map((x) => String(x).trim()).filter(Boolean)),  
73 - ];  
74 - const partnerIds = [  
75 - ...new Set(  
76 - [...(input.partnerIds ?? []), ...(input.companyIds ?? [])]  
77 - .map((x) => String(x).trim())  
78 - .filter(Boolean),  
79 - ),  
80 - ];  
81 - const body: Record<string, unknown> = {};  
82 - const appliedPartnerType = String(input.appliedPartnerType ?? "").trim().toUpperCase();  
83 - if (appliedPartnerType === "ALL" || appliedPartnerType === "SPECIFIED") {  
84 - body.appliedPartnerType = appliedPartnerType;  
85 - }  
86 - if (partnerIds.length) {  
87 - body.partnerIds = partnerIds;  
88 - body.companyIds = partnerIds;  
89 - }  
90 - const availabilityType = String(input.availabilityType ?? "ALL").trim().toUpperCase() || "ALL";  
91 - body.availabilityType = availabilityType;  
92 - if (groupIds.length) {  
93 - body.groupIds = groupIds;  
94 - body.regionIds = groupIds;  
95 - }  
96 - if (locationIds.length) {  
97 - body.locationIds = locationIds;  
98 - }  
99 - return body; 69 + return buildLabelEntityScopeApiBody(input);
100 } 70 }
101 71
102 export async function getLabelCategories(input: LabelCategoryGetListInput, signal?: AbortSignal): Promise<PagedResultDto<LabelCategoryDto>> { 72 export async function getLabelCategories(input: LabelCategoryGetListInput, signal?: AbortSignal): Promise<PagedResultDto<LabelCategoryDto>> {
美国版/Food Labeling Management Platform/src/services/labelMultipleOptionService.ts
1 import { createApiClient } from "../lib/apiClient"; 1 import { createApiClient } from "../lib/apiClient";
  2 +import {
  3 + buildLabelEntityScopeApiBody,
  4 + parseCompanyIdsFromApi,
  5 +} from "../lib/labelEntityScopeApi";
2 import type { 6 import type {
3 LabelMultipleOptionCreateInput, 7 LabelMultipleOptionCreateInput,
4 LabelMultipleOptionDto, 8 LabelMultipleOptionDto,
@@ -63,12 +67,8 @@ function normalizeLabelMultipleOptionDto(item: LabelMultipleOptionDto): LabelMul @@ -63,12 +67,8 @@ function normalizeLabelMultipleOptionDto(item: LabelMultipleOptionDto): LabelMul
63 const locationIds = parseIds( 67 const locationIds = parseIds(
64 (raw as Record<string, unknown>).locationIds ?? (raw as Record<string, unknown>).LocationIds, 68 (raw as Record<string, unknown>).locationIds ?? (raw as Record<string, unknown>).LocationIds,
65 ); 69 );
66 - const partnerIds = parseIds(  
67 - (raw as Record<string, unknown>).partnerIds ??  
68 - (raw as Record<string, unknown>).PartnerIds ??  
69 - (raw as Record<string, unknown>).companyIds ??  
70 - (raw as Record<string, unknown>).CompanyIds,  
71 - ); 70 + const partnerIds = parseCompanyIdsFromApi(raw as Record<string, unknown>);
  71 + const companyIds = partnerIds;
72 const companyRaw = (raw as Record<string, unknown>).company ?? (raw as Record<string, unknown>).Company; 72 const companyRaw = (raw as Record<string, unknown>).company ?? (raw as Record<string, unknown>).Company;
73 return { 73 return {
74 ...item, 74 ...item,
@@ -81,7 +81,7 @@ function normalizeLabelMultipleOptionDto(item: LabelMultipleOptionDto): LabelMul @@ -81,7 +81,7 @@ function normalizeLabelMultipleOptionDto(item: LabelMultipleOptionDto): LabelMul
81 "", 81 "",
82 ).trim() || undefined, 82 ).trim() || undefined,
83 partnerIds, 83 partnerIds,
84 - companyIds: partnerIds, 84 + companyIds,
85 availabilityType: 85 availabilityType:
86 String( 86 String(
87 (raw as Record<string, unknown>).availabilityType ?? 87 (raw as Record<string, unknown>).availabilityType ??
@@ -108,44 +108,7 @@ function optionValuesJsonToApiBody(values: string[]): string { @@ -108,44 +108,7 @@ function optionValuesJsonToApiBody(values: string[]): string {
108 } 108 }
109 109
110 function scopeBodyFromInput(input: LabelMultipleOptionCreateInput): Record<string, unknown> { 110 function scopeBodyFromInput(input: LabelMultipleOptionCreateInput): Record<string, unknown> {
111 - const groupIds = [  
112 - ...new Set(  
113 - [...(input.groupIds ?? []), ...(input.regionIds ?? [])]  
114 - .map((x) => String(x).trim())  
115 - .filter(Boolean),  
116 - ),  
117 - ];  
118 - const locationIds = [  
119 - ...new Set((input.locationIds ?? []).map((x) => String(x).trim()).filter(Boolean)),  
120 - ];  
121 - const partnerIds = [  
122 - ...new Set(  
123 - [...(input.partnerIds ?? []), ...(input.companyIds ?? [])]  
124 - .map((x) => String(x).trim())  
125 - .filter(Boolean),  
126 - ),  
127 - ];  
128 - const body: Record<string, unknown> = {};  
129 - const appliedPartnerType = String(input.appliedPartnerType ?? "").trim().toUpperCase();  
130 - if (appliedPartnerType === "ALL" || appliedPartnerType === "SPECIFIED") {  
131 - body.appliedPartnerType = appliedPartnerType;  
132 - }  
133 - if (partnerIds.length) {  
134 - body.partnerIds = partnerIds;  
135 - body.companyIds = partnerIds;  
136 - }  
137 - const availabilityType = String(input.availabilityType ?? "").trim().toUpperCase();  
138 - if (availabilityType === "ALL" || availabilityType === "SPECIFIED") {  
139 - body.availabilityType = availabilityType;  
140 - }  
141 - if (groupIds.length) {  
142 - body.groupIds = groupIds;  
143 - body.regionIds = groupIds;  
144 - }  
145 - if (locationIds.length) {  
146 - body.locationIds = locationIds;  
147 - }  
148 - return body; 111 + return buildLabelEntityScopeApiBody(input);
149 } 112 }
150 113
151 export async function getLabelMultipleOptions(input: LabelMultipleOptionGetListInput, signal?: AbortSignal): Promise<PagedResultDto<LabelMultipleOptionDto>> { 114 export async function getLabelMultipleOptions(input: LabelMultipleOptionGetListInput, signal?: AbortSignal): Promise<PagedResultDto<LabelMultipleOptionDto>> {
美国版/Food Labeling Management Platform/src/services/labelTemplateService.ts
1 import { createApiClient } from "../lib/apiClient"; 1 import { createApiClient } from "../lib/apiClient";
2 import { 2 import {
  3 + buildLabelTemplateScopeApiBody,
  4 + parseCompanyIdsFromApi,
  5 +} from "../lib/labelEntityScopeApi";
  6 +import {
3 stripLabelConfigPrefixes, 7 stripLabelConfigPrefixes,
4 normalizeTemplateBorder, 8 normalizeTemplateBorder,
5 normalizePrintOrientation, 9 normalizePrintOrientation,
@@ -166,12 +170,13 @@ function normalizeLabelTemplateDto(raw: unknown): LabelTemplateDto { @@ -166,12 +170,13 @@ function normalizeLabelTemplateDto(raw: unknown): LabelTemplateDto {
166 const regionIds = parseIdList(r.regionIds ?? r.RegionIds); 170 const regionIds = parseIdList(r.regionIds ?? r.RegionIds);
167 const groupIds = parseIdList(r.groupIds ?? r.GroupIds); 171 const groupIds = parseIdList(r.groupIds ?? r.GroupIds);
168 const locationIds = parseIdList(r.locationIds ?? r.LocationIds); 172 const locationIds = parseIdList(r.locationIds ?? r.LocationIds);
169 - const partnerIds = parseIdList(r.partnerIds ?? r.PartnerIds ?? r.companyIds ?? r.CompanyIds); 173 + const partnerIds = parseCompanyIdsFromApi(r);
  174 + const mergedPartnerIds = partnerIds;
  175 + const companyIds = partnerIds;
170 const mergedRegionIds = [...new Set([...regionIds, ...groupIds])]; 176 const mergedRegionIds = [...new Set([...regionIds, ...groupIds])];
171 const mergedLocationIds = [ 177 const mergedLocationIds = [
172 ...new Set([...locationIds, ...appliedLocationIds]), 178 ...new Set([...locationIds, ...appliedLocationIds]),
173 ]; 179 ];
174 - const mergedPartnerIds = partnerIds;  
175 const appliedPartnerTypeRaw = r.appliedPartnerType ?? r.AppliedPartnerType; 180 const appliedPartnerTypeRaw = r.appliedPartnerType ?? r.AppliedPartnerType;
176 const appliedRegionTypeRaw = r.appliedRegionType ?? r.AppliedRegionType; 181 const appliedRegionTypeRaw = r.appliedRegionType ?? r.AppliedRegionType;
177 const appliedLocationTypeRaw = 182 const appliedLocationTypeRaw =
@@ -230,7 +235,7 @@ function normalizeLabelTemplateDto(raw: unknown): LabelTemplateDto { @@ -230,7 +235,7 @@ function normalizeLabelTemplateDto(raw: unknown): LabelTemplateDto {
230 lastEdited: (typeof lastEditedVo === "string" ? lastEditedVo : null) ?? (r.lastEdited as string | null), 235 lastEdited: (typeof lastEditedVo === "string" ? lastEditedVo : null) ?? (r.lastEdited as string | null),
231 appliedLocationIds: mergedLocationIds.length ? mergedLocationIds : appliedLocationIds, 236 appliedLocationIds: mergedLocationIds.length ? mergedLocationIds : appliedLocationIds,
232 partnerIds: mergedPartnerIds, 237 partnerIds: mergedPartnerIds,
233 - companyIds: mergedPartnerIds, 238 + companyIds,
234 regionIds: mergedRegionIds, 239 regionIds: mergedRegionIds,
235 groupIds: mergedRegionIds, 240 groupIds: mergedRegionIds,
236 locationIds: mergedLocationIds, 241 locationIds: mergedLocationIds,
@@ -274,31 +279,7 @@ export async function getLabelTemplate(templateCode: string, signal?: AbortSigna @@ -274,31 +279,7 @@ export async function getLabelTemplate(templateCode: string, signal?: AbortSigna
274 } 279 }
275 280
276 function buildLabelTemplateScopeBody(input: LabelTemplateCreateInput): Record<string, unknown> { 281 function buildLabelTemplateScopeBody(input: LabelTemplateCreateInput): Record<string, unknown> {
277 - const partnerIds = [  
278 - ...new Set(  
279 - [...(input.partnerIds ?? []), ...(input.companyIds ?? [])]  
280 - .map((x) => String(x).trim())  
281 - .filter(Boolean),  
282 - ),  
283 - ];  
284 - const regionIds = [  
285 - ...new Set(  
286 - [...(input.regionIds ?? []), ...(input.groupIds ?? [])]  
287 - .map((x) => String(x).trim())  
288 - .filter(Boolean),  
289 - ),  
290 - ];  
291 - const locationIds = [  
292 - ...new Set(  
293 - [...(input.locationIds ?? []), ...(input.appliedLocationIds ?? [])]  
294 - .map((x) => String(x).trim())  
295 - .filter(Boolean),  
296 - ),  
297 - ];  
298 - const appliedPartnerType = String(input.appliedPartnerType ?? "").trim().toUpperCase() || (partnerIds.length ? "SPECIFIED" : "ALL");  
299 - const appliedRegionType = String(input.appliedRegionType ?? "").trim().toUpperCase() || (regionIds.length ? "SPECIFIED" : "ALL");  
300 - const appliedLocation = String(input.appliedLocation ?? "").trim().toUpperCase() || (locationIds.length ? "SPECIFIED" : "ALL");  
301 - 282 + const scope = buildLabelTemplateScopeApiBody(input);
302 const body: Record<string, unknown> = { 283 const body: Record<string, unknown> = {
303 id: input.id, 284 id: input.id,
304 name: input.name, 285 name: input.name,
@@ -306,9 +287,7 @@ function buildLabelTemplateScopeBody(input: LabelTemplateCreateInput): Record&lt;st @@ -306,9 +287,7 @@ function buildLabelTemplateScopeBody(input: LabelTemplateCreateInput): Record&lt;st
306 unit: input.unit, 287 unit: input.unit,
307 width: input.width, 288 width: input.width,
308 height: input.height, 289 height: input.height,
309 - appliedPartnerType,  
310 - appliedRegionType,  
311 - appliedLocation, 290 + ...scope,
312 showRuler: input.showRuler ?? true, 291 showRuler: input.showRuler ?? true,
313 showGrid: input.showGrid ?? true, 292 showGrid: input.showGrid ?? true,
314 border: normalizeTemplateBorder(input.border), 293 border: normalizeTemplateBorder(input.border),
@@ -321,30 +300,6 @@ function buildLabelTemplateScopeBody(input: LabelTemplateCreateInput): Record&lt;st @@ -321,30 +300,6 @@ function buildLabelTemplateScopeBody(input: LabelTemplateCreateInput): Record&lt;st
321 body.contents = input.contents; 300 body.contents = input.contents;
322 } 301 }
323 302
324 - if (appliedPartnerType === "SPECIFIED" && partnerIds.length) {  
325 - body.partnerIds = partnerIds;  
326 - body.companyIds = partnerIds;  
327 - } else {  
328 - body.partnerIds = [];  
329 - body.companyIds = [];  
330 - }  
331 -  
332 - if (appliedRegionType === "SPECIFIED" && regionIds.length) {  
333 - body.regionIds = regionIds;  
334 - body.groupIds = regionIds;  
335 - } else {  
336 - body.regionIds = [];  
337 - body.groupIds = [];  
338 - }  
339 -  
340 - if (appliedLocation === "SPECIFIED" && locationIds.length) {  
341 - body.locationIds = locationIds;  
342 - body.appliedLocationIds = locationIds;  
343 - } else {  
344 - body.locationIds = [];  
345 - body.appliedLocationIds = [];  
346 - }  
347 -  
348 return body; 303 return body;
349 } 304 }
350 305
美国版/Food Labeling Management Platform/src/services/labelTypeService.ts
1 import { createApiClient } from "../lib/apiClient"; 1 import { createApiClient } from "../lib/apiClient";
  2 +import {
  3 + buildLabelEntityScopeApiBody,
  4 + parseCompanyIdsFromApi,
  5 +} from "../lib/labelEntityScopeApi";
2 import type { 6 import type {
3 LabelTypeCreateInput, 7 LabelTypeCreateInput,
4 LabelTypeDto, 8 LabelTypeDto,
@@ -27,7 +31,8 @@ function normalizeLabelTypeDto(raw: unknown): LabelTypeDto { @@ -27,7 +31,8 @@ function normalizeLabelTypeDto(raw: unknown): LabelTypeDto {
27 }; 31 };
28 const groupIds = parseIds(r.groupIds ?? r.GroupIds ?? r.regionIds ?? r.RegionIds); 32 const groupIds = parseIds(r.groupIds ?? r.GroupIds ?? r.regionIds ?? r.RegionIds);
29 const locationIds = parseIds(r.locationIds ?? r.LocationIds); 33 const locationIds = parseIds(r.locationIds ?? r.LocationIds);
30 - const partnerIds = parseIds(r.partnerIds ?? r.PartnerIds ?? r.companyIds ?? r.CompanyIds); 34 + const companyIds = parseCompanyIdsFromApi(r);
  35 + const partnerIds = companyIds;
31 const appliedPartnerType = String(r.appliedPartnerType ?? r.AppliedPartnerType ?? "").trim() || undefined; 36 const appliedPartnerType = String(r.appliedPartnerType ?? r.AppliedPartnerType ?? "").trim() || undefined;
32 const availabilityType = String(r.availabilityType ?? r.AvailabilityType ?? "").trim() || undefined; 37 const availabilityType = String(r.availabilityType ?? r.AvailabilityType ?? "").trim() || undefined;
33 const companyRaw = r.company ?? r.Company; 38 const companyRaw = r.company ?? r.Company;
@@ -52,7 +57,7 @@ function normalizeLabelTypeDto(raw: unknown): LabelTypeDto { @@ -52,7 +57,7 @@ function normalizeLabelTypeDto(raw: unknown): LabelTypeDto {
52 id: String(r.id ?? r.Id ?? ""), 57 id: String(r.id ?? r.Id ?? ""),
53 appliedPartnerType, 58 appliedPartnerType,
54 partnerIds, 59 partnerIds,
55 - companyIds: partnerIds, 60 + companyIds,
56 availabilityType, 61 availabilityType,
57 groupIds, 62 groupIds,
58 regionIds: groupIds, 63 regionIds: groupIds,
@@ -66,44 +71,7 @@ function normalizeLabelTypeDto(raw: unknown): LabelTypeDto { @@ -66,44 +71,7 @@ function normalizeLabelTypeDto(raw: unknown): LabelTypeDto {
66 } 71 }
67 72
68 function scopeBodyFromInput(input: LabelTypeCreateInput): Record<string, unknown> { 73 function scopeBodyFromInput(input: LabelTypeCreateInput): Record<string, unknown> {
69 - const groupIds = [  
70 - ...new Set(  
71 - [...(input.groupIds ?? []), ...(input.regionIds ?? [])]  
72 - .map((x) => String(x).trim())  
73 - .filter(Boolean),  
74 - ),  
75 - ];  
76 - const locationIds = [  
77 - ...new Set((input.locationIds ?? []).map((x) => String(x).trim()).filter(Boolean)),  
78 - ];  
79 - const partnerIds = [  
80 - ...new Set(  
81 - [...(input.partnerIds ?? []), ...(input.companyIds ?? [])]  
82 - .map((x) => String(x).trim())  
83 - .filter(Boolean),  
84 - ),  
85 - ];  
86 - const body: Record<string, unknown> = {};  
87 - const appliedPartnerType = String(input.appliedPartnerType ?? "").trim().toUpperCase();  
88 - if (appliedPartnerType === "ALL" || appliedPartnerType === "SPECIFIED") {  
89 - body.appliedPartnerType = appliedPartnerType;  
90 - }  
91 - if (partnerIds.length) {  
92 - body.partnerIds = partnerIds;  
93 - body.companyIds = partnerIds;  
94 - }  
95 - const availabilityType = String(input.availabilityType ?? "").trim().toUpperCase();  
96 - if (availabilityType === "ALL" || availabilityType === "SPECIFIED") {  
97 - body.availabilityType = availabilityType;  
98 - }  
99 - if (groupIds.length) {  
100 - body.groupIds = groupIds;  
101 - body.regionIds = groupIds;  
102 - }  
103 - if (locationIds.length) {  
104 - body.locationIds = locationIds;  
105 - }  
106 - return body; 74 + return buildLabelEntityScopeApiBody(input);
107 } 75 }
108 76
109 export async function getLabelTypes(input: LabelTypeGetListInput, signal?: AbortSignal): Promise<PagedResultDto<LabelTypeDto>> { 77 export async function getLabelTypes(input: LabelTypeGetListInput, signal?: AbortSignal): Promise<PagedResultDto<LabelTypeDto>> {
美国版/Food Labeling Management Platform/src/types/labelTemplate.ts
@@ -1025,19 +1025,20 @@ function resolveScopeDimensionForSave( @@ -1025,19 +1025,20 @@ function resolveScopeDimensionForSave(
1025 available: string[], 1025 available: string[],
1026 ): { type: AppliedScopeType; ids: string[] } { 1026 ): { type: AppliedScopeType; ids: string[] } {
1027 const avail = dedupeIdList(available); 1027 const avail = dedupeIdList(available);
1028 - const sel = dedupeIdList(selected).filter((id) => !avail.length || avail.includes(id));  
1029 - if (!avail.length || !sel.length) { 1028 + if (!avail.length) {
1030 return { type: 'ALL', ids: [] }; 1029 return { type: 'ALL', ids: [] };
1031 } 1030 }
1032 - if (sel.length >= avail.length && avail.every((id) => sel.includes(id))) {  
1033 - return { type: 'ALL', ids: [] }; 1031 + const sel = dedupeIdList(selected).filter((id) => avail.includes(id));
  1032 + // 空选或全选当前可选项 → 展开为全部 Id
  1033 + if (!sel.length || (sel.length >= avail.length && avail.every((id) => sel.includes(id)))) {
  1034 + return { type: 'SPECIFIED', ids: avail };
1034 } 1035 }
1035 return { type: 'SPECIFIED', ids: sel }; 1036 return { type: 'SPECIFIED', ids: sel };
1036 } 1037 }
1037 1038
1038 /** 1039 /**
1039 * 6-4:模板保存 Body 中的 Company / Region / Location 三维适用范围。 1040 * 6-4:模板保存 Body 中的 Company / Region / Location 三维适用范围。
1040 - * 空选或全选当前可选项 → 该维度 ALL + 空数组;部分选中 → SPECIFIED + Id 数组。 1041 + * 空选或全选当前可选项 → 展开为全部 Id;部分选中 → 对应 Id 数组。
1041 */ 1042 */
1042 export function buildLabelTemplateScopePayload(input: { 1043 export function buildLabelTemplateScopePayload(input: {
1043 selectedPartnerIds: string[]; 1044 selectedPartnerIds: string[];
@@ -1060,12 +1061,23 @@ export function buildLabelTemplateScopePayload(input: { @@ -1060,12 +1061,23 @@ export function buildLabelTemplateScopePayload(input: {
1060 input.availableLocationIds, 1061 input.availableLocationIds,
1061 ); 1062 );
1062 1063
  1064 + const partnerIds = partnerDim.ids;
  1065 + const regionIds = regionDim.ids;
  1066 + const locationIds = locationDim.ids;
  1067 +
  1068 + const appliedPartnerType: AppliedScopeType =
  1069 + partnerIds.length > 0 ? 'SPECIFIED' : 'ALL';
  1070 + const appliedRegionType: AppliedScopeType =
  1071 + regionIds.length > 0 ? 'SPECIFIED' : 'ALL';
  1072 + const appliedLocation: AppliedLocation =
  1073 + locationIds.length > 0 ? 'SPECIFIED' : 'ALL';
  1074 +
1063 const anySpecified = 1075 const anySpecified =
1064 - partnerDim.type === 'SPECIFIED'  
1065 - || regionDim.type === 'SPECIFIED'  
1066 - || locationDim.type === 'SPECIFIED'; 1076 + appliedPartnerType === 'SPECIFIED'
  1077 + || appliedRegionType === 'SPECIFIED'
  1078 + || appliedLocation === 'SPECIFIED';
1067 const effectiveLocationIds = 1079 const effectiveLocationIds =
1068 - locationDim.type === 'SPECIFIED' ? locationDim.ids : input.availableLocationIds; 1080 + locationIds.length > 0 ? locationIds : input.availableLocationIds;
1069 1081
1070 if (anySpecified && effectiveLocationIds.length === 0) { 1082 if (anySpecified && effectiveLocationIds.length === 0) {
1071 return { 1083 return {
@@ -1074,20 +1086,16 @@ export function buildLabelTemplateScopePayload(input: { @@ -1074,20 +1086,16 @@ export function buildLabelTemplateScopePayload(input: {
1074 }; 1086 };
1075 } 1087 }
1076 1088
1077 - const partnerIds = partnerDim.type === 'SPECIFIED' ? partnerDim.ids : [];  
1078 - const regionIds = regionDim.type === 'SPECIFIED' ? regionDim.ids : [];  
1079 - const locationIds = locationDim.type === 'SPECIFIED' ? locationDim.ids : [];  
1080 -  
1081 return { 1089 return {
1082 ok: true, 1090 ok: true,
1083 body: { 1091 body: {
1084 - appliedPartnerType: partnerDim.type, 1092 + appliedPartnerType,
1085 partnerIds, 1093 partnerIds,
1086 companyIds: partnerIds, 1094 companyIds: partnerIds,
1087 - appliedRegionType: regionDim.type, 1095 + appliedRegionType,
1088 regionIds, 1096 regionIds,
1089 groupIds: regionIds, 1097 groupIds: regionIds,
1090 - appliedLocation: locationDim.type, 1098 + appliedLocation,
1091 locationIds, 1099 locationIds,
1092 appliedLocationIds: locationIds, 1100 appliedLocationIds: locationIds,
1093 }, 1101 },