feat(FE-33): create customers table and details

This commit is contained in:
randy-ar
2025-10-09 04:34:56 +07:00
parent 21b9396323
commit 21cc01fe68
7 changed files with 418 additions and 243 deletions
@@ -1,190 +1,205 @@
'use client'
'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";
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();
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('');
// 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 ?? '',
})}`;
// Fetch Data
const picUrl = `${UserApi.basePath}?${new URLSearchParams({
search: picSelectInputValue ?? '',
})}`;
const { data: pic, isLoading: isLoadingPic } = useSWR(
picUrl,
UserApi.getAllFetcher
);
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;
// -- 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);
// Handler Event
const createCustomerHandler = useCallback(
async (payload: CreateCustomerPayload) => {
const createCustomerRes = await CustomerApi.create(payload);
if(isResponseError(createCustomerRes)){
setCustomerFormErrorMessage(createCustomerRes.message);
return;
}
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);
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);
};
// Utils Functions
const normalizeType = (type?: string | { value: string; label: string }) => {
if (!type) return CUSTOMER_TYPE_OPTIONS[0];
return typeof type === 'string' ? { value: type, label: type } : type;
};
// Memo untuk simpan input sebelumnya
const formikInitialValues = useMemo<CustomerFormValues>(() => {
return {
name: initialValues?.name ?? '',
email: initialValues?.email ?? '',
phone: initialValues?.phone ?? '',
picId: initialValues?.pic?.id ?? 0,
pic: initialValues?.pic
? {
value: initialValues.pic.id,
label: initialValues.pic.name,
}
: {
value: 0,
label: '',
},
type: normalizeType(initialValues?.type),
address: initialValues?.address ?? '',
account_number: initialValues?.account_number ?? '',
};
}, [initialValues]);
// -- Option Handler
const picChangeHandler = (val: OptionType | OptionType[] | null) => {
formik.setFieldTouched('pic', true);
formik.setFieldValue('pic', val);
// Formik
const formik = useFormik<CustomerFormValues>({
initialValues: formikInitialValues,
enableReinitialize: true,
onSubmit: async (values) => {
// reset error message
setCustomerFormErrorMessage('');
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);
}
// create payload
const payload: CreateCustomerPayload = {
name: values.name,
email: values.email,
phone: values.phone,
pic_id: values.picId,
type: (values.type as OptionType).value as string,
address: values.address,
account_number: values.account_number,
};
// 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]);
// cek type form yang disubmit
switch (formType) {
case 'add':
await createCustomerHandler(payload);
break;
case 'edit':
await updateCustomerHandler(initialValues?.id as number, payload);
break;
}
},
});
// Formik
const formik = useFormik<CustomerFormValues>({
initialValues: formikInitialValues,
enableReinitialize: true,
onSubmit: async (values) => {
// reset error message
setCustomerFormErrorMessage('');
const { setValues: formikSetValues } = formik;
// 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,
};
// Initialize Formik
useEffect(() => {
formikSetValues(formikInitialValues);
}, [formikSetValues, formikInitialValues]);
// 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">
// Render
return (
<>
<section className='w-full max-w-xl'>
<header className='flex flex-col gap-4'>
<Button
href="/master-data/customer"
variant="link"
className="w-fit p-0 text-primary"
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">
<h1 className='text-2xl font-bold text-center'>
{formType === 'add' && 'Tambah Customer'}
{formType === 'edit' && 'Ubah Customer'}
{formType === 'detail' && 'Detail Customer'}
@@ -194,16 +209,16 @@ const CustomerForm = ({formType = 'add', initialValues} : CustomerFormProps) =>
<form
onSubmit={formik.handleSubmit}
onReset={formik.handleReset}
className="w-full mt-8 flex flex-col gap-6"
>
className='w-full mt-8 flex flex-col gap-6'
>
{/* Fields Form */}
<div className="flex flex-col gap-4">
<TextInput
<div className='flex flex-col gap-4'>
{formik.values.picId}
<TextInput
required
label="Nama"
name="name"
placeholder="Masukkan nama customer"
label='Nama'
name='name'
placeholder='Masukkan nama customer'
value={formik.values.name}
onChange={formik.handleChange}
onBlur={formik.handleBlur}
@@ -213,7 +228,7 @@ const CustomerForm = ({formType = 'add', initialValues} : CustomerFormProps) =>
/>
<SelectInput
required
placeholder="Pilih PIC"
placeholder='Pilih PIC'
label='PIC'
value={formik.values.pic ?? undefined}
onChange={picChangeHandler}
@@ -228,9 +243,13 @@ const CustomerForm = ({formType = 'add', initialValues} : CustomerFormProps) =>
/>
<SelectInput
required
placeholder="Pilih Tipe"
placeholder='Pilih Tipe'
label='Tipe'
value={typeOptions.find((item) => item.value === formik.values.type) ?? undefined}
value={
typeOptions.find(
(item) => item.value === formik.values.type.value
) ?? undefined
}
onChange={typeChangeHandler}
options={typeOptions}
onInputChange={setTypeSelectInputValue}
@@ -240,11 +259,11 @@ const CustomerForm = ({formType = 'add', initialValues} : CustomerFormProps) =>
isClearable
isSearchable={true}
/>
<TextInput
<TextInput
required
label="Email"
name="email"
placeholder="Masukkan email customer"
label='Email'
name='email'
placeholder='Masukkan email customer'
value={formik.values.email}
onChange={formik.handleChange}
onBlur={formik.handleBlur}
@@ -252,35 +271,38 @@ const CustomerForm = ({formType = 'add', initialValues} : CustomerFormProps) =>
errorMessage={formik.errors.email}
readOnly={formType === 'detail'}
/>
<TextInput
<TextInput
required
label="Nomor Telepon"
name="phone"
placeholder="Masukkan nomor telepon customer"
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
/>
<TextInput
required
label="Nomor Rekening"
name="account_number"
placeholder="Masukkan nomor rekening customer"
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)}
isError={
formik.touched.account_number &&
Boolean(formik.errors.account_number)
}
errorMessage={formik.errors.account_number}
readOnly={formType === 'detail'}
/>
<TextArea
<TextArea
required
label="Alamat"
name="address"
placeholder="Masukkan alamat customer"
label='Alamat'
name='address'
placeholder='Masukkan alamat customer'
value={formik.values.address}
onChange={formik.handleChange}
onBlur={formik.handleBlur}
@@ -314,7 +336,7 @@ const CustomerForm = ({formType = 'add', initialValues} : CustomerFormProps) =>
<Button
type='button'
color='warning'
href={`/master-data/area/detail/edit/?areaId=${initialValues?.id}`}
href={`/master-data/customer/detail/edit/?customerId=${initialValues?.id}`}
className='px-4'
>
<Icon
@@ -351,11 +373,22 @@ const CustomerForm = ({formType = 'add', initialValues} : CustomerFormProps) =>
</div>
)}
</div>
{customerFormErrorMessage && (
<div role='alert' className='alert alert-error'>
<Icon
icon='material-symbols:error-outline'
width={24}
height={24}
/>
<span>{customerFormErrorMessage}</span>
</div>
)}
</form>
</section>
{formType !== 'add' && (
<ConfirmationModal
<ConfirmationModal
ref={deleteModal.ref}
type='error'
text={`Apakah anda yakin ingin menghapus data Customer ini (${initialValues?.name})?`}
@@ -370,8 +403,8 @@ const CustomerForm = ({formType = 'add', initialValues} : CustomerFormProps) =>
}}
/>
)}
</>
);
}
</>
);
};
export default CustomerForm;
export default CustomerForm;