feat(FE-33): create suppliers table and forms

This commit is contained in:
randy-ar
2025-10-09 12:27:59 +07:00
parent 21cc01fe68
commit a83452a0e4
17 changed files with 1194 additions and 25 deletions
+3
View File
@@ -39,3 +39,6 @@ yarn-error.log*
# typescript
*.tsbuildinfo
next-env.d.ts
# prettier
.prettierrc
+2 -2
View File
@@ -1,6 +1,6 @@
import CustomerForm from "@/components/pages/master-data/customer/form/CustomerForm";
const AddNonstock = () => {
const AddCustomer = () => {
return (
<section className="w-full p-4 flex flex-row justify-center">
<CustomerForm/>
@@ -8,4 +8,4 @@ const AddNonstock = () => {
);
}
export default AddNonstock;
export default AddCustomer;
+3 -3
View File
@@ -1,11 +1,11 @@
import CustomersTable from "@/components/pages/master-data/customer/CustomersTable";
const Nonstock = () => {
const Customer = () => {
return (
<section>
<section className="w-full p-4">
<CustomersTable />
</section>
)
};
export default Nonstock;
export default Customer;
+11
View File
@@ -0,0 +1,11 @@
import SupplierForm from '@/components/pages/master-data/supplier/form/SupplierForm';
const AddSupplier = () => {
return (
<section className='w-full p-4 flex flex-row justify-center'>
<SupplierForm />
</section>
);
};
export default AddSupplier;
@@ -0,0 +1,49 @@
'use client';
import SupplierForm from '@/components/pages/master-data/supplier/form/SupplierForm';
import { isResponseError, isResponseSuccess } from '@/lib/api-helper';
import { SupplierApi } from '@/services/api/master-data';
import { useSearchParams, useRouter } from 'next/navigation';
import useSWR from 'swr';
const SupplierEdit = () => {
const router = useRouter();
const searchParams = useSearchParams();
// Get Query Params
const supplierId = searchParams.get('supplierId');
// Fetch Data
const { data: supplier, isLoading: isLoadingSupplier } = useSWR(
supplierId,
(id: number) => SupplierApi.getSingle(id)
);
if (!supplierId) {
router.back();
return (
<div className='w-full flex flex-row justify-center items-center p-4'>
<span className='loading loading-spinner loading-xl' />
</div>
);
}
if (!isLoadingSupplier && (!supplier || isResponseError(supplier))) {
router.replace('/404');
return;
}
return (
<div className='w-full p-4 flex flex-row justify-center'>
{isLoadingSupplier && (
<span className='loading loading-spinner loading-xl' />
)}
{!isLoadingSupplier && isResponseSuccess(supplier) && (
<SupplierForm formType='edit' initialValues={supplier.data} />
)}
</div>
);
};
export default SupplierEdit;
@@ -0,0 +1,49 @@
'use client';
import SupplierForm from '@/components/pages/master-data/supplier/form/SupplierForm';
import { isResponseError, isResponseSuccess } from '@/lib/api-helper';
import { SupplierApi } from '@/services/api/master-data';
import { useSearchParams, useRouter } from 'next/navigation';
import useSWR from 'swr';
const SupplierDetail = () => {
const router = useRouter();
const searchParams = useSearchParams();
// Get Query Params
const supplierId = searchParams.get('supplierId');
// Fetch Data
const { data: supplier, isLoading: isLoadingSupplier } = useSWR(
supplierId,
(id: number) => SupplierApi.getSingle(id)
);
if (!supplierId) {
router.back();
return (
<div className='w-full flex flex-row justify-center items-center p-4'>
<span className='loading loading-spinner loading-xl' />
</div>
);
}
if (!isLoadingSupplier && (!supplier || isResponseError(supplier))) {
router.replace('/404');
return;
}
return (
<div className='w-full p-4 flex flex-row justify-center'>
{isLoadingSupplier && (
<span className='loading loading-spinner loading-xl' />
)}
{!isLoadingSupplier && isResponseSuccess(supplier) && (
<SupplierForm formType='detail' initialValues={supplier.data} />
)}
</div>
);
};
export default SupplierDetail;
+11
View File
@@ -0,0 +1,11 @@
import SuppliersTable from "@/components/pages/master-data/supplier/SupplierTable";
const Supplier = () => {
return (
<section className='w-full p-4'>
<SuppliersTable />
</section>
);
};
export default Supplier;
+169
View File
@@ -0,0 +1,169 @@
'use client';
import React, { useState, KeyboardEvent, ChangeEvent, useEffect } from 'react';
import { cn } from '@/lib/helper';
export interface TagInputProps {
label?: string;
bottomLabel?: string;
name: string;
value?: string;
placeholder?: string;
className?: {
wrapper?: string;
label?: string;
inputWrapper?: string;
input?: string;
};
isError?: boolean;
isValid?: boolean;
disabled?: boolean;
readOnly?: boolean;
required?: boolean;
isLoading?: boolean;
errorMessage?: string;
onChange?: (value: string) => void;
}
const TagInput: React.FC<TagInputProps> = ({
label,
bottomLabel,
name,
value = '',
placeholder,
className,
isError,
isValid,
errorMessage,
disabled = false,
readOnly = false,
required = false,
onChange,
}) => {
const [tags, setTags] = useState<string[]>(value ? value.split(',') : []);
const [inputValue, setInputValue] = useState('');
useEffect(() => {
if (value !== undefined && value !== tags.join(',')) {
setTags(value ? value.split(',') : []);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [value]);
const handleKeyDown = (e: KeyboardEvent<HTMLInputElement>) => {
if (e.key === 'Enter' || e.key === ',') {
e.preventDefault();
const newTag = inputValue.trim();
if (newTag && !tags.includes(newTag)) {
const updatedTags = [...tags, newTag];
setTags(updatedTags);
onChange?.(updatedTags.join(','));
}
setInputValue('');
}
};
const handleRemoveTag = (tagToRemove: string) => {
const updatedTags = tags.filter((t) => t !== tagToRemove);
setTags(updatedTags);
onChange?.(updatedTags.join(','));
};
const handleInputChange = (e: ChangeEvent<HTMLInputElement>) => {
setInputValue(e.target.value);
};
return (
<div
className={cn(
'w-full flex flex-col gap-2 text-start',
className?.wrapper
)}
>
{/* Label */}
{label && (
<label
htmlFor={name}
className={cn(
'w-full text-sm font-normal leading-5',
{ 'text-error': isError },
className?.label
)}
>
{label}
{required && (
<>
{' '}
<span className='tooltip tooltip-error' data-tip='required'>
<span className='text-error'> *</span>
</span>
</>
)}
</label>
)}
{/* Input wrapper */}
<div
className={cn(
'flex flex-wrap items-start gap-2 border border-gray-400 rounded-md p-2 focus-within:ring-2 focus-within:ring-blue-500 min-h-[42px] transition-all',
{
'border-error': isError,
'border-success!': isValid,
'opacity-70 cursor-not-allowed': disabled,
},
className?.inputWrapper
)}
onClick={() => {
// Fokuskan input saat area diklik
const inputEl = document.getElementById(name);
inputEl?.focus();
}}
>
{tags.map((tag) => (
<div
key={tag}
className={cn(
'badge badge-primary gap-1 px-3 py-3 text-white flex items-center'
)}
>
<span>{tag}</span>
{!readOnly && (
<button
type='button'
onClick={() => handleRemoveTag(tag)}
className='ml-1 text-white hover:text-red-200 focus:outline-none'
>
</button>
)}
</div>
))}
{!readOnly && (
<input
type='text'
id={name}
name={name}
value={inputValue}
onChange={handleInputChange}
onKeyDown={handleKeyDown}
placeholder={placeholder}
disabled={disabled}
className={cn(
'flex-1 min-w-[120px] border-none outline-none p-1 size-min',
className?.input
)}
/>
)}
</div>
{/* Bottom label or error message */}
{!isError && bottomLabel && (
<p className='w-full text-sm opacity-60'>{bottomLabel}</p>
)}
{isError && <p className='w-full text-sm text-error'>{errorMessage}</p>}
</div>
);
};
export default TagInput;
@@ -18,8 +18,6 @@ import { Icon } from '@iconify/react';
import {
CellContext,
ColumnDef,
ColumnSort,
SortingState,
} from '@tanstack/react-table';
import { useState } from 'react';
import toast from 'react-hot-toast';
@@ -272,7 +270,7 @@ const CustomersTable = () => {
<ConfirmationModal
ref={deleteModal.ref}
type='error'
text={`Apakah anda yakin ingin menghapus data Kandang ini (${selectedCustomer?.name})?`}
text={`Apakah anda yakin ingin menghapus data Customer ini (${selectedCustomer?.name})?`}
secondaryButton={{
text: 'Tidak',
}}
@@ -13,15 +13,7 @@ export const CustomerFormSchema = Yup.object({
type: Yup.object({
value: Yup.string().required(),
label: Yup.string().required(),
})
.oneOf(
[
{ value: 'INDIVIDUAL', label: 'INDIVIDUAL' },
{ value: 'BISNIS', label: 'BISNIS' },
],
'Tipe harus INDIVIDUAL atau BISNIS'
)
.required('Tipe wajib diisi!'),
}).required('Tipe wajib diisi!'),
address: Yup.string().required('Alamat wajib diisi!'),
@@ -11,7 +11,7 @@ import {
import { useRouter } from 'next/navigation';
import { useCallback, useEffect, useMemo, useState } from 'react';
import toast from 'react-hot-toast';
import { CustomerFormValues } from './CustomerForm.schema';
import { CustomerFormSchema, CustomerFormValues, UpdateCustomerFormSchema } from './CustomerForm.schema';
import { useFormik } from 'formik';
import Button from '@/components/Button';
import { Icon } from '@iconify/react';
@@ -22,7 +22,7 @@ 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 { TYPE_OPTIONS } from '@/config/constant';
interface CustomerFormProps {
formType?: 'add' | 'edit' | 'detail';
@@ -60,7 +60,7 @@ const CustomerForm = ({
label: area.name,
}))
: [];
const typeOptions = CUSTOMER_TYPE_OPTIONS;
const typeOptions = TYPE_OPTIONS;
// Handler Event
const createCustomerHandler = useCallback(
@@ -121,7 +121,7 @@ const CustomerForm = ({
// Utils Functions
const normalizeType = (type?: string | { value: string; label: string }) => {
if (!type) return CUSTOMER_TYPE_OPTIONS[0];
if (!type) return TYPE_OPTIONS[0];
return typeof type === 'string' ? { value: type, label: type } : type;
};
@@ -151,6 +151,7 @@ const CustomerForm = ({
const formik = useFormik<CustomerFormValues>({
initialValues: formikInitialValues,
enableReinitialize: true,
validationSchema: formType === 'edit' ? UpdateCustomerFormSchema : CustomerFormSchema,
onSubmit: async (values) => {
// reset error message
setCustomerFormErrorMessage('');
@@ -213,7 +214,6 @@ const CustomerForm = ({
>
{/* Fields Form */}
<div className='flex flex-col gap-4'>
{formik.values.picId}
<TextInput
required
label='Nama'
@@ -247,7 +247,7 @@ const CustomerForm = ({
label='Tipe'
value={
typeOptions.find(
(item) => item.value === formik.values.type.value
(item) => item.value === formik.values.type?.value
) ?? undefined
}
onChange={typeChangeHandler}
@@ -0,0 +1,303 @@
'use client';
import Button from '@/components/Button';
import DebouncedTextInput from '@/components/input/DebouncedTextInput';
import SelectInput, { OptionType } from '@/components/input/SelectInput';
import { useModal } from '@/components/Modal';
import ConfirmationModal from '@/components/modal/ConfirmationModal';
import Table from '@/components/Table';
import RowCollapseOptions from '@/components/table/RowCollapseOptions';
import RowDropdownOptions from '@/components/table/RowDropdownOptions';
import { ROWS_OPTIONS } from '@/config/constant';
import { isResponseSuccess } from '@/lib/api-helper';
import { cn } from '@/lib/helper';
import { SupplierApi } from '@/services/api/master-data';
import { useTableFilter } from '@/services/hooks/useTableFilter';
import { Supplier } from '@/types/api/master-data/supplier';
import { Icon } from '@iconify/react';
import { CellContext, ColumnDef } from '@tanstack/react-table';
import { useState } from 'react';
import toast from 'react-hot-toast';
import useSWR from 'swr';
const RowOptions = ({
type = 'dropdown',
props,
deleteClickHandler,
}: {
type: 'dropdown' | 'collapse';
props: CellContext<Supplier, unknown>;
deleteClickHandler: () => void;
}) => {
return (
<div
tabIndex={type == 'dropdown' ? 0 : undefined}
className={cn(
{
'dropdown-content': type === 'dropdown',
'mt-2': type === 'collapse',
},
'p-2.5 mr-2 flex flex-col gap-1 bg-base-100 rounded-box z-10 border border-black/10 shadow'
)}
>
<Button
href={`/master-data/supplier/detail/?supplierId=${props.row.original.id}`}
variant='ghost'
color='primary'
className='justify-start text-sm'
>
<Icon
icon='mdi:eye-outline'
width={16}
height={16}
className='justify-start text-sm'
/>
Detail
</Button>
<Button
href={`/master-data/supplier/detail/edit/?supplierId=${props.row.original.id}`}
variant='ghost'
color='warning'
className='justify-start text-sm'
>
<Icon
icon='material-symbols:edit-outline'
width={16}
height={16}
className='justify-start text-sm'
/>
Edit
</Button>
<Button
onClick={deleteClickHandler}
variant='ghost'
color='error'
className='text-error hover:text-inherit'
>
<Icon
icon='material-symbols:delete-outline-rounded'
width={16}
height={16}
className='justify-start text-sm'
/>
Delete
</Button>
</div>
);
};
const SuppliersTable = () => {
const {
state: tableFilterState,
updateFilter,
setPage,
setPageSize,
toQueryString: getTableFilterQueryString,
} = useTableFilter({
initial: { search: '', nameSort: '' },
paramMap: {
page: 'page',
pageSize: 'limit',
nameSort: 'sort_name',
},
});
// Fetch Data
const {
data: suppliers,
isLoading,
mutate: refreshSuppliers,
} = useSWR(
`${SupplierApi.basePath}${getTableFilterQueryString()}`,
SupplierApi.getAllFetcher
);
// State
const deleteModal = useModal();
const [selectedSupplier, setSelectedSupplier] = useState<
Supplier | undefined
>(undefined);
const [isDeleteLoading, setIsDeleteLoading] = useState(false);
// Columns Definition
const suppliersColumns: ColumnDef<Supplier>[] = [
{
header: '#',
cell: (props) =>
tableFilterState.pageSize * (tableFilterState.page - 1) +
props.row.index +
1,
},
{
accessorKey: 'name',
header: 'Nama',
},
{
accessorKey: 'alias',
header: 'Alias',
},
{
accessorKey: 'pic',
header: 'Nama PIC',
},
{
accessorKey: 'category',
header: 'Kategori',
},
{
accessorKey: 'type',
header: 'Tipe',
},
{
accessorKey: 'phone',
header: 'No. Telp',
},
{
accessorKey: 'email',
header: 'Email',
},
{
accessorKey: 'address',
header: 'Alamat',
},
{
header: 'Aksi',
cell: (props) => {
const currentPageSize = props.table.getPaginationRowModel().rows.length;
const currentPageRows = props.table.getPaginationRowModel().flatRows;
const currentRowRelativeIndex =
currentPageRows.findIndex((r) => r.id === props.row.id) + 1;
const isLast2Rows = currentRowRelativeIndex > currentPageSize - 2;
const deleteClickHandler = () => {
setSelectedSupplier(props.row.original);
deleteModal.openModal();
};
return (
<>
{currentPageSize > 2 && (
<RowDropdownOptions isLast2Rows={isLast2Rows}>
<RowOptions
type='dropdown'
props={props}
deleteClickHandler={deleteClickHandler}
/>
</RowDropdownOptions>
)}
{currentPageSize <= 2 && (
<RowCollapseOptions>
<RowOptions
type='collapse'
props={props}
deleteClickHandler={deleteClickHandler}
/>
</RowCollapseOptions>
)}
</>
);
},
},
];
// Handler
const confirmationModalDeleteClickHandler = async () => {
setIsDeleteLoading(true);
await SupplierApi.delete(selectedSupplier?.id as number);
refreshSuppliers();
deleteModal.closeModal();
toast.success('Successfully delete Supplier!');
setIsDeleteLoading(false);
};
const searchChangeHandler = (e: React.ChangeEvent<HTMLInputElement>) => {
updateFilter('search', e.target.value);
};
const pageSizeChangeHandler = (val: OptionType | OptionType[] | null) => {
const newVal = val as OptionType;
setPageSize(newVal.value as number);
};
return (
<>
<div className='w-full p-0 sm:p-4'>
<div className='flex flex-col gap-2 mb-4'>
<div className='w-full flex flex-col sm:flex-row justify-between items-end sm:items-center gap-2'>
<div className='flex flex-row'>
<Button href='/master-data/supplier/add' color='primary'>
<Icon icon='ic:round-plus' width={24} height={24} />
Tambah Supplier
</Button>
</div>
<DebouncedTextInput
name='search'
placeholder='Cari Supplier'
value={tableFilterState.search}
onChange={searchChangeHandler}
className={{ wrapper: 'sm:max-w-3xs' }}
/>
</div>
<div className='flex flex-row justify-end'>
<SelectInput
label='Baris'
options={ROWS_OPTIONS}
value={{
label: String(tableFilterState.pageSize),
value: tableFilterState.pageSize,
}}
onChange={pageSizeChangeHandler}
className={{ wrapper: 'max-w-28' }}
/>
</div>
</div>
<Table<Supplier>
data={isResponseSuccess(suppliers) ? suppliers?.data : []}
columns={suppliersColumns}
pageSize={tableFilterState.pageSize}
page={isResponseSuccess(suppliers) ? suppliers?.meta?.page : 0}
totalItems={
isResponseSuccess(suppliers) ? suppliers?.meta?.total_results : 0
}
onPageChange={setPage}
isLoading={isLoading}
className={{
containerClassName: cn({
'mb-20':
isResponseSuccess(suppliers) && suppliers?.data?.length === 0,
}),
tableWrapperClassName: 'overflow-x-auto min-h-full!',
tableClassName: 'font-inter w-full table-auto min-h-full!',
headerRowClassName: 'border-b border-b-gray-200',
headerColumnClassName:
'px-6 py-3 text-xs font-semibold text-gray-500 last:flex last:flex-row last:justify-end',
bodyRowClassName: 'border-b border-b-gray-200',
bodyColumnClassName:
'px-6 py-3 last:flex last:flex-row last:justify-end',
}}
/>
</div>
<ConfirmationModal
ref={deleteModal.ref}
type='error'
text={`Apakah anda yakin ingin menghapus data Supplier ini (${selectedSupplier?.name})?`}
secondaryButton={{
text: 'Tidak',
}}
primaryButton={{
text: 'Ya',
color: 'error',
isLoading: isDeleteLoading,
onClick: confirmationModalDeleteClickHandler,
}}
/>
</>
);
};
export default SuppliersTable;
@@ -0,0 +1,38 @@
import * as Yup from 'yup';
export const SupplierFormSchema = Yup.object({
name: Yup.string().required('Nama wajib diisi!'),
alias: Yup.string().required('Alias wajib diisi!'),
pic: Yup.string().required('PIC wajib diisi!'),
type: Yup.object({
value: Yup.string().required(),
label: Yup.string().required(),
})
.required('Tipe wajib diisi!'),
category: Yup.object({
value: Yup.string().required(),
label: Yup.string().required(),
})
.required('Tipe wajib diisi!'),
hatchery: Yup.string().required('Hatchery wajib diisi!'),
phone: Yup.string()
.matches(/^[0-9]+$/, 'Nomor telepon hanya boleh berisi angka!')
.min(10, 'Nomor telepon minimal 10 digit!')
.max(12, 'Nomor telepon maksimal 12 digit!')
.required('Nomor telepon wajib diisi!'),
email: Yup.string()
.email('Format email tidak valid!')
.required('Email wajib diisi!'),
address: Yup.string().required('Alamat wajib diisi!'),
npwp: Yup.string()
.matches(/^[0-9]+$/, 'Nomor NPWP hanya boleh berisi angka!')
.required('Nomor NPWP wajib diisi!'),
account_number: Yup.string()
.matches(/^[0-9]+$/, 'Nomor rekening hanya boleh berisi angka!')
.required('Nomor rekening wajib diisi!'),
due_date: Yup.number().min(1, 'Tanggal jatuh tempo wajib diisi!').required('Tanggal jatuh tempo wajib diisi!'),
});
export const UpdateSupplierFormSchema = SupplierFormSchema;
export type SupplierFormValues = Yup.InferType<typeof SupplierFormSchema>;
@@ -0,0 +1,471 @@
'use client';
import { useModal } from '@/components/Modal';
import { CATEGORY_OPTIONS, TYPE_OPTIONS } from '@/config/constant';
import { isResponseError } from '@/lib/api-helper';
import { SupplierApi } from '@/services/api/master-data';
import {
CreateSupplierPayload,
Supplier,
} from '@/types/api/master-data/supplier';
import { useRouter } from 'next/navigation';
import { useCallback, useEffect, useMemo, useState } from 'react';
import toast from 'react-hot-toast';
import { SupplierFormSchema, SupplierFormValues, UpdateSupplierFormSchema } from './SupplierForm.schema';
import { useFormik } from 'formik';
import SelectInput, { OptionType } from '@/components/input/SelectInput';
import { Icon } from '@iconify/react';
import Button from '@/components/Button';
import TextInput from '@/components/input/TextInput';
import TagInput from '@/components/input/TagInput';
import TextArea from '@/components/input/TextArea';
import { cn } from '@/lib/helper';
import ConfirmationModal from '@/components/modal/ConfirmationModal';
interface SupplierCustomProps {
formType?: 'add' | 'edit' | 'detail';
initialValues?: Supplier;
}
const SupplierForm = ({
formType = 'add',
initialValues,
}: SupplierCustomProps) => {
// Setup Kebutuhan Form
const router = useRouter();
const deleteModal = useModal();
// Setup State
const [supplierFormErrorMessage, setSupplierFormErrorMessage] = useState('');
const [isDeleteLoading, setIsDeleteLoading] = useState(false);
const [typeSelectInputValue, setTypeSelectInputValue] = useState('');
const [categorySelectInputValue, setCategorySelectInputValue] = useState('');
const [hatcheryTagInputValue, setHatcheryTagInputValue] = useState('');
// -- Options data mapping
const typeOptions = TYPE_OPTIONS;
const categoryOptions = CATEGORY_OPTIONS;
// Handler Event
const createSupplierHandler = useCallback(
async (payload: CreateSupplierPayload) => {
const createSupplierRes = await SupplierApi.create(payload);
if (isResponseError(createSupplierRes)) {
setSupplierFormErrorMessage(createSupplierRes.message);
return;
}
toast.success(createSupplierRes?.message as string);
router.push('/master-data/supplier');
},
[router]
);
const updateSupplierHandler = useCallback(
async (supplierId: number, payload: CreateSupplierPayload) => {
const updateSupplierRes = await SupplierApi.update(supplierId, payload);
if (isResponseError(updateSupplierRes)) {
setSupplierFormErrorMessage(updateSupplierRes.message);
return;
}
toast.success(updateSupplierRes?.message as string);
router.push('/master-data/supplier');
},
[router]
);
const deleteSupplierHandler = () => {
deleteModal.openModal();
};
const confirmationModalDeleteclickHandler = async () => {
setIsDeleteLoading(true);
await SupplierApi.delete(initialValues?.id as number);
deleteModal.closeModal();
setIsDeleteLoading(false);
router.push('/master-data/supplier');
};
// Utils Functions
const normalizeOptionValue = (
type?: string | { value: string; label: string },
options?: OptionType[]
): { value: string; label: string } => {
if (!type && !options) return { value: '', label: '' };
if (!type && options && options.length > 0)
return options[0] as { value: string; label: string };
if (typeof type === 'string') return { value: type, label: type };
return type ?? { value: '', label: '' };
};
// Memo
console.log('Memo');
console.log(initialValues);
const formikInitialValues = useMemo<SupplierFormValues>(() => {
return {
name: initialValues?.name ?? '',
alias: initialValues?.alias ?? '',
pic: initialValues?.pic ?? '',
type: normalizeOptionValue(initialValues?.type, typeOptions),
category: normalizeOptionValue(initialValues?.category, categoryOptions),
hatchery: initialValues?.hatchery ?? '',
phone: initialValues?.phone ?? '',
email: initialValues?.email ?? '',
address: initialValues?.address ?? '',
npwp: initialValues?.npwp ?? '',
account_number: initialValues?.account_number ?? '',
due_date: initialValues?.due_date ?? 1,
};
}, [initialValues]);
// Formik
const formik = useFormik<SupplierFormValues>({
initialValues: formikInitialValues,
enableReinitialize: true,
validationSchema: formType === 'edit' ? UpdateSupplierFormSchema : SupplierFormSchema,
onSubmit: async (values) => {
// reset error message
setSupplierFormErrorMessage('');
// create payload
const payload: CreateSupplierPayload = {
name: values.name,
alias: values.alias,
pic: values.pic,
type: values.type.value,
category: values.category.value,
hatchery: values.hatchery,
phone: values.phone,
email: values.email,
address: values.address,
npwp: values.npwp,
account_number: values.account_number,
due_date: parseInt(values.due_date.toString()),
};
// cek type form yang disubmit
switch (formType) {
case 'add':
await createSupplierHandler(payload);
break;
case 'edit':
await updateSupplierHandler(initialValues?.id as number, payload);
break;
default:
break;
}
},
});
const { setValues: formikSetValues } = formik;
// Initialize Formik
useEffect(() => {
formikSetValues(formikInitialValues);
setHatcheryTagInputValue(formikInitialValues.hatchery);
}, [formikSetValues, formikInitialValues, hatcheryTagInputValue]);
// Option Handler
const typeChangeHandler = (val: OptionType | OptionType[] | null) => {
formik.setFieldTouched('type', true);
formik.setFieldValue('type', val);
};
const categoryChangeHandler = (val: OptionType | OptionType[] | null) => {
formik.setFieldTouched('category', true);
formik.setFieldValue('category', val);
};
// Render
return (
<>
<section className='w-full max-w-xl'>
<header className='flex flex-col gap-4'>
<Button
href='/master-data/supplier'
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 Supplier'}
{formType === 'edit' && 'Ubah Supplier'}
{formType === 'detail' && 'Detail Supplier'}
</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 Supplier'
name='name'
placeholder='Masukkan nama supplier'
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'}
/>
<TextInput
required
label='Nama Alias'
name='alias'
placeholder='Masukkan alias supplier'
value={formik.values.alias}
onChange={formik.handleChange}
onBlur={formik.handleBlur}
isError={formik.touched.alias && Boolean(formik.errors.alias)}
errorMessage={formik.errors.alias}
readOnly={formType === 'detail'}
/>
<TextInput
required
label='Nama PIC'
name='pic'
placeholder='Masukkan PIC supplier'
value={formik.values.pic}
onChange={formik.handleChange}
onBlur={formik.handleBlur}
isError={formik.touched.pic && Boolean(formik.errors.pic)}
errorMessage={formik.errors.pic}
readOnly={formType === 'detail'}
/>
<SelectInput
required
placeholder='Pilih Tipe'
label='Tipe'
value={
typeOptions.find(
(item) => item.value === formik.values.type?.value
) ?? 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}
/>
<SelectInput
required
placeholder='Pilih Kategori'
label='Kategori'
value={
categoryOptions.find(
(item) => item.value === formik.values.category?.value
) ?? undefined
}
onChange={categoryChangeHandler}
options={categoryOptions}
onInputChange={setCategorySelectInputValue}
isError={formik.touched.category && Boolean(formik.errors.category)}
errorMessage={formik.errors.category as string}
isDisabled={formType === 'detail'}
isClearable
isSearchable={true}
/>
<TagInput
name='hatchery'
label='Hatchery'
value={hatcheryTagInputValue}
onChange={(value) => formik.setFieldValue('hatchery', value)}
isError={formik.touched.hatchery && Boolean(formik.errors.hatchery)}
errorMessage={formik.errors.hatchery}
readOnly={formType === 'detail'}
/>
<TextInput
required
label='Nomor Telepon'
name='phone'
placeholder='Masukkan nomor telepon supplier'
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='Email'
name='email'
placeholder='Masukkan email supplier'
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'}
/>
<TextArea
required
label='Alamat'
name='address'
placeholder='Masukkan alamat supplier'
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}
/>
<TextInput
required
label='NPWP'
name='npwp'
placeholder='Masukkan NPWP supplier'
value={formik.values.npwp}
onChange={formik.handleChange}
onBlur={formik.handleBlur}
isError={formik.touched.npwp && Boolean(formik.errors.npwp)}
errorMessage={formik.errors.npwp}
readOnly={formType === 'detail'}
/>
<TextInput
required
label='Nomor Rekening'
name='account_number'
placeholder='Masukkan nomor rekening supplier'
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'}
/>
<TextInput
required
type='number'
className={{
wrapper: 'w-fit',
}}
label='Jatuh Tempo'
name='due_date'
placeholder='Masukkan tanggal pembayaran supplier'
value={formik.values.due_date}
onChange={formik.handleChange}
onBlur={formik.handleBlur}
isError={
formik.touched.due_date && Boolean(formik.errors.due_date)
}
errorMessage={formik.errors.due_date}
readOnly={formType === 'detail'}
endAdornment={<div>Hari</div>}
/>
</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={deleteSupplierHandler}
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/supplier/detail/edit/?supplierId=${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>
{supplierFormErrorMessage && (
<div role='alert' className='alert alert-error'>
<Icon
icon='material-symbols:error-outline'
width={24}
height={24}
/>
<span>{supplierFormErrorMessage}</span>
</div>
)}
</form>
</section>
{formType !== 'add' && (
<ConfirmationModal
ref={deleteModal.ref}
type='error'
text={`Apakah anda yakin ingin menghapus data Supplier ini (${initialValues?.name})?`}
secondaryButton={{
text: 'Tidak',
}}
primaryButton={{
text: 'Ya',
color: 'error',
onClick: confirmationModalDeleteclickHandler,
isLoading: isDeleteLoading,
}}
/>
)}
</>
);
};
export default SupplierForm;
+12 -1
View File
@@ -108,7 +108,7 @@ export const WAREHOUSE_TYPE_OPTIONS = [
},
];
export const CUSTOMER_TYPE_OPTIONS = [
export const TYPE_OPTIONS = [
{
label: 'INDIVIDUAL',
value: 'INDIVIDUAL',
@@ -118,3 +118,14 @@ export const CUSTOMER_TYPE_OPTIONS = [
value: 'BISNIS',
},
];
export const CATEGORY_OPTIONS = [
{
label: 'BOP',
value: 'BOP',
},
{
label: 'SAPRONAK',
value: 'SAPRONAK',
},
];
+11
View File
@@ -29,6 +29,11 @@ import {
Customer,
UpdateCustomerPayload,
} from '@/types/api/master-data/customer';
import {
CreateSupplierPayload,
Supplier,
UpdateSupplierPayload,
} from '@/types/api/master-data/supplier';
export const UomApi = new BaseApiService<
Uom,
@@ -65,3 +70,9 @@ export const CustomerApi = new BaseApiService<
CreateCustomerPayload,
UpdateCustomerPayload
>('/master-data/customers');
export const SupplierApi = new BaseApiService<
Supplier,
CreateSupplierPayload,
UpdateSupplierPayload
>('/master-data/suppliers');
+53
View File
@@ -0,0 +1,53 @@
// {
// // "name": "PT CHAROEN POKPHAND INDONESIA Tbk",
// "name": "BOP Vendor",
// // "alias": "CPI",
// "alias": "BOP",
// "pic": "Super Admin",
// "type": "BISNIS", // "BISNIS" | "INDIVIDUAL"
// // "category": "SAPRONAK", // "BOP" | "SAPRONAK"
// "category": "BOP", // "BOP" | "SAPRONAK"
// "hatchery": "Kopo,Tasik", // Comma Separated // nullable
// "phone": "086172527361",
// "email": "abdulazis@gmail.com",
// "address": "Banten",
// "npwp": "0197239080712", // nullable
// "account_number": "192039801283", // nullable
// "due_date": 1 // day
// }
import { BaseMetadata, CreatedUser } from "@/types/api/api-general";
export type BaseSupplier = {
id: number;
name: string;
alias: string;
pic: string;
type: string;
category: string;
hatchery: string;
phone: string;
email: string;
address: string;
npwp: string;
account_number: string;
due_date: number;
}
export type Supplier = BaseMetadata & BaseSupplier;
export type CreateSupplierPayload = {
name: string;
alias: string;
pic: string;
type: string;
category: string;
hatchery: string;
phone: string;
email: string;
address: string;
npwp: string;
account_number: string;
due_date: number;
}
export type UpdateSupplierPayload = CreateSupplierPayload;