Merge branch 'staging' into 'production'

refactor(FE): Use local state for record date and disable

See merge request mbugroup/lti-web-client!237
This commit is contained in:
Adnan Zahir
2026-01-22 16:20:17 +07:00
17 changed files with 648 additions and 267 deletions
+4 -20
View File
@@ -4463,7 +4463,6 @@
"resolved": "https://registry.npmjs.org/@types/react/-/react-19.2.2.tgz", "resolved": "https://registry.npmjs.org/@types/react/-/react-19.2.2.tgz",
"integrity": "sha512-6mDvHUFSjyT2B2yeNx2nUgMxh9LtOWvkhIU3uePn2I2oyNymUAX1NIsdgviM4CH+JSrp2D2hsMvJOkxY+0wNRA==", "integrity": "sha512-6mDvHUFSjyT2B2yeNx2nUgMxh9LtOWvkhIU3uePn2I2oyNymUAX1NIsdgviM4CH+JSrp2D2hsMvJOkxY+0wNRA==",
"license": "MIT", "license": "MIT",
"peer": true,
"dependencies": { "dependencies": {
"csstype": "^3.0.2" "csstype": "^3.0.2"
} }
@@ -4474,7 +4473,6 @@
"integrity": "sha512-9KQPoO6mZCi7jcIStSnlOWn2nEF3mNmyr3rIAsGnAbQKYbRLyqmeSc39EVgtxXVia+LMT8j3knZLAZAh+xLmrw==", "integrity": "sha512-9KQPoO6mZCi7jcIStSnlOWn2nEF3mNmyr3rIAsGnAbQKYbRLyqmeSc39EVgtxXVia+LMT8j3knZLAZAh+xLmrw==",
"devOptional": true, "devOptional": true,
"license": "MIT", "license": "MIT",
"peer": true,
"peerDependencies": { "peerDependencies": {
"@types/react": "^19.2.0" "@types/react": "^19.2.0"
} }
@@ -4547,7 +4545,6 @@
"integrity": "sha512-BnOroVl1SgrPLywqxyqdJ4l3S2MsKVLDVxZvjI1Eoe8ev2r3kGDo+PcMihNmDE+6/KjkTubSJnmqGZZjQSBq/g==", "integrity": "sha512-BnOroVl1SgrPLywqxyqdJ4l3S2MsKVLDVxZvjI1Eoe8ev2r3kGDo+PcMihNmDE+6/KjkTubSJnmqGZZjQSBq/g==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"peer": true,
"dependencies": { "dependencies": {
"@typescript-eslint/scope-manager": "8.46.2", "@typescript-eslint/scope-manager": "8.46.2",
"@typescript-eslint/types": "8.46.2", "@typescript-eslint/types": "8.46.2",
@@ -5071,7 +5068,6 @@
"integrity": "sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg==", "integrity": "sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"peer": true,
"bin": { "bin": {
"acorn": "bin/acorn" "acorn": "bin/acorn"
}, },
@@ -6002,8 +5998,7 @@
"version": "3.1.3", "version": "3.1.3",
"resolved": "https://registry.npmjs.org/csstype/-/csstype-3.1.3.tgz", "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.1.3.tgz",
"integrity": "sha512-M1uQkMl8rQK/szD0LNhtqxIPLpimGm8sOBwU7lLnCpSbTyY3yeU1Vc7l4KT5zT4s/yOxHH5O7tIuuLOCnLADRw==", "integrity": "sha512-M1uQkMl8rQK/szD0LNhtqxIPLpimGm8sOBwU7lLnCpSbTyY3yeU1Vc7l4KT5zT4s/yOxHH5O7tIuuLOCnLADRw==",
"license": "MIT", "license": "MIT"
"peer": true
}, },
"node_modules/d3-array": { "node_modules/d3-array": {
"version": "3.2.4", "version": "3.2.4",
@@ -6430,8 +6425,7 @@
"version": "8.6.0", "version": "8.6.0",
"resolved": "https://registry.npmjs.org/embla-carousel/-/embla-carousel-8.6.0.tgz", "resolved": "https://registry.npmjs.org/embla-carousel/-/embla-carousel-8.6.0.tgz",
"integrity": "sha512-SjWyZBHJPbqxHOzckOfo8lHisEaJWmwd23XppYFYVh10bU66/Pn5tkVkbkCMZVdbUE5eTCI2nD8OyIP4Z+uwkA==", "integrity": "sha512-SjWyZBHJPbqxHOzckOfo8lHisEaJWmwd23XppYFYVh10bU66/Pn5tkVkbkCMZVdbUE5eTCI2nD8OyIP4Z+uwkA==",
"license": "MIT", "license": "MIT"
"peer": true
}, },
"node_modules/embla-carousel-react": { "node_modules/embla-carousel-react": {
"version": "8.6.0", "version": "8.6.0",
@@ -6701,7 +6695,6 @@
"integrity": "sha512-t5aPOpmtJcZcz5UJyY2GbvpDlsK5E8JqRqoKtfiKE3cNh437KIqfJr3A3AKf5k64NPx6d0G3dno6XDY05PqPtw==", "integrity": "sha512-t5aPOpmtJcZcz5UJyY2GbvpDlsK5E8JqRqoKtfiKE3cNh437KIqfJr3A3AKf5k64NPx6d0G3dno6XDY05PqPtw==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"peer": true,
"dependencies": { "dependencies": {
"@eslint-community/eslint-utils": "^4.8.0", "@eslint-community/eslint-utils": "^4.8.0",
"@eslint-community/regexpp": "^4.12.1", "@eslint-community/regexpp": "^4.12.1",
@@ -6875,7 +6868,6 @@
"integrity": "sha512-whOE1HFo/qJDyX4SnXzP4N6zOWn79WhnCUY/iDR0mPfQZO8wcYE4JClzI2oZrhBnnMUCBCHZhO6VQyoBU95mZA==", "integrity": "sha512-whOE1HFo/qJDyX4SnXzP4N6zOWn79WhnCUY/iDR0mPfQZO8wcYE4JClzI2oZrhBnnMUCBCHZhO6VQyoBU95mZA==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"peer": true,
"dependencies": { "dependencies": {
"@rtsao/scc": "^1.1.0", "@rtsao/scc": "^1.1.0",
"array-includes": "^3.1.9", "array-includes": "^3.1.9",
@@ -8508,7 +8500,6 @@
"resolved": "https://registry.npmjs.org/jspdf/-/jspdf-3.0.4.tgz", "resolved": "https://registry.npmjs.org/jspdf/-/jspdf-3.0.4.tgz",
"integrity": "sha512-dc6oQ8y37rRcHn316s4ngz/nOjayLF/FFxBF4V9zamQKRqXxyiH1zagkCdktdWhtoQId5K20xt1lB90XzkB+hQ==", "integrity": "sha512-dc6oQ8y37rRcHn316s4ngz/nOjayLF/FFxBF4V9zamQKRqXxyiH1zagkCdktdWhtoQId5K20xt1lB90XzkB+hQ==",
"license": "MIT", "license": "MIT",
"peer": true,
"dependencies": { "dependencies": {
"@babel/runtime": "^7.28.4", "@babel/runtime": "^7.28.4",
"fast-png": "^6.2.0", "fast-png": "^6.2.0",
@@ -9961,7 +9952,6 @@
"resolved": "https://registry.npmjs.org/react/-/react-19.2.3.tgz", "resolved": "https://registry.npmjs.org/react/-/react-19.2.3.tgz",
"integrity": "sha512-Ku/hhYbVjOQnXDZFv2+RibmLFGwFdeeKHFcOTlrt7xplBnya5OGn/hIRDsqDiSUcfORsDC7MPxwork8jBwsIWA==", "integrity": "sha512-Ku/hhYbVjOQnXDZFv2+RibmLFGwFdeeKHFcOTlrt7xplBnya5OGn/hIRDsqDiSUcfORsDC7MPxwork8jBwsIWA==",
"license": "MIT", "license": "MIT",
"peer": true,
"engines": { "engines": {
"node": ">=0.10.0" "node": ">=0.10.0"
} }
@@ -9992,7 +9982,6 @@
"resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.2.3.tgz", "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.2.3.tgz",
"integrity": "sha512-yELu4WmLPw5Mr/lmeEpox5rw3RETacE++JgHqQzd2dg+YbJuat3jH4ingc+WPZhxaoFzdv9y33G+F7Nl5O0GBg==", "integrity": "sha512-yELu4WmLPw5Mr/lmeEpox5rw3RETacE++JgHqQzd2dg+YbJuat3jH4ingc+WPZhxaoFzdv9y33G+F7Nl5O0GBg==",
"license": "MIT", "license": "MIT",
"peer": true,
"dependencies": { "dependencies": {
"scheduler": "^0.27.0" "scheduler": "^0.27.0"
}, },
@@ -10060,8 +10049,7 @@
"version": "16.13.1", "version": "16.13.1",
"resolved": "https://registry.npmjs.org/react-is/-/react-is-16.13.1.tgz", "resolved": "https://registry.npmjs.org/react-is/-/react-is-16.13.1.tgz",
"integrity": "sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ==", "integrity": "sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ==",
"license": "MIT", "license": "MIT"
"peer": true
}, },
"node_modules/react-number-format": { "node_modules/react-number-format": {
"version": "5.4.4", "version": "5.4.4",
@@ -10078,7 +10066,6 @@
"resolved": "https://registry.npmjs.org/react-redux/-/react-redux-9.2.0.tgz", "resolved": "https://registry.npmjs.org/react-redux/-/react-redux-9.2.0.tgz",
"integrity": "sha512-ROY9fvHhwOD9ySfrF0wmvu//bKCQ6AeZZq1nJNtbDC+kk5DuSuNX/n6YWYF/SYy7bSba4D4FSz8DJeKY/S/r+g==", "integrity": "sha512-ROY9fvHhwOD9ySfrF0wmvu//bKCQ6AeZZq1nJNtbDC+kk5DuSuNX/n6YWYF/SYy7bSba4D4FSz8DJeKY/S/r+g==",
"license": "MIT", "license": "MIT",
"peer": true,
"dependencies": { "dependencies": {
"@types/use-sync-external-store": "^0.0.6", "@types/use-sync-external-store": "^0.0.6",
"use-sync-external-store": "^1.4.0" "use-sync-external-store": "^1.4.0"
@@ -10291,8 +10278,7 @@
"version": "5.0.1", "version": "5.0.1",
"resolved": "https://registry.npmjs.org/redux/-/redux-5.0.1.tgz", "resolved": "https://registry.npmjs.org/redux/-/redux-5.0.1.tgz",
"integrity": "sha512-M9/ELqF6fy8FwmkpnF0S3YKOqMyoWJ4+CS5Efg2ct3oY9daQvd/Pc71FpGZsVsbl3Cpb+IIcjBDUnnyBdQbq4w==", "integrity": "sha512-M9/ELqF6fy8FwmkpnF0S3YKOqMyoWJ4+CS5Efg2ct3oY9daQvd/Pc71FpGZsVsbl3Cpb+IIcjBDUnnyBdQbq4w==",
"license": "MIT", "license": "MIT"
"peer": true
}, },
"node_modules/redux-thunk": { "node_modules/redux-thunk": {
"version": "3.1.0", "version": "3.1.0",
@@ -11205,7 +11191,6 @@
"integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==", "integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"peer": true,
"engines": { "engines": {
"node": ">=12" "node": ">=12"
}, },
@@ -11391,7 +11376,6 @@
"integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",
"dev": true, "dev": true,
"license": "Apache-2.0", "license": "Apache-2.0",
"peer": true,
"bin": { "bin": {
"tsc": "bin/tsc", "tsc": "bin/tsc",
"tsserver": "bin/tsserver" "tsserver": "bin/tsserver"
+6
View File
@@ -312,6 +312,12 @@ const SelectInput = <T extends OptionType>(props: SelectInputProps<T>) => {
} }
styles={{ styles={{
menuPortal: (base) => ({ ...base, zIndex: 9999 }), menuPortal: (base) => ({ ...base, zIndex: 9999 }),
multiValue(base) {
return {
...base,
borderRadius: '8px',
};
},
}} }}
onMenuScrollToBottom={onMenuScrollToBottom} onMenuScrollToBottom={onMenuScrollToBottom}
/> />
+1 -1
View File
@@ -40,7 +40,7 @@ const CheckboxOption = <
type='checkbox' type='checkbox'
checked={isSelected} checked={isSelected}
onChange={() => null} onChange={() => null}
className='checkbox checkbox-sm checkbox-primary pointer-events-none' className='checkbox checkbox-sm rounded checkbox-primary pointer-events-none'
/> />
<label className='cursor-pointer flex-1 select-none'>{label}</label> <label className='cursor-pointer flex-1 select-none'>{label}</label>
</div> </div>
+70
View File
@@ -0,0 +1,70 @@
'use client';
import { useMemo } from 'react';
import {
OptionProps,
GroupBase,
components as ReactSelectComponents,
} from 'react-select';
import SelectInput, { OptionType, SelectInputProps } from './SelectInput';
import { cn } from '@/lib/helper';
interface SelectInputRadioProps<T = OptionType>
extends Omit<SelectInputProps<T>, 'closeMenuOnSelect' | 'optionComponent'> {
closeMenuOnSelect?: boolean;
}
const RadioOption = <
T extends OptionType,
IsMulti extends boolean,
Group extends GroupBase<T>,
>(
props: OptionProps<T, IsMulti, Group>
) => {
const { isSelected, label, innerRef, innerProps, className } = props;
return (
<div
ref={innerRef}
{...innerProps}
className={cn(
'flex items-center gap-2 px-3 py-2 cursor-pointer',
className
)}
>
<input
type='radio'
checked={isSelected}
onChange={() => null}
className='radio radio-sm radio-primary pointer-events-none'
/>
<label className='cursor-pointer flex-1 select-none'>{label}</label>
</div>
);
};
const SelectInputRadio = <T extends OptionType>(
props: SelectInputRadioProps<T>
) => {
const { closeMenuOnSelect = true, className, ...restProps } = props;
const customComponents = useMemo(() => {
return {
Option: RadioOption as typeof ReactSelectComponents.Option,
};
}, []);
return (
<SelectInput<T>
{...restProps}
closeMenuOnSelect={closeMenuOnSelect}
className={{
...className,
select: cn(className?.select, 'select-radio'),
}}
components={customComponents}
/>
);
};
export default SelectInputRadio;
@@ -112,12 +112,16 @@ const SalesReportTable = ({
<div className='font-semibold text-gray-900'>Total Penjualan</div> <div className='font-semibold text-gray-900'>Total Penjualan</div>
), ),
}, },
// { {
// id: 'age', id: 'age',
// accessorKey: 'age', accessorKey: 'age',
// header: 'Umur', header: 'Umur',
// cell: (props) => props.getValue() || '-', cell: (props) => {
// }, const age = props.row.original.age;
const week = props.row.original.week;
return age && week ? `${age} hari (${week} minggu)` : '-';
},
},
{ {
id: 'do_number', id: 'do_number',
accessorKey: 'do_number', accessorKey: 'do_number',
@@ -8,7 +8,7 @@ import SelectInput, {
OptionType, OptionType,
useSelect, useSelect,
} from '@/components/input/SelectInput'; } from '@/components/input/SelectInput';
import { useState, useEffect, useRef } from 'react'; import { useState, useEffect, useRef, useCallback } from 'react';
import useSWR from 'swr'; import useSWR from 'swr';
import { DashboardApi } from '@/services/api/dashboard'; import { DashboardApi } from '@/services/api/dashboard';
import { useFormik } from 'formik'; import { useFormik } from 'formik';
@@ -38,6 +38,8 @@ import Dropdown from '@/components/Dropdown';
import Menu from '@/components/menu/Menu'; import Menu from '@/components/menu/Menu';
import MenuItem from '@/components/menu/MenuItem'; import MenuItem from '@/components/menu/MenuItem';
import { useDashboardStore } from '@/stores/dashboard'; import { useDashboardStore } from '@/stores/dashboard';
import SelectInputRadio from '@/components/input/SelectInputRadio';
import SelectInputCheckbox from '@/components/input/SelectInputCheckbox';
// Helper function to normalize values to array // Helper function to normalize values to array
const normalizeToArray = ( const normalizeToArray = (
@@ -89,7 +91,6 @@ const DashboardProduction = () => {
isLoadingOptions: isLoadingFlockOptions, isLoadingOptions: isLoadingFlockOptions,
loadMore: loadMoreFlock, loadMore: loadMoreFlock,
} = useSelect(ProjectFlockApi.basePath, 'id', 'flock_name', '', { } = useSelect(ProjectFlockApi.basePath, 'id', 'flock_name', '', {
limit: 'limit',
location_id: selectedLocationIds ? selectedLocationIds.toString() : '', location_id: selectedLocationIds ? selectedLocationIds.toString() : '',
}); });
const { const {
@@ -97,16 +98,13 @@ const DashboardProduction = () => {
options: locationOptions, options: locationOptions,
isLoadingOptions: isLoadingLocationOptions, isLoadingOptions: isLoadingLocationOptions,
loadMore: loadMoreLocation, loadMore: loadMoreLocation,
} = useSelect(LocationApi.basePath, 'id', 'name', '', { } = useSelect(LocationApi.basePath, 'id', 'name');
limit: 'limit',
});
const { const {
setInputValue: setInputValueKandang, setInputValue: setInputValueKandang,
options: kandangOptions, options: kandangOptions,
isLoadingOptions: isLoadingKandangOptions, isLoadingOptions: isLoadingKandangOptions,
loadMore: loadMoreKandang, loadMore: loadMoreKandang,
} = useSelect(KandangApi.basePath, 'id', 'name', '', { } = useSelect(KandangApi.basePath, 'id', 'name', '', {
limit: 'limit',
location_id: selectedLocationIds ? selectedLocationIds.toString() : '', location_id: selectedLocationIds ? selectedLocationIds.toString() : '',
}); });
const comparisonTypeOptions = [ const comparisonTypeOptions = [
@@ -118,17 +116,18 @@ const DashboardProduction = () => {
// ===== FORMIK ===== // ===== FORMIK =====
const formik = useFormik({ const formik = useFormik({
initialValues: { initialValues: {
startDate: filterValues.startDate || '', startDate: filterValues.startDate ?? '',
endDate: filterValues.endDate || '', endDate: filterValues.endDate ?? '',
flock: filterValues.flock || ([] as OptionType[]), flock: filterValues.flock ?? ([] as OptionType[]),
location: filterValues.location || ([] as OptionType[]), location: filterValues.location ?? ([] as OptionType[]),
kandang: filterValues.kandang || ([] as OptionType[]), kandang: filterValues.kandang ?? ([] as OptionType[]),
analysisMode: filterValues.analysisMode || analysisMode, analysisMode: filterValues.analysisMode ?? analysisMode,
comparisonType: filterValues.comparisonType || '', comparisonType: filterValues.comparisonType ?? '',
locationIds: filterValues.locationIds || [], locationIds: filterValues.locationIds ?? [],
flockIds: filterValues.flockIds || [], flockIds: filterValues.flockIds ?? [],
kandangIds: filterValues.kandangIds || [], kandangIds: filterValues.kandangIds ?? [],
} as DashboardFilterType, } as DashboardFilterType,
enableReinitialize: true,
validationSchema: getDashboardFilterSchema(analysisMode), validationSchema: getDashboardFilterSchema(analysisMode),
onSubmit: (values) => { onSubmit: (values) => {
// Save filter values to store // Save filter values to store
@@ -146,13 +145,13 @@ const DashboardProduction = () => {
}, },
}); });
const handleResetFilter = () => { const handleResetFilter = useCallback(() => {
formik.resetForm(); formik.resetForm();
resetFilterValues(); // Clear stored filter values resetFilterValues(); // Clear stored filter values
setAnalysisMode('OVERVIEW'); setAnalysisMode('OVERVIEW');
setEndpointUrl('/dashboards'); setEndpointUrl('/dashboards');
setSelectedLocationIds([]); setSelectedLocationIds([]);
}; }, [resetFilterValues, filterValues, selectedLocationIds]);
const handleApplyFilter = (values: DashboardFilter) => { const handleApplyFilter = (values: DashboardFilter) => {
// Build query params object, only include non-empty values // Build query params object, only include non-empty values
@@ -413,7 +412,7 @@ const DashboardProduction = () => {
{formik.values.analysisMode === 'COMPARISON' && ( {formik.values.analysisMode === 'COMPARISON' && (
<div className='px-4'> <div className='px-4'>
<SelectInput <SelectInputRadio
label='Compared By' label='Compared By'
value={comparisonTypeOptions.find( value={comparisonTypeOptions.find(
(option) => option.value === formik.values.comparisonType (option) => option.value === formik.values.comparisonType
@@ -437,32 +436,65 @@ const DashboardProduction = () => {
{/* Location */} {/* Location */}
<div className='px-4'> <div className='px-4'>
<SelectInput {comparisonTypeOptions.find(
label='Farm' (option) => option.value === formik.values.comparisonType
value={formik.values.location} )?.value === 'FARM' ? (
onInputChange={setInputValueLocation} <SelectInputCheckbox
onMenuScrollToBottom={loadMoreLocation} label='Farm'
onChange={(selected) => { value={
formik.setFieldValue('location', selected); formik.values.location as
// Update selectedLocationIds for kandang filter | { value: number; label: string }
setSelectedLocationIds(normalizeToArray(selected)); | { value: number; label: string }[]
// Reset dependent fields when location changes | null
formik.setFieldValue('flock', []); | undefined
formik.setFieldValue('kandang', []); }
}} onInputChange={setInputValueLocation}
errorMessage={formik.errors.location as string} onMenuScrollToBottom={loadMoreLocation}
options={locationOptions} onChange={(selected) => {
isLoading={isLoadingLocationOptions} formik.setFieldValue('location', selected);
isMulti={ // Update selectedLocationIds for kandang filter
comparisonTypeOptions.find( setSelectedLocationIds(normalizeToArray(selected));
(option) => option.value === formik.values.comparisonType // Reset dependent fields when location changes
)?.value === 'FARM' formik.setFieldValue('flock', []);
} formik.setFieldValue('kandang', []);
isError={ }}
Boolean(formik.errors.location) && errorMessage={formik.errors.location as string}
Boolean(formik.touched.location) options={locationOptions}
} isLoading={isLoadingLocationOptions}
/> isError={
Boolean(formik.errors.location) &&
Boolean(formik.touched.location)
}
/>
) : (
<SelectInputRadio
label='Farm'
value={
formik.values.location as
| { value: number; label: string }
| { value: number; label: string }[]
| null
| undefined
}
onInputChange={setInputValueLocation}
onMenuScrollToBottom={loadMoreLocation}
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}
isError={
Boolean(formik.errors.location) &&
Boolean(formik.touched.location)
}
/>
)}
</div> </div>
{/* Flock */} {/* Flock */}
@@ -474,27 +506,55 @@ const DashboardProduction = () => {
) )
) && ( ) && (
<div className='px-4'> <div className='px-4'>
<SelectInput {comparisonTypeOptions.find(
label='Flock' (option) => option.value === formik.values.comparisonType
value={formik.values.flock} )?.value === 'FLOCK' ? (
onChange={(selected) => <SelectInputCheckbox
formik.setFieldValue('flock', selected) label='Flock'
} value={
errorMessage={formik.errors.flock as string} formik.values.flock as
onInputChange={setInputValueFlock} | { value: number; label: string }
onMenuScrollToBottom={loadMoreFlock} | { value: number; label: string }[]
options={flockOptions} | null
isLoading={isLoadingFlockOptions} | undefined
isMulti={ }
comparisonTypeOptions.find( onChange={(selected) =>
(option) => option.value === formik.values.comparisonType formik.setFieldValue('flock', selected)
)?.value === 'FLOCK' }
} errorMessage={formik.errors.flock as string}
isError={ onInputChange={setInputValueFlock}
Boolean(formik.errors.flock) && onMenuScrollToBottom={loadMoreFlock}
Boolean(formik.touched.flock) options={flockOptions}
} isLoading={isLoadingFlockOptions}
/> isError={
Boolean(formik.errors.flock) &&
Boolean(formik.touched.flock)
}
/>
) : (
<SelectInputRadio
label='Flock'
value={
formik.values.flock as
| { value: number; label: string }
| { value: number; label: string }[]
| null
| undefined
}
onChange={(selected) =>
formik.setFieldValue('flock', selected)
}
errorMessage={formik.errors.flock as string}
onInputChange={setInputValueFlock}
onMenuScrollToBottom={loadMoreFlock}
options={flockOptions}
isLoading={isLoadingFlockOptions}
isError={
Boolean(formik.errors.flock) &&
Boolean(formik.touched.flock)
}
/>
)}
</div> </div>
)} )}
@@ -504,27 +564,55 @@ const DashboardProduction = () => {
!(formik.values.comparisonType === 'KANDANG') !(formik.values.comparisonType === 'KANDANG')
) && ( ) && (
<div className='px-4'> <div className='px-4'>
<SelectInput {comparisonTypeOptions.find(
label='Kandang' (option) => option.value === formik.values.comparisonType
value={formik.values.kandang} )?.value === 'KANDANG' ? (
onChange={(selected) => <SelectInputCheckbox
formik.setFieldValue('kandang', selected) label='Kandang'
} value={
errorMessage={formik.errors.kandang as string} formik.values.kandang as
onInputChange={setInputValueKandang} | { value: number; label: string }
onMenuScrollToBottom={loadMoreKandang} | { value: number; label: string }[]
options={kandangOptions} | null
isLoading={isLoadingKandangOptions} | undefined
isMulti={ }
comparisonTypeOptions.find( onChange={(selected) =>
(option) => option.value === formik.values.comparisonType formik.setFieldValue('kandang', selected)
)?.value === 'KANDANG' }
} errorMessage={formik.errors.kandang as string}
isError={ onInputChange={setInputValueKandang}
Boolean(formik.errors.kandang) && onMenuScrollToBottom={loadMoreKandang}
Boolean(formik.touched.kandang) options={kandangOptions}
} isLoading={isLoadingKandangOptions}
/> isError={
Boolean(formik.errors.kandang) &&
Boolean(formik.touched.kandang)
}
/>
) : (
<SelectInputRadio
label='Kandang'
value={
formik.values.kandang as
| { value: number; label: string }
| { value: number; label: string }[]
| null
| undefined
}
onChange={(selected) =>
formik.setFieldValue('kandang', selected)
}
errorMessage={formik.errors.kandang as string}
onInputChange={setInputValueKandang}
onMenuScrollToBottom={loadMoreKandang}
options={kandangOptions}
isLoading={isLoadingKandangOptions}
isError={
Boolean(formik.errors.kandang) &&
Boolean(formik.touched.kandang)
}
/>
)}
</div> </div>
)} )}
@@ -54,9 +54,6 @@ const FormFinanceAdd = ({
}: FormFinanceAddProps) => { }: FormFinanceAddProps) => {
const router = useRouter(); const router = useRouter();
const [serverErrorMessage, setServerErrorMessage] = useState(''); const [serverErrorMessage, setServerErrorMessage] = useState('');
const [isSupplier, setIsSupplier] = useState(
initialValues?.party?.type === 'SUPPLIER'
);
// ===== Formik ===== // ===== Formik =====
const formikInitialValues = useMemo((): FinanceFormValues => { const formikInitialValues = useMemo((): FinanceFormValues => {
@@ -215,7 +212,7 @@ const FormFinanceAdd = ({
? formik.errors.party_type_option ? formik.errors.party_type_option
: '' : ''
} }
isDisabled={type === 'edit' || isSupplier} isDisabled={type === 'edit'}
required required
isClearable isClearable
/> />
@@ -254,7 +251,7 @@ const FormFinanceAdd = ({
} }
required required
isClearable isClearable
isDisabled={!formik.values.party_type_option?.value || isSupplier} isDisabled={!formik.values.party_type_option?.value}
/> />
<DateInput <DateInput
label='Tanggal' label='Tanggal'
@@ -272,7 +269,6 @@ const FormFinanceAdd = ({
: '' : ''
} }
required required
disabled={isSupplier}
/> />
<SelectInput <SelectInput
label='Metode Pembayaran' label='Metode Pembayaran'
@@ -294,7 +290,6 @@ const FormFinanceAdd = ({
} }
required required
isClearable isClearable
isDisabled={isSupplier}
/> />
<SelectInput <SelectInput
label='Bank' label='Bank'
@@ -335,7 +330,6 @@ const FormFinanceAdd = ({
} }
required required
isClearable isClearable
isDisabled={isSupplier}
/> />
<TextInput <TextInput
label={`Nomor Rekening ${formik.values.party_type_option?.value ? formatTitleCase(formik.values.party_type_option.value as string) : 'Pihak'}`} label={`Nomor Rekening ${formik.values.party_type_option?.value ? formatTitleCase(formik.values.party_type_option.value as string) : 'Pihak'}`}
@@ -356,7 +350,6 @@ const FormFinanceAdd = ({
} }
required required
readOnly readOnly
disabled={isSupplier}
/> />
<TextInput <TextInput
label='Nomor Referensi' label='Nomor Referensi'
@@ -376,7 +369,6 @@ const FormFinanceAdd = ({
: '' : ''
} }
required required
disabled={isSupplier}
/> />
<NumberInput <NumberInput
label='Nominal' label='Nominal'
@@ -392,7 +384,6 @@ const FormFinanceAdd = ({
: '' : ''
} }
required required
disabled={isSupplier}
/> />
<TextArea <TextArea
label='Catatan' label='Catatan'
@@ -408,7 +399,6 @@ const FormFinanceAdd = ({
: '' : ''
} }
required required
disabled={isSupplier}
/> />
<AlertErrorList formErrorList={formErrorList} onClose={close} /> <AlertErrorList formErrorList={formErrorList} onClose={close} />
{serverErrorMessage && ( {serverErrorMessage && (
@@ -143,11 +143,13 @@ const DeliveryOrderProductForm = ({
// ===== SOURCE FIELDS ===== // ===== SOURCE FIELDS =====
case 'qty': { case 'qty': {
if (avgWeight > 0) { if (avgWeight > 0) {
formik.setFieldValue('total_weight', roundWeight(qty * avgWeight)); const tw = roundWeight(qty * avgWeight);
} formik.setFieldValue('total_weight', tw);
if (unitPrice > 0) { // Hitung total_price berdasarkan unit_price × total_weight
formik.setFieldValue('total_price', roundPrice(qty * unitPrice)); if (unitPrice > 0) {
formik.setFieldValue('total_price', roundPrice(unitPrice * tw));
}
} }
break; break;
} }
@@ -157,16 +159,21 @@ const DeliveryOrderProductForm = ({
const tw = roundWeight(qty * avgWeight); const tw = roundWeight(qty * avgWeight);
formik.setFieldValue('total_weight', tw); formik.setFieldValue('total_weight', tw);
// Hitung total_price berdasarkan unit_price × total_weight
if (unitPrice > 0) { if (unitPrice > 0) {
formik.setFieldValue('total_price', roundPrice(qty * unitPrice)); formik.setFieldValue('total_price', roundPrice(unitPrice * tw));
} }
} }
break; break;
} }
case 'unit_price': { case 'unit_price': {
if (unitPrice > 0) { if (unitPrice > 0 && totalWeight > 0) {
formik.setFieldValue('total_price', roundPrice(qty * unitPrice)); // Hitung total_price berdasarkan unit_price × total_weight
formik.setFieldValue(
'total_price',
roundPrice(unitPrice * totalWeight)
);
} }
break; break;
} }
@@ -175,13 +182,25 @@ const DeliveryOrderProductForm = ({
case 'total_weight': { case 'total_weight': {
if (totalWeight > 0) { if (totalWeight > 0) {
formik.setFieldValue('avg_weight', roundWeight(totalWeight / qty)); formik.setFieldValue('avg_weight', roundWeight(totalWeight / qty));
// Hitung ulang total_price berdasarkan unit_price × total_weight
if (unitPrice > 0) {
formik.setFieldValue(
'total_price',
roundPrice(unitPrice * totalWeight)
);
}
} }
break; break;
} }
case 'total_price': { case 'total_price': {
if (totalPrice > 0) { if (totalPrice > 0 && totalWeight > 0) {
formik.setFieldValue('unit_price', roundPrice(totalPrice / qty)); // Hitung unit_price berdasarkan total_price / total_weight
formik.setFieldValue(
'unit_price',
roundPrice(totalPrice / totalWeight)
);
} }
break; break;
} }
@@ -382,7 +401,7 @@ const DeliveryOrderProductForm = ({
/> />
<NumberInput <NumberInput
required required
label='Harga Satuan (Rp)' label={`Harga / ${isResponseSuccess(productData) ? productData?.data?.uom?.name : 'Produk'} (Rp)`}
name='unit_price' name='unit_price'
value={formik.values.unit_price} value={formik.values.unit_price}
onChange={(e) => { onChange={(e) => {
@@ -49,17 +49,6 @@ const SalesOrderProductForm = ({
const [selectedProductWarehouse, setSelectedProductWarehouse] = const [selectedProductWarehouse, setSelectedProductWarehouse] =
useState<ProductWarehouse | null>(null); useState<ProductWarehouse | null>(null);
// ============ Fetch Data ============
const { data: productData } = useSWR(
selectedProductWarehouse?.product_id
? ProductApi.basePath + '/' + selectedProductWarehouse?.product_id
: null,
() =>
selectedProductWarehouse?.product_id
? ProductApi.getSingle(selectedProductWarehouse?.product_id)
: undefined
);
// ============ Formik ============ // ============ Formik ============
const formik = useFormik<SalesOrderProductFormValues>({ const formik = useFormik<SalesOrderProductFormValues>({
enableReinitialize: true, enableReinitialize: true,
@@ -174,15 +163,28 @@ const SalesOrderProductForm = ({
if (qty <= 0) return; if (qty <= 0) return;
// Cek apakah produk memiliki flag OVK atau PAKAN
const productFlags = selectedProductWarehouse?.product?.flags || [];
const isOvkOrPakan =
productFlags.includes('OVK') || productFlags.includes('PAKAN');
switch (field) { switch (field) {
// ===== SOURCE FIELDS ===== // ===== SOURCE FIELDS =====
case 'qty': { case 'qty': {
if (avgWeight > 0) { if (avgWeight > 0) {
formik.setFieldValue('total_weight', roundWeight(qty * avgWeight)); const tw = roundWeight(qty * avgWeight);
} formik.setFieldValue('total_weight', tw);
if (unitPrice > 0) { // Hitung total_price berdasarkan flag produk
formik.setFieldValue('total_price', roundPrice(qty * unitPrice)); if (unitPrice > 0) {
if (isOvkOrPakan) {
// Untuk OVK/PAKAN: total_price = qty × unit_price
formik.setFieldValue('total_price', roundPrice(qty * unitPrice));
} else {
// Untuk produk lain: total_price = unit_price × total_weight
formik.setFieldValue('total_price', roundPrice(unitPrice * tw));
}
}
} }
break; break;
} }
@@ -192,8 +194,15 @@ const SalesOrderProductForm = ({
const tw = roundWeight(qty * avgWeight); const tw = roundWeight(qty * avgWeight);
formik.setFieldValue('total_weight', tw); formik.setFieldValue('total_weight', tw);
// Hitung total_price berdasarkan flag produk
if (unitPrice > 0) { if (unitPrice > 0) {
formik.setFieldValue('total_price', roundPrice(qty * unitPrice)); if (isOvkOrPakan) {
// Untuk OVK/PAKAN: total_price = qty × unit_price
formik.setFieldValue('total_price', roundPrice(qty * unitPrice));
} else {
// Untuk produk lain: total_price = unit_price × total_weight
formik.setFieldValue('total_price', roundPrice(unitPrice * tw));
}
} }
} }
break; break;
@@ -201,7 +210,16 @@ const SalesOrderProductForm = ({
case 'unit_price': { case 'unit_price': {
if (unitPrice > 0) { if (unitPrice > 0) {
formik.setFieldValue('total_price', roundPrice(qty * unitPrice)); if (isOvkOrPakan) {
// Untuk OVK/PAKAN: total_price = qty × unit_price
formik.setFieldValue('total_price', roundPrice(qty * unitPrice));
} else if (totalWeight > 0) {
// Untuk produk lain: total_price = unit_price × total_weight
formik.setFieldValue(
'total_price',
roundPrice(unitPrice * totalWeight)
);
}
} }
break; break;
} }
@@ -210,13 +228,36 @@ const SalesOrderProductForm = ({
case 'total_weight': { case 'total_weight': {
if (totalWeight > 0) { if (totalWeight > 0) {
formik.setFieldValue('avg_weight', roundWeight(totalWeight / qty)); formik.setFieldValue('avg_weight', roundWeight(totalWeight / qty));
// Hitung ulang total_price berdasarkan flag produk
if (unitPrice > 0) {
if (isOvkOrPakan) {
// Untuk OVK/PAKAN: total_price = qty × unit_price
formik.setFieldValue('total_price', roundPrice(qty * unitPrice));
} else {
// Untuk produk lain: total_price = unit_price × total_weight
formik.setFieldValue(
'total_price',
roundPrice(unitPrice * totalWeight)
);
}
}
} }
break; break;
} }
case 'total_price': { case 'total_price': {
if (totalPrice > 0) { if (totalPrice > 0) {
formik.setFieldValue('unit_price', roundPrice(totalPrice / qty)); if (isOvkOrPakan && qty > 0) {
// Untuk OVK/PAKAN: unit_price = total_price / qty
formik.setFieldValue('unit_price', roundPrice(totalPrice / qty));
} else if (totalWeight > 0) {
// Untuk produk lain: unit_price = total_price / total_weight
formik.setFieldValue(
'unit_price',
roundPrice(totalPrice / totalWeight)
);
}
} }
break; break;
} }
@@ -232,7 +273,7 @@ const SalesOrderProductForm = ({
handleBlurField(currentInput); handleBlurField(currentInput);
formik.setFieldValue( formik.setFieldValue(
'uom', 'uom',
isResponseSuccess(productData) ? productData?.data?.uom.name : '' selectedProductWarehouse?.product?.uom?.name
); );
}, },
} }
@@ -330,9 +371,7 @@ const SalesOrderProductForm = ({
endAdornment={ endAdornment={
<div className='flex items-center gap-2'> <div className='flex items-center gap-2'>
<span className='text-sm text-gray-500'> <span className='text-sm text-gray-500'>
{isResponseSuccess(productData) {selectedProductWarehouse?.product?.uom?.name}
? productData?.data?.uom.name
: ''}
</span> </span>
</div> </div>
} }
@@ -343,17 +382,13 @@ const SalesOrderProductForm = ({
warehouseSourceRawData?.data?.find( warehouseSourceRawData?.data?.find(
(item) => item.id === formik.values.product_warehouse_id (item) => item.id === formik.values.product_warehouse_id
)?.quantity ?? 0 )?.quantity ?? 0
)} ${ )} ${selectedProductWarehouse?.product?.uom?.name}`
isResponseSuccess(productData)
? productData?.data?.uom.name
: ''
}`
: '' : ''
} }
/> />
<NumberInput <NumberInput
required required
label='Harga Satuan (Rp)' label={`Harga / ${selectedProductWarehouse?.product?.uom?.name ?? 'Produk'} (Rp)`}
name='unit_price' name='unit_price'
value={formik.values.unit_price} value={formik.values.unit_price}
onChange={(e) => { onChange={(e) => {
@@ -1,6 +1,12 @@
'use client'; 'use client';
import React, { useCallback, useState, useMemo, useEffect } from 'react'; import React, {
useCallback,
useState,
useMemo,
useEffect,
useRef,
} from 'react';
import { RefObject } from 'react'; import { RefObject } from 'react';
import useSWR from 'swr'; import useSWR from 'swr';
import { Icon } from '@iconify/react'; import { Icon } from '@iconify/react';
@@ -28,6 +34,7 @@ import { useTableFilter } from '@/services/hooks/useTableFilter';
import toast from 'react-hot-toast'; import toast from 'react-hot-toast';
import Badge from '@/components/Badge'; import Badge from '@/components/Badge';
import CheckboxInput from '@/components/input/CheckboxInput'; import CheckboxInput from '@/components/input/CheckboxInput';
import { useUiStore } from '@/stores/ui/ui.store';
import { BaseApproval, BaseApiResponse } from '@/types/api/api-general'; import { BaseApproval, BaseApiResponse } from '@/types/api/api-general';
const RowOptionsMenu = ({ const RowOptionsMenu = ({
@@ -344,6 +351,9 @@ const ApprovalHistoryModal = ({
}; };
const RecordingTable = () => { const RecordingTable = () => {
const { searchValue, setSearchValue, resetSearchValue } = useUiStore();
const previousPathRef = useRef<string | null>(null);
const { const {
state: tableFilterState, state: tableFilterState,
updateFilter, updateFilter,
@@ -352,7 +362,7 @@ const RecordingTable = () => {
toQueryString: getTableFilterQueryString, toQueryString: getTableFilterQueryString,
} = useTableFilter({ } = useTableFilter({
initial: { initial: {
search: '', search: searchValue,
areaFilter: '', areaFilter: '',
locationFilter: '', locationFilter: '',
kandangFilter: '', kandangFilter: '',
@@ -403,12 +413,35 @@ const RecordingTable = () => {
); );
}, []); }, []);
useEffect(() => {
// Store current path on mount
previousPathRef.current = window.location.pathname;
return () => {
const currentPath = window.location.pathname;
// if both paths are within /production/recording module
const isCurrentPathRecording = currentPath.includes(
'/production/recording'
);
const isPreviousPathRecording = previousPathRef.current?.includes(
'/production/recording'
);
// reset if we outside recording module entirely
if (isPreviousPathRecording && !isCurrentPathRecording) {
resetSearchValue();
}
};
}, [resetSearchValue]);
const searchChangeHandler = useCallback( const searchChangeHandler = useCallback(
(e: React.ChangeEvent<HTMLInputElement>) => { (e: React.ChangeEvent<HTMLInputElement>) => {
updateFilter('search', e.target.value); updateFilter('search', e.target.value);
setSearchValue(e.target.value);
setPage(1); setPage(1);
}, },
[updateFilter, setPage] [updateFilter, setSearchValue, setPage]
); );
const pageSizeChangeHandler = useCallback( const pageSizeChangeHandler = useCallback(
@@ -23,6 +23,7 @@ import ConfirmationModalWithNotes from '@/components/modal/ConfirmationModalWith
import Modal, { useModal } from '@/components/Modal'; import Modal, { useModal } from '@/components/Modal';
import AlertErrorList from '@/components/helper/form/FormErrors'; import AlertErrorList from '@/components/helper/form/FormErrors';
import Table from '@/components/Table'; import Table from '@/components/Table';
import Tooltip from '@/components/Tooltip';
import { type ColumnDef } from '@tanstack/react-table'; import { type ColumnDef } from '@tanstack/react-table';
import { import {
@@ -197,6 +198,11 @@ const RecordingForm = ({ type = 'add', initialValues }: RecordingFormProps) => {
const router = useRouter(); const router = useRouter();
// ===== STATE MANAGEMENT ===== // ===== STATE MANAGEMENT =====
const [selectedRecordDate, setSelectedRecordDate] = useState<string>(
initialValues?.record_datetime
? new Date(initialValues.record_datetime).toISOString().split('T')[0]
: new Date().toISOString().split('T')[0]
);
const [selectedStocks, setSelectedStocks] = useState<number[]>([]); const [selectedStocks, setSelectedStocks] = useState<number[]>([]);
const [selectedDepletions, setSelectedDepletions] = useState<number[]>([]); const [selectedDepletions, setSelectedDepletions] = useState<number[]>([]);
const [selectedEggs, setSelectedEggs] = useState<number[]>([]); const [selectedEggs, setSelectedEggs] = useState<number[]>([]);
@@ -911,6 +917,8 @@ const RecordingForm = ({ type = 'add', initialValues }: RecordingFormProps) => {
baseValues = getRecordingGrowingFormInitialValues(initialValues); baseValues = getRecordingGrowingFormInitialValues(initialValues);
} }
baseValues.record_date = selectedRecordDate;
if (type === 'add') { if (type === 'add') {
baseValues.location = selectedLocation baseValues.location = selectedLocation
? { ? {
@@ -967,13 +975,22 @@ const RecordingForm = ({ type = 'add', initialValues }: RecordingFormProps) => {
} }
return baseValues; return baseValues;
}, [initialValues, isLayingCategory, projectFlockKandangDetail, type]); }, [
initialValues,
isLayingCategory,
projectFlockKandangDetail,
type,
selectedRecordDate,
selectedLocation,
selectedProjectFlock,
selectedKandang,
]);
const formik = useFormik< const formik = useFormik<
RecordingGrowingFormValues | RecordingLayingFormValues RecordingGrowingFormValues | RecordingLayingFormValues
>({ >({
initialValues: formikInitialValues, initialValues: formikInitialValues,
enableReinitialize: true, enableReinitialize: false,
validationSchema: (() => { validationSchema: (() => {
let schema; let schema;
if (isLayingCategory) { if (isLayingCategory) {
@@ -1333,6 +1350,7 @@ const RecordingForm = ({ type = 'add', initialValues }: RecordingFormProps) => {
(e: React.ChangeEvent<HTMLInputElement>) => { (e: React.ChangeEvent<HTMLInputElement>) => {
const newDate = e.target.value; const newDate = e.target.value;
formik.setFieldValue('record_date', newDate); formik.setFieldValue('record_date', newDate);
setSelectedRecordDate(newDate);
setCurrentRecordDate(newDate); setCurrentRecordDate(newDate);
if (duplicateErrorShown) { if (duplicateErrorShown) {
toast.dismiss(); toast.dismiss();
@@ -2799,7 +2817,23 @@ const RecordingForm = ({ type = 'add', initialValues }: RecordingFormProps) => {
)} )}
<th>Kondisi Telur</th> <th>Kondisi Telur</th>
<th>Jumlah</th> <th>Jumlah</th>
<th>Total Berat (Kilogram)</th> <th className='flex items-center gap-1'>
Total Berat (Kilogram)
<Tooltip
className={{
wrapper: 'cursor-pointer',
}}
position='bottom'
content='Untuk menggunakan koma bisa menekan tombol titik (.) pada keyboard, Misal 0.123'
>
<Icon
icon='heroicons:information-circle'
width={20}
height={20}
className='text-gray-400 hover:text-gray-600 shrink-0'
/>
</Tooltip>
</th>
{(type as 'add' | 'edit' | 'detail') !== 'detail' && ( {(type as 'add' | 'edit' | 'detail') !== 'detail' && (
<th>Action</th> <th>Action</th>
)} )}
@@ -2905,7 +2939,7 @@ const RecordingForm = ({ type = 'add', initialValues }: RecordingFormProps) => {
value={egg.weight ?? ''} value={egg.weight ?? ''}
onChange={handleEggWeightChangeWrapper(idx)} onChange={handleEggWeightChangeWrapper(idx)}
onBlur={formik.handleBlur} onBlur={formik.handleBlur}
decimalScale={0} decimalScale={3}
allowNegative={false} allowNegative={false}
thousandSeparator=',' thousandSeparator=','
decimalSeparator='.' decimalSeparator='.'
@@ -1,6 +1,6 @@
'use client'; 'use client';
import * as XLSX from 'xlsx'; import ExcelJS from 'exceljs';
import { formatDate } from '@/lib/helper'; import { formatDate } from '@/lib/helper';
import { DebtRow, DebtSupplier } from '@/types/api/report/debt-supplier'; import { DebtRow, DebtSupplier } from '@/types/api/report/debt-supplier';
@@ -8,115 +8,174 @@ interface DebtSupplierExportExcelParams {
data: DebtSupplier[]; data: DebtSupplier[];
} }
export const generateDebtSupplierExcel = ( export const generateDebtSupplierExcel = async (
params: DebtSupplierExportExcelParams params: DebtSupplierExportExcelParams
): void => { ): Promise<void> => {
if (!params.data || params.data.length === 0) { if (!params.data || params.data.length === 0) {
return; return;
} }
const workbook = XLSX.utils.book_new(); const workbook = new ExcelJS.Workbook();
params.data.forEach((supplierReport) => { const columns = [
{ header: 'No', key: 'no', width: 5 },
{ header: 'Nomor PR', key: 'prNumber', width: 14 },
{ header: 'Nomor PO', key: 'poNumber', width: 14 },
{ header: 'Tanggal Terima/Bayar', key: 'receivedDate', width: 20 },
{ header: 'Tanggal PO', key: 'poDate', width: 10 },
{ header: 'Aging (Hari)', key: 'aging', width: 10 },
{ header: 'Area', key: 'area', width: 15 },
{ header: 'Gudang', key: 'warehouse', width: 15 },
{ header: 'Jatuh Tempo', key: 'dueDate', width: 12 },
{ header: 'Status Jatuh Tempo', key: 'dueStatus', width: 20 },
{ header: 'Nominal Pembelian (Rp)', key: 'totalPrice', width: 20 },
{ header: 'Pembayaran (Rp)', key: 'paymentPrice', width: 15 },
{ header: 'Sisa Saldo Hutang (Rp)', key: 'balance', width: 20 },
{ header: 'Status', key: 'status', width: 12 },
{ header: 'Nomor Perjalanan', key: 'travelNumber', width: 15 },
];
for (const supplierReport of params.data) {
const supplierData = supplierReport.rows; const supplierData = supplierReport.rows;
const supplierName = supplierReport.supplier.name || 'Unknown Supplier'; const supplierName = supplierReport.supplier.name || 'Unknown Supplier';
const excelData: { [key: string]: string | number }[] = [ const worksheet = workbook.addWorksheet(supplierName.substring(0, 31));
{ worksheet.columns = columns;
No: '',
'Nomor PR': '', // Add initial balance row
'Nomor PO': '', const initialRow = worksheet.addRow({
'Tanggal Terima/Bayar': '', no: '',
'Tanggal PO': '', prNumber: '',
'Aging (Hari)': '', poNumber: '',
Area: '', receivedDate: '',
Gudang: '', poDate: '',
'Jatuh Tempo': '', aging: '',
'Status Jatuh Tempo': '', area: '',
'Nominal Pembelian (Rp)': '', warehouse: '',
'Pembayaran (Rp)': '', dueDate: '',
'Sisa Saldo Hutang (Rp)': supplierReport.initial_balance || 0, dueStatus: '',
Status: '', totalPrice: '',
'Nomor Perjalanan': '', paymentPrice: '',
}, balance: supplierReport.initial_balance || 0,
...supplierData.map((item, index) => ({ status: '',
No: index + 1, travelNumber: '',
'Nomor PR': item.pr_number || '', });
'Nomor PO': item.po_number || '',
'Tanggal Terima/Bayar': item.received_date // Apply red color if initial balance is negative
const initialBalanceCell = initialRow.getCell('balance');
if (
typeof supplierReport.initial_balance === 'number' &&
supplierReport.initial_balance < 0
) {
initialBalanceCell.font = { color: { argb: 'FFFF0000' } };
}
// Add data rows
supplierData.forEach((item, index) => {
const row = worksheet.addRow({
no: index + 1,
prNumber: item.pr_number || '',
poNumber: item.po_number || '',
receivedDate: item.received_date
? item.received_date != '-' ? item.received_date != '-'
? formatDate(item.received_date, 'MM/DD/YYYY') ? formatDate(item.received_date, 'MM/DD/YYYY')
: '-' : '-'
: '-', : '-',
'Tanggal PO': item.po_date poDate: item.po_date
? item.po_date != '-' ? item.po_date != '-'
? formatDate(item.po_date, 'MM/DD/YYYY') ? formatDate(item.po_date, 'MM/DD/YYYY')
: '-' : '-'
: '-', : '-',
'Aging (Hari)': item.aging || 0, aging: item.aging || 0,
Area: item.area?.name || '', area: item.area?.name || '',
Gudang: item.warehouse?.name || '', warehouse: item.warehouse?.name || '',
'Jatuh Tempo': item.due_date dueDate: item.due_date
? item.due_date != '-' ? item.due_date != '-'
? formatDate(item.due_date, 'MM/DD/YYYY') ? formatDate(item.due_date, 'MM/DD/YYYY')
: '-' : '-'
: '-', : '-',
'Status Jatuh Tempo': item.due_status || '', dueStatus: item.due_status || '',
'Nominal Pembelian (Rp)': item.total_price || 0, totalPrice: item.total_price || 0,
'Pembayaran (Rp)': item.payment_price || 0, paymentPrice: item.payment_price || 0,
'Sisa Saldo Hutang (Rp)': item.balance || 0, balance: item.balance || 0,
Status: item.status || '', status: item.status || '',
'Nomor Perjalanan': item.travel_number || '', travelNumber: item.travel_number || '',
})),
];
if (supplierReport.total) {
excelData.push({
No: 'Total',
'Nomor PR': '',
'Nomor PO': '',
'Tanggal Terima/Bayar': '',
'Tanggal PO': '',
'Aging (Hari)': supplierReport.total.aging || 0,
Area: '',
Gudang: '',
'Jatuh Tempo': '',
'Status Jatuh Tempo': '',
'Nominal Pembelian (Rp)': supplierReport.total.total_price || 0,
'Pembayaran (Rp)': supplierReport.total.payment_price || 0,
'Sisa Saldo Hutang (Rp)': supplierReport.total.debt_price || 0,
Status: '',
'Nomor Perjalanan': '',
}); });
// Apply red color for negative values
const totalPriceCell = row.getCell('totalPrice');
if (typeof item.total_price === 'number' && item.total_price < 0) {
totalPriceCell.font = { color: { argb: 'FFFF0000' } };
}
const paymentPriceCell = row.getCell('paymentPrice');
if (typeof item.payment_price === 'number' && item.payment_price < 0) {
paymentPriceCell.font = { color: { argb: 'FFFF0000' } };
}
const balanceCell = row.getCell('balance');
if (typeof item.balance === 'number' && item.balance < 0) {
balanceCell.font = { color: { argb: 'FFFF0000' } };
}
});
// Add total row
if (supplierReport.total) {
const totalRow = worksheet.addRow({
no: 'Total',
prNumber: '',
poNumber: '',
receivedDate: '',
poDate: '',
aging: supplierReport.total.aging || 0,
area: '',
warehouse: '',
dueDate: '',
dueStatus: '',
totalPrice: supplierReport.total.total_price || 0,
paymentPrice: supplierReport.total.payment_price || 0,
balance: supplierReport.total.debt_price || 0,
status: '',
travelNumber: '',
});
// Apply red color for negative totals
const totalPriceCell = totalRow.getCell('totalPrice');
if (
typeof supplierReport.total.total_price === 'number' &&
supplierReport.total.total_price < 0
) {
totalPriceCell.font = { color: { argb: 'FFFF0000' } };
}
const paymentPriceCell = totalRow.getCell('paymentPrice');
if (
typeof supplierReport.total.payment_price === 'number' &&
supplierReport.total.payment_price < 0
) {
paymentPriceCell.font = { color: { argb: 'FFFF0000' } };
}
const balanceCell = totalRow.getCell('balance');
if (
typeof supplierReport.total.debt_price === 'number' &&
supplierReport.total.debt_price < 0
) {
balanceCell.font = { color: { argb: 'FFFF0000' } };
}
} }
}
const worksheet = XLSX.utils.json_to_sheet(excelData);
const colWidths = [
{ wch: 5 }, // No
{ wch: 10 }, // Nomor PR
{ wch: 10 }, // Nomor PO
{ wch: 20 }, // Tanggal Terima/Bayar
{ wch: 10 }, // Tanggal PO
{ wch: 10 }, // Aging
{ wch: 15 }, // Area
{ wch: 15 }, // Gudang
{ wch: 12 }, // Jatuh Tempo
{ wch: 20 }, // Status Jatuh Tempo
{ wch: 20 }, // Nominal Pembelian (Rp)
{ wch: 15 }, // Pembayaran (Rp)
{ wch: 20 }, // Sisa Saldo Hutang (Rp)
{ 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`; const filename = `laporan-hutang-supplier-${formatDate(new Date(), 'YYYY-MM-DD-HHmm')}.xlsx`;
XLSX.writeFile(workbook, filename); const buffer = await workbook.xlsx.writeBuffer();
const blob = new Blob([buffer], {
type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
});
const url = window.URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = filename;
link.click();
window.URL.revokeObjectURL(url);
}; };
@@ -35,6 +35,8 @@ import ButtonFilter from '@/components/helper/ButtonFilter';
import Badge from '@/components/Badge'; import Badge from '@/components/Badge';
import { Color } from '@/types/theme'; import { Color } from '@/types/theme';
import { Supplier } from '@/types/api/master-data/supplier'; import { Supplier } from '@/types/api/master-data/supplier';
import SelectInputCheckbox from '@/components/input/SelectInputCheckbox';
import SelectInputRadio from '@/components/input/SelectInputRadio';
const dueStatus: Record<string, Color> = { const dueStatus: Record<string, Color> = {
'Sudah Jatuh Tempo': 'error', 'Sudah Jatuh Tempo': 'error',
@@ -671,12 +673,18 @@ const DebtSupplierTab = () => {
</div> </div>
<div> <div>
<SelectInput <SelectInputCheckbox
label='Supplier' label='Supplier'
placeholder='Pilih Supplier' placeholder='Pilih Supplier'
isMulti isMulti
options={supplierOptions} options={supplierOptions}
value={formik.values.supplierIds || []} value={
(formik.values.supplierIds as
| { value: number; label: string }
| { value: number; label: string }[]
| null
| undefined) || []
}
onChange={(val) => { onChange={(val) => {
formik.setFieldValue( formik.setFieldValue(
'supplierIds', 'supplierIds',
@@ -696,11 +704,17 @@ const DebtSupplierTab = () => {
</div> </div>
<div> <div>
<SelectInput <SelectInputRadio
label='Filter Berdasarkan' label='Filter Berdasarkan'
placeholder='Pilih Filter Berdasarkan' placeholder='Pilih Filter Berdasarkan'
options={dataTypeOptions} options={dataTypeOptions}
value={formik.values.filterBy || null} value={
(formik.values.filterBy as
| { value: string; label: string }
| { value: string; label: string }[]
| null
| undefined) || null
}
onChange={(val) => { onChange={(val) => {
formik.setFieldValue( formik.setFieldValue(
'filterBy', 'filterBy',
+28
View File
@@ -0,0 +1,28 @@
import { StateCreator } from 'zustand';
export interface TableState {
searchValue: string;
}
export interface TableUISlice {
searchValue: string;
setSearchValue: (value: string) => void;
resetSearchValue: () => void;
}
export const createTableUISlice: StateCreator<
TableUISlice,
[],
[],
TableUISlice
> = (set) => ({
// Initial state
searchValue: '',
// Actions
setSearchValue: (value) => set({ searchValue: value }),
resetSearchValue: () => {
return set({ searchValue: '' });
},
});
+15 -5
View File
@@ -1,18 +1,28 @@
'use client'; 'use client';
import { create } from 'zustand'; import { create } from 'zustand';
import { devtools } from 'zustand/middleware'; import { devtools, persist } from 'zustand/middleware';
import { UIStore } from '@/types/stores'; import { UIStore } from '@/types/stores';
import { createMainUiSlice } from '@/stores/ui/slices/main.slice'; import { createMainUiSlice } from '@/stores/ui/slices/main.slice';
import { createDrawerUISlice } from '@/stores/ui/slices/drawer.slice'; import { createDrawerUISlice } from '@/stores/ui/slices/drawer.slice';
import { createTableUISlice } from '@/stores/ui/slices/table.slice';
export const useUiStore = create<UIStore>()( export const useUiStore = create<UIStore>()(
devtools( devtools(
(...args) => ({ persist(
...createMainUiSlice(...args), (...args) => ({
...createDrawerUISlice(...args), ...createMainUiSlice(...args),
}), ...createDrawerUISlice(...args),
...createTableUISlice(...args),
}),
{
name: 'ui-cache',
partialize: (state) => ({
searchValue: state.searchValue,
}),
}
),
{ {
name: 'UIStore', name: 'UIStore',
} }
+1
View File
@@ -17,6 +17,7 @@ export type BaseSales = {
id: number; id: number;
realization_date: string; realization_date: string;
age: number; age: number;
week: number;
do_number: string; do_number: string;
product: Product; product: Product;
customer: Customer; customer: Customer;
+7 -1
View File
@@ -26,7 +26,13 @@ type DrawerUISlice = {
setIsNextStep: (v: boolean) => void; setIsNextStep: (v: boolean) => void;
}; };
export type UIStore = MainUiSlice & DrawerUISlice; type TableUISlice = {
searchValue: string;
setSearchValue: (value: string) => void;
resetSearchValue: () => void;
};
export type UIStore = MainUiSlice & DrawerUISlice & TableUISlice;
type ProductionStandardFormSlice = { type ProductionStandardFormSlice = {
formData: { formData: {