FPSMS-frontend
25'ten fazla konu seçemezsiniz Konular bir harf veya rakamla başlamalı, kısa çizgiler ('-') içerebilir ve en fazla 35 karakter uzunluğunda olabilir.
 
 
 

192 satır
7.2 KiB

  1. "use client";
  2. import { useCallback, useEffect, useMemo, useState } from "react";
  3. import { useRouter, useSearchParams } from "next/navigation";
  4. import {
  5. FormProvider,
  6. SubmitErrorHandler,
  7. SubmitHandler,
  8. useForm,
  9. } from "react-hook-form";
  10. import { deleteDialog } from "../Swal/CustomAlerts";
  11. import { Box, Button, Grid, Stack, Tab, Tabs, TabsProps, Typography } from "@mui/material";
  12. import { Check, Close, EditNote } from "@mui/icons-material";
  13. import { useGridApiRef } from "@mui/x-data-grid";
  14. import {CreateItemInputs, saveItem} from "@/app/api/settings/item/actions";
  15. import {saveItemQcChecks} from "@/app/api/settings/qcCheck/actions";
  16. import {useTranslation} from "react-i18next/index";
  17. import {ItemQc} from "@/app/api/settings/item";
  18. type Props = {
  19. isEditMode: boolean;
  20. // type: TypeEnum;
  21. defaultValues: Partial<CreateItemInputs> | undefined;
  22. qcChecks: ItemQc[]
  23. };
  24. const CreateItem: React.FC<Props> = ({
  25. isEditMode,
  26. // type,
  27. defaultValues,
  28. qcChecks
  29. }) => {
  30. // console.log(type)
  31. const apiRef = useGridApiRef();
  32. const params = useSearchParams()
  33. console.log(params.get("id"))
  34. const [serverError, setServerError] = useState<String>("");
  35. const [tabIndex, setTabIndex] = useState(0);
  36. const { t } = useTranslation();
  37. const router = useRouter();
  38. const title = "Product / Material"
  39. const [mode, redirPath] = useMemo(() => {
  40. // var typeId = TypeEnum.CONSUMABLE_ID
  41. var title = "";
  42. var mode = "";
  43. var redirPath = "";
  44. // if (type === TypeEnum.MATERIAL) {
  45. // typeId = TypeEnum.MATERIAL_ID
  46. // title = "Material";
  47. // redirPath = "/settings/material";
  48. // }
  49. // if (type === TypeEnum.PRODUCT) {
  50. // typeId = TypeEnum.PRODUCT_ID
  51. title = "Rough Schedule";
  52. redirPath = "/settings/rss";
  53. // }
  54. // if (type === TypeEnum.BYPRODUCT) {
  55. // typeId = TypeEnum.BYPRODUCT_ID
  56. // title = "By-Product";
  57. // redirPath = "/settings/byProduct";
  58. // }
  59. if (isEditMode) {
  60. mode = "Edit";
  61. } else {
  62. mode = "Create";
  63. }
  64. return [mode, redirPath];
  65. }, [isEditMode]);
  66. // console.log(typeId)
  67. const formProps = useForm<CreateItemInputs>({
  68. defaultValues: defaultValues ? defaultValues : {
  69. },
  70. });
  71. const errors = formProps.formState.errors;
  72. const handleCancel = () => {
  73. router.replace(`/settings/product`);
  74. };
  75. const onSubmit = useCallback<SubmitHandler<CreateItemInputs & {}>>(
  76. async (data, event) => {
  77. let hasErrors = false;
  78. console.log(errors)
  79. // console.log(apiRef.current.getCellValue(2, "lowerLimit"))
  80. // apiRef.current.
  81. try {
  82. if (hasErrors) {
  83. setServerError(t("An error has occurred. Please try again later.") as String);
  84. return false;
  85. }
  86. console.log("data posted");
  87. console.log(data);
  88. const qcCheck = data.qcChecks.length > 0 ? data.qcChecks.filter((q) => data.qcChecks_active.includes(q.id!!)).map((qc) => {
  89. return {
  90. qcItemId: qc.id,
  91. instruction: qc.instruction,
  92. lowerLimit: qc.lowerLimit,
  93. upperLimit: qc.upperLimit,
  94. itemId: parseInt(params.get("id")!.toString())
  95. }
  96. }) : []
  97. const test = data.qcChecks.filter((q) => data.qcChecks_active.includes(q.id!!))
  98. // TODO:
  99. // 1. check field ( directly modify col def / check here )
  100. // 2. set error change tab index
  101. console.log(test)
  102. console.log(qcCheck)
  103. // return
  104. // do api
  105. console.log("asdad")
  106. var responseI = await saveItem(data);
  107. console.log("asdad")
  108. var responseQ = await saveItemQcChecks(qcCheck)
  109. if (responseI && responseQ) {
  110. if (!Boolean(responseI.id)) {
  111. formProps.setError(responseI.errorPosition!! as keyof CreateItemInputs, {
  112. message: responseI.message!!,
  113. type: "required",
  114. });
  115. } else if (!Boolean(responseQ.id)) {
  116. } else if (Boolean(responseI.id) && Boolean(responseQ.id)) {
  117. router.replace(redirPath);
  118. }
  119. }
  120. } catch (e) {
  121. // backend error
  122. setServerError(t("An error has occurred. Please try again later."));
  123. console.log(e);
  124. }
  125. },
  126. [apiRef, router, t]
  127. );
  128. // multiple tabs
  129. const onSubmitError = useCallback<SubmitErrorHandler<CreateItemInputs>>(
  130. (errors) => {},
  131. []
  132. );
  133. return (
  134. <>
  135. <FormProvider {...formProps}>
  136. <Stack
  137. spacing={2}
  138. component="form"
  139. onSubmit={formProps.handleSubmit(onSubmit, onSubmitError)}
  140. >
  141. <Grid>
  142. <Typography mb={2} variant="h4">
  143. {t(`${mode} ${title}`)}
  144. </Typography>
  145. </Grid>
  146. <Tabs value={tabIndex} onChange={handleTabChange} variant="scrollable">
  147. <Tab label={t("Product / Material Details")} iconPosition="end"/>
  148. <Tab label={t("Qc items")} iconPosition="end" />
  149. </Tabs>
  150. {serverError && (
  151. <Typography variant="body2" color="error" alignSelf="flex-end">
  152. {serverError}
  153. </Typography>
  154. )}
  155. {tabIndex === 0 && <ProductDetails />}
  156. {tabIndex === 1 && <QcDetails apiRef={apiRef} />}
  157. {/* {type === TypeEnum.MATERIAL && <MaterialDetails />} */}
  158. {/* {type === TypeEnum.BYPRODUCT && <ByProductDetails />} */}
  159. <Stack direction="row" justifyContent="flex-end" gap={1}>
  160. <Button
  161. name="submit"
  162. variant="contained"
  163. startIcon={<Check />}
  164. type="submit"
  165. // disabled={submitDisabled}
  166. >
  167. {isEditMode ? t("Save") as String : t("Confirm") as String}
  168. </Button>
  169. <Button
  170. variant="outlined"
  171. startIcon={<Close />}
  172. onClick={handleCancel}
  173. >
  174. {t("Cancel") as String}
  175. </Button>
  176. </Stack>
  177. </Stack>
  178. </FormProvider>
  179. </>
  180. );
  181. };
  182. export default CreateItem;