FPSMS-frontend
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符
 
 

4718 行
173 KiB

  1. "use client";
  2. import { FLOOR_A_KEY, FLOOR_B_KEY, FLOOR_C_KEY, FLOOR_D_KEY } from "@/config/demoFloors";
  3. import { useUiText } from "@/i18n/useUiText";
  4. import {
  5. Box,
  6. Button,
  7. Stack,
  8. TextField,
  9. Typography,
  10. Alert,
  11. CircularProgress,
  12. Autocomplete,
  13. Table,
  14. TableBody,
  15. TableCell,
  16. TableContainer,
  17. TableHead,
  18. TableRow,
  19. Paper,
  20. Checkbox,
  21. TablePagination,
  22. Modal,
  23. } from "@mui/material";
  24. import TestQrCodeProvider from "../QrCodeScannerProvider/TestQrCodeProvider";
  25. import {
  26. useCallback,
  27. useEffect,
  28. useState,
  29. useRef,
  30. useMemo,
  31. startTransition,
  32. } from "react";
  33. import { useTranslation } from "react-i18next";
  34. import { useRouter } from "next/navigation";
  35. import {
  36. updateStockOutLineStatus,
  37. createStockOutLine,
  38. //applyPickExecutionHoldAndChecked,
  39. fetchFGPickOrdersByUserIdWorkbench,
  40. FGPickOrderResponse,
  41. autoAssignAndReleasePickOrder,
  42. AutoAssignReleaseResponse,
  43. checkPickOrderCompletion,
  44. PickOrderCompletionResponse,
  45. confirmLotSubstitution,
  46. updateStockOutLineStatusByQRCodeAndLotNo, // ✅ 添加
  47. } from "@/app/api/pickOrder/actions";
  48. // 修改:使用 Job Order API
  49. import {
  50. fetchJobOrderLotsHierarchicalByPickOrderIdWorkbench,
  51. updateJoPickOrderHandledBy,
  52. JobOrderLotsHierarchicalWorkbenchResponse,
  53. applyPickExecutionHoldAndChecked,
  54. PrintPickRecord,
  55. } from "@/app/api/jo/actions";
  56. import { assignJobOrderPickOrderForWorkbench } from "@/app/api/jo/workbenchActions";
  57. import { fetchNameList, NameList } from "@/app/api/user/actions";
  58. import { FormProvider, useForm } from "react-hook-form";
  59. import SearchBox, { Criterion } from "../SearchBox";
  60. import { CreateStockOutLine } from "@/app/api/pickOrder/actions";
  61. import {
  62. updateInventoryLotLineQuantities,
  63. analyzeQrCode,
  64. fetchLotDetail,
  65. } from "@/app/api/inventory/actions";
  66. import QrCodeIcon from "@mui/icons-material/QrCode";
  67. import { useQrCodeScannerContext } from "../QrCodeScannerProvider/QrCodeScannerProvider";
  68. import { useSession } from "next-auth/react";
  69. import { SessionWithTokens } from "@/config/authConfig";
  70. import { fetchStockInLineInfo } from "@/app/api/po/actions";
  71. import GoodPickExecutionForm from "../Jodetail/JobPickExecutionForm";
  72. import FGPickOrderCard from "../Jodetail/FGPickOrderCard";
  73. import WorkbenchLotLabelPrintModal from "@/components/DoWorkbench/WorkbenchLotLabelPrintModal";
  74. import LinearProgressWithLabel from "../common/LinearProgressWithLabel";
  75. import ScanStatusAlert from "../common/ScanStatusAlert";
  76. import {
  77. workbenchBatchScanPick,
  78. workbenchScanPick,
  79. } from "@/app/api/doworkbench/actions";
  80. import type { PrinterCombo } from "@/app/api/settings/printer";
  81. import { msg, msgError } from "@/components/Swal/CustomAlerts";
  82. import {
  83. buildPrintPickRecordRequest,
  84. promptAllFloorsPlasticBoxCartonQty,
  85. promptPlasticBoxCartonQty,
  86. type PickRecordFloor,
  87. } from "@/components/Jodetail/pickRecordHelpers";
  88. interface Props {
  89. filterArgs: Record<string, any>;
  90. //onSwitchToRecordTab: () => void;
  91. onBackToList?: () => void;
  92. printerCombo?: PrinterCombo[];
  93. }
  94. /** 過期批號:與 noLot 類似——單筆/批量預設 0,除非 Issue 改數(對齊 GoodPickExecutiondetail) */
  95. function isLotAvailabilityExpired(lot: any): boolean {
  96. return String(lot?.lotAvailability || "").toLowerCase() === "expired";
  97. }
  98. /** inventory_lot_line.status = unavailable(API 可能用 lotAvailability 或 lotStatus) */
  99. function isInventoryLotLineUnavailable(lot: any): boolean {
  100. if (!lot) return false;
  101. if (lot.lotAvailability === "status_unavailable") return true;
  102. return String(lot.lotStatus || "").toLowerCase() === "unavailable";
  103. }
  104. /** 同 DO Workbench:多行時優先替換有建議批號的行 */
  105. function pickExpectedLotForSubstitution(
  106. activeSuggestedLots: any[],
  107. ): any | null {
  108. if (!activeSuggestedLots?.length) return null;
  109. const withLotNo = activeSuggestedLots.filter(
  110. (l) => l.lotNo != null && String(l.lotNo).trim() !== "",
  111. );
  112. if (withLotNo.length === 1) return withLotNo[0];
  113. if (withLotNo.length > 1) {
  114. const pending = withLotNo.find(
  115. (l) => String(l.stockOutLineStatus || "").toLowerCase() === "pending",
  116. );
  117. return pending || withLotNo[0];
  118. }
  119. return activeSuggestedLots[0];
  120. }
  121. type PickOrderT = (key: string, options?: Record<string, unknown>) => string;
  122. /** 與 DO Workbench:優先顯示 scan-pick 暫存拒絕訊息 */
  123. function buildLotRejectDisplayMessage(
  124. lot: any,
  125. scanRejectBySolId: Record<number, string>,
  126. t: PickOrderT,
  127. ): string | undefined {
  128. const solId = Number(lot.stockOutLineId) || 0;
  129. const fromScan = solId > 0 ? scanRejectBySolId[solId]?.trim() : "";
  130. if (fromScan) return fromScan;
  131. const fromApi =
  132. typeof lot.stockOutLineRejectMessage === "string"
  133. ? lot.stockOutLineRejectMessage.trim()
  134. : "";
  135. if (fromApi) return fromApi;
  136. const st = String(lot.stockOutLineStatus || "").toLowerCase();
  137. const av = String(lot.lotAvailability || "").toLowerCase();
  138. const isRejected = st === "rejected" || av === "rejected";
  139. if (!isRejected) return undefined;
  140. if (isLotAvailabilityExpired(lot) || av === "expired") {
  141. return t("Rejected: lot expired or no longer valid.");
  142. }
  143. if (av === "insufficient_stock") {
  144. return t("Rejected: no remaining quantity / empty lot.");
  145. }
  146. if (isInventoryLotLineUnavailable(lot) || av === "status_unavailable") {
  147. return t("Rejected: lot unavailable or not yet putaway.");
  148. }
  149. return t("Pick was rejected. Please scan another lot or check stock.");
  150. }
  151. const JO_ISSUE_PICKED_KEY = (pickOrderId: number) =>
  152. `fpsms-jo-issuePickedQty:${pickOrderId}`;
  153. function loadIssuePickedMapJo(pickOrderId: number): Record<number, number> {
  154. if (typeof window === "undefined" || !pickOrderId) return {};
  155. try {
  156. const raw = sessionStorage.getItem(JO_ISSUE_PICKED_KEY(pickOrderId));
  157. if (!raw) return {};
  158. const parsed = JSON.parse(raw) as Record<string, number>;
  159. const out: Record<number, number> = {};
  160. Object.entries(parsed).forEach(([k, v]) => {
  161. const n = Number(v);
  162. if (!Number.isNaN(n)) out[Number(k)] = n;
  163. });
  164. return out;
  165. } catch {
  166. return {};
  167. }
  168. }
  169. function saveIssuePickedMapJo(
  170. pickOrderId: number,
  171. map: Record<number, number>,
  172. ) {
  173. if (typeof window === "undefined" || !pickOrderId) return;
  174. try {
  175. sessionStorage.setItem(
  176. JO_ISSUE_PICKED_KEY(pickOrderId),
  177. JSON.stringify(map),
  178. );
  179. } catch {
  180. // ignore quota / private mode
  181. }
  182. }
  183. // Manual Lot Confirmation Modal (align with GoodPickExecutiondetail, opened by {2fic})
  184. const ManualLotConfirmationModal: React.FC<{
  185. open: boolean;
  186. onClose: () => void;
  187. onConfirm: (expectedLotNo: string, scannedLotNo: string) => void;
  188. expectedLot: { lotNo: string; itemCode: string; itemName: string } | null;
  189. scannedLot: { lotNo: string; itemCode: string; itemName: string } | null;
  190. isLoading?: boolean;
  191. }> = ({
  192. open,
  193. onClose,
  194. onConfirm,
  195. expectedLot,
  196. scannedLot,
  197. isLoading = false,
  198. }) => {
  199. const { t } = useTranslation("jo");
  200. const [expectedLotInput, setExpectedLotInput] = useState<string>("");
  201. const [scannedLotInput, setScannedLotInput] = useState<string>("");
  202. const [error, setError] = useState<string>("");
  203. useEffect(() => {
  204. if (open) {
  205. setExpectedLotInput(expectedLot?.lotNo || "");
  206. setScannedLotInput(scannedLot?.lotNo || "");
  207. setError("");
  208. }
  209. }, [open, expectedLot, scannedLot]);
  210. const handleConfirm = () => {
  211. if (!expectedLotInput.trim() || !scannedLotInput.trim()) {
  212. setError(t("Please enter both expected and scanned lot numbers."));
  213. return;
  214. }
  215. if (expectedLotInput.trim() === scannedLotInput.trim()) {
  216. setError(t("Expected and scanned lot numbers cannot be the same."));
  217. return;
  218. }
  219. onConfirm(expectedLotInput.trim(), scannedLotInput.trim());
  220. };
  221. return (
  222. <Modal open={open} onClose={onClose}>
  223. <Box
  224. sx={{
  225. position: "absolute",
  226. top: "50%",
  227. left: "50%",
  228. transform: "translate(-50%, -50%)",
  229. bgcolor: "background.paper",
  230. p: 3,
  231. borderRadius: 2,
  232. minWidth: 500,
  233. }}
  234. >
  235. <Typography variant="h6" gutterBottom color="warning.main">
  236. {t("Manual Lot Confirmation")}
  237. </Typography>
  238. <Box sx={{ mb: 2 }}>
  239. <Typography variant="body2" gutterBottom>
  240. <strong>{t("Expected Lot Number")}:</strong>
  241. </Typography>
  242. <TextField
  243. fullWidth
  244. size="small"
  245. value={expectedLotInput}
  246. onChange={(e) => {
  247. setExpectedLotInput(e.target.value);
  248. setError("");
  249. }}
  250. sx={{ mb: 2 }}
  251. error={!!error && !expectedLotInput.trim()}
  252. />
  253. </Box>
  254. <Box sx={{ mb: 2 }}>
  255. <Typography variant="body2" gutterBottom>
  256. <strong>{t("Scanned Lot Number")}:</strong>
  257. </Typography>
  258. <TextField
  259. fullWidth
  260. size="small"
  261. value={scannedLotInput}
  262. onChange={(e) => {
  263. setScannedLotInput(e.target.value);
  264. setError("");
  265. }}
  266. sx={{ mb: 2 }}
  267. error={!!error && !scannedLotInput.trim()}
  268. />
  269. </Box>
  270. {error && (
  271. <Box
  272. sx={{ mb: 2, p: 1, backgroundColor: "#ffebee", borderRadius: 1 }}
  273. >
  274. <Typography variant="body2" color="error">
  275. {error}
  276. </Typography>
  277. </Box>
  278. )}
  279. <Box
  280. sx={{ mt: 2, display: "flex", justifyContent: "flex-end", gap: 2 }}
  281. >
  282. <Button onClick={onClose} variant="outlined" disabled={isLoading}>
  283. {t("Cancel")}
  284. </Button>
  285. <Button
  286. onClick={handleConfirm}
  287. variant="contained"
  288. color="warning"
  289. disabled={
  290. isLoading || !expectedLotInput.trim() || !scannedLotInput.trim()
  291. }
  292. >
  293. {isLoading ? t("Processing...") : t("Confirm")}
  294. </Button>
  295. </Box>
  296. </Box>
  297. </Modal>
  298. );
  299. };
  300. // QR Code Modal Component (from GoodPickExecution)
  301. const QrCodeModal: React.FC<{
  302. open: boolean;
  303. onClose: () => void;
  304. lot: any | null;
  305. onQrCodeSubmit: (lotNo: string) => void;
  306. combinedLotData: any[];
  307. }> = ({ open, onClose, lot, onQrCodeSubmit, combinedLotData }) => {
  308. const { t } = useTranslation("jo");
  309. const {
  310. values: qrValues,
  311. isScanning,
  312. startScan,
  313. stopScan,
  314. resetScan,
  315. } = useQrCodeScannerContext();
  316. const [manualInput, setManualInput] = useState<string>("");
  317. const [selectedFloor, setSelectedFloor] = useState<string | null>(null);
  318. const [manualInputSubmitted, setManualInputSubmitted] =
  319. useState<boolean>(false);
  320. const [manualInputError, setManualInputError] = useState<boolean>(false);
  321. const [isProcessingQr, setIsProcessingQr] = useState<boolean>(false);
  322. const [qrScanFailed, setQrScanFailed] = useState<boolean>(false);
  323. const [qrScanSuccess, setQrScanSuccess] = useState<boolean>(false);
  324. const [processedQrCodes, setProcessedQrCodes] = useState<Set<string>>(
  325. new Set(),
  326. );
  327. const [scannedQrResult, setScannedQrResult] = useState<string>("");
  328. // Process scanned QR codes
  329. useEffect(() => {
  330. if (qrValues.length > 0 && lot && !isProcessingQr && !qrScanSuccess) {
  331. const latestQr = qrValues[qrValues.length - 1];
  332. if (processedQrCodes.has(latestQr)) {
  333. console.log("QR code already processed, skipping...");
  334. return;
  335. }
  336. setProcessedQrCodes((prev) => new Set(prev).add(latestQr));
  337. try {
  338. const qrData = JSON.parse(latestQr);
  339. if (qrData.stockInLineId && qrData.itemId) {
  340. setIsProcessingQr(true);
  341. setQrScanFailed(false);
  342. fetchStockInLineInfo(qrData.stockInLineId)
  343. .then((stockInLineInfo) => {
  344. console.log("Stock in line info:", stockInLineInfo);
  345. setScannedQrResult(stockInLineInfo.lotNo || "Unknown lot number");
  346. if (stockInLineInfo.lotNo === lot.lotNo) {
  347. console.log(` QR Code verified for lot: ${lot.lotNo}`);
  348. setQrScanSuccess(true);
  349. onQrCodeSubmit(lot.lotNo);
  350. onClose();
  351. resetScan();
  352. } else {
  353. console.log(
  354. `❌ QR Code mismatch. Expected: ${lot.lotNo}, Got: ${stockInLineInfo.lotNo}`,
  355. );
  356. setQrScanFailed(true);
  357. setManualInputError(true);
  358. setManualInputSubmitted(true);
  359. }
  360. })
  361. .catch((error) => {
  362. console.error("Error fetching stock in line info:", error);
  363. setScannedQrResult("Error fetching data");
  364. setQrScanFailed(true);
  365. setManualInputError(true);
  366. setManualInputSubmitted(true);
  367. })
  368. .finally(() => {
  369. setIsProcessingQr(false);
  370. });
  371. } else {
  372. const qrContent = latestQr.replace(/[{}]/g, "");
  373. setScannedQrResult(qrContent);
  374. if (qrContent === lot.lotNo) {
  375. setQrScanSuccess(true);
  376. onQrCodeSubmit(lot.lotNo);
  377. onClose();
  378. resetScan();
  379. } else {
  380. setQrScanFailed(true);
  381. setManualInputError(true);
  382. setManualInputSubmitted(true);
  383. }
  384. }
  385. } catch (error) {
  386. console.log("QR code is not JSON format, trying direct comparison");
  387. const qrContent = latestQr.replace(/[{}]/g, "");
  388. setScannedQrResult(qrContent);
  389. if (qrContent === lot.lotNo) {
  390. setQrScanSuccess(true);
  391. onQrCodeSubmit(lot.lotNo);
  392. onClose();
  393. resetScan();
  394. } else {
  395. setQrScanFailed(true);
  396. setManualInputError(true);
  397. setManualInputSubmitted(true);
  398. }
  399. }
  400. }
  401. }, [
  402. qrValues,
  403. lot,
  404. onQrCodeSubmit,
  405. onClose,
  406. resetScan,
  407. isProcessingQr,
  408. qrScanSuccess,
  409. processedQrCodes,
  410. ]);
  411. // Clear states when modal opens
  412. useEffect(() => {
  413. if (open) {
  414. setManualInput("");
  415. setManualInputSubmitted(false);
  416. setManualInputError(false);
  417. setIsProcessingQr(false);
  418. setQrScanFailed(false);
  419. setQrScanSuccess(false);
  420. setScannedQrResult("");
  421. setProcessedQrCodes(new Set());
  422. }
  423. }, [open]);
  424. useEffect(() => {
  425. if (lot) {
  426. setManualInput("");
  427. setManualInputSubmitted(false);
  428. setManualInputError(false);
  429. setIsProcessingQr(false);
  430. setQrScanFailed(false);
  431. setQrScanSuccess(false);
  432. setScannedQrResult("");
  433. setProcessedQrCodes(new Set());
  434. }
  435. }, [lot]);
  436. // Auto-submit manual input when it matches
  437. useEffect(() => {
  438. if (
  439. manualInput.trim() === lot?.lotNo &&
  440. manualInput.trim() !== "" &&
  441. !qrScanFailed &&
  442. !qrScanSuccess
  443. ) {
  444. console.log(" Auto-submitting manual input:", manualInput.trim());
  445. const timer = setTimeout(() => {
  446. setQrScanSuccess(true);
  447. onQrCodeSubmit(lot.lotNo);
  448. onClose();
  449. setManualInput("");
  450. setManualInputError(false);
  451. setManualInputSubmitted(false);
  452. }, 200);
  453. return () => clearTimeout(timer);
  454. }
  455. }, [manualInput, lot, onQrCodeSubmit, onClose, qrScanFailed, qrScanSuccess]);
  456. const handleManualSubmit = () => {
  457. if (manualInput.trim() === lot?.lotNo) {
  458. setQrScanSuccess(true);
  459. onQrCodeSubmit(lot.lotNo);
  460. onClose();
  461. setManualInput("");
  462. } else {
  463. setQrScanFailed(true);
  464. setManualInputError(true);
  465. setManualInputSubmitted(true);
  466. }
  467. };
  468. useEffect(() => {
  469. if (open) {
  470. startScan();
  471. }
  472. }, [open, startScan]);
  473. return (
  474. <Modal open={open} onClose={onClose}>
  475. <Box
  476. sx={{
  477. position: "absolute",
  478. top: "50%",
  479. left: "50%",
  480. transform: "translate(-50%, -50%)",
  481. bgcolor: "background.paper",
  482. p: 3,
  483. borderRadius: 2,
  484. minWidth: 400,
  485. }}
  486. >
  487. <Typography variant="h6" gutterBottom>
  488. {t("QR Code Scan for Lot")}: {lot?.lotNo}
  489. </Typography>
  490. {isProcessingQr && (
  491. <Box
  492. sx={{ mb: 2, p: 2, backgroundColor: "#e3f2fd", borderRadius: 1 }}
  493. >
  494. <Typography variant="body2" color="primary">
  495. {t("Processing QR code...")}
  496. </Typography>
  497. </Box>
  498. )}
  499. <Box sx={{ mb: 2 }}>
  500. <Typography variant="body2" gutterBottom>
  501. <strong>{t("Manual Input")}:</strong>
  502. </Typography>
  503. <TextField
  504. fullWidth
  505. size="small"
  506. value={manualInput}
  507. onChange={(e) => {
  508. setManualInput(e.target.value);
  509. if (qrScanFailed || manualInputError) {
  510. setQrScanFailed(false);
  511. setManualInputError(false);
  512. setManualInputSubmitted(false);
  513. }
  514. }}
  515. sx={{ mb: 1 }}
  516. error={manualInputSubmitted && manualInputError}
  517. helperText={
  518. manualInputSubmitted && manualInputError
  519. ? `${t(
  520. "The input is not the same as the expected lot number.",
  521. )}`
  522. : ""
  523. }
  524. />
  525. <Button
  526. variant="contained"
  527. onClick={handleManualSubmit}
  528. disabled={!manualInput.trim() || lot?.noLot === true || !lot?.lotId}
  529. size="small"
  530. color="primary"
  531. >
  532. {t("Submit")}
  533. </Button>
  534. </Box>
  535. {qrValues.length > 0 && (
  536. <Box
  537. sx={{
  538. mb: 2,
  539. p: 2,
  540. backgroundColor: qrScanFailed
  541. ? "#ffebee"
  542. : qrScanSuccess
  543. ? "#e8f5e8"
  544. : "#f5f5f5",
  545. borderRadius: 1,
  546. }}
  547. >
  548. <Typography
  549. variant="body2"
  550. color={
  551. qrScanFailed
  552. ? "error"
  553. : qrScanSuccess
  554. ? "success"
  555. : "text.secondary"
  556. }
  557. >
  558. <strong>{t("QR Scan Result:")}</strong> {scannedQrResult}
  559. </Typography>
  560. {qrScanSuccess && (
  561. <Typography variant="caption" color="success" display="block">
  562. {t("Verified successfully!")}
  563. </Typography>
  564. )}
  565. </Box>
  566. )}
  567. <Box sx={{ mt: 2, textAlign: "right" }}>
  568. <Button onClick={onClose} variant="outlined">
  569. {t("Cancel")}
  570. </Button>
  571. </Box>
  572. </Box>
  573. </Modal>
  574. );
  575. };
  576. /** FP-MTMS Version Checklist | Functions Ref. No. 43 | v1.0.1 | 2026-08-10 */
  577. const JobPickExecution: React.FC<Props> = ({ filterArgs, onBackToList, printerCombo = [] }) => {
  578. const workbenchMode = true;
  579. const { t } = useTranslation("jo");
  580. const L = useUiText();
  581. const { t: tPick } = useTranslation("pickOrder");
  582. const router = useRouter();
  583. const { data: session } = useSession() as { data: SessionWithTokens | null };
  584. const currentUserId = session?.id ? parseInt(session.id) : undefined;
  585. // 修改:使用 Job Order 数据结构
  586. const [combinedDataLoading, setCombinedDataLoading] = useState(false);
  587. // 添加未分配订单状态
  588. const [unassignedOrders, setUnassignedOrders] = useState<any[]>([]);
  589. const [isLoadingUnassigned, setIsLoadingUnassigned] = useState(false);
  590. const {
  591. values: qrValues,
  592. isScanning,
  593. startScan,
  594. stopScan,
  595. resetScan,
  596. } = useQrCodeScannerContext();
  597. const [expectedLotData, setExpectedLotData] = useState<any>(null);
  598. const [scannedLotData, setScannedLotData] = useState<any>(null);
  599. const [isConfirmingLot, setIsConfirmingLot] = useState(false);
  600. const [qrScanInput, setQrScanInput] = useState<string>("");
  601. const [qrScanError, setQrScanError] = useState<boolean>(false);
  602. const [qrScanErrorMsg, setQrScanErrorMsg] = useState<string>("");
  603. const [qrScanSuccess, setQrScanSuccess] = useState<boolean>(false);
  604. const [jobOrderData, setJobOrderData] =
  605. useState<JobOrderLotsHierarchicalWorkbenchResponse | null>(null);
  606. const a4Printers = useMemo(
  607. () =>
  608. (printerCombo || []).filter((p) =>
  609. String(p.type || "")
  610. .trim()
  611. .toUpperCase()
  612. .includes("A4"),
  613. ),
  614. [printerCombo],
  615. );
  616. const printerOptions = useMemo(
  617. () => (a4Printers.length > 0 ? a4Printers : printerCombo || []),
  618. [a4Printers, printerCombo],
  619. );
  620. const isPrinterComboMissing = printerCombo.length === 0;
  621. const [selectedPrinter, setSelectedPrinter] = useState<PrinterCombo | null>(
  622. printerOptions.length > 0 ? printerOptions[0] : null,
  623. );
  624. const [printQty, setPrintQty] = useState<number>(1);
  625. const pickRecordPrintInFlightRef = useRef(false);
  626. useEffect(() => {
  627. // Keep selected printer valid when combo list changes.
  628. if (!printerOptions.length) {
  629. setSelectedPrinter(null);
  630. return;
  631. }
  632. setSelectedPrinter((prev) => {
  633. if (!prev) return printerOptions[0];
  634. const stillExists = printerOptions.some((p) => p.id === prev.id);
  635. return stillExists ? prev : printerOptions[0];
  636. });
  637. }, [printerOptions]);
  638. useEffect(() => {
  639. console.log("[JO Workbench] printerCombo:", printerCombo);
  640. console.log("[JO Workbench] a4Printers:", a4Printers);
  641. console.log("[JO Workbench] printerOptions:", printerOptions);
  642. }, [printerCombo, a4Printers, printerOptions]);
  643. const handlePickRecord = useCallback(
  644. async (floor: PickRecordFloor) => {
  645. if (pickRecordPrintInFlightRef.current) return;
  646. try {
  647. const pickOrderId = jobOrderData?.pickOrder?.id;
  648. if (!pickOrderId) {
  649. msgError(t("Pick Order not found"));
  650. return;
  651. }
  652. if (!selectedPrinter) {
  653. msgError(t("Please select a printer first"));
  654. return;
  655. }
  656. if (!printQty || printQty < 1) {
  657. msgError(t("Please enter a valid print quantity (at least 1)"));
  658. return;
  659. }
  660. let printRequest;
  661. if (floor === "ALL") {
  662. const allFloorsQty = await promptAllFloorsPlasticBoxCartonQty(t, pickOrderId);
  663. if (allFloorsQty === null) {
  664. return;
  665. }
  666. printRequest = buildPrintPickRecordRequest({
  667. pickOrderId,
  668. printerId: selectedPrinter.id,
  669. printQty,
  670. floor,
  671. allFloorsQty,
  672. });
  673. } else {
  674. const plasticBoxCartonQty = await promptPlasticBoxCartonQty(t);
  675. if (plasticBoxCartonQty === null) {
  676. return;
  677. }
  678. printRequest = buildPrintPickRecordRequest({
  679. pickOrderId,
  680. printerId: selectedPrinter.id,
  681. printQty,
  682. floor,
  683. plasticBoxCartonQty,
  684. });
  685. }
  686. pickRecordPrintInFlightRef.current = true;
  687. const response = await PrintPickRecord(printRequest);
  688. if (response?.success) {
  689. msg(t("Printed Successfully."));
  690. } else {
  691. msgError(response?.message || t("Print failed"));
  692. }
  693. } catch (e) {
  694. console.error(e);
  695. msgError(t("An error occurred while printing"));
  696. } finally {
  697. pickRecordPrintInFlightRef.current = false;
  698. }
  699. },
  700. [jobOrderData, printQty, selectedPrinter, t],
  701. );
  702. const workbenchStoreId = useMemo(() => {
  703. const po = jobOrderData?.pickOrder as
  704. | { storeId?: string | null }
  705. | undefined;
  706. const s = po?.storeId;
  707. return typeof s === "string" && s.trim() !== "" ? s.trim() : null;
  708. }, [jobOrderData]);
  709. const [pickQtyData, setPickQtyData] = useState<Record<string, number>>({});
  710. /** 與 DO Workbench 一致:false = 數量只讀;Edit 切換為可輸入「將提交數量」,不開 Issue 表單 */
  711. const [
  712. workbenchSubmitQtyFieldEnabledByLotKey,
  713. setWorkbenchSubmitQtyFieldEnabledByLotKey,
  714. ] = useState<Record<string, boolean>>({});
  715. const [searchQuery, setSearchQuery] = useState<Record<string, any>>({});
  716. // issue form 里填的 actualPickQty(用于 submit/batch submit 不补拣到 required)
  717. const [issuePickedQtyBySolId, setIssuePickedQtyBySolId] = useState<
  718. Record<number, number>
  719. >({});
  720. const [localSolStatusById, setLocalSolStatusById] = useState<
  721. Record<number, string>
  722. >({});
  723. // 防止同一行(以 stockOutLineId/solId 识别)被重复点击提交/完成
  724. const [actionBusyBySolId, setActionBusyBySolId] = useState<
  725. Record<number, boolean>
  726. >({});
  727. /** DO Workbench:scan-pick 失敗訊息按 SOL 顯示 */
  728. const [scanRejectMessageBySolId, setScanRejectMessageBySolId] = useState<
  729. Record<number, string>
  730. >({});
  731. const rememberWorkbenchScanReject = useCallback(
  732. (stockOutLineId: number, message: string | undefined | null) => {
  733. const id = Number(stockOutLineId);
  734. const m = String(message ?? "").trim();
  735. if (!id || !m) return;
  736. setScanRejectMessageBySolId((prev) => ({ ...prev, [id]: m }));
  737. },
  738. [],
  739. );
  740. const clearWorkbenchScanReject = useCallback((stockOutLineId: number) => {
  741. const id = Number(stockOutLineId);
  742. if (!id) return;
  743. setScanRejectMessageBySolId((prev) => {
  744. if (!(id in prev)) return prev;
  745. const next = { ...prev };
  746. delete next[id];
  747. return next;
  748. });
  749. }, []);
  750. const [paginationController, setPaginationController] = useState({
  751. pageNum: 0,
  752. pageSize: 10,
  753. });
  754. const [usernameList, setUsernameList] = useState<NameList[]>([]);
  755. const initializationRef = useRef(false);
  756. const scannerInitializedRef = useRef(false);
  757. const autoAssignRef = useRef(false);
  758. const formProps = useForm();
  759. const errors = formProps.formState.errors;
  760. const [isSubmittingAll, setIsSubmittingAll] = useState<boolean>(false);
  761. const [autoAssignStatus, setAutoAssignStatus] = useState<
  762. "idle" | "checking" | "assigned" | "no_orders"
  763. >("idle");
  764. const [completionStatus, setCompletionStatus] =
  765. useState<PickOrderCompletionResponse | null>(null);
  766. const [autoAssignMessage, setAutoAssignMessage] = useState<string>("");
  767. // Add QR modal states
  768. const [qrModalOpen, setQrModalOpen] = useState(false);
  769. const [selectedLotForQr, setSelectedLotForQr] = useState<any | null>(null);
  770. const [selectedFloor, setSelectedFloor] = useState<string | null>(null);
  771. // Add GoodPickExecutionForm states
  772. const [pickExecutionFormOpen, setPickExecutionFormOpen] = useState(false);
  773. const [selectedLotForExecutionForm, setSelectedLotForExecutionForm] =
  774. useState<any | null>(null);
  775. const [fgPickOrders, setFgPickOrders] = useState<FGPickOrderResponse[]>([]);
  776. const [fgPickOrdersLoading, setFgPickOrdersLoading] = useState(false);
  777. const [workbenchLotLabelModalOpen, setWorkbenchLotLabelModalOpen] =
  778. useState(false);
  779. const [workbenchLotLabelInitialPayload, setWorkbenchLotLabelInitialPayload] =
  780. useState<{ itemId: number; stockInLineId: number } | null>(null);
  781. const [workbenchLotLabelContextLot, setWorkbenchLotLabelContextLot] =
  782. useState<any | null>(null);
  783. const [workbenchLotLabelReminderText, setWorkbenchLotLabelReminderText] =
  784. useState<string | null>(null);
  785. useEffect(() => {
  786. if (!qrScanSuccess || !workbenchLotLabelModalOpen) return;
  787. setWorkbenchLotLabelModalOpen(false);
  788. setWorkbenchLotLabelInitialPayload(null);
  789. setWorkbenchLotLabelContextLot(null);
  790. setWorkbenchLotLabelReminderText(null);
  791. }, [qrScanSuccess, workbenchLotLabelModalOpen]);
  792. // Add these missing state variables
  793. const [isManualScanning, setIsManualScanning] = useState<boolean>(false);
  794. const [processedQrCodes, setProcessedQrCodes] = useState<Set<string>>(
  795. new Set(),
  796. );
  797. const [lastProcessedQr, setLastProcessedQr] = useState<string>("");
  798. const [isRefreshingData, setIsRefreshingData] = useState<boolean>(false);
  799. // Track processed QR codes by itemId+stockInLineId combination for better lot confirmation handling
  800. const [processedQrCombinations, setProcessedQrCombinations] = useState<
  801. Map<number, Set<number>>
  802. >(new Map());
  803. // Cache for fetchStockInLineInfo API calls to avoid redundant requests
  804. const stockInLineInfoCache = useRef<
  805. Map<number, { lotNo: string | null; timestamp: number }>
  806. >(new Map());
  807. const CACHE_TTL = 60000; // 60 seconds cache TTL
  808. const abortControllerRef = useRef<AbortController | null>(null);
  809. const qrProcessingTimeoutRef = useRef<NodeJS.Timeout | null>(null);
  810. // Use refs for processed QR tracking to avoid useEffect dependency issues and delays
  811. const processedQrCodesRef = useRef<Set<string>>(new Set());
  812. const lastProcessedQrRef = useRef<string>("");
  813. // Store callbacks in refs to avoid useEffect dependency issues
  814. const processOutsideQrCodeRef = useRef<
  815. ((latestQr: string, qrScanCountAtInvoke?: number) => Promise<void>) | null
  816. >(null);
  817. const resetScanRef = useRef<(() => void) | null>(null);
  818. // Manual lot confirmation modal state (test shortcut {2fic})
  819. const [manualLotConfirmationOpen, setManualLotConfirmationOpen] =
  820. useState(false);
  821. const getAllLotsFromHierarchical = useCallback(
  822. (data: JobOrderLotsHierarchicalWorkbenchResponse | null): any[] => {
  823. if (!data || !data.pickOrder || !data.pickOrderLines) {
  824. return [];
  825. }
  826. const allLots: any[] = [];
  827. data.pickOrderLines.forEach((line) => {
  828. // 用来记录这一行已经通过 lots 出现过的 lotId(避免 stockouts 再渲染一次)
  829. const lotIdSet = new Set<number>();
  830. // lots:按 lotId 去重并合并 requiredQty(对齐 DO Workbench / GoodPickExecutiondetail)
  831. if (line.lots && line.lots.length > 0) {
  832. const lotMap = new Map<number, any>();
  833. line.lots.forEach((lot: any) => {
  834. const lotId = lot.lotId;
  835. if (lotId == null) return;
  836. if (lotMap.has(lotId)) {
  837. const existingLot = lotMap.get(lotId);
  838. existingLot.requiredQty =
  839. (existingLot.requiredQty || 0) + (lot.requiredQty || 0);
  840. } else {
  841. lotMap.set(lotId, { ...lot });
  842. }
  843. });
  844. lotMap.forEach((lot: any) => {
  845. if (lot.lotId != null) lotIdSet.add(lot.lotId);
  846. allLots.push({
  847. ...lot,
  848. pickOrderLineId: line.id,
  849. itemId: line.itemId,
  850. itemCode: line.itemCode,
  851. itemName: line.itemName,
  852. uomCode: line.uomCode,
  853. uomDesc: line.uomDesc,
  854. itemTotalAvailableQty: line.totalAvailableQty ?? null,
  855. pickOrderLineRequiredQty: line.requiredQty,
  856. pickOrderLineStatus: line.status,
  857. jobOrderId: data.pickOrder.jobOrder.id,
  858. jobOrderCode: data.pickOrder.jobOrder.code,
  859. pickOrderId: data.pickOrder.id,
  860. pickOrderCode: data.pickOrder.code,
  861. pickOrderConsoCode: data.pickOrder.consoCode,
  862. pickOrderTargetDate: data.pickOrder.targetDate,
  863. pickOrderType: data.pickOrder.type,
  864. pickOrderStatus: data.pickOrder.status,
  865. pickOrderAssignTo: data.pickOrder.assignTo,
  866. handler: line.handler,
  867. noLot: false,
  868. });
  869. });
  870. }
  871. // stockouts:用于“无 suggested lot / noLot”场景也显示并可 submit 0 闭环
  872. // 批號需求數:對齊 DO Workbench——用後端 stockout/SPL qty,不前端推 gap
  873. if (line.stockouts && line.stockouts.length > 0) {
  874. line.stockouts.forEach((stockout: any) => {
  875. const hasLot = stockout.lotId != null;
  876. const lotAlreadyInLots =
  877. hasLot && lotIdSet.has(stockout.lotId as number);
  878. // 有批次 & 已经通过 lots 渲染过 → 跳过,避免一条变两行
  879. if (!stockout.noLot && lotAlreadyInLots) {
  880. return;
  881. }
  882. const stockoutRequiredQty = Number(
  883. stockout?.requiredQty ??
  884. stockout?.suggestedPickQty ??
  885. stockout?.suggestedPickLotQty,
  886. );
  887. const effectiveStockoutRequiredQty = Number.isFinite(
  888. stockoutRequiredQty,
  889. )
  890. ? stockoutRequiredQty
  891. : Number(line.requiredQty) || 0;
  892. allLots.push({
  893. pickOrderLineId: line.id,
  894. itemId: line.itemId,
  895. itemCode: line.itemCode,
  896. itemName: line.itemName,
  897. uomCode: line.uomCode,
  898. uomDesc: line.uomDesc,
  899. itemTotalAvailableQty: line.totalAvailableQty ?? null,
  900. pickOrderLineRequiredQty: line.requiredQty,
  901. pickOrderLineStatus: line.status,
  902. jobOrderId: data.pickOrder.jobOrder.id,
  903. jobOrderCode: data.pickOrder.jobOrder.code,
  904. pickOrderId: data.pickOrder.id,
  905. pickOrderCode: data.pickOrder.code,
  906. pickOrderConsoCode: data.pickOrder.consoCode,
  907. pickOrderTargetDate: data.pickOrder.targetDate,
  908. pickOrderType: data.pickOrder.type,
  909. pickOrderStatus: data.pickOrder.status,
  910. pickOrderAssignTo: data.pickOrder.assignTo,
  911. handler: line.handler,
  912. lotId: stockout.lotId || null,
  913. lotNo: stockout.lotNo || null,
  914. expiryDate: null,
  915. location: stockout.location || null,
  916. availableQty: stockout.availableQty ?? 0,
  917. requiredQty: effectiveStockoutRequiredQty,
  918. actualPickQty: stockout.qty ?? 0,
  919. processingStatus: stockout.status || "pending",
  920. lotAvailability: stockout.noLot
  921. ? "insufficient_stock"
  922. : "available",
  923. suggestedPickLotId: stockout.suggestedPickLotId ?? null,
  924. stockOutLineId: stockout.id || null,
  925. stockOutLineQty: stockout.qty ?? 0,
  926. stockOutLineStatus: stockout.status || null,
  927. stockInLineId: null,
  928. routerIndex: stockout.noLot ? 999999 : null,
  929. routerArea: null,
  930. routerRoute: null,
  931. noLot: !!stockout.noLot,
  932. });
  933. });
  934. }
  935. });
  936. return allLots;
  937. },
  938. [],
  939. );
  940. const extractFloor = (lot: any): string => {
  941. const raw = String(lot.routerRoute || lot.routerArea || lot.location || "");
  942. const head = raw.trim().toUpperCase().replace(/\//g, "").split("-")[0];
  943. if (head === "2" || head === FLOOR_A_KEY) return FLOOR_A_KEY;
  944. if (head === "4" || head === FLOOR_B_KEY) return FLOOR_B_KEY;
  945. if (head === "3" || head === FLOOR_D_KEY) return FLOOR_D_KEY;
  946. if (head === "1" || head === FLOOR_C_KEY) return FLOOR_C_KEY;
  947. return head;
  948. };
  949. // 4/F, then 3/F, then 2/F.
  950. const floorSortOrder = (floor: string): number => {
  951. if (floor === FLOOR_B_KEY) return 4;
  952. if (floor === FLOOR_D_KEY) return 3;
  953. if (floor === FLOOR_A_KEY) return 2;
  954. if (floor === FLOOR_C_KEY) return 1;
  955. return 0;
  956. };
  957. const combinedLotData = useMemo(() => {
  958. const lots = getAllLotsFromHierarchical(jobOrderData);
  959. // 前端覆盖:issue form/submit0 不会立刻改写后端 qty 时,用本地缓存让 UI 与 batch submit 计算一致
  960. return lots.map((lot: any) => {
  961. const solId = Number(lot.stockOutLineId) || 0;
  962. if (solId > 0) {
  963. const hasPickedOverride = Object.prototype.hasOwnProperty.call(
  964. issuePickedQtyBySolId,
  965. solId,
  966. );
  967. const picked = Number(
  968. issuePickedQtyBySolId[solId] ?? lot.actualPickQty ?? 0,
  969. );
  970. const statusRaw =
  971. localSolStatusById[solId] ?? lot.stockOutLineStatus ?? "";
  972. const status = String(statusRaw).toLowerCase();
  973. const isEnded = status === "completed" || status === "rejected";
  974. return {
  975. ...lot,
  976. actualPickQty: hasPickedOverride ? picked : lot.actualPickQty,
  977. stockOutLineQty: hasPickedOverride ? picked : lot.stockOutLineQty,
  978. stockOutLineStatus: isEnded ? statusRaw : statusRaw || "checked",
  979. };
  980. }
  981. return lot;
  982. });
  983. }, [
  984. jobOrderData,
  985. getAllLotsFromHierarchical,
  986. issuePickedQtyBySolId,
  987. localSolStatusById,
  988. ]);
  989. /** 單筆將提交數量:Issue 改數 → pickQtyData → 已完成行用實際量 → noLot/過期/unavailable → 0 → 否則 required(對齊 DO Workbench) */
  990. const resolveSingleSubmitQty = useCallback(
  991. (lot: any) => {
  992. const required = Number(
  993. lot.requiredQty || lot.pickOrderLineRequiredQty || 0,
  994. );
  995. const solId = Number(lot.stockOutLineId) || 0;
  996. const lotId = lot.lotId;
  997. const lotKey =
  998. Number.isFinite(solId) && solId > 0
  999. ? `sol:${solId}`
  1000. : `${lot.pickOrderLineId}-${lotId}`;
  1001. const issuePicked = solId > 0 ? issuePickedQtyBySolId[solId] : undefined;
  1002. if (issuePicked !== undefined && !Number.isNaN(Number(issuePicked))) {
  1003. return Number(issuePicked);
  1004. }
  1005. const st = String(lot.stockOutLineStatus || "").toLowerCase();
  1006. if (
  1007. st === "completed" ||
  1008. st === "partially_completed" ||
  1009. st === "partially_complete"
  1010. ) {
  1011. return Number(lot.stockOutLineQty ?? lot.actualPickQty ?? 0);
  1012. }
  1013. if (Object.prototype.hasOwnProperty.call(pickQtyData, lotKey)) {
  1014. const fromPick = pickQtyData[lotKey];
  1015. if (
  1016. fromPick !== undefined &&
  1017. fromPick !== null &&
  1018. !Number.isNaN(Number(fromPick))
  1019. ) {
  1020. return Number(fromPick);
  1021. }
  1022. }
  1023. if (isInventoryLotLineUnavailable(lot)) {
  1024. return 0;
  1025. }
  1026. if (lot.noLot === true || !lot.lotId) {
  1027. return 0;
  1028. }
  1029. if (isLotAvailabilityExpired(lot)) {
  1030. return 0;
  1031. }
  1032. return required;
  1033. },
  1034. [issuePickedQtyBySolId, pickQtyData],
  1035. );
  1036. const getWorkbenchQtyLotKey = useCallback((lot: any) => {
  1037. const solId = Number(lot?.stockOutLineId) || 0;
  1038. if (Number.isFinite(solId) && solId > 0) return `sol:${solId}`;
  1039. return `${lot?.pickOrderLineId}-${lot?.lotId}`;
  1040. }, []);
  1041. const workbenchScanPickQtyFromLot = useCallback(
  1042. (lot: any) => {
  1043. const solId = Number(lot?.stockOutLineId);
  1044. const sourceLot =
  1045. Number.isFinite(solId) && solId > 0
  1046. ? combinedLotData.find((r) => Number(r.stockOutLineId) === solId) ??
  1047. lot
  1048. : lot;
  1049. const lotKey = getWorkbenchQtyLotKey(sourceLot);
  1050. const hasExplicitPickOverride = Object.prototype.hasOwnProperty.call(
  1051. pickQtyData,
  1052. lotKey,
  1053. );
  1054. const n = Number(resolveSingleSubmitQty(sourceLot));
  1055. if (hasExplicitPickOverride && Number.isFinite(n) && n === 0)
  1056. return { qty: 0 } as const;
  1057. if (!Number.isFinite(n) || n <= 0) return {};
  1058. return { qty: n } as const;
  1059. },
  1060. [resolveSingleSubmitQty, combinedLotData, pickQtyData, getWorkbenchQtyLotKey],
  1061. );
  1062. const lotFloorPrefixFilter = useMemo(() => {
  1063. const storeId = String(workbenchStoreId ?? "")
  1064. .trim()
  1065. .toUpperCase()
  1066. .replace(/\s/g, "");
  1067. const floorKey = storeId.replace(/\//g, "");
  1068. return floorKey ? `${floorKey}-` : "";
  1069. }, [workbenchStoreId]);
  1070. const defaultLabelPrinterName = useMemo(() => {
  1071. const storeId = String(workbenchStoreId ?? "")
  1072. .trim()
  1073. .toUpperCase()
  1074. .replace(/\s/g, "");
  1075. const floorKey = storeId.replace(/\//g, "");
  1076. if (floorKey === FLOOR_A_KEY) return L("Label機 2F A+B", "Label printer 2F A+B");
  1077. if (floorKey === FLOOR_B_KEY) return L("Label機 4F 乾貨 C, D", "Label printer 4F dry goods C, D");
  1078. return undefined;
  1079. }, [workbenchStoreId, L]);
  1080. const openWorkbenchLotLabelModalForLot = useCallback((lot: any, reminderText?: string | null) => {
  1081. const itemId = Number(lot?.itemId);
  1082. const stockInLineId = Number(lot?.stockInLineId);
  1083. const solId = Number(lot?.stockOutLineId);
  1084. if (!Number.isFinite(itemId) || itemId <= 0 || !Number.isFinite(solId) || solId <= 0) {
  1085. return;
  1086. }
  1087. setWorkbenchLotLabelContextLot(lot);
  1088. if (Number.isFinite(stockInLineId) && stockInLineId > 0) {
  1089. setWorkbenchLotLabelInitialPayload({ itemId, stockInLineId });
  1090. } else {
  1091. setWorkbenchLotLabelInitialPayload(null);
  1092. }
  1093. setWorkbenchLotLabelReminderText(reminderText ?? null);
  1094. // Clear latched success so the lot-label modal effect cannot instantly re-close on open.
  1095. setQrScanSuccess(false);
  1096. setWorkbenchLotLabelModalOpen(true);
  1097. }, []);
  1098. const shouldOpenWorkbenchLotLabelModalForFailure = useCallback(
  1099. (code?: string | null, msg?: string | null): boolean => {
  1100. const normalizedCode = String(code || "").toUpperCase();
  1101. if (
  1102. normalizedCode.includes("UNAVAILABLE") ||
  1103. normalizedCode.includes("EXPIRED")
  1104. ) {
  1105. return true;
  1106. }
  1107. const normalizedMsg = String(msg || "").toLowerCase();
  1108. if (!normalizedMsg) return false;
  1109. return (
  1110. normalizedMsg.includes("unavailable") ||
  1111. normalizedMsg.includes("not available") ||
  1112. normalizedMsg.includes("expired") ||
  1113. normalizedMsg.includes("不可用") ||
  1114. normalizedMsg.includes("無法使用") ||
  1115. normalizedMsg.includes("过期")
  1116. );
  1117. },
  1118. [],
  1119. );
  1120. const handleWorkbenchLotLabelScanPick = useCallback(
  1121. async ({
  1122. inventoryLotLineId,
  1123. lotNo,
  1124. qty,
  1125. }: {
  1126. inventoryLotLineId: number;
  1127. lotNo: string;
  1128. qty?: number;
  1129. }) => {
  1130. const lot = workbenchLotLabelContextLot;
  1131. if (!lot?.stockOutLineId) {
  1132. throw new Error(t("Missing stock out line for this row."));
  1133. }
  1134. const qtyPayload = Number.isFinite(Number(qty))
  1135. ? { qty: Number(qty) }
  1136. : workbenchScanPickQtyFromLot(lot);
  1137. const res = await workbenchScanPick({
  1138. stockOutLineId: Number(lot.stockOutLineId),
  1139. lotNo: String(lotNo || "").trim(),
  1140. inventoryLotLineId,
  1141. storeId: workbenchStoreId,
  1142. userId: currentUserId ?? 1,
  1143. ...qtyPayload,
  1144. });
  1145. if (res.code !== "SUCCESS") {
  1146. const errMsg =
  1147. (res as { message?: string })?.message ||
  1148. t("Workbench scan-pick failed.");
  1149. rememberWorkbenchScanReject(Number(lot.stockOutLineId), errMsg);
  1150. throw new Error(errMsg);
  1151. }
  1152. clearWorkbenchScanReject(Number(lot.stockOutLineId));
  1153. const pickOrderId = filterArgs?.pickOrderId
  1154. ? Number(filterArgs.pickOrderId)
  1155. : undefined;
  1156. if (pickOrderId) {
  1157. const latest =
  1158. await fetchJobOrderLotsHierarchicalByPickOrderIdWorkbench(pickOrderId);
  1159. setJobOrderData(latest);
  1160. setIssuePickedQtyBySolId(loadIssuePickedMapJo(pickOrderId));
  1161. getAllLotsFromHierarchical(latest);
  1162. }
  1163. setWorkbenchLotLabelModalOpen(false);
  1164. setWorkbenchLotLabelContextLot(null);
  1165. setWorkbenchLotLabelInitialPayload(null);
  1166. },
  1167. [
  1168. workbenchLotLabelContextLot,
  1169. currentUserId,
  1170. workbenchScanPickQtyFromLot,
  1171. workbenchStoreId,
  1172. rememberWorkbenchScanReject,
  1173. clearWorkbenchScanReject,
  1174. filterArgs?.pickOrderId,
  1175. getAllLotsFromHierarchical,
  1176. t,
  1177. ],
  1178. );
  1179. const workbenchLotLabelSubmitQty = useMemo(() => {
  1180. if (!workbenchLotLabelContextLot) return 0;
  1181. return Number(resolveSingleSubmitQty(workbenchLotLabelContextLot)) || 0;
  1182. }, [workbenchLotLabelContextLot, resolveSingleSubmitQty]);
  1183. const handleWorkbenchLotLabelSubmitQtyChange = useCallback(
  1184. (qty: number) => {
  1185. if (!workbenchLotLabelContextLot) return;
  1186. const lotKey = getWorkbenchQtyLotKey(workbenchLotLabelContextLot);
  1187. setPickQtyData((prev) => ({ ...prev, [lotKey]: qty }));
  1188. },
  1189. [workbenchLotLabelContextLot, getWorkbenchQtyLotKey],
  1190. );
  1191. const workbenchLotLabelScanPickDisabled = useMemo(() => {
  1192. if (!workbenchLotLabelModalOpen || !workbenchLotLabelContextLot) return true;
  1193. const lot = workbenchLotLabelContextLot;
  1194. const status = String(lot.stockOutLineStatus || "").toLowerCase();
  1195. const isNoLot = !lot.lotNo || String(lot.lotNo).trim() === "";
  1196. if (isNoLot) return false;
  1197. if (status === "pending" || status === "rejected") return false;
  1198. return true;
  1199. }, [workbenchLotLabelModalOpen, workbenchLotLabelContextLot]);
  1200. const originalCombinedData = useMemo(() => {
  1201. return getAllLotsFromHierarchical(jobOrderData);
  1202. }, [jobOrderData, getAllLotsFromHierarchical]);
  1203. // Enhanced lotDataIndexes with cached active lots for better performance (align with GoodPickExecutiondetail)
  1204. const lotDataIndexes = useMemo(() => {
  1205. const byItemId = new Map<number, any[]>();
  1206. const byItemCode = new Map<string, any[]>();
  1207. const byLotId = new Map<number, any>();
  1208. const byLotNo = new Map<string, any[]>();
  1209. const byStockInLineId = new Map<number, any[]>();
  1210. const activeLotsByItemId = new Map<number, any[]>();
  1211. const rejectedStatuses = new Set(["rejected"]);
  1212. for (let i = 0; i < combinedLotData.length; i++) {
  1213. const lot = combinedLotData[i];
  1214. const solStatus = String(lot.stockOutLineStatus || "").toLowerCase();
  1215. const lotAvailability = String(lot.lotAvailability || "").toLowerCase();
  1216. const processingStatus = String(lot.processingStatus || "").toLowerCase();
  1217. const isUnavailable = isInventoryLotLineUnavailable(lot);
  1218. const isExpired = isLotAvailabilityExpired(lot);
  1219. const isRejected =
  1220. rejectedStatuses.has(lotAvailability) ||
  1221. rejectedStatuses.has(solStatus) ||
  1222. rejectedStatuses.has(processingStatus);
  1223. const isEnded = solStatus === "checked" || solStatus === "completed";
  1224. const isPartially =
  1225. solStatus === "partially_completed" ||
  1226. solStatus === "partially_complete";
  1227. const isPending = solStatus === "pending" || solStatus === "";
  1228. const isActive =
  1229. !isRejected &&
  1230. !isUnavailable &&
  1231. !isExpired &&
  1232. !isEnded &&
  1233. (isPending || isPartially);
  1234. if (lot.itemId) {
  1235. if (!byItemId.has(lot.itemId)) {
  1236. byItemId.set(lot.itemId, []);
  1237. activeLotsByItemId.set(lot.itemId, []);
  1238. }
  1239. byItemId.get(lot.itemId)!.push(lot);
  1240. if (isActive) activeLotsByItemId.get(lot.itemId)!.push(lot);
  1241. }
  1242. if (lot.itemCode) {
  1243. if (!byItemCode.has(lot.itemCode)) byItemCode.set(lot.itemCode, []);
  1244. byItemCode.get(lot.itemCode)!.push(lot);
  1245. }
  1246. if (lot.lotId) byLotId.set(lot.lotId, lot);
  1247. if (lot.lotNo) {
  1248. if (!byLotNo.has(lot.lotNo)) byLotNo.set(lot.lotNo, []);
  1249. byLotNo.get(lot.lotNo)!.push(lot);
  1250. }
  1251. if (lot.stockInLineId) {
  1252. if (!byStockInLineId.has(lot.stockInLineId))
  1253. byStockInLineId.set(lot.stockInLineId, []);
  1254. byStockInLineId.get(lot.stockInLineId)!.push(lot);
  1255. }
  1256. }
  1257. return {
  1258. byItemId,
  1259. byItemCode,
  1260. byLotId,
  1261. byLotNo,
  1262. byStockInLineId,
  1263. activeLotsByItemId,
  1264. };
  1265. }, [combinedLotData]);
  1266. // Cached version of fetchStockInLineInfo to avoid redundant API calls
  1267. const fetchStockInLineInfoCached = useCallback(
  1268. async (stockInLineId: number): Promise<{ lotNo: string | null }> => {
  1269. const now = Date.now();
  1270. const cached = stockInLineInfoCache.current.get(stockInLineId);
  1271. if (cached && now - cached.timestamp < CACHE_TTL) {
  1272. return { lotNo: cached.lotNo };
  1273. }
  1274. if (abortControllerRef.current) abortControllerRef.current.abort();
  1275. const abortController = new AbortController();
  1276. abortControllerRef.current = abortController;
  1277. const stockInLineInfo = await fetchStockInLineInfo(stockInLineId);
  1278. stockInLineInfoCache.current.set(stockInLineId, {
  1279. lotNo: stockInLineInfo.lotNo || null,
  1280. timestamp: now,
  1281. });
  1282. if (stockInLineInfoCache.current.size > 100) {
  1283. const firstKey = stockInLineInfoCache.current.keys().next().value;
  1284. if (firstKey !== undefined)
  1285. stockInLineInfoCache.current.delete(firstKey);
  1286. }
  1287. return { lotNo: stockInLineInfo.lotNo || null };
  1288. },
  1289. [],
  1290. );
  1291. // 修改:加载未分配的 Job Order 订单
  1292. const loadUnassignedOrders = useCallback(async () => {
  1293. setIsLoadingUnassigned(true);
  1294. try {
  1295. //const orders = await fetchUnassignedJobOrderPickOrders();
  1296. //setUnassignedOrders(orders);
  1297. } catch (error) {
  1298. console.error("Error loading unassigned orders:", error);
  1299. } finally {
  1300. setIsLoadingUnassigned(false);
  1301. }
  1302. }, []);
  1303. // 修改:分配订单给当前用户
  1304. const handleAssignOrder = useCallback(
  1305. async (pickOrderId: number) => {
  1306. if (!currentUserId) {
  1307. console.error("Missing user id in session");
  1308. return;
  1309. }
  1310. try {
  1311. const result = await assignJobOrderPickOrderForWorkbench(
  1312. pickOrderId,
  1313. currentUserId,
  1314. );
  1315. const msg = String(result?.message || "");
  1316. const assignSkippedByStatus =
  1317. msg.toLowerCase().startsWith("skipped assign:");
  1318. if (msg === "Successfully assigned" || assignSkippedByStatus) {
  1319. console.log(" Successfully assigned pick order");
  1320. if (!assignSkippedByStatus) {
  1321. try {
  1322. /*
  1323. const refreshed =
  1324. await fetchJobOrderLotsHierarchicalByPickOrderIdWorkbench(
  1325. pickOrderId,
  1326. );
  1327. const uniqueItemIds = Array.from(
  1328. new Set(
  1329. (refreshed?.pickOrderLines ?? [])
  1330. .map((line) => line?.itemId)
  1331. .filter(
  1332. (itemId): itemId is number =>
  1333. typeof itemId === "number" &&
  1334. Number.isFinite(itemId) &&
  1335. itemId > 0,
  1336. ),
  1337. ),
  1338. );
  1339. await Promise.all(
  1340. uniqueItemIds.map((itemId) =>
  1341. updateJoPickOrderHandledBy({
  1342. pickOrderId,
  1343. itemId,
  1344. userId: currentUserId,
  1345. }),
  1346. ),
  1347. );
  1348. */
  1349. } catch (handledBySyncError) {
  1350. console.warn(
  1351. "⚠️ Assigned but failed to sync JoPickOrder.handledBy for some lines:",
  1352. handledBySyncError,
  1353. );
  1354. }
  1355. }
  1356. // 刷新数据
  1357. window.dispatchEvent(new CustomEvent("pickOrderAssigned"));
  1358. // 重新加载未分配订单列表
  1359. loadUnassignedOrders();
  1360. } else {
  1361. console.warn("⚠️ Assignment failed:", result.message);
  1362. alert(`Assignment failed: ${result.message}`);
  1363. }
  1364. } catch (error) {
  1365. console.error("❌ Error assigning order:", error);
  1366. alert("Error occurred during assignment");
  1367. }
  1368. },
  1369. [currentUserId, loadUnassignedOrders],
  1370. );
  1371. const fetchFgPickOrdersData = useCallback(async () => {
  1372. if (!currentUserId) return;
  1373. setFgPickOrdersLoading(true);
  1374. try {
  1375. const allFgPickOrders = await fetchFGPickOrdersByUserIdWorkbench(
  1376. currentUserId,
  1377. );
  1378. setFgPickOrders(Array.isArray(allFgPickOrders) ? allFgPickOrders : []);
  1379. console.log(" Fetched FG pick orders(workbench):", allFgPickOrders);
  1380. } catch (error) {
  1381. console.error("❌ Error fetching FG pick orders:", error);
  1382. setFgPickOrders([]);
  1383. } finally {
  1384. setFgPickOrdersLoading(false);
  1385. }
  1386. }, [currentUserId]);
  1387. useEffect(() => {
  1388. if (combinedLotData.length > 0) {
  1389. fetchFgPickOrdersData();
  1390. }
  1391. }, [combinedLotData, fetchFgPickOrdersData]);
  1392. // Handle QR code button click
  1393. const handleQrCodeClick = (pickOrderId: number) => {
  1394. console.log(`QR Code clicked for pick order ID: ${pickOrderId}`);
  1395. // TODO: Implement QR code functionality
  1396. };
  1397. // 修改:使用 Job Order API 获取数据
  1398. const fetchJobOrderData = useCallback(
  1399. async (pickOrderId?: number) => {
  1400. setCombinedDataLoading(true);
  1401. try {
  1402. if (!pickOrderId) {
  1403. console.warn("⚠️ No pickOrderId provided, skipping API call");
  1404. return;
  1405. }
  1406. // 直接使用类型化的响应
  1407. const jobOrderData =
  1408. await fetchJobOrderLotsHierarchicalByPickOrderIdWorkbench(pickOrderId);
  1409. console.log("✅ Job Order data (hierarchical):", jobOrderData);
  1410. setJobOrderData(jobOrderData);
  1411. setIssuePickedQtyBySolId(loadIssuePickedMapJo(pickOrderId));
  1412. // 使用辅助函数获取所有 lots(不再扁平化)
  1413. getAllLotsFromHierarchical(jobOrderData);
  1414. } catch (error) {
  1415. console.error("❌ Error fetching job order data:", error);
  1416. setJobOrderData(null);
  1417. setIssuePickedQtyBySolId({});
  1418. } finally {
  1419. setCombinedDataLoading(false);
  1420. }
  1421. },
  1422. [getAllLotsFromHierarchical],
  1423. );
  1424. const applyLocalStockOutLineUpdate = useCallback((..._args: unknown[]) => {
  1425. // JO Workbench:以伺服器刷新為主;保留呼叫點與 DO Workbench 一致(不更新本地 SOL 鏡像)。
  1426. }, []);
  1427. const refreshWorkbenchAfterScanPick = useCallback(async () => {
  1428. const pickOrderId = filterArgs?.pickOrderId
  1429. ? Number(filterArgs.pickOrderId)
  1430. : undefined;
  1431. await fetchJobOrderData(pickOrderId);
  1432. }, [fetchJobOrderData, filterArgs?.pickOrderId]);
  1433. const updateHandledBy = useCallback(
  1434. async (pickOrderId: number, itemId: number) => {
  1435. if (!currentUserId || !pickOrderId || !itemId) {
  1436. return;
  1437. }
  1438. try {
  1439. console.log(
  1440. `Updating JoPickOrder.handledBy for pickOrderId: ${pickOrderId}, itemId: ${itemId}, userId: ${currentUserId}`,
  1441. );
  1442. await updateJoPickOrderHandledBy({
  1443. pickOrderId: pickOrderId,
  1444. itemId: itemId,
  1445. userId: currentUserId,
  1446. });
  1447. console.log("✅ JoPickOrder.handledBy updated successfully");
  1448. } catch (error) {
  1449. console.error("❌ Error updating JoPickOrder.handledBy:", error);
  1450. // Don't throw - this is not critical for the main flow
  1451. }
  1452. },
  1453. [currentUserId],
  1454. );
  1455. // 修改:初始化 — Workbench 先 prime SPL/SOL(後端不寫 pick_order.assignTo),再載入階層資料
  1456. useEffect(() => {
  1457. if (session && currentUserId && !initializationRef.current) {
  1458. console.log("✅ Session loaded, initializing job order...");
  1459. initializationRef.current = true;
  1460. const pickOrderId = filterArgs?.pickOrderId
  1461. ? Number(filterArgs.pickOrderId)
  1462. : undefined;
  1463. if (pickOrderId) {
  1464. void (async () => {
  1465. try {
  1466. await handleAssignOrder(pickOrderId);
  1467. } finally {
  1468. await fetchJobOrderData(pickOrderId);
  1469. }
  1470. })();
  1471. }
  1472. loadUnassignedOrders();
  1473. }
  1474. }, [
  1475. session,
  1476. currentUserId,
  1477. fetchJobOrderData,
  1478. loadUnassignedOrders,
  1479. filterArgs?.pickOrderId,
  1480. handleAssignOrder,
  1481. ]);
  1482. // 與 GoodPickExecutiondetail 一致:session 就緒後自動開啟背景掃碼(平板現場用)
  1483. useEffect(() => {
  1484. if (session && currentUserId && !scannerInitializedRef.current) {
  1485. scannerInitializedRef.current = true;
  1486. console.log("✅ [JO] Auto-starting QR scanner in background mode");
  1487. setIsManualScanning(true);
  1488. startScan();
  1489. }
  1490. }, [session, currentUserId, startScan]);
  1491. // 僅在元件卸載時重置,讓 React Strict Mode 二次掛載仍能再走一次自動開掃(不因 startScan 引用變化而重複開掃)
  1492. useEffect(() => {
  1493. return () => {
  1494. scannerInitializedRef.current = false;
  1495. };
  1496. }, []);
  1497. // Add event listener for manual assignment
  1498. useEffect(() => {
  1499. const handlePickOrderAssigned = () => {
  1500. console.log("🔄 Pick order assigned event received, refreshing data...");
  1501. const pickOrderId = filterArgs?.pickOrderId
  1502. ? Number(filterArgs.pickOrderId)
  1503. : undefined;
  1504. if (pickOrderId) {
  1505. fetchJobOrderData(pickOrderId);
  1506. }
  1507. };
  1508. window.addEventListener("pickOrderAssigned", handlePickOrderAssigned);
  1509. return () => {
  1510. window.removeEventListener("pickOrderAssigned", handlePickOrderAssigned);
  1511. };
  1512. }, [fetchJobOrderData, filterArgs?.pickOrderId]);
  1513. /** 純 lotNo 手動輸入:與 DO Workbench 相同,不寫 checked,改提示用 scan-pick / Just Completed */
  1514. const handleQrCodeSubmit = useCallback(
  1515. async (lotNo: string) => {
  1516. console.log(` Processing QR Code for lot: ${lotNo}`);
  1517. if (!lotNo || lotNo === "null" || lotNo.trim() === "") {
  1518. console.error(" Invalid lotNo: null, undefined, or empty");
  1519. return;
  1520. }
  1521. const currentLotData = combinedLotData;
  1522. console.log(
  1523. ` Available lots:`,
  1524. currentLotData.map((lot) => lot.lotNo),
  1525. );
  1526. const lotNoLower = lotNo.toLowerCase();
  1527. const matchingLots = currentLotData.filter((lot) => {
  1528. if (!lot.lotNo) return false;
  1529. return lot.lotNo === lotNo || lot.lotNo.toLowerCase() === lotNoLower;
  1530. });
  1531. if (matchingLots.length === 0) {
  1532. console.error(` Lot not found: ${lotNo}`);
  1533. setQrScanError(true);
  1534. setQrScanSuccess(false);
  1535. const availableLotNos = currentLotData
  1536. .map((lot) => lot.lotNo)
  1537. .join(", ");
  1538. console.log(
  1539. ` QR Code "${lotNo}" does not match any expected lots. Available lots: ${availableLotNos}`,
  1540. );
  1541. return;
  1542. }
  1543. const hasExpiredLot = matchingLots.some(
  1544. (lot: any) =>
  1545. String(lot.lotAvailability || "").toLowerCase() === "expired",
  1546. );
  1547. if (hasExpiredLot) {
  1548. console.warn(`⚠️ [QR PROCESS] Scanned lot ${lotNo} is expired`);
  1549. setQrScanError(true);
  1550. setQrScanSuccess(false);
  1551. return;
  1552. }
  1553. setQrScanError(true);
  1554. setQrScanSuccess(false);
  1555. setQrScanErrorMsg(
  1556. tPick(
  1557. "Workbench uses scan-pick. Please use Just Completed / submit via scan-pick instead of checked status.",
  1558. ),
  1559. );
  1560. },
  1561. [combinedLotData, tPick],
  1562. );
  1563. const clearLotConfirmationState = useCallback(
  1564. (clearProcessedRefs: boolean = false) => {
  1565. setExpectedLotData(null);
  1566. setScannedLotData(null);
  1567. setSelectedLotForQr(null);
  1568. if (clearProcessedRefs) {
  1569. setTimeout(() => {
  1570. lastProcessedQrRef.current = "";
  1571. processedQrCodesRef.current.clear();
  1572. }, 100);
  1573. }
  1574. },
  1575. [],
  1576. );
  1577. // Add handleLotConfirmation function
  1578. const handleLotConfirmation = useCallback(
  1579. async (overrideScannedLot?: any) => {
  1580. const effectiveScannedLot = overrideScannedLot ?? scannedLotData;
  1581. if (!expectedLotData || !effectiveScannedLot || !selectedLotForQr) {
  1582. console.error(
  1583. "❌ [LOT CONFIRM] Missing required data for lot confirmation",
  1584. );
  1585. return;
  1586. }
  1587. console.log(
  1588. "✅ [LOT CONFIRM] User confirmed lot substitution - processing now",
  1589. );
  1590. console.log("✅ [LOT CONFIRM] Expected lot:", expectedLotData);
  1591. console.log("✅ [LOT CONFIRM] Scanned lot:", scannedLotData);
  1592. console.log("✅ [LOT CONFIRM] Selected lot for QR:", selectedLotForQr);
  1593. setIsConfirmingLot(true);
  1594. try {
  1595. let newLotLineId = effectiveScannedLot?.inventoryLotLineId;
  1596. if (!newLotLineId && effectiveScannedLot?.stockInLineId) {
  1597. try {
  1598. if (
  1599. currentUserId &&
  1600. selectedLotForQr.pickOrderId &&
  1601. selectedLotForQr.itemId
  1602. ) {
  1603. try {
  1604. await updateHandledBy(
  1605. selectedLotForQr.pickOrderId,
  1606. selectedLotForQr.itemId,
  1607. );
  1608. console.log(
  1609. `✅ [LOT CONFIRM] Handler updated for itemId ${selectedLotForQr.itemId}`,
  1610. );
  1611. } catch (error) {
  1612. console.error(
  1613. `❌ [LOT CONFIRM] Error updating handler (non-critical):`,
  1614. error,
  1615. );
  1616. }
  1617. }
  1618. console.log(
  1619. `🔍 [LOT CONFIRM] Fetching lot detail for stockInLineId: ${effectiveScannedLot.stockInLineId}`,
  1620. );
  1621. const ld = await fetchLotDetail(effectiveScannedLot.stockInLineId);
  1622. newLotLineId = ld.inventoryLotLineId;
  1623. console.log(
  1624. `✅ [LOT CONFIRM] Fetched lot detail: inventoryLotLineId=${newLotLineId}`,
  1625. );
  1626. } catch (error) {
  1627. console.error(
  1628. "❌ [LOT CONFIRM] Error fetching lot detail (stockInLineId may not exist):",
  1629. error,
  1630. );
  1631. // If stockInLineId doesn't exist, we can still proceed with lotNo substitution
  1632. // The backend confirmLotSubstitution should handle this case
  1633. }
  1634. }
  1635. if (!newLotLineId) {
  1636. console.warn(
  1637. "⚠️ [LOT CONFIRM] No inventory lot line id for scanned lot, proceeding with lotNo only",
  1638. );
  1639. // Continue anyway - backend may handle lotNo substitution without inventoryLotLineId
  1640. }
  1641. console.log("=== [LOT CONFIRM] Lot Confirmation Debug ===");
  1642. console.log("Selected Lot:", selectedLotForQr);
  1643. console.log("Pick Order Line ID:", selectedLotForQr.pickOrderLineId);
  1644. console.log("Stock Out Line ID:", selectedLotForQr.stockOutLineId);
  1645. console.log(
  1646. "Suggested Pick Lot ID:",
  1647. selectedLotForQr.suggestedPickLotId,
  1648. );
  1649. console.log("Lot ID (fallback):", selectedLotForQr.lotId);
  1650. console.log("New Inventory Lot Line ID:", newLotLineId);
  1651. console.log("Scanned Lot No:", effectiveScannedLot.lotNo);
  1652. console.log(
  1653. "Scanned StockInLineId:",
  1654. effectiveScannedLot.stockInLineId,
  1655. );
  1656. const originalSuggestedPickLotId =
  1657. selectedLotForQr.suggestedPickLotId || selectedLotForQr.lotId;
  1658. let switchedToUnavailable = false;
  1659. // Workbench no-hold: skip classic bind/switch (holdQty). Switch + pick via scan-pick only.
  1660. // Non-workbench: keep confirmLotSubstitution / QR bind (moves hold).
  1661. if (!workbenchMode) {
  1662. // noLot / missing suggestedPickLotId 场景:没有 originalSuggestedPickLotId,改用 updateStockOutLineStatusByQRCodeAndLotNo
  1663. if (!originalSuggestedPickLotId) {
  1664. if (!selectedLotForQr?.stockOutLineId) {
  1665. throw new Error("Missing stockOutLineId for noLot line");
  1666. }
  1667. console.log(
  1668. "🔄 [LOT CONFIRM] No originalSuggestedPickLotId, using updateStockOutLineStatusByQRCodeAndLotNo...",
  1669. );
  1670. const res = await updateStockOutLineStatusByQRCodeAndLotNo({
  1671. pickOrderLineId: selectedLotForQr.pickOrderLineId,
  1672. inventoryLotNo: effectiveScannedLot.lotNo || "",
  1673. stockInLineId: effectiveScannedLot?.stockInLineId ?? null,
  1674. stockOutLineId: selectedLotForQr.stockOutLineId,
  1675. itemId: selectedLotForQr.itemId,
  1676. status: "checked",
  1677. });
  1678. console.log(
  1679. "✅ [LOT CONFIRM] updateStockOutLineStatusByQRCodeAndLotNo result:",
  1680. res,
  1681. );
  1682. switchedToUnavailable = res?.code === "BOUND_UNAVAILABLE";
  1683. const ok =
  1684. res?.code === "checked" ||
  1685. res?.code === "SUCCESS" ||
  1686. switchedToUnavailable;
  1687. if (!ok) {
  1688. const errMsg =
  1689. res?.code === "LOT_UNAVAILABLE"
  1690. ? tPick(
  1691. "The scanned lot inventory line is unavailable. Cannot switch or bind; pick line was not updated.",
  1692. )
  1693. : res?.message ||
  1694. tPick(
  1695. "Lot switch failed; pick line was not marked as checked.",
  1696. );
  1697. setQrScanError(true);
  1698. setQrScanSuccess(false);
  1699. setQrScanErrorMsg(errMsg);
  1700. return;
  1701. }
  1702. } else {
  1703. // Call confirmLotSubstitution to update the suggested lot
  1704. console.log("🔄 [LOT CONFIRM] Calling confirmLotSubstitution...");
  1705. const substitutionResult = await confirmLotSubstitution({
  1706. pickOrderLineId: selectedLotForQr.pickOrderLineId,
  1707. stockOutLineId: selectedLotForQr.stockOutLineId,
  1708. originalSuggestedPickLotId,
  1709. newInventoryLotNo: effectiveScannedLot.lotNo || "",
  1710. // ✅ required by LotSubstitutionConfirmRequest
  1711. newStockInLineId: effectiveScannedLot?.stockInLineId ?? null,
  1712. });
  1713. console.log(
  1714. "✅ [LOT CONFIRM] Lot substitution result:",
  1715. substitutionResult,
  1716. );
  1717. // ✅ CRITICAL: substitution failed => DO NOT mark original stockOutLine as checked.
  1718. // Keep modal open so user can cancel/rescan.
  1719. switchedToUnavailable =
  1720. substitutionResult?.code === "SUCCESS_UNAVAILABLE" ||
  1721. substitutionResult?.code === "BOUND_UNAVAILABLE";
  1722. if (
  1723. !substitutionResult ||
  1724. (substitutionResult.code !== "SUCCESS" && !switchedToUnavailable)
  1725. ) {
  1726. console.error(
  1727. "❌ [LOT CONFIRM] Lot substitution failed. Will NOT update stockOutLine status.",
  1728. );
  1729. const errMsg =
  1730. substitutionResult?.code === "LOT_UNAVAILABLE"
  1731. ? tPick(
  1732. "The scanned lot inventory line is unavailable. Cannot switch or bind; pick line was not updated.",
  1733. )
  1734. : substitutionResult?.message ||
  1735. L(
  1736. `换批失败:stockInLineId ${effectiveScannedLot?.stockInLineId ?? ""} 不存在或无法匹配`,
  1737. `Lot change failed: stock-in line ${effectiveScannedLot?.stockInLineId ?? ""} does not exist or could not be matched`,
  1738. );
  1739. setQrScanError(true);
  1740. setQrScanSuccess(false);
  1741. setQrScanErrorMsg(errMsg);
  1742. return;
  1743. }
  1744. }
  1745. }
  1746. // Workbench:以 scan-pick 過帳(與 DO Workbench 一致);非 workbench 仍寫 checked
  1747. if (
  1748. workbenchMode &&
  1749. selectedLotForQr?.stockOutLineId &&
  1750. !switchedToUnavailable
  1751. ) {
  1752. const lotNoToScan = String(effectiveScannedLot.lotNo || "").trim();
  1753. const silId = effectiveScannedLot?.stockInLineId;
  1754. if (!lotNoToScan) {
  1755. const errMsg = tPick("Cannot resolve lot number for confirmation.");
  1756. setQrScanError(true);
  1757. setQrScanSuccess(false);
  1758. setQrScanErrorMsg(errMsg);
  1759. return;
  1760. }
  1761. const res = await workbenchScanPick({
  1762. stockOutLineId: selectedLotForQr.stockOutLineId,
  1763. lotNo: lotNoToScan,
  1764. ...(typeof silId === "number" && Number.isFinite(silId) && silId > 0
  1765. ? { stockInLineId: silId }
  1766. : {}),
  1767. ...workbenchScanPickQtyFromLot(selectedLotForQr),
  1768. storeId: workbenchStoreId,
  1769. userId: currentUserId ?? 1,
  1770. });
  1771. if (res.code !== "SUCCESS") {
  1772. const errMsg =
  1773. (res as { message?: string })?.message ||
  1774. tPick("Workbench scan-pick failed.");
  1775. setQrScanError(true);
  1776. setQrScanSuccess(false);
  1777. setQrScanErrorMsg(errMsg);
  1778. if (selectedLotForQr.stockOutLineId != null) {
  1779. rememberWorkbenchScanReject(
  1780. Number(selectedLotForQr.stockOutLineId),
  1781. errMsg,
  1782. );
  1783. }
  1784. return;
  1785. }
  1786. clearWorkbenchScanReject(Number(selectedLotForQr.stockOutLineId));
  1787. } else if (selectedLotForQr?.stockOutLineId && !switchedToUnavailable) {
  1788. console.log(
  1789. `🔄 [LOT CONFIRM] Updating stockOutLine ${selectedLotForQr.stockOutLineId} to 'checked'`,
  1790. );
  1791. await updateStockOutLineStatus({
  1792. id: selectedLotForQr.stockOutLineId,
  1793. status: "checked",
  1794. qty: 0,
  1795. });
  1796. console.log(
  1797. `✅ [LOT CONFIRM] Stock out line ${selectedLotForQr.stockOutLineId} status updated to 'checked'`,
  1798. );
  1799. }
  1800. // Close modal and clean up state BEFORE refreshing
  1801. clearLotConfirmationState(false);
  1802. // Clear QR processing state but DON'T clear processedQrCodes yet
  1803. setQrScanError(false);
  1804. setQrScanSuccess(true);
  1805. setQrScanErrorMsg("");
  1806. setQrScanInput("");
  1807. // Set refreshing flag to prevent QR processing during refresh
  1808. setIsRefreshingData(true);
  1809. // Refresh data to show updated lot
  1810. console.log("🔄 Refreshing job order data...");
  1811. const pickOrderId = filterArgs?.pickOrderId
  1812. ? Number(filterArgs.pickOrderId)
  1813. : undefined;
  1814. await fetchJobOrderData(pickOrderId);
  1815. console.log(" Lot substitution confirmed and data refreshed");
  1816. // Clear processed QR codes and flags immediately after refresh
  1817. // This allows new QR codes to be processed right away
  1818. setTimeout(() => {
  1819. console.log(" Clearing processed QR codes and resuming scan");
  1820. setProcessedQrCodes(new Set());
  1821. setLastProcessedQr("");
  1822. setQrScanSuccess(false);
  1823. setIsRefreshingData(false);
  1824. // ✅ Clear processedQrCombinations to allow reprocessing the same QR if needed
  1825. if (effectiveScannedLot?.stockInLineId && selectedLotForQr?.itemId) {
  1826. setProcessedQrCombinations((prev) => {
  1827. const newMap = new Map(prev);
  1828. const itemId = selectedLotForQr.itemId;
  1829. if (itemId && newMap.has(itemId)) {
  1830. newMap.get(itemId)!.delete(effectiveScannedLot.stockInLineId);
  1831. if (newMap.get(itemId)!.size === 0) {
  1832. newMap.delete(itemId);
  1833. }
  1834. }
  1835. return newMap;
  1836. });
  1837. }
  1838. }, 500); // Reduced from 3000ms to 500ms - just enough for UI update
  1839. } catch (error) {
  1840. console.error("Error confirming lot substitution:", error);
  1841. const errMsg = tPick("Lot confirmation failed. Please try again.");
  1842. setQrScanError(true);
  1843. setQrScanSuccess(false);
  1844. setQrScanErrorMsg(errMsg);
  1845. // Clear refresh flag on error
  1846. setIsRefreshingData(false);
  1847. } finally {
  1848. setIsConfirmingLot(false);
  1849. }
  1850. },
  1851. [
  1852. expectedLotData,
  1853. scannedLotData,
  1854. selectedLotForQr,
  1855. fetchJobOrderData,
  1856. currentUserId,
  1857. updateHandledBy,
  1858. tPick,
  1859. clearLotConfirmationState,
  1860. workbenchMode,
  1861. workbenchScanPickQtyFromLot,
  1862. workbenchStoreId,
  1863. rememberWorkbenchScanReject,
  1864. clearWorkbenchScanReject,
  1865. ],
  1866. );
  1867. const processOutsideQrCode = useCallback(
  1868. async (latestQr: string, _qrScanCountAtInvoke?: number) => {
  1869. const totalStartTime = performance.now();
  1870. console.log(
  1871. ` [PROCESS OUTSIDE QR START] QR: ${latestQr.substring(0, 50)}...`,
  1872. );
  1873. console.log(` Start time: ${new Date().toISOString()}`);
  1874. // ✅ Measure index access time
  1875. const indexAccessStart = performance.now();
  1876. const indexes = lotDataIndexes; // Access the memoized indexes
  1877. const indexAccessTime = performance.now() - indexAccessStart;
  1878. console.log(
  1879. ` [PERF] Index access time: ${indexAccessTime.toFixed(2)}ms`,
  1880. );
  1881. // 1) Parse JSON safely (parse once, reuse)
  1882. const parseStartTime = performance.now();
  1883. let qrData: any = null;
  1884. let parseTime = 0;
  1885. try {
  1886. qrData = JSON.parse(latestQr);
  1887. parseTime = performance.now() - parseStartTime;
  1888. console.log(` [PERF] JSON parse time: ${parseTime.toFixed(2)}ms`);
  1889. } catch {
  1890. console.log(
  1891. "QR content is not JSON; skipping lotNo direct submit to avoid false matches.",
  1892. );
  1893. startTransition(() => {
  1894. setQrScanError(true);
  1895. setQrScanSuccess(false);
  1896. });
  1897. return;
  1898. }
  1899. try {
  1900. const validationStartTime = performance.now();
  1901. if (!(qrData?.stockInLineId && qrData?.itemId)) {
  1902. console.log(
  1903. "QR JSON missing required fields (itemId, stockInLineId).",
  1904. );
  1905. startTransition(() => {
  1906. setQrScanError(true);
  1907. setQrScanSuccess(false);
  1908. });
  1909. return;
  1910. }
  1911. const validationTime = performance.now() - validationStartTime;
  1912. console.log(` [PERF] Validation time: ${validationTime.toFixed(2)}ms`);
  1913. const scannedItemId = qrData.itemId;
  1914. const scannedStockInLineId = qrData.stockInLineId;
  1915. // ✅ Check if this combination was already processed
  1916. const duplicateCheckStartTime = performance.now();
  1917. const itemProcessedSet = processedQrCombinations.get(scannedItemId);
  1918. if (itemProcessedSet?.has(scannedStockInLineId)) {
  1919. const duplicateCheckTime =
  1920. performance.now() - duplicateCheckStartTime;
  1921. console.log(
  1922. ` [SKIP] Already processed combination: itemId=${scannedItemId}, stockInLineId=${scannedStockInLineId} (check time: ${duplicateCheckTime.toFixed(
  1923. 2,
  1924. )}ms)`,
  1925. );
  1926. return;
  1927. }
  1928. const duplicateCheckTime = performance.now() - duplicateCheckStartTime;
  1929. console.log(
  1930. ` [PERF] Duplicate check time: ${duplicateCheckTime.toFixed(2)}ms`,
  1931. );
  1932. // ✅ OPTIMIZATION: Use cached active lots directly (no filtering needed)
  1933. const lookupStartTime = performance.now();
  1934. const activeSuggestedLots =
  1935. indexes.activeLotsByItemId.get(scannedItemId) || [];
  1936. // ✅ Also get all lots for this item (not just active ones) to allow lot switching even when all lots are rejected
  1937. const allLotsForItem = indexes.byItemId.get(scannedItemId) || [];
  1938. const lookupTime = performance.now() - lookupStartTime;
  1939. console.log(
  1940. ` [PERF] Index lookup time: ${lookupTime.toFixed(2)}ms, found ${
  1941. activeSuggestedLots.length
  1942. } active lots, ${allLotsForItem.length} total lots`,
  1943. );
  1944. // ✅ Check if scanned lot is rejected BEFORE checking activeSuggestedLots
  1945. // This allows users to scan other lots even when all suggested lots are rejected
  1946. const scannedLot = allLotsForItem.find(
  1947. (lot: any) => lot.stockInLineId === scannedStockInLineId,
  1948. );
  1949. if (scannedLot) {
  1950. const isRejected =
  1951. scannedLot.stockOutLineStatus?.toLowerCase() === "rejected" ||
  1952. scannedLot.lotAvailability === "rejected" ||
  1953. isInventoryLotLineUnavailable(scannedLot);
  1954. if (isRejected) {
  1955. console.warn(
  1956. `⚠️ [QR PROCESS] Scanned lot (stockInLineId: ${scannedStockInLineId}, lotNo: ${scannedLot.lotNo}) is rejected or unavailable`,
  1957. );
  1958. startTransition(() => {
  1959. setQrScanError(true);
  1960. setQrScanSuccess(false);
  1961. setQrScanErrorMsg(
  1962. L(
  1963. `此批次(${scannedLot.lotNo || scannedStockInLineId})已被拒绝,无法使用。请扫描其他批次。`,
  1964. `This lot (${scannedLot.lotNo || scannedStockInLineId}) was rejected and cannot be used. Scan another lot.`,
  1965. ),
  1966. );
  1967. });
  1968. // Mark as processed to prevent re-processing
  1969. setProcessedQrCombinations((prev) => {
  1970. const newMap = new Map(prev);
  1971. if (!newMap.has(scannedItemId))
  1972. newMap.set(scannedItemId, new Set());
  1973. newMap.get(scannedItemId)!.add(scannedStockInLineId);
  1974. return newMap;
  1975. });
  1976. return;
  1977. }
  1978. const isExpired =
  1979. String(scannedLot.lotAvailability || "").toLowerCase() ===
  1980. "expired";
  1981. if (isExpired) {
  1982. console.warn(
  1983. `⚠️ [QR PROCESS] Scanned lot (stockInLineId: ${scannedStockInLineId}, lotNo: ${scannedLot.lotNo}) is expired`,
  1984. );
  1985. startTransition(() => {
  1986. setQrScanError(true);
  1987. setQrScanSuccess(false);
  1988. setQrScanErrorMsg(
  1989. L(
  1990. `此批次(${scannedLot.lotNo || scannedStockInLineId})已过期,无法使用。请扫描其他批次。`,
  1991. `This lot (${scannedLot.lotNo || scannedStockInLineId}) is expired and cannot be used. Scan another lot.`,
  1992. ),
  1993. );
  1994. });
  1995. // Mark as processed to prevent re-processing the same expired QR repeatedly
  1996. setProcessedQrCombinations((prev) => {
  1997. const newMap = new Map(prev);
  1998. if (!newMap.has(scannedItemId))
  1999. newMap.set(scannedItemId, new Set());
  2000. newMap.get(scannedItemId)!.add(scannedStockInLineId);
  2001. return newMap;
  2002. });
  2003. return;
  2004. }
  2005. }
  2006. // ✅ If no active suggested lots, auto-switch to scanned lot (no modal)
  2007. if (activeSuggestedLots.length === 0) {
  2008. // Check if there are any lots for this item (even if all are rejected)
  2009. if (allLotsForItem.length === 0) {
  2010. console.error("No lots found for this item");
  2011. startTransition(() => {
  2012. setQrScanError(true);
  2013. setQrScanSuccess(false);
  2014. setQrScanErrorMsg(L("当前订单中没有此物品的批次信息", "This order has no lot information for this item"));
  2015. });
  2016. return;
  2017. }
  2018. console.log(
  2019. `⚠️ [QR PROCESS] No active suggested lots, auto-switching to scanned lot.`,
  2020. );
  2021. // Find a rejected lot as expected lot (the one that was rejected)
  2022. const rejectedLot = allLotsForItem.find(
  2023. (lot: any) =>
  2024. lot.stockOutLineStatus?.toLowerCase() === "rejected" ||
  2025. lot.lotAvailability === "rejected" ||
  2026. isInventoryLotLineUnavailable(lot),
  2027. );
  2028. const expectedLot =
  2029. rejectedLot ||
  2030. pickExpectedLotForSubstitution(
  2031. allLotsForItem.filter(
  2032. (l: any) => l.lotNo != null && String(l.lotNo).trim() !== "",
  2033. ),
  2034. ) ||
  2035. allLotsForItem[0];
  2036. let scannedLotNo: string | null = scannedLot?.lotNo || null;
  2037. if (!scannedLotNo) {
  2038. try {
  2039. const info =
  2040. await fetchStockInLineInfoCached(scannedStockInLineId);
  2041. scannedLotNo = info?.lotNo || null;
  2042. } catch (e) {
  2043. console.warn(
  2044. "Failed to fetch lotNo for stockInLineId:",
  2045. scannedStockInLineId,
  2046. e,
  2047. );
  2048. }
  2049. }
  2050. if (!scannedLotNo) {
  2051. startTransition(() => {
  2052. setQrScanError(true);
  2053. setQrScanSuccess(false);
  2054. setQrScanErrorMsg(
  2055. tPick(
  2056. "Cannot resolve lot number from QR. Please rescan or use manual confirmation.",
  2057. ),
  2058. );
  2059. });
  2060. return;
  2061. }
  2062. if (!workbenchMode) {
  2063. const substitutionResult = await confirmLotSubstitution({
  2064. pickOrderLineId: expectedLot.pickOrderLineId,
  2065. stockOutLineId: expectedLot.stockOutLineId,
  2066. originalSuggestedPickLotId: expectedLot.suggestedPickLotId,
  2067. newInventoryLotNo: "",
  2068. newStockInLineId: scannedStockInLineId,
  2069. });
  2070. const substitutionCode = (substitutionResult as any)?.code;
  2071. const switchedToUnavailable =
  2072. substitutionCode === "SUCCESS_UNAVAILABLE" ||
  2073. substitutionCode === "BOUND_UNAVAILABLE";
  2074. if (
  2075. !substitutionResult ||
  2076. (substitutionCode !== "SUCCESS" && !switchedToUnavailable)
  2077. ) {
  2078. const errMsg =
  2079. substitutionResult?.message ||
  2080. tPick("Lot switch failed; pick line was not updated.");
  2081. startTransition(() => {
  2082. setQrScanError(true);
  2083. setQrScanSuccess(false);
  2084. setQrScanErrorMsg(errMsg);
  2085. });
  2086. if (expectedLot.stockOutLineId != null) {
  2087. rememberWorkbenchScanReject(
  2088. Number(expectedLot.stockOutLineId),
  2089. errMsg,
  2090. );
  2091. }
  2092. return;
  2093. }
  2094. }
  2095. const res = await workbenchScanPick({
  2096. stockOutLineId: expectedLot.stockOutLineId,
  2097. lotNo: scannedLotNo,
  2098. ...(typeof scannedStockInLineId === "number" &&
  2099. Number.isFinite(scannedStockInLineId) &&
  2100. scannedStockInLineId > 0
  2101. ? { stockInLineId: scannedStockInLineId }
  2102. : {}),
  2103. ...workbenchScanPickQtyFromLot(expectedLot),
  2104. storeId: workbenchStoreId,
  2105. userId: currentUserId ?? 1,
  2106. });
  2107. const ok = res.code === "SUCCESS";
  2108. if (!ok) {
  2109. const failMsg =
  2110. (res as { message?: string })?.message ||
  2111. tPick("Workbench scan-pick failed.");
  2112. if (
  2113. shouldOpenWorkbenchLotLabelModalForFailure(res.code, failMsg) &&
  2114. expectedLot
  2115. ) {
  2116. openWorkbenchLotLabelModalForLot(expectedLot, failMsg);
  2117. return;
  2118. }
  2119. if (workbenchMode && expectedLot.stockOutLineId != null) {
  2120. rememberWorkbenchScanReject(
  2121. Number(expectedLot.stockOutLineId),
  2122. failMsg,
  2123. );
  2124. }
  2125. startTransition(() => {
  2126. setQrScanError(true);
  2127. setQrScanSuccess(false);
  2128. setQrScanErrorMsg(failMsg);
  2129. });
  2130. return;
  2131. }
  2132. clearWorkbenchScanReject(Number(expectedLot.stockOutLineId));
  2133. startTransition(() => {
  2134. setQrScanError(false);
  2135. setQrScanSuccess(true);
  2136. });
  2137. setProcessedQrCombinations((prev) => {
  2138. const newMap = new Map(prev);
  2139. if (!newMap.has(scannedItemId))
  2140. newMap.set(scannedItemId, new Set());
  2141. newMap.get(scannedItemId)!.add(scannedStockInLineId);
  2142. return newMap;
  2143. });
  2144. if (workbenchMode) {
  2145. await refreshWorkbenchAfterScanPick();
  2146. }
  2147. return;
  2148. }
  2149. // ✅ OPTIMIZATION: Direct Map lookup for stockInLineId match (O(1))
  2150. const matchStartTime = performance.now();
  2151. let exactMatch: any = null;
  2152. const stockInLineLots =
  2153. indexes.byStockInLineId.get(scannedStockInLineId) || [];
  2154. // Find exact match from stockInLineId index, then verify it's in active lots
  2155. for (let i = 0; i < stockInLineLots.length; i++) {
  2156. const lot = stockInLineLots[i];
  2157. if (
  2158. lot.itemId === scannedItemId &&
  2159. activeSuggestedLots.includes(lot)
  2160. ) {
  2161. exactMatch = lot;
  2162. break;
  2163. }
  2164. }
  2165. const matchTime = performance.now() - matchStartTime;
  2166. console.log(
  2167. ` [PERF] Find exact match time: ${matchTime.toFixed(2)}ms, found: ${
  2168. exactMatch ? "yes" : "no"
  2169. }`,
  2170. );
  2171. // ✅ Check if scanned lot exists in allLotsForItem but not in activeSuggestedLots
  2172. // This handles the case where Lot A is rejected and user scans Lot B
  2173. // Also handle case where scanned lot is not in allLotsForItem (scannedLot is undefined)
  2174. if (!exactMatch) {
  2175. const expectedLot =
  2176. pickExpectedLotForSubstitution(activeSuggestedLots) ||
  2177. allLotsForItem[0];
  2178. if (expectedLot) {
  2179. const shouldAutoSwitch =
  2180. !scannedLot ||
  2181. scannedLot.stockInLineId !== expectedLot.stockInLineId;
  2182. if (shouldAutoSwitch) {
  2183. console.log(
  2184. `⚠️ [QR PROCESS] Auto-switching (scanned lot ${
  2185. scannedLot?.lotNo || "not in data"
  2186. } is not in active suggested lots)`,
  2187. );
  2188. let scannedLotNo: string | null = scannedLot?.lotNo || null;
  2189. if (!scannedLotNo) {
  2190. try {
  2191. const info =
  2192. await fetchStockInLineInfoCached(scannedStockInLineId);
  2193. scannedLotNo = info?.lotNo || null;
  2194. } catch (e) {
  2195. console.warn(
  2196. "Failed to fetch lotNo for stockInLineId:",
  2197. scannedStockInLineId,
  2198. e,
  2199. );
  2200. }
  2201. }
  2202. if (!scannedLotNo) {
  2203. startTransition(() => {
  2204. setQrScanError(true);
  2205. setQrScanSuccess(false);
  2206. setQrScanErrorMsg(
  2207. tPick(
  2208. "Cannot resolve lot number from QR. Please rescan or use manual confirmation.",
  2209. ),
  2210. );
  2211. });
  2212. return;
  2213. }
  2214. if (!workbenchMode) {
  2215. const substitutionResult = await confirmLotSubstitution({
  2216. pickOrderLineId: expectedLot.pickOrderLineId,
  2217. stockOutLineId: expectedLot.stockOutLineId,
  2218. originalSuggestedPickLotId: expectedLot.suggestedPickLotId,
  2219. newInventoryLotNo: "",
  2220. newStockInLineId: scannedStockInLineId,
  2221. });
  2222. const substitutionCode = (substitutionResult as any)?.code;
  2223. const switchedToUnavailable =
  2224. substitutionCode === "SUCCESS_UNAVAILABLE" ||
  2225. substitutionCode === "BOUND_UNAVAILABLE";
  2226. if (
  2227. !substitutionResult ||
  2228. (substitutionCode !== "SUCCESS" && !switchedToUnavailable)
  2229. ) {
  2230. const errMsg =
  2231. substitutionResult?.message ||
  2232. tPick("Lot switch failed; pick line was not updated.");
  2233. startTransition(() => {
  2234. setQrScanError(true);
  2235. setQrScanSuccess(false);
  2236. setQrScanErrorMsg(errMsg);
  2237. });
  2238. if (expectedLot.stockOutLineId != null) {
  2239. rememberWorkbenchScanReject(
  2240. Number(expectedLot.stockOutLineId),
  2241. errMsg,
  2242. );
  2243. }
  2244. return;
  2245. }
  2246. }
  2247. const res = await workbenchScanPick({
  2248. stockOutLineId: expectedLot.stockOutLineId,
  2249. lotNo: scannedLotNo,
  2250. ...(typeof scannedStockInLineId === "number" &&
  2251. Number.isFinite(scannedStockInLineId) &&
  2252. scannedStockInLineId > 0
  2253. ? { stockInLineId: scannedStockInLineId }
  2254. : {}),
  2255. ...workbenchScanPickQtyFromLot(expectedLot),
  2256. storeId: workbenchStoreId,
  2257. userId: currentUserId ?? 1,
  2258. });
  2259. const ok = res.code === "SUCCESS";
  2260. if (!ok) {
  2261. const failMsg =
  2262. (res as { message?: string })?.message ||
  2263. tPick("Workbench scan-pick failed.");
  2264. if (
  2265. shouldOpenWorkbenchLotLabelModalForFailure(res.code, failMsg) &&
  2266. expectedLot
  2267. ) {
  2268. openWorkbenchLotLabelModalForLot(expectedLot, failMsg);
  2269. return;
  2270. }
  2271. if (workbenchMode && expectedLot.stockOutLineId != null) {
  2272. rememberWorkbenchScanReject(
  2273. Number(expectedLot.stockOutLineId),
  2274. failMsg,
  2275. );
  2276. }
  2277. startTransition(() => {
  2278. setQrScanError(true);
  2279. setQrScanSuccess(false);
  2280. setQrScanErrorMsg(failMsg);
  2281. });
  2282. return;
  2283. }
  2284. clearWorkbenchScanReject(Number(expectedLot.stockOutLineId));
  2285. startTransition(() => {
  2286. setQrScanError(false);
  2287. setQrScanSuccess(true);
  2288. });
  2289. setProcessedQrCombinations((prev) => {
  2290. const newMap = new Map(prev);
  2291. if (!newMap.has(scannedItemId))
  2292. newMap.set(scannedItemId, new Set());
  2293. newMap.get(scannedItemId)!.add(scannedStockInLineId);
  2294. return newMap;
  2295. });
  2296. if (workbenchMode) {
  2297. await refreshWorkbenchAfterScanPick();
  2298. }
  2299. return;
  2300. }
  2301. }
  2302. }
  2303. if (exactMatch) {
  2304. // ✅ Case 1: stockInLineId 匹配 - 直接处理,不需要确认
  2305. console.log(
  2306. `✅ Exact stockInLineId match found for lot: ${exactMatch.lotNo}`,
  2307. );
  2308. if (!exactMatch.stockOutLineId) {
  2309. console.warn(
  2310. "No stockOutLineId on exactMatch, cannot update status by QR.",
  2311. );
  2312. startTransition(() => {
  2313. setQrScanError(true);
  2314. setQrScanSuccess(false);
  2315. });
  2316. return;
  2317. }
  2318. try {
  2319. const apiStartTime = performance.now();
  2320. console.log(
  2321. workbenchMode
  2322. ? ` [API CALL START] workbenchScanPick`
  2323. : ` [API CALL START] Calling updateStockOutLineStatusByQRCodeAndLotNo`,
  2324. );
  2325. console.log(
  2326. ` [API CALL] API start time: ${new Date().toISOString()}`,
  2327. );
  2328. const res = await workbenchScanPick({
  2329. stockOutLineId: exactMatch.stockOutLineId,
  2330. lotNo: exactMatch.lotNo,
  2331. ...(typeof scannedStockInLineId === "number" &&
  2332. Number.isFinite(scannedStockInLineId) &&
  2333. scannedStockInLineId > 0
  2334. ? { stockInLineId: scannedStockInLineId }
  2335. : typeof exactMatch.stockInLineId === "number" &&
  2336. Number.isFinite(exactMatch.stockInLineId) &&
  2337. exactMatch.stockInLineId > 0
  2338. ? { stockInLineId: exactMatch.stockInLineId }
  2339. : {}),
  2340. ...workbenchScanPickQtyFromLot(exactMatch),
  2341. storeId: workbenchStoreId,
  2342. userId: currentUserId ?? 1,
  2343. });
  2344. const apiTime = performance.now() - apiStartTime;
  2345. console.log(
  2346. ` [API CALL END] Total API time: ${apiTime.toFixed(2)}ms (${(
  2347. apiTime / 1000
  2348. ).toFixed(3)}s)`,
  2349. );
  2350. console.log(
  2351. ` [API CALL] API end time: ${new Date().toISOString()}`,
  2352. );
  2353. const ok = res.code === "SUCCESS";
  2354. if (ok) {
  2355. clearWorkbenchScanReject(Number(exactMatch.stockOutLineId));
  2356. // ✅ Batch state updates using startTransition
  2357. const stateUpdateStartTime = performance.now();
  2358. startTransition(() => {
  2359. setQrScanError(false);
  2360. setQrScanSuccess(true);
  2361. });
  2362. const stateUpdateTime = performance.now() - stateUpdateStartTime;
  2363. console.log(
  2364. ` [PERF] State update time: ${stateUpdateTime.toFixed(2)}ms`,
  2365. );
  2366. // Mark this combination as processed
  2367. const markProcessedStartTime = performance.now();
  2368. setProcessedQrCombinations((prev) => {
  2369. const newMap = new Map(prev);
  2370. if (!newMap.has(scannedItemId)) {
  2371. newMap.set(scannedItemId, new Set());
  2372. }
  2373. newMap.get(scannedItemId)!.add(scannedStockInLineId);
  2374. return newMap;
  2375. });
  2376. const markProcessedTime =
  2377. performance.now() - markProcessedStartTime;
  2378. console.log(
  2379. ` [PERF] Mark processed time: ${markProcessedTime.toFixed(
  2380. 2,
  2381. )}ms`,
  2382. );
  2383. if (workbenchMode) {
  2384. await refreshWorkbenchAfterScanPick();
  2385. }
  2386. const totalTime = performance.now() - totalStartTime;
  2387. console.log(
  2388. `✅ [PROCESS OUTSIDE QR END] Total time: ${totalTime.toFixed(
  2389. 2,
  2390. )}ms (${(totalTime / 1000).toFixed(3)}s)`,
  2391. );
  2392. console.log(` End time: ${new Date().toISOString()}`);
  2393. console.log(
  2394. `📊 Breakdown: parse=${parseTime.toFixed(
  2395. 2,
  2396. )}ms, validation=${validationTime.toFixed(
  2397. 2,
  2398. )}ms, duplicateCheck=${duplicateCheckTime.toFixed(
  2399. 2,
  2400. )}ms, lookup=${lookupTime.toFixed(
  2401. 2,
  2402. )}ms, match=${matchTime.toFixed(2)}ms, api=${apiTime.toFixed(
  2403. 2,
  2404. )}ms, stateUpdate=${stateUpdateTime.toFixed(
  2405. 2,
  2406. )}ms, markProcessed=${markProcessedTime.toFixed(2)}ms`,
  2407. );
  2408. console.log(
  2409. workbenchMode
  2410. ? "✅ Workbench scan-pick: list refreshed from server"
  2411. : "✅ Status updated locally, no full data refresh needed",
  2412. );
  2413. } else {
  2414. console.warn("Unexpected response code from backend:", res.code);
  2415. const failMsg =
  2416. (res as { message?: string })?.message ||
  2417. tPick("Workbench scan-pick failed.");
  2418. if (
  2419. shouldOpenWorkbenchLotLabelModalForFailure(res.code, failMsg) &&
  2420. exactMatch
  2421. ) {
  2422. openWorkbenchLotLabelModalForLot(exactMatch, failMsg);
  2423. return;
  2424. }
  2425. if (workbenchMode && exactMatch.stockOutLineId != null) {
  2426. rememberWorkbenchScanReject(
  2427. Number(exactMatch.stockOutLineId),
  2428. failMsg,
  2429. );
  2430. }
  2431. startTransition(() => {
  2432. setQrScanError(true);
  2433. setQrScanSuccess(false);
  2434. setQrScanErrorMsg(failMsg);
  2435. });
  2436. }
  2437. } catch (e) {
  2438. const totalTime = performance.now() - totalStartTime;
  2439. console.error(
  2440. `❌ [PROCESS OUTSIDE QR ERROR] Total time: ${totalTime.toFixed(
  2441. 2,
  2442. )}ms`,
  2443. );
  2444. console.error(
  2445. "Error calling updateStockOutLineStatusByQRCodeAndLotNo:",
  2446. e,
  2447. );
  2448. startTransition(() => {
  2449. setQrScanError(true);
  2450. setQrScanSuccess(false);
  2451. });
  2452. }
  2453. return; // ✅ 直接返回,不需要确认表单
  2454. }
  2455. // ✅ Case 2: itemId 匹配但 stockInLineId 不匹配
  2456. // Workbench 策略:不彈窗,直接切換到掃到的批次並提交一次掃描
  2457. const mismatchCheckStartTime = performance.now();
  2458. const itemProcessedSet2 = processedQrCombinations.get(scannedItemId);
  2459. if (itemProcessedSet2?.has(scannedStockInLineId)) {
  2460. const mismatchCheckTime = performance.now() - mismatchCheckStartTime;
  2461. console.log(
  2462. ` [SKIP] Already processed this exact combination (check time: ${mismatchCheckTime.toFixed(
  2463. 2,
  2464. )}ms)`,
  2465. );
  2466. return;
  2467. }
  2468. const mismatchCheckTime = performance.now() - mismatchCheckStartTime;
  2469. console.log(
  2470. ` [PERF] Mismatch check time: ${mismatchCheckTime.toFixed(2)}ms`,
  2471. );
  2472. const expectedLotStartTime = performance.now();
  2473. const expectedLot = pickExpectedLotForSubstitution(activeSuggestedLots);
  2474. if (!expectedLot) {
  2475. console.error("Could not determine expected lot for auto-switch");
  2476. startTransition(() => {
  2477. setQrScanError(true);
  2478. setQrScanSuccess(false);
  2479. });
  2480. return;
  2481. }
  2482. const expectedLotTime = performance.now() - expectedLotStartTime;
  2483. console.log(
  2484. ` [PERF] Get expected lot time: ${expectedLotTime.toFixed(2)}ms`,
  2485. );
  2486. console.log(
  2487. `⚠️ Lot mismatch (auto): Expected stockInLineId=${expectedLot.stockInLineId}, Scanned stockInLineId=${scannedStockInLineId}`,
  2488. );
  2489. // 1) 先把掃到的 stockInLineId 轉成 lotNo(workbenchScanPick 需要 lotNo)
  2490. let scannedLotNo: string | null = null;
  2491. try {
  2492. const info = await fetchStockInLineInfoCached(scannedStockInLineId);
  2493. scannedLotNo = info?.lotNo || null;
  2494. } catch (e) {
  2495. console.warn(
  2496. "Failed to fetch lotNo for stockInLineId:",
  2497. scannedStockInLineId,
  2498. e,
  2499. );
  2500. }
  2501. if (!scannedLotNo) {
  2502. const msg = tPick(
  2503. "Cannot resolve lot number from QR. Please rescan or use manual confirmation.",
  2504. );
  2505. setQrScanError(true);
  2506. setQrScanSuccess(false);
  2507. setQrScanErrorMsg(msg);
  2508. return;
  2509. }
  2510. // 2) 非 workbench:先 confirmLotSubstitution;workbench 僅依 scan-pick 規則與錯誤訊息
  2511. if (!workbenchMode) {
  2512. const substitutionResult = await confirmLotSubstitution({
  2513. pickOrderLineId: expectedLot.pickOrderLineId,
  2514. stockOutLineId: expectedLot.stockOutLineId,
  2515. originalSuggestedPickLotId: expectedLot.suggestedPickLotId,
  2516. newInventoryLotNo: "",
  2517. newStockInLineId: scannedStockInLineId,
  2518. });
  2519. const substitutionCode = (substitutionResult as any)?.code;
  2520. const switchedToUnavailable =
  2521. substitutionCode === "SUCCESS_UNAVAILABLE" ||
  2522. substitutionCode === "BOUND_UNAVAILABLE";
  2523. if (
  2524. !substitutionResult ||
  2525. (substitutionCode !== "SUCCESS" && !switchedToUnavailable)
  2526. ) {
  2527. const errMsg =
  2528. substitutionResult?.message ||
  2529. tPick("Lot switch failed; pick line was not updated.");
  2530. setQrScanError(true);
  2531. setQrScanSuccess(false);
  2532. setQrScanErrorMsg(errMsg);
  2533. if (expectedLot.stockOutLineId != null) {
  2534. rememberWorkbenchScanReject(
  2535. Number(expectedLot.stockOutLineId),
  2536. errMsg,
  2537. );
  2538. }
  2539. return;
  2540. }
  2541. }
  2542. // 3) 提交掃描(workbench:直接 workbenchScanPick)
  2543. try {
  2544. const res = await workbenchScanPick({
  2545. stockOutLineId: expectedLot.stockOutLineId,
  2546. lotNo: scannedLotNo,
  2547. ...(typeof scannedStockInLineId === "number" &&
  2548. Number.isFinite(scannedStockInLineId) &&
  2549. scannedStockInLineId > 0
  2550. ? { stockInLineId: scannedStockInLineId }
  2551. : {}),
  2552. ...workbenchScanPickQtyFromLot(expectedLot),
  2553. storeId: workbenchStoreId,
  2554. userId: currentUserId ?? 1,
  2555. });
  2556. const ok = res.code === "SUCCESS";
  2557. if (!ok) {
  2558. const failMsg =
  2559. (res as { message?: string })?.message ||
  2560. tPick("Workbench scan-pick failed.");
  2561. if (
  2562. shouldOpenWorkbenchLotLabelModalForFailure(res.code, failMsg) &&
  2563. expectedLot
  2564. ) {
  2565. openWorkbenchLotLabelModalForLot(expectedLot, failMsg);
  2566. return;
  2567. }
  2568. if (workbenchMode && expectedLot.stockOutLineId != null) {
  2569. rememberWorkbenchScanReject(
  2570. Number(expectedLot.stockOutLineId),
  2571. failMsg,
  2572. );
  2573. }
  2574. setQrScanError(true);
  2575. setQrScanSuccess(false);
  2576. setQrScanErrorMsg(failMsg);
  2577. return;
  2578. }
  2579. clearWorkbenchScanReject(Number(expectedLot.stockOutLineId));
  2580. startTransition(() => {
  2581. setQrScanError(false);
  2582. setQrScanSuccess(true);
  2583. });
  2584. setProcessedQrCombinations((prev) => {
  2585. const newMap = new Map(prev);
  2586. if (!newMap.has(scannedItemId))
  2587. newMap.set(scannedItemId, new Set());
  2588. newMap.get(scannedItemId)!.add(scannedStockInLineId);
  2589. return newMap;
  2590. });
  2591. if (workbenchMode) {
  2592. await refreshWorkbenchAfterScanPick();
  2593. }
  2594. } catch (e) {
  2595. console.error("Auto-switch scanPick failed:", e);
  2596. setQrScanError(true);
  2597. setQrScanSuccess(false);
  2598. return;
  2599. }
  2600. const totalTime = performance.now() - totalStartTime;
  2601. console.log(
  2602. `✅ [PROCESS OUTSIDE QR AUTO-SWITCH] Total time: ${totalTime.toFixed(
  2603. 2,
  2604. )}ms (${(totalTime / 1000).toFixed(3)}s)`,
  2605. );
  2606. console.log(` End time: ${new Date().toISOString()}`);
  2607. console.log(
  2608. `📊 Breakdown: parse=${parseTime.toFixed(
  2609. 2,
  2610. )}ms, validation=${validationTime.toFixed(
  2611. 2,
  2612. )}ms, duplicateCheck=${duplicateCheckTime.toFixed(
  2613. 2,
  2614. )}ms, lookup=${lookupTime.toFixed(2)}ms, match=${matchTime.toFixed(
  2615. 2,
  2616. )}ms, mismatchCheck=${mismatchCheckTime.toFixed(
  2617. 2,
  2618. )}ms, expectedLot=${expectedLotTime.toFixed(2)}ms`,
  2619. );
  2620. } catch (error) {
  2621. const totalTime = performance.now() - totalStartTime;
  2622. console.error(
  2623. `❌ [PROCESS OUTSIDE QR ERROR] Total time: ${totalTime.toFixed(2)}ms`,
  2624. );
  2625. console.error("Error during QR code processing:", error);
  2626. startTransition(() => {
  2627. setQrScanError(true);
  2628. setQrScanSuccess(false);
  2629. });
  2630. return;
  2631. }
  2632. },
  2633. [
  2634. lotDataIndexes,
  2635. processedQrCombinations,
  2636. combinedLotData,
  2637. fetchStockInLineInfoCached,
  2638. workbenchMode,
  2639. currentUserId,
  2640. clearWorkbenchScanReject,
  2641. rememberWorkbenchScanReject,
  2642. refreshWorkbenchAfterScanPick,
  2643. workbenchScanPickQtyFromLot,
  2644. tPick,
  2645. workbenchStoreId,
  2646. confirmLotSubstitution,
  2647. openWorkbenchLotLabelModalForLot,
  2648. shouldOpenWorkbenchLotLabelModalForFailure,
  2649. ],
  2650. );
  2651. // Store in refs for immediate access in qrValues effect
  2652. processOutsideQrCodeRef.current = processOutsideQrCode;
  2653. resetScanRef.current = resetScan;
  2654. const handleManualInputSubmit = useCallback(() => {
  2655. if (qrScanInput.trim() !== "") {
  2656. handleQrCodeSubmit(qrScanInput.trim());
  2657. }
  2658. }, [qrScanInput, handleQrCodeSubmit]);
  2659. // Handle QR code submission from modal (internal scanning)
  2660. const handleQrCodeSubmitFromModal = useCallback(
  2661. async (lotNo: string) => {
  2662. if (selectedLotForQr && selectedLotForQr.lotNo === lotNo) {
  2663. console.log(` QR Code verified for lot: ${lotNo}`);
  2664. const requiredQty = selectedLotForQr.requiredQty;
  2665. const lotId = selectedLotForQr.lotId;
  2666. // Create stock out line
  2667. const stockOutLineData: CreateStockOutLine = {
  2668. consoCode: selectedLotForQr.pickOrderConsoCode,
  2669. pickOrderLineId: selectedLotForQr.pickOrderLineId,
  2670. inventoryLotLineId: selectedLotForQr.lotId,
  2671. qty: 0.0,
  2672. };
  2673. try {
  2674. await createStockOutLine(stockOutLineData);
  2675. console.log("Stock out line created successfully!");
  2676. // Close modal
  2677. setQrModalOpen(false);
  2678. setSelectedLotForQr(null);
  2679. // Set pick quantity
  2680. const lotKey = `${selectedLotForQr.pickOrderLineId}-${lotId}`;
  2681. setTimeout(() => {
  2682. setPickQtyData((prev) => ({
  2683. ...prev,
  2684. [lotKey]: requiredQty,
  2685. }));
  2686. console.log(
  2687. ` Auto-set pick quantity to ${requiredQty} for lot ${lotNo}`,
  2688. );
  2689. }, 500);
  2690. // Refresh data
  2691. const pickOrderId = filterArgs?.pickOrderId
  2692. ? Number(filterArgs.pickOrderId)
  2693. : undefined;
  2694. await fetchJobOrderData(pickOrderId);
  2695. } catch (error) {
  2696. console.error("Error creating stock out line:", error);
  2697. }
  2698. }
  2699. },
  2700. [selectedLotForQr, fetchJobOrderData],
  2701. );
  2702. useEffect(() => {
  2703. // Skip if scanner not active or no data or currently refreshing
  2704. if (
  2705. !isManualScanning ||
  2706. qrValues.length === 0 ||
  2707. combinedLotData.length === 0 ||
  2708. isRefreshingData
  2709. )
  2710. return;
  2711. const latestQr = qrValues[qrValues.length - 1];
  2712. // ✅ Test shortcut: {2fitestx,y} or {2fittestx,y} where x=itemId, y=stockInLineId
  2713. if (
  2714. (latestQr.startsWith("{2fitest") || latestQr.startsWith("{2fittest")) &&
  2715. latestQr.endsWith("}")
  2716. ) {
  2717. let content = "";
  2718. if (latestQr.startsWith("{2fittest"))
  2719. content = latestQr.substring(9, latestQr.length - 1);
  2720. else content = latestQr.substring(8, latestQr.length - 1);
  2721. const parts = content.split(",");
  2722. if (parts.length === 2) {
  2723. const itemId = parseInt(parts[0].trim(), 10);
  2724. const stockInLineId = parseInt(parts[1].trim(), 10);
  2725. if (!isNaN(itemId) && !isNaN(stockInLineId)) {
  2726. const simulatedQr = JSON.stringify({ itemId, stockInLineId });
  2727. lastProcessedQrRef.current = latestQr;
  2728. processedQrCodesRef.current.add(latestQr);
  2729. setLastProcessedQr(latestQr);
  2730. setProcessedQrCodes(new Set(processedQrCodesRef.current));
  2731. processOutsideQrCodeRef.current?.(simulatedQr);
  2732. resetScanRef.current?.();
  2733. return;
  2734. }
  2735. }
  2736. }
  2737. // ✅ Shortcut: {2fic} open manual lot confirmation modal
  2738. if (latestQr === "{2fic}") {
  2739. setManualLotConfirmationOpen(true);
  2740. resetScanRef.current?.();
  2741. lastProcessedQrRef.current = latestQr;
  2742. processedQrCodesRef.current.add(latestQr);
  2743. setLastProcessedQr(latestQr);
  2744. setProcessedQrCodes(new Set(processedQrCodesRef.current));
  2745. return;
  2746. }
  2747. // Skip processing if manual modal open for same QR
  2748. if (manualLotConfirmationOpen) {
  2749. if (latestQr === lastProcessedQrRef.current) return;
  2750. }
  2751. // Skip if already processed (refs)
  2752. if (
  2753. processedQrCodesRef.current.has(latestQr) ||
  2754. lastProcessedQrRef.current === latestQr
  2755. )
  2756. return;
  2757. // Mark processed immediately
  2758. lastProcessedQrRef.current = latestQr;
  2759. processedQrCodesRef.current.add(latestQr);
  2760. if (processedQrCodesRef.current.size > 100) {
  2761. const firstValue = processedQrCodesRef.current.values().next().value;
  2762. if (firstValue !== undefined)
  2763. processedQrCodesRef.current.delete(firstValue);
  2764. }
  2765. // Process immediately
  2766. if (qrProcessingTimeoutRef.current) {
  2767. clearTimeout(qrProcessingTimeoutRef.current);
  2768. qrProcessingTimeoutRef.current = null;
  2769. }
  2770. processOutsideQrCodeRef.current?.(latestQr);
  2771. // UI state updates (non-blocking)
  2772. startTransition(() => {
  2773. setLastProcessedQr(latestQr);
  2774. setProcessedQrCodes(new Set(processedQrCodesRef.current));
  2775. });
  2776. return () => {
  2777. if (qrProcessingTimeoutRef.current) {
  2778. clearTimeout(qrProcessingTimeoutRef.current);
  2779. qrProcessingTimeoutRef.current = null;
  2780. }
  2781. };
  2782. }, [
  2783. qrValues.length,
  2784. isManualScanning,
  2785. isRefreshingData,
  2786. combinedLotData.length,
  2787. manualLotConfirmationOpen,
  2788. isConfirmingLot,
  2789. ]);
  2790. const handlePickQtyChange = useCallback(
  2791. (lotKey: string, value: number | string) => {
  2792. if (value === "" || value === null || value === undefined) {
  2793. setPickQtyData((prev) => ({
  2794. ...prev,
  2795. [lotKey]: 0,
  2796. }));
  2797. return;
  2798. }
  2799. const numericValue =
  2800. typeof value === "string" ? parseFloat(value) : value;
  2801. if (isNaN(numericValue)) {
  2802. setPickQtyData((prev) => ({
  2803. ...prev,
  2804. [lotKey]: 0,
  2805. }));
  2806. return;
  2807. }
  2808. setPickQtyData((prev) => ({
  2809. ...prev,
  2810. [lotKey]: numericValue,
  2811. }));
  2812. },
  2813. [],
  2814. );
  2815. const checkAndAutoAssignNext = useCallback(async () => {
  2816. if (!currentUserId) return;
  2817. try {
  2818. const completionResponse = await checkPickOrderCompletion(currentUserId);
  2819. if (
  2820. completionResponse.code === "SUCCESS" &&
  2821. completionResponse.entity?.hasCompletedOrders
  2822. ) {
  2823. console.log("Found completed pick orders, auto-assigning next...");
  2824. // 移除前端的自动分配逻辑,因为后端已经处理了
  2825. // await handleAutoAssignAndRelease(); // 删除这个函数
  2826. }
  2827. } catch (error) {
  2828. console.error("Error checking pick order completion:", error);
  2829. }
  2830. }, [currentUserId]);
  2831. const handleSubmitPickQtyWithQty = useCallback(
  2832. async (
  2833. lot: any,
  2834. submitQty: number,
  2835. source: "justComplete" | "singleSubmit",
  2836. ) => {
  2837. if (!lot.stockOutLineId) {
  2838. console.error("No stock out line found for this lot");
  2839. return;
  2840. }
  2841. const solId = Number(lot.stockOutLineId);
  2842. if (solId > 0 && actionBusyBySolId[solId]) {
  2843. console.warn("Action already in progress for stockOutLineId:", solId);
  2844. return;
  2845. }
  2846. const pickOrderIdForRefresh = filterArgs?.pickOrderId
  2847. ? Number(filterArgs.pickOrderId)
  2848. : undefined;
  2849. try {
  2850. if (solId > 0)
  2851. setActionBusyBySolId((prev) => ({ ...prev, [solId]: true }));
  2852. const targetUnavailable = isInventoryLotLineUnavailable(lot);
  2853. const effectiveSubmitQty =
  2854. targetUnavailable && submitQty > 0 ? 0 : submitQty;
  2855. const canonicalLotForSol =
  2856. solId > 0
  2857. ? combinedLotData.find((r) => Number(r.stockOutLineId) === solId) ??
  2858. lot
  2859. : lot;
  2860. if (workbenchMode && source === "justComplete") {
  2861. const solIdForOverride =
  2862. Number(canonicalLotForSol.stockOutLineId) || 0;
  2863. const lotIdForOverride = canonicalLotForSol.lotId;
  2864. const lotKeyForOverride =
  2865. Number.isFinite(solIdForOverride) && solIdForOverride > 0
  2866. ? `sol:${solIdForOverride}`
  2867. : `${canonicalLotForSol.pickOrderLineId}-${lotIdForOverride}`;
  2868. const hasExplicitSubmitOverride =
  2869. Object.prototype.hasOwnProperty.call(
  2870. pickQtyData,
  2871. lotKeyForOverride,
  2872. );
  2873. const explicitSubmitOverride = hasExplicitSubmitOverride
  2874. ? Number(pickQtyData[lotKeyForOverride])
  2875. : NaN;
  2876. const qtyPayload = workbenchScanPickQtyFromLot(canonicalLotForSol);
  2877. const wbJustQty = qtyPayload.qty;
  2878. const isUnavailableForJustComplete =
  2879. isInventoryLotLineUnavailable(canonicalLotForSol);
  2880. const isNoLotForJustComplete =
  2881. canonicalLotForSol.noLot === true ||
  2882. !String(canonicalLotForSol.lotNo ?? "").trim();
  2883. const canPostScanPick =
  2884. // unavailable lot: Just Completed must always submit qty=0, even without lotNo
  2885. isUnavailableForJustComplete ||
  2886. isLotAvailabilityExpired(canonicalLotForSol) ||
  2887. // noLot row: Just Completed always submit qty=0
  2888. isNoLotForJustComplete ||
  2889. (canonicalLotForSol.lotNo &&
  2890. String(canonicalLotForSol.lotNo).trim() !== "" &&
  2891. ((hasExplicitSubmitOverride &&
  2892. Number.isFinite(explicitSubmitOverride) &&
  2893. explicitSubmitOverride === 0) ||
  2894. (wbJustQty != null && wbJustQty > 0)));
  2895. if (canPostScanPick) {
  2896. const qtyToSend =
  2897. isUnavailableForJustComplete
  2898. ? 0
  2899. : isLotAvailabilityExpired(canonicalLotForSol)
  2900. ? 0
  2901. : isNoLotForJustComplete
  2902. ? 0
  2903. : hasExplicitSubmitOverride && explicitSubmitOverride === 0
  2904. ? 0
  2905. : Number(wbJustQty);
  2906. const res = await workbenchScanPick({
  2907. stockOutLineId: Number(canonicalLotForSol.stockOutLineId),
  2908. lotNo: String(canonicalLotForSol.lotNo).trim(),
  2909. ...(typeof canonicalLotForSol.stockInLineId === "number" &&
  2910. Number.isFinite(canonicalLotForSol.stockInLineId) &&
  2911. canonicalLotForSol.stockInLineId > 0
  2912. ? { stockInLineId: canonicalLotForSol.stockInLineId }
  2913. : {}),
  2914. qty: qtyToSend,
  2915. storeId: workbenchStoreId,
  2916. userId: currentUserId ?? 1,
  2917. });
  2918. const scanOk = res.code === "SUCCESS";
  2919. if (!scanOk) {
  2920. rememberWorkbenchScanReject(
  2921. Number(canonicalLotForSol.stockOutLineId),
  2922. (res as { message?: string })?.message,
  2923. );
  2924. throw new Error(
  2925. (res as { message?: string })?.message ||
  2926. "Workbench scan-pick failed",
  2927. );
  2928. }
  2929. clearWorkbenchScanReject(Number(canonicalLotForSol.stockOutLineId));
  2930. setPickQtyData((prev) => {
  2931. if (!Object.prototype.hasOwnProperty.call(prev, lotKeyForOverride))
  2932. return prev;
  2933. const next = { ...prev };
  2934. delete next[lotKeyForOverride];
  2935. return next;
  2936. });
  2937. await refreshWorkbenchAfterScanPick();
  2938. setTimeout(() => {
  2939. checkAndAutoAssignNext();
  2940. }, 1000);
  2941. console.log(
  2942. "Just Completed (workbench): workbenchScanPick posted without QR.",
  2943. );
  2944. return;
  2945. }
  2946. const justCompleteErr = t(
  2947. "Just Completed (workbench): requires valid quantity; expired rows must not use this button.",
  2948. );
  2949. if (solId > 0) {
  2950. rememberWorkbenchScanReject(solId, justCompleteErr);
  2951. }
  2952. setQrScanErrorMsg(justCompleteErr);
  2953. throw new Error(justCompleteErr);
  2954. }
  2955. if (effectiveSubmitQty === 0 && source === "singleSubmit") {
  2956. console.log(`=== SUBMITTING ALL ZEROS CASE ===`);
  2957. console.log(`Lot: ${lot.lotNo}`);
  2958. console.log(`Stock Out Line ID: ${lot.stockOutLineId}`);
  2959. if (workbenchMode) {
  2960. const res = await workbenchScanPick({
  2961. stockOutLineId: Number(lot.stockOutLineId),
  2962. lotNo: String(lot.lotNo ?? "").trim(),
  2963. ...(typeof lot.stockInLineId === "number" &&
  2964. Number.isFinite(lot.stockInLineId) &&
  2965. lot.stockInLineId > 0
  2966. ? { stockInLineId: lot.stockInLineId }
  2967. : {}),
  2968. qty: 0,
  2969. storeId: workbenchStoreId,
  2970. userId: currentUserId ?? 1,
  2971. });
  2972. const scanOk = res.code === "SUCCESS";
  2973. if (!scanOk) {
  2974. rememberWorkbenchScanReject(
  2975. Number(lot.stockOutLineId),
  2976. (res as { message?: string })?.message,
  2977. );
  2978. throw new Error(
  2979. (res as { message?: string })?.message ||
  2980. "Workbench scan-pick failed (qty=0)",
  2981. );
  2982. }
  2983. clearWorkbenchScanReject(Number(lot.stockOutLineId));
  2984. await refreshWorkbenchAfterScanPick();
  2985. setTimeout(() => {
  2986. checkAndAutoAssignNext();
  2987. }, 1000);
  2988. return;
  2989. }
  2990. throw new Error("Unsupported legacy checked flow on workbench page");
  2991. }
  2992. if (
  2993. workbenchMode &&
  2994. effectiveSubmitQty > 0 &&
  2995. lot.lotNo &&
  2996. String(lot.lotNo).trim() !== "" &&
  2997. !isLotAvailabilityExpired(lot) &&
  2998. !isInventoryLotLineUnavailable(lot)
  2999. ) {
  3000. const res = await workbenchScanPick({
  3001. stockOutLineId: Number(lot.stockOutLineId),
  3002. lotNo: String(lot.lotNo).trim(),
  3003. ...(typeof lot.stockInLineId === "number" &&
  3004. Number.isFinite(lot.stockInLineId) &&
  3005. lot.stockInLineId > 0
  3006. ? { stockInLineId: lot.stockInLineId }
  3007. : {}),
  3008. qty: Number(effectiveSubmitQty),
  3009. storeId: workbenchStoreId,
  3010. userId: currentUserId ?? 1,
  3011. });
  3012. const scanOk = res.code === "SUCCESS";
  3013. if (!scanOk) {
  3014. rememberWorkbenchScanReject(
  3015. Number(lot.stockOutLineId),
  3016. (res as { message?: string })?.message,
  3017. );
  3018. throw new Error(
  3019. (res as { message?: string })?.message ||
  3020. "Workbench scan-pick failed",
  3021. );
  3022. }
  3023. clearWorkbenchScanReject(Number(lot.stockOutLineId));
  3024. const successLotKey = getWorkbenchQtyLotKey(lot);
  3025. setPickQtyData((prev) => {
  3026. if (!Object.prototype.hasOwnProperty.call(prev, successLotKey))
  3027. return prev;
  3028. const next = { ...prev };
  3029. delete next[successLotKey];
  3030. return next;
  3031. });
  3032. await refreshWorkbenchAfterScanPick();
  3033. setTimeout(() => {
  3034. checkAndAutoAssignNext();
  3035. }, 1000);
  3036. return;
  3037. }
  3038. const currentActualPickQty = lot.actualPickQty || 0;
  3039. const cumulativeQty = currentActualPickQty + effectiveSubmitQty;
  3040. let newStatus = "partially_completed";
  3041. if (cumulativeQty >= lot.requiredQty) {
  3042. newStatus = "completed";
  3043. } else if (cumulativeQty > 0) {
  3044. newStatus = "partially_completed";
  3045. } else {
  3046. newStatus = "pending";
  3047. }
  3048. console.log(`=== PICK QUANTITY SUBMISSION DEBUG ===`);
  3049. console.log(`Lot: ${lot.lotNo}`);
  3050. console.log(`Required Qty: ${lot.requiredQty}`);
  3051. console.log(`Current Actual Pick Qty: ${currentActualPickQty}`);
  3052. console.log(`New Submitted Qty: ${effectiveSubmitQty}`);
  3053. console.log(`Cumulative Qty: ${cumulativeQty}`);
  3054. console.log(`New Status: ${newStatus}`);
  3055. console.log(`=====================================`);
  3056. if (!workbenchMode) {
  3057. await updateStockOutLineStatus({
  3058. id: lot.stockOutLineId,
  3059. status: newStatus,
  3060. qty: effectiveSubmitQty,
  3061. });
  3062. applyLocalStockOutLineUpdate(
  3063. Number(lot.stockOutLineId),
  3064. newStatus,
  3065. cumulativeQty,
  3066. );
  3067. }
  3068. // Workbench completion is handled in backend scan-pick flow.
  3069. void fetchJobOrderData(pickOrderIdForRefresh);
  3070. console.log("Pick quantity submitted successfully!");
  3071. setTimeout(() => {
  3072. checkAndAutoAssignNext();
  3073. }, 1000);
  3074. } catch (error) {
  3075. console.error("Error submitting pick quantity:", error);
  3076. setQrScanError(true);
  3077. setQrScanSuccess(false);
  3078. } finally {
  3079. if (solId > 0)
  3080. setActionBusyBySolId((prev) => ({ ...prev, [solId]: false }));
  3081. }
  3082. },
  3083. [
  3084. fetchJobOrderData,
  3085. checkAndAutoAssignNext,
  3086. actionBusyBySolId,
  3087. applyLocalStockOutLineUpdate,
  3088. workbenchMode,
  3089. currentUserId,
  3090. rememberWorkbenchScanReject,
  3091. clearWorkbenchScanReject,
  3092. refreshWorkbenchAfterScanPick,
  3093. combinedLotData,
  3094. workbenchScanPickQtyFromLot,
  3095. pickQtyData,
  3096. tPick,
  3097. workbenchStoreId,
  3098. filterArgs?.pickOrderId,
  3099. ],
  3100. );
  3101. const handleSkip = useCallback(
  3102. async (lot: any) => {
  3103. try {
  3104. console.log(
  3105. "Just Complete clicked (workbench: scan-pick without QR when possible):",
  3106. lot.lotNo,
  3107. );
  3108. await handleSubmitPickQtyWithQty(lot, 0, "justComplete");
  3109. } catch (err) {
  3110. console.error("Error in Skip:", err);
  3111. }
  3112. },
  3113. [handleSubmitPickQtyWithQty],
  3114. );
  3115. const hasPendingBatchSubmit = useMemo(() => {
  3116. return combinedLotData.some((lot) => {
  3117. const status = String(lot.stockOutLineStatus || "").toLowerCase();
  3118. return (
  3119. status === "pending" ||
  3120. status === "partially_completed" ||
  3121. status === "partially_complete"
  3122. );
  3123. });
  3124. }, [combinedLotData]);
  3125. useEffect(() => {
  3126. if (!hasPendingBatchSubmit) return;
  3127. const handler = (event: BeforeUnloadEvent) => {
  3128. event.preventDefault();
  3129. event.returnValue = "";
  3130. };
  3131. window.addEventListener("beforeunload", handler);
  3132. return () => window.removeEventListener("beforeunload", handler);
  3133. }, [hasPendingBatchSubmit]);
  3134. const handleSubmitAllScanned = useCallback(async () => {
  3135. const startTime = performance.now();
  3136. console.log(` [BATCH SUBMIT START]`);
  3137. console.log(` Start time: ${new Date().toISOString()}`);
  3138. const scannedLots = combinedLotData.filter((lot) => {
  3139. const status = lot.stockOutLineStatus;
  3140. const statusLower = String(status || "").toLowerCase();
  3141. if (statusLower === "completed" || statusLower === "complete") {
  3142. return false;
  3143. }
  3144. if (
  3145. lot.noLot === true ||
  3146. isLotAvailabilityExpired(lot) ||
  3147. isInventoryLotLineUnavailable(lot)
  3148. ) {
  3149. return true;
  3150. }
  3151. return false;
  3152. });
  3153. if (scannedLots.length === 0) {
  3154. console.log("No scanned items to submit");
  3155. return;
  3156. }
  3157. setIsSubmittingAll(true);
  3158. console.log(
  3159. `📦 Submitting ${scannedLots.length} items using workbench batch scan-pick (qty=0)...`,
  3160. );
  3161. try {
  3162. const submitStartTime = performance.now();
  3163. const result = await workbenchBatchScanPick({
  3164. lines: scannedLots.map((lot) => ({
  3165. stockOutLineId: Number(lot.stockOutLineId) || 0,
  3166. lotNo: "",
  3167. qty: 0,
  3168. storeId: workbenchStoreId,
  3169. userId: currentUserId ?? 1,
  3170. })),
  3171. });
  3172. const submitTime = performance.now() - submitStartTime;
  3173. console.log(
  3174. ` Batch submit API call completed in ${submitTime.toFixed(2)}ms (${(
  3175. submitTime / 1000
  3176. ).toFixed(3)}s)`,
  3177. );
  3178. console.log(`📥 Batch submit result:`, result);
  3179. const refreshStartTime = performance.now();
  3180. const pickOrderId = filterArgs?.pickOrderId
  3181. ? Number(filterArgs.pickOrderId)
  3182. : undefined;
  3183. await fetchJobOrderData(pickOrderId);
  3184. const refreshTime = performance.now() - refreshStartTime;
  3185. console.log(
  3186. ` Data refresh time: ${refreshTime.toFixed(2)}ms (${(
  3187. refreshTime / 1000
  3188. ).toFixed(3)}s)`,
  3189. );
  3190. const totalTime = performance.now() - startTime;
  3191. console.log(` [BATCH SUBMIT END]`);
  3192. console.log(
  3193. ` Total time: ${totalTime.toFixed(2)}ms (${(totalTime / 1000).toFixed(
  3194. 3,
  3195. )}s)`,
  3196. );
  3197. console.log(` End time: ${new Date().toISOString()}`);
  3198. if (result && result.code === "SUCCESS") {
  3199. setQrScanSuccess(true);
  3200. setTimeout(() => {
  3201. setQrScanSuccess(false);
  3202. checkAndAutoAssignNext();
  3203. if (onBackToList) {
  3204. onBackToList();
  3205. }
  3206. }, 2000);
  3207. } else {
  3208. console.error("Batch submit failed:", result);
  3209. setQrScanError(true);
  3210. }
  3211. } catch (error) {
  3212. console.error("Error submitting all scanned items:", error);
  3213. setQrScanError(true);
  3214. } finally {
  3215. setIsSubmittingAll(false);
  3216. }
  3217. }, [
  3218. combinedLotData,
  3219. fetchJobOrderData,
  3220. checkAndAutoAssignNext,
  3221. currentUserId,
  3222. onBackToList,
  3223. workbenchStoreId,
  3224. filterArgs?.pickOrderId,
  3225. ]);
  3226. const scannedItemsCount = useMemo(() => {
  3227. const filtered = combinedLotData.filter((lot) => {
  3228. const status = lot.stockOutLineStatus;
  3229. const statusLower = String(status || "").toLowerCase();
  3230. if (statusLower === "completed" || statusLower === "complete") {
  3231. return false;
  3232. }
  3233. if (
  3234. lot.noLot === true ||
  3235. isLotAvailabilityExpired(lot) ||
  3236. isInventoryLotLineUnavailable(lot)
  3237. ) {
  3238. return true;
  3239. }
  3240. return false;
  3241. });
  3242. const noLotCount = filtered.filter((l) => l.noLot === true).length;
  3243. const normalCount = filtered.filter((l) => l.noLot !== true).length;
  3244. console.log(
  3245. `📊 scannedItemsCount calculation: total=${filtered.length}, noLot=${noLotCount}, normal=${normalCount}`,
  3246. );
  3247. console.log(`📊 All items breakdown:`, {
  3248. total: combinedLotData.length,
  3249. noLot: combinedLotData.filter((l) => l.noLot === true).length,
  3250. normal: combinedLotData.filter((l) => l.noLot !== true).length,
  3251. });
  3252. return filtered.length;
  3253. }, [combinedLotData]);
  3254. // 先定义 filteredByFloor 和 availableFloors
  3255. const availableFloors = useMemo(() => {
  3256. const floors = new Set<string>();
  3257. combinedLotData.forEach((lot) => {
  3258. const f = extractFloor(lot);
  3259. if (f) floors.add(f);
  3260. });
  3261. return Array.from(floors).sort(
  3262. (a, b) => floorSortOrder(b) - floorSortOrder(a),
  3263. );
  3264. }, [combinedLotData]);
  3265. const filteredByFloor = useMemo(() => {
  3266. if (!selectedFloor) return combinedLotData;
  3267. return combinedLotData.filter((lot) => extractFloor(lot) === selectedFloor);
  3268. }, [combinedLotData, selectedFloor]);
  3269. // 與批量篩選一致:noLot / 過期 的 pending 也算已處理(對齊 GoodPickExecutiondetail)
  3270. const progress = useMemo(() => {
  3271. const data = selectedFloor ? filteredByFloor : combinedLotData;
  3272. if (data.length === 0) return { completed: 0, total: 0 };
  3273. const nonPendingCount = data.filter((lot) => {
  3274. const status = lot.stockOutLineStatus?.toLowerCase();
  3275. if (status !== "pending") return true;
  3276. if (
  3277. lot.noLot === true ||
  3278. isLotAvailabilityExpired(lot) ||
  3279. isInventoryLotLineUnavailable(lot)
  3280. )
  3281. return true;
  3282. return false;
  3283. }).length;
  3284. return { completed: nonPendingCount, total: data.length };
  3285. }, [selectedFloor, filteredByFloor, combinedLotData]);
  3286. // Handle reject lot
  3287. const handleRejectLot = useCallback(
  3288. async (lot: any) => {
  3289. if (!lot.stockOutLineId) {
  3290. console.error("No stock out line found for this lot");
  3291. return;
  3292. }
  3293. try {
  3294. await updateStockOutLineStatus({
  3295. id: lot.stockOutLineId,
  3296. status: "rejected",
  3297. qty: 0,
  3298. });
  3299. const pickOrderId = filterArgs?.pickOrderId
  3300. ? Number(filterArgs.pickOrderId)
  3301. : undefined;
  3302. await fetchJobOrderData(pickOrderId);
  3303. console.log("Lot rejected successfully!");
  3304. setTimeout(() => {
  3305. checkAndAutoAssignNext();
  3306. }, 1000);
  3307. } catch (error) {
  3308. console.error("Error rejecting lot:", error);
  3309. }
  3310. },
  3311. [fetchJobOrderData, checkAndAutoAssignNext],
  3312. );
  3313. // Handle pick execution form
  3314. const handlePickExecutionForm = useCallback((lot: any) => {
  3315. console.log("=== Pick Execution Form ===");
  3316. console.log("Lot data:", lot);
  3317. if (!lot) {
  3318. console.warn("No lot data provided for pick execution form");
  3319. return;
  3320. }
  3321. console.log("Opening pick execution form for lot:", lot.lotNo);
  3322. setSelectedLotForExecutionForm(lot);
  3323. setPickExecutionFormOpen(true);
  3324. console.log("Pick execution form opened for lot ID:", lot.lotId);
  3325. }, []);
  3326. // Calculate remaining required quantity
  3327. const calculateRemainingRequiredQty = useCallback((lot: any) => {
  3328. const requiredQty = lot.requiredQty || 0;
  3329. const stockOutLineQty = lot.stockOutLineQty || 0;
  3330. return Math.max(0, requiredQty - stockOutLineQty);
  3331. }, []);
  3332. const handlePageChange = useCallback((event: unknown, newPage: number) => {
  3333. setPaginationController((prev) => ({
  3334. ...prev,
  3335. pageNum: newPage,
  3336. }));
  3337. }, []);
  3338. const handlePageSizeChange = useCallback(
  3339. (event: React.ChangeEvent<HTMLInputElement>) => {
  3340. const newPageSize = parseInt(event.target.value, 10);
  3341. setPaginationController({
  3342. pageNum: 0,
  3343. pageSize: newPageSize,
  3344. });
  3345. },
  3346. [],
  3347. );
  3348. // Pagination data: align DO workbench grouping display
  3349. const paginatedData = useMemo(() => {
  3350. const sourceData = selectedFloor ? filteredByFloor : combinedLotData;
  3351. /** 同 pick_order_line 內「無庫位 / no-lot」列 extractFloor 為空,若仍用 0 會被排到全表最後,編號欄也變成新群組。繼承該行最大樓層權重並以 polId 相鄰排序。 */
  3352. const lineMaxFloorOrder = new Map<number, number>();
  3353. for (const lot of sourceData) {
  3354. const polId = Number(lot.pickOrderLineId);
  3355. if (!Number.isFinite(polId) || polId <= 0) continue;
  3356. const o = floorSortOrder(extractFloor(lot));
  3357. const prev = lineMaxFloorOrder.get(polId) ?? 0;
  3358. if (o > prev) lineMaxFloorOrder.set(polId, o);
  3359. }
  3360. const effectiveFloorOrder = (lot: any): number => {
  3361. const own = floorSortOrder(extractFloor(lot));
  3362. if (own > 0) return own;
  3363. const polId = Number(lot.pickOrderLineId);
  3364. if (Number.isFinite(polId) && polId > 0) {
  3365. const inherited = lineMaxFloorOrder.get(polId);
  3366. if (inherited != null && inherited > 0) return inherited;
  3367. }
  3368. return 0;
  3369. };
  3370. const isNoLotTailRow = (lot: any) =>
  3371. lot.noLot === true || lot.lotId == null || lot.lotId === undefined;
  3372. /** 同 POL 內對齊 DO Workbench:已掃/已完成在前,resuggest pending 在後 */
  3373. const statusRank = (lot: any) => {
  3374. const st = String(lot?.stockOutLineStatus ?? "").toLowerCase();
  3375. if (
  3376. st === "completed" ||
  3377. st === "partially_completed" ||
  3378. st === "partially_complete"
  3379. ) {
  3380. return 0;
  3381. }
  3382. if (st === "checked") return 1;
  3383. if (st === "pending") return 2;
  3384. if (st === "rejected") return 3;
  3385. return 9;
  3386. };
  3387. const sortedData = [...sourceData].sort((a, b) => {
  3388. const efA = effectiveFloorOrder(a);
  3389. const efB = effectiveFloorOrder(b);
  3390. if (efA !== efB) return efB - efA; // 4F, 3F, 2F(含繼承樓層的缺口列)
  3391. const polA = Number(a.pickOrderLineId);
  3392. const polB = Number(b.pickOrderLineId);
  3393. const hasPolA = Number.isFinite(polA) && polA > 0;
  3394. const hasPolB = Number.isFinite(polB) && polB > 0;
  3395. if (hasPolA && hasPolB && polA !== polB) return polA - polB;
  3396. const aItem = String(a.itemCode || "");
  3397. const bItem = String(b.itemCode || "");
  3398. if (aItem !== bItem) return aItem.localeCompare(bItem);
  3399. const aName = String(a.itemName || "");
  3400. const bName = String(b.itemName || "");
  3401. if (aName !== bName) return aName.localeCompare(bName);
  3402. const ra = statusRank(a);
  3403. const rb = statusRank(b);
  3404. if (ra !== rb) return ra - rb;
  3405. const tailA = isNoLotTailRow(a) ? 1 : 0;
  3406. const tailB = isNoLotTailRow(b) ? 1 : 0;
  3407. if (tailA !== tailB) return tailA - tailB;
  3408. const aIndex = Number(a.routerIndex ?? 0);
  3409. const bIndex = Number(b.routerIndex ?? 0);
  3410. if (aIndex !== bIndex) return aIndex - bIndex;
  3411. return (a.lotNo || "").localeCompare(b.lotNo || "");
  3412. });
  3413. const flattened = sortedData.map((lot, idx, arr) => {
  3414. const key = `${lot.itemId ?? "null"}-${lot.itemCode ?? ""}`;
  3415. const prev = idx > 0 ? arr[idx - 1] : undefined;
  3416. const prevKey = prev
  3417. ? `${prev.itemId ?? "null"}-${prev.itemCode ?? ""}`
  3418. : null;
  3419. const isGroupFirst = key !== prevKey;
  3420. const groupDisplayIndex =
  3421. arr
  3422. .slice(0, idx + 1)
  3423. .filter((row, rowIdx, all) => {
  3424. const rowKey = `${row.itemId ?? "null"}-${row.itemCode ?? ""}`;
  3425. const before = rowIdx > 0 ? all[rowIdx - 1] : undefined;
  3426. const beforeKey = before
  3427. ? `${before.itemId ?? "null"}-${before.itemCode ?? ""}`
  3428. : null;
  3429. return rowKey !== beforeKey;
  3430. }).length;
  3431. return { lot, isGroupFirst, groupDisplayIndex };
  3432. });
  3433. const startIndex =
  3434. paginationController.pageNum * paginationController.pageSize;
  3435. const endIndex = startIndex + paginationController.pageSize;
  3436. return flattened.slice(startIndex, endIndex);
  3437. }, [selectedFloor, filteredByFloor, combinedLotData, paginationController]);
  3438. // Add these functions for manual scanning
  3439. const handleStartScan = useCallback(() => {
  3440. console.log(" Starting manual QR scan...");
  3441. setIsManualScanning(true);
  3442. setProcessedQrCodes(new Set());
  3443. setLastProcessedQr("");
  3444. setQrScanError(false);
  3445. setQrScanSuccess(false);
  3446. startScan();
  3447. }, [startScan]);
  3448. const handleStopScan = useCallback(() => {
  3449. console.log(" Stopping manual QR scan...");
  3450. setIsManualScanning(false);
  3451. setQrScanError(false);
  3452. setQrScanSuccess(false);
  3453. stopScan();
  3454. resetScan();
  3455. }, [stopScan, resetScan]);
  3456. useEffect(() => {
  3457. return () => {
  3458. // Cleanup when component unmounts (e.g., when switching tabs)
  3459. if (isManualScanning) {
  3460. console.log("🧹 Component unmounting, stopping QR scanner...");
  3461. stopScan();
  3462. resetScan();
  3463. }
  3464. };
  3465. }, [isManualScanning, stopScan, resetScan]);
  3466. // 勿在 combinedLotData 仍為空時自動停掃:API 未回傳前會誤觸,與 GoodPickExecutiondetail(已註解掉同段)一致。
  3467. // 無資料時 qrValues effect 本來就不會處理掃碼;真正無單據可再手動按停止。
  3468. const getStatusMessage = useCallback(
  3469. (lot: any) => {
  3470. if (
  3471. lot?.noLot === true ||
  3472. lot?.lotAvailability === "insufficient_stock"
  3473. ) {
  3474. return t("This order is insufficient, please pick another lot.");
  3475. }
  3476. switch (lot.stockOutLineStatus?.toLowerCase()) {
  3477. case "pending":
  3478. return t("Please finish QR code scan and pick order.");
  3479. case "checked":
  3480. return t("Please submit the pick order.");
  3481. case "partially_completed":
  3482. return t(
  3483. "Partial quantity submitted. Please submit more or complete the order.",
  3484. );
  3485. case "completed":
  3486. return t("Pick order completed successfully!");
  3487. case "rejected":
  3488. return t("Lot has been rejected and marked as unavailable.");
  3489. case "unavailable":
  3490. return t("This order is insufficient, please pick another lot.");
  3491. default:
  3492. return t("Please finish QR code scan and pick order.");
  3493. }
  3494. },
  3495. [t],
  3496. );
  3497. return (
  3498. <TestQrCodeProvider
  3499. lotData={combinedLotData}
  3500. onScanLot={handleQrCodeSubmit}
  3501. filterActive={(lot) =>
  3502. lot.lotAvailability !== "rejected" &&
  3503. lot.stockOutLineStatus !== "rejected" &&
  3504. lot.stockOutLineStatus !== "completed"
  3505. }
  3506. >
  3507. <FormProvider {...formProps}>
  3508. <Stack spacing={2}>
  3509. {/* Progress bar + scan status fixed at top */}
  3510. <Box
  3511. sx={{
  3512. position: "fixed",
  3513. top: 0,
  3514. left: 0,
  3515. right: 0,
  3516. zIndex: 1100,
  3517. backgroundColor: "background.paper",
  3518. pt: 2,
  3519. pb: 1,
  3520. px: 2,
  3521. borderBottom: "1px solid",
  3522. borderColor: "divider",
  3523. boxShadow: "0 2px 4px rgba(0,0,0,0.1)",
  3524. }}
  3525. >
  3526. <LinearProgressWithLabel
  3527. completed={progress.completed}
  3528. total={progress.total}
  3529. label={t("Progress")}
  3530. />
  3531. <ScanStatusAlert
  3532. error={qrScanError}
  3533. success={qrScanSuccess}
  3534. errorMessage={
  3535. qrScanErrorMsg ||
  3536. t("QR code does not match any item in current orders.")
  3537. }
  3538. successMessage={t("QR code verified.")}
  3539. />
  3540. </Box>
  3541. <Box
  3542. sx={{
  3543. display: "flex",
  3544. gap: 1,
  3545. alignItems: "center",
  3546. flexWrap: "wrap",
  3547. }}
  3548. >
  3549. <Button
  3550. variant={selectedFloor === null ? "contained" : "outlined"}
  3551. size="small"
  3552. onClick={() => setSelectedFloor(null)}
  3553. >
  3554. {t("All")}
  3555. </Button>
  3556. {availableFloors.map((floor) => (
  3557. <Button
  3558. key={floor}
  3559. variant={selectedFloor === floor ? "contained" : "outlined"}
  3560. size="small"
  3561. onClick={() => setSelectedFloor(floor)}
  3562. >
  3563. {floor}
  3564. </Button>
  3565. ))}
  3566. </Box>
  3567. <Box sx={{ display: "flex", gap: 1, alignItems: "center", flexWrap: "wrap" }}>
  3568. <Typography variant="body2" sx={{ minWidth: "fit-content", mr: 1 }}>
  3569. {t("Select Printer")}:
  3570. </Typography>
  3571. <Autocomplete
  3572. options={printerOptions}
  3573. getOptionLabel={(option) =>
  3574. option.name || option.label || option.code || `Printer ${option.id}`
  3575. }
  3576. value={selectedPrinter}
  3577. onChange={(_, newValue) => setSelectedPrinter(newValue)}
  3578. sx={{ minWidth: 220 }}
  3579. size="small"
  3580. renderInput={(params) => (
  3581. <TextField
  3582. {...params}
  3583. placeholder={t("Printer")}
  3584. inputProps={{ ...params.inputProps, readOnly: true }}
  3585. />
  3586. )}
  3587. />
  3588. <Typography variant="body2" sx={{ minWidth: "fit-content", ml: 1 }}>
  3589. {t("Print Quantity")}:
  3590. </Typography>
  3591. <TextField
  3592. type="number"
  3593. label={t("Print Quantity")}
  3594. value={printQty}
  3595. onChange={(e) => {
  3596. const value = parseInt(e.target.value) || 1;
  3597. setPrintQty(Math.max(1, value));
  3598. }}
  3599. inputProps={{ min: 1, step: 1 }}
  3600. sx={{ width: 120 }}
  3601. size="small"
  3602. />
  3603. <Button
  3604. variant="contained"
  3605. color="primary"
  3606. size="small"
  3607. onClick={() => handlePickRecord("ALL")}
  3608. >
  3609. {t("Print Pick Record")} ALL
  3610. </Button>
  3611. <Button
  3612. variant="contained"
  3613. color="primary"
  3614. size="small"
  3615. onClick={() => handlePickRecord(FLOOR_A_KEY)}
  3616. >
  3617. {t("Print Pick Record")} 2F
  3618. </Button>
  3619. <Button
  3620. variant="contained"
  3621. color="primary"
  3622. size="small"
  3623. onClick={() => handlePickRecord(FLOOR_D_KEY)}
  3624. >
  3625. {t("Print Pick Record")} 3F
  3626. </Button>
  3627. <Button
  3628. variant="contained"
  3629. color="primary"
  3630. size="small"
  3631. onClick={() => handlePickRecord(FLOOR_B_KEY)}
  3632. >
  3633. {t("Print Pick Record")} 4F
  3634. </Button>
  3635. {isPrinterComboMissing && (
  3636. <Alert severity="warning" sx={{ py: 0, px: 1 }}>
  3637. {t("Printer list is empty")}
  3638. </Alert>
  3639. )}
  3640. </Box>
  3641. {/* Job Order Header */}
  3642. {jobOrderData && (
  3643. <Paper sx={{ p: 2 }}>
  3644. <Stack direction="row" spacing={4} useFlexGap flexWrap="wrap">
  3645. <Typography variant="subtitle1">
  3646. <strong>{t("Item Name")}:</strong>{" "}
  3647. {jobOrderData.pickOrder.jobOrder.itemCode || "-"}{" "}{jobOrderData.pickOrder.jobOrder.itemName || "-"}
  3648. </Typography>
  3649. <Typography variant="subtitle1">
  3650. <strong>{t("Job Order")}:</strong>{" "}
  3651. {jobOrderData.pickOrder?.jobOrder?.code || "-"}
  3652. </Typography>
  3653. <Typography variant="subtitle1">
  3654. <strong>{t("Pick Order Code")}:</strong>{" "}
  3655. {jobOrderData.pickOrder?.code || "-"}
  3656. </Typography>
  3657. <Typography variant="subtitle1">
  3658. <strong>{t("Target Date")}:</strong>{" "}
  3659. {jobOrderData.pickOrder?.targetDate || "-"}
  3660. </Typography>
  3661. </Stack>
  3662. </Paper>
  3663. )}
  3664. {/* Combined Lot Table */}
  3665. <Box sx={{ mt: 10 }}>
  3666. <Box
  3667. sx={{
  3668. display: "flex",
  3669. justifyContent: "space-between",
  3670. alignItems: "center",
  3671. mb: 2,
  3672. }}
  3673. >
  3674. <Box sx={{ display: "flex", gap: 2, alignItems: "center" }}>
  3675. {!isManualScanning ? (
  3676. <Button
  3677. variant="contained"
  3678. startIcon={<QrCodeIcon />}
  3679. onClick={handleStartScan}
  3680. color="primary"
  3681. sx={{ minWidth: "120px" }}
  3682. >
  3683. {t("Start QR Scan")}
  3684. </Button>
  3685. ) : (
  3686. <Button
  3687. variant="outlined"
  3688. startIcon={<QrCodeIcon />}
  3689. onClick={handleStopScan}
  3690. color="secondary"
  3691. sx={{ minWidth: "120px" }}
  3692. >
  3693. {t("Stop QR Scan")}
  3694. </Button>
  3695. )}
  3696. {/* ADD THIS: Submit All Scanned Button */}
  3697. <Button
  3698. variant="contained"
  3699. color="success"
  3700. onClick={handleSubmitAllScanned}
  3701. disabled={scannedItemsCount === 0 || isSubmittingAll}
  3702. sx={{ minWidth: "160px" }}
  3703. >
  3704. {isSubmittingAll ? (
  3705. <>
  3706. <CircularProgress size={16} sx={{ mr: 1 }} />
  3707. {t("Submitting...")}
  3708. </>
  3709. ) : (
  3710. `${t("Submit All Scanned")} (${scannedItemsCount})`
  3711. )}
  3712. </Button>
  3713. </Box>
  3714. </Box>
  3715. <TableContainer component={Paper}>
  3716. <Table>
  3717. <TableHead>
  3718. <TableRow>
  3719. <TableCell>{t("Index")}</TableCell>
  3720. <TableCell>{t("Item Code")}</TableCell>
  3721. <TableCell>{t("Route")}</TableCell>
  3722. <TableCell>{t("Handler")}</TableCell>
  3723. <TableCell>{t("Lot No")}</TableCell>
  3724. <TableCell align="right">
  3725. {t("Lot Required Pick Qty")}
  3726. </TableCell>
  3727. <TableCell align="right">{t("Available Qty")}</TableCell>
  3728. <TableCell align="center">{t("Scan Result")}</TableCell>
  3729. <TableCell align="center">{t("Qty will submit")}</TableCell>
  3730. <TableCell align="center">
  3731. {t("Submit Required Pick Qty")}
  3732. </TableCell>
  3733. </TableRow>
  3734. </TableHead>
  3735. <TableBody>
  3736. {paginatedData.length === 0 ? (
  3737. <TableRow>
  3738. <TableCell colSpan={11} align="center">
  3739. <Typography variant="body2" color="text.secondary">
  3740. {t("No data available")}
  3741. </Typography>
  3742. </TableCell>
  3743. </TableRow>
  3744. ) : (
  3745. paginatedData.map((row) => {
  3746. const lot = row.lot;
  3747. const solIdForKey = Number(lot.stockOutLineId) || 0;
  3748. const lotKeyForSubmitQty =
  3749. Number.isFinite(solIdForKey) && solIdForKey > 0
  3750. ? `sol:${solIdForKey}`
  3751. : `${lot.pickOrderLineId}-${lot.lotId}`;
  3752. const submitQtyStatus = String(
  3753. lot.stockOutLineStatus || "",
  3754. ).toLowerCase();
  3755. const isSubmitQtyCompleted =
  3756. submitQtyStatus === "completed" ||
  3757. submitQtyStatus === "partially_completed" ||
  3758. submitQtyStatus === "partially_complete";
  3759. const lockedSubmitQtyDisplay =
  3760. isInventoryLotLineUnavailable(lot) &&
  3761. !isSubmitQtyCompleted
  3762. ? 0
  3763. : resolveSingleSubmitQty(lot);
  3764. const hasPickOverride =
  3765. Object.prototype.hasOwnProperty.call(
  3766. pickQtyData,
  3767. lotKeyForSubmitQty,
  3768. );
  3769. const fromPickRow = hasPickOverride
  3770. ? pickQtyData[lotKeyForSubmitQty]
  3771. : undefined;
  3772. const workbenchSubmitQtyDisplay =
  3773. hasPickOverride &&
  3774. fromPickRow !== undefined &&
  3775. fromPickRow !== null &&
  3776. !Number.isNaN(Number(fromPickRow))
  3777. ? Number(fromPickRow)
  3778. : lockedSubmitQtyDisplay;
  3779. const totalAvail = Number(lot.itemTotalAvailableQty ?? 0);
  3780. const isLastLotUnavailable = Number.isFinite(totalAvail) && totalAvail === 0;
  3781. return (
  3782. <TableRow
  3783. key={`${lot.pickOrderLineId}-${lot.lotId}`}
  3784. sx={{
  3785. // backgroundColor: lot.lotAvailability === 'rejected' ? 'grey.100' : 'inherit',
  3786. //opacity: lot.lotAvailability === 'rejected' ? 0.6 : 1,
  3787. "& .MuiTableCell-root": {
  3788. // color: lot.lotAvailability === 'rejected' ? 'text.disabled' : 'inherit'
  3789. },
  3790. }}
  3791. >
  3792. <TableCell>
  3793. <Typography variant="body2" fontWeight="bold">
  3794. {row.isGroupFirst ? row.groupDisplayIndex : ""}
  3795. </Typography>
  3796. </TableCell>
  3797. <TableCell>
  3798. {row.isGroupFirst ? (
  3799. <>
  3800. {lot.itemCode} <br />
  3801. {lot.itemName} <br />
  3802. {lot.uomDesc}
  3803. </>
  3804. ) : ""}
  3805. </TableCell>
  3806. <TableCell>
  3807. <Typography variant="body2">
  3808. {lot.routerRoute || "-"}
  3809. </Typography>
  3810. </TableCell>
  3811. <TableCell>{lot.handler || "-"}</TableCell>
  3812. <TableCell>
  3813. <Stack
  3814. direction="row"
  3815. spacing={1}
  3816. alignItems="center"
  3817. justifyContent="space-between"
  3818. >
  3819. <Box>
  3820. <Typography
  3821. sx={{
  3822. color:
  3823. isInventoryLotLineUnavailable(lot) &&
  3824. !(
  3825. String(
  3826. lot.stockOutLineStatus || "",
  3827. ).toLowerCase() === "completed" ||
  3828. String(
  3829. lot.stockOutLineStatus || "",
  3830. ).toLowerCase() ===
  3831. "partially_completed" ||
  3832. String(
  3833. lot.stockOutLineStatus || "",
  3834. ).toLowerCase() ===
  3835. "partially_complete"
  3836. )
  3837. ? "error.main"
  3838. : lot.lotAvailability === "expired"
  3839. ? "warning.main"
  3840. : "inherit",
  3841. }}
  3842. >
  3843. {lot.lotNo ? (
  3844. /*
  3845. */
  3846. lot.lotAvailability === "expired" ? (
  3847. <>
  3848. {lot.lotNo}{" "}
  3849. <Box
  3850. component="span"
  3851. sx={{ fontSize: "0.85rem", lineHeight: 1.4 }}
  3852. >
  3853. {t(
  3854. "is expired. Please check around have available QR code or not.",
  3855. )}
  3856. </Box>
  3857. {isLastLotUnavailable && (
  3858. <Box
  3859. component="span"
  3860. sx={{ fontSize: "0.85rem", lineHeight: 1.4 }}
  3861. >
  3862. {t("This is last lot, so no available lot.")}
  3863. </Box>
  3864. )}
  3865. </>
  3866. ) : isInventoryLotLineUnavailable(lot) &&
  3867. !(
  3868. String(
  3869. lot.stockOutLineStatus || "",
  3870. ).toLowerCase() === "completed" ||
  3871. String(
  3872. lot.stockOutLineStatus || "",
  3873. ).toLowerCase() === "partially_completed" ||
  3874. String(
  3875. lot.stockOutLineStatus || "",
  3876. ).toLowerCase() === "partially_complete"
  3877. ) ? (
  3878. <>
  3879. {lot.lotNo}{" "}
  3880. <Box
  3881. component="span"
  3882. sx={{ fontSize: "0.85rem", lineHeight: 1.4 }}
  3883. >
  3884. {t(
  3885. "is unavable. Please check around have available QR code or not.",
  3886. )}
  3887. </Box>
  3888. </>
  3889. ) : (
  3890. lot.lotNo
  3891. )
  3892. ) : (
  3893. <Box
  3894. component="span"
  3895. sx={{ fontSize: "0.85rem", lineHeight: 1.4 }}
  3896. >
  3897. {t(
  3898. "Please check around have QR code or not, may be have just now stock in or transfer in or transfer out.",
  3899. )}
  3900. </Box>
  3901. )}
  3902. </Typography>
  3903. </Box>
  3904. {Number(lot.stockOutLineId) > 0 &&
  3905. Number(lot.itemId) > 0 ? (
  3906. <Button
  3907. variant="outlined"
  3908. size="small"
  3909. onClick={() =>
  3910. openWorkbenchLotLabelModalForLot(lot)
  3911. }
  3912. disabled={
  3913. (Number(lot.stockOutLineId) > 0 &&
  3914. actionBusyBySolId[
  3915. Number(lot.stockOutLineId)
  3916. ] === true)
  3917. }
  3918. sx={{
  3919. flexShrink: 0,
  3920. fontSize: "0.7rem",
  3921. py: 0.25,
  3922. minWidth: "auto",
  3923. px: 1,
  3924. whiteSpace: "nowrap",
  3925. }}
  3926. >
  3927. {L("挑號 QR 碼", "Pick-lot QR code")}
  3928. </Button>
  3929. ) : null}
  3930. </Stack>
  3931. </TableCell>
  3932. <TableCell align="right">
  3933. {(() => {
  3934. const requiredQty = lot.requiredQty || 0;
  3935. const unit =
  3936. lot.noLot === true || !lot.lotId
  3937. ? lot.uomDesc || ""
  3938. : lot.uomDesc || "";
  3939. return `${requiredQty.toLocaleString()}(${unit})`;
  3940. })()}
  3941. </TableCell>
  3942. <TableCell align="right">
  3943. {(() => {
  3944. const avail = lot.itemTotalAvailableQty;
  3945. if (avail == null) return "-";
  3946. const unit = lot.uomDesc || "";
  3947. return `${Number(
  3948. avail,
  3949. ).toLocaleString()}(${unit})`;
  3950. })()}
  3951. </TableCell>
  3952. <TableCell align="center">
  3953. {(() => {
  3954. const status =
  3955. lot.stockOutLineStatus?.toLowerCase();
  3956. const isRejected =
  3957. status === "rejected" ||
  3958. lot.lotAvailability === "rejected";
  3959. const isNoLot = !lot.lotNo;
  3960. if (isRejected && !isNoLot) {
  3961. return (
  3962. <Box
  3963. sx={{
  3964. display: "flex",
  3965. justifyContent: "center",
  3966. alignItems: "center",
  3967. }}
  3968. >
  3969. <Checkbox
  3970. checked={true}
  3971. disabled={true}
  3972. readOnly={true}
  3973. size="large"
  3974. sx={{
  3975. color: "error.main",
  3976. "&.Mui-checked": {
  3977. color: "error.main",
  3978. },
  3979. transform: "scale(1.3)",
  3980. }}
  3981. />
  3982. </Box>
  3983. );
  3984. }
  3985. if (
  3986. isLotAvailabilityExpired(lot) &&
  3987. status !== "rejected" &&
  3988. status !== "completed" &&
  3989. status !== "partially_completed" &&
  3990. status !== "partially_complete"
  3991. ) {
  3992. return null;
  3993. }
  3994. if (
  3995. !isNoLot &&
  3996. status !== "pending" &&
  3997. status !== "rejected"
  3998. ) {
  3999. return (
  4000. <Box
  4001. sx={{
  4002. display: "flex",
  4003. justifyContent: "center",
  4004. alignItems: "center",
  4005. }}
  4006. >
  4007. <Checkbox
  4008. checked={true}
  4009. disabled={true}
  4010. readOnly={true}
  4011. size="large"
  4012. sx={{
  4013. color: "success.main",
  4014. "&.Mui-checked": {
  4015. color: "success.main",
  4016. },
  4017. transform: "scale(1.3)",
  4018. }}
  4019. />
  4020. </Box>
  4021. );
  4022. }
  4023. if (
  4024. isNoLot &&
  4025. (status === "partially_completed" ||
  4026. status === "completed")
  4027. ) {
  4028. return (
  4029. <Box
  4030. sx={{
  4031. display: "flex",
  4032. justifyContent: "center",
  4033. alignItems: "center",
  4034. }}
  4035. >
  4036. <Checkbox
  4037. checked={true}
  4038. disabled={true}
  4039. readOnly={true}
  4040. size="large"
  4041. sx={{
  4042. color: "error.main",
  4043. "&.Mui-checked": {
  4044. color: "error.main",
  4045. },
  4046. transform: "scale(1.3)",
  4047. }}
  4048. />
  4049. </Box>
  4050. );
  4051. }
  4052. return null;
  4053. })()}
  4054. </TableCell>
  4055. <TableCell align="center">
  4056. {workbenchSubmitQtyDisplay}
  4057. </TableCell>
  4058. <TableCell align="center">
  4059. <Box
  4060. sx={{ display: "flex", justifyContent: "center" }}
  4061. >
  4062. {(() => {
  4063. const status =
  4064. lot.stockOutLineStatus?.toLowerCase();
  4065. const isRejected =
  4066. status === "rejected" ||
  4067. lot.lotAvailability === "rejected";
  4068. const isNoLot = !lot.lotNo;
  4069. const isUnavailableLot =
  4070. isInventoryLotLineUnavailable(lot);
  4071. if (isRejected && !isNoLot) {
  4072. const rejectDisplay = buildLotRejectDisplayMessage(
  4073. lot,
  4074. scanRejectMessageBySolId,
  4075. tPick,
  4076. );
  4077. return (
  4078. <Typography
  4079. variant="body2"
  4080. color="error.main"
  4081. sx={{
  4082. textAlign: "center",
  4083. whiteSpace: "normal",
  4084. wordBreak: "break-word",
  4085. maxWidth: "200px",
  4086. lineHeight: 1.5,
  4087. }}
  4088. >
  4089. {rejectDisplay ??
  4090. t(
  4091. "This lot is rejected, please scan another lot.",
  4092. )}
  4093. </Typography>
  4094. );
  4095. }
  4096. const lotKey = lotKeyForSubmitQty;
  4097. const qtyFieldEnabled =
  4098. workbenchSubmitQtyFieldEnabledByLotKey[
  4099. lotKey
  4100. ] === true;
  4101. const displayedSubmitQty =
  4102. workbenchSubmitQtyDisplay;
  4103. const hasPickOverrideRow =
  4104. Object.prototype.hasOwnProperty.call(
  4105. pickQtyData,
  4106. lotKey,
  4107. );
  4108. const textFieldValue = qtyFieldEnabled
  4109. ? hasPickOverrideRow
  4110. ? String(pickQtyData[lotKey])
  4111. : String(displayedSubmitQty)
  4112. : String(displayedSubmitQty);
  4113. return (
  4114. <Stack
  4115. direction="row"
  4116. spacing={1}
  4117. alignItems="center"
  4118. >
  4119. <TextField
  4120. type="number"
  4121. size="small"
  4122. disabled={!qtyFieldEnabled}
  4123. value={textFieldValue}
  4124. onKeyDown={(e) => {
  4125. if (!qtyFieldEnabled) return;
  4126. if (e.key !== "{") return;
  4127. e.preventDefault();
  4128. setWorkbenchSubmitQtyFieldEnabledByLotKey(
  4129. (prev) => ({
  4130. ...prev,
  4131. [lotKey]: false,
  4132. }),
  4133. );
  4134. (
  4135. e.currentTarget as HTMLInputElement
  4136. ).blur();
  4137. }}
  4138. onChange={(e) => {
  4139. if (!qtyFieldEnabled) return;
  4140. handlePickQtyChange(
  4141. lotKey,
  4142. e.target.value,
  4143. );
  4144. }}
  4145. inputProps={{ min: 0, step: 1 }}
  4146. sx={{
  4147. width: 96,
  4148. "& .MuiInputBase-input": {
  4149. fontSize: "0.75rem",
  4150. py: 0.5,
  4151. textAlign: "center",
  4152. },
  4153. }}
  4154. />
  4155. <Button
  4156. variant="outlined"
  4157. size="small"
  4158. onClick={() => {
  4159. setWorkbenchSubmitQtyFieldEnabledByLotKey(
  4160. (prev) => ({
  4161. ...prev,
  4162. [lotKey]: !(prev[lotKey] === true),
  4163. }),
  4164. );
  4165. }}
  4166. disabled={
  4167. lot.stockOutLineStatus ===
  4168. "completed" ||
  4169. (Number(lot.stockOutLineId) > 0 &&
  4170. actionBusyBySolId[
  4171. Number(lot.stockOutLineId)
  4172. ] === true)
  4173. }
  4174. sx={{
  4175. fontSize: "0.7rem",
  4176. py: 0.5,
  4177. minHeight: "28px",
  4178. minWidth: "60px",
  4179. borderColor: "warning.main",
  4180. color: "warning.main",
  4181. }}
  4182. title={
  4183. qtyFieldEnabled
  4184. ? tPick("Lock quantity")
  4185. : tPick("Edit quantity")
  4186. }
  4187. >
  4188. {tPick("Edit")}
  4189. </Button>
  4190. <Button
  4191. variant="outlined"
  4192. size="small"
  4193. onClick={async () => {
  4194. const solId =
  4195. Number(lot.stockOutLineId) || 0;
  4196. if (solId > 0) {
  4197. setActionBusyBySolId((prev) => ({
  4198. ...prev,
  4199. [solId]: true,
  4200. }));
  4201. }
  4202. try {
  4203. if (
  4204. currentUserId &&
  4205. lot.pickOrderId &&
  4206. lot.itemId
  4207. ) {
  4208. try {
  4209. await updateHandledBy(
  4210. lot.pickOrderId,
  4211. lot.itemId,
  4212. );
  4213. } catch (error) {
  4214. console.error(
  4215. "❌ Error updating handler (non-critical):",
  4216. error,
  4217. );
  4218. }
  4219. }
  4220. await handleSubmitPickQtyWithQty(
  4221. lot,
  4222. 0,
  4223. "justComplete",
  4224. );
  4225. } finally {
  4226. if (solId > 0) {
  4227. setActionBusyBySolId((prev) => ({
  4228. ...prev,
  4229. [solId]: false,
  4230. }));
  4231. }
  4232. }
  4233. }}
  4234. disabled={
  4235. (Number(lot.stockOutLineId) > 0 &&
  4236. actionBusyBySolId[
  4237. Number(lot.stockOutLineId)
  4238. ] === true) ||
  4239. lot.stockOutLineStatus ===
  4240. "completed" ||
  4241. lot.stockOutLineStatus === "checked" ||
  4242. lot.stockOutLineStatus ===
  4243. "partially_completed" ||
  4244. lot.stockOutLineStatus ===
  4245. "partially_complete" ||
  4246. // isUnavailableLot ||
  4247. (Number(lot.stockOutLineId) > 0 &&
  4248. issuePickedQtyBySolId[
  4249. Number(lot.stockOutLineId)
  4250. ] !== undefined)
  4251. }
  4252. title={
  4253. isUnavailableLot
  4254. ? t(
  4255. "is unavable. Please check around have available QR code or not.",
  4256. )
  4257. : undefined
  4258. }
  4259. sx={{
  4260. fontSize: "0.7rem",
  4261. py: 0.5,
  4262. minHeight: "28px",
  4263. minWidth: "90px",
  4264. }}
  4265. >
  4266. {tPick("Just Completed")}
  4267. </Button>
  4268. </Stack>
  4269. );
  4270. })()}
  4271. </Box>
  4272. </TableCell>
  4273. </TableRow>
  4274. );
  4275. })
  4276. )}
  4277. </TableBody>
  4278. </Table>
  4279. </TableContainer>
  4280. <TablePagination
  4281. component="div"
  4282. count={
  4283. selectedFloor ? filteredByFloor.length : combinedLotData.length
  4284. }
  4285. page={paginationController.pageNum}
  4286. rowsPerPage={paginationController.pageSize}
  4287. onPageChange={handlePageChange}
  4288. onRowsPerPageChange={handlePageSizeChange}
  4289. rowsPerPageOptions={[10, 25, 50]}
  4290. labelRowsPerPage={t("Rows per page")}
  4291. labelDisplayedRows={({ from, to, count }) =>
  4292. `${from}-${to} of ${count !== -1 ? count : `more than ${to}`}`
  4293. }
  4294. />
  4295. </Box>
  4296. </Stack>
  4297. {/* QR Code Modal */}
  4298. <QrCodeModal
  4299. open={qrModalOpen}
  4300. onClose={() => {
  4301. setQrModalOpen(false);
  4302. setSelectedLotForQr(null);
  4303. // Keep scanner active like GoodPickExecutiondetail.
  4304. resetScan();
  4305. }}
  4306. lot={selectedLotForQr}
  4307. combinedLotData={combinedLotData}
  4308. onQrCodeSubmit={handleQrCodeSubmitFromModal}
  4309. />
  4310. <WorkbenchLotLabelPrintModal
  4311. open={workbenchLotLabelModalOpen}
  4312. onClose={() => {
  4313. setWorkbenchLotLabelModalOpen(false);
  4314. setWorkbenchLotLabelContextLot(null);
  4315. setWorkbenchLotLabelInitialPayload(null);
  4316. setWorkbenchLotLabelReminderText(null);
  4317. }}
  4318. initialPayload={workbenchLotLabelInitialPayload}
  4319. initialItemId={
  4320. workbenchLotLabelContextLot != null
  4321. ? Number(workbenchLotLabelContextLot.itemId)
  4322. : null
  4323. }
  4324. defaultPrinterName={defaultLabelPrinterName}
  4325. hideScanSection={
  4326. workbenchLotLabelInitialPayload != null ||
  4327. workbenchLotLabelContextLot != null
  4328. }
  4329. warehouseCodePrefixFilter={lotFloorPrefixFilter}
  4330. triggerLotAvailableQty={
  4331. workbenchLotLabelContextLot != null
  4332. ? Number(workbenchLotLabelContextLot.availableQty)
  4333. : null
  4334. }
  4335. triggerLotUom={
  4336. workbenchLotLabelContextLot != null
  4337. ? String(workbenchLotLabelContextLot.uomDesc ?? "").trim() || null
  4338. : null
  4339. }
  4340. disableScanPick={workbenchLotLabelScanPickDisabled}
  4341. onWorkbenchScanPick={handleWorkbenchLotLabelScanPick}
  4342. submitQty={workbenchLotLabelSubmitQty}
  4343. onSubmitQtyChange={handleWorkbenchLotLabelSubmitQtyChange}
  4344. reminderText={workbenchLotLabelReminderText ?? undefined}
  4345. />
  4346. {/* Manual Lot Confirmation Modal (test shortcut {2fic}); JO Workbench 不使用 LotConfirmationModal,直接走 handleLotConfirmation */}
  4347. <ManualLotConfirmationModal
  4348. open={manualLotConfirmationOpen}
  4349. onClose={() => setManualLotConfirmationOpen(false)}
  4350. onConfirm={(currentLotNo, newLotNo) => {
  4351. setManualLotConfirmationOpen(false);
  4352. const row = selectedLotForQr;
  4353. if (
  4354. !row?.stockOutLineId ||
  4355. !row?.pickOrderLineId ||
  4356. row.itemId == null
  4357. ) {
  4358. alert(
  4359. L(
  4360. "Open 挑號 QR 碼 on a pick line first, then scan {2fic} to use manual lot substitution.",
  4361. "Open Pick-lot QR code on a pick line first, then scan {2fic} to use manual lot substitution.",
  4362. ),
  4363. );
  4364. return;
  4365. }
  4366. setExpectedLotData({
  4367. ...row,
  4368. lotNo: currentLotNo,
  4369. });
  4370. setScannedLotData({
  4371. lotNo: newLotNo,
  4372. itemCode: String(row.itemCode ?? ""),
  4373. itemName: String(row.itemName ?? ""),
  4374. inventoryLotLineId: null,
  4375. stockInLineId: null,
  4376. });
  4377. window.setTimeout(() => {
  4378. void handleLotConfirmation();
  4379. }, 0);
  4380. }}
  4381. expectedLot={expectedLotData}
  4382. scannedLot={scannedLotData}
  4383. isLoading={isConfirmingLot}
  4384. />
  4385. </FormProvider>
  4386. </TestQrCodeProvider>
  4387. );
  4388. };
  4389. export default JobPickExecution;