Merge branch 'development' into feat/FE/daily-checklist

This commit is contained in:
ValdiANS
2026-01-12 17:37:20 +07:00
77 changed files with 4736 additions and 3913 deletions
+32 -7
View File
@@ -7,22 +7,37 @@ import ClosingDetail from '@/components/pages/closing/ClosingDetail';
import { ClosingApi } from '@/services/api/closing';
import { isResponseError, isResponseSuccess } from '@/lib/api-helper';
import { FlockApi } from '@/services/api/master-data';
import { ProjectFlockApi } from '@/services/api/production/project-flock';
import { ProjectFlockKandangApi } from '@/services/api/production';
const ClosingDetailPage = () => {
const router = useRouter();
const searchParams = useSearchParams();
const closingId = searchParams.get('closingId');
const kandangId = searchParams.get('kandangId'); // project flock kandang ID
const { data: closing, isLoading: isLoadingClosing } = useSWR(
closingId,
(id: number) => ClosingApi.getGeneralInfo(id)
);
// const { data: salesData, isLoading: isLoadingSales } = useSWR(
// closingId ? `sales-${closingId}` : null,
// () => ClosingApi.getPenjualan(Number(closingId))
// );
// WORKAROUND - get flock data from closing ID
const { data: projectData, isLoading: isLoadingProject } = useSWR(
`flock-${closingId}`,
() => ProjectFlockApi.getSingle(Number(closingId))
);
// WORKAROUND - get kandang data from closing ID
const { data: kandangData, isLoading: isLoadingKandang } = useSWR(
kandangId ? `kandang-${closingId}-${kandangId}` : null,
() => ProjectFlockKandangApi.getSingle(Number(kandangId))
);
const { data: salesData, isLoading: isLoadingSales } = useSWR(
closingId ? `sales-${closingId}` : null,
() => ClosingApi.getPenjualan(Number(closingId))
);
const { data: hppEkspedisiData, isLoading: isLoadingHppEkspedisi } = useSWR(
closingId ? `hpp-ekspedisi-${closingId}` : null,
@@ -44,8 +59,12 @@ const ClosingDetailPage = () => {
return;
}
const isLoading = isLoadingClosing || isLoadingHppEkspedisi;
// const isLoading = isLoadingClosing || isLoadingSales || isLoadingHppEkspedisi;
const isLoading =
isLoadingClosing ||
isLoadingSales ||
isLoadingHppEkspedisi ||
isLoadingProject ||
isLoadingKandang;
return (
<div className='w-full p-4 flex flex-row justify-center'>
@@ -55,12 +74,18 @@ const ClosingDetailPage = () => {
<ClosingDetail
id={Number(closingId)}
initialValue={closing.data}
// salesData={isResponseSuccess(salesData) ? salesData.data : undefined}
salesData={isResponseSuccess(salesData) ? salesData.data : undefined}
hppExpeditionData={
isResponseSuccess(hppEkspedisiData)
? hppEkspedisiData.data
: undefined
}
projectData={
isResponseSuccess(projectData) ? projectData.data : undefined
}
kandangData={
isResponseSuccess(kandangData) ? kandangData.data : undefined
}
/>
)}
</div>
+1 -1
View File
@@ -37,7 +37,7 @@ const ExpenseRealization = () => {
const isExpenseCanBeRealized =
isResponseSuccess(expense) &&
expense.data.latest_approval.action !== 'REJECTED' &&
expense.data.latest_approval.step_number === 3;
expense.data.latest_approval.step_number === 4;
if (isResponseSuccess(expense) && !isExpenseCanBeRealized) {
if (typeof window !== 'undefined') {
+7
View File
@@ -0,0 +1,7 @@
import FinanceTabs from '@/components/pages/report/finance/FinanceTabs';
const Finance = () => {
return <FinanceTabs />;
};
export default Finance;
+4 -1
View File
@@ -1,6 +1,7 @@
import Alert from '@/components/Alert';
import Button from '@/components/Button';
import { Icon } from '@iconify/react';
import { useState } from 'react';
/**
* Alert Unique Error List
@@ -14,8 +15,10 @@ const AlertErrorList = ({
formErrorList: string[];
onClose: () => void;
}) => {
if (formErrorList.length === 0) return null;
return (
<Alert color='error' className='flex flex-col gap-2 px-4 m-4'>
<Alert color='error' className='w-full flex flex-col gap-2 px-4 m-4'>
<div className='flex justify-between items-center gap-2 w-full'>
<div className='flex items-center gap-2'>
<Icon icon='material-symbols:error-outline' width={24} height={24} />
+27 -8
View File
@@ -19,12 +19,16 @@ import ClosingOverheadTabContent from '@/components/pages/closing/ClosingOverhea
import ClosingFinanceTabContent from '@/components/pages/closing/ClosingFinanceTabContent';
import SalesReportTable from '@/components/pages/closing/sale/SalesReportTable';
import HppExpeditionReportTable from './hpp-ekspedisi/HppExpeditionReportTable';
import ClosingKandangList from '@/components/pages/closing/ClosingKandangList';
import { ProjectFlock } from '@/types/api/production/project-flock';
import { ProjectFlockKandang } from '@/types/api/production/project-flock-kandang';
interface ClosingDetailProps {
id: number;
initialValue?: ClosingGeneralInformation;
salesData?: BaseClosingSales;
hppExpeditionData?: ClosingHppExpedition;
projectData?: ProjectFlock;
kandangData?: ProjectFlockKandang;
}
const ClosingDetail: React.FC<ClosingDetailProps> = ({
@@ -32,6 +36,8 @@ const ClosingDetail: React.FC<ClosingDetailProps> = ({
initialValue,
salesData,
hppExpeditionData,
projectData,
kandangData,
}) => {
const [activeTab, setActiveTab] = useState<string>('sapronak');
@@ -52,11 +58,11 @@ const ClosingDetail: React.FC<ClosingDetailProps> = ({
/>
),
},
// {
// id: 'penjualan',
// label: 'Penjualan',
// content: <SalesReportTable initialValues={salesData} />,
// },
{
id: 'penjualan',
label: 'Penjualan',
content: <SalesReportTable initialValues={salesData} />,
},
{
id: 'overhead',
label: 'Overhead',
@@ -87,7 +93,9 @@ const ClosingDetail: React.FC<ClosingDetailProps> = ({
<section className='w-full max-w-7xl pb-16'>
<header className='flex flex-col gap-4'>
<Button
href='/closing'
href={
!kandangData ? '/closing' : `/closing/detail/?closingId=${id}`
}
variant='link'
className='w-fit p-0 text-primary'
>
@@ -98,7 +106,18 @@ const ClosingDetail: React.FC<ClosingDetailProps> = ({
<h1 className='text-2xl font-bold text-center'>Detail Closing</h1>
</header>
<ClosingGeneralInformationTable initialValue={initialValue} />
<ClosingGeneralInformationTable
initialValue={initialValue}
projectData={projectData}
kandangData={kandangData}
/>
{!kandangData && (
<ClosingKandangList
initialValue={initialValue}
projectData={projectData}
/>
)}
<Tabs
activeTabId={activeTab}
@@ -1,12 +1,29 @@
import { ClosingGeneralInformation } from '@/types/api/closing';
import { ProjectFlock } from '@/types/api/production/project-flock';
import { ProjectFlockKandang } from '@/types/api/production/project-flock-kandang';
import { useMemo } from 'react';
interface ClosingGeneralInformationProps {
initialValue?: ClosingGeneralInformation;
projectData?: ProjectFlock;
kandangData?: ProjectFlockKandang;
}
const ClosingGeneralInformationTable = ({
initialValue,
projectData,
kandangData,
}: ClosingGeneralInformationProps) => {
const chickinPopulation = useMemo(() => {
if (kandangData) {
return kandangData?.chickins?.reduce(
(acc, chickin) => acc + chickin.usage_qty,
0
);
}
return 0;
}, [kandangData]);
return (
<div className='w-full my-4 @container'>
<div className='flex flex-col @sm:flex-row gap-4'>
@@ -17,7 +34,9 @@ const ClosingGeneralInformationTable = ({
<tr>
<td>Lokasi</td>
<td>:</td>
<td>{initialValue?.location_name}</td>
<td>
{initialValue?.location_name ?? projectData?.location?.name}
</td>
</tr>
<tr>
<td>Periode</td>
@@ -27,12 +46,20 @@ const ClosingGeneralInformationTable = ({
<tr>
<td>Project Flock</td>
<td>:</td>
<td>{initialValue?.project_flock?.name}</td>
<td>
{initialValue?.project_flock?.name ??
projectData?.flock_name}
</td>
</tr>
<tr>
<td>Populasi</td>
<td>:</td>
<td>{initialValue?.population} Ekor</td>
<td>
{!kandangData
? (initialValue?.population ?? 0)
: (chickinPopulation ?? 0)}{' '}
Ekor
</td>
</tr>
<tr>
<td>Jenis Project</td>
@@ -40,9 +67,13 @@ const ClosingGeneralInformationTable = ({
<td>{initialValue?.project_type}</td>
</tr>
<tr className='table-row @sm:hidden'>
<td>Kandang Aktif</td>
<td>Kandang {!kandangData && 'Aktif'}</td>
<td>:</td>
<td>{initialValue?.active_house_count} Kandang</td>
<td>
{!kandangData
? `${initialValue?.active_house_count} Kandang`
: kandangData?.kandang?.name}
</td>
</tr>
<tr className='table-row @sm:hidden'>
<td>Status Pembayaran Penjualan</td>
@@ -69,9 +100,13 @@ const ClosingGeneralInformationTable = ({
<table className='table table-zebra table-sm'>
<tbody>
<tr>
<td>Kandang Aktif</td>
<td>Kandang {!kandangData && 'Aktif'}</td>
<td>:</td>
<td>{initialValue?.active_house_count} Kandang</td>
<td>
{!kandangData
? `${initialValue?.active_house_count} Kandang`
: kandangData?.kandang?.name}
</td>
</tr>
<tr>
<td>Status Pembayaran Penjualan</td>
@@ -0,0 +1,37 @@
import Button from '@/components/Button';
import { ClosingGeneralInformation } from '@/types/api/closing';
import { ProjectFlock } from '@/types/api/production/project-flock';
const ClosingKandangList = ({
initialValue,
projectData,
}: {
initialValue?: ClosingGeneralInformation;
projectData?: ProjectFlock;
}) => {
return (
<div className='w-full my-4 @container'>
<div className='flex flex-col @sm:flex-row gap-4'>
<div className='w-full'>
<div className='overflow-x-auto'>
<h1 className='font-bold my-4'>Kandang</h1>
<div className='flex flex-wrap gap-2 mb-4'>
{projectData?.kandangs?.map((kandang) => (
<Button
key={kandang.id}
variant='outline'
href={`/closing/detail/?closingId=${initialValue?.flock_id}&kandangId=${kandang.project_flock_kandang_id}`}
className='min-w-32'
>
{kandang.name}
</Button>
))}
</div>
</div>
</div>
</div>
</div>
);
};
export default ClosingKandangList;
@@ -14,6 +14,7 @@ import useSWR from 'swr';
import { ClosingApi } from '@/services/api/closing';
import { isResponseSuccess } from '@/lib/api-helper';
import { ClosingGeneralInformation } from '@/types/api/closing';
import { useSearchParams } from 'next/navigation';
interface ClosingSapronakCalculationTableProps {
projectFlockId: number;
@@ -24,9 +25,12 @@ const ClosingSapronakCalculationTable = ({
projectFlockId,
closingGeneralInformation,
}: ClosingSapronakCalculationTableProps) => {
const searchParams = useSearchParams();
const kandangId = searchParams.get('kandangId');
const { data: sapronakCalculation, isLoading } = useSWR(
`/closing/sapronak-calculation/${projectFlockId}`,
() => ClosingApi.getPerhitunganSapronak(projectFlockId),
`/closing/sapronak-calculation/${projectFlockId}${kandangId ? `/${kandangId}` : ''}`,
() => ClosingApi.getPerhitunganSapronak(projectFlockId, Number(kandangId)),
{
keepPreviousData: true,
}
@@ -57,11 +61,11 @@ const ClosingSapronakCalculationTable = ({
cell: (props) =>
props.row.original.qty_in
? formatNumber(props.row.original.qty_in as number)
: '-',
: '0',
footer: total
? () => (
<div className='font-semibold text-gray-900'>
{total?.qty_in ? formatNumber(total?.qty_in) : '-'}
{total?.qty_in ? formatNumber(total?.qty_in) : '0'}
</div>
)
: '',
@@ -72,11 +76,11 @@ const ClosingSapronakCalculationTable = ({
cell: (props) =>
props.row.original.qty_out
? formatNumber(props.row.original.qty_out as number)
: '-',
: '0',
footer: total
? () => (
<div className='font-semibold text-gray-900'>
{total?.qty_out ? formatNumber(total?.qty_out) : '-'}
{total?.qty_out ? formatNumber(total?.qty_out) : '0'}
</div>
)
: '',
@@ -87,11 +91,11 @@ const ClosingSapronakCalculationTable = ({
cell: (props) =>
props.row.original.qty_used
? formatNumber(props.row.original.qty_used as number)
: '-',
: '0',
footer: total
? () => (
<div className='font-semibold text-gray-900'>
{total?.qty_used ? formatNumber(total?.qty_used) : '-'}
{total?.qty_used ? formatNumber(total?.qty_used) : '0'}
</div>
)
: '',
@@ -173,20 +177,12 @@ const ClosingSapronakCalculationTable = ({
[sapronakCalculation]
);
const pulletColumns = useMemo(
() =>
isResponseSuccess(sapronakCalculation)
? createColumns(sapronakCalculation.data?.pullet?.total)
: createColumns(),
[sapronakCalculation]
);
return (
<div className='flex flex-col gap-4'>
{/* Table DOC jika kategori Project Flock Growing */}
<Card
title={
closingGeneralInformation?.project_category === 'GROWING'
closingGeneralInformation?.project_type == 'GROWING'
? 'DOC'
: 'Pullet'
}
@@ -200,20 +196,17 @@ const ClosingSapronakCalculationTable = ({
<Table<RowSapronakCalculation>
data={
isResponseSuccess(sapronakCalculation)
? ((closingGeneralInformation?.project_category === 'GROWING'
? sapronakCalculation.data?.doc?.rows
: sapronakCalculation.data?.pullet?.rows) ?? [])
? (sapronakCalculation.data?.doc?.rows ?? [])
: []
}
columns={
closingGeneralInformation?.project_category === 'GROWING'
? docColumns
: pulletColumns
}
columns={docColumns}
className={{
containerClassName: 'my-4',
}}
renderFooter={isResponseSuccess(sapronakCalculation)}
renderFooter={
isResponseSuccess(sapronakCalculation) &&
sapronakCalculation.data?.doc?.rows.length > 0
}
/>
</Card>
@@ -236,7 +229,10 @@ const ClosingSapronakCalculationTable = ({
className={{
containerClassName: 'my-4',
}}
renderFooter={isResponseSuccess(sapronakCalculation)}
renderFooter={
isResponseSuccess(sapronakCalculation) &&
sapronakCalculation.data?.ovk?.rows.length > 0
}
/>
</Card>
@@ -259,7 +255,10 @@ const ClosingSapronakCalculationTable = ({
className={{
containerClassName: 'my-4',
}}
renderFooter={isResponseSuccess(sapronakCalculation)}
renderFooter={
isResponseSuccess(sapronakCalculation) &&
sapronakCalculation.data?.pakan?.rows.length > 0
}
/>
</Card>
</div>
@@ -215,31 +215,31 @@ const SalesReportTable = ({
return kandang?.name || '-';
},
},
{
id: 'payment_status',
accessorKey: 'payment_status',
header: 'Status Pembayaran',
cell: (props) => {
const status = props.getValue() as string;
const getStatusColor = (status: string) => {
if (!status) return 'neutral';
switch (status.toLowerCase()) {
case 'paid':
return 'success';
case 'tempo':
return 'warning';
default:
return 'neutral';
}
};
// {
// id: 'payment_status',
// accessorKey: 'payment_status',
// header: 'Status Pembayaran',
// cell: (props) => {
// const status = props.getValue() as string;
// const getStatusColor = (status: string) => {
// if (!status) return 'neutral';
// switch (status.toLowerCase()) {
// case 'paid':
// return 'success';
// case 'tempo':
// return 'warning';
// default:
// return 'neutral';
// }
// };
return (
<Badge variant='soft' size='sm' color={getStatusColor(status)}>
{status || '-'}
</Badge>
);
},
},
// return (
// <Badge variant='soft' size='sm' color={getStatusColor(status)}>
// {status || '-'}
// </Badge>
// );
// },
// },
],
[]
);
@@ -1,48 +1,65 @@
'use client';
import Button from '@/components/Button';
import Card from '@/components/Card';
import { Icon } from '@iconify/react';
import ProductionLineChart from '@/components/pages/dashboard/chart/ProductionLineChart';
import StandardLineChart from '@/components/pages/dashboard/chart/StandardLineChart';
import EggWeightBarChart from '@/components/pages/dashboard/chart/EggWeightBarChart';
import FCRBarChart from '@/components/pages/dashboard/chart/FCRBarChart';
import ProductionStat from '@/components/pages/dashboard/chart/ProductionStat';
import Modal, { useModal } from '@/components/Modal';
import DateInput from '@/components/input/DateInput';
import SelectInput, {
OptionType,
useSelect,
} from '@/components/input/SelectInput';
import { RadioGroup } from '@/components/input/RadioInput';
import { useState } from 'react';
import useSWR from 'swr';
import { DashboardApi } from '@/services/api/dashboard';
import { useFormik } from 'formik';
import dashboardProductionFilterSchema from '@/components/pages/dashboard/filter/DashboardProductionFilter.schema';
import { ProjectFlockApi } from '@/services/api/production';
import { ProductionStandardApi } from '@/services/api/master-data';
import { KandangApi, LocationApi } from '@/services/api/master-data';
import {
DashboardFilterType,
getDashboardFilterSchema,
} from '@/components/pages/dashboard/filter/DashboardProductionFilter.schema';
import DashboardLineChart from '@/components/pages/dashboard/chart/DashboardLineChart';
import DashboardLineChartSkeleton from '@/components/pages/dashboard/skeleton/DashboardLineChartSkeleton';
import { RadioGroup, RadioGroupItem } from '@/components/input/RadioInput';
import {
DashboardFilter,
DashboardMeta,
} from '@/types/api/dashboard/dashboard';
import DashboardStats from '@/components/pages/dashboard/chart/DashboardStats';
import { isResponseSuccess } from '@/lib/api-helper';
import AlertErrorList from '@/components/helper/form/FormErrors';
import { useFormikErrorList } from '@/services/hooks/useFormikErrorList';
// Helper function to normalize values to array
const normalizeToArray = (
value: OptionType | OptionType[] | null | undefined
): number[] => {
if (!value) return [];
if (Array.isArray(value)) {
return value.map((v) => Number(v.value));
}
return [Number(value.value)];
};
const DashboardProduction = () => {
const filterModal = useModal();
const [selectedPeriod, setSelectedPeriod] = useState('daily');
const [selectedStandards, setSelectedStandards] = useState<string[]>([
'hen_day',
'hen_house',
]);
const [endpointUrl, setEndpointUrl] = useState('/dashboard');
const [analysisMode, setAnalysisMode] = useState<'OVERVIEW' | 'COMPARISON'>(
'OVERVIEW'
);
const [endpointUrl, setEndpointUrl] = useState('/dashboards');
const [selectedLocationIds, setSelectedLocationIds] = useState<number[]>([]);
// ===== FETCH DATA =====
const {
data: dashboardProductionResponse,
isLoading: isLoadingDashboardProductionData,
error: dashboardProductionError,
mutate: refreshDashboardProductionData,
} = useSWR(endpointUrl, () =>
DashboardApi.getDashboardProductionFetcher(endpointUrl)
);
const dashboardProductionData =
dashboardProductionResponse?.status === 'success'
const dashboardProductionData = isResponseSuccess(dashboardProductionResponse)
? dashboardProductionResponse.data
: undefined;
@@ -50,14 +67,24 @@ const DashboardProduction = () => {
const { options: flockOptions, isLoadingOptions: isLoadingFlockOptions } =
useSelect(ProjectFlockApi.basePath, 'id', 'flock_name', '', {
limit: 'limit',
category: 'LAYING',
location_id: selectedLocationIds ? selectedLocationIds.toString() : '',
});
const {
options: standardProductionOptions,
isLoadingOptions: isLoadingStandardProductionOptions,
} = useSelect(ProductionStandardApi.basePath, 'id', 'name', '', {
options: locationOptions,
isLoadingOptions: isLoadingLocationOptions,
} = useSelect(LocationApi.basePath, 'id', 'name', '', {
limit: 'limit',
});
const { options: kandangOptions, isLoadingOptions: isLoadingKandangOptions } =
useSelect(KandangApi.basePath, 'id', 'name', '', {
limit: 'limit',
location_id: selectedLocationIds ? selectedLocationIds.toString() : '',
});
const comparisonTypeOptions = [
{ value: 'FARM', label: 'Farm' },
{ value: 'FLOCK', label: 'Flock' },
{ value: 'KANDANG', label: 'Kandang' },
];
// ===== FORMIK =====
const formik = useFormik({
@@ -65,57 +92,63 @@ const DashboardProduction = () => {
startDate: '',
endDate: '',
flock: [] as OptionType[],
standard_production_id: [] as OptionType[],
standard_productions: [] as OptionType[],
period: selectedPeriod,
},
validationSchema: dashboardProductionFilterSchema,
location: [] as OptionType[],
kandang: [] as OptionType[],
analysisMode: analysisMode,
comparisonType: '',
lokasiIds: [],
flockIds: [],
kandangIds: [],
} as DashboardFilterType,
validationSchema: getDashboardFilterSchema(analysisMode),
onSubmit: (values) => {
console.log(values);
// Build URL with query parameters
const params = new URLSearchParams();
if (values.startDate) params.set('startDate', values.startDate);
if (values.endDate) params.set('endDate', values.endDate);
if (values.flock && values.flock.length > 0) {
const flockIds = values.flock
.map((f: OptionType) => f.value || f)
.join(',');
params.set('flock', flockIds);
}
if (
values.standard_production_id &&
values.standard_production_id.length > 0
) {
const standardIds = values.standard_production_id
.map((s: OptionType) => s.value || s)
.join(',');
params.set('standard_production_id', standardIds);
}
if (selectedStandards.length > 0) {
params.set('standards', selectedStandards.join(','));
}
params.set('period', selectedPeriod);
const newUrl = `/dashboard?${params.toString()}`;
setEndpointUrl(newUrl);
// Close modal after applying filter
filterModal.closeModal();
handleApplyFilter({
start_date: values.startDate || '',
end_date: values.endDate || '',
analysis_mode: values.analysisMode as 'OVERVIEW' | 'COMPARISON',
location_ids: normalizeToArray(values.location),
flock_ids: normalizeToArray(values.flock),
kandang_ids: normalizeToArray(values.kandang),
comparison_type: values.comparisonType,
});
},
});
const handleResetFilter = () => {
formik.resetForm();
setSelectedPeriod('daily');
setSelectedStandards(['hen_day', 'hen_house']);
setEndpointUrl('/dashboard');
setAnalysisMode('OVERVIEW');
setEndpointUrl('/dashboards');
};
const handleApplyFilter = (values: DashboardFilter) => {
console.log(values);
// Build query params object, only include non-empty values
const params: Record<string, string> = {};
if (values.start_date) params.start_date = values.start_date;
if (values.end_date) params.end_date = values.end_date;
if (values.analysis_mode) params.analysis_mode = values.analysis_mode;
if (values.location_ids.length > 0)
params.location_ids = values.location_ids.toString();
if (values.flock_ids.length > 0)
params.flock_ids = values.flock_ids.toString();
if (values.kandang_ids.length > 0)
params.kandang_ids = values.kandang_ids.toString();
if (values.comparison_type) params.comparison_type = values.comparison_type;
setEndpointUrl(`/dashboards?${new URLSearchParams(params).toString()}`);
console.log(endpointUrl);
filterModal.closeModal();
refreshDashboardProductionData();
formik.resetForm();
};
// ===== Formik Error List =====
const { formErrorList, close, handleFormSubmit } = useFormikErrorList(formik);
if (isLoadingDashboardProductionData) {
return (
<div className='w-full min-h-screen flex items-center justify-center'>
@@ -127,15 +160,57 @@ const DashboardProduction = () => {
<>
<section className='w-full p-4 space-y-6'>
<div className='flex flex-col sm:flex-row items-center justify-between gap-4'>
<h1 className='text-3xl font-bold text-primary'>Dashboard</h1>
<div></div>
<div className='flex flex-row justify-end gap-2'>
<Button
variant='outline'
className='min-w-28 rounded-lg'
className={`min-w-28 rounded-lg ${
isResponseSuccess(dashboardProductionResponse) &&
(dashboardProductionResponse.meta as unknown as DashboardMeta)
.filters
? 'bg-gradient-to-r from-blue-50 to-blue-100 border-blue-500 text-blue-600 hover:from-blue-100 hover:to-blue-200'
: ''
}`}
onClick={() => filterModal.openModal()}
>
<Icon icon='heroicons:funnel' width={20} height={20} />
<Icon
icon='heroicons:funnel'
width={20}
height={20}
className={
isResponseSuccess(dashboardProductionResponse) &&
(dashboardProductionResponse.meta as unknown as DashboardMeta)
.filters
? 'text-blue-600'
: ''
}
/>
Filter
{isResponseSuccess(dashboardProductionResponse) &&
dashboardProductionResponse.meta &&
(dashboardProductionResponse.meta as unknown as DashboardMeta)
.filters && (
<span className='w-6 h-6 text-white bg-red-500 rounded-lg flex items-center justify-center text-xs'>
{(() => {
const meta =
dashboardProductionResponse.meta as unknown as DashboardMeta;
if (!meta.filters) return 0;
const count =
(meta.filters.location_ids.length > 1
? meta.filters.location_ids.length
: 0) +
(meta.filters.flock_ids.length > 1
? meta.filters.flock_ids.length
: 0) +
(meta.filters.kandang_ids.length > 1
? meta.filters.kandang_ids.length
: 0);
return meta.filters.analysis_mode === 'OVERVIEW'
? 1
: count;
})()}
</span>
)}
</Button>
<Button
variant='outline'
@@ -149,55 +224,38 @@ const DashboardProduction = () => {
</div>
</div>
{/* Dashboard Statistics */}
<ProductionStat data={dashboardProductionData?.statistics_data} />
{/* Dashboard Stats */}
<DashboardStats data={dashboardProductionData?.statistics_data ?? []} />
{/* Charts Grid */}
<div className='grid grid-cols-1 gap-4'>
{/* Production Line Chart */}
<Card
variant='bordered'
className={{ wrapper: 'w-full', body: 'p-6' }}
>
<ProductionLineChart
period={
selectedPeriod as 'daily' | 'weekly' | 'monthly' | 'yearly'
{/* Use DashboardLineChart component or skeleton */}
{isLoadingDashboardProductionData ? (
<DashboardLineChartSkeleton />
) : dashboardProductionData &&
dashboardProductionData.charts &&
Object.keys(dashboardProductionData.charts).length > 0 ? (
<DashboardLineChart
analysisMode={
isResponseSuccess(dashboardProductionResponse)
? dashboardProductionResponse.meta
? (
dashboardProductionResponse.meta as unknown as DashboardMeta
).filters?.analysis_mode
: analysisMode
: analysisMode
}
data={dashboardProductionData?.production_charts}
data={dashboardProductionData}
/>
</Card>
{/* Standard Line Chart */}
<Card
variant='bordered'
className={{ wrapper: 'w-full', body: 'p-6' }}
>
<StandardLineChart
selectedStandards={selectedStandards}
data={dashboardProductionData?.standard_productions}
) : (
<DashboardLineChartSkeleton
meta={
isResponseSuccess(dashboardProductionResponse)
? (dashboardProductionResponse.meta as unknown as DashboardMeta)
: undefined
}
/>
</Card>
{/* Bar Charts Grid - 2 columns */}
<div className='grid grid-cols-1 lg:grid-cols-2 gap-4'>
{/* FCR Bar Chart */}
<Card
variant='bordered'
className={{ wrapper: 'w-full', body: 'p-6' }}
>
<FCRBarChart data={dashboardProductionData?.fcr_data} />
</Card>
{/* Egg Weight Bar Chart */}
<Card
variant='bordered'
className={{ wrapper: 'w-full', body: 'p-6' }}
>
<EggWeightBarChart data={dashboardProductionData?.egg_weights} />
</Card>
</div>
</div>
)}
</section>
<Modal
ref={filterModal.ref}
className={{
@@ -221,13 +279,14 @@ const DashboardProduction = () => {
</Button>
</div>
<form className='space-y-4' onSubmit={formik.handleSubmit}>
<form
className='space-y-4'
onSubmit={handleFormSubmit}
onReset={handleResetFilter}
>
{/* Rentang Waktu */}
<div className='px-4'>
<label className='flex items-center gap-2 mb-3'>
<Icon icon='heroicons:calendar' width={20} height={20} />
Rentang Waktu
</label>
<label className='flex items-center gap-2 mb-3'>Tanggal</label>
<div className='flex items-center gap-2'>
<DateInput
name='startDate'
@@ -261,119 +320,152 @@ const DashboardProduction = () => {
</div>
</div>
{/* Analysis Mode */}
<div className='px-4'>
<label className='block mb-3'>Analysis Mode</label>
<RadioGroup
name='analysisMode'
value={formik.values.analysisMode}
onChange={(e) => {
formik.handleChange(e);
setAnalysisMode(e.target.value as 'OVERVIEW' | 'COMPARISON');
// Reset all dependent fields when analysis mode changes
formik.setFieldValue('location', []);
formik.setFieldValue('flock', []);
formik.setFieldValue('kandang', []);
formik.setFieldValue('comparisonType', '');
setSelectedLocationIds([]);
}}
color='primary'
className={{
wrapper: 'w-full my-6 font-semibold text-neutral-500',
}}
>
<RadioGroupItem
color='primary'
value='OVERVIEW'
label='Performance Overview'
/>
<RadioGroupItem
color='primary'
value='COMPARISON'
label='Performance Comparison'
/>
</RadioGroup>
</div>
{formik.values.analysisMode === 'COMPARISON' && (
<div className='px-4'>
<SelectInput
label='Compared By'
value={comparisonTypeOptions.find(
(option) => option.value === formik.values.comparisonType
)}
onChange={(selected) =>
formik.setFieldValue(
'comparisonType',
selected ? (selected as OptionType).value : ''
)
}
errorMessage={formik.errors.comparisonType as string}
options={comparisonTypeOptions}
isLoading={isLoadingLocationOptions}
isError={
Boolean(formik.errors.comparisonType) &&
Boolean(formik.touched.comparisonType)
}
/>
</div>
)}
{/* Location */}
<div className='px-4'>
<SelectInput
label='Farm'
value={formik.values.location}
onChange={(selected) => {
formik.setFieldValue('location', selected);
// Update selectedLocationIds for kandang filter
setSelectedLocationIds(normalizeToArray(selected));
// Reset dependent fields when location changes
formik.setFieldValue('flock', []);
formik.setFieldValue('kandang', []);
}}
errorMessage={formik.errors.location as string}
options={locationOptions}
isLoading={isLoadingLocationOptions}
isMulti={
comparisonTypeOptions.find(
(option) => option.value === formik.values.comparisonType
)?.value === 'FARM'
}
isError={
Boolean(formik.errors.location) &&
Boolean(formik.touched.location)
}
/>
</div>
{/* Flock */}
{!(
formik.values.analysisMode === 'COMPARISON' &&
!(
formik.values.comparisonType === 'FLOCK' ||
formik.values.comparisonType === 'KANDANG'
)
) && (
<div className='px-4'>
<SelectInput
label='Flock'
value={formik.values.flock}
onChange={(selected) => formik.setFieldValue('flock', selected)}
onChange={(selected) =>
formik.setFieldValue('flock', selected)
}
errorMessage={formik.errors.flock as string}
options={flockOptions}
isLoading={isLoadingFlockOptions}
isMulti
isMulti={
comparisonTypeOptions.find(
(option) => option.value === formik.values.comparisonType
)?.value === 'FLOCK'
}
isError={
Boolean(formik.errors.flock) && Boolean(formik.touched.flock)
Boolean(formik.errors.flock) &&
Boolean(formik.touched.flock)
}
/>
</div>
)}
{/* Production */}
{/* Kandang */}
{!(
formik.values.analysisMode === 'COMPARISON' &&
!(formik.values.comparisonType === 'KANDANG')
) && (
<div className='px-4'>
<SelectInput
label='Standard Produksi'
value={formik.values.standard_production_id}
label='Kandang'
value={formik.values.kandang}
onChange={(selected) =>
formik.setFieldValue('standard_production_id', selected)
formik.setFieldValue('kandang', selected)
}
errorMessage={formik.errors.kandang as string}
options={kandangOptions}
isLoading={isLoadingKandangOptions}
isMulti={
comparisonTypeOptions.find(
(option) => option.value === formik.values.comparisonType
)?.value === 'KANDANG'
}
errorMessage={formik.errors.standard_production_id as string}
options={standardProductionOptions}
isLoading={isLoadingStandardProductionOptions}
isMulti
isError={
Boolean(formik.errors.standard_production_id) &&
Boolean(formik.touched.standard_production_id)
Boolean(formik.errors.kandang) &&
Boolean(formik.touched.kandang)
}
/>
</div>
)}
{/* Standard */}
<div className='px-4'>
<SelectInput
label='Standard'
value={selectedStandards.map((s) => ({
value: s,
label:
s === 'hen_day'
? 'Hen Day'
: s === 'hen_house'
? 'Hen House'
: s === 'uniformity'
? 'Uniformity'
: s === 'egg_weight'
? 'Egg Weight'
: 'Egg Mass',
}))}
options={[
{ value: 'hen_day', label: 'Hen Day' },
{ value: 'hen_house', label: 'Hen House' },
{ value: 'uniformity', label: 'Uniformity' },
{ value: 'egg_weight', label: 'Egg Weight' },
{ value: 'egg_mass', label: 'Egg Mass' },
]}
isMulti
onChange={(selected: OptionType | OptionType[] | null) => {
const values = Array.isArray(selected)
? selected.map((item) => String(item.value))
: [];
setSelectedStandards(
values.length > 0 ? values : ['hen_day']
);
}}
isError={
Boolean(formik.errors.standard_productions) &&
Boolean(formik.touched.standard_productions)
}
/>
</div>
{/* Periode Perbandingan */}
<div className='px-4'>
<label className='block mb-3'>Periode Perbandingan</label>
<div className='grid grid-cols-4 gap-2'>
<Button
variant={selectedPeriod === 'daily' ? 'active' : 'soft'}
type='button'
className='rounded-lg'
onClick={() => setSelectedPeriod('daily')}
>
Harian
</Button>
<Button
variant={selectedPeriod === 'weekly' ? 'active' : 'soft'}
type='button'
className='rounded-lg'
onClick={() => setSelectedPeriod('weekly')}
>
Mingguan
</Button>
<Button
variant={selectedPeriod === 'monthly' ? 'active' : 'soft'}
type='button'
className='rounded-lg'
onClick={() => setSelectedPeriod('monthly')}
>
Bulanan
</Button>
<Button
variant={selectedPeriod === 'yearly' ? 'active' : 'soft'}
type='button'
className='rounded-lg'
onClick={() => setSelectedPeriod('yearly')}
>
Tahunan
</Button>
</div>
</div>
<AlertErrorList formErrorList={formErrorList} onClose={close} />
{/* Action Buttons */}
<div className='flex justify-between gap-4 py-4 mt-8 border-t border-gray-300 bg-gray-100'>
@@ -0,0 +1,545 @@
import Button from '@/components/Button';
import Card from '@/components/Card';
import Dropdown from '@/components/Dropdown';
import Menu from '@/components/menu/Menu';
import MenuItem from '@/components/menu/MenuItem';
import {
Dashboard,
DashboardOverviewCharts,
DashboardComparisonCharts,
DashboardChartsSeries,
DashboardChartsDataset,
} from '@/types/api/dashboard/dashboard';
import { Icon } from '@iconify/react';
import { useState, useEffect } from 'react';
import {
CartesianGrid,
Line,
LineChart,
ResponsiveContainer,
Tooltip,
XAxis,
YAxis,
} from 'recharts';
type DashboardLineChartProps = {
analysisMode: 'OVERVIEW' | 'COMPARISON';
data: Dashboard;
};
// Type guard to check if charts is DashboardOverviewCharts
function isOverviewCharts(
charts: DashboardOverviewCharts | DashboardComparisonCharts
): charts is DashboardOverviewCharts {
return 'deplesi' in charts;
}
// Type guard to check if charts is DashboardComparisonCharts
function isComparisonCharts(
charts: DashboardOverviewCharts | DashboardComparisonCharts
): charts is DashboardComparisonCharts {
return 'location' in charts || 'flock' in charts || 'kandang' in charts;
}
const lineColors: Record<string, string> = {
body_weight: '#10B981',
std_body_weight: '#10B981',
act_laying: '#1062B9',
std_laying: '#1062B9',
act_egg_weight: '#10B981',
std_egg_weight: '#10B981',
act_feed_intake: '#F52419',
std_feed_intake: '#F52419',
act_uniformity: '#F59E0B',
std_uniformity: '#F59E0B',
act_fcr: '#10B981',
std_fcr: '#10B981',
act_fcr_cum: '#F52419',
std_fcr_cum: '#10B981',
normal: '#10B981',
abnormal: '#F52419',
act_deplesi: '#10B981',
std_deplesi: '#10B981',
};
const defaultLineColors: string[] = [
'#10B981',
'#1062B9',
'#F52419',
'#F59E0B',
'#7F56D9',
];
// Helper function to get line color
const getLineColor = (
seriesId: string | number,
index: number,
mode: 'OVERVIEW' | 'COMPARISON'
): string => {
// For COMPARISON mode, use default colors with cycling
if (mode === 'COMPARISON') {
return defaultLineColors[index % defaultLineColors.length];
}
// For OVERVIEW mode, use predefined colors or fallback to default
const predefinedColor = lineColors[seriesId];
if (predefinedColor) {
return predefinedColor;
}
// Fallback to default colors with cycling
return defaultLineColors[index % defaultLineColors.length];
};
const DashboardLineChart = ({
analysisMode,
data,
}: DashboardLineChartProps) => {
const [chartData, setChartData] =
useState<keyof DashboardOverviewCharts>('body_weight');
const [open, setOpen] = useState(false);
// Track which series are visible (by series id)
const [visibleSeries, setVisibleSeries] = useState<Set<string | number>>(
new Set()
);
// Mapping for chart type labels
const chartTypeLabels: Record<keyof DashboardOverviewCharts, string> = {
body_weight: 'Body Weight',
performance: 'Performance',
fcr: 'FCR',
quality_control: 'Quality Control',
deplesi: 'Deplesi',
};
// Initialize all series as visible when chartData changes
useEffect(() => {
let seriesData: DashboardChartsSeries[] = [];
if (analysisMode === 'OVERVIEW' && isOverviewCharts(data.charts)) {
seriesData = data.charts[chartData]?.series || [];
} else if (
analysisMode === 'COMPARISON' &&
isComparisonCharts(data.charts)
) {
const comparisonChart =
data.charts.location || data.charts.flock || data.charts.kandang;
seriesData = comparisonChart?.series || [];
}
// Set all series as visible by default
const allSeriesIds = new Set(seriesData.map((s) => s.id));
setVisibleSeries(allSeriesIds);
}, [chartData, analysisMode, data.charts]);
return (
<Card
className={{
wrapper: 'w-full rounded-lg',
}}
variant='bordered'
>
<div className='flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4 mb-6'>
<div className='text-lg font-semibold'>
Performance{' '}
<Icon
icon='heroicons:information-circle'
width={20}
height={20}
className='inline text-neutral-500'
/>
</div>
{analysisMode == 'OVERVIEW' && (
<Dropdown
align='end'
direction='bottom'
trigger={
<Button
variant='outline'
color='none'
className='text-neutral-500 hover:text-neutral-700 rounded-lg px-4 py-2 border-neutral-300'
onClick={() => setOpen(!open)}
>
{chartTypeLabels[chartData]}{' '}
<div className='divider divider-horizontal p-0 m-0 before:bg-neutral-300 after:bg-neutral-300'></div>
<Icon icon='heroicons:chevron-down' width={20} height={20} />
</Button>
}
className={{
content: 'w-52 mt-3',
}}
controlled={open}
>
<Menu>
<MenuItem
title='Body weight'
onClick={() => {
setChartData('body_weight');
setOpen(!open);
}}
/>
<MenuItem
title='Performance'
onClick={() => {
setChartData('performance');
setOpen(!open);
}}
/>
<MenuItem
title='FCR'
onClick={() => {
setChartData('fcr');
setOpen(!open);
}}
/>
<MenuItem
title='Quality Control'
onClick={() => {
setChartData('quality_control');
setOpen(!open);
}}
/>
<MenuItem
title='Deplesi'
onClick={() => {
setChartData('deplesi');
setOpen(!open);
}}
/>
</Menu>
</Dropdown>
)}
</div>
{/* Legend - Dynamic based on series data */}
<div className='flex flex-wrap gap-3 mb-6'>
{(() => {
// Get series data based on current mode and chartData
let seriesData: DashboardChartsSeries[] = [];
if (analysisMode === 'OVERVIEW' && isOverviewCharts(data.charts)) {
seriesData = data.charts[chartData]?.series || [];
} else if (
analysisMode === 'COMPARISON' &&
isComparisonCharts(data.charts)
) {
const comparisonChart =
data.charts.location || data.charts.flock || data.charts.kandang;
seriesData = comparisonChart?.series || [];
}
return seriesData.map((series, index) => {
const isVisible = visibleSeries.has(series.id);
const isStandard = series.id
.toString()
.toLowerCase()
.includes('std');
return (
<button
key={series.id}
onClick={() => {
const newVisible = new Set(visibleSeries);
if (isVisible) {
newVisible.delete(series.id);
} else {
newVisible.add(series.id);
}
setVisibleSeries(newVisible);
}}
className={`flex items-center gap-2 px-3 py-2 rounded-lg border transition-colors ${
isVisible
? 'border-neutral-400 bg-neutral-50'
: 'border-neutral-300 hover:bg-neutral-50'
}`}
>
<div
className={`w-6 h-0.5 ${
isStandard ? 'border-t-2 border-dashed' : ''
} ${!isVisible ? 'opacity-30' : ''}`}
style={{
backgroundColor: isStandard
? 'transparent'
: getLineColor(series.id, index, analysisMode),
borderColor: isStandard
? getLineColor(series.id, index, analysisMode)
: 'transparent',
}}
></div>
<span
className={`text-sm ${isVisible ? 'text-neutral-900 font-medium' : 'text-neutral-700'}`}
>
{series.label}
</span>
<Icon
icon='heroicons:information-circle'
width={16}
height={16}
className='text-neutral-400'
/>
</button>
);
});
})()}
</div>
{/* Chart */}
<ResponsiveContainer width='100%' height={350}>
<LineChart
data={(() => {
// Transform data based on analysisMode
if (analysisMode === 'OVERVIEW') {
// For OVERVIEW mode, use the selected chart data
if (isOverviewCharts(data.charts)) {
const selectedChartData = data.charts[chartData];
if (!selectedChartData || !selectedChartData.dataset) return [];
return selectedChartData.dataset;
}
return [];
} else {
// For COMPARISON mode, use the first available comparison chart
if (isComparisonCharts(data.charts)) {
const chartData =
data.charts.location ||
data.charts.flock ||
data.charts.kandang;
if (!chartData || !chartData.dataset) return [];
return chartData.dataset;
}
return [];
}
})()}
margin={{
top: 5,
right: 10,
left: 0,
bottom: 5,
}}
>
<CartesianGrid strokeDasharray='3 3' stroke='#e5e7eb' />
<XAxis
dataKey='week'
tick={{ fontSize: 11, fill: '#9ca3af' }}
tickLine={false}
axisLine={{ stroke: '#e5e7eb' }}
label={{
value: 'Weeks',
position: 'insideBottom',
offset: -5,
style: { fontSize: 12, fill: '#9ca3af' },
}}
/>
<YAxis
tick={{ fontSize: 11, fill: '#9ca3af' }}
tickLine={false}
axisLine={{ stroke: '#e5e7eb' }}
domain={(() => {
// Calculate dynamic domain based on visible data
let seriesData: DashboardChartsSeries[] = [];
let dataset: DashboardChartsDataset[] = [];
if (
analysisMode === 'OVERVIEW' &&
isOverviewCharts(data.charts)
) {
seriesData = data.charts[chartData]?.series || [];
dataset = data.charts[chartData]?.dataset || [];
} else if (
analysisMode === 'COMPARISON' &&
isComparisonCharts(data.charts)
) {
const comparisonChart =
data.charts.location ||
data.charts.flock ||
data.charts.kandang;
seriesData = comparisonChart?.series || [];
dataset = comparisonChart?.dataset || [];
}
// Get all values from visible series
const visibleSeriesIds = Array.from(visibleSeries);
const allValues: number[] = [];
dataset.forEach((item: DashboardChartsDataset) => {
visibleSeriesIds.forEach((seriesId) => {
const value = item[seriesId];
if (typeof value === 'number') {
allValues.push(value);
}
});
});
if (allValues.length === 0) return [0, 100];
const minValue = Math.min(...allValues);
const maxValue = Math.max(...allValues);
// Add padding (10% on each side)
const padding = (maxValue - minValue) * 0.1;
const domainMin = Math.floor(Math.max(0, minValue - padding));
const domainMax = Math.ceil(maxValue + padding);
return [domainMin, domainMax];
})()}
ticks={(() => {
// Calculate dynamic ticks based on domain
let seriesData: DashboardChartsSeries[] = [];
let dataset: DashboardChartsDataset[] = [];
if (
analysisMode === 'OVERVIEW' &&
isOverviewCharts(data.charts)
) {
seriesData = data.charts[chartData]?.series || [];
dataset = data.charts[chartData]?.dataset || [];
} else if (
analysisMode === 'COMPARISON' &&
isComparisonCharts(data.charts)
) {
const comparisonChart =
data.charts.location ||
data.charts.flock ||
data.charts.kandang;
seriesData = comparisonChart?.series || [];
dataset = comparisonChart?.dataset || [];
}
const visibleSeriesIds = Array.from(visibleSeries);
const allValues: number[] = [];
dataset.forEach((item: DashboardChartsDataset) => {
visibleSeriesIds.forEach((seriesId) => {
const value = item[seriesId];
if (typeof value === 'number') {
allValues.push(value);
}
});
});
if (allValues.length === 0) return [0, 25, 50, 75, 100];
const minValue = Math.min(...allValues);
const maxValue = Math.max(...allValues);
const padding = (maxValue - minValue) * 0.1;
const domainMin = Math.floor(Math.max(0, minValue - padding));
const domainMax = Math.ceil(maxValue + padding);
// Generate 5 evenly spaced ticks
const range = domainMax - domainMin;
const step = range / 4;
return [
domainMin,
Math.round(domainMin + step),
Math.round(domainMin + step * 2),
Math.round(domainMin + step * 3),
domainMax,
];
})()}
/>
<Tooltip
contentStyle={{
backgroundColor: '#1f2937',
border: 'none',
borderRadius: '8px',
padding: '8px 12px',
color: 'white',
}}
labelStyle={{ color: 'white', marginBottom: '4px' }}
itemStyle={{ color: 'white', fontSize: '12px' }}
labelFormatter={(value) => `Week ${value}`}
formatter={(
value: number | undefined,
name: string | undefined
) => {
if (value === undefined || name === undefined) return ['', ''];
// Get series data to find the unit
let seriesData: DashboardChartsSeries[] = [];
if (
analysisMode === 'OVERVIEW' &&
isOverviewCharts(data.charts)
) {
seriesData = data.charts[chartData]?.series || [];
} else if (
analysisMode === 'COMPARISON' &&
isComparisonCharts(data.charts)
) {
const comparisonChart =
data.charts.location ||
data.charts.flock ||
data.charts.kandang;
seriesData = comparisonChart?.series || [];
}
// Find the series that matches this line's name
const series = seriesData.find((s) => s.label === name);
const unit = series?.unit || '';
return [`${value} ${unit}`, name];
}}
/>
{/* Dynamic Line rendering based on visible series */}
{(() => {
let seriesData: DashboardChartsSeries[] = [];
if (analysisMode === 'OVERVIEW' && isOverviewCharts(data.charts)) {
seriesData = data.charts[chartData]?.series || [];
} else if (
analysisMode === 'COMPARISON' &&
isComparisonCharts(data.charts)
) {
const comparisonChart =
data.charts.location ||
data.charts.flock ||
data.charts.kandang;
seriesData = comparisonChart?.series || [];
}
return seriesData
.filter((series) => visibleSeries.has(series.id))
.map((series, index) => {
const isStandard = series.id
.toString()
.toLowerCase()
.includes('std');
// Use series.id directly as dataKey to match dataset fields
const dataKey = series.id.toString();
return (
<Line
key={series.id}
type='monotone'
dataKey={dataKey}
name={series.label}
stroke={getLineColor(series.id, index, analysisMode)}
opacity={isStandard ? 0.5 : 1}
strokeWidth={2}
strokeDasharray={isStandard ? '5 5' : undefined}
dot={
isStandard
? false
: {
r: 3,
fill: '#fff',
stroke: getLineColor(
series.id,
index,
analysisMode
),
strokeWidth: 2,
}
}
activeDot={isStandard ? undefined : { r: 5 }}
/>
);
});
})()}
</LineChart>
</ResponsiveContainer>
</Card>
);
};
export default DashboardLineChart;
@@ -0,0 +1,166 @@
import Alert from '@/components/Alert';
import Card from '@/components/Card';
import { formatNumber } from '@/lib/helper';
import { DashboardStatisticsData } from '@/types/api/dashboard/dashboard';
import { Icon } from '@iconify/react';
interface DashboardStatsProps {
data: DashboardStatisticsData[];
}
// Konfigurasi untuk setiap kartu
const CARD_CONFIG = [
{
key: 'HPP Global',
icon: 'heroicons:banknotes',
alertColor: 'warning' as const,
suffix: ' /Kg',
prefix: 'RP ',
},
{
key: 'Avg. Selling Price',
icon: 'heroicons:document-currency-dollar',
alertColor: 'success' as const,
suffix: ' /Kg',
prefix: '',
},
{
key: 'FCR',
icon: 'heroicons:clipboard-document-list',
alertColor: 'info' as const,
suffix: '',
prefix: '',
},
{
key: 'Mortality',
icon: 'heroicons:exclamation-triangle',
alertColor: 'error' as const,
suffix: ' %',
prefix: '',
},
];
const DashboardStats = ({ data }: DashboardStatsProps) => {
// Helper to get trend icon and color
const getTrendDisplay = (percent: number) => {
const isPositive = percent >= 0;
return {
icon: isPositive
? 'heroicons:arrow-trending-up'
: 'heroicons:arrow-trending-down',
color: isPositive ? 'text-success' : 'text-error',
value: Math.abs(percent),
};
};
// Helper to format value
const formatValue = (value: number, prefix: string, suffix: string) => {
return (
<>
{prefix}
{formatNumber(value)}
{suffix && (
<span className='text-sm font-normal text-neutral-500'>{suffix}</span>
)}
</>
);
};
return (
<div className='grid sm:grid-cols-2 xl:grid-cols-4 gap-6'>
{CARD_CONFIG.map((config) => {
// Find matching data from API
const cardData = data.find((item) => item.label === config.key);
if (!cardData) {
// Show placeholder card for missing data (FCR & Mortality)
return (
<Card
key={config.key}
className={{
wrapper: 'w-full rounded-lg',
body: 'p-0',
}}
variant='bordered'
footer={
<div className='flex flex-row justify-between px-4 pb-4'>
<div className='text-neutral-400 font-semibold text-sm'>
From last month
</div>
<div className='text-neutral-400 font-semibold text-sm'>
Filter Required
</div>
</div>
}
>
<div className='flex flex-row items-center gap-4 px-4 pt-4'>
<Alert variant='soft' className='rounded-lg p-3 bg-neutral-100'>
<Icon
icon={config.icon}
width={32}
height={32}
className='text-neutral-400'
/>
</Alert>
<div>
<h3 className='text-neutral-400 font-semibold text-sm'>
{config.key}
</h3>
<p className='text-2xl font-semibold text-neutral-400'>
********
</p>
</div>
</div>
</Card>
);
}
const trend = getTrendDisplay(cardData.percent_last_month);
return (
<Card
key={config.key}
className={{
wrapper: 'w-full rounded-lg',
body: 'p-0',
}}
variant='bordered'
footer={
<div className='flex flex-row justify-between px-4 pb-4'>
<div className='text-neutral-500 font-semibold text-sm'>
From last month
</div>
<div
className={`${trend.color} font-semibold flex flex-row items-center gap-1 text-sm`}
>
<Icon icon={trend.icon} width={16} height={16} />
{trend.value}%
</div>
</div>
}
>
<div className='flex flex-row items-center gap-4 px-4 pt-4'>
<Alert
variant='soft'
color={config.alertColor}
className='rounded-lg p-3'
>
<Icon icon={config.icon} width={32} height={32} />
</Alert>
<div>
<h3 className='text-neutral-500 font-semibold text-sm'>
{cardData.label}
</h3>
<p className='text-2xl font-semibold'>
{formatValue(cardData.value, config.prefix, config.suffix)}
</p>
</div>
</div>
</Card>
);
})}
</div>
);
};
export default DashboardStats;
@@ -1,89 +0,0 @@
'use client';
import {
BarChart,
Bar,
XAxis,
YAxis,
CartesianGrid,
Tooltip,
ResponsiveContainer,
Cell,
} from 'recharts';
import { DashboardProductionEggWeights } from '@/types/api/dashboard/dashboard-production';
interface EggWeightBarChartProps {
data?: DashboardProductionEggWeights[];
}
const EggWeightBarChart = ({ data }: EggWeightBarChartProps) => {
// Show loading state if no data
if (!data || data.length === 0) {
return (
<div className='w-full h-full'>
<h3 className='text-lg font-semibold mb-4'>
Rata-rata Berat Telur (EW)
</h3>
<div className='flex items-center justify-center h-[350px]'>
<p className='text-gray-500'>Memuat data...</p>
</div>
</div>
);
}
return (
<div className='w-full h-full'>
<h3 className='text-lg font-semibold mb-4'>Rata-rata Berat Telur (EW)</h3>
<ResponsiveContainer width='100%' height={350}>
<BarChart
data={data}
margin={{
top: 5,
right: 30,
left: 0,
bottom: 5,
}}
>
<CartesianGrid strokeDasharray='3 3' stroke='#e5e7eb' />
<XAxis
dataKey='flock.name'
tick={{ fontSize: 12 }}
tickLine={false}
axisLine={{ stroke: '#e5e7eb' }}
/>
<YAxis
tick={{ fontSize: 12 }}
tickLine={false}
axisLine={{ stroke: '#e5e7eb' }}
domain={[0, 'auto']}
label={{
value: 'Berat (gram)',
angle: -90,
position: 'insideLeft',
style: { fontSize: 12 },
}}
/>
<Tooltip
contentStyle={{
backgroundColor: 'white',
border: '1px solid #e5e7eb',
borderRadius: '8px',
padding: '8px 12px',
}}
formatter={(value: number | undefined) =>
value !== undefined ? [`${value} gram`, ''] : ['', '']
}
cursor={{ fill: 'rgba(59, 130, 246, 0.1)' }}
/>
<Bar dataKey='weight' radius={[8, 8, 0, 0]}>
{data.map((entry, index) => (
<Cell key={`cell-${index}`} fill='#3b82f6' />
))}
</Bar>
</BarChart>
</ResponsiveContainer>
</div>
);
};
export default EggWeightBarChart;
@@ -1,97 +0,0 @@
'use client';
import {
BarChart,
Bar,
XAxis,
YAxis,
CartesianGrid,
Tooltip,
ResponsiveContainer,
Cell,
} from 'recharts';
import { DashboardProductionFcrData } from '@/types/api/dashboard/dashboard-production';
interface FCRBarChartProps {
data?: DashboardProductionFcrData[];
}
// Alternating colors: green and red
const colors = ['#10b981', '#ef4444'];
const FCRBarChart = ({ data }: FCRBarChartProps) => {
// Show loading state if no data
if (!data || data.length === 0) {
return (
<div className='w-full h-full'>
<h3 className='text-lg font-semibold mb-4'>
Feed Conversion Ratio (FCR)
</h3>
<div className='flex items-center justify-center h-[350px]'>
<p className='text-gray-500'>Memuat data...</p>
</div>
</div>
);
}
return (
<div className='w-full h-full'>
<h3 className='text-lg font-semibold mb-4'>
Feed Conversion Ratio (FCR)
</h3>
<ResponsiveContainer width='100%' height={350}>
<BarChart
data={data}
margin={{
top: 5,
right: 30,
left: 0,
bottom: 5,
}}
>
<CartesianGrid strokeDasharray='3 3' stroke='#e5e7eb' />
<XAxis
dataKey='flock.name'
tick={{ fontSize: 12 }}
tickLine={false}
axisLine={{ stroke: '#e5e7eb' }}
/>
<YAxis
tick={{ fontSize: 12 }}
tickLine={false}
axisLine={{ stroke: '#e5e7eb' }}
domain={[0, 'auto']}
label={{
value: 'FCR',
angle: -90,
position: 'insideLeft',
style: { fontSize: 12 },
}}
/>
<Tooltip
contentStyle={{
backgroundColor: 'white',
border: '1px solid #e5e7eb',
borderRadius: '8px',
padding: '8px 12px',
}}
formatter={(value: number | undefined) =>
value !== undefined ? [value.toFixed(2), 'FCR'] : ['', '']
}
cursor={{ fill: 'rgba(16, 185, 129, 0.1)' }}
/>
<Bar dataKey='fcr' radius={[8, 8, 0, 0]}>
{data.map((entry, index) => (
<Cell
key={`cell-${index}`}
fill={colors[index % colors.length]}
/>
))}
</Bar>
</BarChart>
</ResponsiveContainer>
</div>
);
};
export default FCRBarChart;
@@ -1,357 +0,0 @@
'use client';
import { useState } from 'react';
import {
LineChart,
Line,
XAxis,
YAxis,
CartesianGrid,
Tooltip,
Legend,
ResponsiveContainer,
} from 'recharts';
// Sample data in API format
const sampleApiData: ProductionChartItem[] = [
{
date: '2025-12-01T00:00:00Z',
flocks: [
{ id: 1, name: 'Flock A-002', data: 88 },
{ id: 2, name: 'Flock A-001', data: 92 },
{ id: 3, name: 'Flock B-001', data: 90 },
{ id: 4, name: 'Flock B-002', data: 85 },
],
},
{
date: '2025-12-03T00:00:00Z',
flocks: [
{ id: 1, name: 'Flock A-002', data: 85 },
{ id: 2, name: 'Flock A-001', data: 95 },
{ id: 3, name: 'Flock B-001', data: 93 },
{ id: 4, name: 'Flock B-002', data: 87 },
],
},
{
date: '2025-12-05T00:00:00Z',
flocks: [
{ id: 1, name: 'Flock A-002', data: 82 },
{ id: 2, name: 'Flock A-001', data: 98 },
{ id: 3, name: 'Flock B-001', data: 91 },
{ id: 4, name: 'Flock B-002', data: 84 },
],
},
{
date: '2025-12-07T00:00:00Z',
flocks: [
{ id: 1, name: 'Flock A-002', data: 80 },
{ id: 2, name: 'Flock A-001', data: 89 },
{ id: 3, name: 'Flock B-001', data: 88 },
{ id: 4, name: 'Flock B-002', data: 82 },
],
},
{
date: '2025-12-08T00:00:00Z',
flocks: [
{ id: 1, name: 'Flock A-002', data: 83 },
{ id: 2, name: 'Flock A-001', data: 92 },
{ id: 3, name: 'Flock B-001', data: 95 },
{ id: 4, name: 'Flock B-002', data: 85 },
],
},
{
date: '2025-12-11T00:00:00Z',
flocks: [
{ id: 1, name: 'Flock A-002', data: 81 },
{ id: 2, name: 'Flock A-001', data: 88 },
{ id: 3, name: 'Flock B-001', data: 92 },
{ id: 4, name: 'Flock B-002', data: 83 },
],
},
{
date: '2025-12-13T00:00:00Z',
flocks: [
{ id: 1, name: 'Flock A-002', data: 84 },
{ id: 2, name: 'Flock A-001', data: 90 },
{ id: 3, name: 'Flock B-001', data: 89 },
{ id: 4, name: 'Flock B-002', data: 86 },
],
},
{
date: '2025-12-15T00:00:00Z',
flocks: [
{ id: 1, name: 'Flock A-002', data: 82 },
{ id: 2, name: 'Flock A-001', data: 94 },
{ id: 3, name: 'Flock B-001', data: 96 },
{ id: 4, name: 'Flock B-002', data: 84 },
],
},
{
date: '2025-12-17T00:00:00Z',
flocks: [
{ id: 1, name: 'Flock A-002', data: 80 },
{ id: 2, name: 'Flock A-001', data: 91 },
{ id: 3, name: 'Flock B-001', data: 93 },
{ id: 4, name: 'Flock B-002', data: 82 },
],
},
{
date: '2025-12-19T00:00:00Z',
flocks: [
{ id: 1, name: 'Flock A-002', data: 79 },
{ id: 2, name: 'Flock A-001', data: 88 },
{ id: 3, name: 'Flock B-001', data: 90 },
{ id: 4, name: 'Flock B-002', data: 81 },
],
},
{
date: '2025-12-21T00:00:00Z',
flocks: [
{ id: 1, name: 'Flock A-002', data: 81 },
{ id: 2, name: 'Flock A-001', data: 97 },
{ id: 3, name: 'Flock B-001', data: 92 },
{ id: 4, name: 'Flock B-002', data: 83 },
],
},
{
date: '2025-12-23T00:00:00Z',
flocks: [
{ id: 1, name: 'Flock A-002', data: 83 },
{ id: 2, name: 'Flock A-001', data: 95 },
{ id: 3, name: 'Flock B-001', data: 98 },
{ id: 4, name: 'Flock B-002', data: 85 },
],
},
{
date: '2025-12-25T00:00:00Z',
flocks: [
{ id: 1, name: 'Flock A-002', data: 80 },
{ id: 2, name: 'Flock A-001', data: 89 },
{ id: 3, name: 'Flock B-001', data: 94 },
{ id: 4, name: 'Flock B-002', data: 82 },
],
},
{
date: '2025-12-27T00:00:00Z',
flocks: [
{ id: 1, name: 'Flock A-002', data: 82 },
{ id: 2, name: 'Flock A-001', data: 93 },
{ id: 3, name: 'Flock B-001', data: 96 },
{ id: 4, name: 'Flock B-002', data: 84 },
],
},
{
date: '2025-12-28T00:00:00Z',
flocks: [
{ id: 1, name: 'Flock A-002', data: 85 },
{ id: 2, name: 'Flock A-001', data: 96 },
{ id: 3, name: 'Flock B-001', data: 95 },
{ id: 4, name: 'Flock B-002', data: 87 },
],
},
];
// Helper function to format date based on period
const formatDateByPeriod = (
dateString: string,
period: 'daily' | 'weekly' | 'monthly' | 'yearly'
): string => {
const date = new Date(dateString);
const monthNames = [
'Jan',
'Feb',
'Mar',
'Apr',
'Mei',
'Jun',
'Jul',
'Agu',
'Sep',
'Okt',
'Nov',
'Des',
];
switch (period) {
case 'daily':
// Format: "1 Des"
return `${date.getDate()} ${monthNames[date.getMonth()]}`;
case 'weekly':
// Format: "Week 1 Des"
const weekNumber = Math.ceil(date.getDate() / 7);
return `Week ${weekNumber} ${monthNames[date.getMonth()]}`;
case 'monthly':
// Format: "Des"
return monthNames[date.getMonth()];
case 'yearly':
// Format: "2025"
return date.getFullYear().toString();
default:
return dateString;
}
};
// Type definitions for API data
interface FlockData {
id: number;
name: string;
data: number;
}
interface ProductionChartItem {
date: string;
flocks: FlockData[];
}
interface ProductionChartsData {
production_charts: ProductionChartItem[];
}
// Transform API data to Recharts format
const transformProductionData = (apiData: ProductionChartItem[]) => {
return apiData.map((item) => {
const transformed: Record<string, string | number> = {
date: item.date.split('T')[0], // Extract YYYY-MM-DD from ISO string
};
// Add each flock's data as a property
item.flocks.forEach((flock) => {
transformed[flock.name] = flock.data;
});
return transformed;
});
};
interface ProductionLineChartProps {
period?: 'daily' | 'weekly' | 'monthly' | 'yearly';
data?: ProductionChartItem[]; // Optional API data
}
const ProductionLineChart = ({
period = 'daily',
data: apiData,
}: ProductionLineChartProps) => {
// State to track which lines are hidden
const [hiddenLines, setHiddenLines] = useState<string[]>([]);
// Use API data if provided, otherwise use sample data
const chartData = apiData
? transformProductionData(apiData)
: transformProductionData(sampleApiData);
// Handle legend click to show/hide lines
const handleLegendClick = (dataKey: string) => {
setHiddenLines((prev) =>
prev.includes(dataKey)
? prev.filter((key) => key !== dataKey)
: [...prev, dataKey]
);
};
return (
<div className='w-full h-full'>
<h3 className='text-lg font-semibold mb-4'>
Performa Produksi per Flock
</h3>
<ResponsiveContainer width='100%' height={400}>
<LineChart
data={chartData}
margin={{
top: 5,
right: 30,
left: 0,
bottom: 5,
}}
>
<CartesianGrid strokeDasharray='3 3' stroke='#e5e7eb' />
<XAxis
dataKey='date'
tick={{ fontSize: 12 }}
tickLine={false}
axisLine={{ stroke: '#e5e7eb' }}
tickFormatter={(value) => formatDateByPeriod(value, period)}
/>
<YAxis
tick={{ fontSize: 12 }}
tickLine={false}
axisLine={{ stroke: '#e5e7eb' }}
domain={[0, 100]}
label={{
value: 'Persentase (%)',
angle: -90,
position: 'insideLeft',
style: { fontSize: 12 },
}}
/>
<Tooltip
contentStyle={{
backgroundColor: 'white',
border: '1px solid #e5e7eb',
borderRadius: '8px',
padding: '8px 12px',
}}
labelFormatter={(value) =>
formatDateByPeriod(value as string, period)
}
/>
<Legend
wrapperStyle={{
paddingTop: '20px',
}}
iconType='circle'
onClick={(e) => {
if (e.dataKey) handleLegendClick(e.dataKey as string);
}}
style={{ cursor: 'pointer' }}
/>
<Line
type='monotone'
dataKey='Flock A-002'
stroke='#3b82f6'
strokeWidth={2}
dot={{ r: 4, fill: '#3b82f6' }}
activeDot={{ r: 6 }}
hide={hiddenLines.includes('Flock A-002')}
/>
<Line
type='monotone'
dataKey='Flock A-001'
stroke='#10b981'
strokeWidth={2}
dot={{ r: 4, fill: '#10b981' }}
activeDot={{ r: 6 }}
hide={hiddenLines.includes('Flock A-001')}
/>
<Line
type='monotone'
dataKey='Flock B-001'
stroke='#f59e0b'
strokeWidth={2}
dot={{ r: 4, fill: '#f59e0b' }}
activeDot={{ r: 6 }}
hide={hiddenLines.includes('Flock B-001')}
/>
<Line
type='monotone'
dataKey='Flock B-002'
stroke='#ef4444'
strokeWidth={2}
dot={{ r: 4, fill: '#ef4444' }}
activeDot={{ r: 6 }}
hide={hiddenLines.includes('Flock B-002')}
/>
</LineChart>
</ResponsiveContainer>
</div>
);
};
export default ProductionLineChart;
// Export types for external use
export type { FlockData, ProductionChartItem, ProductionChartsData };
@@ -1,107 +0,0 @@
import Card from '@/components/Card';
import { Icon } from '@iconify/react';
import { DashboardProductionStatisticsData } from '@/types/api/dashboard/dashboard-production';
import { formatCurrency } from '@/lib/helper';
interface ProductionStatProps {
data?: DashboardProductionStatisticsData[];
}
const ProductionStat = ({ data }: ProductionStatProps) => {
// Helper function to get icon based on title
const getIcon = (title: string) => {
if (title.toLowerCase().includes('keuangan'))
return 'heroicons:currency-dollar';
if (title.toLowerCase().includes('penjualan'))
return 'heroicons:arrow-trending-up';
if (title.toLowerCase().includes('pembelian'))
return 'heroicons:shopping-cart';
if (title.toLowerCase().includes('overhead')) return 'heroicons:calculator';
return 'heroicons:chart-bar';
};
// Helper function to get icon background color
const getIconBgColor = (title: string) => {
if (title.toLowerCase().includes('keuangan')) return 'bg-blue-500';
if (title.toLowerCase().includes('penjualan')) return 'bg-green-500';
if (title.toLowerCase().includes('pembelian')) return 'bg-orange-500';
if (title.toLowerCase().includes('overhead')) return 'bg-purple-500';
return 'bg-gray-500';
};
// Show loading state if no data
if (!data || data.length === 0) {
return (
<section className='grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-4 gap-4'>
{[1, 2, 3, 4].map((i) => (
<Card
key={i}
variant='bordered'
className={{ wrapper: 'w-full', body: 'p-4' }}
>
<div className='animate-pulse'>
<div className='h-4 bg-gray-200 rounded w-1/2 mb-2'></div>
<div className='h-6 bg-gray-200 rounded w-3/4 mb-1'></div>
<div className='h-4 bg-gray-200 rounded w-1/3'></div>
</div>
</Card>
))}
</section>
);
}
return (
<section className='grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-4 gap-4'>
{data.map((stat, index) => (
<Card
key={index}
variant='bordered'
className={{ wrapper: 'w-full', body: 'p-4' }}
>
<div className='flex items-start justify-between'>
<div className='flex-1'>
<p className='text-sm text-gray-600 mb-2'>{stat.title}</p>
<p className='text-xl font-bold text-gray-900 mb-1'>
{formatCurrency(stat.value)}
</p>
<p
className={`text-sm flex items-center gap-1 ${
stat.changeType === 'increase'
? 'text-green-600'
: 'text-red-600'
}`}
>
<Icon
icon={
stat.changeType === 'increase'
? 'heroicons:arrow-trending-up'
: 'heroicons:arrow-trending-down'
}
width={16}
height={16}
/>
{stat.change > 0 ? '+' : ''}
{stat.change}% vs{' '}
{stat.period === 'monthly' ? 'bulan lalu' : 'periode lalu'}
</p>
</div>
<div className='flex-shrink-0'>
<div
className={`w-12 h-12 rounded-lg ${getIconBgColor(stat.title)} flex items-center justify-center`}
>
<Icon
icon={getIcon(stat.title)}
width={24}
height={24}
className='text-white'
/>
</div>
</div>
</div>
</Card>
))}
</section>
);
};
export default ProductionStat;
@@ -1,691 +0,0 @@
'use client';
import { useState } from 'react';
import {
LineChart,
Line,
XAxis,
YAxis,
CartesianGrid,
Tooltip,
Legend,
ResponsiveContainer,
} from 'recharts';
// Type definitions for API data
interface FlockData {
id: number;
name: string;
data: number;
}
interface StandardData {
name: string;
value: number;
}
interface StandardChartItem {
week: number;
standards: StandardData[];
flocks: FlockData[];
}
// Sample data in API format
const sampleApiData: StandardChartItem[] = [
{
week: 18,
standards: [
{ name: 'hen_day', value: 40 },
{ name: 'hen_house', value: 38 },
{ name: 'uniformity', value: 85 },
{ name: 'egg_weight', value: 52 },
{ name: 'egg_mass', value: 20 },
],
flocks: [
{ id: 1, name: 'Flock A-001', data: 38 },
{ id: 2, name: 'Flock A-002', data: 37 },
{ id: 3, name: 'Flock B-001', data: 39 },
{ id: 4, name: 'Flock B-002', data: 36 },
],
},
{
week: 20,
standards: [
{ name: 'hen_day', value: 45 },
{ name: 'hen_house', value: 43 },
{ name: 'uniformity', value: 86 },
{ name: 'egg_weight', value: 54 },
{ name: 'egg_mass', value: 24 },
],
flocks: [
{ id: 1, name: 'Flock A-001', data: 43 },
{ id: 2, name: 'Flock A-002', data: 42 },
{ id: 3, name: 'Flock B-001', data: 44 },
{ id: 4, name: 'Flock B-002', data: 41 },
],
},
{
week: 22,
standards: [
{ name: 'hen_day', value: 48 },
{ name: 'hen_house', value: 46 },
{ name: 'uniformity', value: 87 },
{ name: 'egg_weight', value: 55 },
{ name: 'egg_mass', value: 26 },
],
flocks: [
{ id: 1, name: 'Flock A-001', data: 47 },
{ id: 2, name: 'Flock A-002', data: 46 },
{ id: 3, name: 'Flock B-001', data: 48 },
{ id: 4, name: 'Flock B-002', data: 45 },
],
},
{
week: 24,
standards: [
{ name: 'hen_day', value: 50 },
{ name: 'hen_house', value: 48 },
{ name: 'uniformity', value: 88 },
{ name: 'egg_weight', value: 56 },
{ name: 'egg_mass', value: 28 },
],
flocks: [
{ id: 1, name: 'Flock A-001', data: 49 },
{ id: 2, name: 'Flock A-002', data: 48 },
{ id: 3, name: 'Flock B-001', data: 50 },
{ id: 4, name: 'Flock B-002', data: 47 },
],
},
{
week: 26,
standards: [
{ name: 'hen_day', value: 52 },
{ name: 'hen_house', value: 50 },
{ name: 'uniformity', value: 89 },
{ name: 'egg_weight', value: 57 },
{ name: 'egg_mass', value: 30 },
],
flocks: [
{ id: 1, name: 'Flock A-001', data: 50 },
{ id: 2, name: 'Flock A-002', data: 49 },
{ id: 3, name: 'Flock B-001', data: 51 },
{ id: 4, name: 'Flock B-002', data: 48 },
],
},
{
week: 28,
standards: [
{ name: 'hen_day', value: 55 },
{ name: 'hen_house', value: 53 },
{ name: 'uniformity', value: 90 },
{ name: 'egg_weight', value: 58 },
{ name: 'egg_mass', value: 32 },
],
flocks: [
{ id: 1, name: 'Flock A-001', data: 53 },
{ id: 2, name: 'Flock A-002', data: 52 },
{ id: 3, name: 'Flock B-001', data: 54 },
{ id: 4, name: 'Flock B-002', data: 51 },
],
},
{
week: 30,
standards: [
{ name: 'hen_day', value: 58 },
{ name: 'hen_house', value: 56 },
{ name: 'uniformity', value: 91 },
{ name: 'egg_weight', value: 59 },
{ name: 'egg_mass', value: 34 },
],
flocks: [
{ id: 1, name: 'Flock A-001', data: 55 },
{ id: 2, name: 'Flock A-002', data: 54 },
{ id: 3, name: 'Flock B-001', data: 56 },
{ id: 4, name: 'Flock B-002', data: 53 },
],
},
{
week: 32,
standards: [
{ name: 'hen_day', value: 60 },
{ name: 'hen_house', value: 58 },
{ name: 'uniformity', value: 92 },
{ name: 'egg_weight', value: 60 },
{ name: 'egg_mass', value: 36 },
],
flocks: [
{ id: 1, name: 'Flock A-001', data: 58 },
{ id: 2, name: 'Flock A-002', data: 57 },
{ id: 3, name: 'Flock B-001', data: 59 },
{ id: 4, name: 'Flock B-002', data: 56 },
],
},
{
week: 34,
standards: [
{ name: 'hen_day', value: 62 },
{ name: 'hen_house', value: 60 },
{ name: 'uniformity', value: 92 },
{ name: 'egg_weight', value: 61 },
{ name: 'egg_mass', value: 38 },
],
flocks: [
{ id: 1, name: 'Flock A-001', data: 60 },
{ id: 2, name: 'Flock A-002', data: 59 },
{ id: 3, name: 'Flock B-001', data: 61 },
{ id: 4, name: 'Flock B-002', data: 58 },
],
},
{
week: 36,
standards: [
{ name: 'hen_day', value: 64 },
{ name: 'hen_house', value: 62 },
{ name: 'uniformity', value: 93 },
{ name: 'egg_weight', value: 62 },
{ name: 'egg_mass', value: 40 },
],
flocks: [
{ id: 1, name: 'Flock A-001', data: 62 },
{ id: 2, name: 'Flock A-002', data: 61 },
{ id: 3, name: 'Flock B-001', data: 63 },
{ id: 4, name: 'Flock B-002', data: 60 },
],
},
{
week: 38,
standards: [
{ name: 'hen_day', value: 66 },
{ name: 'hen_house', value: 64 },
{ name: 'uniformity', value: 93 },
{ name: 'egg_weight', value: 63 },
{ name: 'egg_mass', value: 42 },
],
flocks: [
{ id: 1, name: 'Flock A-001', data: 64 },
{ id: 2, name: 'Flock A-002', data: 63 },
{ id: 3, name: 'Flock B-001', data: 65 },
{ id: 4, name: 'Flock B-002', data: 62 },
],
},
{
week: 40,
standards: [
{ name: 'hen_day', value: 68 },
{ name: 'hen_house', value: 66 },
{ name: 'uniformity', value: 94 },
{ name: 'egg_weight', value: 64 },
{ name: 'egg_mass', value: 44 },
],
flocks: [
{ id: 1, name: 'Flock A-001', data: 66 },
{ id: 2, name: 'Flock A-002', data: 65 },
{ id: 3, name: 'Flock B-001', data: 67 },
{ id: 4, name: 'Flock B-002', data: 64 },
],
},
{
week: 42,
standards: [
{ name: 'hen_day', value: 70 },
{ name: 'hen_house', value: 68 },
{ name: 'uniformity', value: 94 },
{ name: 'egg_weight', value: 65 },
{ name: 'egg_mass', value: 46 },
],
flocks: [
{ id: 1, name: 'Flock A-001', data: 68 },
{ id: 2, name: 'Flock A-002', data: 67 },
{ id: 3, name: 'Flock B-001', data: 69 },
{ id: 4, name: 'Flock B-002', data: 66 },
],
},
{
week: 44,
standards: [
{ name: 'hen_day', value: 72 },
{ name: 'hen_house', value: 70 },
{ name: 'uniformity', value: 95 },
{ name: 'egg_weight', value: 66 },
{ name: 'egg_mass', value: 48 },
],
flocks: [
{ id: 1, name: 'Flock A-001', data: 70 },
{ id: 2, name: 'Flock A-002', data: 69 },
{ id: 3, name: 'Flock B-001', data: 71 },
{ id: 4, name: 'Flock B-002', data: 68 },
],
},
{
week: 46,
standards: [
{ name: 'hen_day', value: 74 },
{ name: 'hen_house', value: 72 },
{ name: 'uniformity', value: 95 },
{ name: 'egg_weight', value: 67 },
{ name: 'egg_mass', value: 50 },
],
flocks: [
{ id: 1, name: 'Flock A-001', data: 72 },
{ id: 2, name: 'Flock A-002', data: 71 },
{ id: 3, name: 'Flock B-001', data: 73 },
{ id: 4, name: 'Flock B-002', data: 70 },
],
},
{
week: 48,
standards: [
{ name: 'hen_day', value: 76 },
{ name: 'hen_house', value: 74 },
{ name: 'uniformity', value: 95 },
{ name: 'egg_weight', value: 68 },
{ name: 'egg_mass', value: 52 },
],
flocks: [
{ id: 1, name: 'Flock A-001', data: 74 },
{ id: 2, name: 'Flock A-002', data: 73 },
{ id: 3, name: 'Flock B-001', data: 75 },
{ id: 4, name: 'Flock B-002', data: 72 },
],
},
{
week: 50,
standards: [
{ name: 'hen_day', value: 78 },
{ name: 'hen_house', value: 76 },
{ name: 'uniformity', value: 96 },
{ name: 'egg_weight', value: 69 },
{ name: 'egg_mass', value: 54 },
],
flocks: [
{ id: 1, name: 'Flock A-001', data: 76 },
{ id: 2, name: 'Flock A-002', data: 75 },
{ id: 3, name: 'Flock B-001', data: 77 },
{ id: 4, name: 'Flock B-002', data: 74 },
],
},
{
week: 52,
standards: [
{ name: 'hen_day', value: 80 },
{ name: 'hen_house', value: 78 },
{ name: 'uniformity', value: 96 },
{ name: 'egg_weight', value: 70 },
{ name: 'egg_mass', value: 56 },
],
flocks: [
{ id: 1, name: 'Flock A-001', data: 78 },
{ id: 2, name: 'Flock A-002', data: 77 },
{ id: 3, name: 'Flock B-001', data: 79 },
{ id: 4, name: 'Flock B-002', data: 76 },
],
},
{
week: 54,
standards: [
{ name: 'hen_day', value: 82 },
{ name: 'hen_house', value: 80 },
{ name: 'uniformity', value: 96 },
{ name: 'egg_weight', value: 71 },
{ name: 'egg_mass', value: 58 },
],
flocks: [
{ id: 1, name: 'Flock A-001', data: 80 },
{ id: 2, name: 'Flock A-002', data: 79 },
{ id: 3, name: 'Flock B-001', data: 81 },
{ id: 4, name: 'Flock B-002', data: 78 },
],
},
{
week: 56,
standards: [
{ name: 'hen_day', value: 84 },
{ name: 'hen_house', value: 82 },
{ name: 'uniformity', value: 97 },
{ name: 'egg_weight', value: 72 },
{ name: 'egg_mass', value: 60 },
],
flocks: [
{ id: 1, name: 'Flock A-001', data: 82 },
{ id: 2, name: 'Flock A-002', data: 81 },
{ id: 3, name: 'Flock B-001', data: 83 },
{ id: 4, name: 'Flock B-002', data: 80 },
],
},
{
week: 58,
standards: [
{ name: 'hen_day', value: 86 },
{ name: 'hen_house', value: 84 },
{ name: 'uniformity', value: 97 },
{ name: 'egg_weight', value: 73 },
{ name: 'egg_mass', value: 62 },
],
flocks: [
{ id: 1, name: 'Flock A-001', data: 84 },
{ id: 2, name: 'Flock A-002', data: 83 },
{ id: 3, name: 'Flock B-001', data: 85 },
{ id: 4, name: 'Flock B-002', data: 82 },
],
},
{
week: 60,
standards: [
{ name: 'hen_day', value: 88 },
{ name: 'hen_house', value: 86 },
{ name: 'uniformity', value: 97 },
{ name: 'egg_weight', value: 74 },
{ name: 'egg_mass', value: 64 },
],
flocks: [
{ id: 1, name: 'Flock A-001', data: 86 },
{ id: 2, name: 'Flock A-002', data: 85 },
{ id: 3, name: 'Flock B-001', data: 87 },
{ id: 4, name: 'Flock B-002', data: 84 },
],
},
{
week: 62,
standards: [
{ name: 'hen_day', value: 90 },
{ name: 'hen_house', value: 88 },
{ name: 'uniformity', value: 98 },
{ name: 'egg_weight', value: 75 },
{ name: 'egg_mass', value: 66 },
],
flocks: [
{ id: 1, name: 'Flock A-001', data: 88 },
{ id: 2, name: 'Flock A-002', data: 87 },
{ id: 3, name: 'Flock B-001', data: 89 },
{ id: 4, name: 'Flock B-002', data: 86 },
],
},
{
week: 64,
standards: [
{ name: 'hen_day', value: 92 },
{ name: 'hen_house', value: 90 },
{ name: 'uniformity', value: 98 },
{ name: 'egg_weight', value: 76 },
{ name: 'egg_mass', value: 68 },
],
flocks: [
{ id: 1, name: 'Flock A-001', data: 90 },
{ id: 2, name: 'Flock A-002', data: 89 },
{ id: 3, name: 'Flock B-001', data: 91 },
{ id: 4, name: 'Flock B-002', data: 88 },
],
},
{
week: 66,
standards: [
{ name: 'hen_day', value: 94 },
{ name: 'hen_house', value: 92 },
{ name: 'uniformity', value: 98 },
{ name: 'egg_weight', value: 77 },
{ name: 'egg_mass', value: 70 },
],
flocks: [
{ id: 1, name: 'Flock A-001', data: 92 },
{ id: 2, name: 'Flock A-002', data: 91 },
{ id: 3, name: 'Flock B-001', data: 93 },
{ id: 4, name: 'Flock B-002', data: 90 },
],
},
{
week: 68,
standards: [
{ name: 'hen_day', value: 95 },
{ name: 'hen_house', value: 93 },
{ name: 'uniformity', value: 98 },
{ name: 'egg_weight', value: 78 },
{ name: 'egg_mass', value: 72 },
],
flocks: [
{ id: 1, name: 'Flock A-001', data: 93 },
{ id: 2, name: 'Flock A-002', data: 92 },
{ id: 3, name: 'Flock B-001', data: 94 },
{ id: 4, name: 'Flock B-002', data: 91 },
],
},
{
week: 70,
standards: [
{ name: 'hen_day', value: 96 },
{ name: 'hen_house', value: 94 },
{ name: 'uniformity', value: 99 },
{ name: 'egg_weight', value: 79 },
{ name: 'egg_mass', value: 74 },
],
flocks: [
{ id: 1, name: 'Flock A-001', data: 94 },
{ id: 2, name: 'Flock A-002', data: 93 },
{ id: 3, name: 'Flock B-001', data: 95 },
{ id: 4, name: 'Flock B-002', data: 92 },
],
},
{
week: 72,
standards: [
{ name: 'hen_day', value: 97 },
{ name: 'hen_house', value: 95 },
{ name: 'uniformity', value: 99 },
{ name: 'egg_weight', value: 80 },
{ name: 'egg_mass', value: 76 },
],
flocks: [
{ id: 1, name: 'Flock A-001', data: 95 },
{ id: 2, name: 'Flock A-002', data: 94 },
{ id: 3, name: 'Flock B-001', data: 96 },
{ id: 4, name: 'Flock B-002', data: 93 },
],
},
];
// Transform API data to Recharts format
const transformStandardData = (
apiData: StandardChartItem[],
selectedStandards: string[] = [
'hen_day',
'hen_house',
'uniformity',
'egg_weight',
'egg_mass',
]
) => {
return apiData.map((item) => {
const transformed: Record<string, number> = {
week: item.week,
};
// Add selected standards as properties
selectedStandards.forEach((standardName) => {
const standardData = item.standards.find((s) => s.name === standardName);
if (standardData) {
transformed[standardName] = standardData.value;
}
});
// Add each flock's data as a property
item.flocks.forEach((flock) => {
transformed[flock.name] = flock.data;
});
return transformed;
});
};
interface StandardLineChartProps {
data?: StandardChartItem[];
selectedStandards?: string[];
}
const StandardLineChart = ({
data: apiData,
selectedStandards = [
'hen_day',
'hen_house',
'uniformity',
'egg_weight',
'egg_mass',
],
}: StandardLineChartProps) => {
// State to track which lines are hidden
const [hiddenLines, setHiddenLines] = useState<string[]>([]);
// Use API data if provided, otherwise use sample data
const chartData = apiData
? transformStandardData(apiData, selectedStandards)
: transformStandardData(sampleApiData, selectedStandards);
// Handle legend click to show/hide lines
const handleLegendClick = (dataKey: string) => {
setHiddenLines((prev) =>
prev.includes(dataKey)
? prev.filter((key) => key !== dataKey)
: [...prev, dataKey]
);
};
// Standard line colors mapping
const standardColors: Record<string, string> = {
hen_day: '#94a3b8',
hen_house: '#64748b',
uniformity: '#475569',
egg_weight: '#334155',
egg_mass: '#1e293b',
};
// Standard names mapping for display
const standardLabels: Record<string, string> = {
hen_day: 'Hen Day',
hen_house: 'Hen House',
uniformity: 'Uniformity',
egg_weight: 'Egg Weight',
egg_mass: 'Egg Mass',
};
return (
<div className='w-full h-full'>
<h3 className='text-lg font-semibold mb-4'>
Perbandingan Henday per Umur
</h3>
<ResponsiveContainer width='100%' height={400}>
<LineChart
data={chartData}
margin={{
top: 5,
right: 30,
left: 0,
bottom: 5,
}}
>
<CartesianGrid strokeDasharray='3 3' stroke='#e5e7eb' />
<XAxis
dataKey='week'
tick={{ fontSize: 12 }}
tickLine={false}
axisLine={{ stroke: '#e5e7eb' }}
label={{
value: 'Umur (minggu)',
position: 'insideBottom',
offset: -5,
style: { fontSize: 12 },
}}
/>
<YAxis
tick={{ fontSize: 12 }}
tickLine={false}
axisLine={{ stroke: '#e5e7eb' }}
domain={[0, 100]}
label={{
value: 'Henday (%)',
angle: -90,
position: 'insideLeft',
style: { fontSize: 12 },
}}
/>
<Tooltip
contentStyle={{
backgroundColor: 'white',
border: '1px solid #e5e7eb',
borderRadius: '8px',
padding: '8px 12px',
}}
formatter={(value: number | undefined) =>
value !== undefined ? [`${value}%`, ''] : ['', '']
}
labelFormatter={(label) => `Minggu ${label}`}
/>
<Legend
wrapperStyle={{
paddingTop: '20px',
}}
iconType='circle'
onClick={(e) => {
if (e.dataKey) handleLegendClick(e.dataKey as string);
}}
style={{ cursor: 'pointer' }}
/>
{/* Dynamic Standard Lines */}
{selectedStandards.map((standardName) => (
<Line
key={standardName}
type='monotone'
dataKey={standardName}
name={standardLabels[standardName] || standardName}
stroke={standardColors[standardName] || '#94a3b8'}
strokeWidth={2}
strokeDasharray='5 5'
dot={{ r: 3, fill: standardColors[standardName] || '#94a3b8' }}
activeDot={{ r: 5 }}
hide={hiddenLines.includes(standardName)}
/>
))}
{/* Flock Lines */}
<Line
type='monotone'
dataKey='Flock A-002'
stroke='#3b82f6'
strokeWidth={2}
dot={{ r: 4, fill: '#3b82f6' }}
activeDot={{ r: 6 }}
hide={hiddenLines.includes('Flock A-002')}
/>
<Line
type='monotone'
dataKey='Flock A-001'
stroke='#10b981'
strokeWidth={2}
dot={{ r: 4, fill: '#10b981' }}
activeDot={{ r: 6 }}
hide={hiddenLines.includes('Flock A-001')}
/>
<Line
type='monotone'
dataKey='Flock B-001'
stroke='#f59e0b'
strokeWidth={2}
dot={{ r: 4, fill: '#f59e0b' }}
activeDot={{ r: 6 }}
hide={hiddenLines.includes('Flock B-001')}
/>
<Line
type='monotone'
dataKey='Flock B-002'
stroke='#ef4444'
strokeWidth={2}
dot={{ r: 4, fill: '#ef4444' }}
activeDot={{ r: 6 }}
hide={hiddenLines.includes('Flock B-002')}
/>
</LineChart>
</ResponsiveContainer>
</div>
);
};
export default StandardLineChart;
// Export types for external use
export type { FlockData, StandardData, StandardChartItem };
@@ -1,16 +1,117 @@
import { OptionType } from '@/components/input/SelectInput';
import * as yup from 'yup';
const dashboardProductionFilterSchema = yup.object({
startDate: yup.string().optional(),
endDate: yup.string().optional(),
flock: yup.array().optional(),
standard_production_id: yup.array().optional(),
standard_productions: yup.array().optional(),
period: yup.string().optional(),
export type DashboardFilterType = {
startDate: string;
endDate: string;
analysisMode: string;
comparisonType: string | undefined;
location: OptionType | OptionType[];
lokasiIds: number[] | undefined;
flock: OptionType | OptionType[] | undefined;
flockIds: number[] | undefined;
kandang: OptionType | OptionType[] | undefined;
kandangIds: number[] | undefined;
};
// Schema untuk mode OVERVIEW - semua field required
export const DashboardFilterOverviewSchema: yup.ObjectSchema<DashboardFilterType> =
yup.object({
startDate: yup.string().required('Start date is required'),
endDate: yup.string().required('End date is required'),
analysisMode: yup.string().required('Analysis mode is required'),
comparisonType: yup.string().when('analysisMode', {
is: 'COMPARISON',
then: (schema) => schema.required('Compared by is required'),
otherwise: (schema) => schema.optional(),
}),
lokasiIds: yup.array().optional(),
flockIds: yup.array().optional(),
kandangIds: yup.array().optional(),
location: yup
.mixed<OptionType | OptionType[]>()
.required('Farm is required')
.test('is-not-empty', 'Farm is required', (value) => {
if (Array.isArray(value)) {
return value.length > 0;
}
return !!value;
}),
flock: yup
.mixed<OptionType | OptionType[]>()
.required('Flock is required')
.test('is-not-empty', 'Flock is required', (value) => {
if (Array.isArray(value)) {
return value.length > 0;
}
return !!value;
}),
kandang: yup
.mixed<OptionType | OptionType[]>()
.required('Kandang is required')
.test('is-not-empty', 'Kandang is required', (value) => {
if (Array.isArray(value)) {
return value.length > 0;
}
return !!value;
}),
});
export type DashboardProductionFilterValues = yup.InferType<
typeof dashboardProductionFilterSchema
>;
// Schema untuk mode COMPARISON - conditional validation
export const DashboardFilterComparisonSchema: yup.ObjectSchema<DashboardFilterType> =
yup.object({
startDate: yup.string().required('Start date is required'),
endDate: yup.string().required('End date is required'),
analysisMode: yup.string().required('Analysis mode is required'),
comparisonType: yup.string().when('analysisMode', {
is: 'COMPARISON',
then: (schema) => schema.required('Compared by is required'),
otherwise: (schema) => schema.optional(),
}),
lokasiIds: yup.array().optional(),
flockIds: yup.array().optional(),
kandangIds: yup.array().optional(),
location: yup
.mixed<OptionType | OptionType[]>()
.required('Farm is required')
.test('is-not-empty', 'Farm is required', (value) => {
if (Array.isArray(value)) {
return value.length > 0;
}
return !!value;
}),
flock: yup.mixed<OptionType | OptionType[]>().when('comparisonType', {
is: (value: string) => value === 'FLOCK' || value === 'KANDANG',
then: (schema) =>
schema.test('is-required', 'Flock is required', (value) => {
if (Array.isArray(value)) {
return value.length > 0;
}
return !!value;
}),
otherwise: (schema) => schema.optional(),
}),
kandang: yup.mixed<OptionType | OptionType[]>().when('comparisonType', {
is: 'KANDANG',
then: (schema) =>
schema.test('is-required', 'Kandang is required', (value) => {
if (Array.isArray(value)) {
return value.length > 0;
}
return !!value;
}),
otherwise: (schema) => schema.optional(),
}),
});
export default dashboardProductionFilterSchema;
// Helper function untuk mendapatkan schema yang sesuai berdasarkan analysis mode
export const getDashboardFilterSchema = (analysisMode?: string) => {
return analysisMode === 'OVERVIEW'
? DashboardFilterOverviewSchema
: DashboardFilterComparisonSchema;
};
// Default schema
export const DashboardFilterSchema = DashboardFilterComparisonSchema;
export type DashboardFilterValues = yup.InferType<typeof DashboardFilterSchema>;
@@ -0,0 +1,100 @@
import { Icon } from '@iconify/react';
import { DashboardMeta } from '@/types/api/dashboard/dashboard';
const DashboardLineChartSkeleton = ({ meta }: { meta?: DashboardMeta }) => {
return (
<div className='w-full bg-white rounded-lg shadow-sm border border-gray-200 p-6 relative'>
{/* Header with title skeleton */}
<div className='text-lg font-semibold'>
Performance{' '}
<Icon
icon='heroicons:information-circle'
width={20}
height={20}
className='inline text-neutral-500'
/>
</div>
{/* Chart area with axes skeleton */}
<div className='relative mt-6'>
{/* Main chart container */}
<div className='flex gap-4'>
{/* Y-axis skeleton (left side) */}
<div className='flex flex-col justify-between py-4 space-y-4'>
{[1, 2, 3, 4, 5, 6].map((item) => (
<div
key={item}
className='h-4 w-12 bg-gray-100 rounded animate-pulse'
></div>
))}
</div>
{/* Chart content area */}
<div className='flex-1 relative'>
{/* Empty state centered in chart area */}
<div className='absolute inset-0 flex flex-col items-center justify-center pb-12'>
{!meta?.filters && (
<>
{/* Filter icon */}
<div className='w-12 h-12 bg-blue-500 rounded-xl flex items-center justify-center mb-4'>
<Icon
icon='heroicons:funnel'
className='text-white'
width={24}
height={24}
/>
</div>
{/* Empty state text */}
<h3 className='text-gray-900 font-semibold text-base mb-2'>
No Filters Selected
</h3>
<p className='text-gray-500 text-sm text-center max-w-xs'>
Please choose filters to narrow down your results and make
your search easier.
</p>
</>
)}
{meta?.filters && (
<>
{/* Filter icon */}
<div className='w-12 h-12 bg-blue-500 rounded-xl flex items-center justify-center mb-4'>
<Icon
icon='heroicons:chart-bar'
className='text-white'
width={24}
height={24}
/>
</div>
{/* Empty state text */}
<h3 className='text-gray-900 font-semibold text-base mb-2'>
Data Not Yet Available
</h3>
<p className='text-gray-500 text-sm text-center max-w-xs'>
Please change your filters to get the data.
</p>
</>
)}
</div>
{/* Placeholder for chart height */}
<div className='h-64'></div>
{/* X-axis skeleton (bottom) */}
<div className='flex justify-between pt-4 border-t border-gray-100'>
{[1, 2, 3, 4, 5, 6, 7, 8, 9, 10].map((item) => (
<div
key={item}
className='h-4 w-8 bg-gray-100 rounded animate-pulse'
></div>
))}
</div>
</div>
</div>
</div>
</div>
);
};
export default DashboardLineChartSkeleton;
@@ -28,7 +28,7 @@ const ExpenseDetail: React.FC<ExpenseDetailProps> = ({ initialValues }) => {
if (
initialValues?.latest_approval &&
initialValues?.latest_approval.step_number >= 4 &&
initialValues?.latest_approval.step_number >= 5 &&
initialValues.latest_approval.action !== 'REJECTED'
) {
validTabs.push({
@@ -59,34 +59,40 @@ const ExpenseRequestContent = ({
const isLatestApprovalRejectedOrDone =
isLatestApprovalRejected ||
initialValues?.latest_approval.step_number === 5;
initialValues?.latest_approval.step_number === 6;
const isCurrentApprovalOnManager =
const isCurrentApprovalOnHeadArea =
!isLatestApprovalRejected &&
initialValues?.latest_approval.step_number === 1;
const isCurrentApprovalOnFinance =
const isCurrentApprovalOnUnitVicePresident =
!isLatestApprovalRejected &&
initialValues?.latest_approval.step_number === 2;
const isCurrentApprovalOnFinance =
!isLatestApprovalRejected &&
initialValues?.latest_approval.step_number === 3;
const isCurrentApprovalOnRealization =
!isLatestApprovalRejected &&
initialValues?.latest_approval.step_number === 4;
initialValues?.latest_approval.step_number === 5;
const showEditButton =
initialValues?.latest_approval.step_number !== 5 &&
initialValues?.latest_approval.step_number !== 6 &&
(initialValues?.latest_approval.step_number === 1 ||
initialValues?.latest_approval.step_number === 2 ||
initialValues?.latest_approval.step_number === 3);
initialValues?.latest_approval.step_number === 3 ||
initialValues?.latest_approval.step_number === 4);
const showRejectButton =
!isLatestApprovalRejected &&
(initialValues?.latest_approval.step_number === 1 ||
initialValues?.latest_approval.step_number === 2);
initialValues?.latest_approval.step_number === 2 ||
initialValues?.latest_approval.step_number === 3);
const isExpenseCanBeRealized =
!isLatestApprovalRejected &&
initialValues?.latest_approval.step_number === 3;
initialValues?.latest_approval.step_number === 4;
// Modal hooks
const deleteModal = useModal();
@@ -174,8 +180,15 @@ const ExpenseRequestContent = ({
let approveResponse: BaseApiResponse<Expense> | undefined = undefined;
if (isCurrentApprovalOnManager) {
approveResponse = await ExpenseApi.approveManager(
if (isCurrentApprovalOnHeadArea) {
approveResponse = await ExpenseApi.approveHeadArea(
initialValues.id,
notes
);
}
if (isCurrentApprovalOnUnitVicePresident) {
approveResponse = await ExpenseApi.approveUnitVicePresident(
initialValues.id,
notes
);
@@ -207,8 +220,15 @@ const ExpenseRequestContent = ({
let rejectResponse: BaseApiResponse<Expense> | undefined = undefined;
if (isCurrentApprovalOnManager) {
rejectResponse = await ExpenseApi.rejectManager(initialValues.id, notes);
if (isCurrentApprovalOnHeadArea) {
rejectResponse = await ExpenseApi.rejectHeadArea(initialValues.id, notes);
}
if (isCurrentApprovalOnUnitVicePresident) {
rejectResponse = await ExpenseApi.rejectUnitVicePresident(
initialValues.id,
notes
);
}
if (isCurrentApprovalOnFinance) {
@@ -255,8 +275,8 @@ const ExpenseRequestContent = ({
{/* TODO: apply RBAC */}
<div className='w-full max-w-5xl mx-auto flex flex-col sm:flex-row justify-end gap-2'>
{isCurrentApprovalOnManager && (
<RequirePermission permissions='lti.expense.approve.manager'>
{isCurrentApprovalOnHeadArea && (
<RequirePermission permissions='lti.expense.approve.head_area'>
<Button
variant='outline'
color='info'
@@ -264,7 +284,21 @@ const ExpenseRequestContent = ({
className='w-full sm:w-fit'
>
<Icon icon='lucide-lab:farm' width={24} height={24} />
Approve Manager
Approve Head Area
</Button>
</RequirePermission>
)}
{isCurrentApprovalOnUnitVicePresident && (
<RequirePermission permissions='lti.expense.approve.unit_vice_president'>
<Button
variant='outline'
color='success'
onClick={approveClickHandler}
className='w-full sm:w-fit'
>
<Icon icon='tdesign:money' width={24} height={24} />
Approve Unit Vice President
</Button>
</RequirePermission>
)}
@@ -304,7 +338,8 @@ const ExpenseRequestContent = ({
{showRejectButton && (
<RequirePermission
permissions={[
'lti.expense.approve.manager',
'lti.expense.approve.head_area',
'lti.expense.approve.unit_vice_president',
'lti.expense.approve.finance',
]}
>
@@ -454,8 +489,8 @@ const ExpenseRequestContent = ({
<th>:</th>
<td>
{formatCurrency(
initialValues?.latest_approval.step_number === 4 ||
initialValues?.latest_approval.step_number === 5
initialValues?.latest_approval.step_number === 5 ||
initialValues?.latest_approval.step_number === 6
? (initialValues?.total_realisasi ?? 0)
: (initialValues?.total_pengajuan ?? 0)
)}
+63 -18
View File
@@ -55,15 +55,16 @@ const RowOptionsMenu = ({
deleteClickHandler: () => void;
}) => {
const showEditButton =
props.row.original.latest_approval.step_number !== 5 &&
props.row.original.latest_approval.step_number !== 6 &&
(props.row.original.latest_approval.step_number === 1 ||
props.row.original.latest_approval.step_number === 2 ||
props.row.original.latest_approval.step_number === 3);
props.row.original.latest_approval.step_number === 3 ||
props.row.original.latest_approval.step_number === 4);
// TODO: apply RBAC
const showRealizationButton =
props.row.original.latest_approval.action !== 'REJECTED' &&
props.row.original.latest_approval.step_number === 3;
props.row.original.latest_approval.step_number === 4;
return (
<RowOptionsMenuWrapper type={type}>
@@ -193,7 +194,7 @@ const ExpensesTable = () => {
parseInt(item)
);
const isAllSelectedRowLatestApprovalOnManager = useMemo(() => {
const isAllSelectedRowLatestApprovalOnHeadArea = useMemo(() => {
return selectedRowIds.every((rowId) => {
if (!isResponseSuccess(expenses)) return false;
@@ -202,11 +203,28 @@ const ExpensesTable = () => {
const isLatestApprovalRejected =
expenseItem?.latest_approval.action === 'REJECTED';
const isCurrentApprovalOnManager =
const isCurrentApprovalOnHeadArea =
!isLatestApprovalRejected &&
expenseItem?.latest_approval.step_number === 1;
return isCurrentApprovalOnManager;
return isCurrentApprovalOnHeadArea;
});
}, [expenses, selectedRowIds]);
const isAllSelectedRowLatestApprovalOnUnitVicePresident = useMemo(() => {
return selectedRowIds.every((rowId) => {
if (!isResponseSuccess(expenses)) return false;
const expenseItem = expenses.data.find((item) => item.id === rowId);
const isLatestApprovalRejected =
expenseItem?.latest_approval.action === 'REJECTED';
const isCurrentApprovalOnUnitVicePresident =
!isLatestApprovalRejected &&
expenseItem?.latest_approval.step_number === 2;
return isCurrentApprovalOnUnitVicePresident;
});
}, [expenses, selectedRowIds]);
@@ -221,7 +239,7 @@ const ExpensesTable = () => {
const isCurrentApprovalOnFinance =
!isLatestApprovalRejected &&
expenseItem?.latest_approval.step_number === 2;
expenseItem?.latest_approval.step_number === 3;
return isCurrentApprovalOnFinance;
});
@@ -238,7 +256,7 @@ const ExpensesTable = () => {
const isCurrentApprovalOnRealization =
!isLatestApprovalRejected &&
expenseItem?.latest_approval.step_number === 4;
expenseItem?.latest_approval.step_number === 5;
return isCurrentApprovalOnRealization;
});
@@ -397,7 +415,7 @@ const ExpensesTable = () => {
) => {
return (
row.original.latest_approval.action !== 'REJECTED' &&
row.original.latest_approval.step_number !== 5
row.original.latest_approval.step_number !== 6
);
};
@@ -441,8 +459,13 @@ const ExpensesTable = () => {
let bulkApproveResponse: BaseApiResponse<Expense> | undefined = undefined;
if (isAllSelectedRowLatestApprovalOnManager) {
bulkApproveResponse = await ExpenseApi.bulkApproveManager(
if (isAllSelectedRowLatestApprovalOnHeadArea) {
bulkApproveResponse = await ExpenseApi.bulkApproveHeadArea(
selectedRowIds,
notes
);
} else if (isAllSelectedRowLatestApprovalOnUnitVicePresident) {
bulkApproveResponse = await ExpenseApi.bulkApproveUnitVicePresident(
selectedRowIds,
notes
);
@@ -478,8 +501,13 @@ const ExpensesTable = () => {
let bulkRejectResponse: BaseApiResponse<Expense> | undefined = undefined;
if (isAllSelectedRowLatestApprovalOnManager) {
bulkRejectResponse = await ExpenseApi.bulkRejectManager(
if (isAllSelectedRowLatestApprovalOnHeadArea) {
bulkRejectResponse = await ExpenseApi.bulkRejectHeadArea(
selectedRowIds,
notes
);
} else if (isAllSelectedRowLatestApprovalOnUnitVicePresident) {
bulkRejectResponse = await ExpenseApi.bulkRejectUnitVicePresident(
selectedRowIds,
notes
);
@@ -594,16 +622,31 @@ const ExpensesTable = () => {
{selectedRowIds.length > 0 && (
<>
<RequirePermission permissions='lti.expense.approve.manager'>
<RequirePermission permissions='lti.expense.approve.head_area'>
<Button
variant='outline'
color='info'
onClick={bulkApproveClickHandler}
disabled={!isAllSelectedRowLatestApprovalOnManager}
disabled={!isAllSelectedRowLatestApprovalOnHeadArea}
className='w-full sm:w-fit'
>
<Icon icon='lucide-lab:farm' width={24} height={24} />
Approve Manager
Approve Head Area
</Button>
</RequirePermission>
<RequirePermission permissions='lti.expense.approve.unit_vice_president'>
<Button
variant='outline'
color='success'
onClick={bulkApproveClickHandler}
disabled={
!isAllSelectedRowLatestApprovalOnUnitVicePresident
}
className='w-full sm:w-fit'
>
<Icon icon='tdesign:money' width={24} height={24} />
Approve Unit Vice President
</Button>
</RequirePermission>
@@ -622,7 +665,8 @@ const ExpensesTable = () => {
<RequirePermission
permissions={[
'lti.expense.approve.manager',
'lti.expense.approve.head_area',
'lti.expense.approve.unit_vice_president',
'lti.expense.approve.finance',
]}
>
@@ -631,7 +675,8 @@ const ExpensesTable = () => {
color='error'
onClick={bulkRejectClickHandler}
disabled={
!isAllSelectedRowLatestApprovalOnManager &&
!isAllSelectedRowLatestApprovalOnHeadArea &&
!isAllSelectedRowLatestApprovalOnUnitVicePresident &&
!isAllSelectedRowLatestApprovalOnFinance
}
className='w-full sm:w-fit'
@@ -9,7 +9,7 @@ interface RealizationStatusBadgeProps {
const RealizationStatusBadge = ({ approval }: RealizationStatusBadgeProps) => {
const isLatestApprovalRejected = approval?.action === 'REJECTED';
const isExpenseRealized = approval?.step_number && approval.step_number >= 4;
const isExpenseRealized = approval?.step_number && approval.step_number >= 5;
const realizationStatus = isExpenseRealized
? 'Sudah Realisasi'
@@ -7,18 +7,19 @@ type ExpenseFormSchemaType = {
category?: {
value: 'BOP' | 'NON-BOP';
label: 'BOP' | 'NON-BOP';
};
} | null;
location?: {
value: number;
label: string;
};
} | null;
location_id: number;
transaction_date?: string;
kandangs?: { id?: number; name?: string }[];
supplier?: {
value: number;
label: string;
};
} | null;
supplier_id: number;
existing_documents?: { id: number; name: string; url: string }[];
deleted_documents?: number[];
documents?: File[];
@@ -28,7 +29,8 @@ type ExpenseFormSchemaType = {
nonstock?: {
value: number;
label: string;
};
} | null;
nonstock_id?: number;
quantity?: number;
price?: number;
notes?: string;
@@ -41,16 +43,24 @@ export const ExpenseRequestFormSchema: Yup.ObjectSchema<ExpenseFormSchemaType> =
category: Yup.object({
value: Yup.string().oneOf(['BOP', 'NON-BOP']).required(),
label: Yup.string().oneOf(['BOP', 'NON-BOP']).required(),
}).required('Kategori wajib diisi!'),
})
.nullable()
.optional(),
location: Yup.object({
value: Yup.number().min(1).required(),
label: Yup.string().required(),
}).required('Lokasi wajib diisi!'),
})
.nullable()
.optional(),
location_id: Yup.number().min(1).required('Lokasi wajib diisi!'),
location_id: Yup.number()
.required('Lokasi wajib diisi!')
.min(1, 'Lokasi wajib diisi!')
.typeError('Lokasi wajib diisi!'),
transaction_date: Yup.string().required('Tanggal transaksi wajib diisi!'),
kandangs: Yup.array()
.of(
Yup.object({
@@ -63,15 +73,24 @@ export const ExpenseRequestFormSchema: Yup.ObjectSchema<ExpenseFormSchemaType> =
supplier: Yup.object({
value: Yup.number().min(1).required(),
label: Yup.string().required(),
}).required('Vendor wajib diisi!'),
})
.nullable()
.optional(),
existing_documents: Yup.array().of(
supplier_id: Yup.number()
.required('Vendor wajib diisi!')
.min(1, 'Vendor wajib diisi!')
.typeError('Vendor wajib diisi!'),
existing_documents: Yup.array()
.of(
Yup.object({
id: Yup.number().required(),
name: Yup.string().required(),
url: Yup.string().required(),
})
),
)
.optional(),
deleted_documents: Yup.array().of(Yup.number().required()).optional(),
@@ -87,9 +106,17 @@ export const ExpenseRequestFormSchema: Yup.ObjectSchema<ExpenseFormSchemaType> =
nonstock: Yup.object({
value: Yup.number().min(1).required(),
label: Yup.string().required(),
}).required('Nonstock wajib diisi!'),
quantity: Yup.number().required('Total kuantitas wajib diisi!'),
price: Yup.number().required('Harga satuan wajib diisi!'),
}).nullable(),
nonstock_id: Yup.number()
.required('Nonstock wajib diisi!')
.min(1, 'Nonstock wajib diisi!')
.typeError('Nonstock wajib diisi!'),
quantity: Yup.number()
.required('Total kuantitas wajib diisi!')
.typeError('Total kuantitas wajib diisi!'),
price: Yup.number()
.required('Harga satuan wajib diisi!')
.typeError('Harga satuan wajib diisi!'),
notes: Yup.string(),
})
)
@@ -104,7 +131,16 @@ export const ExpenseRequestFormSchema: Yup.ObjectSchema<ExpenseFormSchemaType> =
export const UpdateExpenseRequestFormSchema = ExpenseRequestFormSchema;
export const UploadRequestDocumentsFormSchema = Yup.object({
documents: Yup.array().of(Yup.mixed<File>().required()).required(),
documents: Yup.array()
.of(
Yup.mixed<File>()
.required()
.test('fileSize', 'Ukuran dokumen maksimal 5 MB', (value) => {
if (!value || !(value instanceof File)) return true;
return value.size <= 5 * 1024 * 1024;
})
)
.required(),
});
export type ExpenseRequestFormValues = Yup.InferType<
@@ -124,13 +160,13 @@ export const getExpenseFormInitialValues = (
value: initialValues.category,
label: initialValues.category,
}
: undefined,
: null,
location: initialValues?.location
? {
value: initialValues.location.id,
label: initialValues.location.name,
}
: undefined,
: null,
location_id: Number(initialValues?.location.id || 0),
transaction_date: initialValues?.transaction_date
? formatDate(initialValues.transaction_date, 'YYYY-MM-DD')
@@ -144,7 +180,8 @@ export const getExpenseFormInitialValues = (
value: initialValues.supplier.id,
label: initialValues.supplier.name,
}
: undefined,
: null,
supplier_id: initialValues?.supplier?.id ?? 0,
existing_documents: initialValues?.documents?.map((doc) => {
const path = doc.path.startsWith('/') ? doc.path.slice(1) : doc.path;
return {
@@ -164,12 +201,25 @@ export const getExpenseFormInitialValues = (
value: expenseItem.nonstock.id,
label: expenseItem.nonstock.name,
},
nonstock_id: expenseItem.nonstock.id,
quantity: expenseItem.qty,
price: expenseItem.price,
notes: expenseItem.note,
}))
: [],
}))
: [],
: [
{
cost_items: [
{
nonstock: null,
nonstock_id: 0,
quantity: undefined,
price: undefined,
notes: '',
},
],
},
],
};
};
@@ -37,6 +37,8 @@ import { cn, sleep } from '@/lib/helper';
import { LocationApi, SupplierApi } from '@/services/api/master-data';
import { ACCEPTED_FILE_TYPE } from '@/config/constant';
import { Supplier } from '@/types/api/master-data/supplier';
import { getUniqueFormikErrors } from '@/lib/formik-helper';
import AlertErrorList from '@/components/helper/form/FormErrors';
interface ExpenseFormProps {
type?: 'add' | 'edit' | 'detail';
@@ -55,6 +57,7 @@ const ExpenseRequestForm = ({
const rejectModal = useModal();
const [expenseFormErrorMessage, setExpenseFormErrorMessage] = useState('');
const [formErrorList, setFormErrorList] = useState<string[]>([]);
const createExpenseHandler = useCallback(
async (payload: CreateExpensePayload) => {
@@ -201,7 +204,8 @@ const ExpenseRequestForm = ({
{
cost_items: [
{
nonstock: undefined,
nonstock: null,
nonstock_id: 0,
quantity: undefined,
price: undefined,
notes: '',
@@ -223,7 +227,8 @@ const ExpenseRequestForm = ({
{
cost_items: [
{
nonstock: undefined,
nonstock: null,
nonstock_id: 0,
quantity: undefined,
price: undefined,
notes: '',
@@ -248,7 +253,8 @@ const ExpenseRequestForm = ({
kandang_id: kandangItem.id,
cost_items: existingExpenseNonstock?.cost_items || [
{
nonstock: undefined,
nonstock: null,
nonstock_id: 0,
quantity: undefined,
price: undefined,
notes: '',
@@ -263,10 +269,20 @@ const ExpenseRequestForm = ({
const supplierChangeHandler = (val: OptionType | OptionType[] | null) => {
formik.setFieldTouched('supplier', true);
formik.setFieldValue('supplier', val);
const supplierId = Array.isArray(val) ? val[0]?.value : val?.value;
formik.setFieldValue('supplier_id', supplierId ?? 0);
};
const requestDocumentsChangeHandler = (val: File[]) => {
formik.setFieldTouched('documents', true);
const invalidFiles = val.filter((file) => file.size > 5 * 1024 * 1024);
if (invalidFiles.length > 0) {
toast.error('Ukuran dokumen maksimal 5 MB!');
return;
}
formik.setFieldValue('documents', val);
};
@@ -322,6 +338,22 @@ const ExpenseRequestForm = ({
router.push('/expense');
};
const handleValidateForm = async () => {
const errors = await formik.validateForm();
if (Object.keys(errors).length > 0) {
const errorMessages = getUniqueFormikErrors(errors);
setFormErrorList(errorMessages);
return;
}
};
const handleFormSubmit = (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
handleValidateForm();
formik.handleSubmit(e);
};
useEffect(() => {
formikSetValues(getExpenseFormInitialValues(initialValues));
}, [formikSetValues, getExpenseFormInitialValues, initialValues]);
@@ -347,10 +379,27 @@ const ExpenseRequestForm = ({
</header>
<form
onSubmit={formik.handleSubmit}
onSubmit={handleFormSubmit}
onReset={formik.handleReset}
className='w-full mt-8 flex flex-col gap-6'
>
{expenseFormErrorMessage && (
<div role='alert' className='alert alert-error'>
<Icon
icon='material-symbols:error-outline'
width={24}
height={24}
/>
<span>{expenseFormErrorMessage}</span>
</div>
)}
{formErrorList.length > 0 && (
<AlertErrorList
formErrorList={formErrorList}
onClose={() => setFormErrorList([])}
/>
)}
<div className='grid grid-cols-12 gap-4'>
<SelectInput
label='Kategori'
@@ -535,17 +584,6 @@ const ExpenseRequestForm = ({
</div>
)}
{expenseFormErrorMessage && (
<div role='alert' className='alert alert-error w-full'>
<Icon
icon='material-symbols:error-outline'
width={24}
height={24}
/>
<span>{expenseFormErrorMessage}</span>
</div>
)}
{type !== 'detail' && (
<div
className={cn('flex flex-row justify-end gap-2', {
@@ -560,7 +598,7 @@ const ExpenseRequestForm = ({
type='submit'
color='primary'
isLoading={formik.isSubmitting}
disabled={!formik.isValid || formik.isSubmitting}
disabled={formik.isSubmitting}
className='px-4'
>
Submit
@@ -25,7 +25,7 @@ interface ExpenseRequestKandangDetailExpenseProps {
location?: {
value: number;
label: string;
};
} | null;
className?: {
wrapper?: string;
};
@@ -59,13 +59,20 @@ const ExpenseRequestKandangDetailExpense: React.FC<
`expense_nonstocks[${kandangExpenseIdx}].cost_items[${expenseIdx}].nonstock`,
val
);
const nonstockId = Array.isArray(val) ? val[0]?.value : val?.value;
formik.setFieldValue(
`expense_nonstocks[${kandangExpenseIdx}].cost_items[${expenseIdx}].nonstock_id`,
nonstockId ?? 0
);
};
const addExpenseItemHandler = (kandangExpenseIdx: number) => {
const newExpensesValue = [
...formik.values.expense_nonstocks[kandangExpenseIdx].cost_items,
{
nonstock: undefined,
nonstock: null,
nonstock_id: 0,
price: undefined,
quantity: undefined,
notes: '',
@@ -198,7 +198,7 @@ const ExpensePDF = ({ expense }: ExpensePDFProps) => {
expense?.latest_approval?.action === 'REJECTED';
const isExpenseRealized =
expense?.latest_approval?.step_number &&
expense?.latest_approval.step_number >= 4;
expense?.latest_approval.step_number >= 5;
const realizationStatus = isExpenseRealized
? 'Sudah Realisasi'
@@ -242,8 +242,8 @@ const ExpensePDF = ({ expense }: ExpensePDFProps) => {
{
label: 'Nominal Biaya',
value: formatCurrency(
expense?.latest_approval.step_number === 4 ||
expense?.latest_approval.step_number === 5
expense?.latest_approval.step_number === 5 ||
expense?.latest_approval.step_number === 6
? (expense?.total_realisasi ?? 0)
: (expense?.total_pengajuan ?? 0)
),
@@ -1,7 +1,7 @@
'use client';
import Button from '@/components/Button';
import Card from '@/components/Card';
import AlertErrorList from '@/components/helper/form/FormErrors';
import { FormHeader } from '@/components/helper/form/FormHeader';
import DateInput from '@/components/input/DateInput';
import NumberInput from '@/components/input/NumberInput';
@@ -21,6 +21,7 @@ import {
} from '@/config/constant';
import { isResponseError, isResponseSuccess } from '@/lib/api-helper';
import { formatDate, formatTitleCase } from '@/lib/helper';
import { useFormikErrorList } from '@/services/hooks/useFormikErrorList';
import { FinanceApi } from '@/services/api/finance';
import { BankApi, CustomerApi, SupplierApi } from '@/services/api/master-data';
import {
@@ -104,6 +105,9 @@ const FormFinanceAdd = ({
},
});
// ===== Formik Error List =====
const { formErrorList, close, handleFormSubmit } = useFormikErrorList(formik);
// ===== Options =====
const {
options: partyOptions,
@@ -180,7 +184,7 @@ const FormFinanceAdd = ({
title={`${type === 'add' ? 'Tambah' : 'Ubah'} Data Keuangan`}
backUrl='/finance'
/>
<form className='flex flex-col gap-4' onSubmit={formik.handleSubmit}>
<form className='flex flex-col gap-4' onSubmit={handleFormSubmit}>
<SelectInput
label='Jenis Transaksi'
placeholder='Pilih jenis transaksi'
@@ -384,6 +388,7 @@ const FormFinanceAdd = ({
}
required
/>
<AlertErrorList formErrorList={formErrorList} onClose={close} />
<div className='flex justify-center gap-4'>
<Button
type='reset'
@@ -1,12 +1,10 @@
'use client';
import Button from '@/components/Button';
import AlertErrorList from '@/components/helper/form/FormErrors';
import { FormHeader } from '@/components/helper/form/FormHeader';
import NumberInput from '@/components/input/NumberInput';
import SelectInput, {
OptionType,
useSelect,
} from '@/components/input/SelectInput';
import SelectInput, { useSelect } from '@/components/input/SelectInput';
import TextArea from '@/components/input/TextArea';
import TextInput from '@/components/input/TextInput';
import {
@@ -17,6 +15,7 @@ import {
FINANCE_INITIAL_BALANCE_TYPE_OPTIONS,
FINANCE_PARTY_TYPE_OPTIONS,
} from '@/config/constant';
import { useFormikErrorList } from '@/services/hooks/useFormikErrorList';
import { isResponseError, isResponseSuccess } from '@/lib/api-helper';
import { formatTitleCase } from '@/lib/helper';
import { FinanceApi } from '@/services/api/finance';
@@ -173,6 +172,9 @@ const FormFinanceAddInitialBalance = ({
[router]
);
// ===== Formik Error List =====
const { formErrorList, close, handleFormSubmit } = useFormikErrorList(formik);
return (
<>
<section className='w-full max-w-xl mx-auto'>
@@ -181,7 +183,7 @@ const FormFinanceAddInitialBalance = ({
title={`${type === 'add' ? 'Tambah' : 'Ubah'} Saldo Awal`}
backUrl='/finance'
/>
<form className='flex flex-col gap-4' onSubmit={formik.handleSubmit}>
<form className='flex flex-col gap-4' onSubmit={handleFormSubmit}>
<SelectInput
label='Jenis Pihak'
placeholder='Pilih jenis pihak'
@@ -352,6 +354,7 @@ const FormFinanceAddInitialBalance = ({
}
required
/>
<AlertErrorList formErrorList={formErrorList} onClose={close} />
<div className='flex justify-center gap-4'>
<Button
type='reset'
@@ -1,18 +1,17 @@
'use client';
import Button from '@/components/Button';
import AlertErrorList from '@/components/helper/form/FormErrors';
import { FormHeader } from '@/components/helper/form/FormHeader';
import DateInput from '@/components/input/DateInput';
import NumberInput from '@/components/input/NumberInput';
import SelectInput, {
OptionType,
useSelect,
} from '@/components/input/SelectInput';
import SelectInput, { useSelect } from '@/components/input/SelectInput';
import TextArea from '@/components/input/TextArea';
import {
InjectionFormSchema,
InjectionFormValues,
} from '@/components/pages/finance/add/injection/FormFinanceInjection.schema';
import { useFormikErrorList } from '@/services/hooks/useFormikErrorList';
import { isResponseError, isResponseSuccess } from '@/lib/api-helper';
import { formatDate } from '@/lib/helper';
import { FinanceApi } from '@/services/api/finance';
@@ -128,6 +127,9 @@ const FormFinanceInjection = ({
[router]
);
// ===== Formik Error List =====
const { formErrorList, close, handleFormSubmit } = useFormikErrorList(formik);
return (
<>
<section className='w-full max-w-xl mx-auto'>
@@ -136,7 +138,7 @@ const FormFinanceInjection = ({
title={`${type === 'add' ? 'Tambah' : 'Ubah'} Injeksi Dana`}
backUrl='/finance'
/>
<form className='flex flex-col gap-4' onSubmit={formik.handleSubmit}>
<form className='flex flex-col gap-4' onSubmit={handleFormSubmit}>
<SelectInput
label='Bank'
placeholder='Pilih bank'
@@ -223,6 +225,7 @@ const FormFinanceInjection = ({
}
required
/>
<AlertErrorList formErrorList={formErrorList} onClose={close} />
<div className='flex justify-center gap-4'>
<Button
type='reset'
@@ -15,6 +15,7 @@ import { Icon } from '@iconify/react';
import { ColumnDef, ColumnSort, SortingState } from '@tanstack/react-table';
import { useCallback, useEffect, useState } from 'react';
import useSWR from 'swr';
import { useFormikErrorList } from '@/services/hooks/useFormikErrorList';
const InventoryAdjustmentTable = () => {
const {
@@ -1,26 +1,42 @@
import * as Yup from 'yup';
import { OptionType } from '@/components/input/SelectInput';
export const InventoryAdjustmentFormSchema = Yup.object({
product_category: Yup.object({
value: Yup.number().required('ID Kategori Produk wajib diisi!'),
label: Yup.string().required('Nama Kategori Produk wajib diisi!'),
}).nullable(),
product_category: Yup.mixed<OptionType>()
.nullable()
.test(
'is-valid-option',
'Kategori Produk wajib diisi!',
(value) => value !== null && value !== undefined
),
product_category_id: Yup.number().nullable(),
product: Yup.object({
value: Yup.number().required('ID Produk wajib diisi!'),
label: Yup.string().required('Nama Produk wajib diisi!'),
}).nullable(),
product: Yup.mixed<OptionType>()
.nullable()
.test(
'is-valid-option',
'Produk wajib diisi!',
(value) => value !== null && value !== undefined
),
product_id: Yup.number().nullable(),
product_id: Yup.number()
.nullable()
.required('Produk wajib diisi!')
.min(1, 'Produk wajib diisi!'),
warehouse: Yup.object({
value: Yup.number().required('ID Gudang wajib diisi!'),
label: Yup.string().required('Nama Gudang wajib diisi!'),
}).nullable(),
warehouse: Yup.mixed<OptionType>()
.nullable()
.test(
'is-valid-option',
'Warehouse wajib diisi!',
(value) => value !== null && value !== undefined
),
warehouse_id: Yup.number().nullable(),
warehouse_id: Yup.number()
.nullable()
.required('Warehouse wajib diisi!')
.min(1, 'Warehouse wajib diisi!'),
transaction_type: Yup.string()
.oneOf(['increase', 'decrease'], 'Tipe transaksi tidak valid')
@@ -26,6 +26,8 @@ import SelectInput, { OptionType } from '@/components/input/SelectInput';
import TextInput from '@/components/input/TextInput';
import { RadioGroup } from '@/components/input/RadioInput';
import TextArea from '@/components/input/TextArea';
import { useFormikErrorList } from '@/services/hooks/useFormikErrorList';
import AlertErrorList from '@/components/helper/form/FormErrors';
interface InventoryAdjustmentFormProps {
type?: 'add' | 'edit' | 'detail';
@@ -245,6 +247,9 @@ const InventoryAdjustmentForm = ({
return decimal ? `${formattedInteger}.${decimal}` : formattedInteger;
};
// ===== Formik Error List =====
const { formErrorList, close, handleFormSubmit } = useFormikErrorList(formik);
// Render
return (
<>
@@ -266,7 +271,7 @@ const InventoryAdjustmentForm = ({
</header>
<form
onSubmit={formik.handleSubmit}
onSubmit={handleFormSubmit}
onReset={formik.handleReset}
className='w-full mt-8 flex flex-col gap-6'
>
@@ -390,6 +395,7 @@ const InventoryAdjustmentForm = ({
readOnly={type === 'detail'}
/>
</div>
<AlertErrorList formErrorList={formErrorList} onClose={close} />
<div className='flex flex-row justify-between gap-2 flex-wrap'>
{type !== 'detail' && (
<div className='flex flex-row justify-end gap-2'>
@@ -405,11 +411,7 @@ const InventoryAdjustmentForm = ({
type='submit'
color='primary'
isLoading={formik.isSubmitting}
disabled={
!formik.isValid ||
formik.isSubmitting ||
formik.values.product == undefined
}
disabled={formik.isSubmitting}
className='px-4'
>
Submit
@@ -48,8 +48,8 @@ import DeliveryOrderProductForm from '@/components/pages/marketing/form/repeater
import { SalesOrderProductFormValues } from '@/components/pages/marketing/form/repeater/sales-order/SalesOrderProduct.schema';
import { DeliveryOrderProductFormValues } from '@/components/pages/marketing/form/repeater/delivery-order/DeliverOrderProduct.schema';
import RequirePermission from '@/components/helper/RequirePermission';
import { getUniqueFormikErrors } from '@/lib/formik-helper';
import AlertErrorList from '@/components/helper/form/FormErrors';
import { useFormikErrorList } from '@/services/hooks/useFormikErrorList';
const MemoizedSalesOrderProductTable = memo(SalesOrderProductTable);
const MemoizedSalesOrderProductForm = memo(SalesOrderProductForm);
@@ -219,7 +219,6 @@ const MarketingForm = ({
const [deliveryFormState, setDeliveryFormState] = useState<'add' | 'edit'>(
'add'
);
const [formErrorList, setFormErrorList] = useState<string[]>([]);
const [deliveryOrderValues, setDeliveryOrderValues] = useState<
DeliveryOrderProductFormValues[]
>(
@@ -561,22 +560,8 @@ const MarketingForm = ({
);
}, [memoSalesOrder]);
const handleValidateForm = async () => {
const errors = await formik.validateForm();
if (Object.keys(errors).length > 0) {
// Parse and display errors
const errorMessages = getUniqueFormikErrors(errors);
setFormErrorList(errorMessages);
return; // Stop submission
}
};
const handleFormSubmit = (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
handleValidateForm();
formik.handleSubmit();
};
// ===== Formik Error List =====
const { formErrorList, close, handleFormSubmit } = useFormikErrorList(formik);
return (
<>
@@ -686,13 +671,7 @@ const MarketingForm = ({
</div>
</div>
{/* Error List Alert */}
{formErrorList.length > 0 && (
<AlertErrorList
formErrorList={formErrorList}
onClose={() => setFormErrorList([])}
/>
)}
<AlertErrorList formErrorList={formErrorList} onClose={close} />
{/* Form Actions */}
<div className='flex flex-row items-start justify-center gap-2 mt-4'>
@@ -16,8 +16,8 @@ import Badge from '@/components/Badge';
import { SalesProductToFieldValues } from '@/components/pages/marketing/form/MarketingForm';
import * as Yup from 'yup';
import { isResponseSuccess } from '@/lib/api-helper';
import { getUniqueFormikErrors } from '@/lib/formik-helper';
import AlertErrorList from '@/components/helper/form/FormErrors';
import { useFormikErrorList } from '@/services/hooks/useFormikErrorList';
const DeliveryOrderProductForm = ({
formState,
@@ -42,7 +42,6 @@ const DeliveryOrderProductForm = ({
null
);
const [currentInput, setCurrentInput] = useState<string>('');
const [formErrorList, setFormErrorList] = useState<string[]>([]);
const salesOrder = salesOrders.find(
(item) => item.id === initialValues?.marketing_product_id
@@ -168,21 +167,8 @@ const DeliveryOrderProductForm = ({
}
}, [initialValues]);
const handleValidateForm = () => {
formik.validateForm();
const formErrorList = getUniqueFormikErrors(formik.errors);
setFormErrorList(formErrorList);
if (formErrorList.length > 0) {
return;
}
};
const handleFormSubmit = (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
handleBlurField(currentInput);
handleValidateForm();
formik.handleSubmit(e);
};
// ===== Formik Error List =====
const { formErrorList, close, handleFormSubmit } = useFormikErrorList(formik);
return (
<>
@@ -388,12 +374,7 @@ const DeliveryOrderProductForm = ({
/>
</div>
{formErrorList.length > 0 && (
<AlertErrorList
formErrorList={formErrorList}
onClose={() => setFormErrorList([])}
/>
)}
<AlertErrorList formErrorList={formErrorList} onClose={close} />
<div className='flex flex-row justify-end gap-3 mt-4'>
<Button type='reset' color='warning'>
@@ -24,8 +24,8 @@ import {
} from '@/lib/helper';
import PatternInput from '@/components/input/PatternInput';
import Alert from '@/components/Alert';
import { getUniqueFormikErrors } from '@/lib/formik-helper';
import AlertErrorList from '@/components/helper/form/FormErrors';
import { useFormikErrorList } from '@/services/hooks/useFormikErrorList';
const SalesOrderProductForm = ({
initialValues,
@@ -39,7 +39,6 @@ const SalesOrderProductForm = ({
}) => {
const [formErrorMessage, setFormErrorMessage] = useState('');
const [currentInput, setCurrentInput] = useState<string>('');
const [formErrorList, setFormErrorList] = useState<string[]>([]);
// ============ Formik ============
const formik = useFormik<SalesOrderProductFormValues>({
@@ -172,23 +171,8 @@ const SalesOrderProductForm = ({
}
};
const handleValidateForm = async () => {
const errors = await formik.validateForm();
if (Object.keys(errors).length > 0) {
// Parse and display errors
const errorMessages = getUniqueFormikErrors(errors);
setFormErrorList(errorMessages);
return; // Stop submission
}
};
const handleFormSubmit = (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
handleBlurField(currentInput);
handleValidateForm();
formik.handleSubmit(e);
};
// ===== Formik Error List =====
const { formErrorList, close, handleFormSubmit } = useFormikErrorList(formik);
return (
<>
@@ -356,13 +340,7 @@ const SalesOrderProductForm = ({
/>
</div>
{/* Error List Alert */}
{formErrorList.length > 0 && (
<AlertErrorList
formErrorList={formErrorList}
onClose={() => setFormErrorList([])}
/>
)}
<AlertErrorList formErrorList={formErrorList} onClose={close} />
<div className='flex flex-row justify-end gap-3 mt-4'>
<Button type='reset' color='warning' onClick={handleResetForm}>
@@ -25,6 +25,8 @@ import {
} from '@/types/api/master-data/area';
import { AreaApi } from '@/services/api/master-data';
import { cn } from '@/lib/helper';
import AlertErrorList from '@/components/helper/form/FormErrors';
import { useFormikErrorList } from '@/services/hooks/useFormikErrorList';
interface AreaFormProps {
type?: 'add' | 'edit' | 'detail';
@@ -118,6 +120,9 @@ const AreaForm = ({ type = 'add', initialValues }: AreaFormProps) => {
formikSetValues(formikInitialValues);
}, [formikSetValues, formikInitialValues]);
// ===== Formik Error List =====
const { formErrorList, close, handleFormSubmit } = useFormikErrorList(formik);
return (
<>
<section className='w-full max-w-xl'>
@@ -139,7 +144,7 @@ const AreaForm = ({ type = 'add', initialValues }: AreaFormProps) => {
</header>
<form
onSubmit={formik.handleSubmit}
onSubmit={handleFormSubmit}
onReset={formik.handleReset}
className='w-full mt-8 flex flex-col gap-6'
>
@@ -199,6 +204,8 @@ const AreaForm = ({ type = 'add', initialValues }: AreaFormProps) => {
</div>
)}
<AlertErrorList formErrorList={formErrorList} onClose={close} />
{type !== 'detail' && (
<div
className={cn('flex flex-row justify-end gap-2', {
@@ -213,7 +220,7 @@ const AreaForm = ({ type = 'add', initialValues }: AreaFormProps) => {
type='submit'
color='primary'
isLoading={formik.isSubmitting}
disabled={!formik.isValid || formik.isSubmitting}
disabled={formik.isSubmitting}
className='px-4'
>
Submit
@@ -25,6 +25,8 @@ import {
} from '@/types/api/master-data/bank';
import { BankApi } from '@/services/api/master-data';
import { cn } from '@/lib/helper';
import AlertErrorList from '@/components/helper/form/FormErrors';
import { useFormikErrorList } from '@/services/hooks/useFormikErrorList';
interface BankFormProps {
type?: 'add' | 'edit' | 'detail';
@@ -124,6 +126,9 @@ const BankForm = ({ type = 'add', initialValues }: BankFormProps) => {
formikSetValues(formikInitialValues);
}, [formikSetValues, formikInitialValues]);
// ===== Formik Error List =====
const { formErrorList, close, handleFormSubmit } = useFormikErrorList(formik);
return (
<>
<section className='w-full max-w-xl'>
@@ -145,7 +150,7 @@ const BankForm = ({ type = 'add', initialValues }: BankFormProps) => {
</header>
<form
onSubmit={formik.handleSubmit}
onSubmit={handleFormSubmit}
onReset={formik.handleReset}
className='w-full mt-8 flex flex-col gap-6'
>
@@ -247,6 +252,8 @@ const BankForm = ({ type = 'add', initialValues }: BankFormProps) => {
</div>
)}
<AlertErrorList formErrorList={formErrorList} onClose={close} />
{type !== 'detail' && (
<div
className={cn('flex flex-row justify-end gap-2', {
@@ -261,7 +268,7 @@ const BankForm = ({ type = 'add', initialValues }: BankFormProps) => {
type='submit'
color='primary'
isLoading={formik.isSubmitting}
disabled={!formik.isValid || formik.isSubmitting}
disabled={formik.isSubmitting}
className='px-4'
>
Submit
@@ -28,6 +28,8 @@ import useSWR from 'swr';
import { UserApi } from '@/services/api/user';
import { TYPE_OPTIONS } from '@/config/constant';
import RequirePermission from '@/components/helper/RequirePermission';
import { useFormikErrorList } from '@/services/hooks/useFormikErrorList';
import AlertErrorList from '@/components/helper/form/FormErrors';
interface CustomerFormProps {
formType?: 'add' | 'edit' | 'detail';
@@ -191,6 +193,9 @@ const CustomerForm = ({
formikSetValues(formikInitialValues);
}, [formikSetValues, formikInitialValues]);
// ===== Formik Error List =====
const { formErrorList, close, handleFormSubmit } = useFormikErrorList(formik);
// Render
return (
<>
@@ -213,7 +218,7 @@ const CustomerForm = ({
</header>
<form
onSubmit={formik.handleSubmit}
onSubmit={handleFormSubmit}
onReset={formik.handleReset}
className='w-full mt-8 flex flex-col gap-6'
>
@@ -358,6 +363,8 @@ const CustomerForm = ({
</div>
)}
<AlertErrorList formErrorList={formErrorList} onClose={close} />
{formType !== 'detail' && (
<div
className={cn('flex flex-row justify-end gap-2', {
@@ -372,7 +379,7 @@ const CustomerForm = ({
type='submit'
color='primary'
isLoading={formik.isSubmitting}
disabled={!formik.isValid || formik.isSubmitting}
disabled={formik.isSubmitting}
className='px-4'
>
Submit
@@ -26,6 +26,8 @@ import {
} from '@/types/api/master-data/fcr';
import { FcrApi } from '@/services/api/master-data';
import { cn } from '@/lib/helper';
import AlertErrorList from '@/components/helper/form/FormErrors';
import { useFormikErrorList } from '@/services/hooks/useFormikErrorList';
interface FcrFormProps {
type?: 'add' | 'edit' | 'detail';
@@ -158,6 +160,9 @@ const FcrForm = ({ type = 'add', initialValues }: FcrFormProps) => {
formikSetValues(formikInitialValues);
}, [formikSetValues, formikInitialValues]);
// ===== Formik Error List =====
const { formErrorList, close, handleFormSubmit } = useFormikErrorList(formik);
return (
<>
<section className='w-full max-w-5xl'>
@@ -179,7 +184,7 @@ const FcrForm = ({ type = 'add', initialValues }: FcrFormProps) => {
</header>
<form
onSubmit={formik.handleSubmit}
onSubmit={handleFormSubmit}
onReset={formik.handleReset}
className='w-full mt-8 flex flex-col gap-6'
>
@@ -294,6 +299,8 @@ const FcrForm = ({ type = 'add', initialValues }: FcrFormProps) => {
)}
</div>
<AlertErrorList formErrorList={formErrorList} onClose={close} />
<div className='flex flex-row justify-between gap-2 flex-wrap'>
{type !== 'add' && (
<div className='flex flex-row justify-start gap-2'>
@@ -349,7 +356,7 @@ const FcrForm = ({ type = 'add', initialValues }: FcrFormProps) => {
type='submit'
color='primary'
isLoading={formik.isSubmitting}
disabled={!formik.isValid || formik.isSubmitting}
disabled={formik.isSubmitting}
className='px-4'
>
Submit
@@ -17,6 +17,8 @@ import TextInput from '@/components/input/TextInput';
import { cn } from '@/lib/helper';
import ConfirmationModal from '@/components/modal/ConfirmationModal';
import RequirePermission from '@/components/helper/RequirePermission';
import AlertErrorList from '@/components/helper/form/FormErrors';
import { useFormikErrorList } from '@/services/hooks/useFormikErrorList';
interface FlockCustomProps {
formType?: 'add' | 'edit' | 'detail';
@@ -86,6 +88,9 @@ const FlockForm = ({ formType = 'add', initialValues }: FlockCustomProps) => {
formikSetValues(formikInitialValue);
}, [formikSetValues, formikInitialValue]);
// ===== Formik Error List =====
const { formErrorList, close, handleFormSubmit } = useFormikErrorList(formik);
// Render
return (
<>
@@ -107,7 +112,7 @@ const FlockForm = ({ formType = 'add', initialValues }: FlockCustomProps) => {
</h1>
</header>
<form
onSubmit={formik.handleSubmit}
onSubmit={handleFormSubmit}
onReset={formik.handleReset}
className='w-full mt-8 flex flex-col gap-6'
>
@@ -168,6 +173,8 @@ const FlockForm = ({ formType = 'add', initialValues }: FlockCustomProps) => {
</div>
)}
<AlertErrorList formErrorList={formErrorList} onClose={close} />
{formType !== 'detail' && (
<div
className={cn('flex flex-row justify-end gap-2', {
@@ -182,7 +189,7 @@ const FlockForm = ({ formType = 'add', initialValues }: FlockCustomProps) => {
type='submit'
color='primary'
isLoading={formik.isSubmitting}
disabled={!formik.isValid || formik.isSubmitting}
disabled={formik.isSubmitting}
className='px-4'
>
Submit
@@ -29,6 +29,8 @@ import { LocationApi, KandangApi } from '@/services/api/master-data';
import { cn } from '@/lib/helper';
import { UserApi } from '@/services/api/user';
import NumberInput from '@/components/input/NumberInput';
import { useFormikErrorList } from '@/services/hooks/useFormikErrorList';
import AlertErrorList from '@/components/helper/form/FormErrors';
interface KandangFormProps {
type?: 'add' | 'edit' | 'detail';
@@ -198,6 +200,9 @@ const KandangForm = ({ type = 'add', initialValues }: KandangFormProps) => {
formikSetValues(formikInitialValues);
}, [formikSetValues, formikInitialValues]);
// ===== Formik Error List =====
const { formErrorList, close, handleFormSubmit } = useFormikErrorList(formik);
return (
<>
<section className='w-full max-w-xl'>
@@ -219,7 +224,7 @@ const KandangForm = ({ type = 'add', initialValues }: KandangFormProps) => {
</header>
<form
onSubmit={formik.handleSubmit}
onSubmit={handleFormSubmit}
onReset={formik.handleReset}
className='w-full mt-8 flex flex-col gap-6'
>
@@ -324,6 +329,8 @@ const KandangForm = ({ type = 'add', initialValues }: KandangFormProps) => {
</div>
)}
<AlertErrorList formErrorList={formErrorList} onClose={close} />
{type !== 'detail' && (
<div
className={cn('flex flex-row justify-end gap-2', {
@@ -338,7 +345,7 @@ const KandangForm = ({ type = 'add', initialValues }: KandangFormProps) => {
type='submit'
color='primary'
isLoading={formik.isSubmitting}
disabled={!formik.isValid || formik.isSubmitting}
disabled={formik.isSubmitting}
className='px-4'
>
Submit
@@ -27,6 +27,8 @@ import {
} from '@/types/api/master-data/location';
import { AreaApi, LocationApi } from '@/services/api/master-data';
import { cn } from '@/lib/helper';
import { useFormikErrorList } from '@/services/hooks/useFormikErrorList';
import AlertErrorList from '@/components/helper/form/FormErrors';
interface LocationFormProps {
type?: 'add' | 'edit' | 'detail';
@@ -160,6 +162,9 @@ const LocationForm = ({ type = 'add', initialValues }: LocationFormProps) => {
formikSetValues(formikInitialValues);
}, [formikSetValues, formikInitialValues]);
// ===== Formik Error List =====
const { formErrorList, close, handleFormSubmit } = useFormikErrorList(formik);
return (
<>
<section className='w-full max-w-xl'>
@@ -181,7 +186,7 @@ const LocationForm = ({ type = 'add', initialValues }: LocationFormProps) => {
</header>
<form
onSubmit={formik.handleSubmit}
onSubmit={handleFormSubmit}
onReset={formik.handleReset}
className='w-full mt-8 flex flex-col gap-6'
>
@@ -268,6 +273,8 @@ const LocationForm = ({ type = 'add', initialValues }: LocationFormProps) => {
</div>
)}
<AlertErrorList formErrorList={formErrorList} onClose={close} />
{type !== 'detail' && (
<div
className={cn('flex flex-row justify-end gap-2', {
@@ -282,7 +289,7 @@ const LocationForm = ({ type = 'add', initialValues }: LocationFormProps) => {
type='submit'
color='primary'
isLoading={formik.isSubmitting}
disabled={!formik.isValid || formik.isSubmitting}
disabled={formik.isSubmitting}
className='px-4'
>
Submit
@@ -29,6 +29,8 @@ import { NonstockApi, SupplierApi, UomApi } from '@/services/api/master-data';
import { cn } from '@/lib/helper';
import { flags } from '@/types/api/api-general';
import { SUPPLIER_FLAG_OPTIONS } from '@/config/constant';
import { useFormikErrorList } from '@/services/hooks/useFormikErrorList';
import AlertErrorList from '@/components/helper/form/FormErrors';
interface NonstockFormProps {
type?: 'add' | 'edit' | 'detail';
@@ -213,6 +215,9 @@ const NonstockForm = ({ type = 'add', initialValues }: NonstockFormProps) => {
formikSetValues(formikInitialValues);
}, [formikSetValues, formikInitialValues]);
// ===== Formik Error List =====
const { formErrorList, close, handleFormSubmit } = useFormikErrorList(formik);
return (
<>
<section className='w-full max-w-xl'>
@@ -234,7 +239,7 @@ const NonstockForm = ({ type = 'add', initialValues }: NonstockFormProps) => {
</header>
<form
onSubmit={formik.handleSubmit}
onSubmit={handleFormSubmit}
onReset={formik.handleReset}
className='w-full mt-8 flex flex-col gap-6'
>
@@ -337,6 +342,8 @@ const NonstockForm = ({ type = 'add', initialValues }: NonstockFormProps) => {
</div>
)}
<AlertErrorList formErrorList={formErrorList} onClose={close} />
{type !== 'detail' && (
<div
className={cn('flex flex-row justify-end gap-2', {
@@ -351,7 +358,7 @@ const NonstockForm = ({ type = 'add', initialValues }: NonstockFormProps) => {
type='submit'
color='primary'
isLoading={formik.isSubmitting}
disabled={!formik.isValid || formik.isSubmitting}
disabled={formik.isSubmitting}
className='px-4'
>
Submit
@@ -11,7 +11,6 @@ import TextInput from '@/components/input/TextInput';
import { useModal } from '@/components/Modal';
import ConfirmationModal from '@/components/modal/ConfirmationModal';
import RequirePermission from '@/components/helper/RequirePermission';
import { getUniqueFormikErrors } from '@/lib/formik-helper';
import AlertErrorList from '@/components/helper/form/FormErrors';
import {
@@ -27,6 +26,7 @@ import {
} from '@/types/api/master-data/product-category';
import { ProductCategoryApi } from '@/services/api/master-data';
import { cn } from '@/lib/helper';
import { useFormikErrorList } from '@/services/hooks/useFormikErrorList';
interface ProductCategoryFormProps {
type?: 'add' | 'edit' | 'detail';
@@ -41,7 +41,6 @@ const ProductCategoryForm = ({
const deleteModal = useModal();
const [formErrorMessage, setFormErrorMessage] = useState('');
const [formErrorList, setFormErrorList] = useState<string[]>([]);
const [isDeleteLoading, setIsDeleteLoading] = useState(false);
const createProductCategoryHandler = useCallback(
@@ -132,21 +131,8 @@ const ProductCategoryForm = ({
formikSetValues(formikInitialValues);
}, [formikSetValues, formikInitialValues]);
const handleValidateForm = async () => {
const errors = await formik.validateForm();
if (Object.keys(errors).length > 0) {
const errorMessages = getUniqueFormikErrors(errors);
setFormErrorList(errorMessages);
return;
}
};
const handleFormSubmit = (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
handleValidateForm();
formik.handleSubmit(e);
};
// ===== Formik Error List =====
const { formErrorList, close, handleFormSubmit } = useFormikErrorList(formik);
return (
<>
@@ -184,13 +170,7 @@ const ProductCategoryForm = ({
</div>
)}
{/* Error List Alert */}
{formErrorList.length > 0 && (
<AlertErrorList
formErrorList={formErrorList}
onClose={() => setFormErrorList([])}
/>
)}
<AlertErrorList formErrorList={formErrorList} onClose={close} />
<div className='flex flex-col gap-4'>
<TextInput
@@ -39,6 +39,7 @@ import {
} from '@/services/api/master-data';
import { cn } from '@/lib/helper';
import { PRODUCT_FLAG_OPTIONS } from '@/config/constant';
import { useFormikErrorList } from '@/services/hooks/useFormikErrorList';
interface ProductFormProps {
type?: 'add' | 'edit' | 'detail';
@@ -50,7 +51,6 @@ const ProductForm = ({ type = 'add', initialValues }: ProductFormProps) => {
const deleteModal = useModal();
const [productFormErrorMessage, setProductFormErrorMessage] = useState('');
const [formErrorList, setFormErrorList] = useState<string[]>([]);
const [isDeleteLoading, setIsDeleteLoading] = useState(false);
const createProductHandler = useCallback(
@@ -204,21 +204,8 @@ const ProductForm = ({ type = 'add', initialValues }: ProductFormProps) => {
formikSetValues(formikInitialValues);
}, [formikSetValues, formikInitialValues]);
const handleValidateForm = async () => {
const errors = await formik.validateForm();
if (Object.keys(errors).length > 0) {
const errorMessages = getUniqueFormikErrors(errors);
setFormErrorList(errorMessages);
return;
}
};
const handleFormSubmit = (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
handleValidateForm();
formik.handleSubmit(e);
};
// ===== Formik Error List =====
const { formErrorList, close, handleFormSubmit } = useFormikErrorList(formik);
return (
<>
@@ -254,13 +241,7 @@ const ProductForm = ({ type = 'add', initialValues }: ProductFormProps) => {
</div>
)}
{/* Error List Alert */}
{formErrorList.length > 0 && (
<AlertErrorList
formErrorList={formErrorList}
onClose={() => setFormErrorList([])}
/>
)}
<AlertErrorList formErrorList={formErrorList} onClose={close} />
<div className='grid grid-cols-1 gap-4'>
<TextInput
@@ -9,6 +9,7 @@ import {
ProductionStandardRepeaterFormSchemaValues,
ProductionStandardFormValues,
createProductionStandardRepeaterFormSchema,
ProductionStandardFormSchema,
} from '@/components/pages/master-data/production-standard/form/ProductionStandardForm.schema';
import Table, { TABLE_DEFAULT_STYLING } from '@/components/Table';
import { FLOCK_CATEGORY_OPTIONS } from '@/config/constant';
@@ -31,6 +32,8 @@ import { useModal } from '@/components/Modal';
import RequirePermission from '@/components/helper/RequirePermission';
import Tooltip from '@/components/Tooltip';
import Alert from '@/components/Alert';
import { useFormikErrorList } from '@/services/hooks/useFormikErrorList';
import AlertErrorList from '@/components/helper/form/FormErrors';
type TableRowsType = {
customRow: boolean;
@@ -207,6 +210,7 @@ const ProductionStandardForm = ({
initialValues: formikInitialValues as ProductionStandardFormValues,
// Only enable reinitialize for edit/detail mode, not add mode
enableReinitialize: formType !== 'add',
validationSchema: ProductionStandardFormSchema,
onSubmit: (values) => {
switch (formType) {
case 'add':
@@ -723,7 +727,8 @@ const ProductionStandardForm = ({
router.push('/master-data/production-standard');
};
// ===== Function =====
// ===== Formik Error List =====
const { formErrorList, close, handleFormSubmit } = useFormikErrorList(formik);
return (
<>
@@ -1210,9 +1215,26 @@ const ProductionStandardForm = ({
return null;
}}
/>
<AlertErrorList formErrorList={formErrorList} onClose={close} />
{productionStandardFormErrorMessage && (
<Alert color='error' className='w-full'>
<div className='flex items-center gap-2 stretch'>
<Icon icon='mdi:alert' />
<span>{productionStandardFormErrorMessage}</span>
</div>
<Icon
icon='mdi:close'
onClick={() => setProductionStandardFormErrorMessage('')}
className='ms-auto'
/>
</Alert>
)}
<form
className='flex justify-between mt-6 gap-2 flex-wrap'
onSubmit={formik.handleSubmit}
onSubmit={handleFormSubmit}
>
{formType === 'detail' && (
<div className='gap-2 flex items-center'>
@@ -1293,19 +1315,6 @@ const ProductionStandardForm = ({
</div>
)}
</form>
{productionStandardFormErrorMessage && (
<Alert color='error' className='w-full'>
<div className='flex items-center gap-2 stretch'>
<Icon icon='mdi:alert' />
<span>{productionStandardFormErrorMessage}</span>
</div>
<Icon
icon='mdi:close'
onClick={() => setProductionStandardFormErrorMessage('')}
className='ms-auto'
/>
</Alert>
)}
</div>
<ConfirmationModal
@@ -25,6 +25,8 @@ import TextArea from '@/components/input/TextArea';
import { cn } from '@/lib/helper';
import ConfirmationModal from '@/components/modal/ConfirmationModal';
import RequirePermission from '@/components/helper/RequirePermission';
import { useFormikErrorList } from '@/services/hooks/useFormikErrorList';
import AlertErrorList from '@/components/helper/form/FormErrors';
interface SupplierCustomProps {
formType?: 'add' | 'edit' | 'detail';
@@ -199,6 +201,9 @@ const SupplierForm = ({
formik.setFieldValue('category', val);
};
// ===== Formik Error List =====
const { formErrorList, close, handleFormSubmit } = useFormikErrorList(formik);
// Render
return (
<>
@@ -221,7 +226,7 @@ const SupplierForm = ({
</header>
<form
onSubmit={formik.handleSubmit}
onSubmit={handleFormSubmit}
onReset={formik.handleReset}
className='w-full mt-8 flex flex-col gap-6'
>
@@ -444,6 +449,8 @@ const SupplierForm = ({
</div>
)}
<AlertErrorList formErrorList={formErrorList} onClose={close} />
{formType !== 'detail' && (
<div
className={cn('flex flex-row justify-end gap-2', {
@@ -458,7 +465,7 @@ const SupplierForm = ({
type='submit'
color='primary'
isLoading={formik.isSubmitting}
disabled={!formik.isValid || formik.isSubmitting}
disabled={formik.isSubmitting}
className='px-4'
>
Submit
@@ -25,6 +25,8 @@ import {
} from '@/types/api/master-data/uom';
import { UomApi } from '@/services/api/master-data';
import { cn } from '@/lib/helper';
import { useFormikErrorList } from '@/services/hooks/useFormikErrorList';
import AlertErrorList from '@/components/helper/form/FormErrors';
interface UomFormProps {
type?: 'add' | 'edit' | 'detail';
@@ -118,6 +120,9 @@ const UomForm = ({ type = 'add', initialValues }: UomFormProps) => {
formikSetValues(formikInitialValues);
}, [formikSetValues, formikInitialValues]);
// ===== Formik Error List =====
const { formErrorList, close, handleFormSubmit } = useFormikErrorList(formik);
return (
<>
<section className='w-full max-w-xl'>
@@ -139,7 +144,7 @@ const UomForm = ({ type = 'add', initialValues }: UomFormProps) => {
</header>
<form
onSubmit={formik.handleSubmit}
onSubmit={handleFormSubmit}
onReset={formik.handleReset}
className='w-full mt-8 flex flex-col gap-6'
>
@@ -199,6 +204,8 @@ const UomForm = ({ type = 'add', initialValues }: UomFormProps) => {
</div>
)}
<AlertErrorList formErrorList={formErrorList} onClose={close} />
{type !== 'detail' && (
<div
className={cn('flex flex-row justify-end gap-2', {
@@ -213,7 +220,7 @@ const UomForm = ({ type = 'add', initialValues }: UomFormProps) => {
type='submit'
color='primary'
isLoading={formik.isSubmitting}
disabled={!formik.isValid || formik.isSubmitting}
disabled={formik.isSubmitting}
className='px-4'
>
Submit
@@ -33,6 +33,8 @@ import {
} from '@/services/api/master-data';
import { cn } from '@/lib/helper';
import { WAREHOUSE_TYPE_OPTIONS } from '@/config/constant';
import { useFormikErrorList } from '@/services/hooks/useFormikErrorList';
import AlertErrorList from '@/components/helper/form/FormErrors';
interface WarehouseFormProps {
type?: 'add' | 'edit' | 'detail';
@@ -323,6 +325,9 @@ const WarehouseForm = ({ type = 'add', initialValues }: WarehouseFormProps) => {
formikSetValues(formikInitialValues);
}, [formikSetValues, formikInitialValues]);
// ===== Formik Error List =====
const { formErrorList, close, handleFormSubmit } = useFormikErrorList(formik);
return (
<>
<section className='w-full max-w-xl'>
@@ -344,7 +349,7 @@ const WarehouseForm = ({ type = 'add', initialValues }: WarehouseFormProps) => {
</header>
<form
onSubmit={formik.handleSubmit}
onSubmit={handleFormSubmit}
onReset={formik.handleReset}
className='w-full mt-8 flex flex-col gap-6'
>
@@ -474,6 +479,8 @@ const WarehouseForm = ({ type = 'add', initialValues }: WarehouseFormProps) => {
</div>
)}
<AlertErrorList formErrorList={formErrorList} onClose={close} />
{type !== 'detail' && (
<div
className={cn('flex flex-row justify-end gap-2', {
@@ -488,7 +495,7 @@ const WarehouseForm = ({ type = 'add', initialValues }: WarehouseFormProps) => {
type='submit'
color='primary'
isLoading={formik.isSubmitting}
disabled={!formik.isValid || formik.isSubmitting}
disabled={formik.isSubmitting}
className='px-4'
>
Submit
@@ -209,20 +209,6 @@ const ProjectFlockDetail = ({
</Badge>
</div>
{/* <div className='col-span-1 flex flex-row items-center text-gray-400 font-semibold gap-2'>
<Icon width={14} height={14} icon={'mdi:clock'} /> History
</div>
<div className='col-span-2'>
<Button variant='outline' className='py-1 text-sm'>
See History{' '}
<Icon
icon='mdi:arrow-top-right-thin'
width={11}
height={11}
/>
</Button>
</div> */}
{/* BARIS 1 */}
<div
className='col-span-1 flex flex-row items-center text-gray-400 font-semibold gap-2
@@ -252,6 +238,18 @@ const ProjectFlockDetail = ({
</div>
<div className='col-span-2'>{projectFlock?.fcr?.name}</div>
<div
className='col-span-1 flex flex-row items-center text-gray-400 font-semibold gap-2
relative
before:content-[""] before:absolute before:left-[5px] before:top-[90%] before:bottom-[-100%] before:w-[1px] before:border-1 before:border-dashed before:border-gray-400'
>
<Icon width={14} height={14} icon='mdi:circle-slice-8' />{' '}
Standard
</div>
<div className='col-span-2'>
{projectFlock?.production_standard?.name ?? '-'}
</div>
{/* BARIS 3 (Terakhir - TIDAK PERLU garis di bawahnya) */}
<div className='col-span-1 flex flex-row items-center text-gray-400 font-semibold gap-2'>
<Icon width={14} height={14} icon='mdi:circle-slice-8' />{' '}
@@ -6,7 +6,6 @@ import SelectInput, {
useSelect,
} from '@/components/input/SelectInput';
import { isResponseError, isResponseSuccess } from '@/lib/api-helper';
import { getUniqueFormikErrors } from '@/lib/formik-helper';
import AlertErrorList from '@/components/helper/form/FormErrors';
import {
AreaApi,
@@ -47,6 +46,7 @@ import { Nonstock } from '@/types/api/master-data/nonstock';
import { useUiStore } from '@/stores/ui/ui.store';
import RequirePermission from '@/components/helper/RequirePermission';
import DrawerHeader from '@/components/helper/drawer/DrawerHeader';
import { useFormikErrorList } from '@/services/hooks/useFormikErrorList';
interface ProjectFlockFormProps {
formType?: 'add' | 'edit' | 'detail';
@@ -66,7 +66,6 @@ const ProjectFlockForm = ({
const [projectFlockFormErrorMessage, setProjectFlockFormErrorMessage] =
useState('');
const [formErrorList, setFormErrorList] = useState<string[]>([]);
const [selectedArea, setSelectedArea] = useState('');
const [selectedLocation, setSelectedLocation] = useState('');
const [selectedCategory, setSelectedCategory] = useState('');
@@ -642,16 +641,8 @@ const ProjectFlockForm = ({
return !isNonstockAlreadyInBudgets;
});
const handleValidateForm = async () => {
const errors = await formik.validateForm();
if (Object.keys(errors).length > 0) {
// Parse and display errors
const errorMessages = getUniqueFormikErrors(errors);
setFormErrorList(errorMessages);
return; // Stop submission
}
};
// ===== Formik Error List =====
const { formErrorList, close, handleFormSubmit } = useFormikErrorList(formik);
return (
<>
@@ -712,11 +703,7 @@ const ProjectFlockForm = ({
<form
className='w-auto h-auto'
onSubmit={(e) => {
e.preventDefault();
handleValidateForm();
formik.handleSubmit(e);
}}
onSubmit={handleFormSubmit}
onReset={formik.handleReset}
>
{/* Form Informasi Umum */}
@@ -1082,13 +1069,7 @@ const ProjectFlockForm = ({
</div>
</div>
{/* Error List Alert */}
{formErrorList.length > 0 && (
<AlertErrorList
formErrorList={formErrorList}
onClose={() => setFormErrorList([])}
/>
)}
<AlertErrorList formErrorList={formErrorList} onClose={close} />
<div className='flex flex-row justify-center gap-2 flex-wrap my-6 px-4'>
{formType !== 'detail' && (
@@ -1737,16 +1737,16 @@ const RecordingForm = ({ type = 'add', initialValues }: RecordingFormProps) => {
<td className='py-3 font-medium'>Egg Mass</td>
<td className='text-center py-3'>
<span className='font-semibold'>
{initialValues.egg_mesh &&
initialValues.egg_mesh > 0
? formatNumber(initialValues.egg_mesh)
{initialValues.egg_mass &&
initialValues.egg_mass > 0
? formatNumber(initialValues.egg_mass)
: '-'}
</span>
</td>
<td className='text-center py-3 text-gray-600'>
{initialValues.egg_mesh_std &&
initialValues.egg_mesh_std > 0
? formatNumber(initialValues.egg_mesh_std)
{initialValues.egg_mass_std &&
initialValues.egg_mass_std > 0
? formatNumber(initialValues.egg_mass_std)
: '-'}
</td>
</tr>
@@ -1773,16 +1773,16 @@ const RecordingForm = ({ type = 'add', initialValues }: RecordingFormProps) => {
<td className='py-3 font-medium'>Hen Day</td>
<td className='text-center py-3'>
<span className='font-semibold'>
{initialValues.hand_day &&
initialValues.hand_day > 0
? formatNumber(initialValues.hand_day)
{initialValues.hen_day &&
initialValues.hen_day > 0
? formatNumber(initialValues.hen_day)
: '-'}
</span>
</td>
<td className='text-center py-3 text-gray-600'>
{initialValues.hand_day_std !== undefined &&
initialValues.hand_day_std > 0
? `${initialValues.hand_day_std}%`
{initialValues.hen_day_std !== undefined &&
initialValues.hen_day_std > 0
? `${initialValues.hen_day_std}%`
: '-'}
</td>
</tr>
@@ -1790,16 +1790,16 @@ const RecordingForm = ({ type = 'add', initialValues }: RecordingFormProps) => {
<td className='py-3 font-medium'>Hen House</td>
<td className='text-center py-3'>
<span className='font-semibold'>
{initialValues.hand_house &&
initialValues.hand_house > 0
? formatNumber(initialValues.hand_house)
{initialValues.hen_house &&
initialValues.hen_house > 0
? formatNumber(initialValues.hen_house)
: '-'}
</span>
</td>
<td className='text-center py-3 text-gray-600'>
{initialValues.hand_house_std !== undefined &&
initialValues.hand_house_std > 0
? `${initialValues.hand_house_std}%`
{initialValues.hen_house_std !== undefined &&
initialValues.hen_house_std > 0
? `${initialValues.hen_house_std}%`
: '-'}
</td>
</tr>
@@ -0,0 +1,30 @@
'use client';
import Tabs from '@/components/Tabs';
import CustomerPaymentTab from '@/components/pages/report/finance/tab/CustomerPaymentTab';
import DebtSupplierTab from '@/components/pages/report/finance/tab/DebtSupplierTab';
const FinanceTabs = () => {
const tabs = [
{
id: '1',
label: 'Kontrol Pembayaran Customer',
content: <CustomerPaymentTab />,
},
{
id: '2',
label: 'Rekapitulasi Hutang Ke Supplier',
content: <DebtSupplierTab />,
},
];
return (
<section className='w-full p-4'>
<Tabs tabs={tabs} variant='lifted' />
</section>
);
};
export default FinanceTabs;
@@ -0,0 +1,425 @@
'use client';
import {
Page,
Text,
View,
Document,
StyleSheet,
Font,
pdf,
} from '@react-pdf/renderer';
import { formatDate, formatCurrency, formatNumber } from '@/lib/helper';
import { CustomerPaymentReport } from '@/types/api/report/customer-payment';
Font.register({
family: 'Helvetica',
src: 'helvetica',
});
const pdfStyles = StyleSheet.create({
page: {
fontSize: 10,
fontFamily: 'Helvetica',
padding: 20,
backgroundColor: '#FFFFFF',
},
titleSection: {
marginBottom: 10,
},
mainTitle: {
fontSize: 14,
fontWeight: 'bold',
marginBottom: 5,
color: '#1f74bf',
},
supplierTitle: {
fontSize: 12,
fontWeight: 'bold',
marginBottom: 8,
color: '#1f74bf',
},
supplierInfo: {
fontSize: 9,
marginBottom: 5,
color: '#333333',
},
table: {
borderWidth: 1,
borderColor: '#000000',
marginBottom: 15,
},
tableRow: {
flexDirection: 'row',
},
tableHeader: {
backgroundColor: '#F5F5F5',
},
tableCell: {
flex: 1,
borderRightWidth: 1,
borderRightColor: '#000000',
borderRightStyle: 'solid',
padding: 4,
fontSize: 7,
textAlign: 'left',
},
tableCellNo: {
flex: 0.5,
borderRightWidth: 1,
borderRightColor: '#000000',
borderRightStyle: 'solid',
padding: 4,
fontSize: 7,
textAlign: 'center',
},
tableCellLast: {
flex: 1,
padding: 4,
fontSize: 7,
},
tableCellHeader: {
flex: 1,
borderRightWidth: 1,
borderRightColor: '#000000',
borderRightStyle: 'solid',
padding: 4,
fontSize: 7,
fontWeight: 'bold',
backgroundColor: '#F5F5F5',
borderBottomWidth: 1,
borderBottomColor: '#000000',
borderBottomStyle: 'solid',
paddingVertical: 12,
textAlign: 'center',
},
tableCellHeaderRight: {
flex: 1,
borderRightWidth: 1,
borderRightColor: '#000000',
borderRightStyle: 'solid',
padding: 4,
fontSize: 7,
fontWeight: 'bold',
backgroundColor: '#F5F5F5',
textAlign: 'right',
borderBottomWidth: 1,
borderBottomColor: '#000000',
borderBottomStyle: 'solid',
paddingVertical: 12,
},
tableCellRight: {
flex: 1,
borderRightWidth: 1,
borderRightColor: '#000000',
borderRightStyle: 'solid',
padding: 4,
fontSize: 7,
textAlign: 'right',
},
tableCellCenter: {
flex: 1,
borderRightWidth: 1,
borderRightColor: '#000000',
borderRightStyle: 'solid',
padding: 4,
fontSize: 7,
textAlign: 'center',
},
tableBorderBottom: {
borderBottomWidth: 1,
borderBottomColor: '#000000',
borderBottomStyle: 'solid',
},
summaryRow: {
backgroundColor: '#F0F0F0',
fontWeight: 'bold',
},
});
interface CustomerPaymentExportPDFParams {
data: CustomerPaymentReport[];
}
const createPDFDocument = (params: CustomerPaymentExportPDFParams) => {
return (
<Document>
{params.data.map((customerReport, customerIndex) => (
<Page
key={customerIndex}
size='A4'
orientation='landscape'
style={pdfStyles.page}
>
{/* Title and Customer Info */}
<View style={pdfStyles.titleSection}>
<Text style={pdfStyles.mainTitle}>
Laporan &gt; Kontrol Pembayaran Customer
</Text>
<Text style={pdfStyles.supplierTitle}>
{customerReport.customer.name}
</Text>
<Text style={pdfStyles.supplierInfo}>
{customerReport.customer_address || ''}
</Text>
<Text style={pdfStyles.supplierInfo}>
NPWP: {customerReport.customer_npwp || '-'}
</Text>
{customerReport.summary && (
<Text style={pdfStyles.supplierInfo}>
Total Saldo Piutang:{' '}
{formatCurrency(
customerReport.summary.total_accounts_receivable
)}
</Text>
)}
</View>
{/* Table */}
<View style={pdfStyles.table}>
{/* Table Header */}
<View style={[pdfStyles.tableRow, pdfStyles.tableHeader]}>
<View style={[pdfStyles.tableCellHeader, { flex: 0.5 }]}>
<Text>No</Text>
</View>
<View style={[pdfStyles.tableCellHeader, { flex: 1.2 }]}>
<Text>Tgl DO/Bayar</Text>
</View>
<View style={[pdfStyles.tableCellHeader, { flex: 1.2 }]}>
<Text>Tgl Realisasi</Text>
</View>
<View style={[pdfStyles.tableCellHeader, { flex: 0.8 }]}>
<Text>Aging</Text>
</View>
<View style={[pdfStyles.tableCellHeader, { flex: 1 }]}>
<Text>Referensi</Text>
</View>
<View style={[pdfStyles.tableCellHeader, { flex: 1.2 }]}>
<Text>No. Polisi</Text>
</View>
<View style={[pdfStyles.tableCellHeaderRight, { flex: 0.8 }]}>
<Text>Qty</Text>
</View>
<View style={[pdfStyles.tableCellHeaderRight, { flex: 1 }]}>
<Text>Berat (Kg)</Text>
</View>
<View style={[pdfStyles.tableCellHeaderRight, { flex: 0.8 }]}>
<Text>AVG</Text>
</View>
<View style={[pdfStyles.tableCellHeaderRight, { flex: 1.2 }]}>
<Text>Harga Awal</Text>
</View>
<View style={[pdfStyles.tableCellHeaderRight, { flex: 1 }]}>
<Text>CN</Text>
</View>
<View style={[pdfStyles.tableCellHeaderRight, { flex: 1.2 }]}>
<Text>Harga Akhir</Text>
</View>
<View style={[pdfStyles.tableCellHeaderRight, { flex: 0.8 }]}>
<Text>PPN (%)</Text>
</View>
<View style={[pdfStyles.tableCellHeaderRight, { flex: 1.2 }]}>
<Text>Total</Text>
</View>
<View style={[pdfStyles.tableCellHeaderRight, { flex: 1.2 }]}>
<Text>Pembayaran</Text>
</View>
<View style={[pdfStyles.tableCellHeaderRight, { flex: 1.2 }]}>
<Text>Saldo Piutang</Text>
</View>
<View style={[pdfStyles.tableCellHeader, { flex: 1.5 }]}>
<Text>Ket</Text>
</View>
<View style={[pdfStyles.tableCellHeader, { flex: 1 }]}>
<Text>Pengambilan</Text>
</View>
<View style={[pdfStyles.tableCellHeader, { flex: 1.5 }]}>
<Text>Sales</Text>
</View>
</View>
{/* Table Body */}
{customerReport.rows.map((item, index) => (
<View
key={index}
style={[
pdfStyles.tableRow,
index < customerReport.rows.length - 1
? pdfStyles.tableBorderBottom
: {},
]}
>
<View style={[pdfStyles.tableCellNo, { flex: 0.5 }]}>
<Text>{index + 1}</Text>
</View>
<View style={[pdfStyles.tableCellCenter, { flex: 1.2 }]}>
<Text>
{item.do_date ? formatDate(item.do_date, 'DD MMM YY') : '-'}
</Text>
</View>
<View style={[pdfStyles.tableCellCenter, { flex: 1.2 }]}>
<Text>
{item.realization_date
? formatDate(item.realization_date, 'DD MMM YY')
: '-'}
</Text>
</View>
<View style={[pdfStyles.tableCellCenter, { flex: 0.8 }]}>
<Text>{formatNumber(item.aging)} hari</Text>
</View>
<View style={[pdfStyles.tableCell, { flex: 1 }]}>
<Text>{item.reference || '-'}</Text>
</View>
<View style={[pdfStyles.tableCell, { flex: 1.2 }]}>
<Text>{item.vehicle_plate || '-'}</Text>
</View>
<View style={[pdfStyles.tableCellRight, { flex: 0.8 }]}>
<Text>{formatNumber(item.qty)}</Text>
</View>
<View style={[pdfStyles.tableCellRight, { flex: 1 }]}>
<Text>{formatNumber(item.weight)}</Text>
</View>
<View style={[pdfStyles.tableCellRight, { flex: 0.8 }]}>
<Text>{formatNumber(item.average_weight)}</Text>
</View>
<View style={[pdfStyles.tableCellRight, { flex: 1.2 }]}>
<Text>{formatCurrency(item.price)}</Text>
</View>
<View style={[pdfStyles.tableCellRight, { flex: 1 }]}>
<Text>{formatCurrency(item.credit_note)}</Text>
</View>
<View style={[pdfStyles.tableCellRight, { flex: 1.2 }]}>
<Text>{formatCurrency(item.final_price)}</Text>
</View>
<View style={[pdfStyles.tableCellRight, { flex: 0.8 }]}>
<Text>{formatNumber(item.ppn)}%</Text>
</View>
<View style={[pdfStyles.tableCellRight, { flex: 1.2 }]}>
<Text>{formatCurrency(item.total)}</Text>
</View>
<View style={[pdfStyles.tableCellRight, { flex: 1.2 }]}>
<Text>{formatCurrency(item.payment)}</Text>
</View>
<View style={[pdfStyles.tableCellRight, { flex: 1.2 }]}>
<Text>{formatCurrency(item.accounts_receivable)}</Text>
</View>
<View style={[pdfStyles.tableCell, { flex: 1.5 }]}>
<Text>{item.notes || '-'}</Text>
</View>
<View style={[pdfStyles.tableCell, { flex: 1 }]}>
<Text>{item.pickup_info || '-'}</Text>
</View>
<View style={[pdfStyles.tableCell, { flex: 1.5 }]}>
<Text>{item.sales_marketing || '-'}</Text>
</View>
</View>
))}
{/* Summary Row */}
{customerReport.summary && (
<View style={[pdfStyles.tableRow, pdfStyles.summaryRow]}>
<View style={[pdfStyles.tableCellNo, { flex: 0.5 }]}>
<Text>Total</Text>
</View>
<View style={[pdfStyles.tableCell, { flex: 1.2 }]}>
<Text></Text>
</View>
<View style={[pdfStyles.tableCell, { flex: 1.2 }]}>
<Text></Text>
</View>
<View style={[pdfStyles.tableCell, { flex: 0.8 }]}>
<Text></Text>
</View>
<View style={[pdfStyles.tableCell, { flex: 1 }]}>
<Text></Text>
</View>
<View style={[pdfStyles.tableCell, { flex: 1.2 }]}>
<Text></Text>
</View>
<View style={[pdfStyles.tableCellRight, { flex: 0.8 }]}>
<Text>{formatNumber(customerReport.summary.total_qty)}</Text>
</View>
<View style={[pdfStyles.tableCellRight, { flex: 1 }]}>
<Text>
{formatNumber(customerReport.summary.total_weight)}
</Text>
</View>
<View style={[pdfStyles.tableCellRight, { flex: 0.8 }]}>
<Text></Text>
</View>
<View style={[pdfStyles.tableCellRight, { flex: 1.2 }]}>
<Text>
{formatCurrency(
customerReport.summary.total_initial_amount
)}
</Text>
</View>
<View style={[pdfStyles.tableCellRight, { flex: 1 }]}>
<Text>
{formatCurrency(customerReport.summary.total_credit_note)}
</Text>
</View>
<View style={[pdfStyles.tableCellRight, { flex: 1.2 }]}>
<Text>
{formatCurrency(customerReport.summary.total_final_amount)}
</Text>
</View>
<View style={[pdfStyles.tableCellRight, { flex: 0.8 }]}>
<Text></Text>
</View>
<View style={[pdfStyles.tableCellRight, { flex: 1.2 }]}>
<Text>
{formatCurrency(customerReport.summary.total_grand_amount)}
</Text>
</View>
<View style={[pdfStyles.tableCellRight, { flex: 1.2 }]}>
<Text>
{formatCurrency(customerReport.summary.total_payment)}
</Text>
</View>
<View style={[pdfStyles.tableCellRight, { flex: 1.2 }]}>
<Text>
{formatCurrency(
customerReport.summary.total_accounts_receivable
)}
</Text>
</View>
<View style={[pdfStyles.tableCell, { flex: 1.5 }]}>
<Text></Text>
</View>
<View style={[pdfStyles.tableCell, { flex: 1 }]}>
<Text></Text>
</View>
<View style={[pdfStyles.tableCellLast, { flex: 1.5 }]}>
<Text></Text>
</View>
</View>
)}
</View>
</Page>
))}
</Document>
);
};
export const generateCustomerPaymentPDF = async (
params: CustomerPaymentExportPDFParams
): Promise<void> => {
const PDFDocument = createPDFDocument(params);
try {
const blob = await pdf(PDFDocument).toBlob();
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = `laporan-kontrol-pembayaran-customer-${formatDate(new Date(), 'YYYY-MM-DD-HHmm')}.pdf`;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(url);
} catch (error) {
throw error;
}
};
@@ -0,0 +1,115 @@
'use client';
import * as XLSX from 'xlsx';
import { formatDate, formatCurrency, formatNumber } from '@/lib/helper';
import { CustomerPaymentReport } from '@/types/api/report/customer-payment';
interface CustomerPaymentExportExcelParams {
data: CustomerPaymentReport[];
}
export const generateCustomerPaymentExcel = (
params: CustomerPaymentExportExcelParams
): void => {
if (!params.data || params.data.length === 0) {
return;
}
const workbook = XLSX.utils.book_new();
params.data.forEach((customerReport) => {
const customerData = customerReport.rows;
const customerName = customerReport.customer.name || 'Unknown Customer';
const excelData: { [key: string]: string | number }[] = customerData.map(
(item, index) => ({
No: index + 1,
'Tanggal DO/Bayar': item.do_date
? formatDate(item.do_date, 'DD MMM YYYY')
: '',
'Tanggal Realisasi': item.realization_date
? formatDate(item.realization_date, 'DD MMM YYYY')
: '',
Aging: formatNumber(item.aging || 0),
Referensi: item.reference || '',
'Nomor Polisi': item.vehicle_plate || '',
'Ekor/Qty': formatNumber(item.qty || 0),
'Berat (Kg)': formatNumber(item.weight || 0),
AVG: formatNumber(item.average_weight || 0),
'Harga Awal': formatCurrency(item.price || 0),
CN: formatCurrency(item.credit_note || 0),
'Harga Akhir': formatCurrency(item.final_price || 0),
'PPN (%)': formatNumber(item.ppn || 0),
Total: formatCurrency(item.total || 0),
Pembayaran: formatCurrency(item.payment || 0),
'Saldo Piutang': formatCurrency(item.accounts_receivable || 0),
Keterangan: item.notes || '',
Pengambilan: item.pickup_info || '',
'Sales/Marketing': item.sales_marketing || '',
})
);
if (customerReport.summary) {
excelData.push({
No: 'Total',
'Tanggal DO/Bayar': '',
'Tanggal Realisasi': '',
Aging: '',
Referensi: '',
'Nomor Polisi': '',
'Ekor/Qty': formatNumber(customerReport.summary.total_qty || 0),
'Berat (Kg)': formatNumber(customerReport.summary.total_weight || 0),
AVG: '',
'Harga Awal': formatCurrency(
customerReport.summary.total_initial_amount || 0
),
CN: formatCurrency(customerReport.summary.total_credit_note || 0),
'Harga Akhir': formatCurrency(
customerReport.summary.total_final_amount || 0
),
'PPN (%)': '',
Total: formatCurrency(customerReport.summary.total_grand_amount || 0),
Pembayaran: formatCurrency(customerReport.summary.total_payment || 0),
'Saldo Piutang': formatCurrency(
customerReport.summary.total_accounts_receivable || 0
),
Keterangan: '',
Pengambilan: '',
'Sales/Marketing': '',
});
}
const worksheet = XLSX.utils.json_to_sheet(excelData);
const colWidths = [
{ wch: 5 }, // No
{ wch: 15 }, // Tanggal DO/Bayar
{ wch: 15 }, // Tanggal Realisasi
{ wch: 8 }, // Aging
{ wch: 12 }, // Referensi
{ wch: 15 }, // Nomor Polisi
{ wch: 10 }, // Ekor/Qty
{ wch: 12 }, // Berat
{ wch: 10 }, // AVG
{ wch: 15 }, // Harga Awal
{ wch: 10 }, // CN
{ wch: 15 }, // Harga Akhir
{ wch: 10 }, // PPN
{ wch: 15 }, // Total
{ wch: 15 }, // Pembayaran
{ wch: 15 }, // Saldo Piutang
{ wch: 20 }, // Keterangan
{ wch: 15 }, // Pengambilan
{ wch: 20 }, // Sales/Marketing
];
worksheet['!cols'] = colWidths;
const sheetName =
customerName.length > 31 ? customerName.substring(0, 31) : customerName;
XLSX.utils.book_append_sheet(workbook, worksheet, sheetName);
});
const filename = `laporan-kontrol-pembayaran-customer-dicetak-pada-${formatDate(new Date(), 'YYYY-MM-DD-HHmm')}.xlsx`;
XLSX.writeFile(workbook, filename);
};
@@ -0,0 +1,363 @@
'use client';
import {
Page,
Text,
View,
Document,
StyleSheet,
Font,
pdf,
} from '@react-pdf/renderer';
import { formatDate, formatCurrency, formatNumber } from '@/lib/helper';
import { DebtSupplier } from '@/types/api/report/debt-supplier';
Font.register({
family: 'Helvetica',
src: 'helvetica',
});
const pdfStyles = StyleSheet.create({
page: {
fontSize: 10,
fontFamily: 'Helvetica',
padding: 20,
backgroundColor: '#FFFFFF',
},
titleSection: {
marginBottom: 10,
},
mainTitle: {
fontSize: 14,
fontWeight: 'bold',
marginBottom: 5,
color: '#1f74bf',
},
supplierTitle: {
fontSize: 12,
fontWeight: 'bold',
marginBottom: 8,
color: '#1f74bf',
},
supplierInfo: {
fontSize: 9,
marginBottom: 5,
color: '#333333',
},
table: {
borderWidth: 1,
borderColor: '#000000',
marginBottom: 15,
},
tableRow: {
flexDirection: 'row',
},
tableHeader: {
backgroundColor: '#F5F5F5',
},
tableCell: {
flex: 1,
borderRightWidth: 1,
borderRightColor: '#000000',
borderRightStyle: 'solid',
padding: 4,
fontSize: 7,
textAlign: 'left',
},
tableCellNo: {
flex: 0.5,
borderRightWidth: 1,
borderRightColor: '#000000',
borderRightStyle: 'solid',
padding: 4,
fontSize: 7,
textAlign: 'center',
},
tableCellLast: {
flex: 1,
padding: 4,
fontSize: 7,
},
tableCellHeader: {
flex: 1,
borderRightWidth: 1,
borderRightColor: '#000000',
borderRightStyle: 'solid',
padding: 4,
fontSize: 7,
fontWeight: 'bold',
backgroundColor: '#F5F5F5',
borderBottomWidth: 1,
borderBottomColor: '#000000',
borderBottomStyle: 'solid',
paddingVertical: 12,
textAlign: 'center',
},
tableCellHeaderRight: {
flex: 1,
borderRightWidth: 1,
borderRightColor: '#000000',
borderRightStyle: 'solid',
padding: 4,
fontSize: 7,
fontWeight: 'bold',
backgroundColor: '#F5F5F5',
textAlign: 'right',
borderBottomWidth: 1,
borderBottomColor: '#000000',
borderBottomStyle: 'solid',
paddingVertical: 12,
},
tableCellRight: {
flex: 1,
borderRightWidth: 1,
borderRightColor: '#000000',
borderRightStyle: 'solid',
padding: 4,
fontSize: 7,
textAlign: 'right',
},
tableCellCenter: {
flex: 1,
borderRightWidth: 1,
borderRightColor: '#000000',
borderRightStyle: 'solid',
padding: 4,
fontSize: 7,
textAlign: 'center',
},
tableBorderBottom: {
borderBottomWidth: 1,
borderBottomColor: '#000000',
borderBottomStyle: 'solid',
},
summaryRow: {
backgroundColor: '#F0F0F0',
fontWeight: 'bold',
},
});
interface DebtSupplierExportPDFParams {
data: DebtSupplier[];
}
const createPDFDocument = (params: DebtSupplierExportPDFParams) => {
return (
<Document>
{params.data.map((supplierReport, supplierIndex) => (
<Page
key={supplierIndex}
size='A4'
orientation='landscape'
style={pdfStyles.page}
>
{/* Title and Supplier Info */}
<View style={pdfStyles.titleSection}>
<Text style={pdfStyles.mainTitle}>
Laporan &gt; Hutang Supplier
</Text>
<Text style={pdfStyles.supplierTitle}>
{supplierReport.supplier.name}
</Text>
</View>
{/* Table */}
<View style={pdfStyles.table}>
{/* Table Header */}
<View style={[pdfStyles.tableRow, pdfStyles.tableHeader]}>
<View style={[pdfStyles.tableCellHeader, { flex: 0.5 }]}>
<Text>No</Text>
</View>
<View style={[pdfStyles.tableCellHeader, { flex: 1 }]}>
<Text>No. PR</Text>
</View>
<View style={[pdfStyles.tableCellHeader, { flex: 1 }]}>
<Text>No. PO</Text>
</View>
<View style={[pdfStyles.tableCellHeader, { flex: 1 }]}>
<Text>Tgl PR</Text>
</View>
<View style={[pdfStyles.tableCellHeader, { flex: 1 }]}>
<Text>Tgl PO</Text>
</View>
<View style={[pdfStyles.tableCellHeader, { flex: 0.8 }]}>
<Text>Aging</Text>
</View>
<View style={[pdfStyles.tableCellHeader, { flex: 1 }]}>
<Text>Area</Text>
</View>
<View style={[pdfStyles.tableCellHeader, { flex: 1 }]}>
<Text>Gudang</Text>
</View>
<View style={[pdfStyles.tableCellHeader, { flex: 1 }]}>
<Text>Tgl Jatuh Tempo</Text>
</View>
<View style={[pdfStyles.tableCellHeader, { flex: 1 }]}>
<Text>Status JT</Text>
</View>
<View style={[pdfStyles.tableCellHeaderRight, { flex: 1.2 }]}>
<Text>Total Harga</Text>
</View>
<View style={[pdfStyles.tableCellHeaderRight, { flex: 1.2 }]}>
<Text>Pembayaran</Text>
</View>
<View style={[pdfStyles.tableCellHeaderRight, { flex: 1.2 }]}>
<Text>Hutang</Text>
</View>
<View style={[pdfStyles.tableCellHeader, { flex: 1 }]}>
<Text>Status</Text>
</View>
<View style={[pdfStyles.tableCellHeader, { flex: 1 }]}>
<Text>No. Perjalanan</Text>
</View>
</View>
{/* Table Body */}
{supplierReport.rows.map((item, index) => (
<View
key={index}
style={[
pdfStyles.tableRow,
index < supplierReport.rows.length - 1
? pdfStyles.tableBorderBottom
: {},
]}
>
<View style={[pdfStyles.tableCellNo, { flex: 0.5 }]}>
<Text>{index + 1}</Text>
</View>
<View style={[pdfStyles.tableCell, { flex: 1 }]}>
<Text>{item.pr_number || '-'}</Text>
</View>
<View style={[pdfStyles.tableCell, { flex: 1 }]}>
<Text>{item.po_number || '-'}</Text>
</View>
<View style={[pdfStyles.tableCellCenter, { flex: 1 }]}>
<Text>
{item.pr_date ? formatDate(item.pr_date, 'DD MMM YY') : '-'}
</Text>
</View>
<View style={[pdfStyles.tableCellCenter, { flex: 1 }]}>
<Text>
{item.po_date ? formatDate(item.po_date, 'DD MMM YY') : '-'}
</Text>
</View>
<View style={[pdfStyles.tableCellCenter, { flex: 0.8 }]}>
<Text>{formatNumber(item.aging)} Hari</Text>
</View>
<View style={[pdfStyles.tableCell, { flex: 1 }]}>
<Text>{item.area?.name || '-'}</Text>
</View>
<View style={[pdfStyles.tableCell, { flex: 1 }]}>
<Text>{item.warehouse?.name || '-'}</Text>
</View>
<View style={[pdfStyles.tableCellCenter, { flex: 1 }]}>
<Text>
{item.due_date
? formatDate(item.due_date, 'DD MMM YY')
: '-'}
</Text>
</View>
<View style={[pdfStyles.tableCell, { flex: 1 }]}>
<Text>{item.due_status || '-'}</Text>
</View>
<View style={[pdfStyles.tableCellRight, { flex: 1.2 }]}>
<Text>{formatCurrency(item.total_price)}</Text>
</View>
<View style={[pdfStyles.tableCellRight, { flex: 1.2 }]}>
<Text>{formatCurrency(item.payment_price)}</Text>
</View>
<View style={[pdfStyles.tableCellRight, { flex: 1.2 }]}>
<Text>{formatCurrency(item.debt_price)}</Text>
</View>
<View style={[pdfStyles.tableCell, { flex: 1 }]}>
<Text>{item.status || '-'}</Text>
</View>
<View style={[pdfStyles.tableCell, { flex: 1 }]}>
<Text>{item.travel_number || '-'}</Text>
</View>
</View>
))}
{/* Summary Row */}
{supplierReport.total && (
<View style={[pdfStyles.tableRow, pdfStyles.summaryRow]}>
<View style={[pdfStyles.tableCellNo, { flex: 0.5 }]}>
<Text>Total</Text>
</View>
<View style={[pdfStyles.tableCell, { flex: 1 }]}>
<Text></Text>
</View>
<View style={[pdfStyles.tableCell, { flex: 1 }]}>
<Text></Text>
</View>
<View style={[pdfStyles.tableCell, { flex: 1 }]}>
<Text></Text>
</View>
<View style={[pdfStyles.tableCell, { flex: 1 }]}>
<Text></Text>
</View>
<View style={[pdfStyles.tableCellCenter, { flex: 0.8 }]}>
<Text>{formatNumber(supplierReport.total.aging)} Hari</Text>
</View>
<View style={[pdfStyles.tableCell, { flex: 1 }]}>
<Text></Text>
</View>
<View style={[pdfStyles.tableCell, { flex: 1 }]}>
<Text></Text>
</View>
<View style={[pdfStyles.tableCell, { flex: 1 }]}>
<Text></Text>
</View>
<View style={[pdfStyles.tableCell, { flex: 1 }]}>
<Text></Text>
</View>
<View style={[pdfStyles.tableCellRight, { flex: 1.2 }]}>
<Text>
{formatCurrency(supplierReport.total.total_price)}
</Text>
</View>
<View style={[pdfStyles.tableCellRight, { flex: 1.2 }]}>
<Text>
{formatCurrency(supplierReport.total.payment_price)}
</Text>
</View>
<View style={[pdfStyles.tableCellRight, { flex: 1.2 }]}>
<Text>{formatCurrency(supplierReport.total.debt_price)}</Text>
</View>
<View style={[pdfStyles.tableCell, { flex: 1 }]}>
<Text></Text>
</View>
<View style={[pdfStyles.tableCellLast, { flex: 1 }]}>
<Text></Text>
</View>
</View>
)}
</View>
</Page>
))}
</Document>
);
};
export const generateDebtSupplierPDF = async (
params: DebtSupplierExportPDFParams
): Promise<void> => {
const PDFDocument = createPDFDocument(params);
try {
const blob = await pdf(PDFDocument).toBlob();
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = `laporan-hutang-supplier-${formatDate(new Date(), 'YYYY-MM-DD-HHmm')}.pdf`;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(url);
} catch (error) {
throw error;
}
};
@@ -0,0 +1,101 @@
'use client';
import * as XLSX from 'xlsx';
import { formatDate, formatCurrency, formatNumber } from '@/lib/helper';
import { DebtSupplier } from '@/types/api/report/debt-supplier';
interface DebtSupplierExportExcelParams {
data: DebtSupplier[];
}
export const generateDebtSupplierExcel = (
params: DebtSupplierExportExcelParams
): void => {
if (!params.data || params.data.length === 0) {
return;
}
const workbook = XLSX.utils.book_new();
params.data.forEach((supplierReport) => {
const supplierData = supplierReport.rows;
const supplierName = supplierReport.supplier.name || 'Unknown Supplier';
const excelData: { [key: string]: string | number }[] = supplierData.map(
(item, index) => ({
No: index + 1,
'Nomor PR': item.pr_number || '',
'Nomor PO': item.po_number || '',
'Tanggal PR': item.pr_date
? formatDate(item.pr_date, 'DD MMM YYYY')
: '',
'Tanggal PO': item.po_date
? formatDate(item.po_date, 'DD MMM YYYY')
: '',
'Aging (Hari)': formatNumber(item.aging || 0),
Area: item.area?.name || '',
Gudang: item.warehouse?.name || '',
'Tanggal Jatuh Tempo': item.due_date
? formatDate(item.due_date, 'DD MMM YYYY')
: '',
'Status Jatuh Tempo': item.due_status || '',
'Total Harga': formatCurrency(item.total_price || 0),
'Harga Pembayaran': formatCurrency(item.payment_price || 0),
'Harga Hutang': formatCurrency(item.debt_price || 0),
Status: item.status || '',
'Nomor Perjalanan': item.travel_number || '',
})
);
if (supplierReport.total) {
excelData.push({
No: 'Total',
'Nomor PR': '',
'Nomor PO': '',
'Tanggal PR': '',
'Tanggal PO': '',
'Aging (Hari)': formatNumber(supplierReport.total.aging || 0),
Area: '',
Gudang: '',
'Tanggal Jatuh Tempo': '',
'Status Jatuh Tempo': '',
'Total Harga': formatCurrency(supplierReport.total.total_price || 0),
'Harga Pembayaran': formatCurrency(
supplierReport.total.payment_price || 0
),
'Harga Hutang': formatCurrency(supplierReport.total.debt_price || 0),
Status: '',
'Nomor Perjalanan': '',
});
}
const worksheet = XLSX.utils.json_to_sheet(excelData);
const colWidths = [
{ wch: 5 }, // No
{ wch: 15 }, // Nomor PR
{ wch: 15 }, // Nomor PO
{ wch: 15 }, // Tanggal PR
{ wch: 15 }, // Tanggal PO
{ wch: 12 }, // Aging
{ wch: 15 }, // Area
{ wch: 15 }, // Gudang
{ wch: 18 }, // Tanggal Jatuh Tempo
{ wch: 18 }, // Status Jatuh Tempo
{ wch: 15 }, // Total Harga
{ wch: 15 }, // Harga Pembayaran
{ wch: 15 }, // Harga Hutang
{ wch: 12 }, // Status
{ wch: 15 }, // Nomor Perjalanan
];
worksheet['!cols'] = colWidths;
const sheetName =
supplierName.length > 31 ? supplierName.substring(0, 31) : supplierName;
XLSX.utils.book_append_sheet(workbook, worksheet, sheetName);
});
const filename = `laporan-hutang-supplier-${formatDate(new Date(), 'YYYY-MM-DD-HHmm')}.xlsx`;
XLSX.writeFile(workbook, filename);
};
@@ -0,0 +1,717 @@
import { useState, useMemo, useCallback } from 'react';
import useSWR from 'swr';
import { Icon } from '@iconify/react';
import Card from '@/components/Card';
import SelectInput, {
useSelect,
OptionType,
} from '@/components/input/SelectInput';
import DateInput from '@/components/input/DateInput';
import { CustomerApi } from '@/services/api/master-data';
import { FinanceApi } from '@/services/api/report/finance-report';
import Table from '@/components/Table';
import { ColumnDef } from '@tanstack/react-table';
import { formatCurrency, formatDate, formatNumber } from '@/lib/helper';
import {
CustomerPaymentReport,
CustomerPaymentSummary,
} from '@/types/api/report/customer-payment';
import { isResponseSuccess } from '@/lib/api-helper';
import Pagination from '@/components/Pagination';
import Button from '@/components/Button';
import Dropdown from '@/components/Dropdown';
import MenuItem from '@/components/menu/MenuItem';
import Menu from '@/components/menu/Menu';
import Modal from '@/components/Modal';
import { useModal } from '@/components/Modal';
import toast from 'react-hot-toast';
import { generateCustomerPaymentExcel } from '@/components/pages/report/finance/export/CustomerPaymentExportXLSX';
import { generateCustomerPaymentPDF } from '@/components/pages/report/finance/export/CustomerPaymentExportPDF';
const CustomerPaymentTab = () => {
// ===== STATE MANAGEMENT =====
const [isPdfExportLoading, setIsPdfExportLoading] = useState(false);
const [isExcelExportLoading, setIsExcelExportLoading] = useState(false);
const isAnyExportLoading = isPdfExportLoading || isExcelExportLoading;
// ===== PAGINATION STATE =====
const [currentPage, setCurrentPage] = useState(1);
const [pageSize, setPageSize] = useState(10);
// ===== SUBMISSION STATE =====
const [isSubmitted, setIsSubmitted] = useState(false);
// ===== FILTER STATE =====
const [filterCustomer, setFilterCustomer] = useState<OptionType[]>([]);
const [filterSales, setFilterSales] = useState<OptionType[]>([]);
const [filterStartDate, setFilterStartDate] = useState('');
const [filterEndDate, setFilterEndDate] = useState('');
const [filterErrors, setFilterErrors] = useState<Record<string, string>>({});
const filterModal = useModal();
const { options: customerOptions, isLoadingOptions: isLoadingCustomers } =
useSelect(CustomerApi.basePath, 'id', 'name', 'search');
const salesOptions = useMemo(
() => [
{ value: 'Sales A', label: 'Sales A' },
{ value: 'Sales B', label: 'Sales B' },
{ value: 'Sales C', label: 'Sales C' },
// TODO: Fetch sales options from API
],
[]
);
const dataTypeOptions = useMemo(
() => [{ value: 'do_date', label: 'Tanggal Jual' }],
[]
);
// ===== FILTER HANDLERS =====
const handleResetFilters = useCallback(() => {
setIsSubmitted(false);
setFilterCustomer([]);
setFilterSales([]);
setFilterStartDate('');
setFilterEndDate('');
setFilterErrors({});
}, []);
const handleApplyFilters = useCallback(() => {
const errors: Record<string, string> = {};
if (!filterStartDate) {
errors.start_date = 'Tanggal mulai wajib diisi';
}
if (!filterEndDate) {
errors.end_date = 'Tanggal akhir wajib diisi';
}
setFilterErrors(errors);
if (Object.keys(errors).length === 0) {
setIsSubmitted(true);
setCurrentPage(1);
filterModal.closeModal();
}
}, [filterModal, filterStartDate, filterEndDate]);
// ===== DATA FETCHING =====
const { data: customerPayment, isLoading } = useSWR(
isSubmitted
? () => {
const params = {
customer_id:
filterCustomer.length > 0
? filterCustomer.map((v) => String(v.value)).join(',')
: undefined,
sales:
filterSales.length > 0
? filterSales.map((v) => String(v.value)).join(',')
: undefined,
filter_by: 'do_date' as const,
start_date: filterStartDate || undefined,
end_date: filterEndDate || undefined,
page: currentPage,
limit: pageSize,
};
return ['customer-payment-report', params];
}
: null,
([, params]) =>
FinanceApi.getCustomerPaymentReport(
params.customer_id,
params.sales,
params.filter_by,
params.start_date,
params.end_date,
params.page,
params.limit
)
);
const data: CustomerPaymentReport[] = useMemo(
() =>
isResponseSuccess(customerPayment)
? (customerPayment?.data as unknown as CustomerPaymentReport[]) || []
: [],
[customerPayment]
);
const meta =
isResponseSuccess(customerPayment) && customerPayment?.meta
? customerPayment.meta
: null;
// ===== EXPORT DATA FETCHER =====
const customerPaymentExport = useCallback(async (): Promise<
CustomerPaymentReport[] | null
> => {
const params = {
customer_id:
filterCustomer.length > 0
? filterCustomer.map((v) => String(v.value)).join(',')
: undefined,
sales:
filterSales.length > 0
? filterSales.map((v) => String(v.value)).join(',')
: undefined,
filter_by: 'do_date' as const,
start_date: filterStartDate || undefined,
end_date: filterEndDate || undefined,
limit: 100,
page: 1,
};
const response = await FinanceApi.getCustomerPaymentReport(
params.customer_id,
params.sales,
params.filter_by,
params.start_date,
params.end_date,
params.page,
params.limit
);
return isResponseSuccess(response)
? (response.data as unknown as CustomerPaymentReport[])
: null;
}, [filterCustomer, filterSales, filterStartDate, filterEndDate]);
// ===== EXPORT HANDLERS =====
const handleExportExcel = useCallback(async () => {
setIsExcelExportLoading(true);
try {
const allDataForExport = await customerPaymentExport();
if (
!allDataForExport ||
!Array.isArray(allDataForExport) ||
allDataForExport.length === 0
) {
toast.error('Tidak ada data untuk diekspor.');
return;
}
generateCustomerPaymentExcel({ data: allDataForExport });
toast.success('Excel berhasil dibuat dan diunduh.');
} catch {
toast.error('Gagal membuat Excel. Silakan coba lagi.');
} finally {
setIsExcelExportLoading(false);
}
}, [customerPaymentExport]);
const handleExportPdf = useCallback(async () => {
setIsPdfExportLoading(true);
try {
const allDataForExport = await customerPaymentExport();
if (
!allDataForExport ||
!Array.isArray(allDataForExport) ||
allDataForExport.length === 0
) {
toast.error('Tidak ada data untuk diekspor.');
return;
}
await generateCustomerPaymentPDF({ data: allDataForExport });
toast.success('PDF berhasil dibuat dan diunduh.');
} catch {
toast.error('Gagal membuat PDF. Silakan coba lagi.');
} finally {
setIsPdfExportLoading(false);
}
}, [customerPaymentExport]);
// ===== PAGINATION HANDLERS =====
const handlePageChange = (page: number) => {
setCurrentPage(page);
};
const handleRowChange = (pageSize: number) => {
setPageSize(pageSize);
};
const handleNextPage = () => {
if (meta && currentPage < meta.total_pages) {
setCurrentPage(currentPage + 1);
}
};
const handlePrevPage = () => {
if (currentPage > 1) {
setCurrentPage(currentPage - 1);
}
};
const getTableColumns = (
summary: CustomerPaymentSummary
): ColumnDef<CustomerPaymentReport['rows'][0]>[] => {
const tableColumns: ColumnDef<CustomerPaymentReport['rows'][0]>[] = [
{
id: 'no',
header: 'No',
cell: (props) => props.row.index + 1,
footer: () => <div className='font-semibold text-gray-900'>Total</div>,
},
{
id: 'do_date_or_payment_date',
header: 'Tanggal DO/Bayar',
accessorKey: 'do_date',
cell: (props) => {
const value = props.row.original.do_date;
return formatDate(value, 'DD MMM YYYY');
},
},
{
id: 'realization_date',
header: 'Tanggal Realisasi',
accessorKey: 'realization_date',
cell: (props) => {
const value = props.row.original.realization_date;
return formatDate(value, 'DD MMM YYYY');
},
},
{
id: 'aging',
header: 'Aging',
accessorKey: 'aging',
cell: (props) => {
const value = props.row.original.aging;
return <div className='text-center'>{formatNumber(value)} hari</div>;
},
},
{
id: 'reference',
header: 'Referensi',
accessorKey: 'reference',
cell: (props) => {
const value = props.row.original.reference;
return value || '-';
},
},
{
id: 'vehicle_plate',
header: 'Nomor Polisi',
accessorKey: 'vehicle_plate',
cell: (props) => {
const value = props.row.original.vehicle_plate;
return value || '-';
},
},
{
id: 'qty',
header: 'Ekor/Qty',
accessorKey: 'qty',
cell: (props) => {
const value = props.row.original.qty;
return <div className='text-right'>{formatNumber(value)}</div>;
},
footer: () => (
<div className='text-right font-semibold text-gray-900'>
{formatNumber(summary.total_qty) || '-'}
</div>
),
},
{
id: 'weight',
header: 'Berat (Kg)',
accessorKey: 'weight',
cell: (props) => {
const value = props.row.original.weight;
return <div className='text-right'>{formatNumber(value)}</div>;
},
footer: () => (
<div className='text-right font-semibold text-gray-900'>
{formatNumber(summary.total_weight) || '-'}
</div>
),
},
{
id: 'average_weight',
header: 'AVG',
accessorKey: 'average_weight',
cell: (props) => {
const value = props.row.original.average_weight;
return <div className='text-right'>{formatNumber(value)}</div>;
},
footer: () => (
<div className='text-right font-semibold text-gray-900'>-</div>
),
},
{
id: 'price',
header: 'Harga Awal',
accessorKey: 'price',
cell: (props) => {
const value = props.row.original.price;
return <div className='text-right'>{formatCurrency(value)}</div>;
},
footer: () => (
<div className='text-right font-semibold text-gray-900'>
{formatCurrency(summary.total_initial_amount) || '-'}
</div>
),
},
{
id: 'credit_note',
header: 'CN',
accessorKey: 'credit_note',
cell: (props) => {
const value = props.row.original.credit_note;
return <div className='text-right'>{formatCurrency(value)}</div>;
},
footer: () => (
<div className='text-right font-semibold text-gray-900'>
{formatCurrency(summary.total_credit_note) || '-'}
</div>
),
},
{
id: 'final_price',
header: 'Harga Akhir',
accessorKey: 'final_price',
cell: (props) => {
const value = props.row.original.final_price;
return <div className='text-right'>{formatCurrency(value)}</div>;
},
footer: () => (
<div className='text-right font-semibold text-gray-900'>
{formatCurrency(summary.total_final_amount) || '-'}
</div>
),
},
{
id: 'ppn',
header: 'PPN (%)',
accessorKey: 'ppn',
cell: (props) => {
const value = props.row.original.ppn;
return <div className='text-right'>{formatNumber(value)}%</div>;
},
footer: () => (
<div className='text-right font-semibold text-gray-900'>-</div>
),
},
{
id: 'total',
header: 'Total',
accessorKey: 'total',
cell: (props) => {
const value = props.row.original.total;
return <div className='text-right'>{formatCurrency(value)}</div>;
},
footer: () => (
<div className='text-right font-semibold text-gray-900'>
{formatCurrency(summary.total_grand_amount) || '-'}
</div>
),
},
{
id: 'payment',
header: 'Pembayaran',
accessorKey: 'payment',
cell: (props) => {
const value = props.row.original.payment;
return <div className='text-right'>{formatCurrency(value)}</div>;
},
footer: () => (
<div className='text-right font-semibold text-gray-900'>
{formatCurrency(summary.total_payment) || '-'}
</div>
),
},
{
id: 'accounts_receivable',
header: 'Saldo Piutang',
accessorKey: 'accounts_receivable',
cell: (props) => {
const value = props.row.original.accounts_receivable;
return <div className='text-right'>{formatCurrency(value)}</div>;
},
footer: () => (
<div className='text-right font-semibold text-gray-900'>
{formatCurrency(summary.total_accounts_receivable) || '-'}
</div>
),
},
{
id: 'notes',
header: 'Keterangan',
accessorKey: 'notes',
cell: (props) => {
const value = props.row.original.notes;
return value || '-';
},
},
{
id: 'pickup_info',
header: 'Pengambilan',
accessorKey: 'pickup_info',
cell: (props) => {
const value = props.row.original.pickup_info;
return value || '-';
},
},
{
id: 'sales_marketing',
header: 'Sales/Marketing',
accessorKey: 'sales_marketing',
cell: (props) => {
const value = props.row.original.sales_marketing;
return value || '-';
},
},
];
return tableColumns;
};
return (
<div className='w-full p-0 sm:p-4'>
<Card
subtitle='Laporan > Kontrol Pembayaran Customer'
className={{ wrapper: 'w-full', body: 'p-1!' }}
>
<div className='mb-4 flex justify-end gap-2 [&_button]:px-4'>
<Button variant='outline' onClick={filterModal.openModal}>
<Icon icon='heroicons:funnel' width={18} height={18} />
Filter
</Button>
<Dropdown
trigger={
<Button variant='outline' isLoading={isAnyExportLoading}>
<Icon
icon='heroicons:cloud-arrow-down'
width={18}
height={18}
/>
Export
</Button>
}
align='end'
>
<Menu>
<MenuItem title='Excel' onClick={handleExportExcel} />
<MenuItem title='PDF' onClick={handleExportPdf} />
</Menu>
</Dropdown>
</div>
{/* Filter Modal */}
<Modal
ref={filterModal.ref}
className={{
modal: 'p-0',
modalBox: 'p-0 rounded-2xl xl:max-w-4/12 max-w-sm',
}}
>
<div className='space-y-6'>
{/* Modal Header */}
<div className='flex items-center justify-between gap-2 py-3 border-b border-gray-300 px-4'>
<div className='flex items-center gap-2 text-primary'>
<Icon icon='heroicons:funnel' width={20} height={20} />
<h3 className='font-semibold'>Filter Data</h3>
</div>
<Button
variant='link'
onClick={filterModal.closeModal}
className='text-gray-500 hover:text-gray-700 transition-colors cursor-pointer'
>
<Icon icon='heroicons:x-mark' width={20} height={20} />
</Button>
</div>
<div className='space-y-4 px-4'>
<div className='grid grid-cols-1 sm:grid-cols-2 sm:gap-4'>
<div>
<DateInput
label='Tanggal'
name='start_date'
value={filterStartDate}
onChange={(e) => {
setFilterStartDate(e.target.value);
setFilterErrors((prev) => ({ ...prev, start_date: '' }));
}}
className={{ wrapper: 'w-full' }}
/>
{filterErrors.start_date && (
<p className='text-red-500 text-sm mt-1'>
{filterErrors.start_date}
</p>
)}
</div>
<div>
<DateInput
label=' '
name='end_date'
value={filterEndDate}
onChange={(e) => {
setFilterEndDate(e.target.value);
setFilterErrors((prev) => ({ ...prev, end_date: '' }));
}}
className={{ wrapper: 'w-full' }}
/>
{filterErrors.end_date && (
<p className='text-red-500 text-sm mt-1'>
{filterErrors.end_date}
</p>
)}
</div>
</div>
<div>
<SelectInput
label='Customer'
placeholder='Pilih Customer'
isMulti
options={customerOptions}
value={filterCustomer}
onChange={(val) => {
setFilterCustomer(
Array.isArray(val) ? val : val ? [val] : []
);
}}
isLoading={isLoadingCustomers}
isClearable
className={{ wrapper: 'w-full' }}
/>
</div>
<div>
<SelectInput
label='Sales'
placeholder='Pilih Sales'
isMulti
options={salesOptions}
value={filterSales}
onChange={(val) => {
setFilterSales(Array.isArray(val) ? val : val ? [val] : []);
}}
isClearable
className={{ wrapper: 'w-full' }}
/>
</div>
<div>
<SelectInput
label='Filter Berdasarkan'
placeholder='Pilih Filter Berdasarkan'
options={dataTypeOptions}
value={dataTypeOptions[0]}
isDisabled={true}
className={{ wrapper: 'w-full' }}
/>
</div>
</div>
{/* Action Buttons */}
<div className='flex justify-between gap-4 py-4 mt-8 border-t border-gray-300 bg-gray-100'>
<Button
variant='soft'
className='ms-4 min-w-36 rounded-lg'
onClick={handleResetFilters}
>
Reset Filter
</Button>
<Button
className='me-4 min-w-36 rounded-lg'
onClick={handleApplyFilters}
>
Apply Filter
</Button>
</div>
</div>
</Modal>
{!isSubmitted ? (
<div className='mt-6 text-center text-gray-500'>
Silakan klik tombol Filter untuk mengatur filter dan menampilkan
data.
</div>
) : isLoading ? (
<div className='w-full flex flex-row justify-center items-center p-4'>
<span className='loading loading-spinner loading-xl' />
</div>
) : data.length === 0 ? (
<div className='mt-6 text-center text-gray-500'>
Tidak ada data yang dapat ditampilkan...
</div>
) : (
data.map((customerReport) => {
const summary = customerReport.summary || {
total_qty: 0,
total_weight: 0,
total_initial_amount: 0,
total_credit_note: 0,
total_final_amount: 0,
total_ppn: 0,
total_grand_amount: 0,
total_payment: 0,
total_accounts_receivable: 0,
};
const totalAccountsReceivable = summary.total_accounts_receivable;
const tableColumns = getTableColumns(summary);
return (
<Card
key={customerReport.customer.id}
title={customerReport.customer.name}
subtitle={`NPWP: ${customerReport.customer_npwp || '-'} | ${customerReport.customer_address || ''}\nSaldo Piutang: ${formatCurrency(totalAccountsReceivable)}`}
className={{ wrapper: 'w-full' }}
variant='bordered'
collapsible={true}
>
<Table
data={customerReport.rows}
columns={tableColumns}
pageSize={10}
renderFooter={customerReport.rows.length > 0}
className={{
containerClassName: 'w-full',
tableWrapperClassName: 'overflow-x-auto mt-4',
tableClassName: 'w-full table-auto text-sm',
headerRowClassName: 'border-b border-b-gray-200 bg-gray-50',
headerColumnClassName:
'px-4 py-3 text-xs font-semibold text-gray-700 text-left border border-gray-200',
bodyRowClassName:
'hover:bg-gray-50 transition-colors border-b border-l border-r border-b-gray-200 border-l-gray-200 border-r-gray-200',
bodyColumnClassName:
'px-4 py-3 text-xs text-gray-900 whitespace-nowrap',
tableFooterClassName:
'bg-gray-100 font-semibold border border-gray-200',
footerRowClassName: 'border-t-2 border-gray-300',
footerColumnClassName:
'px-4 py-3 text-xs text-gray-900 whitespace-nowrap',
paginationClassName: 'hidden',
}}
/>
</Card>
);
})
)}
</Card>
{meta && data.length > 0 && (
<div className='mt-6'>
<Pagination
currentPage={meta.page}
totalItems={meta.total_results}
onPageChange={handlePageChange}
onRowChange={handleRowChange}
onNextPage={handleNextPage}
onPrevPage={handlePrevPage}
rowOptions={[10, 25, 50, 100]}
itemsPerPage={meta.limit}
/>
</div>
)}
</div>
);
};
export default CustomerPaymentTab;
@@ -0,0 +1,608 @@
import Button from '@/components/Button';
import Card from '@/components/Card';
import Dropdown from '@/components/Dropdown';
import DateInput from '@/components/input/DateInput';
import SelectInput, {
OptionType,
useSelect,
} from '@/components/input/SelectInput';
import Menu from '@/components/menu/Menu';
import MenuItem from '@/components/menu/MenuItem';
import Modal, { useModal } from '@/components/Modal';
import Table from '@/components/Table';
import { isResponseSuccess } from '@/lib/api-helper';
import { formatCurrency, formatDate, formatNumber } from '@/lib/helper';
import { SupplierApi } from '@/services/api/master-data';
import { FinanceApi } from '@/services/api/report/finance-report';
import { DebtRow, DebtSupplier } from '@/types/api/report/debt-supplier';
import { generateDebtSupplierExcel } from '@/components/pages/report/finance/export/DebtSupplierExportXLSX';
import { generateDebtSupplierPDF } from '@/components/pages/report/finance/export/DebtSupllierExportPDF';
import { Icon } from '@iconify/react';
import { ColumnDef } from '@tanstack/react-table';
import { useCallback, useMemo, useState } from 'react';
import toast from 'react-hot-toast';
import useSWR from 'swr';
import Pagination from '@/components/Pagination';
const DebtSupplierTab = () => {
// ===== STATE MANAGEMENT =====
const [isPdfExportLoading, setIsPdfExportLoading] = useState(false);
const [isExcelExportLoading, setIsExcelExportLoading] = useState(false);
const isAnyExportLoading = isPdfExportLoading || isExcelExportLoading;
// ===== PAGINATION STATE =====
const [currentPage, setCurrentPage] = useState(1);
const [pageSize, setPageSize] = useState(10);
// ===== SUBMISSION STATE =====
const [isSubmitted, setIsSubmitted] = useState(false);
// ===== FILTER STATE =====
const [filterSupplier, setFilterSupplier] = useState<OptionType[]>([]);
const [filterStartDate, setFilterStartDate] = useState('');
const [filterEndDate, setFilterEndDate] = useState('');
const [filterDataType, setFilterDataType] = useState<OptionType>();
const [filterErrors, setFilterErrors] = useState<Record<string, string>>({});
const filterModal = useModal();
const { options: supplierOptions, isLoadingOptions: isLoadingSuppliers } =
useSelect(SupplierApi.basePath, 'id', 'name', '', {
limit: 'limit',
});
const dataTypeOptions = useMemo(
() => [
{ value: 'do_date', label: 'Tanggal Terima' },
{ value: 'po_date', label: 'Tanggal PO' },
],
[]
);
// ===== FILTER HANDLERS =====
const handleResetFilters = useCallback(() => {
setIsSubmitted(false);
setFilterSupplier([]);
setFilterStartDate('');
setFilterEndDate('');
setFilterErrors({});
}, []);
const handleApplyFilters = useCallback(() => {
const errors: Record<string, string> = {};
if (!filterStartDate) {
errors.start_date = 'Tanggal mulai wajib diisi';
}
if (!filterEndDate) {
errors.end_date = 'Tanggal akhir wajib diisi';
}
setFilterErrors(errors);
if (Object.keys(errors).length === 0) {
setIsSubmitted(true);
setCurrentPage(1);
filterModal.closeModal();
}
}, [filterModal, filterStartDate, filterEndDate]);
// ===== DATA FETCHING =====
const { data: debtSupplier, isLoading } = useSWR(
isSubmitted
? () => {
const params = {
supplier_ids:
filterSupplier.length > 0
? filterSupplier.map((v) => String(v.value)).join(',')
: undefined,
filter_by: filterDataType?.value || 'do_date',
start_date: filterStartDate || undefined,
end_date: filterEndDate || undefined,
page: currentPage,
limit: pageSize,
};
return ['debt-supplier-report', params];
}
: null,
([, params]) =>
FinanceApi.getDebtSupplierReport(
params.supplier_ids,
params.filter_by?.toString(),
params.start_date,
params.end_date,
params.page,
params.limit
)
);
// const { data: debtSupplier, isLoading } = useSWR(FinanceApi.basePath, () =>
// FinanceApi.getDebtSupplierReport()
// );
const data: DebtSupplier[] = useMemo(
() =>
isResponseSuccess(debtSupplier)
? (debtSupplier?.data as unknown as DebtSupplier[]) || []
: [],
[debtSupplier]
);
const meta =
isResponseSuccess(debtSupplier) && debtSupplier?.meta
? debtSupplier.meta
: null;
// ===== EXPORT DATA FETCHER =====
const debtSupplierExport = useCallback(async (): Promise<
DebtSupplier[] | null
> => {
const params = {
supplier_ids:
filterSupplier.length > 0
? filterSupplier.map((v) => String(v.value)).join(',')
: undefined,
filter_by: 'do_date' as const,
start_date: filterStartDate || undefined,
end_date: filterEndDate || undefined,
date_type: filterDataType ? filterDataType.value : undefined,
limit: 100,
page: 1,
};
const response = await FinanceApi.getDebtSupplierReport(
params.supplier_ids,
params.filter_by,
params.start_date,
params.end_date,
params.page,
params.limit
);
return isResponseSuccess(response)
? (response.data as unknown as DebtSupplier[])
: null;
}, [filterSupplier, filterStartDate, filterEndDate]);
// ===== EXPORT HANDLERS =====
const handleExportExcel = useCallback(async () => {
setIsExcelExportLoading(true);
try {
const allDataForExport = await debtSupplierExport();
if (
!allDataForExport ||
!Array.isArray(allDataForExport) ||
allDataForExport.length === 0
) {
toast.error('Tidak ada data untuk diekspor.');
return;
}
generateDebtSupplierExcel({ data: allDataForExport });
toast.success('Excel berhasil dibuat dan diunduh.');
} catch {
toast.error('Gagal membuat Excel. Silakan coba lagi.');
} finally {
setIsExcelExportLoading(false);
}
}, [debtSupplierExport]);
const handleExportPdf = useCallback(async () => {
setIsPdfExportLoading(true);
try {
const allDataForExport = await debtSupplierExport();
if (
!allDataForExport ||
!Array.isArray(allDataForExport) ||
allDataForExport.length === 0
) {
toast.error('Tidak ada data untuk diekspor.');
return;
}
await generateDebtSupplierPDF({ data: allDataForExport });
toast.success('PDF berhasil dibuat dan diunduh.');
} catch {
toast.error('Gagal membuat PDF. Silakan coba lagi.');
} finally {
setIsPdfExportLoading(false);
}
}, [debtSupplierExport]);
// ===== PAGINATION HANDLERS =====
const handlePageChange = (page: number) => {
setCurrentPage(page);
};
const handleRowChange = (pageSize: number) => {
setPageSize(pageSize);
};
const handleNextPage = () => {
if (meta && currentPage < meta.total_pages) {
setCurrentPage(currentPage + 1);
}
};
const handlePrevPage = () => {
if (currentPage > 1) {
setCurrentPage(currentPage - 1);
}
};
const getTableColumns = (supplier: DebtSupplier): ColumnDef<DebtRow>[] => [
{
id: 'no',
header: 'No',
cell: (props) => props.row.index + 1,
},
{
id: 'pr_number',
header: 'Nomor PR',
accessorKey: 'pr_number',
cell: (props) => {
const value = props.row.original.pr_number;
return value || '-';
},
},
{
id: 'po_number',
header: 'Nomor PO',
accessorKey: 'po_number',
cell: (props) => {
const value = props.row.original.po_number;
return value || '-';
},
},
{
id: 'pr_date',
header: 'Tanggal PR',
accessorKey: 'pr_date',
cell: (props) => {
const value = props.row.original.pr_date;
return formatDate(value, 'DD MMM YYYY');
},
},
{
id: 'po_date',
header: 'Tanggal PO',
accessorKey: 'po_date',
cell: (props) => {
const value = props.row.original.po_date;
return formatDate(value, 'DD MMM YYYY');
},
},
{
id: 'aging',
header: 'Aging',
accessorKey: 'aging',
cell: (props) => {
const value = props.row.original.aging;
return <div className='text-center'>{formatNumber(value)} Hari</div>;
},
footer: () => {
const value = supplier.total.aging;
return <div className='text-center'>{formatNumber(value)} Hari</div>;
},
},
{
id: 'area',
header: 'Area',
accessorKey: 'area',
cell: (props) => {
const value = props.row.original.area?.name;
return value || '-';
},
},
{
id: 'warehouse',
header: 'Gudang',
accessorKey: 'warehouse',
cell: (props) => {
const value = props.row.original.warehouse?.name;
return value || '-';
},
},
{
id: 'due_date',
header: 'Tanggal Jatuh Tempo',
accessorKey: 'due_date',
cell: (props) => {
const value = props.row.original.due_date;
return formatDate(value, 'DD MMM YYYY');
},
},
{
id: 'due_status',
header: 'Status Jatuh Tempo',
accessorKey: 'due_status',
cell: (props) => {
const value = props.row.original.due_status;
return value || '-';
},
},
{
id: 'total_price',
header: 'Total Harga',
accessorKey: 'total_price',
cell: (props) => {
const value = props.row.original.total_price;
return <div className='text-right'>{formatCurrency(value)}</div>;
},
footer: () => {
const value = supplier.total.total_price;
return <div className='text-right'>{formatCurrency(value)}</div>;
},
},
{
id: 'payment_price',
header: 'Harga Pembayaran',
accessorKey: 'payment_price',
cell: (props) => {
const value = props.row.original.payment_price;
return <div className='text-right'>{formatCurrency(value)}</div>;
},
footer: () => {
const value = supplier.total.payment_price;
return <div className='text-right'>{formatCurrency(value)}</div>;
},
},
{
id: 'debt_price',
header: 'Harga Hutang',
accessorKey: 'debt_price',
cell: (props) => {
const value = props.row.original.debt_price;
return (
<div className={`text-right ${value < 0 ? 'text-red-500' : ''}`}>
{formatCurrency(value)}
</div>
);
},
footer: () => {
const value = supplier.total.debt_price;
return (
<div className={`text-right ${value < 0 ? 'text-red-500' : ''}`}>
{formatCurrency(value)}
</div>
);
},
},
{
id: 'status',
header: 'Status',
accessorKey: 'status',
cell: (props) => {
const value = props.row.original.status;
return value || '-';
},
},
{
id: 'travel_number',
header: 'Nomor Perjalanan',
accessorKey: 'travel_number',
cell: (props) => {
const value = props.row.original.travel_number;
return value || '-';
},
},
];
return (
<>
<div className='w-full p-0 sm:p-4 flex flex-col gap-4'>
<Card
subtitle='Laporan > Kontrol Hutang Supplier'
className={{ wrapper: 'w-full', body: 'p-1!' }}
>
<div className='mb-4 flex justify-end gap-2 [&_button]:px-4'>
<Button variant='outline' onClick={filterModal.openModal}>
<Icon icon='heroicons:funnel' width={18} height={18} />
Filter
</Button>
<Dropdown
trigger={
<Button variant='outline' isLoading={isAnyExportLoading}>
<Icon
icon='heroicons:cloud-arrow-down'
width={18}
height={18}
/>
Export
</Button>
}
align='end'
>
<Menu>
<MenuItem title='Excel' onClick={handleExportExcel} />
<MenuItem title='PDF' onClick={handleExportPdf} />
</Menu>
</Dropdown>
</div>
</Card>
{!isSubmitted ? (
<div className='mt-6 text-center text-gray-500'>
Silakan klik tombol Filter untuk mengatur filter dan menampilkan
data.
</div>
) : isLoading ? (
<div className='w-full flex flex-row justify-center items-center p-4'>
<span className='loading loading-spinner loading-xl' />
</div>
) : data.length === 0 ? (
<div className='mt-6 text-center text-gray-500'>
Tidak ada data yang dapat ditampilkan...
</div>
) : (
data.map((supplierReport) => {
return (
<Card
key={supplierReport.supplier.id}
title={supplierReport.supplier.name}
className={{ wrapper: 'w-full' }}
variant='bordered'
collapsible={true}
>
<Table
data={supplierReport.rows}
columns={getTableColumns(supplierReport)}
pageSize={supplierReport.rows.length}
renderFooter={supplierReport.rows.length > 0}
className={{
containerClassName: 'w-full',
tableWrapperClassName: 'overflow-x-auto mt-4',
tableClassName: 'w-full table-auto text-sm',
headerRowClassName: 'border-b border-b-gray-200 bg-gray-50',
headerColumnClassName:
'px-4 py-3 text-xs font-semibold text-gray-700 text-left border border-gray-200',
bodyRowClassName:
'hover:bg-gray-50 transition-colors border-b border-l border-r border-b-gray-200 border-l-gray-200 border-r-gray-200',
bodyColumnClassName:
'px-4 py-3 text-xs text-gray-900 whitespace-nowrap',
tableFooterClassName:
'bg-gray-100 font-semibold border border-gray-200',
footerRowClassName: 'border-t-2 border-gray-300',
footerColumnClassName:
'px-4 py-3 text-xs text-gray-900 whitespace-nowrap',
paginationClassName: 'hidden',
}}
/>
</Card>
);
})
)}
</div>
{meta && data.length > 0 && (
<div className='mt-6'>
<Pagination
currentPage={meta.page}
totalItems={meta.total_results}
onPageChange={handlePageChange}
onRowChange={handleRowChange}
onNextPage={handleNextPage}
onPrevPage={handlePrevPage}
rowOptions={[10, 25, 50, 100]}
itemsPerPage={meta.limit}
/>
</div>
)}
{/* Filter Modal */}
<Modal
ref={filterModal.ref}
className={{
modal: 'p-0',
modalBox: 'p-0 rounded-2xl xl:max-w-4/12 max-w-sm',
}}
>
<div className='space-y-6'>
{/* Modal Header */}
<div className='flex items-center justify-between gap-2 py-3 border-b border-gray-300 px-4'>
<div className='flex items-center gap-2 text-primary'>
<Icon icon='heroicons:funnel' width={20} height={20} />
<h3 className='font-semibold'>Filter Data</h3>
</div>
<Button
variant='link'
onClick={filterModal.closeModal}
className='text-gray-500 hover:text-gray-700 transition-colors cursor-pointer'
>
<Icon icon='heroicons:x-mark' width={20} height={20} />
</Button>
</div>
<div className='space-y-4 px-4'>
<div className='grid grid-cols-1 sm:grid-cols-2 sm:gap-4'>
<div>
<DateInput
label='Tanggal'
name='start_date'
value={filterStartDate}
onChange={(e) => {
setFilterStartDate(e.target.value);
setFilterErrors((prev) => ({ ...prev, start_date: '' }));
}}
className={{ wrapper: 'w-full' }}
/>
{filterErrors.start_date && (
<p className='text-red-500 text-sm mt-1'>
{filterErrors.start_date}
</p>
)}
</div>
<div className='mt-auto'>
<DateInput
label=' '
name='end_date'
value={filterEndDate}
onChange={(e) => {
setFilterEndDate(e.target.value);
setFilterErrors((prev) => ({ ...prev, end_date: '' }));
}}
className={{ wrapper: 'w-full' }}
/>
{filterErrors.end_date && (
<p className='text-red-500 text-sm mt-1'>
{filterErrors.end_date}
</p>
)}
</div>
</div>
<div>
<SelectInput
label='Supplier'
placeholder='Pilih Supplier'
isMulti
options={supplierOptions}
value={filterSupplier}
onChange={(val) => {
setFilterSupplier(
Array.isArray(val) ? val : val ? [val] : []
);
}}
isLoading={isLoadingSuppliers}
isClearable
className={{ wrapper: 'w-full' }}
/>
</div>
<div>
<SelectInput
label='Filter Berdasarkan'
placeholder='Pilih Filter Berdasarkan'
options={dataTypeOptions}
value={filterDataType}
onChange={(val) => {
setFilterDataType(val ? (val as OptionType) : undefined);
}}
className={{ wrapper: 'w-full' }}
/>
</div>
</div>
{/* Action Buttons */}
<div className='flex justify-between gap-4 py-4 mt-8 border-t border-gray-300 bg-gray-100'>
<Button
variant='soft'
className='ms-4 min-w-36 rounded-lg'
onClick={handleResetFilters}
>
Reset Filter
</Button>
<Button
className='me-4 min-w-36 rounded-lg'
onClick={handleApplyFilters}
>
Apply Filter
</Button>
</div>
</div>
</Modal>
</>
);
};
export default DebtSupplierTab;
+24 -4
View File
@@ -74,7 +74,23 @@ export const RECORDING_APPROVAL_LINE: ApprovalLine = [
},
{
step_number: 2,
step_name: 'Disetujui',
step_name: 'Approval Head Area',
},
{
step_number: 3,
step_name: 'Approval Business Unit Vice President',
},
{
step_number: 4,
step_name: 'Approval Finance',
},
{
step_number: 5,
step_name: 'Realisasi',
},
{
step_number: 6,
step_name: 'Selesai',
},
] as const;
@@ -130,18 +146,22 @@ export const EXPENSE_REQUEST_APPROVAL_LINE: ApprovalLine = [
},
{
step_number: 2,
step_name: 'Approval Manager',
step_name: 'Approval Head Area',
},
{
step_number: 3,
step_name: 'Approval Finance',
step_name: 'Approval Business Unit Vice President',
},
{
step_number: 4,
step_name: 'Realisasi',
step_name: 'Approval Finance',
},
{
step_number: 5,
step_name: 'Realisasi',
},
{
step_number: 6,
step_name: 'Selesai',
},
] as const;
+4
View File
@@ -133,6 +133,10 @@ export const MAIN_DRAWER_LINKS: SidebarMenuItem[] = [
link: '/report',
icon: 'mdi:chart-box-outline',
submenu: [
{
text: 'Keuangan',
link: '/report/finance',
},
{
text: 'Logistik & Persediaan',
link: '/report/logistic-stock',
+4
View File
@@ -118,6 +118,10 @@ export const ROUTE_PERMISSIONS: Record<string, string[]> = {
'/report/expense/': ['lti.repport.expense.list'],
'/report/marketing/': ['lti.repport.delivery.list'],
'/report/production-result/': ['lti.repport.production_result.list'],
'/report/finance/': [
'lti.repport.finance.list',
'lti.repport.debtsupplier.list',
],
// Inventory
'/inventory/adjustment/': ['lti.inventory.list'],
File diff suppressed because it is too large Load Diff
@@ -1,39 +0,0 @@
/**
* Dummy data for DashboardProduction
* Generated from: dashboard.production.dummy.json
*
* This file is auto-generated. Do not edit manually.
*/
import {
DashboardProductionStatisticsData,
DashboardProductionProductionChartsFlocks,
DashboardProductionProductionCharts,
DashboardProductionStandardProductionsStandards,
DashboardProductionStandardProductions,
DashboardProductionFcrDataFlock,
DashboardProductionEggWeights,
DashboardProductionFcrData,
DashboardProduction,
} from '../../types/api/dashboard/dashboard-production';
import { BaseApiResponse } from '@/types/api/api-general';
import dummyData from './dashboard.production.dummy.json';
/**
* Get dummy DashboardProduction data
* @returns Promise with BaseApiResponse containing DashboardProduction
*/
export async function getDummySingle(): Promise<
BaseApiResponse<DashboardProduction>
> {
return new Promise((resolve) => {
setTimeout(() => {
resolve({
code: 200,
status: 'success',
message: 'Data retrieved successfully',
data: dummyData as unknown as DashboardProduction,
});
}, 500);
});
}
+3 -2
View File
@@ -92,10 +92,11 @@ export class ClosingApiService extends BaseApiService<Closing, null, null> {
}
async getPerhitunganSapronak(
id: number
id: number,
projectKandangId?: number
): Promise<BaseApiResponse<ClosingSapronakCalculation> | undefined> {
try {
const path = `${this.basePath}/${id}/perhitungan_sapronak`;
const path = `${this.basePath}/${id}${projectKandangId ? `/${projectKandangId}` : ''}/perhitungan_sapronak`;
return await httpClient<BaseApiResponse<ClosingSapronakCalculation>>(
path,
{
+8 -17
View File
@@ -1,13 +1,9 @@
import { BaseApiService } from '@/services/api/base';
import { BaseApiResponse } from '@/types/api/api-general';
import { DashboardProduction } from '@/types/api/dashboard/dashboard-production';
import { getDummySingle } from '@/dummy/dashboard/dashboard.production.dummy';
import { Dashboard } from '@/types/api/dashboard/dashboard';
import { httpClientFetcher } from '@/services/http/client';
class DashboardService extends BaseApiService<
DashboardProduction,
unknown,
unknown
> {
class DashboardService extends BaseApiService<Dashboard, unknown, unknown> {
constructor(basePath: string) {
super(basePath);
}
@@ -16,19 +12,14 @@ class DashboardService extends BaseApiService<
* Fetch dashboard production data
* @param endpoint - The endpoint URL with query parameters
* @returns Promise with BaseApiResponse containing DashboardProduction
*
* Note: Currently using dummy data. When real API is ready,
* uncomment the line below and remove getDummySingle() call:
* return await this.customRequest<BaseApiResponse<DashboardProduction>>(endpoint);
*/
async getDashboardProductionFetcher(
endpoint: string
): Promise<BaseApiResponse<DashboardProduction>> {
// For now, we're using dummy data regardless of the endpoint
// The endpoint parameter is kept for future API integration
console.log('Fetching dashboard data with endpoint:', endpoint);
return await getDummySingle();
): Promise<BaseApiResponse<Dashboard> | undefined> {
return await httpClientFetcher<BaseApiResponse<Dashboard>>(
`${endpoint ? endpoint : this.basePath}`
);
}
}
export const DashboardApi = new DashboardService('/dashboard');
export const DashboardApi = new DashboardService('/dashboards');
+116 -8
View File
@@ -169,13 +169,13 @@ export class ExpenseApiService extends BaseApiService<
}
}
async approveManager(
async approveHeadArea(
id: number,
notes?: string
): Promise<BaseApiResponse<Expense> | undefined> {
try {
const approveRes = await httpClient<BaseApiResponse<Expense>>(
`${this.basePath}/approvals/manager`,
`${this.basePath}/approvals/head-area`,
{
method: 'POST',
body: {
@@ -196,13 +196,67 @@ export class ExpenseApiService extends BaseApiService<
}
}
async bulkApproveManager(
async bulkApproveHeadArea(
ids: number[],
notes?: string
): Promise<BaseApiResponse<Expense> | undefined> {
try {
const bulkApproveRes = await httpClient<BaseApiResponse<Expense>>(
`${this.basePath}/approvals/manager`,
`${this.basePath}/approvals/head-area`,
{
method: 'POST',
body: {
action: 'APPROVED',
approvable_ids: ids,
notes: notes,
},
}
);
return bulkApproveRes;
} catch (error) {
if (axios.isAxiosError<BaseApiResponse<Expense>>(error)) {
return error.response?.data;
}
return undefined;
}
}
async approveUnitVicePresident(
id: number,
notes?: string
): Promise<BaseApiResponse<Expense> | undefined> {
try {
const approveRes = await httpClient<BaseApiResponse<Expense>>(
`${this.basePath}/approvals/unit-vice-president`,
{
method: 'POST',
body: {
action: 'APPROVED',
approvable_ids: [id],
notes: notes,
},
}
);
return approveRes;
} catch (error) {
if (axios.isAxiosError<BaseApiResponse<Expense>>(error)) {
return error.response?.data;
}
return undefined;
}
}
async bulkApproveUnitVicePresident(
ids: number[],
notes?: string
): Promise<BaseApiResponse<Expense> | undefined> {
try {
const bulkApproveRes = await httpClient<BaseApiResponse<Expense>>(
`${this.basePath}/approvals/unit-vice-president`,
{
method: 'POST',
body: {
@@ -277,13 +331,13 @@ export class ExpenseApiService extends BaseApiService<
}
}
async rejectManager(
async rejectHeadArea(
id: number,
notes?: string
): Promise<BaseApiResponse<Expense> | undefined> {
try {
const rejectRes = await httpClient<BaseApiResponse<Expense>>(
`${this.basePath}/approvals/manager`,
`${this.basePath}/approvals/head-area`,
{
method: 'POST',
body: {
@@ -304,13 +358,67 @@ export class ExpenseApiService extends BaseApiService<
}
}
async bulkRejectManager(
async bulkRejectHeadArea(
ids: number[],
notes?: string
): Promise<BaseApiResponse<Expense> | undefined> {
try {
const bulkRejectRes = await httpClient<BaseApiResponse<Expense>>(
`${this.basePath}/approvals/manager`,
`${this.basePath}/approvals/head-area`,
{
method: 'POST',
body: {
action: 'REJECTED',
approvable_ids: ids,
notes: notes,
},
}
);
return bulkRejectRes;
} catch (error) {
if (axios.isAxiosError<BaseApiResponse<Expense>>(error)) {
return error.response?.data;
}
return undefined;
}
}
async rejectUnitVicePresident(
id: number,
notes?: string
): Promise<BaseApiResponse<Expense> | undefined> {
try {
const rejectRes = await httpClient<BaseApiResponse<Expense>>(
`${this.basePath}/approvals/unit-vice-president`,
{
method: 'POST',
body: {
action: 'REJECTED',
approvable_ids: [id],
notes: notes,
},
}
);
return rejectRes;
} catch (error) {
if (axios.isAxiosError<BaseApiResponse<Expense>>(error)) {
return error.response?.data;
}
return undefined;
}
}
async bulkRejectUnitVicePresident(
ids: number[],
notes?: string
): Promise<BaseApiResponse<Expense> | undefined> {
try {
const bulkRejectRes = await httpClient<BaseApiResponse<Expense>>(
`${this.basePath}/approvals/unit-vice-president`,
{
method: 'POST',
body: {
+66
View File
@@ -0,0 +1,66 @@
import { BaseApiService } from '@/services/api/base';
import { BaseApiResponse } from '@/types/api/api-general';
import { CustomerPaymentReport } from '@/types/api/report/customer-payment';
import { DebtSupplier } from '@/types/api/report/debt-supplier';
export class FinanceApiService extends BaseApiService<
CustomerPaymentReport,
unknown,
unknown
> {
constructor(basePath: string) {
super(basePath);
}
async getCustomerPaymentReport(
customer_id?: string,
sales?: string,
filter_by?: 'do_date',
start_date?: string,
end_date?: string,
page?: number,
limit?: number
): Promise<BaseApiResponse<CustomerPaymentReport> | undefined> {
return await this.customRequest<BaseApiResponse<CustomerPaymentReport>>(
`customer-payment`,
{
method: 'GET',
params: {
customer_id: customer_id,
sales: sales,
filter_by: filter_by,
start_date: start_date,
end_date: end_date,
page: page,
limit: limit,
},
}
);
}
async getDebtSupplierReport(
supplier_ids?: string,
filter_by?: string,
start_date?: string,
end_date?: string,
page?: number,
limit?: number
): Promise<BaseApiResponse<DebtSupplier[]> | undefined> {
return await this.customRequest<BaseApiResponse<DebtSupplier[]>>(
`debt-supplier`,
{
method: 'GET',
params: {
supplier_ids: supplier_ids,
filter_by: filter_by,
start_date: start_date,
end_date: end_date,
page: page,
limit: limit,
},
}
);
}
}
export const FinanceApi = new FinanceApiService('reports');
+62
View File
@@ -0,0 +1,62 @@
import { getUniqueFormikErrors } from '@/lib/formik-helper';
import { FormikProps } from 'formik';
import { useState } from 'react';
interface UseFormikErrorListOptions {
onBeforeSubmit?: (e: React.FormEvent<HTMLFormElement>) => boolean | void;
onAfterValidation?: () => void | Promise<void>;
}
export const useFormikErrorList = <T>(
formik: FormikProps<T>,
options?: UseFormikErrorListOptions
) => {
const [formErrorList, setFormErrorList] = useState<string[]>([]);
const handleValidateForm = async () => {
const errors = await formik.validateForm();
if (Object.keys(errors).length > 0) {
const errorMessages = getUniqueFormikErrors(errors);
setFormErrorList(errorMessages);
return false;
}
return true;
};
const handleFormSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
// Call onBeforeSubmit callback
if (options?.onBeforeSubmit) {
const shouldContinue = options.onBeforeSubmit(e);
if (shouldContinue === false) {
return; // Cancel submit
}
}
// Validate form
const isValid = await handleValidateForm();
// Call onAfterValidation callback if validation passed
if (options?.onAfterValidation) {
await options.onAfterValidation();
}
// Submit form
formik.handleSubmit();
};
const close = () => {
setFormErrorList([]);
};
return {
formErrorList,
setFormErrorList,
close,
handleValidateForm,
handleFormSubmit,
};
};
+1 -1
View File
@@ -63,6 +63,7 @@ export type BaseClosing = {
location_id: number;
location_name: string;
project_category: 'GROWING' | 'LAYING';
project_type?: 'GROWING' | 'LAYING'; // berubah dari BE?
period: number;
closing_date?: string;
shed_label: string;
@@ -185,7 +186,6 @@ export type ClosingSapronakCalculation = {
doc: ClosingSapronakCalculationItem;
ovk: ClosingSapronakCalculationItem;
pakan: ClosingSapronakCalculationItem;
pullet: ClosingSapronakCalculationItem;
};
// ====== OVERHEAD ======
-52
View File
@@ -1,52 +0,0 @@
export interface DashboardProduction {
statistics_data: DashboardProductionStatisticsData[];
production_charts: DashboardProductionProductionCharts[];
standard_productions: DashboardProductionStandardProductions[];
egg_weights: DashboardProductionEggWeights[];
fcr_data: DashboardProductionFcrData[];
}
export interface DashboardProductionFcrData {
flock: DashboardProductionFcrDataFlock;
fcr: number;
}
export interface DashboardProductionEggWeights {
flock: DashboardProductionFcrDataFlock;
weight: number;
}
export interface DashboardProductionStandardProductions {
week: number;
standards: DashboardProductionStandardProductionsStandards[];
flocks: DashboardProductionProductionChartsFlocks[];
}
export interface DashboardProductionProductionCharts {
date: string;
flocks: DashboardProductionProductionChartsFlocks[];
}
export interface DashboardProductionStatisticsData {
title: string;
value: number;
change: number;
period: string;
changeType: string;
}
export interface DashboardProductionFcrDataFlock {
id: number;
name: string;
}
export interface DashboardProductionStandardProductionsStandards {
name: string;
value: number;
}
export interface DashboardProductionProductionChartsFlocks {
id: number;
name: string;
data: number;
}
+61
View File
@@ -0,0 +1,61 @@
import { SuccessApiResponse } from '@/types/api/api-general';
export interface Dashboard {
statistics_data: DashboardStatisticsData[];
charts: DashboardComparisonCharts | DashboardOverviewCharts;
}
export interface DashboardComparisonCharts {
location: DashboardCharts;
flock: DashboardCharts;
kandang: DashboardCharts;
}
export interface DashboardOverviewCharts {
body_weight: DashboardCharts;
performance: DashboardCharts;
fcr: DashboardCharts;
quality_control: DashboardCharts;
deplesi: DashboardCharts;
}
export interface DashboardCharts {
series: DashboardChartsSeries[];
dataset: DashboardChartsDataset[];
}
export interface DashboardStatisticsData {
label: string;
value: number;
percent_last_month: number;
}
export interface DashboardChartsDataset {
week: number;
// Index signature to support dynamic keys (series IDs) in comparison mode
[key: string | number]: number | undefined;
}
export interface DashboardChartsSeries {
id: string | number;
label: string;
unit: string;
}
export interface DashboardFilter {
start_date: string;
end_date: string;
analysis_mode: 'OVERVIEW' | 'COMPARISON';
location_ids: number[];
comparison_type?: string | undefined;
flock_ids: number[];
kandang_ids: number[];
}
export interface DashboardMeta {
page: number;
limit: number;
total_pages: number;
total_results: number;
filters: DashboardFilter;
}
+1
View File
@@ -5,6 +5,7 @@ import { Kandang } from '@/types/api/master-data/kandang';
import { Location } from '@/types/api/master-data/location';
import { BaseApproval, BaseMetadata } from '@/types/api/api-general';
import { Nonstock } from '@/types/api/master-data/nonstock';
import { ProductionStandard } from '@/types/api/master-data/production-standard';
export type BaseProjectFlock = {
id: number;
+7 -7
View File
@@ -8,15 +8,15 @@ export type ProductionMetrics = {
fcr_value: number;
fcr_std?: number;
total_chick_qty: number;
hand_day?: number;
hand_house?: number;
hen_day?: number;
hen_house?: number;
feed_intake?: number;
egg_mesh?: number;
egg_weight?: number;
hand_day_std?: number;
hand_house_std?: number;
feed_intake_std?: number;
egg_mesh_std?: number;
egg_mass?: number;
egg_weight?: number;
hen_day_std?: number;
hen_house_std?: number;
egg_mass_std?: number;
egg_weight_std?: number;
daily_gain?: number;
avg_daily_gain?: number;
+47
View File
@@ -0,0 +1,47 @@
import { BaseMetadata } from '@/types/api/api-general';
import { BaseCustomer } from '@/types/api/master-data/customer';
import { BaseProduct } from '@/types/api/master-data/product';
export type CustomerPaymentRow = {
no: number;
do_date: string;
payment_date: string;
realization_date: string;
aging: number;
reference: string;
vehicle_plate: string;
qty: number;
weight: number;
average_weight: number;
price: number;
credit_note: number;
final_price: number;
ppn: number;
total: number;
payment: number;
accounts_receivable: number;
notes: string;
pickup_info: string;
sales_marketing: string;
product?: BaseProduct;
};
export type CustomerPaymentSummary = {
total_qty: number;
total_weight: number;
total_initial_amount: number;
total_credit_note: number;
total_final_amount: number;
total_ppn: number;
total_grand_amount: number;
total_payment: number;
total_accounts_receivable: number;
};
export type CustomerPaymentReport = BaseMetadata & {
customer: BaseCustomer;
customer_npwp: string;
customer_address: string;
rows: CustomerPaymentRow[];
summary: CustomerPaymentSummary;
};
+34
View File
@@ -0,0 +1,34 @@
import { BaseMetadata } from '@/types/api/api-general';
import { Area } from '@/types/api/master-data/area';
import { Supplier } from '@/types/api/master-data/supplier';
import { Warehouse } from '@/types/api/master-data/warehouse';
export type DebtSupplier = BaseMetadata & {
supplier: Supplier;
rows: DebtRow[];
total: DebtTotal;
};
export type DebtRow = {
pr_number: string;
po_number: string;
pr_date: string;
po_date: string;
aging: number;
area: Area;
warehouse: Warehouse;
due_date: string;
due_status: string;
total_price: number;
payment_price: number;
debt_price: number;
status: string;
travel_number: string;
};
export type DebtTotal = {
aging: number;
total_price: number;
payment_price: number;
debt_price: number;
};