Merge branch 'development' into fix/project-flock

This commit is contained in:
ValdiANS
2026-02-06 09:51:20 +07:00
34 changed files with 2599 additions and 3123 deletions
@@ -1,11 +0,0 @@
import SuspenseHelper from '@/components/helper/SuspenseHelper';
const Layout = ({
children,
}: Readonly<{
children: React.ReactNode;
}>) => {
return <SuspenseHelper>{children}</SuspenseHelper>;
};
export default Layout;
@@ -1,54 +0,0 @@
'use client';
import MarketingForm from '@/components/pages/marketing/form/MarketingForm';
import { isResponseError, isResponseSuccess } from '@/lib/api-helper';
import { MarketingApi } from '@/services/api/marketing/marketing';
import { useRouter, useSearchParams } from 'next/navigation';
import toast from 'react-hot-toast';
import useSWR from 'swr';
const EditMarketingDelivery = () => {
const router = useRouter();
const searchParams = useSearchParams();
const soId = searchParams.get('marketingId');
const {
data: marketing,
isLoading: isLoading,
mutate: refreshMarketing,
} = useSWR(`get-so-${soId}`, () =>
MarketingApi.getSingle(soId ? parseInt(soId) : 0)
);
if (!soId) {
router.back();
return (
<div className='w-full flex flex-row justify-center items-center p-4'>
<span className='loading loading-spinner loading-xl' />
</div>
);
}
if (!isLoading && (!marketing || isResponseError(marketing))) {
router.replace('/404');
return;
}
return (
<div className='w-full p-4'>
{isLoading && <span className='loading loading-spinner loading-xl' />}
{!isLoading && isResponseSuccess(marketing) && (
<MarketingForm
formType='add_deliver'
initialValues={marketing.data}
afterSubmit={() => {
refreshMarketing();
}}
/>
)}
</div>
);
};
export default EditMarketingDelivery;
@@ -1,11 +0,0 @@
import MarketingForm from '@/components/pages/marketing/form/MarketingForm';
const AddSalesOrder = () => {
return (
<div className='size-full p-4'>
<MarketingForm formType='add' />
</div>
);
};
export default AddSalesOrder;
@@ -1,11 +0,0 @@
import SuspenseHelper from '@/components/helper/SuspenseHelper';
const Layout = ({
children,
}: Readonly<{
children: React.ReactNode;
}>) => {
return <SuspenseHelper>{children}</SuspenseHelper>;
};
export default Layout;
@@ -1,62 +0,0 @@
'use client';
import MarketingForm from '@/components/pages/marketing/form/MarketingForm';
import { isResponseError, isResponseSuccess } from '@/lib/api-helper';
import { MarketingApi } from '@/services/api/marketing/marketing';
import { useRouter, useSearchParams } from 'next/navigation';
import toast from 'react-hot-toast';
import useSWR from 'swr';
const EditMarketingDelivery = () => {
const router = useRouter();
const searchParams = useSearchParams();
const soId = searchParams.get('marketingId');
const {
data: marketing,
isLoading: isLoading,
mutate: refreshMarketing,
} = useSWR(`get-so-${soId}`, () =>
MarketingApi.getSingle(soId ? parseInt(soId) : 0)
);
if (!soId) {
router.back();
return (
<div className='w-full flex flex-row justify-center items-center p-4'>
<span className='loading loading-spinner loading-xl' />
</div>
);
}
if (!isLoading && (!marketing || isResponseError(marketing))) {
router.replace('/404');
return;
}
if (
isResponseSuccess(marketing) &&
marketing.data.latest_approval.step_number != 3
) {
toast.error('Data Marketing perlu dilakukan approval terlebih dahulu!');
router.back();
}
return (
<div className='w-full p-4'>
{isLoading && <span className='loading loading-spinner loading-xl' />}
{!isLoading && isResponseSuccess(marketing) && (
<MarketingForm
formType='edit_deliver'
initialValues={marketing.data}
afterSubmit={() => {
refreshMarketing();
}}
/>
)}
</div>
);
};
export default EditMarketingDelivery;
-11
View File
@@ -1,11 +0,0 @@
import SuspenseHelper from '@/components/helper/SuspenseHelper';
const Layout = ({
children,
}: Readonly<{
children: React.ReactNode;
}>) => {
return <SuspenseHelper>{children}</SuspenseHelper>;
};
export default Layout;
-49
View File
@@ -1,49 +0,0 @@
'use client';
import MarketingDetail from '@/components/pages/marketing/detail/MarketingDetail';
import { isResponseError, isResponseSuccess } from '@/lib/api-helper';
import { MarketingApi } from '@/services/api/marketing/marketing';
import { useRouter, useSearchParams } from 'next/navigation';
import useSWR from 'swr';
const DetailMarketing = () => {
const router = useRouter();
const searchParams = useSearchParams();
const soId = searchParams.get('marketingId');
const {
data: marketing,
isLoading: isLoading,
mutate: refreshMarketing,
} = useSWR(soId, (id: number) => MarketingApi.getSingle(id));
if (!soId) {
router.back();
return (
<div className='w-full flex flex-row justify-center items-center p-4'>
<span className='loading loading-spinner loading-xl' />
</div>
);
}
if (!isLoading && (!marketing || isResponseError(marketing))) {
router.replace('/404');
return;
}
return (
<div className='w-full p-4'>
{isLoading && <span className='loading loading-spinner loading-xl' />}
{!isLoading && isResponseSuccess(marketing) && (
<MarketingDetail
initialValues={marketing.data}
refresh={refreshMarketing}
/>
)}
</div>
);
};
export default DetailMarketing;
@@ -1,11 +0,0 @@
import SuspenseHelper from '@/components/helper/SuspenseHelper';
const Layout = ({
children,
}: Readonly<{
children: React.ReactNode;
}>) => {
return <SuspenseHelper>{children}</SuspenseHelper>;
};
export default Layout;
@@ -1,52 +0,0 @@
'use client';
import MarketingForm from '@/components/pages/marketing/form/MarketingForm';
import { isResponseError, isResponseSuccess } from '@/lib/api-helper';
import { MarketingApi } from '@/services/api/marketing/marketing';
import { useRouter, useSearchParams } from 'next/navigation';
import useSWR from 'swr';
const EditSalesOrder = () => {
const router = useRouter();
const searchParams = useSearchParams();
const soId = searchParams.get('marketingId');
const {
data: marketing,
isLoading: isLoading,
mutate: refreshMarketing,
} = useSWR(`get-so-${soId}`, () =>
MarketingApi.getSingle(soId ? parseInt(soId) : 0)
);
if (!soId) {
router.back();
return (
<div className='w-full flex flex-row justify-center items-center p-4'>
<span className='loading loading-spinner loading-xl' />
</div>
);
}
if (!isLoading && (!marketing || isResponseError(marketing))) {
router.replace('/404');
return;
}
return (
<div className='w-full p-4'>
{isLoading && <span className='loading loading-spinner loading-xl' />}
{!isLoading && isResponseSuccess(marketing) && (
<MarketingForm
formType='edit'
initialValues={marketing.data}
afterSubmit={() => {
refreshMarketing();
}}
/>
)}
</div>
);
};
export default EditSalesOrder;
@@ -49,7 +49,7 @@ const ExpenseStatusBadge = ({ approval }: ExpenseStatusBadgeProps) => {
color={expenseStatusBadgeColor} color={expenseStatusBadgeColor}
text={isLatestApprovalRejected ? 'Ditolak' : (approval?.step_name ?? '')} text={isLatestApprovalRejected ? 'Ditolak' : (approval?.step_name ?? '')}
className={{ className={{
badge: 'w-fit', badge: 'whitespace-nowrap max-w-max w-fit',
}} }}
/> />
); );
@@ -29,7 +29,7 @@ const RealizationStatusBadge = ({ approval }: RealizationStatusBadgeProps) => {
color={realizationStatusBadgeColor} color={realizationStatusBadgeColor}
text={isLatestApprovalRejected ? 'Ditolak' : realizationStatus} text={isLatestApprovalRejected ? 'Ditolak' : realizationStatus}
className={{ className={{
badge: 'w-fit', badge: 'whitespace-nowrap max-w-max w-fit',
}} }}
/> />
); );
+185 -113
View File
@@ -1,13 +1,8 @@
import { import { useEffect, useMemo, useRef, useState } from 'react';
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';
import { useFormik } from 'formik';
import Button from '@/components/Button'; import Button from '@/components/Button';
import Card from '@/components/Card'; import Card from '@/components/Card';
@@ -40,6 +35,10 @@ 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'; import { useUiStore } from '@/stores/ui/ui.store';
import {
FinanceTableFilterSchema,
FinanceTableFilterValues,
} from './FinanceTableFilter.schema';
const RowOptionsMenu = ({ const RowOptionsMenu = ({
type = 'dropdown', type = 'dropdown',
@@ -152,10 +151,10 @@ const FinanceTable = () => {
} = useTableFilter({ } = useTableFilter({
initial: { initial: {
search: searchValue, search: searchValue,
transactionType: '', transactionTypes: '',
bankId: '', bankIds: '',
customerId: '', customerIds: '',
supplierId: '', supplierIds: '',
sortBy: '', sortBy: '',
startDate: '', startDate: '',
endDate: '', endDate: '',
@@ -163,10 +162,10 @@ const FinanceTable = () => {
paramMap: { paramMap: {
page: 'page', page: 'page',
pageSize: 'limit', pageSize: 'limit',
transactionType: 'transaction_type', transactionTypes: 'transaction_types',
bankId: 'bank_id', bankIds: 'bank_ids',
customerId: 'customer_id', customerIds: 'customer_ids',
supplierId: 'supplier_id', supplierIds: 'supplier_ids',
sortBy: 'sort_date', sortBy: 'sort_date',
startDate: 'start_date', startDate: 'start_date',
endDate: 'end_date', endDate: 'end_date',
@@ -174,18 +173,7 @@ const FinanceTable = () => {
}); });
// ===== State ===== // ===== State =====
const [searchParams, setSearchParams] = useSearchParams();
const deleteModal = useModal(); const deleteModal = useModal();
const [pendingFilters, setPendingFilters] = useState({
search: searchValue,
transactionType: '',
bankId: '',
customerId: '',
supplierId: '',
sortBy: '',
startDate: '',
endDate: '',
});
const [selectedTransactionType, setSelectedTransactionType] = useState< const [selectedTransactionType, setSelectedTransactionType] = useState<
OptionType | OptionType[] | null OptionType | OptionType[] | null
>(null); >(null);
@@ -201,6 +189,34 @@ const FinanceTable = () => {
const [selectedSortBy, setSelectedSortBy] = useState<OptionType | null>(null); const [selectedSortBy, setSelectedSortBy] = useState<OptionType | null>(null);
const [selectedFinance, setSelectedFinance] = useState<Finance | null>(null); const [selectedFinance, setSelectedFinance] = useState<Finance | null>(null);
const [isDeleteLoading, setIsDeleteLoading] = useState(false); const [isDeleteLoading, setIsDeleteLoading] = useState(false);
const [dateErrorShown, setDateErrorShown] = useState(false);
// ===== Formik for Filter =====
const filterFormik = useFormik<FinanceTableFilterValues>({
initialValues: {
search: searchValue,
transaction_types: '',
bank_ids: '',
customer_ids: '',
supplier_ids: '',
sort_by: '',
start_date: '',
end_date: '',
},
validationSchema: FinanceTableFilterSchema,
enableReinitialize: true,
onSubmit: (values) => {
updateFilter('search', values.search);
setSearchValue(values.search);
updateFilter('transactionTypes', values.transaction_types);
updateFilter('bankIds', values.bank_ids);
updateFilter('customerIds', values.customer_ids);
updateFilter('supplierIds', values.supplier_ids);
updateFilter('sortBy', values.sort_by);
updateFilter('startDate', values.start_date);
updateFilter('endDate', values.end_date);
},
});
// ===== Fetch Data ===== // ===== Fetch Data =====
const { const {
@@ -237,84 +253,141 @@ const FinanceTable = () => {
loadMore: bankLoadMore, loadMore: bankLoadMore,
} = useSelect<Bank>(BankApi.basePath, 'id', 'alias'); } = useSelect<Bank>(BankApi.basePath, 'id', 'alias');
const bankSelectOptions = useMemo(() => {
if (!isResponseSuccess(bankRawData)) return [];
return bankOptions.map((bank) => {
const bankData = bankRawData.data.find((data) => data.id === bank?.value);
return {
label: bankData
? `${bankData.alias} - ${bankData.account_number} - ${bankData.owner}`
: '',
value: bank?.value,
};
});
}, [bankOptions, bankRawData]);
// ===== Handler ===== // ===== Handler =====
const searchChangeHandler: ChangeEventHandler<HTMLInputElement> = (e) => { const searchChangeHandler = (e: React.ChangeEvent<HTMLInputElement>) => {
setPendingFilters((prev) => ({ ...prev, search: e.target.value })); filterFormik.setFieldValue('search', e.target.value);
}; };
const transactionTypeChangeHandler = ( const transactionTypeChangeHandler = (
val: OptionType | OptionType[] | null val: OptionType | OptionType[] | null
) => { ) => {
setSelectedTransactionType(val); setSelectedTransactionType(val);
setPendingFilters((prev) => ({ filterFormik.setFieldValue(
...prev, 'transaction_types',
transactionType: val val
? Array.isArray(val) ? Array.isArray(val)
? val.map((item) => item.value).join(',') ? val.map((item) => item.value).join(',')
: (val.value as string) : (val.value as string)
: '', : ''
})); );
}; };
const bankChangeHandler = (val: OptionType | OptionType[] | null) => { const bankChangeHandler = (val: OptionType | OptionType[] | null) => {
setSelectedBank(val); setSelectedBank(val);
setPendingFilters((prev) => ({ filterFormik.setFieldValue(
...prev, 'bank_ids',
bankId: val val
? Array.isArray(val) ? Array.isArray(val)
? val.map((item) => item.value).join(',') ? val.map((item) => item.value).join(',')
: (val.value as string) : (val.value as string)
: '', : ''
})); );
}; };
const customerIdChangeHandler = (val: OptionType | OptionType[] | null) => { const customerIdChangeHandler = (val: OptionType | OptionType[] | null) => {
setSelectedCustomerId(val); setSelectedCustomerId(val);
setPendingFilters((prev) => ({ filterFormik.setFieldValue(
...prev, 'customer_ids',
customerId: val val
? Array.isArray(val) ? Array.isArray(val)
? val.map((item) => item.value).join(',') ? val.map((item) => item.value).join(',')
: (val.value as string) : (val.value as string)
: '', : ''
})); );
}; };
const supplierIdChangeHandler = (val: OptionType | OptionType[] | null) => { const supplierIdChangeHandler = (val: OptionType | OptionType[] | null) => {
setSelectedSupplierId(val); setSelectedSupplierId(val);
setPendingFilters((prev) => ({ filterFormik.setFieldValue(
...prev, 'supplier_ids',
supplierId: val val
? Array.isArray(val) ? Array.isArray(val)
? val.map((item) => item.value).join(',') ? val.map((item) => item.value).join(',')
: (val.value as string) : (val.value as string)
: '', : ''
})); );
}; };
const sortByChangeHandler = (val: OptionType | OptionType[] | null) => { const sortByChangeHandler = (val: OptionType | OptionType[] | null) => {
setSelectedSortBy(val as OptionType); setSelectedSortBy(val as OptionType);
setPendingFilters((prev) => ({ filterFormik.setFieldValue(
...prev, 'sort_by',
sortBy: val ? ((val as OptionType).value as string) : '', val ? ((val as OptionType).value as string) : ''
})); );
}; };
const startDateChangeHandler: ChangeEventHandler<HTMLInputElement> = (e) => {
setPendingFilters((prev) => ({ ...prev, startDate: e.target.value })); const startDateChangeHandler = (e: React.ChangeEvent<HTMLInputElement>) => {
const value = e.target.value;
const endDate = filterFormik.values.end_date;
filterFormik.setFieldValue('start_date', value);
if (value && endDate) {
const startDate = new Date(value);
const endDateObj = new Date(endDate);
if (endDateObj < startDate) {
filterFormik.setFieldError(
'end_date',
'Tanggal akhir tidak boleh masa lampau'
);
if (!dateErrorShown) {
toast.error('Tanggal akhir tidak boleh masa lampau', {
duration: Infinity,
});
setDateErrorShown(true);
}
} else {
filterFormik.setFieldError('end_date', undefined);
if (dateErrorShown) {
toast.dismiss();
setDateErrorShown(false);
}
}
}
}; };
const endDateChangeHandler: ChangeEventHandler<HTMLInputElement> = (e) => {
setPendingFilters((prev) => ({ ...prev, endDate: e.target.value })); const endDateChangeHandler = (e: React.ChangeEvent<HTMLInputElement>) => {
}; const value = e.target.value;
const pageSizeChangeHandler = (val: OptionType | OptionType[] | null) => { const startDate = filterFormik.values.start_date;
const newVal = val as OptionType;
setPageSize(newVal.value as number); filterFormik.setFieldValue('end_date', value);
};
const submitFilterHandler = () => { if (value && startDate) {
updateFilter('search', pendingFilters.search); const startDateObj = new Date(startDate);
setSearchValue(pendingFilters.search); const endDate = new Date(value);
updateFilter('transactionType', pendingFilters.transactionType);
updateFilter('bankId', pendingFilters.bankId); if (endDate < startDateObj) {
updateFilter('customerId', pendingFilters.customerId); filterFormik.setFieldError(
updateFilter('supplierId', pendingFilters.supplierId); 'end_date',
updateFilter('sortBy', pendingFilters.sortBy); 'Tanggal akhir tidak boleh masa lampau'
updateFilter('startDate', pendingFilters.startDate); );
updateFilter('endDate', pendingFilters.endDate); if (!dateErrorShown) {
toast.error('Tanggal akhir tidak boleh masa lampau', {
duration: Infinity,
});
setDateErrorShown(true);
}
return;
}
}
filterFormik.setFieldError('end_date', undefined);
if (dateErrorShown) {
toast.dismiss();
setDateErrorShown(false);
}
}; };
const resetFilterHandler = () => { const resetFilterHandler = () => {
setSelectedTransactionType(null); setSelectedTransactionType(null);
setSelectedBank(null); setSelectedBank(null);
@@ -322,24 +395,14 @@ const FinanceTable = () => {
setSelectedSupplierId(null); setSelectedSupplierId(null);
setSelectedSortBy(null); setSelectedSortBy(null);
const emptyFilters = { filterFormik.resetForm();
search: '',
transactionType: '',
bankId: '',
customerId: '',
supplierId: '',
sortBy: '',
startDate: '',
endDate: '',
};
setPendingFilters(emptyFilters);
updateFilter('search', ''); updateFilter('search', '');
resetSearchValue(); resetSearchValue();
updateFilter('transactionType', ''); updateFilter('transactionTypes', '');
updateFilter('bankId', ''); updateFilter('bankIds', '');
updateFilter('customerId', ''); updateFilter('customerIds', '');
updateFilter('supplierId', ''); updateFilter('supplierIds', '');
updateFilter('sortBy', ''); updateFilter('sortBy', '');
updateFilter('startDate', ''); updateFilter('startDate', '');
updateFilter('endDate', ''); updateFilter('endDate', '');
@@ -464,26 +527,36 @@ const FinanceTable = () => {
}, []); }, []);
useEffect(() => { useEffect(() => {
// Store current path on mount return () => {
if (dateErrorShown) {
toast.dismiss();
}
};
}, [dateErrorShown]);
useEffect(() => {
previousPathRef.current = window.location.pathname; previousPathRef.current = window.location.pathname;
return () => { return () => {
const currentPath = window.location.pathname; const currentPath = window.location.pathname;
// if both paths are within /finance module
const isCurrentPathFinance = currentPath.includes('/finance'); const isCurrentPathFinance = currentPath.includes('/finance');
const isPreviousPathFinance = const isPreviousPathFinance =
previousPathRef.current?.includes('/finance'); previousPathRef.current?.includes('/finance');
// reset if we outside finance module entirely
if (isPreviousPathFinance && !isCurrentPathFinance) { if (isPreviousPathFinance && !isCurrentPathFinance) {
resetSearchValue(); resetSearchValue();
} }
if (dateErrorShown) {
toast.dismiss();
setDateErrorShown(false);
}
}; };
}, [resetSearchValue]); }, [resetSearchValue, dateErrorShown]);
return ( return (
<section className='size-full p-6 flex flex-col gap-6'> <section className='size-full flex flex-col gap-6'>
<div className='flex justify-end gap-2'> <div className='flex justify-end gap-2'>
<RequirePermission permissions='lti.finance.injections.create'> <RequirePermission permissions='lti.finance.injections.create'>
<Button <Button
@@ -526,7 +599,7 @@ const FinanceTable = () => {
<Button <Button
color='primary' color='primary'
className='min-w-24' className='min-w-24'
onClick={submitFilterHandler} onClick={() => filterFormik.handleSubmit()}
> >
Cari Cari
</Button> </Button>
@@ -539,6 +612,7 @@ const FinanceTable = () => {
label='Jenis Transaksi' label='Jenis Transaksi'
value={selectedTransactionType} value={selectedTransactionType}
onChange={transactionTypeChangeHandler} onChange={transactionTypeChangeHandler}
closeMenuOnSelect={false}
isClearable isClearable
isMulti isMulti
/> />
@@ -550,6 +624,7 @@ const FinanceTable = () => {
onInputChange={customerInputValue} onInputChange={customerInputValue}
onMenuScrollToBottom={customerLoadMore} onMenuScrollToBottom={customerLoadMore}
isLoading={customerIsLoadingOptions} isLoading={customerIsLoadingOptions}
closeMenuOnSelect={false}
isClearable isClearable
isMulti isMulti
/> />
@@ -561,31 +636,18 @@ const FinanceTable = () => {
onInputChange={supplierInputValue} onInputChange={supplierInputValue}
onMenuScrollToBottom={supplierLoadMore} onMenuScrollToBottom={supplierLoadMore}
isLoading={supplierIsLoadingOptions} isLoading={supplierIsLoadingOptions}
closeMenuOnSelect={false}
isClearable isClearable
isMulti isMulti
/> />
<SelectInput <SelectInput
options={ options={bankSelectOptions}
isResponseSuccess(bankRawData)
? bankOptions.map((bank) => ({
label:
bankRawData.data.find((data) => data.id === bank?.value)
?.alias +
' - ' +
bankRawData.data.find((data) => data.id === bank?.value)
?.account_number +
' - ' +
bankRawData.data.find((data) => data.id === bank?.value)
?.owner,
value: bank?.value,
}))
: []
}
label='Bank' label='Bank'
value={selectedBank} value={selectedBank}
onChange={bankChangeHandler} onChange={bankChangeHandler}
onInputChange={bankInputValue} onInputChange={bankInputValue}
onMenuScrollToBottom={bankLoadMore} onMenuScrollToBottom={bankLoadMore}
closeMenuOnSelect={false}
isClearable isClearable
isMulti isMulti
/> />
@@ -597,22 +659,32 @@ const FinanceTable = () => {
isClearable isClearable
/> />
<DateInput <DateInput
name='startDate' name='start_date'
label='Periode Tanggal (Mulai)' label='Periode Tanggal (Mulai)'
value={pendingFilters.startDate} value={filterFormik.values.start_date}
onChange={startDateChangeHandler} onChange={startDateChangeHandler}
errorMessage={
filterFormik.errors.end_date
? filterFormik.errors.end_date
: undefined
}
/> />
<DateInput <DateInput
name='endDate' name='end_date'
label='Periode Tanggal (Akhir)' label='Periode Tanggal (Akhir)'
value={pendingFilters.endDate} value={filterFormik.values.end_date}
onChange={endDateChangeHandler} onChange={endDateChangeHandler}
errorMessage={
filterFormik.errors.end_date
? filterFormik.errors.end_date
: undefined
}
/> />
<DebouncedTextInput <DebouncedTextInput
name='search' name='search'
label='Cari' label='Cari'
placeholder='Cari' placeholder='Cari'
value={pendingFilters.search} value={filterFormik.values.search}
onChange={searchChangeHandler} onChange={searchChangeHandler}
/> />
</div> </div>
@@ -0,0 +1,38 @@
import * as yup from 'yup';
export type FinanceTableFilterType = {
search: string;
transaction_types: string;
bank_ids: string;
customer_ids: string;
supplier_ids: string;
sort_by: string;
start_date: string;
end_date: string;
};
export const FinanceTableFilterSchema = yup.object({
search: yup.string().optional(),
transaction_types: yup.string().optional(),
bank_ids: yup.string().optional(),
customer_ids: yup.string().optional(),
supplier_ids: yup.string().optional(),
sort_by: yup.string().optional(),
start_date: yup.string().optional(),
end_date: yup
.string()
.optional()
.test(
'is-greater-than-start',
'Tanggal akhir tidak boleh masa lampau',
function (value) {
const { start_date } = this.parent;
if (!start_date || !value) return true;
return new Date(value) >= new Date(start_date);
}
),
}) as yup.ObjectSchema<FinanceTableFilterType>;
export type FinanceTableFilterValues = yup.InferType<
typeof FinanceTableFilterSchema
>;
@@ -1,16 +1,10 @@
'use client'; 'use client';
import AlertErrorList from '@/components/helper/form/FormErrors'; import AlertErrorList from '@/components/helper/form/FormErrors';
import { useSelect, OptionType } from '@/components/input/SelectInput'; import { OptionType } from '@/components/input/SelectInput';
import Modal, { useModal } from '@/components/Modal'; import Modal, { useModal } from '@/components/Modal';
import ConfirmationModal from '@/components/modal/ConfirmationModal'; import ConfirmationModal from '@/components/modal/ConfirmationModal';
import {
mergeSOwithDO,
SalesProductToFieldValues,
DeliveryProductToFieldValues,
} from '@/components/pages/marketing/form/MarketingForm';
import { DeliveryOrderProductFormValues } from '@/components/pages/marketing/form/repeater/delivery-order/DeliverOrderProduct.schema'; import { DeliveryOrderProductFormValues } from '@/components/pages/marketing/form/repeater/delivery-order/DeliverOrderProduct.schema';
import { SalesOrderProductFormValues } from '@/components/pages/marketing/form/repeater/sales-order/SalesOrderProduct.schema';
import { isResponseSuccess, isResponseError } from '@/lib/api-helper'; import { isResponseSuccess, isResponseError } from '@/lib/api-helper';
import { formatCurrency, formatDate, formatTitleCase } from '@/lib/helper'; import { formatCurrency, formatDate, formatTitleCase } from '@/lib/helper';
import { import {
@@ -18,16 +12,13 @@ import {
MarketingApi, MarketingApi,
SalesOrderApi, SalesOrderApi,
} from '@/services/api/marketing/marketing'; } from '@/services/api/marketing/marketing';
import { CustomerApi } from '@/services/api/master-data';
import { UserApi } from '@/services/api/user';
import { useFormikErrorList } from '@/services/hooks/useFormikErrorList'; import { useFormikErrorList } from '@/services/hooks/useFormikErrorList';
import { BaseApproval, CreatedUser } from '@/types/api/api-general'; import { BaseApproval } from '@/types/api/api-general';
import { import {
CreateDeliveryOrderPayload, CreateDeliveryOrderPayload,
Marketing, Marketing,
UpdateDeliveryOrderPayload, UpdateDeliveryOrderPayload,
} from '@/types/api/marketing/marketing'; } from '@/types/api/marketing/marketing';
import { Customer } from '@/types/api/master-data/customer';
import { useFormik } from 'formik'; import { useFormik } from 'formik';
import { Icon } from '@iconify/react'; import { Icon } from '@iconify/react';
import { useRouter, useSearchParams } from 'next/navigation'; import { useRouter, useSearchParams } from 'next/navigation';
@@ -47,6 +38,9 @@ import {
DeliveryOrderSchema, DeliveryOrderSchema,
getFilledMarketingFormInitialValues, getFilledMarketingFormInitialValues,
SalesOrderFormValues, SalesOrderFormValues,
mergeSOwithDO,
SalesProductToFieldValues,
DeliveryProductToFieldValues,
} from '@/components/pages/marketing/form/MarketingForm.schema'; } from '@/components/pages/marketing/form/MarketingForm.schema';
import ConfirmationModalWithNotes from '@/components/modal/ConfirmationModalWithNotes'; import ConfirmationModalWithNotes from '@/components/modal/ConfirmationModalWithNotes';
import RequirePermission from '@/components/helper/RequirePermission'; import RequirePermission from '@/components/helper/RequirePermission';
@@ -116,13 +110,6 @@ const DeliveryOrderFormModal = ({
const formRef = useRef<HTMLFormElement>(null); const formRef = useRef<HTMLFormElement>(null);
const textareaRef = useRef<HTMLTextAreaElement>(null); const textareaRef = useRef<HTMLTextAreaElement>(null);
const [grandTotal, setGrandTotal] = useState(
isResponseSuccess(marketing) &&
marketing?.data.sales_order
?.map((item) => item.total_price)
.reduce((a, b) => a + b, 0)
);
const [formErrorMessage, setFormErrorMessage] = useState<string | null>(null); const [formErrorMessage, setFormErrorMessage] = useState<string | null>(null);
const [isLoading, setIsLoading] = useState(false); const [isLoading, setIsLoading] = useState(false);
const [selectedDeliveryProduct, setSelectedDeliveryProduct] = const [selectedDeliveryProduct, setSelectedDeliveryProduct] =
@@ -505,6 +492,14 @@ const DeliveryOrderFormModal = ({
formik.setFieldValue('delivery_order', deliveryOrderValues); formik.setFieldValue('delivery_order', deliveryOrderValues);
}, [deliveryOrderValues]); }, [deliveryOrderValues]);
const grandTotal = useMemo(() => {
return deliveryOrderValues.reduce(
(total, product) =>
total + parseFloat((product.total_price as string) || '0'),
0
);
}, [deliveryOrderValues]);
return ( return (
<> <>
<Modal <Modal
@@ -663,26 +658,28 @@ const DeliveryOrderFormModal = ({
steps={MARKETING_APPROVAL_LINE} steps={MARKETING_APPROVAL_LINE}
/> />
)} )}
<div className='w-full p-4 gap-3 flex flex-col'> <div className='w-full gap-3 flex flex-col'>
<h4 className='text-base font-medium text-base-content/50 font-roboto'> <h4 className='px-4 pt-4 text-base font-medium text-base-content/50 font-roboto'>
{step == 2 && 'Ubah '} Informasi{' '} {step == 2 && 'Ubah '} Informasi{' '}
{step == 2 ? 'Delivery' : 'Produk'} {step == 2 ? 'Delivery' : 'Produk'}
</h4> </h4>
{step === 1 && ( {step === 1 && (
<MemoizedDeliveryOrderProductTable <div className='px-4'>
marketing={marketing.data} <MemoizedDeliveryOrderProductTable
formType={ marketing={marketing.data}
deliveryRejected formType={
? 'rejected' deliveryRejected
: isPending ? 'rejected'
? 'pending' : isPending
: modalAction ? 'pending'
} : modalAction
data={deliveryOrderValues} }
onEdit={handleEditDO} data={deliveryOrderValues}
onDelete={handleDeleteDO} onEdit={handleEditDO}
onAddProductClick={handleAddDOClick} onDelete={handleDeleteDO}
/> onAddProductClick={handleAddDOClick}
/>
</div>
)} )}
{step === 2 && ( {step === 2 && (
<MemoizedDeliveryOrderProductForm <MemoizedDeliveryOrderProductForm
@@ -1,572 +0,0 @@
'use client';
import Button from '@/components/Button';
import Card from '@/components/Card';
import { FormHeader } from '@/components/helper/form/FormHeader';
import { useModal } from '@/components/Modal';
import ConfirmationModal from '@/components/modal/ConfirmationModal';
import ConfirmationModalWithNotes from '@/components/modal/ConfirmationModalWithNotes';
import ApprovalSteps, {
useApprovalSteps,
} from '@/components/pages/ApprovalSteps';
import Table from '@/components/Table';
import { MARKETING_APPROVAL_LINE } from '@/config/approval-line';
import {
cn,
formatCurrency,
formatDate,
formatNumber,
formatTitleCase,
formatVechicleNumber,
} from '@/lib/helper';
import {
MarketingApi,
SalesOrderApi,
} from '@/services/api/marketing/marketing';
import {
BaseDelivery,
BaseSalesOrder,
Marketing,
} from '@/types/api/marketing/marketing';
import { Icon } from '@iconify/react';
import { useRouter } from 'next/navigation';
import { useState } from 'react';
import toast from 'react-hot-toast';
import SalesOrderExport from '@/components/pages/marketing/pdf/SalesOrderExport';
import DeliveryOrderExport from '@/components/pages/marketing/pdf/DeliveryOrderExport';
import RequirePermission from '@/components/helper/RequirePermission';
import Badge from '@/components/Badge';
const MarketingDetail = ({
initialValues,
refresh,
}: {
initialValues?: Marketing;
refresh?: () => void;
}) => {
const router = useRouter();
const [approvalAction, setApprovalAction] = useState<'APPROVED' | 'REJECTED'>(
'APPROVED'
);
const [grandTotal, setGrandTotal] = useState(
initialValues?.sales_order
?.map((item) => item.total_price)
.reduce((a, b) => a + b, 0)
);
const [isLoading, setIsLoading] = useState(false);
const deleteModal = useModal();
const confirmationModal = useModal();
const deliveryModal = useModal();
const {
approvals,
isLoading: isLoadingApproval,
refresh: refreshApproval,
} = useApprovalSteps({
latestApproval: initialValues?.latest_approval,
approvalLines: MARKETING_APPROVAL_LINE,
moduleName: 'MARKETINGS',
moduleId: initialValues?.id as number as unknown as string,
});
const approveClickHandler = () => {
setApprovalAction('APPROVED');
confirmationModal.openModal();
};
const rejectClickHandler = () => {
setApprovalAction('REJECTED');
confirmationModal.openModal();
};
const deleteClickHandler = () => {
deleteModal.openModal();
};
const confirmationModalDeleteClickHandler = async () => {
setIsLoading(true);
const res = await MarketingApi.delete(initialValues?.id as number);
deleteModal.closeModal();
router.push('/marketing');
toast.success(res?.message as string);
setIsLoading(false);
};
const confirmationModalApproveClickHandler = async (notes: string) => {
setIsLoading(true);
const res = await SalesOrderApi.singleApproval(
initialValues?.id as number,
approvalAction,
notes
);
setIsLoading(false);
confirmationModal.closeModal();
toast.success(res?.message as string);
refresh?.();
refreshApproval?.();
};
const confirmationModalDeliveryClickHandler = async (notes: string) => {
setIsLoading(true);
const res = await SalesOrderApi.delivery(
initialValues?.id as number,
notes
);
setIsLoading(false);
deliveryModal.closeModal();
toast.success(res?.message as string);
refresh?.();
refreshApproval?.();
router.push(
`/marketing/detail/delivery-orders/edit?marketingId=${initialValues?.id}`
);
};
const approval = initialValues?.latest_approval;
const isRejected = approval?.action == 'REJECTED';
const isApproved = approval?.action == 'APPROVED';
return (
<>
<div className='flex flex-col w-full gap-4'>
<FormHeader
title={`Detail ${Number(initialValues?.latest_approval?.step_number) > 2 ? 'Delivery Order' : 'Sales Order'}`}
backUrl='/marketing'
/>
{!isLoadingApproval && approvals && (
<ApprovalSteps approvals={approvals} />
)}
<div className='flex-row flex gap-3'>
{initialValues?.latest_approval?.step_number == 1 && (
<>
<RequirePermission permissions='lti.marketing.sales_order.approve'>
<Button
color='success'
onClick={approveClickHandler}
disabled={
initialValues?.latest_approval?.step_number == 1 &&
initialValues?.latest_approval?.action == 'REJECTED'
}
>
<Icon icon='mdi:check' width={24} height={24} />
Approve
</Button>
</RequirePermission>
<RequirePermission permissions='lti.marketing.sales_order.approve'>
<Button
color='error'
onClick={rejectClickHandler}
disabled={
initialValues?.latest_approval?.step_number == 1 &&
initialValues?.latest_approval?.action == 'REJECTED'
}
>
<Icon icon='mdi:close' width={24} height={24} />
Reject
</Button>
</RequirePermission>
</>
)}
{initialValues?.latest_approval?.step_number != 1 && (
<>
<RequirePermission
permissions={
initialValues?.latest_approval?.step_number == 3
? 'lti.marketing.delivery_order.update'
: 'lti.marketing.delivery_order.create'
}
>
<Button
color='success'
href={
initialValues?.latest_approval?.step_number == 3
? `/marketing/detail/delivery-orders/edit?marketingId=${initialValues?.id}`
: `/marketing/add/delivery-orders?marketingId=${initialValues?.id}`
}
>
<Icon icon='mdi:truck' width={24} height={24} />
{initialValues?.latest_approval?.step_number == 3
? 'Edit '
: 'Tambah '}
Delivery Order
</Button>
</RequirePermission>
</>
)}
</div>
<Card
title='Informasi Penjualan'
className={{
wrapper: 'w-full bg-white',
}}
>
<div className='overflow-x-auto rounded-box border border-base-content/5 bg-base-100 mt-3'>
<table className='table'>
<tbody>
<tr>
<td width='45%' className='font-semibold'>
No. Sales Order
</td>
<td>:</td>
<td width='50%' className='font-mono'>
{initialValues?.so_number}
</td>
</tr>
{Number(initialValues?.latest_approval?.step_number) > 2 && (
<tr>
<td width='45%' className='font-semibold'>
No. Delivery Order
</td>
<td>:</td>
<td width='50%' className='font-mono'>
{initialValues?.delivery_order
?.map((item) => item.do_number)
.join(', ')}
</td>
</tr>
)}
<tr>
<td className='font-semibold'>Nama Pelanggan</td>
<td>:</td>
<td>{initialValues?.customer?.name}</td>
</tr>
<tr>
<td className='font-semibold'>Status</td>
<td>:</td>
<td>
<Badge
variant='soft'
className={{
badge:
'rounded-lg px-2 w-fit flex flex-row justify-start whitespace-nowrap',
}}
color={
isRejected
? 'error'
: isApproved
? approval?.step_number == 1
? 'neutral'
: approval?.step_number == 2
? 'primary'
: approval?.step_number == 3
? 'success'
: 'neutral'
: 'neutral'
}
>
<Icon
icon='mdi:circle'
width={12}
height={12}
color={
approval?.step_number == 1
? 'neutral'
: approval?.step_number == 2
? 'primary'
: approval?.step_number == 3
? 'success'
: 'neutral'
}
/>
{isRejected
? 'Ditolak'
: formatTitleCase(approval?.step_name || '')}
</Badge>
</td>
</tr>
<tr>
<td className='font-semibold'>Tanggal Penjualan</td>
<td>:</td>
<td>{formatDate(initialValues?.so_date, 'DD MMM yyyy')}</td>
</tr>
<tr>
<td className='font-semibold'>Total Penjualan</td>
<td>:</td>
<td>{formatCurrency(grandTotal as number)}</td>
</tr>
<tr>
<td className='font-semibold'>Catatan</td>
<td>:</td>
<td>{initialValues?.notes ?? '-'}</td>
</tr>
<tr>
<td className='font-semibold'>Dokumen Penjualan</td>
<td>:</td>
<td>
<SalesOrderExport data={initialValues} />
</td>
</tr>
{Number(initialValues?.latest_approval?.step_number) > 2 && (
<tr>
<td className='font-semibold'>Dokumen Pengiriman</td>
<td>:</td>
<td className='flex flex-wrap gap-2'>
{initialValues?.delivery_order?.map((item, index) => (
<DeliveryOrderExport
key={index}
data={initialValues}
deliveryOrder={item}
/>
))}
</td>
</tr>
)}
</tbody>
</table>
</div>
</Card>
{initialValues?.sales_order && (
<Card
title='Informasi Produk'
className={{
wrapper: 'w-full bg-white',
}}
>
<Table<BaseSalesOrder>
data={initialValues?.sales_order}
columns={[
{
header: 'Kandang',
accessorFn(row) {
return row.product_warehouse.warehouse.name;
},
},
{
header: 'Produk',
accessorFn(row) {
return row.product_warehouse.product.name;
},
},
{
header: 'Harga Satuan (Rp)',
accessorFn(row) {
return formatCurrency(row.unit_price);
},
},
{
header: 'Total Bobot (Kg)',
accessorFn(row) {
return formatNumber(row.total_weight);
},
},
{
header: 'Kuantitas',
accessorFn(row) {
return formatNumber(row.qty);
},
},
{
header: 'Avg. Bobot (Kg)',
accessorFn(row) {
return formatNumber(row.avg_weight);
},
},
{
header: 'Total Penjualan (Rp)',
accessorFn(row) {
return formatCurrency(row.total_price);
},
},
]}
className={{
containerClassName: cn({
'mb-20':
initialValues?.sales_order &&
initialValues?.sales_order?.length === 0,
}),
tableWrapperClassName: 'overflow-x-auto min-h-full!',
tableClassName: 'font-inter w-full table-auto min-h-full!',
headerRowClassName: 'border-b border-b-gray-200',
headerColumnClassName:
'px-6 py-3 text-xs font-semibold text-gray-500 last:flex last:flex-row last:justify-end',
bodyRowClassName: 'border-b border-b-gray-200',
bodyColumnClassName:
'px-6 py-3 last:flex last:flex-row last:justify-end',
paginationClassName: 'hidden',
}}
/>
</Card>
)}
{initialValues?.delivery_order && (
<Card
title='Informasi Pengiriman'
className={{
wrapper: 'w-full bg-white',
}}
>
{initialValues?.delivery_order.map((delivery, index) => {
return (
<div key={index}>
<Card
className={{
wrapper: 'w-full',
}}
>
<div className='flex flex-row gap-3'>
<div className='font-semibold'>
Nomor DO : {delivery.do_number}
</div>
</div>
<Table<BaseDelivery>
data={delivery.deliveries}
columns={[
{
header: 'Tanggal Pengiriman',
accessorFn() {
return formatDate(
delivery.delivery_date,
'DD MMM yyyy'
);
},
},
{
header: 'No. Polisi',
accessorFn(row) {
return formatVechicleNumber(row.vehicle_number);
},
},
{
header: 'Kandang',
accessorFn(row) {
return row.product_warehouse.warehouse.name;
},
},
{
header: 'Produk',
accessorFn(row) {
return row.product_warehouse.product.name;
},
},
{
header: 'Harga Satuan (Rp)',
accessorFn(row) {
return formatCurrency(row.unit_price);
},
},
{
header: 'Total Bobot (Kg)',
accessorFn(row) {
return formatNumber(row.total_weight);
},
},
{
header: 'Kuantitas',
accessorFn(row) {
return formatNumber(row.qty);
},
},
{
header: 'Avg. Bobot (Kg)',
accessorFn(row) {
return formatNumber(row.avg_weight);
},
},
{
header: 'Total Penjualan (Rp)',
accessorFn(row) {
return formatCurrency(row.total_price);
},
},
]}
className={{
containerClassName: cn({
'mb-20':
initialValues?.sales_order &&
initialValues?.sales_order?.length === 0,
}),
tableWrapperClassName: 'overflow-x-auto min-h-full!',
tableClassName:
'font-inter w-full table-auto min-h-full!',
headerRowClassName: 'border-b border-b-gray-200',
headerColumnClassName:
'px-6 py-3 text-xs font-semibold text-gray-500 last:flex last:flex-row last:justify-end',
bodyRowClassName: 'border-b border-b-gray-200',
bodyColumnClassName:
'px-6 py-3 last:flex last:flex-row last:justify-end',
paginationClassName: 'hidden',
}}
/>
</Card>
<div className='flex flex-row gap-3 my-3'>
<DeliveryOrderExport
data={initialValues}
deliveryOrder={delivery}
/>
</div>
</div>
);
})}
</Card>
)}
<div className='flex flex-row gap-3'>
{initialValues?.latest_approval?.step_number != 3 && (
<>
<RequirePermission permissions='lti.marketing.sales_order.update'>
<Button
color='warning'
type='button'
href={`/marketing/detail/${initialValues?.latest_approval?.step_number == 3 ? 'delivery-orders' : 'sales-orders'}/edit?marketingId=${initialValues?.id}`}
>
<Icon icon='mdi:pencil' width={24} height={24} />
Edit
</Button>
</RequirePermission>
</>
)}
<RequirePermission permissions='lti.marketing.sales_order.delete'>
<Button color='error' onClick={deleteClickHandler}>
<Icon icon='mdi:delete' width={24} height={24} />
Hapus
</Button>
</RequirePermission>
</div>
</div>
<ConfirmationModal
ref={deleteModal.ref}
type='error'
text={`Apakah anda yakin ingin menghapus data penjualan ini?`}
secondaryButton={{
text: 'Tidak',
}}
primaryButton={{
text: 'Ya',
color: 'error',
isLoading: isLoading,
onClick: confirmationModalDeleteClickHandler,
}}
/>
<ConfirmationModalWithNotes
ref={confirmationModal.ref}
type={approvalAction === 'APPROVED' ? 'success' : 'error'}
text={`Apakah anda yakin ingin ${approvalAction == 'APPROVED' ? 'approve' : 'reject'} data penjualan ini?`}
secondaryButton={{
text: 'Tidak',
}}
primaryButton={{
text: 'Ya',
color: approvalAction === 'APPROVED' ? 'success' : 'error',
isLoading: isLoading,
onClick: confirmationModalApproveClickHandler,
}}
/>
<ConfirmationModalWithNotes
ref={deliveryModal.ref}
type={'success'}
text={`Apakah anda yakin ingin deliver penjualan ini?`}
secondaryButton={{
text: 'Tidak',
}}
primaryButton={{
text: 'Ya',
color: 'success',
isLoading: isLoading,
onClick: confirmationModalDeliveryClickHandler,
}}
/>
</>
);
};
export default MarketingDetail;
@@ -623,7 +623,10 @@ const MarketingTable = () => {
data={allData} data={allData}
columns={columns} columns={columns}
pageSize={tableFilterState.pageSize} pageSize={tableFilterState.pageSize}
page={tableFilterState.page} page={isResponseSuccess(marketing) ? marketing?.meta?.page : 1}
totalItems={
isResponseSuccess(marketing) ? marketing?.meta?.total_results : 0
}
isLoading={isLoadingMarketing} isLoading={isLoadingMarketing}
className={{ className={{
containerClassName: cn('p-3', { containerClassName: cn('p-3', {
@@ -14,8 +14,6 @@ import {
DeliveryProductToFieldValues, DeliveryProductToFieldValues,
mergeSOwithDO, mergeSOwithDO,
SalesProductToFieldValues, SalesProductToFieldValues,
} from '@/components/pages/marketing/form/MarketingForm';
import {
DeliveryOrderFormValues, DeliveryOrderFormValues,
DeliveryOrderSchema, DeliveryOrderSchema,
getFilledMarketingFormInitialValues, getFilledMarketingFormInitialValues,
@@ -186,15 +184,31 @@ const SalesOrderFormModal = ({
date: formatDate(values.so_date as string, 'yyyy-MM-DD'), date: formatDate(values.so_date as string, 'yyyy-MM-DD'),
notes: values.notes as string, notes: values.notes as string,
marketing_products: values.sales_order.map((product) => { marketing_products: values.sales_order.map((product) => {
// Workaround untuk TELUR + QTY: kirim "KG" karena BE tidak support "QTY"
const convertionUnitValue =
product.convertion_unit?.value?.toUpperCase();
const normalizedConvertionUnit =
product.marketing_type?.value?.toLowerCase() === 'telur'
? convertionUnitValue === 'PETI'
? 'PETI'
: 'KG' // termasuk "QTY" dan "KG"
: undefined;
return { return {
vehicle_number: product.vehicle_number as string, vehicle_number: product.vehicle_number as string,
kandang_id: product.kandang_id as number, kandang_id: product.kandang_id as number,
product_warehouse_id: product.product_warehouse_id as number, product_warehouse_id: product.product_warehouse_id as number,
unit_price: parseFloat(product.unit_price as string), unit_price: parseFloat(String(product.unit_price || 0)),
total_weight: parseFloat(product.total_weight as string), total_weight: parseFloat(String(product.total_weight || 0)),
qty: parseFloat(product.qty as string), qty: parseFloat(String(product.qty || 0)),
avg_weight: parseFloat(product.avg_weight as string), avg_weight: parseFloat(String(product.avg_weight || 0)),
total_price: parseFloat(product.total_price as string), total_price: parseFloat(String(product.total_price || 0)),
marketing_type:
product.marketing_type?.value?.toUpperCase() || '',
convertion_unit: normalizedConvertionUnit,
weight_per_convertion:
product.weight_per_convertion ?? undefined,
week: product.week?.value ?? undefined,
} as CreateSalesOrderProductPayload; } as CreateSalesOrderProductPayload;
}), }),
} as CreateSalesOrderPayload) } as CreateSalesOrderPayload)
@@ -282,6 +296,7 @@ const SalesOrderFormModal = ({
// ================== HANDLER ================== // ================== HANDLER ==================
const nextButtonHandler = () => { const nextButtonHandler = () => {
setSelectedMarketingProduct(null);
setStep(step + 1); setStep(step + 1);
}; };
const prevButtonHandler = () => { const prevButtonHandler = () => {
@@ -375,6 +390,7 @@ const SalesOrderFormModal = ({
} }
formik.setFieldValue('sales_order', updatedProducts); formik.setFieldValue('sales_order', updatedProducts);
console.log(formik.values);
nextButtonHandler(); nextButtonHandler();
}, },
[memoSalesOrder, nextButtonHandler] [memoSalesOrder, nextButtonHandler]
@@ -650,8 +666,9 @@ const SalesOrderFormModal = ({
</Button> </Button>
</RequirePermission> </RequirePermission>
</div> </div>
<div className='flex flex-1 flex-col p-4'> <div className='flex flex-1 flex-col'>
<MemoizedSalesOrderProductForm <MemoizedSalesOrderProductForm
key={selectedMarketingProduct?.id ?? 'new'}
onSubmitForm={handleAddSubmitSO} onSubmitForm={handleAddSubmitSO}
initialValues={selectedMarketingProduct ?? undefined} initialValues={selectedMarketingProduct ?? undefined}
exisitingValues={memoSalesOrder} exisitingValues={memoSalesOrder}
@@ -1,572 +0,0 @@
'use client';
import Button from '@/components/Button';
import Card from '@/components/Card';
import { FormHeader } from '@/components/helper/form/FormHeader';
import { useModal } from '@/components/Modal';
import ConfirmationModal from '@/components/modal/ConfirmationModal';
import ConfirmationModalWithNotes from '@/components/modal/ConfirmationModalWithNotes';
import ApprovalSteps, {
useApprovalSteps,
} from '@/components/pages/ApprovalSteps';
import Table from '@/components/Table';
import { MARKETING_APPROVAL_LINE } from '@/config/approval-line';
import {
cn,
formatCurrency,
formatDate,
formatNumber,
formatTitleCase,
formatVechicleNumber,
} from '@/lib/helper';
import {
MarketingApi,
SalesOrderApi,
} from '@/services/api/marketing/marketing';
import {
BaseDelivery,
BaseSalesOrder,
Marketing,
} from '@/types/api/marketing/marketing';
import { Icon } from '@iconify/react';
import { useRouter } from 'next/navigation';
import { useState } from 'react';
import toast from 'react-hot-toast';
import SalesOrderExport from '@/components/pages/marketing/pdf/SalesOrderExport';
import DeliveryOrderExport from '@/components/pages/marketing/pdf/DeliveryOrderExport';
import RequirePermission from '@/components/helper/RequirePermission';
import Badge from '@/components/Badge';
const MarketingDetail = ({
initialValues,
refresh,
}: {
initialValues?: Marketing;
refresh?: () => void;
}) => {
const router = useRouter();
const [approvalAction, setApprovalAction] = useState<'APPROVED' | 'REJECTED'>(
'APPROVED'
);
const [grandTotal, setGrandTotal] = useState(
initialValues?.sales_order
?.map((item) => item.total_price)
.reduce((a, b) => a + b, 0)
);
const [isLoading, setIsLoading] = useState(false);
const deleteModal = useModal();
const confirmationModal = useModal();
const deliveryModal = useModal();
const {
approvals,
isLoading: isLoadingApproval,
refresh: refreshApproval,
} = useApprovalSteps({
latestApproval: initialValues?.latest_approval,
approvalLines: MARKETING_APPROVAL_LINE,
moduleName: 'MARKETINGS',
moduleId: initialValues?.id as number as unknown as string,
});
const approveClickHandler = () => {
setApprovalAction('APPROVED');
confirmationModal.openModal();
};
const rejectClickHandler = () => {
setApprovalAction('REJECTED');
confirmationModal.openModal();
};
const deleteClickHandler = () => {
deleteModal.openModal();
};
const confirmationModalDeleteClickHandler = async () => {
setIsLoading(true);
const res = await MarketingApi.delete(initialValues?.id as number);
deleteModal.closeModal();
router.push('/marketing');
toast.success(res?.message as string);
setIsLoading(false);
};
const confirmationModalApproveClickHandler = async (notes: string) => {
setIsLoading(true);
const res = await SalesOrderApi.singleApproval(
initialValues?.id as number,
approvalAction,
notes
);
setIsLoading(false);
confirmationModal.closeModal();
toast.success(res?.message as string);
refresh?.();
refreshApproval?.();
};
const confirmationModalDeliveryClickHandler = async (notes: string) => {
setIsLoading(true);
const res = await SalesOrderApi.delivery(
initialValues?.id as number,
notes
);
setIsLoading(false);
deliveryModal.closeModal();
toast.success(res?.message as string);
refresh?.();
refreshApproval?.();
router.push(
`/marketing/detail/delivery-orders/edit?marketingId=${initialValues?.id}`
);
};
const approval = initialValues?.latest_approval;
const isRejected = approval?.action == 'REJECTED';
const isApproved = approval?.action == 'APPROVED';
return (
<>
<div className='flex flex-col w-full gap-4'>
<FormHeader
title={`Detail ${Number(initialValues?.latest_approval?.step_number) > 2 ? 'Delivery Order' : 'Sales Order'}`}
backUrl='/marketing'
/>
{!isLoadingApproval && approvals && (
<ApprovalSteps approvals={approvals} />
)}
<div className='flex-row flex gap-3'>
{initialValues?.latest_approval?.step_number == 1 && (
<>
<RequirePermission permissions='lti.marketing.sales_order.approve'>
<Button
color='success'
onClick={approveClickHandler}
disabled={
initialValues?.latest_approval?.step_number == 1 &&
initialValues?.latest_approval?.action == 'REJECTED'
}
>
<Icon icon='mdi:check' width={24} height={24} />
Approve
</Button>
</RequirePermission>
<RequirePermission permissions='lti.marketing.sales_order.approve'>
<Button
color='error'
onClick={rejectClickHandler}
disabled={
initialValues?.latest_approval?.step_number == 1 &&
initialValues?.latest_approval?.action == 'REJECTED'
}
>
<Icon icon='mdi:close' width={24} height={24} />
Reject
</Button>
</RequirePermission>
</>
)}
{initialValues?.latest_approval?.step_number != 1 && (
<>
<RequirePermission
permissions={
initialValues?.latest_approval?.step_number == 3
? 'lti.marketing.delivery_order.update'
: 'lti.marketing.delivery_order.create'
}
>
<Button
color='success'
href={
initialValues?.latest_approval?.step_number == 3
? `/marketing/detail/delivery-orders/edit?marketingId=${initialValues?.id}`
: `/marketing/add/delivery-orders?marketingId=${initialValues?.id}`
}
>
<Icon icon='mdi:truck' width={24} height={24} />
{initialValues?.latest_approval?.step_number == 3
? 'Edit '
: 'Tambah '}
Delivery Order
</Button>
</RequirePermission>
</>
)}
</div>
<Card
title='Informasi Penjualan'
className={{
wrapper: 'w-full bg-white',
}}
>
<div className='overflow-x-auto rounded-box border border-base-content/5 bg-base-100 mt-3'>
<table className='table'>
<tbody>
<tr>
<td width='45%' className='font-semibold'>
No. Sales Order
</td>
<td>:</td>
<td width='50%' className='font-mono'>
{initialValues?.so_number}
</td>
</tr>
{Number(initialValues?.latest_approval?.step_number) > 2 && (
<tr>
<td width='45%' className='font-semibold'>
No. Delivery Order
</td>
<td>:</td>
<td width='50%' className='font-mono'>
{initialValues?.delivery_order
?.map((item) => item.do_number)
.join(', ')}
</td>
</tr>
)}
<tr>
<td className='font-semibold'>Nama Pelanggan</td>
<td>:</td>
<td>{initialValues?.customer?.name}</td>
</tr>
<tr>
<td className='font-semibold'>Status</td>
<td>:</td>
<td>
<Badge
variant='soft'
className={{
badge:
'rounded-lg px-2 w-fit flex flex-row justify-start whitespace-nowrap',
}}
color={
isRejected
? 'error'
: isApproved
? approval?.step_number == 1
? 'neutral'
: approval?.step_number == 2
? 'primary'
: approval?.step_number == 3
? 'success'
: 'neutral'
: 'neutral'
}
>
<Icon
icon='mdi:circle'
width={12}
height={12}
color={
approval?.step_number == 1
? 'neutral'
: approval?.step_number == 2
? 'primary'
: approval?.step_number == 3
? 'success'
: 'neutral'
}
/>
{isRejected
? 'Ditolak'
: formatTitleCase(approval?.step_name || '')}
</Badge>
</td>
</tr>
<tr>
<td className='font-semibold'>Tanggal Penjualan</td>
<td>:</td>
<td>{formatDate(initialValues?.so_date, 'DD MMM yyyy')}</td>
</tr>
<tr>
<td className='font-semibold'>Total Penjualan</td>
<td>:</td>
<td>{formatCurrency(grandTotal as number)}</td>
</tr>
<tr>
<td className='font-semibold'>Catatan</td>
<td>:</td>
<td>{initialValues?.notes ?? '-'}</td>
</tr>
<tr>
<td className='font-semibold'>Dokumen Penjualan</td>
<td>:</td>
<td>
<SalesOrderExport data={initialValues} />
</td>
</tr>
{Number(initialValues?.latest_approval?.step_number) > 2 && (
<tr>
<td className='font-semibold'>Dokumen Pengiriman</td>
<td>:</td>
<td className='flex flex-wrap gap-2'>
{initialValues?.delivery_order?.map((item, index) => (
<DeliveryOrderExport
key={index}
data={initialValues}
deliveryOrder={item}
/>
))}
</td>
</tr>
)}
</tbody>
</table>
</div>
</Card>
{initialValues?.sales_order && (
<Card
title='Informasi Produk'
className={{
wrapper: 'w-full bg-white',
}}
>
<Table<BaseSalesOrder>
data={initialValues?.sales_order}
columns={[
{
header: 'Kandang',
accessorFn(row) {
return row.product_warehouse.warehouse.name;
},
},
{
header: 'Produk',
accessorFn(row) {
return row.product_warehouse.product.name;
},
},
{
header: 'Harga Satuan (Rp)',
accessorFn(row) {
return formatCurrency(row.unit_price);
},
},
{
header: 'Total Bobot (Kg)',
accessorFn(row) {
return formatNumber(row.total_weight);
},
},
{
header: 'Kuantitas',
accessorFn(row) {
return formatNumber(row.qty);
},
},
{
header: 'Avg. Bobot (Kg)',
accessorFn(row) {
return formatNumber(row.avg_weight);
},
},
{
header: 'Total Penjualan (Rp)',
accessorFn(row) {
return formatCurrency(row.total_price);
},
},
]}
className={{
containerClassName: cn({
'mb-20':
initialValues?.sales_order &&
initialValues?.sales_order?.length === 0,
}),
tableWrapperClassName: 'overflow-x-auto min-h-full!',
tableClassName: 'font-inter w-full table-auto min-h-full!',
headerRowClassName: 'border-b border-b-gray-200',
headerColumnClassName:
'px-6 py-3 text-xs font-semibold text-gray-500 last:flex last:flex-row last:justify-end',
bodyRowClassName: 'border-b border-b-gray-200',
bodyColumnClassName:
'px-6 py-3 last:flex last:flex-row last:justify-end',
paginationClassName: 'hidden',
}}
/>
</Card>
)}
{initialValues?.delivery_order && (
<Card
title='Informasi Pengiriman'
className={{
wrapper: 'w-full bg-white',
}}
>
{initialValues?.delivery_order.map((delivery, index) => {
return (
<div key={index}>
<Card
className={{
wrapper: 'w-full',
}}
>
<div className='flex flex-row gap-3'>
<div className='font-semibold'>
Nomor DO : {delivery.do_number}
</div>
</div>
<Table<BaseDelivery>
data={delivery.deliveries}
columns={[
{
header: 'Tanggal Pengiriman',
accessorFn() {
return formatDate(
delivery.delivery_date,
'DD MMM yyyy'
);
},
},
{
header: 'No. Polisi',
accessorFn(row) {
return formatVechicleNumber(row.vehicle_number);
},
},
{
header: 'Kandang',
accessorFn(row) {
return row.product_warehouse.warehouse.name;
},
},
{
header: 'Produk',
accessorFn(row) {
return row.product_warehouse.product.name;
},
},
{
header: 'Harga Satuan (Rp)',
accessorFn(row) {
return formatCurrency(row.unit_price);
},
},
{
header: 'Total Bobot (Kg)',
accessorFn(row) {
return formatNumber(row.total_weight);
},
},
{
header: 'Kuantitas',
accessorFn(row) {
return formatNumber(row.qty);
},
},
{
header: 'Avg. Bobot (Kg)',
accessorFn(row) {
return formatNumber(row.avg_weight);
},
},
{
header: 'Total Penjualan (Rp)',
accessorFn(row) {
return formatCurrency(row.total_price);
},
},
]}
className={{
containerClassName: cn({
'mb-20':
initialValues?.sales_order &&
initialValues?.sales_order?.length === 0,
}),
tableWrapperClassName: 'overflow-x-auto min-h-full!',
tableClassName:
'font-inter w-full table-auto min-h-full!',
headerRowClassName: 'border-b border-b-gray-200',
headerColumnClassName:
'px-6 py-3 text-xs font-semibold text-gray-500 last:flex last:flex-row last:justify-end',
bodyRowClassName: 'border-b border-b-gray-200',
bodyColumnClassName:
'px-6 py-3 last:flex last:flex-row last:justify-end',
paginationClassName: 'hidden',
}}
/>
</Card>
<div className='flex flex-row gap-3 my-3'>
<DeliveryOrderExport
data={initialValues}
deliveryOrder={delivery}
/>
</div>
</div>
);
})}
</Card>
)}
<div className='flex flex-row gap-3'>
{initialValues?.latest_approval?.step_number != 3 && (
<>
<RequirePermission permissions='lti.marketing.sales_order.update'>
<Button
color='warning'
type='button'
href={`/marketing/detail/${initialValues?.latest_approval?.step_number == 3 ? 'delivery-orders' : 'sales-orders'}/edit?marketingId=${initialValues?.id}`}
>
<Icon icon='mdi:pencil' width={24} height={24} />
Edit
</Button>
</RequirePermission>
</>
)}
<RequirePermission permissions='lti.marketing.sales_order.delete'>
<Button color='error' onClick={deleteClickHandler}>
<Icon icon='mdi:delete' width={24} height={24} />
Hapus
</Button>
</RequirePermission>
</div>
</div>
<ConfirmationModal
ref={deleteModal.ref}
type='error'
text={`Apakah anda yakin ingin menghapus data penjualan ini?`}
secondaryButton={{
text: 'Tidak',
}}
primaryButton={{
text: 'Ya',
color: 'error',
isLoading: isLoading,
onClick: confirmationModalDeleteClickHandler,
}}
/>
<ConfirmationModalWithNotes
ref={confirmationModal.ref}
type={approvalAction === 'APPROVED' ? 'success' : 'error'}
text={`Apakah anda yakin ingin ${approvalAction == 'APPROVED' ? 'approve' : 'reject'} data penjualan ini?`}
secondaryButton={{
text: 'Tidak',
}}
primaryButton={{
text: 'Ya',
color: approvalAction === 'APPROVED' ? 'success' : 'error',
isLoading: isLoading,
onClick: confirmationModalApproveClickHandler,
}}
/>
<ConfirmationModalWithNotes
ref={deliveryModal.ref}
type={'success'}
text={`Apakah anda yakin ingin deliver penjualan ini?`}
secondaryButton={{
text: 'Tidak',
}}
primaryButton={{
text: 'Ya',
color: 'success',
isLoading: isLoading,
onClick: confirmationModalDeliveryClickHandler,
}}
/>
</>
);
};
export default MarketingDetail;
@@ -12,7 +12,7 @@ import {
BaseSalesOrder, BaseSalesOrder,
Marketing, Marketing,
} from '@/types/api/marketing/marketing'; } from '@/types/api/marketing/marketing';
import { formatDate } from '@/lib/helper'; import { formatDate, formatTitleCase } from '@/lib/helper';
type MarketingSchemaType = { type MarketingSchemaType = {
customer_id: number | undefined; customer_id: number | undefined;
@@ -94,7 +94,7 @@ export type SalesOrderFormValues = Yup.InferType<typeof SalesOrderSchema>;
export type DeliveryOrderFormValues = Yup.InferType<typeof DeliveryOrderSchema>; export type DeliveryOrderFormValues = Yup.InferType<typeof DeliveryOrderSchema>;
// ================ Helper Function ================ // ================ Helper Function ================
const SalesProductToFieldValues = ( export const SalesProductToFieldValues = (
product: BaseSalesOrder product: BaseSalesOrder
): SalesOrderProductFormValues => { ): SalesOrderProductFormValues => {
return { return {
@@ -109,15 +109,37 @@ const SalesProductToFieldValues = (
value: product.product_warehouse.id, value: product.product_warehouse.id,
label: product.product_warehouse.product.name, label: product.product_warehouse.product.name,
}, },
product_warehouse_data: product.product_warehouse,
product_warehouse_id: product.product_warehouse.id, product_warehouse_id: product.product_warehouse.id,
unit_price: product.unit_price, unit_price: product.unit_price,
total_weight: product.total_weight, total_weight: product.total_weight,
qty: product.qty, qty: product.qty,
avg_weight: product.avg_weight, avg_weight: product.avg_weight,
total_price: product.total_price, total_price: product.total_price,
marketing_type: product.marketing_type
? {
value: product.marketing_type,
label: formatTitleCase(product.marketing_type),
}
: null,
convertion_unit: product.convertion_unit
? {
value: product.convertion_unit,
label: formatTitleCase(product.convertion_unit),
}
: null,
week: product.week
? {
value: product.week,
label: `Week ${product.week}`,
}
: null,
total_peti: product.total_peti,
weight_per_convertion: product.weight_per_convertion,
uom: product.product_warehouse.product.uom.name,
}; };
}; };
const DeliveryProductToFieldValues = ( export const DeliveryProductToFieldValues = (
salesOrders: BaseSalesOrder[], salesOrders: BaseSalesOrder[],
delivery: BaseDeliveryOrder delivery: BaseDeliveryOrder
): DeliveryOrderProductFormValues[] => { ): DeliveryOrderProductFormValues[] => {
@@ -181,6 +203,24 @@ export const mergeSOwithDO = (
avg_weight: autofill ? so.avg_weight : delivery?.avg_weight, avg_weight: autofill ? so.avg_weight : delivery?.avg_weight,
total_price: autofill ? so.total_price : delivery?.total_price, total_price: autofill ? so.total_price : delivery?.total_price,
marketing_product: so, // jika ada, override marketing_product: so, // jika ada, override
uom: autofill ? so.uom : delivery?.uom,
weight_per_convertion: autofill
? so.weight_per_convertion
: delivery?.weight_per_convertion,
price_per_convertion: autofill
? so.price_per_convertion
: delivery?.price_per_convertion,
convertion_unit: autofill
? so.convertion_unit
: delivery?.convertion_unit,
marketing_type: autofill ? so.marketing_type : delivery?.marketing_type,
total_peti: autofill ? so.total_peti : delivery?.total_peti,
price_per_qty: autofill ? so.price_per_qty : delivery?.price_per_qty,
sisa_berat: autofill ? so.sisa_berat : delivery?.sisa_berat,
price_sisa_berat: autofill
? so.price_sisa_berat
: delivery?.price_sisa_berat,
week: autofill ? so.week : delivery?.week,
} as DeliveryOrderProductFormValues; } as DeliveryOrderProductFormValues;
}); });
}; };
@@ -213,3 +253,11 @@ export const getFilledMarketingFormInitialValues = (
), ),
}; };
}; };
export const getPricePerConvertion = (
totalPrice: number,
weightPerConvertion: number,
totalPeti: number
) => {
return totalPrice / (weightPerConvertion * totalPeti);
};
@@ -1,872 +0,0 @@
'use client';
import Button from '@/components/Button';
import Card from '@/components/Card';
import { FormHeader } from '@/components/helper/form/FormHeader';
import DateInput from '@/components/input/DateInput';
import SelectInput, {
OptionType,
useSelect,
} from '@/components/input/SelectInput';
import Modal, { useModal } from '@/components/Modal';
import { formatCurrency, formatDate } from '@/lib/helper';
import {
BaseDeliveryOrder,
BaseSalesOrder,
CreateDeliveryOrderPayload,
CreateSalesOrderPayload,
CreateSalesOrderProductPayload,
Marketing,
UpdateDeliveryOrderPayload,
UpdateSalesOrderPayload,
} from '@/types/api/marketing/marketing';
import { Icon } from '@iconify/react';
import { memo, useCallback, useEffect, useMemo, useState } from 'react';
import { Customer } from '@/types/api/master-data/customer';
import { CustomerApi } from '@/services/api/master-data';
import { useFormik } from 'formik';
import {
DeliveryOrderFormValues,
DeliveryOrderSchema,
SalesOrderFormValues,
SalesOrderSchema,
} from '@/components/pages/marketing/form/MarketingForm.schema';
import { isResponseError, isResponseSuccess } from '@/lib/api-helper';
import {
DeliveryOrderApi,
MarketingApi,
SalesOrderApi,
} from '@/services/api/marketing/marketing';
import ConfirmationModal from '@/components/modal/ConfirmationModal';
import toast from 'react-hot-toast';
import { useRouter } from 'next/navigation';
import DebouncedTextArea from '@/components/input/DebouncedTextArea';
import SalesOrderProductForm from '@/components/pages/marketing/form/repeater/sales-order/SalesOrderProductForm';
import DeliveryOrderProductTable from '@/components/pages/marketing/form/table-view/DeliveryOrderProductTable';
import DeliveryOrderProductForm from '@/components/pages/marketing/form/repeater/delivery-order/DeliverOrderProduct';
import { SalesOrderProductFormValues } from '@/components/pages/marketing/form/repeater/sales-order/SalesOrderProduct.schema';
import { DeliveryOrderProductFormValues } from '@/components/pages/marketing/form/repeater/delivery-order/DeliverOrderProduct.schema';
import RequirePermission from '@/components/helper/RequirePermission';
import AlertErrorList from '@/components/helper/form/FormErrors';
import { useFormikErrorList } from '@/services/hooks/useFormikErrorList';
import { CreatedUser } from '@/types/api/api-general';
import { UserApi } from '@/services/api/user';
const MemoizedSalesOrderProductForm = memo(SalesOrderProductForm);
const MemoizedDeliveryOrderProductTable = memo(DeliveryOrderProductTable);
const MemoizedDeliveryOrderProductForm = memo(DeliveryOrderProductForm);
// ================== EXTERNAL HELPER FUNCTION ==================
export interface ProductCalculationFields {
qty: string | number | undefined;
unit_price: string | number | undefined;
total_price: string | number | undefined;
avg_weight: string | number | undefined;
total_weight: string | number | undefined;
}
export const SalesProductToFieldValues = (
product: BaseSalesOrder
): SalesOrderProductFormValues => {
return {
id: product.id,
vehicle_number: product.vehicle_number,
kandang_id: product.product_warehouse.warehouse.id,
kandang: {
value: product.product_warehouse.warehouse.id,
label: product.product_warehouse.warehouse.name,
},
product_warehouse: {
value: product.product_warehouse.id,
label: product.product_warehouse.product.name,
},
product_warehouse_id: product.product_warehouse.id,
unit_price: product.unit_price,
total_weight: product.total_weight,
qty: product.qty,
avg_weight: product.avg_weight,
total_price: product.total_price,
};
};
export const DeliveryProductToFieldValues = (
salesOrders: BaseSalesOrder[],
delivery: BaseDeliveryOrder
): DeliveryOrderProductFormValues[] => {
const data = delivery.deliveries.map((item) => {
const soId = salesOrders.find(
(so) => so.product_warehouse.id === item.product_warehouse.id
)?.id;
return {
id: soId,
unit_price: item.unit_price,
total_weight: item.total_weight,
qty: item.qty,
avg_weight: item.avg_weight,
total_price: item.total_price,
vehicle_number: item.vehicle_number,
delivery_date: formatDate(delivery.delivery_date, 'yyyy-MM-DD'),
do_number: delivery.do_number,
marketing_product_id: soId,
marketing_product: {
id: soId,
vehicle_number: item.vehicle_number,
kandang_id: item.product_warehouse.warehouse.id,
kandang: {
value: item.product_warehouse.warehouse.id,
label: item.product_warehouse.warehouse.name,
},
product_warehouse: {
value: item.product_warehouse.id,
label: item.product_warehouse.product.name,
},
product_warehouse_id: item.product_warehouse.id,
unit_price: item.unit_price,
total_weight: item.total_weight,
qty: item.qty,
avg_weight: item.avg_weight,
total_price: item.total_price,
},
} as DeliveryOrderProductFormValues;
});
return data;
};
export const mergeSOwithDO = (
salesOrders: SalesOrderProductFormValues[],
deliveryOrders: DeliveryOrderProductFormValues[],
autofill?: boolean
): DeliveryOrderProductFormValues[] => {
return salesOrders.map((so) => {
const delivery = deliveryOrders.find(
(d) => d?.marketing_product_id === so.id
);
return {
...so, // nilai dasar dari sales order
marketing_product_id: so.id,
delivery_date: delivery?.delivery_date || undefined,
do_number: delivery?.do_number || undefined,
vehicle_number: delivery?.vehicle_number || so.vehicle_number,
unit_price: autofill ? so.unit_price : delivery?.unit_price,
total_weight: autofill ? so.total_weight : delivery?.total_weight,
qty: autofill ? so.qty : delivery?.qty,
avg_weight: autofill ? so.avg_weight : delivery?.avg_weight,
total_price: autofill ? so.total_price : delivery?.total_price,
marketing_product: so, // jika ada, override
} as DeliveryOrderProductFormValues;
});
};
export const recalculate = (
field: string,
values: ProductCalculationFields
) => {
const { qty, unit_price, total_price, avg_weight, total_weight } = values;
const result: Partial<ProductCalculationFields> = {};
if (field == 'unit_price' || field == 'total_price' || field == 'qty') {
if (qty && unit_price && (field == 'unit_price' || field == 'qty')) {
result.total_price = Number(qty) * Number(unit_price);
} else if (qty && total_price && field == 'total_price') {
result.unit_price = Number(total_price) / Number(qty);
}
}
if (field == 'avg_weight' || field == 'total_weight' || field == 'qty') {
if (qty && avg_weight && (field == 'avg_weight' || field == 'qty')) {
result.total_weight = Number(qty) * Number(avg_weight);
} else if (qty && total_weight && field == 'total_weight') {
result.avg_weight = Number(total_weight) / Number(qty);
}
}
return result;
};
export const getSubmitField = (values: ProductCalculationFields) => {
const { qty, unit_price, total_price, avg_weight, total_weight } = values;
// Harga logic
if (qty && unit_price && !total_price) {
return 'unit_price';
}
if (qty && total_price && !unit_price) {
return 'total_price';
}
// Bobot logic
if (qty && avg_weight && !total_weight) {
return 'avg_weight';
}
if (qty && total_weight && !avg_weight) {
return 'total_weight';
}
// Tidak ada yang perlu dihitung
return '';
};
const MarketingForm = ({
formType = 'add',
initialValues,
afterSubmit,
}: {
formType?: 'add' | 'edit' | 'add_deliver' | 'edit_deliver';
initialValues?: Marketing;
afterSubmit?: () => void;
}) => {
const router = useRouter();
const deleteModal = useModal();
const [isLoading, setIsLoading] = useState(false);
const [selectedMarketingProduct, setSelectedMarketingProduct] =
useState<SalesOrderProductFormValues | null>(null);
const [selectedDeliveryProduct, setSelectedDeliveryProduct] =
useState<DeliveryOrderProductFormValues | null>(null);
const [deliveryFormState, setDeliveryFormState] = useState<'add' | 'edit'>(
'add'
);
const [deliveryOrderValues, setDeliveryOrderValues] = useState<
DeliveryOrderProductFormValues[]
>(
mergeSOwithDO(
initialValues?.sales_order?.map(SalesProductToFieldValues) ?? [],
initialValues?.delivery_order?.flatMap((delivery) =>
DeliveryProductToFieldValues(initialValues.sales_order, delivery)
) ?? []
)
);
// ================== REPEATER ==================
const addSOModal = useModal();
const addDOModal = useModal();
const [rowSOSelection, setRowSOSelection] = useState<Record<string, boolean>>(
{}
);
const selectedRowSOIds = Object.keys(rowSOSelection).map((item) =>
parseInt(item)
);
// ================== FETCH OPTIONS ==================
const {
options: customerOptions,
isLoadingOptions: isLoadingCustomerOptions,
setInputValue: setInputCustomerValue,
loadMore: loadMoreCustomer,
} = useSelect<Customer>(CustomerApi.basePath, 'id', 'name');
const {
options: salesOptions,
isLoadingOptions: isLoadingSalesOptions,
setInputValue: setInputSalesValue,
loadMore: loadMoreSales,
} = useSelect<CreatedUser>(UserApi.basePath, 'id', 'name');
// ================== SETUP FORMIK ==================
const formikInitialValues = useMemo<
SalesOrderFormValues & DeliveryOrderFormValues
>(() => {
return {
so_date: initialValues?.so_date || undefined,
notes: initialValues?.notes || undefined,
customer_id: initialValues?.customer?.id || undefined,
sales_person_id: initialValues?.sales_person?.id || 1,
sales_person: initialValues?.sales_person
? {
value: initialValues.sales_person.id,
label: initialValues.sales_person.name,
}
: null,
customer: initialValues?.customer
? {
value: initialValues.customer.id,
label: initialValues.customer.name,
}
: null,
sales_order:
initialValues?.sales_order?.map((product) =>
SalesProductToFieldValues(product)
) ?? [],
delivery_order: mergeSOwithDO(
initialValues?.sales_order?.map(SalesProductToFieldValues) ?? [],
initialValues?.delivery_order?.flatMap((delivery) =>
DeliveryProductToFieldValues(initialValues.sales_order, delivery)
) ?? []
),
};
}, [initialValues]);
const formik = useFormik<SalesOrderFormValues & DeliveryOrderFormValues>({
enableReinitialize: true,
initialValues: formikInitialValues,
validationSchema:
formType == 'add_deliver' || formType == 'edit_deliver'
? DeliveryOrderSchema
: SalesOrderSchema,
validateOnMount: true,
onSubmit: async (values) => {
const payload =
formType != 'add_deliver' && formType != 'edit_deliver'
? ({
customer_id: values.customer_id as number,
sales_person_id: values.sales_person_id as number,
date: formatDate(values.so_date as string, 'yyyy-MM-DD'),
notes: values.notes as string,
marketing_products: values.sales_order.map((product) => {
return {
vehicle_number: product.vehicle_number as string,
kandang_id: product.kandang_id as number,
product_warehouse_id: product.product_warehouse_id as number,
unit_price: parseFloat(product.unit_price as string),
total_weight: parseFloat(product.total_weight as string),
qty: parseFloat(product.qty as string),
avg_weight: parseFloat(product.avg_weight as string),
total_price: parseFloat(product.total_price as string),
} as CreateSalesOrderProductPayload;
}),
} as CreateSalesOrderPayload)
: ({
marketing_id: initialValues?.id as number,
delivery_products: values.delivery_order
.map((product) => {
if (Boolean(product.delivery_date)) {
return {
marketing_product_id:
product.marketing_product_id as number,
unit_price: parseFloat(product.unit_price as string),
total_weight: parseFloat(product.total_weight as string),
qty: parseFloat(product.qty as string),
avg_weight: parseFloat(product.avg_weight as string),
total_price: parseFloat(product.total_price as string),
delivery_date: formatDate(
product.delivery_date as string,
'yyyy-MM-DD'
),
vehicle_number: product.vehicle_number,
};
}
})
.filter((item) => Boolean(item)),
} as UpdateDeliveryOrderPayload);
switch (formType) {
case 'add':
await createMarketingHandler(payload as CreateSalesOrderPayload);
break;
case 'edit':
await updateMarketingHandler(payload as UpdateSalesOrderPayload);
break;
case 'add_deliver':
await createDeliveryHandler(payload as CreateDeliveryOrderPayload);
break;
case 'edit_deliver':
await updateDeliveryHandler(payload as UpdateDeliveryOrderPayload);
break;
default:
break;
}
afterSubmit?.();
},
});
const memoSalesOrder = formik.values.sales_order;
// ================== FORM REPEATER HANDLER ==================
const createMarketingHandler = async (values: CreateSalesOrderPayload) => {
setIsLoading(true);
const createMarketingRes = await SalesOrderApi.create(values);
if (isResponseSuccess(createMarketingRes)) {
toast.success(createMarketingRes?.message as string);
router.push('/marketing');
}
if (isResponseError(createMarketingRes)) {
toast.error(createMarketingRes?.message as string);
}
setIsLoading(false);
};
const updateMarketingHandler = async (values: UpdateSalesOrderPayload) => {
setIsLoading(true);
const updateMarketingRes = await SalesOrderApi.update(
initialValues?.id as number,
values
);
if (isResponseSuccess(updateMarketingRes)) {
toast.success(updateMarketingRes?.message as string);
router.push(`/marketing/detail?marketingId=${initialValues?.id}`);
}
if (isResponseError(updateMarketingRes)) {
toast.error(updateMarketingRes?.message as string);
}
setIsLoading(false);
};
const createDeliveryHandler = async (values: CreateDeliveryOrderPayload) => {
setIsLoading(true);
const createDeliveryRes = await DeliveryOrderApi.create(values);
if (isResponseSuccess(createDeliveryRes)) {
toast.success(createDeliveryRes?.message as string);
setDeliveryOrderValues(
createDeliveryRes.data?.delivery_order?.flatMap((delivery) =>
DeliveryProductToFieldValues(
createDeliveryRes.data?.sales_order,
delivery
)
) ?? []
);
router.push(`/marketing/detail?marketingId=${initialValues?.id}`);
}
if (isResponseError(createDeliveryRes)) {
toast.error(createDeliveryRes?.message as string);
}
setIsLoading(false);
};
const updateDeliveryHandler = async (values: UpdateDeliveryOrderPayload) => {
setIsLoading(true);
const updateDeliveryRes = await DeliveryOrderApi.update(
initialValues?.id as number,
values
);
if (isResponseSuccess(updateDeliveryRes)) {
toast.success(updateDeliveryRes?.message as string);
setDeliveryOrderValues(
mergeSOwithDO(
formik.values.sales_order,
updateDeliveryRes.data?.delivery_order?.flatMap((delivery) =>
DeliveryProductToFieldValues(
updateDeliveryRes.data?.sales_order,
delivery
)
) ?? []
)
);
router.push(`/marketing/detail?marketingId=${initialValues?.id}`);
}
if (isResponseError(updateDeliveryRes)) {
toast.error(updateDeliveryRes?.message as string);
}
setIsLoading(false);
};
// ================== MARKETING HANDLER ==================
const deleteMarketingHandler = async () => {
setIsLoading(true);
const deleteMarketingRes = await MarketingApi.delete(
initialValues?.id as number
);
if (isResponseSuccess(deleteMarketingRes)) {
toast.success(deleteMarketingRes?.message as string);
}
if (isResponseError(deleteMarketingRes)) {
toast.error(deleteMarketingRes?.message as string);
}
setIsLoading(false);
deleteModal.closeModal();
router.push('/marketing');
};
const handleChangeCustomer = useCallback(
(val: OptionType | OptionType[] | null) => {
formik.setFieldValue('customer_id', (val as OptionType)?.value);
formik.setFieldValue('customer', val as OptionType);
},
[]
);
const handleChangeSalesPerson = useCallback(
(val: OptionType | OptionType[] | null) => {
formik.setFieldValue('sales_person_id', (val as OptionType)?.value);
formik.setFieldValue('sales_person', val as OptionType);
},
[]
);
const handleDelete = useCallback(() => {
deleteModal.openModal();
}, [deleteModal]);
// ================== SALES ORDER HANDLER ==================
const handleDeleteSO = useCallback(
(id: number) => {
const currentProducts = formik.values.sales_order;
formik.setFieldValue(
'sales_order',
currentProducts.filter((p) => p.id != id)
);
},
[memoSalesOrder]
);
const handleEditSO = useCallback(
(id: number) => {
const currentProducts = formik.values.sales_order;
const selectedProduct = currentProducts.find((p) => p.id == id);
setSelectedMarketingProduct(selectedProduct ?? null);
addSOModal.openModal();
},
[memoSalesOrder]
);
const handleBulkDeleteSO = useCallback(() => {
const currentProducts = formik.values.sales_order;
formik.setFieldValue(
'sales_order',
currentProducts.filter(
(product) => !selectedRowSOIds.includes(product.id ?? -1)
)
);
setRowSOSelection({});
}, [selectedRowSOIds, memoSalesOrder]);
const handleAddSOClick = useCallback(() => {
setSelectedMarketingProduct(null);
addSOModal.openModal();
}, [addSOModal]);
const handleAddSubmitSO = useCallback(
async (values: SalesOrderProductFormValues, id?: number) => {
const currentProducts = formik.values.sales_order;
const newValues = {
...values,
id: values.id ?? Date.now(),
};
let updatedProducts = [];
if (id) {
// Overwrite
updatedProducts = currentProducts.map((item) =>
item.id === id ? newValues : item
);
} else {
// Add new item
updatedProducts = [...currentProducts, newValues];
}
formik.setFieldValue('sales_order', updatedProducts);
addSOModal.closeModal();
},
[addSOModal, memoSalesOrder]
);
// ================== DELIVERY ORDER HANDLER ==================
const handleEditDO = useCallback(
(id: number, values?: DeliveryOrderProductFormValues) => {
setDeliveryFormState('edit');
const currentProducts = formik.values.delivery_order.find(
(product) => product.id == id
);
setSelectedDeliveryProduct(values ?? currentProducts ?? null);
addDOModal.openModal();
},
[addDOModal]
);
const handleAddDOClick = useCallback(() => {
setDeliveryFormState('add');
setSelectedDeliveryProduct(null);
addDOModal.openModal();
}, [addDOModal]);
const handleAddSubmitDO = useCallback(
async (values: DeliveryOrderProductFormValues) => {
const newValues = {
...values,
id: values.id ?? Date.now(),
};
setDeliveryOrderValues((prev) => [...prev, newValues]);
addDOModal.closeModal();
setSelectedDeliveryProduct(null);
},
[addDOModal]
);
const handleUpdateDO = useCallback(
async (id: number, values: DeliveryOrderProductFormValues) => {
setDeliveryOrderValues((prev) =>
prev.map((product) =>
product.id === id ? { ...product, ...values } : product
)
);
addDOModal.closeModal();
setSelectedDeliveryProduct(null);
},
[addDOModal]
);
const handleDeleteDO = useCallback(
async (id: number) => {
setDeliveryOrderValues((prev) =>
prev.map((product) =>
product.id === id
? {
...product,
...{
unit_price: '',
total_weight: '',
qty: '',
avg_weight: '',
total_price: '',
delivery_date: '',
},
}
: product
)
);
addDOModal.closeModal();
setSelectedDeliveryProduct(null);
},
[addDOModal]
);
useEffect(() => {
formik.setFieldValue('delivery_order', deliveryOrderValues);
}, [deliveryOrderValues, initialValues]);
const grandTotal = useMemo(() => {
return memoSalesOrder.reduce(
(total, product) =>
total + parseFloat((product.total_price as string) || '0'),
0
);
}, [memoSalesOrder]);
// ===== Formik Error List =====
const { formErrorList, close, handleFormSubmit } = useFormikErrorList(formik);
return (
<>
<form
className='flex flex-col gap-4'
onSubmit={handleFormSubmit}
onReset={formik.handleReset}
>
<FormHeader
title={`${formType == 'add' || formType == 'add_deliver' ? 'Tambah' : 'Edit'} ${formType === 'add_deliver' || formType === 'edit_deliver' ? 'Delivery' : 'Sales'} Order`}
backUrl='/marketing'
/>
{/* Input Cutomer And Date */}
<Card
title='Informasi Order'
className={{
wrapper: 'bg-white w-full',
}}
variant='bordered'
>
<div className='grid sm:grid-cols-2 gap-3 mt-3'>
<SelectInput
label='Pelanggan'
options={customerOptions}
isLoading={isLoadingCustomerOptions}
value={formik.values.customer}
onChange={handleChangeCustomer}
onInputChange={setInputCustomerValue}
onMenuScrollToBottom={loadMoreCustomer}
isError={
formik.touched.customer_id && Boolean(formik.errors.customer_id)
}
errorMessage={formik.errors.customer_id}
isClearable
placeholder='Pilih Pelanggan'
isDisabled={
formType === 'add_deliver' ||
formType === 'edit_deliver' ||
formType === 'edit'
}
/>
<DateInput
name='so_date'
label='Tanggal'
value={formik.values.so_date}
onChange={formik.handleChange}
isError={formik.touched.so_date && Boolean(formik.errors.so_date)}
errorMessage={formik.errors.so_date}
placeholder='Pilih Tanggal'
readOnly={formType == 'add_deliver' || formType == 'edit_deliver'}
/>
</div>
</Card>
{/* Input Table Repeater Sales Order */}
<Card
title='Informasi Produk'
className={{
wrapper: 'bg-white w-full',
}}
variant='bordered'
>
{/* <MemoizedSalesOrderProductTable
formType={formType}
data={memoSalesOrder}
rowSelection={rowSOSelection}
setRowSelection={setRowSOSelection}
selectedRowIds={selectedRowSOIds}
onDelete={handleDeleteSO}
onEdit={handleEditSO}
onBulkDelete={handleBulkDeleteSO}
onAddProductClick={handleAddSOClick}
/> */}
</Card>
{/* Input Table Repeater Delivery Order */}
{(formType == 'add_deliver' || formType == 'edit_deliver') &&
initialValues?.sales_order &&
initialValues?.sales_order.length > 0 && (
<Card
title='Informasi Pengiriman'
className={{
wrapper: 'bg-white w-full',
}}
>
<MemoizedDeliveryOrderProductTable
marketing={initialValues}
formType={formType}
data={deliveryOrderValues}
onEdit={handleEditDO}
onDelete={handleDeleteDO}
onAddProductClick={handleAddDOClick}
/>
</Card>
)}
{/* Input Notes */}
<div className='grid sm:grid-cols-2 gap-3'>
<div className='flex flex-col h-full items-end gap-3'>
<SelectInput
label='Sales'
options={salesOptions}
isLoading={isLoadingSalesOptions}
value={formik.values.sales_person}
onChange={handleChangeSalesPerson}
onInputChange={setInputSalesValue}
onMenuScrollToBottom={loadMoreSales}
isError={
formik.touched.sales_person_id &&
Boolean(formik.errors.sales_person_id)
}
errorMessage={formik.errors.sales_person_id}
isClearable
placeholder='Pilih Sales'
isDisabled={
formType === 'add_deliver' || formType === 'edit_deliver'
}
/>
<DebouncedTextArea
required
name='notes'
label='Catatan'
rows={3}
placeholder='Masukan catatan penjualan'
value={formik.values.notes}
onChange={formik.handleChange}
isError={formik.touched.notes && Boolean(formik.errors.notes)}
errorMessage={formik.errors.notes}
disabled={
formType === 'add_deliver' || formType === 'edit_deliver'
}
/>
</div>
<div className='flex flex-col h-full justify-end items-end'>
<span>Total Penjualan</span>
<span className='text-lg font-semibold'>
{formatCurrency(grandTotal)}{' '}
</span>
</div>
</div>
<AlertErrorList formErrorList={formErrorList} onClose={close} />
{/* Form Actions */}
<div className='flex flex-row items-start justify-center gap-2 mt-4'>
<Button type='reset' color='warning' disabled={formik.isSubmitting}>
Reset
</Button>
<Button
type='submit'
disabled={formik.isSubmitting}
isLoading={formik.isSubmitting}
>
Submit
</Button>
</div>
</form>
{/* Actions button */}
{formType == 'edit' && (
<div className='flex flex-row justify-start'>
<RequirePermission permissions='lti.marketing.sales_order.delete'>
<Button
type='button'
color='error'
onClick={handleDelete}
isLoading={isLoading}
>
<Icon icon='mdi:trash' width={24} height={24} />
Hapus
</Button>
</RequirePermission>
</div>
)}
{/* Modals */}
<Modal
ref={addSOModal.ref}
closeOnBackdrop
className={{
modalBox: 'max-w-4/5 z-100',
}}
>
<div className='flex flex-col gap-4'>
<div className='flex flex-row items-center justify-between'>
<h3 className='text-lg font-semibold mb-4'>Tambah Produk</h3>
<Button
variant='ghost'
color='error'
className='rounded-full'
onClick={addSOModal.closeModal}
>
<Icon icon='mdi:close' width={20} height={20} />
</Button>
</div>
<div>
<MemoizedSalesOrderProductForm
onSubmitForm={handleAddSubmitSO}
initialValues={selectedMarketingProduct ?? undefined}
exisitingValues={memoSalesOrder}
/>
</div>
</div>
</Modal>
<Modal
ref={addDOModal.ref}
closeOnBackdrop
className={{
modalBox: 'max-w-4/5 z-100',
}}
>
<div className='flex flex-col gap-4'>
<div className='flex flex-row items-center justify-between'>
<h3 className='text-lg font-semibold mb-4'>
{selectedDeliveryProduct ? 'Edit' : 'Tambah'} Pengiriman
</h3>
<Button
variant='ghost'
color='error'
className='rounded-full'
onClick={addDOModal.closeModal}
>
<Icon icon='mdi:close' width={20} height={20} />
</Button>
</div>
<div>
<MemoizedDeliveryOrderProductForm
formState={deliveryFormState}
salesOrders={initialValues?.sales_order ?? []}
exisitingValues={deliveryOrderValues}
onSubmitForm={handleAddSubmitDO}
initialValues={selectedDeliveryProduct ?? undefined}
onUpdateForm={handleUpdateDO}
/>
</div>
</div>
</Modal>
<ConfirmationModal
ref={deleteModal.ref}
type='error'
text={`Apakah anda yakin ingin menghapus data penjualan ini?`}
secondaryButton={{
text: 'Tidak',
onClick: deleteModal.closeModal,
}}
primaryButton={{
text: 'Ya',
color: 'error',
onClick: deleteMarketingHandler,
}}
/>
</>
);
};
export default MarketingForm;
@@ -13,6 +13,30 @@ type DeliveryOrderProductSchemaType = {
vehicle_number: string | undefined; vehicle_number: string | undefined;
delivery_date: string | undefined | null; delivery_date: string | undefined | null;
do_number?: string | undefined | null; // Uncertain do_number?: string | undefined | null; // Uncertain
uom?: string | null | undefined;
convertion_unit?: {
value: string;
label: string;
} | null;
weight_per_convertion?: number | null | undefined;
price_per_convertion?: number | null | undefined;
marketing_type?: {
value: string;
label: string;
} | null;
total_peti?: number | null | undefined;
sisa_berat?: number | null | undefined;
price_sisa_berat?: number | null | undefined;
/** Harga per butir telur untuk TELUR + QTY */
price_per_qty?: number | null | undefined;
/** Week untuk ayam pullet */
week?:
| {
value?: number;
label?: string;
}
| null
| undefined;
}; };
export const DeliveryOrderProductSchema: Yup.ObjectSchema<DeliveryOrderProductSchemaType> = export const DeliveryOrderProductSchema: Yup.ObjectSchema<DeliveryOrderProductSchemaType> =
@@ -40,6 +64,43 @@ export const DeliveryOrderProductSchema: Yup.ObjectSchema<DeliveryOrderProductSc
vehicle_number: Yup.string().required('Nomor Kendaraan wajib diisi!'), vehicle_number: Yup.string().required('Nomor Kendaraan wajib diisi!'),
delivery_date: Yup.string().required('Tanggal Pengiriman wajib diisi!'), delivery_date: Yup.string().required('Tanggal Pengiriman wajib diisi!'),
do_number: Yup.string().nullable().optional(), do_number: Yup.string().nullable().optional(),
uom: Yup.string().nullable().optional().notRequired(),
convertion_unit: Yup.object({
value: Yup.string().required('Konversi Satuan wajib diisi!'),
label: Yup.string().required('Konversi Satuan wajib diisi!'),
}).nullable(),
weight_per_convertion: Yup.number().nullable().optional().notRequired(),
marketing_type: Yup.object({
value: Yup.string().required('Kategori Penjualan wajib diisi!'),
label: Yup.string().required('Kategori Penjualan wajib diisi!'),
}).nullable(),
price_per_convertion: Yup.number().nullable().optional().notRequired(),
total_peti: Yup.number().nullable().optional().notRequired(),
sisa_berat: Yup.number().nullable().optional().notRequired(),
price_sisa_berat: Yup.number().nullable().optional().notRequired(),
price_per_qty: Yup.number().nullable().optional().notRequired(),
week: Yup.object({
value: Yup.number(),
label: Yup.string(),
})
.nullable()
.default(null)
.when('marketing_type', {
is: (marketingType: { value: string } | null | undefined) =>
marketingType?.value?.toLowerCase() === 'ayam_pullet',
then: (schema) =>
schema
.shape({
value: Yup.number().required(
'Week wajib diisi untuk Ayam Pullet!'
),
label: Yup.string().required(
'Week wajib diisi untuk Ayam Pullet!'
),
})
.required('Week wajib diisi untuk Ayam Pullet!'),
otherwise: (schema) => schema.optional().notRequired(),
}),
}); });
export type DeliveryOrderProductFormValues = Yup.InferType< export type DeliveryOrderProductFormValues = Yup.InferType<
@@ -1,4 +1,4 @@
import { useEffect, useState } from 'react'; import { useEffect, useMemo, useState } from 'react';
import { import {
DeliveryOrderProductFormValues, DeliveryOrderProductFormValues,
DeliveryOrderProductSchema, DeliveryOrderProductSchema,
@@ -8,10 +8,10 @@ import Alert from '@/components/Alert';
import Button from '@/components/Button'; import Button from '@/components/Button';
import NumberInput from '@/components/input/NumberInput'; import NumberInput from '@/components/input/NumberInput';
import PatternInput from '@/components/input/PatternInput'; import PatternInput from '@/components/input/PatternInput';
import { formatVechicleNumber } from '@/lib/helper'; import { formatTitleCase, formatVechicleNumber } from '@/lib/helper';
import DateInput from '@/components/input/DateInput'; import DateInput from '@/components/input/DateInput';
import { BaseSalesOrder } from '@/types/api/marketing/marketing'; import { BaseSalesOrder } from '@/types/api/marketing/marketing';
import { SalesProductToFieldValues } from '@/components/pages/marketing/form/MarketingForm'; import { SalesProductToFieldValues } from '@/components/pages/marketing/form/MarketingForm.schema';
import * as Yup from 'yup'; import * as Yup from 'yup';
import { isResponseSuccess } from '@/lib/api-helper'; import { isResponseSuccess } from '@/lib/api-helper';
import AlertErrorList from '@/components/helper/form/FormErrors'; import AlertErrorList from '@/components/helper/form/FormErrors';
@@ -21,9 +21,13 @@ import { ProductApi } from '@/services/api/master-data';
import StatusBadge from '@/components/helper/StatusBadge'; import StatusBadge from '@/components/helper/StatusBadge';
import SelectInputRadio from '@/components/input/SelectInputRadio'; import SelectInputRadio from '@/components/input/SelectInputRadio';
import { OptionType } from '@/components/input/SelectInput'; import { OptionType } from '@/components/input/SelectInput';
import {
const roundWeight = (value: number) => Number(value.toFixed(2)); MARKETING_CONVERTION_UNIT_OPTIONS,
const roundPrice = (value: number) => Math.round(value); MARKETING_TYPE_OPTIONS,
} from '@/config/constant';
import Dropdown from '@/components/Dropdown';
import { Icon } from '@iconify/react';
import { handleMarketingCalculation } from '@/lib/marketing-calculation';
const DeliveryOrderProductForm = ({ const DeliveryOrderProductForm = ({
formState, formState,
@@ -49,6 +53,35 @@ const DeliveryOrderProductForm = ({
); );
const [currentInput, setCurrentInput] = useState<string>(''); const [currentInput, setCurrentInput] = useState<string>('');
// Check jika ada sisa berat = total_weight - (weight_per_convertion * total_peti)
const initialSisaBerat =
initialValues?.total_weight &&
initialValues?.weight_per_convertion &&
initialValues?.total_peti
? Number(initialValues.total_weight) -
Number(initialValues.weight_per_convertion) *
Number(initialValues.total_peti)
: 0;
const initialPricePerConvertion =
initialValues?.total_price &&
initialValues?.total_peti &&
Number(initialValues.total_peti) !== 0
? (Number(initialValues.total_price) -
initialSisaBerat * Number(initialValues.unit_price || 0)) /
Number(initialValues.total_peti)
: 0;
const initialPriceSisaBerat =
initialValues?.total_price && initialValues?.total_peti
? Number(initialValues.total_price) -
initialPricePerConvertion * Number(initialValues.total_peti)
: 0;
const [hasSisaBerat, setHasSisaBerat] = useState<boolean>(
initialSisaBerat > 0
);
// ============ Fetch Data ============ // ============ Fetch Data ============
const { data: productData } = useSWR( const { data: productData } = useSWR(
selectedProduct?.value selectedProduct?.value
@@ -60,6 +93,27 @@ const DeliveryOrderProductForm = ({
: undefined : undefined
); );
// Options Week dari minggu 1 - 22
const optionsWeek = useMemo(() => {
return Array.from({ length: 22 }, (_, i) => ({
value: i + 1,
label: `Week ${i + 1}`,
}));
}, []);
const options = exisitingValues
?.map((item) => {
if (!Boolean(item.qty)) {
return {
value: item.id,
label: `${item.marketing_product?.product_warehouse?.label} - ${item.marketing_product?.kandang?.label}`,
} as OptionType;
} else {
return null;
}
})
?.filter((item) => item != null) as OptionType[];
const salesOrder = salesOrders.find( const salesOrder = salesOrders.find(
(item) => item.id === initialValues?.marketing_product_id (item) => item.id === initialValues?.marketing_product_id
); );
@@ -77,6 +131,19 @@ const DeliveryOrderProductForm = ({
avg_weight: initialValues?.avg_weight || undefined, avg_weight: initialValues?.avg_weight || undefined,
total_price: initialValues?.total_price || undefined, total_price: initialValues?.total_price || undefined,
marketing_product: initialValues?.marketing_product || undefined, marketing_product: initialValues?.marketing_product || undefined,
uom: initialValues?.uom || '',
weight_per_convertion:
initialValues?.weight_per_convertion != null
? Number(initialValues.weight_per_convertion)
: null,
price_per_convertion: initialPricePerConvertion,
convertion_unit: initialValues?.convertion_unit || null,
marketing_type: initialValues?.marketing_type || null,
total_peti: initialValues?.total_peti ?? null,
price_per_qty: initialValues?.price_per_qty ?? null,
sisa_berat: initialSisaBerat,
price_sisa_berat: initialPriceSisaBerat,
week: initialValues?.week ?? null,
}, },
isInitialValid: false, isInitialValid: false,
validationSchema: Yup.object().shape({ validationSchema: Yup.object().shape({
@@ -124,6 +191,16 @@ const DeliveryOrderProductForm = ({
avg_weight: '', avg_weight: '',
total_price: '', total_price: '',
marketing_product: undefined, marketing_product: undefined,
total_peti: null,
price_per_qty: null,
price_sisa_berat: null,
sisa_berat: null,
convertion_unit: null,
marketing_type: null,
weight_per_convertion: null,
price_per_convertion: null,
uom: '',
week: null,
}, },
}); });
// setSelectedProduct(null); // setSelectedProduct(null);
@@ -132,94 +209,34 @@ const DeliveryOrderProductForm = ({
const handleBlurField = (field: string) => { const handleBlurField = (field: string) => {
setCurrentInput(field); setCurrentInput(field);
const qty = Number(formik.values.qty || 0); handleMarketingCalculation(field, {
const avgWeight = Number(formik.values.avg_weight || 0); values: formik.values,
const totalWeight = Number(formik.values.total_weight || 0); setFieldValue: formik.setFieldValue,
const unitPrice = Number(formik.values.unit_price || 0); hasSisaBerat,
const totalPrice = Number(formik.values.total_price || 0); });
if (qty <= 0) return;
switch (field) {
// ===== SOURCE FIELDS =====
case 'qty': {
if (avgWeight > 0) {
const tw = roundWeight(qty * avgWeight);
formik.setFieldValue('total_weight', tw);
// Hitung total_price berdasarkan unit_price × total_weight
if (unitPrice > 0) {
formik.setFieldValue('total_price', roundPrice(unitPrice * tw));
}
}
break;
}
case 'avg_weight': {
if (avgWeight > 0) {
const tw = roundWeight(qty * avgWeight);
formik.setFieldValue('total_weight', tw);
// Hitung total_price berdasarkan unit_price × total_weight
if (unitPrice > 0) {
formik.setFieldValue('total_price', roundPrice(unitPrice * tw));
}
}
break;
}
case 'unit_price': {
if (unitPrice > 0 && totalWeight > 0) {
// Hitung total_price berdasarkan unit_price × total_weight
formik.setFieldValue(
'total_price',
roundPrice(unitPrice * totalWeight)
);
}
break;
}
// ===== TOTAL EDITABLE =====
case 'total_weight': {
if (totalWeight > 0) {
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;
}
case 'total_price': {
if (totalPrice > 0 && totalWeight > 0) {
// Hitung unit_price berdasarkan total_price / total_weight
formik.setFieldValue(
'unit_price',
roundPrice(totalPrice / totalWeight)
);
}
break;
}
}
}; };
const options = exisitingValues // Handler khusus untuk toggle sisa berat - langsung pakai nilai baru
?.map((item) => { const handleSisaBeratToggle = (newHasSisaBerat: boolean) => {
if (!Boolean(item.qty)) { setHasSisaBerat(newHasSisaBerat);
return {
value: item.id, if (!newHasSisaBerat) {
label: `${item.marketing_product?.product_warehouse?.label} - ${item.marketing_product?.kandang?.label}`, // Ketika OFF - set nilai ke 0 dan recalculate tanpa sisa
} as OptionType; formik.setFieldValue('sisa_berat', 0);
} else { formik.setFieldValue('price_sisa_berat', 0);
return null; }
}
}) // Langsung trigger recalculation dengan hasSisaBerat yang baru
?.filter((item) => item != null) as OptionType[]; handleMarketingCalculation('total_peti', {
values: {
...formik.values,
sisa_berat: newHasSisaBerat ? formik.values.sisa_berat : 0,
price_sisa_berat: newHasSisaBerat ? formik.values.price_sisa_berat : 0,
},
setFieldValue: formik.setFieldValue,
hasSisaBerat: newHasSisaBerat,
});
};
const { setValues: setFormikValues } = formik; const { setValues: setFormikValues } = formik;
@@ -229,9 +246,6 @@ const DeliveryOrderProductForm = ({
handleResetForm(); handleResetForm();
} else { } else {
setFormikValues(initialValues); setFormikValues(initialValues);
// const value = exisitingValues?.find(
// (item) => item.id === initialValues?.id
// );
if (initialValues?.marketing_product_id) { if (initialValues?.marketing_product_id) {
setSelectedProduct({ setSelectedProduct({
value: initialValues?.id, value: initialValues?.id,
@@ -243,7 +257,23 @@ const DeliveryOrderProductForm = ({
}, [initialValues]); }, [initialValues]);
// ===== Formik Error List ===== // ===== Formik Error List =====
const { formErrorList, close, handleFormSubmit } = useFormikErrorList(formik); const { formErrorList, close, handleFormSubmit } = useFormikErrorList(
formik,
{
onBeforeSubmit(e) {
e.preventDefault();
handleBlurField(currentInput);
formik.setFieldValue(
'uom',
isResponseSuccess(productData) ? productData?.data?.uom?.name : ''
);
},
}
);
useEffect(() => {
handleBlurField('week');
}, [formik.values.week]);
return ( return (
<> <>
@@ -252,214 +282,514 @@ const DeliveryOrderProductForm = ({
onSubmit={handleFormSubmit} onSubmit={handleFormSubmit}
onReset={handleResetForm} onReset={handleResetForm}
> >
{formikErrorMessage && ( <div className='flex flex-col px-4 pb-4 gap-1.5 border-b border-base-content/10'>
<div onClick={() => setFormErrorMessage('')} className='my-3 w-full'> {formikErrorMessage && (
<Alert color='error'>{formikErrorMessage}</Alert> <div
</div> onClick={() => setFormErrorMessage('')}
)} className='my-3 w-full'
<DateInput >
name='delivery_date' <Alert color='error'>{formikErrorMessage}</Alert>
label='Tanggal' </div>
value={formik.values.delivery_date ?? undefined} )}
onChange={formik.handleChange}
onBlur={formik.handleBlur} {/* Tanggal Pengiriman */}
isError={ <DateInput
formik.touched.delivery_date && Boolean(formik.errors.delivery_date) name='delivery_date'
} label='Tanggal'
errorMessage={formik.errors.delivery_date} value={formik.values.delivery_date ?? undefined}
placeholder='Pilih Tanggal' onChange={formik.handleChange}
className={{ onBlur={formik.handleBlur}
inputWrapper: 'bg-white', isError={
}} formik.touched.delivery_date &&
required Boolean(formik.errors.delivery_date)
/> }
<SelectInputRadio errorMessage={formik.errors.delivery_date}
options={options} placeholder='Pilih Tanggal'
label='Produk' className={{
placeholder='Pilih Produk' inputWrapper: 'bg-white',
readOnly={formState == 'edit'} }}
value={ required
selectedProduct />
? ({
value: selectedProduct?.value, {/* No. Polisi */}
label: exisitingValues?.find( <PatternInput
(item) => item.id === selectedProduct?.value name='vehicle_number'
)?.marketing_product?.product_warehouse?.label, label='No. Polisi'
} as OptionType) format='AA #### AAA'
: null mask='_'
} inputVehicleNumber
onChange={(value) => { required
const selected = value as OptionType; type='text'
setSelectedProduct(selected); placeholder='B 1234 CDE'
value={formatVechicleNumber(formik.values.vehicle_number ?? '')}
onChange={formik.handleChange}
onBlur={formik.handleBlur}
isError={Boolean(formik.errors.vehicle_number)}
errorMessage={formik.errors.vehicle_number}
/>
{/* Produk */}
<SelectInputRadio
options={options}
label='Produk'
placeholder='Pilih Produk'
readOnly={formState == 'edit'}
value={
selectedProduct
? ({
value: selectedProduct?.value,
label: exisitingValues?.find(
(item) => item.id === selectedProduct?.value
)?.marketing_product?.product_warehouse?.label,
} as OptionType)
: null
}
onChange={(value) => {
const selected = value as OptionType;
setSelectedProduct(selected);
const so = salesOrders?.find(
(item) => item.id === selected?.value
);
if (!so) {
formik.setValues({
...formik.values,
marketing_product_id: undefined,
marketing_product: null,
qty: '',
unit_price: '',
total_price: '',
avg_weight: '',
total_weight: '',
vehicle_number: '',
});
return;
}
const so = salesOrders?.find((item) => item.id === selected?.value);
if (!so) {
formik.setValues({ formik.setValues({
...formik.values, ...formik.values,
marketing_product_id: undefined, marketing_product_id: selected.value as number,
marketing_product: null, marketing_product: SalesProductToFieldValues(so),
qty: '', qty: so.qty,
unit_price: '', unit_price: so.unit_price,
total_price: '', total_price: so.total_price,
avg_weight: '', avg_weight: so.avg_weight,
total_weight: '', total_weight: so.total_weight,
vehicle_number: '', vehicle_number: so.vehicle_number,
}); });
return; }}
startAdornment={
selectedProduct && (
<StatusBadge
text={
exisitingValues?.find(
(item) => item.id === selectedProduct?.value
)?.marketing_product?.kandang?.label ?? ''
}
color='success'
className={{
badge: 'whitespace-nowrap w-fit font-semibold',
}}
/>
)
} }
isClearable
isError={Boolean(formik.errors.marketing_product_id)}
errorMessage={formik.errors.marketing_product_id}
required
/>
formik.setValues({ {/* Kategori */}
...formik.values, <SelectInputRadio
marketing_product_id: selected.value as number, required
marketing_product: SalesProductToFieldValues(so), label='Kategori '
qty: so.qty, options={MARKETING_TYPE_OPTIONS}
unit_price: so.unit_price, value={formik.values.marketing_type}
total_price: so.total_price, onChange={(val) => {
avg_weight: so.avg_weight, formik.setFieldValue('marketing_type', val);
total_weight: so.total_weight, }}
vehicle_number: so.vehicle_number, isClearable
}); placeholder='Pilih Kategori'
}} isDisabled
startAdornment={ />
selectedProduct && (
<StatusBadge {/* Konversi Satuan Telur */}
text={ {formik.values.marketing_type &&
exisitingValues?.find( formik.values.marketing_type.value.toLowerCase() === 'telur' &&
(item) => item.id === selectedProduct?.value (!formik.values.convertion_unit ||
)?.marketing_product?.kandang?.label ?? '' formik.values.convertion_unit.value.toLowerCase() !== 'peti') && (
} <SelectInputRadio
color='success' required
className={{ label='Tipe Konversi'
badge: 'whitespace-nowrap w-fit font-semibold', options={MARKETING_CONVERTION_UNIT_OPTIONS}
}} value={formik.values.convertion_unit}
onChange={(val) => formik.setFieldValue('convertion_unit', val)}
isClearable
placeholder='Pilih Konversi Satuan'
/> />
) )}
} {formik.values.convertion_unit &&
isClearable formik.values.convertion_unit.value.toLowerCase() === 'peti' && (
isError={Boolean(formik.errors.marketing_product_id)} <div className='flex flex-col'>
errorMessage={formik.errors.marketing_product_id} <label className='font-semibold text-xs py-2 leading-5'>
required Tipe Konversi <span className='text-error'>*</span>
/> </label>
<div className='flex items-center gap-2 border border-base-content/10 rounded-lg pe-3 text-sm text-base-content'>
<div>
<Dropdown
align='start'
direction='bottom'
trigger={
<div className='flex flex-row items-stretch gap-2 py-1 ps-3 text-sm'>
<div className='py-1.5 flex items-center gap-2'>
{formatTitleCase(
formik.values.convertion_unit.value
)}
<Icon
icon='heroicons:chevron-down-solid'
className='my-auto'
/>
</div>
<div className='w-px border-none bg-base-content/10'></div>
</div>
}
className={{
wrapper: 'relative',
content:
'rounded-xl mt-1 border border-base-content/5 shadow-sm overflow-hidden min-w-68.5 sm:min-w-103.25 w-full',
}}
>
<ul className='rounded-lg w-full'>
{MARKETING_CONVERTION_UNIT_OPTIONS.map((option) => (
<li className='w-full' key={option.value}>
<Button
variant='ghost'
color='none'
className='w-full p-3 gap-3 font-medium justify-start text-sm text-base-content/50'
onClick={() =>
formik.setFieldValue('convertion_unit', option)
}
>
<input
type='radio'
checked={
formik.values.convertion_unit?.value ===
option.value
}
onChange={() => null}
className='radio radio-md radio-primary pointer-events-none'
/>{' '}
{option.label}
</Button>
</li>
))}
</ul>
</Dropdown>
</div>
<input
type='number'
className='w-full h-full focus:outline-none appearance-none [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none'
placeholder={`Berat ${
formik.values.convertion_unit?.value === 'peti'
? 'kg'
: ''
} per ${formik.values.convertion_unit?.value}`}
value={formik.values.weight_per_convertion ?? ''}
onChange={(e) => {
formik.setFieldValue(
'weight_per_convertion',
Number(e.target.value)
);
setCurrentInput(e.target.name);
}}
onBlur={() => handleBlurField('weight_per_convertion')}
/>
</div>
</div>
)}
<PatternInput {/* Konversi Satuan Week Pullet */}
name='vehicle_number' {formik.values.marketing_type?.value.toLowerCase() ===
label='No. Polisi' 'ayam_pullet' && (
format='AA #### AAA' <SelectInputRadio
mask='_' required
inputVehicleNumber label='Minggu'
required options={optionsWeek}
type='text' value={
placeholder='B 1234 CDE' formik.values.week?.value
value={formatVechicleNumber(formik.values.vehicle_number ?? '')} ? (formik.values.week as { value: number; label: string })
onChange={formik.handleChange} : null
onBlur={formik.handleBlur} }
isError={Boolean(formik.errors.vehicle_number)} onChange={(val) => {
errorMessage={formik.errors.vehicle_number} formik.setFieldValue('week', val);
/> }}
<NumberInput placeholder='Pilih Week'
required />
label='Kuantitas' )}
name='qty'
value={formik.values.qty} {/* Total Peti */}
onChange={(e) => { {formik.values.convertion_unit?.value.toLowerCase() === 'peti' && (
formik.handleChange(e); <NumberInput
setCurrentInput(e.target.name); required
}} label='Total Peti'
onBlur={() => handleBlurField('qty')} name='total_peti'
isError={Boolean(formik.errors.qty)} value={formik.values.total_peti ?? undefined}
errorMessage={formik.errors.qty} onChange={(e) => {
placeholder='Masukan Kuantitas' formik.handleChange(e);
endAdornment={ setCurrentInput(e.target.name);
<div className='flex items-center gap-2'> }}
<span className='text-sm text-gray-500'> onBlur={() => handleBlurField('total_peti')}
{isResponseSuccess(productData) isError={
? productData?.data?.uom.name formik.touched.total_peti && Boolean(formik.errors.total_peti)
: ''} }
errorMessage={formik.errors.total_peti}
placeholder='Masukan Total Peti'
endAdornment={
<div className='flex items-center gap-2'>
<span className='text-sm text-base-content/50'>Kg</span>
</div>
}
bottomLabel={`1 ${formik.values.convertion_unit?.value.toLowerCase()} = ${formik.values.weight_per_convertion ?? 0} Kg`}
/>
)}
{/* Avg. Bobot */}
{formik.values.marketing_type?.value.toLowerCase() === 'trading' ||
(formik.values.convertion_unit?.value.toLowerCase() !== 'peti' &&
formik.values.convertion_unit?.value.toLowerCase() !== 'kg' && (
<NumberInput
required
label='Avg. Bobot (Kg)'
name='avg_weight'
value={formik.values.avg_weight}
onChange={(e) => {
formik.handleChange(e);
setCurrentInput(e.target.name);
}}
onBlur={() => handleBlurField('avg_weight')}
isError={
formik.touched.avg_weight &&
Boolean(formik.errors.avg_weight)
}
errorMessage={formik.errors.avg_weight}
placeholder='Masukan Bobot Rata-rata'
/>
))}
{/* Total Bobot */}
{formik.values.marketing_type?.value.toLowerCase() !== 'trading' && (
<NumberInput
required
label='Total Bobot (Kg)'
name='total_weight'
value={formik.values.total_weight}
onChange={(e) => {
formik.handleChange(e);
setCurrentInput(e.target.name);
}}
onBlur={() => handleBlurField('total_weight')}
isError={
formik.touched.total_weight &&
Boolean(formik.errors.total_weight)
}
errorMessage={formik.errors.total_weight}
placeholder='Masukan Total Bobot'
/>
)}
{/* Kuantitas */}
<NumberInput
required
label={
formik.values.marketing_type &&
formik.values.marketing_type.value.toLowerCase() === 'telur'
? `Total Butir Telur`
: `Total Kuantitas`
}
name='qty'
value={formik.values.qty}
onChange={(e) => {
formik.handleChange(e);
setCurrentInput(e.target.name);
}}
onBlur={() => handleBlurField('qty')}
isError={Boolean(formik.errors.qty)}
errorMessage={formik.errors.qty}
placeholder='Masukan Kuantitas'
endAdornment={
<div className='flex items-center gap-2'>
<span className='text-sm text-gray-500'>
{isResponseSuccess(productData)
? productData?.data?.uom.name
: ''}
</span>
</div>
}
bottomLabel={
formik.values.marketing_product_id
? 'Stok dijual: ' +
salesOrders?.find(
(item) => item.id === formik.values.marketing_product_id
)?.qty +
' ' +
(isResponseSuccess(productData)
? productData?.data?.uom.name
: '')
: ''
}
/>
{/* Harga per convertion unit (PETI / KG) */}
{(formik.values.convertion_unit?.value.toLowerCase() === 'peti' ||
formik.values.convertion_unit?.value.toLowerCase() === 'kg') && (
<NumberInput
required
label={`Harga / ${formik.values.convertion_unit?.label ?? 'Produk'} (Rp)`}
name='price_per_convertion'
value={formik.values.price_per_convertion ?? undefined}
onChange={(e) => {
formik.handleChange(e);
setCurrentInput(e.target.name);
}}
onBlur={() => handleBlurField('price_per_convertion')}
isError={
formik.touched.price_per_convertion &&
Boolean(formik.errors.price_per_convertion)
}
errorMessage={formik.errors.price_per_convertion}
placeholder='Masukan Harga Satuan'
/>
)}
{/* Harga per butir untuk TELUR + QTY */}
{formik.values.marketing_type?.value.toLowerCase() === 'telur' &&
formik.values.convertion_unit?.value.toLowerCase() === 'qty' && (
<NumberInput
required
label='Harga / Butir (Rp)'
name='price_per_qty'
value={formik.values.price_per_qty ?? undefined}
onChange={(e) => {
formik.setFieldValue('price_per_qty', Number(e.target.value));
setCurrentInput('price_per_qty');
}}
onBlur={() => handleBlurField('price_per_qty')}
isError={
formik.touched.price_per_qty &&
Boolean(formik.errors.price_per_qty)
}
errorMessage={formik.errors.price_per_qty}
placeholder='Masukan Harga per Butir'
/>
)}
{/* Harga Satuan */}
{formik.values.convertion_unit?.value.toLowerCase() !== 'peti' &&
formik.values.convertion_unit?.value.toLowerCase() !== 'kg' && (
<NumberInput
required
label={`Harga / ${isResponseSuccess(productData) ? productData?.data?.uom?.name : 'Produk'} (Rp)`}
name='unit_price'
value={formik.values.unit_price}
onChange={(e) => {
formik.handleChange(e);
setCurrentInput(e.target.name);
}}
onBlur={() => handleBlurField('unit_price')}
isError={Boolean(formik.errors.unit_price)}
errorMessage={formik.errors.unit_price}
placeholder='Masukan Harga Satuan'
/>
)}
{/* Sisa kg diluar peti */}
{formik.values.convertion_unit?.value.toLowerCase() === 'peti' && (
<div className='flex flex-col'>
<div className='py-2 gap-3 flex items-center'>
<input
type='checkbox'
name='sisa_berat_toggle'
checked={hasSisaBerat}
onChange={() => handleSisaBeratToggle(!hasSisaBerat)}
className='toggle toggle-primary rounded-full before:rounded-full before:bg-base-content/50 border-base-content/50 checked:border-primary checked:bg-primary checked:before:bg-base-100'
/>
<label className='text-sm text-base-content/50'>
Apakah ada sisa berat di luar peti?
</label>
</div>
<span className='text-xs text-base-content/30 leading-4 pt-1.5'>
Jika ada, masukan berat di luar peti
</span> </span>
</div> </div>
} )}
bottomLabel={
formik.values.marketing_product_id
? 'Stok dijual: ' +
salesOrders?.find(
(item) => item.id === formik.values.marketing_product_id
)?.qty +
' ' +
(isResponseSuccess(productData)
? productData?.data?.uom.name
: '')
: ''
}
/>
<NumberInput
required
label={`Harga / ${isResponseSuccess(productData) ? productData?.data?.uom?.name : 'Produk'} (Rp)`}
name='unit_price'
value={formik.values.unit_price}
onChange={(e) => {
formik.handleChange(e);
setCurrentInput(e.target.name);
}}
onBlur={() => handleBlurField('unit_price')}
isError={Boolean(formik.errors.unit_price)}
errorMessage={formik.errors.unit_price}
placeholder='Masukan Harga Satuan'
/>
<NumberInput
required
label='Avg. Bobot (Kg)'
name='avg_weight'
value={formik.values.avg_weight}
onChange={(e) => {
formik.handleChange(e);
setCurrentInput(e.target.name);
}}
onBlur={() => handleBlurField('avg_weight')}
isError={Boolean(formik.errors.avg_weight)}
errorMessage={formik.errors.avg_weight}
placeholder='Masukan Bobot Rata-rata'
/>
<NumberInput
required
label='Total Bobot (Kg)'
name='total_weight'
value={formik.values.total_weight}
onChange={(e) => {
formik.handleChange(e);
setCurrentInput(e.target.name);
}}
onBlur={() => handleBlurField('total_weight')}
isError={Boolean(formik.errors.total_weight)}
errorMessage={formik.errors.total_weight}
placeholder='Masukan Total Bobot'
/>
<NumberInput {hasSisaBerat && (
required <>
label='Total Penjualan (Rp)' <NumberInput
name='total_price' required
value={formik.values.total_price} label='Sisa Berat (Kg)'
onChange={(e) => { name='sisa_berat'
formik.handleChange(e); value={formik.values.sisa_berat ?? undefined}
setCurrentInput(e.target.name); onChange={(e) => {
}} formik.handleChange(e);
onBlur={() => handleBlurField('total_price')} setCurrentInput(e.target.name);
isError={Boolean(formik.errors.total_price)} }}
errorMessage={formik.errors.total_price} onBlur={() => handleBlurField('sisa_berat')}
placeholder='Masukan Total Penjualan' isError={
/> formik.touched.sisa_berat && Boolean(formik.errors.sisa_berat)
}
errorMessage={formik.errors.sisa_berat}
placeholder='Masukan Sisa Berat'
/>
<NumberInput
required
label='Harga Sisa Berat (Rp)'
name='price_sisa_berat'
value={formik.values.price_sisa_berat ?? undefined}
onChange={(e) => {
formik.handleChange(e);
setCurrentInput(e.target.name);
}}
onBlur={() => handleBlurField('price_sisa_berat')}
isError={
formik.touched.price_sisa_berat &&
Boolean(formik.errors.price_sisa_berat)
}
errorMessage={formik.errors.price_sisa_berat}
placeholder='Masukan Harga Sisa Berat'
/>
</>
)}
<AlertErrorList {/* Total Penjualan */}
className={{ <NumberInput
alert: 'w-full my-4', required
}} label='Total Penjualan (Rp)'
formErrorList={formErrorList} name='total_price'
onClose={close} value={formik.values.total_price}
/> onChange={(e) => {
formik.handleChange(e);
setCurrentInput(e.target.name);
}}
onBlur={() => handleBlurField('total_price')}
isError={
formik.touched.total_price && Boolean(formik.errors.total_price)
}
errorMessage={formik.errors.total_price}
placeholder='Masukan Total Penjualan'
/>
<AlertErrorList
className={{
alert: 'w-full my-4',
}}
formErrorList={formErrorList}
onClose={close}
/>
</div>
<div className='h-18' /> <div className='h-18' />
<div className='absolute sm:w-full bottom-0 right-0'> <div className='absolute sm:w-full bottom-0 right-0 p-4'>
<Button <Button
type='submit' type='submit'
isLoading={formik.isSubmitting} isLoading={formik.isSubmitting}
@@ -1,3 +1,4 @@
import { ProductWarehouse } from '@/types/api/inventory/product-warehouse';
import * as Yup from 'yup'; import * as Yup from 'yup';
type SalesOrderProductSchemaType = { type SalesOrderProductSchemaType = {
@@ -11,6 +12,7 @@ type SalesOrderProductSchemaType = {
value: number; value: number;
label: string; label: string;
} | null; } | null;
product_warehouse_data?: ProductWarehouse | null | undefined;
product_warehouse_id?: number; product_warehouse_id?: number;
unit_price: string | number | undefined; unit_price: string | number | undefined;
total_weight: string | number | undefined; total_weight: string | number | undefined;
@@ -19,6 +21,29 @@ type SalesOrderProductSchemaType = {
total_price: string | number | undefined; total_price: string | number | undefined;
vehicle_number?: string | undefined; vehicle_number?: string | undefined;
uom?: string | null | undefined; uom?: string | null | undefined;
convertion_unit?: {
value: string;
label: string;
} | null;
weight_per_convertion?: number | null | undefined;
price_per_convertion?: number | null | undefined;
marketing_type?: {
value: string;
label: string;
} | null;
total_peti?: number | null | undefined;
sisa_berat?: number | null | undefined;
price_sisa_berat?: number | null | undefined;
/** Harga per butir telur untuk TELUR + QTY */
price_per_qty?: number | null | undefined;
/** Week untuk ayam pullet */
week?:
| {
value?: number;
label?: string;
}
| null
| undefined;
}; };
export const SalesOrderProductSchema: Yup.ObjectSchema<SalesOrderProductSchemaType> = export const SalesOrderProductSchema: Yup.ObjectSchema<SalesOrderProductSchemaType> =
@@ -40,6 +65,10 @@ export const SalesOrderProductSchema: Yup.ObjectSchema<SalesOrderProductSchemaTy
.required('Produk wajib diisi!'), .required('Produk wajib diisi!'),
label: Yup.string().required('Produk wajib diisi!'), label: Yup.string().required('Produk wajib diisi!'),
}).nullable(), }).nullable(),
product_warehouse_data: Yup.mixed<ProductWarehouse>()
.nullable()
.optional()
.notRequired(),
product_warehouse_id: Yup.number() product_warehouse_id: Yup.number()
.min(1, 'Produk wajib diisi!') .min(1, 'Produk wajib diisi!')
.required('Produk wajib diisi!'), .required('Produk wajib diisi!'),
@@ -59,6 +88,42 @@ export const SalesOrderProductSchema: Yup.ObjectSchema<SalesOrderProductSchemaTy
.min(1, 'Total Penjualan wajib diisi!') .min(1, 'Total Penjualan wajib diisi!')
.required('Total Penjualan wajib diisi!'), .required('Total Penjualan wajib diisi!'),
uom: Yup.string().nullable().optional().notRequired(), uom: Yup.string().nullable().optional().notRequired(),
convertion_unit: Yup.object({
value: Yup.string().required('Konversi Satuan wajib diisi!'),
label: Yup.string().required('Konversi Satuan wajib diisi!'),
}).nullable(),
weight_per_convertion: Yup.number().nullable().optional().notRequired(),
marketing_type: Yup.object({
value: Yup.string().required('Kategori Penjualan wajib diisi!'),
label: Yup.string().required('Kategori Penjualan wajib diisi!'),
}).nullable(),
price_per_convertion: Yup.number().nullable().optional().notRequired(),
total_peti: Yup.number().nullable().optional().notRequired(),
sisa_berat: Yup.number().nullable().optional().notRequired(),
price_sisa_berat: Yup.number().nullable().optional().notRequired(),
price_per_qty: Yup.number().nullable().optional().notRequired(),
week: Yup.object({
value: Yup.number(),
label: Yup.string(),
})
.nullable()
.default(null)
.when('marketing_type', {
is: (marketingType: { value: string } | null | undefined) =>
marketingType?.value?.toLowerCase() === 'ayam_pullet',
then: (schema) =>
schema
.shape({
value: Yup.number().required(
'Week wajib diisi untuk Ayam Pullet!'
),
label: Yup.string().required(
'Week wajib diisi untuk Ayam Pullet!'
),
})
.required('Week wajib diisi untuk Ayam Pullet!'),
otherwise: (schema) => schema.optional().notRequired(),
}),
}); });
export type SalesOrderProductFormValues = Yup.InferType< export type SalesOrderProductFormValues = Yup.InferType<
@@ -5,7 +5,7 @@ import {
SalesOrderProductFormValues, SalesOrderProductFormValues,
SalesOrderProductSchema, SalesOrderProductSchema,
} from '@/components/pages/marketing/form/repeater/sales-order/SalesOrderProduct.schema'; } from '@/components/pages/marketing/form/repeater/sales-order/SalesOrderProduct.schema';
import { RefObject, useMemo, useState } from 'react'; import { RefObject, useEffect, useMemo, useState } from 'react';
import { OptionType, useSelect } from '@/components/input/SelectInput'; import { OptionType, useSelect } from '@/components/input/SelectInput';
import { Kandang } from '@/types/api/master-data/kandang'; import { Kandang } from '@/types/api/master-data/kandang';
import { WarehouseApi } from '@/services/api/master-data'; import { WarehouseApi } from '@/services/api/master-data';
@@ -14,15 +14,23 @@ import { ProductWarehouseApi } from '@/services/api/inventory';
import NumberInput from '@/components/input/NumberInput'; import NumberInput from '@/components/input/NumberInput';
import Button from '@/components/Button'; import Button from '@/components/Button';
import { isResponseSuccess } from '@/lib/api-helper'; import { isResponseSuccess } from '@/lib/api-helper';
import { formatNumber, formatVechicleNumber } from '@/lib/helper'; import {
formatNumber,
formatTitleCase,
formatVechicleNumber,
} from '@/lib/helper';
import PatternInput from '@/components/input/PatternInput'; import PatternInput from '@/components/input/PatternInput';
import Alert from '@/components/Alert'; import Alert from '@/components/Alert';
import AlertErrorList from '@/components/helper/form/FormErrors'; import AlertErrorList from '@/components/helper/form/FormErrors';
import { useFormikErrorList } from '@/services/hooks/useFormikErrorList'; import { useFormikErrorList } from '@/services/hooks/useFormikErrorList';
import SelectInputRadio from '@/components/input/SelectInputRadio'; import SelectInputRadio from '@/components/input/SelectInputRadio';
import {
const roundWeight = (value: number) => Number(value.toFixed(2)); MARKETING_CONVERTION_UNIT_OPTIONS,
const roundPrice = (value: number) => Math.round(value); MARKETING_TYPE_OPTIONS,
} from '@/config/constant';
import { Icon } from '@iconify/react';
import Dropdown from '@/components/Dropdown';
import { handleMarketingCalculation } from '@/lib/marketing-calculation';
const SalesOrderProductForm = ({ const SalesOrderProductForm = ({
initialValues, initialValues,
@@ -42,6 +50,35 @@ const SalesOrderProductForm = ({
const [selectedProductWarehouse, setSelectedProductWarehouse] = const [selectedProductWarehouse, setSelectedProductWarehouse] =
useState<ProductWarehouse | null>(null); useState<ProductWarehouse | null>(null);
// Check jika ada sisa berat = total_weight - (weight_per_convertion * total_peti)
const initialSisaBerat =
initialValues?.total_weight &&
initialValues?.weight_per_convertion &&
initialValues?.total_peti
? Number(initialValues.total_weight) -
Number(initialValues.weight_per_convertion) *
Number(initialValues.total_peti)
: 0;
const initialPricePerConvertion =
initialValues?.total_price &&
initialValues?.total_peti &&
Number(initialValues.total_peti) !== 0
? (Number(initialValues.total_price) -
initialSisaBerat * Number(initialValues.unit_price || 0)) /
Number(initialValues.total_peti)
: 0;
const initialPriceSisaBerat =
initialValues?.total_price && initialValues?.total_peti
? Number(initialValues.total_price) -
initialPricePerConvertion * Number(initialValues.total_peti)
: 0;
const [hasSisaBerat, setHasSisaBerat] = useState<boolean>(
initialSisaBerat > 0
);
// ============ Formik ============ // ============ Formik ============
const formik = useFormik<SalesOrderProductFormValues>({ const formik = useFormik<SalesOrderProductFormValues>({
enableReinitialize: true, enableReinitialize: true,
@@ -57,6 +94,18 @@ const SalesOrderProductForm = ({
avg_weight: initialValues?.avg_weight || '', avg_weight: initialValues?.avg_weight || '',
total_price: initialValues?.total_price || '', total_price: initialValues?.total_price || '',
uom: initialValues?.uom || '', uom: initialValues?.uom || '',
weight_per_convertion:
initialValues?.weight_per_convertion != null
? Number(initialValues.weight_per_convertion)
: null,
price_per_convertion: initialPricePerConvertion,
convertion_unit: initialValues?.convertion_unit || null,
marketing_type: initialValues?.marketing_type || null,
total_peti: initialValues?.total_peti ?? null,
price_per_qty: initialValues?.price_per_qty ?? null,
sisa_berat: initialSisaBerat,
price_sisa_berat: initialPriceSisaBerat,
week: initialValues?.week ?? null,
}, },
validationSchema: SalesOrderProductSchema, validationSchema: SalesOrderProductSchema,
onSubmit: async (values) => { onSubmit: async (values) => {
@@ -76,6 +125,14 @@ const SalesOrderProductForm = ({
loadMore: loadMoreKandang, loadMore: loadMoreKandang,
} = useSelect<Kandang>(WarehouseApi.basePath, 'id', 'name'); } = useSelect<Kandang>(WarehouseApi.basePath, 'id', 'name');
// Options Week dari minggu 1 - 22
const optionsWeek = useMemo(() => {
return Array.from({ length: 22 }, (_, i) => ({
value: i + 1,
label: `Week ${i + 1}`,
}));
}, []);
const { const {
options: warehouseSourceOptions, options: warehouseSourceOptions,
rawData: warehouseSourceRawData, rawData: warehouseSourceRawData,
@@ -89,6 +146,7 @@ const SalesOrderProductForm = ({
'', '',
{ {
warehouse_id: formik.values.kandang_id?.toString() ?? '', warehouse_id: formik.values.kandang_id?.toString() ?? '',
type: formik.values.marketing_type?.value.toLocaleUpperCase() ?? '',
} }
); );
@@ -121,14 +179,18 @@ const SalesOrderProductForm = ({
); );
setSelectedProductWarehouse(productWarehouse || null); setSelectedProductWarehouse(productWarehouse || null);
formik.setFieldValue('qty', productWarehouse?.quantity); formik.setFieldValue('qty', productWarehouse?.quantity);
formik.setFieldValue('uom', productWarehouse?.product?.uom?.name || '');
handleBlurField('qty'); handleBlurField('qty');
} else { } else {
formik.setFieldValue('qty', ''); formik.setFieldValue('qty', '');
formik.setFieldValue('uom', '');
} }
}; };
const handleResetForm = () => { const handleResetForm = () => {
setFormErrorMessage(''); setFormErrorMessage('');
setHasSisaBerat(false);
setSelectedProductWarehouse(null);
formik.resetForm({ formik.resetForm({
values: { values: {
vehicle_number: '', vehicle_number: '',
@@ -141,6 +203,16 @@ const SalesOrderProductForm = ({
qty: '', qty: '',
avg_weight: '', avg_weight: '',
total_price: '', total_price: '',
total_peti: null,
price_per_qty: null,
price_sisa_berat: null,
sisa_berat: null,
convertion_unit: null,
marketing_type: null,
weight_per_convertion: null,
price_per_convertion: null,
uom: '',
week: null,
}, },
}); });
}; };
@@ -148,113 +220,33 @@ const SalesOrderProductForm = ({
const handleBlurField = (field: string) => { const handleBlurField = (field: string) => {
setCurrentInput(field); setCurrentInput(field);
const qty = Number(formik.values.qty || 0); handleMarketingCalculation(field, {
const avgWeight = Number(formik.values.avg_weight || 0); values: formik.values,
const totalWeight = Number(formik.values.total_weight || 0); setFieldValue: formik.setFieldValue,
const unitPrice = Number(formik.values.unit_price || 0); hasSisaBerat,
const totalPrice = Number(formik.values.total_price || 0); });
};
if (qty <= 0) return; // Handler khusus untuk toggle sisa berat - langsung pakai nilai baru
const handleSisaBeratToggle = (newHasSisaBerat: boolean) => {
setHasSisaBerat(newHasSisaBerat);
// Cek apakah produk memiliki flag OVK atau PAKAN if (!newHasSisaBerat) {
const productFlags = selectedProductWarehouse?.product?.flags || []; // Ketika OFF - set nilai ke 0 dan recalculate tanpa sisa
const isOvkOrPakan = formik.setFieldValue('sisa_berat', 0);
productFlags.includes('OVK') || productFlags.includes('PAKAN'); formik.setFieldValue('price_sisa_berat', 0);
switch (field) {
// ===== SOURCE FIELDS =====
case 'qty': {
if (avgWeight > 0) {
const tw = roundWeight(qty * avgWeight);
formik.setFieldValue('total_weight', tw);
// Hitung 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 * tw));
}
}
}
break;
}
case 'avg_weight': {
if (avgWeight > 0) {
const tw = roundWeight(qty * avgWeight);
formik.setFieldValue('total_weight', tw);
// Hitung 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 * tw));
}
}
}
break;
}
case 'unit_price': {
if (unitPrice > 0) {
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;
}
// ===== TOTAL EDITABLE =====
case 'total_weight': {
if (totalWeight > 0) {
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;
}
case 'total_price': {
if (totalPrice > 0) {
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;
}
} }
// Langsung trigger recalculation dengan hasSisaBerat yang baru
handleMarketingCalculation('total_peti', {
values: {
...formik.values,
sisa_berat: newHasSisaBerat ? formik.values.sisa_berat : 0,
price_sisa_berat: newHasSisaBerat ? formik.values.price_sisa_berat : 0,
},
setFieldValue: formik.setFieldValue,
hasSisaBerat: newHasSisaBerat,
});
}; };
// ===== Formik Error List ===== // ===== Formik Error List =====
@@ -272,6 +264,10 @@ const SalesOrderProductForm = ({
} }
); );
useEffect(() => {
handleBlurField('week');
}, [formik.values.week]);
return ( return (
<> <>
<form <form
@@ -279,174 +275,476 @@ const SalesOrderProductForm = ({
onSubmit={handleFormSubmit} onSubmit={handleFormSubmit}
onReset={handleResetForm} onReset={handleResetForm}
> >
{formErrorMessage && ( <div className='flex flex-col gap-1.5 p-4 border-b border-base-content/10'>
<div onClick={() => setFormErrorMessage('')} className='my-3 w-full'> {formErrorMessage && (
<Alert color='error'> <div
{formErrorMessage ? formErrorMessage : ''} onClick={() => setFormErrorMessage('')}
</Alert> className='my-3 w-full'
</div> >
)} <Alert color='error'>
<PatternInput {formErrorMessage ? formErrorMessage : ''}
name='vehicle_number' </Alert>
label='No. Polisi' </div>
format='AA #### AAA' )}
mask='_' {/* Nomor Polisi */}
inputVehicleNumber <PatternInput
required name='vehicle_number'
type='text' label='No. Polisi'
placeholder='B 1234 CDE' format='AA #### AAA'
value={formatVechicleNumber(formik.values.vehicle_number ?? '')} mask='_'
onChange={formik.handleChange} inputVehicleNumber
onBlur={formik.handleBlur} required
isError={ type='text'
formik.touched.vehicle_number && placeholder='B 1234 CDE'
Boolean(formik.errors.vehicle_number) value={formatVechicleNumber(formik.values.vehicle_number ?? '')}
} onChange={formik.handleChange}
errorMessage={formik.errors.vehicle_number} onBlur={formik.handleBlur}
/> isError={
<SelectInputRadio formik.touched.vehicle_number &&
required Boolean(formik.errors.vehicle_number)
label='Kandang' }
options={kandangSourceOptions} errorMessage={formik.errors.vehicle_number}
isLoading={isLoadingKandangSourceOptions} />
value={formik.values.kandang}
onChange={kandangChangeHandler} {/* Gudang */}
isClearable <SelectInputRadio
onInputChange={setKandangInputValue} required
onMenuScrollToBottom={loadMoreKandang} label='Gudang'
isError={ options={kandangSourceOptions}
formik.touched.kandang_id && Boolean(formik.errors.kandang_id) isLoading={isLoadingKandangSourceOptions}
} value={formik.values.kandang}
errorMessage={formik.errors.kandang_id} onChange={kandangChangeHandler}
placeholder='Pilih Kandang' isClearable
/> onInputChange={setKandangInputValue}
<SelectInputRadio onMenuScrollToBottom={loadMoreKandang}
required isError={
label='Produk' formik.touched.kandang_id && Boolean(formik.errors.kandang_id)
options={productOptionsFiltered} }
isLoading={isLoadingWarehouseSourceOptions} errorMessage={formik.errors.kandang_id}
value={formik.values.product_warehouse} placeholder='Pilih Gudang'
onChange={warehouseChangeHandler} />
onInputChange={setWarehouseInputValue}
onMenuScrollToBottom={loadMoreWarehouse} {/* Kategori */}
isClearable <SelectInputRadio
placeholder={ required
formik.values.kandang_id label='Kategori '
? productOptionsFiltered.length == 0 options={MARKETING_TYPE_OPTIONS}
? 'Tidak ada produk yang tersedia' value={formik.values.marketing_type}
: 'Pilih produk' onChange={(val) => {
: 'Pilih Kandang Terlebih Dahulu' formik.setFieldValue('marketing_type', val);
} warehouseChangeHandler(null);
isDisabled={!formik.values.kandang_id} formik.setFieldValue('product_warehouse', null);
isError={ formik.setFieldValue('product_warehouse_id', null);
formik.touched.product_warehouse_id && formik.setFieldValue('convertion_unit', null);
Boolean(formik.errors.product_warehouse_id) formik.setFieldValue('weight_per_convertion', null);
} formik.setFieldValue('total_peti', null);
errorMessage={formik.errors.product_warehouse_id} }}
/> isClearable
<NumberInput placeholder='Pilih Kategori'
required />
label='Kuantitas'
name='qty' {/* Produk */}
value={formik.values.qty} <SelectInputRadio
onChange={(e) => { required
formik.handleChange(e); label='Produk'
setCurrentInput(e.target.name); options={productOptionsFiltered}
}} isLoading={isLoadingWarehouseSourceOptions}
onBlur={() => handleBlurField('qty')} value={formik.values.product_warehouse}
isError={formik.touched.qty && Boolean(formik.errors.qty)} onChange={warehouseChangeHandler}
errorMessage={formik.errors.qty} onInputChange={setWarehouseInputValue}
placeholder='Masukan Kuantitas' onMenuScrollToBottom={loadMoreWarehouse}
endAdornment={ isClearable
<div className='flex items-center gap-2'> placeholder={
<span className='text-sm text-gray-500'> formik.values.kandang_id
{selectedProductWarehouse?.product?.uom?.name} ? productOptionsFiltered.length == 0
? 'Tidak ada produk yang tersedia'
: 'Pilih produk'
: 'Pilih Kandang Terlebih Dahulu'
}
isDisabled={!formik.values.kandang_id}
isError={
formik.touched.product_warehouse_id &&
Boolean(formik.errors.product_warehouse_id)
}
errorMessage={formik.errors.product_warehouse_id}
/>
{/* Konversi Satuan Telur */}
{formik.values.marketing_type &&
formik.values.marketing_type.value.toLowerCase() === 'telur' &&
(!formik.values.convertion_unit ||
formik.values.convertion_unit.value.toLowerCase() !== 'peti') && (
<SelectInputRadio
required
label='Tipe Konversi'
options={MARKETING_CONVERTION_UNIT_OPTIONS}
value={formik.values.convertion_unit}
onChange={(val) => formik.setFieldValue('convertion_unit', val)}
isClearable
placeholder='Pilih Konversi Satuan'
/>
)}
{formik.values.convertion_unit &&
formik.values.convertion_unit.value.toLowerCase() === 'peti' && (
<div className='flex flex-col'>
<label className='font-semibold text-xs py-2 leading-5'>
Tipe Konversi <span className='text-error'>*</span>
</label>
<div className='flex items-center gap-2 border border-base-content/10 rounded-lg pe-3 text-sm text-base-content'>
<div>
<Dropdown
align='start'
direction='bottom'
trigger={
<div className='flex flex-row items-stretch gap-2 py-1 ps-3 text-sm'>
<div className='py-1.5 flex items-center gap-2'>
{formatTitleCase(
formik.values.convertion_unit.value
)}
<Icon
icon='heroicons:chevron-down-solid'
className='my-auto'
/>
</div>
<div className='w-px border-none bg-base-content/10'></div>
</div>
}
className={{
wrapper: 'relative',
content:
'rounded-xl mt-1 border border-base-content/5 shadow-sm overflow-hidden min-w-68.5 sm:min-w-103.25 w-full',
}}
>
<ul className='rounded-lg w-full'>
{MARKETING_CONVERTION_UNIT_OPTIONS.map((option) => (
<li className='w-full' key={option.value}>
<Button
variant='ghost'
color='none'
className='w-full p-3 gap-3 font-medium justify-start text-sm text-base-content/50'
onClick={() =>
formik.setFieldValue('convertion_unit', option)
}
>
<input
type='radio'
checked={
formik.values.convertion_unit?.value ===
option.value
}
onChange={() => null}
className='radio radio-md radio-primary pointer-events-none'
/>{' '}
{option.label}
</Button>
</li>
))}
</ul>
</Dropdown>
</div>
<input
type='number'
className='w-full h-full focus:outline-none appearance-none [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none'
placeholder={`Berat ${
formik.values.convertion_unit?.value === 'peti'
? 'kg'
: ''
} per ${formik.values.convertion_unit?.value}`}
value={formik.values.weight_per_convertion ?? ''}
onChange={(e) => {
formik.setFieldValue(
'weight_per_convertion',
Number(e.target.value)
);
setCurrentInput(e.target.name);
}}
onBlur={() => handleBlurField('weight_per_convertion')}
/>
</div>
</div>
)}
{/* Konversi Satuan Week Pullet */}
{formik.values.marketing_type?.value.toLowerCase() ===
'ayam_pullet' && (
<SelectInputRadio
required
label='Minggu'
options={optionsWeek}
value={
formik.values.week?.value
? (formik.values.week as { value: number; label: string })
: null
}
onChange={(val) => {
formik.setFieldValue('week', val);
}}
placeholder='Pilih Week'
/>
)}
{/* Total Peti */}
{formik.values.convertion_unit?.value.toLowerCase() === 'peti' && (
<NumberInput
required
label='Total Peti'
name='total_peti'
value={formik.values.total_peti ?? undefined}
onChange={(e) => {
formik.handleChange(e);
setCurrentInput(e.target.name);
}}
onBlur={() => handleBlurField('total_peti')}
isError={
formik.touched.total_peti && Boolean(formik.errors.total_peti)
}
errorMessage={formik.errors.total_peti}
placeholder='Masukan Total Peti'
endAdornment={
<div className='flex items-center gap-2'>
<span className='text-sm text-base-content/50'>Kg</span>
</div>
}
bottomLabel={`1 ${formik.values.convertion_unit?.value.toLowerCase()} = ${formik.values.weight_per_convertion ?? 0} Kg`}
/>
)}
{/* Avg. Bobot */}
{formik.values.marketing_type?.value.toLowerCase() === 'trading' ||
(formik.values.convertion_unit?.value.toLowerCase() !== 'peti' &&
formik.values.convertion_unit?.value.toLowerCase() !== 'kg' && (
<NumberInput
required
label='Avg. Bobot (Kg)'
name='avg_weight'
value={formik.values.avg_weight}
onChange={(e) => {
formik.handleChange(e);
setCurrentInput(e.target.name);
}}
onBlur={() => handleBlurField('avg_weight')}
isError={
formik.touched.avg_weight &&
Boolean(formik.errors.avg_weight)
}
errorMessage={formik.errors.avg_weight}
placeholder='Masukan Bobot Rata-rata'
/>
))}
{/* Total Bobot */}
{formik.values.marketing_type?.value.toLowerCase() !== 'trading' && (
<NumberInput
required
label='Total Bobot (Kg)'
name='total_weight'
value={formik.values.total_weight}
onChange={(e) => {
formik.handleChange(e);
setCurrentInput(e.target.name);
}}
onBlur={() => handleBlurField('total_weight')}
isError={
formik.touched.total_weight &&
Boolean(formik.errors.total_weight)
}
errorMessage={formik.errors.total_weight}
placeholder='Masukan Total Bobot'
/>
)}
{/* Kuantitas */}
<NumberInput
required
label={
formik.values.marketing_type &&
formik.values.marketing_type.value.toLowerCase() === 'telur'
? `Total Butir Telur`
: `Total Kuantitas`
}
name='qty'
value={formik.values.qty}
onChange={(e) => {
formik.handleChange(e);
setCurrentInput(e.target.name);
}}
onBlur={() => handleBlurField('qty')}
isError={formik.touched.qty && Boolean(formik.errors.qty)}
errorMessage={formik.errors.qty}
placeholder='Masukan Kuantitas'
endAdornment={
formik.values.uom ? (
<div className='flex items-center gap-2'>
<span className='text-sm text-base-content/50'>
{formik.values.uom}
</span>
</div>
) : undefined
}
bottomLabel={
isResponseSuccess(warehouseSourceRawData) &&
formik.values.product_warehouse_id
? `Stok tersedia: ${formatNumber(
warehouseSourceRawData?.data?.find(
(item) => item.id === formik.values.product_warehouse_id
)?.quantity ?? 0
)} ${formik.values.uom}`
: ''
}
/>
{/* Harga per convertion unit (PETI / KG) */}
{(formik.values.convertion_unit?.value.toLowerCase() === 'peti' ||
formik.values.convertion_unit?.value.toLowerCase() === 'kg') && (
<NumberInput
required
label={`Harga / ${formik.values.convertion_unit?.label ?? 'Produk'} (Rp)`}
name='price_per_convertion'
value={formik.values.price_per_convertion ?? undefined}
onChange={(e) => {
formik.handleChange(e);
setCurrentInput(e.target.name);
}}
onBlur={() => handleBlurField('price_per_convertion')}
isError={
formik.touched.price_per_convertion &&
Boolean(formik.errors.price_per_convertion)
}
errorMessage={formik.errors.price_per_convertion}
placeholder='Masukan Harga Satuan'
/>
)}
{/* Harga per butir untuk TELUR + QTY */}
{formik.values.marketing_type?.value.toLowerCase() === 'telur' &&
formik.values.convertion_unit?.value.toLowerCase() === 'qty' && (
<NumberInput
required
label='Harga / Butir (Rp)'
name='price_per_qty'
value={formik.values.price_per_qty ?? undefined}
onChange={(e) => {
formik.setFieldValue('price_per_qty', Number(e.target.value));
setCurrentInput('price_per_qty');
}}
onBlur={() => handleBlurField('price_per_qty')}
isError={
formik.touched.price_per_qty &&
Boolean(formik.errors.price_per_qty)
}
errorMessage={formik.errors.price_per_qty}
placeholder='Masukan Harga per Butir'
/>
)}
{/* Harga Satuan per Uom Produk Warehouse */}
{formik.values.convertion_unit?.value.toLowerCase() !== 'peti' &&
formik.values.convertion_unit?.value.toLowerCase() !== 'kg' && (
<NumberInput
required
label={`Harga / ${formik.values.convertion_unit?.label !== 'qty' ? 'Kg' : (selectedProductWarehouse?.product?.uom?.name ?? 'Produk')} (Rp)`}
name='unit_price'
value={formik.values.unit_price}
onChange={(e) => {
formik.handleChange(e);
setCurrentInput(e.target.name);
}}
onBlur={() => handleBlurField('unit_price')}
isError={
formik.touched.unit_price && Boolean(formik.errors.unit_price)
}
errorMessage={formik.errors.unit_price}
placeholder='Masukan Harga Satuan'
/>
)}
{/* Sisa kg diluar peti */}
{formik.values.convertion_unit?.value.toLowerCase() === 'peti' && (
<div className='flex flex-col'>
<div className='py-2 gap-3 flex items-center'>
<input
type='checkbox'
name='sisa_berat_toggle'
checked={hasSisaBerat}
onChange={() => handleSisaBeratToggle(!hasSisaBerat)}
className='toggle toggle-primary rounded-full before:rounded-full before:bg-base-content/50 border-base-content/50 checked:border-primary checked:bg-primary checked:before:bg-base-100'
/>
<label className='text-sm text-base-content/50'>
Apakah ada sisa berat di luar peti?
</label>
</div>
<span className='text-xs text-base-content/30 leading-4 pt-1.5'>
Jika ada, masukan berat di luar peti
</span> </span>
</div> </div>
} )}
bottomLabel={
isResponseSuccess(warehouseSourceRawData) &&
formik.values.product_warehouse_id
? `Stok tersedia: ${formatNumber(
warehouseSourceRawData?.data?.find(
(item) => item.id === formik.values.product_warehouse_id
)?.quantity ?? 0
)} ${selectedProductWarehouse?.product?.uom?.name}`
: ''
}
/>
<NumberInput
required
label={`Harga / ${selectedProductWarehouse?.product?.uom?.name ?? 'Produk'} (Rp)`}
name='unit_price'
value={formik.values.unit_price}
onChange={(e) => {
formik.handleChange(e);
setCurrentInput(e.target.name);
}}
onBlur={() => handleBlurField('unit_price')}
isError={
formik.touched.unit_price && Boolean(formik.errors.unit_price)
}
errorMessage={formik.errors.unit_price}
placeholder='Masukan Harga Satuan'
/>
<NumberInput
required
label='Avg. Bobot (Kg)'
name='avg_weight'
value={formik.values.avg_weight}
onChange={(e) => {
formik.handleChange(e);
setCurrentInput(e.target.name);
}}
onBlur={() => handleBlurField('avg_weight')}
isError={
formik.touched.avg_weight && Boolean(formik.errors.avg_weight)
}
errorMessage={formik.errors.avg_weight}
placeholder='Masukan Bobot Rata-rata'
/>
<NumberInput
required
label='Total Bobot (Kg)'
name='total_weight'
value={formik.values.total_weight}
onChange={(e) => {
formik.handleChange(e);
setCurrentInput(e.target.name);
}}
onBlur={() => handleBlurField('total_weight')}
isError={
formik.touched.total_weight && Boolean(formik.errors.total_weight)
}
errorMessage={formik.errors.total_weight}
placeholder='Masukan Total Bobot'
/>
<NumberInput
required
label='Total Penjualan (Rp)'
name='total_price'
value={formik.values.total_price}
onChange={(e) => {
formik.handleChange(e);
setCurrentInput(e.target.name);
}}
onBlur={() => handleBlurField('total_price')}
isError={
formik.touched.total_price && Boolean(formik.errors.total_price)
}
errorMessage={formik.errors.total_price}
placeholder='Masukan Total Penjualan'
/>
<div className='mt-4'> {hasSisaBerat && (
<AlertErrorList formErrorList={formErrorList} onClose={close} /> <>
<NumberInput
required
label='Sisa Berat (Kg)'
name='sisa_berat'
value={formik.values.sisa_berat ?? undefined}
onChange={(e) => {
formik.handleChange(e);
setCurrentInput(e.target.name);
}}
onBlur={() => handleBlurField('sisa_berat')}
isError={
formik.touched.sisa_berat && Boolean(formik.errors.sisa_berat)
}
errorMessage={formik.errors.sisa_berat}
placeholder='Masukan Sisa Berat'
/>
<NumberInput
required
label='Harga Sisa Berat (Rp)'
name='price_sisa_berat'
value={formik.values.price_sisa_berat ?? undefined}
onChange={(e) => {
formik.handleChange(e);
setCurrentInput(e.target.name);
}}
onBlur={() => handleBlurField('price_sisa_berat')}
isError={
formik.touched.price_sisa_berat &&
Boolean(formik.errors.price_sisa_berat)
}
errorMessage={formik.errors.price_sisa_berat}
placeholder='Masukan Harga Sisa Berat'
/>
</>
)}
{/* Total Penjualan */}
<NumberInput
required
label='Total Penjualan (Rp)'
name='total_price'
value={formik.values.total_price}
onChange={(e) => {
formik.handleChange(e);
setCurrentInput(e.target.name);
}}
onBlur={() => handleBlurField('total_price')}
isError={
formik.touched.total_price && Boolean(formik.errors.total_price)
}
errorMessage={formik.errors.total_price}
placeholder='Masukan Total Penjualan'
/>
{formErrorList.length > 0 && (
<div className='mt-4'>
<AlertErrorList formErrorList={formErrorList} onClose={close} />
</div>
)}
</div> </div>
<div className='h-18' /> <div className='h-18' />
<div className='absolute w-full bottom-0 right-0'> <div className='absolute w-full bottom-0 right-0 p-4'>
<Button <Button
type='submit' type='submit'
isLoading={formik.isSubmitting} isLoading={formik.isSubmitting}
@@ -208,8 +208,12 @@ const SalesOrderProductTable = ({
</tr> </tr>
<tr> <tr>
<td className='text-sm px-4 py-3'>Gudang</td> <td className='text-sm px-4 py-3'>Gudang</td>
<td className='text-sm px-4 py-3'>{item.kandang?.label}</td>
</tr>
<tr>
<td className='text-sm px-4 py-3'>Kategori</td>
<td className='text-sm px-4 py-3'> <td className='text-sm px-4 py-3'>
{item.product_warehouse?.label} {item.marketing_type?.label}
</td> </td>
</tr> </tr>
<tr> <tr>
@@ -218,33 +222,65 @@ const SalesOrderProductTable = ({
{item.product_warehouse?.label} {item.product_warehouse?.label}
</td> </td>
</tr> </tr>
{item.marketing_type?.value.toLowerCase() === 'telur' && (
<tr>
<td className='text-sm px-4 py-3'>Tipe Konversi</td>
<td className='text-sm px-4 py-3'>
{item.convertion_unit?.label}
</td>
</tr>
)}
{item.marketing_type?.value.toLowerCase() ===
'ayam_pullet' && (
<tr>
<td className='text-sm px-4 py-3'>Tipe Konversi</td>
<td className='text-sm px-4 py-3'>{item.week?.label}</td>
</tr>
)}
{item.convertion_unit?.value.toLowerCase() === 'peti' && (
<tr>
<td className='text-sm px-4 py-3'>Total Peti</td>
<td className='text-sm px-4 py-3'>
{item.total_peti} {item.convertion_unit?.label}
</td>
</tr>
)}
{item.marketing_type?.value.toLowerCase() !== 'trading' && (
<>
<tr>
<td className='text-sm px-4 py-3'>Total Bobot</td>
<td className='text-sm px-4 py-3'>
{item.total_weight
? formatNumber(
parseFloat(item.total_weight as string)
) + ' Kg'
: '0 Kg'}
</td>
</tr>
<tr>
<td className='text-sm px-4 py-3'>Avg Bobot</td>
<td className='text-sm px-4 py-3'>
{item.avg_weight
? formatNumber(
parseFloat(item.avg_weight as string)
) + ' Kg'
: '0 Kg'}
</td>
</tr>
</>
)}
<tr> <tr>
<td className='text-sm px-4 py-3'>Total Bobot</td>
<td className='text-sm px-4 py-3'> <td className='text-sm px-4 py-3'>
{item.total_weight {item.marketing_type?.value === 'telur'
? formatNumber( ? 'Total Butir Telur'
parseFloat(item.total_weight as string) : 'Qty'}
) + ' Kg'
: '-'}
</td> </td>
</tr>
<tr>
<td className='text-sm px-4 py-3'>Avg Bobot</td>
<td className='text-sm px-4 py-3'>
{item.avg_weight
? formatNumber(parseFloat(item.avg_weight as string)) +
' Kg'
: '-'}
</td>
</tr>
<tr>
<td className='text-sm px-4 py-3'>Qty</td>
<td className='text-sm px-4 py-3'> <td className='text-sm px-4 py-3'>
{`${formatNumber(parseFloat(item.qty as string))} ${item.uom || ''}`} {`${formatNumber(parseFloat(item.qty as string))} ${item.uom || ''}`}
</td> </td>
</tr> </tr>
<tr> <tr>
<td className='text-sm px-4 py-3'>Total Harga Satuan</td> <td className='text-sm px-4 py-3'>Harga Satuan</td>
<td className='text-sm px-4 py-3'> <td className='text-sm px-4 py-3'>
{formatCurrency(parseFloat(item.unit_price as string))} {formatCurrency(parseFloat(item.unit_price as string))}
</td> </td>
+109 -4
View File
@@ -17,6 +17,7 @@ import RowCollapseOptions from '@/components/table/RowCollapseOptions';
import RowOptionsMenuWrapper from '@/components/table/RowOptionsMenuWrapper'; import RowOptionsMenuWrapper from '@/components/table/RowOptionsMenuWrapper';
import RequirePermission from '@/components/helper/RequirePermission'; import RequirePermission from '@/components/helper/RequirePermission';
import StatusBadge from '@/components/helper/StatusBadge'; import StatusBadge from '@/components/helper/StatusBadge';
import PurchaseOrderInvoice from '@/components/pages/purchase/order/PurchaseOrderInvoice';
import { cn, formatDate } from '@/lib/helper'; import { cn, formatDate } from '@/lib/helper';
import { isResponseSuccess } from '@/lib/api-helper'; import { isResponseSuccess } from '@/lib/api-helper';
@@ -158,6 +159,27 @@ const PurchaseTable = () => {
PurchaseApi.getAllFetcher PurchaseApi.getAllFetcher
); );
const [isDownloadingInvoice, setIsDownloadingInvoice] = useState(false);
const [invoicePurchaseData, setInvoicePurchaseData] =
useState<Purchase | null>(null);
const handleDownloadInvoice = async (purchaseId: number) => {
setIsDownloadingInvoice(true);
try {
const response = await PurchaseApi.getSingle(purchaseId);
if (isResponseSuccess(response) && response.data) {
setInvoicePurchaseData(response.data);
setTimeout(() => {
setInvoicePurchaseData(null);
}, 1000);
}
} catch {
toast.error('Gagal mengambil data purchase order.');
} finally {
setIsDownloadingInvoice(false);
}
};
// ===== TABLE COLUMNS DEFINITION ===== // ===== TABLE COLUMNS DEFINITION =====
const purchaseColumns: ColumnDef<Purchase>[] = [ const purchaseColumns: ColumnDef<Purchase>[] = [
{ {
@@ -168,10 +190,66 @@ const PurchaseTable = () => {
}, },
}, },
{ {
accessorKey: 'supplier', accessorKey: 'po_expedition',
header: 'PO Ekspedisi',
cell: (props) => {
const purchase = props.row.original;
if (!purchase.po_number || purchase.po_number === 'Belum dibuat') {
return <span>-</span>;
}
return (
<Button
color='primary'
className='w-fit min-w-32 flex items-center justify-start gap-1 px-2 py-1 text-sm font-mono'
onClick={() => handleDownloadInvoice(purchase.id)}
disabled={isDownloadingInvoice}
>
<Icon
icon={
isDownloadingInvoice
? 'eos-icons:loading'
: 'material-symbols:file-open-outline'
}
width={16}
height={16}
/>
{purchase.po_number}
</Button>
);
},
},
{
accessorKey: 'supplier.name',
header: 'Vendor', header: 'Vendor',
cell: (props) => props.row.original.supplier.name, cell: (props) => props.row.original.supplier.name,
}, },
{
accessorKey: 'requester_name',
header: 'Nama Pengaju',
cell: (props) => props.row.original.requester_name || '-',
},
{
accessorKey: 'products.name',
header: 'Produk',
cell: (props) => {
const products = props.row.original.products;
if (!products || products.length === 0) return '-';
return (
<ul className='list-disc pl-4'>
{products.map((product, index) => (
<li key={index}>{product.name}</li>
))}
</ul>
);
},
},
{
accessorKey: 'location.name',
header: 'Lokasi',
cell: (props) => props.row.original.location?.name || '-',
},
{ {
accessorKey: 'po_date', accessorKey: 'po_date',
header: 'Tgl. PO', header: 'Tgl. PO',
@@ -180,6 +258,14 @@ const PurchaseTable = () => {
? formatDate(props.row.original.po_date, 'DD MMM YYYY') ? formatDate(props.row.original.po_date, 'DD MMM YYYY')
: '-', : '-',
}, },
{
accessorKey: 'due_date',
header: 'Jatuh Tempo',
cell: (props) =>
props.row.original.due_date
? formatDate(props.row.original.due_date, 'DD MMM YYYY')
: '-',
},
{ {
header: 'Aging', header: 'Aging',
cell: (props) => { cell: (props) => {
@@ -231,7 +317,7 @@ const PurchaseTable = () => {
color={statusColor} color={statusColor}
text={statusText} text={statusText}
className={{ className={{
badge: 'whitespace-nowrap', badge: 'whitespace-nowrap max-w-max w-fit',
}} }}
/> />
); );
@@ -330,11 +416,21 @@ const PurchaseTable = () => {
<DebouncedTextInput <DebouncedTextInput
name='search' name='search'
placeholder='Cari Pembelian' placeholder='Search'
value={tableFilterState.search} value={tableFilterState.search}
onChange={searchChangeHandler} onChange={searchChangeHandler}
startAdornment={
<Icon
icon='heroicons:magnifying-glass'
width={20}
height={20}
/>
}
className={{ className={{
wrapper: 'sm:max-w-3xs', wrapper: 'w-full min-w-24 max-w-3xs',
inputWrapper: 'rounded-xl! shadow-button-soft',
input:
'placeholder:font-semibold placeholder:text-base-content/50',
}} }}
/> />
</div> </div>
@@ -409,6 +505,15 @@ const PurchaseTable = () => {
onClick: confirmationModalDeleteClickHandler, onClick: confirmationModalDeleteClickHandler,
}} }}
/> />
{invoicePurchaseData && (
<div className='hidden'>
<PurchaseOrderInvoice
data={invoicePurchaseData}
triggerDownloadOnMount={true}
/>
</div>
)}
</> </>
); );
}; };
@@ -1,6 +1,6 @@
'use client'; 'use client';
import { useMemo, useState } from 'react'; import { useMemo, useState, useEffect, useCallback, useRef } from 'react';
import { import {
Page, Page,
Text, Text,
@@ -235,11 +235,16 @@ const pdfStyles = StyleSheet.create({
interface PurchaseOrderInvoiceProps { interface PurchaseOrderInvoiceProps {
data?: Purchase; data?: Purchase;
className?: string; className?: string;
triggerDownloadOnMount?: boolean;
} }
const PurchaseOrderInvoice = ({ data }: PurchaseOrderInvoiceProps) => { const PurchaseOrderInvoice = ({
data,
triggerDownloadOnMount,
}: PurchaseOrderInvoiceProps) => {
const [, setIsGeneratingPDF] = useState(false); const [, setIsGeneratingPDF] = useState(false);
const purchaseData = data; const purchaseData = data;
const hasDownloadedRef = useRef(false);
const grandTotal = useMemo(() => { const grandTotal = useMemo(() => {
return ( return (
@@ -250,7 +255,7 @@ const PurchaseOrderInvoice = ({ data }: PurchaseOrderInvoiceProps) => {
); );
}, [purchaseData?.items]); }, [purchaseData?.items]);
const handleDownloadPDF = async () => { const handleDownloadPDF = useCallback(async () => {
if (!purchaseData) { if (!purchaseData) {
toast.error('No purchase order data available'); toast.error('No purchase order data available');
return; return;
@@ -510,7 +515,20 @@ const PurchaseOrderInvoice = ({ data }: PurchaseOrderInvoiceProps) => {
} finally { } finally {
setIsGeneratingPDF(false); setIsGeneratingPDF(false);
} }
}; }, [purchaseData]);
useEffect(() => {
if (triggerDownloadOnMount && purchaseData && !hasDownloadedRef.current) {
hasDownloadedRef.current = true;
handleDownloadPDF();
}
}, [triggerDownloadOnMount, purchaseData]);
useEffect(() => {
if (!triggerDownloadOnMount) {
hasDownloadedRef.current = false;
}
}, [triggerDownloadOnMount]);
if (!purchaseData) { if (!purchaseData) {
return ( return (
@@ -520,6 +538,10 @@ const PurchaseOrderInvoice = ({ data }: PurchaseOrderInvoiceProps) => {
); );
} }
if (triggerDownloadOnMount) {
return null;
}
return purchaseData?.po_number && return purchaseData?.po_number &&
purchaseData.po_number !== 'Belum dibuat' ? ( purchaseData.po_number !== 'Belum dibuat' ? (
<Button <Button
@@ -96,8 +96,7 @@ interface CustomerPaymentExportPDFParams {
// sales?: string; // sales?: string;
start_date?: string; start_date?: string;
end_date?: string; end_date?: string;
// TODO: Uncomment when BE is ready filter_by?: string;
// filter_by?: string;
}; };
} }
@@ -3,18 +3,18 @@ import useSWR from 'swr';
import { Icon } from '@iconify/react'; import { Icon } from '@iconify/react';
import Card from '@/components/Card'; import Card from '@/components/Card';
import Badge from '@/components/Badge'; import Badge from '@/components/Badge';
import SelectInput, { useSelect } from '@/components/input/SelectInput'; import { useSelect } from '@/components/input/SelectInput';
import SelectInputCheckbox from '@/components/input/SelectInputCheckbox'; import SelectInputCheckbox from '@/components/input/SelectInputCheckbox';
import SelectInputRadio from '@/components/input/SelectInputRadio';
import DateInput from '@/components/input/DateInput'; import DateInput from '@/components/input/DateInput';
import { CustomerApi } from '@/services/api/master-data'; import { CustomerApi } from '@/services/api/master-data';
import { FinanceApi } from '@/services/api/report/finance-report'; import { FinanceApi } from '@/services/api/report/finance-report';
import { UserApi } from '@/services/api/user'; // import { UserApi } from '@/services/api/user';
import Table from '@/components/Table'; import Table from '@/components/Table';
import { ColumnDef } from '@tanstack/react-table'; import { ColumnDef } from '@tanstack/react-table';
import { formatCurrency, formatDate, formatNumber, cn } from '@/lib/helper'; import { formatCurrency, formatDate, formatNumber, cn } from '@/lib/helper';
import { import {
CustomerPaymentReport, CustomerPaymentReport,
CustomerPaymentRow,
CustomerPaymentSummary, CustomerPaymentSummary,
} from '@/types/api/report/customer-payment'; } from '@/types/api/report/customer-payment';
import { isResponseSuccess } from '@/lib/api-helper'; import { isResponseSuccess } from '@/lib/api-helper';
@@ -48,38 +48,58 @@ const CustomerPaymentTab = ({ tabId }: CustomerPaymentTabProps) => {
const [isSubmitted, setIsSubmitted] = useState(false); const [isSubmitted, setIsSubmitted] = useState(false);
// ===== FILTER STATE ===== // ===== FILTER STATE =====
const [appliedFilterCustomer, setAppliedFilterCustomer] = useState<
typeof customerOptions
>([]);
// TODO: Uncomment when BE is ready
// const [appliedFilterSales, setAppliedFilterSales] = useState<
// typeof salesOptions
// >([]);
const [appliedFilterByType, setAppliedFilterByType] = useState<
(typeof dataTypeOptions)[0] | null
>(null);
const [appliedFilterStartDate, setAppliedFilterStartDate] = useState('');
const [appliedFilterEndDate, setAppliedFilterEndDate] = useState('');
const [dateErrorShown, setDateErrorShown] = useState(false);
const [hasDateError, setHasDateError] = useState(false);
const [filterCustomer, setFilterCustomer] = useState<typeof customerOptions>( const [filterCustomer, setFilterCustomer] = useState<typeof customerOptions>(
[] []
); );
// TODO: Uncomment when BE is ready // TODO: Uncomment when BE is ready
// const [filterSales, setFilterSales] = useState<typeof salesOptions>([]); // const [filterSales, setFilterSales] = useState<typeof salesOptions>([]);
const [filterSales, setFilterSales] = useState<typeof salesOptions>([]);
const [filterStartDate, setFilterStartDate] = useState(''); const [filterStartDate, setFilterStartDate] = useState('');
const [filterEndDate, setFilterEndDate] = useState(''); const [filterEndDate, setFilterEndDate] = useState('');
const filterModal = useModal(); const filterModal = useModal();
const dataTypeOptions = useMemo(
() => [
{ value: 'trans_date', label: 'Tanggal Jual/Bayar' },
{ value: 'realization_date', label: 'Tanggal Realisasi' },
],
[]
);
const [filterByType, setFilterByType] = useState<
(typeof dataTypeOptions)[0] | null
>(null);
const { const {
options: customerOptions, options: customerOptions,
setInputValue: setCustomerInputValue, setInputValue: setCustomerInputValue,
isLoadingOptions: isLoadingCustomers, isLoadingOptions: isLoadingCustomers,
loadMore: loadMoreCustomers, loadMore: loadMoreCustomers,
hasMore: hasMoreCustomers,
} = useSelect(CustomerApi.basePath, 'id', 'name', 'search'); } = useSelect(CustomerApi.basePath, 'id', 'name', 'search');
// TODO: Uncomment when BE is ready // TODO: Uncomment when BE is ready
const { // const {
options: salesOptions, // options: salesOptions,
setInputValue: setSalesInputValue, // setInputValue: setSalesInputValue,
isLoadingOptions: isLoadingSales, // isLoadingOptions: isLoadingSales,
loadMore: loadMoreSales, // loadMore: loadMoreSales,
hasMore: hasMoreSales, // hasMore: hasMoreSales,
} = useSelect(UserApi.basePath, 'id', 'name', 'search'); // } = useSelect(UserApi.basePath, 'id', 'name', 'search');
const dataTypeOptions = useMemo(
() => [{ value: 'do_date', label: 'Tanggal Jual' }],
[]
);
const getPaymentStatusColor = (notes: string) => { const getPaymentStatusColor = (notes: string) => {
const normalizedValue = notes.toLowerCase(); const normalizedValue = notes.toLowerCase();
@@ -119,49 +139,145 @@ const CustomerPaymentTab = ({ tabId }: CustomerPaymentTabProps) => {
// ===== FILTER HANDLERS ===== // ===== FILTER HANDLERS =====
const handleFilterModalOpen = useCallback(() => { const handleFilterModalOpen = useCallback(() => {
setFilterCustomer(appliedFilterCustomer);
// setFilterSales(appliedFilterSales);
setFilterByType(appliedFilterByType);
setFilterStartDate(appliedFilterStartDate);
setFilterEndDate(appliedFilterEndDate);
filterModal.openModal(); filterModal.openModal();
}, [filterModal]); }, [
filterModal,
appliedFilterCustomer,
appliedFilterByType,
appliedFilterStartDate,
appliedFilterEndDate,
]);
const handleResetFilters = useCallback(() => { const handleResetFilters = useCallback(() => {
setIsSubmitted(false); setIsSubmitted(false);
setFilterCustomer([]); setFilterCustomer([]);
setFilterSales([]); setFilterByType(null);
setFilterStartDate(''); setFilterStartDate('');
setFilterEndDate(''); setFilterEndDate('');
}, []); setAppliedFilterCustomer([]);
setAppliedFilterByType(null);
setAppliedFilterStartDate('');
setAppliedFilterEndDate('');
setHasDateError(false);
if (dateErrorShown) {
toast.dismiss();
setDateErrorShown(false);
}
}, [dateErrorShown]);
const handleApplyFilters = useCallback(() => { const handleApplyFilters = useCallback(() => {
setAppliedFilterCustomer(filterCustomer);
setAppliedFilterByType(filterByType);
setAppliedFilterStartDate(filterStartDate);
setAppliedFilterEndDate(filterEndDate);
setIsSubmitted(true); setIsSubmitted(true);
setCurrentPage(1); setCurrentPage(1);
filterModal.closeModal(); filterModal.closeModal();
}, [filterModal]); }, [
filterModal,
filterCustomer,
filterByType,
filterStartDate,
filterEndDate,
]);
const handleStartDateChange = useCallback(
(e: React.ChangeEvent<HTMLInputElement>) => {
const value = e.target.value;
setFilterStartDate(value);
if (value && filterEndDate) {
const startDate = new Date(value);
const endDateObj = new Date(filterEndDate);
if (endDateObj < startDate) {
setHasDateError(true);
if (!dateErrorShown) {
toast.error('Tanggal akhir tidak boleh masa lampau', {
duration: Infinity,
});
setDateErrorShown(true);
}
} else {
setHasDateError(false);
if (dateErrorShown) {
toast.dismiss();
setDateErrorShown(false);
}
}
} else {
setHasDateError(false);
}
},
[filterEndDate, dateErrorShown]
);
const handleEndDateChange = useCallback(
(e: React.ChangeEvent<HTMLInputElement>) => {
const value = e.target.value;
setFilterEndDate(value);
if (value && filterStartDate) {
const startDateObj = new Date(filterStartDate);
const endDate = new Date(value);
if (endDate < startDateObj) {
setHasDateError(true);
if (!dateErrorShown) {
toast.error('Tanggal akhir tidak boleh masa lampau', {
duration: Infinity,
});
setDateErrorShown(true);
}
return;
}
}
setHasDateError(false);
if (dateErrorShown) {
toast.dismiss();
setDateErrorShown(false);
}
},
[filterStartDate, dateErrorShown]
);
// ===== ACTIVE FILTERS COUNT ===== // ===== ACTIVE FILTERS COUNT =====
const activeFiltersCount = useMemo(() => { const activeFiltersCount = useMemo(() => {
let count = 0; let count = 0;
// Date filter (start_date + end_date = 1 filter) // Date filter (start_date + end_date = 1 filter)
if (filterStartDate || filterEndDate) { if (appliedFilterStartDate || appliedFilterEndDate) {
count += 1; count += 1;
} }
// Customer filter // Customer filter
if (filterCustomer.length > 0) { if (appliedFilterCustomer.length > 0) {
count += 1;
}
// Filter by type filter (hanya dihitung jika ada nilai yang dipilih)
if (appliedFilterByType) {
count += 1; count += 1;
} }
// TODO: Uncomment when BE is ready // TODO: Uncomment when BE is ready
// // Sales filter // // Sales filter
// if (filterSales.length > 0) { // if (appliedFilterSales.length > 0) {
// count += 1; // count += 1;
// } // }
return count; return count;
}, [ }, [
filterStartDate, appliedFilterStartDate,
filterEndDate, appliedFilterEndDate,
filterCustomer, appliedFilterCustomer,
// filterSales, appliedFilterByType,
]); ]);
const hasFilters = activeFiltersCount > 0; const hasFilters = activeFiltersCount > 0;
@@ -172,17 +288,20 @@ const CustomerPaymentTab = ({ tabId }: CustomerPaymentTabProps) => {
? () => { ? () => {
const params = { const params = {
customer_ids: customer_ids:
filterCustomer.length > 0 appliedFilterCustomer.length > 0
? filterCustomer.map((v) => String(v.value)).join(',') ? appliedFilterCustomer.map((v) => String(v.value)).join(',')
: undefined, : undefined,
// TODO: Uncomment when BE is ready // TODO: Uncomment when BE is ready
// sales_id: // sales_id:
// filterSales.length > 0 // appliedFilterSales.length > 0
// ? filterSales.map((v) => String(v.value)).join(',') // ? appliedFilterSales.map((v) => String(v.value)).join(',')
// : undefined, // : undefined,
// filter_by: 'do_date' as const, filter_by: appliedFilterByType?.value as
start_date: filterStartDate || undefined, | 'trans_date'
end_date: filterEndDate || undefined, | 'realization_date'
| undefined,
start_date: appliedFilterStartDate || undefined,
end_date: appliedFilterEndDate || undefined,
page: currentPage, page: currentPage,
limit: pageSize, limit: pageSize,
}; };
@@ -193,8 +312,7 @@ const CustomerPaymentTab = ({ tabId }: CustomerPaymentTabProps) => {
([, params]) => ([, params]) =>
FinanceApi.getCustomerPaymentReport( FinanceApi.getCustomerPaymentReport(
params.customer_ids, params.customer_ids,
undefined, // TODO: Change to params.sales_id when BE is ready params.filter_by,
undefined, // TODO: Change to params.filter_by when BE is ready
params.start_date, params.start_date,
params.end_date, params.end_date,
params.page, params.page,
@@ -216,24 +334,27 @@ const CustomerPaymentTab = ({ tabId }: CustomerPaymentTabProps) => {
> => { > => {
const params = { const params = {
customer_ids: customer_ids:
filterCustomer.length > 0 appliedFilterCustomer.length > 0
? filterCustomer.map((v) => String(v.value)).join(',') ? appliedFilterCustomer.map((v) => String(v.value)).join(',')
: undefined, : undefined,
// TODO: Uncomment when BE is ready // TODO: Uncomment when BE is ready
// sales_id: // sales_id:
// filterSales.length > 0 // appliedFilterSales.length > 0
// ? filterSales.map((v) => String(v.value)).join(',') // ? appliedFilterSales.map((v) => String(v.value)).join(',')
// : undefined, // : undefined,
start_date: filterStartDate || undefined, filter_by: appliedFilterByType?.value as
end_date: filterEndDate || undefined, | 'trans_date'
| 'realization_date'
| undefined,
start_date: appliedFilterStartDate || undefined,
end_date: appliedFilterEndDate || undefined,
limit: 100, limit: 100,
page: 1, page: 1,
}; };
const response = await FinanceApi.getCustomerPaymentReport( const response = await FinanceApi.getCustomerPaymentReport(
params.customer_ids, params.customer_ids,
undefined, // TODO: Change to params.sales_id when BE is ready params.filter_by,
undefined, // TODO: Change to params.filter_by when BE is ready
params.start_date, params.start_date,
params.end_date, params.end_date,
params.page, params.page,
@@ -243,7 +364,13 @@ const CustomerPaymentTab = ({ tabId }: CustomerPaymentTabProps) => {
return isResponseSuccess(response) return isResponseSuccess(response)
? (response.data as unknown as CustomerPaymentReport[]) ? (response.data as unknown as CustomerPaymentReport[])
: null; : null;
}, [filterCustomer, filterSales, filterStartDate, filterEndDate]); }, [
appliedFilterCustomer,
// appliedFilterSales,
appliedFilterStartDate,
appliedFilterEndDate,
appliedFilterByType,
]);
// ===== EXPORT HANDLERS ===== // ===== EXPORT HANDLERS =====
const handleExportExcel = useCallback(async () => { const handleExportExcel = useCallback(async () => {
@@ -287,18 +414,20 @@ const CustomerPaymentTab = ({ tabId }: CustomerPaymentTabProps) => {
data: allDataForExport, data: allDataForExport,
params: { params: {
customer_name: customer_name:
filterCustomer.length > 0 appliedFilterCustomer.length > 0
? filterCustomer.map((c) => c.label).join(', ') ? appliedFilterCustomer.map((c) => c.label).join(', ')
: undefined, : undefined,
// TODO: Uncomment when BE is ready // TODO: Uncomment when BE is ready
// sales: // sales:
// filterSales.length > 0 // appliedFilterSales.length > 0
// ? filterSales.map((s) => s.label).join(', ') // ? appliedFilterSales.map((s) => s.label).join(', ')
// : undefined, // : undefined,
start_date: filterStartDate || undefined, start_date: appliedFilterStartDate || undefined,
end_date: filterEndDate || undefined, end_date: appliedFilterEndDate || undefined,
// TODO: Uncomment when BE is ready filter_by: appliedFilterByType?.value as
// filter_by: 'do_date' as const, | 'trans_date'
| 'realization_date'
| undefined,
}, },
}); });
toast.success('PDF berhasil dibuat dan diunduh.'); toast.success('PDF berhasil dibuat dan diunduh.');
@@ -406,7 +535,7 @@ const CustomerPaymentTab = ({ tabId }: CustomerPaymentTabProps) => {
footer: () => <div className='font-semibold text-gray-900'>Total</div>, footer: () => <div className='font-semibold text-gray-900'>Total</div>,
}, },
{ {
id: 'do_date_or_payment_date', id: 'trans_date',
header: 'Tanggal Jual/Bayar', header: 'Tanggal Jual/Bayar',
accessorKey: 'trans_date', accessorKey: 'trans_date',
enableSorting: false, enableSorting: false,
@@ -811,9 +940,7 @@ const CustomerPaymentTab = ({ tabId }: CustomerPaymentTabProps) => {
<DateInput <DateInput
name='start_date' name='start_date'
value={filterStartDate} value={filterStartDate}
onChange={(e) => { onChange={handleStartDateChange}
setFilterStartDate(e.target.value);
}}
className={{ wrapper: 'w-full' }} className={{ wrapper: 'w-full' }}
isNestedModal isNestedModal
/> />
@@ -822,9 +949,7 @@ const CustomerPaymentTab = ({ tabId }: CustomerPaymentTabProps) => {
<DateInput <DateInput
name='end_date' name='end_date'
value={filterEndDate} value={filterEndDate}
onChange={(e) => { onChange={handleEndDateChange}
setFilterEndDate(e.target.value);
}}
className={{ wrapper: 'w-full' }} className={{ wrapper: 'w-full' }}
isNestedModal isNestedModal
/> />
@@ -864,17 +989,18 @@ const CustomerPaymentTab = ({ tabId }: CustomerPaymentTabProps) => {
/> />
</div> */} </div> */}
{/* TODO: Uncomment when BE is ready */} <SelectInputRadio
{/* <div> label='Filter Berdasarkan'
<SelectInput placeholder='Pilih Filter Berdasarkan'
label='Filter Berdasarkan' options={dataTypeOptions}
placeholder='Pilih Filter Berdasarkan' value={filterByType}
options={dataTypeOptions} onChange={(val) => {
value={dataTypeOptions[0]} if (val && !Array.isArray(val)) {
isDisabled={true} setFilterByType(val);
className={{ wrapper: 'w-full' }} }
/> }}
</div> */} className={{ wrapper: 'w-full' }}
/>
{/* Action Buttons */} {/* Action Buttons */}
</div> </div>
@@ -889,6 +1015,7 @@ const CustomerPaymentTab = ({ tabId }: CustomerPaymentTabProps) => {
<Button <Button
className='min-w-40 text-sm rounded-lg py-3 text-white font-semibold' className='min-w-40 text-sm rounded-lg py-3 text-white font-semibold'
onClick={handleApplyFilters} onClick={handleApplyFilters}
disabled={hasDateError}
> >
Apply Filter Apply Filter
</Button> </Button>
+24 -5
View File
@@ -513,16 +513,35 @@ export const FILTER_TYPE_OPTIONS = [
export const MARKETING_TYPE_OPTIONS = [ export const MARKETING_TYPE_OPTIONS = [
{ {
label: 'Ayam', label: 'Ayam Pullet',
value: 'ayam', value: 'AYAM_PULLET',
}, },
{ {
label: 'Telur', label: 'Ayam',
value: 'telur', value: 'AYAM',
}, },
{ {
label: 'Trading', label: 'Trading',
value: 'trading', value: 'TRADING',
},
{
label: 'Telur',
value: 'TELUR',
},
];
export const MARKETING_CONVERTION_UNIT_OPTIONS = [
{
label: 'Kg',
value: 'kg',
},
{
label: 'Qty',
value: 'qty',
},
{
label: 'Peti',
value: 'peti',
}, },
]; ];
+507
View File
@@ -0,0 +1,507 @@
/**
* Marketing Product Calculation Hook
*
* Reusable calculation logic for Sales Order and Delivery Order forms.
* Handles 6 scenarios: TRADING, AYAM_PULLET, AYAM, TELUR+KG, TELUR+PETI, TELUR+QTY
*/
// ============ Types ============
export type MarketingFormValues = {
qty?: string | number;
avg_weight?: string | number;
total_weight?: string | number;
unit_price?: string | number;
total_price?: string | number;
marketing_type?: { value: string; label: string } | null;
convertion_unit?: { value: string; label: string } | null;
week?: { value?: number; label?: string } | null;
weight_per_convertion?: number | null;
price_per_convertion?: number | null;
total_peti?: number | null;
sisa_berat?: number | null;
price_sisa_berat?: number | null;
/** Harga per butir telur untuk TELUR + QTY */
price_per_qty?: number | null;
};
export type SetFieldValueFn = (
field: string,
value: string | number | null
) => void;
export type CalculationContext = {
values: MarketingFormValues;
setFieldValue: SetFieldValueFn;
hasSisaBerat: boolean;
};
// ============ Helper Functions ============
/**
* Round weight untuk operasi perkalian (total_weight = avg_weight × qty)
* Precision: 2 decimal places
*/
export const roundWeight = (value: number): number => Number(value.toFixed(2));
/**
* Precise weight untuk operasi pembagian (avg_weight = total_weight / qty)
* Tidak di-round untuk menjaga akurasi maksimal
*/
export const preciseWeight = (value: number): number => value;
export const roundPrice = (value: number): number => Math.round(value);
// ============ Calculation Handlers ============
/**
* TRADING: Penjualan non-livestock (obat-obatan, pakan, dll)
* - Formula: total_price = qty × unit_price
* - Weight fields: always 0
*/
export const calculateTrading = (
field: string,
ctx: CalculationContext
): void => {
const { values, setFieldValue } = ctx;
const unitPrice = Number(values.unit_price || 0);
const qty = Number(values.qty || 0);
const totalPrice = Number(values.total_price || 0);
// Trading: avg_weight = 0, total_weight = 0
setFieldValue('avg_weight', 0);
setFieldValue('total_weight', 0);
switch (field) {
case 'unit_price':
case 'qty': {
if (unitPrice > 0 && qty > 0) {
setFieldValue('total_price', roundPrice(unitPrice * qty));
}
break;
}
case 'total_price': {
if (totalPrice > 0 && qty > 0) {
setFieldValue('unit_price', roundPrice(totalPrice / qty));
}
break;
}
}
};
/**
* AYAM_PULLET: Penjualan pullet dengan harga berdasarkan umur minggu
* - Formula: total_price = unit_price × week × qty
* - total_weight = avg_weight × qty
*/
export const calculateAyamPullet = (
field: string,
ctx: CalculationContext
): void => {
const { values, setFieldValue } = ctx;
const unitPrice = Number(values.unit_price || 0);
const week = Number(values.week?.value || 0);
const qty = Number(values.qty || 0);
const avgWeight = Number(values.avg_weight || 0);
const totalWeight = Number(values.total_weight || 0);
const totalPrice = Number(values.total_price || 0);
switch (field) {
case 'unit_price':
case 'week':
case 'qty': {
// total_price = unit_price × week × qty
if (unitPrice > 0 && week > 0 && qty > 0) {
setFieldValue('total_price', roundPrice(unitPrice * week * qty));
}
// total_weight = avg_weight × qty
if (avgWeight > 0 && qty > 0) {
setFieldValue('total_weight', roundWeight(avgWeight * qty));
}
break;
}
case 'avg_weight': {
if (avgWeight > 0 && qty > 0) {
setFieldValue('total_weight', roundWeight(avgWeight * qty));
}
break;
}
case 'total_weight': {
if (totalWeight > 0 && qty > 0) {
setFieldValue('avg_weight', preciseWeight(totalWeight / qty));
}
break;
}
case 'total_price': {
// Reverse: unit_price = total_price / (week × qty)
if (totalPrice > 0 && week > 0 && qty > 0) {
setFieldValue('unit_price', roundPrice(totalPrice / (week * qty)));
}
break;
}
}
};
/**
* AYAM: Penjualan ayam hidup/potong dengan harga per kg
* - Formula: total_price = total_weight × unit_price
* - total_weight = qty × avg_weight
*/
export const calculateAyam = (field: string, ctx: CalculationContext): void => {
const { values, setFieldValue } = ctx;
const unitPrice = Number(values.unit_price || 0);
const qty = Number(values.qty || 0);
const avgWeight = Number(values.avg_weight || 0);
const totalWeight = Number(values.total_weight || 0);
const totalPrice = Number(values.total_price || 0);
switch (field) {
case 'qty':
case 'avg_weight': {
// total_weight = qty × avg_weight
if (qty > 0 && avgWeight > 0) {
const tw = roundWeight(qty * avgWeight);
setFieldValue('total_weight', tw);
// total_price = total_weight × unit_price
if (unitPrice > 0) {
setFieldValue('total_price', roundPrice(tw * unitPrice));
}
}
break;
}
case 'total_weight': {
// avg_weight = total_weight / qty
if (totalWeight > 0 && qty > 0) {
setFieldValue('avg_weight', preciseWeight(totalWeight / qty));
}
// total_price = total_weight × unit_price
if (unitPrice > 0 && totalWeight > 0) {
setFieldValue('total_price', roundPrice(totalWeight * unitPrice));
}
break;
}
case 'unit_price': {
// total_price = total_weight × unit_price
if (unitPrice > 0 && totalWeight > 0) {
setFieldValue('total_price', roundPrice(totalWeight * unitPrice));
}
break;
}
case 'total_price': {
// unit_price = total_price / total_weight
if (totalPrice > 0 && totalWeight > 0) {
setFieldValue('unit_price', roundPrice(totalPrice / totalWeight));
}
break;
}
}
};
/**
* TELUR + PETI: Penjualan telur dalam satuan peti
*
* Formulas:
* - total_weight = (weight_per_convertion × total_peti) + sisa_berat
* - total_price = (price_per_convertion × total_peti) + price_sisa_berat
* - unit_price = total_price / total_weight (untuk BE)
* - avg_weight = total_weight / qty
*/
export const calculateTelurPeti = (
field: string,
ctx: CalculationContext
): void => {
const { values, setFieldValue, hasSisaBerat } = ctx;
const pricePerConvertion = Number(values.price_per_convertion || 0);
const totalPeti = Number(values.total_peti || 0);
const weightPerConvertion = Number(values.weight_per_convertion || 0);
const sisaBerat = hasSisaBerat ? Number(values.sisa_berat || 0) : 0;
const priceSisaBerat = hasSisaBerat
? Number(values.price_sisa_berat || 0)
: 0;
const qty = Number(values.qty || 0);
// Helper untuk menghitung dan set unit_price = total_price / total_weight
const updateUnitPrice = (tp: number, tw: number) => {
if (tw > 0 && tp > 0) {
setFieldValue('unit_price', roundPrice(tp / tw));
}
};
switch (field) {
case 'price_per_convertion': {
// Recalculate total_price = (price_per_convertion × total_peti) + price_sisa_berat
if (pricePerConvertion > 0 && totalPeti > 0) {
const totalPrice = pricePerConvertion * totalPeti + priceSisaBerat;
setFieldValue('total_price', roundPrice(totalPrice));
// Recalculate unit_price = total_price / total_weight
const totalWeight = weightPerConvertion * totalPeti + sisaBerat;
updateUnitPrice(totalPrice, totalWeight);
}
break;
}
case 'total_peti': {
// Recalculate total_weight = (weight_per_convertion × total_peti) + sisa_berat
let totalWeight = 0;
if (weightPerConvertion > 0 && totalPeti > 0) {
totalWeight = weightPerConvertion * totalPeti + sisaBerat;
setFieldValue('total_weight', roundWeight(totalWeight));
// Recalculate avg_weight = total_weight / qty
if (qty > 0) {
setFieldValue('avg_weight', preciseWeight(totalWeight / qty));
}
}
// Recalculate total_price = (price_per_convertion × total_peti) + price_sisa_berat
if (pricePerConvertion > 0 && totalPeti > 0) {
const totalPrice = pricePerConvertion * totalPeti + priceSisaBerat;
setFieldValue('total_price', roundPrice(totalPrice));
// Recalculate unit_price = total_price / total_weight
updateUnitPrice(totalPrice, totalWeight);
}
break;
}
case 'price_sisa_berat': {
// Recalculate total_price
if (pricePerConvertion > 0 && totalPeti > 0) {
const totalPrice = pricePerConvertion * totalPeti + priceSisaBerat;
setFieldValue('total_price', roundPrice(totalPrice));
// Recalculate unit_price = total_price / total_weight
const totalWeight = weightPerConvertion * totalPeti + sisaBerat;
updateUnitPrice(totalPrice, totalWeight);
}
break;
}
case 'weight_per_convertion': {
// Recalculate total_weight = (weight_per_convertion × total_peti) + sisa_berat
if (weightPerConvertion > 0 && totalPeti > 0) {
const totalWeight = weightPerConvertion * totalPeti + sisaBerat;
setFieldValue('total_weight', roundWeight(totalWeight));
// Recalculate avg_weight = total_weight / qty
if (qty > 0) {
setFieldValue('avg_weight', preciseWeight(totalWeight / qty));
}
// Recalculate unit_price = total_price / total_weight
const totalPrice = pricePerConvertion * totalPeti + priceSisaBerat;
updateUnitPrice(totalPrice, totalWeight);
}
break;
}
case 'sisa_berat': {
// Recalculate total_weight
if (weightPerConvertion > 0 && totalPeti > 0) {
const totalWeight = weightPerConvertion * totalPeti + sisaBerat;
setFieldValue('total_weight', roundWeight(totalWeight));
// Recalculate avg_weight = total_weight / qty
if (qty > 0) {
setFieldValue('avg_weight', preciseWeight(totalWeight / qty));
}
// Recalculate unit_price = total_price / total_weight
const totalPrice = pricePerConvertion * totalPeti + priceSisaBerat;
updateUnitPrice(totalPrice, totalWeight);
}
break;
}
case 'total_price': {
const totalPrice = Number(values.total_price || 0);
// Reverse calculate price_per_convertion
if (totalPeti > 0 && totalPrice > priceSisaBerat) {
setFieldValue(
'price_per_convertion',
roundPrice((totalPrice - priceSisaBerat) / totalPeti)
);
}
// Update unit_price = total_price / total_weight
const totalWeight = weightPerConvertion * totalPeti + sisaBerat;
updateUnitPrice(totalPrice, totalWeight);
break;
}
}
};
/**
* TELUR + KG: Penjualan telur dalam satuan kilogram
* - Formula: total_price = total_weight × unit_price
* - avg_weight = total_weight / qty (calculated)
*/
export const calculateTelurKg = (
field: string,
ctx: CalculationContext
): void => {
const { values, setFieldValue } = ctx;
const qty = Number(values.qty || 0);
const totalWeight = Number(values.total_weight || 0);
const totalPrice = Number(values.total_price || 0);
const pricePerConvertion = Number(values.price_per_convertion || 0);
switch (field) {
case 'total_weight':
case 'qty': {
// avg_weight = total_weight / qty
if (totalWeight > 0 && qty > 0) {
setFieldValue('avg_weight', preciseWeight(totalWeight / qty));
}
// total_price = total_weight × unit_price
if (pricePerConvertion > 0 && totalWeight > 0) {
setFieldValue(
'total_price',
roundPrice(totalWeight * pricePerConvertion)
);
setFieldValue('unit_price', pricePerConvertion);
}
break;
}
case 'price_per_convertion': {
// total_price = total_weight × price_per_convertion
if (pricePerConvertion > 0 && totalWeight > 0) {
setFieldValue(
'total_price',
roundPrice(totalWeight * pricePerConvertion)
);
setFieldValue('unit_price', pricePerConvertion);
}
break;
}
case 'total_price': {
// unit_price = total_price / total_weight
if (totalPrice > 0 && totalWeight > 0) {
setFieldValue('unit_price', roundPrice(totalPrice / totalWeight));
setFieldValue(
'price_per_convertion',
roundPrice(totalPrice / totalWeight)
);
}
break;
}
}
};
/**
* TELUR + QTY Workaround:
* - User inputs: qty, avg_weight, price_per_qty (harga per butir)
* - FE calculates:
* - total_weight = avg_weight × qty
* - total_price = qty × price_per_qty
* - unit_price = total_price / total_weight (normalisasi untuk BE)
* - Kirim convertion_unit: "KG" karena BE tidak support "QTY"
* - BE akan hitung: total_price = total_weight × unit_price (hasil sama)
*/
export const calculateTelurQty = (
field: string,
ctx: CalculationContext
): void => {
const { values, setFieldValue } = ctx;
const qty = Number(values.qty || 0);
const avgWeight = Number(values.avg_weight || 0);
const totalWeight = Number(values.total_weight || 0);
const pricePerQty = Number(values.price_per_qty || 0);
const totalPrice = Number(values.total_price || 0);
const unitPrice = Number(values.unit_price || 0);
switch (field) {
case 'qty':
case 'avg_weight': {
// total_weight = avg_weight × qty
if (avgWeight > 0 && qty > 0) {
const tw = roundWeight(avgWeight * qty);
setFieldValue('total_weight', tw);
// total_price = qty × price_per_qty
if (pricePerQty > 0) {
const tp = roundPrice(qty * pricePerQty);
setFieldValue('total_price', tp);
// unit_price = total_price / total_weight (untuk BE)
if (tw > 0) {
setFieldValue('unit_price', roundPrice(tp / tw));
}
}
}
break;
}
case 'total_weight': {
// avg_weight = total_weight / qty
if (totalWeight > 0 && qty > 0) {
setFieldValue('avg_weight', preciseWeight(totalWeight / qty));
// Recalculate total_price jika ada unit_price
if (unitPrice > 0) {
setFieldValue('total_price', roundPrice(totalWeight * unitPrice));
}
}
break;
}
case 'price_per_qty': {
// total_price = qty × price_per_qty
if (pricePerQty > 0 && qty > 0) {
const tp = roundPrice(qty * pricePerQty);
setFieldValue('total_price', tp);
// unit_price = total_price / total_weight (untuk BE)
if (totalWeight > 0) {
setFieldValue('unit_price', roundPrice(tp / totalWeight));
}
}
break;
}
case 'total_price': {
// price_per_qty = total_price / qty
if (totalPrice > 0 && qty > 0) {
setFieldValue('price_per_qty', roundPrice(totalPrice / qty));
// unit_price = total_price / total_weight (untuk BE)
if (totalWeight > 0) {
setFieldValue('unit_price', roundPrice(totalPrice / totalWeight));
}
}
break;
}
case 'unit_price': {
// total_price = total_weight × unit_price
if (unitPrice > 0 && totalWeight > 0) {
setFieldValue('total_price', roundPrice(totalWeight * unitPrice));
}
// price_per_qty = total_price / qty
if (totalPrice > 0 && qty > 0) {
setFieldValue('price_per_qty', roundPrice(totalPrice / qty));
}
break;
}
}
};
// ============ Main Dispatcher ============
/**
* Handle field blur and dispatch to appropriate calculation handler
* based on marketing_type and convertion_unit
*/
export const handleMarketingCalculation = (
field: string,
ctx: CalculationContext
): void => {
const { values } = ctx;
const marketingType = values.marketing_type?.value?.toLowerCase();
const convertionUnit = values.convertion_unit?.value?.toLowerCase();
if (!marketingType) return;
const qty = Number(values.qty || 0);
if (qty <= 0) return;
switch (marketingType) {
case 'trading':
calculateTrading(field, ctx);
break;
case 'ayam_pullet':
calculateAyamPullet(field, ctx);
break;
case 'telur':
if (convertionUnit === 'peti') {
calculateTelurPeti(field, ctx);
} else if (convertionUnit === 'kg') {
calculateTelurKg(field, ctx);
} else {
// QTY mode - workaround dengan kirim KG ke BE
calculateTelurQty(field, ctx);
}
break;
case 'ayam':
default:
calculateAyam(field, ctx);
break;
}
};
+2 -4
View File
@@ -15,9 +15,7 @@ export class FinanceApiService extends BaseApiService<
customer_ids?: string, customer_ids?: string,
// TODO: Uncomment when BE is ready // TODO: Uncomment when BE is ready
// sales_id?: string, // sales_id?: string,
// filter_by?: 'do_date', filter_by?: 'trans_date' | 'realization_date',
sales_id?: string,
filter_by?: 'do_date' | undefined,
start_date?: string, start_date?: string,
end_date?: string, end_date?: string,
page?: number, page?: number,
@@ -31,7 +29,7 @@ export class FinanceApiService extends BaseApiService<
customer_ids: customer_ids, customer_ids: customer_ids,
// TODO: Uncomment when BE is ready // TODO: Uncomment when BE is ready
// sales_id: sales_id, // sales_id: sales_id,
// filter_by: filter_by, filter_by: filter_by,
start_date: start_date, start_date: start_date,
end_date: end_date, end_date: end_date,
page: page, page: page,
+12
View File
@@ -36,6 +36,12 @@ export type BaseSalesOrder = {
total_price: number; total_price: number;
product_warehouse: ProductWarehouse; product_warehouse: ProductWarehouse;
vehicle_number: string; vehicle_number: string;
marketing_type: string;
convertion_unit: string;
total_peti: number;
weight_per_convertion: number;
/** Umur minggu untuk AYAM_PULLET */
week?: number;
}; };
export type BaseDeliveryOrder = { export type BaseDeliveryOrder = {
@@ -110,6 +116,12 @@ export type BaseCreateMarketingProductPayload = {
qty: string | number | undefined; qty: string | number | undefined;
avg_weight: string | number | undefined; avg_weight: string | number | undefined;
total_price: string | number | undefined; total_price: string | number | undefined;
marketing_type: string;
convertion_unit?: 'PETI' | 'KG';
/** Berat per peti (kg), hanya untuk TELUR + PETI */
weight_per_convertion?: number;
/** Umur minggu untuk AYAM_PULLET */
week?: number;
}; };
/** /**
+14 -4
View File
@@ -1,10 +1,15 @@
import { BaseApproval, BaseMetadata } from '@/types/api/api-general'; import {
BaseApproval,
BaseMetadata,
CreatedUser,
} from '@/types/api/api-general';
import { Supplier } from '@/types/api/master-data/supplier'; import { Supplier } from '@/types/api/master-data/supplier';
import { Warehouse } from '@/types/api/master-data/warehouse'; import { Warehouse } from '@/types/api/master-data/warehouse';
import { Product } from '@/types/api/master-data/product'; import { Product } from '@/types/api/master-data/product';
import { ProductWarehouse } from '@/types/api/inventory/product-warehouse'; import { ProductWarehouse } from '@/types/api/inventory/product-warehouse';
import { Area } from '@/types/api/master-data/area'; import { Area } from '@/types/api/master-data/area';
import { Location } from '@/types/api/master-data/location'; import { Location } from '@/types/api/master-data/location';
import { Uom } from '@/types/api/master-data/uom';
export type PurchaseItemProduct = { export type PurchaseItemProduct = {
id: number; id: number;
@@ -12,14 +17,15 @@ export type PurchaseItemProduct = {
flags?: string[]; flags?: string[];
ProductPrice?: number; ProductPrice?: number;
SellingPrice?: number; SellingPrice?: number;
uom?: { uom: Uom;
name: string;
};
product_category?: product_category?:
| { | {
id: number;
name: string; name: string;
code: string;
} }
| string; | string;
suppliers?: Supplier[];
}; };
export type PurchaseItem = { export type PurchaseItem = {
@@ -69,6 +75,10 @@ export type BasePurchase = {
warehouse?: Warehouse; warehouse?: Warehouse;
items?: PurchaseItem[]; items?: PurchaseItem[];
latest_approval?: BaseApproval; latest_approval?: BaseApproval;
requester_name?: string;
po_expedition?: string[];
created_user?: CreatedUser;
products?: PurchaseItemProduct[];
}; };
export type Purchase = BaseMetadata & BasePurchase; export type Purchase = BaseMetadata & BasePurchase;