Merge branch 'development' into fix/transfer-to-laying

This commit is contained in:
ValdiANS
2026-01-23 23:07:51 +07:00
17 changed files with 401 additions and 153 deletions
@@ -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';
@@ -91,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 {
@@ -99,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 = [
@@ -120,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
@@ -148,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
@@ -444,7 +441,13 @@ const DashboardProduction = () => {
)?.value === 'FARM' ? ( )?.value === 'FARM' ? (
<SelectInputCheckbox <SelectInputCheckbox
label='Farm' label='Farm'
value={formik.values.location} value={
formik.values.location as
| { value: number; label: string }
| { value: number; label: string }[]
| null
| undefined
}
onInputChange={setInputValueLocation} onInputChange={setInputValueLocation}
onMenuScrollToBottom={loadMoreLocation} onMenuScrollToBottom={loadMoreLocation}
onChange={(selected) => { onChange={(selected) => {
@@ -466,7 +469,13 @@ const DashboardProduction = () => {
) : ( ) : (
<SelectInputRadio <SelectInputRadio
label='Farm' label='Farm'
value={formik.values.location as OptionType} value={
formik.values.location as
| { value: number; label: string }
| { value: number; label: string }[]
| null
| undefined
}
onInputChange={setInputValueLocation} onInputChange={setInputValueLocation}
onMenuScrollToBottom={loadMoreLocation} onMenuScrollToBottom={loadMoreLocation}
onChange={(selected) => { onChange={(selected) => {
@@ -502,7 +511,13 @@ const DashboardProduction = () => {
)?.value === 'FLOCK' ? ( )?.value === 'FLOCK' ? (
<SelectInputCheckbox <SelectInputCheckbox
label='Flock' label='Flock'
value={formik.values.flock as OptionType[]} value={
formik.values.flock as
| { value: number; label: string }
| { value: number; label: string }[]
| null
| undefined
}
onChange={(selected) => onChange={(selected) =>
formik.setFieldValue('flock', selected) formik.setFieldValue('flock', selected)
} }
@@ -519,7 +534,13 @@ const DashboardProduction = () => {
) : ( ) : (
<SelectInputRadio <SelectInputRadio
label='Flock' label='Flock'
value={formik.values.flock as OptionType} value={
formik.values.flock as
| { value: number; label: string }
| { value: number; label: string }[]
| null
| undefined
}
onChange={(selected) => onChange={(selected) =>
formik.setFieldValue('flock', selected) formik.setFieldValue('flock', selected)
} }
@@ -548,7 +569,13 @@ const DashboardProduction = () => {
)?.value === 'KANDANG' ? ( )?.value === 'KANDANG' ? (
<SelectInputCheckbox <SelectInputCheckbox
label='Kandang' label='Kandang'
value={formik.values.kandang as OptionType[]} value={
formik.values.kandang as
| { value: number; label: string }
| { value: number; label: string }[]
| null
| undefined
}
onChange={(selected) => onChange={(selected) =>
formik.setFieldValue('kandang', selected) formik.setFieldValue('kandang', selected)
} }
@@ -565,7 +592,13 @@ const DashboardProduction = () => {
) : ( ) : (
<SelectInputRadio <SelectInputRadio
label='Kandang' label='Kandang'
value={formik.values.kandang as OptionType} value={
formik.values.kandang as
| { value: number; label: string }
| { value: number; label: string }[]
| null
| undefined
}
onChange={(selected) => onChange={(selected) =>
formik.setFieldValue('kandang', selected) formik.setFieldValue('kandang', selected)
} }
+35 -3
View File
@@ -1,4 +1,10 @@
import { ChangeEventHandler, useMemo, useState } from 'react'; import {
ChangeEventHandler,
useEffect,
useMemo,
useRef,
useState,
} from 'react';
import { CellContext } from '@tanstack/react-table'; import { CellContext } from '@tanstack/react-table';
import { useSearchParams } from 'next/navigation'; import { useSearchParams } from 'next/navigation';
import useSWR from 'swr'; import useSWR from 'swr';
@@ -33,6 +39,7 @@ import RequirePermission from '@/components/helper/RequirePermission';
import { Icon } from '@iconify/react'; import { Icon } from '@iconify/react';
import RowDropdownOptions from '@/components/table/RowDropdownOptions'; import RowDropdownOptions from '@/components/table/RowDropdownOptions';
import RowCollapseOptions from '@/components/table/RowCollapseOptions'; import RowCollapseOptions from '@/components/table/RowCollapseOptions';
import { useUiStore } from '@/stores/ui/ui.store';
const RowOptionsMenu = ({ const RowOptionsMenu = ({
type = 'dropdown', type = 'dropdown',
@@ -133,6 +140,9 @@ const RowOptionsMenu = ({
}; };
const FinanceTable = () => { const FinanceTable = () => {
const { searchValue, setSearchValue, resetSearchValue } = useUiStore();
const previousPathRef = useRef<string | null>(null);
const { const {
state: tableFilterState, state: tableFilterState,
updateFilter, updateFilter,
@@ -141,7 +151,7 @@ const FinanceTable = () => {
toQueryString: getTableFilterQueryString, toQueryString: getTableFilterQueryString,
} = useTableFilter({ } = useTableFilter({
initial: { initial: {
search: '', search: searchValue,
transactionType: '', transactionType: '',
bankId: '', bankId: '',
customerId: '', customerId: '',
@@ -167,7 +177,7 @@ const FinanceTable = () => {
const [searchParams, setSearchParams] = useSearchParams(); const [searchParams, setSearchParams] = useSearchParams();
const deleteModal = useModal(); const deleteModal = useModal();
const [pendingFilters, setPendingFilters] = useState({ const [pendingFilters, setPendingFilters] = useState({
search: '', search: searchValue,
transactionType: '', transactionType: '',
bankId: '', bankId: '',
customerId: '', customerId: '',
@@ -296,6 +306,7 @@ const FinanceTable = () => {
}; };
const submitFilterHandler = () => { const submitFilterHandler = () => {
updateFilter('search', pendingFilters.search); updateFilter('search', pendingFilters.search);
setSearchValue(pendingFilters.search);
updateFilter('transactionType', pendingFilters.transactionType); updateFilter('transactionType', pendingFilters.transactionType);
updateFilter('bankId', pendingFilters.bankId); updateFilter('bankId', pendingFilters.bankId);
updateFilter('customerId', pendingFilters.customerId); updateFilter('customerId', pendingFilters.customerId);
@@ -324,6 +335,7 @@ const FinanceTable = () => {
setPendingFilters(emptyFilters); setPendingFilters(emptyFilters);
updateFilter('search', ''); updateFilter('search', '');
resetSearchValue();
updateFilter('transactionType', ''); updateFilter('transactionType', '');
updateFilter('bankId', ''); updateFilter('bankId', '');
updateFilter('customerId', ''); updateFilter('customerId', '');
@@ -447,6 +459,26 @@ const FinanceTable = () => {
}, },
]; ];
}, []); }, []);
useEffect(() => {
// Store current path on mount
previousPathRef.current = window.location.pathname;
return () => {
const currentPath = window.location.pathname;
// if both paths are within /finance module
const isCurrentPathFinance = currentPath.includes('/finance');
const isPreviousPathFinance =
previousPathRef.current?.includes('/finance');
// reset if we outside finance module entirely
if (isPreviousPathFinance && !isCurrentPathFinance) {
resetSearchValue();
}
};
}, [resetSearchValue]);
return ( return (
<section className='size-full p-6 flex flex-col gap-6'> <section className='size-full p-6 flex flex-col gap-6'>
<div className='flex justify-end gap-2'> <div className='flex justify-end gap-2'>
@@ -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,11 @@ const FormFinanceAdd = ({
} }
required required
isClearable isClearable
isDisabled={!formik.values.party_type_option?.value || isSupplier} isDisabled={
!formik.values.party_type_option?.value ||
(type === 'edit' &&
formik.values.party_type_option.value == 'SUPPLIER')
}
/> />
<DateInput <DateInput
label='Tanggal' label='Tanggal'
@@ -272,7 +273,6 @@ const FormFinanceAdd = ({
: '' : ''
} }
required required
disabled={isSupplier}
/> />
<SelectInput <SelectInput
label='Metode Pembayaran' label='Metode Pembayaran'
@@ -294,7 +294,6 @@ const FormFinanceAdd = ({
} }
required required
isClearable isClearable
isDisabled={isSupplier}
/> />
<SelectInput <SelectInput
label='Bank' label='Bank'
@@ -335,7 +334,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 +354,6 @@ const FormFinanceAdd = ({
} }
required required
readOnly readOnly
disabled={isSupplier}
/> />
<TextInput <TextInput
label='Nomor Referensi' label='Nomor Referensi'
@@ -376,7 +373,6 @@ const FormFinanceAdd = ({
: '' : ''
} }
required required
disabled={isSupplier}
/> />
<NumberInput <NumberInput
label='Nominal' label='Nominal'
@@ -392,7 +388,6 @@ const FormFinanceAdd = ({
: '' : ''
} }
required required
disabled={isSupplier}
/> />
<TextArea <TextArea
label='Catatan' label='Catatan'
@@ -408,7 +403,6 @@ const FormFinanceAdd = ({
: '' : ''
} }
required required
disabled={isSupplier}
/> />
<AlertErrorList formErrorList={formErrorList} onClose={close} /> <AlertErrorList formErrorList={formErrorList} onClose={close} />
{serverErrorMessage && ( {serverErrorMessage && (
@@ -433,7 +427,7 @@ const FormFinanceAdd = ({
<Button <Button
type='submit' type='submit'
className='w-min-24' className='w-min-24'
disabled={formik.isSubmitting || !formik.isValid} disabled={formik.isSubmitting}
> >
Submit Submit
</Button> </Button>
@@ -396,7 +396,7 @@ const FormFinanceAddInitialBalance = ({
<Button <Button
type='submit' type='submit'
className='w-min-24' className='w-min-24'
disabled={formik.isSubmitting || !formik.isValid} disabled={formik.isSubmitting}
> >
Submit Submit
</Button> </Button>
@@ -257,7 +257,7 @@ const FormFinanceInjection = ({
<Button <Button
type='submit' type='submit'
className='w-min-24' className='w-min-24'
disabled={formik.isSubmitting || !formik.isValid} disabled={formik.isSubmitting}
> >
Submit Submit
</Button> </Button>
@@ -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);
// 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;
} }
@@ -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);
// Hitung total_price berdasarkan flag produk
if (unitPrice > 0) { if (unitPrice > 0) {
if (isOvkOrPakan) {
// Untuk OVK/PAKAN: total_price = qty × unit_price
formik.setFieldValue('total_price', roundPrice(qty * unitPrice)); 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) {
if (isOvkOrPakan) {
// Untuk OVK/PAKAN: total_price = qty × unit_price
formik.setFieldValue('total_price', roundPrice(qty * unitPrice)); 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) {
if (isOvkOrPakan) {
// Untuk OVK/PAKAN: total_price = qty × unit_price
formik.setFieldValue('total_price', roundPrice(qty * unitPrice)); 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) {
if (isOvkOrPakan && qty > 0) {
// Untuk OVK/PAKAN: unit_price = total_price / qty
formik.setFieldValue('unit_price', roundPrice(totalPrice / 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='.'
@@ -678,7 +678,13 @@ const DebtSupplierTab = () => {
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',
@@ -702,7 +708,13 @@ const DebtSupplierTab = () => {
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',
+5
View File
@@ -32,6 +32,11 @@ export const formatNumber = (
}).format(value); }).format(value);
}; };
export const safeRound = (num: number, decimals: number) => {
const factor = 10 ** decimals;
return Math.round((num + Number.EPSILON) * factor) / factor;
};
export const formatTitleCase = (value: string) => { export const formatTitleCase = (value: string) => {
return value return value
.toLowerCase() .toLowerCase()
+46 -44
View File
@@ -1,6 +1,6 @@
import * as XLSX from 'xlsx'; import * as XLSX from 'xlsx';
import toast from 'react-hot-toast'; import toast from 'react-hot-toast';
import { formatDate } from '@/lib/helper'; import { formatDate, safeRound } from '@/lib/helper';
import { isResponseSuccess } from '@/lib/api-helper'; import { isResponseSuccess } from '@/lib/api-helper';
import { BaseApiService } from '@/services/api/base'; import { BaseApiService } from '@/services/api/base';
import { httpClient, httpClientFetcher } from '@/services/http/client'; import { httpClient, httpClientFetcher } from '@/services/http/client';
@@ -32,21 +32,21 @@ export class ProductionResultReportApiService extends BaseApiService<
const mappedProductionResults: { const mappedProductionResults: {
projectFlockKandang: BaseProjectFlockKandang; projectFlockKandang: BaseProjectFlockKandang;
productionResult: ProductionResult[] | null; productionResult: ProductionResult[] | null;
}[] = []; }[] = await Promise.all(
(projectFlockKandangs || []).map(async (projectFlockKandang) => {
projectFlockKandangs?.forEach(async (projectFlockKandang) => {
const getProductionResultPath = `${this.basePath}/${projectFlockKandang.id}?page=1&limit=99999999`; const getProductionResultPath = `${this.basePath}/${projectFlockKandang.id}?page=1&limit=99999999`;
const getProductionResultRes = await httpClient< const getProductionResultRes = await httpClient<
BaseApiResponse<ProductionResult[]> BaseApiResponse<ProductionResult[]>
>(getProductionResultPath); >(getProductionResultPath);
mappedProductionResults.push({ return {
projectFlockKandang, projectFlockKandang,
productionResult: isResponseSuccess(getProductionResultRes) productionResult: isResponseSuccess(getProductionResultRes)
? getProductionResultRes.data ? getProductionResultRes.data
: null, : null,
}); };
}); })
);
const rows = mappedProductionResults; const rows = mappedProductionResults;
if (!rows || rows.length === 0) { if (!rows || rows.length === 0) {
@@ -68,44 +68,46 @@ export class ProductionResultReportApiService extends BaseApiService<
row.productionResult?.forEach((productionResult) => { row.productionResult?.forEach((productionResult) => {
groupedData[kandangName].push({ groupedData[kandangName].push({
woa: productionResult.woa, woa: safeRound(productionResult.woa, 2),
bw: productionResult.bw, bw: safeRound(productionResult.bw, 2),
std_bw: productionResult.std_bw, std_bw: safeRound(productionResult.std_bw, 2),
uniformity: productionResult.uniformity, uniformity: safeRound(productionResult.uniformity, 2),
std_uniformity: productionResult.std_uniformity, std_uniformity: productionResult.std_uniformity,
dep_kum: productionResult.dep_kum, dep_kum: safeRound(productionResult.dep_kum, 2),
dep_std: productionResult.dep_std, dep_std: safeRound(productionResult.dep_std, 2),
butiran_utuh: productionResult.butiran_utuh, butiran_utuh: safeRound(productionResult.butiran_utuh, 2),
butiran_putih: productionResult.butiran_putih, butiran_putih: safeRound(productionResult.butiran_putih, 2),
butiran_retak: productionResult.butiran_retak, butiran_retak: safeRound(productionResult.butiran_retak, 2),
butiran_pecah: productionResult.butiran_pecah, butiran_pecah: safeRound(productionResult.butiran_pecah, 2),
butiran_jumlah: productionResult.butiran_jumlah, butiran_jumlah: safeRound(productionResult.butiran_jumlah, 2),
total_butir: productionResult.total_butir, total_butir: safeRound(productionResult.total_butir, 2),
kg_utuh: productionResult.kg_utuh, kg_utuh: safeRound(productionResult.kg_utuh, 2),
kg_putih: productionResult.kg_putih, kg_putih: safeRound(productionResult.kg_putih, 2),
kg_retak: productionResult.kg_retak, kg_retak: safeRound(productionResult.kg_retak, 2),
kg_pecah: productionResult.kg_pecah, kg_pecah: safeRound(productionResult.kg_pecah, 2),
kg_jumlah: productionResult.kg_jumlah, kg_jumlah: safeRound(productionResult.kg_jumlah, 2),
total_kg: productionResult.total_kg, total_kg: safeRound(productionResult.total_kg, 2),
persen_utuh: productionResult.persen_utuh, persen_utuh: safeRound(productionResult.persen_utuh, 2),
persen_putih: productionResult.persen_putih, persen_putih: safeRound(productionResult.persen_putih, 2),
persen_retak: productionResult.persen_retak, persen_retak: safeRound(productionResult.persen_retak, 2),
persen_pecah: productionResult.persen_pecah, persen_pecah: safeRound(productionResult.persen_pecah, 2),
hd: productionResult.hd, hd: safeRound(productionResult.hd, 2),
hd_std: productionResult.hd_std, hd_std: safeRound(productionResult.hd_std, 2),
fi: productionResult.fi, fi: safeRound(productionResult.fi, 2),
fi_std: productionResult.fi_std, fi_std: safeRound(productionResult.fi_std, 2),
em: productionResult.em, em: safeRound(productionResult.em, 2),
em_std: productionResult.em_std, em_std: safeRound(productionResult.em_std, 2),
ew: productionResult.ew, ew: safeRound(productionResult.ew, 2),
ew_std: productionResult.ew_std, ew_std: safeRound(productionResult.ew_std, 2),
fcr: productionResult.fcr, fcr: safeRound(productionResult.fcr, 2),
fcr_std: productionResult.fcr_std, fcr_std: safeRound(productionResult.fcr_std, 2),
hh: productionResult.hh, hh: safeRound(productionResult.hh, 2),
hh_std: productionResult.hh_std, hh_std: safeRound(productionResult.hh_std, 2),
project_flock_name: productionResult.project_flock.name, project_flock_name:
project_flock_category: productionResult.project_flock.category, row.projectFlockKandang.project_flock.flock_name,
kandang_name: productionResult.project_flock.kandang.name, project_flock_category:
row.projectFlockKandang.project_flock.category,
kandang_name: row.projectFlockKandang.kandang.name,
created_at: formatDate(productionResult.created_at, 'YYYY-MM-DD'), created_at: formatDate(productionResult.created_at, 'YYYY-MM-DD'),
updated_at: formatDate(productionResult.updated_at, 'YYYY-MM-DD'), updated_at: formatDate(productionResult.updated_at, 'YYYY-MM-DD'),
}); });
+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: '' });
},
});
+11 -1
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(
persist(
(...args) => ({ (...args) => ({
...createMainUiSlice(...args), ...createMainUiSlice(...args),
...createDrawerUISlice(...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: {