"use client"; import { PurchaseQcResult, PurchaseQCInput } from "@/app/api/po/actions"; import { Box, Card, CardContent, Checkbox, FormControl, FormControlLabel, Grid, Radio, RadioGroup, Stack, Tab, Tabs, TabsProps, TextField, Tooltip, Typography, } from "@mui/material"; import { useFormContext, Controller } from "react-hook-form"; import { useTranslation } from "react-i18next"; import StyledDataGrid from "../StyledDataGrid"; import { Dispatch, SetStateAction, useCallback, useEffect, useMemo, useState } from "react"; import { GridColDef, GridRowIdGetter, GridRowModel, useGridApiContext, GridRenderCellParams, GridRenderEditCellParams, useGridApiRef, GridRowSelectionModel, } from "@mui/x-data-grid"; import InputDataGrid from "../InputDataGrid"; import { TableRow } from "../InputDataGrid/InputDataGrid"; import TwoLineCell from "./TwoLineCell"; import QcSelect from "./QcSelect"; import { GridEditInputCell } from "@mui/x-data-grid"; import { StockInLine } from "@/app/api/po"; import { stockInLineStatusMap } from "@/app/utils/formatUtil"; import { fetchQcItemCheck, fetchQcResult } from "@/app/api/qc/actions"; import { QcItemWithChecks, QcData } from "@/app/api/qc"; import axios from "@/app/(main)/axios/axiosInstance"; import { NEXT_PUBLIC_API_URL } from "@/config/api"; import axiosInstance from "@/app/(main)/axios/axiosInstance"; import EscalationComponent from "./EscalationComponent"; import QcDataGrid from "./QCDatagrid"; import StockInFormVer2 from "./StockInFormVer2"; import { dummyEscalationHistory, dummyQCData } from "./dummyQcTemplate"; import { ModalFormInput } from "@/app/api/po/actions"; import { escape } from "lodash"; import { PanoramaSharp } from "@mui/icons-material"; import EscalationLogTable from "../DashboardPage/escalation/EscalationLogTable"; import { EscalationResult } from "@/app/api/escalation"; interface Props { itemDetail: StockInLine & { qcResult?: PurchaseQcResult[] } & { escResult?: EscalationResult[] }; qc: QcItemWithChecks[]; disabled: boolean; qcItems: QcData[] setQcItems: Dispatch> } type EntryError = | { [field in keyof QcData]?: string; } | undefined; type QcRow = TableRow, EntryError>; // fetchQcItemCheck const QcFormVer2: React.FC = ({ qc, itemDetail, disabled, qcItems, setQcItems }) => { const { t } = useTranslation("purchaseOrder"); const apiRef = useGridApiRef(); const { register, formState: { errors, defaultValues, touchedFields }, watch, control, setValue, getValues, reset, resetField, setError, clearErrors, } = useFormContext(); const [tabIndex, setTabIndex] = useState(0); const [rowSelectionModel, setRowSelectionModel] = useState(); const [escalationHistory, setEscalationHistory] = useState(dummyEscalationHistory); // const [qcResult, setQcResult] = useState(); const qcAccept = watch("qcAccept"); const qcDecision = watch("qcDecision"); //WIP const qcResult = watch("qcResult"); console.log(qcResult); // const [qcAccept, setQcAccept] = useState(true); // const [qcItems, setQcItems] = useState(dummyQCData) const column = useMemo( () => [ { field: "escalation", headerName: t("escalation"), flex: 1, }, { field: "supervisor", headerName: t("supervisor"), flex: 1, }, ], [] ) const handleTabChange = useCallback>( (_e, newValue) => { setTabIndex(newValue); }, [], ); //// validate form const accQty = watch("acceptQty"); const validateForm = useCallback(() => { if (qcDecision == 1) { if (accQty > itemDetail.acceptedQty) { setError("acceptQty", { message: `${t("acceptQty must not greater than")} ${ itemDetail.acceptedQty }`, type: "required", }); } if (accQty < 1) { setError("acceptQty", { message: t("minimal value is 1"), type: "required", }); } if (isNaN(accQty)) { setError("acceptQty", { message: t("value must be a number"), type: "required", }); } } }, [accQty, qcDecision]); useEffect(() => { clearErrors(); validateForm(); }, [clearErrors, validateForm]); const columns = useMemo( () => [ { field: "escalation", headerName: t("escalation"), flex: 1, }, { field: "supervisor", headerName: t("supervisor"), flex: 1, }, ], [], ); /// validate datagrid const validation = useCallback( (newRow: GridRowModel): EntryError => { const error: EntryError = {}; // const { qcItemId, failQty } = newRow; return Object.keys(error).length > 0 ? error : undefined; }, [], ); function BooleanEditCell(params: GridRenderEditCellParams) { const apiRef = useGridApiContext(); const { id, field, value } = params; const handleChange = (e: React.ChangeEvent) => { apiRef.current.setEditCellValue({ id, field, value: e.target.checked }); apiRef.current.stopCellEditMode({ id, field }); // commit immediately }; return ; } const qcColumns: GridColDef[] = [ { field: "code", headerName: t("qcItem"), flex: 2, renderCell: (params) => ( {`${params.api.getRowIndexRelativeToVisibleRows(params.id) + 1}. ${params.value}`}
{params.row.name}
), }, { field: 'qcPassed', headerName: t("qcResult"), flex: 1.5, renderCell: (params) => { const currentValue = params.row; const index = params.api.getRowIndexRelativeToVisibleRows(params.id); // console.log(currentValue.row); return ( { const value = e.target.value; setQcItems((prev) => prev.map((r): QcData => (r.id === params.id ? { ...r, qcPassed: value === "true" } : r)) ); // setValue(`qcResult.${index}.qcPassed`, value == "true"); }} name={`qcPassed-${params.id}`} > } label="合格" disabled={disabled || itemDetail.status == "escalated"} sx={{ color: currentValue.qcPassed === true ? "green" : "inherit", "& .Mui-checked": {color: "green"} }} /> } label="不合格" disabled={disabled || itemDetail.status == "escalated"} sx={{ color: currentValue.qcPassed === false ? "red" : "inherit", "& .Mui-checked": {color: "red"} }} /> ); }, }, { field: "failQty", headerName: t("failedQty"), flex: 1, // editable: true, renderCell: (params) => ( { const v = e.target.value; const next = v === '' ? undefined : Number(v); if (Number.isNaN(next)) return; setQcItems((prev) => prev.map((r) => (r.id === params.id ? { ...r, failQty: next } : r)) ); // setValue(`failQty`,failQty); }} onClick={(e) => e.stopPropagation()} onMouseDown={(e) => e.stopPropagation()} onKeyDown={(e) => e.stopPropagation()} inputProps={{ min: 0 }} sx={{ width: '100%' }} /> ), }, { field: "remarks", headerName: t("remarks"), flex: 2, renderCell: (params) => ( { const remarks = e.target.value; // const next = v === '' ? undefined : Number(v); // if (Number.isNaN(next)) return; setQcItems((prev) => prev.map((r) => (r.id === params.id ? { ...r, remarks: remarks } : r)) ); }} // {...register(`qcResult.${params.row.rowIndex}.remarks`, { // required: "remarks required!", // })} onClick={(e) => e.stopPropagation()} onMouseDown={(e) => e.stopPropagation()} onKeyDown={(e) => e.stopPropagation()} inputProps={{ min: 0 }} sx={{ width: '100%' }} /> ), }, ] // Set initial value for acceptQty useEffect(() => { if (itemDetail?.demandQty > 0) { //!== undefined) { setValue("acceptQty", itemDetail.demandQty); // THIS NEED TO UPDATE TO NOT USE DEMAND QTY } else { setValue("acceptQty", itemDetail?.acceptedQty); } }, [itemDetail?.demandQty, itemDetail?.acceptedQty, setValue]); // const [openCollapse, setOpenCollapse] = useState(false) const [isCollapsed, setIsCollapsed] = useState(true); const onFailedOpenCollapse = useCallback((qcItems: PurchaseQcResult[]) => { const isFailed = qcItems.some((qc) => !qc.qcPassed) console.log(isFailed) if (isFailed) { setIsCollapsed(true) } else { setIsCollapsed(false) } }, []) // const handleRadioChange = useCallback((event: React.ChangeEvent) => { // const value = event.target.value === 'true'; // setValue("qcAccept", value); // }, [setValue]); useEffect(() => { console.log("ItemDetail in QC:", itemDetail); console.log("Qc Result in QC:", qcResult); }, [itemDetail]); const setQcDecision = (status : string | undefined) => { const param = status?.toLowerCase(); if (param !== undefined && param !== null) { if (param == "completed") { return 1; } else if (param == "rejected") { return 2; } else if (param == "escalated") { return 3; } else { return undefined; } } else { return undefined; } } useEffect(() => { // onFailedOpenCollapse(qcItems) // This function is no longer needed }, [qcItems]); return ( <> {tabIndex == 0 && ( <> Group A - 急凍貨類 (QCA1-MEAT01) 品檢類型:IQC 記錄探測溫度的時間,請在1小時内完成卸貨盤點入庫,以保障食品安全
監察方法:目視檢查、嗅覺檢查和使用適當的食物溫度計,檢查食物溫度是否符合指標
{/* apiRef={apiRef} columns={qcColumns} _formKey="qcResult" validateRow={validation} /> */} 0 ? qcResult : qcItems} // rows={disabled? qcResult:qcItems} autoHeight />
)} {tabIndex == 1 && ( <> {/* */} {/* {t("Escalation Info")} */} {/* { setRowSelectionModel(newRowSelectionModel); }} /> */} )} ( { const value = e.target.value.toString();// === 'true'; if (value != "1" && Boolean(errors.acceptQty)) { // if (!value && Boolean(errors.acceptQty)) { setValue("acceptQty", itemDetail.acceptedQty ?? 0); } field.onChange(value); }} > } label="接受" /> } sx={{"& .Mui-checked": {color: "red"}}} label="不接受" /> } sx={{"& .Mui-checked": {color: "blue"}}} label="上報品檢結果" /> )} /> {qcDecision == 3 && ( // {!qcAccept && ( )} {/* {qcAccept && {t("Escalation Result")} } */}
); }; export default QcFormVer2;