FPSMS-frontend
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

3869 line
147 KiB

  1. "use client";
  2. import {
  3. Box,
  4. Button,
  5. Stack,
  6. TextField,
  7. Typography,
  8. Alert,
  9. CircularProgress,
  10. Table,
  11. TableBody,
  12. TableCell,
  13. TableContainer,
  14. TableHead,
  15. TableRow,
  16. Paper,
  17. Checkbox,
  18. TablePagination,
  19. Modal,
  20. Chip,
  21. } from "@mui/material";
  22. import dayjs from 'dayjs';
  23. import TestQrCodeProvider from '../QrCodeScannerProvider/TestQrCodeProvider';
  24. import { fetchLotDetail } from "@/app/api/inventory/actions";
  25. import React, { useCallback, useEffect, useState, useRef, useMemo, startTransition } from "react";
  26. import { useTranslation } from "react-i18next";
  27. import { useRouter } from "next/navigation";
  28. import {
  29. updateStockOutLineStatus,
  30. createStockOutLine,
  31. updateStockOutLine,
  32. recordPickExecutionIssue,
  33. fetchFGPickOrders, // Add this import
  34. FGPickOrderResponse,
  35. stockReponse,
  36. PickExecutionIssueData,
  37. checkPickOrderCompletion,
  38. fetchAllPickOrderLotsHierarchical,
  39. PickOrderCompletionResponse,
  40. checkAndCompletePickOrderByConsoCode,
  41. updateSuggestedLotLineId,
  42. updateStockOutLineStatusByQRCodeAndLotNo,
  43. confirmLotSubstitution,
  44. fetchDoPickOrderDetail, // 必须添加
  45. DoPickOrderDetail, // 必须添加
  46. fetchFGPickOrdersByUserId ,
  47. batchQrSubmit,
  48. batchSubmitList, // 添加:导入 batchSubmitList
  49. batchSubmitListRequest, // 添加:导入类型
  50. batchSubmitListLineRequest,
  51. batchScan,
  52. BatchScanRequest,
  53. BatchScanLineRequest,
  54. } from "@/app/api/pickOrder/actions";
  55. import FGPickOrderInfoCard from "./FGPickOrderInfoCard";
  56. import LotConfirmationModal from "./LotConfirmationModal";
  57. //import { fetchItem } from "@/app/api/settings/item";
  58. import { updateInventoryLotLineStatus, analyzeQrCode } from "@/app/api/inventory/actions";
  59. import { fetchNameList, NameList } from "@/app/api/user/actions";
  60. import {
  61. FormProvider,
  62. useForm,
  63. } from "react-hook-form";
  64. import SearchBox, { Criterion } from "../SearchBox";
  65. import { CreateStockOutLine } from "@/app/api/pickOrder/actions";
  66. import { updateInventoryLotLineQuantities } from "@/app/api/inventory/actions";
  67. import QrCodeIcon from '@mui/icons-material/QrCode';
  68. import { useQrCodeScannerContext } from '../QrCodeScannerProvider/QrCodeScannerProvider';
  69. import { useSession } from "next-auth/react";
  70. import { SessionWithTokens } from "@/config/authConfig";
  71. import { fetchStockInLineInfo } from "@/app/api/po/actions";
  72. import GoodPickExecutionForm from "./GoodPickExecutionForm";
  73. import FGPickOrderCard from "./FGPickOrderCard";
  74. import LinearProgressWithLabel from "../common/LinearProgressWithLabel";
  75. import ScanStatusAlert from "../common/ScanStatusAlert";
  76. interface Props {
  77. filterArgs: Record<string, any>;
  78. onSwitchToRecordTab?: () => void;
  79. onRefreshReleasedOrderCount?: () => void;
  80. }
  81. /** 同物料多行时,优先对「有建议批次号」的行做替换,避免误选「无批次/不足」行 */
  82. function pickExpectedLotForSubstitution(activeSuggestedLots: any[]): any | null {
  83. if (!activeSuggestedLots?.length) return null;
  84. const withLotNo = activeSuggestedLots.filter(
  85. (l) => l.lotNo != null && String(l.lotNo).trim() !== ""
  86. );
  87. if (withLotNo.length === 1) return withLotNo[0];
  88. if (withLotNo.length > 1) {
  89. const pending = withLotNo.find(
  90. (l) => (l.stockOutLineStatus || "").toLowerCase() === "pending"
  91. );
  92. return pending || withLotNo[0];
  93. }
  94. return activeSuggestedLots[0];
  95. }
  96. // QR Code Modal Component (from LotTable)
  97. const QrCodeModal: React.FC<{
  98. open: boolean;
  99. onClose: () => void;
  100. lot: any | null;
  101. onQrCodeSubmit: (lotNo: string) => void;
  102. combinedLotData: any[]; // Add this prop
  103. lotConfirmationOpen: boolean;
  104. }> = ({ open, onClose, lot, onQrCodeSubmit, combinedLotData,lotConfirmationOpen = false }) => {
  105. const { t } = useTranslation("pickOrder");
  106. const { values: qrValues, isScanning, startScan, stopScan, resetScan } = useQrCodeScannerContext();
  107. const [manualInput, setManualInput] = useState<string>('');
  108. const [manualInputSubmitted, setManualInputSubmitted] = useState<boolean>(false);
  109. const [manualInputError, setManualInputError] = useState<boolean>(false);
  110. const [isProcessingQr, setIsProcessingQr] = useState<boolean>(false);
  111. const [qrScanFailed, setQrScanFailed] = useState<boolean>(false);
  112. const [qrScanSuccess, setQrScanSuccess] = useState<boolean>(false);
  113. const [processedQrCodes, setProcessedQrCodes] = useState<Set<string>>(new Set());
  114. const [scannedQrResult, setScannedQrResult] = useState<string>('');
  115. const [fgPickOrder, setFgPickOrder] = useState<FGPickOrderResponse | null>(null);
  116. const fetchingRef = useRef<Set<number>>(new Set());
  117. // Process scanned QR codes
  118. useEffect(() => {
  119. // ✅ Don't process if modal is not open
  120. if (!open) {
  121. return;
  122. }
  123. // ✅ Don't process if lot confirmation modal is open
  124. if (lotConfirmationOpen) {
  125. console.log("Lot confirmation modal is open, skipping QrCodeModal processing...");
  126. return;
  127. }
  128. if (qrValues.length > 0 && lot && !isProcessingQr && !qrScanSuccess) {
  129. const latestQr = qrValues[qrValues.length - 1];
  130. if (processedQrCodes.has(latestQr)) {
  131. console.log("QR code already processed, skipping...");
  132. return;
  133. }
  134. try {
  135. const qrData = JSON.parse(latestQr);
  136. if (qrData.stockInLineId && qrData.itemId) {
  137. // ✅ Check if we're already fetching this stockInLineId
  138. if (fetchingRef.current.has(qrData.stockInLineId)) {
  139. console.log(` [QR MODAL] Already fetching stockInLineId: ${qrData.stockInLineId}, skipping duplicate call`);
  140. return;
  141. }
  142. setProcessedQrCodes(prev => new Set(prev).add(latestQr));
  143. setIsProcessingQr(true);
  144. setQrScanFailed(false);
  145. // ✅ Mark as fetching
  146. fetchingRef.current.add(qrData.stockInLineId);
  147. const fetchStartTime = performance.now();
  148. console.log(` [QR MODAL] Starting fetchStockInLineInfo for stockInLineId: ${qrData.stockInLineId}`);
  149. fetchStockInLineInfo(qrData.stockInLineId)
  150. .then((stockInLineInfo) => {
  151. // ✅ Remove from fetching set
  152. fetchingRef.current.delete(qrData.stockInLineId);
  153. // ✅ Check again if modal is still open and lot confirmation is not open
  154. if (!open || lotConfirmationOpen) {
  155. console.log("Modal state changed, skipping result processing");
  156. return;
  157. }
  158. const fetchTime = performance.now() - fetchStartTime;
  159. console.log(` [QR MODAL] fetchStockInLineInfo time: ${fetchTime.toFixed(2)}ms (${(fetchTime / 1000).toFixed(3)}s)`);
  160. console.log("Stock in line info:", stockInLineInfo);
  161. setScannedQrResult(stockInLineInfo.lotNo || 'Unknown lot number');
  162. if (stockInLineInfo.lotNo === lot.lotNo) {
  163. console.log(` QR Code verified for lot: ${lot.lotNo}`);
  164. setQrScanSuccess(true);
  165. onQrCodeSubmit(lot.lotNo);
  166. // onClose();
  167. //resetScan();
  168. } else {
  169. console.log(` QR Code mismatch. Expected: ${lot.lotNo}, Got: ${stockInLineInfo.lotNo}`);
  170. setQrScanFailed(true);
  171. setManualInputError(true);
  172. setManualInputSubmitted(true);
  173. }
  174. })
  175. .catch((error) => {
  176. // ✅ Remove from fetching set
  177. fetchingRef.current.delete(qrData.stockInLineId);
  178. // ✅ Check again if modal is still open
  179. if (!open || lotConfirmationOpen) {
  180. console.log("Modal state changed, skipping error handling");
  181. return;
  182. }
  183. const fetchTime = performance.now() - fetchStartTime;
  184. console.error(`❌ [QR MODAL] fetchStockInLineInfo failed after ${fetchTime.toFixed(2)}ms:`, error);
  185. setScannedQrResult('Error fetching data');
  186. setQrScanFailed(true);
  187. setManualInputError(true);
  188. setManualInputSubmitted(true);
  189. })
  190. .finally(() => {
  191. setIsProcessingQr(false);
  192. });
  193. } else {
  194. const qrContent = latestQr.replace(/[{}]/g, '');
  195. setScannedQrResult(qrContent);
  196. if (qrContent === lot.lotNo) {
  197. setQrScanSuccess(true);
  198. onQrCodeSubmit(lot.lotNo);
  199. onClose();
  200. resetScan();
  201. } else {
  202. setQrScanFailed(true);
  203. setManualInputError(true);
  204. setManualInputSubmitted(true);
  205. }
  206. }
  207. } catch (error) {
  208. console.log("QR code is not JSON format, trying direct comparison");
  209. const qrContent = latestQr.replace(/[{}]/g, '');
  210. setScannedQrResult(qrContent);
  211. if (qrContent === lot.lotNo) {
  212. setQrScanSuccess(true);
  213. onQrCodeSubmit(lot.lotNo);
  214. onClose();
  215. resetScan();
  216. } else {
  217. setQrScanFailed(true);
  218. setManualInputError(true);
  219. setManualInputSubmitted(true);
  220. }
  221. }
  222. }
  223. }, [qrValues, lot, onQrCodeSubmit, onClose, resetScan, isProcessingQr, qrScanSuccess, processedQrCodes, lotConfirmationOpen, open]);
  224. // Clear states when modal opens
  225. useEffect(() => {
  226. if (open) {
  227. setManualInput('');
  228. setManualInputSubmitted(false);
  229. setManualInputError(false);
  230. setIsProcessingQr(false);
  231. setQrScanFailed(false);
  232. setQrScanSuccess(false);
  233. setScannedQrResult('');
  234. setProcessedQrCodes(new Set());
  235. }
  236. }, [open]);
  237. useEffect(() => {
  238. if (lot) {
  239. setManualInput('');
  240. setManualInputSubmitted(false);
  241. setManualInputError(false);
  242. setIsProcessingQr(false);
  243. setQrScanFailed(false);
  244. setQrScanSuccess(false);
  245. setScannedQrResult('');
  246. setProcessedQrCodes(new Set());
  247. }
  248. }, [lot]);
  249. // Auto-submit manual input when it matches
  250. useEffect(() => {
  251. if (manualInput.trim() === lot?.lotNo && manualInput.trim() !== '' && !qrScanFailed && !qrScanSuccess) {
  252. console.log(' Auto-submitting manual input:', manualInput.trim());
  253. const timer = setTimeout(() => {
  254. setQrScanSuccess(true);
  255. onQrCodeSubmit(lot.lotNo);
  256. onClose();
  257. setManualInput('');
  258. setManualInputError(false);
  259. setManualInputSubmitted(false);
  260. }, 200);
  261. return () => clearTimeout(timer);
  262. }
  263. }, [manualInput, lot, onQrCodeSubmit, onClose, qrScanFailed, qrScanSuccess]);
  264. const handleManualSubmit = () => {
  265. if (manualInput.trim() === lot?.lotNo) {
  266. setQrScanSuccess(true);
  267. onQrCodeSubmit(lot.lotNo);
  268. onClose();
  269. setManualInput('');
  270. } else {
  271. setQrScanFailed(true);
  272. setManualInputError(true);
  273. setManualInputSubmitted(true);
  274. }
  275. };
  276. useEffect(() => {
  277. if (open) {
  278. startScan();
  279. }
  280. }, [open, startScan]);
  281. return (
  282. <Modal open={open} onClose={onClose}>
  283. <Box sx={{
  284. position: 'absolute',
  285. top: '50%',
  286. left: '50%',
  287. transform: 'translate(-50%, -50%)',
  288. bgcolor: 'background.paper',
  289. p: 3,
  290. borderRadius: 2,
  291. minWidth: 400,
  292. }}>
  293. <Typography variant="h6" gutterBottom>
  294. {t("QR Code Scan for Lot")}: {lot?.lotNo}
  295. </Typography>
  296. {isProcessingQr && (
  297. <Box sx={{ mb: 2, p: 2, backgroundColor: '#e3f2fd', borderRadius: 1 }}>
  298. <Typography variant="body2" color="primary">
  299. {t("Processing QR code...")}
  300. </Typography>
  301. </Box>
  302. )}
  303. <Box sx={{ mb: 2 }}>
  304. <Typography variant="body2" gutterBottom>
  305. <strong>{t("Manual Input")}:</strong>
  306. </Typography>
  307. <TextField
  308. fullWidth
  309. size="small"
  310. value={manualInput}
  311. onChange={(e) => {
  312. setManualInput(e.target.value);
  313. if (qrScanFailed || manualInputError) {
  314. setQrScanFailed(false);
  315. setManualInputError(false);
  316. setManualInputSubmitted(false);
  317. }
  318. }}
  319. sx={{ mb: 1 }}
  320. error={manualInputSubmitted && manualInputError}
  321. helperText={
  322. manualInputSubmitted && manualInputError
  323. ? `${t("The input is not the same as the expected lot number.")}`
  324. : ''
  325. }
  326. />
  327. <Button
  328. variant="contained"
  329. onClick={handleManualSubmit}
  330. disabled={!manualInput.trim()}
  331. size="small"
  332. color="primary"
  333. >
  334. {t("Submit")}
  335. </Button>
  336. </Box>
  337. {qrValues.length > 0 && (
  338. <Box sx={{
  339. mb: 2,
  340. p: 2,
  341. backgroundColor: qrScanFailed ? '#ffebee' : qrScanSuccess ? '#e8f5e8' : '#f5f5f5',
  342. borderRadius: 1
  343. }}>
  344. <Typography variant="body2" color={qrScanFailed ? 'error' : qrScanSuccess ? 'success' : 'text.secondary'}>
  345. <strong>{t("QR Scan Result:")}</strong> {scannedQrResult}
  346. </Typography>
  347. {qrScanSuccess && (
  348. <Typography variant="caption" color="success" display="block">
  349. {t("Verified successfully!")}
  350. </Typography>
  351. )}
  352. </Box>
  353. )}
  354. <Box sx={{ mt: 2, textAlign: 'right' }}>
  355. <Button onClick={onClose} variant="outlined">
  356. {t("Cancel")}
  357. </Button>
  358. </Box>
  359. </Box>
  360. </Modal>
  361. );
  362. };
  363. const ManualLotConfirmationModal: React.FC<{
  364. open: boolean;
  365. onClose: () => void;
  366. onConfirm: (expectedLotNo: string, scannedLotNo: string) => void;
  367. expectedLot: {
  368. lotNo: string;
  369. itemCode: string;
  370. itemName: string;
  371. } | null;
  372. scannedLot: {
  373. lotNo: string;
  374. itemCode: string;
  375. itemName: string;
  376. } | null;
  377. isLoading?: boolean;
  378. }> = ({ open, onClose, onConfirm, expectedLot, scannedLot, isLoading = false }) => {
  379. const { t } = useTranslation("pickOrder");
  380. const [expectedLotInput, setExpectedLotInput] = useState<string>('');
  381. const [scannedLotInput, setScannedLotInput] = useState<string>('');
  382. const [error, setError] = useState<string>('');
  383. // 当模态框打开时,预填充输入框
  384. useEffect(() => {
  385. if (open) {
  386. setExpectedLotInput(expectedLot?.lotNo || '');
  387. setScannedLotInput(scannedLot?.lotNo || '');
  388. setError('');
  389. }
  390. }, [open, expectedLot, scannedLot]);
  391. const handleConfirm = () => {
  392. if (!expectedLotInput.trim() || !scannedLotInput.trim()) {
  393. setError(t("Please enter both expected and scanned lot numbers."));
  394. return;
  395. }
  396. if (expectedLotInput.trim() === scannedLotInput.trim()) {
  397. setError(t("Expected and scanned lot numbers cannot be the same."));
  398. return;
  399. }
  400. onConfirm(expectedLotInput.trim(), scannedLotInput.trim());
  401. };
  402. return (
  403. <Modal open={open} onClose={onClose}>
  404. <Box sx={{
  405. position: 'absolute',
  406. top: '50%',
  407. left: '50%',
  408. transform: 'translate(-50%, -50%)',
  409. bgcolor: 'background.paper',
  410. p: 3,
  411. borderRadius: 2,
  412. minWidth: 500,
  413. }}>
  414. <Typography variant="h6" gutterBottom color="warning.main">
  415. {t("Manual Lot Confirmation")}
  416. </Typography>
  417. <Box sx={{ mb: 2 }}>
  418. <Typography variant="body2" gutterBottom>
  419. <strong>{t("Expected Lot Number")}:</strong>
  420. </Typography>
  421. <TextField
  422. fullWidth
  423. size="small"
  424. value={expectedLotInput}
  425. onChange={(e) => {
  426. setExpectedLotInput(e.target.value);
  427. setError('');
  428. }}
  429. placeholder={expectedLot?.lotNo || t("Enter expected lot number")}
  430. sx={{ mb: 2 }}
  431. error={!!error && !expectedLotInput.trim()}
  432. />
  433. </Box>
  434. <Box sx={{ mb: 2 }}>
  435. <Typography variant="body2" gutterBottom>
  436. <strong>{t("Scanned Lot Number")}:</strong>
  437. </Typography>
  438. <TextField
  439. fullWidth
  440. size="small"
  441. value={scannedLotInput}
  442. onChange={(e) => {
  443. setScannedLotInput(e.target.value);
  444. setError('');
  445. }}
  446. placeholder={scannedLot?.lotNo || t("Enter scanned lot number")}
  447. sx={{ mb: 2 }}
  448. error={!!error && !scannedLotInput.trim()}
  449. />
  450. </Box>
  451. {error && (
  452. <Box sx={{ mb: 2, p: 1, backgroundColor: '#ffebee', borderRadius: 1 }}>
  453. <Typography variant="body2" color="error">
  454. {error}
  455. </Typography>
  456. </Box>
  457. )}
  458. <Box sx={{ mt: 2, display: 'flex', justifyContent: 'flex-end', gap: 2 }}>
  459. <Button onClick={onClose} variant="outlined" disabled={isLoading}>
  460. {t("Cancel")}
  461. </Button>
  462. <Button
  463. onClick={handleConfirm}
  464. variant="contained"
  465. color="warning"
  466. disabled={isLoading || !expectedLotInput.trim() || !scannedLotInput.trim()}
  467. >
  468. {isLoading ? t("Processing...") : t("Confirm")}
  469. </Button>
  470. </Box>
  471. </Box>
  472. </Modal>
  473. );
  474. };
  475. /** 過期批號(未換有效批前):與 noLot 類似——單筆/批量預設提交量為 0,除非 Issue 改數 */
  476. function isLotAvailabilityExpired(lot: any): boolean {
  477. return String(lot?.lotAvailability || "").toLowerCase() === "expired";
  478. }
  479. /** Issue「改數」未寫入 SOL,刷新/換頁後需靠 session 還原,否則 Qty will submit 會回到 req */
  480. const FG_ISSUE_PICKED_KEY = (doPickOrderId: number) =>
  481. `fpsms-fg-issuePickedQty:${doPickOrderId}`;
  482. function loadIssuePickedMap(doPickOrderId: number): Record<number, number> {
  483. if (typeof window === "undefined" || !doPickOrderId) return {};
  484. try {
  485. const raw = sessionStorage.getItem(FG_ISSUE_PICKED_KEY(doPickOrderId));
  486. if (!raw) return {};
  487. const parsed = JSON.parse(raw) as Record<string, number>;
  488. const out: Record<number, number> = {};
  489. Object.entries(parsed).forEach(([k, v]) => {
  490. const n = Number(v);
  491. if (!Number.isNaN(n)) out[Number(k)] = n;
  492. });
  493. return out;
  494. } catch {
  495. return {};
  496. }
  497. }
  498. function saveIssuePickedMap(doPickOrderId: number, map: Record<number, number>) {
  499. if (typeof window === "undefined" || !doPickOrderId) return;
  500. try {
  501. sessionStorage.setItem(FG_ISSUE_PICKED_KEY(doPickOrderId), JSON.stringify(map));
  502. } catch {
  503. // quota / private mode
  504. }
  505. }
  506. const PickExecution: React.FC<Props> = ({ filterArgs, onSwitchToRecordTab, onRefreshReleasedOrderCount }) => {
  507. const { t } = useTranslation("pickOrder");
  508. const router = useRouter();
  509. const { data: session } = useSession() as { data: SessionWithTokens | null };
  510. const [doPickOrderDetail, setDoPickOrderDetail] = useState<DoPickOrderDetail | null>(null);
  511. const [selectedPickOrderId, setSelectedPickOrderId] = useState<number | null>(null);
  512. const [pickOrderSwitching, setPickOrderSwitching] = useState(false);
  513. const currentUserId = session?.id ? parseInt(session.id) : undefined;
  514. const [allLotsCompleted, setAllLotsCompleted] = useState(false);
  515. const [combinedLotData, setCombinedLotData] = useState<any[]>([]);
  516. const [combinedDataLoading, setCombinedDataLoading] = useState(false);
  517. const [originalCombinedData, setOriginalCombinedData] = useState<any[]>([]);
  518. // issue form 里填的 actualPickQty(用于 batch submit 只提交实际拣到数量,而不是补拣到 required)
  519. const [issuePickedQtyBySolId, setIssuePickedQtyBySolId] = useState<Record<number, number>>({});
  520. const applyLocalStockOutLineUpdate = useCallback((
  521. stockOutLineId: number,
  522. status: string,
  523. actualPickQty?: number
  524. ) => {
  525. setCombinedLotData(prev => prev.map((lot) => {
  526. if (Number(lot.stockOutLineId) !== Number(stockOutLineId)) return lot;
  527. return {
  528. ...lot,
  529. stockOutLineStatus: status,
  530. ...(typeof actualPickQty === "number"
  531. ? { actualPickQty, stockOutLineQty: actualPickQty }
  532. : {}),
  533. };
  534. }));
  535. }, []);
  536. // 防止重复点击(Submit / Just Completed / Issue)
  537. const [actionBusyBySolId, setActionBusyBySolId] = useState<Record<number, boolean>>({});
  538. const { values: qrValues, isScanning, startScan, stopScan, resetScan } = useQrCodeScannerContext();
  539. const [qrScanInput, setQrScanInput] = useState<string>('');
  540. const [qrScanError, setQrScanError] = useState<boolean>(false);
  541. const [qrScanErrorMsg, setQrScanErrorMsg] = useState<string>('');
  542. const [qrScanSuccess, setQrScanSuccess] = useState<boolean>(false);
  543. const [manualLotConfirmationOpen, setManualLotConfirmationOpen] = useState(false);
  544. const [pickQtyData, setPickQtyData] = useState<Record<string, number>>({});
  545. const [searchQuery, setSearchQuery] = useState<Record<string, any>>({});
  546. const [paginationController, setPaginationController] = useState({
  547. pageNum: 0,
  548. pageSize: -1,
  549. });
  550. const [usernameList, setUsernameList] = useState<NameList[]>([]);
  551. const initializationRef = useRef(false);
  552. const autoAssignRef = useRef(false);
  553. const formProps = useForm();
  554. const errors = formProps.formState.errors;
  555. // QR scanner states (always-on, no modal)
  556. const [selectedLotForQr, setSelectedLotForQr] = useState<any | null>(null);
  557. const [lotConfirmationOpen, setLotConfirmationOpen] = useState(false);
  558. const [expectedLotData, setExpectedLotData] = useState<any>(null);
  559. const [scannedLotData, setScannedLotData] = useState<any>(null);
  560. const [isConfirmingLot, setIsConfirmingLot] = useState(false);
  561. // Add GoodPickExecutionForm states
  562. const [pickExecutionFormOpen, setPickExecutionFormOpen] = useState(false);
  563. const [selectedLotForExecutionForm, setSelectedLotForExecutionForm] = useState<any | null>(null);
  564. const [fgPickOrders, setFgPickOrders] = useState<FGPickOrderResponse[]>([]);
  565. const [fgPickOrdersLoading, setFgPickOrdersLoading] = useState(false);
  566. // Add these missing state variables after line 352
  567. const [isManualScanning, setIsManualScanning] = useState<boolean>(false);
  568. // Track processed QR codes by itemId+stockInLineId combination for better lot confirmation handling
  569. const [processedQrCombinations, setProcessedQrCombinations] = useState<Map<number, Set<number>>>(new Map());
  570. const [processedQrCodes, setProcessedQrCodes] = useState<Set<string>>(new Set());
  571. const [lastProcessedQr, setLastProcessedQr] = useState<string>('');
  572. const [isRefreshingData, setIsRefreshingData] = useState<boolean>(false);
  573. const [isSubmittingAll, setIsSubmittingAll] = useState<boolean>(false);
  574. // Cache for fetchStockInLineInfo API calls to avoid redundant requests
  575. const stockInLineInfoCache = useRef<Map<number, { lotNo: string | null; timestamp: number }>>(new Map());
  576. const CACHE_TTL = 60000; // 60 seconds cache TTL
  577. const abortControllerRef = useRef<AbortController | null>(null);
  578. const qrProcessingTimeoutRef = useRef<NodeJS.Timeout | null>(null);
  579. // Use refs for processed QR tracking to avoid useEffect dependency issues and delays
  580. const processedQrCodesRef = useRef<Set<string>>(new Set());
  581. const lastProcessedQrRef = useRef<string>('');
  582. // Store callbacks in refs to avoid useEffect dependency issues
  583. const processOutsideQrCodeRef = useRef<
  584. ((latestQr: string, qrScanCountAtInvoke?: number) => Promise<void>) | null
  585. >(null);
  586. const resetScanRef = useRef<(() => void) | null>(null);
  587. const lotConfirmOpenedQrCountRef = useRef<number>(0);
  588. // Handle QR code button click
  589. const handleQrCodeClick = (pickOrderId: number) => {
  590. console.log(`QR Code clicked for pick order ID: ${pickOrderId}`);
  591. // TODO: Implement QR code functionality
  592. };
  593. const progress = useMemo(() => {
  594. if (combinedLotData.length === 0) {
  595. return { completed: 0, total: 0 };
  596. }
  597. // 與 allItemsReady 一致:noLot / 過期批號 的 pending 也算「已面對該行」可收尾
  598. const nonPendingCount = combinedLotData.filter((lot) => {
  599. const status = lot.stockOutLineStatus?.toLowerCase();
  600. if (status !== "pending") return true;
  601. if (lot.noLot === true || isLotAvailabilityExpired(lot)) return true;
  602. return false;
  603. }).length;
  604. return {
  605. completed: nonPendingCount,
  606. total: combinedLotData.length,
  607. };
  608. }, [combinedLotData]);
  609. // Cached version of fetchStockInLineInfo to avoid redundant API calls
  610. const fetchStockInLineInfoCached = useCallback(async (stockInLineId: number): Promise<{ lotNo: string | null }> => {
  611. const now = Date.now();
  612. const cached = stockInLineInfoCache.current.get(stockInLineId);
  613. // Return cached value if still valid
  614. if (cached && (now - cached.timestamp) < CACHE_TTL) {
  615. console.log(`✅ [CACHE HIT] Using cached stockInLineInfo for ${stockInLineId}`);
  616. return { lotNo: cached.lotNo };
  617. }
  618. // Cancel previous request if exists
  619. if (abortControllerRef.current) {
  620. abortControllerRef.current.abort();
  621. }
  622. // Create new abort controller for this request
  623. const abortController = new AbortController();
  624. abortControllerRef.current = abortController;
  625. try {
  626. console.log(` [CACHE MISS] Fetching stockInLineInfo for ${stockInLineId}`);
  627. const stockInLineInfo = await fetchStockInLineInfo(stockInLineId);
  628. // Store in cache
  629. stockInLineInfoCache.current.set(stockInLineId, {
  630. lotNo: stockInLineInfo.lotNo || null,
  631. timestamp: now
  632. });
  633. // Limit cache size to prevent memory leaks
  634. if (stockInLineInfoCache.current.size > 100) {
  635. const firstKey = stockInLineInfoCache.current.keys().next().value;
  636. if (firstKey !== undefined) {
  637. stockInLineInfoCache.current.delete(firstKey);
  638. }
  639. }
  640. return { lotNo: stockInLineInfo.lotNo || null };
  641. } catch (error: any) {
  642. if (error.name === 'AbortError') {
  643. console.log(` [CACHE] Request aborted for ${stockInLineId}`);
  644. throw error;
  645. }
  646. console.error(`❌ [CACHE] Error fetching stockInLineInfo for ${stockInLineId}:`, error);
  647. throw error;
  648. }
  649. }, []);
  650. const handleLotMismatch = useCallback((expectedLot: any, scannedLot: any, qrScanCountAtOpen?: number) => {
  651. const mismatchStartTime = performance.now();
  652. console.log(` [HANDLE LOT MISMATCH START]`);
  653. console.log(` Start time: ${new Date().toISOString()}`);
  654. console.log("Lot mismatch detected:", { expectedLot, scannedLot });
  655. lotConfirmOpenedQrCountRef.current =
  656. typeof qrScanCountAtOpen === "number" ? qrScanCountAtOpen : 1;
  657. // ✅ Use setTimeout to avoid flushSync warning - schedule modal update in next tick
  658. const setTimeoutStartTime = performance.now();
  659. console.time('setLotConfirmationOpen');
  660. setTimeout(() => {
  661. const setStateStartTime = performance.now();
  662. setExpectedLotData(expectedLot);
  663. setScannedLotData({
  664. ...scannedLot,
  665. lotNo: scannedLot.lotNo || null,
  666. });
  667. setLotConfirmationOpen(true);
  668. const setStateTime = performance.now() - setStateStartTime;
  669. console.timeEnd('setLotConfirmationOpen');
  670. console.log(` [HANDLE LOT MISMATCH] Modal state set to open (setState time: ${setStateTime.toFixed(2)}ms)`);
  671. console.log(`✅ [HANDLE LOT MISMATCH] Modal state set to open`);
  672. }, 0);
  673. const setTimeoutTime = performance.now() - setTimeoutStartTime;
  674. console.log(` [PERF] setTimeout scheduling time: ${setTimeoutTime.toFixed(2)}ms`);
  675. // ✅ Fetch lotNo in background ONLY for display purposes (using cached version)
  676. if (!scannedLot.lotNo && scannedLot.stockInLineId) {
  677. const stockInLineId = scannedLot.stockInLineId;
  678. if (typeof stockInLineId !== 'number') {
  679. console.warn(` [HANDLE LOT MISMATCH] Invalid stockInLineId: ${stockInLineId}`);
  680. return;
  681. }
  682. console.log(` [HANDLE LOT MISMATCH] Fetching lotNo in background (stockInLineId: ${stockInLineId})`);
  683. const fetchStartTime = performance.now();
  684. fetchStockInLineInfoCached(stockInLineId)
  685. .then((stockInLineInfo) => {
  686. const fetchTime = performance.now() - fetchStartTime;
  687. console.log(` [HANDLE LOT MISMATCH] fetchStockInLineInfoCached time: ${fetchTime.toFixed(2)}ms (${(fetchTime / 1000).toFixed(3)}s)`);
  688. const updateStateStartTime = performance.now();
  689. startTransition(() => {
  690. setScannedLotData((prev: any) => ({
  691. ...prev,
  692. lotNo: stockInLineInfo.lotNo || null,
  693. }));
  694. });
  695. const updateStateTime = performance.now() - updateStateStartTime;
  696. console.log(` [PERF] Update scanned lot data time: ${updateStateTime.toFixed(2)}ms`);
  697. const totalTime = performance.now() - mismatchStartTime;
  698. console.log(` [HANDLE LOT MISMATCH] Background fetch completed: ${totalTime.toFixed(2)}ms (${(totalTime / 1000).toFixed(3)}s)`);
  699. })
  700. .catch((error) => {
  701. if (error.name !== 'AbortError') {
  702. const fetchTime = performance.now() - fetchStartTime;
  703. console.error(`❌ [HANDLE LOT MISMATCH] fetchStockInLineInfoCached failed after ${fetchTime.toFixed(2)}ms:`, error);
  704. }
  705. });
  706. } else {
  707. const totalTime = performance.now() - mismatchStartTime;
  708. console.log(` [HANDLE LOT MISMATCH END] Total time: ${totalTime.toFixed(2)}ms (${(totalTime / 1000).toFixed(3)}s)`);
  709. }
  710. }, [fetchStockInLineInfoCached]);
  711. const checkAllLotsCompleted = useCallback((lotData: any[]) => {
  712. if (lotData.length === 0) {
  713. setAllLotsCompleted(false);
  714. return false;
  715. }
  716. // Filter out rejected lots
  717. const nonRejectedLots = lotData.filter(lot =>
  718. lot.lotAvailability !== 'rejected' &&
  719. lot.stockOutLineStatus !== 'rejected'
  720. );
  721. if (nonRejectedLots.length === 0) {
  722. setAllLotsCompleted(false);
  723. return false;
  724. }
  725. // Check if all non-rejected lots are completed
  726. const allCompleted = nonRejectedLots.every(lot =>
  727. lot.stockOutLineStatus === 'completed'
  728. );
  729. setAllLotsCompleted(allCompleted);
  730. return allCompleted;
  731. }, []);
  732. // 在 fetchAllCombinedLotData 函数中(约 446-684 行)
  733. const fetchAllCombinedLotData = useCallback(async (userId?: number, pickOrderIdOverride?: number) => {
  734. setCombinedDataLoading(true);
  735. try {
  736. const userIdToUse = userId || currentUserId;
  737. console.log(" fetchAllCombinedLotData called with userId:", userIdToUse);
  738. if (!userIdToUse) {
  739. console.warn("⚠️ No userId available, skipping API call");
  740. setCombinedLotData([]);
  741. setOriginalCombinedData([]);
  742. setAllLotsCompleted(false);
  743. setIssuePickedQtyBySolId({});
  744. return;
  745. }
  746. // 获取新结构的层级数据
  747. const hierarchicalData = await fetchAllPickOrderLotsHierarchical(userIdToUse);
  748. console.log(" Hierarchical data (new structure):", hierarchicalData);
  749. // 检查数据结构
  750. if (!hierarchicalData.fgInfo || !hierarchicalData.pickOrders || hierarchicalData.pickOrders.length === 0) {
  751. console.warn("⚠️ No FG info or pick orders found");
  752. setCombinedLotData([]);
  753. setOriginalCombinedData([]);
  754. setAllLotsCompleted(false);
  755. setIssuePickedQtyBySolId({});
  756. return;
  757. }
  758. // 使用合并后的 pick order 对象(现在只有一个对象,包含所有数据)
  759. const mergedPickOrder = hierarchicalData.pickOrders[0];
  760. // 设置 FG info 到 fgPickOrders(用于显示 FG 信息卡片)
  761. // 修改第 478-509 行的 fgOrder 构建逻辑:
  762. const fgOrder: FGPickOrderResponse = {
  763. doPickOrderId: hierarchicalData.fgInfo.doPickOrderId,
  764. ticketNo: hierarchicalData.fgInfo.ticketNo,
  765. storeId: hierarchicalData.fgInfo.storeId,
  766. shopCode: hierarchicalData.fgInfo.shopCode,
  767. shopName: hierarchicalData.fgInfo.shopName,
  768. truckLanceCode: hierarchicalData.fgInfo.truckLanceCode,
  769. DepartureTime: hierarchicalData.fgInfo.departureTime,
  770. shopAddress: "",
  771. pickOrderCode: mergedPickOrder.pickOrderCodes?.[0] || "",
  772. // 兼容字段(注意 consoCodes 是数组)
  773. pickOrderId: mergedPickOrder.pickOrderIds?.[0] || 0,
  774. pickOrderConsoCode: Array.isArray(mergedPickOrder.consoCodes)
  775. ? mergedPickOrder.consoCodes[0] || ""
  776. : "",
  777. pickOrderTargetDate: mergedPickOrder.targetDate || "",
  778. pickOrderStatus: mergedPickOrder.status || "",
  779. deliveryOrderId: mergedPickOrder.doOrderIds?.[0] || 0,
  780. deliveryNo: mergedPickOrder.deliveryOrderCodes?.[0] || "",
  781. deliveryDate: "",
  782. shopId: 0,
  783. shopPoNo: "",
  784. numberOfCartons: mergedPickOrder.pickOrderLines?.length || 0,
  785. qrCodeData: hierarchicalData.fgInfo.doPickOrderId,
  786. // 多个 pick orders 信息:全部保留为数组
  787. numberOfPickOrders: mergedPickOrder.pickOrderIds?.length || 0,
  788. pickOrderIds: mergedPickOrder.pickOrderIds || [],
  789. pickOrderCodes: Array.isArray(mergedPickOrder.pickOrderCodes)
  790. ? mergedPickOrder.pickOrderCodes
  791. : [],
  792. deliveryOrderIds: mergedPickOrder.doOrderIds || [],
  793. deliveryNos: Array.isArray(mergedPickOrder.deliveryOrderCodes)
  794. ? mergedPickOrder.deliveryOrderCodes
  795. : [],
  796. lineCountsPerPickOrder: Array.isArray(mergedPickOrder.lineCountsPerPickOrder)
  797. ? mergedPickOrder.lineCountsPerPickOrder
  798. : [],
  799. };
  800. setFgPickOrders([fgOrder]);
  801. console.log(" DEBUG fgOrder.lineCountsPerPickOrder:", fgOrder.lineCountsPerPickOrder);
  802. console.log(" DEBUG fgOrder.pickOrderCodes:", fgOrder.pickOrderCodes);
  803. console.log(" DEBUG fgOrder.deliveryNos:", fgOrder.deliveryNos);
  804. // 直接使用合并后的 pickOrderLines
  805. console.log("🎯 Displaying merged pick order lines");
  806. // 将层级数据转换为平铺格式(用于表格显示)
  807. const flatLotData: any[] = [];
  808. // 2/F 與後端 store_id 一致時需按 itemOrder;避免 API 未走 2F 分支時畫面仍亂序
  809. const doFloorKey = String(hierarchicalData.fgInfo.storeId ?? '')
  810. .trim()
  811. .toUpperCase()
  812. .replace(/\//g, '')
  813. .replace(/\s/g, '');
  814. const pickOrderLinesForDisplay =
  815. doFloorKey === '2F'
  816. ? [...(mergedPickOrder.pickOrderLines || [])].sort((a: any, b: any) => {
  817. const ao = a.itemOrder != null ? Number(a.itemOrder) : 999999;
  818. const bo = b.itemOrder != null ? Number(b.itemOrder) : 999999;
  819. if (ao !== bo) return ao - bo;
  820. return (Number(a.id) || 0) - (Number(b.id) || 0);
  821. })
  822. : mergedPickOrder.pickOrderLines || [];
  823. pickOrderLinesForDisplay.forEach((line: any) => {
  824. // 用来记录这一行已经通过 lots 出现过的 lotId
  825. const lotIdSet = new Set<number>();
  826. // ✅ lots:按 lotId 去重并合并 requiredQty
  827. if (line.lots && line.lots.length > 0) {
  828. const lotMap = new Map<number, any>();
  829. line.lots.forEach((lot: any) => {
  830. const lotId = lot.id;
  831. if (lotMap.has(lotId)) {
  832. const existingLot = lotMap.get(lotId);
  833. existingLot.requiredQty =
  834. (existingLot.requiredQty || 0) + (lot.requiredQty || 0);
  835. } else {
  836. lotMap.set(lotId, { ...lot });
  837. }
  838. });
  839. lotMap.forEach((lot: any) => {
  840. if (lot.id != null) {
  841. lotIdSet.add(lot.id);
  842. }
  843. flatLotData.push({
  844. pickOrderConsoCode: Array.isArray(mergedPickOrder.consoCodes)
  845. ? mergedPickOrder.consoCodes[0] || ""
  846. : "",
  847. pickOrderTargetDate: mergedPickOrder.targetDate,
  848. pickOrderStatus: mergedPickOrder.status,
  849. pickOrderId: line.pickOrderId || mergedPickOrder.pickOrderIds?.[0] || 0,
  850. pickOrderCode: mergedPickOrder.pickOrderCodes?.[0] || "",
  851. pickOrderLineId: line.id,
  852. pickOrderLineRequiredQty: line.requiredQty,
  853. pickOrderLineStatus: line.status,
  854. itemId: line.item.id,
  855. itemCode: line.item.code,
  856. itemName: line.item.name,
  857. uomDesc: line.item.uomDesc,
  858. uomShortDesc: line.item.uomShortDesc,
  859. lotId: lot.id,
  860. lotNo: lot.lotNo,
  861. expiryDate: lot.expiryDate,
  862. location: lot.location,
  863. stockUnit: lot.stockUnit,
  864. availableQty: lot.availableQty,
  865. requiredQty: lot.requiredQty,
  866. actualPickQty: lot.actualPickQty,
  867. inQty: lot.inQty,
  868. outQty: lot.outQty,
  869. holdQty: lot.holdQty,
  870. lotStatus: lot.lotStatus,
  871. lotAvailability: lot.lotAvailability,
  872. processingStatus: lot.processingStatus,
  873. suggestedPickLotId: lot.suggestedPickLotId,
  874. stockOutLineId: lot.stockOutLineId,
  875. stockOutLineStatus: lot.stockOutLineStatus,
  876. stockOutLineQty: lot.stockOutLineQty,
  877. stockInLineId: lot.stockInLineId,
  878. routerId: lot.router?.id,
  879. routerIndex: lot.router?.index,
  880. routerRoute: lot.router?.route,
  881. routerArea: lot.router?.area,
  882. noLot: false,
  883. });
  884. });
  885. }
  886. // ✅ stockouts:只保留“真正无批次 / 未在 lots 出现过”的行
  887. if (line.stockouts && line.stockouts.length > 0) {
  888. line.stockouts.forEach((stockout: any) => {
  889. const hasLot = stockout.lotId != null;
  890. const lotAlreadyInLots =
  891. hasLot && lotIdSet.has(stockout.lotId as number);
  892. // 有批次 & 已经通过 lots 渲染过 → 跳过,避免一条变两行
  893. if (!stockout.noLot && lotAlreadyInLots) {
  894. return;
  895. }
  896. // 只渲染:
  897. // - noLot === true 的 Null stock 行
  898. // - 或者 lotId 在 lots 中不存在的特殊情况
  899. flatLotData.push({
  900. pickOrderConsoCode: Array.isArray(mergedPickOrder.consoCodes)
  901. ? mergedPickOrder.consoCodes[0] || ""
  902. : "",
  903. pickOrderTargetDate: mergedPickOrder.targetDate,
  904. pickOrderStatus: mergedPickOrder.status,
  905. pickOrderId: line.pickOrderId || mergedPickOrder.pickOrderIds?.[0] || 0,
  906. pickOrderCode: mergedPickOrder.pickOrderCodes?.[0] || "",
  907. pickOrderLineId: line.id,
  908. pickOrderLineRequiredQty: line.requiredQty,
  909. pickOrderLineStatus: line.status,
  910. itemId: line.item.id,
  911. itemCode: line.item.code,
  912. itemName: line.item.name,
  913. uomDesc: line.item.uomDesc,
  914. uomShortDesc: line.item.uomShortDesc,
  915. lotId: stockout.lotId || null,
  916. lotNo: stockout.lotNo || null,
  917. expiryDate: null,
  918. location: stockout.location || null,
  919. stockUnit: line.item.uomDesc,
  920. availableQty: stockout.availableQty || 0,
  921. requiredQty: line.requiredQty,
  922. actualPickQty: stockout.qty || 0,
  923. inQty: 0,
  924. outQty: 0,
  925. holdQty: 0,
  926. lotStatus: stockout.noLot ? "unavailable" : "available",
  927. lotAvailability: stockout.noLot ? "insufficient_stock" : "available",
  928. processingStatus: stockout.status || "pending",
  929. suggestedPickLotId: null,
  930. stockOutLineId: stockout.id || null,
  931. stockOutLineStatus: stockout.status || null,
  932. stockOutLineQty: stockout.qty || 0,
  933. routerId: null,
  934. routerIndex: stockout.noLot ? 999999 : null,
  935. routerRoute: null,
  936. routerArea: null,
  937. noLot: !!stockout.noLot,
  938. });
  939. });
  940. }
  941. });
  942. console.log(" Transformed flat lot data:", flatLotData);
  943. console.log(" Total items (including null stock):", flatLotData.length);
  944. setCombinedLotData(flatLotData);
  945. setOriginalCombinedData(flatLotData);
  946. const doPid = hierarchicalData.fgInfo?.doPickOrderId;
  947. if (doPid) {
  948. setIssuePickedQtyBySolId(loadIssuePickedMap(doPid));
  949. }
  950. checkAllLotsCompleted(flatLotData);
  951. } catch (error) {
  952. console.error(" Error fetching combined lot data:", error);
  953. setCombinedLotData([]);
  954. setOriginalCombinedData([]);
  955. setAllLotsCompleted(false);
  956. setIssuePickedQtyBySolId({});
  957. } finally {
  958. setCombinedDataLoading(false);
  959. }
  960. }, [currentUserId, checkAllLotsCompleted]); // 移除 selectedPickOrderId 依赖
  961. // Add effect to check completion when lot data changes
  962. const handleManualLotConfirmation = useCallback(async (currentLotNo: string, newLotNo: string) => {
  963. console.log(` Manual lot confirmation: Current=${currentLotNo}, New=${newLotNo}`);
  964. // 使用第一个输入框的 lot number 查找当前数据
  965. const currentLot = combinedLotData.find(lot =>
  966. lot.lotNo && lot.lotNo === currentLotNo
  967. );
  968. if (!currentLot) {
  969. console.error(`❌ Current lot not found: ${currentLotNo}`);
  970. alert(t("Current lot number not found. Please verify and try again."));
  971. return;
  972. }
  973. if (!currentLot.stockOutLineId) {
  974. console.error("❌ No stockOutLineId found for current lot");
  975. alert(t("No stock out line found for current lot. Please contact administrator."));
  976. return;
  977. }
  978. setIsConfirmingLot(true);
  979. try {
  980. // 调用 updateStockOutLineStatusByQRCodeAndLotNo API
  981. // 第一个 lot 用于获取 pickOrderLineId, stockOutLineId, itemId
  982. // 第二个 lot 作为 inventoryLotNo
  983. const res = await updateStockOutLineStatusByQRCodeAndLotNo({
  984. pickOrderLineId: currentLot.pickOrderLineId,
  985. inventoryLotNo: newLotNo, // 第二个输入框的值
  986. stockOutLineId: currentLot.stockOutLineId,
  987. itemId: currentLot.itemId,
  988. status: "checked",
  989. });
  990. console.log("📥 updateStockOutLineStatusByQRCodeAndLotNo result:", res);
  991. if (res.code === "checked" || res.code === "SUCCESS") {
  992. // ✅ 更新本地状态
  993. const entity = res.entity as any;
  994. setCombinedLotData(prev => prev.map(lot => {
  995. if (lot.stockOutLineId === currentLot.stockOutLineId &&
  996. lot.pickOrderLineId === currentLot.pickOrderLineId) {
  997. return {
  998. ...lot,
  999. stockOutLineStatus: 'checked',
  1000. stockOutLineQty: entity?.qty ? Number(entity.qty) : lot.stockOutLineQty,
  1001. };
  1002. }
  1003. return lot;
  1004. }));
  1005. setOriginalCombinedData(prev => prev.map(lot => {
  1006. if (lot.stockOutLineId === currentLot.stockOutLineId &&
  1007. lot.pickOrderLineId === currentLot.pickOrderLineId) {
  1008. return {
  1009. ...lot,
  1010. stockOutLineStatus: 'checked',
  1011. stockOutLineQty: entity?.qty ? Number(entity.qty) : lot.stockOutLineQty,
  1012. };
  1013. }
  1014. return lot;
  1015. }));
  1016. console.log("✅ Lot substitution completed successfully");
  1017. setQrScanSuccess(true);
  1018. setQrScanError(false);
  1019. // 关闭手动输入模态框
  1020. setManualLotConfirmationOpen(false);
  1021. // 刷新数据
  1022. await fetchAllCombinedLotData();
  1023. } else if (res.code === "LOT_NUMBER_MISMATCH") {
  1024. console.warn("⚠️ Backend reported LOT_NUMBER_MISMATCH:", res.message);
  1025. // ✅ 打开 lot confirmation modal 而不是显示 alert
  1026. // 从响应消息中提取 expected lot number(如果可能)
  1027. // 或者使用 currentLotNo 作为 expected lot
  1028. const expectedLotNo = currentLotNo; // 当前 lot 是期望的
  1029. // 查找新 lot 的信息(如果存在于 combinedLotData 中)
  1030. const newLot = combinedLotData.find(lot =>
  1031. lot.lotNo && lot.lotNo === newLotNo
  1032. );
  1033. // 设置 expected lot data
  1034. setExpectedLotData({
  1035. lotNo: expectedLotNo,
  1036. itemCode: currentLot.itemCode || '',
  1037. itemName: currentLot.itemName || ''
  1038. });
  1039. // 设置 scanned lot data
  1040. setScannedLotData({
  1041. lotNo: newLotNo,
  1042. itemCode: newLot?.itemCode || currentLot.itemCode || '',
  1043. itemName: newLot?.itemName || currentLot.itemName || '',
  1044. inventoryLotLineId: newLot?.lotId || null,
  1045. stockInLineId: null // 手动输入时可能没有 stockInLineId
  1046. });
  1047. // 设置 selectedLotForQr 为当前 lot
  1048. setSelectedLotForQr(currentLot);
  1049. // 关闭手动输入模态框
  1050. setManualLotConfirmationOpen(false);
  1051. // 打开 lot confirmation modal
  1052. setLotConfirmationOpen(true);
  1053. setQrScanError(false); // 不显示错误,因为会打开确认模态框
  1054. setQrScanSuccess(false);
  1055. } else if (res.code === "ITEM_MISMATCH") {
  1056. console.warn("⚠️ Backend reported ITEM_MISMATCH:", res.message);
  1057. alert(t("Item mismatch: {message}", { message: res.message || "" }));
  1058. setQrScanError(true);
  1059. setQrScanSuccess(false);
  1060. // 关闭手动输入模态框
  1061. setManualLotConfirmationOpen(false);
  1062. } else {
  1063. console.warn("⚠️ Unexpected response code:", res.code);
  1064. alert(t("Failed to update lot status. Response: {code}", { code: res.code }));
  1065. setQrScanError(true);
  1066. setQrScanSuccess(false);
  1067. // 关闭手动输入模态框
  1068. setManualLotConfirmationOpen(false);
  1069. }
  1070. } catch (error) {
  1071. console.error("❌ Error in manual lot confirmation:", error);
  1072. alert(t("Failed to confirm lot substitution. Please try again."));
  1073. setQrScanError(true);
  1074. setQrScanSuccess(false);
  1075. // 关闭手动输入模态框
  1076. setManualLotConfirmationOpen(false);
  1077. } finally {
  1078. setIsConfirmingLot(false);
  1079. }
  1080. }, [combinedLotData, fetchAllCombinedLotData, t]);
  1081. useEffect(() => {
  1082. if (combinedLotData.length > 0) {
  1083. checkAllLotsCompleted(combinedLotData);
  1084. }
  1085. }, [combinedLotData, checkAllLotsCompleted]);
  1086. // Add function to expose completion status to parent
  1087. const getCompletionStatus = useCallback(() => {
  1088. return allLotsCompleted;
  1089. }, [allLotsCompleted]);
  1090. // Expose completion status to parent component
  1091. useEffect(() => {
  1092. // Dispatch custom event with completion status
  1093. const event = new CustomEvent('pickOrderCompletionStatus', {
  1094. detail: {
  1095. allLotsCompleted,
  1096. tabIndex: 1 // 明确指定这是来自标签页 1 的事件
  1097. }
  1098. });
  1099. window.dispatchEvent(event);
  1100. }, [allLotsCompleted]);
  1101. const clearLotConfirmationState = useCallback((clearProcessedRefs: boolean = false) => {
  1102. setLotConfirmationOpen(false);
  1103. setExpectedLotData(null);
  1104. setScannedLotData(null);
  1105. setSelectedLotForQr(null);
  1106. if (clearProcessedRefs) {
  1107. setTimeout(() => {
  1108. lastProcessedQrRef.current = '';
  1109. processedQrCodesRef.current.clear();
  1110. console.log(` [LOT CONFIRM MODAL] Cleared refs to allow reprocessing`);
  1111. }, 100);
  1112. }
  1113. }, []);
  1114. const parseQrPayload = useCallback((rawQr: string): { itemId: number; stockInLineId: number } | null => {
  1115. if (!rawQr) return null;
  1116. if ((rawQr.startsWith("{2fitest") || rawQr.startsWith("{2fittest")) && rawQr.endsWith("}")) {
  1117. let content = '';
  1118. if (rawQr.startsWith("{2fittest")) {
  1119. content = rawQr.substring(9, rawQr.length - 1);
  1120. } else {
  1121. content = rawQr.substring(8, rawQr.length - 1);
  1122. }
  1123. const parts = content.split(',');
  1124. if (parts.length === 2) {
  1125. const itemId = parseInt(parts[0].trim(), 10);
  1126. const stockInLineId = parseInt(parts[1].trim(), 10);
  1127. if (!isNaN(itemId) && !isNaN(stockInLineId)) {
  1128. return { itemId, stockInLineId };
  1129. }
  1130. }
  1131. return null;
  1132. }
  1133. try {
  1134. const parsed = JSON.parse(rawQr);
  1135. if (parsed?.itemId && parsed?.stockInLineId) {
  1136. return { itemId: parsed.itemId, stockInLineId: parsed.stockInLineId };
  1137. }
  1138. return null;
  1139. } catch {
  1140. return null;
  1141. }
  1142. }, []);
  1143. const handleLotConfirmation = useCallback(async () => {
  1144. if (!expectedLotData || !scannedLotData || !selectedLotForQr) return;
  1145. setIsConfirmingLot(true);
  1146. try {
  1147. const newLotNo = scannedLotData?.lotNo;
  1148. const newStockInLineId = scannedLotData?.stockInLineId;
  1149. await confirmLotSubstitution({
  1150. pickOrderLineId: selectedLotForQr.pickOrderLineId,
  1151. stockOutLineId: selectedLotForQr.stockOutLineId,
  1152. originalSuggestedPickLotId: selectedLotForQr.suggestedPickLotId,
  1153. newInventoryLotNo: "",
  1154. newStockInLineId: newStockInLineId
  1155. });
  1156. setQrScanError(false);
  1157. setQrScanSuccess(false);
  1158. setQrScanInput('');
  1159. // ✅ 修复:在确认后重置扫描状态,避免重复处理
  1160. resetScan();
  1161. // ✅ 修复:不要清空 processedQrCodes,而是保留当前 QR code 的标记
  1162. // 或者如果确实需要清空,应该在重置扫描后再清空
  1163. // setProcessedQrCodes(new Set());
  1164. // setLastProcessedQr('');
  1165. setPickExecutionFormOpen(false);
  1166. if(selectedLotForQr?.stockOutLineId){
  1167. const stockOutLineUpdate = await updateStockOutLineStatus({
  1168. id: selectedLotForQr.stockOutLineId,
  1169. status: 'checked',
  1170. qty: 0
  1171. });
  1172. }
  1173. // ✅ 修复:先关闭 modal 和清空状态,再刷新数据
  1174. clearLotConfirmationState(false);
  1175. // ✅ 修复:刷新数据前设置刷新标志,避免在刷新期间处理新的 QR code
  1176. setIsRefreshingData(true);
  1177. await fetchAllCombinedLotData();
  1178. setIsRefreshingData(false);
  1179. } catch (error) {
  1180. console.error("Error confirming lot substitution:", error);
  1181. } finally {
  1182. setIsConfirmingLot(false);
  1183. }
  1184. }, [expectedLotData, scannedLotData, selectedLotForQr, fetchAllCombinedLotData, resetScan, clearLotConfirmationState]);
  1185. const handleLotConfirmationByRescan = useCallback(async (rawQr: string): Promise<boolean> => {
  1186. if (!lotConfirmationOpen || !selectedLotForQr || !expectedLotData || !scannedLotData) {
  1187. return false;
  1188. }
  1189. const payload = parseQrPayload(rawQr);
  1190. const expectedStockInLineId = Number(selectedLotForQr.stockInLineId);
  1191. const mismatchedStockInLineId = Number(scannedLotData?.stockInLineId);
  1192. if (payload) {
  1193. const rescannedStockInLineId = Number(payload.stockInLineId);
  1194. // 再扫“差异 lot” => 直接执行切换
  1195. if (
  1196. Number.isFinite(mismatchedStockInLineId) &&
  1197. rescannedStockInLineId === mismatchedStockInLineId
  1198. ) {
  1199. await handleLotConfirmation();
  1200. return true;
  1201. }
  1202. // 再扫“原建议 lot” => 关闭弹窗并按原 lot 正常记一次扫描
  1203. if (
  1204. Number.isFinite(expectedStockInLineId) &&
  1205. rescannedStockInLineId === expectedStockInLineId
  1206. ) {
  1207. clearLotConfirmationState(false);
  1208. if (processOutsideQrCodeRef.current) {
  1209. await processOutsideQrCodeRef.current(JSON.stringify(payload));
  1210. }
  1211. return true;
  1212. }
  1213. } else {
  1214. // 兼容纯 lotNo 文本扫码
  1215. const scannedText = rawQr?.trim();
  1216. const expectedLotNo = expectedLotData?.lotNo?.trim();
  1217. const mismatchedLotNo = scannedLotData?.lotNo?.trim();
  1218. if (mismatchedLotNo && scannedText === mismatchedLotNo) {
  1219. await handleLotConfirmation();
  1220. return true;
  1221. }
  1222. if (expectedLotNo && scannedText === expectedLotNo) {
  1223. clearLotConfirmationState(false);
  1224. if (processOutsideQrCodeRef.current) {
  1225. await processOutsideQrCodeRef.current(JSON.stringify({
  1226. itemId: selectedLotForQr.itemId,
  1227. stockInLineId: selectedLotForQr.stockInLineId,
  1228. }));
  1229. }
  1230. return true;
  1231. }
  1232. }
  1233. return false;
  1234. }, [lotConfirmationOpen, selectedLotForQr, expectedLotData, scannedLotData, parseQrPayload, handleLotConfirmation, clearLotConfirmationState]);
  1235. const handleQrCodeSubmit = useCallback(async (lotNo: string) => {
  1236. console.log(` Processing QR Code for lot: ${lotNo}`);
  1237. // 检查 lotNo 是否为 null 或 undefined(包括字符串 "null")
  1238. if (!lotNo || lotNo === 'null' || lotNo.trim() === '') {
  1239. console.error(" Invalid lotNo: null, undefined, or empty");
  1240. return;
  1241. }
  1242. // Use current data without refreshing to avoid infinite loop
  1243. const currentLotData = combinedLotData;
  1244. console.log(` Available lots:`, currentLotData.map(lot => lot.lotNo));
  1245. // 修复:在比较前确保 lotNo 不为 null
  1246. const lotNoLower = lotNo.toLowerCase();
  1247. const matchingLots = currentLotData.filter(lot => {
  1248. if (!lot.lotNo) return false; // 跳过 null lotNo
  1249. return lot.lotNo === lotNo || lot.lotNo.toLowerCase() === lotNoLower;
  1250. });
  1251. if (matchingLots.length === 0) {
  1252. console.error(` Lot not found: ${lotNo}`);
  1253. setQrScanError(true);
  1254. setQrScanSuccess(false);
  1255. const availableLotNos = currentLotData.map(lot => lot.lotNo).join(', ');
  1256. console.log(` QR Code "${lotNo}" does not match any expected lots. Available lots: ${availableLotNos}`);
  1257. return;
  1258. }
  1259. const hasExpiredLot = matchingLots.some(
  1260. (lot: any) => String(lot.lotAvailability || '').toLowerCase() === 'expired'
  1261. );
  1262. if (hasExpiredLot) {
  1263. console.warn(`⚠️ [QR PROCESS] Scanned lot ${lotNo} is expired`);
  1264. setQrScanError(true);
  1265. setQrScanSuccess(false);
  1266. return;
  1267. }
  1268. console.log(` Found ${matchingLots.length} matching lots:`, matchingLots);
  1269. setQrScanError(false);
  1270. try {
  1271. let successCount = 0;
  1272. let errorCount = 0;
  1273. for (const matchingLot of matchingLots) {
  1274. console.log(`🔄 Processing pick order line ${matchingLot.pickOrderLineId} for lot ${lotNo}`);
  1275. if (matchingLot.stockOutLineId) {
  1276. const stockOutLineUpdate = await updateStockOutLineStatus({
  1277. id: matchingLot.stockOutLineId,
  1278. status: 'checked',
  1279. qty: 0
  1280. });
  1281. console.log(`Update stock out line result for line ${matchingLot.pickOrderLineId}:`, stockOutLineUpdate);
  1282. // Treat multiple backend shapes as success (type-safe via any)
  1283. const r: any = stockOutLineUpdate as any;
  1284. const updateOk =
  1285. r?.code === 'SUCCESS' ||
  1286. typeof r?.id === 'number' ||
  1287. r?.type === 'checked' ||
  1288. r?.status === 'checked' ||
  1289. typeof r?.entity?.id === 'number' ||
  1290. r?.entity?.status === 'checked';
  1291. if (updateOk) {
  1292. successCount++;
  1293. } else {
  1294. errorCount++;
  1295. }
  1296. } else {
  1297. const createStockOutLineData = {
  1298. consoCode: matchingLot.pickOrderConsoCode,
  1299. pickOrderLineId: matchingLot.pickOrderLineId,
  1300. inventoryLotLineId: matchingLot.lotId,
  1301. qty: 0
  1302. };
  1303. const createResult = await createStockOutLine(createStockOutLineData);
  1304. console.log(`Create stock out line result for line ${matchingLot.pickOrderLineId}:`, createResult);
  1305. if (createResult && createResult.code === "SUCCESS") {
  1306. // Immediately set status to checked for new line
  1307. let newSolId: number | undefined;
  1308. const anyRes: any = createResult as any;
  1309. if (typeof anyRes?.id === 'number') {
  1310. newSolId = anyRes.id;
  1311. } else if (anyRes?.entity) {
  1312. newSolId = Array.isArray(anyRes.entity) ? anyRes.entity[0]?.id : anyRes.entity?.id;
  1313. }
  1314. if (newSolId) {
  1315. const setChecked = await updateStockOutLineStatus({
  1316. id: newSolId,
  1317. status: 'checked',
  1318. qty: 0
  1319. });
  1320. if (setChecked && setChecked.code === "SUCCESS") {
  1321. successCount++;
  1322. } else {
  1323. errorCount++;
  1324. }
  1325. } else {
  1326. console.warn("Created stock out line but no ID returned; cannot set to checked");
  1327. errorCount++;
  1328. }
  1329. } else {
  1330. errorCount++;
  1331. }
  1332. }
  1333. }
  1334. // FIXED: Set refresh flag before refreshing data
  1335. setIsRefreshingData(true);
  1336. console.log("🔄 Refreshing data after QR code processing...");
  1337. await fetchAllCombinedLotData();
  1338. if (successCount > 0) {
  1339. console.log(` QR Code processing completed: ${successCount} updated/created`);
  1340. setQrScanSuccess(true);
  1341. setQrScanError(false);
  1342. setQrScanInput(''); // Clear input after successful processing
  1343. //setIsManualScanning(false);
  1344. // stopScan();
  1345. // resetScan();
  1346. // Clear success state after a delay
  1347. //setTimeout(() => {
  1348. //setQrScanSuccess(false);
  1349. //}, 2000);
  1350. } else {
  1351. console.error(` QR Code processing failed: ${errorCount} errors`);
  1352. setQrScanError(true);
  1353. setQrScanSuccess(false);
  1354. // Clear error state after a delay
  1355. // setTimeout(() => {
  1356. // setQrScanError(false);
  1357. //}, 3000);
  1358. }
  1359. } catch (error) {
  1360. console.error(" Error processing QR code:", error);
  1361. setQrScanError(true);
  1362. setQrScanSuccess(false);
  1363. // Clear error state after a delay
  1364. setTimeout(() => {
  1365. setQrScanError(false);
  1366. }, 3000);
  1367. } finally {
  1368. // Clear refresh flag after a short delay
  1369. setTimeout(() => {
  1370. setIsRefreshingData(false);
  1371. }, 1000);
  1372. }
  1373. }, [combinedLotData]);
  1374. const handleFastQrScan = useCallback(async (lotNo: string) => {
  1375. const startTime = performance.now();
  1376. console.log(` [FAST SCAN START] Lot: ${lotNo}`);
  1377. console.log(` Start time: ${new Date().toISOString()}`);
  1378. // 从 combinedLotData 中找到对应的 lot
  1379. const findStartTime = performance.now();
  1380. const matchingLot = combinedLotData.find(lot =>
  1381. lot.lotNo && lot.lotNo === lotNo
  1382. );
  1383. const findTime = performance.now() - findStartTime;
  1384. console.log(` Find lot time: ${findTime.toFixed(2)}ms`);
  1385. if (!matchingLot || !matchingLot.stockOutLineId) {
  1386. const totalTime = performance.now() - startTime;
  1387. console.warn(`⚠️ Fast scan: Lot ${lotNo} not found or no stockOutLineId`);
  1388. console.log(` Total time: ${totalTime.toFixed(2)}ms`);
  1389. return;
  1390. }
  1391. try {
  1392. // ✅ 使用快速 API
  1393. const apiStartTime = performance.now();
  1394. const res = await updateStockOutLineStatusByQRCodeAndLotNo({
  1395. pickOrderLineId: matchingLot.pickOrderLineId,
  1396. inventoryLotNo: lotNo,
  1397. stockOutLineId: matchingLot.stockOutLineId,
  1398. itemId: matchingLot.itemId,
  1399. status: "checked",
  1400. });
  1401. const apiTime = performance.now() - apiStartTime;
  1402. console.log(` API call time: ${apiTime.toFixed(2)}ms`);
  1403. if (res.code === "checked" || res.code === "SUCCESS") {
  1404. // ✅ 只更新本地状态,不调用 fetchAllCombinedLotData
  1405. const updateStartTime = performance.now();
  1406. const entity = res.entity as any;
  1407. setCombinedLotData(prev => prev.map(lot => {
  1408. if (lot.stockOutLineId === matchingLot.stockOutLineId &&
  1409. lot.pickOrderLineId === matchingLot.pickOrderLineId) {
  1410. return {
  1411. ...lot,
  1412. stockOutLineStatus: 'checked',
  1413. stockOutLineQty: entity?.qty ? Number(entity.qty) : lot.stockOutLineQty,
  1414. };
  1415. }
  1416. return lot;
  1417. }));
  1418. setOriginalCombinedData(prev => prev.map(lot => {
  1419. if (lot.stockOutLineId === matchingLot.stockOutLineId &&
  1420. lot.pickOrderLineId === matchingLot.pickOrderLineId) {
  1421. return {
  1422. ...lot,
  1423. stockOutLineStatus: 'checked',
  1424. stockOutLineQty: entity?.qty ? Number(entity.qty) : lot.stockOutLineQty,
  1425. };
  1426. }
  1427. return lot;
  1428. }));
  1429. const updateTime = performance.now() - updateStartTime;
  1430. console.log(` State update time: ${updateTime.toFixed(2)}ms`);
  1431. const totalTime = performance.now() - startTime;
  1432. console.log(`✅ [FAST SCAN END] Lot: ${lotNo}`);
  1433. console.log(` Total time: ${totalTime.toFixed(2)}ms (${(totalTime / 1000).toFixed(3)}s)`);
  1434. console.log(` End time: ${new Date().toISOString()}`);
  1435. } else {
  1436. const totalTime = performance.now() - startTime;
  1437. console.warn(`⚠️ Fast scan failed for ${lotNo}:`, res.code);
  1438. console.log(` Total time: ${totalTime.toFixed(2)}ms`);
  1439. }
  1440. } catch (error) {
  1441. const totalTime = performance.now() - startTime;
  1442. console.error(` Fast scan error for ${lotNo}:`, error);
  1443. console.log(` Total time: ${totalTime.toFixed(2)}ms`);
  1444. }
  1445. }, [combinedLotData, updateStockOutLineStatusByQRCodeAndLotNo]);
  1446. // Enhanced lotDataIndexes with cached active lots for better performance
  1447. const lotDataIndexes = useMemo(() => {
  1448. const indexStartTime = performance.now();
  1449. console.log(` [PERF] lotDataIndexes calculation START, data length: ${combinedLotData.length}`);
  1450. const byItemId = new Map<number, any[]>();
  1451. const byItemCode = new Map<string, any[]>();
  1452. const byLotId = new Map<number, any>();
  1453. const byLotNo = new Map<string, any[]>();
  1454. const byStockInLineId = new Map<number, any[]>();
  1455. // Cache active lots separately to avoid filtering on every scan
  1456. const activeLotsByItemId = new Map<number, any[]>();
  1457. const rejectedStatuses = new Set(['rejected']);
  1458. // ✅ Use for loop instead of forEach for better performance on tablets
  1459. for (let i = 0; i < combinedLotData.length; i++) {
  1460. const lot = combinedLotData[i];
  1461. const isActive = !rejectedStatuses.has(lot.lotAvailability) &&
  1462. !rejectedStatuses.has(lot.stockOutLineStatus) &&
  1463. !rejectedStatuses.has(lot.processingStatus);
  1464. if (lot.itemId) {
  1465. if (!byItemId.has(lot.itemId)) {
  1466. byItemId.set(lot.itemId, []);
  1467. activeLotsByItemId.set(lot.itemId, []);
  1468. }
  1469. byItemId.get(lot.itemId)!.push(lot);
  1470. if (isActive) {
  1471. activeLotsByItemId.get(lot.itemId)!.push(lot);
  1472. }
  1473. }
  1474. if (lot.itemCode) {
  1475. if (!byItemCode.has(lot.itemCode)) {
  1476. byItemCode.set(lot.itemCode, []);
  1477. }
  1478. byItemCode.get(lot.itemCode)!.push(lot);
  1479. }
  1480. if (lot.lotId) {
  1481. byLotId.set(lot.lotId, lot);
  1482. }
  1483. if (lot.lotNo) {
  1484. if (!byLotNo.has(lot.lotNo)) {
  1485. byLotNo.set(lot.lotNo, []);
  1486. }
  1487. byLotNo.get(lot.lotNo)!.push(lot);
  1488. }
  1489. if (lot.stockInLineId) {
  1490. if (!byStockInLineId.has(lot.stockInLineId)) {
  1491. byStockInLineId.set(lot.stockInLineId, []);
  1492. }
  1493. byStockInLineId.get(lot.stockInLineId)!.push(lot);
  1494. }
  1495. }
  1496. const indexTime = performance.now() - indexStartTime;
  1497. if (indexTime > 10) {
  1498. console.log(` [PERF] lotDataIndexes calculation END: ${indexTime.toFixed(2)}ms (${(indexTime / 1000).toFixed(3)}s)`);
  1499. }
  1500. return { byItemId, byItemCode, byLotId, byLotNo, byStockInLineId, activeLotsByItemId };
  1501. }, [combinedLotData.length, combinedLotData]);
  1502. // Store resetScan in ref for immediate access (update on every render)
  1503. resetScanRef.current = resetScan;
  1504. const processOutsideQrCode = useCallback(async (latestQr: string, qrScanCountAtInvoke?: number) => {
  1505. const totalStartTime = performance.now();
  1506. console.log(` [PROCESS OUTSIDE QR START] QR: ${latestQr.substring(0, 50)}...`);
  1507. console.log(` Start time: ${new Date().toISOString()}`);
  1508. // ✅ Measure index access time
  1509. const indexAccessStart = performance.now();
  1510. const indexes = lotDataIndexes; // Access the memoized indexes
  1511. const indexAccessTime = performance.now() - indexAccessStart;
  1512. console.log(` [PERF] Index access time: ${indexAccessTime.toFixed(2)}ms`);
  1513. // 1) Parse JSON safely (parse once, reuse)
  1514. const parseStartTime = performance.now();
  1515. let qrData: any = null;
  1516. let parseTime = 0;
  1517. try {
  1518. qrData = JSON.parse(latestQr);
  1519. parseTime = performance.now() - parseStartTime;
  1520. console.log(` [PERF] JSON parse time: ${parseTime.toFixed(2)}ms`);
  1521. } catch {
  1522. console.log("QR content is not JSON; skipping lotNo direct submit to avoid false matches.");
  1523. startTransition(() => {
  1524. setQrScanError(true);
  1525. setQrScanSuccess(false);
  1526. });
  1527. return;
  1528. }
  1529. try {
  1530. const validationStartTime = performance.now();
  1531. if (!(qrData?.stockInLineId && qrData?.itemId)) {
  1532. console.log("QR JSON missing required fields (itemId, stockInLineId).");
  1533. startTransition(() => {
  1534. setQrScanError(true);
  1535. setQrScanSuccess(false);
  1536. });
  1537. return;
  1538. }
  1539. const validationTime = performance.now() - validationStartTime;
  1540. console.log(` [PERF] Validation time: ${validationTime.toFixed(2)}ms`);
  1541. const scannedItemId = qrData.itemId;
  1542. const scannedStockInLineId = qrData.stockInLineId;
  1543. // ✅ Check if this combination was already processed
  1544. const duplicateCheckStartTime = performance.now();
  1545. const itemProcessedSet = processedQrCombinations.get(scannedItemId);
  1546. if (itemProcessedSet?.has(scannedStockInLineId)) {
  1547. const duplicateCheckTime = performance.now() - duplicateCheckStartTime;
  1548. console.log(` [SKIP] Already processed combination: itemId=${scannedItemId}, stockInLineId=${scannedStockInLineId} (check time: ${duplicateCheckTime.toFixed(2)}ms)`);
  1549. return;
  1550. }
  1551. const duplicateCheckTime = performance.now() - duplicateCheckStartTime;
  1552. console.log(` [PERF] Duplicate check time: ${duplicateCheckTime.toFixed(2)}ms`);
  1553. // ✅ OPTIMIZATION: Use cached active lots directly (no filtering needed)
  1554. const lookupStartTime = performance.now();
  1555. const activeSuggestedLots = indexes.activeLotsByItemId.get(scannedItemId) || [];
  1556. // ✅ Also get all lots for this item (not just active ones) to allow lot switching even when all lots are rejected
  1557. const allLotsForItem = indexes.byItemId.get(scannedItemId) || [];
  1558. const lookupTime = performance.now() - lookupStartTime;
  1559. console.log(` [PERF] Index lookup time: ${lookupTime.toFixed(2)}ms, found ${activeSuggestedLots.length} active lots, ${allLotsForItem.length} total lots`);
  1560. // ✅ Check if scanned lot is rejected BEFORE checking activeSuggestedLots
  1561. // This allows users to scan other lots even when all suggested lots are rejected
  1562. const scannedLot = allLotsForItem.find(
  1563. (lot: any) => lot.stockInLineId === scannedStockInLineId
  1564. );
  1565. if (scannedLot) {
  1566. const isRejected =
  1567. scannedLot.stockOutLineStatus?.toLowerCase() === 'rejected' ||
  1568. scannedLot.lotAvailability === 'rejected' ||
  1569. scannedLot.lotAvailability === 'status_unavailable';
  1570. if (isRejected) {
  1571. console.warn(`⚠️ [QR PROCESS] Scanned lot (stockInLineId: ${scannedStockInLineId}, lotNo: ${scannedLot.lotNo}) is rejected or unavailable`);
  1572. startTransition(() => {
  1573. setQrScanError(true);
  1574. setQrScanSuccess(false);
  1575. setQrScanErrorMsg(
  1576. `此批次(${scannedLot.lotNo || scannedStockInLineId})已被拒绝,无法使用。请扫描其他批次。`
  1577. );
  1578. });
  1579. // Mark as processed to prevent re-processing
  1580. setProcessedQrCombinations(prev => {
  1581. const newMap = new Map(prev);
  1582. if (!newMap.has(scannedItemId)) newMap.set(scannedItemId, new Set());
  1583. newMap.get(scannedItemId)!.add(scannedStockInLineId);
  1584. return newMap;
  1585. });
  1586. return;
  1587. }
  1588. const isExpired =
  1589. String(scannedLot.lotAvailability || '').toLowerCase() === 'expired';
  1590. if (isExpired) {
  1591. console.warn(`⚠️ [QR PROCESS] Scanned lot (stockInLineId: ${scannedStockInLineId}, lotNo: ${scannedLot.lotNo}) is expired`);
  1592. startTransition(() => {
  1593. setQrScanError(true);
  1594. setQrScanSuccess(false);
  1595. setQrScanErrorMsg(
  1596. `此批次(${scannedLot.lotNo || scannedStockInLineId})已过期,无法使用。请扫描其他批次。`
  1597. );
  1598. });
  1599. // Mark as processed to prevent re-processing the same expired QR repeatedly
  1600. setProcessedQrCombinations(prev => {
  1601. const newMap = new Map(prev);
  1602. if (!newMap.has(scannedItemId)) newMap.set(scannedItemId, new Set());
  1603. newMap.get(scannedItemId)!.add(scannedStockInLineId);
  1604. return newMap;
  1605. });
  1606. return;
  1607. }
  1608. }
  1609. // ✅ If no active suggested lots, but scanned lot is not rejected, allow lot switching
  1610. if (activeSuggestedLots.length === 0) {
  1611. // Check if there are any lots for this item (even if all are rejected)
  1612. if (allLotsForItem.length === 0) {
  1613. console.error("No lots found for this item");
  1614. startTransition(() => {
  1615. setQrScanError(true);
  1616. setQrScanSuccess(false);
  1617. setQrScanErrorMsg("当前订单中没有此物品的批次信息");
  1618. });
  1619. return;
  1620. }
  1621. // ✅ Allow lot switching: find a rejected lot as expected lot, or use first lot
  1622. // This allows users to switch to a new lot even when all suggested lots are rejected
  1623. console.log(`⚠️ [QR PROCESS] No active suggested lots, but allowing lot switching.`);
  1624. // Find a rejected lot as expected lot (the one that was rejected)
  1625. const rejectedLot = allLotsForItem.find((lot: any) =>
  1626. lot.stockOutLineStatus?.toLowerCase() === 'rejected' ||
  1627. lot.lotAvailability === 'rejected' ||
  1628. lot.lotAvailability === 'status_unavailable'
  1629. );
  1630. const expectedLot =
  1631. rejectedLot ||
  1632. pickExpectedLotForSubstitution(
  1633. allLotsForItem.filter(
  1634. (l: any) => l.lotNo != null && String(l.lotNo).trim() !== ""
  1635. )
  1636. ) ||
  1637. allLotsForItem[0];
  1638. // ✅ Always open confirmation modal when no active lots (user needs to confirm switching)
  1639. // handleLotMismatch will fetch lotNo from backend using stockInLineId if needed
  1640. console.log(`⚠️ [QR PROCESS] Opening confirmation modal for lot switch (no active lots)`);
  1641. setSelectedLotForQr(expectedLot);
  1642. handleLotMismatch(
  1643. {
  1644. lotNo: expectedLot.lotNo,
  1645. itemCode: expectedLot.itemCode,
  1646. itemName: expectedLot.itemName
  1647. },
  1648. {
  1649. lotNo: scannedLot?.lotNo || null, // Will be fetched by handleLotMismatch if null
  1650. itemCode: expectedLot.itemCode,
  1651. itemName: expectedLot.itemName,
  1652. inventoryLotLineId: scannedLot?.lotId || null,
  1653. stockInLineId: scannedStockInLineId // handleLotMismatch will use this to fetch lotNo
  1654. },
  1655. qrScanCountAtInvoke
  1656. );
  1657. return;
  1658. }
  1659. // ✅ OPTIMIZATION: Direct Map lookup for stockInLineId match (O(1))
  1660. const matchStartTime = performance.now();
  1661. let exactMatch: any = null;
  1662. const stockInLineLots = indexes.byStockInLineId.get(scannedStockInLineId) || [];
  1663. // Find exact match from stockInLineId index, then verify it's in active lots
  1664. for (let i = 0; i < stockInLineLots.length; i++) {
  1665. const lot = stockInLineLots[i];
  1666. if (lot.itemId === scannedItemId && activeSuggestedLots.includes(lot)) {
  1667. exactMatch = lot;
  1668. break;
  1669. }
  1670. }
  1671. const matchTime = performance.now() - matchStartTime;
  1672. console.log(` [PERF] Find exact match time: ${matchTime.toFixed(2)}ms, found: ${exactMatch ? 'yes' : 'no'}`);
  1673. // ✅ Check if scanned lot exists in allLotsForItem but not in activeSuggestedLots
  1674. // This handles the case where Lot A is rejected and user scans Lot B
  1675. // Also handle case where scanned lot is not in allLotsForItem (scannedLot is undefined)
  1676. if (!exactMatch) {
  1677. // Scanned lot is not in active suggested lots, open confirmation modal
  1678. const expectedLot =
  1679. pickExpectedLotForSubstitution(activeSuggestedLots) || allLotsForItem[0];
  1680. if (expectedLot) {
  1681. // Check if scanned lot is different from expected, or if scannedLot is undefined (not in allLotsForItem)
  1682. const shouldOpenModal = !scannedLot || (scannedLot.stockInLineId !== expectedLot.stockInLineId);
  1683. if (shouldOpenModal) {
  1684. console.log(`⚠️ [QR PROCESS] Opening confirmation modal (scanned lot ${scannedLot?.lotNo || 'not in data'} is not in active suggested lots)`);
  1685. setSelectedLotForQr(expectedLot);
  1686. handleLotMismatch(
  1687. {
  1688. lotNo: expectedLot.lotNo,
  1689. itemCode: expectedLot.itemCode,
  1690. itemName: expectedLot.itemName
  1691. },
  1692. {
  1693. lotNo: scannedLot?.lotNo || null, // Will be fetched by handleLotMismatch if null
  1694. itemCode: expectedLot.itemCode,
  1695. itemName: expectedLot.itemName,
  1696. inventoryLotLineId: scannedLot?.lotId || null,
  1697. stockInLineId: scannedStockInLineId // handleLotMismatch will use this to fetch lotNo
  1698. },
  1699. qrScanCountAtInvoke
  1700. );
  1701. return;
  1702. }
  1703. }
  1704. }
  1705. if (exactMatch) {
  1706. // ✅ Case 1: stockInLineId 匹配 - 直接处理,不需要确认
  1707. console.log(`✅ Exact stockInLineId match found for lot: ${exactMatch.lotNo}`);
  1708. if (!exactMatch.stockOutLineId) {
  1709. console.warn("No stockOutLineId on exactMatch, cannot update status by QR.");
  1710. startTransition(() => {
  1711. setQrScanError(true);
  1712. setQrScanSuccess(false);
  1713. });
  1714. return;
  1715. }
  1716. try {
  1717. const apiStartTime = performance.now();
  1718. console.log(` [API CALL START] Calling updateStockOutLineStatusByQRCodeAndLotNo`);
  1719. console.log(` [API CALL] API start time: ${new Date().toISOString()}`);
  1720. const res = await updateStockOutLineStatusByQRCodeAndLotNo({
  1721. pickOrderLineId: exactMatch.pickOrderLineId,
  1722. inventoryLotNo: exactMatch.lotNo,
  1723. stockOutLineId: exactMatch.stockOutLineId,
  1724. itemId: exactMatch.itemId,
  1725. status: "checked",
  1726. });
  1727. const apiTime = performance.now() - apiStartTime;
  1728. console.log(` [API CALL END] Total API time: ${apiTime.toFixed(2)}ms (${(apiTime / 1000).toFixed(3)}s)`);
  1729. console.log(` [API CALL] API end time: ${new Date().toISOString()}`);
  1730. if (res.code === "checked" || res.code === "SUCCESS") {
  1731. const entity = res.entity as any;
  1732. // ✅ Batch state updates using startTransition
  1733. const stateUpdateStartTime = performance.now();
  1734. startTransition(() => {
  1735. setQrScanError(false);
  1736. setQrScanSuccess(true);
  1737. setCombinedLotData(prev => prev.map(lot => {
  1738. if (lot.stockOutLineId === exactMatch.stockOutLineId &&
  1739. lot.pickOrderLineId === exactMatch.pickOrderLineId) {
  1740. return {
  1741. ...lot,
  1742. stockOutLineStatus: 'checked',
  1743. stockOutLineQty: entity?.qty ?? lot.stockOutLineQty,
  1744. };
  1745. }
  1746. return lot;
  1747. }));
  1748. setOriginalCombinedData(prev => prev.map(lot => {
  1749. if (lot.stockOutLineId === exactMatch.stockOutLineId &&
  1750. lot.pickOrderLineId === exactMatch.pickOrderLineId) {
  1751. return {
  1752. ...lot,
  1753. stockOutLineStatus: 'checked',
  1754. stockOutLineQty: entity?.qty ?? lot.stockOutLineQty,
  1755. };
  1756. }
  1757. return lot;
  1758. }));
  1759. });
  1760. const stateUpdateTime = performance.now() - stateUpdateStartTime;
  1761. console.log(` [PERF] State update time: ${stateUpdateTime.toFixed(2)}ms`);
  1762. // Mark this combination as processed
  1763. const markProcessedStartTime = performance.now();
  1764. setProcessedQrCombinations(prev => {
  1765. const newMap = new Map(prev);
  1766. if (!newMap.has(scannedItemId)) {
  1767. newMap.set(scannedItemId, new Set());
  1768. }
  1769. newMap.get(scannedItemId)!.add(scannedStockInLineId);
  1770. return newMap;
  1771. });
  1772. const markProcessedTime = performance.now() - markProcessedStartTime;
  1773. console.log(` [PERF] Mark processed time: ${markProcessedTime.toFixed(2)}ms`);
  1774. const totalTime = performance.now() - totalStartTime;
  1775. console.log(`✅ [PROCESS OUTSIDE QR END] Total time: ${totalTime.toFixed(2)}ms (${(totalTime / 1000).toFixed(3)}s)`);
  1776. console.log(` End time: ${new Date().toISOString()}`);
  1777. console.log(`📊 Breakdown: parse=${parseTime.toFixed(2)}ms, validation=${validationTime.toFixed(2)}ms, duplicateCheck=${duplicateCheckTime.toFixed(2)}ms, lookup=${lookupTime.toFixed(2)}ms, match=${matchTime.toFixed(2)}ms, api=${apiTime.toFixed(2)}ms, stateUpdate=${stateUpdateTime.toFixed(2)}ms, markProcessed=${markProcessedTime.toFixed(2)}ms`);
  1778. console.log("✅ Status updated locally, no full data refresh needed");
  1779. } else {
  1780. console.warn("Unexpected response code from backend:", res.code);
  1781. startTransition(() => {
  1782. setQrScanError(true);
  1783. setQrScanSuccess(false);
  1784. });
  1785. }
  1786. } catch (e) {
  1787. const totalTime = performance.now() - totalStartTime;
  1788. console.error(`❌ [PROCESS OUTSIDE QR ERROR] Total time: ${totalTime.toFixed(2)}ms`);
  1789. console.error("Error calling updateStockOutLineStatusByQRCodeAndLotNo:", e);
  1790. startTransition(() => {
  1791. setQrScanError(true);
  1792. setQrScanSuccess(false);
  1793. });
  1794. }
  1795. return; // ✅ 直接返回,不需要确认表单
  1796. }
  1797. // ✅ Case 2: itemId 匹配但 stockInLineId 不匹配 - 显示确认表单
  1798. // Check if we should allow reopening (different stockInLineId)
  1799. const mismatchCheckStartTime = performance.now();
  1800. const itemProcessedSet2 = processedQrCombinations.get(scannedItemId);
  1801. if (itemProcessedSet2?.has(scannedStockInLineId)) {
  1802. const mismatchCheckTime = performance.now() - mismatchCheckStartTime;
  1803. console.log(` [SKIP] Already processed this exact combination (check time: ${mismatchCheckTime.toFixed(2)}ms)`);
  1804. return;
  1805. }
  1806. const mismatchCheckTime = performance.now() - mismatchCheckStartTime;
  1807. console.log(` [PERF] Mismatch check time: ${mismatchCheckTime.toFixed(2)}ms`);
  1808. // 取应被替换的活跃行(同物料多行时优先有建议批次的行)
  1809. const expectedLotStartTime = performance.now();
  1810. const expectedLot = pickExpectedLotForSubstitution(activeSuggestedLots);
  1811. if (!expectedLot) {
  1812. console.error("Could not determine expected lot for confirmation");
  1813. startTransition(() => {
  1814. setQrScanError(true);
  1815. setQrScanSuccess(false);
  1816. });
  1817. return;
  1818. }
  1819. const expectedLotTime = performance.now() - expectedLotStartTime;
  1820. console.log(` [PERF] Get expected lot time: ${expectedLotTime.toFixed(2)}ms`);
  1821. // ✅ 立即打开确认模态框,不等待其他操作
  1822. console.log(`⚠️ Lot mismatch: Expected stockInLineId=${expectedLot.stockInLineId}, Scanned stockInLineId=${scannedStockInLineId}`);
  1823. // Set selected lot immediately (no transition delay)
  1824. const setSelectedLotStartTime = performance.now();
  1825. setSelectedLotForQr(expectedLot);
  1826. const setSelectedLotTime = performance.now() - setSelectedLotStartTime;
  1827. console.log(` [PERF] Set selected lot time: ${setSelectedLotTime.toFixed(2)}ms`);
  1828. // ✅ 获取扫描的 lot 信息(从 QR 数据中提取,或使用默认值)
  1829. // Call handleLotMismatch immediately - it will open the modal
  1830. const handleMismatchStartTime = performance.now();
  1831. handleLotMismatch(
  1832. {
  1833. lotNo: expectedLot.lotNo,
  1834. itemCode: expectedLot.itemCode,
  1835. itemName: expectedLot.itemName
  1836. },
  1837. {
  1838. lotNo: null, // 扫描的 lotNo 未知,需要从后端获取或显示为未知
  1839. itemCode: expectedLot.itemCode,
  1840. itemName: expectedLot.itemName,
  1841. inventoryLotLineId: null,
  1842. stockInLineId: scannedStockInLineId // ✅ 传递 stockInLineId
  1843. },
  1844. qrScanCountAtInvoke
  1845. );
  1846. const handleMismatchTime = performance.now() - handleMismatchStartTime;
  1847. console.log(` [PERF] Handle mismatch call time: ${handleMismatchTime.toFixed(2)}ms`);
  1848. const totalTime = performance.now() - totalStartTime;
  1849. console.log(`⚠️ [PROCESS OUTSIDE QR MISMATCH] Total time before modal: ${totalTime.toFixed(2)}ms (${(totalTime / 1000).toFixed(3)}s)`);
  1850. console.log(` End time: ${new Date().toISOString()}`);
  1851. console.log(`📊 Breakdown: parse=${parseTime.toFixed(2)}ms, validation=${validationTime.toFixed(2)}ms, duplicateCheck=${duplicateCheckTime.toFixed(2)}ms, lookup=${lookupTime.toFixed(2)}ms, match=${matchTime.toFixed(2)}ms, mismatchCheck=${mismatchCheckTime.toFixed(2)}ms, expectedLot=${expectedLotTime.toFixed(2)}ms, setSelectedLot=${setSelectedLotTime.toFixed(2)}ms, handleMismatch=${handleMismatchTime.toFixed(2)}ms`);
  1852. } catch (error) {
  1853. const totalTime = performance.now() - totalStartTime;
  1854. console.error(`❌ [PROCESS OUTSIDE QR ERROR] Total time: ${totalTime.toFixed(2)}ms`);
  1855. console.error("Error during QR code processing:", error);
  1856. startTransition(() => {
  1857. setQrScanError(true);
  1858. setQrScanSuccess(false);
  1859. });
  1860. return;
  1861. }
  1862. }, [lotDataIndexes, handleLotMismatch, processedQrCombinations, combinedLotData, fetchStockInLineInfoCached]);
  1863. // Store processOutsideQrCode in ref for immediate access (update on every render)
  1864. processOutsideQrCodeRef.current = processOutsideQrCode;
  1865. useEffect(() => {
  1866. // Skip if scanner is not active or no data available
  1867. if (!isManualScanning || qrValues.length === 0 || combinedLotData.length === 0 || isRefreshingData) {
  1868. return;
  1869. }
  1870. const qrValuesChangeStartTime = performance.now();
  1871. console.log(` [QR VALUES EFFECT] Triggered at: ${new Date().toISOString()}`);
  1872. console.log(` [QR VALUES EFFECT] qrValues.length: ${qrValues.length}`);
  1873. console.log(` [QR VALUES EFFECT] qrValues:`, qrValues);
  1874. const latestQr = qrValues[qrValues.length - 1];
  1875. console.log(` [QR VALUES EFFECT] Latest QR: ${latestQr}`);
  1876. console.log(` [QR VALUES EFFECT] Latest QR detected at: ${new Date().toISOString()}`);
  1877. // ✅ FIXED: Handle test shortcut {2fitestx,y} or {2fittestx,y} where x=itemId, y=stockInLineId
  1878. // Support both formats: {2fitest (2 t's) and {2fittest (3 t's)
  1879. if ((latestQr.startsWith("{2fitest") || latestQr.startsWith("{2fittest")) && latestQr.endsWith("}")) {
  1880. // Extract content: remove "{2fitest" or "{2fittest" and "}"
  1881. let content = '';
  1882. if (latestQr.startsWith("{2fittest")) {
  1883. content = latestQr.substring(9, latestQr.length - 1); // Remove "{2fittest" and "}"
  1884. } else if (latestQr.startsWith("{2fitest")) {
  1885. content = latestQr.substring(8, latestQr.length - 1); // Remove "{2fitest" and "}"
  1886. }
  1887. const parts = content.split(',');
  1888. if (parts.length === 2) {
  1889. const itemId = parseInt(parts[0].trim(), 10);
  1890. const stockInLineId = parseInt(parts[1].trim(), 10);
  1891. if (!isNaN(itemId) && !isNaN(stockInLineId)) {
  1892. console.log(
  1893. `%c TEST QR: Detected ${latestQr.substring(0, 9)}... - Simulating QR input (itemId=${itemId}, stockInLineId=${stockInLineId})`,
  1894. "color: purple; font-weight: bold"
  1895. );
  1896. // ✅ Simulate QR code JSON format
  1897. const simulatedQr = JSON.stringify({
  1898. itemId: itemId,
  1899. stockInLineId: stockInLineId
  1900. });
  1901. console.log(` [TEST QR] Simulated QR content: ${simulatedQr}`);
  1902. console.log(` [TEST QR] Start time: ${new Date().toISOString()}`);
  1903. const testStartTime = performance.now();
  1904. // ✅ Mark as processed FIRST to avoid duplicate processing
  1905. lastProcessedQrRef.current = latestQr;
  1906. processedQrCodesRef.current.add(latestQr);
  1907. if (processedQrCodesRef.current.size > 100) {
  1908. const firstValue = processedQrCodesRef.current.values().next().value;
  1909. if (firstValue !== undefined) {
  1910. processedQrCodesRef.current.delete(firstValue);
  1911. }
  1912. }
  1913. setLastProcessedQr(latestQr);
  1914. setProcessedQrCodes(new Set(processedQrCodesRef.current));
  1915. // ✅ Process immediately (bypass QR scanner delay)
  1916. if (processOutsideQrCodeRef.current) {
  1917. processOutsideQrCodeRef.current(simulatedQr, qrValues.length).then(() => {
  1918. const testTime = performance.now() - testStartTime;
  1919. console.log(` [TEST QR] Total processing time: ${testTime.toFixed(2)}ms (${(testTime / 1000).toFixed(3)}s)`);
  1920. console.log(` [TEST QR] End time: ${new Date().toISOString()}`);
  1921. }).catch((error) => {
  1922. const testTime = performance.now() - testStartTime;
  1923. console.error(`❌ [TEST QR] Error after ${testTime.toFixed(2)}ms:`, error);
  1924. });
  1925. }
  1926. // Reset scan
  1927. if (resetScanRef.current) {
  1928. resetScanRef.current();
  1929. }
  1930. const qrValuesChangeTime = performance.now() - qrValuesChangeStartTime;
  1931. console.log(` [QR VALUES EFFECT] Test QR handling time: ${qrValuesChangeTime.toFixed(2)}ms`);
  1932. return; // ✅ IMPORTANT: Return early to prevent normal processing
  1933. } else {
  1934. console.warn(` [TEST QR] Invalid itemId or stockInLineId: itemId=${parts[0]}, stockInLineId=${parts[1]}`);
  1935. }
  1936. } else {
  1937. console.warn(` [TEST QR] Invalid format. Expected {2fitestx,y} or {2fittestx,y}, got: ${latestQr}`);
  1938. }
  1939. }
  1940. // 批次确认弹窗:须第二次扫码选择沿用建议批次或切换(不再自动确认)
  1941. if (lotConfirmationOpen) {
  1942. if (isConfirmingLot) {
  1943. return;
  1944. }
  1945. if (qrValues.length <= lotConfirmOpenedQrCountRef.current) {
  1946. return;
  1947. }
  1948. void (async () => {
  1949. try {
  1950. const handled = await handleLotConfirmationByRescan(latestQr);
  1951. if (handled && resetScanRef.current) {
  1952. resetScanRef.current();
  1953. }
  1954. } catch (e) {
  1955. console.error("Lot confirmation rescan failed:", e);
  1956. }
  1957. })();
  1958. return;
  1959. }
  1960. // Skip processing if manual confirmation modal is open
  1961. if (manualLotConfirmationOpen) {
  1962. // Check if this is a different QR code than what triggered the modal
  1963. const modalTriggerQr = lastProcessedQrRef.current;
  1964. if (latestQr === modalTriggerQr) {
  1965. console.log(` [QR PROCESS] Skipping - manual modal open for same QR`);
  1966. return;
  1967. }
  1968. // If it's a different QR, allow processing
  1969. console.log(` [QR PROCESS] Different QR detected while manual modal open, allowing processing`);
  1970. }
  1971. const qrDetectionStartTime = performance.now();
  1972. console.log(` [QR DETECTION] Latest QR detected: ${latestQr?.substring(0, 50)}...`);
  1973. console.log(` [QR DETECTION] Detection time: ${new Date().toISOString()}`);
  1974. console.log(` [QR DETECTION] Time since QR scanner set value: ${(qrDetectionStartTime - qrValuesChangeStartTime).toFixed(2)}ms`);
  1975. // Skip if already processed (use refs to avoid dependency issues and delays)
  1976. const checkProcessedStartTime = performance.now();
  1977. if (processedQrCodesRef.current.has(latestQr) || lastProcessedQrRef.current === latestQr) {
  1978. const checkTime = performance.now() - checkProcessedStartTime;
  1979. console.log(` [QR PROCESS] Already processed check time: ${checkTime.toFixed(2)}ms`);
  1980. return;
  1981. }
  1982. const checkTime = performance.now() - checkProcessedStartTime;
  1983. console.log(` [QR PROCESS] Not processed check time: ${checkTime.toFixed(2)}ms`);
  1984. // Handle special shortcut
  1985. if (latestQr === "{2fic}") {
  1986. console.log(" Detected {2fic} shortcut - opening manual lot confirmation form");
  1987. setManualLotConfirmationOpen(true);
  1988. if (resetScanRef.current) {
  1989. resetScanRef.current();
  1990. }
  1991. lastProcessedQrRef.current = latestQr;
  1992. processedQrCodesRef.current.add(latestQr);
  1993. if (processedQrCodesRef.current.size > 100) {
  1994. const firstValue = processedQrCodesRef.current.values().next().value;
  1995. if (firstValue !== undefined) {
  1996. processedQrCodesRef.current.delete(firstValue);
  1997. }
  1998. }
  1999. setLastProcessedQr(latestQr);
  2000. setProcessedQrCodes(prev => {
  2001. const newSet = new Set(prev);
  2002. newSet.add(latestQr);
  2003. if (newSet.size > 100) {
  2004. const firstValue = newSet.values().next().value;
  2005. if (firstValue !== undefined) {
  2006. newSet.delete(firstValue);
  2007. }
  2008. }
  2009. return newSet;
  2010. });
  2011. return;
  2012. }
  2013. // Process new QR code immediately (background mode - no modal)
  2014. // Check against refs to avoid state update delays
  2015. if (latestQr && latestQr !== lastProcessedQrRef.current) {
  2016. const processingStartTime = performance.now();
  2017. console.log(` [QR PROCESS] Starting processing at: ${new Date().toISOString()}`);
  2018. console.log(` [QR PROCESS] Time since detection: ${(processingStartTime - qrDetectionStartTime).toFixed(2)}ms`);
  2019. // ✅ Process immediately for better responsiveness
  2020. // Clear any pending debounced processing
  2021. if (qrProcessingTimeoutRef.current) {
  2022. clearTimeout(qrProcessingTimeoutRef.current);
  2023. qrProcessingTimeoutRef.current = null;
  2024. }
  2025. // Log immediately (console.log is synchronous)
  2026. console.log(` [QR PROCESS] Processing new QR code with enhanced validation: ${latestQr}`);
  2027. // Update refs immediately (no state update delay) - do this FIRST
  2028. const refUpdateStartTime = performance.now();
  2029. lastProcessedQrRef.current = latestQr;
  2030. processedQrCodesRef.current.add(latestQr);
  2031. if (processedQrCodesRef.current.size > 100) {
  2032. const firstValue = processedQrCodesRef.current.values().next().value;
  2033. if (firstValue !== undefined) {
  2034. processedQrCodesRef.current.delete(firstValue);
  2035. }
  2036. }
  2037. const refUpdateTime = performance.now() - refUpdateStartTime;
  2038. console.log(` [QR PROCESS] Ref update time: ${refUpdateTime.toFixed(2)}ms`);
  2039. // Process immediately in background - no modal/form needed, no delays
  2040. // Use ref to avoid dependency issues
  2041. const processCallStartTime = performance.now();
  2042. if (processOutsideQrCodeRef.current) {
  2043. processOutsideQrCodeRef.current(latestQr, qrValues.length).then(() => {
  2044. const processCallTime = performance.now() - processCallStartTime;
  2045. const totalProcessingTime = performance.now() - processingStartTime;
  2046. console.log(` [QR PROCESS] processOutsideQrCode call time: ${processCallTime.toFixed(2)}ms`);
  2047. console.log(` [QR PROCESS] Total processing time: ${totalProcessingTime.toFixed(2)}ms (${(totalProcessingTime / 1000).toFixed(3)}s)`);
  2048. }).catch((error) => {
  2049. const processCallTime = performance.now() - processCallStartTime;
  2050. const totalProcessingTime = performance.now() - processingStartTime;
  2051. console.error(`❌ [QR PROCESS] processOutsideQrCode error after ${processCallTime.toFixed(2)}ms:`, error);
  2052. console.error(`❌ [QR PROCESS] Total processing time before error: ${totalProcessingTime.toFixed(2)}ms`);
  2053. });
  2054. }
  2055. // Update state for UI (but don't block on it)
  2056. const stateUpdateStartTime = performance.now();
  2057. setLastProcessedQr(latestQr);
  2058. setProcessedQrCodes(new Set(processedQrCodesRef.current));
  2059. const stateUpdateTime = performance.now() - stateUpdateStartTime;
  2060. console.log(` [QR PROCESS] State update time: ${stateUpdateTime.toFixed(2)}ms`);
  2061. const detectionTime = performance.now() - qrDetectionStartTime;
  2062. const totalEffectTime = performance.now() - qrValuesChangeStartTime;
  2063. console.log(` [QR DETECTION] Total detection time: ${detectionTime.toFixed(2)}ms`);
  2064. console.log(` [QR VALUES EFFECT] Total effect time: ${totalEffectTime.toFixed(2)}ms`);
  2065. }
  2066. return () => {
  2067. if (qrProcessingTimeoutRef.current) {
  2068. clearTimeout(qrProcessingTimeoutRef.current);
  2069. qrProcessingTimeoutRef.current = null;
  2070. }
  2071. };
  2072. }, [qrValues, isManualScanning, isRefreshingData, combinedLotData.length, lotConfirmationOpen, manualLotConfirmationOpen, handleLotConfirmationByRescan, isConfirmingLot]);
  2073. const renderCountRef = useRef(0);
  2074. const renderStartTimeRef = useRef<number | null>(null);
  2075. // Track render performance
  2076. useEffect(() => {
  2077. renderCountRef.current++;
  2078. const now = performance.now();
  2079. if (renderStartTimeRef.current !== null) {
  2080. const renderTime = now - renderStartTimeRef.current;
  2081. if (renderTime > 100) { // Only log slow renders (>100ms)
  2082. console.log(` [PERF] Render #${renderCountRef.current} took ${renderTime.toFixed(2)}ms, combinedLotData length: ${combinedLotData.length}`);
  2083. }
  2084. renderStartTimeRef.current = null;
  2085. }
  2086. // Track when lotConfirmationOpen changes
  2087. if (lotConfirmationOpen) {
  2088. renderStartTimeRef.current = performance.now();
  2089. console.log(` [PERF] Render triggered by lotConfirmationOpen=true`);
  2090. }
  2091. }, [combinedLotData.length, lotConfirmationOpen]);
  2092. // Auto-start scanner only once on mount
  2093. const scannerInitializedRef = useRef(false);
  2094. useEffect(() => {
  2095. if (session && currentUserId && !initializationRef.current) {
  2096. console.log(" Session loaded, initializing pick order...");
  2097. initializationRef.current = true;
  2098. // Only fetch existing data, no auto-assignment
  2099. fetchAllCombinedLotData();
  2100. }
  2101. }, [session, currentUserId, fetchAllCombinedLotData]);
  2102. // Separate effect for auto-starting scanner (only once, prevents multiple resets)
  2103. useEffect(() => {
  2104. if (session && currentUserId && !scannerInitializedRef.current) {
  2105. scannerInitializedRef.current = true;
  2106. // ✅ Auto-start scanner on mount for tablet use (background mode - no modal)
  2107. console.log("✅ Auto-starting QR scanner in background mode");
  2108. setIsManualScanning(true);
  2109. startScan();
  2110. }
  2111. }, [session, currentUserId, startScan]);
  2112. // Add event listener for manual assignment
  2113. useEffect(() => {
  2114. const handlePickOrderAssigned = () => {
  2115. console.log("🔄 Pick order assigned event received, refreshing data...");
  2116. fetchAllCombinedLotData();
  2117. };
  2118. window.addEventListener('pickOrderAssigned', handlePickOrderAssigned);
  2119. return () => {
  2120. window.removeEventListener('pickOrderAssigned', handlePickOrderAssigned);
  2121. };
  2122. }, [fetchAllCombinedLotData]);
  2123. const handleManualInputSubmit = useCallback(() => {
  2124. if (qrScanInput.trim() !== '') {
  2125. handleQrCodeSubmit(qrScanInput.trim());
  2126. }
  2127. }, [qrScanInput, handleQrCodeSubmit]);
  2128. // Handle QR code submission from modal (internal scanning)
  2129. const handleQrCodeSubmitFromModal = useCallback(async (lotNo: string) => {
  2130. if (selectedLotForQr && selectedLotForQr.lotNo === lotNo) {
  2131. console.log(` QR Code verified for lot: ${lotNo}`);
  2132. const requiredQty = selectedLotForQr.requiredQty;
  2133. const lotId = selectedLotForQr.lotId;
  2134. // Create stock out line
  2135. try {
  2136. const stockOutLineUpdate = await updateStockOutLineStatus({
  2137. id: selectedLotForQr.stockOutLineId,
  2138. status: 'checked',
  2139. qty: selectedLotForQr.stockOutLineQty || 0
  2140. });
  2141. console.log("Stock out line updated successfully!");
  2142. setQrScanSuccess(true);
  2143. setQrScanError(false);
  2144. // Clear selected lot (scanner stays active)
  2145. setSelectedLotForQr(null);
  2146. // Set pick quantity
  2147. const lotKey = `${selectedLotForQr.pickOrderLineId}-${lotId}`;
  2148. setTimeout(() => {
  2149. setPickQtyData(prev => ({
  2150. ...prev,
  2151. [lotKey]: requiredQty
  2152. }));
  2153. console.log(` Auto-set pick quantity to ${requiredQty} for lot ${lotNo}`);
  2154. }, 500);
  2155. } catch (error) {
  2156. console.error("Error creating stock out line:", error);
  2157. }
  2158. }
  2159. }, [selectedLotForQr]);
  2160. const handlePickQtyChange = useCallback((lotKey: string, value: number | string) => {
  2161. if (value === '' || value === null || value === undefined) {
  2162. setPickQtyData(prev => ({
  2163. ...prev,
  2164. [lotKey]: 0
  2165. }));
  2166. return;
  2167. }
  2168. const numericValue = typeof value === 'string' ? parseFloat(value) : value;
  2169. if (isNaN(numericValue)) {
  2170. setPickQtyData(prev => ({
  2171. ...prev,
  2172. [lotKey]: 0
  2173. }));
  2174. return;
  2175. }
  2176. setPickQtyData(prev => ({
  2177. ...prev,
  2178. [lotKey]: numericValue
  2179. }));
  2180. }, []);
  2181. const [autoAssignStatus, setAutoAssignStatus] = useState<'idle' | 'checking' | 'assigned' | 'no_orders'>('idle');
  2182. const [autoAssignMessage, setAutoAssignMessage] = useState<string>('');
  2183. const [completionStatus, setCompletionStatus] = useState<PickOrderCompletionResponse | null>(null);
  2184. const checkAndAutoAssignNext = useCallback(async () => {
  2185. if (!currentUserId) return;
  2186. try {
  2187. const completionResponse = await checkPickOrderCompletion(currentUserId);
  2188. if (completionResponse.code === "SUCCESS" && completionResponse.entity?.hasCompletedOrders) {
  2189. console.log("Found completed pick orders, auto-assigning next...");
  2190. // 移除前端的自动分配逻辑,因为后端已经处理了
  2191. // await handleAutoAssignAndRelease(); // 删除这个函数
  2192. }
  2193. } catch (error) {
  2194. console.error("Error checking pick order completion:", error);
  2195. }
  2196. }, [currentUserId]);
  2197. const resolveSingleSubmitQty = useCallback(
  2198. (lot: any) => {
  2199. const required = Number(lot.requiredQty || lot.pickOrderLineRequiredQty || 0);
  2200. const solId = Number(lot.stockOutLineId) || 0;
  2201. const lotKey = `${lot.pickOrderLineId}-${lot.lotId}`;
  2202. const issuePicked = solId > 0 ? issuePickedQtyBySolId[solId] : undefined;
  2203. if (issuePicked !== undefined && !Number.isNaN(Number(issuePicked))) {
  2204. return Number(issuePicked);
  2205. }
  2206. const fromPick = pickQtyData[lotKey];
  2207. if (fromPick !== undefined && fromPick !== null && !Number.isNaN(Number(fromPick))) {
  2208. return Number(fromPick);
  2209. }
  2210. if (lot.noLot === true) {
  2211. return 0;
  2212. }
  2213. if (isLotAvailabilityExpired(lot)) {
  2214. return 0;
  2215. }
  2216. return required;
  2217. },
  2218. [issuePickedQtyBySolId, pickQtyData]
  2219. );
  2220. // Handle reject lot
  2221. // Handle pick execution form
  2222. const handlePickExecutionForm = useCallback((lot: any) => {
  2223. console.log("=== Pick Execution Form ===");
  2224. console.log("Lot data:", lot);
  2225. if (!lot) {
  2226. console.warn("No lot data provided for pick execution form");
  2227. return;
  2228. }
  2229. console.log("Opening pick execution form for lot:", lot.lotNo);
  2230. setSelectedLotForExecutionForm(lot);
  2231. setPickExecutionFormOpen(true);
  2232. console.log("Pick execution form opened for lot ID:", lot.lotId);
  2233. }, []);
  2234. const handlePickExecutionFormSubmit = useCallback(async (data: any) => {
  2235. try {
  2236. console.log("Pick execution form submitted:", data);
  2237. const issueData = {
  2238. ...data,
  2239. type: "Do", // Delivery Order Record 类型
  2240. pickerName: session?.user?.name || '',
  2241. };
  2242. const result = await recordPickExecutionIssue(issueData);
  2243. console.log("Pick execution issue recorded:", result);
  2244. if (result && result.code === "SUCCESS") {
  2245. console.log(" Pick execution issue recorded successfully");
  2246. // 关键:issue form 只记录问题,不会更新 SOL.qty
  2247. // 但 batch submit 需要知道“实际拣到多少”,否则会按 requiredQty 补拣到满
  2248. const solId = Number(issueData.stockOutLineId || issueData.stockOutLineId === 0 ? issueData.stockOutLineId : data?.stockOutLineId);
  2249. if (solId > 0) {
  2250. const picked = Number(issueData.actualPickQty || 0);
  2251. setIssuePickedQtyBySolId((prev) => {
  2252. const next = { ...prev, [solId]: picked };
  2253. const doId = fgPickOrders[0]?.doPickOrderId;
  2254. if (doId) saveIssuePickedMap(doId, next);
  2255. return next;
  2256. });
  2257. setCombinedLotData(prev => prev.map(lot => {
  2258. if (Number(lot.stockOutLineId) === solId) {
  2259. return { ...lot, actualPickQty: picked, stockOutLineQty: picked };
  2260. }
  2261. return lot;
  2262. }));
  2263. }
  2264. } else {
  2265. console.error(" Failed to record pick execution issue:", result);
  2266. }
  2267. setPickExecutionFormOpen(false);
  2268. setSelectedLotForExecutionForm(null);
  2269. setQrScanError(false);
  2270. setQrScanSuccess(false);
  2271. setQrScanInput('');
  2272. // ✅ Keep scanner active after form submission - don't stop scanning
  2273. // Only clear processed QR codes for the specific lot, not all
  2274. // setIsManualScanning(false); // Removed - keep scanner active
  2275. // stopScan(); // Removed - keep scanner active
  2276. // resetScan(); // Removed - keep scanner active
  2277. // Don't clear all processed codes - only clear for this specific lot if needed
  2278. await fetchAllCombinedLotData();
  2279. } catch (error) {
  2280. console.error("Error submitting pick execution form:", error);
  2281. }
  2282. }, [fetchAllCombinedLotData, session, fgPickOrders]);
  2283. // Calculate remaining required quantity
  2284. const calculateRemainingRequiredQty = useCallback((lot: any) => {
  2285. const requiredQty = lot.requiredQty || 0;
  2286. const stockOutLineQty = lot.stockOutLineQty || 0;
  2287. return Math.max(0, requiredQty - stockOutLineQty);
  2288. }, []);
  2289. // Search criteria
  2290. const searchCriteria: Criterion<any>[] = [
  2291. {
  2292. label: t("Pick Order Code"),
  2293. paramName: "pickOrderCode",
  2294. type: "text",
  2295. },
  2296. {
  2297. label: t("Item Code"),
  2298. paramName: "itemCode",
  2299. type: "text",
  2300. },
  2301. {
  2302. label: t("Item Name"),
  2303. paramName: "itemName",
  2304. type: "text",
  2305. },
  2306. {
  2307. label: t("Lot No"),
  2308. paramName: "lotNo",
  2309. type: "text",
  2310. },
  2311. ];
  2312. const handleSearch = useCallback((query: Record<string, any>) => {
  2313. setSearchQuery({ ...query });
  2314. console.log("Search query:", query);
  2315. if (!originalCombinedData) return;
  2316. const filtered = originalCombinedData.filter((lot: any) => {
  2317. const pickOrderCodeMatch = !query.pickOrderCode ||
  2318. lot.pickOrderCode?.toLowerCase().includes((query.pickOrderCode || "").toLowerCase());
  2319. const itemCodeMatch = !query.itemCode ||
  2320. lot.itemCode?.toLowerCase().includes((query.itemCode || "").toLowerCase());
  2321. const itemNameMatch = !query.itemName ||
  2322. lot.itemName?.toLowerCase().includes((query.itemName || "").toLowerCase());
  2323. const lotNoMatch = !query.lotNo ||
  2324. lot.lotNo?.toLowerCase().includes((query.lotNo || "").toLowerCase());
  2325. return pickOrderCodeMatch && itemCodeMatch && itemNameMatch && lotNoMatch;
  2326. });
  2327. setCombinedLotData(filtered);
  2328. console.log("Filtered lots count:", filtered.length);
  2329. }, [originalCombinedData]);
  2330. const handleReset = useCallback(() => {
  2331. setSearchQuery({});
  2332. if (originalCombinedData) {
  2333. setCombinedLotData(originalCombinedData);
  2334. }
  2335. }, [originalCombinedData]);
  2336. const handlePageChange = useCallback((event: unknown, newPage: number) => {
  2337. setPaginationController(prev => ({
  2338. ...prev,
  2339. pageNum: newPage,
  2340. }));
  2341. }, []);
  2342. const handlePageSizeChange = useCallback((event: React.ChangeEvent<HTMLInputElement>) => {
  2343. const newPageSize = parseInt(event.target.value, 10);
  2344. setPaginationController({
  2345. pageNum: 0,
  2346. pageSize: newPageSize === -1 ? -1 : newPageSize,
  2347. });
  2348. }, []);
  2349. // Pagination data with sorting by routerIndex
  2350. // Remove the sorting logic and just do pagination
  2351. // ✅ Memoize paginatedData to prevent re-renders when modal opens
  2352. const paginatedData = useMemo(() => {
  2353. if (paginationController.pageSize === -1) {
  2354. return combinedLotData; // Show all items
  2355. }
  2356. const startIndex = paginationController.pageNum * paginationController.pageSize;
  2357. const endIndex = startIndex + paginationController.pageSize;
  2358. return combinedLotData.slice(startIndex, endIndex); // No sorting needed
  2359. }, [combinedLotData, paginationController.pageNum, paginationController.pageSize]);
  2360. const allItemsReady = useMemo(() => {
  2361. if (combinedLotData.length === 0) return false;
  2362. return combinedLotData.every((lot: any) => {
  2363. const status = lot.stockOutLineStatus?.toLowerCase();
  2364. const isRejected =
  2365. status === 'rejected' || lot.lotAvailability === 'rejected';
  2366. const isCompleted =
  2367. status === 'completed' || status === 'partially_completed' || status === 'partially_complete';
  2368. const isChecked = status === 'checked';
  2369. const isPending = status === 'pending';
  2370. // ✅ FIXED: 无库存(noLot)行:pending 状态也应该被视为 ready(可以提交)
  2371. // ✅ 過期批號(未換批):與 noLot 相同,視為可收尾
  2372. if (lot.noLot === true || isLotAvailabilityExpired(lot)) {
  2373. return isChecked || isCompleted || isRejected || isPending;
  2374. }
  2375. // 正常 lot:必须已扫描/提交或者被拒收
  2376. return isChecked || isCompleted || isRejected;
  2377. });
  2378. }, [combinedLotData]);
  2379. const handleSubmitPickQtyWithQty = useCallback(async (lot: any, submitQty: number, source: 'justComplete' | 'singleSubmit') => {
  2380. if (!lot.stockOutLineId) {
  2381. console.error("No stock out line found for this lot");
  2382. return;
  2383. }
  2384. const solId = Number(lot.stockOutLineId);
  2385. if (solId > 0 && actionBusyBySolId[solId]) {
  2386. console.warn("Action already in progress for stockOutLineId:", solId);
  2387. return;
  2388. }
  2389. try {
  2390. if (solId > 0) setActionBusyBySolId(prev => ({ ...prev, [solId]: true }));
  2391. // Just Complete: mark checked only, real posting happens in batch submit
  2392. if (submitQty === 0 && source === 'justComplete') {
  2393. console.log(`=== SUBMITTING ALL ZEROS CASE ===`);
  2394. console.log(`Lot: ${lot.lotNo}`);
  2395. console.log(`Stock Out Line ID: ${lot.stockOutLineId}`);
  2396. console.log(`Setting status to 'checked' with qty: 0`);
  2397. const updateResult = await updateStockOutLineStatus({
  2398. id: lot.stockOutLineId,
  2399. status: 'checked',
  2400. qty: 0
  2401. });
  2402. console.log('Update result:', updateResult);
  2403. const r: any = updateResult as any;
  2404. const updateOk =
  2405. r?.code === 'SUCCESS' ||
  2406. r?.type === 'completed' ||
  2407. typeof r?.id === 'number' ||
  2408. typeof r?.entity?.id === 'number' ||
  2409. (r?.message && r.message.includes('successfully'));
  2410. if (!updateResult || !updateOk) {
  2411. console.error('Failed to update stock out line status:', updateResult);
  2412. throw new Error('Failed to update stock out line status');
  2413. }
  2414. applyLocalStockOutLineUpdate(Number(lot.stockOutLineId), "checked", Number(lot.actualPickQty || 0));
  2415. void fetchAllCombinedLotData();
  2416. console.log("Just Complete marked as checked successfully (waiting for batch submit).");
  2417. setTimeout(() => {
  2418. checkAndAutoAssignNext();
  2419. }, 1000);
  2420. return;
  2421. }
  2422. if (submitQty === 0 && source === 'singleSubmit') {
  2423. console.log(`=== SUBMITTING ALL ZEROS CASE ===`);
  2424. console.log(`Lot: ${lot.lotNo}`);
  2425. console.log(`Stock Out Line ID: ${lot.stockOutLineId}`);
  2426. console.log(`Setting status to 'checked' with qty: 0`);
  2427. const updateResult = await updateStockOutLineStatus({
  2428. id: lot.stockOutLineId,
  2429. status: 'checked',
  2430. qty: 0
  2431. });
  2432. console.log('Update result:', updateResult);
  2433. const r: any = updateResult as any;
  2434. const updateOk =
  2435. r?.code === 'SUCCESS' ||
  2436. r?.type === 'completed' ||
  2437. typeof r?.id === 'number' ||
  2438. typeof r?.entity?.id === 'number' ||
  2439. (r?.message && r.message.includes('successfully'));
  2440. if (!updateResult || !updateOk) {
  2441. console.error('Failed to update stock out line status:', updateResult);
  2442. throw new Error('Failed to update stock out line status');
  2443. }
  2444. applyLocalStockOutLineUpdate(Number(lot.stockOutLineId), "checked", Number(lot.actualPickQty || 0));
  2445. void fetchAllCombinedLotData();
  2446. console.log("Just Complete marked as checked successfully (waiting for batch submit).");
  2447. setTimeout(() => {
  2448. checkAndAutoAssignNext();
  2449. }, 1000);
  2450. return;
  2451. }
  2452. // FIXED: Calculate cumulative quantity correctly
  2453. const currentActualPickQty = lot.actualPickQty || 0;
  2454. const cumulativeQty = currentActualPickQty + submitQty;
  2455. // FIXED: Determine status based on cumulative quantity vs required quantity
  2456. let newStatus = 'partially_completed';
  2457. if (cumulativeQty >= lot.requiredQty) {
  2458. newStatus = 'completed';
  2459. } else if (cumulativeQty > 0) {
  2460. newStatus = 'partially_completed';
  2461. } else {
  2462. newStatus = 'checked'; // QR scanned but no quantity submitted yet
  2463. }
  2464. console.log(`=== PICK QUANTITY SUBMISSION DEBUG ===`);
  2465. console.log(`Lot: ${lot.lotNo}`);
  2466. console.log(`Required Qty: ${lot.requiredQty}`);
  2467. console.log(`Current Actual Pick Qty: ${currentActualPickQty}`);
  2468. console.log(`New Submitted Qty: ${submitQty}`);
  2469. console.log(`Cumulative Qty: ${cumulativeQty}`);
  2470. console.log(`New Status: ${newStatus}`);
  2471. console.log(`=====================================`);
  2472. await updateStockOutLineStatus({
  2473. id: lot.stockOutLineId,
  2474. status: newStatus,
  2475. // 后端 updateStatus 的 qty 是“增量 delta”,不能传 cumulativeQty(否则会重复累加导致 out/hold 大幅偏移)
  2476. qty: submitQty
  2477. });
  2478. applyLocalStockOutLineUpdate(Number(lot.stockOutLineId), newStatus, cumulativeQty);
  2479. // 注意:库存过账(hold->out)与 ledger 由后端 updateStatus 内部统一处理;
  2480. // 前端不再额外调用 updateInventoryLotLineQuantities(operation='pick'),避免 double posting。
  2481. // Check if pick order is completed when lot status becomes 'completed'
  2482. if (newStatus === 'completed' && lot.pickOrderConsoCode) {
  2483. console.log(` Lot ${lot.lotNo} completed, checking if pick order ${lot.pickOrderConsoCode} is complete...`);
  2484. try {
  2485. const completionResponse = await checkAndCompletePickOrderByConsoCode(lot.pickOrderConsoCode);
  2486. console.log(` Pick order completion check result:`, completionResponse);
  2487. if (completionResponse.code === "SUCCESS") {
  2488. console.log(` Pick order ${lot.pickOrderConsoCode} completed successfully!`);
  2489. } else if (completionResponse.message === "not completed") {
  2490. console.log(`⏳ Pick order not completed yet, more lines remaining`);
  2491. } else {
  2492. console.error(` Error checking completion: ${completionResponse.message}`);
  2493. }
  2494. } catch (error) {
  2495. console.error("Error checking pick order completion:", error);
  2496. }
  2497. }
  2498. void fetchAllCombinedLotData();
  2499. console.log("Pick quantity submitted successfully!");
  2500. setTimeout(() => {
  2501. checkAndAutoAssignNext();
  2502. }, 1000);
  2503. } catch (error) {
  2504. console.error("Error submitting pick quantity:", error);
  2505. } finally {
  2506. if (solId > 0) setActionBusyBySolId(prev => ({ ...prev, [solId]: false }));
  2507. }
  2508. }, [fetchAllCombinedLotData, checkAndAutoAssignNext, actionBusyBySolId, applyLocalStockOutLineUpdate]);
  2509. const handleSkip = useCallback(async (lot: any) => {
  2510. try {
  2511. console.log("Just Complete clicked, mark checked with 0 qty for lot:", lot.lotNo);
  2512. await handleSubmitPickQtyWithQty(lot, 0, 'justComplete');
  2513. } catch (err) {
  2514. console.error("Error in Skip:", err);
  2515. }
  2516. }, [handleSubmitPickQtyWithQty]);
  2517. const hasPendingBatchSubmit = useMemo(() => {
  2518. return combinedLotData.some((lot) => {
  2519. const status = String(lot.stockOutLineStatus || "").toLowerCase();
  2520. return status === "checked" || status === "pending" || status === "partially_completed" || status === "partially_complete";
  2521. });
  2522. }, [combinedLotData]);
  2523. useEffect(() => {
  2524. if (!hasPendingBatchSubmit) return;
  2525. const handler = (event: BeforeUnloadEvent) => {
  2526. event.preventDefault();
  2527. event.returnValue = "";
  2528. };
  2529. window.addEventListener("beforeunload", handler);
  2530. return () => window.removeEventListener("beforeunload", handler);
  2531. }, [hasPendingBatchSubmit]);
  2532. const handleStartScan = useCallback(() => {
  2533. const startTime = performance.now();
  2534. console.log(` [START SCAN] Called at: ${new Date().toISOString()}`);
  2535. console.log(` [START SCAN] Starting manual QR scan...`);
  2536. setIsManualScanning(true);
  2537. const setManualScanningTime = performance.now() - startTime;
  2538. console.log(` [START SCAN] setManualScanning time: ${setManualScanningTime.toFixed(2)}ms`);
  2539. setProcessedQrCodes(new Set());
  2540. setLastProcessedQr('');
  2541. setQrScanError(false);
  2542. setQrScanSuccess(false);
  2543. const beforeStartScanTime = performance.now();
  2544. startScan();
  2545. const startScanTime = performance.now() - beforeStartScanTime;
  2546. console.log(` [START SCAN] startScan() call time: ${startScanTime.toFixed(2)}ms`);
  2547. const totalTime = performance.now() - startTime;
  2548. console.log(` [START SCAN] Total start scan time: ${totalTime.toFixed(2)}ms`);
  2549. console.log(` [START SCAN] Start scan completed at: ${new Date().toISOString()}`);
  2550. }, [startScan]);
  2551. const handlePickOrderSwitch = useCallback(async (pickOrderId: number) => {
  2552. if (pickOrderSwitching) return;
  2553. setPickOrderSwitching(true);
  2554. try {
  2555. console.log(" Switching to pick order:", pickOrderId);
  2556. setSelectedPickOrderId(pickOrderId);
  2557. // 强制刷新数据,确保显示正确的 pick order 数据
  2558. await fetchAllCombinedLotData(currentUserId, pickOrderId);
  2559. } catch (error) {
  2560. console.error("Error switching pick order:", error);
  2561. } finally {
  2562. setPickOrderSwitching(false);
  2563. }
  2564. }, [pickOrderSwitching, currentUserId, fetchAllCombinedLotData]);
  2565. const handleStopScan = useCallback(() => {
  2566. console.log("⏸️ Pausing QR scanner...");
  2567. setIsManualScanning(false);
  2568. setQrScanError(false);
  2569. setQrScanSuccess(false);
  2570. stopScan();
  2571. resetScan();
  2572. }, [stopScan, resetScan]);
  2573. // ... existing code around line 1469 ...
  2574. const handlelotnull = useCallback(async (lot: any) => {
  2575. // 优先使用 stockouts 中的 id,如果没有则使用 stockOutLineId
  2576. const stockOutLineId = lot.stockOutLineId;
  2577. if (!stockOutLineId) {
  2578. console.error(" No stockOutLineId found for lot:", lot);
  2579. return;
  2580. }
  2581. const solId = Number(stockOutLineId);
  2582. if (solId > 0 && actionBusyBySolId[solId]) {
  2583. console.warn("Action already in progress for stockOutLineId:", solId);
  2584. return;
  2585. }
  2586. try {
  2587. if (solId > 0) setActionBusyBySolId(prev => ({ ...prev, [solId]: true }));
  2588. // Step 1: Update stock out line status
  2589. await updateStockOutLineStatus({
  2590. id: stockOutLineId,
  2591. status: 'completed',
  2592. qty: 0
  2593. });
  2594. // Step 2: Create pick execution issue for no-lot case
  2595. // Get pick order ID from fgPickOrders or use 0 if not available
  2596. const pickOrderId = lot.pickOrderId || fgPickOrders[0]?.pickOrderId || 0;
  2597. const pickOrderCode = lot.pickOrderCode || fgPickOrders[0]?.pickOrderCode || lot.pickOrderConsoCode || '';
  2598. const issueData: PickExecutionIssueData = {
  2599. type: "Do", // Delivery Order type
  2600. pickOrderId: pickOrderId,
  2601. pickOrderCode: pickOrderCode,
  2602. pickOrderCreateDate: dayjs().format('YYYY-MM-DD'), // Use dayjs format
  2603. pickExecutionDate: dayjs().format('YYYY-MM-DD'),
  2604. pickOrderLineId: lot.pickOrderLineId,
  2605. itemId: lot.itemId,
  2606. itemCode: lot.itemCode || '',
  2607. itemDescription: lot.itemName || '',
  2608. lotId: null, // No lot available
  2609. lotNo: null, // No lot number
  2610. storeLocation: lot.location || '',
  2611. requiredQty: lot.requiredQty || lot.pickOrderLineRequiredQty || 0,
  2612. actualPickQty: 0, // No items picked (no lot available)
  2613. missQty: lot.requiredQty || lot.pickOrderLineRequiredQty || 0, // All quantity is missing
  2614. badItemQty: 0,
  2615. issueRemark: `No lot available for this item. Handled via handlelotnull.`,
  2616. pickerName: session?.user?.name || '',
  2617. };
  2618. const result = await recordPickExecutionIssue(issueData);
  2619. console.log(" Pick execution issue created for no-lot item:", result);
  2620. if (result && result.code === "SUCCESS") {
  2621. console.log(" No-lot item handled and issue recorded successfully");
  2622. } else {
  2623. console.error(" Failed to record pick execution issue:", result);
  2624. }
  2625. // Step 3: Refresh data
  2626. await fetchAllCombinedLotData();
  2627. } catch (error) {
  2628. console.error(" Error in handlelotnull:", error);
  2629. } finally {
  2630. if (solId > 0) setActionBusyBySolId(prev => ({ ...prev, [solId]: false }));
  2631. }
  2632. }, [fetchAllCombinedLotData, session, currentUserId, fgPickOrders, actionBusyBySolId]);
  2633. const handleBatchScan = useCallback(async () => {
  2634. const startTime = performance.now();
  2635. console.log(` [BATCH SCAN START]`);
  2636. console.log(` Start time: ${new Date().toISOString()}`);
  2637. // 获取所有活跃批次(未扫描的)
  2638. const activeLots = combinedLotData.filter(lot => {
  2639. return (
  2640. lot.lotAvailability !== 'rejected' &&
  2641. lot.stockOutLineStatus !== 'rejected' &&
  2642. lot.stockOutLineStatus !== 'completed' &&
  2643. lot.stockOutLineStatus !== 'checked' && // ✅ 只处理未扫描的
  2644. lot.processingStatus !== 'completed' &&
  2645. lot.noLot !== true &&
  2646. lot.lotNo // ✅ 必须有 lotNo
  2647. );
  2648. });
  2649. if (activeLots.length === 0) {
  2650. console.log("No active lots to scan");
  2651. return;
  2652. }
  2653. console.log(`📦 Batch scanning ${activeLots.length} active lots using batch API...`);
  2654. try {
  2655. // ✅ 转换为批量扫描 API 所需的格式
  2656. const lines: BatchScanLineRequest[] = activeLots.map((lot) => ({
  2657. pickOrderLineId: Number(lot.pickOrderLineId),
  2658. inventoryLotLineId: lot.lotId ? Number(lot.lotId) : null,
  2659. pickOrderConsoCode: String(lot.pickOrderConsoCode || ''),
  2660. lotNo: lot.lotNo || null,
  2661. itemId: Number(lot.itemId),
  2662. itemCode: String(lot.itemCode || ''),
  2663. stockOutLineId: lot.stockOutLineId ? Number(lot.stockOutLineId) : null, // ✅ 新增
  2664. }));
  2665. const request: BatchScanRequest = {
  2666. userId: currentUserId || 0,
  2667. lines: lines
  2668. };
  2669. console.log(`📤 Sending batch scan request with ${lines.length} lines`);
  2670. console.log(`📋 Request data:`, JSON.stringify(request, null, 2));
  2671. const scanStartTime = performance.now();
  2672. // ✅ 使用新的批量扫描 API(一次性处理所有请求)
  2673. const result = await batchScan(request);
  2674. const scanTime = performance.now() - scanStartTime;
  2675. console.log(` Batch scan API call completed in ${scanTime.toFixed(2)}ms (${(scanTime / 1000).toFixed(3)}s)`);
  2676. console.log(`📥 Batch scan result:`, result);
  2677. // ✅ 刷新数据以获取最新的状态
  2678. const refreshStartTime = performance.now();
  2679. await fetchAllCombinedLotData();
  2680. const refreshTime = performance.now() - refreshStartTime;
  2681. console.log(` Data refresh time: ${refreshTime.toFixed(2)}ms (${(refreshTime / 1000).toFixed(3)}s)`);
  2682. const totalTime = performance.now() - startTime;
  2683. console.log(` [BATCH SCAN END]`);
  2684. console.log(` Total time: ${totalTime.toFixed(2)}ms (${(totalTime / 1000).toFixed(3)}s)`);
  2685. console.log(` End time: ${new Date().toISOString()}`);
  2686. if (result && result.code === "SUCCESS") {
  2687. setQrScanSuccess(true);
  2688. setQrScanError(false);
  2689. } else {
  2690. console.error("❌ Batch scan failed:", result);
  2691. setQrScanError(true);
  2692. setQrScanSuccess(false);
  2693. }
  2694. } catch (error) {
  2695. console.error("❌ Error in batch scan:", error);
  2696. setQrScanError(true);
  2697. setQrScanSuccess(false);
  2698. }
  2699. }, [combinedLotData, fetchAllCombinedLotData, currentUserId]);
  2700. const handleSubmitAllScanned = useCallback(async () => {
  2701. const startTime = performance.now();
  2702. console.log(` [BATCH SUBMIT START]`);
  2703. console.log(` Start time: ${new Date().toISOString()}`);
  2704. const scannedLots = combinedLotData.filter(lot => {
  2705. const status = lot.stockOutLineStatus;
  2706. const statusLower = String(status || "").toLowerCase();
  2707. if (statusLower === "completed" || statusLower === "complete") {
  2708. return false;
  2709. }
  2710. // ✅ noLot / 過期批號:與 noLot 相同,允許 pending(未換批也可批量收尾)
  2711. if (lot.noLot === true || isLotAvailabilityExpired(lot)) {
  2712. return (
  2713. status === "checked" ||
  2714. status === "pending" ||
  2715. status === "partially_completed" ||
  2716. status === "PARTIALLY_COMPLETE"
  2717. );
  2718. }
  2719. return (
  2720. status === "checked" ||
  2721. status === "partially_completed" ||
  2722. status === "PARTIALLY_COMPLETE"
  2723. );
  2724. });
  2725. if (scannedLots.length === 0) {
  2726. console.log("No scanned items to submit");
  2727. return;
  2728. }
  2729. setIsSubmittingAll(true);
  2730. console.log(`📦 Submitting ${scannedLots.length} scanned items using batchSubmitList...`);
  2731. try {
  2732. // 转换为 batchSubmitList 所需的格式(与后端 QrPickBatchSubmitRequest 匹配)
  2733. const lines: batchSubmitListLineRequest[] = scannedLots.map((lot) => {
  2734. // 1. 需求数量
  2735. const requiredQty =
  2736. Number(lot.requiredQty || lot.pickOrderLineRequiredQty || 0);
  2737. // 2. 当前已经拣到的数量
  2738. // issue form 不会写回 SOL.qty,所以如果这条 SOL 有 issue,就用 issue form 的 actualPickQty 作为“已拣到数量”
  2739. const solId = Number(lot.stockOutLineId) || 0;
  2740. const issuePicked = solId > 0 ? issuePickedQtyBySolId[solId] : undefined;
  2741. const currentActualPickQty = Number(issuePicked ?? lot.actualPickQty ?? 0);
  2742. // 🔹 判断是否走“只改状态模式”
  2743. // 这里先给一个简单条件示例:如果你不想再补拣,只想把当前数量标记完成,
  2744. // 就让这个条件为 true(后面你可以根据业务加 UI 开关或别的 flag)。
  2745. const onlyComplete =
  2746. lot.stockOutLineStatus === "partially_completed" || issuePicked !== undefined;
  2747. const expired = isLotAvailabilityExpired(lot);
  2748. let targetActual: number;
  2749. let newStatus: string;
  2750. // ✅ 過期且未在 Issue 填實際量:與 noLot 一樣按 0 完成
  2751. if (expired && issuePicked === undefined) {
  2752. targetActual = 0;
  2753. newStatus = "completed";
  2754. } else if (onlyComplete) {
  2755. targetActual = currentActualPickQty;
  2756. newStatus = "completed";
  2757. } else {
  2758. const remainingQty = Math.max(0, requiredQty - currentActualPickQty);
  2759. const cumulativeQty = currentActualPickQty + remainingQty;
  2760. targetActual = cumulativeQty;
  2761. newStatus = "partially_completed";
  2762. if (requiredQty > 0 && cumulativeQty >= requiredQty) {
  2763. newStatus = "completed";
  2764. }
  2765. }
  2766. return {
  2767. stockOutLineId: Number(lot.stockOutLineId) || 0,
  2768. pickOrderLineId: Number(lot.pickOrderLineId),
  2769. inventoryLotLineId: lot.lotId ? Number(lot.lotId) : null,
  2770. requiredQty,
  2771. // 后端用 targetActual - 当前 qty 算增量,onlyComplete 时就是 0
  2772. actualPickQty: targetActual,
  2773. stockOutLineStatus: newStatus,
  2774. pickOrderConsoCode: String(lot.pickOrderConsoCode || ""),
  2775. noLot: Boolean(lot.noLot === true),
  2776. };
  2777. });
  2778. const request: batchSubmitListRequest = {
  2779. userId: currentUserId || 0,
  2780. lines: lines
  2781. };
  2782. console.log(`📤 Sending batch submit request with ${lines.length} lines`);
  2783. console.log(`📋 Request data:`, JSON.stringify(request, null, 2));
  2784. const submitStartTime = performance.now();
  2785. // 使用 batchSubmitList API
  2786. const result = await batchSubmitList(request);
  2787. const submitTime = performance.now() - submitStartTime;
  2788. console.log(` Batch submit API call completed in ${submitTime.toFixed(2)}ms (${(submitTime / 1000).toFixed(3)}s)`);
  2789. console.log(`📥 Batch submit result:`, result);
  2790. // Refresh data once after batch submission
  2791. const refreshStartTime = performance.now();
  2792. await fetchAllCombinedLotData();
  2793. const refreshTime = performance.now() - refreshStartTime;
  2794. console.log(` Data refresh time: ${refreshTime.toFixed(2)}ms (${(refreshTime / 1000).toFixed(3)}s)`);
  2795. const totalTime = performance.now() - startTime;
  2796. console.log(` [BATCH SUBMIT END]`);
  2797. console.log(` Total time: ${totalTime.toFixed(2)}ms (${(totalTime / 1000).toFixed(3)}s)`);
  2798. console.log(` End time: ${new Date().toISOString()}`);
  2799. if (result && result.code === "SUCCESS") {
  2800. setQrScanSuccess(true);
  2801. setTimeout(() => {
  2802. setQrScanSuccess(false);
  2803. checkAndAutoAssignNext();
  2804. if (onSwitchToRecordTab) {
  2805. onSwitchToRecordTab();
  2806. }
  2807. if (onRefreshReleasedOrderCount) {
  2808. onRefreshReleasedOrderCount();
  2809. }
  2810. }, 2000);
  2811. } else {
  2812. console.error("Batch submit failed:", result);
  2813. setQrScanError(true);
  2814. }
  2815. } catch (error) {
  2816. console.error("Error submitting all scanned items:", error);
  2817. setQrScanError(true);
  2818. } finally {
  2819. setIsSubmittingAll(false);
  2820. }
  2821. }, [combinedLotData, fetchAllCombinedLotData, checkAndAutoAssignNext, currentUserId, onSwitchToRecordTab, onRefreshReleasedOrderCount, issuePickedQtyBySolId]);
  2822. // Calculate scanned items count
  2823. // Calculate scanned items count (should match handleSubmitAllScanned filter logic)
  2824. const scannedItemsCount = useMemo(() => {
  2825. const filtered = combinedLotData.filter(lot => {
  2826. const status = lot.stockOutLineStatus;
  2827. const statusLower = String(status || "").toLowerCase();
  2828. if (statusLower === "completed" || statusLower === "complete") {
  2829. return false;
  2830. }
  2831. // ✅ 与 handleSubmitAllScanned 完全保持一致
  2832. if (lot.noLot === true || isLotAvailabilityExpired(lot)) {
  2833. return (
  2834. status === "checked" ||
  2835. status === "pending" ||
  2836. status === "partially_completed" ||
  2837. status === "PARTIALLY_COMPLETE"
  2838. );
  2839. }
  2840. return (
  2841. status === "checked" ||
  2842. status === "partially_completed" ||
  2843. status === "PARTIALLY_COMPLETE"
  2844. );
  2845. });
  2846. // 添加调试日志
  2847. const noLotCount = filtered.filter(l => l.noLot === true).length;
  2848. const normalCount = filtered.filter(l => l.noLot !== true).length;
  2849. console.log(`📊 scannedItemsCount calculation: total=${filtered.length}, noLot=${noLotCount}, normal=${normalCount}`);
  2850. console.log(`📊 All items breakdown:`, {
  2851. total: combinedLotData.length,
  2852. noLot: combinedLotData.filter(l => l.noLot === true).length,
  2853. normal: combinedLotData.filter(l => l.noLot !== true).length
  2854. });
  2855. return filtered.length;
  2856. }, [combinedLotData]);
  2857. /*
  2858. // ADD THIS: Auto-stop scan when no data available
  2859. useEffect(() => {
  2860. if (isManualScanning && combinedLotData.length === 0) {
  2861. console.log("⏹️ No data available, auto-stopping QR scan...");
  2862. handleStopScan();
  2863. }
  2864. }, [combinedLotData.length, isManualScanning, handleStopScan]);
  2865. */
  2866. // Cleanup effect
  2867. useEffect(() => {
  2868. return () => {
  2869. // Cleanup when component unmounts (e.g., when switching tabs)
  2870. if (isManualScanning) {
  2871. console.log("🧹 Pick execution component unmounting, stopping QR scanner...");
  2872. stopScan();
  2873. resetScan();
  2874. }
  2875. };
  2876. }, [isManualScanning, stopScan, resetScan]);
  2877. const getStatusMessage = useCallback((lot: any) => {
  2878. switch (lot.stockOutLineStatus?.toLowerCase()) {
  2879. case 'pending':
  2880. return t("Please finish QR code scan and pick order.");
  2881. case 'checked':
  2882. return t("Please submit the pick order.");
  2883. case 'partially_completed':
  2884. return t("Partial quantity submitted. Please submit more or complete the order.");
  2885. case 'completed':
  2886. return t("Pick order completed successfully!");
  2887. case 'rejected':
  2888. return t("Lot has been rejected and marked as unavailable.");
  2889. case 'unavailable':
  2890. return t("This order is insufficient, please pick another lot.");
  2891. default:
  2892. return t("Please finish QR code scan and pick order.");
  2893. }
  2894. }, [t]);
  2895. return (
  2896. <TestQrCodeProvider
  2897. lotData={combinedLotData}
  2898. onScanLot={handleQrCodeSubmit}
  2899. onBatchScan={handleBatchScan}
  2900. filterActive={(lot) => (
  2901. lot.lotAvailability !== 'rejected' &&
  2902. lot.stockOutLineStatus !== 'rejected' &&
  2903. lot.stockOutLineStatus !== 'completed'
  2904. )}
  2905. >
  2906. <FormProvider {...formProps}>
  2907. <Stack spacing={2}>
  2908. <Box
  2909. sx={{
  2910. position: 'fixed',
  2911. top: 0,
  2912. left: 0,
  2913. right: 0,
  2914. zIndex: 1100, // Higher than other elements
  2915. backgroundColor: 'background.paper',
  2916. pt: 2,
  2917. pb: 1,
  2918. px: 2,
  2919. borderBottom: '1px solid',
  2920. borderColor: 'divider',
  2921. boxShadow: '0 2px 4px rgba(0,0,0,0.1)',
  2922. }}
  2923. >
  2924. <LinearProgressWithLabel
  2925. completed={progress.completed}
  2926. total={progress.total}
  2927. label={t("Progress")}
  2928. />
  2929. <ScanStatusAlert
  2930. error={qrScanError}
  2931. success={qrScanSuccess}
  2932. errorMessage={t("QR code does not match any item in current orders.")}
  2933. successMessage={t("QR code verified.")}
  2934. />
  2935. </Box>
  2936. {/* DO Header */}
  2937. {/* 保留:Combined Lot Table - 包含所有 QR 扫描功能 */}
  2938. <Box>
  2939. <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 2, mt: 10 }}>
  2940. <Typography variant="h6" gutterBottom sx={{ mb: 0 }}>
  2941. {t("All Pick Order Lots")}
  2942. </Typography>
  2943. <Box sx={{ display: 'flex', gap: 2, alignItems: 'center' }}>
  2944. {/* Scanner status indicator (always visible) */}
  2945. {/*
  2946. <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
  2947. <QrCodeIcon
  2948. sx={{
  2949. color: isManualScanning ? '#4caf50' : '#9e9e9e',
  2950. animation: isManualScanning ? 'pulse 2s infinite' : 'none',
  2951. '@keyframes pulse': {
  2952. '0%, 100%': { opacity: 1 },
  2953. '50%': { opacity: 0.5 }
  2954. }
  2955. }}
  2956. />
  2957. <Typography variant="body2" sx={{ color: isManualScanning ? '#4caf50' : '#9e9e9e' }}>
  2958. {isManualScanning ? t("Scanner Active") : t("Scanner Inactive")}
  2959. </Typography>
  2960. </Box>
  2961. */}
  2962. {/* Pause/Resume button instead of Start/Stop */}
  2963. {isManualScanning ? (
  2964. <Button
  2965. variant="outlined"
  2966. startIcon={<QrCodeIcon />}
  2967. onClick={handleStopScan}
  2968. color="secondary"
  2969. sx={{ minWidth: '120px' }}
  2970. >
  2971. {t("Stop QR Scan")}
  2972. </Button>
  2973. ) : (
  2974. <Button
  2975. variant="contained"
  2976. startIcon={<QrCodeIcon />}
  2977. onClick={handleStartScan}
  2978. color="primary"
  2979. sx={{ minWidth: '120px' }}
  2980. >
  2981. {t("Start QR Scan")}
  2982. </Button>
  2983. )}
  2984. {/* 保留:Submit All Scanned Button */}
  2985. <Button
  2986. variant="contained"
  2987. color="success"
  2988. onClick={handleSubmitAllScanned}
  2989. disabled={
  2990. scannedItemsCount === 0
  2991. || isSubmittingAll}
  2992. sx={{ minWidth: '160px' }}
  2993. >
  2994. {isSubmittingAll ? (
  2995. <>
  2996. <CircularProgress size={16} sx={{ mr: 1, color: 'white' }} />
  2997. {t("Submitting...")}
  2998. </>
  2999. ) : (
  3000. `${t("Submit All Scanned")} (${scannedItemsCount})`
  3001. )}
  3002. </Button>
  3003. </Box>
  3004. </Box>
  3005. {fgPickOrders.length > 0 && (
  3006. <Paper sx={{ p: 2, mb: 2 }}>
  3007. <Stack spacing={2}>
  3008. {/* 基本信息 */}
  3009. <Stack direction="row" spacing={4} useFlexGap flexWrap="wrap">
  3010. <Typography variant="subtitle1">
  3011. <strong>{t("Shop Name")}:</strong> {fgPickOrders[0].shopName || '-'}
  3012. </Typography>
  3013. <Typography variant="subtitle1">
  3014. <strong>{t("Store ID")}:</strong> {fgPickOrders[0].storeId || '-'}
  3015. </Typography>
  3016. <Typography variant="subtitle1">
  3017. <strong>{t("Ticket No.")}:</strong> {fgPickOrders[0].ticketNo || '-'}
  3018. </Typography>
  3019. <Typography variant="subtitle1">
  3020. <strong>{t("Departure Time")}:</strong> {fgPickOrders[0].DepartureTime || '-'}
  3021. </Typography>
  3022. </Stack>
  3023. {/* 改进:三个字段显示在一起,使用表格式布局 */}
  3024. {/* 改进:三个字段合并显示 */}
  3025. {/* 改进:表格式显示每个 pick order */}
  3026. <Box sx={{
  3027. p: 2,
  3028. backgroundColor: '#f5f5f5',
  3029. borderRadius: 1
  3030. }}>
  3031. <Typography variant="subtitle2" sx={{ mb: 1, fontWeight: 'bold' }}>
  3032. {t("Pick Orders Details")}:
  3033. </Typography>
  3034. {(() => {
  3035. const pickOrderCodes = fgPickOrders[0].pickOrderCodes as string[] | string | undefined;
  3036. const deliveryNos = fgPickOrders[0].deliveryNos as string[] | string | undefined;
  3037. const lineCounts = fgPickOrders[0].lineCountsPerPickOrder;
  3038. const pickOrderCodesArray = Array.isArray(pickOrderCodes)
  3039. ? pickOrderCodes
  3040. : (typeof pickOrderCodes === 'string' ? pickOrderCodes.split(', ') : []);
  3041. const deliveryNosArray = Array.isArray(deliveryNos)
  3042. ? deliveryNos
  3043. : (typeof deliveryNos === 'string' ? deliveryNos.split(', ') : []);
  3044. const lineCountsArray = Array.isArray(lineCounts) ? lineCounts : [];
  3045. const maxLength = Math.max(
  3046. pickOrderCodesArray.length,
  3047. deliveryNosArray.length,
  3048. lineCountsArray.length
  3049. );
  3050. if (maxLength === 0) {
  3051. return <Typography variant="body2" color="text.secondary">-</Typography>;
  3052. }
  3053. // 使用与外部基本信息相同的样式
  3054. return Array.from({ length: maxLength }, (_, idx) => (
  3055. <Stack
  3056. key={idx}
  3057. direction="row"
  3058. spacing={4}
  3059. useFlexGap
  3060. flexWrap="wrap"
  3061. sx={{ mb: idx < maxLength - 1 ? 1 : 0 }} // 除了最后一行,都添加底部间距
  3062. >
  3063. <Typography variant="subtitle1">
  3064. <strong>{t("Delivery Order")}:</strong> {deliveryNosArray[idx] || '-'}
  3065. </Typography>
  3066. <Typography variant="subtitle1">
  3067. <strong>{t("Pick Order")}:</strong> {pickOrderCodesArray[idx] || '-'}
  3068. </Typography>
  3069. <Typography variant="subtitle1">
  3070. <strong>{t("Finsihed good items")}:</strong> {lineCountsArray[idx] || '-'}<strong>{t("kinds")}</strong>
  3071. </Typography>
  3072. </Stack>
  3073. ));
  3074. })()}
  3075. </Box>
  3076. </Stack>
  3077. </Paper>
  3078. )}
  3079. <TableContainer component={Paper}>
  3080. <Table>
  3081. <TableHead>
  3082. <TableRow>
  3083. <TableCell>{t("Index")}</TableCell>
  3084. <TableCell>{t("Route")}</TableCell>
  3085. <TableCell>{t("Item Code")}</TableCell>
  3086. <TableCell>{t("Item Name")}</TableCell>
  3087. <TableCell>{t("Lot#")}</TableCell>
  3088. <TableCell align="right">{t("Lot Required Pick Qty")}</TableCell>
  3089. <TableCell align="center">{t("Scan Result")}</TableCell>
  3090. <TableCell align="center">{t("Qty will submit")}</TableCell>
  3091. <TableCell align="center">{t("Submit Required Pick Qty")}</TableCell>
  3092. </TableRow>
  3093. </TableHead>
  3094. <TableBody>
  3095. {paginatedData.length === 0 ? (
  3096. <TableRow>
  3097. <TableCell colSpan={11} align="center">
  3098. <Typography variant="body2" color="text.secondary">
  3099. {t("No data available")}
  3100. </Typography>
  3101. </TableCell>
  3102. </TableRow>
  3103. ) : (
  3104. // 在第 1797-1938 行之间,将整个 map 函数修改为:
  3105. paginatedData.map((lot, index) => {
  3106. // 检查是否是 issue lot
  3107. const isIssueLot = lot.stockOutLineStatus === 'rejected' || !lot.lotNo;
  3108. return (
  3109. <TableRow
  3110. key={`${lot.pickOrderLineId}-${lot.lotId || 'null'}`}
  3111. sx={{
  3112. //backgroundColor: isIssueLot ? '#fff3e0' : 'inherit',
  3113. // opacity: isIssueLot ? 0.6 : 1,
  3114. '& .MuiTableCell-root': {
  3115. //color: isIssueLot ? 'warning.main' : 'inherit'
  3116. }
  3117. }}
  3118. >
  3119. <TableCell>
  3120. <Typography variant="body2" fontWeight="bold">
  3121. {paginationController.pageNum * paginationController.pageSize + index + 1}
  3122. </Typography>
  3123. </TableCell>
  3124. <TableCell>
  3125. <Typography variant="body2">
  3126. {lot.routerRoute || '-'}
  3127. </Typography>
  3128. </TableCell>
  3129. <TableCell>{lot.itemCode}</TableCell>
  3130. <TableCell>{lot.itemName + '(' + lot.stockUnit + ')'}</TableCell>
  3131. <TableCell>
  3132. <Box>
  3133. <Typography
  3134. sx={{
  3135. color:
  3136. lot.lotAvailability === 'expired'
  3137. ? 'warning.main'
  3138. : /* isIssueLot ? 'warning.main' : lot.lotAvailability === 'rejected' ? 'text.disabled' : */ 'inherit',
  3139. }}
  3140. >
  3141. {lot.lotNo ? (
  3142. lot.lotAvailability === 'expired' ? (
  3143. <>
  3144. {lot.lotNo}{' '}
  3145. {t('is expired. Please check around have available QR code or not.')}
  3146. </>
  3147. ) : (
  3148. lot.lotNo
  3149. )
  3150. ) : (
  3151. t(
  3152. 'Please check around have QR code or not, may be have just now stock in or transfer in or transfer out.'
  3153. )
  3154. )}
  3155. </Typography>
  3156. </Box>
  3157. </TableCell>
  3158. <TableCell align="right">
  3159. {(() => {
  3160. const requiredQty = lot.requiredQty || 0;
  3161. return requiredQty.toLocaleString() + '(' + lot.uomShortDesc + ')';
  3162. })()}
  3163. </TableCell>
  3164. <TableCell align="center">
  3165. {(() => {
  3166. const status = lot.stockOutLineStatus?.toLowerCase();
  3167. const isRejected = status === 'rejected' || lot.lotAvailability === 'rejected';
  3168. const isNoLot = !lot.lotNo;
  3169. // rejected lot:显示红色勾选(已扫描但被拒绝)
  3170. if (isRejected && !isNoLot) {
  3171. return (
  3172. <Box sx={{ display: 'flex', justifyContent: 'center', alignItems: 'center' }}>
  3173. <Checkbox
  3174. checked={true}
  3175. disabled={true}
  3176. readOnly={true}
  3177. size="large"
  3178. sx={{
  3179. color: 'error.main',
  3180. '&.Mui-checked': { color: 'error.main' },
  3181. transform: 'scale(1.3)',
  3182. }}
  3183. />
  3184. </Box>
  3185. );
  3186. }
  3187. // 過期批號:與 noLot 同類——視為已掃到/可處理(含 pending),顯示警示色勾選
  3188. if (isLotAvailabilityExpired(lot) && status !== "rejected") {
  3189. return (
  3190. <Box sx={{ display: "flex", justifyContent: "center", alignItems: "center" }}>
  3191. <Checkbox
  3192. checked={true}
  3193. disabled={true}
  3194. readOnly={true}
  3195. size="large"
  3196. sx={{
  3197. color: "warning.main",
  3198. "&.Mui-checked": { color: "warning.main" },
  3199. transform: "scale(1.3)",
  3200. }}
  3201. />
  3202. </Box>
  3203. );
  3204. }
  3205. // 正常 lot:已扫描(checked/partially_completed/completed)
  3206. if (!isNoLot && status !== 'pending' && status !== 'rejected') {
  3207. return (
  3208. <Box sx={{ display: 'flex', justifyContent: 'center', alignItems: 'center' }}>
  3209. <Checkbox
  3210. checked={true}
  3211. disabled={true}
  3212. readOnly={true}
  3213. size="large"
  3214. sx={{
  3215. color: 'success.main',
  3216. '&.Mui-checked': { color: 'success.main' },
  3217. transform: 'scale(1.3)',
  3218. }}
  3219. />
  3220. </Box>
  3221. );
  3222. }
  3223. // noLot 且已完成/部分完成:显示红色勾选
  3224. if (isNoLot && (status === 'partially_completed' || status === 'completed')) {
  3225. return (
  3226. <Box sx={{ display: 'flex', justifyContent: 'center', alignItems: 'center' }}>
  3227. <Checkbox
  3228. checked={true}
  3229. disabled={true}
  3230. readOnly={true}
  3231. size="large"
  3232. sx={{
  3233. color: 'error.main',
  3234. '&.Mui-checked': { color: 'error.main' },
  3235. transform: 'scale(1.3)',
  3236. }}
  3237. />
  3238. </Box>
  3239. );
  3240. }
  3241. return null;
  3242. })()}
  3243. </TableCell>
  3244. <TableCell align="center">{resolveSingleSubmitQty(lot)}</TableCell>
  3245. <TableCell align="center">
  3246. <Box sx={{ display: 'flex', justifyContent: 'center' }}>
  3247. {(() => {
  3248. const status = lot.stockOutLineStatus?.toLowerCase();
  3249. const isRejected = status === 'rejected' || lot.lotAvailability === 'rejected';
  3250. const isNoLot = !lot.lotNo;
  3251. // ✅ rejected lot:显示提示文本(换行显示)
  3252. if (isRejected && !isNoLot) {
  3253. return (
  3254. <Typography
  3255. variant="body2"
  3256. color="error.main"
  3257. sx={{
  3258. textAlign: 'center',
  3259. whiteSpace: 'normal',
  3260. wordBreak: 'break-word',
  3261. maxWidth: '200px',
  3262. lineHeight: 1.5
  3263. }}
  3264. >
  3265. {t("This lot is rejected, please scan another lot.")}
  3266. </Typography>
  3267. );
  3268. }
  3269. // noLot 情况:只显示 Issue 按钮
  3270. if (isNoLot) {
  3271. return (
  3272. <Button
  3273. variant="outlined"
  3274. size="small"
  3275. onClick={() => handlelotnull(lot)}
  3276. disabled={
  3277. status === 'completed' ||
  3278. (Number(lot.stockOutLineId) > 0 && actionBusyBySolId[Number(lot.stockOutLineId)] === true)
  3279. }
  3280. sx={{
  3281. fontSize: '0.7rem',
  3282. py: 0.5,
  3283. minHeight: '28px',
  3284. minWidth: '60px',
  3285. borderColor: 'warning.main',
  3286. color: 'warning.main'
  3287. }}
  3288. >
  3289. {t("Issue")}
  3290. </Button>
  3291. );
  3292. }
  3293. // 正常 lot:显示 Submit 和 Issue 按钮
  3294. return (
  3295. <Stack direction="row" spacing={1} alignItems="center">
  3296. <Button
  3297. variant="contained"
  3298. onClick={() => {
  3299. const lotKey = `${lot.pickOrderLineId}-${lot.lotId}`;
  3300. const submitQty = resolveSingleSubmitQty(lot);
  3301. handlePickQtyChange(lotKey, submitQty);
  3302. handleSubmitPickQtyWithQty(lot, submitQty, 'singleSubmit');
  3303. }}
  3304. disabled={
  3305. lot.lotAvailability === 'expired' ||
  3306. lot.lotAvailability === 'status_unavailable' ||
  3307. lot.lotAvailability === 'rejected' ||
  3308. lot.stockOutLineStatus === 'completed' ||
  3309. lot.stockOutLineStatus === 'pending' ||
  3310. (Number(lot.stockOutLineId) > 0 && actionBusyBySolId[Number(lot.stockOutLineId)] === true)
  3311. }
  3312. sx={{ fontSize: '0.75rem', py: 0.5, minHeight: '28px', minWidth: '70px' }}
  3313. >
  3314. {t("Submit")}
  3315. </Button>
  3316. <Button
  3317. variant="outlined"
  3318. size="small"
  3319. onClick={() => handlePickExecutionForm(lot)}
  3320. disabled={
  3321. lot.lotAvailability === 'expired' ||
  3322. lot.stockOutLineStatus === 'completed' ||
  3323. (Number(lot.stockOutLineId) > 0 && actionBusyBySolId[Number(lot.stockOutLineId)] === true)
  3324. }
  3325. sx={{
  3326. fontSize: '0.7rem',
  3327. py: 0.5,
  3328. minHeight: '28px',
  3329. minWidth: '60px',
  3330. borderColor: 'warning.main',
  3331. color: 'warning.main'
  3332. }}
  3333. title="Report missing or bad items"
  3334. >
  3335. {t("Edit")}
  3336. </Button>
  3337. <Button
  3338. variant="outlined"
  3339. size="small"
  3340. onClick={() => handleSkip(lot)}
  3341. disabled={
  3342. lot.stockOutLineStatus === 'completed' ||
  3343. lot.stockOutLineStatus === 'checked' ||
  3344. lot.stockOutLineStatus === 'partially_completed' ||
  3345. lot.lotAvailability === 'expired' ||
  3346. // 使用 issue form 後,禁用「Just Completed」(避免再次点击造成重复提交)
  3347. (Number(lot.stockOutLineId) > 0 && issuePickedQtyBySolId[Number(lot.stockOutLineId)] !== undefined) ||
  3348. (Number(lot.stockOutLineId) > 0 && actionBusyBySolId[Number(lot.stockOutLineId)] === true)
  3349. }
  3350. sx={{ fontSize: '0.7rem', py: 0.5, minHeight: '28px', minWidth: '60px' }}
  3351. >
  3352. {t("Just Completed")}
  3353. </Button>
  3354. </Stack>
  3355. );
  3356. })()}
  3357. </Box>
  3358. </TableCell>
  3359. </TableRow>
  3360. );
  3361. })
  3362. )}
  3363. </TableBody>
  3364. </Table>
  3365. </TableContainer>
  3366. <TablePagination
  3367. component="div"
  3368. count={combinedLotData.length}
  3369. page={paginationController.pageNum}
  3370. rowsPerPage={paginationController.pageSize}
  3371. onPageChange={handlePageChange}
  3372. onRowsPerPageChange={handlePageSizeChange}
  3373. rowsPerPageOptions={[10, 25, 50,-1]}
  3374. labelRowsPerPage={t("Rows per page")}
  3375. labelDisplayedRows={({ from, to, count }) =>
  3376. `${from}-${to} of ${count !== -1 ? count : `more than ${to}`}`
  3377. }
  3378. />
  3379. </Box>
  3380. </Stack>
  3381. {/* QR Code Scanner works in background - no modal needed */}
  3382. <ManualLotConfirmationModal
  3383. open={manualLotConfirmationOpen}
  3384. onClose={() => {
  3385. setManualLotConfirmationOpen(false);
  3386. }}
  3387. onConfirm={handleManualLotConfirmation}
  3388. expectedLot={expectedLotData}
  3389. scannedLot={scannedLotData}
  3390. isLoading={isConfirmingLot}
  3391. />
  3392. {/* 保留:Lot Confirmation Modal */}
  3393. {lotConfirmationOpen && expectedLotData && scannedLotData && (
  3394. <LotConfirmationModal
  3395. open={lotConfirmationOpen}
  3396. onClose={() => {
  3397. console.log(` [LOT CONFIRM MODAL] Closing modal, clearing state`);
  3398. clearLotConfirmationState(true);
  3399. }}
  3400. onConfirm={handleLotConfirmation}
  3401. expectedLot={expectedLotData}
  3402. scannedLot={scannedLotData}
  3403. isLoading={isConfirmingLot}
  3404. />
  3405. )}
  3406. {/* 保留:Good Pick Execution Form Modal */}
  3407. {pickExecutionFormOpen && selectedLotForExecutionForm && (
  3408. <GoodPickExecutionForm
  3409. open={pickExecutionFormOpen}
  3410. onClose={() => {
  3411. setPickExecutionFormOpen(false);
  3412. setSelectedLotForExecutionForm(null);
  3413. }}
  3414. onSubmit={handlePickExecutionFormSubmit}
  3415. selectedLot={selectedLotForExecutionForm}
  3416. selectedPickOrderLine={{
  3417. id: selectedLotForExecutionForm.pickOrderLineId,
  3418. itemId: selectedLotForExecutionForm.itemId,
  3419. itemCode: selectedLotForExecutionForm.itemCode,
  3420. itemName: selectedLotForExecutionForm.itemName,
  3421. pickOrderCode: selectedLotForExecutionForm.pickOrderCode,
  3422. availableQty: selectedLotForExecutionForm.availableQty || 0,
  3423. requiredQty: selectedLotForExecutionForm.requiredQty || 0,
  3424. // uomCode: selectedLotForExecutionForm.uomCode || '',
  3425. uomDesc: selectedLotForExecutionForm.uomDesc || '',
  3426. pickedQty: selectedLotForExecutionForm.actualPickQty || 0,
  3427. uomShortDesc: selectedLotForExecutionForm.uomShortDesc || '',
  3428. suggestedList: [],
  3429. noLotLines: [],
  3430. }}
  3431. pickOrderId={selectedLotForExecutionForm.pickOrderId}
  3432. pickOrderCreateDate={new Date()}
  3433. />
  3434. )}
  3435. </FormProvider>
  3436. </TestQrCodeProvider>
  3437. );
  3438. };
  3439. export default PickExecution;