243 lines
8.2 KiB
TypeScript
243 lines
8.2 KiB
TypeScript
// components/UserProfile.tsx
|
|
import { useParams } from 'react-router-dom';
|
|
import { useFormik } from 'formik';
|
|
import * as Yup from 'yup';
|
|
import { Dropdown } from 'primereact/dropdown';
|
|
import { Calendar } from 'primereact/calendar';
|
|
import type { ConcessionType, ConcessionValidationDto } from '../models';
|
|
import { useEffect, useState } from 'react';
|
|
import { concessionvalidationService as concessService } from '../services';
|
|
import { useNavigate } from 'react-router-dom';
|
|
import { Utils } from '../share';
|
|
//import { concessionTypeService } from '../services';
|
|
import moment from 'moment';
|
|
import { useAppSelector, useAppDispatch } from '../store/hook';
|
|
//import { type RootState } from '../store/store';
|
|
import { funThunkLoadConcessionType, funThunkLoadValidationPoint } from '../store/slice';
|
|
|
|
type RouteParams = {
|
|
id: string;
|
|
};
|
|
|
|
// 1. Set the initial form states based on the interface
|
|
export default function EditConcessionValidationApp() {
|
|
// useParams returns a partial object, so explicitly cast or type it
|
|
const { id } = useParams<RouteParams>();
|
|
const navigate = useNavigate();
|
|
const dispatch = useAppDispatch();
|
|
const conTypeList = useAppSelector(state => state.concessionTypeRE.concessionTypes);
|
|
const validationPointList = useAppSelector(state => state.concessionTypeRE.validationPoints);
|
|
|
|
console.log(" 1 get login ");
|
|
const loginUser = Utils.getLogin();
|
|
console.log(" 2 get login ");
|
|
// const dispatch = useAppDispatch();
|
|
// State elements are automatically typed based on the store schema
|
|
//const { concessionTypes } = useAppSelector((state: RootState) => state.convalidation);
|
|
const initialValues: ConcessionValidationDto =
|
|
{
|
|
id: -1,
|
|
validateDate: '',
|
|
iDate: new Date(),
|
|
concessionCard: '',
|
|
concessionHolder: '',
|
|
concessionExpiry: false,
|
|
concessionTypeId: 0,
|
|
active: true,
|
|
/*
|
|
stafflinkNo: "",
|
|
validationPointId: 0,
|
|
staffFirstName: "",
|
|
staffLastName: "",
|
|
staffEmail: "",
|
|
*/
|
|
|
|
|
|
stafflinkNo: loginUser.username ?? "",
|
|
validationPointId: loginUser.validationPointId ?? 0,
|
|
staffFirstName: loginUser.firstName,
|
|
staffLastName: loginUser.lastName,
|
|
staffEmail: loginUser.email,
|
|
|
|
|
|
|
|
};
|
|
const iid = parseInt(id ?? '0');
|
|
const [isLoading, setIsLoading] = useState<boolean>(true);
|
|
const [initialFormValues, setInitialFormValues] = useState<ConcessionValidationDto>(initialValues);
|
|
//const [conTypeList, setconTypeList] = useState<ConcessionType[]>([]);
|
|
|
|
const fetchExistingRecord = async () => {
|
|
try {
|
|
setIsLoading(true);
|
|
|
|
if (iid > 0) {
|
|
// Replace this with your actual Axios, Fetch, or SDK call
|
|
const response = await concessService.getById(iid);
|
|
if (response.statusCode == 1)
|
|
// Update state with the fetched record
|
|
setInitialFormValues(response.data);
|
|
}
|
|
} catch (error) {
|
|
|
|
console.error('Failed to fetch the record data:', error);
|
|
|
|
} finally {
|
|
|
|
setIsLoading(false);
|
|
|
|
}
|
|
};
|
|
|
|
useEffect(() => {
|
|
fetchExistingRecord();
|
|
if (conTypeList.length < 1)
|
|
dispatch(funThunkLoadValidationPoint());
|
|
if (validationPointList.length < 1)
|
|
dispatch(funThunkLoadConcessionType());
|
|
return () => {
|
|
// isMounted = false;
|
|
// dispatch(clearConcessionType());
|
|
};
|
|
}, [iid, dispatch]);
|
|
|
|
|
|
//if (concessionTypes != null)
|
|
// setconTypeList(concessionTypes);
|
|
/*
|
|
const fecthConcessionType = async () => {
|
|
try {
|
|
const vpres = await concessionTypeService.get();
|
|
if (vpres.statusCode == 1)
|
|
setconTypeList(vpres.data);
|
|
}
|
|
catch (error) {
|
|
console.error('error loading Validation Point', error);
|
|
}
|
|
};
|
|
*/
|
|
|
|
const formik = useFormik<ConcessionValidationDto>({
|
|
initialValues: initialFormValues,
|
|
enableReinitialize: true, // Ensures form updates when state fills
|
|
validationSchema: Yup.object({
|
|
concessionCard: Yup.string().required('concessionCard field cannot be blank'),
|
|
}),
|
|
onSubmit: async (data) => {
|
|
/* using redux thunk *****
|
|
***********************************************************
|
|
// 1. Dispatch and wait for the thunk to complete
|
|
const resultAction = await dispatch(updateCustomerApi({ name, email, purchaseHistory }));
|
|
|
|
// 2. Unwrap the action payload safely
|
|
if (updateCustomerApi.fulfilled.match(resultAction)) {
|
|
// The fresh server response is inside the action payload directly!
|
|
const myNewId = resultAction.payload.id;
|
|
console.log("Got the new ID immediately:", myNewId);
|
|
*************************************************************
|
|
|
|
option two
|
|
// 1. Keep your selector at the top-level of the component
|
|
const myNewId = useAppSelector((state) => state.customer.activeItem?.id);
|
|
|
|
// 2. Submit handler only triggers the mutation
|
|
const handleSubmit = (e: React.FormEvent) => {
|
|
e.preventDefault();
|
|
dispatch(triggerIdGenerationAction());
|
|
};
|
|
|
|
// 3. Effect listens for the variable to change on subsequent renders
|
|
useEffect(() => {
|
|
if (myNewId) {
|
|
console.log("State updated! Moving to next screen with ID:", myNewId);
|
|
navigate(`/receipt/${myNewId}`);
|
|
}
|
|
}, [myNewId, navigate]); // Fires automatically when myNewId changes
|
|
***************************************************************************
|
|
*/
|
|
|
|
|
|
// alert(values.description);
|
|
console.log('on submit', data);
|
|
data.validateDate = moment(data.iDate).format('YYYY-MM-DD');
|
|
const res = await concessService.save(data);
|
|
if (res.statusCode == 1)
|
|
alert('save success');
|
|
navigate(-1);
|
|
},
|
|
});
|
|
|
|
if (isLoading) {
|
|
return <div>Loading your record info...</div>;
|
|
}
|
|
|
|
|
|
// return <h1>Edit Concession Type from React Router: {id}</h1>;
|
|
return (
|
|
|
|
<form onSubmit={formik.handleSubmit} >
|
|
<label>Edit Concession Validation</label>
|
|
<div className='grid grid-cols-2 gap-2'>
|
|
<input
|
|
id="concessionCard"
|
|
name="concessionCard"
|
|
type="text"
|
|
onChange={formik.handleChange}
|
|
onBlur={formik.handleBlur}
|
|
placeholder='Card'
|
|
value={formik.values.concessionCard}
|
|
/>
|
|
{formik.touched.concessionCard && formik.errors.concessionCard ? (
|
|
<div>{formik.errors.concessionCard}</div>
|
|
) : null}
|
|
<input
|
|
id="concessionHolder"
|
|
name="concessionHolder"
|
|
type="text"
|
|
placeholder='Card Holder'
|
|
onChange={formik.handleChange}
|
|
onBlur={formik.handleBlur}
|
|
value={formik.values.concessionHolder}
|
|
/>
|
|
<Calendar value={formik.values.iDate} onChange={(e) => formik.setFieldValue('iDate', e.value)} dateFormat="dd/mm/yy" />
|
|
</div>
|
|
<div className='ml-2 mt-2'>
|
|
<input
|
|
id="concessionExpiry"
|
|
name="concessionExpiry"
|
|
type="checkbox"
|
|
onChange={formik.handleChange}
|
|
onBlur={formik.handleBlur}
|
|
checked={formik.values.concessionExpiry}
|
|
/>
|
|
<label htmlFor="concessionExpiry" className='ml-2'>Expiry</label>
|
|
<Dropdown value={formik.values.concessionTypeId} onChange={(e) => formik.setFieldValue('concessionTypeId', e.value)}
|
|
options={conTypeList} optionLabel="description" optionValue="id"
|
|
placeholder="Select a concession Type" className="w-full md:w-14rem" />
|
|
<Dropdown value={formik.values.validationPointId} onChange={(e) => formik.setFieldValue('validationPointId', e.value)}
|
|
options={validationPointList} optionLabel="description" optionValue="id"
|
|
placeholder="Select a concession Type" className="w-full md:w-14rem" />
|
|
</div>
|
|
<button className='flex ml-auto mt-2' type="submit">Submit</button>
|
|
</form>
|
|
);
|
|
};
|
|
|
|
/* navigate to edit page
|
|
import { useNavigate } from 'react-router-dom';
|
|
|
|
interface UserButtonProps {
|
|
id: string | number;
|
|
}
|
|
|
|
export default function UserButton({ id }: UserButtonProps) {
|
|
const navigate = useNavigate();
|
|
|
|
const handleClick = () => {
|
|
// Navigates to /users/42 using template literals
|
|
navigate(`/users/${id}`);
|
|
};
|
|
|
|
return <button onClick={handleClick}>View Profile</button>;
|
|
*/
|