FPSMS-frontend
Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.
 
 
 

219 linhas
6.8 KiB

  1. "use client";
  2. import { ModalFormInput, PurchaseQCInput, PurchaseQcResult, StockInInput, StockInLineEntry, updateStockInLine } from "@/app/api/po/actions";
  3. import { Box, Button, Modal, ModalProps, Stack } from "@mui/material";
  4. import { Dispatch, SetStateAction, useCallback, useEffect, useMemo, useState } from "react";
  5. import { FormProvider, SubmitHandler, useForm } from "react-hook-form";
  6. import { useTranslation } from "react-i18next";
  7. import QcForm from "./QcForm";
  8. import { QcItemWithChecks } from "@/app/api/qc";
  9. import { Check, CurrencyYuanRounded } from "@mui/icons-material";
  10. import { StockInLine } from "@/app/api/po";
  11. import { useSearchParams } from "next/navigation";
  12. import { StockInLineRow } from "./PoInputGrid";
  13. import EscalationForm from "./EscalationForm";
  14. import StockInForm from "./StockInForm";
  15. import PutawayForm from "./PutawayForm";
  16. import { stockInLineStatusMap } from "@/app/utils/formatUtil";
  17. interface CommonProps extends Omit<ModalProps, "children"> {
  18. setEntries: Dispatch<SetStateAction<StockInLineRow[]>>
  19. itemDetail: StockInLine & {qcResult?: PurchaseQcResult[]};
  20. qc?: QcItemWithChecks[];
  21. warehouse?: any[];
  22. type: "qc" | "stockIn" | "escalation" | "putaway"
  23. }
  24. interface QcProps extends CommonProps {
  25. qc: QcItemWithChecks[];
  26. type: "qc"
  27. }
  28. interface StockInProps extends CommonProps {
  29. // naming
  30. type: "stockIn"
  31. }
  32. interface PutawayProps extends CommonProps {
  33. // naming
  34. // warehouse: any[];
  35. warehouse: any[];
  36. type: "putaway"
  37. }
  38. interface EscalationProps extends CommonProps {
  39. // naming
  40. type: "escalation"
  41. }
  42. type Props = QcProps | StockInProps | EscalationProps | PutawayProps;
  43. const style = {
  44. position: "absolute",
  45. top: "50%",
  46. left: "50%",
  47. transform: "translate(-50%, -50%)",
  48. bgcolor: "background.paper",
  49. pt: 5,
  50. px: 5,
  51. pb: 10,
  52. width: { xs: "80%", sm: "80%", md: "80%" },
  53. };
  54. const PoQcStockInModal: React.FC<Props> = ({
  55. type,
  56. setEntries,
  57. open,
  58. onClose,
  59. itemDetail,
  60. qc,
  61. warehouse,
  62. }) => {
  63. console.log(itemDetail)
  64. const [serverError, setServerError] = useState("");
  65. const { t } = useTranslation();
  66. const params = useSearchParams()
  67. console.log(params.get("id"))
  68. const [defaultValues, setDefaultValues] = useState({});
  69. const defaultValue = useMemo(() => {
  70. // switch (type) {
  71. // case "qc":
  72. // return {qcResult: itemDetail.qcResult}
  73. // }
  74. // return {}
  75. return {...itemDetail}
  76. }, [])
  77. // const formProps = useForm<ModalFormInput>({
  78. // defaultValues: defaultValues ? defaultValues : {},
  79. // });
  80. const formProps = useForm<ModalFormInput>({
  81. defaultValues: defaultValue
  82. });
  83. const errors = formProps.formState.errors;
  84. const closeHandler = useCallback<NonNullable<ModalProps["onClose"]>>(
  85. (...args) => {
  86. onClose?.(...args);
  87. // reset();
  88. },
  89. [onClose]
  90. );
  91. useEffect(() => {
  92. setDefaultValues({});
  93. }, []);
  94. const onSubmit = useCallback<SubmitHandler<ModalFormInput & {}>>(
  95. async (data, event) => {
  96. let hasErrors = false;
  97. console.log(errors);
  98. console.log(data);
  99. console.log(itemDetail);
  100. try {
  101. // add checking
  102. // const qty = data.sampleRate
  103. //////////////////////// modify this mess later //////////////////////
  104. var productionDate = null
  105. var acceptedQty = null
  106. if (data.productionDate && data.productionDate.length > 0) {
  107. productionDate = data.productionDate
  108. }
  109. if (data.qcResult) {
  110. acceptedQty = itemDetail.acceptedQty - data.qcResult.reduce((acc, curr) => acc + curr.failQty, 0)
  111. }
  112. const args = {
  113. id: itemDetail.id,
  114. purchaseOrderId: parseInt(params.get("id")!!),
  115. purchaseOrderLineId: itemDetail.purchaseOrderLineId,
  116. itemId: itemDetail.itemId,
  117. ...data,
  118. productionDate: productionDate,
  119. } as StockInLineEntry & ModalFormInput;
  120. //////////////////////////////////////////////////////////////////////
  121. console.log(args)
  122. // return
  123. if (hasErrors) {
  124. setServerError(t("An error has occurred. Please try again later."));
  125. return false;
  126. }
  127. const res = await updateStockInLine(args)
  128. if (Boolean(res.id)) {
  129. // update entries
  130. const newEntries = res.entity as StockInLine[]
  131. setEntries((prev) => {
  132. const updatedEntries = [...prev]; // Create a new array
  133. newEntries.forEach((item) => {
  134. const index = updatedEntries.findIndex(p => p.id === item.id);
  135. if (index !== -1) {
  136. // Update existing item
  137. updatedEntries[index] = item;
  138. } else {
  139. // Add new item
  140. updatedEntries.push(item);
  141. }
  142. });
  143. return updatedEntries; // Return the new array
  144. })
  145. // add loading
  146. closeHandler({}, "backdropClick")
  147. }
  148. console.log(res)
  149. // if (res)
  150. } catch (e) {
  151. // server error
  152. setServerError(t("An error has occurred. Please try again later."));
  153. console.log(e);
  154. }
  155. },
  156. [t, itemDetail]
  157. );
  158. const renderSubmitButton = useMemo((): Boolean => {
  159. if (itemDetail) {
  160. const status = itemDetail.status
  161. console.log(status)
  162. switch (type) {
  163. case "qc":
  164. return stockInLineStatusMap[status] === 1
  165. case "putaway":
  166. return stockInLineStatusMap[status] === 7
  167. case "stockIn":
  168. return stockInLineStatusMap[status] === 6
  169. default:
  170. return false; // Handle unexpected type
  171. }
  172. } else return false
  173. }, [type, itemDetail])
  174. useEffect(() => {
  175. console.log(renderSubmitButton)
  176. }, [renderSubmitButton])
  177. return (
  178. <>
  179. <Modal open={open} onClose={closeHandler}>
  180. <FormProvider {...formProps}>
  181. <Box
  182. sx={style}
  183. component="form"
  184. onSubmit={formProps.handleSubmit(onSubmit)}
  185. >
  186. {type === "qc" && <QcForm qc={qc} itemDetail={itemDetail} />}
  187. {type === "stockIn" && <StockInForm itemDetail={itemDetail} />}
  188. {type === "escalation" && <EscalationForm itemDetail={itemDetail} />}
  189. {type === "putaway" && <PutawayForm itemDetail={itemDetail} warehouse={warehouse} />}
  190. {renderSubmitButton ? (
  191. <Stack direction="row" justifyContent="flex-end" gap={1}>
  192. <Button
  193. name="submit"
  194. variant="contained"
  195. startIcon={<Check />}
  196. type="submit"
  197. // disabled={submitDisabled}
  198. >
  199. {t("submit")}
  200. </Button>
  201. </Stack>
  202. ) : undefined
  203. }
  204. </Box>
  205. </FormProvider>
  206. </Modal>
  207. </>
  208. );
  209. };
  210. export default PoQcStockInModal;