feat(FE-33): create customers forms

This commit is contained in:
sweetpotet
2025-10-08 16:40:30 +07:00
parent af60e682ee
commit 21b9396323
12 changed files with 1008 additions and 9 deletions
@@ -0,0 +1,377 @@
'use client'
import { useModal } from "@/components/Modal";
import { isResponseError, isResponseSuccess } from "@/lib/api-helper";
import { CustomerApi } from "@/services/api/master-data";
import { CreateCustomerPayload, Customer, UpdateCustomerPayload } from "@/types/api/master-data/customer";
import { useRouter } from "next/navigation";
import { useCallback, useEffect, useMemo, useState } from "react";
import toast from "react-hot-toast";
import { CustomerFormValues } from "./CustomerForm.schema";
import { useFormik } from "formik";
import Button from "@/components/Button";
import { Icon } from "@iconify/react";
import TextInput from "@/components/input/TextInput";
import { cn } from "@/lib/helper";
import ConfirmationModal from "@/components/modal/ConfirmationModal";
import TextArea from "@/components/input/TextArea";
import SelectInput, { OptionType } from "@/components/input/SelectInput";
import useSWR from "swr";
import { UserApi } from "@/services/api/user";
import { CUSTOMER_TYPE_OPTIONS } from "@/config/constant";
interface CustomerFormProps {
formType?: 'add' | 'edit' | 'detail';
initialValues?: Customer;
}
const CustomerForm = ({formType = 'add', initialValues} : CustomerFormProps) => {
// Setup Kebutuhan Form
const router = useRouter();
const deleteModal = useModal();
// Setup State
const [customerFormErrorMessage, setCustomerFormErrorMessage] = useState('');
const [isDeleteLoading, setIsDeleteLoading] = useState(false);
const [picSelectInputValue, setPicSelectInputValue] = useState('');
const [typeSelectInputValue, setTypeSelectInputValue] = useState('');
// Fetch Data
const picUrl = `${UserApi.basePath}?${new URLSearchParams({
search: picSelectInputValue ?? '',
})}`;
const { data: pic, isLoading: isLoadingPic } = useSWR(
picUrl,
UserApi.getAllFetcher
);
// -- Options data mapping
const picOptions = isResponseSuccess(pic)
? pic?.data.map((area) => ({
value: area.id,
label: area.name,
}))
: [];
const typeOptions = CUSTOMER_TYPE_OPTIONS;
// Handler Event
const createCustomerHandler = useCallback(
async (payload : CreateCustomerPayload) => {
const createCustomerRes = await CustomerApi.create(payload);
if(isResponseError(createCustomerRes)){
setCustomerFormErrorMessage(createCustomerRes.message);
return;
}
toast.success(createCustomerRes?.message as string);
router.push('/master-data/customer');
},
[router]
);
const updateCustomerHandler = useCallback(
async (customerId : number, payload : UpdateCustomerPayload) => {
const updateCustomerRes = await CustomerApi.update(customerId, payload);
if(isResponseError(updateCustomerRes)){
setCustomerFormErrorMessage(updateCustomerRes.message);
return;
}
toast.success(updateCustomerRes?.message as string);
router.push('/master-data/customer');
},
[router]
);
const deleteCustomerHandler = () => {
deleteModal.openModal();
}
const confirmationModalDeleteclickHandler = async () => {
setIsDeleteLoading(true);
await CustomerApi.delete(initialValues?.id as number);
deleteModal.closeModal();
setIsDeleteLoading(false);
router.push('/master-data/customer');
};
// -- Option Handler
const picChangeHandler = (val: OptionType | OptionType[] | null) => {
formik.setFieldTouched('pic', true);
formik.setFieldValue('pic', val);
formik.setFieldTouched('picId', true);
formik.setFieldValue('picId', (val as OptionType)?.value);
}
const typeChangeHandler = (val: OptionType | OptionType[] | null) => {
formik.setFieldTouched('type', true);
formik.setFieldValue('type', val);
}
// Memo untuk simpan input sebelumnya
const formikInitialValues = useMemo<CustomerFormValues>(() => {
return {
name: initialValues?.name as string ?? '',
email: initialValues?.email ?? '',
phone: initialValues?.phone ?? '',
picId: initialValues?.pic?.id ?? 0,
pic: initialValues?.pic ? {
value: initialValues.pic.id,
label: initialValues.pic.name,
} : null,
type: initialValues?.type ?? 'INDIVIDUAL',
address: initialValues?.address ?? '',
account_number: initialValues?.account_number ?? '',
};
}, [initialValues]);
// Formik
const formik = useFormik<CustomerFormValues>({
initialValues: formikInitialValues,
enableReinitialize: true,
onSubmit: async (values) => {
// reset error message
setCustomerFormErrorMessage('');
// create payload
const payload: CreateCustomerPayload = {
name: values.name,
email: values.email,
phone: values.phone,
pic_id: values.picId,
type: values.type,
address: values.address,
account_number: values.account_number,
};
// cek type form yang disubmit
switch (formType) {
case 'add':
await createCustomerHandler(payload);
break;
case 'edit':
await updateCustomerHandler(initialValues?.id as number, payload);
break;
}
}
});
const {setValues: formikSetValues} = formik;
// Initialize Formik
useEffect(() => {
formikSetValues(formikInitialValues);
}, [formikSetValues, formikInitialValues]);
// Render
return (
<>
<section className="mx-auto my-8 max-w-xl">
<header className="flex flex-col gap-4">
<Button
href="/master-data/customer"
variant="link"
className="w-fit p-0 text-primary"
>
<Icon icon='uil:arrow-left' width={24} height={24} />
Kembali
</Button>
<h1 className="text-2xl font-bold text-center">
{formType === 'add' && 'Tambah Customer'}
{formType === 'edit' && 'Ubah Customer'}
{formType === 'detail' && 'Detail Customer'}
</h1>
</header>
<form
onSubmit={formik.handleSubmit}
onReset={formik.handleReset}
className="w-full mt-8 flex flex-col gap-6"
>
{/* Fields Form */}
<div className="flex flex-col gap-4">
<TextInput
required
label="Nama"
name="name"
placeholder="Masukkan nama customer"
value={formik.values.name}
onChange={formik.handleChange}
onBlur={formik.handleBlur}
isError={formik.touched.name && Boolean(formik.errors.name)}
errorMessage={formik.errors.name}
readOnly={formType === 'detail'}
/>
<SelectInput
required
placeholder="Pilih PIC"
label='PIC'
value={formik.values.pic ?? undefined}
onChange={picChangeHandler}
options={picOptions}
onInputChange={setPicSelectInputValue}
isLoading={isLoadingPic}
isError={formik.touched.picId && Boolean(formik.errors.picId)}
errorMessage={formik.errors.picId as string}
isDisabled={formType === 'detail'}
isClearable
isSearchable={true}
/>
<SelectInput
required
placeholder="Pilih Tipe"
label='Tipe'
value={typeOptions.find((item) => item.value === formik.values.type) ?? undefined}
onChange={typeChangeHandler}
options={typeOptions}
onInputChange={setTypeSelectInputValue}
isError={formik.touched.type && Boolean(formik.errors.type)}
errorMessage={formik.errors.type as string}
isDisabled={formType === 'detail'}
isClearable
isSearchable={true}
/>
<TextInput
required
label="Email"
name="email"
placeholder="Masukkan email customer"
value={formik.values.email}
onChange={formik.handleChange}
onBlur={formik.handleBlur}
isError={formik.touched.email && Boolean(formik.errors.email)}
errorMessage={formik.errors.email}
readOnly={formType === 'detail'}
/>
<TextInput
required
label="Nomor Telepon"
name="phone"
placeholder="Masukkan nomor telepon customer"
value={formik.values.phone}
onChange={formik.handleChange}
onBlur={formik.handleBlur}
isError={formik.touched.phone && Boolean(formik.errors.phone)}
errorMessage={formik.errors.phone}
readOnly={formType === 'detail'}
/>
<TextInput
required
label="Nomor Rekening"
name="account_number"
placeholder="Masukkan nomor rekening customer"
value={formik.values.account_number}
onChange={formik.handleChange}
onBlur={formik.handleBlur}
isError={formik.touched.account_number && Boolean(formik.errors.account_number)}
errorMessage={formik.errors.account_number}
readOnly={formType === 'detail'}
/>
<TextArea
required
label="Alamat"
name="address"
placeholder="Masukkan alamat customer"
value={formik.values.address}
onChange={formik.handleChange}
onBlur={formik.handleBlur}
isError={formik.touched.address && Boolean(formik.errors.address)}
errorMessage={formik.errors.address}
readOnly={formType === 'detail'}
cols={8}
/>
</div>
{/* Action Button */}
<div className='flex flex-row justify-between gap-2 flex-wrap'>
{formType !== 'add' && (
<div className='flex flex-row justify-start gap-2'>
<Button
type='button'
color='error'
onClick={deleteCustomerHandler}
className='px-4'
>
<Icon
icon='material-symbols:delete-outline-rounded'
width={24}
height={24}
className='justify-start text-sm'
/>
Delete
</Button>
{formType !== 'edit' && (
<Button
type='button'
color='warning'
href={`/master-data/area/detail/edit/?areaId=${initialValues?.id}`}
className='px-4'
>
<Icon
icon='material-symbols:edit-outline'
width={24}
height={24}
className='justify-start text-sm'
/>
Edit
</Button>
)}
</div>
)}
{formType !== 'detail' && (
<div
className={cn('flex flex-row justify-end gap-2', {
'w-full': formType === 'add',
})}
>
<Button type='reset' color='warning' className='px-4'>
Reset
</Button>
<Button
type='submit'
color='primary'
isLoading={formik.isSubmitting}
disabled={!formik.isValid || formik.isSubmitting}
className='px-4'
>
Submit
</Button>
</div>
)}
</div>
</form>
</section>
{formType !== 'add' && (
<ConfirmationModal
ref={deleteModal.ref}
type='error'
text={`Apakah anda yakin ingin menghapus data Customer ini (${initialValues?.name})?`}
secondaryButton={{
text: 'Tidak',
}}
primaryButton={{
text: 'Ya',
color: 'error',
onClick: confirmationModalDeleteclickHandler,
isLoading: isDeleteLoading,
}}
/>
)}
</>
);
}
export default CustomerForm;