Non puoi selezionare più di 25 argomenti Gli argomenti devono iniziare con una lettera o un numero, possono includere trattini ('-') e possono essere lunghi fino a 35 caratteri.

373 righe
18 KiB

  1. // material-ui
  2. import {
  3. Grid, Button, Typography,
  4. Dialog, DialogTitle, DialogContent, DialogActions,
  5. FormHelperText,
  6. // TextField
  7. } from '@mui/material';
  8. import MainCard from "components/MainCard";
  9. import * as React from "react";
  10. import * as yup from 'yup';
  11. import { useEffect, useState } from "react";
  12. import * as DateUtils from 'utils/DateUtils';
  13. import * as HttpUtils from 'utils/HttpUtils';
  14. import * as UrlUtils from "utils/ApiPathConst";
  15. import * as FieldUtils from "utils/FieldUtils";
  16. import * as ComboData from "utils/ComboData";
  17. import { useNavigate } from "react-router-dom";
  18. import { useFormik } from 'formik';
  19. const LoadingComponent = Loadable(lazy(() => import('../../extra-pages/LoadingComponent')));
  20. import Loadable from 'components/Loadable';
  21. import { lazy } from 'react';
  22. import { notifyCreateSuccess } from 'utils/CommonFunction';
  23. import { useIntl } from "react-intl";
  24. import {DatePicker} from "@mui/x-date-pickers/DatePicker";
  25. import dayjs from "dayjs";
  26. import {DemoItem} from "@mui/x-date-pickers/internals/demo";
  27. import {LocalizationProvider} from "@mui/x-date-pickers/LocalizationProvider";
  28. import {AdapterDayjs} from "@mui/x-date-pickers/AdapterDayjs";
  29. // ==============================|| DASHBOARD - DEFAULT ||============================== //
  30. const OrganizationCard_loadFromUser = ({ userData, userId }) => {
  31. const intl = useIntl();
  32. const [currentUserData, setCurrentUserData] = useState(userData);
  33. const navigate = useNavigate();
  34. const [onReady, setOnReady] = useState(false);
  35. const [isFailPopUp, setIsFailPopUp] = useState(false);
  36. const [failText, setFailText] = useState("");
  37. const [errorMsg, setErrorMsg] = useState("");
  38. const [minDate] = React.useState(new Date().setDate(new Date().getDate() + 1));
  39. const [fromDate, setFromDate] = React.useState(null);
  40. const [fromDateValue, setFromDateValue] = React.useState(null);
  41. useEffect(() => {
  42. //if state data are ready and assign to different field
  43. // console.log(currentApplicationDetailData)
  44. if (Object.keys(currentUserData).length > 0) {
  45. if(DateUtils.dateValue(currentUserData.brExpiryDate)>DateUtils.dateValue(minDate)){
  46. setFromDate(currentUserData.brExpiryDate);
  47. }else{
  48. setErrorMsg("Please select a date after today.")
  49. }
  50. // setFromDate(currentUserData.brExpiryDate)
  51. setOnReady(true);
  52. }
  53. }, [currentUserData]);
  54. React.useEffect(() => {
  55. setFromDateValue(fromDate);
  56. }, [fromDate]);
  57. function displayErrorMsg(errorMsg) {
  58. return <Typography variant="errorMessage1">{errorMsg}</Typography>
  59. }
  60. const formik = useFormik({
  61. enableReinitialize: true,
  62. initialValues: currentUserData,
  63. validationSchema: yup.object().shape({
  64. enCompanyName: yup.string().max(255, displayErrorMsg(intl.formatMessage({ id: 'userRequireEnglishName' }))).required(displayErrorMsg(intl.formatMessage({ id: 'userRequireEnglishName' }))),
  65. chCompanyName: yup.string().max(255, displayErrorMsg(intl.formatMessage({ id: 'userRequireChineseName' }))).nullable(),
  66. addressLine1: yup.string().max(40).required(displayErrorMsg(intl.formatMessage({ id: 'validateAddressLine1' }))),
  67. addressLine2: yup.string().max(40).nullable(),
  68. addressLine3: yup.string().max(40).nullable(),
  69. fax_countryCode: yup.string().min(3, displayErrorMsg(intl.formatMessage({ id: 'requireDialingCode' }))).nullable(),
  70. tel_countryCode: yup.string().min(3, displayErrorMsg(intl.formatMessage({ id: 'requireDialingCode' }))),
  71. phoneNumber: yup.string().min(8, displayErrorMsg(intl.formatMessage({ id: 'requiredValidNumber' }))).required(displayErrorMsg(intl.formatMessage({ id: 'requireContactNumber' }))),
  72. faxNumber: yup.string().min(8).nullable(),
  73. brExpiryDate: yup.string().min(8).required(displayErrorMsg(intl.formatMessage({ id: 'pleaseFillInBusinessRegCertValidityDate' }))),
  74. brNo: yup.string().max(8).required(displayErrorMsg(intl.formatMessage({ id: 'pleaseFillInBusinessRegCertNumber' })))
  75. .test('checkBrNoFormat', displayErrorMsg(`${intl.formatMessage({ id: 'pleaseFillInValidBusinessRegCertNumber' })} (e.g. 12341234)`), function (value) {
  76. var brNo_pattern = /[0-9]{8}/
  77. if (value !== undefined) {
  78. if (value.match(brNo_pattern)) {
  79. return true
  80. } else {
  81. return false
  82. }
  83. }
  84. }),
  85. }),
  86. onSubmit: values => {
  87. if (values.country == null) {
  88. setErrorMsg(intl.formatMessage({ id: 'pleaseFillInCountry' }))
  89. } else {
  90. if (values.country.type == "hongKong" && values.district == null) {
  91. setErrorMsg(intl.formatMessage({ id: 'pleaseFillInDistrict' }))
  92. } else {
  93. let sentDateFrom = "";
  94. if (fromDateValue == null) {
  95. setErrorMsg(intl.formatMessage({ id: 'pleaseFillInBusinessRegCertValidityDate' }))
  96. }else{
  97. sentDateFrom = DateUtils.dateValue(fromDateValue)
  98. HttpUtils.post({
  99. url: UrlUtils.POST_ORG_SAVE_PATH,
  100. params: {
  101. id: null,
  102. primaryUserId: userId,
  103. enCompanyName: values.enCompanyName,
  104. chCompanyName: values.chCompanyName,
  105. brNo: values.brNo,
  106. brExpiryDate: sentDateFrom,
  107. enCompanyNameTemp: values.enCompanyNameTemp,
  108. chCompanyNameTemp: values.chCompanyNameTemp,
  109. brExpiryDateTemp: values.brExpiryDateTemp,
  110. contactPerson: values.contactPerson,
  111. contactTel: {
  112. countryCode: values.tel_countryCode,
  113. phoneNumber: values.phoneNumber
  114. },
  115. faxNo: {
  116. countryCode: values.fax_countryCode,
  117. faxNumber: values.faxNumber
  118. },
  119. addressTemp: {
  120. country: values.country.type,
  121. district: values.district?.type,
  122. addressLine1: values.addressLine1,
  123. addressLine2: values.addressLine2,
  124. addressLine3: values.addressLine3,
  125. }
  126. },
  127. onSuccess: function (responseData) {
  128. if (responseData.msg) {
  129. setFailText(responseData.msg);
  130. setIsFailPopUp(true);
  131. return;
  132. }
  133. navigate('/org/' + responseData.id);
  134. notifyCreateSuccess()
  135. }
  136. });
  137. }
  138. }
  139. }
  140. }
  141. });
  142. useEffect(() => {
  143. if (Object.keys(userData).length > 0) {
  144. setCurrentUserData(userData);
  145. }
  146. }, [userData]);
  147. return (
  148. <MainCard elevation={0}
  149. border={false}
  150. content={false}
  151. >
  152. {/* <div style={{ border: "solid 1px;", color: "red" }}>
  153. TODO: Error Summary
  154. {Object.values(formik.errors).map(error => (
  155. <div>{error}</div>
  156. ))}
  157. </div> */}
  158. <div style={{ padding: 24 }}>
  159. <form onSubmit={formik.handleSubmit}>
  160. {!onReady ?
  161. <LoadingComponent />
  162. :
  163. <Grid container spacing={1}>
  164. {/*top*/}
  165. <Grid item s={12} md={12} lg={12} sx={{ mb: 3 }} alignItems={"start"} justifyContent="center">
  166. <Grid item sx={{ mr: 3 }}>
  167. <Button
  168. size="large"
  169. variant="contained"
  170. type="submit"
  171. sx={{
  172. textTransform: 'capitalize',
  173. alignItems: 'end'
  174. }}
  175. >
  176. Create
  177. </Button>
  178. </Grid>
  179. </Grid>
  180. {/*top*/}
  181. <Grid item xs={12}>
  182. <FormHelperText error id="helper-text-address1-signup">
  183. <Typography variant="errorMessage1">
  184. {errorMsg}
  185. </Typography>
  186. </FormHelperText>
  187. </Grid>
  188. <Grid item xs={12} lg={4}>
  189. {FieldUtils.getTextField({
  190. label: "BR No.:",
  191. valueName: "brNo",
  192. form: formik
  193. })}
  194. </Grid>
  195. <Grid item xs={12} lg={8}></Grid>
  196. <Grid item xs={12} lg={4}>
  197. {FieldUtils.getTextField({
  198. label: FieldUtils.notNullFieldLabel("Name (Eng):"),
  199. valueName: "enCompanyName",
  200. form: formik
  201. })}
  202. </Grid>
  203. <Grid item xs={12} lg={4}>
  204. {FieldUtils.getTextField({
  205. label: "Name (Ch):",
  206. valueName: "chCompanyName",
  207. form: formik
  208. })}
  209. </Grid>
  210. <Grid item xs={12} lg={4} >
  211. <Grid container alignItems={"center"}>
  212. <Grid item xs={12} md={3} lg={3} sx={{ display: 'flex', alignItems: 'center' }}>
  213. <Typography variant="pnspsFormParagraphBold">{FieldUtils.notNullFieldLabel("Expiry Date:")}</Typography>
  214. </Grid>
  215. <Grid item xs={12} md={6} lg={6}>
  216. <LocalizationProvider dateAdapter={AdapterDayjs}>
  217. <DemoItem components={['DatePicker']}>
  218. <DatePicker
  219. id="brExpiryDate"
  220. name="brExpiryDate"
  221. // onError={Boolean(formik.errors["brExpiryDate"])}
  222. slotProps={{
  223. field: { readOnly: true, },
  224. // textField: {
  225. // helperText:formik.errors["brExpiryDate"] ? formik.errors["brExpiryDate"] : ''
  226. // },
  227. }}
  228. format="DD/MM/YYYY"
  229. // label={"Submit Date (From)"}
  230. value={fromDate == null ? null : dayjs(fromDate)}
  231. minDate={minDate == null ? null : dayjs(minDate)}
  232. // disabled={(!editMode && !createMode)}
  233. onChange={(newValue) => {
  234. setErrorMsg("")
  235. if(DateUtils.dateValue(newValue)>DateUtils.dateValue(new Date())){
  236. setFromDate(newValue);
  237. }else{
  238. setErrorMsg("Please select a date after today.")
  239. }
  240. }}
  241. />
  242. </DemoItem >
  243. </LocalizationProvider>
  244. {/* <TextField
  245. fullWidth
  246. id="brExpiryDate"
  247. name="brExpiryDate"
  248. type="date"
  249. inputProps={{ min: DateUtils.dateValue(new Date()) }}
  250. error={Boolean(formik.errors["brExpiryDate"])}
  251. helperText={formik.errors["brExpiryDate"] ? formik.errors["brExpiryDate"] : ''}
  252. onChange={formik.handleChange}
  253. value={formik.values["brExpiryDate"]}
  254. sx={{
  255. width: '100%'
  256. }}
  257. /> */}
  258. </Grid>
  259. </Grid>
  260. </Grid>
  261. <Grid item xs={12} lg={4}>
  262. {FieldUtils.getTextField({
  263. label: FieldUtils.notNullFieldLabel("Contact Person:"),
  264. valueName: "contactPerson",
  265. form: formik
  266. })}
  267. </Grid>
  268. <Grid item xs={12} lg={4}>
  269. {FieldUtils.getPhoneField({
  270. label: FieldUtils.notNullFieldLabel("Contact Tel:"),
  271. valueName: {
  272. code: "tel_countryCode",
  273. num: "phoneNumber"
  274. },
  275. form: formik
  276. })}
  277. </Grid>
  278. <Grid item xs={12} lg={4}>
  279. {FieldUtils.getPhoneField({
  280. label: "Fax No:",
  281. valueName: {
  282. code: "fax_countryCode",
  283. num: "faxNumber"
  284. },
  285. form: formik
  286. })}
  287. </Grid>
  288. <Grid item xs={12}>
  289. {FieldUtils.getAddressField({
  290. label: FieldUtils.notNullFieldLabel("Address:"),
  291. valueName: ["addressLine1", "addressLine2", "addressLine3"],
  292. form: formik
  293. })}
  294. </Grid>
  295. <Grid item xs={12} lg={12}>
  296. {FieldUtils.getComboField({
  297. label: "",
  298. valueName: "district",
  299. dataList: ComboData.district,
  300. getOptionLabel: (option) => option.type ? intl.formatMessage({ id: option.type }) : "",
  301. form: formik
  302. })}
  303. </Grid>
  304. <Grid item xs={12} lg={12}>
  305. {FieldUtils.getComboField({
  306. label: "",
  307. valueName: "country",
  308. disabled: true,
  309. dataList: ComboData.country,
  310. getOptionLabel: (option) => option.type ? intl.formatMessage({ id: option.type }) : "",
  311. form: formik
  312. })}
  313. </Grid>
  314. </Grid>
  315. }
  316. </form>
  317. </div>
  318. <div>
  319. <Dialog
  320. open={isFailPopUp}
  321. onClose={() => setIsFailPopUp(false)}
  322. PaperProps={{
  323. sx: {
  324. minWidth: '40vw',
  325. maxWidth: { xs: '90vw', s: '90vw', m: '70vw', lg: '70vw' },
  326. maxHeight: { xs: '90vh', s: '70vh', m: '70vh', lg: '60vh' }
  327. }
  328. }}
  329. >
  330. <DialogTitle><Typography variant="h3">Action Fail</Typography></DialogTitle>
  331. <DialogContent style={{ display: 'flex', }}>
  332. <Typography variant="h4" style={{ padding: '16px' }}>{failText}</Typography>
  333. </DialogContent>
  334. <DialogActions>
  335. <Button onClick={() => setIsFailPopUp(false)}><Typography variant="h5">OK</Typography></Button>
  336. </DialogActions>
  337. </Dialog>
  338. </div>
  339. </MainCard>
  340. );
  341. };
  342. export default OrganizationCard_loadFromUser;