mirror of
https://gitlab.com/mbugroup/lti-web-client.git
synced 2026-05-20 13:32:00 +00:00
Merge branch 'feat/FE/US-76/TASK-129-130-137-integrate-api-daily-recording-growing' into 'feat/FE/US-76/daily-recording-growing'
[FEAT/FE][US#76/TASK#129-130-137] Integration API for Feature Daily Recording Growing See merge request mbugroup/lti-web-client!39
This commit is contained in:
@@ -40,8 +40,5 @@ yarn-error.log*
|
|||||||
*.tsbuildinfo
|
*.tsbuildinfo
|
||||||
next-env.d.ts
|
next-env.d.ts
|
||||||
|
|
||||||
# prettier
|
|
||||||
.prettierrc
|
|
||||||
|
|
||||||
# idea
|
# idea
|
||||||
.idea
|
.idea
|
||||||
|
|||||||
Generated
+474
-548
File diff suppressed because it is too large
Load Diff
@@ -21,6 +21,7 @@
|
|||||||
"react": "19.1.0",
|
"react": "19.1.0",
|
||||||
"react-dom": "19.1.0",
|
"react-dom": "19.1.0",
|
||||||
"react-hot-toast": "^2.6.0",
|
"react-hot-toast": "^2.6.0",
|
||||||
|
"react-number-format": "^5.4.4",
|
||||||
"react-select": "^5.10.2",
|
"react-select": "^5.10.2",
|
||||||
"swr": "^2.3.6",
|
"swr": "^2.3.6",
|
||||||
"tailwind-merge": "^3.3.1",
|
"tailwind-merge": "^3.3.1",
|
||||||
@@ -40,6 +41,7 @@
|
|||||||
"eslint": "^9",
|
"eslint": "^9",
|
||||||
"eslint-config-next": "15.5.3",
|
"eslint-config-next": "15.5.3",
|
||||||
"husky": "^9.1.7",
|
"husky": "^9.1.7",
|
||||||
|
"prettier": "3.6.2",
|
||||||
"tailwindcss": "^4",
|
"tailwindcss": "^4",
|
||||||
"typescript": "^5"
|
"typescript": "^5"
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,6 +3,7 @@
|
|||||||
import Button from '@/components/Button';
|
import Button from '@/components/Button';
|
||||||
import SelectInput, { OptionType } from '@/components/input/SelectInput';
|
import SelectInput, { OptionType } from '@/components/input/SelectInput';
|
||||||
import Modal, { useModal } from '@/components/Modal';
|
import Modal, { useModal } from '@/components/Modal';
|
||||||
|
import ConfirmationModal from '@/components/modal/ConfirmationModal';
|
||||||
import ChickinForm from '@/components/pages/production/chickin/form/ChickinForm';
|
import ChickinForm from '@/components/pages/production/chickin/form/ChickinForm';
|
||||||
import Table from '@/components/Table';
|
import Table from '@/components/Table';
|
||||||
import { isResponseError, isResponseSuccess } from '@/lib/api-helper';
|
import { isResponseError, isResponseSuccess } from '@/lib/api-helper';
|
||||||
@@ -14,7 +15,7 @@ import { Kandang } from '@/types/api/master-data/kandang';
|
|||||||
import { ProjectFlockKandang } from '@/types/api/production/project-flock-kandang';
|
import { ProjectFlockKandang } from '@/types/api/production/project-flock-kandang';
|
||||||
import { Icon } from '@iconify/react';
|
import { Icon } from '@iconify/react';
|
||||||
import { useRouter, useSearchParams } from 'next/navigation';
|
import { useRouter, useSearchParams } from 'next/navigation';
|
||||||
import { useEffect, useState } from 'react';
|
import { useState } from 'react';
|
||||||
|
|
||||||
import useSWR from 'swr';
|
import useSWR from 'swr';
|
||||||
|
|
||||||
@@ -33,6 +34,10 @@ const AddChickin = () => {
|
|||||||
const [selectedKandang, setSelectedKandang] = useState<Kandang | undefined>(
|
const [selectedKandang, setSelectedKandang] = useState<Kandang | undefined>(
|
||||||
undefined
|
undefined
|
||||||
);
|
);
|
||||||
|
const [projectFlockKandang, setProjectFlockKandang] =
|
||||||
|
useState<BaseApiResponse<ProjectFlockKandang>>();
|
||||||
|
const [isLoadingProjectFlockKandang, setIsLoadingProjectFlockKandang] =
|
||||||
|
useState(false);
|
||||||
const [searchProjectFlock, setSearchProjectFlock] = useState('');
|
const [searchProjectFlock, setSearchProjectFlock] = useState('');
|
||||||
|
|
||||||
// Fetch Data
|
// Fetch Data
|
||||||
@@ -41,44 +46,26 @@ const AddChickin = () => {
|
|||||||
(id: number) => ProjectFlockApi.getSingle(id)
|
(id: number) => ProjectFlockApi.getSingle(id)
|
||||||
);
|
);
|
||||||
const { data: listProjectFlock, isLoading: isLoadingListProjectFlock } =
|
const { data: listProjectFlock, isLoading: isLoadingListProjectFlock } =
|
||||||
useSWR(`${ProjectFlockApi.basePath}?${new URLSearchParams({
|
useSWR(
|
||||||
|
`${ProjectFlockApi.basePath}?${new URLSearchParams({
|
||||||
search: searchProjectFlock,
|
search: searchProjectFlock,
|
||||||
}).toString()}`, ProjectFlockApi.getAllFetcher);
|
}).toString()}`,
|
||||||
|
ProjectFlockApi.getAllFetcher
|
||||||
const getProjectFlockKandangUrl = `/kandangs/lookup`;
|
|
||||||
const {
|
|
||||||
data: projectFlockKandang,
|
|
||||||
isLoading: isLoadingProjectFlockKandang,
|
|
||||||
mutate: refreshProjectFlockKandang,
|
|
||||||
} = useSWR(getProjectFlockKandangUrl, () =>
|
|
||||||
ProjectFlockApi.customRequest<BaseApiResponse<ProjectFlockKandang>, 'GET'>(
|
|
||||||
getProjectFlockKandangUrl,
|
|
||||||
{
|
|
||||||
method: 'GET',
|
|
||||||
params: {
|
|
||||||
project_flock_id: projectFlockId ?? 0,
|
|
||||||
kandang_id: selectedKandang?.id,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
)
|
|
||||||
);
|
);
|
||||||
|
|
||||||
|
const getProjectFlockKandangUrl = `/kandangs/lookup`;
|
||||||
// Mapping Options
|
// Mapping Options
|
||||||
const options = isResponseSuccess(listProjectFlock)
|
const options = isResponseSuccess(listProjectFlock)
|
||||||
? listProjectFlock?.data.map((projectFlock) => {
|
? listProjectFlock?.data.map((projectFlock) => {
|
||||||
return {
|
return {
|
||||||
value: projectFlock.id,
|
value: projectFlock.id,
|
||||||
label: `${projectFlock?.flock.name} - ${projectFlock?.category} - Periode ${projectFlock.period}` ,
|
label: `${projectFlock?.flock?.name} - ${projectFlock?.category} - Periode ${projectFlock.period}`,
|
||||||
};
|
};
|
||||||
})
|
})
|
||||||
: [];
|
: [];
|
||||||
|
|
||||||
const chickinModal = useModal();
|
const chickinModal = useModal();
|
||||||
|
const alertModal = useModal();
|
||||||
// Use Effect
|
|
||||||
useEffect(() => {
|
|
||||||
refreshProjectFlockKandang();
|
|
||||||
}, [selectedKandang, refreshProjectFlockKandang]);
|
|
||||||
|
|
||||||
if (!projectFlockId) {
|
if (!projectFlockId) {
|
||||||
router.back();
|
router.back();
|
||||||
@@ -99,13 +86,33 @@ const AddChickin = () => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Handle Function
|
// Handle Function
|
||||||
const handleChickinClick = (kandang: Kandang) => {
|
const handleChickinClick = async (kandang: Kandang) => {
|
||||||
|
setIsLoadingProjectFlockKandang(true);
|
||||||
setSelectedKandang(kandang);
|
setSelectedKandang(kandang);
|
||||||
refreshProjectFlockKandang();
|
const ProjectFlockKandangRes = await ProjectFlockApi.customRequest<
|
||||||
|
BaseApiResponse<ProjectFlockKandang>,
|
||||||
|
'GET'
|
||||||
|
>(getProjectFlockKandangUrl, {
|
||||||
|
method: 'GET',
|
||||||
|
params: {
|
||||||
|
project_flock_id: projectFlockId ?? 0,
|
||||||
|
kandang_id: kandang.id,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
if (isResponseSuccess(ProjectFlockKandangRes)) {
|
||||||
|
setProjectFlockKandang(ProjectFlockKandangRes);
|
||||||
|
setIsLoadingProjectFlockKandang(false);
|
||||||
|
if (
|
||||||
|
ProjectFlockKandangRes.data.available_quantity &&
|
||||||
|
ProjectFlockKandangRes.data.available_quantity > 0
|
||||||
|
) {
|
||||||
chickinModal.openModal();
|
chickinModal.openModal();
|
||||||
|
} else {
|
||||||
|
alertModal.openModal();
|
||||||
|
}
|
||||||
|
}
|
||||||
};
|
};
|
||||||
const handleAfterSubmit = () => {
|
const handleAfterSubmit = () => {
|
||||||
refreshProjectFlockKandang();
|
|
||||||
chickinModal.closeModal();
|
chickinModal.closeModal();
|
||||||
router.push('/production/chickin');
|
router.push('/production/chickin');
|
||||||
};
|
};
|
||||||
@@ -126,7 +133,7 @@ const AddChickin = () => {
|
|||||||
</Button>
|
</Button>
|
||||||
|
|
||||||
<div className='flex flex-col gap-4 w-full my-4'>
|
<div className='flex flex-col gap-4 w-full my-4'>
|
||||||
<div className='max-w-1/4'>
|
<div className='max-w-full sm:max-w-1/2 md:max-w-3/5 lg:max-w-2/5'>
|
||||||
<SelectInput
|
<SelectInput
|
||||||
required
|
required
|
||||||
isSearchable
|
isSearchable
|
||||||
@@ -134,8 +141,8 @@ const AddChickin = () => {
|
|||||||
options={options}
|
options={options}
|
||||||
isLoading={isLoadingListProjectFlock}
|
isLoading={isLoadingListProjectFlock}
|
||||||
value={{
|
value={{
|
||||||
label: `${projectFlock.data.flock.name} - ${projectFlock.data.category} - Periode ${projectFlock.data.period}`,
|
label: `${projectFlock.data?.flock?.name} - ${projectFlock.data?.category} - Periode ${projectFlock.data?.period}`,
|
||||||
value: projectFlock.data.id,
|
value: projectFlock.data?.id,
|
||||||
}}
|
}}
|
||||||
onChange={(val) =>
|
onChange={(val) =>
|
||||||
router.push(
|
router.push(
|
||||||
@@ -152,7 +159,7 @@ const AddChickin = () => {
|
|||||||
</div>
|
</div>
|
||||||
</header>
|
</header>
|
||||||
<Table<Kandang>
|
<Table<Kandang>
|
||||||
data={projectFlock.data.kandangs}
|
data={projectFlock.data?.kandangs}
|
||||||
columns={[
|
columns={[
|
||||||
{
|
{
|
||||||
header: '#',
|
header: '#',
|
||||||
@@ -173,10 +180,10 @@ const AddChickin = () => {
|
|||||||
<Button
|
<Button
|
||||||
color='success'
|
color='success'
|
||||||
variant='outline'
|
variant='outline'
|
||||||
isLoading={isLoadingProjectFlockKandang}
|
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
handleChickinClick(props.row.original);
|
handleChickinClick(props.row.original);
|
||||||
}}
|
}}
|
||||||
|
disabled={isLoadingProjectFlockKandang}
|
||||||
>
|
>
|
||||||
<Icon
|
<Icon
|
||||||
icon='mdi:home-import-outline'
|
icon='mdi:home-import-outline'
|
||||||
@@ -195,7 +202,7 @@ const AddChickin = () => {
|
|||||||
containerClassName: cn({
|
containerClassName: cn({
|
||||||
'mb-20':
|
'mb-20':
|
||||||
isResponseSuccess(projectFlock) &&
|
isResponseSuccess(projectFlock) &&
|
||||||
projectFlock.data.kandangs?.length === 0,
|
projectFlock.data?.kandangs?.length === 0,
|
||||||
}),
|
}),
|
||||||
tableWrapperClassName: 'overflow-x-auto min-h-full!',
|
tableWrapperClassName: 'overflow-x-auto min-h-full!',
|
||||||
tableClassName: 'font-inter w-full table-auto min-h-full!',
|
tableClassName: 'font-inter w-full table-auto min-h-full!',
|
||||||
@@ -232,14 +239,28 @@ const AddChickin = () => {
|
|||||||
<ChickinForm
|
<ChickinForm
|
||||||
initialValues={{
|
initialValues={{
|
||||||
project_flock_kandang: projectFlockKandang.data,
|
project_flock_kandang: projectFlockKandang.data,
|
||||||
created_user: projectFlock.data.created_user,
|
created_user: projectFlock.data?.created_user,
|
||||||
created_at: projectFlock.data.created_at,
|
created_at: projectFlock.data?.created_at,
|
||||||
updated_at: projectFlock.data.updated_at,
|
updated_at: projectFlock.data?.updated_at,
|
||||||
|
approval: projectFlock.data?.approval,
|
||||||
}}
|
}}
|
||||||
afterSubmit={handleAfterSubmit}
|
afterSubmit={handleAfterSubmit}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
</Modal>
|
</Modal>
|
||||||
|
<ConfirmationModal
|
||||||
|
ref={alertModal.ref}
|
||||||
|
type='info'
|
||||||
|
text={`Persediaan Day Old Chick pada kandang (${selectedKandang?.name}) belum ada, mohon isi terlebih dahulu di bagian Persediaan!`}
|
||||||
|
secondaryButton={undefined}
|
||||||
|
primaryButton={{
|
||||||
|
text: 'Ya',
|
||||||
|
color: 'info',
|
||||||
|
onClick: () => {
|
||||||
|
alertModal.closeModal();
|
||||||
|
},
|
||||||
|
}}
|
||||||
|
/>
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
</>
|
</>
|
||||||
|
|||||||
@@ -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,351 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
import Button from '@/components/Button';
|
||||||
|
import Card from '@/components/Card';
|
||||||
|
import Modal, { useModal } from '@/components/Modal';
|
||||||
|
import ConfirmationModal from '@/components/modal/ConfirmationModal';
|
||||||
|
import ChickinForm from '@/components/pages/production/chickin/form/ChickinForm';
|
||||||
|
import { isResponseError, isResponseSuccess } from '@/lib/api-helper';
|
||||||
|
import { ChickinApi } from '@/services/api/production';
|
||||||
|
import { BaseApiResponse } from '@/types/api/api-general';
|
||||||
|
import {
|
||||||
|
Chickin,
|
||||||
|
ChickinApprovalPayload,
|
||||||
|
} from '@/types/api/production/chickin';
|
||||||
|
import { Icon } from '@iconify/react';
|
||||||
|
import { useRouter, useSearchParams } from 'next/navigation';
|
||||||
|
import { useState } from 'react';
|
||||||
|
import toast from 'react-hot-toast';
|
||||||
|
import useSWR from 'swr';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* TODO: Refactor code - pindahin detail ke reuseable component
|
||||||
|
* setelah implement approval and reject
|
||||||
|
*/
|
||||||
|
|
||||||
|
const DetailChickin = () => {
|
||||||
|
const router = useRouter();
|
||||||
|
const searchParams = useSearchParams();
|
||||||
|
const chickinId = searchParams.get('chickinId');
|
||||||
|
const [isApproveLoading, setIsApproveLoading] = useState(false);
|
||||||
|
const [isDeleteLoading, setIsDeleteLoading] = useState(false);
|
||||||
|
|
||||||
|
const confirmModal = useModal();
|
||||||
|
const deleteModal = useModal();
|
||||||
|
const chickinModal = useModal();
|
||||||
|
const {
|
||||||
|
data: chickin,
|
||||||
|
isLoading,
|
||||||
|
mutate: refreshChickin,
|
||||||
|
} = useSWR(chickinId, (id: number) => ChickinApi.getSingle(id));
|
||||||
|
|
||||||
|
const [isApprovedDisabled, setIsApprovedDisabled] = useState(
|
||||||
|
// chickin.data?.approval.step_number == 1 ? false : true
|
||||||
|
true
|
||||||
|
);
|
||||||
|
const [isRejectedDisabled, setIsRejectedDisabled] = useState(
|
||||||
|
!isApprovedDisabled
|
||||||
|
);
|
||||||
|
const [approvalAction, setApprovalAction] = useState<'APPROVED' | 'REJECTED'>(
|
||||||
|
!isApprovedDisabled ? 'APPROVED' : 'REJECTED'
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!chickinId) {
|
||||||
|
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 (!isLoading && (!chickin || isResponseError(chickin))) {
|
||||||
|
router.replace('/404');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!isResponseSuccess(chickin)) {
|
||||||
|
return (
|
||||||
|
<div className='w-full flex flex-row justify-center items-center p-4'>
|
||||||
|
<span className='loading loading-spinner loading-xl' />
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const confirmationModalClickHandler = async ({
|
||||||
|
action = 'APPROVED',
|
||||||
|
}: {
|
||||||
|
action: 'APPROVED' | 'REJECTED';
|
||||||
|
}) => {
|
||||||
|
if (chickin?.data.id === undefined) return;
|
||||||
|
setIsApproveLoading(true);
|
||||||
|
const approveChickinRes = await ChickinApi.customRequest<
|
||||||
|
BaseApiResponse<Chickin>,
|
||||||
|
ChickinApprovalPayload
|
||||||
|
>(`/approvals`, {
|
||||||
|
method: 'POST',
|
||||||
|
payload: {
|
||||||
|
action: action,
|
||||||
|
approvable_ids: [chickin.data.id],
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
if (isResponseSuccess(approveChickinRes)) {
|
||||||
|
if (refreshChickin) {
|
||||||
|
await refreshChickin();
|
||||||
|
}
|
||||||
|
toast.success(approveChickinRes.message as string);
|
||||||
|
}
|
||||||
|
if (isResponseError(approveChickinRes)) {
|
||||||
|
toast.error(approveChickinRes?.message as string);
|
||||||
|
}
|
||||||
|
confirmModal.closeModal();
|
||||||
|
setIsApproveLoading(false);
|
||||||
|
};
|
||||||
|
|
||||||
|
const confirmationModalDeleteClickHandler = async () => {
|
||||||
|
setIsDeleteLoading(true);
|
||||||
|
const deleteProjectFlockRes = await ChickinApi.delete(
|
||||||
|
chickin.data?.id as number
|
||||||
|
);
|
||||||
|
|
||||||
|
if (isResponseSuccess(deleteProjectFlockRes)) {
|
||||||
|
toast.success(deleteProjectFlockRes?.message as string);
|
||||||
|
router.push('/production/chickin');
|
||||||
|
}
|
||||||
|
if (isResponseError(deleteProjectFlockRes)) {
|
||||||
|
toast.error(deleteProjectFlockRes?.message as string);
|
||||||
|
}
|
||||||
|
deleteModal.closeModal();
|
||||||
|
setIsDeleteLoading(false);
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<div className='w-full p-4 flex flex-col justify-center gap-4'>
|
||||||
|
{isLoading && <span className='loading loading-spinner loading-xl' />}
|
||||||
|
{!isLoading && isResponseSuccess(chickin) && (
|
||||||
|
<>
|
||||||
|
{/* <div className='w-full flex flex-col sm:flex-row gap-2'>
|
||||||
|
<Button
|
||||||
|
variant='outline'
|
||||||
|
color='success'
|
||||||
|
onClick={(() => {
|
||||||
|
if (chickin?.data.id) {
|
||||||
|
setApprovalAction('APPROVED');
|
||||||
|
confirmModal.openModal();
|
||||||
|
}
|
||||||
|
})}
|
||||||
|
disabled={!chickin?.data.id || isApprovedDisabled}
|
||||||
|
className='w-full sm:w-fit'
|
||||||
|
>
|
||||||
|
<Icon icon='material-symbols:check' width={24} height={24} />
|
||||||
|
Approve
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
variant='outline'
|
||||||
|
color='error'
|
||||||
|
onClick={() => {
|
||||||
|
if (chickin?.data.id) {
|
||||||
|
setApprovalAction('REJECTED');
|
||||||
|
confirmModal.openModal();
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
disabled={!chickin?.data.id || isRejectedDisabled}
|
||||||
|
className='w-full sm:w-fit'
|
||||||
|
>
|
||||||
|
<Icon icon='mdi:times' width={24} height={24} />
|
||||||
|
Reject
|
||||||
|
</Button>
|
||||||
|
</div> */}
|
||||||
|
<Card
|
||||||
|
title='Informasi Umum'
|
||||||
|
variant='bordered'
|
||||||
|
className={{
|
||||||
|
wrapper: 'w-full',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<div className='grid grid-cols-2 gap-4 mt-4'>
|
||||||
|
<div className='flex flex-col gap-2'>
|
||||||
|
<div className='font-semibold text-sm'>Flock</div>
|
||||||
|
<div className='text-sm'>
|
||||||
|
{
|
||||||
|
chickin.data.project_flock_kandang?.project_flock.flock
|
||||||
|
.name
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className='flex flex-col gap-2'>
|
||||||
|
<div className='font-semibold text-sm'>Area</div>
|
||||||
|
<div className='text-sm'>
|
||||||
|
{
|
||||||
|
chickin.data.project_flock_kandang?.project_flock.area
|
||||||
|
.name
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className='flex flex-col gap-2'>
|
||||||
|
<div className='font-semibold text-sm'>Kategori</div>
|
||||||
|
<div className='text-sm'>
|
||||||
|
{chickin.data.project_flock_kandang?.project_flock.category}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className='flex flex-col gap-2'>
|
||||||
|
<div className='font-semibold text-sm'>Lokasi</div>
|
||||||
|
<div className='text-sm'>
|
||||||
|
{
|
||||||
|
chickin.data.project_flock_kandang?.project_flock.location
|
||||||
|
.name
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className='flex flex-col gap-2'>
|
||||||
|
<div className='font-semibold text-sm'>Periode</div>
|
||||||
|
<div className='text-sm'>
|
||||||
|
{chickin.data.project_flock_kandang?.project_flock.period}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className='flex flex-col gap-2'>
|
||||||
|
<div className='font-semibold text-sm'>Kandang</div>
|
||||||
|
<div className='text-sm'>
|
||||||
|
{chickin.data.project_flock_kandang?.kandang.name}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</Card>
|
||||||
|
<Card
|
||||||
|
title='Detail Chickin'
|
||||||
|
variant='bordered'
|
||||||
|
className={{
|
||||||
|
wrapper: 'w-full',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<div className='grid grid-cols-2 gap-4 mt-4'>
|
||||||
|
<div className='flex flex-col gap-2'>
|
||||||
|
<div className='font-semibold text-sm'>Flock Kandang</div>
|
||||||
|
<div className='text-sm'>
|
||||||
|
{
|
||||||
|
chickin.data.project_flock_kandang?.project_flock.flock
|
||||||
|
.name
|
||||||
|
}{' '}
|
||||||
|
- {chickin.data.project_flock_kandang?.kandang.name}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className='flex flex-col gap-2'>
|
||||||
|
<div className='font-semibold text-sm'>Tanggal Chickin</div>
|
||||||
|
<div className='text-sm'>
|
||||||
|
{chickin.data.chick_in_date
|
||||||
|
? new Date(chickin.data.chick_in_date).toLocaleDateString(
|
||||||
|
'id-ID'
|
||||||
|
)
|
||||||
|
: '-'}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className='flex flex-col gap-2'>
|
||||||
|
<div className='font-semibold text-sm'>Jumlah (Ekor)</div>
|
||||||
|
<div className='text-sm'>
|
||||||
|
{chickin.data.quantity?.toLocaleString('id-ID')}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className='flex flex-col gap-2'>
|
||||||
|
<div className='font-semibold text-sm'>Catatan</div>
|
||||||
|
<div className='text-sm'>{chickin.data.note}</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</Card>
|
||||||
|
<div className='w-full flex flex-col sm:flex-row gap-2'>
|
||||||
|
<Button
|
||||||
|
color='error'
|
||||||
|
onClick={() => {
|
||||||
|
deleteModal.openModal();
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Icon icon='mdi:times' width={24} height={24} />
|
||||||
|
Delete
|
||||||
|
</Button>
|
||||||
|
<Button color='warning'
|
||||||
|
onClick={() => {
|
||||||
|
chickinModal.openModal();
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Icon icon='mdi:pencil-outline' width={24} height={24} />
|
||||||
|
Edit
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<ConfirmationModal
|
||||||
|
ref={deleteModal.ref}
|
||||||
|
type='error'
|
||||||
|
text={`Apakah anda yakin ingin menghapus data Project Flock ini (${chickin?.data.project_flock_kandang?.project_flock.flock.name} - ${chickin?.data.project_flock_kandang?.kandang.name})?`}
|
||||||
|
secondaryButton={{
|
||||||
|
text: 'Tidak',
|
||||||
|
}}
|
||||||
|
primaryButton={{
|
||||||
|
text: 'Ya',
|
||||||
|
color: 'error',
|
||||||
|
isLoading: isDeleteLoading,
|
||||||
|
onClick: confirmationModalDeleteClickHandler,
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<Modal ref={chickinModal.ref}>
|
||||||
|
<div className='flex flex-row justify-between items-center'>
|
||||||
|
<h1 className='text-xl font-semibold text-center mb-6'>
|
||||||
|
Chickin Kandang -{' '}
|
||||||
|
{chickin?.data?.project_flock_kandang &&
|
||||||
|
chickin?.data?.project_flock_kandang.kandang?.name}
|
||||||
|
</h1>
|
||||||
|
<Button
|
||||||
|
color='error'
|
||||||
|
variant='link'
|
||||||
|
onClick={chickinModal.closeModal}
|
||||||
|
>
|
||||||
|
<Icon
|
||||||
|
className='text-black'
|
||||||
|
icon='uil:times'
|
||||||
|
width={24}
|
||||||
|
height={24}
|
||||||
|
/>
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
<ChickinForm
|
||||||
|
initialValues={chickin?.data}
|
||||||
|
formType='edit'
|
||||||
|
afterSubmit={() => {
|
||||||
|
refreshChickin();
|
||||||
|
chickinModal.closeModal();
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</Modal>
|
||||||
|
|
||||||
|
<ConfirmationModal
|
||||||
|
ref={confirmModal.ref}
|
||||||
|
type={approvalAction == 'APPROVED' ? 'success' : 'error'}
|
||||||
|
text={`Apakah anda yakin ingin ${
|
||||||
|
approvalAction == 'APPROVED' ? 'approve' : 'reject'
|
||||||
|
} chickin berikut? (${
|
||||||
|
chickin?.data.project_flock_kandang?.project_flock.flock.name
|
||||||
|
} - ${chickin?.data.project_flock_kandang?.kandang.name})?`}
|
||||||
|
secondaryButton={{
|
||||||
|
text: 'Tidak',
|
||||||
|
}}
|
||||||
|
primaryButton={{
|
||||||
|
text: 'Ya',
|
||||||
|
color: approvalAction == 'APPROVED' ? 'success' : 'error',
|
||||||
|
isLoading: isApproveLoading,
|
||||||
|
onClick: () => {
|
||||||
|
confirmationModalClickHandler({
|
||||||
|
action: approvalAction,
|
||||||
|
});
|
||||||
|
},
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default DetailChickin;
|
||||||
@@ -1,46 +1,51 @@
|
|||||||
'use client'
|
'use client';
|
||||||
|
|
||||||
|
import ProjectFlockForm from '@/components/pages/production/project-flock/form/ProjectFlockForm';
|
||||||
import ProjectFlockForm from "@/components/pages/production/project-flock/form/ProjectFlockForm";
|
import { isResponseError, isResponseSuccess } from '@/lib/api-helper';
|
||||||
import { isResponseError, isResponseSuccess } from "@/lib/api-helper";
|
import { ProjectFlockApi } from '@/services/api/production';
|
||||||
import { ProjectFlockApi } from "@/services/api/production";
|
import { useRouter, useSearchParams } from 'next/navigation';
|
||||||
import { useRouter, useSearchParams } from "next/navigation";
|
import useSWR from 'swr';
|
||||||
import useSWR from "swr";
|
|
||||||
|
|
||||||
const ProjectFlockDetail = () => {
|
const ProjectFlockDetail = () => {
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
const searchParams = useSearchParams();
|
const searchParams = useSearchParams();
|
||||||
|
|
||||||
const projectFlockId = searchParams.get("projectFlockId");
|
const projectFlockId = searchParams.get('projectFlockId');
|
||||||
|
|
||||||
const { data: projectFlock, isLoading: isLoadingCostumer } = useSWR(
|
const {
|
||||||
projectFlockId,
|
data: projectFlock,
|
||||||
(id: number) => ProjectFlockApi.getSingle(id)
|
isLoading: isLoadingProjectFlock,
|
||||||
);
|
mutate: refreshProjectFlock,
|
||||||
|
} = useSWR(projectFlockId, (id: number) => ProjectFlockApi.getSingle(id));
|
||||||
|
|
||||||
if (!projectFlockId) {
|
if (!projectFlockId) {
|
||||||
router.back();
|
router.back();
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="w-full flex flex-row justify-center items-center p-4">
|
<div className='w-full flex flex-row justify-center items-center p-4'>
|
||||||
<span className="loading loading-spinner loading-xl" />
|
<span className='loading loading-spinner loading-xl' />
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
if(!isLoadingCostumer && (!projectFlock || isResponseError(projectFlock))){
|
if (
|
||||||
router.replace("/404");
|
!isLoadingProjectFlock &&
|
||||||
|
(!projectFlock || isResponseError(projectFlock))
|
||||||
|
) {
|
||||||
|
router.replace('/404');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="w-full p-4 flex flex-row justify-center">
|
<div className='w-full p-4 flex flex-row justify-center'>
|
||||||
{isLoadingCostumer && <span className="loading loading-spinner loading-xl" />}
|
{isLoadingProjectFlock && (
|
||||||
{!isLoadingCostumer && isResponseSuccess(projectFlock) && (
|
<span className='loading loading-spinner loading-xl' />
|
||||||
<ProjectFlockForm formType="detail" initialValues={projectFlock.data} />
|
)}
|
||||||
|
{!isLoadingProjectFlock && isResponseSuccess(projectFlock) && (
|
||||||
|
<ProjectFlockForm formType='detail' initialValues={projectFlock.data} refreshProjectFlocks={refreshProjectFlock} />
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
)
|
);
|
||||||
}
|
};
|
||||||
|
|
||||||
export default ProjectFlockDetail;
|
export default ProjectFlockDetail;
|
||||||
@@ -1,4 +1,3 @@
|
|||||||
import ProjectFlockForm from "@/components/pages/production/project-flock/form/ProjectFlockForm"
|
|
||||||
import ProjectFlockTable from "@/components/pages/production/project-flock/ProjectFlockTable";
|
import ProjectFlockTable from "@/components/pages/production/project-flock/ProjectFlockTable";
|
||||||
|
|
||||||
const ProjectFlock = () => {
|
const ProjectFlock = () => {
|
||||||
|
|||||||
@@ -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,148 @@
|
|||||||
|
'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_EDIT: TransferToLaying = {
|
||||||
|
id: 1,
|
||||||
|
transfer_date: '2025-10-14',
|
||||||
|
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 TransferToLayingEdit = () => {
|
||||||
|
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>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// TODO: remove dummy data and integrate with real API
|
||||||
|
if (
|
||||||
|
!isLoadingTransferToLaying &&
|
||||||
|
(!transferToLaying ||
|
||||||
|
(isResponseError(transferToLaying) && !DUMMY_TRANSFER_TO_LAYING_EDIT))
|
||||||
|
) {
|
||||||
|
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={transferToLaying.data}
|
||||||
|
/>
|
||||||
|
)} */}
|
||||||
|
|
||||||
|
{/* TODO: remove this dummy data and integrate to real API */}
|
||||||
|
<TransferToLayingForm
|
||||||
|
type='edit'
|
||||||
|
initialValues={DUMMY_TRANSFER_TO_LAYING_EDIT}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default TransferToLayingEdit;
|
||||||
@@ -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,148 @@
|
|||||||
|
'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: '2025-10-14',
|
||||||
|
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>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// TODO: remove dummy data and integrate with real API
|
||||||
|
if (
|
||||||
|
!isLoadingTransferToLaying &&
|
||||||
|
(!transferToLaying ||
|
||||||
|
(isResponseError(transferToLaying) && !DUMMY_TRANSFER_TO_LAYING_DETAIL))
|
||||||
|
) {
|
||||||
|
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={transferToLaying.data}
|
||||||
|
/>
|
||||||
|
)} */}
|
||||||
|
|
||||||
|
{/* TODO: remove this dummy data and integrate to real API */}
|
||||||
|
<TransferToLayingForm
|
||||||
|
type='detail'
|
||||||
|
initialValues={DUMMY_TRANSFER_TO_LAYING_DETAIL}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default TransferToLayingDetail;
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
import TransferToLayingsTable from '@/components/pages/production/transfer-to-laying/TransferToLayingsTable';
|
||||||
|
|
||||||
|
const TransferToLaying = () => {
|
||||||
|
return (
|
||||||
|
<section className='w-full p-4'>
|
||||||
|
<TransferToLayingsTable />
|
||||||
|
</section>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default TransferToLaying;
|
||||||
@@ -6,6 +6,7 @@ import {
|
|||||||
} from 'react';
|
} from 'react';
|
||||||
|
|
||||||
import { cn } from '@/lib/helper';
|
import { cn } from '@/lib/helper';
|
||||||
|
import Image from 'next/image';
|
||||||
|
|
||||||
export interface CardProps extends Omit<HTMLAttributes<HTMLDivElement>, 'className'> {
|
export interface CardProps extends Omit<HTMLAttributes<HTMLDivElement>, 'className'> {
|
||||||
title?: string;
|
title?: string;
|
||||||
@@ -108,7 +109,7 @@ const Card = ({
|
|||||||
return (
|
return (
|
||||||
<div className={getCardClasses()} {...props}>
|
<div className={getCardClasses()} {...props}>
|
||||||
<figure>
|
<figure>
|
||||||
<img
|
<Image
|
||||||
src={image}
|
src={image}
|
||||||
alt={imageAlt || title || 'Card image'}
|
alt={imageAlt || title || 'Card image'}
|
||||||
className={getImageClasses()}
|
className={getImageClasses()}
|
||||||
@@ -129,7 +130,7 @@ const Card = ({
|
|||||||
<div className={getCardClasses()} {...props}>
|
<div className={getCardClasses()} {...props}>
|
||||||
{image && (
|
{image && (
|
||||||
<figure>
|
<figure>
|
||||||
<img
|
<Image
|
||||||
src={image}
|
src={image}
|
||||||
alt={imageAlt || title || 'Card image'}
|
alt={imageAlt || title || 'Card image'}
|
||||||
className={getImageClasses()}
|
className={getImageClasses()}
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ import Menu from '@/components/menu/Menu';
|
|||||||
import MenuItem from '@/components/menu/MenuItem';
|
import MenuItem from '@/components/menu/MenuItem';
|
||||||
import Navbar from '@/components/Navbar';
|
import Navbar from '@/components/Navbar';
|
||||||
import Collapse from '@/components/Collapse';
|
import Collapse from '@/components/Collapse';
|
||||||
|
import Button from '@/components/Button';
|
||||||
|
|
||||||
import { useUiStore } from '@/stores/ui/ui.store';
|
import { useUiStore } from '@/stores/ui/ui.store';
|
||||||
import { MAIN_DRAWER_LINKS } from '@/config/constant';
|
import { MAIN_DRAWER_LINKS } from '@/config/constant';
|
||||||
@@ -155,9 +156,15 @@ const MainDrawerMenu = () => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const MainDrawerContent = () => {
|
const MainDrawerContent = () => {
|
||||||
|
const { setMainDrawerOpen } = useUiStore();
|
||||||
|
|
||||||
|
const closeMainDrawerHandler = () => {
|
||||||
|
setMainDrawerOpen(false);
|
||||||
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className='w-full p-4 flex flex-col gap-4'>
|
<div className='w-full p-4 flex flex-col gap-4'>
|
||||||
<div className='flex items-center gap-4'>
|
<div className='flex flex-row items-center gap-4'>
|
||||||
<Image
|
<Image
|
||||||
src='/assets/img/lti-logo.png'
|
src='/assets/img/lti-logo.png'
|
||||||
alt='MBU Logo'
|
alt='MBU Logo'
|
||||||
@@ -167,6 +174,21 @@ const MainDrawerContent = () => {
|
|||||||
/>
|
/>
|
||||||
|
|
||||||
<h1 className='text-xl font-bold'>LTI ERP</h1>
|
<h1 className='text-xl font-bold'>LTI ERP</h1>
|
||||||
|
|
||||||
|
<div className='grow flex flex-row justify-end sm:hidden'>
|
||||||
|
<Button
|
||||||
|
variant='soft'
|
||||||
|
color='error'
|
||||||
|
onClick={closeMainDrawerHandler}
|
||||||
|
className='rounded-full'
|
||||||
|
>
|
||||||
|
<Icon
|
||||||
|
icon='material-symbols:close-rounded'
|
||||||
|
width={24}
|
||||||
|
height={24}
|
||||||
|
/>
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<MainDrawerMenu />
|
<MainDrawerMenu />
|
||||||
|
|||||||
@@ -0,0 +1,31 @@
|
|||||||
|
import { ReactNode } from 'react';
|
||||||
|
import { cn } from '@/lib/helper';
|
||||||
|
|
||||||
|
interface PillBadgeProps {
|
||||||
|
content: ReactNode;
|
||||||
|
color?: 'yellow' | 'blue' | 'green' | 'red' | 'purple' | 'gray';
|
||||||
|
className?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
const PillBadge = ({ content, color = 'gray', className }: PillBadgeProps) => {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
className={cn(
|
||||||
|
'w-fit min-w-max px-2 py-0.5 flex justify-center items-center gap-1 rounded-full border border-gray-200 bg-gray-50 text-gray-500 drop-shadow-xs capitalize',
|
||||||
|
{
|
||||||
|
'border-yellow-200 bg-yellow-50 text-yellow-500': color === 'yellow',
|
||||||
|
'border-blue-200 bg-blue-50 text-blue-500': color === 'blue',
|
||||||
|
'border-green-200 bg-green-50 text-green-500': color === 'green',
|
||||||
|
'border-red-200 bg-red-50 text-red-500': color === 'red',
|
||||||
|
'border-purple-200 bg-purple-50 text-purple-500': color === 'purple',
|
||||||
|
'border-neutral-200 bg-neutral-50 text-neutral-500': color === 'gray',
|
||||||
|
},
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{content}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default PillBadge;
|
||||||
@@ -48,6 +48,8 @@ export interface TableProps<TData extends object> {
|
|||||||
sorting?: SortingState;
|
sorting?: SortingState;
|
||||||
setSorting?: OnChangeFn<SortingState>;
|
setSorting?: OnChangeFn<SortingState>;
|
||||||
manualSorting?: boolean;
|
manualSorting?: boolean;
|
||||||
|
rowSelection?: Record<string, boolean>;
|
||||||
|
setRowSelection?: OnChangeFn<Record<string, boolean>>;
|
||||||
}
|
}
|
||||||
|
|
||||||
const DUMMY_SKELETON_DATA = [{}, {}, {}, {}, {}];
|
const DUMMY_SKELETON_DATA = [{}, {}, {}, {}, {}];
|
||||||
@@ -86,6 +88,8 @@ const Table = <TData extends object>({
|
|||||||
sorting,
|
sorting,
|
||||||
setSorting,
|
setSorting,
|
||||||
manualSorting = false,
|
manualSorting = false,
|
||||||
|
rowSelection,
|
||||||
|
setRowSelection,
|
||||||
}: TableProps<TData>) => {
|
}: TableProps<TData>) => {
|
||||||
const isServerSideTable =
|
const isServerSideTable =
|
||||||
totalItems !== undefined &&
|
totalItems !== undefined &&
|
||||||
@@ -137,6 +141,15 @@ const Table = <TData extends object>({
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (rowSelection && setRowSelection) {
|
||||||
|
tableOptions.onRowSelectionChange = setRowSelection;
|
||||||
|
tableOptions.state = {
|
||||||
|
...tableOptions.state,
|
||||||
|
rowSelection,
|
||||||
|
};
|
||||||
|
tableOptions.getRowId = (row) => (row as { id: string }).id;
|
||||||
|
}
|
||||||
|
|
||||||
const table = useReactTable(tableOptions);
|
const table = useReactTable(tableOptions);
|
||||||
const { setPageSize } = table;
|
const { setPageSize } = table;
|
||||||
|
|
||||||
|
|||||||
@@ -158,7 +158,7 @@ const RequireAuth = ({ children }: RequireAuthProps) => {
|
|||||||
|
|
||||||
const { data: userResponse, isLoading: isLoadingUserResponse } =
|
const { data: userResponse, isLoading: isLoadingUserResponse } =
|
||||||
useSWRImmutable<GetMeResponse & { ok?: boolean }, unknown, SWRHttpKey>(
|
useSWRImmutable<GetMeResponse & { ok?: boolean }, unknown, SWRHttpKey>(
|
||||||
'/auth/get-me',
|
'/auth/sso/userinfo',
|
||||||
httpClientFetcher,
|
httpClientFetcher,
|
||||||
{
|
{
|
||||||
shouldRetryOnError: false,
|
shouldRetryOnError: false,
|
||||||
|
|||||||
@@ -9,6 +9,11 @@ interface FormActionsProps<T> {
|
|||||||
editUrl?: string;
|
editUrl?: string;
|
||||||
onDelete?: () => void;
|
onDelete?: () => void;
|
||||||
disableSubmit?: boolean;
|
disableSubmit?: boolean;
|
||||||
|
onApprove?: () => void;
|
||||||
|
onReject?: () => void;
|
||||||
|
isApproveLoading?: boolean;
|
||||||
|
isRejectLoading?: boolean;
|
||||||
|
showApproveReject?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
export const FormActions = <T,>({
|
export const FormActions = <T,>({
|
||||||
@@ -17,11 +22,17 @@ export const FormActions = <T,>({
|
|||||||
editUrl,
|
editUrl,
|
||||||
onDelete,
|
onDelete,
|
||||||
disableSubmit = false,
|
disableSubmit = false,
|
||||||
|
onApprove,
|
||||||
|
onReject,
|
||||||
|
isApproveLoading = false,
|
||||||
|
isRejectLoading = false,
|
||||||
|
showApproveReject = false,
|
||||||
}: FormActionsProps<T>) => {
|
}: FormActionsProps<T>) => {
|
||||||
return (
|
return (
|
||||||
<div className='flex flex-row justify-between gap-2 flex-wrap'>
|
<div className='flex flex-row justify-between gap-2 flex-wrap'>
|
||||||
{type !== 'add' && onDelete && (
|
{type !== 'add' && (
|
||||||
<div className='flex flex-row justify-start gap-2'>
|
<div className='flex flex-row justify-start gap-2'>
|
||||||
|
{onDelete && (
|
||||||
<Button
|
<Button
|
||||||
type='button'
|
type='button'
|
||||||
color='error'
|
color='error'
|
||||||
@@ -36,6 +47,7 @@ export const FormActions = <T,>({
|
|||||||
/>
|
/>
|
||||||
Delete
|
Delete
|
||||||
</Button>
|
</Button>
|
||||||
|
)}
|
||||||
{type !== 'edit' && editUrl && (
|
{type !== 'edit' && editUrl && (
|
||||||
<Button
|
<Button
|
||||||
type='button'
|
type='button'
|
||||||
@@ -52,6 +64,44 @@ export const FormActions = <T,>({
|
|||||||
Edit
|
Edit
|
||||||
</Button>
|
</Button>
|
||||||
)}
|
)}
|
||||||
|
{type === 'detail' && showApproveReject && (onApprove || onReject) && (
|
||||||
|
<>
|
||||||
|
{onApprove && (
|
||||||
|
<Button
|
||||||
|
type='button'
|
||||||
|
color='success'
|
||||||
|
onClick={onApprove}
|
||||||
|
className='px-4'
|
||||||
|
isLoading={isApproveLoading}
|
||||||
|
>
|
||||||
|
<Icon
|
||||||
|
icon='material-symbols:check-circle-outline'
|
||||||
|
width={24}
|
||||||
|
height={24}
|
||||||
|
className='justify-start text-sm'
|
||||||
|
/>
|
||||||
|
Approve
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
{onReject && (
|
||||||
|
<Button
|
||||||
|
type='button'
|
||||||
|
color='error'
|
||||||
|
onClick={onReject}
|
||||||
|
className='px-4'
|
||||||
|
isLoading={isRejectLoading}
|
||||||
|
>
|
||||||
|
<Icon
|
||||||
|
icon='material-symbols:cancel-outline'
|
||||||
|
width={24}
|
||||||
|
height={24}
|
||||||
|
className='justify-start text-sm'
|
||||||
|
/>
|
||||||
|
Reject
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
{type !== 'detail' && (
|
{type !== 'detail' && (
|
||||||
|
|||||||
@@ -88,7 +88,7 @@ const DateInput = ({
|
|||||||
|
|
||||||
<div
|
<div
|
||||||
className={cn(
|
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 flex items-center',
|
'input h-12 px-4 py-2 text-base font-normal leading-6 w-full rounded outline-none! transition-all duration-200 flex items-center',
|
||||||
{
|
{
|
||||||
'border-error': isError,
|
'border-error': isError,
|
||||||
'border-success!': isValid,
|
'border-success!': isValid,
|
||||||
|
|||||||
@@ -70,7 +70,7 @@ const FileInput = ({
|
|||||||
onBlur={onBlur}
|
onBlur={onBlur}
|
||||||
disabled={disabled}
|
disabled={disabled}
|
||||||
className={cn(
|
className={cn(
|
||||||
'grow file-input w-full h-12 rounded-lg!',
|
'grow file-input w-full h-12 rounded',
|
||||||
className?.input
|
className?.input
|
||||||
)}
|
)}
|
||||||
readOnly={readOnly}
|
readOnly={readOnly}
|
||||||
|
|||||||
@@ -1,415 +1,59 @@
|
|||||||
'use client';
|
'use client';
|
||||||
|
|
||||||
import {
|
import { ChangeEvent, ReactNode } from 'react';
|
||||||
ChangeEvent,
|
import { NumericFormat, OnValueChange } from 'react-number-format';
|
||||||
ChangeEventHandler,
|
import TextInput, { TextInputProps } from '@/components/input/TextInput';
|
||||||
FocusEventHandler,
|
|
||||||
ReactNode,
|
|
||||||
useEffect,
|
|
||||||
useRef,
|
|
||||||
useState,
|
|
||||||
} from 'react';
|
|
||||||
|
|
||||||
import { cn } from '@/lib/helper';
|
interface NumberInputProps extends Omit<TextInputProps, 'type'> {
|
||||||
import Inputmask from 'inputmask';
|
|
||||||
|
|
||||||
const createInputMask = (
|
|
||||||
maskType: MaskType,
|
|
||||||
decimals: number,
|
|
||||||
thousandSeparator: string,
|
|
||||||
decimalSeparator: string,
|
|
||||||
allowNegative: boolean,
|
|
||||||
oncomplete?: () => void,
|
|
||||||
onincomplete?: () => void,
|
|
||||||
oncleared?: () => void
|
|
||||||
): Inputmask.Instance => {
|
|
||||||
const options: Inputmask.Options = {
|
|
||||||
alias: 'numeric',
|
|
||||||
groupSeparator: thousandSeparator,
|
|
||||||
radixPoint: decimalSeparator,
|
|
||||||
digits: decimals,
|
|
||||||
allowMinus: allowNegative,
|
|
||||||
rightAlign: false,
|
|
||||||
insertMode: true,
|
|
||||||
autoUnmask: false,
|
|
||||||
clearMaskOnLostFocus: false,
|
|
||||||
digitsOptional: decimals > 0,
|
|
||||||
placeholder: '0',
|
|
||||||
numericInput: false,
|
|
||||||
positionCaretOnClick: 'radixFocus',
|
|
||||||
greedy: true,
|
|
||||||
oncomplete,
|
|
||||||
onincomplete,
|
|
||||||
oncleared
|
|
||||||
};
|
|
||||||
|
|
||||||
return new Inputmask(options);
|
|
||||||
};
|
|
||||||
|
|
||||||
export type MaskType = 'currency' | 'weight' | 'decimal' | 'number' | 'text';
|
|
||||||
|
|
||||||
export interface NumberInputProps {
|
|
||||||
label?: string;
|
|
||||||
bottomLabel?: string;
|
|
||||||
name: string;
|
|
||||||
value?: number | string;
|
|
||||||
placeholder?: string;
|
|
||||||
|
|
||||||
className?: {
|
|
||||||
wrapper?: string;
|
|
||||||
label?: string;
|
|
||||||
inputWrapper?: string;
|
|
||||||
input?: string;
|
|
||||||
};
|
|
||||||
|
|
||||||
isError?: boolean;
|
|
||||||
isValid?: boolean;
|
|
||||||
errorMessage?: string;
|
|
||||||
disabled?: boolean;
|
|
||||||
readOnly?: boolean;
|
|
||||||
required?: boolean;
|
|
||||||
isLoading?: boolean;
|
|
||||||
|
|
||||||
startAdornment?: ReactNode;
|
|
||||||
endAdornment?: ReactNode;
|
|
||||||
|
|
||||||
onChange?: ChangeEventHandler<HTMLInputElement>;
|
|
||||||
onBlur?: FocusEventHandler<HTMLInputElement>;
|
|
||||||
onFocus?: FocusEventHandler<HTMLInputElement>;
|
|
||||||
|
|
||||||
maskType?: MaskType;
|
|
||||||
decimals?: number;
|
|
||||||
thousandSeparator?: string;
|
thousandSeparator?: string;
|
||||||
decimalSeparator?: string;
|
decimalSeparator?: string;
|
||||||
currencyPrefix?: string;
|
decimalScale?: number;
|
||||||
weightUnit?: string;
|
|
||||||
|
|
||||||
min?: number;
|
|
||||||
max?: number;
|
|
||||||
allowNegative?: boolean;
|
allowNegative?: boolean;
|
||||||
|
prefix?: string;
|
||||||
oncomplete?: () => void;
|
suffix?: string;
|
||||||
onincomplete?: () => void;
|
fixedDecimalScale?: boolean;
|
||||||
oncleared?: () => void;
|
inputPrefix?: ReactNode;
|
||||||
|
inputSuffix?: ReactNode;
|
||||||
}
|
}
|
||||||
|
|
||||||
const NumberInput = ({
|
const NumberInput = ({
|
||||||
label,
|
|
||||||
bottomLabel,
|
|
||||||
name,
|
|
||||||
value,
|
|
||||||
placeholder,
|
|
||||||
className,
|
|
||||||
isError,
|
|
||||||
isValid,
|
|
||||||
errorMessage,
|
|
||||||
startAdornment,
|
|
||||||
endAdornment,
|
|
||||||
disabled = false,
|
|
||||||
required = false,
|
|
||||||
onChange,
|
|
||||||
onBlur,
|
|
||||||
onFocus,
|
|
||||||
readOnly = false,
|
|
||||||
isLoading = false,
|
|
||||||
maskType = 'number',
|
|
||||||
decimals = 0,
|
|
||||||
thousandSeparator = ',',
|
thousandSeparator = ',',
|
||||||
decimalSeparator = '.',
|
decimalSeparator = '.',
|
||||||
currencyPrefix = 'Rp ',
|
decimalScale = 5,
|
||||||
weightUnit = 'kg',
|
allowNegative = true,
|
||||||
allowNegative = false,
|
onChange,
|
||||||
oncomplete,
|
inputPrefix,
|
||||||
onincomplete,
|
inputSuffix,
|
||||||
oncleared,
|
...restProps
|
||||||
}: NumberInputProps) => {
|
}: NumberInputProps) => {
|
||||||
const inputRef = useRef<HTMLInputElement>(null);
|
const valueChangeHandler: OnValueChange = (
|
||||||
const inputmaskRef = useRef<Inputmask.Instance | null>(null);
|
numberFormatValues,
|
||||||
const [maskComplete, setMaskComplete] = useState<boolean>(false);
|
sourceInfo
|
||||||
const [maskIncomplete, setMaskIncomplete] = useState<boolean>(false);
|
) => {
|
||||||
const [maskCleared, setMaskCleared] = useState<boolean>(false);
|
const newChangeEvent = sourceInfo.event as
|
||||||
|
| ChangeEvent<HTMLInputElement>
|
||||||
|
| undefined;
|
||||||
|
|
||||||
const getInputPrefix = (): string => {
|
if (newChangeEvent) {
|
||||||
switch (maskType) {
|
newChangeEvent.target.value = numberFormatValues.value;
|
||||||
case 'currency':
|
|
||||||
return currencyPrefix;
|
onChange?.(newChangeEvent);
|
||||||
default:
|
|
||||||
return '';
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const getInputSuffix = (): string => {
|
|
||||||
switch (maskType) {
|
|
||||||
case 'weight':
|
|
||||||
return weightUnit;
|
|
||||||
default:
|
|
||||||
return '';
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
if (inputRef.current && !readOnly && !disabled) {
|
|
||||||
if (inputmaskRef.current) {
|
|
||||||
try {
|
|
||||||
inputmaskRef.current.remove();
|
|
||||||
} catch (error) {
|
|
||||||
console.warn('Error removing Inputmask:', error);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const handleComplete = () => {
|
|
||||||
setMaskComplete(true);
|
|
||||||
setMaskIncomplete(false);
|
|
||||||
setMaskCleared(false);
|
|
||||||
if (oncomplete) oncomplete();
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleIncomplete = () => {
|
|
||||||
setMaskIncomplete(true);
|
|
||||||
setMaskComplete(false);
|
|
||||||
setMaskCleared(false);
|
|
||||||
if (onincomplete) onincomplete();
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleCleared = () => {
|
|
||||||
setMaskCleared(true);
|
|
||||||
setMaskComplete(false);
|
|
||||||
setMaskIncomplete(false);
|
|
||||||
if (oncleared) oncleared();
|
|
||||||
};
|
|
||||||
|
|
||||||
const im = createInputMask(
|
|
||||||
maskType,
|
|
||||||
decimals,
|
|
||||||
',',
|
|
||||||
'.',
|
|
||||||
allowNegative,
|
|
||||||
handleComplete,
|
|
||||||
handleIncomplete,
|
|
||||||
handleCleared
|
|
||||||
);
|
|
||||||
|
|
||||||
try {
|
|
||||||
im.mask(inputRef.current);
|
|
||||||
inputmaskRef.current = im;
|
|
||||||
} catch (error) {
|
|
||||||
console.warn('Error applying Inputmask:', error);
|
|
||||||
inputmaskRef.current = null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return () => {
|
|
||||||
if (inputmaskRef.current) {
|
|
||||||
try {
|
|
||||||
inputmaskRef.current.remove();
|
|
||||||
} catch (error) {
|
|
||||||
console.warn('Error removing Inputmask on cleanup:', error);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
};
|
|
||||||
}, [maskType, decimals, thousandSeparator, decimalSeparator, allowNegative, readOnly, disabled, oncomplete, onincomplete, oncleared]);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
if (inputRef.current && value !== undefined) {
|
|
||||||
if (value === null || value === '') {
|
|
||||||
inputRef.current.value = '';
|
|
||||||
} else {
|
|
||||||
inputRef.current.value = String(value);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}, [value]);
|
|
||||||
|
|
||||||
const handleKeyUp = (e: React.KeyboardEvent<HTMLInputElement>) => {
|
|
||||||
const currentValue = (e.currentTarget as HTMLInputElement).value;
|
|
||||||
console.log('✅ After format:', currentValue);
|
|
||||||
|
|
||||||
if (onChange) {
|
|
||||||
const syntheticEvent = {
|
|
||||||
target: {
|
|
||||||
name,
|
|
||||||
value: currentValue,
|
|
||||||
},
|
|
||||||
} as ChangeEvent<HTMLInputElement>;
|
|
||||||
onChange(syntheticEvent);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const inputPrefix = getInputPrefix();
|
|
||||||
const inputSuffix = getInputSuffix();
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div
|
<NumericFormat
|
||||||
className={cn(
|
thousandSeparator={thousandSeparator}
|
||||||
'w-full flex flex-col gap-2 text-start',
|
decimalSeparator={decimalSeparator}
|
||||||
className?.wrapper
|
customInput={TextInput}
|
||||||
)}
|
onValueChange={valueChangeHandler}
|
||||||
>
|
decimalScale={decimalScale}
|
||||||
{label && (
|
allowNegative={allowNegative}
|
||||||
<label
|
inputPrefix={inputPrefix}
|
||||||
htmlFor={name}
|
inputSuffix={inputSuffix}
|
||||||
className={cn(
|
{...restProps}
|
||||||
'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>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<div className='relative flex'>
|
|
||||||
{inputPrefix && (
|
|
||||||
<div
|
|
||||||
className={cn(
|
|
||||||
'inline-flex items-center px-4 py-2 border border-r-0 rounded-l-md transition-all duration-200',
|
|
||||||
{
|
|
||||||
'bg-gray-100 border-gray-300': !disabled,
|
|
||||||
'bg-gray-50 border-gray-200': disabled,
|
|
||||||
}
|
|
||||||
)}
|
|
||||||
>
|
|
||||||
<span
|
|
||||||
className={cn(
|
|
||||||
'text-sm font-medium select-none whitespace-nowrap',
|
|
||||||
{
|
|
||||||
'text-gray-600': !disabled,
|
|
||||||
'text-gray-400': disabled,
|
|
||||||
}
|
|
||||||
)}
|
|
||||||
>
|
|
||||||
{inputPrefix}
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<div
|
|
||||||
className={cn(
|
|
||||||
'input h-12 text-base font-normal leading-6 flex-1 rounded-lg! outline-none! transition-all duration-200 flex items-center bg-white',
|
|
||||||
{
|
|
||||||
'border-error': isError,
|
|
||||||
'border-success!': isValid,
|
|
||||||
'rounded-l-none!': inputPrefix,
|
|
||||||
'rounded-r-none!': inputSuffix,
|
|
||||||
'input-disabled': disabled,
|
|
||||||
'cursor-not-allowed': disabled,
|
|
||||||
'bg-gray-50': disabled,
|
|
||||||
},
|
|
||||||
className?.inputWrapper
|
|
||||||
)}
|
|
||||||
>
|
|
||||||
{startAdornment && startAdornment}
|
|
||||||
|
|
||||||
<input
|
|
||||||
type='text'
|
|
||||||
id={name}
|
|
||||||
name={name}
|
|
||||||
ref={inputRef}
|
|
||||||
placeholder={placeholder || '0'}
|
|
||||||
onKeyUp={handleKeyUp}
|
|
||||||
onFocus={onFocus}
|
|
||||||
onBlur={onBlur}
|
|
||||||
disabled={disabled}
|
|
||||||
className={cn(
|
|
||||||
'grow bg-transparent outline-none',
|
|
||||||
{
|
|
||||||
'cursor-not-allowed': disabled,
|
|
||||||
'text-gray-500': disabled,
|
|
||||||
},
|
|
||||||
className?.input
|
|
||||||
)}
|
|
||||||
readOnly={readOnly}
|
|
||||||
inputMode='text'
|
|
||||||
autoComplete='off'
|
|
||||||
spellCheck={false}
|
|
||||||
/>
|
/>
|
||||||
|
|
||||||
{(isLoading || endAdornment) && (
|
|
||||||
<div className='flex flex-row gap-2'>
|
|
||||||
{isLoading && <span className='loading loading-spinner' />}
|
|
||||||
{endAdornment && endAdornment}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{inputSuffix && (
|
|
||||||
<div
|
|
||||||
className={cn(
|
|
||||||
'inline-flex items-center px-4 py-2 border border-l-0 rounded-r-md transition-all duration-200',
|
|
||||||
{
|
|
||||||
'bg-gray-100 border-gray-300': !disabled,
|
|
||||||
'bg-gray-50 border-gray-200': disabled,
|
|
||||||
}
|
|
||||||
)}
|
|
||||||
>
|
|
||||||
<span
|
|
||||||
className={cn(
|
|
||||||
'text-sm font-medium select-none whitespace-nowrap',
|
|
||||||
{
|
|
||||||
'text-gray-600': !disabled,
|
|
||||||
'text-gray-400': disabled,
|
|
||||||
}
|
|
||||||
)}
|
|
||||||
>
|
|
||||||
{inputSuffix}
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{(maskType === 'text' || (oncomplete || onincomplete || oncleared)) && (
|
|
||||||
<div className='flex gap-2 text-xs'>
|
|
||||||
<span
|
|
||||||
className={cn(
|
|
||||||
'px-2 py-1 rounded transition-all duration-200',
|
|
||||||
maskComplete
|
|
||||||
? 'bg-green-100 text-green-700 border border-green-200'
|
|
||||||
: 'bg-gray-50 text-gray-400 border border-gray-200'
|
|
||||||
)}
|
|
||||||
>
|
|
||||||
Complete
|
|
||||||
</span>
|
|
||||||
<span
|
|
||||||
className={cn(
|
|
||||||
'px-2 py-1 rounded transition-all duration-200',
|
|
||||||
maskIncomplete
|
|
||||||
? 'bg-yellow-100 text-yellow-700 border border-yellow-200'
|
|
||||||
: 'bg-gray-50 text-gray-400 border border-gray-200'
|
|
||||||
)}
|
|
||||||
>
|
|
||||||
Incomplete
|
|
||||||
</span>
|
|
||||||
<span
|
|
||||||
className={cn(
|
|
||||||
'px-2 py-1 rounded transition-all duration-200',
|
|
||||||
maskCleared
|
|
||||||
? 'bg-blue-100 text-blue-700 border border-blue-200'
|
|
||||||
: 'bg-gray-50 text-gray-400 border border-gray-200'
|
|
||||||
)}
|
|
||||||
>
|
|
||||||
Cleared
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{!isError && bottomLabel && (
|
|
||||||
<p className='w-full text-sm opacity-60'>{bottomLabel}</p>
|
|
||||||
)}
|
|
||||||
{isError && errorMessage && (
|
|
||||||
<p className='w-full text-sm text-error'>{errorMessage}</p>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
export default NumberInput;
|
export default NumberInput;
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,60 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
import { ChangeEvent } from 'react';
|
||||||
|
import { PatternFormat, OnValueChange } from 'react-number-format';
|
||||||
|
import TextInput, { TextInputProps } from '@/components/input/TextInput';
|
||||||
|
|
||||||
|
interface PatternInputProps extends Omit<TextInputProps, 'type'> {
|
||||||
|
type?: 'password' | 'tel' | 'text' | undefined;
|
||||||
|
|
||||||
|
/** Format pattern, e.g. "##/##/####", "(###) ###-####", "####-####-####" */
|
||||||
|
format: string;
|
||||||
|
|
||||||
|
/** Mask character for empty slots, e.g. "_" */
|
||||||
|
mask?: string;
|
||||||
|
|
||||||
|
/** Allow showing mask even when value is empty */
|
||||||
|
allowEmptyFormatting?: boolean;
|
||||||
|
|
||||||
|
patternChar?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
const PatternInput = ({
|
||||||
|
type = 'text',
|
||||||
|
format,
|
||||||
|
mask = '_',
|
||||||
|
allowEmptyFormatting = false,
|
||||||
|
patternChar = '#',
|
||||||
|
onChange,
|
||||||
|
...restProps
|
||||||
|
}: PatternInputProps) => {
|
||||||
|
const valueChangeHandler: OnValueChange = (
|
||||||
|
patternFormatValues,
|
||||||
|
sourceInfo
|
||||||
|
) => {
|
||||||
|
const newChangeEvent = sourceInfo.event as
|
||||||
|
| ChangeEvent<HTMLInputElement>
|
||||||
|
| undefined;
|
||||||
|
|
||||||
|
if (newChangeEvent) {
|
||||||
|
newChangeEvent.target.value = patternFormatValues.value;
|
||||||
|
|
||||||
|
onChange?.(newChangeEvent);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<PatternFormat
|
||||||
|
type={type}
|
||||||
|
format={format}
|
||||||
|
mask={mask}
|
||||||
|
allowEmptyFormatting={allowEmptyFormatting}
|
||||||
|
patternChar={patternChar}
|
||||||
|
customInput={TextInput}
|
||||||
|
onValueChange={valueChangeHandler}
|
||||||
|
{...restProps}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default PatternInput;
|
||||||
@@ -1,6 +1,8 @@
|
|||||||
'use client';
|
'use client';
|
||||||
|
|
||||||
import { ComponentType, ReactNode, useEffect, useMemo, useState } from 'react';
|
import { ComponentType, ReactNode, useEffect, useMemo, useState } from 'react';
|
||||||
|
import useSWR from 'swr';
|
||||||
|
|
||||||
import Select, {
|
import Select, {
|
||||||
OptionProps,
|
OptionProps,
|
||||||
GroupBase,
|
GroupBase,
|
||||||
@@ -11,7 +13,10 @@ import Select, {
|
|||||||
import CreatableSelect from 'react-select/creatable';
|
import CreatableSelect from 'react-select/creatable';
|
||||||
import makeAnimated from 'react-select/animated';
|
import makeAnimated from 'react-select/animated';
|
||||||
import { useDebounce } from 'use-debounce';
|
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 {
|
export interface OptionType {
|
||||||
value: string | number;
|
value: string | number;
|
||||||
@@ -48,6 +53,7 @@ interface SelectInputBaseProps<T = OptionType> {
|
|||||||
openMenu?: boolean;
|
openMenu?: boolean;
|
||||||
delay?: number;
|
delay?: number;
|
||||||
onInputChange?: (search: string) => void;
|
onInputChange?: (search: string) => void;
|
||||||
|
startAdornment?: ReactNode;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface SelectInputProps<T = OptionType> extends SelectInputBaseProps<T> {
|
interface SelectInputProps<T = OptionType> extends SelectInputBaseProps<T> {
|
||||||
@@ -82,6 +88,7 @@ const SelectInput = <T extends OptionType>(props: SelectInputProps<T>) => {
|
|||||||
delay = 300,
|
delay = 300,
|
||||||
createables = false,
|
createables = false,
|
||||||
onInputChange,
|
onInputChange,
|
||||||
|
startAdornment,
|
||||||
} = props;
|
} = props;
|
||||||
|
|
||||||
const [internalInputValue, setInternalInputValue] = useState('');
|
const [internalInputValue, setInternalInputValue] = useState('');
|
||||||
@@ -144,7 +151,7 @@ const SelectInput = <T extends OptionType>(props: SelectInputProps<T>) => {
|
|||||||
<SelectComponent<T, boolean, GroupBase<T>>
|
<SelectComponent<T, boolean, GroupBase<T>>
|
||||||
instanceId='select'
|
instanceId='select'
|
||||||
value={value ?? (isMulti ? [] : null)}
|
value={value ?? (isMulti ? [] : null)}
|
||||||
onChange={handleChange}
|
onChange={onChange ? handleChange : undefined}
|
||||||
options={options}
|
options={options}
|
||||||
menuIsOpen={openMenu}
|
menuIsOpen={openMenu}
|
||||||
inputValue={internalInputValue}
|
inputValue={internalInputValue}
|
||||||
@@ -160,7 +167,7 @@ const SelectInput = <T extends OptionType>(props: SelectInputProps<T>) => {
|
|||||||
classNames={{
|
classNames={{
|
||||||
control: ({ isFocused, isDisabled }) =>
|
control: ({ isFocused, isDisabled }) =>
|
||||||
cn(
|
cn(
|
||||||
'w-full min-h-12! rounded-lg! border bg-white transition-shadow cursor-pointer!',
|
'w-full min-h-12! rounded border bg-white transition-shadow cursor-pointer!',
|
||||||
{
|
{
|
||||||
'border-red-500! ring-2 ring-red-200': isError,
|
'border-red-500! ring-2 ring-red-200': isError,
|
||||||
'border-indigo-500 ring-2 ring-indigo-200': isFocused,
|
'border-indigo-500 ring-2 ring-indigo-200': isFocused,
|
||||||
@@ -176,16 +183,16 @@ const SelectInput = <T extends OptionType>(props: SelectInputProps<T>) => {
|
|||||||
input: () => cn('text-gray-900'),
|
input: () => cn('text-gray-900'),
|
||||||
indicatorsContainer: () => cn('flex items-center gap-1 pr-2'),
|
indicatorsContainer: () => cn('flex items-center gap-1 pr-2'),
|
||||||
dropdownIndicator: ({ isFocused }) =>
|
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-900': isFocused,
|
||||||
'text-gray-500': !isFocused,
|
'text-gray-500': !isFocused,
|
||||||
'text-error!': isError,
|
'text-error!': isError,
|
||||||
}),
|
}),
|
||||||
menu: () =>
|
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'),
|
menuList: () => cn('p-2! max-h-60 overflow-auto'),
|
||||||
option: ({ isFocused, isSelected }) =>
|
option: ({ isFocused, isSelected }) =>
|
||||||
cn('mt-1 px-3 py-2 rounded-md cursor-pointer!', {
|
cn('mt-1 px-3 py-2 rounded cursor-pointer!', {
|
||||||
'bg-indigo-600 text-white': isFocused,
|
'bg-indigo-600 text-white': isFocused,
|
||||||
'bg-blue-500!': isSelected,
|
'bg-blue-500!': isSelected,
|
||||||
'text-gray-700': !isFocused && !isSelected,
|
'text-gray-700': !isFocused && !isSelected,
|
||||||
@@ -193,7 +200,7 @@ const SelectInput = <T extends OptionType>(props: SelectInputProps<T>) => {
|
|||||||
multiValue: ({ getValue, index }) => {
|
multiValue: ({ getValue, index }) => {
|
||||||
const selectedValues = getValue() as T[];
|
const selectedValues = getValue() as T[];
|
||||||
return cn(
|
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
|
selectedValues[index]?.className
|
||||||
);
|
);
|
||||||
},
|
},
|
||||||
@@ -205,6 +212,28 @@ const SelectInput = <T extends OptionType>(props: SelectInputProps<T>) => {
|
|||||||
components={{
|
components={{
|
||||||
...components,
|
...components,
|
||||||
...(optionComponent ? { Option: optionComponent } : {}),
|
...(optionComponent ? { Option: optionComponent } : {}),
|
||||||
|
...(startAdornment ? {
|
||||||
|
Control: ({ children, innerRef, innerProps, menuIsOpen, isFocused, isDisabled }) => (
|
||||||
|
<div
|
||||||
|
ref={innerRef}
|
||||||
|
{...innerProps}
|
||||||
|
className={cn(
|
||||||
|
'w-full min-h-12! rounded-lg! border bg-white transition-shadow cursor-pointer! flex items-center',
|
||||||
|
{
|
||||||
|
'border-red-500! ring-2 ring-red-200': isError,
|
||||||
|
'border-indigo-500 ring-2 ring-indigo-200': isFocused,
|
||||||
|
'border-gray-300': !isError && !isFocused,
|
||||||
|
'bg-gray-100 text-gray-400 cursor-not-allowed': isDisabled,
|
||||||
|
}
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
<div className='flex-1 px-4! gap-1 flex items-center'>
|
||||||
|
{startAdornment}
|
||||||
|
{children}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
),
|
||||||
|
} : {}),
|
||||||
}}
|
}}
|
||||||
menuPortalTarget={
|
menuPortalTarget={
|
||||||
typeof document !== 'undefined' ? document.body : undefined
|
typeof document !== 'undefined' ? document.body : undefined
|
||||||
@@ -222,4 +251,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<T, number>(item, valueKey as string),
|
||||||
|
label: getByPath<T, string>(item, labelKey as string),
|
||||||
|
};
|
||||||
|
})
|
||||||
|
: [];
|
||||||
|
|
||||||
|
return {
|
||||||
|
inputValue,
|
||||||
|
setInputValue,
|
||||||
|
options,
|
||||||
|
isLoadingOptions: isLoading,
|
||||||
|
rawData: data,
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
export { useSelect };
|
||||||
export default SelectInput;
|
export default SelectInput;
|
||||||
|
|||||||
@@ -83,7 +83,7 @@ const TextArea = ({
|
|||||||
|
|
||||||
<textarea
|
<textarea
|
||||||
className={cn(
|
className={cn(
|
||||||
'input h-auto px-4 py-2 text-base font-normal leading-6 w-full rounded-lg! outline-none! transition-all bg-white',
|
'input h-auto px-4 py-2 text-base font-normal leading-6 w-full rounded outline-none! transition-all bg-white',
|
||||||
{
|
{
|
||||||
'border-error': isError,
|
'border-error': isError,
|
||||||
'border-success!': isValid,
|
'border-success!': isValid,
|
||||||
|
|||||||
@@ -31,6 +31,8 @@ export interface TextInputProps {
|
|||||||
errorMessage?: string;
|
errorMessage?: string;
|
||||||
startAdornment?: ReactNode;
|
startAdornment?: ReactNode;
|
||||||
endAdornment?: ReactNode;
|
endAdornment?: ReactNode;
|
||||||
|
inputPrefix?: ReactNode;
|
||||||
|
inputSuffix?: ReactNode;
|
||||||
onChange?: ChangeEventHandler<HTMLInputElement>;
|
onChange?: ChangeEventHandler<HTMLInputElement>;
|
||||||
onBlur?: FocusEventHandler<HTMLInputElement>;
|
onBlur?: FocusEventHandler<HTMLInputElement>;
|
||||||
}
|
}
|
||||||
@@ -48,6 +50,8 @@ const TextInput = ({
|
|||||||
errorMessage,
|
errorMessage,
|
||||||
startAdornment,
|
startAdornment,
|
||||||
endAdornment,
|
endAdornment,
|
||||||
|
inputPrefix,
|
||||||
|
inputSuffix,
|
||||||
disabled = false,
|
disabled = false,
|
||||||
required = false,
|
required = false,
|
||||||
onChange,
|
onChange,
|
||||||
@@ -85,6 +89,83 @@ const TextInput = ({
|
|||||||
</label>
|
</label>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
{inputPrefix || inputSuffix ? (
|
||||||
|
<div className='relative flex'>
|
||||||
|
{inputPrefix && (
|
||||||
|
<div
|
||||||
|
className={cn(
|
||||||
|
'inline-flex items-center px-4 py-2 border border-r-0 rounded-l-md transition-all duration-200',
|
||||||
|
{
|
||||||
|
'bg-gray-100 border-gray-300': !disabled,
|
||||||
|
'bg-gray-50 border-gray-200': disabled,
|
||||||
|
}
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{inputPrefix}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<div
|
||||||
|
className={cn(
|
||||||
|
'input h-12 text-base font-normal leading-6 flex-1 rounded-lg! outline-none! transition-all duration-200 flex items-center bg-white',
|
||||||
|
{
|
||||||
|
'border-error': isError,
|
||||||
|
'border-success!': isValid,
|
||||||
|
'rounded-l-none!': inputPrefix,
|
||||||
|
'rounded-r-none!': inputSuffix,
|
||||||
|
'input-disabled': disabled,
|
||||||
|
'cursor-not-allowed': disabled,
|
||||||
|
'bg-gray-50': disabled,
|
||||||
|
},
|
||||||
|
className?.inputWrapper
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{startAdornment && startAdornment}
|
||||||
|
|
||||||
|
<input
|
||||||
|
type={type}
|
||||||
|
id={name}
|
||||||
|
name={name}
|
||||||
|
placeholder={placeholder}
|
||||||
|
value={value}
|
||||||
|
onChange={onChange}
|
||||||
|
onBlur={onBlur}
|
||||||
|
disabled={disabled}
|
||||||
|
className={cn(
|
||||||
|
'grow bg-transparent outline-none',
|
||||||
|
{
|
||||||
|
'cursor-not-allowed': disabled,
|
||||||
|
'text-gray-500': disabled,
|
||||||
|
},
|
||||||
|
className?.input
|
||||||
|
)}
|
||||||
|
readOnly={readOnly}
|
||||||
|
/>
|
||||||
|
|
||||||
|
{(isLoading || endAdornment) && (
|
||||||
|
<div className='flex flex-row gap-2'>
|
||||||
|
{isLoading && <span className='loading loading-spinner' />}
|
||||||
|
|
||||||
|
{endAdornment && endAdornment}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{inputSuffix && (
|
||||||
|
<div
|
||||||
|
className={cn(
|
||||||
|
'inline-flex items-center px-4 py-2 border border-l-0 rounded-r-md transition-all duration-200',
|
||||||
|
{
|
||||||
|
'bg-gray-100 border-gray-300': !disabled,
|
||||||
|
'bg-gray-50 border-gray-200': disabled,
|
||||||
|
}
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{inputSuffix}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
<div
|
<div
|
||||||
className={cn(
|
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 bg-white',
|
'input h-12 px-4 py-2 text-base font-normal leading-6 w-full rounded-lg! outline-none! transition-all duration-200 bg-white',
|
||||||
@@ -118,6 +199,7 @@ const TextInput = ({
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
{!isError && bottomLabel && (
|
{!isError && bottomLabel && (
|
||||||
<p className='w-full text-sm opacity-60'>{bottomLabel}</p>
|
<p className='w-full text-sm opacity-60'>{bottomLabel}</p>
|
||||||
|
|||||||
@@ -30,6 +30,7 @@ import { ProductWarehouseApi } from '@/services/api/inventory';
|
|||||||
import { toast } from 'react-hot-toast';
|
import { toast } from 'react-hot-toast';
|
||||||
import FileInput from '@/components/input/FileInput';
|
import FileInput from '@/components/input/FileInput';
|
||||||
import CheckboxInput from '@/components/input/CheckboxInput';
|
import CheckboxInput from '@/components/input/CheckboxInput';
|
||||||
|
import Badge from '@/components/Badge';
|
||||||
|
|
||||||
interface MovementFormProps {
|
interface MovementFormProps {
|
||||||
type?: 'add' | 'edit' | 'detail';
|
type?: 'add' | 'edit' | 'detail';
|
||||||
@@ -37,6 +38,7 @@ interface MovementFormProps {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const MovementForm = ({ type = 'add', initialValues }: MovementFormProps) => {
|
const MovementForm = ({ type = 'add', initialValues }: MovementFormProps) => {
|
||||||
|
// ===== STATE MANAGEMENT =====
|
||||||
const [, setMovementFormErrorMessage] = useState('');
|
const [, setMovementFormErrorMessage] = useState('');
|
||||||
const [
|
const [
|
||||||
productWarehouseSelectInputValue,
|
productWarehouseSelectInputValue,
|
||||||
@@ -44,17 +46,94 @@ const MovementForm = ({ type = 'add', initialValues }: MovementFormProps) => {
|
|||||||
] = useState('');
|
] = useState('');
|
||||||
const [selectedProducts, setSelectedProducts] = useState<number[]>([]);
|
const [selectedProducts, setSelectedProducts] = useState<number[]>([]);
|
||||||
const [selectedDeliveries, setSelectedDeliveries] = useState<number[]>([]);
|
const [selectedDeliveries, setSelectedDeliveries] = useState<number[]>([]);
|
||||||
|
const [warehouseSelectInputValue, setWarehouseSelectInputValue] =
|
||||||
|
useState('');
|
||||||
|
const [supplierSelectInputValue, setSupplierSelectInputValue] = useState('');
|
||||||
|
|
||||||
|
// ===== FORM HANDLERS =====
|
||||||
const {
|
const {
|
||||||
deleteModal,
|
|
||||||
movementFormErrorMessage,
|
movementFormErrorMessage,
|
||||||
isDeleteLoading,
|
|
||||||
createMovementHandler,
|
createMovementHandler,
|
||||||
updateMovementHandler,
|
updateMovementHandler,
|
||||||
deleteMovementClickHandler,
|
|
||||||
confirmationModalDeleteClickHandler,
|
|
||||||
} = useMovementFormHandlers(initialValues?.id);
|
} = useMovementFormHandlers(initialValues?.id);
|
||||||
|
|
||||||
|
// ===== INTERFACES =====
|
||||||
|
interface WarehouseOptionType extends OptionType {
|
||||||
|
area?: string;
|
||||||
|
location?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ProductWarehouseOptionType extends OptionType {
|
||||||
|
product_id: number;
|
||||||
|
warehouse_id: number;
|
||||||
|
warehouse_name: string;
|
||||||
|
quantity: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ===== API DATA FETCHING =====
|
||||||
|
const allProductWarehousesUrl = `${ProductWarehouseApi.basePath}`;
|
||||||
|
const { data: allProductWarehouses } = useSWR(
|
||||||
|
allProductWarehousesUrl,
|
||||||
|
ProductWarehouseApi.getAllFetcher
|
||||||
|
);
|
||||||
|
|
||||||
|
const warehousesUrl = `${WarehouseApi.basePath}?${new URLSearchParams({ search: warehouseSelectInputValue }).toString()}`;
|
||||||
|
const { data: warehouses, isLoading: isLoadingWarehouses } = useSWR(
|
||||||
|
warehousesUrl,
|
||||||
|
WarehouseApi.getAllFetcher
|
||||||
|
);
|
||||||
|
|
||||||
|
const suppliersUrl = `${SupplierApi.basePath}?${new URLSearchParams({ search: supplierSelectInputValue }).toString()}`;
|
||||||
|
const { data: suppliers, isLoading: isLoadingSuppliers } = useSWR(
|
||||||
|
suppliersUrl,
|
||||||
|
SupplierApi.getAllFetcher
|
||||||
|
);
|
||||||
|
|
||||||
|
// ===== DATA PROCESSING =====
|
||||||
|
const warehouseStockMap = useMemo(() => {
|
||||||
|
if (!isResponseSuccess(allProductWarehouses)) return new Map();
|
||||||
|
|
||||||
|
const stockMap = new Map<
|
||||||
|
number,
|
||||||
|
{ totalQty: number; productCount: number }
|
||||||
|
>();
|
||||||
|
|
||||||
|
allProductWarehouses.data.forEach((pw) => {
|
||||||
|
const warehouseId = pw.warehouse.id;
|
||||||
|
const existing = stockMap.get(warehouseId) || {
|
||||||
|
totalQty: 0,
|
||||||
|
productCount: 0,
|
||||||
|
};
|
||||||
|
|
||||||
|
stockMap.set(warehouseId, {
|
||||||
|
totalQty: existing.totalQty + pw.quantity,
|
||||||
|
productCount: existing.productCount + 1,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
return stockMap;
|
||||||
|
}, [allProductWarehouses]);
|
||||||
|
|
||||||
|
const warehouseOptions = isResponseSuccess(warehouses)
|
||||||
|
? warehouses?.data.map((w) => {
|
||||||
|
warehouseStockMap.get(w.id);
|
||||||
|
return {
|
||||||
|
value: w.id,
|
||||||
|
label: w.name,
|
||||||
|
area: w.area?.name,
|
||||||
|
location:
|
||||||
|
'type' in w && (w.type === 'LOKASI' || w.type === 'KANDANG')
|
||||||
|
? w.location?.name
|
||||||
|
: undefined,
|
||||||
|
};
|
||||||
|
})
|
||||||
|
: [];
|
||||||
|
|
||||||
|
const supplierOptions = isResponseSuccess(suppliers)
|
||||||
|
? suppliers?.data.map((s) => ({ value: s.id, label: s.name }))
|
||||||
|
: [];
|
||||||
|
|
||||||
|
// ===== FORM INITIALIZATION =====
|
||||||
const formikInitialValues = useMemo<MovementFormValues>(
|
const formikInitialValues = useMemo<MovementFormValues>(
|
||||||
() => getMovementFormInitialValues(initialValues),
|
() => getMovementFormInitialValues(initialValues),
|
||||||
[initialValues]
|
[initialValues]
|
||||||
@@ -77,7 +156,6 @@ const MovementForm = ({ type = 'add', initialValues }: MovementFormProps) => {
|
|||||||
if (d.document && d.document instanceof File) {
|
if (d.document && d.document instanceof File) {
|
||||||
documents.push(d.document);
|
documents.push(d.document);
|
||||||
documentIndex = documents.length - 1;
|
documentIndex = documents.length - 1;
|
||||||
} else {
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
@@ -122,91 +200,39 @@ const MovementForm = ({ type = 'add', initialValues }: MovementFormProps) => {
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
const addProduct = () => {
|
// ===== PRODUCT WAREHOUSE FETCHING (after form initialization) =====
|
||||||
const newProducts = [
|
const getProductWarehousesUrl = useCallback(() => {
|
||||||
...(formik.values.products || []),
|
const productWarehouseParams = new URLSearchParams({
|
||||||
{
|
search: productWarehouseSelectInputValue,
|
||||||
product: null,
|
});
|
||||||
product_id: 0,
|
if (formik.values.source_warehouse_id) {
|
||||||
product_qty: 0,
|
productWarehouseParams.append(
|
||||||
},
|
'warehouse_id',
|
||||||
];
|
formik.values.source_warehouse_id.toString()
|
||||||
formik.setFieldValue('products', newProducts);
|
);
|
||||||
};
|
|
||||||
|
|
||||||
const removeProduct = useCallback(
|
|
||||||
(i: number) => {
|
|
||||||
const updatedProducts =
|
|
||||||
formik.values.products?.reduce((acc: ProductSchema[], item, index) => {
|
|
||||||
if (index !== i) {
|
|
||||||
acc.push(item);
|
|
||||||
}
|
}
|
||||||
return acc;
|
return `${ProductWarehouseApi.basePath}?${productWarehouseParams.toString()}`;
|
||||||
}, []) ?? [];
|
}, [formik.values.source_warehouse_id, productWarehouseSelectInputValue]);
|
||||||
|
|
||||||
formik.setFieldValue('products', updatedProducts);
|
const productWarehousesUrl = getProductWarehousesUrl();
|
||||||
},
|
const { data: productWarehouses, isLoading: isLoadingProductWarehouses } =
|
||||||
[formik]
|
useSWR(
|
||||||
|
formik.values.source_warehouse_id ? productWarehousesUrl : null,
|
||||||
|
ProductWarehouseApi.getAllFetcher
|
||||||
);
|
);
|
||||||
|
|
||||||
const bulkRemoveProduct = useCallback(() => {
|
const productWarehouseOptions = isResponseSuccess(productWarehouses)
|
||||||
const updatedProducts =
|
? productWarehouses?.data.map((pw) => ({
|
||||||
formik.values.products?.filter(
|
value: pw.product.id,
|
||||||
(_, idx) => !selectedProducts.includes(idx)
|
label: pw.product.name,
|
||||||
) ?? [];
|
product_id: pw.product.id,
|
||||||
formik.setFieldValue('products', updatedProducts);
|
warehouse_id: pw.warehouse.id,
|
||||||
setSelectedProducts([]);
|
warehouse_name: pw.warehouse.name,
|
||||||
}, [formik, selectedProducts]);
|
quantity: pw.quantity,
|
||||||
|
}))
|
||||||
const addDelivery = () => {
|
: [];
|
||||||
formik.setFieldValue('deliveries', [
|
|
||||||
...(formik.values.deliveries || []),
|
|
||||||
{
|
|
||||||
delivery_cost: undefined,
|
|
||||||
delivery_cost_per_item: undefined,
|
|
||||||
document: null,
|
|
||||||
driver_name: '',
|
|
||||||
vehicle_plate: '',
|
|
||||||
supplier: null,
|
|
||||||
supplier_id: 0,
|
|
||||||
products: [
|
|
||||||
{
|
|
||||||
product: null,
|
|
||||||
product_id: 0,
|
|
||||||
product_qty: 0,
|
|
||||||
},
|
|
||||||
],
|
|
||||||
},
|
|
||||||
]);
|
|
||||||
};
|
|
||||||
|
|
||||||
const removeDelivery = useCallback(
|
|
||||||
(i: number) => {
|
|
||||||
const updatedDeliveries =
|
|
||||||
formik.values.deliveries?.reduce(
|
|
||||||
(acc: DeliverySchema[], item, index) => {
|
|
||||||
if (index !== i) {
|
|
||||||
acc.push(item);
|
|
||||||
}
|
|
||||||
return acc;
|
|
||||||
},
|
|
||||||
[]
|
|
||||||
) ?? [];
|
|
||||||
|
|
||||||
formik.setFieldValue('deliveries', updatedDeliveries);
|
|
||||||
},
|
|
||||||
[formik]
|
|
||||||
);
|
|
||||||
|
|
||||||
const bulkRemoveDelivery = useCallback(() => {
|
|
||||||
const updatedDeliveries =
|
|
||||||
formik.values.deliveries?.filter(
|
|
||||||
(_, idx) => !selectedDeliveries.includes(idx)
|
|
||||||
) ?? [];
|
|
||||||
formik.setFieldValue('deliveries', updatedDeliveries);
|
|
||||||
setSelectedDeliveries([]);
|
|
||||||
}, [formik, selectedDeliveries]);
|
|
||||||
|
|
||||||
|
// ===== HELPER FUNCTIONS =====
|
||||||
const isRepeaterInputError = <T extends 'products' | 'deliveries'>(
|
const isRepeaterInputError = <T extends 'products' | 'deliveries'>(
|
||||||
arrayName: T,
|
arrayName: T,
|
||||||
column: T extends 'products' ? keyof ProductSchema : keyof DeliverySchema,
|
column: T extends 'products' ? keyof ProductSchema : keyof DeliverySchema,
|
||||||
@@ -263,118 +289,98 @@ const MovementForm = ({ type = 'add', initialValues }: MovementFormProps) => {
|
|||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
|
||||||
interface WarehouseOptionType extends OptionType {
|
// ===== EVENT HANDLERS =====
|
||||||
area?: string;
|
// Product Handlers
|
||||||
location?: string;
|
const addProduct = () => {
|
||||||
}
|
const newProducts = [
|
||||||
|
...(formik.values.products || []),
|
||||||
interface ProductWarehouseOptionType extends OptionType {
|
{
|
||||||
product_id: number;
|
product: null,
|
||||||
warehouse_id: number;
|
product_id: 0,
|
||||||
warehouse_name: string;
|
product_qty: 0,
|
||||||
quantity: number;
|
},
|
||||||
}
|
];
|
||||||
|
formik.setFieldValue('products', newProducts);
|
||||||
const allProductWarehousesUrl = `${ProductWarehouseApi.basePath}`;
|
|
||||||
const { data: allProductWarehouses } = useSWR(
|
|
||||||
allProductWarehousesUrl,
|
|
||||||
ProductWarehouseApi.getAllFetcher
|
|
||||||
);
|
|
||||||
|
|
||||||
const warehouseStockMap = useMemo(() => {
|
|
||||||
if (!isResponseSuccess(allProductWarehouses)) return new Map();
|
|
||||||
|
|
||||||
const stockMap = new Map<
|
|
||||||
number,
|
|
||||||
{ totalQty: number; productCount: number }
|
|
||||||
>();
|
|
||||||
|
|
||||||
allProductWarehouses.data.forEach((pw) => {
|
|
||||||
const warehouseId = pw.warehouse.id;
|
|
||||||
const existing = stockMap.get(warehouseId) || {
|
|
||||||
totalQty: 0,
|
|
||||||
productCount: 0,
|
|
||||||
};
|
};
|
||||||
|
|
||||||
stockMap.set(warehouseId, {
|
const removeProduct = useCallback(
|
||||||
totalQty: existing.totalQty + pw.quantity,
|
(i: number) => {
|
||||||
productCount: existing.productCount + 1,
|
const updatedProducts =
|
||||||
});
|
formik.values.products?.reduce((acc: ProductSchema[], item, index) => {
|
||||||
});
|
if (index !== i) {
|
||||||
|
acc.push(item);
|
||||||
return stockMap;
|
|
||||||
}, [allProductWarehouses]);
|
|
||||||
|
|
||||||
// Warehouse selection
|
|
||||||
const [warehouseSelectInputValue, setWarehouseSelectInputValue] =
|
|
||||||
useState('');
|
|
||||||
const warehousesUrl = `${WarehouseApi.basePath}?${new URLSearchParams({ search: warehouseSelectInputValue }).toString()}`;
|
|
||||||
const { data: warehouses, isLoading: isLoadingWarehouses } = useSWR(
|
|
||||||
warehousesUrl,
|
|
||||||
WarehouseApi.getAllFetcher
|
|
||||||
);
|
|
||||||
const warehouseOptions = isResponseSuccess(warehouses)
|
|
||||||
? warehouses?.data.map((w) => {
|
|
||||||
const stockInfo = warehouseStockMap.get(w.id);
|
|
||||||
const stockLabel = stockInfo
|
|
||||||
? ` (Stock: ${stockInfo.totalQty.toLocaleString('id-ID')} items, ${stockInfo.productCount} produk)`
|
|
||||||
: ' (Kosong)';
|
|
||||||
|
|
||||||
return {
|
|
||||||
value: w.id,
|
|
||||||
label: `${w.name}${stockLabel}`,
|
|
||||||
area: w.area?.name,
|
|
||||||
location:
|
|
||||||
'type' in w && (w.type === 'LOKASI' || w.type === 'KANDANG')
|
|
||||||
? w.location?.name
|
|
||||||
: undefined,
|
|
||||||
};
|
|
||||||
})
|
|
||||||
: [];
|
|
||||||
|
|
||||||
// Product Warehouse selection - Filter by source warehouse
|
|
||||||
const productWarehouseParams = new URLSearchParams({
|
|
||||||
search: productWarehouseSelectInputValue,
|
|
||||||
});
|
|
||||||
if (formik.values.source_warehouse_id) {
|
|
||||||
productWarehouseParams.append(
|
|
||||||
'warehouse_id',
|
|
||||||
formik.values.source_warehouse_id.toString()
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
const productWarehousesUrl = `${ProductWarehouseApi.basePath}?${productWarehouseParams.toString()}`;
|
return acc;
|
||||||
const { data: productWarehouses, isLoading: isLoadingProductWarehouses } =
|
}, []) ?? [];
|
||||||
useSWR(
|
|
||||||
formik.values.source_warehouse_id ? productWarehousesUrl : null,
|
|
||||||
ProductWarehouseApi.getAllFetcher
|
|
||||||
);
|
|
||||||
const productWarehouseOptions = isResponseSuccess(productWarehouses)
|
|
||||||
? productWarehouses?.data.map((pw) => ({
|
|
||||||
value: pw.product.id,
|
|
||||||
label: `${pw.product.name} - ${pw.warehouse.name} (Stock: ${pw.quantity.toLocaleString('id-ID')})`,
|
|
||||||
product_id: pw.product.id,
|
|
||||||
warehouse_id: pw.warehouse.id,
|
|
||||||
warehouse_name: pw.warehouse.name,
|
|
||||||
quantity: pw.quantity,
|
|
||||||
}))
|
|
||||||
: [];
|
|
||||||
|
|
||||||
// Supplier selection
|
formik.setFieldValue('products', updatedProducts);
|
||||||
const [supplierSelectInputValue, setSupplierSelectInputValue] = useState('');
|
},
|
||||||
const suppliersUrl = `${SupplierApi.basePath}?${new URLSearchParams({ search: supplierSelectInputValue }).toString()}`;
|
[formik]
|
||||||
const { data: suppliers, isLoading: isLoadingSuppliers } = useSWR(
|
|
||||||
suppliersUrl,
|
|
||||||
SupplierApi.getAllFetcher
|
|
||||||
);
|
);
|
||||||
const supplierOptions = isResponseSuccess(suppliers)
|
|
||||||
? suppliers?.data.map((s) => ({ value: s.id, label: s.name }))
|
|
||||||
: [];
|
|
||||||
|
|
||||||
// Handle cost calculation when delivery_cost changes
|
const bulkRemoveProduct = useCallback(() => {
|
||||||
|
const updatedProducts =
|
||||||
|
formik.values.products?.filter(
|
||||||
|
(_, idx) => !selectedProducts.includes(idx)
|
||||||
|
) ?? [];
|
||||||
|
formik.setFieldValue('products', updatedProducts);
|
||||||
|
setSelectedProducts([]);
|
||||||
|
}, [formik, selectedProducts]);
|
||||||
|
|
||||||
|
// Delivery Handlers
|
||||||
|
const addDelivery = () => {
|
||||||
|
formik.setFieldValue('deliveries', [
|
||||||
|
...(formik.values.deliveries || []),
|
||||||
|
{
|
||||||
|
delivery_cost: undefined,
|
||||||
|
delivery_cost_per_item: undefined,
|
||||||
|
document: null,
|
||||||
|
driver_name: '',
|
||||||
|
vehicle_plate: '',
|
||||||
|
supplier: null,
|
||||||
|
supplier_id: 0,
|
||||||
|
products: [
|
||||||
|
{
|
||||||
|
product: null,
|
||||||
|
product_id: 0,
|
||||||
|
product_qty: 0,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
};
|
||||||
|
|
||||||
|
const removeDelivery = useCallback(
|
||||||
|
(i: number) => {
|
||||||
|
const updatedDeliveries =
|
||||||
|
formik.values.deliveries?.reduce(
|
||||||
|
(acc: DeliverySchema[], item, index) => {
|
||||||
|
if (index !== i) {
|
||||||
|
acc.push(item);
|
||||||
|
}
|
||||||
|
return acc;
|
||||||
|
},
|
||||||
|
[]
|
||||||
|
) ?? [];
|
||||||
|
|
||||||
|
formik.setFieldValue('deliveries', updatedDeliveries);
|
||||||
|
},
|
||||||
|
[formik]
|
||||||
|
);
|
||||||
|
|
||||||
|
const bulkRemoveDelivery = useCallback(() => {
|
||||||
|
const updatedDeliveries =
|
||||||
|
formik.values.deliveries?.filter(
|
||||||
|
(_, idx) => !selectedDeliveries.includes(idx)
|
||||||
|
) ?? [];
|
||||||
|
formik.setFieldValue('deliveries', updatedDeliveries);
|
||||||
|
setSelectedDeliveries([]);
|
||||||
|
}, [formik, selectedDeliveries]);
|
||||||
|
|
||||||
|
// Cost Calculation Handlers
|
||||||
const handleDeliveryCostChange = useCallback(
|
const handleDeliveryCostChange = useCallback(
|
||||||
(idx: number, value: string) => {
|
(idx: number, value: number) => {
|
||||||
const numValue = parseFloat(value) || 0;
|
formik.setFieldValue(`deliveries.${idx}.delivery_cost`, value);
|
||||||
formik.setFieldValue(`deliveries.${idx}.delivery_cost`, numValue);
|
|
||||||
|
|
||||||
const delivery = formik.values.deliveries?.[idx];
|
const delivery = formik.values.deliveries?.[idx];
|
||||||
if (delivery) {
|
if (delivery) {
|
||||||
@@ -382,13 +388,13 @@ const MovementForm = ({ type = 'add', initialValues }: MovementFormProps) => {
|
|||||||
(sum, p) => sum + p.product_qty,
|
(sum, p) => sum + p.product_qty,
|
||||||
0
|
0
|
||||||
);
|
);
|
||||||
if (productQty > 0 && numValue > 0) {
|
if (productQty > 0 && value > 0) {
|
||||||
const perItem = numValue / productQty;
|
const perItem = value / productQty;
|
||||||
formik.setFieldValue(
|
formik.setFieldValue(
|
||||||
`deliveries.${idx}.delivery_cost_per_item`,
|
`deliveries.${idx}.delivery_cost_per_item`,
|
||||||
perItem
|
perItem
|
||||||
);
|
);
|
||||||
} else if (numValue === 0) {
|
} else if (value === 0) {
|
||||||
formik.setFieldValue(`deliveries.${idx}.delivery_cost_per_item`, 0);
|
formik.setFieldValue(`deliveries.${idx}.delivery_cost_per_item`, 0);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -396,14 +402,9 @@ const MovementForm = ({ type = 'add', initialValues }: MovementFormProps) => {
|
|||||||
[formik]
|
[formik]
|
||||||
);
|
);
|
||||||
|
|
||||||
// Handle cost calculation when delivery_cost_per_item changes
|
|
||||||
const handleDeliveryCostPerItemChange = useCallback(
|
const handleDeliveryCostPerItemChange = useCallback(
|
||||||
(idx: number, value: string) => {
|
(idx: number, value: number) => {
|
||||||
const numValue = parseFloat(value) || 0;
|
formik.setFieldValue(`deliveries.${idx}.delivery_cost_per_item`, value);
|
||||||
formik.setFieldValue(
|
|
||||||
`deliveries.${idx}.delivery_cost_per_item`,
|
|
||||||
numValue
|
|
||||||
);
|
|
||||||
|
|
||||||
const delivery = formik.values.deliveries?.[idx];
|
const delivery = formik.values.deliveries?.[idx];
|
||||||
if (delivery) {
|
if (delivery) {
|
||||||
@@ -411,10 +412,10 @@ const MovementForm = ({ type = 'add', initialValues }: MovementFormProps) => {
|
|||||||
(sum, p) => sum + p.product_qty,
|
(sum, p) => sum + p.product_qty,
|
||||||
0
|
0
|
||||||
);
|
);
|
||||||
if (productQty > 0 && numValue > 0) {
|
if (productQty > 0 && value > 0) {
|
||||||
const totalCost = numValue * productQty;
|
const totalCost = value * productQty;
|
||||||
formik.setFieldValue(`deliveries.${idx}.delivery_cost`, totalCost);
|
formik.setFieldValue(`deliveries.${idx}.delivery_cost`, totalCost);
|
||||||
} else if (numValue === 0) {
|
} else if (value === 0) {
|
||||||
formik.setFieldValue(`deliveries.${idx}.delivery_cost`, 0);
|
formik.setFieldValue(`deliveries.${idx}.delivery_cost`, 0);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -422,57 +423,23 @@ const MovementForm = ({ type = 'add', initialValues }: MovementFormProps) => {
|
|||||||
[formik]
|
[formik]
|
||||||
);
|
);
|
||||||
|
|
||||||
// Auto-recalculate when product quantity changes
|
const handleDeliveryCostChangeWrapper = useCallback(
|
||||||
useEffect(() => {
|
(idx: number) => (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||||
formik.values.deliveries?.forEach((delivery, idx) => {
|
const value = parseFloat(e.target.value) || 0;
|
||||||
const productQty = delivery.products.reduce(
|
handleDeliveryCostChange(idx, value);
|
||||||
(sum, p) => sum + p.product_qty,
|
},
|
||||||
0
|
[handleDeliveryCostChange]
|
||||||
);
|
);
|
||||||
|
|
||||||
// If delivery_cost is set, recalculate delivery_cost_per_item
|
const handleDeliveryCostPerItemChangeWrapper = useCallback(
|
||||||
if (
|
(idx: number) => (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||||
delivery.delivery_cost &&
|
const value = parseFloat(e.target.value) || 0;
|
||||||
delivery.delivery_cost > 0 &&
|
handleDeliveryCostPerItemChange(idx, value);
|
||||||
productQty > 0
|
},
|
||||||
) {
|
[handleDeliveryCostPerItemChange]
|
||||||
const perItem = delivery.delivery_cost / productQty;
|
|
||||||
if (Math.abs((delivery.delivery_cost_per_item || 0) - perItem) > 0.01) {
|
|
||||||
formik.setFieldValue(
|
|
||||||
`deliveries.${idx}.delivery_cost_per_item`,
|
|
||||||
perItem
|
|
||||||
);
|
);
|
||||||
}
|
|
||||||
}
|
|
||||||
// If delivery_cost_per_item is set, recalculate delivery_cost
|
|
||||||
else if (
|
|
||||||
delivery.delivery_cost_per_item &&
|
|
||||||
delivery.delivery_cost_per_item > 0 &&
|
|
||||||
productQty > 0
|
|
||||||
) {
|
|
||||||
const totalCost = delivery.delivery_cost_per_item * productQty;
|
|
||||||
if (Math.abs((delivery.delivery_cost || 0) - totalCost) > 0.01) {
|
|
||||||
formik.setFieldValue(`deliveries.${idx}.delivery_cost`, totalCost);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}, [
|
|
||||||
formik.values.deliveries
|
|
||||||
?.map((d) => d.products.reduce((sum, p) => sum + p.product_qty, 0))
|
|
||||||
.join(','),
|
|
||||||
]);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
if (
|
|
||||||
formik.values.source_warehouse_id &&
|
|
||||||
type !== 'edit' &&
|
|
||||||
type !== 'detail'
|
|
||||||
) {
|
|
||||||
formik.setFieldValue('products', []);
|
|
||||||
formik.setFieldValue('deliveries', []);
|
|
||||||
}
|
|
||||||
}, [formik.values.source_warehouse_id]);
|
|
||||||
|
|
||||||
|
// UTILITY FUNCTIONS
|
||||||
const getFilteredProductWarehouseOptions = useCallback(() => {
|
const getFilteredProductWarehouseOptions = useCallback(() => {
|
||||||
return (
|
return (
|
||||||
formik.values.products
|
formik.values.products
|
||||||
@@ -495,31 +462,92 @@ const MovementForm = ({ type = 'add', initialValues }: MovementFormProps) => {
|
|||||||
[productWarehouseOptions, type]
|
[productWarehouseOptions, type]
|
||||||
);
|
);
|
||||||
|
|
||||||
const getProductQtyAdornment = useCallback(
|
const getProductQtyBottomLabel = useCallback(
|
||||||
(productIdx: number) => {
|
(productIdx: number) => {
|
||||||
if (type === 'detail') return null;
|
if (type === 'detail') return undefined;
|
||||||
const product = formik.values.products?.[productIdx];
|
const product = formik.values.products?.[productIdx];
|
||||||
if (!product || !product.product_id) return null;
|
if (!product || !product.product_id) return undefined;
|
||||||
|
|
||||||
const availableStock = getAvailableStock(product.product_id);
|
const availableStock = getAvailableStock(product.product_id);
|
||||||
const requestedQty = Number(product.product_qty) || 0;
|
const requestedQty = Number(product.product_qty) || 0;
|
||||||
const remainingStock = availableStock - requestedQty;
|
const remainingStock = availableStock - requestedQty;
|
||||||
|
|
||||||
if (requestedQty > 0) {
|
if (requestedQty > 0) {
|
||||||
|
return `Sisa: ${remainingStock.toLocaleString('en-US')}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
return `Tersedia: ${availableStock.toLocaleString('en-US')}`;
|
||||||
|
},
|
||||||
|
[formik.values.products, getAvailableStock, type]
|
||||||
|
);
|
||||||
|
|
||||||
|
const getDeliveryProductQtyBottomLabel = useCallback(
|
||||||
|
(deliveryIdx: number, productIdx: number) => {
|
||||||
|
if (type === 'detail') return undefined;
|
||||||
|
const delivery = formik.values.deliveries?.[deliveryIdx];
|
||||||
|
if (!delivery) return undefined;
|
||||||
|
|
||||||
|
const deliveryProduct = delivery.products[productIdx];
|
||||||
|
if (!deliveryProduct || !deliveryProduct.product_id) return undefined;
|
||||||
|
|
||||||
|
const relatedProduct = formik.values.products?.find(
|
||||||
|
(p) => p.product_id === deliveryProduct.product_id
|
||||||
|
);
|
||||||
|
if (!relatedProduct) return undefined;
|
||||||
|
|
||||||
|
const totalQtyUsed =
|
||||||
|
formik.values.deliveries?.reduce((total, d, dIdx) => {
|
||||||
|
const productQty = d.products.reduce((sum, p, pIdx) => {
|
||||||
|
if (
|
||||||
|
p.product_id === deliveryProduct.product_id &&
|
||||||
|
!(dIdx === deliveryIdx && pIdx === productIdx)
|
||||||
|
) {
|
||||||
|
return sum + (Number(p.product_qty) || 0);
|
||||||
|
}
|
||||||
|
return sum;
|
||||||
|
}, 0);
|
||||||
|
return total + productQty;
|
||||||
|
}, 0) || 0;
|
||||||
|
|
||||||
|
const availableQty = Number(relatedProduct.product_qty) - totalQtyUsed;
|
||||||
|
return `Tersedia: ${availableQty.toLocaleString('en-US')}`;
|
||||||
|
},
|
||||||
|
[formik.values.deliveries, formik.values.products, type]
|
||||||
|
);
|
||||||
|
|
||||||
|
const getWarehouseStockAdornment = useCallback(
|
||||||
|
(warehouseId: number) => {
|
||||||
|
const stockInfo = warehouseStockMap.get(warehouseId);
|
||||||
|
if (!stockInfo) {
|
||||||
return (
|
return (
|
||||||
<span className='text-sm text-gray-600 whitespace-nowrap'>
|
<Badge
|
||||||
(sisa: {remainingStock.toLocaleString('id-ID')})
|
variant='ghost'
|
||||||
</span>
|
color='neutral'
|
||||||
|
size='sm'
|
||||||
|
className={{ badge: 'whitespace-nowrap font-semibold' }}
|
||||||
|
>
|
||||||
|
Kosong
|
||||||
|
</Badge>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const { productCount } = stockInfo;
|
||||||
|
let color: 'neutral' | 'success' | 'warning' = 'neutral';
|
||||||
|
if (productCount === 0) color = 'warning';
|
||||||
|
else if (productCount > 0) color = 'success';
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<span className='text-sm text-gray-600 whitespace-nowrap'>
|
<Badge
|
||||||
(tersedia: {availableStock.toLocaleString('id-ID')})
|
variant='soft'
|
||||||
</span>
|
color={color}
|
||||||
|
size='sm'
|
||||||
|
className={{ badge: 'whitespace-nowrap font-semibold' }}
|
||||||
|
>
|
||||||
|
Tersedia {productCount} produk
|
||||||
|
</Badge>
|
||||||
);
|
);
|
||||||
},
|
},
|
||||||
[formik.values.products, getAvailableStock, type]
|
[warehouseStockMap]
|
||||||
);
|
);
|
||||||
|
|
||||||
const getProductQtyError = useCallback(
|
const getProductQtyError = useCallback(
|
||||||
@@ -532,7 +560,7 @@ const MovementForm = ({ type = 'add', initialValues }: MovementFormProps) => {
|
|||||||
const requestedQty = Number(product.product_qty) || 0;
|
const requestedQty = Number(product.product_qty) || 0;
|
||||||
|
|
||||||
if (requestedQty > availableStock) {
|
if (requestedQty > availableStock) {
|
||||||
return `Qty melebihi stok tersedia! Maksimal: ${availableStock.toLocaleString('id-ID')}`;
|
return `Qty melebihi stok tersedia! Maksimal: ${availableStock.toLocaleString('en-US')}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
return null;
|
return null;
|
||||||
@@ -618,6 +646,7 @@ const MovementForm = ({ type = 'add', initialValues }: MovementFormProps) => {
|
|||||||
[formik.values.deliveries, formik.values.products, type]
|
[formik.values.deliveries, formik.values.products, type]
|
||||||
);
|
);
|
||||||
|
|
||||||
|
// ===== COMPUTED VALUES =====
|
||||||
const invalidQtyRows = useMemo(
|
const invalidQtyRows = useMemo(
|
||||||
() =>
|
() =>
|
||||||
type === 'detail'
|
type === 'detail'
|
||||||
@@ -650,6 +679,54 @@ const MovementForm = ({ type = 'add', initialValues }: MovementFormProps) => {
|
|||||||
);
|
);
|
||||||
}, [formik.values.products, getProductQtyError, type]);
|
}, [formik.values.products, getProductQtyError, type]);
|
||||||
|
|
||||||
|
// ===== EFFECTS =====
|
||||||
|
useEffect(() => {
|
||||||
|
formik.values.deliveries?.forEach((delivery, idx) => {
|
||||||
|
const productQty = delivery.products.reduce(
|
||||||
|
(sum, p) => sum + p.product_qty,
|
||||||
|
0
|
||||||
|
);
|
||||||
|
|
||||||
|
if (
|
||||||
|
delivery.delivery_cost &&
|
||||||
|
delivery.delivery_cost > 0 &&
|
||||||
|
productQty > 0
|
||||||
|
) {
|
||||||
|
const perItem = delivery.delivery_cost / productQty;
|
||||||
|
if (Math.abs((delivery.delivery_cost_per_item || 0) - perItem) > 0.01) {
|
||||||
|
formik.setFieldValue(
|
||||||
|
`deliveries.${idx}.delivery_cost_per_item`,
|
||||||
|
perItem
|
||||||
|
);
|
||||||
|
}
|
||||||
|
} else if (
|
||||||
|
delivery.delivery_cost_per_item &&
|
||||||
|
delivery.delivery_cost_per_item > 0 &&
|
||||||
|
productQty > 0
|
||||||
|
) {
|
||||||
|
const totalCost = delivery.delivery_cost_per_item * productQty;
|
||||||
|
if (Math.abs((delivery.delivery_cost || 0) - totalCost) > 0.01) {
|
||||||
|
formik.setFieldValue(`deliveries.${idx}.delivery_cost`, totalCost);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}, [
|
||||||
|
formik.values.deliveries
|
||||||
|
?.map((d) => d.products.reduce((sum, p) => sum + p.product_qty, 0))
|
||||||
|
.join(','),
|
||||||
|
]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (
|
||||||
|
formik.values.source_warehouse_id &&
|
||||||
|
type !== 'edit' &&
|
||||||
|
type !== 'detail'
|
||||||
|
) {
|
||||||
|
formik.setFieldValue('products', []);
|
||||||
|
formik.setFieldValue('deliveries', []);
|
||||||
|
}
|
||||||
|
}, [formik.values.source_warehouse_id]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<section className='w-full'>
|
<section className='w-full'>
|
||||||
@@ -728,6 +805,13 @@ const MovementForm = ({ type = 'add', initialValues }: MovementFormProps) => {
|
|||||||
errorMessage={formik.errors.source_warehouse_id as string}
|
errorMessage={formik.errors.source_warehouse_id as string}
|
||||||
isDisabled={type === 'detail'}
|
isDisabled={type === 'detail'}
|
||||||
isClearable
|
isClearable
|
||||||
|
startAdornment={
|
||||||
|
formik.values.source_warehouse_id
|
||||||
|
? getWarehouseStockAdornment(
|
||||||
|
formik.values.source_warehouse_id
|
||||||
|
)
|
||||||
|
: undefined
|
||||||
|
}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
{/* Area and Location Info */}
|
{/* Area and Location Info */}
|
||||||
@@ -790,6 +874,13 @@ const MovementForm = ({ type = 'add', initialValues }: MovementFormProps) => {
|
|||||||
}
|
}
|
||||||
isDisabled={type === 'detail'}
|
isDisabled={type === 'detail'}
|
||||||
isClearable
|
isClearable
|
||||||
|
startAdornment={
|
||||||
|
formik.values.destination_warehouse_id
|
||||||
|
? getWarehouseStockAdornment(
|
||||||
|
formik.values.destination_warehouse_id
|
||||||
|
)
|
||||||
|
: undefined
|
||||||
|
}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
{/* Area and Location Info */}
|
{/* Area and Location Info */}
|
||||||
@@ -839,7 +930,6 @@ const MovementForm = ({ type = 'add', initialValues }: MovementFormProps) => {
|
|||||||
<tr>
|
<tr>
|
||||||
{type !== 'detail' && (
|
{type !== 'detail' && (
|
||||||
<th>
|
<th>
|
||||||
<div className='flex justify-center'>
|
|
||||||
<CheckboxInput
|
<CheckboxInput
|
||||||
name='select-all-products'
|
name='select-all-products'
|
||||||
checked={
|
checked={
|
||||||
@@ -865,7 +955,6 @@ const MovementForm = ({ type = 'add', initialValues }: MovementFormProps) => {
|
|||||||
checkbox: 'checkbox checkbox-sm',
|
checkbox: 'checkbox checkbox-sm',
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
</div>
|
|
||||||
</th>
|
</th>
|
||||||
)}
|
)}
|
||||||
<th>
|
<th>
|
||||||
@@ -893,8 +982,7 @@ const MovementForm = ({ type = 'add', initialValues }: MovementFormProps) => {
|
|||||||
{formik.values.products?.map((product, idx) => (
|
{formik.values.products?.map((product, idx) => (
|
||||||
<tr key={`product-row-${idx}-${product.product_id}`}>
|
<tr key={`product-row-${idx}-${product.product_id}`}>
|
||||||
{type !== 'detail' && (
|
{type !== 'detail' && (
|
||||||
<td>
|
<td className='!align-middle'>
|
||||||
<div className='flex justify-center'>
|
|
||||||
<CheckboxInput
|
<CheckboxInput
|
||||||
name={`product-${idx}`}
|
name={`product-${idx}`}
|
||||||
checked={selectedProducts.includes(idx)}
|
checked={selectedProducts.includes(idx)}
|
||||||
@@ -917,7 +1005,6 @@ const MovementForm = ({ type = 'add', initialValues }: MovementFormProps) => {
|
|||||||
checkbox: 'checkbox checkbox-sm',
|
checkbox: 'checkbox checkbox-sm',
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
</div>
|
|
||||||
</td>
|
</td>
|
||||||
)}
|
)}
|
||||||
<td>
|
<td>
|
||||||
@@ -967,14 +1054,17 @@ const MovementForm = ({ type = 'add', initialValues }: MovementFormProps) => {
|
|||||||
/>
|
/>
|
||||||
</td>
|
</td>
|
||||||
<td>
|
<td>
|
||||||
<TextInput
|
<NumberInput
|
||||||
required
|
required
|
||||||
type='number'
|
|
||||||
name={`products.${idx}.product_qty`}
|
name={`products.${idx}.product_qty`}
|
||||||
value={product.product_qty ?? ''}
|
value={product.product_qty ?? ''}
|
||||||
onChange={formik.handleChange}
|
onChange={formik.handleChange}
|
||||||
onBlur={formik.handleBlur}
|
onBlur={formik.handleBlur}
|
||||||
endAdornment={getProductQtyAdornment(idx)}
|
decimalScale={0}
|
||||||
|
allowNegative={false}
|
||||||
|
thousandSeparator=','
|
||||||
|
decimalSeparator='.'
|
||||||
|
bottomLabel={getProductQtyBottomLabel(idx)}
|
||||||
isError={
|
isError={
|
||||||
isRepeaterInputError(
|
isRepeaterInputError(
|
||||||
'products',
|
'products',
|
||||||
@@ -1061,7 +1151,6 @@ const MovementForm = ({ type = 'add', initialValues }: MovementFormProps) => {
|
|||||||
<tr>
|
<tr>
|
||||||
{type !== 'detail' && (
|
{type !== 'detail' && (
|
||||||
<th>
|
<th>
|
||||||
<div className='flex justify-center'>
|
|
||||||
<CheckboxInput
|
<CheckboxInput
|
||||||
name='select-all-deliveries'
|
name='select-all-deliveries'
|
||||||
checked={
|
checked={
|
||||||
@@ -1087,7 +1176,6 @@ const MovementForm = ({ type = 'add', initialValues }: MovementFormProps) => {
|
|||||||
checkbox: 'checkbox checkbox-sm',
|
checkbox: 'checkbox checkbox-sm',
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
</div>
|
|
||||||
</th>
|
</th>
|
||||||
)}
|
)}
|
||||||
<th>
|
<th>
|
||||||
@@ -1161,8 +1249,7 @@ const MovementForm = ({ type = 'add', initialValues }: MovementFormProps) => {
|
|||||||
{formik.values.deliveries?.map((delivery, idx) => (
|
{formik.values.deliveries?.map((delivery, idx) => (
|
||||||
<tr key={`delivery-row-${idx}`}>
|
<tr key={`delivery-row-${idx}`}>
|
||||||
{type !== 'detail' && (
|
{type !== 'detail' && (
|
||||||
<td>
|
<td className='!align-middle'>
|
||||||
<div className='flex justify-center'>
|
|
||||||
<CheckboxInput
|
<CheckboxInput
|
||||||
name={`delivery-${idx}`}
|
name={`delivery-${idx}`}
|
||||||
checked={selectedDeliveries.includes(idx)}
|
checked={selectedDeliveries.includes(idx)}
|
||||||
@@ -1176,9 +1263,7 @@ const MovementForm = ({ type = 'add', initialValues }: MovementFormProps) => {
|
|||||||
]);
|
]);
|
||||||
} else {
|
} else {
|
||||||
setSelectedDeliveries(
|
setSelectedDeliveries(
|
||||||
selectedDeliveries.filter(
|
selectedDeliveries.filter((i) => i !== idx)
|
||||||
(i) => i !== idx
|
|
||||||
)
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}}
|
}}
|
||||||
@@ -1187,7 +1272,6 @@ const MovementForm = ({ type = 'add', initialValues }: MovementFormProps) => {
|
|||||||
checkbox: 'checkbox checkbox-sm',
|
checkbox: 'checkbox checkbox-sm',
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
</div>
|
|
||||||
</td>
|
</td>
|
||||||
)}
|
)}
|
||||||
<td>
|
<td>
|
||||||
@@ -1230,13 +1314,16 @@ const MovementForm = ({ type = 'add', initialValues }: MovementFormProps) => {
|
|||||||
/>
|
/>
|
||||||
</td>
|
</td>
|
||||||
<td>
|
<td>
|
||||||
<TextInput
|
<NumberInput
|
||||||
required
|
required
|
||||||
type='number'
|
|
||||||
name={`deliveries.${idx}.products.0.product_qty`}
|
name={`deliveries.${idx}.products.0.product_qty`}
|
||||||
value={delivery.products[0]?.product_qty ?? ''}
|
value={delivery.products[0]?.product_qty ?? ''}
|
||||||
onChange={formik.handleChange}
|
onChange={formik.handleChange}
|
||||||
onBlur={formik.handleBlur}
|
onBlur={formik.handleBlur}
|
||||||
|
decimalScale={0}
|
||||||
|
allowNegative={false}
|
||||||
|
thousandSeparator=','
|
||||||
|
decimalSeparator='.'
|
||||||
isError={
|
isError={
|
||||||
isDeliveryProductInputError(idx, 0, 'product_qty')
|
isDeliveryProductInputError(idx, 0, 'product_qty')
|
||||||
.isError || Boolean(getDeliveryQtyError(idx, 0))
|
.isError || Boolean(getDeliveryQtyError(idx, 0))
|
||||||
@@ -1247,6 +1334,10 @@ const MovementForm = ({ type = 'add', initialValues }: MovementFormProps) => {
|
|||||||
getDeliveryQtyError(idx, 0) ||
|
getDeliveryQtyError(idx, 0) ||
|
||||||
undefined
|
undefined
|
||||||
}
|
}
|
||||||
|
bottomLabel={getDeliveryProductQtyBottomLabel(
|
||||||
|
idx,
|
||||||
|
0
|
||||||
|
)}
|
||||||
readOnly={type === 'detail'}
|
readOnly={type === 'detail'}
|
||||||
className={{
|
className={{
|
||||||
wrapper: 'w-full min-w-48',
|
wrapper: 'w-full min-w-48',
|
||||||
@@ -1373,13 +1464,13 @@ const MovementForm = ({ type = 'add', initialValues }: MovementFormProps) => {
|
|||||||
required
|
required
|
||||||
name={`deliveries.${idx}.delivery_cost`}
|
name={`deliveries.${idx}.delivery_cost`}
|
||||||
value={delivery.delivery_cost || ''}
|
value={delivery.delivery_cost || ''}
|
||||||
onChange={(e) =>
|
onChange={handleDeliveryCostChangeWrapper(idx)}
|
||||||
handleDeliveryCostChange(idx, e.target.value)
|
|
||||||
}
|
|
||||||
onBlur={formik.handleBlur}
|
onBlur={formik.handleBlur}
|
||||||
maskType='currency'
|
decimalScale={0}
|
||||||
decimals={0}
|
allowNegative={false}
|
||||||
min={0}
|
thousandSeparator=','
|
||||||
|
decimalSeparator='.'
|
||||||
|
inputPrefix='Rp'
|
||||||
{...isRepeaterInputError(
|
{...isRepeaterInputError(
|
||||||
'deliveries',
|
'deliveries',
|
||||||
'delivery_cost',
|
'delivery_cost',
|
||||||
@@ -1397,16 +1488,15 @@ const MovementForm = ({ type = 'add', initialValues }: MovementFormProps) => {
|
|||||||
required
|
required
|
||||||
name={`deliveries.${idx}.delivery_cost_per_item`}
|
name={`deliveries.${idx}.delivery_cost_per_item`}
|
||||||
value={delivery.delivery_cost_per_item || ''}
|
value={delivery.delivery_cost_per_item || ''}
|
||||||
onChange={(e) =>
|
onChange={handleDeliveryCostPerItemChangeWrapper(
|
||||||
handleDeliveryCostPerItemChange(
|
idx
|
||||||
idx,
|
)}
|
||||||
e.target.value
|
|
||||||
)
|
|
||||||
}
|
|
||||||
onBlur={formik.handleBlur}
|
onBlur={formik.handleBlur}
|
||||||
maskType='currency'
|
decimalScale={0}
|
||||||
decimals={0}
|
allowNegative={false}
|
||||||
min={0}
|
thousandSeparator=','
|
||||||
|
decimalSeparator='.'
|
||||||
|
inputPrefix='Rp'
|
||||||
{...isRepeaterInputError(
|
{...isRepeaterInputError(
|
||||||
'deliveries',
|
'deliveries',
|
||||||
'delivery_cost_per_item',
|
'delivery_cost_per_item',
|
||||||
|
|||||||
@@ -11,8 +11,8 @@ import RowDropdownOptions from '@/components/table/RowDropdownOptions';
|
|||||||
import { TableRowSizeSelector } from '@/components/table/TableRowSizeSelector';
|
import { TableRowSizeSelector } from '@/components/table/TableRowSizeSelector';
|
||||||
import { ROWS_OPTIONS } from '@/config/constant';
|
import { ROWS_OPTIONS } from '@/config/constant';
|
||||||
import { isResponseSuccess } from '@/lib/api-helper';
|
import { isResponseSuccess } from '@/lib/api-helper';
|
||||||
import { cn } from '@/lib/helper';
|
import { cn, formatNumber } from '@/lib/helper';
|
||||||
import { ChickinApi, ProjectFlockApi } from '@/services/api/production';
|
import { ChickinApi } from '@/services/api/production';
|
||||||
import { useTableFilter } from '@/services/hooks/useTableFilter';
|
import { useTableFilter } from '@/services/hooks/useTableFilter';
|
||||||
import { Chickin } from '@/types/api/production/chickin';
|
import { Chickin } from '@/types/api/production/chickin';
|
||||||
import { Icon } from '@iconify/react';
|
import { Icon } from '@iconify/react';
|
||||||
@@ -57,13 +57,6 @@ const ChickinTable = () => {
|
|||||||
`${ChickinApi.basePath}${getTableFilterQueryString()}`,
|
`${ChickinApi.basePath}${getTableFilterQueryString()}`,
|
||||||
ChickinApi.getAllFetcher
|
ChickinApi.getAllFetcher
|
||||||
);
|
);
|
||||||
const {
|
|
||||||
data: projectFlocks,
|
|
||||||
isLoading: isLoadingProjectFlocks,
|
|
||||||
} = useSWR(
|
|
||||||
`${ProjectFlockApi.basePath}${getTableFilterQueryString()}`,
|
|
||||||
ProjectFlockApi.getAllFetcher
|
|
||||||
);
|
|
||||||
|
|
||||||
const searchChangeHandler = (event: React.ChangeEvent<HTMLInputElement>) => {
|
const searchChangeHandler = (event: React.ChangeEvent<HTMLInputElement>) => {
|
||||||
updateFilter('search', event.target.value);
|
updateFilter('search', event.target.value);
|
||||||
@@ -131,6 +124,13 @@ const ChickinTable = () => {
|
|||||||
{
|
{
|
||||||
accessorFn: (row) => row.quantity,
|
accessorFn: (row) => row.quantity,
|
||||||
header: 'Jumlah Chickin',
|
header: 'Jumlah Chickin',
|
||||||
|
cell: (props) => {
|
||||||
|
if (props.row.original.quantity) {
|
||||||
|
return formatNumber(props.row.original.quantity);
|
||||||
|
} else {
|
||||||
|
return '-';
|
||||||
|
}
|
||||||
|
}
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
accessorFn: (row) => row.chick_in_date,
|
accessorFn: (row) => row.chick_in_date,
|
||||||
@@ -287,7 +287,7 @@ const RowOptionsMenu = ({
|
|||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
<Button
|
<Button
|
||||||
href={`/production/chickin/detail?projectFlockId=${props.row.original.id}`}
|
href={`/production/chickin/detail?chickinId=${props.row.original.id}`}
|
||||||
variant='ghost'
|
variant='ghost'
|
||||||
color='primary'
|
color='primary'
|
||||||
className='justify-start text-sm'
|
className='justify-start text-sm'
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ import {
|
|||||||
ChickinFormValues,
|
ChickinFormValues,
|
||||||
UpdateChickinFormSchema,
|
UpdateChickinFormSchema,
|
||||||
} from '@/components/pages/production/chickin/form/ChickinForm.schema';
|
} from '@/components/pages/production/chickin/form/ChickinForm.schema';
|
||||||
import { useCallback, useEffect, useMemo, useState } from 'react';
|
import { use, useCallback, useEffect, useMemo, useState } from 'react';
|
||||||
import { useFormik } from 'formik';
|
import { useFormik } from 'formik';
|
||||||
import { ChickinApi } from '@/services/api/production';
|
import { ChickinApi } from '@/services/api/production';
|
||||||
import DateInput from '@/components/input/DateInput';
|
import DateInput from '@/components/input/DateInput';
|
||||||
@@ -20,6 +20,7 @@ import toast from 'react-hot-toast';
|
|||||||
import { Icon } from '@iconify/react';
|
import { Icon } from '@iconify/react';
|
||||||
import TextArea from '@/components/input/TextArea';
|
import TextArea from '@/components/input/TextArea';
|
||||||
import TextInput from '@/components/input/TextInput';
|
import TextInput from '@/components/input/TextInput';
|
||||||
|
import NumberInput from '@/components/input/NumberInput';
|
||||||
|
|
||||||
interface ChickinFormProps {
|
interface ChickinFormProps {
|
||||||
formType?: 'add' | 'detail' | 'edit';
|
formType?: 'add' | 'detail' | 'edit';
|
||||||
@@ -45,8 +46,11 @@ const ChickinForm = ({
|
|||||||
const formikInitialValue = useMemo<ChickinFormValues>(() => {
|
const formikInitialValue = useMemo<ChickinFormValues>(() => {
|
||||||
return {
|
return {
|
||||||
chick_in_date: formatDateForInput(initialValues?.chick_in_date) ?? '',
|
chick_in_date: formatDateForInput(initialValues?.chick_in_date) ?? '',
|
||||||
note: initialValues?.note ?? `Catatan Chickin ${initialValues?.project_flock_kandang?.project_flock.flock.name}`,
|
note: initialValues?.note ?? '',
|
||||||
quantity: initialValues?.quantity ?? 1,
|
quantity:
|
||||||
|
initialValues?.quantity ??
|
||||||
|
initialValues?.project_flock_kandang?.available_quantity ??
|
||||||
|
0,
|
||||||
};
|
};
|
||||||
}, [initialValues]);
|
}, [initialValues]);
|
||||||
|
|
||||||
@@ -71,10 +75,7 @@ const ChickinForm = ({
|
|||||||
payload: UpdateChickinPayload,
|
payload: UpdateChickinPayload,
|
||||||
afterSubmit: (() => void) | undefined
|
afterSubmit: (() => void) | undefined
|
||||||
) => {
|
) => {
|
||||||
const res = await ChickinApi.update(
|
const res = await ChickinApi.update(payload.id, payload);
|
||||||
payload.project_flock_kandang_id as number,
|
|
||||||
payload
|
|
||||||
);
|
|
||||||
if (isResponseError(res)) {
|
if (isResponseError(res)) {
|
||||||
setChickinFormErrorMessage(res.message);
|
setChickinFormErrorMessage(res.message);
|
||||||
return;
|
return;
|
||||||
@@ -95,7 +96,10 @@ const ChickinForm = ({
|
|||||||
// reset error message
|
// reset error message
|
||||||
setChickinFormErrorMessage('');
|
setChickinFormErrorMessage('');
|
||||||
|
|
||||||
if (initialValues?.project_flock_kandang?.id == undefined) {
|
if (
|
||||||
|
initialValues?.project_flock_kandang?.id == undefined ||
|
||||||
|
(formType == 'edit' && initialValues?.id == undefined)
|
||||||
|
) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -103,9 +107,13 @@ const ChickinForm = ({
|
|||||||
const payload = {
|
const payload = {
|
||||||
chick_in_date: values.chick_in_date,
|
chick_in_date: values.chick_in_date,
|
||||||
project_flock_kandang_id: initialValues?.project_flock_kandang?.id,
|
project_flock_kandang_id: initialValues?.project_flock_kandang?.id,
|
||||||
|
note: values.note,
|
||||||
|
quantity: values.quantity,
|
||||||
|
id: initialValues.id ?? 0,
|
||||||
};
|
};
|
||||||
|
|
||||||
// cek type form yang disubmit
|
// cek type form yang disubmit
|
||||||
|
console.log(formType);
|
||||||
switch (formType) {
|
switch (formType) {
|
||||||
case 'add':
|
case 'add':
|
||||||
handleCreate(payload, afterSubmit);
|
handleCreate(payload, afterSubmit);
|
||||||
@@ -144,28 +152,34 @@ const ChickinForm = ({
|
|||||||
}
|
}
|
||||||
errorMessage={formik.errors.chick_in_date}
|
errorMessage={formik.errors.chick_in_date}
|
||||||
/>
|
/>
|
||||||
<TextInput
|
<NumberInput
|
||||||
value={formik.values.quantity}
|
value={formik.values.quantity}
|
||||||
onChange={formik.handleChange}
|
onChange={formik.handleChange}
|
||||||
onBlur={formik.handleBlur}
|
onBlur={formik.handleBlur}
|
||||||
name='quantity'
|
name='quantity'
|
||||||
label='Jumlah Chickin'
|
label='Jumlah (Ekor)'
|
||||||
required
|
required
|
||||||
isError={formik.touched.quantity && Boolean(formik.errors.quantity)}
|
isError={
|
||||||
errorMessage={formik.errors.quantity}
|
(formik.touched.quantity && Boolean(formik.errors.quantity)) ||
|
||||||
type='number'
|
formik.values.quantity == 0
|
||||||
disabled
|
}
|
||||||
|
errorMessage={
|
||||||
|
formik.values.quantity == 0
|
||||||
|
? 'Masukan Persediaan Day Old Chick terlebih dahulu.'
|
||||||
|
: formik.errors.quantity
|
||||||
|
}
|
||||||
|
readOnly
|
||||||
/>
|
/>
|
||||||
<TextArea
|
<TextArea
|
||||||
required
|
required
|
||||||
label='Catatan'
|
label='Catatan'
|
||||||
name='note'
|
name='note'
|
||||||
|
placeholder='Masukan catatan chickin'
|
||||||
value={formik.values.note}
|
value={formik.values.note}
|
||||||
onChange={formik.handleChange}
|
onChange={formik.handleChange}
|
||||||
onBlur={formik.handleBlur}
|
onBlur={formik.handleBlur}
|
||||||
isError={formik.touched.note && Boolean(formik.errors.note)}
|
isError={formik.touched.note && Boolean(formik.errors.note)}
|
||||||
errorMessage={formik.errors.note}
|
errorMessage={formik.errors.note}
|
||||||
|
|
||||||
/>
|
/>
|
||||||
{initialValues?.project_flock_kandang?.id == undefined && (
|
{initialValues?.project_flock_kandang?.id == undefined && (
|
||||||
<p className='text-error'>Project Flock Kandang tidak ditemukan.</p>
|
<p className='text-error'>Project Flock Kandang tidak ditemukan.</p>
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
'use client';
|
'use client';
|
||||||
|
|
||||||
import Button from '@/components/Button';
|
import Button from '@/components/Button';
|
||||||
|
import CheckboxInput from '@/components/input/CheckboxInput';
|
||||||
import DebouncedTextInput from '@/components/input/DebouncedTextInput';
|
import DebouncedTextInput from '@/components/input/DebouncedTextInput';
|
||||||
import SelectInput, { OptionType } from '@/components/input/SelectInput';
|
import SelectInput, { OptionType } from '@/components/input/SelectInput';
|
||||||
import { useModal } from '@/components/Modal';
|
import { useModal } from '@/components/Modal';
|
||||||
@@ -16,13 +17,12 @@ import { ProjectFlockApi } from '@/services/api/production';
|
|||||||
import { useTableFilter } from '@/services/hooks/useTableFilter';
|
import { useTableFilter } from '@/services/hooks/useTableFilter';
|
||||||
import { BaseApiResponse } from '@/types/api/api-general';
|
import { BaseApiResponse } from '@/types/api/api-general';
|
||||||
import { Kandang } from '@/types/api/master-data/kandang';
|
import { Kandang } from '@/types/api/master-data/kandang';
|
||||||
import { ProjectFlock } from '@/types/api/production/project-flock';
|
|
||||||
import { Icon } from '@iconify/react';
|
|
||||||
import {
|
import {
|
||||||
CellContext,
|
ProjectFlockApprovalPayload,
|
||||||
ColumnDef,
|
ProjectFlock,
|
||||||
SortingState,
|
} from '@/types/api/production/project-flock';
|
||||||
} from '@tanstack/react-table';
|
import { Icon } from '@iconify/react';
|
||||||
|
import { CellContext, SortingState } from '@tanstack/react-table';
|
||||||
import { ChangeEventHandler, useState } from 'react';
|
import { ChangeEventHandler, useState } from 'react';
|
||||||
import toast from 'react-hot-toast';
|
import toast from 'react-hot-toast';
|
||||||
import useSWR from 'swr';
|
import useSWR from 'swr';
|
||||||
@@ -56,6 +56,7 @@ const RowOptionsMenu = ({
|
|||||||
<Icon icon='mdi:eye-outline' width={16} height={16} />
|
<Icon icon='mdi:eye-outline' width={16} height={16} />
|
||||||
Detail
|
Detail
|
||||||
</Button>
|
</Button>
|
||||||
|
{props.row.original.approval.step_name === 'Aktif' && (
|
||||||
<Button
|
<Button
|
||||||
href={`/production/chickin/add?projectFlockId=${props.row.original.id}`}
|
href={`/production/chickin/add?projectFlockId=${props.row.original.id}`}
|
||||||
variant='ghost'
|
variant='ghost'
|
||||||
@@ -65,7 +66,9 @@ const RowOptionsMenu = ({
|
|||||||
<Icon icon='mdi:home-import-outline' width={16} height={16} />
|
<Icon icon='mdi:home-import-outline' width={16} height={16} />
|
||||||
Chickin
|
Chickin
|
||||||
</Button>
|
</Button>
|
||||||
{/* <Button
|
)}
|
||||||
|
{props.row.original.approval.step_name === 'Pengajuan' && (
|
||||||
|
<Button
|
||||||
href={`/production/project-flock/detail/edit?projectFlockId=${props.row.original.id}`}
|
href={`/production/project-flock/detail/edit?projectFlockId=${props.row.original.id}`}
|
||||||
variant='ghost'
|
variant='ghost'
|
||||||
color='warning'
|
color='warning'
|
||||||
@@ -73,7 +76,8 @@ const RowOptionsMenu = ({
|
|||||||
>
|
>
|
||||||
<Icon icon='mdi:pencil-outline' width={16} height={16} />
|
<Icon icon='mdi:pencil-outline' width={16} height={16} />
|
||||||
Edit
|
Edit
|
||||||
</Button> */}
|
</Button>
|
||||||
|
)}
|
||||||
<Button
|
<Button
|
||||||
onClick={deleteClickHandler}
|
onClick={deleteClickHandler}
|
||||||
variant='ghost'
|
variant='ghost'
|
||||||
@@ -117,10 +121,15 @@ const ProjectFlockTable = () => {
|
|||||||
periodFilter: 'period',
|
periodFilter: 'period',
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// State
|
||||||
|
const [rowSelection, setRowSelection] = useState<Record<string, boolean>>({});
|
||||||
|
const selectedRowIds = Object.keys(rowSelection)
|
||||||
|
.filter((id) => rowSelection[id])
|
||||||
|
.map((id) => parseInt(id));
|
||||||
const [locationSelectInputValue, setLocationSelectInputValue] = useState('');
|
const [locationSelectInputValue, setLocationSelectInputValue] = useState('');
|
||||||
const [areaSelectInputValue, setAreaSelectInputValue] = useState('');
|
const [areaSelectInputValue, setAreaSelectInputValue] = useState('');
|
||||||
const [kandangSelectInputValue, setKandangSelectInputValue] = useState('');
|
const [kandangSelectInputValue, setKandangSelectInputValue] = useState('');
|
||||||
|
|
||||||
const [selectedArea, setSelectedArea] = useState<OptionType | null>(null);
|
const [selectedArea, setSelectedArea] = useState<OptionType | null>(null);
|
||||||
const [selectedLocation, setSelectedLocation] = useState<OptionType | null>(
|
const [selectedLocation, setSelectedLocation] = useState<OptionType | null>(
|
||||||
null
|
null
|
||||||
@@ -129,6 +138,13 @@ const ProjectFlockTable = () => {
|
|||||||
null
|
null
|
||||||
);
|
);
|
||||||
const [periodInputValue, setPeriodInputValue] = useState<number | null>(null);
|
const [periodInputValue, setPeriodInputValue] = useState<number | null>(null);
|
||||||
|
const [sorting, setSorting] = useState<SortingState>([]);
|
||||||
|
const [selectedProjectFlock, setSelectedProjectFlock] =
|
||||||
|
useState<ProjectFlock>();
|
||||||
|
const deleteModal = useModal();
|
||||||
|
const confirmModal = useModal();
|
||||||
|
const [isDeleteLoading, setIsDeleteLoading] = useState(false);
|
||||||
|
const [isApproveLoading, setIsApproveLoading] = useState(false);
|
||||||
|
|
||||||
// Fetch Data
|
// Fetch Data
|
||||||
const {
|
const {
|
||||||
@@ -144,20 +160,20 @@ const ProjectFlockTable = () => {
|
|||||||
search: areaSelectInputValue,
|
search: areaSelectInputValue,
|
||||||
limit: '100',
|
limit: '100',
|
||||||
}).toString()}`;
|
}).toString()}`;
|
||||||
const {
|
const { data: areas, isLoading: isLoadingAreas } = useSWR(
|
||||||
data: areas,
|
areaUrl,
|
||||||
isLoading: isLoadingAreas,
|
AreaApi.getAllFetcher
|
||||||
} = useSWR(areaUrl, AreaApi.getAllFetcher);
|
);
|
||||||
|
|
||||||
const locationUrl = `${LocationApi.basePath}?${new URLSearchParams({
|
const locationUrl = `${LocationApi.basePath}?${new URLSearchParams({
|
||||||
search: locationSelectInputValue,
|
search: locationSelectInputValue,
|
||||||
area_id: selectedArea != null ? selectedArea.value.toString() : '',
|
area_id: selectedArea != null ? selectedArea.value.toString() : '',
|
||||||
limit: '100',
|
limit: '100',
|
||||||
}).toString()}`;
|
}).toString()}`;
|
||||||
const {
|
const { data: locations, isLoading: isLoadingLocations } = useSWR(
|
||||||
data: locations,
|
locationUrl,
|
||||||
isLoading: isLoadingLocations,
|
LocationApi.getAllFetcher
|
||||||
} = useSWR(locationUrl, LocationApi.getAllFetcher);
|
);
|
||||||
|
|
||||||
const kandangUrl = `${KandangApi.basePath}?${new URLSearchParams({
|
const kandangUrl = `${KandangApi.basePath}?${new URLSearchParams({
|
||||||
search: kandangSelectInputValue,
|
search: kandangSelectInputValue,
|
||||||
@@ -165,10 +181,10 @@ const ProjectFlockTable = () => {
|
|||||||
selectedLocation != null ? selectedLocation.value.toString() : '',
|
selectedLocation != null ? selectedLocation.value.toString() : '',
|
||||||
limit: '100',
|
limit: '100',
|
||||||
}).toString()}`;
|
}).toString()}`;
|
||||||
const {
|
const { data: kandangs, isLoading: isLoadingKandang } = useSWR(
|
||||||
data: kandangs,
|
kandangUrl,
|
||||||
isLoading: isLoadingKandang,
|
KandangApi.getAllFetcher
|
||||||
} = useSWR(kandangUrl, KandangApi.getAllFetcher);
|
);
|
||||||
|
|
||||||
// Data to Options Mapping
|
// Data to Options Mapping
|
||||||
const optionsArea = isResponseSuccess(areas)
|
const optionsArea = isResponseSuccess(areas)
|
||||||
@@ -190,139 +206,6 @@ const ProjectFlockTable = () => {
|
|||||||
}))
|
}))
|
||||||
: [];
|
: [];
|
||||||
|
|
||||||
// State
|
|
||||||
const [sorting, setSorting] = useState<SortingState>([]);
|
|
||||||
const [selectedProjectFlock, setSelectedProjectFlock] =
|
|
||||||
useState<ProjectFlock>();
|
|
||||||
const deleteModal = useModal();
|
|
||||||
const confirmModal = useModal();
|
|
||||||
const [isDeleteLoading, setIsDeleteLoading] = useState(false);
|
|
||||||
const [selectedIds, setSelectedIds] = useState<number[]>([]);
|
|
||||||
const [selectedFlocks, setSelectedFlocks] = useState<ProjectFlock[]>([]);
|
|
||||||
const [isApproveLoading, setIsApproveLoading] = useState(false);
|
|
||||||
|
|
||||||
// Columns
|
|
||||||
const projectFlocksColumns: ColumnDef<ProjectFlock>[] = [
|
|
||||||
{
|
|
||||||
id: 'select',
|
|
||||||
header: () => {
|
|
||||||
const allSelected =
|
|
||||||
isResponseSuccess(projectFlocks) &&
|
|
||||||
projectFlocks.data.length > 0 &&
|
|
||||||
selectedIds.length === projectFlocks.data.length;
|
|
||||||
|
|
||||||
return (
|
|
||||||
<input
|
|
||||||
type='checkbox'
|
|
||||||
className='checkbox checkbox-sm'
|
|
||||||
checked={allSelected}
|
|
||||||
onChange={(e) => handleSelectAll(e.target.checked)}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
},
|
|
||||||
cell: (props) => {
|
|
||||||
const id = props.row.original.id;
|
|
||||||
const isChecked = selectedIds.includes(id);
|
|
||||||
|
|
||||||
return (
|
|
||||||
<input
|
|
||||||
type='checkbox'
|
|
||||||
className='checkbox checkbox-sm'
|
|
||||||
checked={isChecked}
|
|
||||||
onChange={(e) => handleSelectRow(id, e.target.checked)}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
},
|
|
||||||
},
|
|
||||||
|
|
||||||
{
|
|
||||||
accessorKey: 'flock.name',
|
|
||||||
header: 'Flock',
|
|
||||||
},
|
|
||||||
{
|
|
||||||
accessorKey: 'area.name',
|
|
||||||
header: 'Area',
|
|
||||||
},
|
|
||||||
{
|
|
||||||
accessorKey: 'location.name',
|
|
||||||
header: 'Lokasi',
|
|
||||||
},
|
|
||||||
{
|
|
||||||
accessorKey: 'fcr.name',
|
|
||||||
header: 'FCR',
|
|
||||||
},
|
|
||||||
{
|
|
||||||
accessorKey: 'category',
|
|
||||||
header: 'Kategori',
|
|
||||||
},
|
|
||||||
{
|
|
||||||
header: 'Kandang',
|
|
||||||
cell: (props) => {
|
|
||||||
const kandang = props.row.original.kandangs;
|
|
||||||
if (kandang) {
|
|
||||||
const kandangNames = kandang.map((k: Kandang) => k.name);
|
|
||||||
return (
|
|
||||||
<div>
|
|
||||||
{kandangNames.length > 0 ? kandangNames.join(', ') : 'Tidak ada'}
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
} else {
|
|
||||||
return '-';
|
|
||||||
}
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
accessorKey: 'period',
|
|
||||||
header: 'Periode',
|
|
||||||
},
|
|
||||||
{
|
|
||||||
accessorKey: 'created_at',
|
|
||||||
header: 'Dibuat pada',
|
|
||||||
cell: (props) =>
|
|
||||||
new Date(props.row.original.created_at).toLocaleDateString(),
|
|
||||||
},
|
|
||||||
{
|
|
||||||
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 = () => {
|
|
||||||
setSelectedProjectFlock(props.row.original);
|
|
||||||
deleteModal.openModal();
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
|
||||||
<>
|
|
||||||
{currentPageSize > 2 && (
|
|
||||||
<RowDropdownOptions isLast2Rows={isLast2Rows}>
|
|
||||||
<RowOptionsMenu
|
|
||||||
type='dropdown'
|
|
||||||
props={props}
|
|
||||||
deleteClickHandler={deleteClickHandler}
|
|
||||||
/>
|
|
||||||
</RowDropdownOptions>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{currentPageSize <= 2 && (
|
|
||||||
<RowCollapseOptions>
|
|
||||||
<RowOptionsMenu
|
|
||||||
type='dropdown'
|
|
||||||
props={props}
|
|
||||||
deleteClickHandler={deleteClickHandler}
|
|
||||||
/>
|
|
||||||
</RowCollapseOptions>
|
|
||||||
)}
|
|
||||||
</>
|
|
||||||
);
|
|
||||||
},
|
|
||||||
},
|
|
||||||
];
|
|
||||||
|
|
||||||
// Handler
|
// Handler
|
||||||
const pageSizeChangeHandler = (val: OptionType | OptionType[] | null) => {
|
const pageSizeChangeHandler = (val: OptionType | OptionType[] | null) => {
|
||||||
const newVal = val as OptionType;
|
const newVal = val as OptionType;
|
||||||
@@ -341,45 +224,17 @@ const ProjectFlockTable = () => {
|
|||||||
const searchChangeHandler: ChangeEventHandler<HTMLInputElement> = (e) => {
|
const searchChangeHandler: ChangeEventHandler<HTMLInputElement> = (e) => {
|
||||||
updateFilter('search', e.target.value);
|
updateFilter('search', e.target.value);
|
||||||
};
|
};
|
||||||
const handleSelectAll = (checked: boolean) => {
|
|
||||||
if (checked && isResponseSuccess(projectFlocks)) {
|
|
||||||
const allIds = projectFlocks.data.map((item) => item.id);
|
|
||||||
setSelectedIds(allIds);
|
|
||||||
setSelectedFlocks(projectFlocks.data);
|
|
||||||
} else {
|
|
||||||
setSelectedIds([]);
|
|
||||||
setSelectedFlocks([]);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleSelectRow = (id: number, checked: boolean) => {
|
|
||||||
if (!isResponseSuccess(projectFlocks)) return;
|
|
||||||
|
|
||||||
const targetFlock = projectFlocks.data.find((item) => item.id === id);
|
|
||||||
|
|
||||||
if (!targetFlock) return;
|
|
||||||
|
|
||||||
if (checked) {
|
|
||||||
setSelectedIds((prev) => [...prev, id]);
|
|
||||||
setSelectedFlocks((prev) => [...(prev || []), targetFlock]);
|
|
||||||
} else {
|
|
||||||
setSelectedIds((prev) => prev.filter((val) => val !== id));
|
|
||||||
setSelectedFlocks((prev) =>
|
|
||||||
(prev || []).filter((flock) => flock.id !== id)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const confirmationModalApproveClickHandler = async () => {
|
const confirmationModalApproveClickHandler = async () => {
|
||||||
setIsApproveLoading(true);
|
setIsApproveLoading(true);
|
||||||
const approveProjectFlockRes = await ProjectFlockApi.customRequest<
|
const approveProjectFlockRes = await ProjectFlockApi.customRequest<
|
||||||
BaseApiResponse<ProjectFlock>,
|
BaseApiResponse<ProjectFlock>,
|
||||||
'POST'
|
ProjectFlockApprovalPayload
|
||||||
>(`/approve`, {
|
>(`/approvals`, {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
payload: 'POST',
|
payload: {
|
||||||
params: {
|
action: 'APPROVED',
|
||||||
ids: selectedFlocks.map((flock) => flock.id).join(','),
|
approvable_ids: selectedRowIds.map((id) => id),
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -391,6 +246,8 @@ const ProjectFlockTable = () => {
|
|||||||
toast.error(approveProjectFlockRes?.message as string);
|
toast.error(approveProjectFlockRes?.message as string);
|
||||||
confirmModal.closeModal();
|
confirmModal.closeModal();
|
||||||
}
|
}
|
||||||
|
setRowSelection({});
|
||||||
|
refreshProjectFlocks();
|
||||||
setIsApproveLoading(false);
|
setIsApproveLoading(false);
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -412,11 +269,9 @@ const ProjectFlockTable = () => {
|
|||||||
variant='outline'
|
variant='outline'
|
||||||
color='success'
|
color='success'
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
if (selectedIds.length > 0) {
|
|
||||||
confirmModal.openModal();
|
confirmModal.openModal();
|
||||||
}
|
|
||||||
}}
|
}}
|
||||||
disabled={!(selectedIds.length > 0)}
|
disabled={selectedRowIds.length === 0}
|
||||||
className='w-full sm:w-fit'
|
className='w-full sm:w-fit'
|
||||||
>
|
>
|
||||||
<Icon icon='material-symbols:check' width={24} height={24} />
|
<Icon icon='material-symbols:check' width={24} height={24} />
|
||||||
@@ -508,7 +363,162 @@ const ProjectFlockTable = () => {
|
|||||||
|
|
||||||
<Table<ProjectFlock>
|
<Table<ProjectFlock>
|
||||||
data={isResponseSuccess(projectFlocks) ? projectFlocks?.data : []}
|
data={isResponseSuccess(projectFlocks) ? projectFlocks?.data : []}
|
||||||
columns={projectFlocksColumns}
|
columns={[
|
||||||
|
{
|
||||||
|
id: 'select',
|
||||||
|
header: ({ table }) => {
|
||||||
|
const allRows = table.getRowModel().rows;
|
||||||
|
const selectableRows = allRows.filter(
|
||||||
|
(row) => row.original?.approval?.step_number == 1
|
||||||
|
);
|
||||||
|
|
||||||
|
const allSelected = selectableRows.every((row) =>
|
||||||
|
row.getIsSelected()
|
||||||
|
) && selectableRows.length != 0;
|
||||||
|
|
||||||
|
const someSelected =
|
||||||
|
selectableRows.some((row) => row.getIsSelected()) &&
|
||||||
|
!allSelected;
|
||||||
|
|
||||||
|
const toggleSelectableRows = () => {
|
||||||
|
const shouldSelect = !allSelected;
|
||||||
|
selectableRows.forEach((row) =>
|
||||||
|
row.toggleSelected(shouldSelect)
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className='w-full flex flex-row justify-center'>
|
||||||
|
<CheckboxInput
|
||||||
|
name='allRow'
|
||||||
|
checked={allSelected}
|
||||||
|
indeterminate={someSelected}
|
||||||
|
onChange={toggleSelectableRows}
|
||||||
|
disabled={
|
||||||
|
isResponseSuccess(projectFlocks) &&
|
||||||
|
projectFlocks?.data?.filter(
|
||||||
|
(flock) => flock.approval.step_number == 1
|
||||||
|
).length == 0
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
},
|
||||||
|
cell: ({ row }) => {
|
||||||
|
return (
|
||||||
|
<CheckboxInput
|
||||||
|
name='row'
|
||||||
|
checked={
|
||||||
|
row.getIsSelected() &&
|
||||||
|
row.original.approval.step_number == 1
|
||||||
|
}
|
||||||
|
disabled={
|
||||||
|
!row.getCanSelect() ||
|
||||||
|
row.original.approval.step_number != 1
|
||||||
|
}
|
||||||
|
indeterminate={row.getIsSomeSelected()}
|
||||||
|
onChange={row.getToggleSelectedHandler()}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
},
|
||||||
|
},
|
||||||
|
|
||||||
|
{
|
||||||
|
accessorKey: 'flock.name',
|
||||||
|
header: 'Flock',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
accessorKey: 'area.name',
|
||||||
|
header: 'Area',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
accessorKey: 'location.name',
|
||||||
|
header: 'Lokasi',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
accessorKey: 'fcr.name',
|
||||||
|
header: 'FCR',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
accessorKey: 'category',
|
||||||
|
header: 'Kategori',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
accessorKey: 'approval.step_name',
|
||||||
|
header: 'Status',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
header: 'Kandang',
|
||||||
|
cell: (props) => {
|
||||||
|
const kandang = props.row.original.kandangs;
|
||||||
|
if (kandang) {
|
||||||
|
const kandangNames = kandang.map((k: Kandang) => k.name);
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
{kandangNames.length > 0
|
||||||
|
? kandangNames.join(', ')
|
||||||
|
: 'Tidak ada'}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
return '-';
|
||||||
|
}
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
accessorKey: 'period',
|
||||||
|
header: 'Periode',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
accessorKey: 'created_at',
|
||||||
|
header: 'Dibuat pada',
|
||||||
|
cell: (props) =>
|
||||||
|
new Date(props.row.original.created_at).toLocaleDateString(),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
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 = () => {
|
||||||
|
setSelectedProjectFlock(props.row.original);
|
||||||
|
deleteModal.openModal();
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
{currentPageSize > 2 && (
|
||||||
|
<RowDropdownOptions isLast2Rows={isLast2Rows}>
|
||||||
|
<RowOptionsMenu
|
||||||
|
type='dropdown'
|
||||||
|
props={props}
|
||||||
|
deleteClickHandler={deleteClickHandler}
|
||||||
|
/>
|
||||||
|
</RowDropdownOptions>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{currentPageSize <= 2 && (
|
||||||
|
<RowCollapseOptions>
|
||||||
|
<RowOptionsMenu
|
||||||
|
type='dropdown'
|
||||||
|
props={props}
|
||||||
|
deleteClickHandler={deleteClickHandler}
|
||||||
|
/>
|
||||||
|
</RowCollapseOptions>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
},
|
||||||
|
},
|
||||||
|
]}
|
||||||
pageSize={tableFilterState.pageSize}
|
pageSize={tableFilterState.pageSize}
|
||||||
page={
|
page={
|
||||||
isResponseSuccess(projectFlocks) ? projectFlocks?.meta?.page : 0
|
isResponseSuccess(projectFlocks) ? projectFlocks?.meta?.page : 0
|
||||||
@@ -522,6 +532,8 @@ const ProjectFlockTable = () => {
|
|||||||
isLoading={isLoading}
|
isLoading={isLoading}
|
||||||
sorting={sorting}
|
sorting={sorting}
|
||||||
setSorting={setSorting}
|
setSorting={setSorting}
|
||||||
|
rowSelection={rowSelection}
|
||||||
|
setRowSelection={setRowSelection}
|
||||||
className={{
|
className={{
|
||||||
containerClassName: cn({
|
containerClassName: cn({
|
||||||
'mb-20':
|
'mb-20':
|
||||||
@@ -559,18 +571,19 @@ const ProjectFlockTable = () => {
|
|||||||
<ConfirmationModal
|
<ConfirmationModal
|
||||||
ref={confirmModal.ref}
|
ref={confirmModal.ref}
|
||||||
type='success'
|
type='success'
|
||||||
text={
|
text={`Apakah anda yakin ingin reject data transfer ke laying ini (${selectedRowIds.length} data)?`}
|
||||||
selectedFlocks.length > 0
|
// text={
|
||||||
? `Apakah anda yakin ingin approve Project Flock berikut? (${selectedFlocks
|
// selectedFlocks.length > 0
|
||||||
.map(
|
// ? `Apakah anda yakin ingin approve Project Flock berikut? (${selectedFlocks
|
||||||
(flock) =>
|
// .map(
|
||||||
`${flock.flock?.name ?? '(Tanpa nama)'} - ${
|
// (flock) =>
|
||||||
flock.area?.name ?? '-'
|
// `${flock.flock?.name ?? '(Tanpa nama)'} - ${
|
||||||
}`
|
// flock.area?.name ?? '-'
|
||||||
)
|
// }`
|
||||||
.join(', ')})`
|
// )
|
||||||
: 'Tidak ada Project Flock yang dipilih.'
|
// .join(', ')})`
|
||||||
}
|
// : 'Tidak ada Project Flock yang dipilih.'
|
||||||
|
// }
|
||||||
secondaryButton={{
|
secondaryButton={{
|
||||||
text: 'Tidak',
|
text: 'Tidak',
|
||||||
}}
|
}}
|
||||||
|
|||||||
@@ -14,13 +14,14 @@ import { Icon } from '@iconify/react';
|
|||||||
import { useFormik } from 'formik';
|
import { useFormik } from 'formik';
|
||||||
import { useRouter } from 'next/navigation';
|
import { useRouter } from 'next/navigation';
|
||||||
import { useEffect, useMemo, useState } from 'react';
|
import { useEffect, useMemo, useState } from 'react';
|
||||||
import useSWR from 'swr';
|
import useSWR, { KeyedMutator } from 'swr';
|
||||||
import {
|
import {
|
||||||
ProjectFlockFormSchema,
|
ProjectFlockFormSchema,
|
||||||
ProjectFlockFormValues,
|
ProjectFlockFormValues,
|
||||||
UpdateProjectFlockFormSchema,
|
UpdateProjectFlockFormSchema,
|
||||||
} from '@/components/pages/production/project-flock/form/ProjectFlockForm.schema';
|
} from '@/components/pages/production/project-flock/form/ProjectFlockForm.schema';
|
||||||
import {
|
import {
|
||||||
|
ProjectFlockApprovalPayload,
|
||||||
CreateProjectFlockPayload,
|
CreateProjectFlockPayload,
|
||||||
PeriodFlock,
|
PeriodFlock,
|
||||||
ProjectFlock,
|
ProjectFlock,
|
||||||
@@ -34,15 +35,20 @@ import { BaseApiResponse } from '@/types/api/api-general';
|
|||||||
import { FLOCK_CATEGORY_OPTIONS } from '@/config/constant';
|
import { FLOCK_CATEGORY_OPTIONS } from '@/config/constant';
|
||||||
import { useModal } from '@/components/Modal';
|
import { useModal } from '@/components/Modal';
|
||||||
import ConfirmationModal from '@/components/modal/ConfirmationModal';
|
import ConfirmationModal from '@/components/modal/ConfirmationModal';
|
||||||
|
import ProjectFlockKandangTable from './ProjectFlockKandangTable';
|
||||||
|
|
||||||
interface ProjectFlockFormProps {
|
interface ProjectFlockFormProps {
|
||||||
formType?: 'add' | 'edit' | 'detail';
|
formType?: 'add' | 'edit' | 'detail';
|
||||||
initialValues?: ProjectFlock;
|
initialValues?: ProjectFlock;
|
||||||
|
refreshProjectFlocks?: KeyedMutator<
|
||||||
|
BaseApiResponse<ProjectFlock> | undefined
|
||||||
|
>;
|
||||||
}
|
}
|
||||||
|
|
||||||
const ProjectFlockForm = ({
|
const ProjectFlockForm = ({
|
||||||
formType = 'add',
|
formType = 'add',
|
||||||
initialValues,
|
initialValues,
|
||||||
|
refreshProjectFlocks,
|
||||||
}: ProjectFlockFormProps) => {
|
}: ProjectFlockFormProps) => {
|
||||||
// State
|
// State
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
@@ -70,6 +76,34 @@ const ProjectFlockForm = ({
|
|||||||
|
|
||||||
const [isDeleteLoading, setIsDeleteLoading] = useState(false);
|
const [isDeleteLoading, setIsDeleteLoading] = useState(false);
|
||||||
const [isApproveLoading, setIsApproveLoading] = useState(false);
|
const [isApproveLoading, setIsApproveLoading] = useState(false);
|
||||||
|
const [isApprovedDisabled, setIsApprovedDisabled] = useState(
|
||||||
|
initialValues?.approval.step_name == 'Pengajuan' ? false : true
|
||||||
|
);
|
||||||
|
const [isRejectedDisabled, setIsRejectedDisabled] = useState(
|
||||||
|
!isApprovedDisabled
|
||||||
|
);
|
||||||
|
const [approvalAction, setApprovalAction] = useState<'APPROVED' | 'REJECTED'>(
|
||||||
|
!isApprovedDisabled ? 'APPROVED' : 'REJECTED'
|
||||||
|
);
|
||||||
|
|
||||||
|
const [rowSelection, setRowSelection] = useState<Record<string, boolean>>(
|
||||||
|
() =>
|
||||||
|
Object.fromEntries(
|
||||||
|
(initialValues?.kandangs ?? []).map((k: Kandang) => [
|
||||||
|
k.id.toString(),
|
||||||
|
true,
|
||||||
|
])
|
||||||
|
)
|
||||||
|
);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (initialValues?.approval?.step_name) {
|
||||||
|
const approvedDisabled = initialValues.approval.step_name !== 'Pengajuan';
|
||||||
|
setIsApprovedDisabled(approvedDisabled);
|
||||||
|
setIsRejectedDisabled(!approvedDisabled);
|
||||||
|
setApprovalAction(!approvedDisabled ? 'APPROVED' : 'REJECTED');
|
||||||
|
}
|
||||||
|
}, [initialValues]);
|
||||||
|
|
||||||
// Fetch Data
|
// Fetch Data
|
||||||
const flockUrl = `${FlockApi.basePath}?${new URLSearchParams({
|
const flockUrl = `${FlockApi.basePath}?${new URLSearchParams({
|
||||||
@@ -109,7 +143,7 @@ const ProjectFlockForm = ({
|
|||||||
search: '',
|
search: '',
|
||||||
location_id: selectedLocation == '' ? '0' : selectedLocation,
|
location_id: selectedLocation == '' ? '0' : selectedLocation,
|
||||||
}).toString()}`;
|
}).toString()}`;
|
||||||
const { data: kandang, isLoading: isLoadingKandang } = useSWR(
|
const { data: kandang, isLoading: isLoadingKandang, mutate: refreshKandang} = useSWR(
|
||||||
kandangUrl,
|
kandangUrl,
|
||||||
KandangApi.getAllFetcher
|
KandangApi.getAllFetcher
|
||||||
);
|
);
|
||||||
@@ -167,6 +201,20 @@ const ProjectFlockForm = ({
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}, [kandang]);
|
}, [kandang]);
|
||||||
|
useEffect(() => {
|
||||||
|
if (initialValues?.kandangs) {
|
||||||
|
refreshKandang();
|
||||||
|
setOpenSelectKandangs(true);
|
||||||
|
|
||||||
|
const newRowSelection = Object.fromEntries(
|
||||||
|
initialValues.kandangs.map((k: Kandang) => [
|
||||||
|
k.id.toString(),
|
||||||
|
true,
|
||||||
|
])
|
||||||
|
);
|
||||||
|
setRowSelection(newRowSelection);
|
||||||
|
}
|
||||||
|
}, [initialValues, refreshKandang]);
|
||||||
|
|
||||||
// Options Handler
|
// Options Handler
|
||||||
const areaChangeHandler = (val: OptionType | OptionType[] | null) => {
|
const areaChangeHandler = (val: OptionType | OptionType[] | null) => {
|
||||||
@@ -211,38 +259,6 @@ const ProjectFlockForm = ({
|
|||||||
formik.setFieldTouched('category', true);
|
formik.setFieldTouched('category', true);
|
||||||
};
|
};
|
||||||
|
|
||||||
const kandangChangeHandler = (event: React.ChangeEvent<HTMLInputElement>) => {
|
|
||||||
const { value, checked } = event.target;
|
|
||||||
if (checked) {
|
|
||||||
formik.setFieldValue(
|
|
||||||
'kandang_ids',
|
|
||||||
formik.values.kandang_ids.concat(parseInt(value))
|
|
||||||
);
|
|
||||||
} else {
|
|
||||||
formik.setFieldValue(
|
|
||||||
'kandang_ids',
|
|
||||||
formik.values.kandang_ids.filter((id) => id !== parseInt(value))
|
|
||||||
);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
const kandangCheckAll = (event: React.ChangeEvent<HTMLInputElement>) => {
|
|
||||||
const { checked } = event.target;
|
|
||||||
if (checked) {
|
|
||||||
formik.setFieldValue(
|
|
||||||
'kandang_ids',
|
|
||||||
optionsKandang
|
|
||||||
.filter(
|
|
||||||
(kandang) =>
|
|
||||||
kandang.status === 'NON_ACTIVE' ||
|
|
||||||
formik.values.kandang_ids.includes(kandang.id)
|
|
||||||
)
|
|
||||||
.map((kandang) => kandang.id)
|
|
||||||
);
|
|
||||||
} else {
|
|
||||||
formik.setFieldValue('kandang_ids', []);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
// Submit Handler
|
// Submit Handler
|
||||||
const createProjectFlockHandler = async (
|
const createProjectFlockHandler = async (
|
||||||
payload: CreateProjectFlockPayload
|
payload: CreateProjectFlockPayload
|
||||||
@@ -405,6 +421,16 @@ const ProjectFlockForm = ({
|
|||||||
}
|
}
|
||||||
}, [periodFlocks]);
|
}, [periodFlocks]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const selectedRowIds = Object.keys(rowSelection)
|
||||||
|
.filter((id) => rowSelection[id])
|
||||||
|
.map((id) => parseInt(id));
|
||||||
|
formikSetValues({
|
||||||
|
...formik.values,
|
||||||
|
kandang_ids: selectedRowIds,
|
||||||
|
});
|
||||||
|
}, [rowSelection, formikSetValues]);
|
||||||
|
|
||||||
// Actions handler
|
// Actions handler
|
||||||
const confirmationModalDeleteClickHandler = async () => {
|
const confirmationModalDeleteClickHandler = async () => {
|
||||||
setIsDeleteLoading(true);
|
setIsDeleteLoading(true);
|
||||||
@@ -422,23 +448,42 @@ const ProjectFlockForm = ({
|
|||||||
setIsDeleteLoading(false);
|
setIsDeleteLoading(false);
|
||||||
};
|
};
|
||||||
|
|
||||||
const confirmationModalApproveClickHandler = async () => {
|
const confirmationModalClickHandler = async ({
|
||||||
|
action = 'APPROVED',
|
||||||
|
}: {
|
||||||
|
action: 'APPROVED' | 'REJECTED';
|
||||||
|
}) => {
|
||||||
|
if (initialValues?.id === undefined) return;
|
||||||
setIsApproveLoading(true);
|
setIsApproveLoading(true);
|
||||||
const approveProjectFlockRes = await ProjectFlockApi.customRequest<
|
const approveProjectFlockRes = await ProjectFlockApi.customRequest<
|
||||||
BaseApiResponse<ProjectFlock>,
|
BaseApiResponse<ProjectFlock>,
|
||||||
'POST'
|
ProjectFlockApprovalPayload
|
||||||
>(`/${initialValues?.id}/approve`, {
|
>(`/approvals`, {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
|
payload: {
|
||||||
|
action: action,
|
||||||
|
approvable_ids: [initialValues.id],
|
||||||
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
if (isResponseSuccess(approveProjectFlockRes)) {
|
if (isResponseSuccess(approveProjectFlockRes)) {
|
||||||
toast.success('Project Flock berhasil di-approve!');
|
if (refreshProjectFlocks) {
|
||||||
confirmModal.closeModal();
|
await refreshProjectFlocks();
|
||||||
|
}
|
||||||
|
// if (action == 'APPROVED') {
|
||||||
|
// setIsApprovedDisabled(true);
|
||||||
|
// setIsRejectedDisabled(false);
|
||||||
|
// }
|
||||||
|
// if (action == 'REJECTED') {
|
||||||
|
// setIsRejectedDisabled(true);
|
||||||
|
// setIsApprovedDisabled(false);
|
||||||
|
// }
|
||||||
|
toast.success(approveProjectFlockRes.message as string);
|
||||||
}
|
}
|
||||||
if (isResponseError(approveProjectFlockRes)) {
|
if (isResponseError(approveProjectFlockRes)) {
|
||||||
toast.error(approveProjectFlockRes?.message as string);
|
toast.error(approveProjectFlockRes?.message as string);
|
||||||
confirmModal.closeModal();
|
|
||||||
}
|
}
|
||||||
|
confirmModal.closeModal();
|
||||||
setIsApproveLoading(false);
|
setIsApproveLoading(false);
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -481,21 +526,37 @@ const ProjectFlockForm = ({
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
{formType == 'detail' && (
|
{formType == 'detail' && (
|
||||||
<div className='w-full py-4'>
|
<div className='w-full flex flex-col sm:flex-row gap-2 py-4'>
|
||||||
<Button
|
<Button
|
||||||
variant='outline'
|
variant='outline'
|
||||||
color='success'
|
color='success'
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
if (initialValues?.id) {
|
if (initialValues?.id) {
|
||||||
|
setApprovalAction('APPROVED');
|
||||||
confirmModal.openModal();
|
confirmModal.openModal();
|
||||||
}
|
}
|
||||||
}}
|
}}
|
||||||
disabled={!initialValues?.id}
|
disabled={!initialValues?.id || isApprovedDisabled}
|
||||||
className='w-full sm:w-fit'
|
className='w-full sm:w-fit'
|
||||||
>
|
>
|
||||||
<Icon icon='material-symbols:check' width={24} height={24} />
|
<Icon icon='material-symbols:check' width={24} height={24} />
|
||||||
Approve
|
Approve
|
||||||
</Button>
|
</Button>
|
||||||
|
<Button
|
||||||
|
variant='outline'
|
||||||
|
color='error'
|
||||||
|
onClick={() => {
|
||||||
|
if (initialValues?.id) {
|
||||||
|
setApprovalAction('REJECTED');
|
||||||
|
confirmModal.openModal();
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
disabled={!initialValues?.id || isRejectedDisabled}
|
||||||
|
className='w-full sm:w-fit'
|
||||||
|
>
|
||||||
|
<Icon icon='mdi:times' width={24} height={24} />
|
||||||
|
Reject
|
||||||
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
<form
|
<form
|
||||||
@@ -505,9 +566,7 @@ const ProjectFlockForm = ({
|
|||||||
>
|
>
|
||||||
<div className='card bg-base-100 shadow w-full mb-6'>
|
<div className='card bg-base-100 shadow w-full mb-6'>
|
||||||
<div className='card-body'>
|
<div className='card-body'>
|
||||||
<div className='card-title mb-4'>
|
<div className='card-title mb-4'>Informasi Umum</div>
|
||||||
Informasi Umum
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className='grid sm:grid-cols-2 gap-4'>
|
<div className='grid sm:grid-cols-2 gap-4'>
|
||||||
<SelectInput
|
<SelectInput
|
||||||
@@ -614,7 +673,7 @@ const ProjectFlockForm = ({
|
|||||||
variant='link'
|
variant='link'
|
||||||
className={`text-primary rotate-${
|
className={`text-primary rotate-${
|
||||||
openSelectKandangs ? '180' : '0'
|
openSelectKandangs ? '180' : '0'
|
||||||
} transition-transform hover:text-inherit`}
|
} transition-transform hover:text-inherit me-3`}
|
||||||
>
|
>
|
||||||
<Icon
|
<Icon
|
||||||
icon='material-symbols:keyboard-arrow-down'
|
icon='material-symbols:keyboard-arrow-down'
|
||||||
@@ -631,102 +690,15 @@ const ProjectFlockForm = ({
|
|||||||
>
|
>
|
||||||
<div className='overflow-x-auto'>
|
<div className='overflow-x-auto'>
|
||||||
{isLoadingKandang && (
|
{isLoadingKandang && (
|
||||||
<span className="loading loading-dots loading-xl"></span>
|
<span className='loading loading-dots loading-xl'></span>
|
||||||
)}
|
)}
|
||||||
<table className='table'>
|
<ProjectFlockKandangTable
|
||||||
{/* head */}
|
listKandang={optionsKandang}
|
||||||
<thead>
|
rowSelection={rowSelection}
|
||||||
<tr>
|
setRowSelection={setRowSelection}
|
||||||
<th>
|
selectedIds={formik.values.kandang_ids}
|
||||||
<label>
|
formType={formType}
|
||||||
<input
|
|
||||||
type='checkbox'
|
|
||||||
checked={
|
|
||||||
optionsKandang
|
|
||||||
.filter(
|
|
||||||
(k) =>
|
|
||||||
k.status === 'NON_ACTIVE' ||
|
|
||||||
formik.values.kandang_ids.includes(k.id)
|
|
||||||
)
|
|
||||||
.every((k) =>
|
|
||||||
formik.values.kandang_ids.includes(k.id)
|
|
||||||
) &&
|
|
||||||
optionsKandang.filter(
|
|
||||||
(k) =>
|
|
||||||
k.status === 'NON_ACTIVE' ||
|
|
||||||
formik.values.kandang_ids.includes(k.id)
|
|
||||||
).length > 0
|
|
||||||
}
|
|
||||||
className='checkbox transition-none'
|
|
||||||
disabled={
|
|
||||||
formType === 'detail' ||
|
|
||||||
optionsKandang.filter(
|
|
||||||
(k) => k.status === 'NON_ACTIVE'
|
|
||||||
).length == 0
|
|
||||||
}
|
|
||||||
onChange={
|
|
||||||
formType === 'detail'
|
|
||||||
? () => {}
|
|
||||||
: kandangCheckAll
|
|
||||||
}
|
|
||||||
/>
|
/>
|
||||||
</label>
|
|
||||||
</th>
|
|
||||||
<th>Kandang</th>
|
|
||||||
<th>Status</th>
|
|
||||||
<th>Penanggung Jawab</th>
|
|
||||||
</tr>
|
|
||||||
</thead>
|
|
||||||
<tbody>
|
|
||||||
{/* rows */}
|
|
||||||
{selectedLocation != '' &&
|
|
||||||
optionsKandang.map((kandang) => (
|
|
||||||
<tr key={kandang.id}>
|
|
||||||
<th>
|
|
||||||
<label>
|
|
||||||
<input
|
|
||||||
value={kandang.id}
|
|
||||||
type='checkbox'
|
|
||||||
className='checkbox transition-none'
|
|
||||||
checked={formik.values.kandang_ids.includes(
|
|
||||||
kandang.id
|
|
||||||
)}
|
|
||||||
onChange={
|
|
||||||
formType === 'detail'
|
|
||||||
? () => {}
|
|
||||||
: kandangChangeHandler
|
|
||||||
}
|
|
||||||
disabled={
|
|
||||||
formType === 'detail' ||
|
|
||||||
kandang.status != 'NON_ACTIVE'
|
|
||||||
}
|
|
||||||
/>
|
|
||||||
</label>
|
|
||||||
</th>
|
|
||||||
<td>{kandang.name}</td>
|
|
||||||
<td>{kandang.status}</td>
|
|
||||||
<td>{kandang.pic?.name}</td>
|
|
||||||
</tr>
|
|
||||||
))}
|
|
||||||
{selectedLocation == '' && (
|
|
||||||
<tr>
|
|
||||||
<td colSpan={3} className='text-center text-muted'>
|
|
||||||
Data tidak tersedia
|
|
||||||
</td>
|
|
||||||
</tr>
|
|
||||||
)}
|
|
||||||
</tbody>
|
|
||||||
{/* foot */}
|
|
||||||
{selectedLocation != '' && (
|
|
||||||
<tfoot>
|
|
||||||
<tr>
|
|
||||||
<th></th>
|
|
||||||
<th>Kandang</th>
|
|
||||||
<th>Penanggung Jawab</th>
|
|
||||||
</tr>
|
|
||||||
</tfoot>
|
|
||||||
)}
|
|
||||||
</table>
|
|
||||||
</div>
|
</div>
|
||||||
</Collapse>
|
</Collapse>
|
||||||
</div>
|
</div>
|
||||||
@@ -795,16 +767,24 @@ const ProjectFlockForm = ({
|
|||||||
|
|
||||||
<ConfirmationModal
|
<ConfirmationModal
|
||||||
ref={confirmModal.ref}
|
ref={confirmModal.ref}
|
||||||
type='success'
|
type={approvalAction == 'APPROVED' ? 'success' : 'error'}
|
||||||
text={`Apakah anda yakin ingin approve Project Flock berikut? (${initialValues?.flock?.name} - ${initialValues?.area?.name})?`}
|
text={`Apakah anda yakin ingin ${
|
||||||
|
approvalAction == 'APPROVED' ? 'approve' : 'reject'
|
||||||
|
} Project Flock berikut? (${initialValues?.flock?.name} - ${
|
||||||
|
initialValues?.area?.name
|
||||||
|
})?`}
|
||||||
secondaryButton={{
|
secondaryButton={{
|
||||||
text: 'Tidak',
|
text: 'Tidak',
|
||||||
}}
|
}}
|
||||||
primaryButton={{
|
primaryButton={{
|
||||||
text: 'Ya',
|
text: 'Ya',
|
||||||
color: 'success',
|
color: approvalAction == 'APPROVED' ? 'success' : 'error',
|
||||||
isLoading: isApproveLoading,
|
isLoading: isApproveLoading,
|
||||||
onClick: confirmationModalApproveClickHandler,
|
onClick: () => {
|
||||||
|
confirmationModalClickHandler({
|
||||||
|
action: approvalAction,
|
||||||
|
});
|
||||||
|
},
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
</>
|
</>
|
||||||
|
|||||||
@@ -0,0 +1,146 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
import CheckboxInput from '@/components/input/CheckboxInput';
|
||||||
|
import PillBadge from '@/components/PillBadge';
|
||||||
|
import Table from '@/components/Table';
|
||||||
|
import { cn } from '@/lib/helper';
|
||||||
|
import { Kandang } from '@/types/api/master-data/kandang';
|
||||||
|
import { OnChangeFn } from '@tanstack/react-table';
|
||||||
|
|
||||||
|
const ProjectFlockKandangTable = ({
|
||||||
|
listKandang,
|
||||||
|
rowSelection,
|
||||||
|
setRowSelection,
|
||||||
|
selectedIds,
|
||||||
|
formType = 'add',
|
||||||
|
}: {
|
||||||
|
listKandang: Kandang[];
|
||||||
|
rowSelection: Record<string, boolean>;
|
||||||
|
setRowSelection: OnChangeFn<Record<string, boolean>>;
|
||||||
|
selectedIds: (number | undefined)[];
|
||||||
|
formType: 'add' | 'edit' | 'detail';
|
||||||
|
}) => {
|
||||||
|
console.log('selectedIds');
|
||||||
|
console.log(selectedIds);
|
||||||
|
return (
|
||||||
|
<Table<Kandang>
|
||||||
|
data={listKandang}
|
||||||
|
columns={[
|
||||||
|
{
|
||||||
|
id: 'select',
|
||||||
|
header: ({ table }) => {
|
||||||
|
const allRows = table.getRowModel().rows;
|
||||||
|
const selectableRows = allRows.filter(
|
||||||
|
(row) =>
|
||||||
|
row.original.status == 'NON_ACTIVE' ||
|
||||||
|
row.original.status == 'PENGAJUAN'
|
||||||
|
);
|
||||||
|
|
||||||
|
const allSelected =
|
||||||
|
selectableRows.every((row) => row.getIsSelected()) &&
|
||||||
|
selectableRows.length != 0 && formType != 'detail';
|
||||||
|
|
||||||
|
const someSelected =
|
||||||
|
selectableRows.some((row) => row.getIsSelected()) && !allSelected && formType != 'detail';
|
||||||
|
|
||||||
|
const toggleSelectableRows = () => {
|
||||||
|
const shouldSelect = !allSelected;
|
||||||
|
selectableRows.forEach((row) => row.toggleSelected(shouldSelect));
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className='w-full flex flex-row justify-center'>
|
||||||
|
<CheckboxInput
|
||||||
|
name='allRow'
|
||||||
|
checked={allSelected}
|
||||||
|
indeterminate={someSelected}
|
||||||
|
onChange={toggleSelectableRows}
|
||||||
|
disabled={
|
||||||
|
listKandang.filter(
|
||||||
|
(kandang) =>
|
||||||
|
kandang.status == 'NON_ACTIVE' ||
|
||||||
|
kandang.status == 'PENGAJUAN'
|
||||||
|
).length == 0 || formType == 'detail'
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
},
|
||||||
|
cell: ({ row }) => {
|
||||||
|
return (
|
||||||
|
<CheckboxInput
|
||||||
|
name='row'
|
||||||
|
checked={
|
||||||
|
(row.getIsSelected() &&
|
||||||
|
(row.original.status == 'NON_ACTIVE' ||
|
||||||
|
row.original.status == 'PENGAJUAN')) ||
|
||||||
|
selectedIds.includes(row.original.id)
|
||||||
|
}
|
||||||
|
disabled={
|
||||||
|
!row.getCanSelect() ||
|
||||||
|
(row.original.status != 'NON_ACTIVE' &&
|
||||||
|
row.original.status != 'PENGAJUAN') ||
|
||||||
|
formType == 'detail'
|
||||||
|
}
|
||||||
|
indeterminate={row.getIsSomeSelected()}
|
||||||
|
onChange={row.getToggleSelectedHandler()}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
accessorFn: (row) => row.name,
|
||||||
|
header: 'Kandang',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
accessorFn: (row) => row.status,
|
||||||
|
header: 'Status',
|
||||||
|
cell: (props) => {
|
||||||
|
return (
|
||||||
|
<PillBadge
|
||||||
|
color={(() => {
|
||||||
|
switch (props.row.original.status) {
|
||||||
|
case 'ACTIVE':
|
||||||
|
return 'red';
|
||||||
|
case 'PENGAJUAN':
|
||||||
|
return 'green';
|
||||||
|
case 'NON_ACTIVE':
|
||||||
|
return 'blue';
|
||||||
|
default:
|
||||||
|
return 'gray';
|
||||||
|
}
|
||||||
|
})()}
|
||||||
|
content={props.row.original.status
|
||||||
|
.toLowerCase()
|
||||||
|
.replace(/_/g, ' ')
|
||||||
|
.replace(/\b\w/g, (char) => char.toUpperCase())}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
accessorFn: (row) => row.pic?.name,
|
||||||
|
header: 'Penanggung Jawab',
|
||||||
|
},
|
||||||
|
]}
|
||||||
|
className={{
|
||||||
|
containerClassName: cn({
|
||||||
|
'mb-20': listKandang?.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',
|
||||||
|
paginationClassName: 'hidden',
|
||||||
|
}}
|
||||||
|
rowSelection={rowSelection}
|
||||||
|
setRowSelection={setRowSelection}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default ProjectFlockKandangTable;
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
'use client';
|
'use client';
|
||||||
|
|
||||||
import { useCallback, useMemo, useState } from 'react';
|
import { useCallback, useMemo, useState } from 'react';
|
||||||
|
import useSWR from 'swr';
|
||||||
import { Icon } from '@iconify/react';
|
import { Icon } from '@iconify/react';
|
||||||
import { SortingState } from '@tanstack/react-table';
|
import { SortingState } from '@tanstack/react-table';
|
||||||
import { cn } from '@/lib/helper';
|
import { cn } from '@/lib/helper';
|
||||||
@@ -8,7 +9,9 @@ import { useModal } from '@/components/Modal';
|
|||||||
import Button from '@/components/Button';
|
import Button from '@/components/Button';
|
||||||
import ConfirmationModal from '@/components/modal/ConfirmationModal';
|
import ConfirmationModal from '@/components/modal/ConfirmationModal';
|
||||||
import { OptionType } from '@/components/input/SelectInput';
|
import { OptionType } from '@/components/input/SelectInput';
|
||||||
|
import SelectInput from '@/components/input/SelectInput';
|
||||||
import { ROWS_OPTIONS } from '@/config/constant';
|
import { ROWS_OPTIONS } from '@/config/constant';
|
||||||
|
import CheckboxInput from '@/components/input/CheckboxInput';
|
||||||
import { TableToolbar } from '@/components/table/TableToolbar';
|
import { TableToolbar } from '@/components/table/TableToolbar';
|
||||||
import { TableRowSizeSelector } from '@/components/table/TableRowSizeSelector';
|
import { TableRowSizeSelector } from '@/components/table/TableRowSizeSelector';
|
||||||
import Table from '@/components/Table';
|
import Table from '@/components/Table';
|
||||||
@@ -16,105 +19,14 @@ import RowDropdownOptions from '@/components/table/RowDropdownOptions';
|
|||||||
import RowCollapseOptions from '@/components/table/RowCollapseOptions';
|
import RowCollapseOptions from '@/components/table/RowCollapseOptions';
|
||||||
import { type CellContext } from '@tanstack/react-table';
|
import { type CellContext } from '@tanstack/react-table';
|
||||||
import { type Recording } from '@/types/api/production/recording';
|
import { type Recording } from '@/types/api/production/recording';
|
||||||
|
import { type BaseApiResponse } from '@/types/api/api-general';
|
||||||
const dummyRecordings: Recording[] = [
|
import { RecordingApi } from '@/services/api/production';
|
||||||
{
|
import { AreaApi } from '@/services/api/master-data';
|
||||||
id: 1,
|
import { LocationApi } from '@/services/api/master-data';
|
||||||
flock: {
|
import { KandangApi } from '@/services/api/master-data';
|
||||||
id: 1,
|
import { isResponseSuccess, isResponseError } from '@/lib/api-helper';
|
||||||
name: 'Flock Recording 1',
|
import { useTableFilter } from '@/services/hooks/useTableFilter';
|
||||||
created_at: '2024-01-01',
|
import toast from 'react-hot-toast';
|
||||||
updated_at: '2024-01-01',
|
|
||||||
created_user: {
|
|
||||||
id: 1,
|
|
||||||
id_user: 1,
|
|
||||||
email: 'admin@example.com',
|
|
||||||
name: 'Admin',
|
|
||||||
},
|
|
||||||
},
|
|
||||||
recording_date: '2024-01-01',
|
|
||||||
location: {
|
|
||||||
id: 1,
|
|
||||||
name: 'Location 1',
|
|
||||||
address: 'Jl. Contoh No. 1',
|
|
||||||
area: {
|
|
||||||
id: 1,
|
|
||||||
name: 'Area 1',
|
|
||||||
},
|
|
||||||
created_at: '2024-01-01',
|
|
||||||
updated_at: '2024-01-01',
|
|
||||||
created_user: {
|
|
||||||
id: 1,
|
|
||||||
id_user: 1,
|
|
||||||
email: 'admin@example.com',
|
|
||||||
name: 'Admin',
|
|
||||||
},
|
|
||||||
},
|
|
||||||
coop: {
|
|
||||||
id: 1,
|
|
||||||
name: 'Coop 1',
|
|
||||||
status: 'ACTIVE',
|
|
||||||
location: {
|
|
||||||
id: 1,
|
|
||||||
name: 'Location 1',
|
|
||||||
address: 'Jl. Contoh No. 1',
|
|
||||||
area: {
|
|
||||||
id: 1,
|
|
||||||
name: 'Area 1',
|
|
||||||
},
|
|
||||||
},
|
|
||||||
pic: {
|
|
||||||
id: 1,
|
|
||||||
id_user: 1,
|
|
||||||
email: 'pic@example.com',
|
|
||||||
name: 'PIC User',
|
|
||||||
},
|
|
||||||
created_at: '2024-01-01',
|
|
||||||
updated_at: '2024-01-01',
|
|
||||||
created_user: {
|
|
||||||
id: 1,
|
|
||||||
id_user: 1,
|
|
||||||
email: 'admin@example.com',
|
|
||||||
name: 'Admin',
|
|
||||||
},
|
|
||||||
},
|
|
||||||
feed_data: [
|
|
||||||
{
|
|
||||||
feed_name: 'Feed 1',
|
|
||||||
feed_qty: 100,
|
|
||||||
feed_stock: 500,
|
|
||||||
},
|
|
||||||
],
|
|
||||||
body_weight: [
|
|
||||||
{
|
|
||||||
chicken_weight: 2.5,
|
|
||||||
chicken_count: 1000,
|
|
||||||
average_chicken_weight: 2.5,
|
|
||||||
},
|
|
||||||
],
|
|
||||||
vaccination: [
|
|
||||||
{
|
|
||||||
vaccine_name: 'Vaccine 1',
|
|
||||||
total_stock: 200,
|
|
||||||
used_stock: 150,
|
|
||||||
},
|
|
||||||
],
|
|
||||||
mortality: [
|
|
||||||
{
|
|
||||||
condition: 'NORMAL',
|
|
||||||
count: 5,
|
|
||||||
},
|
|
||||||
],
|
|
||||||
created_at: '2024-01-01',
|
|
||||||
updated_at: '2024-01-01',
|
|
||||||
created_user: {
|
|
||||||
id: 1,
|
|
||||||
id_user: 1,
|
|
||||||
email: 'admin@example.com',
|
|
||||||
name: 'Admin',
|
|
||||||
},
|
|
||||||
},
|
|
||||||
];
|
|
||||||
|
|
||||||
const RowOptionsMenu = ({
|
const RowOptionsMenu = ({
|
||||||
type = 'dropdown',
|
type = 'dropdown',
|
||||||
@@ -173,12 +85,34 @@ const RowOptionsMenu = ({
|
|||||||
};
|
};
|
||||||
|
|
||||||
const RecordingTable = () => {
|
const RecordingTable = () => {
|
||||||
const [search, setSearch] = useState('');
|
const {
|
||||||
const [page, setPage] = useState(1);
|
state: tableFilterState,
|
||||||
const [pageSize, setPageSize] = useState(10);
|
updateFilter,
|
||||||
|
setPage,
|
||||||
|
setPageSize,
|
||||||
|
toQueryString: getTableFilterQueryString,
|
||||||
|
} = useTableFilter({
|
||||||
|
initial: {
|
||||||
|
search: '',
|
||||||
|
areaFilter: '',
|
||||||
|
locationFilter: '',
|
||||||
|
kandangFilter: '',
|
||||||
|
periodFilter: '',
|
||||||
|
},
|
||||||
|
paramMap: {
|
||||||
|
page: 'page',
|
||||||
|
pageSize: 'limit',
|
||||||
|
search: 'search',
|
||||||
|
areaFilter: 'area_id',
|
||||||
|
locationFilter: 'location_id',
|
||||||
|
kandangFilter: 'kandang_id',
|
||||||
|
periodFilter: 'period',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
const [sorting, setSorting] = useState<SortingState>([]);
|
const [sorting, setSorting] = useState<SortingState>([]);
|
||||||
const [selectedRecordings, setSelectedRecordings] = useState<number[]>([]);
|
const [rowSelection, setRowSelection] = useState<Record<string, boolean>>({});
|
||||||
const [, setSelectedRecording] = useState<Recording | undefined>(undefined);
|
const [selectedRecording, setSelectedRecording] = useState<Recording | undefined>(undefined);
|
||||||
const [isDeleteLoading, setIsDeleteLoading] = useState(false);
|
const [isDeleteLoading, setIsDeleteLoading] = useState(false);
|
||||||
const [isBulkApproveLoading, setIsBulkApproveLoading] = useState(false);
|
const [isBulkApproveLoading, setIsBulkApproveLoading] = useState(false);
|
||||||
const [isBulkRejectLoading, setIsBulkRejectLoading] = useState(false);
|
const [isBulkRejectLoading, setIsBulkRejectLoading] = useState(false);
|
||||||
@@ -187,12 +121,81 @@ const RecordingTable = () => {
|
|||||||
const bulkApproveModal = useModal();
|
const bulkApproveModal = useModal();
|
||||||
const bulkRejectModal = useModal();
|
const bulkRejectModal = useModal();
|
||||||
|
|
||||||
|
// State for dropdown search
|
||||||
|
const [locationSelectInputValue, setLocationSelectInputValue] = useState('');
|
||||||
|
const [areaSelectInputValue, setAreaSelectInputValue] = useState('');
|
||||||
|
const [kandangSelectInputValue, setKandangSelectInputValue] = useState('');
|
||||||
|
|
||||||
|
const [selectedArea, setSelectedArea] = useState<OptionType | null>(null);
|
||||||
|
const [selectedLocation, setSelectedLocation] = useState<OptionType | null>(null);
|
||||||
|
const [selectedKandang, setSelectedKandang] = useState<OptionType | null>(null);
|
||||||
|
|
||||||
|
const {
|
||||||
|
data: recordings,
|
||||||
|
isLoading,
|
||||||
|
mutate: refreshRecordings,
|
||||||
|
} = useSWR(
|
||||||
|
`${RecordingApi.basePath}${getTableFilterQueryString()}`,
|
||||||
|
RecordingApi.getAllFetcher
|
||||||
|
);
|
||||||
|
|
||||||
|
// Fetch data for dropdowns
|
||||||
|
const areaUrl = `${AreaApi.basePath}?${new URLSearchParams({
|
||||||
|
search: areaSelectInputValue,
|
||||||
|
limit: '100',
|
||||||
|
}).toString()}`;
|
||||||
|
const {
|
||||||
|
data: areas,
|
||||||
|
isLoading: isLoadingAreas,
|
||||||
|
} = useSWR(areaUrl, AreaApi.getAllFetcher);
|
||||||
|
|
||||||
|
const locationUrl = `${LocationApi.basePath}?${new URLSearchParams({
|
||||||
|
search: locationSelectInputValue,
|
||||||
|
area_id: selectedArea != null ? selectedArea.value.toString() : '',
|
||||||
|
limit: '100',
|
||||||
|
}).toString()}`;
|
||||||
|
const {
|
||||||
|
data: locations,
|
||||||
|
isLoading: isLoadingLocations,
|
||||||
|
} = useSWR(locationUrl, LocationApi.getAllFetcher);
|
||||||
|
|
||||||
|
const kandangUrl = `${KandangApi.basePath}?${new URLSearchParams({
|
||||||
|
search: kandangSelectInputValue,
|
||||||
|
location_id:
|
||||||
|
selectedLocation != null ? selectedLocation.value.toString() : '',
|
||||||
|
limit: '100',
|
||||||
|
}).toString()}`;
|
||||||
|
const {
|
||||||
|
data: kandangs,
|
||||||
|
isLoading: isLoadingKandang,
|
||||||
|
} = useSWR(kandangUrl, KandangApi.getAllFetcher);
|
||||||
|
|
||||||
|
// Data to Options Mapping
|
||||||
|
const optionsArea = isResponseSuccess(areas)
|
||||||
|
? areas?.data.map((area) => ({
|
||||||
|
value: area.id,
|
||||||
|
label: area.name,
|
||||||
|
}))
|
||||||
|
: [];
|
||||||
|
const optionsLocation = isResponseSuccess(locations)
|
||||||
|
? locations?.data.map((location) => ({
|
||||||
|
value: location.id,
|
||||||
|
label: location.name,
|
||||||
|
}))
|
||||||
|
: [];
|
||||||
|
const optionsKandang = isResponseSuccess(kandangs)
|
||||||
|
? kandangs?.data.map((kandang) => ({
|
||||||
|
value: kandang.id,
|
||||||
|
label: kandang.name,
|
||||||
|
}))
|
||||||
|
: [];
|
||||||
|
|
||||||
const searchChangeHandler = useCallback(
|
const searchChangeHandler = useCallback(
|
||||||
(e: React.ChangeEvent<HTMLInputElement>) => {
|
(e: React.ChangeEvent<HTMLInputElement>) => {
|
||||||
setSearch(e.target.value);
|
updateFilter('search', e.target.value);
|
||||||
setPage(1);
|
setPage(1);
|
||||||
},
|
},
|
||||||
[]
|
[updateFilter, setPage]
|
||||||
);
|
);
|
||||||
|
|
||||||
const pageSizeChangeHandler = useCallback(
|
const pageSizeChangeHandler = useCallback(
|
||||||
@@ -201,52 +204,80 @@ const RecordingTable = () => {
|
|||||||
setPageSize(newVal.value as number);
|
setPageSize(newVal.value as number);
|
||||||
setPage(1);
|
setPage(1);
|
||||||
},
|
},
|
||||||
[]
|
[setPageSize, setPage]
|
||||||
);
|
);
|
||||||
|
|
||||||
const paginatedData = useMemo(() => {
|
const paginatedData = useMemo(() => {
|
||||||
const filteredData = dummyRecordings.filter(
|
if (!recordings || recordings.status !== 'success') return [];
|
||||||
(recording) =>
|
|
||||||
recording.flock.name.toLowerCase().includes(search.toLowerCase()) ||
|
return recordings.data;
|
||||||
recording.location.name.toLowerCase().includes(search.toLowerCase()) ||
|
}, [recordings]);
|
||||||
recording.coop.name.toLowerCase().includes(search.toLowerCase())
|
|
||||||
);
|
const selectedRowIds = Object.keys(rowSelection).map((item) => parseInt(item));
|
||||||
const start = (page - 1) * pageSize;
|
|
||||||
return filteredData.slice(start, start + pageSize);
|
|
||||||
}, [page, pageSize, search]);
|
|
||||||
|
|
||||||
const bulkApproveHandler = async () => {
|
const bulkApproveHandler = async () => {
|
||||||
setIsBulkApproveLoading(true);
|
setIsBulkApproveLoading(true);
|
||||||
console.log(
|
|
||||||
'Approved recordings:',
|
const approveResponse = await RecordingApi.customRequest<
|
||||||
paginatedData.filter((_, idx) => selectedRecordings.includes(idx))
|
BaseApiResponse<Recording[]>
|
||||||
);
|
>('approvals', {
|
||||||
setTimeout(() => {
|
method: 'POST',
|
||||||
setIsBulkApproveLoading(false);
|
payload: {
|
||||||
setSelectedRecordings([]);
|
action: 'APPROVED',
|
||||||
|
approvable_ids: selectedRowIds,
|
||||||
|
notes: 'Bulk Approved',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
if (isResponseSuccess(approveResponse)) {
|
||||||
|
await refreshRecordings();
|
||||||
|
setRowSelection({});
|
||||||
bulkApproveModal.closeModal();
|
bulkApproveModal.closeModal();
|
||||||
}, 1000);
|
toast.success(`Successfully approved ${selectedRowIds.length} recordings!`);
|
||||||
|
}
|
||||||
|
if (isResponseError(approveResponse)) {
|
||||||
|
toast.error(approveResponse?.message as string);
|
||||||
|
bulkApproveModal.closeModal();
|
||||||
|
}
|
||||||
|
setIsBulkApproveLoading(false);
|
||||||
};
|
};
|
||||||
|
|
||||||
const bulkRejectHandler = async () => {
|
const bulkRejectHandler = async () => {
|
||||||
setIsBulkRejectLoading(true);
|
setIsBulkRejectLoading(true);
|
||||||
console.log(
|
|
||||||
'Rejected recordings:',
|
const rejectResponse = await RecordingApi.customRequest<
|
||||||
paginatedData.filter((_, idx) => selectedRecordings.includes(idx))
|
BaseApiResponse<Recording[]>
|
||||||
);
|
>('approvals', {
|
||||||
setTimeout(() => {
|
method: 'POST',
|
||||||
setIsBulkRejectLoading(false);
|
payload: {
|
||||||
setSelectedRecordings([]);
|
action: 'REJECTED',
|
||||||
|
approvable_ids: selectedRowIds,
|
||||||
|
notes: 'Bulk Rejected',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
if (isResponseSuccess(rejectResponse)) {
|
||||||
|
refreshRecordings();
|
||||||
|
setRowSelection({});
|
||||||
bulkRejectModal.closeModal();
|
bulkRejectModal.closeModal();
|
||||||
}, 1000);
|
toast.success(`Successfully rejected ${selectedRowIds.length} recordings!`);
|
||||||
|
}
|
||||||
|
if (isResponseError(rejectResponse)) {
|
||||||
|
toast.error(rejectResponse?.message as string);
|
||||||
|
bulkRejectModal.closeModal();
|
||||||
|
}
|
||||||
|
setIsBulkRejectLoading(false);
|
||||||
};
|
};
|
||||||
|
|
||||||
const singleDeleteHandler = async () => {
|
const singleDeleteHandler = async () => {
|
||||||
setIsDeleteLoading(true);
|
setIsDeleteLoading(true);
|
||||||
setTimeout(() => {
|
|
||||||
setIsDeleteLoading(false);
|
await RecordingApi.delete(selectedRecording?.id as number);
|
||||||
|
refreshRecordings();
|
||||||
|
|
||||||
singleDeleteModal.closeModal();
|
singleDeleteModal.closeModal();
|
||||||
}, 1000);
|
toast.success('Successfully delete Recording!');
|
||||||
|
setIsDeleteLoading(false);
|
||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
@@ -258,21 +289,189 @@ const RecordingTable = () => {
|
|||||||
label: 'Tambah Recording',
|
label: 'Tambah Recording',
|
||||||
}}
|
}}
|
||||||
search={{
|
search={{
|
||||||
value: search,
|
value: tableFilterState.search,
|
||||||
onChange: searchChangeHandler,
|
onChange: searchChangeHandler,
|
||||||
placeholder: 'Cari Recording',
|
placeholder: 'Cari Recording',
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
<TableRowSizeSelector
|
<TableRowSizeSelector
|
||||||
value={pageSize}
|
value={tableFilterState.pageSize}
|
||||||
onChange={pageSizeChangeHandler}
|
onChange={pageSizeChangeHandler}
|
||||||
options={ROWS_OPTIONS}
|
options={ROWS_OPTIONS}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
|
{/* Filter Dropdowns - Desktop */}
|
||||||
|
<div className='hidden sm:grid sm:grid-cols-4 gap-4 mt-4'>
|
||||||
|
<SelectInput
|
||||||
|
label='Area'
|
||||||
|
placeholder='Pilih Area'
|
||||||
|
options={optionsArea}
|
||||||
|
value={selectedArea}
|
||||||
|
onChange={(selected) => {
|
||||||
|
const selectedValue = selected as OptionType | null;
|
||||||
|
setSelectedArea(selectedValue);
|
||||||
|
setSelectedLocation(null);
|
||||||
|
setSelectedKandang(null);
|
||||||
|
updateFilter('areaFilter', selectedValue ? selectedValue.value.toString() : '');
|
||||||
|
updateFilter('locationFilter', '');
|
||||||
|
updateFilter('kandangFilter', '');
|
||||||
|
setPage(1);
|
||||||
|
}}
|
||||||
|
className={{ wrapper: 'w-full' }}
|
||||||
|
onInputChange={(value) => setAreaSelectInputValue(value)}
|
||||||
|
isLoading={isLoadingAreas}
|
||||||
|
isClearable
|
||||||
|
/>
|
||||||
|
|
||||||
|
<SelectInput
|
||||||
|
label='Lokasi'
|
||||||
|
placeholder='Pilih Lokasi'
|
||||||
|
options={optionsLocation}
|
||||||
|
value={selectedLocation}
|
||||||
|
onChange={(selected) => {
|
||||||
|
const selectedValue = selected as OptionType | null;
|
||||||
|
setSelectedLocation(selectedValue);
|
||||||
|
setSelectedKandang(null);
|
||||||
|
updateFilter('locationFilter', selectedValue ? selectedValue.value.toString() : '');
|
||||||
|
updateFilter('kandangFilter', '');
|
||||||
|
setPage(1);
|
||||||
|
}}
|
||||||
|
className={{ wrapper: 'w-full' }}
|
||||||
|
onInputChange={(value) => setLocationSelectInputValue(value)}
|
||||||
|
isLoading={isLoadingLocations}
|
||||||
|
isClearable
|
||||||
|
isDisabled={!selectedArea}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<SelectInput
|
||||||
|
label='Kandang'
|
||||||
|
placeholder='Pilih Kandang'
|
||||||
|
options={optionsKandang}
|
||||||
|
value={selectedKandang}
|
||||||
|
onChange={(selected) => {
|
||||||
|
const selectedValue = selected as OptionType | null;
|
||||||
|
setSelectedKandang(selectedValue);
|
||||||
|
updateFilter('kandangFilter', selectedValue ? selectedValue.value.toString() : '');
|
||||||
|
setPage(1);
|
||||||
|
}}
|
||||||
|
className={{ wrapper: 'w-full' }}
|
||||||
|
onInputChange={(value) => setKandangSelectInputValue(value)}
|
||||||
|
isLoading={isLoadingKandang}
|
||||||
|
isClearable
|
||||||
|
isDisabled={!selectedLocation}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<SelectInput
|
||||||
|
label='Periode'
|
||||||
|
placeholder='Pilih Periode'
|
||||||
|
options={[
|
||||||
|
{ value: '1', label: 'Periode 1' },
|
||||||
|
{ value: '2', label: 'Periode 2' },
|
||||||
|
{ value: '3', label: 'Periode 3' },
|
||||||
|
]}
|
||||||
|
value={
|
||||||
|
tableFilterState.periodFilter
|
||||||
|
? { value: tableFilterState.periodFilter, label: `Periode ${tableFilterState.periodFilter}` }
|
||||||
|
: null
|
||||||
|
}
|
||||||
|
onChange={(selected) => {
|
||||||
|
const selectedValue = selected as OptionType | null;
|
||||||
|
updateFilter('periodFilter', selectedValue ? selectedValue.value.toString() : '');
|
||||||
|
setPage(1);
|
||||||
|
}}
|
||||||
|
className={{ wrapper: 'w-full' }}
|
||||||
|
isClearable
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Filter Dropdowns - Mobile */}
|
||||||
|
<div className='sm:hidden flex flex-col gap-3 mt-4'>
|
||||||
|
<SelectInput
|
||||||
|
label='Area'
|
||||||
|
placeholder='Pilih Area'
|
||||||
|
options={optionsArea}
|
||||||
|
value={selectedArea}
|
||||||
|
onChange={(selected) => {
|
||||||
|
const selectedValue = selected as OptionType | null;
|
||||||
|
setSelectedArea(selectedValue);
|
||||||
|
setSelectedLocation(null);
|
||||||
|
setSelectedKandang(null);
|
||||||
|
updateFilter('areaFilter', selectedValue ? selectedValue.value.toString() : '');
|
||||||
|
updateFilter('locationFilter', '');
|
||||||
|
updateFilter('kandangFilter', '');
|
||||||
|
setPage(1);
|
||||||
|
}}
|
||||||
|
className={{ wrapper: 'w-full' }}
|
||||||
|
onInputChange={(value) => setAreaSelectInputValue(value)}
|
||||||
|
isLoading={isLoadingAreas}
|
||||||
|
isClearable
|
||||||
|
/>
|
||||||
|
|
||||||
|
<SelectInput
|
||||||
|
label='Lokasi'
|
||||||
|
placeholder='Pilih Lokasi'
|
||||||
|
options={optionsLocation}
|
||||||
|
value={selectedLocation}
|
||||||
|
onChange={(selected) => {
|
||||||
|
const selectedValue = selected as OptionType | null;
|
||||||
|
setSelectedLocation(selectedValue);
|
||||||
|
setSelectedKandang(null);
|
||||||
|
updateFilter('locationFilter', selectedValue ? selectedValue.value.toString() : '');
|
||||||
|
updateFilter('kandangFilter', '');
|
||||||
|
setPage(1);
|
||||||
|
}}
|
||||||
|
className={{ wrapper: 'w-full' }}
|
||||||
|
onInputChange={(value) => setLocationSelectInputValue(value)}
|
||||||
|
isLoading={isLoadingLocations}
|
||||||
|
isClearable
|
||||||
|
isDisabled={!selectedArea}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<SelectInput
|
||||||
|
label='Kandang'
|
||||||
|
placeholder='Pilih Kandang'
|
||||||
|
options={optionsKandang}
|
||||||
|
value={selectedKandang}
|
||||||
|
onChange={(selected) => {
|
||||||
|
const selectedValue = selected as OptionType | null;
|
||||||
|
setSelectedKandang(selectedValue);
|
||||||
|
updateFilter('kandangFilter', selectedValue ? selectedValue.value.toString() : '');
|
||||||
|
setPage(1);
|
||||||
|
}}
|
||||||
|
className={{ wrapper: 'w-full' }}
|
||||||
|
onInputChange={(value) => setKandangSelectInputValue(value)}
|
||||||
|
isLoading={isLoadingKandang}
|
||||||
|
isClearable
|
||||||
|
isDisabled={!selectedLocation}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<SelectInput
|
||||||
|
label='Periode'
|
||||||
|
placeholder='Pilih Periode'
|
||||||
|
options={[
|
||||||
|
{ value: '1', label: 'Periode 1' },
|
||||||
|
{ value: '2', label: 'Periode 2' },
|
||||||
|
{ value: '3', label: 'Periode 3' },
|
||||||
|
]}
|
||||||
|
value={
|
||||||
|
tableFilterState.periodFilter
|
||||||
|
? { value: tableFilterState.periodFilter, label: `Periode ${tableFilterState.periodFilter}` }
|
||||||
|
: null
|
||||||
|
}
|
||||||
|
onChange={(selected) => {
|
||||||
|
const selectedValue = selected as OptionType | null;
|
||||||
|
updateFilter('periodFilter', selectedValue ? selectedValue.value.toString() : '');
|
||||||
|
setPage(1);
|
||||||
|
}}
|
||||||
|
className={{ wrapper: 'w-full' }}
|
||||||
|
isClearable
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Bulk action buttons */}
|
{/* Bulk action buttons */}
|
||||||
<div className={'flex justify-end items-center'}>
|
<div className={'flex justify-end items-center'}>
|
||||||
{selectedRecordings.length > 0 && (
|
{selectedRowIds.length > 0 && (
|
||||||
<div className='flex gap-2 mb-4'>
|
<div className='flex gap-2 mb-4'>
|
||||||
<Button
|
<Button
|
||||||
type='button'
|
type='button'
|
||||||
@@ -285,7 +484,7 @@ const RecordingTable = () => {
|
|||||||
width={20}
|
width={20}
|
||||||
height={20}
|
height={20}
|
||||||
/>
|
/>
|
||||||
Approve ({selectedRecordings.length})
|
Approve ({selectedRowIds.length})
|
||||||
</Button>
|
</Button>
|
||||||
<Button
|
<Button
|
||||||
type='button'
|
type='button'
|
||||||
@@ -298,7 +497,7 @@ const RecordingTable = () => {
|
|||||||
width={20}
|
width={20}
|
||||||
height={20}
|
height={20}
|
||||||
/>
|
/>
|
||||||
Reject ({selectedRecordings.length})
|
Reject ({selectedRowIds.length})
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
@@ -306,7 +505,7 @@ const RecordingTable = () => {
|
|||||||
<ConfirmationModal
|
<ConfirmationModal
|
||||||
ref={bulkApproveModal.ref}
|
ref={bulkApproveModal.ref}
|
||||||
type='success'
|
type='success'
|
||||||
text={`Apakah anda yakin ingin menyetujui ${selectedRecordings.length} data Recording yang dipilih?`}
|
text={`Apakah anda yakin ingin menyetujui ${selectedRowIds.length} data Recording yang dipilih?`}
|
||||||
secondaryButton={{
|
secondaryButton={{
|
||||||
text: 'Tidak',
|
text: 'Tidak',
|
||||||
}}
|
}}
|
||||||
@@ -321,7 +520,7 @@ const RecordingTable = () => {
|
|||||||
<ConfirmationModal
|
<ConfirmationModal
|
||||||
ref={bulkRejectModal.ref}
|
ref={bulkRejectModal.ref}
|
||||||
type='error'
|
type='error'
|
||||||
text={`Apakah anda yakin ingin menolak ${selectedRecordings.length} data Recording yang dipilih?`}
|
text={`Apakah anda yakin ingin menolak ${selectedRowIds.length} data Recording yang dipilih?`}
|
||||||
secondaryButton={{
|
secondaryButton={{
|
||||||
text: 'Tidak',
|
text: 'Tidak',
|
||||||
}}
|
}}
|
||||||
@@ -339,75 +538,83 @@ const RecordingTable = () => {
|
|||||||
columns={[
|
columns={[
|
||||||
{
|
{
|
||||||
id: 'select',
|
id: 'select',
|
||||||
accessorKey: 'id',
|
|
||||||
header: ({ table }) => (
|
header: ({ table }) => (
|
||||||
<input
|
<div className='w-full flex flex-row justify-center'>
|
||||||
type='checkbox'
|
<CheckboxInput
|
||||||
className='checkbox'
|
name='allRow'
|
||||||
checked={
|
checked={table.getIsAllRowsSelected()}
|
||||||
table.getRowModel().rows.length > 0 &&
|
indeterminate={table.getIsSomeRowsSelected()}
|
||||||
table
|
onChange={table.getToggleAllRowsSelectedHandler()}
|
||||||
.getRowModel()
|
|
||||||
.rows.every((row) => selectedRecordings.includes(row.index))
|
|
||||||
}
|
|
||||||
onChange={(e) => {
|
|
||||||
if (e.target.checked) {
|
|
||||||
setSelectedRecordings(
|
|
||||||
table.getRowModel().rows.map((row) => row.index)
|
|
||||||
);
|
|
||||||
} else {
|
|
||||||
setSelectedRecordings([]);
|
|
||||||
}
|
|
||||||
}}
|
|
||||||
/>
|
/>
|
||||||
|
</div>
|
||||||
),
|
),
|
||||||
cell: ({ row }) => (
|
cell: ({ row }) => (
|
||||||
<input
|
<div>
|
||||||
type='checkbox'
|
<CheckboxInput
|
||||||
className='checkbox'
|
name='row'
|
||||||
checked={selectedRecordings.includes(row.index)}
|
checked={row.getIsSelected()}
|
||||||
onChange={(e) => {
|
disabled={!row.getCanSelect()}
|
||||||
if (e.target.checked) {
|
indeterminate={row.getIsSomeSelected()}
|
||||||
setSelectedRecordings([...selectedRecordings, row.index]);
|
onChange={row.getToggleSelectedHandler()}
|
||||||
} else {
|
|
||||||
setSelectedRecordings(
|
|
||||||
selectedRecordings.filter((i) => i !== row.index)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}}
|
|
||||||
/>
|
/>
|
||||||
|
</div>
|
||||||
),
|
),
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
header: '#',
|
header: '#',
|
||||||
cell: (props) => pageSize * (page - 1) + props.row.index + 1,
|
cell: (props) => tableFilterState.pageSize * (tableFilterState.page - 1) + props.row.index + 1,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
accessorKey: 'flock.name',
|
header: 'Nama Project',
|
||||||
header: 'Flock',
|
cell: (props) => `Project ${props.row.original.project_flock_kandang_id}`,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
accessorKey: 'recording_date',
|
header: 'Umur (hari)',
|
||||||
header: 'Tanggal Recording',
|
cell: (props) => props.row.original.day,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
accessorKey: 'record_date',
|
||||||
|
header: 'Waktu Recording',
|
||||||
cell: (props) =>
|
cell: (props) =>
|
||||||
new Date(props.row.original.recording_date).toLocaleDateString(),
|
new Date(props.row.original.record_date).toLocaleDateString(),
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
accessorKey: 'location.name',
|
header: 'Populasi Awal',
|
||||||
header: 'Lokasi',
|
cell: (props) => props.row.original.total_chick?.toLocaleString() || '-',
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
accessorKey: 'coop.name',
|
header: 'BW',
|
||||||
header: 'Kandang',
|
cell: (props) => props.row.original.avg_daily_gain?.toFixed(2) || '-',
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
accessorKey: 'mortality',
|
header: 'Pakan',
|
||||||
header: 'Total Mortality',
|
cell: (props) => props.row.original.cum_intake?.toLocaleString() || '-',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
header: 'FCR',
|
||||||
|
cell: (props) => props.row.original.fcr_value?.toFixed(2) || '-',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
accessorKey: 'total_depletion',
|
||||||
|
header: 'Total Deplesi',
|
||||||
|
cell: (props) => props.row.original.total_depletion,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
header: 'Deplesi (%)',
|
||||||
|
cell: (props) => props.row.original.daily_depletion_rate?.toFixed(2) || '-',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
header: 'Populasi Akhir',
|
||||||
|
cell: (props) => (props.row.original.total_chick - props.row.original.total_depletion)?.toLocaleString() || '-',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
header: 'Ketepatan Waktu',
|
||||||
|
cell: (props) => props.row.original.ontime ? 'Tepat Waktu' : 'Terlambat',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
header: 'Tanggal Submit',
|
||||||
cell: (props) =>
|
cell: (props) =>
|
||||||
props.row.original.mortality.reduce(
|
new Date(props.row.original.created_at).toLocaleString(),
|
||||||
(acc, curr) => acc + curr.count,
|
|
||||||
0
|
|
||||||
),
|
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
header: 'Aksi',
|
header: 'Aksi',
|
||||||
@@ -452,13 +659,15 @@ const RecordingTable = () => {
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
]}
|
]}
|
||||||
pageSize={pageSize}
|
pageSize={tableFilterState.pageSize}
|
||||||
page={page}
|
page={recordings?.status === 'success' ? recordings.meta?.page : tableFilterState.page}
|
||||||
totalItems={dummyRecordings.length}
|
totalItems={recordings?.status === 'success' ? recordings.meta?.total_results : 0}
|
||||||
onPageChange={setPage}
|
onPageChange={setPage}
|
||||||
isLoading={false}
|
isLoading={isLoading}
|
||||||
sorting={sorting}
|
sorting={sorting}
|
||||||
setSorting={setSorting}
|
setSorting={setSorting}
|
||||||
|
rowSelection={rowSelection}
|
||||||
|
setRowSelection={setRowSelection}
|
||||||
className={{
|
className={{
|
||||||
containerClassName: cn({
|
containerClassName: cn({
|
||||||
'mb-20': paginatedData.length === 0,
|
'mb-20': paginatedData.length === 0,
|
||||||
@@ -477,7 +686,7 @@ const RecordingTable = () => {
|
|||||||
<ConfirmationModal
|
<ConfirmationModal
|
||||||
ref={singleDeleteModal.ref}
|
ref={singleDeleteModal.ref}
|
||||||
type='error'
|
type='error'
|
||||||
text={`Apakah anda yakin ingin menghapus data Recording ini?`}
|
text={`Apakah anda yakin ingin menghapus data Recording ini (ID: ${selectedRecording?.id})?`}
|
||||||
secondaryButton={{
|
secondaryButton={{
|
||||||
text: 'Tidak',
|
text: 'Tidak',
|
||||||
}}
|
}}
|
||||||
|
|||||||
@@ -1,212 +1,222 @@
|
|||||||
import * as Yup from 'yup';
|
import * as Yup from 'yup';
|
||||||
import { RECORDING_FLAG_OPTIONS } from '@/config/constant';
|
import { RECORDING_FLAG_OPTIONS } from '@/config/constant';
|
||||||
import { Recording } from '@/types/api/production/recording';
|
import {
|
||||||
|
Recording,
|
||||||
|
CreateRecordingPayload,
|
||||||
|
} from '@/types/api/production/recording';
|
||||||
|
|
||||||
export const RecordingFormSchema = Yup.object({
|
export const RecordingFormSchema = Yup.object({
|
||||||
flock: Yup.object({
|
project_flock_kandang: Yup.object({
|
||||||
value: Yup.number().min(1).required(),
|
value: Yup.number().min(1).required(),
|
||||||
label: Yup.string().required(),
|
label: Yup.string().required(),
|
||||||
}).nullable(),
|
}).nullable(),
|
||||||
flock_id: Yup.number()
|
project_flock_kandang_id: Yup.number()
|
||||||
.default(0)
|
.default(0)
|
||||||
.typeError('Flock wajib diisi!')
|
.typeError('Project Flock Kandang wajib diisi!')
|
||||||
.test(
|
.test(
|
||||||
'is-valid-flock',
|
'is-valid-project-flock-kandang',
|
||||||
'Flock wajib diisi!',
|
'Project Flock Kandang wajib diisi!',
|
||||||
(value) => value !== undefined && value !== null && value > 0
|
(value) => value !== undefined && value !== null && value > 0
|
||||||
)
|
)
|
||||||
.required('Flock wajib diisi!'),
|
.required('Project Flock Kandang wajib diisi!')
|
||||||
location: Yup.object({
|
|
||||||
value: Yup.number().min(1).required(),
|
|
||||||
label: Yup.string().required(),
|
|
||||||
}).nullable(),
|
|
||||||
location_id: Yup.number()
|
|
||||||
.default(0)
|
|
||||||
.typeError('Lokasi wajib diisi!')
|
|
||||||
.test(
|
.test(
|
||||||
'is-valid-location',
|
'not-already-recorded',
|
||||||
'Lokasi wajib diisi!',
|
'Project Flock ini sudah direcord hari ini!',
|
||||||
(value) => value !== undefined && value !== null && value > 0
|
|
||||||
)
|
|
||||||
.required('Lokasi wajib diisi!'),
|
|
||||||
coop: Yup.object({
|
|
||||||
value: Yup.number().min(1).required(),
|
|
||||||
label: Yup.string().required(),
|
|
||||||
}).nullable(),
|
|
||||||
coop_id: Yup.number()
|
|
||||||
.default(0)
|
|
||||||
.typeError('Kandang wajib diisi!')
|
|
||||||
.test(
|
|
||||||
'is-valid-coop',
|
|
||||||
'Kandang wajib diisi!',
|
|
||||||
(value) => value !== undefined && value !== null && value > 0
|
|
||||||
)
|
|
||||||
.required('Kandang wajib diisi!'),
|
|
||||||
recording_date: Yup.date()
|
|
||||||
.required('Tanggal recording wajib diisi')
|
|
||||||
.typeError('Format tanggal tidak valid'),
|
|
||||||
feed_data: Yup.array()
|
|
||||||
.of(
|
|
||||||
Yup.object({
|
|
||||||
feed_id: Yup.string().required('Nama pakan wajib diisi!'),
|
|
||||||
feed_qty: Yup.mixed<number | ''>().notRequired(),
|
|
||||||
feed_stock: Yup.number()
|
|
||||||
.required('Jumlah pakan yang digunakan wajib diisi!')
|
|
||||||
.min(1, 'Jumlah pakan minimal 1!')
|
|
||||||
.typeError('Jumlah pakan yang digunakan harus berupa angka!')
|
|
||||||
.test(
|
|
||||||
'is-not-exceed-qty',
|
|
||||||
'Jumlah pakan yang digunakan tidak boleh melebihi stok tersedia!',
|
|
||||||
function(value) {
|
function(value) {
|
||||||
const { feed_qty } = this.parent;
|
const recordedProjectFlockIds = this.options.context?.recordedProjectFlockIds as Set<number>;
|
||||||
if (value === undefined) return true;
|
const formType = this.options.context?.type as 'add' | 'edit' | 'detail';
|
||||||
if (
|
if (formType !== 'add') return true;
|
||||||
feed_qty === undefined ||
|
if (value && recordedProjectFlockIds?.has(value)) {
|
||||||
feed_qty === '' ||
|
return false;
|
||||||
typeof feed_qty !== 'number'
|
}
|
||||||
)
|
|
||||||
return true;
|
return true;
|
||||||
return value <= feed_qty;
|
|
||||||
}
|
}
|
||||||
),
|
),
|
||||||
})
|
body_weights: Yup.array()
|
||||||
)
|
|
||||||
.min(1, 'Minimal harus ada 1 data pakan!')
|
|
||||||
.required('Data pakan wajib diisi!'),
|
|
||||||
body_weight: Yup.array()
|
|
||||||
.of(
|
.of(
|
||||||
Yup.object({
|
Yup.object({
|
||||||
chicken_weight: Yup.number()
|
weight: Yup.number()
|
||||||
.required('Berat ayam wajib diisi!')
|
.required('Berat ayam wajib diisi!')
|
||||||
.min(1, 'Berat ayam minimal 1 gram!')
|
.min(1, 'Berat ayam minimal 1 gram!')
|
||||||
.typeError('Berat ayam harus berupa angka!'),
|
.typeError('Berat ayam harus berupa angka!'),
|
||||||
chicken_count: Yup.number()
|
qty: Yup.number()
|
||||||
.required('Jumlah ayam wajib diisi!')
|
.required('Jumlah ayam wajib diisi!')
|
||||||
.min(1, 'Jumlah ayam minimal 1 ekor!')
|
.min(1, 'Jumlah ayam minimal 1 ekor!')
|
||||||
.typeError('Jumlah ayam harus berupa angka!'),
|
.typeError('Jumlah ayam harus berupa angka!')
|
||||||
average_chicken_weight: Yup.number()
|
.default(1),
|
||||||
.required('Rata-rata berat ayam wajib diisi!')
|
average_weight: Yup.number()
|
||||||
.min(1, 'Rata-rata berat ayam minimal 1 gram!')
|
.optional()
|
||||||
.typeError('Rata-rata berat ayam harus berupa angka!'),
|
.min(0, 'Rata-rata berat tidak boleh negatif!')
|
||||||
|
.typeError('Rata-rata berat harus berupa angka!')
|
||||||
|
.default(0),
|
||||||
})
|
})
|
||||||
)
|
)
|
||||||
.min(1, 'Minimal harus ada 1 data bobot badan!')
|
.min(1, 'Minimal harus ada 1 data bobot badan!')
|
||||||
.required('Data bobot badan wajib diisi!'),
|
.required('Data bobot badan wajib diisi!'),
|
||||||
vaccination: Yup.array()
|
stocks: Yup.array()
|
||||||
.of(
|
.of(
|
||||||
Yup.object({
|
Yup.object({
|
||||||
vaccine_id: Yup.string().required('Nama vaksin wajib diisi!'),
|
product_warehouse_id: Yup.number()
|
||||||
total_stock: Yup.mixed<number | ''>().notRequired(),
|
.required('Produk wajib diisi!')
|
||||||
used_stock: Yup.number()
|
.min(1, 'Produk wajib diisi!')
|
||||||
.required('Jumlah vaksin yang digunakan wajib diisi!')
|
.typeError('Produk harus berupa angka!'),
|
||||||
.min(1, 'Jumlah vaksin minimal 1!')
|
usage_amount: Yup.number()
|
||||||
.typeError('Jumlah vaksin yang digunakan harus berupa angka!')
|
.required('Jumlah penggunaan wajib diisi!')
|
||||||
.test(
|
.min(0, 'Jumlah penggunaan tidak boleh negatif!')
|
||||||
'is-not-exceed-total',
|
.typeError('Jumlah penggunaan harus berupa angka!'),
|
||||||
'Jumlah vaksin yang digunakan tidak boleh melebihi stok tersedia!',
|
notes: Yup.string().optional(),
|
||||||
function (value) {
|
|
||||||
const { total_stock } = this.parent;
|
|
||||||
if (value === undefined) return true;
|
|
||||||
if (
|
|
||||||
total_stock === undefined ||
|
|
||||||
total_stock === '' ||
|
|
||||||
typeof total_stock !== 'number'
|
|
||||||
)
|
|
||||||
return true;
|
|
||||||
return value <= total_stock;
|
|
||||||
}
|
|
||||||
),
|
|
||||||
})
|
})
|
||||||
)
|
)
|
||||||
.min(1, 'Minimal harus ada 1 data vaksinasi!')
|
.min(1, 'Minimal harus ada 1 data stok!')
|
||||||
.required('Data vaksinasi wajib diisi!'),
|
.required('Data stok wajib diisi!'),
|
||||||
mortality: Yup.array()
|
depletions: Yup.array()
|
||||||
.of(
|
.of(
|
||||||
Yup.object({
|
Yup.object({
|
||||||
condition: Yup.mixed<string>()
|
total: Yup.number()
|
||||||
|
.required('Jumlah depletions wajib diisi!')
|
||||||
|
.min(1, 'Jumlah depletions minimal 1!')
|
||||||
|
.typeError('Jumlah depletions harus berupa angka!'),
|
||||||
|
notes: Yup.string()
|
||||||
|
.required('Kondisi depletions wajib diisi!')
|
||||||
.oneOf(
|
.oneOf(
|
||||||
RECORDING_FLAG_OPTIONS.map((opt) => opt.value),
|
RECORDING_FLAG_OPTIONS.map((option) => option.value),
|
||||||
'Kondisi tidak valid!'
|
'Kondisi depletions tidak valid!'
|
||||||
)
|
)
|
||||||
.required('Kondisi wajib diisi!'),
|
.typeError('Kondisi depletions harus berupa teks!')
|
||||||
count: Yup.number()
|
.min(1, 'Kondisi depletions wajib diisi!'),
|
||||||
.required('Jumlah mortalitas wajib diisi!')
|
|
||||||
.min(1, 'Jumlah mortalitas minimal 1 ekor!')
|
|
||||||
.typeError('Jumlah mortalitas harus berupa angka!'),
|
|
||||||
})
|
})
|
||||||
)
|
)
|
||||||
.min(1, 'Minimal harus ada 1 data mortalitas!')
|
.min(1, 'Minimal harus ada 1 data depletions!')
|
||||||
.required('Data mortalitas wajib diisi!'),
|
.required('Data depletions wajib diisi!'),
|
||||||
});
|
});
|
||||||
|
|
||||||
export const UpdateRecordingFormSchema = RecordingFormSchema;
|
export const UpdateRecordingFormSchema = Yup.object({
|
||||||
|
project_flock_kandang: Yup.object({
|
||||||
|
value: Yup.number().min(1).required(),
|
||||||
|
label: Yup.string().required(),
|
||||||
|
}).nullable(),
|
||||||
|
project_flock_kandang_id: Yup.number()
|
||||||
|
.default(0)
|
||||||
|
.typeError('Project Flock Kandang wajib diisi!')
|
||||||
|
.test(
|
||||||
|
'is-valid-project-flock-kandang',
|
||||||
|
'Project Flock Kandang wajib diisi!',
|
||||||
|
(value) => value !== undefined && value !== null && value > 0
|
||||||
|
)
|
||||||
|
.required('Project Flock Kandang wajib diisi!'),
|
||||||
|
body_weights: Yup.array()
|
||||||
|
.of(
|
||||||
|
Yup.object({
|
||||||
|
weight: Yup.number()
|
||||||
|
.required('Berat ayam wajib diisi!')
|
||||||
|
.min(1, 'Berat ayam minimal 1 gram!')
|
||||||
|
.typeError('Berat ayam harus berupa angka!'),
|
||||||
|
qty: Yup.number()
|
||||||
|
.required('Jumlah ayam wajib diisi!')
|
||||||
|
.min(1, 'Jumlah ayam minimal 1 ekor!')
|
||||||
|
.typeError('Jumlah ayam harus berupa angka!')
|
||||||
|
.default(1),
|
||||||
|
average_weight: Yup.number()
|
||||||
|
.optional()
|
||||||
|
.min(0, 'Rata-rata berat tidak boleh negatif!')
|
||||||
|
.typeError('Rata-rata berat harus berupa angka!')
|
||||||
|
.default(0),
|
||||||
|
})
|
||||||
|
)
|
||||||
|
.min(1, 'Minimal harus ada 1 data bobot badan!')
|
||||||
|
.required('Data bobot badan wajib diisi!'),
|
||||||
|
stocks: Yup.array()
|
||||||
|
.of(
|
||||||
|
Yup.object({
|
||||||
|
product_warehouse_id: Yup.number()
|
||||||
|
.required('Produk wajib diisi!')
|
||||||
|
.min(1, 'Produk wajib diisi!')
|
||||||
|
.typeError('Produk harus berupa angka!'),
|
||||||
|
usage_amount: Yup.number()
|
||||||
|
.required('Jumlah penggunaan wajib diisi!')
|
||||||
|
.min(0, 'Jumlah penggunaan tidak boleh negatif!')
|
||||||
|
.typeError('Jumlah penggunaan harus berupa angka!'),
|
||||||
|
notes: Yup.string().optional(),
|
||||||
|
})
|
||||||
|
)
|
||||||
|
.min(1, 'Minimal harus ada 1 data stok!')
|
||||||
|
.required('Data stok wajib diisi!'),
|
||||||
|
depletions: Yup.array()
|
||||||
|
.of(
|
||||||
|
Yup.object({
|
||||||
|
total: Yup.number()
|
||||||
|
.required('Jumlah depletions wajib diisi!')
|
||||||
|
.min(1, 'Jumlah depletions minimal 1!')
|
||||||
|
.typeError('Jumlah depletions harus berupa angka!'),
|
||||||
|
notes: Yup.string()
|
||||||
|
.required('Kondisi depletions wajib diisi!')
|
||||||
|
.oneOf(
|
||||||
|
RECORDING_FLAG_OPTIONS.map((option) => option.value),
|
||||||
|
'Kondisi depletions tidak valid!'
|
||||||
|
)
|
||||||
|
.typeError('Kondisi depletions harus berupa teks!')
|
||||||
|
.min(1, 'Kondisi depletions wajib diisi!'),
|
||||||
|
})
|
||||||
|
)
|
||||||
|
.min(1, 'Minimal harus ada 1 data depletions!')
|
||||||
|
.required('Data depletions wajib diisi!'),
|
||||||
|
});
|
||||||
|
|
||||||
export type RecordingFormValues = Yup.InferType<typeof RecordingFormSchema>;
|
export type RecordingFormValues = Yup.InferType<typeof RecordingFormSchema>;
|
||||||
|
|
||||||
|
type RecordingFormData = Partial<Recording> & {
|
||||||
|
body_weights?: CreateRecordingPayload['body_weights'];
|
||||||
|
stocks?: CreateRecordingPayload['stocks'];
|
||||||
|
depletions?: CreateRecordingPayload['depletions'];
|
||||||
|
};
|
||||||
|
|
||||||
export const getRecordingFormInitialValues = (
|
export const getRecordingFormInitialValues = (
|
||||||
initialValues?: Recording
|
initialValues?: RecordingFormData
|
||||||
): RecordingFormValues => ({
|
): RecordingFormValues => ({
|
||||||
flock: initialValues?.flock
|
project_flock_kandang: initialValues?.project_flock_kandang_id
|
||||||
? {
|
? {
|
||||||
value: initialValues.flock.id,
|
value: initialValues.project_flock_kandang_id,
|
||||||
label: initialValues.flock.name,
|
label: `Project Flock #${initialValues.project_flock_kandang_id}`,
|
||||||
}
|
}
|
||||||
: null,
|
: null,
|
||||||
flock_id: initialValues?.flock?.id ?? 0,
|
project_flock_kandang_id: initialValues?.project_flock_kandang_id ?? 0,
|
||||||
location: initialValues?.location
|
body_weights: initialValues?.body_weights?.map(
|
||||||
? {
|
(bw: NonNullable<CreateRecordingPayload['body_weights']>[0]) => ({
|
||||||
value: initialValues.location.id,
|
weight: bw.weight,
|
||||||
label: initialValues.location.name,
|
qty: bw.qty,
|
||||||
}
|
average_weight: bw.qty > 0 ? Math.round(bw.weight / bw.qty) : 0,
|
||||||
: null,
|
})
|
||||||
location_id: initialValues?.location?.id ?? 0,
|
) ?? [
|
||||||
coop: initialValues?.coop
|
|
||||||
? {
|
|
||||||
value: initialValues.coop.id,
|
|
||||||
label: initialValues.coop.name,
|
|
||||||
}
|
|
||||||
: null,
|
|
||||||
coop_id: initialValues?.coop?.id ?? 0,
|
|
||||||
recording_date: initialValues?.recording_date
|
|
||||||
? new Date(initialValues.recording_date)
|
|
||||||
: new Date(),
|
|
||||||
feed_data: initialValues?.feed_data
|
|
||||||
? initialValues.feed_data.map((feed) => ({
|
|
||||||
feed_id: feed.feed_name,
|
|
||||||
feed_qty: feed.feed_qty,
|
|
||||||
feed_stock: feed.feed_stock,
|
|
||||||
}))
|
|
||||||
: [
|
|
||||||
{
|
{
|
||||||
feed_id: '',
|
weight: 0,
|
||||||
feed_qty: '',
|
qty: 0,
|
||||||
feed_stock: 0,
|
average_weight: 0,
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
body_weight: initialValues?.body_weight ?? [
|
stocks: initialValues?.stocks?.map(
|
||||||
|
(stock: NonNullable<CreateRecordingPayload['stocks']>[0]) => ({
|
||||||
|
product_warehouse_id: stock.product_warehouse_id,
|
||||||
|
usage_amount: stock.usage_amount,
|
||||||
|
notes: stock.notes,
|
||||||
|
})
|
||||||
|
) ?? [
|
||||||
{
|
{
|
||||||
chicken_weight: 0,
|
product_warehouse_id: 0,
|
||||||
chicken_count: 0,
|
usage_amount: 0,
|
||||||
average_chicken_weight: 0,
|
notes: '',
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
vaccination: initialValues?.vaccination
|
depletions: initialValues?.depletions?.map(
|
||||||
? initialValues.vaccination.map((vaccine) => ({
|
(depletion: NonNullable<CreateRecordingPayload['depletions']>[0]) => ({
|
||||||
vaccine_id: vaccine.vaccine_name,
|
product_warehouse_id: depletion.product_warehouse_id,
|
||||||
total_stock: vaccine.total_stock,
|
total: depletion.total,
|
||||||
used_stock: vaccine.used_stock,
|
notes: depletion.notes,
|
||||||
}))
|
})
|
||||||
: [
|
) ?? [
|
||||||
{
|
{
|
||||||
vaccine_id: '',
|
product_warehouse_id: 0,
|
||||||
total_stock: '',
|
total: 0,
|
||||||
used_stock: 0,
|
notes: '',
|
||||||
},
|
|
||||||
],
|
|
||||||
mortality: initialValues?.mortality ?? [
|
|
||||||
{
|
|
||||||
condition: '',
|
|
||||||
count: 0,
|
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
});
|
});
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -24,7 +24,7 @@ export const useRecordingFormHandlers = (initialValuesId?: number) => {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
toast.success(res?.message as string);
|
toast.success(res?.message as string);
|
||||||
router.push('/flock/recording');
|
router.push('/production/recording');
|
||||||
},
|
},
|
||||||
[router]
|
[router]
|
||||||
);
|
);
|
||||||
@@ -38,7 +38,7 @@ export const useRecordingFormHandlers = (initialValuesId?: number) => {
|
|||||||
}
|
}
|
||||||
toast.success(res?.message as string);
|
toast.success(res?.message as string);
|
||||||
router.refresh();
|
router.refresh();
|
||||||
router.push('/flock/recording');
|
router.push('/production/recording');
|
||||||
},
|
},
|
||||||
[router]
|
[router]
|
||||||
);
|
);
|
||||||
@@ -55,7 +55,7 @@ export const useRecordingFormHandlers = (initialValuesId?: number) => {
|
|||||||
deleteModal.closeModal();
|
deleteModal.closeModal();
|
||||||
toast.success('Successfully delete Recording!');
|
toast.success('Successfully delete Recording!');
|
||||||
setIsDeleteLoading(false);
|
setIsDeleteLoading(false);
|
||||||
router.push('/flock/recording');
|
router.push('/production/recording');
|
||||||
}, [deleteModal, initialValuesId, router]);
|
}, [deleteModal, initialValuesId, router]);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
|
|||||||
@@ -0,0 +1,633 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
import { ChangeEventHandler, useState } from 'react';
|
||||||
|
import useSWR from 'swr';
|
||||||
|
import { CellContext, ColumnDef, SortingState } from '@tanstack/react-table';
|
||||||
|
import toast from 'react-hot-toast';
|
||||||
|
|
||||||
|
import { Icon } from '@iconify/react';
|
||||||
|
import Table from '@/components/Table';
|
||||||
|
import DebouncedTextInput from '@/components/input/DebouncedTextInput';
|
||||||
|
import Button from '@/components/Button';
|
||||||
|
import { useModal } from '@/components/Modal';
|
||||||
|
import ConfirmationModal from '@/components/modal/ConfirmationModal';
|
||||||
|
import SelectInput, {
|
||||||
|
OptionType,
|
||||||
|
useSelect,
|
||||||
|
} from '@/components/input/SelectInput';
|
||||||
|
import RowDropdownOptions from '@/components/table/RowDropdownOptions';
|
||||||
|
import RowCollapseOptions from '@/components/table/RowCollapseOptions';
|
||||||
|
import TextInput from '@/components/input/TextInput';
|
||||||
|
import CheckboxInput from '@/components/input/CheckboxInput';
|
||||||
|
|
||||||
|
import { TransferToLaying } from '@/types/api/production/transfer-to-laying';
|
||||||
|
import { TransferToLayingApi } from '@/services/api/production/transfer-to-laying';
|
||||||
|
import { cn, formatDate } from '@/lib/helper';
|
||||||
|
import { isResponseSuccess } from '@/lib/api-helper';
|
||||||
|
import { useTableFilter } from '@/services/hooks/useTableFilter';
|
||||||
|
import { ROWS_OPTIONS } from '@/config/constant';
|
||||||
|
import { Flock } from '@/types/api/master-data/flock';
|
||||||
|
import { FlockApi } from '@/services/api/master-data';
|
||||||
|
|
||||||
|
const RowOptionsMenu = ({
|
||||||
|
type = 'dropdown',
|
||||||
|
props,
|
||||||
|
approveClickHandler,
|
||||||
|
rejectClickHandler,
|
||||||
|
deleteClickHandler,
|
||||||
|
}: {
|
||||||
|
type: 'dropdown' | 'collapse';
|
||||||
|
props: CellContext<TransferToLaying, unknown>;
|
||||||
|
approveClickHandler: () => void;
|
||||||
|
rejectClickHandler: () => void;
|
||||||
|
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={`/production/transfer-to-laying/detail/?transferToLayingId=${props.row.original.id}`}
|
||||||
|
variant='ghost'
|
||||||
|
color='primary'
|
||||||
|
className='justify-start text-sm'
|
||||||
|
>
|
||||||
|
<Icon icon='mdi:eye-outline' width={16} height={16} />
|
||||||
|
Detail
|
||||||
|
</Button>
|
||||||
|
|
||||||
|
<Button
|
||||||
|
href={`/production/transfer-to-laying/detail/edit/?transferToLayingId=${props.row.original.id}`}
|
||||||
|
variant='ghost'
|
||||||
|
color='warning'
|
||||||
|
className='justify-start text-sm'
|
||||||
|
>
|
||||||
|
<Icon icon='material-symbols:edit-outline' width={16} height={16} />
|
||||||
|
Edit
|
||||||
|
</Button>
|
||||||
|
|
||||||
|
<Button
|
||||||
|
variant='ghost'
|
||||||
|
color='success'
|
||||||
|
onClick={approveClickHandler}
|
||||||
|
className='justify-start text-sm'
|
||||||
|
>
|
||||||
|
<Icon icon='material-symbols:check' width={24} height={24} />
|
||||||
|
Approve
|
||||||
|
</Button>
|
||||||
|
|
||||||
|
<Button
|
||||||
|
variant='ghost'
|
||||||
|
color='error'
|
||||||
|
onClick={rejectClickHandler}
|
||||||
|
className='justify-start text-sm'
|
||||||
|
>
|
||||||
|
<Icon icon='material-symbols:close' width={24} height={24} />
|
||||||
|
Reject
|
||||||
|
</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 TransferToLayingsTable = () => {
|
||||||
|
const {
|
||||||
|
state: tableFilterState,
|
||||||
|
updateFilter,
|
||||||
|
setPage,
|
||||||
|
setPageSize,
|
||||||
|
toQueryString: getTableFilterQueryString,
|
||||||
|
} = useTableFilter({
|
||||||
|
initial: {
|
||||||
|
search: '',
|
||||||
|
transferDate: '',
|
||||||
|
flockSource: '',
|
||||||
|
flockDestination: '',
|
||||||
|
},
|
||||||
|
paramMap: {
|
||||||
|
page: 'page',
|
||||||
|
pageSize: 'limit',
|
||||||
|
transferDate: 'transfer_date',
|
||||||
|
flockSource: 'flock_source',
|
||||||
|
flockDestination: 'flock_destination',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const {
|
||||||
|
data: transferToLayings,
|
||||||
|
isLoading,
|
||||||
|
mutate: refreshTransferToLayings,
|
||||||
|
} = useSWR(
|
||||||
|
`${TransferToLayingApi.basePath}${getTableFilterQueryString()}`,
|
||||||
|
TransferToLayingApi.getAllFetcher
|
||||||
|
);
|
||||||
|
|
||||||
|
// Modal hooks
|
||||||
|
const deleteModal = useModal();
|
||||||
|
const approveModal = useModal();
|
||||||
|
const rejectModal = useModal();
|
||||||
|
|
||||||
|
// Flocks data
|
||||||
|
const {
|
||||||
|
setInputValue: setFlockSourceInputValue,
|
||||||
|
options: flockSourceOptions,
|
||||||
|
isLoadingOptions: isLoadingFlockSourceOptions,
|
||||||
|
} = useSelect<Flock>(FlockApi.basePath, 'id', 'name');
|
||||||
|
|
||||||
|
const {
|
||||||
|
setInputValue: setFlockDestinationInputValue,
|
||||||
|
options: flockDestinationOptions,
|
||||||
|
isLoadingOptions: isLoadingFlockDestinationOptions,
|
||||||
|
} = useSelect<Flock>(FlockApi.basePath, 'id', 'name');
|
||||||
|
|
||||||
|
// Flocks value
|
||||||
|
const [selectedFlockSource, setSelectedFlockSource] =
|
||||||
|
useState<OptionType | null>(null);
|
||||||
|
const [selectedFlockDestination, setSelectedFlockDestination] =
|
||||||
|
useState<OptionType | null>(null);
|
||||||
|
|
||||||
|
const [selectedTransferToLaying, setSelectedTransferToLaying] = useState<
|
||||||
|
TransferToLaying | undefined
|
||||||
|
>(undefined);
|
||||||
|
|
||||||
|
// Modal loading state
|
||||||
|
const [isDeleteLoading, setIsDeleteLoading] = useState(false);
|
||||||
|
const [isApproveLoading, setIsApproveLoading] = useState(false);
|
||||||
|
const [isRejectLoading, setIsRejectLoading] = useState(false);
|
||||||
|
|
||||||
|
const [sorting, setSorting] = useState<SortingState>([]);
|
||||||
|
const [rowSelection, setRowSelection] = useState<Record<string, boolean>>({});
|
||||||
|
const selectedRowIds = Object.keys(rowSelection).map((item) =>
|
||||||
|
parseInt(item)
|
||||||
|
);
|
||||||
|
|
||||||
|
const transferToLayingsColumns: ColumnDef<TransferToLaying>[] = [
|
||||||
|
{
|
||||||
|
id: 'select',
|
||||||
|
header: ({ table }) => (
|
||||||
|
<div className='w-full flex flex-row justify-center'>
|
||||||
|
<CheckboxInput
|
||||||
|
name='allRow'
|
||||||
|
checked={table.getIsAllRowsSelected()}
|
||||||
|
indeterminate={table.getIsSomeRowsSelected()}
|
||||||
|
onChange={table.getToggleAllRowsSelectedHandler()}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
),
|
||||||
|
cell: ({ row }) => (
|
||||||
|
<div>
|
||||||
|
<CheckboxInput
|
||||||
|
name='row'
|
||||||
|
checked={row.getIsSelected()}
|
||||||
|
disabled={!row.getCanSelect()}
|
||||||
|
indeterminate={row.getIsSomeSelected()}
|
||||||
|
onChange={row.getToggleSelectedHandler()}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
header: '#',
|
||||||
|
cell: (props) =>
|
||||||
|
tableFilterState.pageSize * (tableFilterState.page - 1) +
|
||||||
|
props.row.index +
|
||||||
|
1,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
accessorKey: 'transfer_date',
|
||||||
|
header: 'Tanggal Transfer',
|
||||||
|
cell: (props) => formatDate(props.getValue() as string, 'DD MMM YYYY'),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
accessorKey: 'flock_source',
|
||||||
|
header: 'Flock Asal',
|
||||||
|
cell: (props) => props.row.original.flock_source.name,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
accessorKey: 'flock_destination',
|
||||||
|
header: 'Flock Tujuan',
|
||||||
|
cell: (props) => props.row.original.flock_destination.name,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
accessorKey: 'quantity',
|
||||||
|
header: 'Kuantitas',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
accessorKey: 'reason',
|
||||||
|
header: 'Alasan Transfer',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
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 approveClickHandler = () => {
|
||||||
|
setSelectedTransferToLaying(props.row.original);
|
||||||
|
|
||||||
|
// Set row selection
|
||||||
|
setRowSelection({
|
||||||
|
[String(props.row.original.id)]: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
approveModal.openModal();
|
||||||
|
};
|
||||||
|
|
||||||
|
const rejectClickHandler = () => {
|
||||||
|
setSelectedTransferToLaying(props.row.original);
|
||||||
|
|
||||||
|
// Set row selection
|
||||||
|
setRowSelection({
|
||||||
|
[String(props.row.original.id)]: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
rejectModal.openModal();
|
||||||
|
};
|
||||||
|
|
||||||
|
const deleteClickHandler = () => {
|
||||||
|
setSelectedTransferToLaying(props.row.original);
|
||||||
|
deleteModal.openModal();
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
{currentPageSize > 2 && (
|
||||||
|
<RowDropdownOptions isLast2Rows={isLast2Rows}>
|
||||||
|
<RowOptionsMenu
|
||||||
|
type='dropdown'
|
||||||
|
props={props}
|
||||||
|
approveClickHandler={approveClickHandler}
|
||||||
|
rejectClickHandler={rejectClickHandler}
|
||||||
|
deleteClickHandler={deleteClickHandler}
|
||||||
|
/>
|
||||||
|
</RowDropdownOptions>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{currentPageSize <= 2 && (
|
||||||
|
<RowCollapseOptions>
|
||||||
|
<RowOptionsMenu
|
||||||
|
type='dropdown'
|
||||||
|
props={props}
|
||||||
|
approveClickHandler={approveClickHandler}
|
||||||
|
rejectClickHandler={rejectClickHandler}
|
||||||
|
deleteClickHandler={deleteClickHandler}
|
||||||
|
/>
|
||||||
|
</RowCollapseOptions>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
},
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
const bulkApproveClickHandler = () => {
|
||||||
|
approveModal.openModal();
|
||||||
|
};
|
||||||
|
|
||||||
|
const bulkRejectClickHandler = () => {
|
||||||
|
rejectModal.openModal();
|
||||||
|
};
|
||||||
|
|
||||||
|
// Modal confirm click handler
|
||||||
|
const confirmationModalDeleteClickHandler = async () => {
|
||||||
|
setIsDeleteLoading(true);
|
||||||
|
|
||||||
|
await TransferToLayingApi.delete(selectedTransferToLaying?.id as number);
|
||||||
|
refreshTransferToLayings();
|
||||||
|
|
||||||
|
deleteModal.closeModal();
|
||||||
|
toast.success('Berhasil menghapus data transfer ke laying!');
|
||||||
|
setIsDeleteLoading(false);
|
||||||
|
};
|
||||||
|
|
||||||
|
const confirmationModalApproveClickHandler = async () => {
|
||||||
|
setIsApproveLoading(true);
|
||||||
|
|
||||||
|
const bulkApproveResponse = await TransferToLayingApi.bulkApprove(
|
||||||
|
selectedRowIds
|
||||||
|
);
|
||||||
|
|
||||||
|
if (isResponseSuccess(bulkApproveResponse)) {
|
||||||
|
refreshTransferToLayings();
|
||||||
|
approveModal.closeModal();
|
||||||
|
|
||||||
|
// TODO: remove console.log
|
||||||
|
console.log('Approved data:', selectedRowIds);
|
||||||
|
|
||||||
|
toast.success(
|
||||||
|
`Berhasil approve ${selectedRowIds.length} data transfer ke laying!`
|
||||||
|
);
|
||||||
|
|
||||||
|
setRowSelection({});
|
||||||
|
} else {
|
||||||
|
approveModal.closeModal();
|
||||||
|
|
||||||
|
toast.error(
|
||||||
|
`Gagal approve ${selectedRowIds.length} data transfer ke laying!`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
setIsApproveLoading(false);
|
||||||
|
};
|
||||||
|
|
||||||
|
const confirmationModalRejectClickHandler = async () => {
|
||||||
|
setIsRejectLoading(true);
|
||||||
|
|
||||||
|
const bulkRejectResponse = await TransferToLayingApi.bulkReject(
|
||||||
|
selectedRowIds
|
||||||
|
);
|
||||||
|
|
||||||
|
if (isResponseSuccess(bulkRejectResponse)) {
|
||||||
|
refreshTransferToLayings();
|
||||||
|
rejectModal.closeModal();
|
||||||
|
|
||||||
|
// TODO: remove console.log
|
||||||
|
console.log('Rejected data:', selectedRowIds);
|
||||||
|
|
||||||
|
toast.success(
|
||||||
|
`Berhasil reject ${selectedRowIds.length} data transfer ke laying!`
|
||||||
|
);
|
||||||
|
setRowSelection({});
|
||||||
|
} else {
|
||||||
|
rejectModal.closeModal();
|
||||||
|
|
||||||
|
toast.error(
|
||||||
|
`Gagal reject ${selectedRowIds.length} data transfer ke laying!`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
setIsRejectLoading(false);
|
||||||
|
};
|
||||||
|
|
||||||
|
const searchChangeHandler: ChangeEventHandler<HTMLInputElement> = (e) => {
|
||||||
|
updateFilter('search', e.target.value);
|
||||||
|
};
|
||||||
|
|
||||||
|
const pageSizeChangeHandler = (val: OptionType | OptionType[] | null) => {
|
||||||
|
const newVal = val as OptionType;
|
||||||
|
|
||||||
|
setPageSize(newVal.value as number);
|
||||||
|
};
|
||||||
|
|
||||||
|
const transferDateChangeHandler: ChangeEventHandler<HTMLInputElement> = (
|
||||||
|
e
|
||||||
|
) => {
|
||||||
|
updateFilter('transferDate', e.target.value);
|
||||||
|
};
|
||||||
|
|
||||||
|
const flockSourceChangeHandler = (val: OptionType | OptionType[] | null) => {
|
||||||
|
setSelectedFlockSource(val as OptionType);
|
||||||
|
updateFilter(
|
||||||
|
'flockSource',
|
||||||
|
val ? ((val as OptionType).value as string) : ''
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
const flockDestinationChangeHandler = (
|
||||||
|
val: OptionType | OptionType[] | null
|
||||||
|
) => {
|
||||||
|
setSelectedFlockDestination(val as OptionType);
|
||||||
|
updateFilter(
|
||||||
|
'flockDestination',
|
||||||
|
val ? ((val as OptionType).value as string) : ''
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
// track sorting
|
||||||
|
// useEffect(() => {
|
||||||
|
// const isNameSorted = sorting.find((sortItem) => sortItem.id === 'name');
|
||||||
|
|
||||||
|
// if (!isNameSorted) {
|
||||||
|
// updateFilter('nameSort', '');
|
||||||
|
// } else {
|
||||||
|
// updateFilter('nameSort', isNameSorted.desc ? 'desc' : 'asc');
|
||||||
|
// }
|
||||||
|
// }, [sorting, updateFilter]);
|
||||||
|
|
||||||
|
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 xl:flex-row justify-between items-end xl:items-center gap-2'>
|
||||||
|
<div className='w-full sm:w-fit flex flex-col sm:flex-row self-start gap-2'>
|
||||||
|
<Button
|
||||||
|
href='/production/transfer-to-laying/add'
|
||||||
|
color='primary'
|
||||||
|
className='w-full sm:w-fit'
|
||||||
|
>
|
||||||
|
<Icon icon='ic:round-plus' width={24} height={24} />
|
||||||
|
Tambah Transfer ke Laying
|
||||||
|
</Button>
|
||||||
|
|
||||||
|
{selectedRowIds.length > 0 && (
|
||||||
|
<>
|
||||||
|
<Button
|
||||||
|
variant='outline'
|
||||||
|
color='success'
|
||||||
|
onClick={bulkApproveClickHandler}
|
||||||
|
disabled={selectedRowIds.length === 0}
|
||||||
|
className='w-full sm:w-fit'
|
||||||
|
>
|
||||||
|
<Icon
|
||||||
|
icon='material-symbols:check'
|
||||||
|
width={24}
|
||||||
|
height={24}
|
||||||
|
/>
|
||||||
|
Approve
|
||||||
|
</Button>
|
||||||
|
|
||||||
|
<Button
|
||||||
|
variant='outline'
|
||||||
|
color='error'
|
||||||
|
onClick={bulkRejectClickHandler}
|
||||||
|
disabled={selectedRowIds.length === 0}
|
||||||
|
className='w-full sm:w-fit'
|
||||||
|
>
|
||||||
|
<Icon
|
||||||
|
icon='material-symbols:close'
|
||||||
|
width={24}
|
||||||
|
height={24}
|
||||||
|
/>
|
||||||
|
Reject
|
||||||
|
</Button>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<DebouncedTextInput
|
||||||
|
name='search'
|
||||||
|
placeholder='Cari TransferToLaying'
|
||||||
|
value={tableFilterState.search}
|
||||||
|
onChange={searchChangeHandler}
|
||||||
|
className={{ wrapper: 'sm:max-w-3xs' }}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className='grid grid-cols-12 justify-end gap-4'>
|
||||||
|
<TextInput
|
||||||
|
required
|
||||||
|
type='date'
|
||||||
|
label='Tanggal Transfer'
|
||||||
|
name='transfer_date'
|
||||||
|
placeholder='Masukkan tanggal transfer'
|
||||||
|
value={tableFilterState.transferDate}
|
||||||
|
onChange={transferDateChangeHandler}
|
||||||
|
className={{ wrapper: 'col-span-12 sm:col-span-3' }}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<SelectInput
|
||||||
|
label='Flock Asal'
|
||||||
|
options={flockSourceOptions}
|
||||||
|
isLoading={isLoadingFlockSourceOptions}
|
||||||
|
value={selectedFlockSource}
|
||||||
|
onChange={flockSourceChangeHandler}
|
||||||
|
onInputChange={setFlockSourceInputValue}
|
||||||
|
isClearable
|
||||||
|
className={{
|
||||||
|
wrapper: 'col-span-12 sm:col-span-3',
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<SelectInput
|
||||||
|
label='Flock Tujuan'
|
||||||
|
options={flockDestinationOptions}
|
||||||
|
isLoading={isLoadingFlockDestinationOptions}
|
||||||
|
value={selectedFlockDestination}
|
||||||
|
onChange={flockDestinationChangeHandler}
|
||||||
|
onInputChange={setFlockDestinationInputValue}
|
||||||
|
isClearable
|
||||||
|
className={{
|
||||||
|
wrapper: 'col-span-12 sm:col-span-3',
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<SelectInput
|
||||||
|
label='Baris'
|
||||||
|
options={ROWS_OPTIONS}
|
||||||
|
value={{
|
||||||
|
label: String(tableFilterState.pageSize),
|
||||||
|
value: tableFilterState.pageSize,
|
||||||
|
}}
|
||||||
|
onChange={pageSizeChangeHandler}
|
||||||
|
className={{
|
||||||
|
wrapper:
|
||||||
|
'col-span-6 sm:col-span-3 max-w-28 sm:justify-self-end',
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<Table<TransferToLaying>
|
||||||
|
data={
|
||||||
|
isResponseSuccess(transferToLayings) ? transferToLayings?.data : []
|
||||||
|
}
|
||||||
|
columns={transferToLayingsColumns}
|
||||||
|
pageSize={tableFilterState.pageSize}
|
||||||
|
page={
|
||||||
|
isResponseSuccess(transferToLayings)
|
||||||
|
? transferToLayings?.meta?.page
|
||||||
|
: 0
|
||||||
|
}
|
||||||
|
totalItems={
|
||||||
|
isResponseSuccess(transferToLayings)
|
||||||
|
? transferToLayings?.meta?.total_results
|
||||||
|
: 0
|
||||||
|
}
|
||||||
|
onPageChange={setPage}
|
||||||
|
isLoading={isLoading}
|
||||||
|
sorting={sorting}
|
||||||
|
setSorting={setSorting}
|
||||||
|
rowSelection={rowSelection}
|
||||||
|
setRowSelection={setRowSelection}
|
||||||
|
className={{
|
||||||
|
containerClassName: cn({
|
||||||
|
'mb-20':
|
||||||
|
isResponseSuccess(transferToLayings) &&
|
||||||
|
transferToLayings?.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 transfer ke laying ini?`}
|
||||||
|
secondaryButton={{
|
||||||
|
text: 'Tidak',
|
||||||
|
}}
|
||||||
|
primaryButton={{
|
||||||
|
text: 'Ya',
|
||||||
|
color: 'error',
|
||||||
|
isLoading: isDeleteLoading,
|
||||||
|
onClick: confirmationModalDeleteClickHandler,
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<ConfirmationModal
|
||||||
|
ref={approveModal.ref}
|
||||||
|
type='success'
|
||||||
|
text={`Apakah anda yakin ingin approve data transfer ke laying ini (${selectedRowIds.length} data)?`}
|
||||||
|
secondaryButton={{
|
||||||
|
text: 'Tidak',
|
||||||
|
}}
|
||||||
|
primaryButton={{
|
||||||
|
text: 'Ya',
|
||||||
|
color: 'success',
|
||||||
|
isLoading: isApproveLoading,
|
||||||
|
onClick: confirmationModalApproveClickHandler,
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<ConfirmationModal
|
||||||
|
ref={rejectModal.ref}
|
||||||
|
type='error'
|
||||||
|
text={`Apakah anda yakin ingin reject data transfer ke laying ini (${selectedRowIds.length} data)?`}
|
||||||
|
secondaryButton={{
|
||||||
|
text: 'Tidak',
|
||||||
|
}}
|
||||||
|
primaryButton={{
|
||||||
|
text: 'Ya',
|
||||||
|
color: 'error',
|
||||||
|
isLoading: isRejectLoading,
|
||||||
|
onClick: confirmationModalRejectClickHandler,
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default TransferToLayingsTable;
|
||||||
+83
@@ -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,688 @@
|
|||||||
|
'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();
|
||||||
|
|
||||||
|
// Modal hooks
|
||||||
|
const deleteModal = useModal();
|
||||||
|
const approveModal = useModal();
|
||||||
|
const rejectModal = useModal();
|
||||||
|
|
||||||
|
const [formErrorMessage, setFormErrorMessage] = useState('');
|
||||||
|
|
||||||
|
// Modal loading state
|
||||||
|
const [isDeleteLoading, setIsDeleteLoading] = useState(false);
|
||||||
|
const [isApproveLoading, setIsApproveLoading] = useState(false);
|
||||||
|
const [isRejectLoading, setIsRejectLoading] = 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 approveClickHandler = () => {
|
||||||
|
approveModal.openModal();
|
||||||
|
};
|
||||||
|
|
||||||
|
const rejectClickHandler = () => {
|
||||||
|
rejectModal.openModal();
|
||||||
|
};
|
||||||
|
|
||||||
|
// Modal confirm click handler
|
||||||
|
const confirmationModalDeleteClickHandler = async () => {
|
||||||
|
setIsDeleteLoading(true);
|
||||||
|
|
||||||
|
// TODO: delete data and integrate to real API
|
||||||
|
deleteModal.closeModal();
|
||||||
|
toast.success('Berhasil menghapus data transfer ke laying!');
|
||||||
|
|
||||||
|
setIsDeleteLoading(false);
|
||||||
|
};
|
||||||
|
|
||||||
|
const confirmationModalApproveClickHandler = async () => {
|
||||||
|
setIsApproveLoading(true);
|
||||||
|
|
||||||
|
const approveResponse = await TransferToLayingApi.approve(
|
||||||
|
initialValues?.id as number
|
||||||
|
);
|
||||||
|
|
||||||
|
if (isResponseSuccess(approveResponse)) {
|
||||||
|
approveModal.closeModal();
|
||||||
|
|
||||||
|
toast.success('Berhasil approve data transfer ke laying!');
|
||||||
|
} else {
|
||||||
|
approveModal.closeModal();
|
||||||
|
|
||||||
|
toast.error('Gagal approve data transfer ke laying!');
|
||||||
|
}
|
||||||
|
|
||||||
|
setIsApproveLoading(false);
|
||||||
|
};
|
||||||
|
|
||||||
|
const confirmationModalRejectClickHandler = async () => {
|
||||||
|
setIsRejectLoading(true);
|
||||||
|
|
||||||
|
const rejectResponse = await TransferToLayingApi.reject(
|
||||||
|
initialValues?.id as number
|
||||||
|
);
|
||||||
|
|
||||||
|
if (isResponseSuccess(rejectResponse)) {
|
||||||
|
rejectModal.closeModal();
|
||||||
|
|
||||||
|
toast.success('Berhasil reject data transfer ke laying!');
|
||||||
|
} else {
|
||||||
|
rejectModal.closeModal();
|
||||||
|
|
||||||
|
toast.error('Gagal reject data transfer ke laying!');
|
||||||
|
}
|
||||||
|
|
||||||
|
setIsRejectLoading(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='/production/transfer-to-laying'
|
||||||
|
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>
|
||||||
|
|
||||||
|
<div className='w-full my-4 flex flex-row justify-end gap-2'>
|
||||||
|
{type === 'detail' && (
|
||||||
|
<>
|
||||||
|
<Button
|
||||||
|
variant='outline'
|
||||||
|
color='success'
|
||||||
|
onClick={approveClickHandler}
|
||||||
|
// disabled={selectedRowIds.length === 0}
|
||||||
|
className='w-full sm:w-fit'
|
||||||
|
>
|
||||||
|
<Icon icon='material-symbols:check' width={24} height={24} />
|
||||||
|
Approve
|
||||||
|
</Button>
|
||||||
|
|
||||||
|
<Button
|
||||||
|
variant='outline'
|
||||||
|
color='error'
|
||||||
|
onClick={rejectClickHandler}
|
||||||
|
// disabled={selectedRowIds.length === 0}
|
||||||
|
className='w-full sm:w-fit'
|
||||||
|
>
|
||||||
|
<Icon icon='material-symbols:close' width={24} height={24} />
|
||||||
|
Reject
|
||||||
|
</Button>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<form
|
||||||
|
onSubmit={formik.handleSubmit}
|
||||||
|
onReset={formik.handleReset}
|
||||||
|
className='w-full 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
|
||||||
|
className={{
|
||||||
|
wrapper: 'min-w-52',
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</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'}
|
||||||
|
className={{
|
||||||
|
wrapper: 'min-w-52',
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</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={`/production/transfer-to-laying/detail/edit/?transferToLayingId=${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 transfer ke laying ini?'
|
||||||
|
secondaryButton={{
|
||||||
|
text: 'Tidak',
|
||||||
|
}}
|
||||||
|
primaryButton={{
|
||||||
|
text: 'Ya',
|
||||||
|
color: 'error',
|
||||||
|
isLoading: isDeleteLoading,
|
||||||
|
onClick: confirmationModalDeleteClickHandler,
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{type === 'detail' && (
|
||||||
|
<>
|
||||||
|
<ConfirmationModal
|
||||||
|
ref={approveModal.ref}
|
||||||
|
type='success'
|
||||||
|
text='Apakah anda yakin ingin approve data transfer ke laying ini?'
|
||||||
|
secondaryButton={{
|
||||||
|
text: 'Tidak',
|
||||||
|
}}
|
||||||
|
primaryButton={{
|
||||||
|
text: 'Ya',
|
||||||
|
color: 'success',
|
||||||
|
isLoading: isApproveLoading,
|
||||||
|
onClick: confirmationModalApproveClickHandler,
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<ConfirmationModal
|
||||||
|
ref={rejectModal.ref}
|
||||||
|
type='error'
|
||||||
|
text='Apakah anda yakin ingin reject data transfer ke laying ini?'
|
||||||
|
secondaryButton={{
|
||||||
|
text: 'Tidak',
|
||||||
|
}}
|
||||||
|
primaryButton={{
|
||||||
|
text: 'Ya',
|
||||||
|
color: 'error',
|
||||||
|
isLoading: isRejectLoading,
|
||||||
|
onClick: confirmationModalRejectClickHandler,
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default TransferToLayingForm;
|
||||||
+14
-9
@@ -13,7 +13,7 @@ export const MAIN_DRAWER_LINKS: MAIN_DRAWER_MENU[] = [
|
|||||||
},
|
},
|
||||||
|
|
||||||
{
|
{
|
||||||
title: 'Production',
|
title: 'Produksi',
|
||||||
link: '/production',
|
link: '/production',
|
||||||
icon: 'material-symbols:conveyor-belt-outline-rounded',
|
icon: 'material-symbols:conveyor-belt-outline-rounded',
|
||||||
submenu: [
|
submenu: [
|
||||||
@@ -32,6 +32,11 @@ export const MAIN_DRAWER_LINKS: MAIN_DRAWER_MENU[] = [
|
|||||||
link: '/production/recording',
|
link: '/production/recording',
|
||||||
icon: 'mdi:clipboard-text',
|
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',
|
link: '/inventory',
|
||||||
icon: 'mdi:warehouse',
|
icon: 'mdi:warehouse',
|
||||||
submenu: [
|
submenu: [
|
||||||
{
|
// {
|
||||||
title: 'Product',
|
// title: 'Product',
|
||||||
link: '/inventory/product',
|
// link: '/inventory/product',
|
||||||
icon: 'mdi:package-variant-closed',
|
// icon: 'mdi:package-variant-closed',
|
||||||
},
|
// },
|
||||||
{
|
{
|
||||||
title: 'Penyesuaian Stok',
|
title: 'Penyesuaian Stok',
|
||||||
link: '/inventory/adjustment',
|
link: '/inventory/adjustment',
|
||||||
@@ -216,7 +221,7 @@ export const SUPPLIER_FLAG_OPTIONS = [
|
|||||||
];
|
];
|
||||||
|
|
||||||
export const RECORDING_FLAG_OPTIONS = [
|
export const RECORDING_FLAG_OPTIONS = [
|
||||||
{ label: 'Ayam Afkir', value: 'Ayam Afkir' },
|
{ label: 'Ayam Afkir', value: 'Afkir' },
|
||||||
{ label: 'Ayam Culling', value: 'Ayam Culling' },
|
{ label: 'Ayam Culling', value: 'Culling' },
|
||||||
{ label: 'Ayam Mati', value: 'Ayam Mati' },
|
{ label: 'Ayam Mati', value: 'Mati' },
|
||||||
];
|
];
|
||||||
|
|||||||
@@ -1,7 +1,11 @@
|
|||||||
import moment from 'moment';
|
import moment from 'moment';
|
||||||
|
import 'moment/locale/id';
|
||||||
import { twMerge } from 'tailwind-merge';
|
import { twMerge } from 'tailwind-merge';
|
||||||
import clsx, { ClassValue } from 'clsx';
|
import clsx, { ClassValue } from 'clsx';
|
||||||
|
|
||||||
|
// set locale globally
|
||||||
|
moment.locale('id');
|
||||||
|
|
||||||
export const sleep = (ms: number = 1000) =>
|
export const sleep = (ms: number = 1000) =>
|
||||||
new Promise((resolve) => setTimeout(resolve, ms));
|
new Promise((resolve) => setTimeout(resolve, ms));
|
||||||
|
|
||||||
@@ -13,6 +17,19 @@ export const cn = (...inputs: ClassValue[]) => {
|
|||||||
return twMerge(clsx(inputs));
|
return twMerge(clsx(inputs));
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export const formatNumber = (
|
||||||
|
value: number | bigint | Intl.StringNumericLiteral,
|
||||||
|
locale = 'en-US',
|
||||||
|
minimumFractionDigits = 0,
|
||||||
|
maximumFractionDigits = 2
|
||||||
|
) => {
|
||||||
|
return new Intl.NumberFormat(locale, {
|
||||||
|
minimumFractionDigits,
|
||||||
|
maximumFractionDigits,
|
||||||
|
}).format(value);
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
export const formatCurrency = (
|
export const formatCurrency = (
|
||||||
value: number | bigint | Intl.StringNumericLiteral,
|
value: number | bigint | Intl.StringNumericLiteral,
|
||||||
currency = 'USD',
|
currency = 'USD',
|
||||||
@@ -27,3 +44,37 @@ export const formatCurrency = (
|
|||||||
maximumFractionDigits,
|
maximumFractionDigits,
|
||||||
}).format(value);
|
}).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
|
||||||
|
): D {
|
||||||
|
if (obj == null) return defaultValue as D;
|
||||||
|
if (!path) return obj as D;
|
||||||
|
|
||||||
|
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 D;
|
||||||
|
}
|
||||||
|
|||||||
@@ -24,7 +24,7 @@ export const RecordingApi = new BaseApiService<
|
|||||||
Recording,
|
Recording,
|
||||||
CreateRecordingPayload,
|
CreateRecordingPayload,
|
||||||
UpdateRecordingPayload
|
UpdateRecordingPayload
|
||||||
>('/flock/recordings');
|
>('/production/recordings');
|
||||||
export const ChickinApi = new BaseApiService<
|
export const ChickinApi = new BaseApiService<
|
||||||
Chickin,
|
Chickin,
|
||||||
CreateChickinPayload,
|
CreateChickinPayload,
|
||||||
|
|||||||
@@ -0,0 +1,876 @@
|
|||||||
|
import { sleep } from '@/lib/helper';
|
||||||
|
import { BaseApiService } from '@/services/api/base';
|
||||||
|
import { BaseApiResponse } from '@/types/api/api-general';
|
||||||
|
|
||||||
|
import {
|
||||||
|
CreateTransferToLayingPayload,
|
||||||
|
TransferToLaying,
|
||||||
|
UpdateTransferToLayingPayload,
|
||||||
|
} from '@/types/api/production/transfer-to-laying';
|
||||||
|
import { FlockWithKandangs } from '@/types/api/master-data/flock';
|
||||||
|
|
||||||
|
// TODO: delete this dummy data
|
||||||
|
const GET_ALL_TRANSFER_TO_LAYING_DUMMY_DATA: BaseApiResponse<
|
||||||
|
TransferToLaying[]
|
||||||
|
> = {
|
||||||
|
code: 200,
|
||||||
|
status: 'success',
|
||||||
|
message: 'Successfully get all transfer to laying data!',
|
||||||
|
meta: {
|
||||||
|
page: 1,
|
||||||
|
limit: 10,
|
||||||
|
total_pages: 1,
|
||||||
|
total_results: 8,
|
||||||
|
},
|
||||||
|
data: [
|
||||||
|
{
|
||||||
|
id: 201,
|
||||||
|
transfer_date: '2025-10-10',
|
||||||
|
flock_source: { id: 1, name: 'Flock A' },
|
||||||
|
flock_destination: { id: 10, name: 'Laying House 1' },
|
||||||
|
quantity: 1200,
|
||||||
|
kandangs: [
|
||||||
|
{
|
||||||
|
kandang: {
|
||||||
|
id: 11,
|
||||||
|
name: 'KDG-11',
|
||||||
|
status: 'ACTIVE',
|
||||||
|
location: {
|
||||||
|
id: 101,
|
||||||
|
name: 'Farm Alpha',
|
||||||
|
address: 'Jl. Raya Alpha No. 1',
|
||||||
|
area: { id: 1001, name: 'Area Utara' },
|
||||||
|
},
|
||||||
|
pic: {
|
||||||
|
id: 501,
|
||||||
|
id_user: 501,
|
||||||
|
email: 'rina@farm.co',
|
||||||
|
name: 'Rina Setiawan',
|
||||||
|
},
|
||||||
|
created_user: {
|
||||||
|
id: 9001,
|
||||||
|
id_user: 9001,
|
||||||
|
email: 'admin@farm.co',
|
||||||
|
name: 'System Admin',
|
||||||
|
},
|
||||||
|
created_at: '2025-09-01T08:00:00Z',
|
||||||
|
updated_at: '2025-10-01T08:00:00Z',
|
||||||
|
},
|
||||||
|
quantity: 600,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
kandang: {
|
||||||
|
id: 12,
|
||||||
|
name: 'KDG-12',
|
||||||
|
status: 'ACTIVE',
|
||||||
|
location: {
|
||||||
|
id: 101,
|
||||||
|
name: 'Farm Alpha',
|
||||||
|
address: 'Jl. Raya Alpha No. 1',
|
||||||
|
area: { id: 1001, name: 'Area Utara' },
|
||||||
|
},
|
||||||
|
pic: {
|
||||||
|
id: 502,
|
||||||
|
id_user: 502,
|
||||||
|
email: 'budi@farm.co',
|
||||||
|
name: 'Budi Hartono',
|
||||||
|
},
|
||||||
|
created_user: {
|
||||||
|
id: 9002,
|
||||||
|
id_user: 9002,
|
||||||
|
email: 'ops@farm.co',
|
||||||
|
name: 'Ops Bot',
|
||||||
|
},
|
||||||
|
created_at: '2025-08-25T08:00:00Z',
|
||||||
|
updated_at: '2025-09-20T08:00:00Z',
|
||||||
|
},
|
||||||
|
quantity: 600,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
reason: 'Start laying cycle',
|
||||||
|
created_user: {
|
||||||
|
id: 9100,
|
||||||
|
id_user: 9100,
|
||||||
|
email: 'planner@farm.co',
|
||||||
|
name: 'Planning',
|
||||||
|
},
|
||||||
|
created_at: '2025-10-10T06:00:00Z',
|
||||||
|
updated_at: '2025-10-10T06:00:00Z',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 202,
|
||||||
|
transfer_date: '2025-10-11',
|
||||||
|
flock_source: { id: 2, name: 'Flock B' },
|
||||||
|
flock_destination: { id: 10, name: 'Laying House 1' },
|
||||||
|
quantity: 950,
|
||||||
|
kandangs: [
|
||||||
|
{
|
||||||
|
kandang: {
|
||||||
|
id: 13,
|
||||||
|
name: 'KDG-13',
|
||||||
|
status: 'ACTIVE',
|
||||||
|
location: {
|
||||||
|
id: 102,
|
||||||
|
name: 'Farm Beta',
|
||||||
|
address: 'Jl. Melati 2',
|
||||||
|
area: { id: 1002, name: 'Area Selatan' },
|
||||||
|
},
|
||||||
|
pic: {
|
||||||
|
id: 503,
|
||||||
|
id_user: 503,
|
||||||
|
email: 'sari@farm.co',
|
||||||
|
name: 'Sari Wulandari',
|
||||||
|
},
|
||||||
|
created_user: {
|
||||||
|
id: 9003,
|
||||||
|
id_user: 9003,
|
||||||
|
email: 'system@farm.co',
|
||||||
|
name: 'System',
|
||||||
|
},
|
||||||
|
created_at: '2025-09-05T08:00:00Z',
|
||||||
|
updated_at: '2025-10-02T08:00:00Z',
|
||||||
|
},
|
||||||
|
quantity: 500,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
kandang: {
|
||||||
|
id: 14,
|
||||||
|
name: 'KDG-14',
|
||||||
|
status: 'MAINTENANCE',
|
||||||
|
location: {
|
||||||
|
id: 102,
|
||||||
|
name: 'Farm Beta',
|
||||||
|
address: 'Jl. Melati 2',
|
||||||
|
area: { id: 1002, name: 'Area Selatan' },
|
||||||
|
},
|
||||||
|
pic: {
|
||||||
|
id: 504,
|
||||||
|
id_user: 504,
|
||||||
|
email: 'agus@farm.co',
|
||||||
|
name: 'Agus Pratama',
|
||||||
|
},
|
||||||
|
created_user: {
|
||||||
|
id: 9003,
|
||||||
|
id_user: 9003,
|
||||||
|
email: 'system@farm.co',
|
||||||
|
name: 'System',
|
||||||
|
},
|
||||||
|
created_at: '2025-07-15T08:00:00Z',
|
||||||
|
updated_at: '2025-09-15T08:00:00Z',
|
||||||
|
},
|
||||||
|
quantity: 450,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
reason: 'Capacity balancing',
|
||||||
|
created_user: {
|
||||||
|
id: 9101,
|
||||||
|
id_user: 9101,
|
||||||
|
email: 'planner@farm.co',
|
||||||
|
name: 'Planning',
|
||||||
|
},
|
||||||
|
created_at: '2025-10-11T06:00:00Z',
|
||||||
|
updated_at: '2025-10-11T06:00:00Z',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 203,
|
||||||
|
transfer_date: '2025-10-12',
|
||||||
|
flock_source: { id: 3, name: 'Flock C' },
|
||||||
|
flock_destination: { id: 11, name: 'Laying House 2' },
|
||||||
|
quantity: 1100,
|
||||||
|
kandangs: [
|
||||||
|
{
|
||||||
|
kandang: {
|
||||||
|
id: 21,
|
||||||
|
name: 'KDG-21',
|
||||||
|
status: 'ACTIVE',
|
||||||
|
location: {
|
||||||
|
id: 103,
|
||||||
|
name: 'Farm Gamma',
|
||||||
|
address: 'Dusun Gamma',
|
||||||
|
area: { id: 1003, name: 'Area Timur' },
|
||||||
|
},
|
||||||
|
pic: {
|
||||||
|
id: 505,
|
||||||
|
id_user: 505,
|
||||||
|
email: 'dewi@farm.co',
|
||||||
|
name: 'Dewi Lestari',
|
||||||
|
},
|
||||||
|
created_user: {
|
||||||
|
id: 9004,
|
||||||
|
id_user: 9004,
|
||||||
|
email: 'ops@farm.co',
|
||||||
|
name: 'Ops Bot',
|
||||||
|
},
|
||||||
|
created_at: '2025-09-10T08:00:00Z',
|
||||||
|
updated_at: '2025-10-05T08:00:00Z',
|
||||||
|
},
|
||||||
|
quantity: 700,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
kandang: {
|
||||||
|
id: 22,
|
||||||
|
name: 'KDG-22',
|
||||||
|
status: 'ACTIVE',
|
||||||
|
location: {
|
||||||
|
id: 103,
|
||||||
|
name: 'Farm Gamma',
|
||||||
|
address: 'Dusun Gamma',
|
||||||
|
area: { id: 1003, name: 'Area Timur' },
|
||||||
|
},
|
||||||
|
pic: {
|
||||||
|
id: 506,
|
||||||
|
id_user: 506,
|
||||||
|
email: 'hadi@farm.co',
|
||||||
|
name: 'Hadi Santoso',
|
||||||
|
},
|
||||||
|
created_user: {
|
||||||
|
id: 9004,
|
||||||
|
id_user: 9004,
|
||||||
|
email: 'ops@farm.co',
|
||||||
|
name: 'Ops Bot',
|
||||||
|
},
|
||||||
|
created_at: '2025-09-12T08:00:00Z',
|
||||||
|
updated_at: '2025-10-06T08:00:00Z',
|
||||||
|
},
|
||||||
|
quantity: 400,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
reason: 'Align age group',
|
||||||
|
created_user: {
|
||||||
|
id: 9102,
|
||||||
|
id_user: 9102,
|
||||||
|
email: 'scheduler@farm.co',
|
||||||
|
name: 'Scheduler',
|
||||||
|
},
|
||||||
|
created_at: '2025-10-12T06:00:00Z',
|
||||||
|
updated_at: '2025-10-12T06:00:00Z',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 204,
|
||||||
|
transfer_date: '2025-10-13',
|
||||||
|
flock_source: { id: 1, name: 'Flock A' },
|
||||||
|
flock_destination: { id: 12, name: 'Laying House 3' },
|
||||||
|
quantity: 800,
|
||||||
|
kandangs: [
|
||||||
|
{
|
||||||
|
kandang: {
|
||||||
|
id: 15,
|
||||||
|
name: 'KDG-15',
|
||||||
|
status: 'ACTIVE',
|
||||||
|
location: {
|
||||||
|
id: 101,
|
||||||
|
name: 'Farm Alpha',
|
||||||
|
address: 'Jl. Raya Alpha No. 1',
|
||||||
|
area: { id: 1001, name: 'Area Utara' },
|
||||||
|
},
|
||||||
|
pic: {
|
||||||
|
id: 507,
|
||||||
|
id_user: 507,
|
||||||
|
email: 'nadia@farm.co',
|
||||||
|
name: 'Nadia Putri',
|
||||||
|
},
|
||||||
|
created_user: {
|
||||||
|
id: 9001,
|
||||||
|
id_user: 9001,
|
||||||
|
email: 'admin@farm.co',
|
||||||
|
name: 'System Admin',
|
||||||
|
},
|
||||||
|
created_at: '2025-08-01T08:00:00Z',
|
||||||
|
updated_at: '2025-09-28T08:00:00Z',
|
||||||
|
},
|
||||||
|
quantity: 800,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
reason: 'Open capacity in LH3',
|
||||||
|
created_user: {
|
||||||
|
id: 9103,
|
||||||
|
id_user: 9103,
|
||||||
|
email: 'opslead@farm.co',
|
||||||
|
name: 'Ops Lead',
|
||||||
|
},
|
||||||
|
created_at: '2025-10-13T06:00:00Z',
|
||||||
|
updated_at: '2025-10-13T06:00:00Z',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 205,
|
||||||
|
transfer_date: '2025-10-14',
|
||||||
|
flock_source: { id: 4, name: 'Flock D' },
|
||||||
|
flock_destination: { id: 11, name: 'Laying House 2' },
|
||||||
|
quantity: 650,
|
||||||
|
kandangs: [
|
||||||
|
{
|
||||||
|
kandang: {
|
||||||
|
id: 23,
|
||||||
|
name: 'KDG-23',
|
||||||
|
status: 'ACTIVE',
|
||||||
|
location: {
|
||||||
|
id: 104,
|
||||||
|
name: 'Farm Delta',
|
||||||
|
address: 'Jl. Delta 4',
|
||||||
|
area: { id: 1004, name: 'Area Barat' },
|
||||||
|
},
|
||||||
|
pic: {
|
||||||
|
id: 508,
|
||||||
|
id_user: 508,
|
||||||
|
email: 'yoga@farm.co',
|
||||||
|
name: 'Yoga Prabowo',
|
||||||
|
},
|
||||||
|
created_user: {
|
||||||
|
id: 9005,
|
||||||
|
id_user: 9005,
|
||||||
|
email: 'ops@farm.co',
|
||||||
|
name: 'Ops Bot',
|
||||||
|
},
|
||||||
|
created_at: '2025-09-20T08:00:00Z',
|
||||||
|
updated_at: '2025-10-10T08:00:00Z',
|
||||||
|
},
|
||||||
|
quantity: 350,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
kandang: {
|
||||||
|
id: 24,
|
||||||
|
name: 'KDG-24',
|
||||||
|
status: 'ACTIVE',
|
||||||
|
location: {
|
||||||
|
id: 104,
|
||||||
|
name: 'Farm Delta',
|
||||||
|
address: 'Jl. Delta 4',
|
||||||
|
area: { id: 1004, name: 'Area Barat' },
|
||||||
|
},
|
||||||
|
pic: {
|
||||||
|
id: 509,
|
||||||
|
id_user: 509,
|
||||||
|
email: 'mega@farm.co',
|
||||||
|
name: 'Mega Anggraini',
|
||||||
|
},
|
||||||
|
created_user: {
|
||||||
|
id: 9005,
|
||||||
|
id_user: 9005,
|
||||||
|
email: 'ops@farm.co',
|
||||||
|
name: 'Ops Bot',
|
||||||
|
},
|
||||||
|
created_at: '2025-09-21T08:00:00Z',
|
||||||
|
updated_at: '2025-10-10T08:00:00Z',
|
||||||
|
},
|
||||||
|
quantity: 300,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
reason: 'Fill remaining LH2 slots',
|
||||||
|
created_user: {
|
||||||
|
id: 9104,
|
||||||
|
id_user: 9104,
|
||||||
|
email: 'scheduler@farm.co',
|
||||||
|
name: 'Scheduler',
|
||||||
|
},
|
||||||
|
created_at: '2025-10-14T06:00:00Z',
|
||||||
|
updated_at: '2025-10-14T06:00:00Z',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 206,
|
||||||
|
transfer_date: '2025-10-15',
|
||||||
|
flock_source: { id: 2, name: 'Flock B' },
|
||||||
|
flock_destination: { id: 12, name: 'Laying House 3' },
|
||||||
|
quantity: 720,
|
||||||
|
kandangs: [
|
||||||
|
{
|
||||||
|
kandang: {
|
||||||
|
id: 16,
|
||||||
|
name: 'KDG-16',
|
||||||
|
status: 'ACTIVE',
|
||||||
|
location: {
|
||||||
|
id: 102,
|
||||||
|
name: 'Farm Beta',
|
||||||
|
address: 'Jl. Melati 2',
|
||||||
|
area: { id: 1002, name: 'Area Selatan' },
|
||||||
|
},
|
||||||
|
pic: {
|
||||||
|
id: 510,
|
||||||
|
id_user: 510,
|
||||||
|
email: 'rizky@farm.co',
|
||||||
|
name: 'Rizky Maulana',
|
||||||
|
},
|
||||||
|
created_user: {
|
||||||
|
id: 9003,
|
||||||
|
id_user: 9003,
|
||||||
|
email: 'system@farm.co',
|
||||||
|
name: 'System',
|
||||||
|
},
|
||||||
|
created_at: '2025-08-12T08:00:00Z',
|
||||||
|
updated_at: '2025-10-01T08:00:00Z',
|
||||||
|
},
|
||||||
|
quantity: 420,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
kandang: {
|
||||||
|
id: 17,
|
||||||
|
name: 'KDG-17',
|
||||||
|
status: 'ACTIVE',
|
||||||
|
location: {
|
||||||
|
id: 102,
|
||||||
|
name: 'Farm Beta',
|
||||||
|
address: 'Jl. Melati 2',
|
||||||
|
area: { id: 1002, name: 'Area Selatan' },
|
||||||
|
},
|
||||||
|
pic: {
|
||||||
|
id: 511,
|
||||||
|
id_user: 511,
|
||||||
|
email: 'tia@farm.co',
|
||||||
|
name: 'Tia Safitri',
|
||||||
|
},
|
||||||
|
created_user: {
|
||||||
|
id: 9003,
|
||||||
|
id_user: 9003,
|
||||||
|
email: 'system@farm.co',
|
||||||
|
name: 'System',
|
||||||
|
},
|
||||||
|
created_at: '2025-08-18T08:00:00Z',
|
||||||
|
updated_at: '2025-10-01T08:00:00Z',
|
||||||
|
},
|
||||||
|
quantity: 300,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
reason: 'Stage-by-stage transfer',
|
||||||
|
created_user: {
|
||||||
|
id: 9105,
|
||||||
|
id_user: 9105,
|
||||||
|
email: 'opslead@farm.co',
|
||||||
|
name: 'Ops Lead',
|
||||||
|
},
|
||||||
|
created_at: '2025-10-15T06:00:00Z',
|
||||||
|
updated_at: '2025-10-15T06:00:00Z',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 207,
|
||||||
|
transfer_date: '2025-10-16',
|
||||||
|
flock_source: { id: 5, name: 'Flock E' },
|
||||||
|
flock_destination: { id: 10, name: 'Laying House 1' },
|
||||||
|
quantity: 500,
|
||||||
|
kandangs: [
|
||||||
|
{
|
||||||
|
kandang: {
|
||||||
|
id: 18,
|
||||||
|
name: 'KDG-18',
|
||||||
|
status: 'ACTIVE',
|
||||||
|
location: {
|
||||||
|
id: 105,
|
||||||
|
name: 'Farm Epsilon',
|
||||||
|
address: 'Kp. Epsilon',
|
||||||
|
area: { id: 1005, name: 'Area Tengah' },
|
||||||
|
},
|
||||||
|
pic: {
|
||||||
|
id: 512,
|
||||||
|
id_user: 512,
|
||||||
|
email: 'lukas@farm.co',
|
||||||
|
name: 'Lukas Aditya',
|
||||||
|
},
|
||||||
|
created_user: {
|
||||||
|
id: 9006,
|
||||||
|
id_user: 9006,
|
||||||
|
email: 'ops@farm.co',
|
||||||
|
name: 'Ops Bot',
|
||||||
|
},
|
||||||
|
created_at: '2025-09-01T08:00:00Z',
|
||||||
|
updated_at: '2025-10-12T08:00:00Z',
|
||||||
|
},
|
||||||
|
quantity: 250,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
kandang: {
|
||||||
|
id: 19,
|
||||||
|
name: 'KDG-19',
|
||||||
|
status: 'ACTIVE',
|
||||||
|
location: {
|
||||||
|
id: 105,
|
||||||
|
name: 'Farm Epsilon',
|
||||||
|
address: 'Kp. Epsilon',
|
||||||
|
area: { id: 1005, name: 'Area Tengah' },
|
||||||
|
},
|
||||||
|
pic: {
|
||||||
|
id: 513,
|
||||||
|
id_user: 513,
|
||||||
|
email: 'maya@farm.co',
|
||||||
|
name: 'Maya Kartika',
|
||||||
|
},
|
||||||
|
created_user: {
|
||||||
|
id: 9006,
|
||||||
|
id_user: 9006,
|
||||||
|
email: 'ops@farm.co',
|
||||||
|
name: 'Ops Bot',
|
||||||
|
},
|
||||||
|
created_at: '2025-09-03T08:00:00Z',
|
||||||
|
updated_at: '2025-10-12T08:00:00Z',
|
||||||
|
},
|
||||||
|
quantity: 250,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
reason: 'Trial batch',
|
||||||
|
created_user: {
|
||||||
|
id: 9106,
|
||||||
|
id_user: 9106,
|
||||||
|
email: 'planner@farm.co',
|
||||||
|
name: 'Planning',
|
||||||
|
},
|
||||||
|
created_at: '2025-10-16T06:00:00Z',
|
||||||
|
updated_at: '2025-10-16T06:00:00Z',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 208,
|
||||||
|
transfer_date: '2025-10-17',
|
||||||
|
flock_source: { id: 6, name: 'Flock F' },
|
||||||
|
flock_destination: { id: 13, name: 'Laying House 4' },
|
||||||
|
quantity: 1300,
|
||||||
|
kandangs: [
|
||||||
|
{
|
||||||
|
kandang: {
|
||||||
|
id: 25,
|
||||||
|
name: 'KDG-25',
|
||||||
|
status: 'ACTIVE',
|
||||||
|
location: {
|
||||||
|
id: 106,
|
||||||
|
name: 'Farm Zeta',
|
||||||
|
address: 'Jl. Zeta 6',
|
||||||
|
area: { id: 1006, name: 'Area Tenggara' },
|
||||||
|
},
|
||||||
|
pic: {
|
||||||
|
id: 514,
|
||||||
|
id_user: 514,
|
||||||
|
email: 'rara@farm.co',
|
||||||
|
name: 'Rara Pertiwi',
|
||||||
|
},
|
||||||
|
created_user: {
|
||||||
|
id: 9007,
|
||||||
|
id_user: 9007,
|
||||||
|
email: 'ops@farm.co',
|
||||||
|
name: 'Ops Bot',
|
||||||
|
},
|
||||||
|
created_at: '2025-09-07T08:00:00Z',
|
||||||
|
updated_at: '2025-10-13T08:00:00Z',
|
||||||
|
},
|
||||||
|
quantity: 700,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
kandang: {
|
||||||
|
id: 26,
|
||||||
|
name: 'KDG-26',
|
||||||
|
status: 'ACTIVE',
|
||||||
|
location: {
|
||||||
|
id: 106,
|
||||||
|
name: 'Farm Zeta',
|
||||||
|
address: 'Jl. Zeta 6',
|
||||||
|
area: { id: 1006, name: 'Area Tenggara' },
|
||||||
|
},
|
||||||
|
pic: {
|
||||||
|
id: 515,
|
||||||
|
id_user: 515,
|
||||||
|
email: 'doni@farm.co',
|
||||||
|
name: 'Doni Firmansyah',
|
||||||
|
},
|
||||||
|
created_user: {
|
||||||
|
id: 9007,
|
||||||
|
id_user: 9007,
|
||||||
|
email: 'ops@farm.co',
|
||||||
|
name: 'Ops Bot',
|
||||||
|
},
|
||||||
|
created_at: '2025-09-09T08:00:00Z',
|
||||||
|
updated_at: '2025-10-13T08:00:00Z',
|
||||||
|
},
|
||||||
|
quantity: 600,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
reason: 'Open new house',
|
||||||
|
created_user: {
|
||||||
|
id: 9107,
|
||||||
|
id_user: 9107,
|
||||||
|
email: 'scheduler@farm.co',
|
||||||
|
name: 'Scheduler',
|
||||||
|
},
|
||||||
|
created_at: '2025-10-17T06:00:00Z',
|
||||||
|
updated_at: '2025-10-17T06:00:00Z',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
|
||||||
|
// 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 extends BaseApiService<
|
||||||
|
TransferToLaying,
|
||||||
|
CreateTransferToLayingPayload,
|
||||||
|
UpdateTransferToLayingPayload
|
||||||
|
> {
|
||||||
|
constructor(basePath: string = '') {
|
||||||
|
super(basePath);
|
||||||
|
}
|
||||||
|
|
||||||
|
// TODO: remove dummy data and integrate to real API
|
||||||
|
override async getAllFetcher(
|
||||||
|
endpoint: string
|
||||||
|
): Promise<BaseApiResponse<TransferToLaying[]>> {
|
||||||
|
// return await httpClientFetcher<BaseApiResponse<T[]>>(endpoint);
|
||||||
|
|
||||||
|
await sleep(750);
|
||||||
|
|
||||||
|
return GET_ALL_TRANSFER_TO_LAYING_DUMMY_DATA;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TODO: remove dummy data and integrate to real API
|
||||||
|
async approve(
|
||||||
|
id: number
|
||||||
|
): Promise<BaseApiResponse<{ message: string }> | undefined> {
|
||||||
|
try {
|
||||||
|
await sleep(750);
|
||||||
|
|
||||||
|
return {
|
||||||
|
code: 200,
|
||||||
|
status: 'success',
|
||||||
|
message: 'Berhasil approve data transfer ke laying!',
|
||||||
|
data: {
|
||||||
|
message: 'Berhasil approve data transfer ke laying!',
|
||||||
|
},
|
||||||
|
};
|
||||||
|
} catch (error) {
|
||||||
|
// if (axios.isAxiosError<BaseApiResponse<T>>(error)) {
|
||||||
|
// return error.response?.data;
|
||||||
|
// }
|
||||||
|
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TODO: remove dummy data and integrate to real API
|
||||||
|
async bulkApprove(
|
||||||
|
ids: number[]
|
||||||
|
): Promise<BaseApiResponse<{ message: string }> | undefined> {
|
||||||
|
try {
|
||||||
|
await sleep(750);
|
||||||
|
|
||||||
|
return {
|
||||||
|
code: 200,
|
||||||
|
status: 'success',
|
||||||
|
message: 'Berhasil approve data transfer ke laying!',
|
||||||
|
data: {
|
||||||
|
message: 'Berhasil approve data transfer ke laying!',
|
||||||
|
},
|
||||||
|
};
|
||||||
|
} catch (error) {
|
||||||
|
// if (axios.isAxiosError<BaseApiResponse<T>>(error)) {
|
||||||
|
// return error.response?.data;
|
||||||
|
// }
|
||||||
|
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TODO: remove dummy data and integrate to real API
|
||||||
|
async reject(
|
||||||
|
id: number
|
||||||
|
): Promise<BaseApiResponse<{ message: string }> | undefined> {
|
||||||
|
try {
|
||||||
|
await sleep(750);
|
||||||
|
|
||||||
|
return {
|
||||||
|
code: 200,
|
||||||
|
status: 'success',
|
||||||
|
message: 'Berhasil reject data transfer ke laying!',
|
||||||
|
data: {
|
||||||
|
message: 'Berhasil reject data transfer ke laying!',
|
||||||
|
},
|
||||||
|
};
|
||||||
|
} catch (error) {
|
||||||
|
// if (axios.isAxiosError<BaseApiResponse<T>>(error)) {
|
||||||
|
// return error.response?.data;
|
||||||
|
// }
|
||||||
|
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TODO: remove dummy data and integrate to real API
|
||||||
|
async bulkReject(
|
||||||
|
ids: number[]
|
||||||
|
): Promise<BaseApiResponse<{ message: string }> | undefined> {
|
||||||
|
try {
|
||||||
|
await sleep(750);
|
||||||
|
|
||||||
|
return {
|
||||||
|
code: 200,
|
||||||
|
status: 'success',
|
||||||
|
message: 'Berhasil reject data transfer ke laying!',
|
||||||
|
data: {
|
||||||
|
message: 'Berhasil reject data transfer ke laying!',
|
||||||
|
},
|
||||||
|
};
|
||||||
|
} catch (error) {
|
||||||
|
// if (axios.isAxiosError<BaseApiResponse<T>>(error)) {
|
||||||
|
// return error.response?.data;
|
||||||
|
// }
|
||||||
|
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export const TransferToLayingApi = new TransferToLayingService('');
|
||||||
Vendored
+11
@@ -104,3 +104,14 @@ export type ApprovalsLine = {
|
|||||||
role?: string;
|
role?: string;
|
||||||
status: 'approved' | 'rejected' | 'waiting';
|
status: 'approved' | 'rejected' | 'waiting';
|
||||||
}[];
|
}[];
|
||||||
|
|
||||||
|
export type BaseApproval = {
|
||||||
|
step_number: number;
|
||||||
|
step_name: string;
|
||||||
|
action: string;
|
||||||
|
notes: string | null;
|
||||||
|
action_by: CreatedUser;
|
||||||
|
action_at: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type ApproveAction = 'APPROVED' | 'REJECTED';
|
||||||
|
|||||||
Vendored
+12
@@ -12,3 +12,15 @@ export type CreateFlockPayload = {
|
|||||||
};
|
};
|
||||||
|
|
||||||
export type UpdateFlockPayload = CreateFlockPayload;
|
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;
|
||||||
|
}[];
|
||||||
|
};
|
||||||
|
|||||||
+11
-2
@@ -1,4 +1,4 @@
|
|||||||
import { BaseMetadata } from "@/types/api/api-general";
|
import { BaseApproval, BaseMetadata } from "@/types/api/api-general";
|
||||||
import { ProjectFlockKandang } from "@/types/api/production/project-flock-kandang";
|
import { ProjectFlockKandang } from "@/types/api/production/project-flock-kandang";
|
||||||
|
|
||||||
export type BaseChickin = {
|
export type BaseChickin = {
|
||||||
@@ -7,6 +7,7 @@ export type BaseChickin = {
|
|||||||
quantity?: number;
|
quantity?: number;
|
||||||
note?: string;
|
note?: string;
|
||||||
project_flock_kandang?: ProjectFlockKandang;
|
project_flock_kandang?: ProjectFlockKandang;
|
||||||
|
approval: BaseApproval;
|
||||||
}
|
}
|
||||||
|
|
||||||
export type Chickin = BaseMetadata & BaseChickin;
|
export type Chickin = BaseMetadata & BaseChickin;
|
||||||
@@ -14,7 +15,15 @@ export type Chickin = BaseMetadata & BaseChickin;
|
|||||||
export type CreateChickinPayload = {
|
export type CreateChickinPayload = {
|
||||||
project_flock_kandang_id: number;
|
project_flock_kandang_id: number;
|
||||||
chick_in_date: string;
|
chick_in_date: string;
|
||||||
|
note: string;
|
||||||
|
quantity?: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
export type UpdateChickinPayload = CreateChickinPayload;
|
export type UpdateChickinPayload = CreateChickinPayload & {
|
||||||
|
id: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type ChickinApprovalPayload = {
|
||||||
|
action: 'APPROVED' | 'REJECTED';
|
||||||
|
approvable_ids: number[];
|
||||||
|
};
|
||||||
@@ -7,6 +7,12 @@ export type BaseProjectFlockKandang = {
|
|||||||
kandang_id: number;
|
kandang_id: number;
|
||||||
kandang: Kandang;
|
kandang: Kandang;
|
||||||
project_flock: ProjectFlock;
|
project_flock: ProjectFlock;
|
||||||
|
available_quantity?: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
export type ProjectFlockKandang = BaseProjectFlockKandang;
|
export type ProjectFlockKandang = BaseProjectFlockKandang;
|
||||||
|
|
||||||
|
export type LookupProjectFlockKandangPayload = {
|
||||||
|
project_flock_id: number;
|
||||||
|
kandang_id: number;
|
||||||
|
}
|
||||||
+7
-1
@@ -3,7 +3,7 @@ import { Fcr } from '@/types/api/master-data/fcr';
|
|||||||
import { Flock } from '@/types/api/master-data/flock';
|
import { Flock } from '@/types/api/master-data/flock';
|
||||||
import { Kandang } from '@/types/api/master-data/kandang';
|
import { Kandang } from '@/types/api/master-data/kandang';
|
||||||
import { Location } from '@/types/api/master-data/location';
|
import { Location } from '@/types/api/master-data/location';
|
||||||
import { BaseMetadata } from '@/types/api/api-general';
|
import { BaseApproval, BaseMetadata } from '@/types/api/api-general';
|
||||||
|
|
||||||
export type BaseProjectFlock = {
|
export type BaseProjectFlock = {
|
||||||
id: number;
|
id: number;
|
||||||
@@ -21,6 +21,7 @@ export type BaseProjectFlock = {
|
|||||||
period: number;
|
period: number;
|
||||||
kandang_ids: number[];
|
kandang_ids: number[];
|
||||||
kandangs: Kandang[];
|
kandangs: Kandang[];
|
||||||
|
approval: BaseApproval;
|
||||||
};
|
};
|
||||||
|
|
||||||
export type PeriodFlock = {
|
export type PeriodFlock = {
|
||||||
@@ -41,3 +42,8 @@ export type CreateProjectFlockPayload = {
|
|||||||
};
|
};
|
||||||
|
|
||||||
export type UpdateProjectFlockPayload = CreateProjectFlockPayload;
|
export type UpdateProjectFlockPayload = CreateProjectFlockPayload;
|
||||||
|
|
||||||
|
export type ProjectFlockApprovalPayload = {
|
||||||
|
action: 'APPROVED' | 'REJECTED';
|
||||||
|
approvable_ids: number[];
|
||||||
|
};
|
||||||
|
|||||||
+33
-48
@@ -1,60 +1,45 @@
|
|||||||
import { BaseMetadata } from '@/types/api/api-general';
|
import { BaseMetadata, User } from '@/types/api/api-general';
|
||||||
import { Location } from '@/types/api/master-data/location';
|
|
||||||
import { Kandang } from '@/types/api/master-data/kandang';
|
export type ProductionMetrics = {
|
||||||
import { Flock } from '@/types/api/master-data/flock';
|
total_depletion: number;
|
||||||
|
cum_depletion_rate: number;
|
||||||
|
daily_gain: number;
|
||||||
|
avg_daily_gain: number;
|
||||||
|
cum_intake: number;
|
||||||
|
fcr_value: number;
|
||||||
|
total_chick: number;
|
||||||
|
daily_depletion_rate: number;
|
||||||
|
cum_depletion: number;
|
||||||
|
};
|
||||||
|
|
||||||
export type BaseRecording = {
|
export type BaseRecording = {
|
||||||
id: number;
|
id: number;
|
||||||
flock: Flock;
|
project_flock_kandang_id: number;
|
||||||
recording_date: string;
|
record_datetime: string;
|
||||||
location: Location;
|
record_date: string;
|
||||||
coop: Kandang;
|
status: number;
|
||||||
feed_data: {
|
ontime: boolean;
|
||||||
feed_name: string;
|
day: number;
|
||||||
feed_qty: number;
|
created_user: User;
|
||||||
feed_stock: number;
|
} & ProductionMetrics;
|
||||||
}[];
|
|
||||||
body_weight: {
|
|
||||||
chicken_weight: number;
|
|
||||||
chicken_count: number;
|
|
||||||
average_chicken_weight: number;
|
|
||||||
}[];
|
|
||||||
vaccination: {
|
|
||||||
vaccine_name: string;
|
|
||||||
total_stock: number;
|
|
||||||
used_stock: number;
|
|
||||||
}[];
|
|
||||||
mortality: {
|
|
||||||
condition: string;
|
|
||||||
count: number;
|
|
||||||
}[];
|
|
||||||
};
|
|
||||||
|
|
||||||
export type Recording = BaseMetadata & BaseRecording;
|
export type Recording = BaseMetadata & BaseRecording;
|
||||||
|
|
||||||
export type CreateRecordingPayload = {
|
export type CreateRecordingPayload = {
|
||||||
flock_id: number;
|
project_flock_kandang_id: number;
|
||||||
recording_date: string;
|
body_weights: {
|
||||||
location_id: number;
|
weight: number;
|
||||||
coop_id: number;
|
qty: number;
|
||||||
feed_data: {
|
|
||||||
feed_id: string;
|
|
||||||
feed_qty: number;
|
|
||||||
feed_stock: number;
|
|
||||||
}[];
|
}[];
|
||||||
body_weight: {
|
stocks?: {
|
||||||
chicken_weight: number;
|
product_warehouse_id: number;
|
||||||
chicken_count: number;
|
usage_amount: number;
|
||||||
average_chicken_weight: number;
|
notes: string;
|
||||||
}[];
|
}[];
|
||||||
vaccination: {
|
depletions?: {
|
||||||
vaccine_id: string;
|
product_warehouse_id?: number;
|
||||||
total_stock: number;
|
total: number;
|
||||||
used_stock: number;
|
notes: string;
|
||||||
}[];
|
|
||||||
mortality: {
|
|
||||||
condition: string;
|
|
||||||
count: number;
|
|
||||||
}[];
|
}[];
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -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;
|
||||||
Reference in New Issue
Block a user