Merge branch 'feat/FE/US-77/TASK-113-slicing-transfer-to-laying-create-form' into 'feat/FE/US-77/transfer-to-laying'

[FEAT/FE][US#77/TASK#113] Slicing Transfer to Laying Create Form

See merge request mbugroup/lti-web-client!21
This commit is contained in:
Rivaldi A N S
2025-10-21 09:10:07 +00:00
16 changed files with 1198 additions and 55 deletions
@@ -0,0 +1,11 @@
import TransferToLayingForm from '@/components/pages/production/transfer-to-laying/form/TransferToLayingForm';
const AddTransferToLaying = () => {
return (
<div className='w-full p-4 flex flex-row justify-center'>
<TransferToLayingForm />
</div>
);
};
export default AddTransferToLaying;
@@ -0,0 +1,11 @@
import SuspenseHelper from '@/components/helper/SuspenseHelper';
const Layout = ({
children,
}: Readonly<{
children: React.ReactNode;
}>) => {
return <SuspenseHelper>{children}</SuspenseHelper>;
};
export default Layout;
@@ -0,0 +1,140 @@
'use client';
import { useRouter, useSearchParams } from 'next/navigation';
import useSWR from 'swr';
import TransferToLayingForm from '@/components/pages/production/transfer-to-laying/form/TransferToLayingForm';
import { TransferToLayingApi } from '@/services/api/production/transfer-to-laying';
import { isResponseError, isResponseSuccess } from '@/lib/api-helper';
import { TransferToLaying } from '@/types/api/production/transfer-to-laying';
// TODO: delete dummy data
const DUMMY_TRANSFER_TO_LAYING_DETAIL: TransferToLaying = {
id: 1,
transfer_date: '14-10-2025',
flock_source: {
id: 1,
name: 'Flock asal test',
},
flock_destination: {
id: 2,
name: 'Flock tujuan destination',
},
quantity: 10,
kandangs: [
{
kandang: {
id: 1,
name: 'Kandang test',
status: 'ACTIVE',
location: {
id: 1,
name: 'test location',
address: 'test address 1',
area: { id: 1, name: 'test area 1' },
},
pic: {
id: 1,
id_user: 2,
email: 'test@gmail.com',
name: 'test',
},
created_user: {
id: 1,
id_user: 2,
email: 'test@gmail.com',
name: 'test',
},
created_at: '14-10-2025',
updated_at: '14-10-2025',
},
quantity: 8,
},
{
kandang: {
id: 1,
name: 'Kandang test 2',
status: 'ACTIVE',
location: {
id: 1,
name: 'test location',
address: 'test address 1',
area: { id: 1, name: 'test area 1' },
},
pic: {
id: 1,
id_user: 2,
email: 'test@gmail.com',
name: 'test',
},
created_user: {
id: 1,
id_user: 2,
email: 'test@gmail.com',
name: 'test',
},
created_at: '14-10-2025',
updated_at: '14-10-2025',
},
quantity: 2,
},
],
reason: 'Test alasan',
created_user: {
id: 1,
id_user: 2,
email: 'test@gmail.com',
name: 'test',
},
created_at: '14-10-2025',
updated_at: '14-10-2025',
};
const TransferToLayingDetail = () => {
const router = useRouter();
const searchParams = useSearchParams();
const transferToLayingId = searchParams.get('transferToLayingId');
const { data: transferToLaying, isLoading: isLoadingTransferToLaying } =
useSWR(transferToLayingId, (id: number) =>
TransferToLayingApi.getSingle(id)
);
if (!transferToLayingId) {
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 (
!isLoadingTransferToLaying &&
(!transferToLaying || isResponseError(transferToLaying))
) {
router.replace('/404');
return;
}
return (
<div className='w-full p-4 flex flex-row justify-center'>
{isLoadingTransferToLaying && (
<span className='loading loading-spinner loading-xl' />
)}
{!isLoadingTransferToLaying && isResponseSuccess(transferToLaying) && (
<TransferToLayingForm
type='detail'
initialValues={DUMMY_TRANSFER_TO_LAYING_DETAIL}
/>
)}
</div>
);
};
export default TransferToLayingDetail;
@@ -0,0 +1,16 @@
import { Icon } from '@iconify/react';
import Button from '@/components/Button';
const TransferToLaying = () => {
return (
<section className='w-full p-4'>
<h1 className='mb-4'>Transfer to Laying</h1>
<Button href='/production/transfer-to-laying/add' color='primary'>
<Icon icon='ic:round-plus' width={24} height={24} />
Tambah Transfer to Laying
</Button>
</section>
);
};
export default TransferToLaying;
+1 -1
View File
@@ -158,7 +158,7 @@ const RequireAuth = ({ children }: RequireAuthProps) => {
const { data: userResponse, isLoading: isLoadingUserResponse } =
useSWRImmutable<GetMeResponse & { ok?: boolean }, unknown, SWRHttpKey>(
'/auth/get-me',
'/auth/sso/userinfo',
httpClientFetcher,
{
shouldRetryOnError: false,
+53 -7
View File
@@ -1,6 +1,8 @@
'use client';
import { ComponentType, ReactNode, useEffect, useMemo, useState } from 'react';
import useSWR from 'swr';
import Select, {
OptionProps,
GroupBase,
@@ -11,7 +13,10 @@ import Select, {
import CreatableSelect from 'react-select/creatable';
import makeAnimated from 'react-select/animated';
import { useDebounce } from 'use-debounce';
import { cn } from '@/lib/helper';
import { cn, getByPath } from '@/lib/helper';
import { httpClientFetcher } from '@/services/http/client';
import { isResponseSuccess } from '@/lib/api-helper';
import { BaseApiResponse } from '@/types/api/api-general';
export interface OptionType {
value: string | number;
@@ -160,7 +165,7 @@ const SelectInput = <T extends OptionType>(props: SelectInputProps<T>) => {
classNames={{
control: ({ isFocused, isDisabled }) =>
cn(
'w-full min-h-12! rounded-lg! border bg-white transition-shadow cursor-pointer!',
'w-full min-h-12! rounded! border bg-base-100 transition-shadow cursor-pointer!',
{
'border-red-500! ring-2 ring-red-200': isError,
'border-indigo-500 ring-2 ring-indigo-200': isFocused,
@@ -176,24 +181,24 @@ const SelectInput = <T extends OptionType>(props: SelectInputProps<T>) => {
input: () => cn('text-gray-900'),
indicatorsContainer: () => cn('flex items-center gap-1 pr-2'),
dropdownIndicator: ({ isFocused }) =>
cn('p-1 rounded-md hover:bg-gray-100', {
cn('p-1 rounded hover:bg-gray-100', {
'text-gray-900': isFocused,
'text-gray-500': !isFocused,
'text-error!': isError,
}),
menu: () =>
cn('border border-gray-200 rounded-lg bg-white shadow-lg!'),
cn('border border-gray-200 rounded! bg-base-100 shadow-lg!'),
menuList: () => cn('p-2! max-h-60 overflow-auto'),
option: ({ isFocused, isSelected }) =>
cn('mt-1 px-3 py-2 rounded-md cursor-pointer!', {
'bg-indigo-600 text-white': isFocused,
cn('mt-1 px-3 py-2 rounded cursor-pointer!', {
'bg-indigo-600 text-base-100': isFocused,
'bg-blue-500!': isSelected,
'text-gray-700': !isFocused && !isSelected,
}),
multiValue: ({ getValue, index }) => {
const selectedValues = getValue() as T[];
return cn(
'bg-indigo-50 rounded-md py-0.5 pl-2 pr-1 flex items-center gap-1!',
'bg-indigo-50 rounded py-0.5 pl-2 pr-1 flex items-center gap-1!',
selectedValues[index]?.className
);
},
@@ -222,4 +227,45 @@ const SelectInput = <T extends OptionType>(props: SelectInputProps<T>) => {
);
};
const useSelect = <T,>(
basePath: string,
valueKey: keyof T,
labelKey: keyof T,
searchKey: string = 'search',
params?: { [key: string]: string }
) => {
const [inputValue, setInputValue] = useState('');
const optionsUrlParams = useMemo(() => {
return new URLSearchParams({
[searchKey]: inputValue ?? '',
...params,
}).toString();
}, [inputValue, searchKey]);
const optionsUrl = `${basePath}?${optionsUrlParams}`;
const { data, isLoading } = useSWR(optionsUrl, async (url) => {
return await httpClientFetcher<BaseApiResponse<T[]>>(url);
});
const options = isResponseSuccess(data)
? data.data.map((item) => {
return {
value: getByPath(item, valueKey as string),
label: getByPath(item, labelKey as string),
};
})
: [];
return {
inputValue,
setInputValue,
options,
isLoadingOptions: isLoading,
rawData: data,
};
};
export { useSelect };
export default SelectInput;
+29 -33
View File
@@ -1,10 +1,6 @@
'use client';
import {
ChangeEventHandler,
FocusEventHandler,
ReactNode,
} from 'react';
import { ChangeEventHandler, FocusEventHandler, ReactNode } from 'react';
import { cn } from '@/lib/helper';
@@ -52,7 +48,7 @@ const TextArea = ({
onBlur,
readOnly = false,
isLoading = false,
rows = 3
rows = 3,
}: TextAreaProps) => {
return (
<div
@@ -83,35 +79,35 @@ const TextArea = ({
)}
</label>
)}
{startAdornment && startAdornment}
{startAdornment && startAdornment}
<textarea
className={cn(
'input h-auto px-4 py-2 text-base font-normal leading-6 w-full rounded-lg! outline-none! transition-all',
{
'border-error': isError,
'border-success!': isValid,
},
className?.inputWrapper
)}
id={name}
name={name}
placeholder={placeholder}
value={value}
rows={rows}
onChange={onChange}
onBlur={onBlur}
disabled={disabled}
readOnly={readOnly}
/>
{(isLoading || endAdornment) && (
<div className='flex flex-row gap-2'>
{isLoading && <span className='loading loading-spinner' />}
{endAdornment && endAdornment}
</div>
<textarea
className={cn(
'input h-auto px-4 py-2 text-base font-normal leading-6 w-full rounded! outline-none! transition-all',
{
'border-error': isError,
'border-success!': isValid,
},
className?.inputWrapper
)}
id={name}
name={name}
placeholder={placeholder}
value={value}
rows={rows}
onChange={onChange}
onBlur={onBlur}
disabled={disabled}
readOnly={readOnly}
/>
{(isLoading || endAdornment) && (
<div className='flex flex-row gap-2'>
{isLoading && <span className='loading loading-spinner' />}
{endAdornment && endAdornment}
</div>
)}
{!isError && bottomLabel && (
<p className='w-full text-sm opacity-60'>{bottomLabel}</p>
+1 -1
View File
@@ -87,7 +87,7 @@ const TextInput = ({
<div
className={cn(
'input h-12 px-4 py-2 text-base font-normal leading-6 w-full rounded-lg! outline-none! transition-all duration-200',
'input h-12 px-4 py-2 text-base font-normal leading-6 w-full rounded! outline-none! transition-all duration-200',
{
'border-error': isError,
'border-success!': isValid,
@@ -0,0 +1,83 @@
import * as Yup from 'yup';
type TransferToLayingFormSchemaType = {
transfer_date?: string;
flockSource?: {
value: number;
label: string;
};
flockDestination?: {
value: number;
label: string;
};
totalQuantity?: number;
maxTotalQuantity?: number; // original cap (hidden), helper
kandangs: {
kandang: {
value: number;
label: string;
};
quantity: number | string; // editable
maxQuantity?: number; // original cap (hidden), helper
}[];
reason?: string;
};
export const TransferToLayingFormSchema: Yup.ObjectSchema<TransferToLayingFormSchemaType> =
Yup.object({
transfer_date: Yup.string().required('Tanggal transfer wajib diisi!'),
flockSource: Yup.object({
value: Yup.number().min(1).required(),
label: Yup.string().required(),
}).required('Flock asal wajib diisi!'),
flockDestination: Yup.object({
value: Yup.number().min(1).required(),
label: Yup.string().required(),
}).required('Flock tujuan wajib diisi!'),
totalQuantity: Yup.number()
.min(1, 'Jumlah transfer minimal 1')
.max(
Yup.ref('maxTotalQuantity'),
({ max }) => `Kuantitas maksimal ${max}!`
)
.required('Jumlah transfer wajib diisi!'),
maxTotalQuantity: Yup.number()
.min(1, 'Jumlah transfer minimal 1')
.required('Jumlah transfer wajib diisi!'),
kandangs: Yup.array()
.of(
Yup.object({
kandang: Yup.object({
value: Yup.number().min(1).required(),
label: Yup.string().required(),
}).required('Kandang wajib diisi!'),
quantity: Yup.number()
.min(0, 'Kuantitas minimal 0!')
.max(
Yup.ref('maxQuantity'),
({ max }) => `Kuantitas maksimal ${max}!`
)
.required('Kuantitas wajib diisi!'),
maxQuantity: Yup.number().min(1).required(), // internal helper field
})
)
.min(1, 'Minimal 1 kandang terisi!')
.required('Kandang wajib diisi!'),
reason: Yup.string().required('Alasan transfer wajib diisi!'),
});
export const UpdateTransferToLayingFormSchema = TransferToLayingFormSchema;
export type TransferToLayingFormValues = Yup.InferType<
typeof TransferToLayingFormSchema
>;
@@ -0,0 +1,562 @@
'use client';
import { useCallback, useEffect, useMemo, useState } from 'react';
import { useRouter } from 'next/navigation';
import { useFormik } from 'formik';
import { toast } from 'react-hot-toast';
import useSWR from 'swr';
import { Icon } from '@iconify/react';
import Button from '@/components/Button';
import TextInput from '@/components/input/TextInput';
import SelectInput, {
OptionType,
// useSelect,
} from '@/components/input/SelectInput';
import TextArea from '@/components/input/TextArea';
import { useModal } from '@/components/Modal';
import ConfirmationModal from '@/components/modal/ConfirmationModal';
import {
TransferToLayingFormSchema,
TransferToLayingFormValues,
UpdateTransferToLayingFormSchema,
} from '@/components/pages/production/transfer-to-laying/form/TransferToLayingForm.schema';
import { isResponseError, isResponseSuccess } from '@/lib/api-helper';
import {
TransferToLaying,
CreateTransferToLayingPayload,
UpdateTransferToLayingPayload,
} from '@/types/api/production/transfer-to-laying';
import { cn } from '@/lib/helper';
import { TransferToLayingApi } from '@/services/api/production/transfer-to-laying';
interface TransferToLayingFormProps {
type?: 'add' | 'edit' | 'detail';
initialValues?: TransferToLaying;
}
const TransferToLayingForm = ({
type = 'add',
initialValues,
}: TransferToLayingFormProps) => {
const router = useRouter();
const deleteModal = useModal();
const [formErrorMessage, setFormErrorMessage] = useState('');
const [isDeleteLoading, setIsDeleteLoading] = useState(false);
const createTransferToLayingHandler = useCallback(
async (payload: CreateTransferToLayingPayload) => {
console.log('Create transfer to laying:', { payload });
toast.success('Berhasil menambahkan data transfer ke laying!');
},
[router]
);
const updateTransferToLayingHandler = useCallback(
async (
transferToLayingId: number,
payload: UpdateTransferToLayingPayload
) => {
console.log(
`Update transfer to laying with ID of ${transferToLayingId}:`,
{ payload }
);
toast.success('Berhasil mengubah data transfer ke laying!');
},
[router]
);
const formikInitialValues = useMemo<TransferToLayingFormValues>(() => {
return {
transfer_date: initialValues?.transfer_date ?? '',
flockSource: initialValues?.flock_source
? {
value: initialValues?.flock_source.id,
label: initialValues?.flock_source.name,
}
: undefined,
flockDestination: initialValues?.flock_destination
? {
value: initialValues?.flock_destination.id,
label: initialValues?.flock_destination.name,
}
: undefined,
totalQuantity: initialValues?.quantity ?? undefined,
kandangs: initialValues?.kandangs
? initialValues.kandangs.map((kandang) => ({
kandang: {
value: kandang.kandang.id,
label: kandang.kandang.name,
},
quantity: kandang.quantity,
}))
: [],
reason: initialValues?.reason ?? undefined,
};
}, [initialValues]);
const formik = useFormik<TransferToLayingFormValues>({
initialValues: formikInitialValues,
validationSchema:
type === 'edit'
? UpdateTransferToLayingFormSchema
: TransferToLayingFormSchema,
onSubmit: async (values) => {
console.log({ values });
setFormErrorMessage('');
const transferToLayingPayload: CreateTransferToLayingPayload = {
transfer_date: values.transfer_date as string,
flock_source_id: values.flockSource?.value as number,
flock_destination_id: values.flockDestination?.value as number,
totalQuantity: values.totalQuantity as number,
kandangs: values.kandangs?.map((kandang) => ({
kandang_id: kandang.kandang.value,
quantity: kandang.quantity,
})) as {
kandang_id: number;
quantity: number;
}[],
reason: values.reason as string,
};
switch (type) {
case 'add':
await createTransferToLayingHandler(transferToLayingPayload);
break;
case 'edit':
await updateTransferToLayingHandler(
initialValues?.id as number,
transferToLayingPayload
);
break;
}
},
});
const { setValues: formikSetValues, values: formikValues } = formik;
const { kandangs: kandangsValue } = formikValues;
const deleteTransferToLayingClickHandler = () => {
deleteModal.openModal();
};
const confirmationModalDeleteClickHandler = async () => {
setIsDeleteLoading(true);
deleteModal.closeModal();
toast.success('Successfully delete TransferToLaying!');
setIsDeleteLoading(false);
};
const isRepeaterInputError = (
column: keyof TransferToLayingFormValues['kandangs'][0],
idx: number
) => {
return (
formik.touched.kandangs?.[idx]?.[column] &&
Boolean(
formik.errors.kandangs?.[idx] instanceof Object &&
formik.errors.kandangs?.[idx]?.[column]
)
);
};
const repeaterInputErrorMessage = (
column: keyof TransferToLayingFormValues['kandangs'][0],
idx: number
) => {
return (formik.errors.kandangs?.[idx] as Record<string, string>)?.[column];
};
// TODO: remove dummy data and use real data
// Flock Source
// const {
// inputValue: flockSourceInputValue,
// setInputValue: setFlockSourceInputValue,
// options: flockSourceOptions,
// isLoadingOptions: isLoadingFlockSourceOptions,
// } = useSelect<FlockWithKandangs>('/transfer-to-laying/production/get-flock-source', 'id', 'name');
// TODO: remove this dummy data
const { data: flockSources, isLoading: isLoadingFlockSourceOptions } = useSWR(
'test',
() => TransferToLayingApi.getFlockSource()
);
const flockSourceOptions = isResponseSuccess(flockSources)
? flockSources?.data.map((flockSource) => ({
value: flockSource.id,
label: flockSource.name,
}))
: [];
const flockSourceChangeHandler = (val: OptionType | OptionType[] | null) => {
// Get flock source data for total quantity and kandang
const flockSource =
isResponseSuccess(flockSources) && val !== null
? flockSources.data.find(
(item) => item.id === (val as OptionType).value
)
: undefined;
// Set total quantity and kandangs
if (flockSource) {
const formattedKandangs = flockSource.kandangs.map((item) => ({
kandang: {
value: item.kandang.id,
label: item.kandang.name,
},
quantity: '',
maxQuantity: item.quantity,
}));
formik.setFieldValue('totalQuantity', flockSource.totalQuantity);
formik.setFieldValue('maxTotalQuantity', flockSource.totalQuantity);
formik.setFieldValue('kandangs', formattedKandangs);
} else {
formik.setFieldValue('totalQuantity', undefined);
formik.setFieldValue('kandangs', undefined);
formik.setFieldValue('reason', '');
}
formik.setFieldTouched('flockSource', true);
formik.setFieldValue('flockSource', val);
};
// TODO: remove dummy data and use real data
// Flock Destination
// const {
// inputValue: flockDestinationInputValue,
// setInputValue: setFlockDestinationInputValue,
// options: flockDestinationOptions,
// isLoadingOptions: isLoadingFlockDestinationOptions,
// } = useSelect<FlockWithKandangs>('/transfer-to-laying/production/get-flock-destination', 'id', 'name');
// TODO: remove this dummy data
const {
data: flockDestinations,
isLoading: isLoadingFlockDestinationOptions,
} = useSWR('test', () => TransferToLayingApi.getFlockSource());
const flockDestinationOptions = isResponseSuccess(flockDestinations)
? flockDestinations?.data.map((flockDestination) => ({
value: flockDestination.id,
label: flockDestination.name,
}))
: [];
const flockDestinationChangeHandler = (
val: OptionType | OptionType[] | null
) => {
formik.setFieldTouched('flockDestination', true);
formik.setFieldValue('flockDestination', val);
};
useEffect(() => {
formikSetValues(formikInitialValues);
}, [formikSetValues, formikInitialValues]);
useEffect(() => {
// calculate total quantity if kandangs quantity change
if (kandangsValue && kandangsValue.length > 0) {
let newTotalQuantity = 0;
kandangsValue.forEach((item) => {
newTotalQuantity += item.quantity as number;
});
formik.setFieldValue('totalQuantity', newTotalQuantity);
formik.validateField('totalQuantity');
}
}, [formikSetValues, kandangsValue]);
return (
<>
<section className='w-full max-w-3xl'>
<header className='flex flex-col gap-4'>
<Button
href='/master-data/nonstock'
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 Transfer ke Laying'}
{type === 'edit' && 'Edit Transfer ke Laying'}
{type === 'detail' && 'Detail Transfer ke Laying'}
</h1>
</header>
<form
onSubmit={formik.handleSubmit}
onReset={formik.handleReset}
className='w-full mt-8 flex flex-col gap-6'
>
<div className='flex flex-col gap-4'>
<TextInput
required
type='date'
label='Tanggal Transfer'
name='transfer_date'
placeholder='Masukkan tanggal transfer'
value={formik.values.transfer_date}
onChange={formik.handleChange}
onBlur={formik.handleBlur}
isError={
formik.touched.transfer_date &&
Boolean(formik.errors.transfer_date)
}
errorMessage={formik.errors.transfer_date}
readOnly={type === 'detail'}
/>
<div className='flex flex-col sm:flex-row gap-4'>
<SelectInput
required
label='Flock Asal'
placeholder='Flock asal'
value={formik.values.flockSource as OptionType}
options={flockSourceOptions}
onChange={flockSourceChangeHandler}
isLoading={isLoadingFlockSourceOptions}
// onInputChange={setFlockSourceInputValue}
isError={
formik.touched.flockSource &&
Boolean(typeof formik.errors.flockSource === 'string')
}
errorMessage={formik.errors.flockSource as string}
isDisabled={type === 'detail'}
isClearable
/>
<SelectInput
required
label='Flock Tujuan'
placeholder='Flock tujuan'
value={formik.values.flockDestination as OptionType}
options={flockDestinationOptions}
onChange={flockDestinationChangeHandler}
isLoading={isLoadingFlockDestinationOptions}
// onInputChange={setFlockDestinationInputValue}
isError={
formik.touched.flockDestination &&
Boolean(typeof formik.errors.flockDestination === 'string')
}
errorMessage={formik.errors.flockDestination as string}
isDisabled={type === 'detail'}
isClearable
/>
</div>
<TextInput
required
type='number'
name='totalQuantity'
label='Jumlah Transfer'
bottomLabel={
formikValues.maxTotalQuantity
? `Max: ${formikValues.maxTotalQuantity}`
: undefined
}
placeholder='Masukkan jumlah transfer'
value={formik.values.totalQuantity ?? ''}
onChange={formik.handleChange}
onBlur={formik.handleBlur}
isError={
formik.touched.totalQuantity &&
Boolean(formik.errors.totalQuantity)
}
errorMessage={formik.errors.totalQuantity}
// readOnly={type === 'detail'}
// disabled={Boolean(formik.errors.flockSource)}
disabled
/>
<div>
<div className='overflow-x-auto'>
<table className='table'>
<thead>
<tr>
<th>Kandang</th>
<th>Kuantitas</th>
</tr>
</thead>
<tbody>
{(!formik.values.kandangs ||
formik.values.kandangs.length === 0) && (
<tr>
<td colSpan={2}>
<p className='w-full text-center text-gray-400'>
Pilih flock asal terlebih dahulu!
</p>
</td>
</tr>
)}
{formik.values.kandangs &&
formik.values.kandangs.map((kandang, idx) => (
<tr key={idx}>
<td>
<SelectInput
value={kandang.kandang}
options={[]}
isDisabled
/>
</td>
<td>
<TextInput
required
type='number'
name={`kandangs[${idx}].quantity`}
bottomLabel={
kandang.maxQuantity
? `Max: ${kandang.maxQuantity}`
: undefined
}
placeholder='Masukkan kuantitas'
value={kandang.quantity}
onChange={formik.handleChange}
onBlur={formik.handleBlur}
isError={isRepeaterInputError('quantity', idx)}
errorMessage={repeaterInputErrorMessage(
'quantity',
idx
)}
readOnly={type === 'detail'}
/>
</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
<TextArea
required
rows={5}
name='reason'
label='Alasan Transfer'
placeholder='Alasan transfer'
value={formik.values.reason}
onChange={formik.handleChange}
onBlur={formik.handleBlur}
isError={formik.touched.reason && Boolean(formik.errors.reason)}
errorMessage={formik.errors.reason}
readOnly={type === 'detail'}
disabled={Boolean(formik.errors.flockSource)}
/>
</div>
<div className='flex flex-row justify-between gap-2 flex-wrap'>
{type !== 'add' && (
<div className='flex flex-row justify-start gap-2'>
<Button
type='button'
color='error'
onClick={deleteTransferToLayingClickHandler}
className='px-4'
>
<Icon
icon='material-symbols:delete-outline-rounded'
width={24}
height={24}
className='justify-start text-sm'
/>
Delete
</Button>
{type !== 'edit' && (
<Button
type='button'
color='warning'
href={`/master-data/nonstock/detail/edit/?nonstockId=${initialValues?.id}`}
className='px-4'
>
<Icon
icon='material-symbols:edit-outline'
width={24}
height={24}
className='justify-start text-sm'
/>
Edit
</Button>
)}
</div>
)}
{type !== 'detail' && (
<div
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>
{formErrorMessage && (
<div role='alert' className='alert alert-error'>
<Icon
icon='material-symbols:error-outline'
width={24}
height={24}
/>
<span>{formErrorMessage}</span>
</div>
)}
</form>
</section>
{type !== 'add' && (
<ConfirmationModal
ref={deleteModal.ref}
type='error'
text='Apakah anda yakin ingin menghapus data TransferToLaying?'
secondaryButton={{
text: 'Tidak',
}}
primaryButton={{
text: 'Ya',
color: 'error',
isLoading: isDeleteLoading,
onClick: confirmationModalDeleteClickHandler,
}}
/>
)}
</>
);
};
export default TransferToLayingForm;
+12 -8
View File
@@ -13,7 +13,7 @@ export const MAIN_DRAWER_LINKS: MAIN_DRAWER_MENU[] = [
},
{
title: 'Production',
title: 'Produksi',
link: '/production',
icon: 'material-symbols:conveyor-belt-outline-rounded',
submenu: [
@@ -32,6 +32,11 @@ export const MAIN_DRAWER_LINKS: MAIN_DRAWER_MENU[] = [
link: '/production/recording',
icon: 'mdi:clipboard-text',
},
{
title: 'Transfer ke Laying',
link: '/production/transfer-to-laying',
icon: 'streamline:transfer-van',
},
],
},
@@ -40,11 +45,11 @@ export const MAIN_DRAWER_LINKS: MAIN_DRAWER_MENU[] = [
link: '/inventory',
icon: 'mdi:warehouse',
submenu: [
{
title: 'Product',
link: '/inventory/product',
icon: 'mdi:package-variant-closed',
},
// {
// title: 'Product',
// link: '/inventory/product',
// icon: 'mdi:package-variant-closed',
// },
{
title: 'Penyesuaian Stok',
link: '/inventory/adjustment',
@@ -126,13 +131,12 @@ export const MAIN_DRAWER_LINKS: MAIN_DRAWER_MENU[] = [
{
title: 'Flock',
link: '/master-data/flock',
icon: 'material-symbols:raven-outline-rounded'
icon: 'material-symbols:raven-outline-rounded',
},
],
},
] as const;
export const ROWS_OPTIONS = [
{
label: '10',
+34
View File
@@ -27,3 +27,37 @@ export const formatCurrency = (
maximumFractionDigits,
}).format(value);
};
/**
* Retrieves a nested value from an object using a dot-delimited key path.
* Supports array indexes (e.g., "users.0.name") and returns a default value
* if the path does not exist.
*
* @param obj - The source object to search.
* @param path - Dot-delimited key string (e.g., "user.address.city").
* @param defaultValue - Optional value to return if the key path is not found.
* @returns The value found at the specified path, or the default value.
*/
export function getByPath<T, D = undefined>(
obj: T,
path: string,
defaultValue?: D
): unknown | D {
if (obj == null) return defaultValue as D;
if (!path) return obj as unknown;
const segments = path.split('.').filter(Boolean);
let cur: { [key: string]: unknown } = obj;
for (const seg of segments) {
if (cur == null) return defaultValue as D;
const key: string | number =
Array.isArray(cur) && /^\d+$/.test(seg) ? Number(seg) : seg;
if (Object(cur) !== cur || !(key in cur)) {
return defaultValue as D;
}
cur = cur[key] as { [key: string]: unknown };
}
return cur as unknown;
}
@@ -0,0 +1,187 @@
import { sleep } from '@/lib/helper';
import { BaseApiService } from '@/services/api/base';
import { BaseApiResponse } from '@/types/api/api-general';
import { FlockWithKandangs } from '@/types/api/master-data/flock';
// TODO: delete this dummy data
const FLOCK_SOURCE_DUMMY_DATA: BaseApiResponse<FlockWithKandangs[]> = {
code: 200,
status: 'success',
message: 'Get all projectflocks successfully',
meta: {
page: 1,
limit: 10,
total_pages: 1,
total_results: 2,
},
data: [
{
id: 2,
name: 'Flock Banten',
totalQuantity: 300,
kandangs: [
{
kandang: {
id: 3,
name: 'Cikaum 1',
status: 'ACTIVE',
location: {
id: 1,
name: 'Singaparna',
address: 'Tasik',
area: {
id: 1,
name: 'test area',
},
},
pic: {
id: 1,
id_user: 1,
email: 'admin@mbugroup.id',
name: 'Super Admin',
},
},
quantity: 100,
},
{
kandang: {
id: 4,
name: 'Cikaum 2',
status: 'ACTIVE',
location: {
id: 1,
name: 'Singaparna',
address: 'Tasik',
area: {
id: 1,
name: 'test area',
},
},
pic: {
id: 1,
id_user: 1,
email: 'admin@mbugroup.id',
name: 'Super Admin',
},
},
quantity: 150,
},
{
kandang: {
id: 5,
name: 'Cikaum 3',
status: 'ACTIVE',
location: {
id: 1,
name: 'Singaparna',
address: 'Tasik',
area: {
id: 1,
name: 'test area',
},
},
pic: {
id: 1,
id_user: 1,
email: 'admin@mbugroup.id',
name: 'Super Admin',
},
},
quantity: 50,
},
],
},
{
id: 3,
name: 'Flock Priangan',
totalQuantity: 200,
kandangs: [
{
kandang: {
id: 3,
name: 'Cikaum 1',
status: 'ACTIVE',
location: {
id: 1,
name: 'Singaparna',
address: 'Tasik',
area: {
id: 1,
name: 'Priangan',
},
},
pic: {
id: 1,
id_user: 1,
email: 'admin@mbugroup.id',
name: 'Super Admin',
},
},
quantity: 100,
},
{
kandang: {
id: 4,
name: 'Cikaum 2',
status: 'ACTIVE',
location: {
id: 1,
name: 'Singaparna',
address: 'Tasik',
area: {
id: 1,
name: 'test area',
},
},
pic: {
id: 1,
id_user: 1,
email: 'admin@mbugroup.id',
name: 'Super Admin',
},
},
quantity: 100,
},
],
},
],
};
export class TransferToLayingService<
T,
CreatePayloadGeneric,
UpdatePayloadGeneric
> extends BaseApiService<T, CreatePayloadGeneric, UpdatePayloadGeneric> {
constructor(basePath: string = '') {
super(basePath);
}
// TODO: remove dummy data and integrate to real API
async getFlockSource(): Promise<
BaseApiResponse<FlockWithKandangs[]> | undefined
> {
try {
// const getFlockSourcePath = `${this.basePath}/${flockSourcePath}`;
// const getSingleRes = await httpClient<FlockSourceType>(getFlockSourcePath);
// return getSingleRes;
await sleep(500);
return FLOCK_SOURCE_DUMMY_DATA;
} catch (error) {
// if (axios.isAxiosError<BaseApiResponse<T>>(error)) {
// return error.response?.data;
// }
return undefined;
}
}
}
export const TransferToLayingApi = new TransferToLayingService<
unknown,
unknown,
unknown
>('');
+4
View File
@@ -8,4 +8,8 @@
--step-bg: var(--color-error);
--step-fg: var(--color-error-content);
}
.table :where(th, td) {
vertical-align: top;
}
}
+15 -3
View File
@@ -1,14 +1,26 @@
import { BaseMetadata } from "@/types/api/api-general";
import { BaseMetadata } from '@/types/api/api-general';
export type BaseFlock = {
id: number;
name: string;
}
};
export type Flock = BaseMetadata & BaseFlock;
export type CreateFlockPayload = {
name: string;
}
};
export type UpdateFlockPayload = CreateFlockPayload;
// ---------------------------------------
// TODO: adjust this later after Transfer to Laying API done
import { BaseKandang } from '@/types/api/master-data/kandang';
export type FlockWithKandangs = BaseFlock & {
totalQuantity: number;
kandangs: {
kandang: BaseKandang;
quantity: number;
}[];
};
+37
View File
@@ -0,0 +1,37 @@
import { BaseApiResponse, BaseMetadata, flags } from '@/types/api/api-general';
import { Kandang } from '@/types/api/master-data/kandang';
export type BaseTransferToLaying = {
id: number;
transfer_date: string;
flock_source: {
id: number;
name: string;
};
flock_destination: {
id: number;
name: string;
};
quantity: number;
kandangs: {
kandang: Kandang;
quantity: number;
}[];
reason: string;
};
export type TransferToLaying = BaseMetadata & BaseTransferToLaying;
export type CreateTransferToLayingPayload = {
transfer_date: string;
flock_source_id: number;
flock_destination_id: number;
totalQuantity: number;
kandangs: {
kandang_id: number;
quantity: number;
}[];
reason: string;
};
export type UpdateTransferToLayingPayload = CreateTransferToLayingPayload;