FPSMS-frontend
Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.
 
 

994 рядки
30 KiB

  1. "use client";
  2. import {
  3. FooterPropsOverrides,
  4. GridActionsCellItem,
  5. GridCellParams,
  6. GridRowId,
  7. GridRowIdGetter,
  8. GridRowModel,
  9. GridRowModes,
  10. GridRowModesModel,
  11. GridToolbarContainer,
  12. useGridApiRef,
  13. } from "@mui/x-data-grid";
  14. import {
  15. Dispatch,
  16. MutableRefObject,
  17. SetStateAction,
  18. useCallback,
  19. useEffect,
  20. useMemo,
  21. useState,
  22. } from "react";
  23. import StyledDataGrid from "../StyledDataGrid";
  24. import { GridColDef } from "@mui/x-data-grid";
  25. import { Box, Button, Grid, Typography } from "@mui/material";
  26. import { useTranslation } from "react-i18next";
  27. import { Add } from "@mui/icons-material";
  28. import SaveIcon from "@mui/icons-material/Save";
  29. import DeleteIcon from "@mui/icons-material/Delete";
  30. import CancelIcon from "@mui/icons-material/Cancel";
  31. import FactCheckIcon from "@mui/icons-material/FactCheck";
  32. import ShoppingCartIcon from "@mui/icons-material/ShoppingCart";
  33. import { QcItemWithChecks } from "src/app/api/qc";
  34. import PlayArrowIcon from "@mui/icons-material/PlayArrow";
  35. import { PurchaseOrderLine, StockInLine } from "@/app/api/po";
  36. import { createStockInLine, PurchaseQcResult } from "@/app/api/po/actions";
  37. import { usePathname, useRouter, useSearchParams } from "next/navigation";
  38. import {
  39. returnWeightUnit,
  40. calculateWeight,
  41. stockInLineStatusMap,
  42. arrayToDateString,
  43. } from "@/app/utils/formatUtil";
  44. // import PoQcStockInModal from "./PoQcStockInModal";
  45. import NotificationImportantIcon from "@mui/icons-material/NotificationImportant";
  46. import { WarehouseResult } from "@/app/api/warehouse";
  47. import LooksOneIcon from "@mui/icons-material/LooksOne";
  48. import LooksTwoIcon from "@mui/icons-material/LooksTwo";
  49. import Looks3Icon from "@mui/icons-material/Looks3";
  50. import axiosInstance from "@/app/(main)/axios/axiosInstance";
  51. // import axios, { AxiosRequestConfig } from "axios";
  52. import { BASE_API_URL, NEXT_PUBLIC_API_URL } from "@/config/api";
  53. import qs from "qs";
  54. import QrCodeIcon from "@mui/icons-material/QrCode";
  55. import { downloadFile } from "@/app/utils/commonUtil";
  56. import { fetchPoQrcode } from "@/app/api/pdf/actions";
  57. import { fetchQcResult } from "@/app/api/qc/actions";
  58. import PoQcStockInModal from "./PoQcStockInModal";
  59. import DoDisturbIcon from "@mui/icons-material/DoDisturb";
  60. import { useSession } from "next-auth/react";
  61. import PoQcStockInModalVer2 from "./QcStockInModalVer2";
  62. import { decimalFormatter, integerFormatter } from "@/app/utils/formatUtil";
  63. interface ResultWithId {
  64. id: number;
  65. }
  66. interface Props {
  67. qc: QcItemWithChecks[];
  68. setRows: Dispatch<SetStateAction<PurchaseOrderLine[]>>;
  69. setStockInLine: Dispatch<SetStateAction<StockInLine[]>>;
  70. setProcessedQty: Dispatch<SetStateAction<number>>;
  71. itemDetail: PurchaseOrderLine;
  72. stockInLine: StockInLine[];
  73. warehouse: WarehouseResult[];
  74. fetchPoDetail: (poId: string) => void;
  75. }
  76. export type StockInLineEntryError = {
  77. [field in keyof StockInLine]?: string;
  78. };
  79. export type StockInLineRow = Partial<
  80. StockInLine & {
  81. isActive: boolean | undefined;
  82. _isNew: boolean;
  83. _error: StockInLineEntryError;
  84. } & ResultWithId
  85. >;
  86. class ProcessRowUpdateError extends Error {
  87. public readonly row: StockInLineRow;
  88. public readonly errors: StockInLineEntryError | undefined;
  89. constructor(
  90. row: StockInLineRow,
  91. message?: string,
  92. errors?: StockInLineEntryError,
  93. ) {
  94. super(message);
  95. this.row = row;
  96. this.errors = errors;
  97. Object.setPrototypeOf(this, ProcessRowUpdateError.prototype);
  98. }
  99. }
  100. function PoInputGrid({
  101. qc,
  102. setRows,
  103. setStockInLine,
  104. setProcessedQty,
  105. itemDetail,
  106. stockInLine,
  107. warehouse,
  108. fetchPoDetail
  109. }: Props) {
  110. console.log(itemDetail);
  111. const { t } = useTranslation("purchaseOrder");
  112. const apiRef = useGridApiRef();
  113. const [rowModesModel, setRowModesModel] = useState<GridRowModesModel>({});
  114. const getRowId = useCallback<GridRowIdGetter<StockInLineRow>>(
  115. (row) => row.id as number,
  116. [],
  117. );
  118. console.log(stockInLine);
  119. const [entries, setEntries] = useState<StockInLineRow[]>(stockInLine || []);
  120. useEffect(() => {
  121. setEntries(stockInLine)
  122. }, [stockInLine])
  123. const [modalInfo, setModalInfo] = useState<
  124. StockInLine & { qcResult?: PurchaseQcResult[] }
  125. >();
  126. const pathname = usePathname()
  127. const router = useRouter();
  128. const searchParams = useSearchParams();
  129. const [qcOpen, setQcOpen] = useState(false);
  130. const [escalOpen, setEscalOpen] = useState(false);
  131. const [stockInOpen, setStockInOpen] = useState(false);
  132. const [putAwayOpen, setPutAwayOpen] = useState(false);
  133. const [rejectOpen, setRejectOpen] = useState(false);
  134. const [btnIsLoading, setBtnIsLoading] = useState(false);
  135. const [currQty, setCurrQty] = useState(() => {
  136. const total = entries.reduce(
  137. (acc, curr) => acc + (curr.acceptedQty || 0),
  138. 0,
  139. );
  140. return total;
  141. });
  142. const { data: session } = useSession();
  143. useEffect(() => {
  144. const completedList = entries.filter(
  145. (e) => stockInLineStatusMap[e.status!] >= 8,
  146. );
  147. const processedQty = completedList.reduce(
  148. (acc, curr) => acc + (curr.acceptedQty || 0),
  149. 0,
  150. );
  151. setProcessedQty(processedQty);
  152. }, [entries, setProcessedQty]);
  153. const handleDelete = useCallback(
  154. (id: GridRowId) => () => {
  155. setEntries((es) => es.filter((e) => getRowId(e) !== id));
  156. },
  157. [getRowId],
  158. );
  159. const closeQcModal = useCallback(() => {
  160. setQcOpen(false);
  161. }, []);
  162. const openQcModal = useCallback(() => {
  163. setQcOpen(true);
  164. }, []);
  165. const closeStockInModal = useCallback(() => {
  166. setStockInOpen(false);
  167. }, []);
  168. const openStockInModal = useCallback(() => {
  169. setStockInOpen(true);
  170. }, []);
  171. const closePutAwayModal = useCallback(() => {
  172. setPutAwayOpen(false);
  173. }, []);
  174. const openPutAwayModal = useCallback(() => {
  175. setPutAwayOpen(true);
  176. }, []);
  177. const closeEscalationModal = useCallback(() => {
  178. setEscalOpen(false);
  179. }, []);
  180. const openEscalationModal = useCallback(() => {
  181. setEscalOpen(true);
  182. }, []);
  183. const closeRejectModal = useCallback(() => {
  184. setRejectOpen(false);
  185. }, []);
  186. const openRejectModal = useCallback(() => {
  187. setRejectOpen(true);
  188. }, []);
  189. const handleStart = useCallback(
  190. (id: GridRowId, params: any) => () => {
  191. setBtnIsLoading(true);
  192. setRowModesModel((prev) => ({
  193. ...prev,
  194. [id]: { mode: GridRowModes.View },
  195. }));
  196. setTimeout(async () => {
  197. // post stock in line
  198. const oldId = params.row.id;
  199. const postData = {
  200. itemId: params.row.itemId,
  201. itemNo: params.row.itemNo,
  202. itemName: params.row.itemName,
  203. purchaseOrderId: params.row.purchaseOrderId,
  204. purchaseOrderLineId: params.row.purchaseOrderLineId,
  205. acceptedQty: params.row.acceptedQty,
  206. };
  207. const res = await createStockInLine(postData);
  208. console.log(res);
  209. setEntries((prev) =>
  210. prev.map((p) => (p.id === oldId ? (res.entity as StockInLine) : p)),
  211. );
  212. setStockInLine(
  213. (prev) =>
  214. prev.map((p) =>
  215. p.id === oldId ? (res.entity as StockInLine) : p,
  216. ) as StockInLine[],
  217. );
  218. setBtnIsLoading(false);
  219. // do post directly to test
  220. // openStartModal();
  221. }, 200);
  222. },
  223. [setStockInLine],
  224. );
  225. const fetchQcDefaultValue = useCallback(async (stockInLineId: GridRowId) => {
  226. return await fetchQcResult(stockInLineId as number);
  227. }, []);
  228. const handleQC = useCallback(
  229. (id: GridRowId, params: any) => async () => {
  230. setBtnIsLoading(true);
  231. setRowModesModel((prev) => ({
  232. ...prev,
  233. [id]: { mode: GridRowModes.View },
  234. }));
  235. const qcResult = await fetchQcDefaultValue(id);
  236. console.log(params.row);
  237. console.log(qcResult);
  238. setModalInfo({
  239. ...params.row,
  240. qcResult: qcResult,
  241. });
  242. // set default values
  243. setTimeout(() => {
  244. // open qc modal
  245. console.log("delayed");
  246. openQcModal();
  247. setBtnIsLoading(false);
  248. }, 200);
  249. },
  250. [fetchQcDefaultValue, openQcModal],
  251. );
  252. const [newOpen, setNewOpen] = useState(false);
  253. const stockInLineId = searchParams.get("stockInLineId");
  254. const closeNewModal = useCallback(() => {
  255. const newParams = new URLSearchParams(searchParams.toString());
  256. newParams.delete("stockInLineId"); // Remove the parameter
  257. router.replace(`${pathname}?${newParams.toString()}`);
  258. fetchPoDetail(itemDetail.purchaseOrderId.toString());
  259. setTimeout(() => {
  260. setNewOpen(false); // Close the modal first
  261. }, 300); // Add a delay to avoid immediate re-trigger of useEffect
  262. }, [searchParams, pathname, router]);
  263. // Open modal
  264. const openNewModal = useCallback(() => {
  265. setNewOpen(true);
  266. }, []);
  267. // Button handler to update the URL and open the modal
  268. const handleNewQC = useCallback(
  269. (id: GridRowId, params: any) => async () => {
  270. // console.log(id)
  271. // console.log(params)
  272. setBtnIsLoading(true);
  273. setRowModesModel((prev) => ({
  274. ...prev,
  275. [id]: { mode: GridRowModes.View },
  276. }));
  277. const qcResult = await fetchQcDefaultValue(id);
  278. setModalInfo({
  279. ...params.row,
  280. qcResult: qcResult,
  281. receivedQty: itemDetail.receivedQty,
  282. });
  283. setTimeout(() => {
  284. const newParams = new URLSearchParams(searchParams.toString());
  285. newParams.set("stockInLineId", id.toString()); // Ensure `set` to avoid duplicates
  286. router.replace(`${pathname}?${newParams.toString()}`);
  287. console.log("hello")
  288. openNewModal()
  289. setBtnIsLoading(false);
  290. }, 200);
  291. },
  292. [fetchQcDefaultValue, openNewModal, pathname, router, searchParams]
  293. );
  294. // Open modal if `stockInLineId` exists in the URL
  295. useEffect(() => {
  296. if (stockInLineId) {
  297. console.log("heeloo")
  298. console.log(stockInLineId)
  299. handleNewQC(stockInLineId, apiRef.current.getRow(stockInLineId));
  300. }
  301. }, [stockInLineId, newOpen, handleNewQC, apiRef]);
  302. const handleEscalation = useCallback(
  303. (id: GridRowId, params: any) => () => {
  304. // setBtnIsLoading(true);
  305. setRowModesModel((prev) => ({
  306. ...prev,
  307. [id]: { mode: GridRowModes.View },
  308. }));
  309. setModalInfo(params.row);
  310. setTimeout(() => {
  311. // open qc modal
  312. console.log("delayed");
  313. openEscalationModal();
  314. // setBtnIsLoading(false);
  315. }, 200);
  316. },
  317. [openEscalationModal],
  318. );
  319. const handleReject = useCallback(
  320. (id: GridRowId, params: any) => () => {
  321. setRowModesModel((prev) => ({
  322. ...prev,
  323. [id]: { mode: GridRowModes.View },
  324. }));
  325. setModalInfo(params.row);
  326. setTimeout(() => {
  327. // open stock in modal
  328. // openPutAwayModal();
  329. // return the record with its status as pending
  330. // update layout
  331. console.log("delayed");
  332. openRejectModal();
  333. // printQrcode(params.row);
  334. }, 200);
  335. },
  336. [openRejectModal],
  337. );
  338. const handleStockIn = useCallback(
  339. (id: GridRowId, params: any) => () => {
  340. // setBtnIsLoading(true);
  341. setRowModesModel((prev) => ({
  342. ...prev,
  343. [id]: { mode: GridRowModes.View },
  344. }));
  345. setModalInfo(params.row);
  346. setTimeout(() => {
  347. // open stock in modal
  348. openStockInModal();
  349. // return the record with its status as pending
  350. // update layout
  351. console.log("delayed");
  352. // setBtnIsLoading(false);
  353. }, 200);
  354. },
  355. [openStockInModal],
  356. );
  357. const handlePutAway = useCallback(
  358. (id: GridRowId, params: any) => () => {
  359. // setBtnIsLoading(true);
  360. setRowModesModel((prev) => ({
  361. ...prev,
  362. [id]: { mode: GridRowModes.View },
  363. }));
  364. setModalInfo(params.row);
  365. setTimeout(() => {
  366. // open stock in modal
  367. openPutAwayModal();
  368. // return the record with its status as pending
  369. // update layout
  370. console.log("delayed");
  371. // setBtnIsLoading(false);
  372. }, 200);
  373. },
  374. [openPutAwayModal],
  375. );
  376. const printQrcode = useCallback(
  377. async (row: any) => {
  378. setBtnIsLoading(true);
  379. console.log(row.id);
  380. const postData = { stockInLineIds: [row.id] };
  381. // const postData = { stockInLineIds: [42,43,44] };
  382. const response = await fetchPoQrcode(postData);
  383. if (response) {
  384. console.log(response);
  385. downloadFile(new Uint8Array(response.blobValue), response.filename!);
  386. }
  387. setBtnIsLoading(false);
  388. },
  389. [],
  390. );
  391. const getButtonSx = (status : string) => {
  392. let btnSx = {label:"", color:""};
  393. switch (status) {
  394. case "received": btnSx = {label: t("putaway processing"), color:"secondary.main"}; break;
  395. case "rejected":
  396. case "completed": btnSx = {label: t("view stockin"), color:"info.main"}; break;
  397. default: btnSx = {label: t("qc processing"), color:"success.main"};
  398. }
  399. return btnSx
  400. };
  401. // const handleQrCode = useCallback(
  402. // (id: GridRowId, params: any) => () => {
  403. // setRowModesModel((prev) => ({
  404. // ...prev,
  405. // [id]: { mode: GridRowModes.View },
  406. // }));
  407. // setModalInfo(params.row);
  408. // setTimeout(() => {
  409. // // open stock in modal
  410. // // openPutAwayModal();
  411. // // return the record with its status as pending
  412. // // update layout
  413. // console.log("delayed");
  414. // printQrcode(params.row);
  415. // }, 200);
  416. // },
  417. // [printQrcode],
  418. // );
  419. const columns = useMemo<GridColDef[]>(
  420. () => [
  421. // {
  422. // field: "itemNo",
  423. // headerName: t("itemNo"),
  424. // width: 100,
  425. // // flex: 0.4,
  426. // },
  427. {
  428. field: "dnNo",
  429. headerName: t("dnNo"),
  430. width: 125,
  431. // renderCell: () => {
  432. // return <>DN0000001</>
  433. // }
  434. // flex: 0.4,
  435. },
  436. {
  437. field: "dnDate",
  438. headerName: t("dnDate"),
  439. width: 125,
  440. renderCell: (params) => {
  441. console.log(params.row)
  442. // return <>07/08/2025</>
  443. return arrayToDateString(params.value)
  444. }
  445. // flex: 0.4,
  446. },
  447. {
  448. field: "productLotNo",
  449. headerName: t("productLotNo"),
  450. width: 125,
  451. },
  452. // {
  453. // field: "itemName",
  454. // headerName: t("itemName"),
  455. // width: 100,
  456. // // flex: 0.6,
  457. // },
  458. {
  459. field: "acceptedQty",
  460. headerName: t("acceptedQty"),
  461. // flex: 0.5,
  462. width: 125,
  463. type: "number",
  464. // editable: true,
  465. // replace with tooltip + content
  466. renderCell: (params) => {
  467. return integerFormatter.format(params.value)
  468. }
  469. },
  470. {
  471. field: "uom",
  472. headerName: t("uom"),
  473. width: 120,
  474. // flex: 0.5,
  475. renderCell: (params) => {
  476. return params.row.uom.code;
  477. },
  478. },
  479. {
  480. field: "stockQty",
  481. headerName: t("Stock In Qty"),
  482. // flex: 0.5,
  483. width: 125,
  484. type: "number",
  485. // editable: true,
  486. // replace with tooltip + content
  487. renderCell: (params) => {
  488. const baseQty = (params.row.acceptedQty ?? 0) * (itemDetail.stockUom.purchaseRatioN ?? 1) / (itemDetail.stockUom.purchaseRatioD ?? 1)
  489. const stockQty = baseQty * (itemDetail.stockUom.stockRatioD ?? 1) / (itemDetail.stockUom.stockRatioN ?? 1)
  490. return decimalFormatter.format(stockQty)
  491. }
  492. },
  493. {
  494. field: "stockUom",
  495. headerName: t("Stock UoM"),
  496. width: 120,
  497. // flex: 0.5,
  498. renderCell: (params) => {
  499. return itemDetail.stockUom.stockUomCode;
  500. },
  501. },
  502. // {
  503. // field: "weight",
  504. // headerName: t("weight"),
  505. // width: 120,
  506. // // flex: 0.5,
  507. // renderCell: (params) => {
  508. // const weight = calculateWeight(
  509. // params.row.acceptedQty,
  510. // params.row.uom,
  511. // );
  512. // const weightUnit = returnWeightUnit(params.row.uom);
  513. // return `${decimalFormatter.format(weight)} ${weightUnit}`;
  514. // },
  515. // },
  516. {
  517. field: "status",
  518. headerName: t("Status"),
  519. width: 140,
  520. // flex: 0.5,
  521. renderCell: (params) => {
  522. return t(`${params.row.status}`);
  523. },
  524. },
  525. {
  526. field: "actions",
  527. type: "actions",
  528. // headerName: `${t("start")} | ${t("qc")} | ${t("escalation")} | ${t(
  529. // "stock in",
  530. // )} | ${t("putaway")} | ${t("delete")}`,
  531. headerName: "動作",
  532. // headerName: "start | qc | escalation | stock in | putaway | delete",
  533. width: 200,
  534. // flex: 2,
  535. cellClassName: "actions",
  536. getActions: (params) => {
  537. // console.log(params.row.status);
  538. const status = params.row.status.toLowerCase();
  539. const btnSx = getButtonSx(status);
  540. // console.log(stockInLineStatusMap[status]);
  541. // console.log(session?.user?.abilities?.includes("APPROVAL"));
  542. return [
  543. <GridActionsCellItem
  544. icon={<Button variant="contained" sx={{ width: '150px', backgroundColor: btnSx.color }}>
  545. {btnSx.label}</Button>}
  546. label="start"
  547. sx={{
  548. // color: "primary.main",
  549. // marginRight: 1,
  550. }}
  551. // disabled={!(stockInLineStatusMap[status] === 0)}
  552. // set _isNew to false after posting
  553. // or check status
  554. onClick={handleNewQC(params.row.id, params)}
  555. color="inherit"
  556. key="edit"
  557. />,
  558. // <GridActionsCellItem
  559. // icon={<Button variant="contained">{t("putawayBtn")}</Button>}
  560. // label="start"
  561. // sx={{
  562. // color: "primary.main",
  563. // // marginRight: 1,
  564. // }}
  565. // // disabled={!(stockInLineStatusMap[status] === 0)}
  566. // // set _isNew to false after posting
  567. // // or check status
  568. // onClick={handleStart(params.row.id, params)}
  569. // color="inherit"
  570. // key="edit"
  571. // />,
  572. // <GridActionsCellItem
  573. // icon={<Button variant="contained">{t("qc processing")}</Button>}
  574. // label="start"
  575. // sx={{
  576. // color: "primary.main",
  577. // // marginRight: 1,
  578. // }}
  579. // disabled={!(stockInLineStatusMap[status] === 0)}
  580. // // set _isNew to false after posting
  581. // // or check status
  582. // onClick={handleStart(params.row.id, params)}
  583. // color="inherit"
  584. // key="edit"
  585. // />,
  586. // <GridActionsCellItem
  587. // icon={<FactCheckIcon />}
  588. // label="qc"
  589. // sx={{
  590. // color: "primary.main",
  591. // // marginRight: 1,
  592. // }}
  593. // disabled={
  594. // // stockInLineStatusMap[status] === 9 ||
  595. // stockInLineStatusMap[status] < 1
  596. // }
  597. // // set _isNew to false after posting
  598. // // or check status
  599. // onClick={handleQC(params.row.id, params)}
  600. // color="inherit"
  601. // key="edit"
  602. // />,
  603. // <GridActionsCellItem
  604. // icon={<NotificationImportantIcon />}
  605. // label="escalation"
  606. // sx={{
  607. // color: "primary.main",
  608. // // marginRight: 1,
  609. // }}
  610. // disabled={
  611. // stockInLineStatusMap[status] === 9 ||
  612. // stockInLineStatusMap[status] <= 0 ||
  613. // stockInLineStatusMap[status] >= 5
  614. // }
  615. // // set _isNew to false after posting
  616. // // or check status
  617. // onClick={handleEscalation(params.row.id, params)}
  618. // color="inherit"
  619. // key="edit"
  620. // />,
  621. // <GridActionsCellItem
  622. // icon={<ShoppingCartIcon />}
  623. // label="stockin"
  624. // sx={{
  625. // color: "primary.main",
  626. // // marginRight: 1,
  627. // }}
  628. // disabled={
  629. // stockInLineStatusMap[status] === 9 ||
  630. // stockInLineStatusMap[status] <= 2 ||
  631. // stockInLineStatusMap[status] >= 7 ||
  632. // (stockInLineStatusMap[status] >= 3 &&
  633. // stockInLineStatusMap[status] <= 5 &&
  634. // !session?.user?.abilities?.includes("APPROVAL"))
  635. // }
  636. // // set _isNew to false after posting
  637. // // or check status
  638. // onClick={handleStockIn(params.row.id, params)}
  639. // color="inherit"
  640. // key="edit"
  641. // />,
  642. // <GridActionsCellItem
  643. // icon={<ShoppingCartIcon />}
  644. // label="putaway"
  645. // sx={{
  646. // color: "primary.main",
  647. // // marginRight: 1,
  648. // }}
  649. // disabled={
  650. // stockInLineStatusMap[status] === 9 ||
  651. // stockInLineStatusMap[status] < 7
  652. // }
  653. // // set _isNew to false after posting
  654. // // or check status
  655. // onClick={handlePutAway(params.row.id, params)}
  656. // color="inherit"
  657. // key="edit"
  658. // />,
  659. // // <GridActionsCellItem
  660. // // icon={<QrCodeIcon />}
  661. // // label="putaway"
  662. // // sx={{
  663. // // color: "primary.main",
  664. // // // marginRight: 1,
  665. // // }}
  666. // // disabled={stockInLineStatusMap[status] === 9 || stockInLineStatusMap[status] !== 8}
  667. // // // set _isNew to false after posting
  668. // // // or check status
  669. // // onClick={handleQrCode(params.row.id, params)}
  670. // // color="inherit"
  671. // // key="edit"
  672. // // />,
  673. // <GridActionsCellItem
  674. // icon={
  675. // stockInLineStatusMap[status] >= 1 ? (
  676. // <DoDisturbIcon />
  677. // ) : (
  678. // <DeleteIcon />
  679. // )
  680. // }
  681. // label="Delete"
  682. // sx={{
  683. // color: "error.main",
  684. // }}
  685. // disabled={
  686. // stockInLineStatusMap[status] >= 7 &&
  687. // stockInLineStatusMap[status] <= 9
  688. // }
  689. // onClick={
  690. // stockInLineStatusMap[status] === 0
  691. // ? handleDelete(params.row.id)
  692. // : handleReject(params.row.id, params)
  693. // }
  694. // color="inherit"
  695. // key="edit"
  696. // />,
  697. ];
  698. },
  699. },
  700. ],
  701. [t, handleStart, handleQC, handleEscalation, session?.user?.abilities, handleStockIn, handlePutAway, handleDelete, handleReject, itemDetail],
  702. );
  703. const addRow = useCallback(() => {
  704. console.log(itemDetail);
  705. const newEntry = {
  706. id: Date.now(),
  707. _isNew: true,
  708. itemId: itemDetail.itemId,
  709. purchaseOrderId: itemDetail.purchaseOrderId,
  710. purchaseOrderLineId: itemDetail.id,
  711. itemNo: itemDetail.itemNo,
  712. itemName: itemDetail.itemName,
  713. acceptedQty: itemDetail.qty - currQty, // this bug
  714. uom: itemDetail.uom,
  715. status: "draft",
  716. };
  717. setEntries((e) => [...e, newEntry]);
  718. setRowModesModel((model) => ({
  719. ...model,
  720. [getRowId(newEntry)]: {
  721. mode: GridRowModes.Edit,
  722. // fieldToFocus: "projectId",
  723. },
  724. }));
  725. }, [currQty, getRowId, itemDetail]);
  726. const validation = useCallback(
  727. (
  728. newRow: GridRowModel<StockInLineRow>,
  729. // rowModel: GridRowSelectionModel
  730. ): StockInLineEntryError | undefined => {
  731. const error: StockInLineEntryError = {};
  732. console.log(newRow);
  733. console.log(currQty);
  734. if (newRow.acceptedQty && newRow.acceptedQty > itemDetail.qty) {
  735. error["acceptedQty"] = t("qty cannot be greater than remaining qty");
  736. }
  737. return Object.keys(error).length > 0 ? error : undefined;
  738. },
  739. [currQty, itemDetail.qty, t],
  740. );
  741. const processRowUpdate = useCallback(
  742. (
  743. newRow: GridRowModel<StockInLineRow>,
  744. originalRow: GridRowModel<StockInLineRow>,
  745. ) => {
  746. const errors = validation(newRow); // change to validation
  747. if (errors) {
  748. throw new ProcessRowUpdateError(
  749. originalRow,
  750. "validation error",
  751. errors,
  752. );
  753. }
  754. const { _isNew, _error, ...updatedRow } = newRow;
  755. const rowToSave = {
  756. ...updatedRow,
  757. } satisfies StockInLineRow;
  758. const newEntries = entries.map((e) =>
  759. getRowId(e) === getRowId(originalRow) ? rowToSave : e,
  760. );
  761. setStockInLine(newEntries as StockInLine[]);
  762. console.log("triggered");
  763. setEntries(newEntries);
  764. //update remaining qty
  765. const total = newEntries.reduce(
  766. (acc, curr) => acc + (curr.acceptedQty || 0),
  767. 0,
  768. );
  769. setCurrQty(total);
  770. return rowToSave;
  771. },
  772. [validation, entries, setStockInLine, getRowId],
  773. );
  774. const onProcessRowUpdateError = useCallback(
  775. (updateError: ProcessRowUpdateError) => {
  776. const errors = updateError.errors;
  777. const oldRow = updateError.row;
  778. apiRef.current.updateRows([{ ...oldRow, _error: errors }]);
  779. },
  780. [apiRef],
  781. );
  782. const footer = (
  783. <>
  784. {/* <Box display="flex" gap={2} alignItems="center">
  785. <Button
  786. disableRipple
  787. variant="outlined"
  788. startIcon={<Add />}
  789. disabled={itemDetail.qty - currQty <= 0}
  790. onClick={addRow}
  791. size="small"
  792. >
  793. {t("Record pol")}
  794. </Button>
  795. </Box> */}
  796. </>
  797. );
  798. return (
  799. <>
  800. <StyledDataGrid
  801. getRowId={getRowId}
  802. apiRef={apiRef}
  803. autoHeight
  804. sx={{
  805. "--DataGrid-overlayHeight": "100px",
  806. ".MuiDataGrid-row .MuiDataGrid-cell.hasError": {
  807. border: "1px solid",
  808. borderColor: "error.main",
  809. },
  810. ".MuiDataGrid-row .MuiDataGrid-cell.hasWarning": {
  811. border: "1px solid",
  812. borderColor: "warning.main",
  813. },
  814. }}
  815. disableColumnMenu
  816. editMode="row"
  817. rows={entries}
  818. rowModesModel={rowModesModel}
  819. onRowModesModelChange={setRowModesModel}
  820. processRowUpdate={processRowUpdate}
  821. onProcessRowUpdateError={onProcessRowUpdateError}
  822. columns={columns}
  823. isCellEditable={(params) => {
  824. const status = params.row.status.toLowerCase();
  825. return (
  826. stockInLineStatusMap[status] >= 0 ||
  827. stockInLineStatusMap[status] <= 1
  828. );
  829. }}
  830. getCellClassName={(params: GridCellParams<StockInLineRow>) => {
  831. let classname = "";
  832. if (params.row._error) {
  833. classname = "hasError";
  834. }
  835. return classname;
  836. }}
  837. slots={{
  838. footer: FooterToolbar,
  839. noRowsOverlay: NoRowsOverlay,
  840. }}
  841. slotProps={{
  842. footer: { child: footer },
  843. }}
  844. />
  845. {modalInfo !== undefined && (
  846. <>
  847. <PoQcStockInModalVer2
  848. // setRows={setRows}
  849. setEntries={setEntries}
  850. setStockInLine={setStockInLine}
  851. setItemDetail={setModalInfo}
  852. qc={qc}
  853. warehouse={warehouse}
  854. open={newOpen}
  855. onClose={closeNewModal}
  856. itemDetail={modalInfo}
  857. />
  858. </>
  859. )
  860. }
  861. {modalInfo !== undefined && (
  862. <>
  863. <PoQcStockInModal
  864. type={"qc"}
  865. // setRows={setRows}
  866. setEntries={setEntries}
  867. setStockInLine={setStockInLine}
  868. setItemDetail={setModalInfo}
  869. qc={qc}
  870. open={qcOpen}
  871. onClose={closeQcModal}
  872. itemDetail={modalInfo}
  873. />
  874. </>
  875. )}
  876. {modalInfo !== undefined && (
  877. <>
  878. <PoQcStockInModal
  879. type={"escalation"}
  880. // setRows={setRows}
  881. setEntries={setEntries}
  882. setStockInLine={setStockInLine}
  883. setItemDetail={setModalInfo}
  884. // qc={qc}
  885. open={escalOpen}
  886. onClose={closeEscalationModal}
  887. itemDetail={modalInfo}
  888. />
  889. </>
  890. )}
  891. {modalInfo !== undefined && (
  892. <>
  893. <PoQcStockInModal
  894. type={"reject"}
  895. // setRows={setRows}
  896. setEntries={setEntries}
  897. setStockInLine={setStockInLine}
  898. setItemDetail={setModalInfo}
  899. // qc={qc}
  900. open={rejectOpen}
  901. onClose={closeRejectModal}
  902. itemDetail={modalInfo}
  903. />
  904. </>
  905. )}
  906. {modalInfo !== undefined && (
  907. <>
  908. <PoQcStockInModal
  909. type={"stockIn"}
  910. // setRows={setRows}
  911. setEntries={setEntries}
  912. setStockInLine={setStockInLine}
  913. // qc={qc}
  914. setItemDetail={setModalInfo}
  915. open={stockInOpen}
  916. onClose={closeStockInModal}
  917. itemDetail={modalInfo}
  918. />
  919. </>
  920. )}
  921. {modalInfo !== undefined && (
  922. <>
  923. <PoQcStockInModal
  924. type={"putaway"}
  925. // setRows={setRows}
  926. setEntries={setEntries}
  927. setStockInLine={setStockInLine}
  928. setItemDetail={setModalInfo}
  929. open={putAwayOpen}
  930. warehouse={warehouse}
  931. onClose={closePutAwayModal}
  932. itemDetail={modalInfo}
  933. />
  934. </>
  935. )}
  936. </>
  937. );
  938. }
  939. const NoRowsOverlay: React.FC = () => {
  940. const { t } = useTranslation("home");
  941. return (
  942. <Box
  943. display="flex"
  944. justifyContent="center"
  945. alignItems="center"
  946. height="100%"
  947. >
  948. <Typography variant="caption">{t("Add some entries!")}</Typography>
  949. </Box>
  950. );
  951. };
  952. const FooterToolbar: React.FC<FooterPropsOverrides> = ({ child }) => {
  953. return <GridToolbarContainer sx={{ p: 2 }}>{child}</GridToolbarContainer>;
  954. };
  955. export default PoInputGrid;