FPSMS-frontend
Non puoi selezionare più di 25 argomenti Gli argomenti devono iniziare con una lettera o un numero, possono includere trattini ('-') e possono essere lunghi fino a 35 caratteri.
 
 

4710 righe
172 KiB

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