feat(FE-40,41): create NonstockForm component

This commit is contained in:
ValdiANS
2025-10-08 15:00:06 +07:00
parent d24d50474d
commit 96fea80f62
@@ -3,26 +3,31 @@
import { useCallback, useEffect, useMemo, useState } from 'react'; import { useCallback, useEffect, useMemo, useState } from 'react';
import { useRouter } from 'next/navigation'; import { useRouter } from 'next/navigation';
import { useFormik } from 'formik'; import { useFormik } from 'formik';
import { toast } from 'react-hot-toast';
import useSWR from 'swr';
import { Icon } from '@iconify/react'; import { Icon } from '@iconify/react';
import Button from '@/components/Button'; import Button from '@/components/Button';
import TextInput from '@/components/input/TextInput'; import TextInput from '@/components/input/TextInput';
import SelectInput, { OptionType } from '@/components/input/SelectInput';
import { useModal } from '@/components/Modal';
import ConfirmationModal from '@/components/modal/ConfirmationModal';
import { import {
NonstockFormSchema, NonstockFormSchema,
NonstockFormValues, NonstockFormValues,
UpdateNonstockFormSchema, UpdateNonstockFormSchema,
} from '@/components/pages/master-data/nonstock/form/NonstockForm.schema'; } from '@/components/pages/master-data/nonstock/form/NonstockForm.schema';
import { isResponseError } from '@/lib/api-helper'; import { isResponseError, isResponseSuccess } from '@/lib/api-helper';
import { import {
CreateNonstockPayload,
Nonstock, Nonstock,
CreateNonstockPayload,
UpdateNonstockPayload, UpdateNonstockPayload,
} from '@/types/api/master-data/nonstock'; } from '@/types/api/master-data/nonstock';
import { import { NonstockApi, SupplierApi, UomApi } from '@/services/api/master-data';
createNonstock, import { cn } from '@/lib/helper';
updateNonstock, import { flags } from '@/types/api/api-general';
} from '@/services/api/master-data/nonstock'; import { SUPPLIER_FLAG_OPTIONS } from '@/config/constant';
interface NonstockFormProps { interface NonstockFormProps {
type?: 'add' | 'edit' | 'detail'; type?: 'add' | 'edit' | 'detail';
@@ -31,19 +36,21 @@ interface NonstockFormProps {
const NonstockForm = ({ type = 'add', initialValues }: NonstockFormProps) => { const NonstockForm = ({ type = 'add', initialValues }: NonstockFormProps) => {
const router = useRouter(); const router = useRouter();
const deleteModal = useModal();
const [nonstockFormErrorMessage, setNonstockFormErrorMessage] = useState(''); const [nonstockFormErrorMessage, setNonstockFormErrorMessage] = useState('');
const [isDeleteLoading, setIsDeleteLoading] = useState(false);
const createNonstockHandler = useCallback( const createNonstockHandler = useCallback(
async (payload: CreateNonstockPayload) => { async (payload: CreateNonstockPayload) => {
const createNonstockRes = await createNonstock(payload); const createNonstockRes = await NonstockApi.create(payload);
if (isResponseError(createNonstockRes)) { if (isResponseError(createNonstockRes)) {
setNonstockFormErrorMessage(createNonstockRes.message); setNonstockFormErrorMessage(createNonstockRes.message);
return; return;
} }
alert(createNonstockRes?.message); toast.success(createNonstockRes?.message as string);
router.push('/master-data/nonstock'); router.push('/master-data/nonstock');
}, },
[router] [router]
@@ -51,14 +58,14 @@ const NonstockForm = ({ type = 'add', initialValues }: NonstockFormProps) => {
const updateNonstockHandler = useCallback( const updateNonstockHandler = useCallback(
async (nonstockId: number, payload: UpdateNonstockPayload) => { async (nonstockId: number, payload: UpdateNonstockPayload) => {
const updateNonstockRes = await updateNonstock(nonstockId, payload); const updateNonstockRes = await NonstockApi.update(nonstockId, payload);
if (updateNonstockRes?.status === 'error') { if (updateNonstockRes?.status === 'error') {
setNonstockFormErrorMessage(updateNonstockRes.message); setNonstockFormErrorMessage(updateNonstockRes.message);
return; return;
} }
alert(updateNonstockRes?.message); toast.success(updateNonstockRes?.message as string);
router.refresh(); router.refresh();
router.push('/master-data/nonstock'); router.push('/master-data/nonstock');
}, },
@@ -68,6 +75,22 @@ const NonstockForm = ({ type = 'add', initialValues }: NonstockFormProps) => {
const formikInitialValues = useMemo<NonstockFormValues>(() => { const formikInitialValues = useMemo<NonstockFormValues>(() => {
return { return {
name: initialValues?.name ?? '', name: initialValues?.name ?? '',
uomId: initialValues?.uom_id ?? 0,
uom: initialValues?.uom
? {
value: initialValues?.uom.id,
label: initialValues?.uom.name,
}
: null,
supplierIds:
initialValues?.suppliers.map((supplier) => supplier.id) ?? [],
suppliers:
initialValues?.suppliers.map((supplier) => ({
value: supplier.id,
label: supplier.name,
})) ?? [],
flags: initialValues?.flags ?? [],
}; };
}, [initialValues]); }, [initialValues]);
@@ -80,6 +103,9 @@ const NonstockForm = ({ type = 'add', initialValues }: NonstockFormProps) => {
const nonstockPayload: CreateNonstockPayload = { const nonstockPayload: CreateNonstockPayload = {
name: values.name, name: values.name,
uom_id: values.uomId,
supplier_ids: values.supplierIds as number[],
flags: values.flags as flags[],
}; };
switch (type) { switch (type) {
@@ -97,81 +123,268 @@ const NonstockForm = ({ type = 'add', initialValues }: NonstockFormProps) => {
}, },
}); });
const { setValues: formikSetValues } = formik;
// UOM
const [uomSelectInputValue, setUomSelectInputValue] = useState('');
const uomsUrl = `${UomApi.basePath}?${new URLSearchParams({
search: uomSelectInputValue ?? '',
}).toString()}`;
const { data: uoms, isLoading: isLoadingUoms } = useSWR(
uomsUrl,
UomApi.getAllFetcher
);
const uomOptions = isResponseSuccess(uoms)
? uoms?.data.map((uom) => ({
value: uom.id,
label: uom.name,
}))
: [];
const uomChangeHandler = (val: OptionType | OptionType[] | null) => {
formik.setFieldTouched('uom', true);
formik.setFieldValue('uom', val);
formik.setFieldTouched('uomId', true);
formik.setFieldValue('uomId', (val as OptionType)?.value);
};
// supplier
const [supplierSelectInputValue, setSupplierSelectInputValue] = useState('');
const suppliersUrl = `${SupplierApi.basePath}?${new URLSearchParams({
search: supplierSelectInputValue ?? '',
}).toString()}`;
const { data: suppliers, isLoading: isLoadingSuppliers } = useSWR(
suppliersUrl,
SupplierApi.getAllFetcher
);
const supplierOptions = isResponseSuccess(suppliers)
? suppliers?.data
.filter((sup) => sup.category === 'BOP')
.map((supplier) => ({
value: supplier.id,
label: supplier.name,
}))
: [];
const supplierChangeHandler = (val: OptionType | OptionType[] | null) => {
formik.setFieldTouched('suppliers', true);
formik.setFieldValue('suppliers', val);
const supplierIds = (val as OptionType[]).map(
(supplier) => supplier.value as number
);
formik.setFieldTouched('supplierIds', true);
formik.setFieldValue('supplierIds', supplierIds);
};
const deleteNonstockClickHandler = () => {
deleteModal.openModal();
};
const confirmationModalDeleteClickHandler = async () => {
setIsDeleteLoading(true);
await NonstockApi.delete(initialValues?.id as number);
deleteModal.closeModal();
toast.success('Successfully delete Nonstock!');
setIsDeleteLoading(false);
router.push('/master-data/nonstock');
};
const flagsChangeHandler = (val: OptionType | OptionType[] | null) => {
const formattedFlags = (val as OptionType[]).map(
(flag) => flag.value as string
);
formik.setFieldValue('flags', formattedFlags);
};
useEffect(() => { useEffect(() => {
formik.setValues(formikInitialValues); formikSetValues(formikInitialValues);
}, [formikInitialValues]); }, [formikSetValues, formikInitialValues]);
return ( return (
<section className='w-full max-w-xl'> <>
<header className='flex flex-col gap-4'> <section className='w-full max-w-xl'>
<Button <header className='flex flex-col gap-4'>
href='/master-data/nonstock' <Button
variant='link' href='/master-data/nonstock'
className='w-fit p-0 text-primary' 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'>
{type === 'add' && 'Tambah Nonstock'}
{type === 'edit' && 'Edit Nonstock'}
{type === 'detail' && 'Detail Nonstock'}
</h1>
</header>
<form
onSubmit={formik.handleSubmit}
onReset={formik.handleReset}
className='w-full mt-8 flex flex-col gap-6'
> >
<Icon icon='uil:arrow-left' width={24} height={24} /> <div className='flex flex-col gap-4'>
Kembali <TextInput
</Button> required
label='Nama'
name='name'
placeholder='Masukkan nama lokasi'
value={formik.values.name}
onChange={formik.handleChange}
onBlur={formik.handleBlur}
isError={formik.touched.name && Boolean(formik.errors.name)}
errorMessage={formik.errors.name}
readOnly={type === 'detail'}
/>
<h1 className='text-2xl font-bold text-center'> <SelectInput
{type === 'add' && 'Tambah Non Stock'} required
{type === 'edit' && 'Edit Non Stock'} label='UOM'
{type === 'detail' && 'Detail Non Stock'} value={formik.values.uom ?? undefined}
</h1> onChange={uomChangeHandler}
</header> options={uomOptions}
onInputChange={setUomSelectInputValue}
isLoading={isLoadingUoms}
isError={formik.touched.uomId && Boolean(formik.errors.uomId)}
errorMessage={formik.errors.uomId as string}
isDisabled={type === 'detail'}
isClearable
/>
<form <SelectInput
onSubmit={formik.handleSubmit} label='Supplier'
onReset={formik.handleReset} isMulti
className='w-full mt-8 flex flex-col gap-6' value={formik.values.suppliers}
> onChange={supplierChangeHandler}
<div className='flex flex-col gap-4'> options={supplierOptions ?? []}
<TextInput onInputChange={setSupplierSelectInputValue}
required isLoading={isLoadingSuppliers}
label='Nama' isError={
name='name' formik.touched.suppliers && Boolean(formik.errors.suppliers)
placeholder='Masukkan nama nonstock' }
value={formik.values.name} errorMessage={formik.errors.suppliers as string}
onChange={formik.handleChange} isDisabled={type === 'detail'}
onBlur={formik.handleBlur} />
isError={formik.touched.name && Boolean(formik.errors.name)}
errorMessage={formik.errors.name}
readOnly={type === 'detail'}
/>
</div>
{type !== 'detail' && ( <SelectInput
<> label='Flags'
<div className='flex flex-row justify-end gap-2'> isMulti
<Button type='reset' color='error' className='px-4'> value={SUPPLIER_FLAG_OPTIONS.filter((opt) =>
Reset formik.values.flags?.includes(opt.value)
</Button> )}
onChange={flagsChangeHandler}
options={SUPPLIER_FLAG_OPTIONS}
isError={formik.touched.flags && Boolean(formik.errors.flags)}
errorMessage={formik.errors.flags as string}
isDisabled={type === 'detail'}
isClearable
/>
</div>
<Button <div className='flex flex-row justify-between gap-2 flex-wrap'>
type='submit' {type !== 'add' && (
color='primary' <div className='flex flex-row justify-start gap-2'>
isLoading={formik.isSubmitting} <Button
disabled={!formik.isValid || formik.isSubmitting} type='button'
className='px-4' color='error'
> onClick={deleteNonstockClickHandler}
Submit className='px-4'
</Button> >
</div> <Icon
icon='material-symbols:delete-outline-rounded'
width={24}
height={24}
className='justify-start text-sm'
/>
Delete
</Button>
{nonstockFormErrorMessage && ( {type !== 'edit' && (
<div role='alert' className='alert alert-error'> <Button
<Icon type='button'
icon='material-symbols:error-outline' color='warning'
width={24} href={`/master-data/nonstock/detail/edit/?nonstockId=${initialValues?.id}`}
height={24} className='px-4'
/> >
<span>{nonstockFormErrorMessage}</span> <Icon
icon='material-symbols:edit-outline'
width={24}
height={24}
className='justify-start text-sm'
/>
Edit
</Button>
)}
</div> </div>
)} )}
</>
)} {type !== 'detail' && (
</form> <div
</section> className={cn('flex flex-row justify-end gap-2', {
'w-full': type === '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>
{nonstockFormErrorMessage && (
<div role='alert' className='alert alert-error'>
<Icon
icon='material-symbols:error-outline'
width={24}
height={24}
/>
<span>{nonstockFormErrorMessage}</span>
</div>
)}
</form>
</section>
{type !== 'add' && (
<ConfirmationModal
ref={deleteModal.ref}
type='error'
text={`Apakah anda yakin ingin menghapus data Nonstock ini (${initialValues?.name})?`}
secondaryButton={{
text: 'Tidak',
}}
primaryButton={{
text: 'Ya',
color: 'error',
isLoading: isDeleteLoading,
onClick: confirmationModalDeleteClickHandler,
}}
/>
)}
</>
); );
}; };