mirror of
https://gitlab.com/mbugroup/lti-web-client.git
synced 2026-05-24 15:25:46 +00:00
Merge branch 'staging' into 'production'
Staging See merge request mbugroup/lti-web-client!316
This commit is contained in:
@@ -68,6 +68,8 @@
|
|||||||
|
|
||||||
--shadow-button-soft:
|
--shadow-button-soft:
|
||||||
0 3px 2px -2px var(--color-base-200), 0 4px 3px -2px var(--color-base-200);
|
0 3px 2px -2px var(--color-base-200), 0 4px 3px -2px var(--color-base-200);
|
||||||
|
|
||||||
|
--shadow-bg: 0px -2px 4px 0px #00000014;
|
||||||
}
|
}
|
||||||
|
|
||||||
html {
|
html {
|
||||||
|
|||||||
@@ -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;
|
|
||||||
@@ -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,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;
|
|
||||||
@@ -1,9 +1,14 @@
|
|||||||
|
import DeliveryOrderFormModal from '@/components/pages/marketing/DeliveryOrderFormModal';
|
||||||
import MarketingTable from '@/components/pages/marketing/MarketingTable';
|
import MarketingTable from '@/components/pages/marketing/MarketingTable';
|
||||||
|
import SalesOrderFormModal from '@/components/pages/marketing/SalesOrderFormModal';
|
||||||
|
|
||||||
const Marketing = () => {
|
const Marketing = () => {
|
||||||
return (
|
return (
|
||||||
<div className='w-full p-4'>
|
<div className='w-full'>
|
||||||
<MarketingTable />
|
<MarketingTable />
|
||||||
|
|
||||||
|
<SalesOrderFormModal />
|
||||||
|
<DeliveryOrderFormModal />
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -0,0 +1,5 @@
|
|||||||
|
import PageNotFound from '@/components/helper/NotFoundPage';
|
||||||
|
|
||||||
|
export default function NotFound() {
|
||||||
|
return <PageNotFound />;
|
||||||
|
}
|
||||||
@@ -50,5 +50,3 @@ const ProjectFlockDetailPage = () => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
export default ProjectFlockDetailPage;
|
export default ProjectFlockDetailPage;
|
||||||
ProjectFlockDetail;
|
|
||||||
ProjectFlockDetail;
|
|
||||||
|
|||||||
@@ -1,10 +1,10 @@
|
|||||||
'use client';
|
'use client';
|
||||||
|
|
||||||
import { usePathname, useRouter } from 'next/navigation';
|
import { usePathname, useRouter } from 'next/navigation';
|
||||||
import Drawer from '@/components/Drawer';
|
import React, { ReactNode, useEffect } from 'react';
|
||||||
import React, { ReactNode } from 'react';
|
|
||||||
import ProjectFlockTable from '@/components/pages/production/project-flock/ProjectFlockTable';
|
import ProjectFlockTable from '@/components/pages/production/project-flock/ProjectFlockTable';
|
||||||
import { useUiStore } from '@/stores/ui/ui.store';
|
import { useUiStore } from '@/stores/ui/ui.store';
|
||||||
|
import Modal, { useModal } from '@/components/Modal';
|
||||||
|
|
||||||
export default function ProjectFlockLayout({
|
export default function ProjectFlockLayout({
|
||||||
children,
|
children,
|
||||||
@@ -23,9 +23,12 @@ export default function ProjectFlockLayout({
|
|||||||
|
|
||||||
const isOpen = isAdd || isEdit || isDetail || isChickin || isClosing;
|
const isOpen = isAdd || isEdit || isDetail || isChickin || isClosing;
|
||||||
|
|
||||||
|
const formModal = useModal();
|
||||||
|
|
||||||
const handleBackdropClick = () => {
|
const handleBackdropClick = () => {
|
||||||
const unsub = useUiStore.getState().subscribeIsValid((isValid) => {
|
const unsub = useUiStore.getState().subscribeIsValid((isValid) => {
|
||||||
if (isValid) {
|
if (isValid) {
|
||||||
|
formModal.closeModal();
|
||||||
unsub(); // berhenti listen
|
unsub(); // berhenti listen
|
||||||
router.push('/production/project-flock');
|
router.push('/production/project-flock');
|
||||||
}
|
}
|
||||||
@@ -34,6 +37,14 @@ export default function ProjectFlockLayout({
|
|||||||
toggleValidate();
|
toggleValidate();
|
||||||
};
|
};
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (isOpen && !formModal.open) {
|
||||||
|
formModal.openModal();
|
||||||
|
} else {
|
||||||
|
formModal.closeModal();
|
||||||
|
}
|
||||||
|
}, [isOpen]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
{/* List page always rendered */}
|
{/* List page always rendered */}
|
||||||
@@ -43,18 +54,19 @@ export default function ProjectFlockLayout({
|
|||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Render Drawer only on /add */}
|
{/* Render Modal only on /add */}
|
||||||
<Drawer
|
<Modal
|
||||||
open={isOpen}
|
ref={formModal.ref}
|
||||||
setOpen={(v) => {
|
position='end'
|
||||||
if (!v) router.push('/production/project-flock');
|
|
||||||
}}
|
|
||||||
closeOnBackdropClick={isDetail ? true : false}
|
|
||||||
onBackdropClick={handleBackdropClick}
|
onBackdropClick={handleBackdropClick}
|
||||||
variant='right'
|
className={{
|
||||||
zIndex='99999'
|
modalBox: 'w-full sm:w-fit p-3 rounded-xl bg-transparent shadow-none',
|
||||||
sidebarContent={isOpen && <div className=''>{children}</div>}
|
}}
|
||||||
/>
|
>
|
||||||
|
<div className='w-full sm:w-[446px] h-full flex flex-col sm:flex-row items-stretch bg-base-100 rounded-xl overflow-hidden'>
|
||||||
|
{isOpen && children}
|
||||||
|
</div>
|
||||||
|
</Modal>
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,15 +1,16 @@
|
|||||||
import { ReactNode } from 'react';
|
import { ReactNode, Ref } from 'react';
|
||||||
|
|
||||||
import { cn } from '@/lib/helper';
|
import { cn } from '@/lib/helper';
|
||||||
|
|
||||||
interface AlertProps {
|
interface AlertProps {
|
||||||
|
ref?: Ref<HTMLDivElement> | undefined;
|
||||||
variant?: 'outline' | 'dash' | 'soft';
|
variant?: 'outline' | 'dash' | 'soft';
|
||||||
color?: 'info' | 'success' | 'warning' | 'error';
|
color?: 'info' | 'success' | 'warning' | 'error';
|
||||||
children?: ReactNode;
|
children?: ReactNode;
|
||||||
className?: string;
|
className?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
const Alert = ({ children, variant, color, className }: AlertProps) => {
|
const Alert = ({ children, ref, variant, color, className }: AlertProps) => {
|
||||||
const alertBaseClassName = cn('alert', {
|
const alertBaseClassName = cn('alert', {
|
||||||
'alert-soft': variant === 'soft',
|
'alert-soft': variant === 'soft',
|
||||||
'alert-outline': variant === 'outline',
|
'alert-outline': variant === 'outline',
|
||||||
@@ -21,7 +22,11 @@ const Alert = ({ children, variant, color, className }: AlertProps) => {
|
|||||||
'alert-error': color === 'error',
|
'alert-error': color === 'error',
|
||||||
});
|
});
|
||||||
|
|
||||||
return <div className={cn(alertBaseClassName, className)}>{children}</div>;
|
return (
|
||||||
|
<div ref={ref} className={cn(alertBaseClassName, className)}>
|
||||||
|
{children}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
export default Alert;
|
export default Alert;
|
||||||
|
|||||||
@@ -74,6 +74,8 @@ const MainDrawer = ({
|
|||||||
|
|
||||||
const formattedPathname = pathname.endsWith('/') ? pathname : `${pathname}/`;
|
const formattedPathname = pathname.endsWith('/') ? pathname : `${pathname}/`;
|
||||||
|
|
||||||
|
const isPathnameNotFoundPage = formattedPathname === '/404/';
|
||||||
|
|
||||||
const isPermitted = ROUTE_PERMISSIONS[formattedPathname]?.some((permission) =>
|
const isPermitted = ROUTE_PERMISSIONS[formattedPathname]?.some((permission) =>
|
||||||
permissionCheck(permission)
|
permissionCheck(permission)
|
||||||
);
|
);
|
||||||
@@ -82,10 +84,14 @@ const MainDrawer = ({
|
|||||||
setMainDrawerOpen(!mainDrawerOpen);
|
setMainDrawerOpen(!mainDrawerOpen);
|
||||||
};
|
};
|
||||||
|
|
||||||
if (!isPermitted) {
|
if (!isPermitted && !isPathnameNotFoundPage) {
|
||||||
return <PermissionNotFound />;
|
return <PermissionNotFound />;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (isPathnameNotFoundPage) {
|
||||||
|
return children;
|
||||||
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Drawer
|
<Drawer
|
||||||
open={mainDrawerOpen}
|
open={mainDrawerOpen}
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ import Button from '@/components/Button';
|
|||||||
import { cn, formatDate } from '@/lib/helper';
|
import { cn, formatDate } from '@/lib/helper';
|
||||||
|
|
||||||
interface ApprovalStepsV2Props {
|
interface ApprovalStepsV2Props {
|
||||||
|
title?: string;
|
||||||
approvals?: BaseApproval[];
|
approvals?: BaseApproval[];
|
||||||
steps: {
|
steps: {
|
||||||
step_number: number;
|
step_number: number;
|
||||||
@@ -23,6 +24,7 @@ interface ApprovalStepsV2Props {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const ApprovalStepsV2 = ({
|
const ApprovalStepsV2 = ({
|
||||||
|
title = 'Progress Details',
|
||||||
approvals,
|
approvals,
|
||||||
steps,
|
steps,
|
||||||
maxVisibleSteps = 2,
|
maxVisibleSteps = 2,
|
||||||
@@ -99,7 +101,7 @@ const ApprovalStepsV2 = ({
|
|||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
<h4 className='text-base font-medium text-base-content/50 font-roboto'>
|
<h4 className='text-base font-medium text-base-content/50 font-roboto'>
|
||||||
Progress Details
|
{title}
|
||||||
</h4>
|
</h4>
|
||||||
|
|
||||||
<div
|
<div
|
||||||
|
|||||||
@@ -0,0 +1,17 @@
|
|||||||
|
import Button from '@/components/Button';
|
||||||
|
|
||||||
|
const PageNotFound = () => {
|
||||||
|
return (
|
||||||
|
<div className='w-full h-full flex-1 flex flex-col justify-center items-center gap-4'>
|
||||||
|
<h2 className='text-2xl font-bold text-error'>Halaman Tidak Ditemukan</h2>
|
||||||
|
<p className='text-gray-600 text-center'>
|
||||||
|
Halaman atau data yang anda cari tidak ditemukan.
|
||||||
|
</p>
|
||||||
|
<Button href='/dashboard' className='text-base-100'>
|
||||||
|
Kembali ke Dashboard
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default PageNotFound;
|
||||||
@@ -1,24 +1,30 @@
|
|||||||
|
import { ReactNode } from 'react';
|
||||||
|
|
||||||
import Badge from '@/components/Badge';
|
import Badge from '@/components/Badge';
|
||||||
|
|
||||||
import { cn } from '@/lib/helper';
|
import { cn } from '@/lib/helper';
|
||||||
import { Color } from '@/types/theme';
|
import { Color } from '@/types/theme';
|
||||||
|
|
||||||
interface StatusBadgeProps {
|
interface StatusBadgeProps {
|
||||||
color: Color;
|
color: Color;
|
||||||
text: string;
|
text: ReactNode;
|
||||||
className?: {
|
className?: {
|
||||||
badge?: string;
|
badge?: string;
|
||||||
status?: string;
|
status?: string;
|
||||||
};
|
};
|
||||||
|
onClick?: () => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
const StatusBadge = ({
|
const StatusBadge = ({
|
||||||
color = 'neutral',
|
color = 'neutral',
|
||||||
text,
|
text,
|
||||||
className,
|
className,
|
||||||
|
onClick,
|
||||||
}: StatusBadgeProps) => {
|
}: StatusBadgeProps) => {
|
||||||
return (
|
return (
|
||||||
<Badge
|
<Badge
|
||||||
variant='soft'
|
variant='soft'
|
||||||
|
onClick={onClick}
|
||||||
className={{
|
className={{
|
||||||
badge: cn(
|
badge: cn(
|
||||||
'px-2 py-1 w-full flex flex-row justify-start gap-1 rounded-lg border border-base-content/10 text-xs font-medium text-base-content',
|
'px-2 py-1 w-full flex flex-row justify-start gap-1 rounded-lg border border-base-content/10 text-xs font-medium text-base-content',
|
||||||
@@ -28,6 +34,7 @@ const StatusBadge = ({
|
|||||||
'bg-error/20': color === 'error',
|
'bg-error/20': color === 'error',
|
||||||
'bg-primary/20': color === 'info',
|
'bg-primary/20': color === 'info',
|
||||||
'bg-[#FF9A20]/12': color === 'warning',
|
'bg-[#FF9A20]/12': color === 'warning',
|
||||||
|
'bg-[#1166EF]/12': color === 'primary',
|
||||||
},
|
},
|
||||||
className?.badge
|
className?.badge
|
||||||
),
|
),
|
||||||
@@ -45,6 +52,7 @@ const StatusBadge = ({
|
|||||||
'text-error': color === 'error',
|
'text-error': color === 'error',
|
||||||
'text-primary': color === 'info',
|
'text-primary': color === 'info',
|
||||||
'text-[#FF9A20]': color === 'warning',
|
'text-[#FF9A20]': color === 'warning',
|
||||||
|
'text-[#1166EF]': color === 'primary',
|
||||||
})}
|
})}
|
||||||
>
|
>
|
||||||
<circle r='6' cx='6' cy='6' fill='currentColor' />
|
<circle r='6' cx='6' cy='6' fill='currentColor' />
|
||||||
|
|||||||
@@ -27,7 +27,7 @@ export interface DrawerHeaderProps {
|
|||||||
|
|
||||||
const DrawerHeader = ({
|
const DrawerHeader = ({
|
||||||
leftIcon = 'mdi:close',
|
leftIcon = 'mdi:close',
|
||||||
leftIconSize = 24,
|
leftIconSize = 20,
|
||||||
leftIconHref,
|
leftIconHref,
|
||||||
leftIconOnClick,
|
leftIconOnClick,
|
||||||
leftIconClassName,
|
leftIconClassName,
|
||||||
@@ -43,7 +43,7 @@ const DrawerHeader = ({
|
|||||||
icon={leftIcon}
|
icon={leftIcon}
|
||||||
width={leftIconSize}
|
width={leftIconSize}
|
||||||
height={leftIconSize}
|
height={leftIconSize}
|
||||||
className={cn('cursor-pointer', leftIconClassName)}
|
className={cn('cursor-pointer text-base-content ', leftIconClassName)}
|
||||||
/>
|
/>
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -73,7 +73,7 @@ const DrawerHeader = ({
|
|||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
className={cn(
|
className={cn(
|
||||||
'flex flex-row justify-between items-center px-4 pt-4 pb-4 border-b border-base-content/10',
|
'flex flex-row justify-between items-center p-4 border-b border-base-content/10',
|
||||||
className
|
className
|
||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
@@ -82,7 +82,7 @@ const DrawerHeader = ({
|
|||||||
{renderLeftIcon()}
|
{renderLeftIcon()}
|
||||||
|
|
||||||
{showDivider && subtitle && (
|
{showDivider && subtitle && (
|
||||||
<div className='divider divider-horizontal p-0 m-0'></div>
|
<div className='w-px h-full border-none bg-base-content/10' />
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{subtitle && (
|
{subtitle && (
|
||||||
|
|||||||
@@ -1,7 +1,10 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
import Alert from '@/components/Alert';
|
import Alert from '@/components/Alert';
|
||||||
import Button from '@/components/Button';
|
import Button from '@/components/Button';
|
||||||
|
import { cn } from '@/lib/helper';
|
||||||
import { Icon } from '@iconify/react';
|
import { Icon } from '@iconify/react';
|
||||||
import { useState } from 'react';
|
import { useEffect, useRef } from 'react';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Alert Unique Error List
|
* Alert Unique Error List
|
||||||
@@ -10,34 +13,81 @@ import { useState } from 'react';
|
|||||||
*/
|
*/
|
||||||
const AlertErrorList = ({
|
const AlertErrorList = ({
|
||||||
formErrorList,
|
formErrorList,
|
||||||
|
className,
|
||||||
onClose,
|
onClose,
|
||||||
|
title,
|
||||||
}: {
|
}: {
|
||||||
formErrorList: string[];
|
formErrorList: string[];
|
||||||
|
className?: {
|
||||||
|
alert?: string;
|
||||||
|
button?: string;
|
||||||
|
headerWrapper?: string;
|
||||||
|
headerIcon?: string;
|
||||||
|
headerText?: string;
|
||||||
|
titleWrapper?: string;
|
||||||
|
ul?: string;
|
||||||
|
li?: string;
|
||||||
|
};
|
||||||
onClose: () => void;
|
onClose: () => void;
|
||||||
|
title?: string;
|
||||||
}) => {
|
}) => {
|
||||||
|
const alertRef = useRef<HTMLDivElement | null>(null);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (formErrorList.length > 0) {
|
||||||
|
alertRef.current?.scrollIntoView({
|
||||||
|
behavior: 'smooth',
|
||||||
|
block: 'start',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}, [formErrorList.length]);
|
||||||
|
|
||||||
if (formErrorList.length === 0) return null;
|
if (formErrorList.length === 0) return null;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Alert color='error' className='w-full flex flex-col gap-2 px-4'>
|
<Alert
|
||||||
<div className='flex justify-between items-center gap-2 w-full'>
|
ref={alertRef}
|
||||||
<div className='flex items-center gap-2'>
|
color='error'
|
||||||
<Icon icon='material-symbols:error-outline' width={24} height={24} />
|
className={cn(
|
||||||
<span className='font-semibold'>
|
'w-full flex flex-col gap-2 px-3 rounded-lg',
|
||||||
Terdapat {formErrorList.length} error pada form:
|
className?.alert
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
<div
|
||||||
|
className={cn(
|
||||||
|
'flex justify-between items-center gap-2 w-full',
|
||||||
|
className?.headerWrapper
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
<div className={cn('flex items-center gap-2', className?.titleWrapper)}>
|
||||||
|
<Icon
|
||||||
|
icon='material-symbols:error-outline'
|
||||||
|
className={cn(className?.headerIcon)}
|
||||||
|
width={20}
|
||||||
|
height={20}
|
||||||
|
/>
|
||||||
|
<span className={cn('font-semibold text-sm', className?.headerText)}>
|
||||||
|
{title || `Terdapat ${formErrorList.length} error pada form:`}
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
<Button
|
<Button
|
||||||
|
type='button'
|
||||||
onClick={onClose}
|
onClick={onClose}
|
||||||
variant='link'
|
variant='link'
|
||||||
className='ml-auto p-0 w-fit text-white'
|
className={cn('ml-auto p-0 w-fit text-white', className?.button)}
|
||||||
color='none'
|
color='none'
|
||||||
>
|
>
|
||||||
<Icon icon='material-symbols:close' width={24} height={24} />
|
<Icon icon='material-symbols:close' width={20} height={20} />
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
<ul className='list-disc list-inside pl-8 space-y-1 w-full'>
|
<ul
|
||||||
|
className={cn(
|
||||||
|
'list-disc list-inside pl-4 space-y-1.5 w-full',
|
||||||
|
className?.ul
|
||||||
|
)}
|
||||||
|
>
|
||||||
{formErrorList.map((error, index) => (
|
{formErrorList.map((error, index) => (
|
||||||
<li key={index} className='text-sm'>
|
<li key={index} className={cn('text-sm', className?.li)}>
|
||||||
{error}
|
{error}
|
||||||
</li>
|
</li>
|
||||||
))}
|
))}
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ import TextArea, { TextAreaProps } from '@/components/input/TextArea';
|
|||||||
|
|
||||||
interface DebouncedTextAreaProps extends TextAreaProps {
|
interface DebouncedTextAreaProps extends TextAreaProps {
|
||||||
delay?: number;
|
delay?: number;
|
||||||
|
ref?: React.RefObject<HTMLTextAreaElement | null>;
|
||||||
}
|
}
|
||||||
|
|
||||||
const DebouncedTextArea = (props: DebouncedTextAreaProps) => {
|
const DebouncedTextArea = (props: DebouncedTextAreaProps) => {
|
||||||
@@ -19,6 +20,11 @@ const DebouncedTextArea = (props: DebouncedTextAreaProps) => {
|
|||||||
const [debouncedChangeEvent] = useDebounce(internalChangeEvent, delay ?? 300);
|
const [debouncedChangeEvent] = useDebounce(internalChangeEvent, delay ?? 300);
|
||||||
const [debouncedValue] = useDebounce(internalValue, delay ?? 300);
|
const [debouncedValue] = useDebounce(internalValue, delay ?? 300);
|
||||||
|
|
||||||
|
// Sync internal value with external props.value when it changes (e.g., form reset)
|
||||||
|
useEffect(() => {
|
||||||
|
setInternalValue(props.value);
|
||||||
|
}, [props.value]);
|
||||||
|
|
||||||
const internalChangeHandler: ChangeEventHandler<HTMLTextAreaElement> = (
|
const internalChangeHandler: ChangeEventHandler<HTMLTextAreaElement> = (
|
||||||
e
|
e
|
||||||
) => {
|
) => {
|
||||||
@@ -35,6 +41,7 @@ const DebouncedTextArea = (props: DebouncedTextAreaProps) => {
|
|||||||
return (
|
return (
|
||||||
<TextArea
|
<TextArea
|
||||||
{...props}
|
{...props}
|
||||||
|
ref={props.ref}
|
||||||
value={internalValue}
|
value={internalValue}
|
||||||
onChange={internalChangeHandler}
|
onChange={internalChangeHandler}
|
||||||
/>
|
/>
|
||||||
|
|||||||
@@ -28,6 +28,7 @@ export interface TextAreaProps {
|
|||||||
onChange?: ChangeEventHandler<HTMLTextAreaElement>;
|
onChange?: ChangeEventHandler<HTMLTextAreaElement>;
|
||||||
onBlur?: FocusEventHandler<HTMLTextAreaElement>;
|
onBlur?: FocusEventHandler<HTMLTextAreaElement>;
|
||||||
rows?: number;
|
rows?: number;
|
||||||
|
ref?: React.RefObject<HTMLTextAreaElement | null>;
|
||||||
}
|
}
|
||||||
|
|
||||||
const TextArea = ({
|
const TextArea = ({
|
||||||
@@ -49,6 +50,7 @@ const TextArea = ({
|
|||||||
readOnly = false,
|
readOnly = false,
|
||||||
isLoading = false,
|
isLoading = false,
|
||||||
rows = 3,
|
rows = 3,
|
||||||
|
ref,
|
||||||
}: TextAreaProps) => {
|
}: TextAreaProps) => {
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
@@ -99,6 +101,7 @@ const TextArea = ({
|
|||||||
onBlur={onBlur}
|
onBlur={onBlur}
|
||||||
disabled={disabled}
|
disabled={disabled}
|
||||||
readOnly={readOnly}
|
readOnly={readOnly}
|
||||||
|
ref={ref}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
{(isLoading || endAdornment) && (
|
{(isLoading || endAdornment) && (
|
||||||
|
|||||||
@@ -122,10 +122,18 @@ const ConfirmationModal = ({
|
|||||||
closeOnBackdrop={closeOnBackdrop}
|
closeOnBackdrop={closeOnBackdrop}
|
||||||
className={{
|
className={{
|
||||||
...className,
|
...className,
|
||||||
modalBox: cn('rounded-xl p-4', className?.modalBox),
|
modalBox: cn(
|
||||||
|
'rounded-xl p-4 flex flex-col gap-4 max-h-[90vh]',
|
||||||
|
className?.modalBox
|
||||||
|
),
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<div className='w-full flex flex-col gap-4'>
|
<div
|
||||||
|
className={cn(
|
||||||
|
'flex flex-col gap-4',
|
||||||
|
children && 'sticky top-0 bg-inherit z-10'
|
||||||
|
)}
|
||||||
|
>
|
||||||
{iconPosition === 'center' ? (
|
{iconPosition === 'center' ? (
|
||||||
<>
|
<>
|
||||||
<div className='w-fit mx-auto'>
|
<div className='w-fit mx-auto'>
|
||||||
@@ -164,71 +172,74 @@ const ConfirmationModal = ({
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
{children && <div className='w-full'>{children}</div>}
|
{children && (
|
||||||
|
<div className='w-full flex-1 overflow-y-auto'>{children}</div>
|
||||||
|
)}
|
||||||
|
|
||||||
{(secondaryButton || primaryButton) && (
|
{(secondaryButton || primaryButton) && (
|
||||||
<div
|
<div
|
||||||
className={cn('w-full grid gap-3', {
|
className={cn(
|
||||||
|
'w-full grid gap-3',
|
||||||
|
children && 'sticky bottom-0 bg-inherit z-10',
|
||||||
|
{
|
||||||
'grid-cols-2': secondaryButton && primaryButton,
|
'grid-cols-2': secondaryButton && primaryButton,
|
||||||
'grid-cols-1':
|
'grid-cols-1':
|
||||||
(secondaryButton && !primaryButton) ||
|
(secondaryButton && !primaryButton) ||
|
||||||
(!secondaryButton && primaryButton),
|
(!secondaryButton && primaryButton),
|
||||||
})}
|
}
|
||||||
>
|
)}
|
||||||
{secondaryButton && secondaryButton.text && (
|
>
|
||||||
<Button
|
{secondaryButton && secondaryButton.text && (
|
||||||
{...secondaryButton}
|
<Button
|
||||||
variant='outline'
|
{...secondaryButton}
|
||||||
color={secondaryButton?.color}
|
variant='outline'
|
||||||
isLoading={secondaryButton?.isLoading}
|
color={secondaryButton?.color}
|
||||||
disabled={
|
isLoading={secondaryButton?.isLoading}
|
||||||
secondaryButton?.isLoading !== undefined
|
disabled={
|
||||||
? secondaryButton?.isLoading
|
secondaryButton?.isLoading !== undefined
|
||||||
: isPrimaryButtonLoading
|
? secondaryButton?.isLoading
|
||||||
|
: isPrimaryButtonLoading
|
||||||
|
}
|
||||||
|
onClick={(e) => {
|
||||||
|
if (secondaryButton?.onClick) {
|
||||||
|
secondaryButton.onClick(e);
|
||||||
|
} else {
|
||||||
|
closeModalHandler();
|
||||||
}
|
}
|
||||||
onClick={(e) => {
|
}}
|
||||||
if (secondaryButton?.onClick) {
|
className={cn(
|
||||||
secondaryButton.onClick(e);
|
'p-2 rounded-xl text-sm',
|
||||||
} else {
|
secondaryButton?.className
|
||||||
closeModalHandler();
|
)}
|
||||||
}
|
>
|
||||||
}}
|
{secondaryButton?.text ?? 'Tidak'}
|
||||||
className={cn(
|
</Button>
|
||||||
'p-2 rounded-xl text-sm',
|
)}
|
||||||
secondaryButton?.className
|
|
||||||
)}
|
|
||||||
>
|
|
||||||
{secondaryButton?.text ?? 'Tidak'}
|
|
||||||
</Button>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{primaryButton && primaryButton.text && (
|
{primaryButton && primaryButton.text && (
|
||||||
<Button
|
<Button
|
||||||
{...primaryButton}
|
{...primaryButton}
|
||||||
color={primaryButton?.color ?? 'info'}
|
color={primaryButton?.color ?? 'info'}
|
||||||
onClick={primaryButtonClickHandler}
|
onClick={primaryButtonClickHandler}
|
||||||
isLoading={
|
isLoading={
|
||||||
primaryButton?.isLoading !== undefined
|
primaryButton?.isLoading !== undefined
|
||||||
? primaryButton?.isLoading
|
? primaryButton?.isLoading
|
||||||
: isPrimaryButtonLoading
|
: isPrimaryButtonLoading
|
||||||
}
|
}
|
||||||
disabled={
|
disabled={
|
||||||
primaryButton?.isLoading !== undefined
|
primaryButton?.isLoading !== undefined
|
||||||
? primaryButton?.isLoading
|
? primaryButton?.isLoading
|
||||||
: isPrimaryButtonLoading
|
: isPrimaryButtonLoading
|
||||||
}
|
}
|
||||||
className={cn(
|
className={cn('p-2 rounded-xl text-sm', primaryButton?.className)}
|
||||||
'p-2 rounded-xl text-sm',
|
>
|
||||||
primaryButton?.className
|
{primaryButton?.text ?? 'Ya'}
|
||||||
)}
|
</Button>
|
||||||
>
|
)}
|
||||||
{primaryButton?.text ?? 'Ya'}
|
</div>
|
||||||
</Button>
|
)}
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</Modal>
|
</Modal>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ interface ConfirmationModalWithNotesProps
|
|||||||
extends Omit<ConfirmationModalProps, 'children' | 'primaryButton'> {
|
extends Omit<ConfirmationModalProps, 'children' | 'primaryButton'> {
|
||||||
rows?: number;
|
rows?: number;
|
||||||
placeholder?: string;
|
placeholder?: string;
|
||||||
|
onClose?: () => void;
|
||||||
|
|
||||||
primaryButton?: {
|
primaryButton?: {
|
||||||
text?: string;
|
text?: string;
|
||||||
@@ -32,6 +33,7 @@ const ConfirmationModalWithNotes: React.FC<ConfirmationModalWithNotesProps> = ({
|
|||||||
className,
|
className,
|
||||||
rows = 3,
|
rows = 3,
|
||||||
placeholder = 'Catatan...',
|
placeholder = 'Catatan...',
|
||||||
|
onClose,
|
||||||
...props
|
...props
|
||||||
}) => {
|
}) => {
|
||||||
const randomId = useId();
|
const randomId = useId();
|
||||||
@@ -41,6 +43,11 @@ const ConfirmationModalWithNotes: React.FC<ConfirmationModalWithNotesProps> = ({
|
|||||||
setNotes(e.target.value);
|
setNotes(e.target.value);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const closeModalHandler = () => {
|
||||||
|
onClose?.();
|
||||||
|
ref.current?.close();
|
||||||
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<ConfirmationModal
|
<ConfirmationModal
|
||||||
ref={ref}
|
ref={ref}
|
||||||
@@ -49,12 +56,32 @@ const ConfirmationModalWithNotes: React.FC<ConfirmationModalWithNotesProps> = ({
|
|||||||
closeOnBackdrop={closeOnBackdrop}
|
closeOnBackdrop={closeOnBackdrop}
|
||||||
primaryButton={{
|
primaryButton={{
|
||||||
...primaryButton,
|
...primaryButton,
|
||||||
onClick: () => {
|
onClick: (e) => {
|
||||||
primaryButton?.onClick?.(notes);
|
if (primaryButton && primaryButton?.onClick) {
|
||||||
|
primaryButton?.onClick?.(notes);
|
||||||
|
} else {
|
||||||
|
closeModalHandler();
|
||||||
|
}
|
||||||
|
|
||||||
setNotes('');
|
setNotes('');
|
||||||
},
|
},
|
||||||
}}
|
}}
|
||||||
secondaryButton={secondaryButton}
|
secondaryButton={
|
||||||
|
secondaryButton
|
||||||
|
? {
|
||||||
|
text: secondaryButton?.text ?? 'Tidak',
|
||||||
|
onClick: (e) => {
|
||||||
|
if (secondaryButton && secondaryButton?.onClick) {
|
||||||
|
secondaryButton.onClick?.(e);
|
||||||
|
} else {
|
||||||
|
closeModalHandler();
|
||||||
|
}
|
||||||
|
|
||||||
|
setNotes('');
|
||||||
|
},
|
||||||
|
}
|
||||||
|
: undefined
|
||||||
|
}
|
||||||
className={className}
|
className={className}
|
||||||
{...props}
|
{...props}
|
||||||
>
|
>
|
||||||
|
|||||||
@@ -309,9 +309,10 @@ const useApprovalSteps = ({
|
|||||||
moduleId: string;
|
moduleId: string;
|
||||||
params?: {
|
params?: {
|
||||||
page?: number;
|
page?: number;
|
||||||
limit: number | string;
|
limit?: number | string;
|
||||||
search?: string;
|
search?: string;
|
||||||
group_step_number?: boolean;
|
group_step_number?: boolean;
|
||||||
|
order_by_date?: 'ASC' | 'DESC';
|
||||||
};
|
};
|
||||||
}) => {
|
}) => {
|
||||||
// Membuat URL Parameters
|
// Membuat URL Parameters
|
||||||
@@ -319,6 +320,8 @@ const useApprovalSteps = ({
|
|||||||
page: params?.page?.toString() || '',
|
page: params?.page?.toString() || '',
|
||||||
limit: params?.limit?.toString() || '',
|
limit: params?.limit?.toString() || '',
|
||||||
search: params?.search || '',
|
search: params?.search || '',
|
||||||
|
group_step_number: params?.group_step_number?.toString() || '',
|
||||||
|
order_by_date: params?.order_by_date || '',
|
||||||
}).toString();
|
}).toString();
|
||||||
|
|
||||||
// fetching data approvals
|
// fetching data approvals
|
||||||
|
|||||||
@@ -66,7 +66,13 @@ const ClosingDetail: React.FC<ClosingDetailProps> = ({
|
|||||||
{
|
{
|
||||||
id: 'overhead',
|
id: 'overhead',
|
||||||
label: 'Overhead',
|
label: 'Overhead',
|
||||||
content: <ClosingOverheadTabContent projectFlockId={id} />,
|
content: (
|
||||||
|
<ClosingOverheadTabContent
|
||||||
|
projectFlockId={id}
|
||||||
|
generalInformation={initialValue}
|
||||||
|
kandangData={kandangData}
|
||||||
|
/>
|
||||||
|
),
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
id: 'hppEkspedisi',
|
id: 'hppEkspedisi',
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import { formatNumber } from '@/lib/helper';
|
||||||
import { ClosingGeneralInformation } from '@/types/api/closing';
|
import { ClosingGeneralInformation } from '@/types/api/closing';
|
||||||
import { ProjectFlock } from '@/types/api/production/project-flock';
|
import { ProjectFlock } from '@/types/api/production/project-flock';
|
||||||
import { ProjectFlockKandang } from '@/types/api/production/project-flock-kandang';
|
import { ProjectFlockKandang } from '@/types/api/production/project-flock-kandang';
|
||||||
@@ -56,8 +57,8 @@ const ClosingGeneralInformationTable = ({
|
|||||||
<td>:</td>
|
<td>:</td>
|
||||||
<td>
|
<td>
|
||||||
{!kandangData
|
{!kandangData
|
||||||
? (initialValue?.population ?? 0)
|
? formatNumber(initialValue?.population || 0)
|
||||||
: (chickinPopulation ?? 0)}{' '}
|
: formatNumber(chickinPopulation || 0)}{' '}
|
||||||
Ekor
|
Ekor
|
||||||
</td>
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
|
|||||||
@@ -48,10 +48,7 @@ const ClosingIncomingSapronaksTable = ({
|
|||||||
const { data: incomingSapronaks, isLoading: isLoadingIncomingSapronaks } =
|
const { data: incomingSapronaks, isLoading: isLoadingIncomingSapronaks } =
|
||||||
useSWR(
|
useSWR(
|
||||||
`${ClosingApi.basePath}/${projectFlockId}/sapronak${getTableFilterQueryString()}&type=incoming&kandang_id=${kandangId ? `${kandangId}` : ''}`,
|
`${ClosingApi.basePath}/${projectFlockId}/sapronak${getTableFilterQueryString()}&type=incoming&kandang_id=${kandangId ? `${kandangId}` : ''}`,
|
||||||
ClosingApi.getAllIncomingSapronakFetcher,
|
ClosingApi.getAllIncomingSapronakFetcher
|
||||||
{
|
|
||||||
keepPreviousData: true,
|
|
||||||
}
|
|
||||||
);
|
);
|
||||||
|
|
||||||
const [open, setOpen] = useState(true);
|
const [open, setOpen] = useState(true);
|
||||||
|
|||||||
@@ -48,10 +48,7 @@ const ClosingOutgoingSapronaksTable = ({
|
|||||||
const { data: outgoingSapronaks, isLoading: isLoadingOutgoingSapronaks } =
|
const { data: outgoingSapronaks, isLoading: isLoadingOutgoingSapronaks } =
|
||||||
useSWR(
|
useSWR(
|
||||||
`${ClosingApi.basePath}/${projectFlockId}/sapronak${getTableFilterQueryString()}&type=outgoing&kandang_id=${kandangId ? `${kandangId}` : ''}`,
|
`${ClosingApi.basePath}/${projectFlockId}/sapronak${getTableFilterQueryString()}&type=outgoing&kandang_id=${kandangId ? `${kandangId}` : ''}`,
|
||||||
ClosingApi.getAllOutgoingSapronakFetcher,
|
ClosingApi.getAllOutgoingSapronakFetcher
|
||||||
{
|
|
||||||
keepPreviousData: true,
|
|
||||||
}
|
|
||||||
);
|
);
|
||||||
|
|
||||||
const [open, setOpen] = useState(true);
|
const [open, setOpen] = useState(true);
|
||||||
|
|||||||
@@ -1,16 +1,26 @@
|
|||||||
import ClosingOverheadTable from '@/components/pages/closing/ClosingOverheadTable';
|
import ClosingOverheadTable from '@/components/pages/closing/ClosingOverheadTable';
|
||||||
|
import { ClosingGeneralInformation } from '@/types/api/closing';
|
||||||
|
import { ProjectFlockKandang } from '@/types/api/production/project-flock-kandang';
|
||||||
|
|
||||||
interface ClosingOverheadTabContentProps {
|
interface ClosingOverheadTabContentProps {
|
||||||
projectFlockId: number;
|
projectFlockId: number;
|
||||||
|
generalInformation?: ClosingGeneralInformation;
|
||||||
|
kandangData?: ProjectFlockKandang;
|
||||||
}
|
}
|
||||||
|
|
||||||
const ClosingOverheadTabContent = ({
|
const ClosingOverheadTabContent = ({
|
||||||
projectFlockId,
|
projectFlockId,
|
||||||
|
generalInformation,
|
||||||
|
kandangData,
|
||||||
}: ClosingOverheadTabContentProps) => {
|
}: ClosingOverheadTabContentProps) => {
|
||||||
return (
|
return (
|
||||||
<div className='flex flex-col gap-4'>
|
<div className='flex flex-col gap-4'>
|
||||||
{projectFlockId && (
|
{projectFlockId && (
|
||||||
<ClosingOverheadTable projectFlockId={projectFlockId} />
|
<ClosingOverheadTable
|
||||||
|
projectFlockId={projectFlockId}
|
||||||
|
generalInformation={generalInformation}
|
||||||
|
kandangData={kandangData}
|
||||||
|
/>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -3,7 +3,13 @@ import Table, { TABLE_DEFAULT_STYLING } from '@/components/Table';
|
|||||||
import { isResponseSuccess } from '@/lib/api-helper';
|
import { isResponseSuccess } from '@/lib/api-helper';
|
||||||
import { cn, formatCurrency, formatDate, formatNumber } from '@/lib/helper';
|
import { cn, formatCurrency, formatDate, formatNumber } from '@/lib/helper';
|
||||||
import { ClosingApi } from '@/services/api/closing';
|
import { ClosingApi } from '@/services/api/closing';
|
||||||
import { Overhead, OverheadTotal } from '@/types/api/closing';
|
import {
|
||||||
|
ClosingGeneralInformation,
|
||||||
|
Overhead,
|
||||||
|
OverheadTotal,
|
||||||
|
} from '@/types/api/closing';
|
||||||
|
import { ProjectFlockKandang } from '@/types/api/production/project-flock-kandang';
|
||||||
|
import { Icon } from '@iconify/react';
|
||||||
import { ColumnDef } from '@tanstack/react-table';
|
import { ColumnDef } from '@tanstack/react-table';
|
||||||
import { useSearchParams } from 'next/navigation';
|
import { useSearchParams } from 'next/navigation';
|
||||||
import { useMemo } from 'react';
|
import { useMemo } from 'react';
|
||||||
@@ -11,16 +17,30 @@ import useSWR from 'swr';
|
|||||||
|
|
||||||
interface ClosingOverheadTableProps {
|
interface ClosingOverheadTableProps {
|
||||||
projectFlockId: number;
|
projectFlockId: number;
|
||||||
|
generalInformation?: ClosingGeneralInformation;
|
||||||
|
kandangData?: ProjectFlockKandang;
|
||||||
}
|
}
|
||||||
|
|
||||||
const ClosingOverheadTable = ({
|
const ClosingOverheadTable = ({
|
||||||
projectFlockId,
|
projectFlockId,
|
||||||
|
generalInformation,
|
||||||
|
kandangData,
|
||||||
}: ClosingOverheadTableProps) => {
|
}: ClosingOverheadTableProps) => {
|
||||||
const searchParams = useSearchParams();
|
const searchParams = useSearchParams();
|
||||||
const kandangId = searchParams.get('kandangId');
|
const kandangId = searchParams.get('kandangId');
|
||||||
|
|
||||||
const { data: overhead, isLoading: isLoadingOverhead } = useSWR(
|
const { data: overhead, isLoading: isLoadingOverhead } = useSWR(
|
||||||
`${ClosingApi.basePath}/${projectFlockId}${kandangId ? `/${kandangId}` : ''}/overhead`,
|
`${ClosingApi.basePath}/${projectFlockId}/overhead`,
|
||||||
|
() => ClosingApi.getOverhead(projectFlockId),
|
||||||
|
{
|
||||||
|
keepPreviousData: true,
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
const { data: overheadKandang, isLoading: isLoadingOverheadKandang } = useSWR(
|
||||||
|
kandangId
|
||||||
|
? `${ClosingApi.basePath}/${projectFlockId}/${kandangId}/overhead`
|
||||||
|
: undefined,
|
||||||
() =>
|
() =>
|
||||||
ClosingApi.getOverhead(
|
ClosingApi.getOverhead(
|
||||||
projectFlockId,
|
projectFlockId,
|
||||||
@@ -31,6 +51,26 @@ const ClosingOverheadTable = ({
|
|||||||
}
|
}
|
||||||
);
|
);
|
||||||
|
|
||||||
|
const chickinPopulation = useMemo(() => {
|
||||||
|
if (kandangData) {
|
||||||
|
return kandangData?.chickins?.reduce(
|
||||||
|
(acc, chickin) => acc + chickin.usage_qty,
|
||||||
|
0
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return 0;
|
||||||
|
}, [kandangData]);
|
||||||
|
|
||||||
|
const kandangTotal = useMemo(() => {
|
||||||
|
if (!isResponseSuccess(overhead)) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
const total =
|
||||||
|
((chickinPopulation ?? 0) * overhead.data.total.actual_total_amount) /
|
||||||
|
(generalInformation?.population ?? 0);
|
||||||
|
return total;
|
||||||
|
}, [overhead, chickinPopulation, generalInformation]);
|
||||||
|
|
||||||
// Helper function to create columns with footer support
|
// Helper function to create columns with footer support
|
||||||
const createColumns = (
|
const createColumns = (
|
||||||
total?: OverheadTotal,
|
total?: OverheadTotal,
|
||||||
@@ -44,29 +84,22 @@ const ClosingOverheadTable = ({
|
|||||||
{
|
{
|
||||||
id: 'budget_quantity',
|
id: 'budget_quantity',
|
||||||
header: 'Jumlah',
|
header: 'Jumlah',
|
||||||
accessorFn: (props) =>
|
accessorFn: (props) => formatNumber(props.budget_quantity),
|
||||||
props.budget_quantity ? formatNumber(props.budget_quantity) : '-',
|
|
||||||
footer: total ? () => formatNumber(total.budget_quantity) : '',
|
footer: total ? () => formatNumber(total.budget_quantity) : '',
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
id: 'budget_unit_price',
|
id: 'budget_unit_price',
|
||||||
header: 'Harga Satuan',
|
header: 'Harga Satuan',
|
||||||
accessorFn: (props) =>
|
accessorFn: (props) => formatCurrency(props.budget_unit_price),
|
||||||
props.budget_unit_price
|
|
||||||
? formatCurrency(props.budget_unit_price)
|
|
||||||
: '-',
|
|
||||||
footer: '',
|
footer: '',
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
id: 'budget_total_amount',
|
id: 'budget_total_amount',
|
||||||
header: 'Total',
|
header: 'Total',
|
||||||
accessorFn: (props) =>
|
accessorFn: (props) => formatCurrency(props.budget_total_amount),
|
||||||
props.budget_total_amount
|
|
||||||
? formatCurrency(props.budget_total_amount)
|
|
||||||
: '-',
|
|
||||||
footer: total
|
footer: total
|
||||||
? () => formatCurrency(total.budget_total_amount)
|
? () => formatCurrency(total.budget_total_amount)
|
||||||
: '',
|
: '0',
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
@@ -78,37 +111,28 @@ const ClosingOverheadTable = ({
|
|||||||
id: 'actual_date',
|
id: 'actual_date',
|
||||||
header: 'Tanggal',
|
header: 'Tanggal',
|
||||||
accessorFn: (props) =>
|
accessorFn: (props) =>
|
||||||
props.actual_date
|
formatDate(props.actual_date, 'DD MMM, YYYY'),
|
||||||
? formatDate(props.actual_date, 'DD MMM, YYYY')
|
|
||||||
: '-',
|
|
||||||
footer: '',
|
footer: '',
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
id: 'actual_quantity',
|
id: 'actual_quantity',
|
||||||
header: 'Jumlah',
|
header: 'Jumlah',
|
||||||
accessorFn: (props) =>
|
accessorFn: (props) => formatNumber(props.actual_quantity),
|
||||||
props.actual_quantity ? formatNumber(props.actual_quantity) : '-',
|
footer: total ? () => formatNumber(total.actual_quantity) : '0',
|
||||||
footer: total ? () => formatNumber(total.actual_quantity) : '',
|
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
id: 'actual_unit_price',
|
id: 'actual_unit_price',
|
||||||
header: 'Harga Satuan',
|
header: 'Harga Satuan',
|
||||||
accessorFn: (props) =>
|
accessorFn: (props) => formatCurrency(props.actual_unit_price),
|
||||||
props.actual_unit_price
|
|
||||||
? formatCurrency(props.actual_unit_price)
|
|
||||||
: '-',
|
|
||||||
footer: '',
|
footer: '',
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
id: 'actual_total_amount',
|
id: 'actual_total_amount',
|
||||||
header: 'Total',
|
header: 'Total',
|
||||||
accessorFn: (props) =>
|
accessorFn: (props) => formatCurrency(props.actual_total_amount),
|
||||||
props.actual_total_amount
|
|
||||||
? formatCurrency(props.actual_total_amount)
|
|
||||||
: '-',
|
|
||||||
footer: total
|
footer: total
|
||||||
? () => formatCurrency(total.actual_total_amount)
|
? () => formatCurrency(total.actual_total_amount)
|
||||||
: '',
|
: '0',
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
@@ -118,35 +142,25 @@ const ClosingOverheadTable = ({
|
|||||||
{
|
{
|
||||||
id: 'actual_date',
|
id: 'actual_date',
|
||||||
header: 'Tanggal',
|
header: 'Tanggal',
|
||||||
accessorFn: (props) =>
|
accessorFn: (props) => formatDate(props.actual_date, 'DD MMM, YYYY'),
|
||||||
props.actual_date
|
|
||||||
? formatDate(props.actual_date, 'DD MMM, YYYY')
|
|
||||||
: '-',
|
|
||||||
footer: '',
|
footer: '',
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
id: 'actual_quantity',
|
id: 'actual_quantity',
|
||||||
header: 'Jumlah',
|
header: 'Jumlah',
|
||||||
accessorFn: (props) =>
|
accessorFn: (props) => formatNumber(props.actual_quantity),
|
||||||
props.actual_quantity ? formatNumber(props.actual_quantity) : '-',
|
|
||||||
footer: total ? () => formatNumber(total.actual_quantity) : '',
|
footer: total ? () => formatNumber(total.actual_quantity) : '',
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
id: 'actual_unit_price',
|
id: 'actual_unit_price',
|
||||||
header: 'Harga Satuan',
|
header: 'Harga Satuan',
|
||||||
accessorFn: (props) =>
|
accessorFn: (props) => formatCurrency(props.actual_unit_price),
|
||||||
props.actual_unit_price
|
|
||||||
? formatCurrency(props.actual_unit_price)
|
|
||||||
: '-',
|
|
||||||
footer: '',
|
footer: '',
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
id: 'actual_total_amount',
|
id: 'actual_total_amount',
|
||||||
header: 'Total',
|
header: 'Total',
|
||||||
accessorFn: (props) =>
|
accessorFn: (props) => formatCurrency(props.actual_total_amount),
|
||||||
props.actual_total_amount
|
|
||||||
? formatCurrency(props.actual_total_amount)
|
|
||||||
: '-',
|
|
||||||
footer: total ? () => formatCurrency(total.actual_total_amount) : '',
|
footer: total ? () => formatCurrency(total.actual_total_amount) : '',
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
@@ -171,8 +185,7 @@ const ClosingOverheadTable = ({
|
|||||||
{
|
{
|
||||||
id: 'cost_per_bird',
|
id: 'cost_per_bird',
|
||||||
header: 'Rp/Ekor',
|
header: 'Rp/Ekor',
|
||||||
accessorFn: (props) =>
|
accessorFn: (props) => formatCurrency(props.cost_per_bird),
|
||||||
props.cost_per_bird ? formatCurrency(props.cost_per_bird) : '-',
|
|
||||||
footer: total ? () => formatCurrency(total.cost_per_bird) : '',
|
footer: total ? () => formatCurrency(total.cost_per_bird) : '',
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
@@ -183,11 +196,15 @@ const ClosingOverheadTable = ({
|
|||||||
() =>
|
() =>
|
||||||
isResponseSuccess(overhead)
|
isResponseSuccess(overhead)
|
||||||
? createColumns(
|
? createColumns(
|
||||||
overhead.data?.total,
|
kandangId
|
||||||
|
? isResponseSuccess(overheadKandang)
|
||||||
|
? overheadKandang.data?.total
|
||||||
|
: undefined
|
||||||
|
: overhead.data?.total,
|
||||||
kandangId ? Number(kandangId) : undefined
|
kandangId ? Number(kandangId) : undefined
|
||||||
)
|
)
|
||||||
: createColumns(),
|
: createColumns(),
|
||||||
[overhead]
|
[overhead, kandangId, overheadKandang]
|
||||||
);
|
);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
@@ -203,7 +220,13 @@ const ClosingOverheadTable = ({
|
|||||||
>
|
>
|
||||||
<Table<Overhead>
|
<Table<Overhead>
|
||||||
data={
|
data={
|
||||||
isResponseSuccess(overhead) ? (overhead.data?.overheads ?? []) : []
|
kandangId
|
||||||
|
? isResponseSuccess(overheadKandang)
|
||||||
|
? (overheadKandang.data?.overheads ?? [])
|
||||||
|
: []
|
||||||
|
: isResponseSuccess(overhead)
|
||||||
|
? (overhead.data?.overheads ?? [])
|
||||||
|
: []
|
||||||
}
|
}
|
||||||
columns={columns}
|
columns={columns}
|
||||||
className={{
|
className={{
|
||||||
@@ -220,6 +243,60 @@ const ClosingOverheadTable = ({
|
|||||||
: false
|
: false
|
||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
|
{kandangId && (
|
||||||
|
<Card
|
||||||
|
className={{
|
||||||
|
wrapper: 'w-full',
|
||||||
|
body: 'p-4 shadow-button-soft border border-base-content/10 rounded-lg',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<div className='flex flex-row gap-3 w-full justify-center items-stretch'>
|
||||||
|
<div className='flex flex-row items-center justify-between'>
|
||||||
|
<h2 className='text-base font-bold'>Pembelian Kandang </h2>
|
||||||
|
</div>
|
||||||
|
<div className='flex flex-col items-center justify-center'>
|
||||||
|
<Icon icon='heroicons:equals' className='inline' />
|
||||||
|
</div>
|
||||||
|
<div className='flex flex-col flex-1 gap-1.5'>
|
||||||
|
<div className='flex flex-row gap-1.5 text-center items-center justify-center font-medium'>
|
||||||
|
Populasi Akhir KANDANG{' '}
|
||||||
|
<Icon icon='heroicons:x-mark' className='inline' /> Pemakaian
|
||||||
|
Di FARM
|
||||||
|
</div>
|
||||||
|
<hr className='w-full h-fit m-0 p-0 text-base-content/65' />
|
||||||
|
<div className='flex flex-row gap-1.5 text-center items-center justify-center font-medium'>
|
||||||
|
Populasi Akhir Proyek
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className='flex flex-col items-center justify-center'>
|
||||||
|
<Icon icon='heroicons:equals' className='inline' />
|
||||||
|
</div>
|
||||||
|
<div className='flex flex-col flex-1 gap-1.5'>
|
||||||
|
<div className='flex flex-row gap-1.5 text-center items-center justify-center font-medium'>
|
||||||
|
{formatNumber(chickinPopulation ?? 0)}
|
||||||
|
<Icon icon='heroicons:x-mark' className='inline' />
|
||||||
|
{formatCurrency(
|
||||||
|
isResponseSuccess(overhead)
|
||||||
|
? overhead.data?.total.actual_total_amount
|
||||||
|
: 0
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<hr className='w-full h-fit m-0 p-0 text-base-content/65' />
|
||||||
|
<div className='flex flex-row gap-1.5 text-center items-center justify-center font-medium'>
|
||||||
|
{formatNumber(generalInformation?.population ?? 0)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className='flex flex-col items-center justify-center'>
|
||||||
|
<Icon icon='heroicons:equals' className='inline' />
|
||||||
|
</div>
|
||||||
|
<div className='flex flex-row items-center justify-between'>
|
||||||
|
<h2 className='text-base font-bold'>
|
||||||
|
{formatNumber(kandangTotal || 0)}
|
||||||
|
</h2>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</Card>
|
||||||
|
)}
|
||||||
</Card>
|
</Card>
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -67,7 +67,7 @@ const lineColors: Record<string, string> = {
|
|||||||
act_fcr: '#10B981',
|
act_fcr: '#10B981',
|
||||||
std_fcr: '#10B981',
|
std_fcr: '#10B981',
|
||||||
act_fcr_cum: '#F52419',
|
act_fcr_cum: '#F52419',
|
||||||
std_fcr_cum: '#10B981',
|
std_fcr_cum: '#F52419',
|
||||||
normal: '#10B981',
|
normal: '#10B981',
|
||||||
abnormal: '#F52419',
|
abnormal: '#F52419',
|
||||||
act_deplesi: '#10B981',
|
act_deplesi: '#10B981',
|
||||||
@@ -659,44 +659,50 @@ const DashboardLineChart = ({
|
|||||||
seriesData = comparisonChart?.series || [];
|
seriesData = comparisonChart?.series || [];
|
||||||
}
|
}
|
||||||
|
|
||||||
return seriesData
|
return seriesData.map((series, originalIndex) => {
|
||||||
.filter((series) => visibleSeries.has(series.id))
|
// Skip rendering if series is not visible
|
||||||
.map((series, index) => {
|
if (!visibleSeries.has(series.id)) {
|
||||||
const isStandard = series.id
|
return null;
|
||||||
.toString()
|
}
|
||||||
.toLowerCase()
|
|
||||||
.includes('std');
|
|
||||||
// Use series.id directly as dataKey to match dataset fields
|
|
||||||
const dataKey = series.id.toString();
|
|
||||||
|
|
||||||
return (
|
const isStandard = series.id
|
||||||
<Line
|
.toString()
|
||||||
key={`${series.id}--${index}`}
|
.toLowerCase()
|
||||||
type='monotone'
|
.includes('std');
|
||||||
dataKey={dataKey}
|
const dataKey = series.id.toString();
|
||||||
name={series.label}
|
|
||||||
stroke={getLineColor(series.id, index, analysisMode)}
|
return (
|
||||||
opacity={isStandard ? 0.5 : 1}
|
<Line
|
||||||
strokeWidth={2}
|
key={`${series.id}--${originalIndex}`}
|
||||||
strokeDasharray={isStandard ? '5 5' : undefined}
|
type='monotone'
|
||||||
dot={
|
dataKey={dataKey}
|
||||||
isStandard
|
name={series.label}
|
||||||
? false
|
stroke={getLineColor(
|
||||||
: {
|
series.id,
|
||||||
r: 3,
|
originalIndex,
|
||||||
fill: '#fff',
|
analysisMode
|
||||||
stroke: getLineColor(
|
)}
|
||||||
series.id,
|
opacity={isStandard ? 0.5 : 1}
|
||||||
index,
|
strokeWidth={2}
|
||||||
analysisMode
|
strokeDasharray={isStandard ? '5 5' : undefined}
|
||||||
),
|
dot={
|
||||||
strokeWidth: 2,
|
isStandard
|
||||||
}
|
? false
|
||||||
}
|
: {
|
||||||
activeDot={isStandard ? undefined : { r: 5 }}
|
r: 3,
|
||||||
/>
|
fill: '#fff',
|
||||||
);
|
stroke: getLineColor(
|
||||||
});
|
series.id,
|
||||||
|
originalIndex,
|
||||||
|
analysisMode
|
||||||
|
),
|
||||||
|
strokeWidth: 2,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
activeDot={isStandard ? undefined : { r: 5 }}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
});
|
||||||
})()}
|
})()}
|
||||||
</LineChart>
|
</LineChart>
|
||||||
</ResponsiveContainer>
|
</ResponsiveContainer>
|
||||||
|
|||||||
@@ -66,7 +66,7 @@ const lineColors: Record<string, string> = {
|
|||||||
act_fcr: '#10B981',
|
act_fcr: '#10B981',
|
||||||
std_fcr: '#10B981',
|
std_fcr: '#10B981',
|
||||||
act_fcr_cum: '#F52419',
|
act_fcr_cum: '#F52419',
|
||||||
std_fcr_cum: '#10B981',
|
std_fcr_cum: '#F52419',
|
||||||
normal: '#10B981',
|
normal: '#10B981',
|
||||||
abnormal: '#F52419',
|
abnormal: '#F52419',
|
||||||
act_deplesi: '#10B981',
|
act_deplesi: '#10B981',
|
||||||
|
|||||||
@@ -100,6 +100,7 @@ const ExpenseRequestContent = ({
|
|||||||
const [isCompleteLoading, setIsCompleteLoading] = useState(false);
|
const [isCompleteLoading, setIsCompleteLoading] = useState(false);
|
||||||
const [isApproveLoading, setIsApproveLoading] = useState(false);
|
const [isApproveLoading, setIsApproveLoading] = useState(false);
|
||||||
const [isRejectLoading, setIsRejectLoading] = useState(false);
|
const [isRejectLoading, setIsRejectLoading] = useState(false);
|
||||||
|
const [, setApprovalNotes] = useState('');
|
||||||
|
|
||||||
const formik = useFormik<UploadRequestDocumentsFormValues>({
|
const formik = useFormik<UploadRequestDocumentsFormValues>({
|
||||||
initialValues: {
|
initialValues: {
|
||||||
@@ -130,10 +131,12 @@ const ExpenseRequestContent = ({
|
|||||||
};
|
};
|
||||||
|
|
||||||
const approveClickHandler = () => {
|
const approveClickHandler = () => {
|
||||||
|
setApprovalNotes('');
|
||||||
approveModal.openModal();
|
approveModal.openModal();
|
||||||
};
|
};
|
||||||
|
|
||||||
const rejectClickHandler = () => {
|
const rejectClickHandler = () => {
|
||||||
|
setApprovalNotes('');
|
||||||
rejectModal.openModal();
|
rejectModal.openModal();
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -200,6 +203,7 @@ const ExpenseRequestContent = ({
|
|||||||
approveModal.closeModal();
|
approveModal.closeModal();
|
||||||
|
|
||||||
toast.success(approveResponse?.message);
|
toast.success(approveResponse?.message);
|
||||||
|
setApprovalNotes('');
|
||||||
router.push('/expense');
|
router.push('/expense');
|
||||||
} else {
|
} else {
|
||||||
approveModal.closeModal();
|
approveModal.closeModal();
|
||||||
@@ -234,6 +238,7 @@ const ExpenseRequestContent = ({
|
|||||||
rejectModal.closeModal();
|
rejectModal.closeModal();
|
||||||
|
|
||||||
toast.success(rejectResponse.message);
|
toast.success(rejectResponse.message);
|
||||||
|
setApprovalNotes('');
|
||||||
router.push('/expense');
|
router.push('/expense');
|
||||||
} else {
|
} else {
|
||||||
rejectModal.closeModal();
|
rejectModal.closeModal();
|
||||||
@@ -710,6 +715,10 @@ const ExpenseRequestContent = ({
|
|||||||
text='Apakah anda yakin ingin approve data biaya operasional ini?'
|
text='Apakah anda yakin ingin approve data biaya operasional ini?'
|
||||||
secondaryButton={{
|
secondaryButton={{
|
||||||
text: 'Tidak',
|
text: 'Tidak',
|
||||||
|
onClick: () => {
|
||||||
|
setApprovalNotes('');
|
||||||
|
approveModal.closeModal();
|
||||||
|
},
|
||||||
}}
|
}}
|
||||||
primaryButton={{
|
primaryButton={{
|
||||||
text: 'Ya',
|
text: 'Ya',
|
||||||
@@ -725,6 +734,10 @@ const ExpenseRequestContent = ({
|
|||||||
text='Apakah anda yakin ingin reject data biaya operasional ini?'
|
text='Apakah anda yakin ingin reject data biaya operasional ini?'
|
||||||
secondaryButton={{
|
secondaryButton={{
|
||||||
text: 'Tidak',
|
text: 'Tidak',
|
||||||
|
onClick: () => {
|
||||||
|
setApprovalNotes('');
|
||||||
|
rejectModal.closeModal();
|
||||||
|
},
|
||||||
}}
|
}}
|
||||||
primaryButton={{
|
primaryButton={{
|
||||||
text: 'Ya',
|
text: 'Ya',
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import PillBadge from '@/components/PillBadge';
|
import StatusBadge from '@/components/helper/StatusBadge';
|
||||||
|
|
||||||
import { BaseApproval } from '@/types/api/api-general';
|
import { BaseApproval } from '@/types/api/api-general';
|
||||||
|
import { Color } from '@/types/theme';
|
||||||
|
|
||||||
interface ExpenseStatusBadgeProps {
|
interface ExpenseStatusBadgeProps {
|
||||||
approval?: BaseApproval;
|
approval?: BaseApproval;
|
||||||
@@ -11,49 +12,45 @@ const ExpenseStatusBadge = ({ approval }: ExpenseStatusBadgeProps) => {
|
|||||||
|
|
||||||
const latestApprovalStepNumber = approval?.step_number;
|
const latestApprovalStepNumber = approval?.step_number;
|
||||||
|
|
||||||
let expenseStatusPillBadgeColor:
|
let expenseStatusBadgeColor: Color = 'neutral';
|
||||||
| 'yellow'
|
|
||||||
| 'green'
|
|
||||||
| 'gray'
|
|
||||||
| 'red'
|
|
||||||
| 'purple'
|
|
||||||
| 'blue' = 'gray';
|
|
||||||
|
|
||||||
switch (latestApprovalStepNumber) {
|
switch (latestApprovalStepNumber) {
|
||||||
case 1:
|
case 1:
|
||||||
expenseStatusPillBadgeColor = 'gray';
|
expenseStatusBadgeColor = 'neutral';
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case 2:
|
case 2:
|
||||||
expenseStatusPillBadgeColor = 'purple';
|
expenseStatusBadgeColor = 'info';
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case 3:
|
case 3:
|
||||||
expenseStatusPillBadgeColor = 'blue';
|
expenseStatusBadgeColor = 'warning';
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case 4:
|
case 4:
|
||||||
expenseStatusPillBadgeColor = 'yellow';
|
expenseStatusBadgeColor = 'error';
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case 5:
|
case 5:
|
||||||
expenseStatusPillBadgeColor = 'green';
|
expenseStatusBadgeColor = 'success';
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case 6:
|
case 6:
|
||||||
expenseStatusPillBadgeColor = 'green';
|
expenseStatusBadgeColor = 'success';
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (isLatestApprovalRejected) {
|
if (isLatestApprovalRejected) {
|
||||||
expenseStatusPillBadgeColor = 'red';
|
expenseStatusBadgeColor = 'error';
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<PillBadge
|
<StatusBadge
|
||||||
content={isLatestApprovalRejected ? 'Ditolak' : approval?.step_name}
|
color={expenseStatusBadgeColor}
|
||||||
color={expenseStatusPillBadgeColor}
|
text={isLatestApprovalRejected ? 'Ditolak' : (approval?.step_name ?? '')}
|
||||||
className='text-xs'
|
className={{
|
||||||
|
badge: 'whitespace-nowrap max-w-max w-fit',
|
||||||
|
}}
|
||||||
/>
|
/>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -185,6 +185,7 @@ const ExpensesTable = () => {
|
|||||||
const [isDeleteLoading, setIsDeleteLoading] = useState(false);
|
const [isDeleteLoading, setIsDeleteLoading] = useState(false);
|
||||||
const [isApproveLoading, setIsApproveLoading] = useState(false);
|
const [isApproveLoading, setIsApproveLoading] = useState(false);
|
||||||
const [isRejectLoading, setIsRejectLoading] = useState(false);
|
const [isRejectLoading, setIsRejectLoading] = useState(false);
|
||||||
|
const [, setApprovalNotes] = useState('');
|
||||||
|
|
||||||
const [sorting, setSorting] = useState<SortingState>([]);
|
const [sorting, setSorting] = useState<SortingState>([]);
|
||||||
const [rowSelection, setRowSelection] = useState<Record<string, boolean>>({});
|
const [rowSelection, setRowSelection] = useState<Record<string, boolean>>({});
|
||||||
@@ -342,6 +343,7 @@ const ExpensesTable = () => {
|
|||||||
[String(props.row.original.id)]: true,
|
[String(props.row.original.id)]: true,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
setApprovalNotes('');
|
||||||
approveModal.openModal();
|
approveModal.openModal();
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -353,6 +355,7 @@ const ExpensesTable = () => {
|
|||||||
[String(props.row.original.id)]: true,
|
[String(props.row.original.id)]: true,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
setApprovalNotes('');
|
||||||
rejectModal.openModal();
|
rejectModal.openModal();
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -412,10 +415,12 @@ const ExpensesTable = () => {
|
|||||||
// };
|
// };
|
||||||
|
|
||||||
const bulkApproveClickHandler = () => {
|
const bulkApproveClickHandler = () => {
|
||||||
|
setApprovalNotes('');
|
||||||
approveModal.openModal();
|
approveModal.openModal();
|
||||||
};
|
};
|
||||||
|
|
||||||
const bulkRejectClickHandler = () => {
|
const bulkRejectClickHandler = () => {
|
||||||
|
setApprovalNotes('');
|
||||||
rejectModal.openModal();
|
rejectModal.openModal();
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -468,6 +473,7 @@ const ExpensesTable = () => {
|
|||||||
`Berhasil approve ${selectedRowIds.length} data biaya operasional!`
|
`Berhasil approve ${selectedRowIds.length} data biaya operasional!`
|
||||||
);
|
);
|
||||||
|
|
||||||
|
setApprovalNotes('');
|
||||||
setRowSelection({});
|
setRowSelection({});
|
||||||
} else {
|
} else {
|
||||||
approveModal.closeModal();
|
approveModal.closeModal();
|
||||||
@@ -509,6 +515,7 @@ const ExpensesTable = () => {
|
|||||||
toast.success(
|
toast.success(
|
||||||
`Berhasil reject ${selectedRowIds.length} data biaya operasional!`
|
`Berhasil reject ${selectedRowIds.length} data biaya operasional!`
|
||||||
);
|
);
|
||||||
|
setApprovalNotes('');
|
||||||
setRowSelection({});
|
setRowSelection({});
|
||||||
} else {
|
} else {
|
||||||
rejectModal.closeModal();
|
rejectModal.closeModal();
|
||||||
@@ -589,12 +596,11 @@ const ExpensesTable = () => {
|
|||||||
<RequirePermission permissions='lti.expense.create'>
|
<RequirePermission permissions='lti.expense.create'>
|
||||||
<Button
|
<Button
|
||||||
href='/expense/add'
|
href='/expense/add'
|
||||||
variant='outline'
|
|
||||||
color='primary'
|
color='primary'
|
||||||
className='w-full sm:w-fit'
|
className='px-3 py-2.5 w-fit text-sm text-base-100 rounded-lg shadow-sm'
|
||||||
>
|
>
|
||||||
<Icon icon='ic:round-plus' width={24} height={24} />
|
<Icon icon='heroicons:plus' width={20} height={20} />
|
||||||
Tambah
|
Add Expense
|
||||||
</Button>
|
</Button>
|
||||||
</RequirePermission>
|
</RequirePermission>
|
||||||
|
|
||||||
@@ -787,6 +793,10 @@ const ExpensesTable = () => {
|
|||||||
text='Apakah anda yakin ingin approve data biaya operasional ini?'
|
text='Apakah anda yakin ingin approve data biaya operasional ini?'
|
||||||
secondaryButton={{
|
secondaryButton={{
|
||||||
text: 'Tidak',
|
text: 'Tidak',
|
||||||
|
onClick: () => {
|
||||||
|
setApprovalNotes('');
|
||||||
|
approveModal.closeModal();
|
||||||
|
},
|
||||||
}}
|
}}
|
||||||
primaryButton={{
|
primaryButton={{
|
||||||
text: 'Ya',
|
text: 'Ya',
|
||||||
@@ -802,6 +812,10 @@ const ExpensesTable = () => {
|
|||||||
text='Apakah anda yakin ingin reject data biaya operasional ini?'
|
text='Apakah anda yakin ingin reject data biaya operasional ini?'
|
||||||
secondaryButton={{
|
secondaryButton={{
|
||||||
text: 'Tidak',
|
text: 'Tidak',
|
||||||
|
onClick: () => {
|
||||||
|
setApprovalNotes('');
|
||||||
|
rejectModal.closeModal();
|
||||||
|
},
|
||||||
}}
|
}}
|
||||||
primaryButton={{
|
primaryButton={{
|
||||||
text: 'Ya',
|
text: 'Ya',
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import PillBadge from '@/components/PillBadge';
|
import StatusBadge from '@/components/helper/StatusBadge';
|
||||||
|
|
||||||
import { BaseApproval } from '@/types/api/api-general';
|
import { BaseApproval } from '@/types/api/api-general';
|
||||||
|
import { Color } from '@/types/theme';
|
||||||
|
|
||||||
interface RealizationStatusBadgeProps {
|
interface RealizationStatusBadgeProps {
|
||||||
approval?: BaseApproval;
|
approval?: BaseApproval;
|
||||||
@@ -15,23 +16,21 @@ const RealizationStatusBadge = ({ approval }: RealizationStatusBadgeProps) => {
|
|||||||
? 'Sudah Realisasi'
|
? 'Sudah Realisasi'
|
||||||
: 'Belum Realisasi';
|
: 'Belum Realisasi';
|
||||||
|
|
||||||
let realizationStatusPillBadgeColor:
|
let realizationStatusBadgeColor: Color = isExpenseRealized
|
||||||
| 'yellow'
|
? 'success'
|
||||||
| 'green'
|
: 'warning';
|
||||||
| 'gray'
|
|
||||||
| 'red'
|
|
||||||
| 'purple'
|
|
||||||
| 'blue' = isExpenseRealized ? 'green' : 'yellow';
|
|
||||||
|
|
||||||
if (isLatestApprovalRejected) {
|
if (isLatestApprovalRejected) {
|
||||||
realizationStatusPillBadgeColor = 'red';
|
realizationStatusBadgeColor = 'error';
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<PillBadge
|
<StatusBadge
|
||||||
content={isLatestApprovalRejected ? 'Ditolak' : realizationStatus}
|
color={realizationStatusBadgeColor}
|
||||||
color={realizationStatusPillBadgeColor}
|
text={isLatestApprovalRejected ? 'Ditolak' : realizationStatus}
|
||||||
className='text-xs'
|
className={{
|
||||||
|
badge: 'whitespace-nowrap max-w-max w-fit',
|
||||||
|
}}
|
||||||
/>
|
/>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -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
|
||||||
|
>;
|
||||||
@@ -151,12 +151,11 @@ const MovementTable = () => {
|
|||||||
<RequirePermission permissions='lti.inventory.transfer.create'>
|
<RequirePermission permissions='lti.inventory.transfer.create'>
|
||||||
<Button
|
<Button
|
||||||
href='/inventory/movement/add'
|
href='/inventory/movement/add'
|
||||||
variant='outline'
|
|
||||||
color='primary'
|
color='primary'
|
||||||
className='w-full sm:w-fit'
|
className='px-3 py-2.5 w-fit text-sm text-base-100 rounded-lg shadow-sm'
|
||||||
>
|
>
|
||||||
<Icon icon='ic:round-plus' width={24} height={24} />
|
<Icon icon='heroicons:plus' width={20} height={20} />
|
||||||
Tambah
|
Add Movement
|
||||||
</Button>
|
</Button>
|
||||||
</RequirePermission>
|
</RequirePermission>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -0,0 +1,806 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
import AlertErrorList from '@/components/helper/form/FormErrors';
|
||||||
|
import { OptionType } from '@/components/input/SelectInput';
|
||||||
|
import Modal, { useModal } from '@/components/Modal';
|
||||||
|
import ConfirmationModal from '@/components/modal/ConfirmationModal';
|
||||||
|
import { DeliveryOrderProductFormValues } from '@/components/pages/marketing/form/repeater/delivery-order/DeliverOrderProduct.schema';
|
||||||
|
import { isResponseSuccess, isResponseError } from '@/lib/api-helper';
|
||||||
|
import { formatCurrency, formatDate, formatTitleCase } from '@/lib/helper';
|
||||||
|
import {
|
||||||
|
DeliveryOrderApi,
|
||||||
|
MarketingApi,
|
||||||
|
SalesOrderApi,
|
||||||
|
} from '@/services/api/marketing/marketing';
|
||||||
|
import { useFormikErrorList } from '@/services/hooks/useFormikErrorList';
|
||||||
|
import { BaseApproval } from '@/types/api/api-general';
|
||||||
|
import {
|
||||||
|
CreateDeliveryOrderPayload,
|
||||||
|
Marketing,
|
||||||
|
UpdateDeliveryOrderPayload,
|
||||||
|
} from '@/types/api/marketing/marketing';
|
||||||
|
import { useFormik } from 'formik';
|
||||||
|
import { Icon } from '@iconify/react';
|
||||||
|
import { useRouter, useSearchParams } from 'next/navigation';
|
||||||
|
import { useState, useRef, useMemo, useCallback, useEffect } from 'react';
|
||||||
|
import toast from 'react-hot-toast';
|
||||||
|
import useSWR, { useSWRConfig } from 'swr';
|
||||||
|
import Button from '@/components/Button';
|
||||||
|
import { memo } from 'react';
|
||||||
|
import SalesOrderExport from '@/components/pages/marketing/pdf/SalesOrderExport';
|
||||||
|
import ApprovalStepsV2 from '@/components/helper/ApprovalStepsV2';
|
||||||
|
import { useApprovalSteps } from '@/components/pages/ApprovalSteps';
|
||||||
|
import { MARKETING_APPROVAL_LINE } from '@/config/approval-line';
|
||||||
|
import DeliveryOrderProductForm from '@/components/pages/marketing/form/repeater/delivery-order/DeliverOrderProduct';
|
||||||
|
import DeliveryOrderProductTable from '@/components/pages/marketing/form/table-view/DeliveryOrderProductTable';
|
||||||
|
import {
|
||||||
|
DeliveryOrderFormValues,
|
||||||
|
DeliveryOrderSchema,
|
||||||
|
getFilledMarketingFormInitialValues,
|
||||||
|
SalesOrderFormValues,
|
||||||
|
mergeSOwithDO,
|
||||||
|
SalesProductToFieldValues,
|
||||||
|
DeliveryProductToFieldValues,
|
||||||
|
} from '@/components/pages/marketing/form/MarketingForm.schema';
|
||||||
|
import ConfirmationModalWithNotes from '@/components/modal/ConfirmationModalWithNotes';
|
||||||
|
import RequirePermission from '@/components/helper/RequirePermission';
|
||||||
|
|
||||||
|
const MemoizedDeliveryOrderProductTable = memo(DeliveryOrderProductTable);
|
||||||
|
const MemoizedDeliveryOrderProductForm = memo(DeliveryOrderProductForm);
|
||||||
|
|
||||||
|
const DeliveryOrderFormModal = ({
|
||||||
|
initialValues,
|
||||||
|
}: {
|
||||||
|
initialValues?: Marketing;
|
||||||
|
}) => {
|
||||||
|
const router = useRouter();
|
||||||
|
const searchParams = useSearchParams();
|
||||||
|
|
||||||
|
const modalAction = searchParams.get('action');
|
||||||
|
const marketingId = searchParams.get('id');
|
||||||
|
|
||||||
|
const isModalActionForForm =
|
||||||
|
modalAction === 'add_delivery' ||
|
||||||
|
modalAction === 'edit_delivery' ||
|
||||||
|
modalAction === 'detail';
|
||||||
|
|
||||||
|
const { mutate } = useSWRConfig();
|
||||||
|
|
||||||
|
const refreshMarketing = () => {
|
||||||
|
mutate(
|
||||||
|
(key) => typeof key === 'string' && key.includes(MarketingApi.basePath)
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
const { data: marketing, isLoading: isLoadingMarketing } = useSWR(
|
||||||
|
isModalActionForForm && marketingId
|
||||||
|
? `detail-marketing-${marketingId}`
|
||||||
|
: undefined,
|
||||||
|
() => MarketingApi.getSingle(Number(marketingId))
|
||||||
|
);
|
||||||
|
|
||||||
|
const {
|
||||||
|
approvals,
|
||||||
|
rawDataApprovals,
|
||||||
|
isLoading: isLoadingApproval,
|
||||||
|
refresh: refreshApproval,
|
||||||
|
} = useApprovalSteps({
|
||||||
|
latestApproval: isResponseSuccess(marketing)
|
||||||
|
? marketing?.data.latest_approval
|
||||||
|
: undefined,
|
||||||
|
approvalLines: MARKETING_APPROVAL_LINE,
|
||||||
|
moduleName: 'MARKETINGS',
|
||||||
|
moduleId: marketingId as string,
|
||||||
|
params: {
|
||||||
|
group_step_number: false,
|
||||||
|
order_by_date: 'ASC',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Step 1: View Details
|
||||||
|
* Step 2: Edit Delivery
|
||||||
|
*/
|
||||||
|
const [step, setStep] = useState(1);
|
||||||
|
|
||||||
|
const formModal = useModal();
|
||||||
|
const successModal = useModal();
|
||||||
|
const rejectModal = useModal();
|
||||||
|
const deleteModal = useModal();
|
||||||
|
const formRef = useRef<HTMLFormElement>(null);
|
||||||
|
const textareaRef = useRef<HTMLTextAreaElement>(null);
|
||||||
|
|
||||||
|
const [formErrorMessage, setFormErrorMessage] = useState<string | null>(null);
|
||||||
|
const [isLoading, setIsLoading] = useState(false);
|
||||||
|
const [selectedDeliveryProduct, setSelectedDeliveryProduct] =
|
||||||
|
useState<DeliveryOrderProductFormValues | null>(null);
|
||||||
|
const [deliveryOrderValues, setDeliveryOrderValues] = useState<
|
||||||
|
DeliveryOrderProductFormValues[]
|
||||||
|
>(
|
||||||
|
isResponseSuccess(marketing)
|
||||||
|
? mergeSOwithDO(
|
||||||
|
marketing?.data.sales_order?.map(SalesProductToFieldValues) ?? [],
|
||||||
|
marketing?.data.delivery_order?.flatMap((delivery) =>
|
||||||
|
DeliveryProductToFieldValues(marketing.data.sales_order, delivery)
|
||||||
|
) ?? [],
|
||||||
|
true
|
||||||
|
)
|
||||||
|
: []
|
||||||
|
);
|
||||||
|
|
||||||
|
// ================== SETUP FORMIK ==================
|
||||||
|
const formikInitialValues = useMemo<
|
||||||
|
SalesOrderFormValues & DeliveryOrderFormValues
|
||||||
|
>(() => {
|
||||||
|
if (!isResponseSuccess(marketing))
|
||||||
|
return {} as SalesOrderFormValues & DeliveryOrderFormValues;
|
||||||
|
const deliveryValues = mergeSOwithDO(
|
||||||
|
marketing?.data.sales_order?.map(SalesProductToFieldValues) ?? [],
|
||||||
|
marketing?.data.delivery_order?.flatMap((delivery) =>
|
||||||
|
DeliveryProductToFieldValues(marketing.data.sales_order, delivery)
|
||||||
|
) ?? [],
|
||||||
|
true
|
||||||
|
);
|
||||||
|
|
||||||
|
setDeliveryOrderValues(deliveryValues);
|
||||||
|
|
||||||
|
return {
|
||||||
|
so_date: marketing?.data?.so_date || undefined,
|
||||||
|
notes: marketing?.data?.notes || undefined,
|
||||||
|
customer_id: marketing?.data?.customer?.id || undefined,
|
||||||
|
sales_person_id: marketing?.data?.sales_person?.id || undefined,
|
||||||
|
sales_person: marketing?.data?.sales_person
|
||||||
|
? {
|
||||||
|
value: marketing?.data.sales_person.id,
|
||||||
|
label: marketing?.data.sales_person.name,
|
||||||
|
}
|
||||||
|
: null,
|
||||||
|
customer: marketing?.data?.customer
|
||||||
|
? {
|
||||||
|
value: marketing?.data.customer.id,
|
||||||
|
label: marketing?.data.customer.name,
|
||||||
|
}
|
||||||
|
: null,
|
||||||
|
sales_order:
|
||||||
|
marketing?.data?.sales_order?.map((product) =>
|
||||||
|
SalesProductToFieldValues(product)
|
||||||
|
) ?? [],
|
||||||
|
delivery_order: deliveryValues,
|
||||||
|
};
|
||||||
|
}, [marketing]);
|
||||||
|
|
||||||
|
const formik = useFormik<SalesOrderFormValues & DeliveryOrderFormValues>({
|
||||||
|
enableReinitialize: true,
|
||||||
|
initialValues: formikInitialValues,
|
||||||
|
validationSchema: DeliveryOrderSchema,
|
||||||
|
validateOnMount: true,
|
||||||
|
onSubmit: async (values) => {
|
||||||
|
const payload = {
|
||||||
|
marketing_id: Number(marketingId),
|
||||||
|
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 (modalAction) {
|
||||||
|
case 'add_delivery':
|
||||||
|
await createDeliveryHandler(payload as CreateDeliveryOrderPayload);
|
||||||
|
break;
|
||||||
|
case 'edit_delivery':
|
||||||
|
await updateDeliveryHandler(payload as UpdateDeliveryOrderPayload);
|
||||||
|
break;
|
||||||
|
case 'detail':
|
||||||
|
const dataMarketing = isResponseSuccess(marketing)
|
||||||
|
? marketing.data
|
||||||
|
: null;
|
||||||
|
if (!dataMarketing) break;
|
||||||
|
if (
|
||||||
|
dataMarketing.delivery_order &&
|
||||||
|
dataMarketing.delivery_order.length > 0
|
||||||
|
) {
|
||||||
|
await updateDeliveryHandler(payload as UpdateDeliveryOrderPayload);
|
||||||
|
break;
|
||||||
|
} else {
|
||||||
|
await createDeliveryHandler(payload as CreateDeliveryOrderPayload);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
// ===== Formik Error List =====
|
||||||
|
const { formErrorList, setFormErrorList, close, handleFormSubmit } =
|
||||||
|
useFormikErrorList(formik);
|
||||||
|
|
||||||
|
// ================== FORM HANDLER ==================
|
||||||
|
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
|
||||||
|
)
|
||||||
|
) ?? []
|
||||||
|
);
|
||||||
|
closeModalHandler(false);
|
||||||
|
successModal.openModal();
|
||||||
|
}
|
||||||
|
if (isResponseError(createDeliveryRes)) {
|
||||||
|
setFormErrorMessage(createDeliveryRes?.message as string);
|
||||||
|
}
|
||||||
|
setIsLoading(false);
|
||||||
|
};
|
||||||
|
const updateDeliveryHandler = async (values: UpdateDeliveryOrderPayload) => {
|
||||||
|
setIsLoading(true);
|
||||||
|
const updateDeliveryRes = await DeliveryOrderApi.update(
|
||||||
|
Number(marketingId),
|
||||||
|
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
|
||||||
|
)
|
||||||
|
) ?? []
|
||||||
|
)
|
||||||
|
);
|
||||||
|
closeModalHandler(false);
|
||||||
|
successModal.openModal();
|
||||||
|
}
|
||||||
|
if (isResponseError(updateDeliveryRes)) {
|
||||||
|
setFormErrorMessage(updateDeliveryRes?.message as string);
|
||||||
|
}
|
||||||
|
setIsLoading(false);
|
||||||
|
};
|
||||||
|
|
||||||
|
const memoSalesOrder = formik.values.sales_order;
|
||||||
|
|
||||||
|
// ================== HANDLER ==================
|
||||||
|
const nextButtonHandler = () => {
|
||||||
|
setStep(step + 1);
|
||||||
|
};
|
||||||
|
const prevButtonHandler = () => {
|
||||||
|
setStep(step - 1);
|
||||||
|
};
|
||||||
|
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 rejectMarketingHandler = async (notes: string) => {
|
||||||
|
if (!marketingId) {
|
||||||
|
toast.error(`Tidak ada data yang valid untuk di reject.`);
|
||||||
|
rejectModal.closeModal();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const rejectMarketingRes = await SalesOrderApi.singleApproval(
|
||||||
|
Number(marketingId),
|
||||||
|
'REJECTED',
|
||||||
|
notes
|
||||||
|
);
|
||||||
|
|
||||||
|
if (isResponseSuccess(rejectMarketingRes)) {
|
||||||
|
rejectModal.closeModal();
|
||||||
|
toast.success(rejectMarketingRes?.message as string);
|
||||||
|
closeModalHandler();
|
||||||
|
router.push('/marketing');
|
||||||
|
}
|
||||||
|
if (isResponseError(rejectMarketingRes)) {
|
||||||
|
rejectModal.closeModal();
|
||||||
|
toast.error(rejectMarketingRes?.message as string);
|
||||||
|
}
|
||||||
|
refreshMarketing();
|
||||||
|
refreshApproval();
|
||||||
|
};
|
||||||
|
|
||||||
|
const deleteClickHandler = () => {
|
||||||
|
deleteModal.openModal();
|
||||||
|
};
|
||||||
|
|
||||||
|
const confirmationModalDeleteClickHandler = async () => {
|
||||||
|
if (!marketingId) {
|
||||||
|
toast.error(`Tidak ada data yang valid untuk di hapus.`);
|
||||||
|
deleteModal.closeModal();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setIsLoading(true);
|
||||||
|
const res = await MarketingApi.delete(Number(marketingId));
|
||||||
|
deleteModal.closeModal();
|
||||||
|
toast.success(res?.message as string);
|
||||||
|
setIsLoading(false);
|
||||||
|
router.replace('/marketing');
|
||||||
|
};
|
||||||
|
|
||||||
|
// ================== DELIVERY ORDER HANDLER ==================
|
||||||
|
const handleEditDO = useCallback(
|
||||||
|
(id: number, values?: DeliveryOrderProductFormValues) => {
|
||||||
|
const currentProducts = deliveryOrderValues?.find(
|
||||||
|
(product) => product.id == id
|
||||||
|
);
|
||||||
|
setSelectedDeliveryProduct(values ?? currentProducts ?? null);
|
||||||
|
if (id) {
|
||||||
|
setStep(2);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
[deliveryOrderValues, setSelectedDeliveryProduct, setStep]
|
||||||
|
);
|
||||||
|
const handleAddDOClick = useCallback(() => {
|
||||||
|
setSelectedDeliveryProduct(null);
|
||||||
|
}, []);
|
||||||
|
const handleAddSubmitDO = useCallback(
|
||||||
|
async (values: DeliveryOrderProductFormValues) => {
|
||||||
|
const newValues = {
|
||||||
|
...values,
|
||||||
|
id: values.id ?? Date.now(),
|
||||||
|
};
|
||||||
|
|
||||||
|
setDeliveryOrderValues((prev) => [...prev, newValues]);
|
||||||
|
setSelectedDeliveryProduct(null);
|
||||||
|
prevButtonHandler();
|
||||||
|
},
|
||||||
|
[prevButtonHandler]
|
||||||
|
);
|
||||||
|
const handleUpdateDO = useCallback(
|
||||||
|
async (id: number, values: DeliveryOrderProductFormValues) => {
|
||||||
|
setDeliveryOrderValues((prev) =>
|
||||||
|
prev.map((product) =>
|
||||||
|
product.id === id ? { ...product, ...values } : product
|
||||||
|
)
|
||||||
|
);
|
||||||
|
setSelectedDeliveryProduct(null);
|
||||||
|
prevButtonHandler();
|
||||||
|
},
|
||||||
|
[prevButtonHandler]
|
||||||
|
);
|
||||||
|
const handleDeleteDO = useCallback(async (id: number) => {
|
||||||
|
setDeliveryOrderValues((prev) =>
|
||||||
|
prev.map((product) =>
|
||||||
|
product.id === id
|
||||||
|
? {
|
||||||
|
...product,
|
||||||
|
...{
|
||||||
|
delivery_date: '',
|
||||||
|
},
|
||||||
|
}
|
||||||
|
: product
|
||||||
|
)
|
||||||
|
);
|
||||||
|
setSelectedDeliveryProduct(null);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
// ================== MEMOIZED ==================
|
||||||
|
const isNextButtonDisabled = useMemo(() => {
|
||||||
|
if (step === 1) {
|
||||||
|
return Boolean(
|
||||||
|
!formik.values.customer_id ||
|
||||||
|
!formik.values.sales_person_id ||
|
||||||
|
!formik.values.so_date ||
|
||||||
|
!formik.values.notes
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}, [step, formik.values]);
|
||||||
|
const deliveryRejected = useMemo(() => {
|
||||||
|
return (
|
||||||
|
isResponseSuccess(marketing) &&
|
||||||
|
((marketing.data.latest_approval.step_number === 3 &&
|
||||||
|
marketing.data.latest_approval.action === 'REJECTED') ||
|
||||||
|
(marketing.data.latest_approval.step_number === 2 &&
|
||||||
|
marketing.data.latest_approval.action === 'REJECTED'))
|
||||||
|
);
|
||||||
|
}, [marketing]);
|
||||||
|
|
||||||
|
const isPending = useMemo(() => {
|
||||||
|
return (
|
||||||
|
isResponseSuccess(marketing) &&
|
||||||
|
marketing.data.latest_approval.step_number === 1
|
||||||
|
);
|
||||||
|
}, [marketing]);
|
||||||
|
|
||||||
|
// ================== EFFECT ==================
|
||||||
|
useEffect(() => {
|
||||||
|
if (
|
||||||
|
modalAction === 'add_delivery' ||
|
||||||
|
modalAction === 'edit_delivery' ||
|
||||||
|
modalAction === 'detail'
|
||||||
|
) {
|
||||||
|
formModal.openModal();
|
||||||
|
}
|
||||||
|
}, [modalAction]);
|
||||||
|
|
||||||
|
const closeModalHandler = (shouldPushToRoute: boolean = true) => {
|
||||||
|
refreshMarketing();
|
||||||
|
|
||||||
|
if (shouldPushToRoute) {
|
||||||
|
formik.resetForm();
|
||||||
|
textareaRef.current?.setAttribute('value', '');
|
||||||
|
successModal.closeModal();
|
||||||
|
router.push('/marketing');
|
||||||
|
}
|
||||||
|
|
||||||
|
setStep(1);
|
||||||
|
setFormErrorMessage('');
|
||||||
|
formModal.closeModal();
|
||||||
|
};
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const getFilledInitialValues = async () => {
|
||||||
|
if (marketingId && isResponseSuccess(marketing)) {
|
||||||
|
const filledInitialValues = await getFilledMarketingFormInitialValues(
|
||||||
|
marketing.data
|
||||||
|
);
|
||||||
|
|
||||||
|
formik.setValues(filledInitialValues);
|
||||||
|
setStep(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isResponseError(marketing)) {
|
||||||
|
router.push('/marketing');
|
||||||
|
closeModalHandler();
|
||||||
|
toast.error(marketing.message);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
getFilledInitialValues();
|
||||||
|
}, [marketingId, marketing]);
|
||||||
|
|
||||||
|
// Reset error message when step changes
|
||||||
|
useEffect(() => {
|
||||||
|
setFormErrorList([]);
|
||||||
|
setFormErrorMessage('');
|
||||||
|
}, [step]);
|
||||||
|
|
||||||
|
// sync delivery order values to formik
|
||||||
|
useEffect(() => {
|
||||||
|
formik.setFieldValue('delivery_order', deliveryOrderValues);
|
||||||
|
}, [deliveryOrderValues]);
|
||||||
|
|
||||||
|
const grandTotal = useMemo(() => {
|
||||||
|
return deliveryOrderValues.reduce(
|
||||||
|
(total, product) =>
|
||||||
|
total + parseFloat((product.total_price as string) || '0'),
|
||||||
|
0
|
||||||
|
);
|
||||||
|
}, [deliveryOrderValues]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<Modal
|
||||||
|
ref={formModal.ref}
|
||||||
|
position='end'
|
||||||
|
className={{
|
||||||
|
modalBox: 'w-full sm:w-fit p-3 rounded-xl bg-transparent shadow-none',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<div
|
||||||
|
onSubmit={(e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
}}
|
||||||
|
className='w-full min-h-full flex flex-col sm:flex-row items-stretch bg-base-100 rounded-xl overflow-y-auto'
|
||||||
|
>
|
||||||
|
{step <= 2 && isResponseSuccess(marketing) && (
|
||||||
|
<>
|
||||||
|
<div className='w-full sm:w-[446px]'>
|
||||||
|
<div className='w-full p-4 flex flex-row items-stretch gap-3 border-b border-base-content/10'>
|
||||||
|
<Button
|
||||||
|
type='button'
|
||||||
|
variant='ghost'
|
||||||
|
color='none'
|
||||||
|
onClick={() => closeModalHandler()}
|
||||||
|
className='p-0 text-black hover:text-base-content'
|
||||||
|
>
|
||||||
|
<Icon icon='heroicons:x-mark' width={20} height={20} />
|
||||||
|
</Button>
|
||||||
|
|
||||||
|
<div className='w-px border-none bg-base-content/10' />
|
||||||
|
|
||||||
|
<h4 className='text-sm font-medium text-base-content/50'>
|
||||||
|
View Details
|
||||||
|
</h4>
|
||||||
|
</div>
|
||||||
|
<form
|
||||||
|
className='w-full p-4 gap-3 flex flex-col border-b border-base-content/10'
|
||||||
|
ref={formRef}
|
||||||
|
onSubmit={handleFormSubmit}
|
||||||
|
>
|
||||||
|
<h4 className='text-base font-medium text-base-content/50 font-roboto'>
|
||||||
|
Informasi Penjualan
|
||||||
|
</h4>
|
||||||
|
<div className='rounded-lg border border-tools-table-outline border-base-content/5'>
|
||||||
|
<table
|
||||||
|
style={{
|
||||||
|
borderRadius: '0.5rem',
|
||||||
|
}}
|
||||||
|
className='border-none w-full'
|
||||||
|
>
|
||||||
|
<tbody className='w-full'>
|
||||||
|
<tr className='border-b border-tools-table-outline border-base-content/5'>
|
||||||
|
<th className='w-1/3 text-start not-first:font-medium text-base-content/50 text-sm px-4 py-3'>
|
||||||
|
Label
|
||||||
|
</th>
|
||||||
|
<th className='text-start font-medium text-base-content/50 text-sm px-4 py-3'>
|
||||||
|
<div className='flex w-full flex-row gap-1 items-center justify-between h-full mt-2'>
|
||||||
|
<div>Value</div>
|
||||||
|
</div>
|
||||||
|
</th>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td className='text-sm px-4 py-3'>No. Sales Order</td>
|
||||||
|
<td className='text-sm px-4 py-3'>
|
||||||
|
{marketing.data.so_number}
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td className='text-sm px-4 py-3'>Nama Pelanggan</td>
|
||||||
|
<td className='text-sm px-4 py-3'>
|
||||||
|
{marketing.data.customer.name}
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td className='text-sm px-4 py-3'>Status</td>
|
||||||
|
<td className='text-sm px-4 py-3'>
|
||||||
|
{formatTitleCase(
|
||||||
|
marketing.data.latest_approval.step_name
|
||||||
|
)}
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td className='text-sm px-4 py-3'>
|
||||||
|
Tanggal Penjualan
|
||||||
|
</td>
|
||||||
|
<td className='text-sm px-4 py-3'>
|
||||||
|
{formatDate(marketing.data.so_date, 'DD MMM yyyy')}
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td className='text-sm px-4 py-3'>Total Penjualan</td>
|
||||||
|
<td className='text-sm px-4 py-3'>
|
||||||
|
{formatCurrency(grandTotal || 0)}
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td className='text-sm px-4 py-3'>
|
||||||
|
Dokumen Penjualan
|
||||||
|
</td>
|
||||||
|
<td className='text-sm px-4 py-3'>
|
||||||
|
<SalesOrderExport data={marketing.data} />
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
<div className='w-full min-h-full flex flex-col sm:w-[446px] border-l border-base-content/10'>
|
||||||
|
<div className='w-full p-4 flex flex-row items-center justify-between gap-3 border-b border-base-content/10'>
|
||||||
|
<div className='w-full flex flex-row items-stretch gap-3'>
|
||||||
|
{step === 2 && (
|
||||||
|
<>
|
||||||
|
<Button
|
||||||
|
type='button'
|
||||||
|
variant='ghost'
|
||||||
|
color='none'
|
||||||
|
onClick={() => {
|
||||||
|
setStep(1);
|
||||||
|
}}
|
||||||
|
className='p-0 text-black hover:text-base-content'
|
||||||
|
>
|
||||||
|
<Icon
|
||||||
|
icon='heroicons:chevron-left'
|
||||||
|
width={20}
|
||||||
|
height={20}
|
||||||
|
/>
|
||||||
|
</Button>
|
||||||
|
|
||||||
|
<div className='w-px border-none bg-base-content/10' />
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
<h4 className='text-sm font-medium text-base-content/50'>
|
||||||
|
Informasi
|
||||||
|
</h4>
|
||||||
|
</div>
|
||||||
|
{step === 1 && (
|
||||||
|
<RequirePermission permissions='lti.marketing.sales_order.delete'>
|
||||||
|
<Button
|
||||||
|
type='button'
|
||||||
|
variant='ghost'
|
||||||
|
color='none'
|
||||||
|
onClick={() => {
|
||||||
|
deleteClickHandler();
|
||||||
|
}}
|
||||||
|
className='p-0 text-error hover:text-base-content'
|
||||||
|
>
|
||||||
|
<Icon icon='heroicons:trash' width={20} height={20} />
|
||||||
|
</Button>
|
||||||
|
</RequirePermission>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
{step === 1 && (
|
||||||
|
<ApprovalStepsV2
|
||||||
|
approvals={rawDataApprovals as BaseApproval[]}
|
||||||
|
steps={MARKETING_APPROVAL_LINE}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
<div className='w-full gap-3 flex flex-col'>
|
||||||
|
<h4 className='px-4 pt-4 text-base font-medium text-base-content/50 font-roboto'>
|
||||||
|
{step == 2 && 'Ubah '} Informasi{' '}
|
||||||
|
{step == 2 ? 'Delivery' : 'Produk'}
|
||||||
|
</h4>
|
||||||
|
{step === 1 && (
|
||||||
|
<div className='px-4'>
|
||||||
|
<MemoizedDeliveryOrderProductTable
|
||||||
|
marketing={marketing.data}
|
||||||
|
formType={
|
||||||
|
deliveryRejected
|
||||||
|
? 'rejected'
|
||||||
|
: isPending
|
||||||
|
? 'pending'
|
||||||
|
: modalAction
|
||||||
|
}
|
||||||
|
data={deliveryOrderValues}
|
||||||
|
onEdit={handleEditDO}
|
||||||
|
onDelete={handleDeleteDO}
|
||||||
|
onAddProductClick={handleAddDOClick}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{step === 2 && (
|
||||||
|
<MemoizedDeliveryOrderProductForm
|
||||||
|
formState={'edit'}
|
||||||
|
salesOrders={marketing?.data?.sales_order ?? []}
|
||||||
|
exisitingValues={deliveryOrderValues}
|
||||||
|
onSubmitForm={handleAddSubmitDO}
|
||||||
|
initialValues={selectedDeliveryProduct ?? undefined}
|
||||||
|
onUpdateForm={handleUpdateDO}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
{formErrorMessage && (
|
||||||
|
<div className='px-4 pb-4'>
|
||||||
|
<AlertErrorList
|
||||||
|
className={{
|
||||||
|
alert: 'w-full',
|
||||||
|
}}
|
||||||
|
formErrorList={[formErrorMessage]}
|
||||||
|
onClose={() => setFormErrorMessage('')}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{formErrorList && (
|
||||||
|
<div className='px-4 pb-4 '>
|
||||||
|
<AlertErrorList
|
||||||
|
className={{
|
||||||
|
alert: 'w-full',
|
||||||
|
}}
|
||||||
|
formErrorList={formErrorList}
|
||||||
|
onClose={close}
|
||||||
|
title={`Terdapat ${formErrorList.length} error pada ${formErrorMessage ? 'server' : 'form'}:`}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{step === 1 && (
|
||||||
|
<div className='w-full px-4 py-3 grid grid-cols-2 items-center justify-between gap-3 border-t border-base-content/10'>
|
||||||
|
<Button
|
||||||
|
type='button'
|
||||||
|
variant='outline'
|
||||||
|
color='none'
|
||||||
|
onClick={() => rejectModal.openModal()}
|
||||||
|
disabled={deliveryRejected || isPending}
|
||||||
|
className='p-3 border-base-content/10 shadow-button-soft rounded-lg text-sm text-base-content/50 font-semibold'
|
||||||
|
>
|
||||||
|
Reject
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
type='button'
|
||||||
|
color='primary'
|
||||||
|
onClick={() => {
|
||||||
|
formRef.current?.requestSubmit();
|
||||||
|
}}
|
||||||
|
className='p-3 shadow-button-soft text-base-100 rounded-lg text-sm font-semibold'
|
||||||
|
disabled={deliveryRejected || isPending}
|
||||||
|
>
|
||||||
|
Approve
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</Modal>
|
||||||
|
<ConfirmationModal
|
||||||
|
ref={successModal.ref}
|
||||||
|
iconPosition='left'
|
||||||
|
type='success'
|
||||||
|
text={`${modalAction === 'add' ? 'Data Berhasil Disimpan' : 'Data Berhasil Diubah'}`}
|
||||||
|
subtitleText={`${modalAction === 'add' ? 'Data delivery order telah berhasil disimpan.' : 'Data delivery order telah berhasil diubah.'}`}
|
||||||
|
primaryButton={{
|
||||||
|
text: 'Oke',
|
||||||
|
color: 'primary',
|
||||||
|
className: 'rounded-lg',
|
||||||
|
onClick: (e) => {
|
||||||
|
closeModalHandler();
|
||||||
|
},
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<MemoizedDeliveryOrderProductTable
|
||||||
|
marketing={isResponseSuccess(marketing) ? marketing.data : undefined}
|
||||||
|
formType={'success'}
|
||||||
|
data={deliveryOrderValues}
|
||||||
|
onDelete={handleDeleteDO}
|
||||||
|
onEdit={handleEditDO}
|
||||||
|
onAddProductClick={handleAddDOClick}
|
||||||
|
/>
|
||||||
|
</ConfirmationModal>
|
||||||
|
|
||||||
|
<ConfirmationModalWithNotes
|
||||||
|
ref={rejectModal.ref}
|
||||||
|
type={'error'}
|
||||||
|
text={`Apakah anda yakin ingin reject data penjualan?`}
|
||||||
|
secondaryButton={{
|
||||||
|
text: 'Tidak',
|
||||||
|
onClick: rejectModal.closeModal,
|
||||||
|
}}
|
||||||
|
primaryButton={{
|
||||||
|
text: 'Ya',
|
||||||
|
color: 'error',
|
||||||
|
onClick: rejectMarketingHandler,
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<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,
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default DeliveryOrderFormModal;
|
||||||
@@ -0,0 +1,186 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
import { RefObject } from 'react';
|
||||||
|
import { useFormik } from 'formik';
|
||||||
|
import { Icon } from '@iconify/react';
|
||||||
|
import Modal from '@/components/Modal';
|
||||||
|
import Button from '@/components/Button';
|
||||||
|
import SelectInput, {
|
||||||
|
OptionType,
|
||||||
|
useSelect,
|
||||||
|
} from '@/components/input/SelectInput';
|
||||||
|
import { CustomerApi, ProductApi } from '@/services/api/master-data';
|
||||||
|
import { MARKETING_APPROVAL_LINE } from '@/config/approval-line';
|
||||||
|
import { MarketingFilter } from '@/types/api/marketing/marketing';
|
||||||
|
import SelectInputCheckbox from '@/components/input/SelectInputCheckbox';
|
||||||
|
|
||||||
|
interface MarketingFilterModal {
|
||||||
|
ref: RefObject<HTMLDialogElement | null>;
|
||||||
|
onSubmit?: (values: MarketingFilter) => void;
|
||||||
|
onReset?: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
const MarketingFilterModal = ({
|
||||||
|
ref,
|
||||||
|
onSubmit,
|
||||||
|
onReset,
|
||||||
|
}: MarketingFilterModal) => {
|
||||||
|
const closeModalHandler = () => {
|
||||||
|
ref.current?.close();
|
||||||
|
};
|
||||||
|
|
||||||
|
// ===== OPTIONS =====
|
||||||
|
const {
|
||||||
|
options: productsOptions,
|
||||||
|
isLoadingOptions: isLoadingProductsOptions,
|
||||||
|
setInputValue: setProductsInputValue,
|
||||||
|
loadMore: loadMoreProducts,
|
||||||
|
} = useSelect(ProductApi.basePath, 'id', 'name', '', {
|
||||||
|
limit: 'limit',
|
||||||
|
});
|
||||||
|
const {
|
||||||
|
options: customersOptions,
|
||||||
|
isLoadingOptions: isLoadingCustomersOptions,
|
||||||
|
setInputValue: setCustomersInputValue,
|
||||||
|
loadMore: loadMoreCustomers,
|
||||||
|
} = useSelect(CustomerApi.basePath, 'id', 'name', '', {
|
||||||
|
limit: 'limit',
|
||||||
|
});
|
||||||
|
const statusOptions = MARKETING_APPROVAL_LINE.map((item) => ({
|
||||||
|
value: item.step_name.split(' ').join('_').toUpperCase(),
|
||||||
|
label: item.step_name,
|
||||||
|
}));
|
||||||
|
|
||||||
|
const formik = useFormik<{
|
||||||
|
product_ids: OptionType[];
|
||||||
|
status: OptionType | null;
|
||||||
|
customer_id: OptionType | null;
|
||||||
|
}>({
|
||||||
|
initialValues: {
|
||||||
|
product_ids: [],
|
||||||
|
status: null,
|
||||||
|
customer_id: null,
|
||||||
|
},
|
||||||
|
|
||||||
|
onSubmit: async (values) => {
|
||||||
|
const formattedValues = {
|
||||||
|
...values,
|
||||||
|
product_ids: values.product_ids.map((item) => Number(item.value)),
|
||||||
|
status: values.status?.value.toString() || '',
|
||||||
|
customer_id: Number(values.customer_id?.value),
|
||||||
|
};
|
||||||
|
|
||||||
|
onSubmit?.(formattedValues);
|
||||||
|
closeModalHandler();
|
||||||
|
},
|
||||||
|
|
||||||
|
onReset: () => {
|
||||||
|
onReset?.();
|
||||||
|
closeModalHandler();
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const productChangeHandler = (val: OptionType | OptionType[] | null) => {
|
||||||
|
formik.setFieldValue('product_ids', val as OptionType[]);
|
||||||
|
};
|
||||||
|
|
||||||
|
const customerChangeHandler = (val: OptionType | OptionType[] | null) => {
|
||||||
|
formik.setFieldValue('customer_id', val as OptionType);
|
||||||
|
};
|
||||||
|
|
||||||
|
const statusChangeHandler = (val: OptionType | OptionType[] | null) => {
|
||||||
|
formik.setFieldValue('status', val as OptionType);
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Modal
|
||||||
|
ref={ref}
|
||||||
|
className={{
|
||||||
|
modalBox: 'p-0 rounded-xl',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<form
|
||||||
|
onSubmit={formik.handleSubmit}
|
||||||
|
onReset={formik.handleReset}
|
||||||
|
className='w-full flex flex-col'
|
||||||
|
>
|
||||||
|
{/* Modal Header */}
|
||||||
|
<div className='p-4 flex items-center justify-between gap-2 border-b border-gray-300'>
|
||||||
|
<div className='flex items-center gap-2 text-primary'>
|
||||||
|
<Icon icon='heroicons:funnel' width={20} height={20} />
|
||||||
|
<h3 className='text-sm font-medium'>Filter Data</h3>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<Button
|
||||||
|
type='button'
|
||||||
|
variant='ghost'
|
||||||
|
color='none'
|
||||||
|
onClick={closeModalHandler}
|
||||||
|
className='p-0 text-base-content/50 hover:text-base-content'
|
||||||
|
>
|
||||||
|
<Icon icon='heroicons:x-mark' width={20} height={20} />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Modal Body */}
|
||||||
|
<div className='p-4 flex flex-col gap-1.5'>
|
||||||
|
{/* select multiple product */}
|
||||||
|
<SelectInputCheckbox
|
||||||
|
label='Product'
|
||||||
|
isClearable
|
||||||
|
placeholder='Pilih product'
|
||||||
|
options={productsOptions}
|
||||||
|
isLoading={isLoadingProductsOptions}
|
||||||
|
value={formik.values.product_ids}
|
||||||
|
onChange={productChangeHandler}
|
||||||
|
onInputChange={setProductsInputValue}
|
||||||
|
onMenuScrollToBottom={loadMoreProducts}
|
||||||
|
isMulti
|
||||||
|
/>
|
||||||
|
{/* select status */}
|
||||||
|
<SelectInput
|
||||||
|
label='Status'
|
||||||
|
isClearable
|
||||||
|
placeholder='Pilih status'
|
||||||
|
options={statusOptions}
|
||||||
|
value={formik.values.status}
|
||||||
|
onChange={statusChangeHandler}
|
||||||
|
/>
|
||||||
|
{/* select customer */}
|
||||||
|
<SelectInput
|
||||||
|
label='Customer'
|
||||||
|
isClearable
|
||||||
|
placeholder='Pilih customer'
|
||||||
|
options={customersOptions}
|
||||||
|
isLoading={isLoadingCustomersOptions}
|
||||||
|
value={formik.values.customer_id}
|
||||||
|
onChange={customerChangeHandler}
|
||||||
|
onInputChange={setCustomersInputValue}
|
||||||
|
onMenuScrollToBottom={loadMoreCustomers}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Modal Footer */}
|
||||||
|
<div className='p-4 flex justify-between gap-4 border-t border-gray-300 bg-gray-100'>
|
||||||
|
<Button
|
||||||
|
type='reset'
|
||||||
|
variant='ghost'
|
||||||
|
color='none'
|
||||||
|
className='p-3 rounded-lg text-base-content/65'
|
||||||
|
>
|
||||||
|
Reset Filter
|
||||||
|
</Button>
|
||||||
|
|
||||||
|
<Button
|
||||||
|
type='submit'
|
||||||
|
className='p-3 rounded-lg w-fit sm:w-full max-w-40 text-base-100 text-sm'
|
||||||
|
>
|
||||||
|
Apply Filter
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</Modal>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default MarketingFilterModal;
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,765 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
import Button from '@/components/Button';
|
||||||
|
import AlertErrorList from '@/components/helper/form/FormErrors';
|
||||||
|
import RequirePermission from '@/components/helper/RequirePermission';
|
||||||
|
import DateInput from '@/components/input/DateInput';
|
||||||
|
import DebouncedTextArea from '@/components/input/DebouncedTextArea';
|
||||||
|
import NumberInput from '@/components/input/NumberInput';
|
||||||
|
import { OptionType, useSelect } from '@/components/input/SelectInput';
|
||||||
|
import SelectInputRadio from '@/components/input/SelectInputRadio';
|
||||||
|
import Modal, { useModal } from '@/components/Modal';
|
||||||
|
import ConfirmationModal from '@/components/modal/ConfirmationModal';
|
||||||
|
import {
|
||||||
|
DeliveryProductToFieldValues,
|
||||||
|
mergeSOwithDO,
|
||||||
|
SalesProductToFieldValues,
|
||||||
|
DeliveryOrderFormValues,
|
||||||
|
DeliveryOrderSchema,
|
||||||
|
getFilledMarketingFormInitialValues,
|
||||||
|
SalesOrderFormValues,
|
||||||
|
SalesOrderSchema,
|
||||||
|
} from '@/components/pages/marketing/form/MarketingForm.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 SalesOrderProductForm from '@/components/pages/marketing/form/repeater/sales-order/SalesOrderProductForm';
|
||||||
|
import SalesOrderProductTable from '@/components/pages/marketing/form/table-view/SalesOrderProductTable';
|
||||||
|
import { isResponseError, isResponseSuccess } from '@/lib/api-helper';
|
||||||
|
import { formatDate } from '@/lib/helper';
|
||||||
|
import {
|
||||||
|
MarketingApi,
|
||||||
|
SalesOrderApi,
|
||||||
|
} 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 { CreatedUser } from '@/types/api/api-general';
|
||||||
|
import {
|
||||||
|
CreateSalesOrderPayload,
|
||||||
|
CreateSalesOrderProductPayload,
|
||||||
|
Marketing,
|
||||||
|
UpdateDeliveryOrderPayload,
|
||||||
|
UpdateSalesOrderPayload,
|
||||||
|
} from '@/types/api/marketing/marketing';
|
||||||
|
import { Customer } from '@/types/api/master-data/customer';
|
||||||
|
import { Icon } from '@iconify/react';
|
||||||
|
import { useFormik } from 'formik';
|
||||||
|
import { useRouter, useSearchParams } from 'next/navigation';
|
||||||
|
import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||||
|
import toast from 'react-hot-toast';
|
||||||
|
import useSWR, { useSWRConfig } from 'swr';
|
||||||
|
|
||||||
|
const MemoizedSalesOrderProductTable = memo(SalesOrderProductTable);
|
||||||
|
const MemoizedSalesOrderProductForm = memo(SalesOrderProductForm);
|
||||||
|
|
||||||
|
const SalesOrderFormModal = ({
|
||||||
|
initialValues,
|
||||||
|
}: {
|
||||||
|
initialValues?: Marketing;
|
||||||
|
}) => {
|
||||||
|
const router = useRouter();
|
||||||
|
const searchParams = useSearchParams();
|
||||||
|
|
||||||
|
const modalAction = searchParams.get('action');
|
||||||
|
const marketingId = searchParams.get('id');
|
||||||
|
|
||||||
|
const isModalActionForForm =
|
||||||
|
modalAction === 'add' ||
|
||||||
|
modalAction === 'edit' ||
|
||||||
|
modalAction === 'add_delivery' ||
|
||||||
|
modalAction === 'edit_delivery';
|
||||||
|
|
||||||
|
const { mutate } = useSWRConfig();
|
||||||
|
|
||||||
|
const refreshMarketing = () => {
|
||||||
|
mutate(
|
||||||
|
(key) => typeof key === 'string' && key.includes(MarketingApi.basePath)
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
const { data: marketing, isLoading: isLoadingMarketing } = useSWR(
|
||||||
|
isModalActionForForm && marketingId
|
||||||
|
? `detail-marketing-${marketingId}`
|
||||||
|
: undefined,
|
||||||
|
() => MarketingApi.getSingle(Number(marketingId))
|
||||||
|
);
|
||||||
|
|
||||||
|
// ================== 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');
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Step 1: General Information
|
||||||
|
* Step 2: Repeater Add Product
|
||||||
|
* Step 3: Submit
|
||||||
|
*/
|
||||||
|
const [step, setStep] = useState(1);
|
||||||
|
|
||||||
|
const formModal = useModal();
|
||||||
|
const successModal = useModal();
|
||||||
|
const deleteModal = useModal();
|
||||||
|
const formRef = useRef<HTMLFormElement>(null);
|
||||||
|
const textareaRef = useRef<HTMLTextAreaElement>(null);
|
||||||
|
|
||||||
|
const [formikLastValues, setFormikLastValues] = useState<
|
||||||
|
SalesOrderFormValues | undefined
|
||||||
|
>(undefined);
|
||||||
|
const [formErrorMessage, setFormErrorMessage] = useState<string | null>(null);
|
||||||
|
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)
|
||||||
|
) ?? []
|
||||||
|
)
|
||||||
|
);
|
||||||
|
|
||||||
|
// ================== 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 || undefined,
|
||||||
|
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:
|
||||||
|
modalAction == 'add_deliver' || modalAction == 'edit_deliver'
|
||||||
|
? DeliveryOrderSchema
|
||||||
|
: SalesOrderSchema,
|
||||||
|
validateOnMount: true,
|
||||||
|
onSubmit: async (values) => {
|
||||||
|
const payload =
|
||||||
|
modalAction != 'add_deliver' && modalAction != '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) => {
|
||||||
|
// 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 {
|
||||||
|
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(String(product.unit_price || 0)),
|
||||||
|
total_weight: parseFloat(String(product.total_weight || 0)),
|
||||||
|
qty: parseFloat(String(product.qty || 0)),
|
||||||
|
avg_weight: parseFloat(String(product.avg_weight || 0)),
|
||||||
|
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 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 (modalAction) {
|
||||||
|
case 'add':
|
||||||
|
await createMarketingHandler(payload as CreateSalesOrderPayload);
|
||||||
|
break;
|
||||||
|
case 'edit':
|
||||||
|
await updateMarketingHandler(payload as UpdateSalesOrderPayload);
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
// ===== Formik Error List =====
|
||||||
|
const { formErrorList, setFormErrorList, close, handleFormSubmit } =
|
||||||
|
useFormikErrorList(formik, {
|
||||||
|
onAfterSubmit: () => {
|
||||||
|
router.push('/marketing');
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
// ================== FORM REPEATER HANDLER ==================
|
||||||
|
const createMarketingHandler = async (values: CreateSalesOrderPayload) => {
|
||||||
|
setIsLoading(true);
|
||||||
|
const createMarketingRes = await SalesOrderApi.create(values);
|
||||||
|
if (isResponseSuccess(createMarketingRes)) {
|
||||||
|
closeModalHandler(false);
|
||||||
|
successModal.openModal();
|
||||||
|
refreshMarketing();
|
||||||
|
}
|
||||||
|
if (isResponseError(createMarketingRes)) {
|
||||||
|
toast.error(createMarketingRes?.message as string);
|
||||||
|
}
|
||||||
|
setIsLoading(false);
|
||||||
|
};
|
||||||
|
const updateMarketingHandler = async (values: UpdateSalesOrderPayload) => {
|
||||||
|
setIsLoading(true);
|
||||||
|
if (!marketingId) {
|
||||||
|
toast.error('Marketing ID is required');
|
||||||
|
setIsLoading(false);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const updateMarketingRes = await SalesOrderApi.update(
|
||||||
|
Number(marketingId),
|
||||||
|
values
|
||||||
|
);
|
||||||
|
if (isResponseSuccess(updateMarketingRes)) {
|
||||||
|
closeModalHandler(false);
|
||||||
|
successModal.openModal();
|
||||||
|
refreshMarketing();
|
||||||
|
}
|
||||||
|
if (isResponseError(updateMarketingRes)) {
|
||||||
|
toast.error(updateMarketingRes?.message as string);
|
||||||
|
}
|
||||||
|
setIsLoading(false);
|
||||||
|
};
|
||||||
|
|
||||||
|
const memoSalesOrder = formik.values.sales_order;
|
||||||
|
|
||||||
|
// ================== HANDLER ==================
|
||||||
|
const nextButtonHandler = () => {
|
||||||
|
setSelectedMarketingProduct(null);
|
||||||
|
setStep(step + 1);
|
||||||
|
};
|
||||||
|
const prevButtonHandler = () => {
|
||||||
|
setStep(step - 1);
|
||||||
|
};
|
||||||
|
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 deleteClickHandler = () => {
|
||||||
|
deleteModal.openModal();
|
||||||
|
};
|
||||||
|
|
||||||
|
const confirmationModalDeleteClickHandler = async () => {
|
||||||
|
if (!marketingId) {
|
||||||
|
toast.error(`Tidak ada data yang valid untuk di hapus.`);
|
||||||
|
deleteModal.closeModal();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setIsLoading(true);
|
||||||
|
const res = await MarketingApi.delete(Number(marketingId));
|
||||||
|
deleteModal.closeModal();
|
||||||
|
toast.success(res?.message as string);
|
||||||
|
setIsLoading(false);
|
||||||
|
refreshMarketing();
|
||||||
|
closeModalHandler();
|
||||||
|
router.replace('/marketing');
|
||||||
|
};
|
||||||
|
|
||||||
|
// ================== 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 handleDeleteAllSO = useCallback(() => {
|
||||||
|
formik.setFieldValue('sales_order', []);
|
||||||
|
}, [memoSalesOrder]);
|
||||||
|
const handleEditSO = useCallback(
|
||||||
|
(id: number) => {
|
||||||
|
const currentProducts = formik.values.sales_order;
|
||||||
|
const selectedProduct = currentProducts.find((p) => p.id == id);
|
||||||
|
setSelectedMarketingProduct(selectedProduct ?? null);
|
||||||
|
setStep(2);
|
||||||
|
},
|
||||||
|
[memoSalesOrder]
|
||||||
|
);
|
||||||
|
const handleAddSOClick = useCallback(() => {
|
||||||
|
setSelectedMarketingProduct(null);
|
||||||
|
if (step === 3) {
|
||||||
|
setStep(2);
|
||||||
|
} else {
|
||||||
|
prevButtonHandler();
|
||||||
|
}
|
||||||
|
}, [step]);
|
||||||
|
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);
|
||||||
|
console.log(formik.values);
|
||||||
|
nextButtonHandler();
|
||||||
|
},
|
||||||
|
[memoSalesOrder, nextButtonHandler]
|
||||||
|
);
|
||||||
|
|
||||||
|
const isNextButtonDisabled = useMemo(() => {
|
||||||
|
if (step === 1) {
|
||||||
|
return Boolean(
|
||||||
|
!formik.values.customer_id ||
|
||||||
|
!formik.values.sales_person_id ||
|
||||||
|
!formik.values.so_date ||
|
||||||
|
!formik.values.notes
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}, [step, formik.values]);
|
||||||
|
|
||||||
|
// ================== EFFECT ==================
|
||||||
|
useEffect(() => {
|
||||||
|
if (modalAction === 'add' || modalAction === 'edit') {
|
||||||
|
formModal.openModal();
|
||||||
|
}
|
||||||
|
}, [modalAction]);
|
||||||
|
|
||||||
|
const closeModalHandler = (shouldPushToRoute: boolean = true) => {
|
||||||
|
refreshMarketing();
|
||||||
|
if (shouldPushToRoute) {
|
||||||
|
formik.resetForm();
|
||||||
|
textareaRef.current?.setAttribute('value', '');
|
||||||
|
successModal.closeModal();
|
||||||
|
router.push('/marketing');
|
||||||
|
}
|
||||||
|
|
||||||
|
setStep(1);
|
||||||
|
setFormErrorMessage('');
|
||||||
|
formModal.closeModal();
|
||||||
|
};
|
||||||
|
|
||||||
|
const grandTotal = useMemo(() => {
|
||||||
|
return memoSalesOrder.reduce(
|
||||||
|
(total, product) =>
|
||||||
|
total + parseFloat((product.total_price as string) || '0'),
|
||||||
|
0
|
||||||
|
);
|
||||||
|
}, [memoSalesOrder]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const getFilledInitialValues = async () => {
|
||||||
|
if (marketingId && isResponseSuccess(marketing)) {
|
||||||
|
const filledInitialValues = await getFilledMarketingFormInitialValues(
|
||||||
|
marketing.data
|
||||||
|
);
|
||||||
|
|
||||||
|
formik.setValues(filledInitialValues);
|
||||||
|
setStep(3);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isResponseError(marketing)) {
|
||||||
|
router.push('/marketing');
|
||||||
|
closeModalHandler();
|
||||||
|
toast.error(marketing.message);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
getFilledInitialValues();
|
||||||
|
}, [marketingId, marketing]);
|
||||||
|
|
||||||
|
// Reset error message when step changes
|
||||||
|
useEffect(() => {
|
||||||
|
setFormErrorList([]);
|
||||||
|
setFormErrorMessage('');
|
||||||
|
}, [step]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (memoSalesOrder.length === 0) {
|
||||||
|
setStep(1);
|
||||||
|
}
|
||||||
|
}, [memoSalesOrder]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<Modal
|
||||||
|
ref={formModal.ref}
|
||||||
|
position='end'
|
||||||
|
className={{
|
||||||
|
modalBox: 'w-full sm:w-fit p-3 rounded-xl bg-transparent shadow-none',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<div
|
||||||
|
onSubmit={(e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
}}
|
||||||
|
className='w-full min-h-full flex flex-col sm:flex-row items-stretch bg-base-100 rounded-xl overflow-y-auto'
|
||||||
|
>
|
||||||
|
{step <= 3 && (
|
||||||
|
<div className='w-full sm:w-[446px]'>
|
||||||
|
<div className='w-full p-4 flex flex-row items-stretch gap-3 border-b border-base-content/10'>
|
||||||
|
<Button
|
||||||
|
type='button'
|
||||||
|
variant='ghost'
|
||||||
|
color='none'
|
||||||
|
onClick={() => closeModalHandler()}
|
||||||
|
className='p-0 text-black hover:text-base-content'
|
||||||
|
>
|
||||||
|
<Icon icon='heroicons:x-mark' width={20} height={20} />
|
||||||
|
</Button>
|
||||||
|
|
||||||
|
<div className='w-px border-none bg-base-content/10' />
|
||||||
|
|
||||||
|
<h4 className='text-sm font-medium text-base-content/50'>
|
||||||
|
{modalAction === 'add' ? 'Add' : 'Edit'} Sales Order
|
||||||
|
</h4>
|
||||||
|
</div>
|
||||||
|
<form
|
||||||
|
className='w-full p-4 flex flex-col border-b border-base-content/10'
|
||||||
|
ref={formRef}
|
||||||
|
onSubmit={handleFormSubmit}
|
||||||
|
>
|
||||||
|
<h4 className='text-base font-medium text-base-content/50 font-roboto'>
|
||||||
|
Informasi Order
|
||||||
|
</h4>
|
||||||
|
|
||||||
|
<SelectInputRadio
|
||||||
|
required
|
||||||
|
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={
|
||||||
|
modalAction === 'add_deliver' ||
|
||||||
|
modalAction === 'edit_deliver' ||
|
||||||
|
modalAction === 'edit'
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
<DateInput
|
||||||
|
required
|
||||||
|
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={
|
||||||
|
modalAction == 'add_deliver' ||
|
||||||
|
modalAction == 'edit_deliver'
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
<SelectInputRadio
|
||||||
|
required
|
||||||
|
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={
|
||||||
|
modalAction === 'add_deliver' ||
|
||||||
|
modalAction === 'edit_deliver'
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
<DebouncedTextArea
|
||||||
|
ref={textareaRef}
|
||||||
|
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={
|
||||||
|
modalAction === 'add_deliver' ||
|
||||||
|
modalAction === 'edit_deliver'
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
<NumberInput
|
||||||
|
name='total_price'
|
||||||
|
label='Total Penjualan'
|
||||||
|
value={grandTotal}
|
||||||
|
disabled={
|
||||||
|
grandTotal === 0 && formik.values.sales_order.length === 0
|
||||||
|
}
|
||||||
|
readOnly
|
||||||
|
startAdornment={
|
||||||
|
<span className='font-semibold py-1 text-xs'>Rp</span>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
<AlertErrorList
|
||||||
|
className={{
|
||||||
|
alert: 'w-full mt-4',
|
||||||
|
}}
|
||||||
|
formErrorList={formErrorList}
|
||||||
|
onClose={close}
|
||||||
|
/>
|
||||||
|
</form>
|
||||||
|
|
||||||
|
<div className='w-full p-4'>
|
||||||
|
{step === 1 && (
|
||||||
|
<Button
|
||||||
|
type='button'
|
||||||
|
onClick={nextButtonHandler}
|
||||||
|
disabled={isNextButtonDisabled}
|
||||||
|
className='w-full rounded-lg text-sm text-base-100'
|
||||||
|
>
|
||||||
|
Tambah Produk
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{step === 2 && (
|
||||||
|
<div className='w-full min-h-full flex flex-col sm:w-[446px] border-l border-base-content/10'>
|
||||||
|
<div className='w-full p-4 flex flex-row items-center justify-between gap-3 border-b border-base-content/10'>
|
||||||
|
<div className='w-full flex flex-row items-stretch gap-3'>
|
||||||
|
{memoSalesOrder.length > 0 && (
|
||||||
|
<>
|
||||||
|
<Button
|
||||||
|
type='button'
|
||||||
|
variant='ghost'
|
||||||
|
color='none'
|
||||||
|
onClick={() => {
|
||||||
|
setStep(3);
|
||||||
|
}}
|
||||||
|
className='p-0 text-black hover:text-base-content'
|
||||||
|
>
|
||||||
|
<Icon
|
||||||
|
icon='heroicons:chevron-left'
|
||||||
|
width={20}
|
||||||
|
height={20}
|
||||||
|
/>
|
||||||
|
</Button>
|
||||||
|
|
||||||
|
<div className='w-px border-none bg-base-content/10' />
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<h4 className='text-sm font-medium text-base-content/50'>
|
||||||
|
{selectedMarketingProduct?.id ? 'Ubah' : 'Tambah'} Produk
|
||||||
|
</h4>
|
||||||
|
</div>
|
||||||
|
<RequirePermission permissions='lti.marketing.sales_order.delete'>
|
||||||
|
<Button
|
||||||
|
type='button'
|
||||||
|
variant='ghost'
|
||||||
|
color='none'
|
||||||
|
onClick={deleteClickHandler}
|
||||||
|
className='p-0 text-error hover:text-base-content'
|
||||||
|
>
|
||||||
|
<Icon icon='heroicons:trash' width={20} height={20} />
|
||||||
|
</Button>
|
||||||
|
</RequirePermission>
|
||||||
|
</div>
|
||||||
|
<div className='flex flex-1 flex-col'>
|
||||||
|
<MemoizedSalesOrderProductForm
|
||||||
|
key={selectedMarketingProduct?.id ?? 'new'}
|
||||||
|
onSubmitForm={handleAddSubmitSO}
|
||||||
|
initialValues={selectedMarketingProduct ?? undefined}
|
||||||
|
exisitingValues={memoSalesOrder}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{step === 3 && (
|
||||||
|
<div className='w-full min-h-full flex flex-col sm:w-[446px] border-l border-base-content/10 relative'>
|
||||||
|
<div className='w-full p-4 flex flex-row items-center justify-between gap-3 border-b border-base-content/10'>
|
||||||
|
<h4 className='text-sm font-medium text-base-content/50'>
|
||||||
|
Informasi Produk
|
||||||
|
</h4>
|
||||||
|
<RequirePermission permissions='lti.marketing.sales_order.delete'>
|
||||||
|
<Button
|
||||||
|
type='button'
|
||||||
|
variant='ghost'
|
||||||
|
color='none'
|
||||||
|
onClick={deleteClickHandler}
|
||||||
|
className='p-0 text-error hover:text-base-content'
|
||||||
|
>
|
||||||
|
<Icon icon='heroicons:trash' width={20} height={20} />
|
||||||
|
</Button>
|
||||||
|
</RequirePermission>
|
||||||
|
</div>
|
||||||
|
<div className='flex flex-1 flex-col'>
|
||||||
|
{memoSalesOrder.length > 0 && (
|
||||||
|
<div className='px-4 pt-4'>
|
||||||
|
<MemoizedSalesOrderProductTable
|
||||||
|
formType={(modalAction || 'add') as 'add' | 'edit'}
|
||||||
|
data={memoSalesOrder}
|
||||||
|
onDelete={handleDeleteSO}
|
||||||
|
onEdit={handleEditSO}
|
||||||
|
onAddProductClick={handleAddSOClick}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
<div className='p-4 w-full'>
|
||||||
|
<Button
|
||||||
|
type='button'
|
||||||
|
className='justify-center w-full p-3 rounded-lg text-center text-sm text-base-100'
|
||||||
|
onClick={() => formRef.current?.requestSubmit()}
|
||||||
|
>
|
||||||
|
Submit
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</Modal>
|
||||||
|
<ConfirmationModal
|
||||||
|
ref={successModal.ref}
|
||||||
|
iconPosition='left'
|
||||||
|
type='success'
|
||||||
|
text={`${modalAction === 'add' ? 'Data Berhasil Ditambahkan' : 'Data Berhasil Diubah'}`}
|
||||||
|
subtitleText={`${modalAction === 'add' ? 'Data sales order telah berhasil disimpan.' : 'Data sales order telah berhasil diubah.'}`}
|
||||||
|
primaryButton={{
|
||||||
|
text: 'Oke',
|
||||||
|
color: 'primary',
|
||||||
|
className: 'rounded-lg',
|
||||||
|
onClick: (e) => {
|
||||||
|
closeModalHandler();
|
||||||
|
},
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<MemoizedSalesOrderProductTable
|
||||||
|
formType={'success'}
|
||||||
|
data={memoSalesOrder}
|
||||||
|
onDelete={handleDeleteSO}
|
||||||
|
onEdit={handleEditSO}
|
||||||
|
onAddProductClick={handleAddSOClick}
|
||||||
|
/>
|
||||||
|
</ConfirmationModal>
|
||||||
|
|
||||||
|
<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,
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default SalesOrderFormModal;
|
||||||
@@ -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;
|
|
||||||
@@ -7,6 +7,12 @@ import {
|
|||||||
DeliveryOrderProductFormValues,
|
DeliveryOrderProductFormValues,
|
||||||
DeliveryOrderProductSchema,
|
DeliveryOrderProductSchema,
|
||||||
} from '@/components/pages/marketing/form/repeater/delivery-order/DeliverOrderProduct.schema';
|
} from '@/components/pages/marketing/form/repeater/delivery-order/DeliverOrderProduct.schema';
|
||||||
|
import {
|
||||||
|
BaseDeliveryOrder,
|
||||||
|
BaseSalesOrder,
|
||||||
|
Marketing,
|
||||||
|
} from '@/types/api/marketing/marketing';
|
||||||
|
import { formatDate, formatTitleCase } from '@/lib/helper';
|
||||||
|
|
||||||
type MarketingSchemaType = {
|
type MarketingSchemaType = {
|
||||||
customer_id: number | undefined;
|
customer_id: number | undefined;
|
||||||
@@ -64,7 +70,7 @@ export const DeliveryOrderSchema: Yup.ObjectSchema<DeliveryOrderSchemaType> =
|
|||||||
.required('Pengiriman wajib diisi!')
|
.required('Pengiriman wajib diisi!')
|
||||||
.test(
|
.test(
|
||||||
'at-least-one-valid-row',
|
'at-least-one-valid-row',
|
||||||
'Minimal ada satu baris pengiriman yang valid!',
|
'Minimal harus ada satu baris pengiriman yang lengkap diisi!',
|
||||||
function (items) {
|
function (items) {
|
||||||
if (!items || items.length === 0) return false;
|
if (!items || items.length === 0) return false;
|
||||||
|
|
||||||
@@ -86,3 +92,172 @@ export const UpdateSalesOrderSchema = SalesOrderSchema;
|
|||||||
export type SalesOrderFormValues = Yup.InferType<typeof SalesOrderSchema>;
|
export type SalesOrderFormValues = Yup.InferType<typeof SalesOrderSchema>;
|
||||||
|
|
||||||
export type DeliveryOrderFormValues = Yup.InferType<typeof DeliveryOrderSchema>;
|
export type DeliveryOrderFormValues = Yup.InferType<typeof DeliveryOrderSchema>;
|
||||||
|
|
||||||
|
// ================ Helper Function ================
|
||||||
|
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_data: product.product_warehouse,
|
||||||
|
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,
|
||||||
|
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,
|
||||||
|
};
|
||||||
|
};
|
||||||
|
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
|
||||||
|
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;
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
export const getFilledMarketingFormInitialValues = (
|
||||||
|
marketing: Marketing
|
||||||
|
): SalesOrderFormValues & DeliveryOrderFormValues => {
|
||||||
|
return {
|
||||||
|
customer_id: marketing.customer.id,
|
||||||
|
sales_person_id: marketing.sales_person.id,
|
||||||
|
sales_person: {
|
||||||
|
value: marketing.sales_person.id,
|
||||||
|
label: marketing.sales_person.name,
|
||||||
|
},
|
||||||
|
customer: {
|
||||||
|
value: marketing.customer.id,
|
||||||
|
label: marketing.customer.name,
|
||||||
|
},
|
||||||
|
so_date: formatDate(marketing.so_date, 'yyyy-MM-DD'),
|
||||||
|
notes: marketing.notes,
|
||||||
|
sales_order: marketing.sales_order.map((so) =>
|
||||||
|
SalesProductToFieldValues(so)
|
||||||
|
),
|
||||||
|
delivery_order: mergeSOwithDO(
|
||||||
|
marketing.sales_order?.map(SalesProductToFieldValues) ?? [],
|
||||||
|
marketing.delivery_order?.flatMap((delivery) =>
|
||||||
|
DeliveryProductToFieldValues(marketing.sales_order, delivery)
|
||||||
|
) ?? [],
|
||||||
|
marketing.latest_approval.step_number > 1
|
||||||
|
),
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
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 SalesOrderProductTable from '@/components/pages/marketing/form/table-view/SalesOrderProductTable';
|
|
||||||
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 MemoizedSalesOrderProductTable = memo(SalesOrderProductTable);
|
|
||||||
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[]
|
|
||||||
): 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: delivery?.unit_price,
|
|
||||||
total_weight: delivery?.total_weight,
|
|
||||||
qty: delivery?.qty,
|
|
||||||
avg_weight: delivery?.avg_weight,
|
|
||||||
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
|
|
||||||
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;
|
|
||||||
+61
@@ -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<
|
||||||
|
|||||||
+526
-199
@@ -1,4 +1,4 @@
|
|||||||
import { useEffect, useState } from 'react';
|
import { useEffect, useMemo, useState } from 'react';
|
||||||
import {
|
import {
|
||||||
DeliveryOrderProductFormValues,
|
DeliveryOrderProductFormValues,
|
||||||
DeliveryOrderProductSchema,
|
DeliveryOrderProductSchema,
|
||||||
@@ -8,21 +8,26 @@ 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 SelectInput, { OptionType } from '@/components/input/SelectInput';
|
|
||||||
import { BaseSalesOrder } from '@/types/api/marketing/marketing';
|
import { BaseSalesOrder } from '@/types/api/marketing/marketing';
|
||||||
import Badge from '@/components/Badge';
|
import { SalesProductToFieldValues } from '@/components/pages/marketing/form/MarketingForm.schema';
|
||||||
import { SalesProductToFieldValues } from '@/components/pages/marketing/form/MarketingForm';
|
|
||||||
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';
|
||||||
import { useFormikErrorList } from '@/services/hooks/useFormikErrorList';
|
import { useFormikErrorList } from '@/services/hooks/useFormikErrorList';
|
||||||
import useSWR from 'swr';
|
import useSWR from 'swr';
|
||||||
import { ProductApi } from '@/services/api/master-data';
|
import { ProductApi } from '@/services/api/master-data';
|
||||||
|
import StatusBadge from '@/components/helper/StatusBadge';
|
||||||
const roundWeight = (value: number) => Number(value.toFixed(2));
|
import SelectInputRadio from '@/components/input/SelectInputRadio';
|
||||||
const roundPrice = (value: number) => Math.round(value);
|
import { OptionType } from '@/components/input/SelectInput';
|
||||||
|
import {
|
||||||
|
MARKETING_CONVERTION_UNIT_OPTIONS,
|
||||||
|
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,
|
||||||
@@ -48,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
|
||||||
@@ -59,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
|
||||||
);
|
);
|
||||||
@@ -76,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({
|
||||||
@@ -123,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);
|
||||||
@@ -131,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;
|
||||||
|
|
||||||
@@ -228,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,
|
||||||
@@ -242,27 +257,83 @@ 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 (
|
||||||
<>
|
<>
|
||||||
<form
|
<form
|
||||||
className='size-full'
|
className='size-full flex flex-col relative gap-1.5'
|
||||||
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'
|
||||||
|
>
|
||||||
|
<Alert color='error'>{formikErrorMessage}</Alert>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
<div className='grid sm:grid-cols-3 gap-4'>
|
{/* Tanggal Pengiriman */}
|
||||||
<SelectInput
|
<DateInput
|
||||||
|
name='delivery_date'
|
||||||
|
label='Tanggal'
|
||||||
|
value={formik.values.delivery_date ?? undefined}
|
||||||
|
onChange={formik.handleChange}
|
||||||
|
onBlur={formik.handleBlur}
|
||||||
|
isError={
|
||||||
|
formik.touched.delivery_date &&
|
||||||
|
Boolean(formik.errors.delivery_date)
|
||||||
|
}
|
||||||
|
errorMessage={formik.errors.delivery_date}
|
||||||
|
placeholder='Pilih Tanggal'
|
||||||
|
className={{
|
||||||
|
inputWrapper: 'bg-white',
|
||||||
|
}}
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
|
||||||
|
{/* No. Polisi */}
|
||||||
|
<PatternInput
|
||||||
|
name='vehicle_number'
|
||||||
|
label='No. Polisi'
|
||||||
|
format='AA #### AAA'
|
||||||
|
mask='_'
|
||||||
|
inputVehicleNumber
|
||||||
|
required
|
||||||
|
type='text'
|
||||||
|
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}
|
options={options}
|
||||||
label='Produk'
|
label='Produk'
|
||||||
placeholder='Pilih Produk'
|
placeholder='Pilih Produk'
|
||||||
isDisabled={formState == 'edit'}
|
readOnly={formState == 'edit'}
|
||||||
value={
|
value={
|
||||||
selectedProduct
|
selectedProduct
|
||||||
? ({
|
? ({
|
||||||
@@ -309,18 +380,17 @@ const DeliveryOrderProductForm = ({
|
|||||||
}}
|
}}
|
||||||
startAdornment={
|
startAdornment={
|
||||||
selectedProduct && (
|
selectedProduct && (
|
||||||
<Badge
|
<StatusBadge
|
||||||
variant='soft'
|
text={
|
||||||
color='success'
|
|
||||||
size='sm'
|
|
||||||
className={{ badge: 'whitespace-nowrap font-semibold' }}
|
|
||||||
>
|
|
||||||
{
|
|
||||||
exisitingValues?.find(
|
exisitingValues?.find(
|
||||||
(item) => item.id === selectedProduct?.value
|
(item) => item.id === selectedProduct?.value
|
||||||
)?.marketing_product?.kandang?.label
|
)?.marketing_product?.kandang?.label ?? ''
|
||||||
}
|
}
|
||||||
</Badge>
|
color='success'
|
||||||
|
className={{
|
||||||
|
badge: 'whitespace-nowrap w-fit font-semibold',
|
||||||
|
}}
|
||||||
|
/>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
isClearable
|
isClearable
|
||||||
@@ -328,45 +398,214 @@ const DeliveryOrderProductForm = ({
|
|||||||
errorMessage={formik.errors.marketing_product_id}
|
errorMessage={formik.errors.marketing_product_id}
|
||||||
required
|
required
|
||||||
/>
|
/>
|
||||||
<DateInput
|
|
||||||
name='delivery_date'
|
{/* Kategori */}
|
||||||
label='Tanggal'
|
<SelectInputRadio
|
||||||
value={formik.values.delivery_date ?? undefined}
|
|
||||||
onChange={formik.handleChange}
|
|
||||||
onBlur={formik.handleBlur}
|
|
||||||
isError={
|
|
||||||
formik.touched.delivery_date &&
|
|
||||||
Boolean(formik.errors.delivery_date)
|
|
||||||
}
|
|
||||||
errorMessage={formik.errors.delivery_date}
|
|
||||||
placeholder='Pilih Tanggal'
|
|
||||||
className={{
|
|
||||||
inputWrapper: 'bg-white',
|
|
||||||
}}
|
|
||||||
required
|
required
|
||||||
|
label='Kategori '
|
||||||
|
options={MARKETING_TYPE_OPTIONS}
|
||||||
|
value={formik.values.marketing_type}
|
||||||
|
onChange={(val) => {
|
||||||
|
formik.setFieldValue('marketing_type', val);
|
||||||
|
}}
|
||||||
|
isClearable
|
||||||
|
placeholder='Pilih Kategori'
|
||||||
|
isDisabled
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<PatternInput
|
{/* Konversi Satuan Telur */}
|
||||||
name='vehicle_number'
|
{formik.values.marketing_type &&
|
||||||
label='No. Polisi'
|
formik.values.marketing_type.value.toLowerCase() === 'telur' &&
|
||||||
format='AA #### AAA'
|
(!formik.values.convertion_unit ||
|
||||||
mask='_'
|
formik.values.convertion_unit.value.toLowerCase() !== 'peti') && (
|
||||||
inputVehicleNumber
|
<SelectInputRadio
|
||||||
required
|
required
|
||||||
type='text'
|
label='Tipe Konversi'
|
||||||
placeholder='B 1234 CDE'
|
options={MARKETING_CONVERTION_UNIT_OPTIONS}
|
||||||
value={formatVechicleNumber(formik.values.vehicle_number ?? '')}
|
value={formik.values.convertion_unit}
|
||||||
onChange={formik.handleChange}
|
onChange={(val) => formik.setFieldValue('convertion_unit', val)}
|
||||||
onBlur={formik.handleBlur}
|
isClearable
|
||||||
isError={Boolean(formik.errors.vehicle_number)}
|
placeholder='Pilih Konversi Satuan'
|
||||||
errorMessage={formik.errors.vehicle_number}
|
/>
|
||||||
/>
|
)}
|
||||||
</div>
|
{formik.values.convertion_unit &&
|
||||||
<div className='divider my-6'></div>
|
formik.values.convertion_unit.value.toLowerCase() === 'peti' && (
|
||||||
<div className='grid sm:grid-cols-3 gap-4'>
|
<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
|
<NumberInput
|
||||||
required
|
required
|
||||||
label='Kuantitas'
|
label={
|
||||||
|
formik.values.marketing_type &&
|
||||||
|
formik.values.marketing_type.value.toLowerCase() === 'telur'
|
||||||
|
? `Total Butir Telur`
|
||||||
|
: `Total Kuantitas`
|
||||||
|
}
|
||||||
name='qty'
|
name='qty'
|
||||||
value={formik.values.qty}
|
value={formik.values.qty}
|
||||||
onChange={(e) => {
|
onChange={(e) => {
|
||||||
@@ -399,49 +638,130 @@ const DeliveryOrderProductForm = ({
|
|||||||
: ''
|
: ''
|
||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
<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'
|
|
||||||
/>
|
|
||||||
|
|
||||||
|
{/* 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>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{hasSisaBerat && (
|
||||||
|
<>
|
||||||
|
<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
|
<NumberInput
|
||||||
required
|
required
|
||||||
label='Total Penjualan (Rp)'
|
label='Total Penjualan (Rp)'
|
||||||
@@ -452,22 +772,29 @@ const DeliveryOrderProductForm = ({
|
|||||||
setCurrentInput(e.target.name);
|
setCurrentInput(e.target.name);
|
||||||
}}
|
}}
|
||||||
onBlur={() => handleBlurField('total_price')}
|
onBlur={() => handleBlurField('total_price')}
|
||||||
isError={Boolean(formik.errors.total_price)}
|
isError={
|
||||||
|
formik.touched.total_price && Boolean(formik.errors.total_price)
|
||||||
|
}
|
||||||
errorMessage={formik.errors.total_price}
|
errorMessage={formik.errors.total_price}
|
||||||
placeholder='Masukan Total Penjualan'
|
placeholder='Masukan Total Penjualan'
|
||||||
/>
|
/>
|
||||||
|
|
||||||
|
<AlertErrorList
|
||||||
|
className={{
|
||||||
|
alert: 'w-full my-4',
|
||||||
|
}}
|
||||||
|
formErrorList={formErrorList}
|
||||||
|
onClose={close}
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
<div className='h-18' />
|
||||||
|
|
||||||
<AlertErrorList formErrorList={formErrorList} onClose={close} />
|
<div className='absolute sm:w-full bottom-0 right-0 p-4'>
|
||||||
|
|
||||||
<div className='flex flex-row justify-end gap-3 mt-4'>
|
|
||||||
<Button type='reset' color='warning'>
|
|
||||||
Reset
|
|
||||||
</Button>
|
|
||||||
<Button
|
<Button
|
||||||
type='submit'
|
type='submit'
|
||||||
isLoading={formik.isSubmitting}
|
isLoading={formik.isSubmitting}
|
||||||
disabled={formik.isSubmitting}
|
disabled={formik.isSubmitting}
|
||||||
|
className='w-full p-3 rounded-lg text-base-100 text-sm font-semibold'
|
||||||
>
|
>
|
||||||
Submit
|
Submit
|
||||||
</Button>
|
</Button>
|
||||||
|
|||||||
@@ -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<
|
||||||
|
|||||||
+479
-193
@@ -5,31 +5,32 @@ 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 SelectInput, {
|
import { OptionType, useSelect } from '@/components/input/SelectInput';
|
||||||
OptionType,
|
|
||||||
useSelect,
|
|
||||||
} from '@/components/input/SelectInput';
|
|
||||||
import { Kandang } from '@/types/api/master-data/kandang';
|
import { Kandang } from '@/types/api/master-data/kandang';
|
||||||
import { ProductApi, UomApi, WarehouseApi } from '@/services/api/master-data';
|
import { WarehouseApi } from '@/services/api/master-data';
|
||||||
import { ProductWarehouse } from '@/types/api/inventory/product-warehouse';
|
import { ProductWarehouse } from '@/types/api/inventory/product-warehouse';
|
||||||
import { ProductWarehouseApi } from '@/services/api/inventory';
|
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 {
|
import {
|
||||||
formatCurrency,
|
|
||||||
formatNumber,
|
formatNumber,
|
||||||
|
formatTitleCase,
|
||||||
formatVechicleNumber,
|
formatVechicleNumber,
|
||||||
} from '@/lib/helper';
|
} 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 useSWR from 'swr';
|
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,
|
||||||
@@ -49,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,
|
||||||
@@ -64,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) => {
|
||||||
@@ -83,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,
|
||||||
@@ -96,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() ?? '',
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -128,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: '',
|
||||||
@@ -148,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,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
@@ -155,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 =====
|
||||||
@@ -279,21 +264,29 @@ const SalesOrderProductForm = ({
|
|||||||
}
|
}
|
||||||
);
|
);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
handleBlurField('week');
|
||||||
|
}, [formik.values.week]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<form
|
<form
|
||||||
className='size-full'
|
className='size-full flex flex-col gap-1.5 relative'
|
||||||
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'>
|
||||||
<div className='grid sm:grid-cols-3 gap-4 z-200'>
|
{formErrorMessage ? formErrorMessage : ''}
|
||||||
|
</Alert>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{/* Nomor Polisi */}
|
||||||
<PatternInput
|
<PatternInput
|
||||||
name='vehicle_number'
|
name='vehicle_number'
|
||||||
label='No. Polisi'
|
label='No. Polisi'
|
||||||
@@ -312,9 +305,11 @@ const SalesOrderProductForm = ({
|
|||||||
}
|
}
|
||||||
errorMessage={formik.errors.vehicle_number}
|
errorMessage={formik.errors.vehicle_number}
|
||||||
/>
|
/>
|
||||||
<SelectInput
|
|
||||||
|
{/* Gudang */}
|
||||||
|
<SelectInputRadio
|
||||||
required
|
required
|
||||||
label='Kandang'
|
label='Gudang'
|
||||||
options={kandangSourceOptions}
|
options={kandangSourceOptions}
|
||||||
isLoading={isLoadingKandangSourceOptions}
|
isLoading={isLoadingKandangSourceOptions}
|
||||||
value={formik.values.kandang}
|
value={formik.values.kandang}
|
||||||
@@ -326,9 +321,30 @@ const SalesOrderProductForm = ({
|
|||||||
formik.touched.kandang_id && Boolean(formik.errors.kandang_id)
|
formik.touched.kandang_id && Boolean(formik.errors.kandang_id)
|
||||||
}
|
}
|
||||||
errorMessage={formik.errors.kandang_id}
|
errorMessage={formik.errors.kandang_id}
|
||||||
placeholder='Pilih Kandang'
|
placeholder='Pilih Gudang'
|
||||||
/>
|
/>
|
||||||
<SelectInput
|
|
||||||
|
{/* Kategori */}
|
||||||
|
<SelectInputRadio
|
||||||
|
required
|
||||||
|
label='Kategori '
|
||||||
|
options={MARKETING_TYPE_OPTIONS}
|
||||||
|
value={formik.values.marketing_type}
|
||||||
|
onChange={(val) => {
|
||||||
|
formik.setFieldValue('marketing_type', val);
|
||||||
|
warehouseChangeHandler(null);
|
||||||
|
formik.setFieldValue('product_warehouse', null);
|
||||||
|
formik.setFieldValue('product_warehouse_id', null);
|
||||||
|
formik.setFieldValue('convertion_unit', null);
|
||||||
|
formik.setFieldValue('weight_per_convertion', null);
|
||||||
|
formik.setFieldValue('total_peti', null);
|
||||||
|
}}
|
||||||
|
isClearable
|
||||||
|
placeholder='Pilih Kategori'
|
||||||
|
/>
|
||||||
|
|
||||||
|
{/* Produk */}
|
||||||
|
<SelectInputRadio
|
||||||
required
|
required
|
||||||
label='Produk'
|
label='Produk'
|
||||||
options={productOptionsFiltered}
|
options={productOptionsFiltered}
|
||||||
@@ -352,12 +368,200 @@ const SalesOrderProductForm = ({
|
|||||||
}
|
}
|
||||||
errorMessage={formik.errors.product_warehouse_id}
|
errorMessage={formik.errors.product_warehouse_id}
|
||||||
/>
|
/>
|
||||||
</div>
|
|
||||||
<div className='divider my-6'></div>
|
{/* Konversi Satuan Telur */}
|
||||||
<div className='grid sm:grid-cols-3 gap-4 z-200'>
|
{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
|
<NumberInput
|
||||||
required
|
required
|
||||||
label='Kuantitas'
|
label={
|
||||||
|
formik.values.marketing_type &&
|
||||||
|
formik.values.marketing_type.value.toLowerCase() === 'telur'
|
||||||
|
? `Total Butir Telur`
|
||||||
|
: `Total Kuantitas`
|
||||||
|
}
|
||||||
name='qty'
|
name='qty'
|
||||||
value={formik.values.qty}
|
value={formik.values.qty}
|
||||||
onChange={(e) => {
|
onChange={(e) => {
|
||||||
@@ -369,11 +573,13 @@ const SalesOrderProductForm = ({
|
|||||||
errorMessage={formik.errors.qty}
|
errorMessage={formik.errors.qty}
|
||||||
placeholder='Masukan Kuantitas'
|
placeholder='Masukan Kuantitas'
|
||||||
endAdornment={
|
endAdornment={
|
||||||
<div className='flex items-center gap-2'>
|
formik.values.uom ? (
|
||||||
<span className='text-sm text-gray-500'>
|
<div className='flex items-center gap-2'>
|
||||||
{selectedProductWarehouse?.product?.uom?.name}
|
<span className='text-sm text-base-content/50'>
|
||||||
</span>
|
{formik.values.uom}
|
||||||
</div>
|
</span>
|
||||||
|
</div>
|
||||||
|
) : undefined
|
||||||
}
|
}
|
||||||
bottomLabel={
|
bottomLabel={
|
||||||
isResponseSuccess(warehouseSourceRawData) &&
|
isResponseSuccess(warehouseSourceRawData) &&
|
||||||
@@ -382,58 +588,136 @@ const SalesOrderProductForm = ({
|
|||||||
warehouseSourceRawData?.data?.find(
|
warehouseSourceRawData?.data?.find(
|
||||||
(item) => item.id === formik.values.product_warehouse_id
|
(item) => item.id === formik.values.product_warehouse_id
|
||||||
)?.quantity ?? 0
|
)?.quantity ?? 0
|
||||||
)} ${selectedProductWarehouse?.product?.uom?.name}`
|
)} ${formik.values.uom}`
|
||||||
: ''
|
: ''
|
||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
<NumberInput
|
|
||||||
required
|
{/* Harga per convertion unit (PETI / KG) */}
|
||||||
label={`Harga / ${selectedProductWarehouse?.product?.uom?.name ?? 'Produk'} (Rp)`}
|
{(formik.values.convertion_unit?.value.toLowerCase() === 'peti' ||
|
||||||
name='unit_price'
|
formik.values.convertion_unit?.value.toLowerCase() === 'kg') && (
|
||||||
value={formik.values.unit_price}
|
<NumberInput
|
||||||
onChange={(e) => {
|
required
|
||||||
formik.handleChange(e);
|
label={`Harga / ${formik.values.convertion_unit?.label ?? 'Produk'} (Rp)`}
|
||||||
setCurrentInput(e.target.name);
|
name='price_per_convertion'
|
||||||
}}
|
value={formik.values.price_per_convertion ?? undefined}
|
||||||
onBlur={() => handleBlurField('unit_price')}
|
onChange={(e) => {
|
||||||
isError={
|
formik.handleChange(e);
|
||||||
formik.touched.unit_price && Boolean(formik.errors.unit_price)
|
setCurrentInput(e.target.name);
|
||||||
}
|
}}
|
||||||
errorMessage={formik.errors.unit_price}
|
onBlur={() => handleBlurField('price_per_convertion')}
|
||||||
placeholder='Masukan Harga Satuan'
|
isError={
|
||||||
/>
|
formik.touched.price_per_convertion &&
|
||||||
<NumberInput
|
Boolean(formik.errors.price_per_convertion)
|
||||||
required
|
}
|
||||||
label='Avg. Bobot (Kg)'
|
errorMessage={formik.errors.price_per_convertion}
|
||||||
name='avg_weight'
|
placeholder='Masukan Harga Satuan'
|
||||||
value={formik.values.avg_weight}
|
/>
|
||||||
onChange={(e) => {
|
)}
|
||||||
formik.handleChange(e);
|
|
||||||
setCurrentInput(e.target.name);
|
{/* Harga per butir untuk TELUR + QTY */}
|
||||||
}}
|
{formik.values.marketing_type?.value.toLowerCase() === 'telur' &&
|
||||||
onBlur={() => handleBlurField('avg_weight')}
|
formik.values.convertion_unit?.value.toLowerCase() === 'qty' && (
|
||||||
isError={
|
<NumberInput
|
||||||
formik.touched.avg_weight && Boolean(formik.errors.avg_weight)
|
required
|
||||||
}
|
label='Harga / Butir (Rp)'
|
||||||
errorMessage={formik.errors.avg_weight}
|
name='price_per_qty'
|
||||||
placeholder='Masukan Bobot Rata-rata'
|
value={formik.values.price_per_qty ?? undefined}
|
||||||
/>
|
onChange={(e) => {
|
||||||
<NumberInput
|
formik.setFieldValue('price_per_qty', Number(e.target.value));
|
||||||
required
|
setCurrentInput('price_per_qty');
|
||||||
label='Total Bobot (Kg)'
|
}}
|
||||||
name='total_weight'
|
onBlur={() => handleBlurField('price_per_qty')}
|
||||||
value={formik.values.total_weight}
|
isError={
|
||||||
onChange={(e) => {
|
formik.touched.price_per_qty &&
|
||||||
formik.handleChange(e);
|
Boolean(formik.errors.price_per_qty)
|
||||||
setCurrentInput(e.target.name);
|
}
|
||||||
}}
|
errorMessage={formik.errors.price_per_qty}
|
||||||
onBlur={() => handleBlurField('total_weight')}
|
placeholder='Masukan Harga per Butir'
|
||||||
isError={
|
/>
|
||||||
formik.touched.total_weight && Boolean(formik.errors.total_weight)
|
)}
|
||||||
}
|
|
||||||
errorMessage={formik.errors.total_weight}
|
{/* Harga Satuan per Uom Produk Warehouse */}
|
||||||
placeholder='Masukan Total Bobot'
|
{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>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{hasSisaBerat && (
|
||||||
|
<>
|
||||||
|
<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
|
<NumberInput
|
||||||
required
|
required
|
||||||
label='Total Penjualan (Rp)'
|
label='Total Penjualan (Rp)'
|
||||||
@@ -450,20 +734,22 @@ const SalesOrderProductForm = ({
|
|||||||
errorMessage={formik.errors.total_price}
|
errorMessage={formik.errors.total_price}
|
||||||
placeholder='Masukan Total Penjualan'
|
placeholder='Masukan Total Penjualan'
|
||||||
/>
|
/>
|
||||||
|
|
||||||
|
{formErrorList.length > 0 && (
|
||||||
|
<div className='mt-4'>
|
||||||
|
<AlertErrorList formErrorList={formErrorList} onClose={close} />
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className='mt-4'>
|
<div className='h-18' />
|
||||||
<AlertErrorList formErrorList={formErrorList} onClose={close} />
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className='flex flex-row justify-end gap-3 mt-4'>
|
<div className='absolute w-full bottom-0 right-0 p-4'>
|
||||||
<Button type='reset' color='warning' onClick={handleResetForm}>
|
|
||||||
Reset
|
|
||||||
</Button>
|
|
||||||
<Button
|
<Button
|
||||||
type='submit'
|
type='submit'
|
||||||
isLoading={formik.isSubmitting}
|
isLoading={formik.isSubmitting}
|
||||||
disabled={formik.isSubmitting}
|
disabled={formik.isSubmitting}
|
||||||
|
className='w-full p-3 rounded-lg text-base-100'
|
||||||
>
|
>
|
||||||
Submit
|
Submit
|
||||||
</Button>
|
</Button>
|
||||||
|
|||||||
@@ -1,21 +1,27 @@
|
|||||||
import Table from '@/components/Table';
|
|
||||||
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 Button from '@/components/Button';
|
import Button from '@/components/Button';
|
||||||
import { Icon } from '@iconify/react';
|
import { Icon } from '@iconify/react';
|
||||||
import * as TanStack from '@tanstack/react-table';
|
import { useRef } from 'react';
|
||||||
import { useMemo, useRef } from 'react';
|
import { formatCurrency, formatDate, formatNumber } from '@/lib/helper';
|
||||||
import {
|
import DeliveryOrderExport from '@/components/pages/marketing/pdf/DeliveryOrderExport';
|
||||||
cn,
|
import { Marketing } from '@/types/api/marketing/marketing';
|
||||||
formatCurrency,
|
|
||||||
formatDate,
|
|
||||||
formatNumber,
|
|
||||||
formatVechicleNumber,
|
|
||||||
} from '@/lib/helper';
|
|
||||||
|
|
||||||
type DeliveryOrderProductTableProps = {
|
type DeliveryOrderProductTableProps = {
|
||||||
data: DeliveryOrderProductFormValues[];
|
data: DeliveryOrderProductFormValues[];
|
||||||
formType?: 'add' | 'edit' | 'add_deliver' | 'edit_deliver';
|
formType?:
|
||||||
onEdit: (id: number) => void;
|
| 'add'
|
||||||
|
| 'edit'
|
||||||
|
| 'add_deliver'
|
||||||
|
| 'edit_deliver'
|
||||||
|
| 'add_delivery'
|
||||||
|
| 'edit_delivery'
|
||||||
|
| 'detail'
|
||||||
|
| 'rejected'
|
||||||
|
| 'pending'
|
||||||
|
| string
|
||||||
|
| null;
|
||||||
|
marketing?: Marketing;
|
||||||
|
onEdit: (id: number, values: DeliveryOrderProductFormValues) => void;
|
||||||
onDelete: (id: number) => void;
|
onDelete: (id: number) => void;
|
||||||
onAddProductClick: () => void;
|
onAddProductClick: () => void;
|
||||||
};
|
};
|
||||||
@@ -26,201 +32,168 @@ const DeliveryOrderProductTable = ({
|
|||||||
onEdit,
|
onEdit,
|
||||||
onDelete,
|
onDelete,
|
||||||
onAddProductClick,
|
onAddProductClick,
|
||||||
|
marketing,
|
||||||
}: DeliveryOrderProductTableProps) => {
|
}: DeliveryOrderProductTableProps) => {
|
||||||
const onEditRef = useRef(onEdit);
|
const onEditRef = useRef(onEdit);
|
||||||
onEditRef.current = onEdit;
|
onEditRef.current = onEdit;
|
||||||
const onDeleteRef = useRef(onDelete);
|
const onDeleteRef = useRef(onDelete);
|
||||||
onDeleteRef.current = onDelete;
|
onDeleteRef.current = onDelete;
|
||||||
|
|
||||||
const canAddData = data.filter((item) => !Boolean(item.qty));
|
|
||||||
|
|
||||||
const columns = useMemo(() => {
|
|
||||||
const cols = [
|
|
||||||
{
|
|
||||||
accessorFn: (row: DeliveryOrderProductFormValues) => row.do_number,
|
|
||||||
header: 'No. Pengiriman',
|
|
||||||
cell: (
|
|
||||||
props: TanStack.CellContext<DeliveryOrderProductFormValues, unknown>
|
|
||||||
) => (
|
|
||||||
<>
|
|
||||||
{props.row.original.do_number ? props.row.original.do_number : '-'}
|
|
||||||
</>
|
|
||||||
),
|
|
||||||
},
|
|
||||||
{
|
|
||||||
accessorFn: (row: DeliveryOrderProductFormValues) => row.vehicle_number,
|
|
||||||
header: 'No. Polisi',
|
|
||||||
cell: (
|
|
||||||
props: TanStack.CellContext<DeliveryOrderProductFormValues, unknown>
|
|
||||||
) =>
|
|
||||||
props.row.original.vehicle_number
|
|
||||||
? formatVechicleNumber(props.row.original.vehicle_number as string)
|
|
||||||
: '-',
|
|
||||||
},
|
|
||||||
{
|
|
||||||
accessorFn: (row: DeliveryOrderProductFormValues) =>
|
|
||||||
row.marketing_product?.kandang?.label,
|
|
||||||
header: 'Kandang',
|
|
||||||
},
|
|
||||||
{
|
|
||||||
accessorFn: (row: DeliveryOrderProductFormValues) =>
|
|
||||||
row.marketing_product?.product_warehouse?.label,
|
|
||||||
header: 'Produk',
|
|
||||||
},
|
|
||||||
{
|
|
||||||
accessorFn: (row: DeliveryOrderProductFormValues) =>
|
|
||||||
row.delivery_date
|
|
||||||
? formatDate(row.delivery_date as string, 'DD MMM YYYY')
|
|
||||||
: '-',
|
|
||||||
header: 'Tanggal Delivery',
|
|
||||||
cell: (
|
|
||||||
props: TanStack.CellContext<DeliveryOrderProductFormValues, unknown>
|
|
||||||
) =>
|
|
||||||
props.row.original.delivery_date
|
|
||||||
? formatDate(
|
|
||||||
props.row.original.delivery_date as string,
|
|
||||||
'DD MMM YYYY'
|
|
||||||
)
|
|
||||||
: '-',
|
|
||||||
},
|
|
||||||
{
|
|
||||||
accessorFn: (row: DeliveryOrderProductFormValues) => row.unit_price,
|
|
||||||
header: 'Harga Satuan (Rp)',
|
|
||||||
cell: (
|
|
||||||
props: TanStack.CellContext<DeliveryOrderProductFormValues, unknown>
|
|
||||||
) =>
|
|
||||||
props.row.original.unit_price
|
|
||||||
? formatCurrency(
|
|
||||||
parseFloat(props.row.original.unit_price as string)
|
|
||||||
)
|
|
||||||
: '-',
|
|
||||||
},
|
|
||||||
{
|
|
||||||
accessorFn: (row: DeliveryOrderProductFormValues) => row.total_weight,
|
|
||||||
header: 'Total Bobot (Kg)',
|
|
||||||
cell: (
|
|
||||||
props: TanStack.CellContext<DeliveryOrderProductFormValues, unknown>
|
|
||||||
) =>
|
|
||||||
props.row.original.total_weight
|
|
||||||
? formatNumber(
|
|
||||||
parseFloat(props.row.original.total_weight as string)
|
|
||||||
)
|
|
||||||
: '-',
|
|
||||||
},
|
|
||||||
{
|
|
||||||
accessorFn: (row: DeliveryOrderProductFormValues) => row.qty,
|
|
||||||
header: 'Kuantitas',
|
|
||||||
cell: (
|
|
||||||
props: TanStack.CellContext<DeliveryOrderProductFormValues, unknown>
|
|
||||||
) =>
|
|
||||||
props.row.original.qty
|
|
||||||
? formatNumber(parseFloat(props.row.original.qty as string))
|
|
||||||
: '-',
|
|
||||||
},
|
|
||||||
{
|
|
||||||
accessorFn: (row: DeliveryOrderProductFormValues) => row.avg_weight,
|
|
||||||
header: 'Avg. Bobot (Kg)',
|
|
||||||
cell: (
|
|
||||||
props: TanStack.CellContext<DeliveryOrderProductFormValues, unknown>
|
|
||||||
) =>
|
|
||||||
props.row.original.avg_weight
|
|
||||||
? formatNumber(parseFloat(props.row.original.avg_weight as string))
|
|
||||||
: '-',
|
|
||||||
},
|
|
||||||
{
|
|
||||||
accessorFn: (row: DeliveryOrderProductFormValues) => row.total_price,
|
|
||||||
header: 'Total Penjualan (Rp)',
|
|
||||||
cell: (
|
|
||||||
props: TanStack.CellContext<DeliveryOrderProductFormValues, unknown>
|
|
||||||
) =>
|
|
||||||
props.row.original.total_price
|
|
||||||
? formatCurrency(
|
|
||||||
parseFloat(props.row.original.total_price as string)
|
|
||||||
)
|
|
||||||
: '-',
|
|
||||||
},
|
|
||||||
|
|
||||||
{
|
|
||||||
header: 'Aksi',
|
|
||||||
cell: (
|
|
||||||
props: TanStack.CellContext<DeliveryOrderProductFormValues, unknown>
|
|
||||||
) => (
|
|
||||||
<div className='flex flex-row gap-1 items-center justify-end h-full mt-2'>
|
|
||||||
<>
|
|
||||||
{props.row.original.qty && (
|
|
||||||
<>
|
|
||||||
<Button
|
|
||||||
color='warning'
|
|
||||||
className='px-2 py-1 text-sm'
|
|
||||||
onClick={() =>
|
|
||||||
onEditRef.current(props.row.original.id as number)
|
|
||||||
}
|
|
||||||
type='button'
|
|
||||||
>
|
|
||||||
<Icon icon='mdi:edit' width={16} height={16} /> Edit
|
|
||||||
</Button>
|
|
||||||
<Button
|
|
||||||
color='error'
|
|
||||||
className='px-2 py-1 text-sm'
|
|
||||||
onClick={() =>
|
|
||||||
onDeleteRef.current(props.row.original.id as number)
|
|
||||||
}
|
|
||||||
type='button'
|
|
||||||
disabled={!!props.row.original.do_number}
|
|
||||||
>
|
|
||||||
<Icon icon='mdi:delete' width={16} height={16} /> Hapus
|
|
||||||
</Button>
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
{!props.row.original.qty && '-'}
|
|
||||||
</>
|
|
||||||
</div>
|
|
||||||
),
|
|
||||||
},
|
|
||||||
];
|
|
||||||
if (formType == 'add_deliver') {
|
|
||||||
return cols.filter((col) => col.header != 'No. Pengiriman');
|
|
||||||
}
|
|
||||||
return cols;
|
|
||||||
}, [formType, onEditRef]);
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<Table<DeliveryOrderProductFormValues>
|
<div className='size-full flex flex-col relative overflow-x-hidden gap-3'>
|
||||||
data={data}
|
{data.map((item) => {
|
||||||
columns={columns}
|
const doItem = marketing?.delivery_order?.find(
|
||||||
className={{
|
(doItem) => doItem.do_number === item.do_number
|
||||||
tableWrapperClassName: 'overflow-x-auto min-h-full!',
|
);
|
||||||
tableClassName: 'font-inter w-full table-auto min-h-full!',
|
return (
|
||||||
headerRowClassName: 'border-b border-b-gray-200',
|
<div
|
||||||
headerColumnClassName:
|
className='rounded-lg border border-tools-table-outline border-base-content/5'
|
||||||
'px-2 py-2 text-xs font-semibold text-gray-500 last:flex last:flex-row last:justify-end first:flex first:flex-row first:justify-start',
|
key={`table-${item.id}`}
|
||||||
bodyRowClassName: 'border-b border-b-gray-200',
|
>
|
||||||
bodyColumnClassName:
|
<table
|
||||||
'px-2 py-2 last:flex last:flex-row last:justify-end',
|
style={{
|
||||||
paginationClassName: 'hidden',
|
borderRadius: '0.5rem',
|
||||||
}}
|
}}
|
||||||
emptyContent={
|
className='border-none w-full'
|
||||||
<div
|
>
|
||||||
className={cn(
|
<tbody className='w-full'>
|
||||||
'w-full h-16 flex flex-col justify-center items-center gap-2'
|
<tr className='border-b border-tools-table-outline border-base-content/5'>
|
||||||
)}
|
<th className='w-1/3 text-start not-first:font-medium text-base-content/50 text-sm px-4 py-3'>
|
||||||
>
|
Label
|
||||||
<span className='text-gray-500'>Belum ada data pengiriman</span>
|
</th>
|
||||||
</div>
|
<th className='text-start font-medium text-base-content/50 text-sm px-4 py-3'>
|
||||||
}
|
<div className='flex w-full flex-row gap-1 items-center justify-between h-full mt-2'>
|
||||||
/>
|
<div>Value</div>
|
||||||
<div className='flex flex-row gap-3 mt-3'>
|
{(formType === 'add_delivery' ||
|
||||||
<Button
|
formType === 'edit_delivery' ||
|
||||||
type='button'
|
formType === 'detail') && (
|
||||||
variant='outline'
|
<div className='flex flex-row gap-1.5 items-center'>
|
||||||
className='justify-start w-fit py-1 text-sm'
|
<Button
|
||||||
onClick={onAddProductClick}
|
type='button'
|
||||||
disabled={!canAddData}
|
variant='ghost'
|
||||||
>
|
color='none'
|
||||||
<Icon icon='mdi:plus' width={16} height={16} />
|
onClick={() => {
|
||||||
Tambah Pengiriman
|
onEditRef.current(item.id as number, item);
|
||||||
</Button>
|
}}
|
||||||
|
className='p-0 hover:text-base-content'
|
||||||
|
>
|
||||||
|
<Icon
|
||||||
|
icon='heroicons:pencil'
|
||||||
|
width={20}
|
||||||
|
height={20}
|
||||||
|
/>
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
type='button'
|
||||||
|
variant='ghost'
|
||||||
|
color='none'
|
||||||
|
onClick={() => {
|
||||||
|
onDeleteRef.current(item.id as number);
|
||||||
|
}}
|
||||||
|
className='p-0 text-error hover:text-base-content'
|
||||||
|
>
|
||||||
|
<Icon
|
||||||
|
icon='heroicons:trash'
|
||||||
|
width={20}
|
||||||
|
height={20}
|
||||||
|
/>
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</th>
|
||||||
|
</tr>
|
||||||
|
<>
|
||||||
|
<tr>
|
||||||
|
<td className='text-sm px-4 py-3'>Tanggal Pengiriman</td>
|
||||||
|
<td className='text-sm px-4 py-3'>
|
||||||
|
{item.delivery_date ? (
|
||||||
|
formatDate(item.delivery_date, 'DD MMM YYYY')
|
||||||
|
) : (
|
||||||
|
<span className='text-error'>Belum diisi</span>
|
||||||
|
)}
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
{item.do_number && (
|
||||||
|
<tr>
|
||||||
|
<td className='text-sm px-4 py-3'>No. Pengiriman</td>
|
||||||
|
<td className='text-sm px-4 py-3'>{item.do_number}</td>
|
||||||
|
</tr>
|
||||||
|
)}
|
||||||
|
<tr>
|
||||||
|
<td className='text-sm px-4 py-3'>No. Polisi</td>
|
||||||
|
<td className='text-sm px-4 py-3'>
|
||||||
|
{item.vehicle_number}
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td className='text-sm px-4 py-3'>Gudang</td>
|
||||||
|
<td className='text-sm px-4 py-3'>
|
||||||
|
{item.marketing_product?.product_warehouse?.label}
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td className='text-sm px-4 py-3'>Produk</td>
|
||||||
|
<td className='text-sm px-4 py-3'>
|
||||||
|
{item.marketing_product?.product_warehouse?.label}
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td className='text-sm px-4 py-3'>Qty</td>
|
||||||
|
<td className='text-sm px-4 py-3'>
|
||||||
|
{item.qty
|
||||||
|
? `${formatNumber(parseFloat(item.qty as string))} ${item.marketing_product?.uom ?? ''}`
|
||||||
|
: '-'}
|
||||||
|
</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'>Total Bobot</td>
|
||||||
|
<td className='text-sm px-4 py-3'>
|
||||||
|
{formatNumber(parseFloat(item.total_weight as string))}
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td className='text-sm px-4 py-3'>Total Harga Satuan</td>
|
||||||
|
<td className='text-sm px-4 py-3'>
|
||||||
|
{formatCurrency(parseFloat(item.unit_price as string))}
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td className='text-sm px-4 py-3'>Total Penjualan</td>
|
||||||
|
<td className='text-sm px-4 py-3'>
|
||||||
|
{formatCurrency(parseFloat(item.total_price as string))}
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
{doItem && (
|
||||||
|
<tr>
|
||||||
|
<td className='text-sm px-4 py-3'>
|
||||||
|
Dokumen Pengiriman
|
||||||
|
</td>
|
||||||
|
<td className='text-sm px-4 py-3'>
|
||||||
|
<DeliveryOrderExport
|
||||||
|
data={marketing}
|
||||||
|
deliveryOrder={doItem}
|
||||||
|
/>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})}
|
||||||
</div>
|
</div>
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -1,42 +1,30 @@
|
|||||||
'use client';
|
'use client';
|
||||||
|
|
||||||
import Button from '@/components/Button';
|
import Button from '@/components/Button';
|
||||||
import Table from '@/components/Table';
|
|
||||||
import { SalesOrderProductFormValues } from '@/components/pages/marketing/form/repeater/sales-order/SalesOrderProduct.schema';
|
import { SalesOrderProductFormValues } from '@/components/pages/marketing/form/repeater/sales-order/SalesOrderProduct.schema';
|
||||||
import {
|
import {
|
||||||
cn,
|
|
||||||
formatCurrency,
|
formatCurrency,
|
||||||
formatNumber,
|
formatNumber,
|
||||||
formatVechicleNumber,
|
formatVechicleNumber,
|
||||||
} from '@/lib/helper';
|
} from '@/lib/helper';
|
||||||
import { Icon } from '@iconify/react';
|
import { Icon } from '@iconify/react';
|
||||||
import { useMemo, useRef, useState } from 'react';
|
import { useMemo, useRef } from 'react';
|
||||||
import * as TanStack from '@tanstack/react-table';
|
import * as TanStack from '@tanstack/react-table';
|
||||||
import CheckboxInput from '@/components/input/CheckboxInput';
|
import CheckboxInput from '@/components/input/CheckboxInput';
|
||||||
|
|
||||||
type SalesOrderProductTableProps = {
|
type SalesOrderProductTableProps = {
|
||||||
data: SalesOrderProductFormValues[];
|
data: SalesOrderProductFormValues[];
|
||||||
formType: 'add' | 'edit' | 'add_deliver' | 'edit_deliver';
|
formType: 'add' | 'edit' | 'add_deliver' | 'edit_deliver' | 'success';
|
||||||
rowSelection: Record<string, boolean>;
|
|
||||||
setRowSelection: React.Dispatch<
|
|
||||||
React.SetStateAction<Record<string, boolean>>
|
|
||||||
>;
|
|
||||||
selectedRowIds: number[];
|
|
||||||
onDelete: (id: number) => void;
|
onDelete: (id: number) => void;
|
||||||
onEdit: (id: number) => void;
|
onEdit: (id: number) => void;
|
||||||
onBulkDelete: () => void;
|
|
||||||
onAddProductClick: () => void;
|
onAddProductClick: () => void;
|
||||||
};
|
};
|
||||||
|
|
||||||
const SalesOrderProductTable = ({
|
const SalesOrderProductTable = ({
|
||||||
data,
|
data,
|
||||||
formType,
|
formType,
|
||||||
rowSelection,
|
|
||||||
setRowSelection,
|
|
||||||
selectedRowIds,
|
|
||||||
onDelete,
|
onDelete,
|
||||||
onEdit,
|
onEdit,
|
||||||
onBulkDelete,
|
|
||||||
onAddProductClick,
|
onAddProductClick,
|
||||||
}: SalesOrderProductTableProps) => {
|
}: SalesOrderProductTableProps) => {
|
||||||
const onDeleteRef = useRef(onDelete);
|
const onDeleteRef = useRef(onDelete);
|
||||||
@@ -156,67 +144,171 @@ const SalesOrderProductTable = ({
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<Table<SalesOrderProductFormValues>
|
<div className='size-full flex flex-col relative overflow-x-hidden gap-3'>
|
||||||
rowSelection={rowSelection}
|
{data.map((item) => (
|
||||||
setRowSelection={setRowSelection}
|
|
||||||
data={data}
|
|
||||||
columns={
|
|
||||||
formType == 'add_deliver' || formType == 'edit_deliver'
|
|
||||||
? columns.filter(
|
|
||||||
(col) => col.header != 'Aksi' && col.id != 'select'
|
|
||||||
)
|
|
||||||
: columns
|
|
||||||
}
|
|
||||||
className={{
|
|
||||||
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-2 py-2 text-xs font-semibold text-gray-500 last:flex last:flex-row last:justify-end first:flex first:flex-row first:justify-start',
|
|
||||||
bodyRowClassName: 'border-b border-b-gray-200',
|
|
||||||
bodyColumnClassName:
|
|
||||||
'px-2 py-2 last:flex last:flex-row last:justify-end first:flex first:flex-row first:justify-start',
|
|
||||||
paginationClassName: 'hidden',
|
|
||||||
}}
|
|
||||||
emptyContent={
|
|
||||||
<div
|
<div
|
||||||
className={cn(
|
className='rounded-lg border border-tools-table-outline border-base-content/5'
|
||||||
'w-full h-16 flex flex-col justify-center items-center gap-2'
|
key={`table-${item.id}`}
|
||||||
)}
|
|
||||||
>
|
>
|
||||||
<span className='text-gray-500'>Belum ada data penjualan</span>
|
<table
|
||||||
|
style={{
|
||||||
|
borderRadius: '0.5rem',
|
||||||
|
}}
|
||||||
|
className='border-none w-full'
|
||||||
|
>
|
||||||
|
<tbody className='w-full'>
|
||||||
|
<tr className='border-b border-tools-table-outline border-base-content/5'>
|
||||||
|
<th className='w-1/3 text-start not-first:font-medium text-base-content/50 text-sm px-4 py-3'>
|
||||||
|
Label
|
||||||
|
</th>
|
||||||
|
<th className='text-start font-medium text-base-content/50 text-sm px-4 py-3'>
|
||||||
|
<div className='flex w-full flex-row gap-1 items-center justify-between h-full mt-2'>
|
||||||
|
<div>Value</div>
|
||||||
|
{formType !== 'success' && (
|
||||||
|
<div className='flex flex-row gap-1.5 items-center'>
|
||||||
|
<Button
|
||||||
|
type='button'
|
||||||
|
variant='ghost'
|
||||||
|
color='none'
|
||||||
|
onClick={() => {
|
||||||
|
onEditRef.current(item.id as number);
|
||||||
|
}}
|
||||||
|
className='p-0 hover:text-base-content'
|
||||||
|
>
|
||||||
|
<Icon
|
||||||
|
icon='heroicons:pencil'
|
||||||
|
width={20}
|
||||||
|
height={20}
|
||||||
|
/>
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
type='button'
|
||||||
|
variant='ghost'
|
||||||
|
color='none'
|
||||||
|
onClick={() => {
|
||||||
|
onDeleteRef.current(item.id as number);
|
||||||
|
}}
|
||||||
|
className='p-0 text-error hover:text-base-content'
|
||||||
|
>
|
||||||
|
<Icon
|
||||||
|
icon='heroicons:trash'
|
||||||
|
width={20}
|
||||||
|
height={20}
|
||||||
|
/>
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</th>
|
||||||
|
</tr>
|
||||||
|
<>
|
||||||
|
<tr>
|
||||||
|
<td className='text-sm px-4 py-3'>No. Polisi</td>
|
||||||
|
<td className='text-sm px-4 py-3'>{item.vehicle_number}</td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<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'>
|
||||||
|
{item.marketing_type?.label}
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td className='text-sm px-4 py-3'>Produk</td>
|
||||||
|
<td className='text-sm px-4 py-3'>
|
||||||
|
{item.product_warehouse?.label}
|
||||||
|
</td>
|
||||||
|
</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>
|
||||||
|
<td className='text-sm px-4 py-3'>
|
||||||
|
{item.marketing_type?.value === 'telur'
|
||||||
|
? 'Total Butir Telur'
|
||||||
|
: 'Qty'}
|
||||||
|
</td>
|
||||||
|
<td className='text-sm px-4 py-3'>
|
||||||
|
{`${formatNumber(parseFloat(item.qty as string))} ${item.uom || ''}`}
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td className='text-sm px-4 py-3'>Harga Satuan</td>
|
||||||
|
<td className='text-sm px-4 py-3'>
|
||||||
|
{formatCurrency(parseFloat(item.unit_price as string))}
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td className='text-sm px-4 py-3'>Total Penjualan</td>
|
||||||
|
<td className='text-sm px-4 py-3'>
|
||||||
|
{formatCurrency(parseFloat(item.total_price as string))}
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
</>
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
</div>
|
</div>
|
||||||
}
|
))}
|
||||||
/>
|
{formType != 'add_deliver' &&
|
||||||
{formType != 'add_deliver' && formType != 'edit_deliver' && (
|
formType != 'edit_deliver' &&
|
||||||
<div className='flex flex-row gap-3 mt-3'>
|
formType != 'success' && (
|
||||||
<Button
|
|
||||||
type='button'
|
|
||||||
variant='outline'
|
|
||||||
className='justify-start w-fit py-1 text-sm'
|
|
||||||
onClick={onAddProductClick}
|
|
||||||
>
|
|
||||||
<Icon icon='mdi:plus' width={16} height={16} />
|
|
||||||
Tambah Produk
|
|
||||||
</Button>
|
|
||||||
{selectedRowIds.length > 0 && (
|
|
||||||
<Button
|
<Button
|
||||||
type='button'
|
type='button'
|
||||||
variant='outline'
|
variant='outline'
|
||||||
color='error'
|
className='justify-center p-3 w-full rounded-lg text-center text-sm mt-3'
|
||||||
className='justify-start w-fit py-1 text-sm'
|
onClick={onAddProductClick}
|
||||||
onClick={onBulkDelete}
|
|
||||||
>
|
>
|
||||||
<Icon icon='mdi:trash' width={16} height={16} />
|
Tambah Produk
|
||||||
Hapus
|
|
||||||
{selectedRowIds.length > 0
|
|
||||||
? ` (${selectedRowIds.length})`
|
|
||||||
: ''}{' '}
|
|
||||||
Produk
|
|
||||||
</Button>
|
</Button>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
)}
|
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -4,10 +4,9 @@ import { Icon } from '@iconify/react';
|
|||||||
import { Document, Image, Page, pdf, Text, View } from '@react-pdf/renderer';
|
import { Document, Image, Page, pdf, Text, View } from '@react-pdf/renderer';
|
||||||
import { useMemo, useState } from 'react';
|
import { useMemo, useState } from 'react';
|
||||||
import { formatDate, formatNumber, formatVechicleNumber } from '@/lib/helper';
|
import { formatDate, formatNumber, formatVechicleNumber } from '@/lib/helper';
|
||||||
import { format } from 'path';
|
|
||||||
import { date } from 'yup';
|
|
||||||
import pdfStyles from '@/components/pages/marketing/pdf/styles/MarketingPDFStyles';
|
import pdfStyles from '@/components/pages/marketing/pdf/styles/MarketingPDFStyles';
|
||||||
import toast from 'react-hot-toast';
|
import toast from 'react-hot-toast';
|
||||||
|
import { useSearchParams } from 'next/navigation';
|
||||||
|
|
||||||
interface DeliveryOrderExportProps {
|
interface DeliveryOrderExportProps {
|
||||||
data?: Marketing;
|
data?: Marketing;
|
||||||
@@ -21,6 +20,9 @@ const DeliveryOrderExport = ({
|
|||||||
}: DeliveryOrderExportProps) => {
|
}: DeliveryOrderExportProps) => {
|
||||||
const [isGeneratingPDF, setIsGeneratingPDF] = useState(false);
|
const [isGeneratingPDF, setIsGeneratingPDF] = useState(false);
|
||||||
const salesData = data;
|
const salesData = data;
|
||||||
|
const searchParams = useSearchParams();
|
||||||
|
const action = searchParams.get('action');
|
||||||
|
const id = searchParams.get('id');
|
||||||
|
|
||||||
const handleDownloadPDF = async () => {
|
const handleDownloadPDF = async () => {
|
||||||
if (!salesData) {
|
if (!salesData) {
|
||||||
@@ -32,37 +34,47 @@ const DeliveryOrderExport = ({
|
|||||||
const blob = await pdf(
|
const blob = await pdf(
|
||||||
<PDFDocument data={salesData} deliveryOrder={deliveryOrder} />
|
<PDFDocument data={salesData} deliveryOrder={deliveryOrder} />
|
||||||
).toBlob();
|
).toBlob();
|
||||||
const url = URL.createObjectURL(blob);
|
const url = window.URL.createObjectURL(blob);
|
||||||
const link = document.createElement('a');
|
const link = document.createElement('a');
|
||||||
|
link.style.display = 'none';
|
||||||
link.href = url;
|
link.href = url;
|
||||||
link.download = `${deliveryOrder?.do_number || 'delivery-order'}.pdf`;
|
link.download = `${deliveryOrder?.do_number || 'delivery-order'}.pdf`;
|
||||||
|
link.setAttribute('target', '_blank');
|
||||||
|
link.setAttribute('rel', 'noopener noreferrer');
|
||||||
document.body.appendChild(link);
|
document.body.appendChild(link);
|
||||||
link.click();
|
link.click();
|
||||||
document.body.removeChild(link);
|
|
||||||
URL.revokeObjectURL(url);
|
// Delay cleanup to ensure download starts
|
||||||
|
setTimeout(() => {
|
||||||
|
document.body.removeChild(link);
|
||||||
|
window.URL.revokeObjectURL(url);
|
||||||
|
}, 150);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
toast.error('Failed to generate PDF. Please try again.');
|
toast.error('Failed to generate PDF. Please try again.');
|
||||||
} finally {
|
} finally {
|
||||||
setIsGeneratingPDF(false);
|
setIsGeneratingPDF(false);
|
||||||
|
window.location.href = `/marketing?action=${action}&id=${id}`;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
if (!salesData) {
|
if (!salesData) {
|
||||||
return (
|
return (
|
||||||
<div className='flex items-center justify-center min-h-screen'>
|
<div className='flex items-start justify-start'>
|
||||||
<div className='text-gray-500'>No sales order data available</div>
|
<div className='text-gray-500'>No sales order data available</div>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
return salesData?.so_number && salesData.so_number !== 'Belum dibuat' ? (
|
return deliveryOrder?.do_number ? (
|
||||||
<Button
|
<Button
|
||||||
color='primary'
|
variant='outline'
|
||||||
className='w-fit min-w-32 flex items-center justify-start gap-1 px-2 py-1 text-sm font-mono'
|
color='none'
|
||||||
|
className='w-fit text-sm px-3 py-2.5 rounded-lg border-base-content/10 text-base-content/50'
|
||||||
onClick={handleDownloadPDF}
|
onClick={handleDownloadPDF}
|
||||||
isLoading={isGeneratingPDF}
|
isLoading={isGeneratingPDF}
|
||||||
|
type='button'
|
||||||
>
|
>
|
||||||
<Icon icon='material-symbols:file-open-outline' width={16} height={16} />
|
<Icon icon='heroicons:document-text' width={20} height={20} />
|
||||||
{deliveryOrder.do_number}
|
{deliveryOrder.do_number}
|
||||||
</Button>
|
</Button>
|
||||||
) : null;
|
) : null;
|
||||||
@@ -87,11 +99,6 @@ const PDFDocument = ({
|
|||||||
<Page size='A4' style={pdfStyles.page}>
|
<Page size='A4' style={pdfStyles.page}>
|
||||||
{/* Header Section */}
|
{/* Header Section */}
|
||||||
<View style={pdfStyles.header}>
|
<View style={pdfStyles.header}>
|
||||||
<Image
|
|
||||||
src={'https://placehold.co/120x30/png'}
|
|
||||||
style={pdfStyles.logo}
|
|
||||||
id={'mbu-logo'}
|
|
||||||
/>
|
|
||||||
<Text style={pdfStyles.companyInfo}>PT LUMBUNG TELUR INDONESIA</Text>
|
<Text style={pdfStyles.companyInfo}>PT LUMBUNG TELUR INDONESIA</Text>
|
||||||
<Text style={pdfStyles.address}>
|
<Text style={pdfStyles.address}>
|
||||||
SOHO Building Lt.3 (Paris Van Java), Jalan Karang Tinggal, Kel.
|
SOHO Building Lt.3 (Paris Van Java), Jalan Karang Tinggal, Kel.
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import { useMemo, useState } from 'react';
|
|||||||
import { formatDate, formatNumber } from '@/lib/helper';
|
import { formatDate, formatNumber } from '@/lib/helper';
|
||||||
import pdfStyles from '@/components/pages/marketing/pdf/styles/MarketingPDFStyles';
|
import pdfStyles from '@/components/pages/marketing/pdf/styles/MarketingPDFStyles';
|
||||||
import toast from 'react-hot-toast';
|
import toast from 'react-hot-toast';
|
||||||
|
import { useSearchParams } from 'next/navigation';
|
||||||
|
|
||||||
interface SalesOrderExportProps {
|
interface SalesOrderExportProps {
|
||||||
data?: Marketing;
|
data?: Marketing;
|
||||||
@@ -15,6 +16,9 @@ interface SalesOrderExportProps {
|
|||||||
const SalesOrderExport = ({ data }: SalesOrderExportProps) => {
|
const SalesOrderExport = ({ data }: SalesOrderExportProps) => {
|
||||||
const [isGeneratingPDF, setIsGeneratingPDF] = useState(false);
|
const [isGeneratingPDF, setIsGeneratingPDF] = useState(false);
|
||||||
const salesData = data;
|
const salesData = data;
|
||||||
|
const searchParams = useSearchParams();
|
||||||
|
const action = searchParams.get('action');
|
||||||
|
const id = searchParams.get('id');
|
||||||
|
|
||||||
const handleDownloadPDF = async () => {
|
const handleDownloadPDF = async () => {
|
||||||
if (!salesData) {
|
if (!salesData) {
|
||||||
@@ -24,24 +28,32 @@ const SalesOrderExport = ({ data }: SalesOrderExportProps) => {
|
|||||||
setIsGeneratingPDF(true);
|
setIsGeneratingPDF(true);
|
||||||
try {
|
try {
|
||||||
const blob = await pdf(<PDFDocument data={salesData} />).toBlob();
|
const blob = await pdf(<PDFDocument data={salesData} />).toBlob();
|
||||||
const url = URL.createObjectURL(blob);
|
const url = window.URL.createObjectURL(blob);
|
||||||
const link = document.createElement('a');
|
const link = document.createElement('a');
|
||||||
|
link.style.display = 'none';
|
||||||
link.href = url;
|
link.href = url;
|
||||||
link.download = `${salesData?.so_number || 'sales-order'}.pdf`;
|
link.download = `${salesData?.so_number || 'sales-order'}.pdf`;
|
||||||
|
link.setAttribute('target', '_blank');
|
||||||
|
link.setAttribute('rel', 'noopener noreferrer');
|
||||||
document.body.appendChild(link);
|
document.body.appendChild(link);
|
||||||
link.click();
|
link.click();
|
||||||
document.body.removeChild(link);
|
|
||||||
URL.revokeObjectURL(url);
|
// Delay cleanup to ensure download starts
|
||||||
|
setTimeout(() => {
|
||||||
|
document.body.removeChild(link);
|
||||||
|
window.URL.revokeObjectURL(url);
|
||||||
|
}, 150);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
toast.error('Failed to generate PDF. Please try again.');
|
toast.error('Failed to generate PDF. Please try again.');
|
||||||
} finally {
|
} finally {
|
||||||
setIsGeneratingPDF(false);
|
setIsGeneratingPDF(false);
|
||||||
|
window.location.href = `/marketing?action=${action}&id=${id}`;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
if (!salesData) {
|
if (!salesData) {
|
||||||
return (
|
return (
|
||||||
<div className='flex items-center justify-center min-h-screen'>
|
<div className='flex items-start justify-start'>
|
||||||
<div className='text-gray-500'>No sales order data available</div>
|
<div className='text-gray-500'>No sales order data available</div>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
@@ -49,12 +61,14 @@ const SalesOrderExport = ({ data }: SalesOrderExportProps) => {
|
|||||||
|
|
||||||
return salesData?.so_number && salesData.so_number !== 'Belum dibuat' ? (
|
return salesData?.so_number && salesData.so_number !== 'Belum dibuat' ? (
|
||||||
<Button
|
<Button
|
||||||
color='primary'
|
variant='outline'
|
||||||
className='w-fit min-w-32 flex items-center justify-start gap-1 px-2 py-1 text-sm font-mono'
|
color='none'
|
||||||
|
className='w-fit text-sm px-3 py-2.5 rounded-lg border-base-content/10 text-base-content/50'
|
||||||
onClick={handleDownloadPDF}
|
onClick={handleDownloadPDF}
|
||||||
isLoading={isGeneratingPDF}
|
isLoading={isGeneratingPDF}
|
||||||
|
type='button'
|
||||||
>
|
>
|
||||||
<Icon icon='material-symbols:file-open-outline' width={16} height={16} />
|
<Icon icon='heroicons:document-text' width={20} height={20} />
|
||||||
{salesData.so_number}
|
{salesData.so_number}
|
||||||
</Button>
|
</Button>
|
||||||
) : null;
|
) : null;
|
||||||
@@ -71,11 +85,6 @@ const PDFDocument = ({ data }: { data: Marketing }) => {
|
|||||||
<Page size='A4' style={pdfStyles.page}>
|
<Page size='A4' style={pdfStyles.page}>
|
||||||
{/* Header Section */}
|
{/* Header Section */}
|
||||||
<View style={pdfStyles.header}>
|
<View style={pdfStyles.header}>
|
||||||
<Image
|
|
||||||
src={'https://placehold.co/120x30/png'}
|
|
||||||
style={pdfStyles.logo}
|
|
||||||
id={'mbu-logo'}
|
|
||||||
/>
|
|
||||||
<Text style={pdfStyles.companyInfo}>PT LUMBUNG TELUR INDONESIA</Text>
|
<Text style={pdfStyles.companyInfo}>PT LUMBUNG TELUR INDONESIA</Text>
|
||||||
<Text style={pdfStyles.address}>
|
<Text style={pdfStyles.address}>
|
||||||
SOHO Building Lt.3 (Paris Van Java), Jalan Karang Tinggal, Kel.
|
SOHO Building Lt.3 (Paris Van Java), Jalan Karang Tinggal, Kel.
|
||||||
|
|||||||
+1
-1
@@ -32,7 +32,7 @@ const GrowingRepeaterFormSchema = Yup.object({
|
|||||||
target_hen_house_production: Yup.number().optional(),
|
target_hen_house_production: Yup.number().optional(),
|
||||||
target_egg_weight: Yup.number().optional(),
|
target_egg_weight: Yup.number().optional(),
|
||||||
target_egg_mass: Yup.number().optional(),
|
target_egg_mass: Yup.number().optional(),
|
||||||
standard_fcr: Yup.number().optional(),
|
standard_fcr: Yup.number().required('Wajib diisi!'),
|
||||||
}).optional(),
|
}).optional(),
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
+62
-42
@@ -386,14 +386,6 @@ const ProductionStandardForm = ({
|
|||||||
`${row.original.production_standard_details?.target_egg_mass} kg`,
|
`${row.original.production_standard_details?.target_egg_mass} kg`,
|
||||||
enableSorting: false,
|
enableSorting: false,
|
||||||
},
|
},
|
||||||
{
|
|
||||||
header: 'FCR',
|
|
||||||
accessorFn: (row) =>
|
|
||||||
row.production_standard_details?.standard_fcr,
|
|
||||||
cell: ({ row }) =>
|
|
||||||
`${row.original.production_standard_details?.standard_fcr} g`,
|
|
||||||
enableSorting: false,
|
|
||||||
},
|
|
||||||
]
|
]
|
||||||
: [];
|
: [];
|
||||||
|
|
||||||
@@ -468,6 +460,13 @@ const ProductionStandardForm = ({
|
|||||||
return [
|
return [
|
||||||
...baseColumns,
|
...baseColumns,
|
||||||
...productionColumns,
|
...productionColumns,
|
||||||
|
{
|
||||||
|
header: 'FCR',
|
||||||
|
accessorFn: (row) => row.production_standard_details?.standard_fcr,
|
||||||
|
cell: ({ row }) =>
|
||||||
|
`${row.original.production_standard_details?.standard_fcr} g`,
|
||||||
|
enableSorting: false,
|
||||||
|
},
|
||||||
...uniformityColumns,
|
...uniformityColumns,
|
||||||
...(formType !== 'detail' ? [actionColumn] : []),
|
...(formType !== 'detail' ? [actionColumn] : []),
|
||||||
];
|
];
|
||||||
@@ -753,24 +752,46 @@ const ProductionStandardForm = ({
|
|||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
|
|
||||||
// For GROWING category, clear production_standard_details errors and set default values
|
// For GROWING category, clear production_standard_details errors and set default values
|
||||||
|
// but preserve standard_fcr since it's used for both LAYING and GROWING
|
||||||
if (formik.values.project_category === 'GROWING') {
|
if (formik.values.project_category === 'GROWING') {
|
||||||
// Set default values for production_standard_details
|
// Set default values for production_standard_details, preserving standard_fcr
|
||||||
formik.values.details?.forEach((detail) => {
|
formik.values.details?.forEach((detail) => {
|
||||||
detail.production_standard_details = {
|
detail.production_standard_details = {
|
||||||
target_hen_day_production: 0,
|
target_hen_day_production: 0,
|
||||||
target_hen_house_production: 0,
|
target_hen_house_production: 0,
|
||||||
target_egg_weight: 0,
|
target_egg_weight: 0,
|
||||||
target_egg_mass: 0,
|
target_egg_mass: 0,
|
||||||
standard_fcr: 0,
|
standard_fcr:
|
||||||
|
detail.production_standard_details?.standard_fcr || 0,
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
|
|
||||||
// Clear any errors related to production_standard_details
|
// Clear errors only for LAYING-specific fields in production_standard_details
|
||||||
|
// Preserve standard_fcr error since it's required for both categories
|
||||||
const currentErrors = { ...formik.errors };
|
const currentErrors = { ...formik.errors };
|
||||||
if (currentErrors.details && Array.isArray(currentErrors.details)) {
|
if (currentErrors.details && Array.isArray(currentErrors.details)) {
|
||||||
const cleanedDetails = currentErrors.details
|
const cleanedDetails = currentErrors.details
|
||||||
.map((detailError) => {
|
.map((detailError) => {
|
||||||
if (detailError && typeof detailError === 'object') {
|
if (detailError && typeof detailError === 'object') {
|
||||||
|
const prodDetails = (
|
||||||
|
detailError as {
|
||||||
|
production_standard_details?: ProductionDetailsErrors;
|
||||||
|
}
|
||||||
|
).production_standard_details;
|
||||||
|
|
||||||
|
// If there's standard_fcr error, preserve it
|
||||||
|
if (prodDetails && prodDetails.standard_fcr) {
|
||||||
|
const { production_standard_details, ...rest } =
|
||||||
|
detailError;
|
||||||
|
return {
|
||||||
|
...rest,
|
||||||
|
production_standard_details: {
|
||||||
|
standard_fcr: prodDetails.standard_fcr,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// Otherwise, remove entire production_standard_details errors
|
||||||
const { production_standard_details, ...rest } = detailError;
|
const { production_standard_details, ...rest } = detailError;
|
||||||
return Object.keys(rest).length > 0 ? rest : undefined;
|
return Object.keys(rest).length > 0 ? rest : undefined;
|
||||||
}
|
}
|
||||||
@@ -896,7 +917,7 @@ const ProductionStandardForm = ({
|
|||||||
gridTemplateColumns:
|
gridTemplateColumns:
|
||||||
formik.values.project_category === 'LAYING'
|
formik.values.project_category === 'LAYING'
|
||||||
? 'repeat(10, minmax(auto, 1fr)) minmax(auto, auto)'
|
? 'repeat(10, minmax(auto, 1fr)) minmax(auto, auto)'
|
||||||
: 'repeat(4, minmax(auto, 1fr)) minmax(auto, auto)',
|
: 'repeat(5, minmax(auto, 1fr)) minmax(auto, auto)',
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<NumberInput
|
<NumberInput
|
||||||
@@ -1042,39 +1063,38 @@ const ProductionStandardForm = ({
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
<NumberInput
|
</>
|
||||||
name='production_standard_details.standard_fcr'
|
)}
|
||||||
label='FCR'
|
<NumberInput
|
||||||
placeholder='1'
|
name='production_standard_details.standard_fcr'
|
||||||
value={
|
label='FCR'
|
||||||
repeaterFormik.values
|
placeholder='1'
|
||||||
.production_standard_details?.standard_fcr
|
value={
|
||||||
}
|
repeaterFormik.values.production_standard_details
|
||||||
onChange={repeaterFormik.handleChange}
|
?.standard_fcr
|
||||||
onBlur={repeaterFormik.handleBlur}
|
}
|
||||||
bottomLabel='Gram (g)'
|
onChange={repeaterFormik.handleChange}
|
||||||
errorMessage={getProductionDetailsError(
|
onBlur={repeaterFormik.handleBlur}
|
||||||
|
bottomLabel='Gram (g)'
|
||||||
|
errorMessage={getProductionDetailsError(
|
||||||
|
repeaterFormik.errors.production_standard_details,
|
||||||
|
'standard_fcr'
|
||||||
|
)}
|
||||||
|
isError={
|
||||||
|
Boolean(
|
||||||
|
getProductionDetailsError(
|
||||||
repeaterFormik.errors
|
repeaterFormik.errors
|
||||||
.production_standard_details,
|
.production_standard_details,
|
||||||
'standard_fcr'
|
'standard_fcr'
|
||||||
)}
|
)
|
||||||
isError={
|
) &&
|
||||||
Boolean(
|
getProductionDetailsTouched(
|
||||||
getProductionDetailsError(
|
repeaterFormik.touched
|
||||||
repeaterFormik.errors
|
.production_standard_details,
|
||||||
.production_standard_details,
|
'standard_fcr'
|
||||||
'standard_fcr'
|
)
|
||||||
)
|
}
|
||||||
) &&
|
/>
|
||||||
getProductionDetailsTouched(
|
|
||||||
repeaterFormik.touched
|
|
||||||
.production_standard_details,
|
|
||||||
'standard_fcr'
|
|
||||||
)
|
|
||||||
}
|
|
||||||
/>
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
<NumberInput
|
<NumberInput
|
||||||
name='production_standard_uniformity_details.target_mean_bw'
|
name='production_standard_uniformity_details.target_mean_bw'
|
||||||
label='Mean BW'
|
label='Mean BW'
|
||||||
|
|||||||
@@ -53,7 +53,7 @@ const ChickinFormKandang = ({
|
|||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<section className='w-full h-full sm:w-[446px] overflow-y-auto'>
|
||||||
<DrawerHeader
|
<DrawerHeader
|
||||||
subtitle={`Chick In ${initialValues.kandang?.name ?? 'Kandang'}`}
|
subtitle={`Chick In ${initialValues.kandang?.name ?? 'Kandang'}`}
|
||||||
leftIcon='mdi:arrow-left'
|
leftIcon='mdi:arrow-left'
|
||||||
@@ -198,7 +198,7 @@ const ChickinFormKandang = ({
|
|||||||
afterSubmit={afterSubmitFormChickin}
|
afterSubmit={afterSubmitFormChickin}
|
||||||
/>
|
/>
|
||||||
</RequirePermission>
|
</RequirePermission>
|
||||||
</>
|
</section>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,159 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
import { ChangeEventHandler, RefObject, useId, useState } from 'react';
|
||||||
|
import useSWR from 'swr';
|
||||||
|
|
||||||
|
import ConfirmationModal, {
|
||||||
|
ConfirmationModalProps,
|
||||||
|
} from '@/components/modal/ConfirmationModal';
|
||||||
|
import TextArea from '@/components/input/TextArea';
|
||||||
|
import { ProjectFlockFormConfirmationTable } from '@/components/pages/production/project-flock/form/ProjectFlockForm';
|
||||||
|
|
||||||
|
import { ProjectFlockFormValues } from '@/components/pages/production/project-flock/form/ProjectFlockForm.schema';
|
||||||
|
import { Color } from '@/types/theme';
|
||||||
|
import { isResponseSuccess } from '@/lib/api-helper';
|
||||||
|
import { KandangApi } from '@/services/api/master-data';
|
||||||
|
|
||||||
|
interface ProjectFlockConfirmationModalProps
|
||||||
|
extends Omit<ConfirmationModalProps, 'children' | 'primaryButton'> {
|
||||||
|
ref: RefObject<HTMLDialogElement | null>;
|
||||||
|
type?: 'info' | 'success' | 'error';
|
||||||
|
projectFlockIds?: number[];
|
||||||
|
projectFlockForm?: ProjectFlockFormValues;
|
||||||
|
onClose?: () => void;
|
||||||
|
|
||||||
|
withNote?: boolean;
|
||||||
|
noteLabel?: string;
|
||||||
|
rows?: number;
|
||||||
|
placeholder?: string;
|
||||||
|
|
||||||
|
primaryButton?: {
|
||||||
|
text?: string;
|
||||||
|
color?: Color;
|
||||||
|
isLoading?: boolean;
|
||||||
|
onClick?: (notes: string) => void;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const ProjectFlockConfirmationModal = ({
|
||||||
|
ref,
|
||||||
|
type = 'success',
|
||||||
|
projectFlockForm,
|
||||||
|
projectFlockIds,
|
||||||
|
onClose,
|
||||||
|
withNote,
|
||||||
|
rows = 4,
|
||||||
|
noteLabel,
|
||||||
|
placeholder = 'Alasan',
|
||||||
|
primaryButton,
|
||||||
|
secondaryButton,
|
||||||
|
...props
|
||||||
|
}: ProjectFlockConfirmationModalProps) => {
|
||||||
|
const randomId = useId();
|
||||||
|
|
||||||
|
const [notes, setNotes] = useState('');
|
||||||
|
|
||||||
|
const kandangUrl = `${KandangApi.basePath}?${new URLSearchParams({
|
||||||
|
search: '',
|
||||||
|
location_id: projectFlockForm?.location_id
|
||||||
|
? String(projectFlockForm?.location_id)
|
||||||
|
: '',
|
||||||
|
limit: '500',
|
||||||
|
}).toString()}`;
|
||||||
|
const {
|
||||||
|
data: kandang,
|
||||||
|
isLoading: isLoadingKandang,
|
||||||
|
mutate: refreshKandang,
|
||||||
|
} = useSWR(kandangUrl, KandangApi.getAllFetcher);
|
||||||
|
|
||||||
|
const notesChangeHandler: ChangeEventHandler<HTMLTextAreaElement> = (e) => {
|
||||||
|
setNotes(e.target.value);
|
||||||
|
};
|
||||||
|
|
||||||
|
const closeModalHandler = () => {
|
||||||
|
onClose?.();
|
||||||
|
ref.current?.close();
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<ConfirmationModal
|
||||||
|
ref={ref}
|
||||||
|
iconPosition='left'
|
||||||
|
type={type}
|
||||||
|
primaryButton={{
|
||||||
|
...primaryButton,
|
||||||
|
text: primaryButton?.text ?? 'Oke',
|
||||||
|
color: primaryButton?.color ?? 'primary',
|
||||||
|
className: 'rounded-lg',
|
||||||
|
onClick: (e) => {
|
||||||
|
if (withNote) {
|
||||||
|
primaryButton?.onClick?.(notes);
|
||||||
|
} else if (primaryButton && primaryButton?.onClick) {
|
||||||
|
primaryButton?.onClick?.('');
|
||||||
|
} else {
|
||||||
|
closeModalHandler();
|
||||||
|
}
|
||||||
|
|
||||||
|
setNotes('');
|
||||||
|
},
|
||||||
|
}}
|
||||||
|
secondaryButton={
|
||||||
|
secondaryButton
|
||||||
|
? {
|
||||||
|
text: secondaryButton?.text ?? 'Cancel',
|
||||||
|
color: secondaryButton?.color ?? 'none',
|
||||||
|
onClick: (e) => {
|
||||||
|
if (secondaryButton && secondaryButton?.onClick) {
|
||||||
|
secondaryButton.onClick?.(e);
|
||||||
|
} else {
|
||||||
|
closeModalHandler();
|
||||||
|
}
|
||||||
|
|
||||||
|
setNotes('');
|
||||||
|
},
|
||||||
|
}
|
||||||
|
: undefined
|
||||||
|
}
|
||||||
|
className={{
|
||||||
|
modalBox: 'max-h-full',
|
||||||
|
}}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
<div className='flex flex-col gap-4'>
|
||||||
|
{!projectFlockIds && projectFlockForm && (
|
||||||
|
<ProjectFlockFormConfirmationTable
|
||||||
|
projectFlockForm={projectFlockForm}
|
||||||
|
kandangs={
|
||||||
|
isResponseSuccess(kandang) && kandang?.data ? kandang.data : []
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* {projectFlockIds &&
|
||||||
|
!projectFlockForm &&
|
||||||
|
projectFlockIds.map((projectFlockId, idx) => (
|
||||||
|
<ProjectFlockFormConfirmationTable
|
||||||
|
key={idx}
|
||||||
|
projectFlockId={projectFlockId}
|
||||||
|
kandangs={
|
||||||
|
isResponseSuccess(kandang) && kandang?.data ? kandang.data : []
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
))} */}
|
||||||
|
|
||||||
|
{withNote && (
|
||||||
|
<TextArea
|
||||||
|
name={randomId}
|
||||||
|
label={noteLabel}
|
||||||
|
placeholder={placeholder}
|
||||||
|
value={notes}
|
||||||
|
onChange={notesChangeHandler}
|
||||||
|
rows={rows}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</ConfirmationModal>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default ProjectFlockConfirmationModal;
|
||||||
@@ -13,6 +13,7 @@ import { useModal } from '@/components/Modal';
|
|||||||
import ConfirmationModal from '@/components/modal/ConfirmationModal';
|
import ConfirmationModal from '@/components/modal/ConfirmationModal';
|
||||||
import ConfirmationModalWithNotes from '@/components/modal/ConfirmationModalWithNotes';
|
import ConfirmationModalWithNotes from '@/components/modal/ConfirmationModalWithNotes';
|
||||||
import Table from '@/components/Table';
|
import Table from '@/components/Table';
|
||||||
|
import Dropdown from '@/components/Dropdown';
|
||||||
import { ROWS_OPTIONS } from '@/config/constant';
|
import { ROWS_OPTIONS } from '@/config/constant';
|
||||||
import { isResponseError, isResponseSuccess } from '@/lib/api-helper';
|
import { isResponseError, isResponseSuccess } from '@/lib/api-helper';
|
||||||
import { cn, formatDate, formatTitleCase } from '@/lib/helper';
|
import { cn, formatDate, formatTitleCase } from '@/lib/helper';
|
||||||
@@ -29,6 +30,111 @@ import toast from 'react-hot-toast';
|
|||||||
import useSWR from 'swr';
|
import useSWR from 'swr';
|
||||||
|
|
||||||
import RequirePermission from '@/components/helper/RequirePermission';
|
import RequirePermission from '@/components/helper/RequirePermission';
|
||||||
|
import StatusBadge from '@/components/helper/StatusBadge';
|
||||||
|
import PopoverButton from '@/components/popover/PopoverButton';
|
||||||
|
import PopoverContent from '@/components/popover/PopoverContent';
|
||||||
|
|
||||||
|
const RowOptionsMenu = ({
|
||||||
|
props,
|
||||||
|
popoverPosition = 'bottom',
|
||||||
|
editClickHandler,
|
||||||
|
detailClickHandler,
|
||||||
|
deleteClickHandler,
|
||||||
|
}: {
|
||||||
|
props: CellContext<ProjectFlock, unknown>;
|
||||||
|
popoverPosition: 'bottom' | 'top';
|
||||||
|
editClickHandler: (id: number) => void;
|
||||||
|
detailClickHandler: (id: number) => void;
|
||||||
|
deleteClickHandler: () => void;
|
||||||
|
}) => {
|
||||||
|
// TODO: change this to real condition
|
||||||
|
const showEditButton = true;
|
||||||
|
|
||||||
|
const showDeleteButton = showEditButton;
|
||||||
|
|
||||||
|
const popoverId = `projectFlock#${props.row.original.id}`;
|
||||||
|
const popoverAnchorName = `--anchor-projectFlock#${props.row.original.id}`;
|
||||||
|
|
||||||
|
const closePopover = () => {
|
||||||
|
document.getElementById(popoverId)?.hidePopover();
|
||||||
|
};
|
||||||
|
|
||||||
|
const detailClickHandlerWrapper = () => {
|
||||||
|
detailClickHandler(props.row.original.id);
|
||||||
|
closePopover();
|
||||||
|
};
|
||||||
|
|
||||||
|
const editClickHandlerWrapper = () => {
|
||||||
|
editClickHandler(props.row.original.id);
|
||||||
|
closePopover();
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className='relative'>
|
||||||
|
<PopoverButton
|
||||||
|
tabIndex={0}
|
||||||
|
variant='ghost'
|
||||||
|
color='none'
|
||||||
|
popoverTarget={popoverId}
|
||||||
|
anchorName={popoverAnchorName}
|
||||||
|
>
|
||||||
|
<Icon icon='material-symbols:more-vert' width={16} height={16} />
|
||||||
|
</PopoverButton>
|
||||||
|
|
||||||
|
<PopoverContent
|
||||||
|
id={popoverId}
|
||||||
|
anchorName={popoverAnchorName}
|
||||||
|
position={popoverPosition === 'bottom' ? 'bottom-start' : 'left'}
|
||||||
|
className='w-full max-w-40 rounded-xl border border-base-content/5 shadow-sm'
|
||||||
|
>
|
||||||
|
<div className='flex flex-col bg-base-100 rounded-xl'>
|
||||||
|
<RequirePermission permissions='lti.production.project_flocks.detail'>
|
||||||
|
<Button
|
||||||
|
// href={`/production/project-flock/detail/?projectFlockId=${props.row.original.id}`}
|
||||||
|
variant='ghost'
|
||||||
|
color='none'
|
||||||
|
onClick={detailClickHandlerWrapper}
|
||||||
|
className='p-3 justify-start text-sm font-semibold w-full'
|
||||||
|
>
|
||||||
|
<Icon icon='heroicons:eye' width={20} height={20} />
|
||||||
|
View Details
|
||||||
|
</Button>
|
||||||
|
</RequirePermission>
|
||||||
|
|
||||||
|
{showEditButton && (
|
||||||
|
<RequirePermission permissions='lti.production.project_flocks.update'>
|
||||||
|
<Button
|
||||||
|
// href={`/production/project-flock/detail/edit/?projectFlockId=${props.row.original.id}`}
|
||||||
|
variant='ghost'
|
||||||
|
color='none'
|
||||||
|
onClick={editClickHandlerWrapper}
|
||||||
|
className='p-3 justify-start text-sm font-semibold w-full'
|
||||||
|
>
|
||||||
|
<Icon icon='heroicons:pencil-square' width={20} height={20} />
|
||||||
|
Edit
|
||||||
|
</Button>
|
||||||
|
</RequirePermission>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{showDeleteButton && (
|
||||||
|
<RequirePermission permissions='lti.production.project_flocks.delete'>
|
||||||
|
<hr className='mx-3 border-base-content/10 h-px' />
|
||||||
|
<Button
|
||||||
|
onClick={deleteClickHandler}
|
||||||
|
variant='ghost'
|
||||||
|
color='error'
|
||||||
|
className='p-3 justify-start text-sm font-semibold w-full'
|
||||||
|
>
|
||||||
|
<Icon icon='heroicons:trash' width={20} height={20} />
|
||||||
|
Delete
|
||||||
|
</Button>
|
||||||
|
</RequirePermission>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</PopoverContent>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
const ProjectFlockTable = ({ refresh }: { refresh?: () => void }) => {
|
const ProjectFlockTable = ({ refresh }: { refresh?: () => void }) => {
|
||||||
const {
|
const {
|
||||||
@@ -62,6 +168,7 @@ const ProjectFlockTable = ({ refresh }: { refresh?: () => void }) => {
|
|||||||
const selectedRowIds = Object.keys(rowSelection)
|
const selectedRowIds = Object.keys(rowSelection)
|
||||||
.filter((id) => rowSelection[id])
|
.filter((id) => rowSelection[id])
|
||||||
.map((id) => parseInt(id));
|
.map((id) => parseInt(id));
|
||||||
|
|
||||||
const [selectedArea, setSelectedArea] = useState<OptionType | null>(null);
|
const [selectedArea, setSelectedArea] = useState<OptionType | null>(null);
|
||||||
const [selectedLocation, setSelectedLocation] = useState<OptionType | null>(
|
const [selectedLocation, setSelectedLocation] = useState<OptionType | null>(
|
||||||
null
|
null
|
||||||
@@ -78,6 +185,8 @@ const ProjectFlockTable = ({ refresh }: { refresh?: () => void }) => {
|
|||||||
);
|
);
|
||||||
const [isDeleteLoading, setIsDeleteLoading] = useState(false);
|
const [isDeleteLoading, setIsDeleteLoading] = useState(false);
|
||||||
const [isApproveLoading, setIsApproveLoading] = useState(false);
|
const [isApproveLoading, setIsApproveLoading] = useState(false);
|
||||||
|
const [isLoadingExportingToExcel, setIsLoadingExportingToExcel] =
|
||||||
|
useState(false);
|
||||||
|
|
||||||
// ===== Fetch Data =====
|
// ===== Fetch Data =====
|
||||||
const {
|
const {
|
||||||
@@ -175,14 +284,27 @@ const ProjectFlockTable = ({ refresh }: { refresh?: () => void }) => {
|
|||||||
: null;
|
: null;
|
||||||
}, [rowSelection]);
|
}, [rowSelection]);
|
||||||
|
|
||||||
|
// const canApprove = useMemo(() => {
|
||||||
|
// if (!selectedSingleRow || isApproveLoading) return false;
|
||||||
|
|
||||||
|
// const isPengajuan = selectedSingleRow.approval?.step_number == 1;
|
||||||
|
// const isNotRejected = selectedSingleRow.approval?.action != 'REJECTED';
|
||||||
|
|
||||||
|
// return isPengajuan && isNotRejected;
|
||||||
|
// }, [selectedSingleRow, isApproveLoading]);
|
||||||
|
|
||||||
const canApprove = useMemo(() => {
|
const canApprove = useMemo(() => {
|
||||||
if (!selectedSingleRow || isApproveLoading) return false;
|
return selectedRowIds.every((id) => {
|
||||||
|
const projectFlock = isResponseSuccess(projectFlocks)
|
||||||
|
? projectFlocks?.data.find((row) => row.id === id)
|
||||||
|
: null;
|
||||||
|
|
||||||
const isPengajuan = selectedSingleRow.approval?.step_number == 1;
|
const isProjectFlockRequesting = projectFlock?.approval?.step_number == 1;
|
||||||
const isNotRejected = selectedSingleRow.approval?.action != 'REJECTED';
|
const isProjectFlockNotRejected =
|
||||||
|
projectFlock?.approval?.action != 'REJECTED';
|
||||||
return isPengajuan && isNotRejected;
|
return isProjectFlockRequesting && isProjectFlockNotRejected;
|
||||||
}, [selectedSingleRow, isApproveLoading]);
|
});
|
||||||
|
}, [selectedRowIds, projectFlocks]);
|
||||||
|
|
||||||
// ====== COLUMNS ======
|
// ====== COLUMNS ======
|
||||||
const columns = useMemo<ColumnDef<ProjectFlock>[]>(
|
const columns = useMemo<ColumnDef<ProjectFlock>[]>(
|
||||||
@@ -256,44 +378,39 @@ const ProjectFlockTable = ({ refresh }: { refresh?: () => void }) => {
|
|||||||
const approval = props.row.original.approval;
|
const approval = props.row.original.approval;
|
||||||
const isRejected = approval?.action == 'REJECTED';
|
const isRejected = approval?.action == 'REJECTED';
|
||||||
const isApproved = approval?.action == 'APPROVED';
|
const isApproved = approval?.action == 'APPROVED';
|
||||||
return (
|
|
||||||
<Badge
|
let latestApprovalStepName = approval.step_name;
|
||||||
variant='soft'
|
|
||||||
className={{
|
const badgeColor = isRejected
|
||||||
badge: 'rounded-lg px-2 w-full flex flex-row justify-start',
|
? 'error'
|
||||||
}}
|
: isApproved
|
||||||
color={
|
? approval?.step_number == 1
|
||||||
isRejected
|
? 'neutral'
|
||||||
? 'error'
|
: approval?.step_number == 2
|
||||||
: isApproved
|
? 'success'
|
||||||
? approval?.step_number == 1
|
: approval?.step_number == 3
|
||||||
? 'neutral'
|
? 'error'
|
||||||
: approval?.step_number == 2
|
|
||||||
? 'primary'
|
|
||||||
: approval?.step_number == 3
|
|
||||||
? 'success'
|
|
||||||
: 'neutral'
|
|
||||||
: 'neutral'
|
: 'neutral'
|
||||||
}
|
: 'neutral';
|
||||||
>
|
|
||||||
<Icon
|
switch (approval.action.toLowerCase()) {
|
||||||
icon='mdi:circle'
|
case 'pengajuan':
|
||||||
width={12}
|
latestApprovalStepName = 'Pengajuan';
|
||||||
height={12}
|
break;
|
||||||
color={
|
case 'aktif':
|
||||||
approval?.step_number == 1
|
latestApprovalStepName = 'Aktif';
|
||||||
? 'neutral'
|
break;
|
||||||
: approval?.step_number == 2
|
case 'Selesai':
|
||||||
? 'primary'
|
latestApprovalStepName = 'Closing';
|
||||||
: approval?.step_number == 3
|
break;
|
||||||
? 'success'
|
}
|
||||||
: 'neutral'
|
|
||||||
}
|
if (isRejected) {
|
||||||
/>
|
latestApprovalStepName = 'Ditolak';
|
||||||
{isRejected
|
}
|
||||||
? 'Ditolak'
|
|
||||||
: formatTitleCase(approval?.step_name || '')}
|
return (
|
||||||
</Badge>
|
<StatusBadge color={badgeColor} text={latestApprovalStepName} />
|
||||||
);
|
);
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
@@ -325,27 +442,88 @@ const ProjectFlockTable = ({ refresh }: { refresh?: () => void }) => {
|
|||||||
cell: (props) =>
|
cell: (props) =>
|
||||||
formatDate(props.row.original.created_at, 'MMM DD, YYYY'),
|
formatDate(props.row.original.created_at, 'MMM DD, YYYY'),
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
id: 'actions',
|
||||||
|
cell: (props) => {
|
||||||
|
const currentPageSize =
|
||||||
|
props.table.getPaginationRowModel().rows.length;
|
||||||
|
const currentPageRows = props.table.getPaginationRowModel().flatRows;
|
||||||
|
const currentRowRelativeIndex =
|
||||||
|
currentPageRows.findIndex((r) => r.id === props.row.id) + 1;
|
||||||
|
|
||||||
|
const isLast2Rows = currentRowRelativeIndex > currentPageSize - 2;
|
||||||
|
|
||||||
|
const detailClickHandler = (id: number) => {
|
||||||
|
router.push(
|
||||||
|
`/production/project-flock/detail/?projectFlockId=${id}`
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
const editClickHandler = (id: number) => {
|
||||||
|
router.push(
|
||||||
|
`/production/project-flock/detail/edit/?projectFlockId=${id}`
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
const deleteClickHandler = () => {
|
||||||
|
// Set row selection
|
||||||
|
setRowSelection({
|
||||||
|
[String(props.row.original.id)]: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
deleteModal.openModal();
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<RowOptionsMenu
|
||||||
|
props={props}
|
||||||
|
detailClickHandler={detailClickHandler}
|
||||||
|
editClickHandler={editClickHandler}
|
||||||
|
deleteClickHandler={deleteClickHandler}
|
||||||
|
popoverPosition={isLast2Rows ? 'top' : 'bottom'}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
},
|
||||||
|
},
|
||||||
],
|
],
|
||||||
[]
|
[]
|
||||||
);
|
);
|
||||||
|
|
||||||
|
const exportToExcelHandler = async () => {
|
||||||
|
setIsLoadingExportingToExcel(true);
|
||||||
|
|
||||||
|
toast.error('Not implemented yet!');
|
||||||
|
|
||||||
|
setIsLoadingExportingToExcel(false);
|
||||||
|
};
|
||||||
|
|
||||||
|
const bulkApproveClickHandler = () => {
|
||||||
|
setApprovalAction('APPROVED');
|
||||||
|
confirmModal.openModal();
|
||||||
|
};
|
||||||
|
|
||||||
|
const bulkRejectClickHandler = () => {
|
||||||
|
setApprovalAction('REJECTED');
|
||||||
|
confirmModal.openModal();
|
||||||
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<div className='min-h-screen w-full p-4'>
|
<div className='@container min-h-screen w-full'>
|
||||||
<div className='flex flex-col gap-2 mb-4'>
|
<div className='flex flex-col mb-4'>
|
||||||
<div className='w-full flex flex-col justify-between items-end gap-2'>
|
{/* <div className='w-full flex flex-col justify-between items-end gap-2'>
|
||||||
<div className='flex flex-col sm:flex-row gap-3 w-full'>
|
<div className='flex flex-col sm:flex-row gap-3 w-full'>
|
||||||
<RequirePermission permissions='lti.production.project_flocks.create'>
|
<RequirePermission permissions='lti.production.project_flocks.create'>
|
||||||
<Button
|
<Button
|
||||||
color='primary'
|
color='primary'
|
||||||
className='w-full sm:w-fit'
|
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
setRowSelection({});
|
setRowSelection({});
|
||||||
router.push('/production/project-flock/add');
|
router.push('/production/project-flock/add');
|
||||||
}}
|
}}
|
||||||
|
className='px-3 py-2.5 w-fit text-sm text-base-100 rounded-lg shadow-sm'
|
||||||
>
|
>
|
||||||
<Icon icon='ic:round-plus' width={24} height={24} />
|
<Icon icon='heroicons:plus' width={20} height={20} />
|
||||||
Tambah
|
Add Flock
|
||||||
</Button>
|
</Button>
|
||||||
</RequirePermission>
|
</RequirePermission>
|
||||||
<div className='ms-auto w-full sm:w-auto'>
|
<div className='ms-auto w-full sm:w-auto'>
|
||||||
@@ -423,6 +601,158 @@ const ProjectFlockTable = ({ refresh }: { refresh?: () => void }) => {
|
|||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
</div> */}
|
||||||
|
|
||||||
|
<div className='w-full p-3 flex flex-row justify-between gap-3 flex-wrap border-b border-base-content/10'>
|
||||||
|
<div className='w-fit flex flex-row gap-3 flex-wrap'>
|
||||||
|
<RequirePermission permissions='lti.production.project_flocks.create'>
|
||||||
|
<Button
|
||||||
|
color='primary'
|
||||||
|
onClick={() => {
|
||||||
|
setRowSelection({});
|
||||||
|
router.push('/production/project-flock/add');
|
||||||
|
}}
|
||||||
|
className='px-3 py-2.5 w-fit text-sm text-base-100 rounded-lg shadow-sm'
|
||||||
|
>
|
||||||
|
<Icon icon='heroicons:plus' width={20} height={20} />
|
||||||
|
Add Flock
|
||||||
|
</Button>
|
||||||
|
</RequirePermission>
|
||||||
|
|
||||||
|
{selectedRowIds.length > 0 && canApprove && (
|
||||||
|
<>
|
||||||
|
<hr className='w-px h-full border-none bg-base-content/10 hidden @sm:block' />
|
||||||
|
|
||||||
|
<RequirePermission permissions='lti.production.transfer_to_laying.approve'>
|
||||||
|
<Button
|
||||||
|
variant='outline'
|
||||||
|
color='none'
|
||||||
|
onClick={bulkRejectClickHandler}
|
||||||
|
disabled={selectedRowIds.length === 0}
|
||||||
|
className='px-3 py-2.5 gap-1.5 text-sm text-base-content/50 border border-base-content/10 rounded-xl shadow-button-soft'
|
||||||
|
>
|
||||||
|
<Icon
|
||||||
|
icon='heroicons:x-mark'
|
||||||
|
width={20}
|
||||||
|
height={20}
|
||||||
|
className='text-error'
|
||||||
|
/>
|
||||||
|
Reject
|
||||||
|
</Button>
|
||||||
|
</RequirePermission>
|
||||||
|
|
||||||
|
<RequirePermission permissions='lti.production.transfer_to_laying.approve'>
|
||||||
|
<Button
|
||||||
|
variant='outline'
|
||||||
|
color='none'
|
||||||
|
onClick={bulkApproveClickHandler}
|
||||||
|
disabled={selectedRowIds.length === 0}
|
||||||
|
className='px-3 py-2.5 gap-1.5 text-sm text-base-content/50 border border-base-content/10 rounded-xl shadow-button-soft'
|
||||||
|
>
|
||||||
|
<Icon
|
||||||
|
icon='heroicons:check'
|
||||||
|
width={20}
|
||||||
|
height={20}
|
||||||
|
className='text-success'
|
||||||
|
/>
|
||||||
|
Approve
|
||||||
|
</Button>
|
||||||
|
</RequirePermission>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className='flex flex-1 flex-row justify-start sm:justify-end items-center gap-3 flex-wrap'>
|
||||||
|
<DebouncedTextInput
|
||||||
|
name='search'
|
||||||
|
placeholder='Search'
|
||||||
|
value={tableFilterState.search ?? ''}
|
||||||
|
onChange={searchChangeHandler}
|
||||||
|
startAdornment={
|
||||||
|
<Icon
|
||||||
|
icon='heroicons:magnifying-glass'
|
||||||
|
width={20}
|
||||||
|
height={20}
|
||||||
|
/>
|
||||||
|
}
|
||||||
|
className={{
|
||||||
|
wrapper: 'w-full min-w-24 max-w-3xs',
|
||||||
|
inputWrapper: 'rounded-xl! shadow-button-soft',
|
||||||
|
input:
|
||||||
|
'placeholder:font-semibold placeholder:text-base-content/50',
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<Button
|
||||||
|
variant='outline'
|
||||||
|
color='none'
|
||||||
|
// onClick={filterModal.openModal}
|
||||||
|
className={cn(
|
||||||
|
'px-3 py-2.5 gap-1.5 text-sm text-base-content/50 border border-base-content/10 rounded-xl shadow-button-soft transition-all',
|
||||||
|
{
|
||||||
|
// 'border-primary-gradient text-primary': isFilterActive,
|
||||||
|
}
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
<Icon icon='heroicons:funnel' width={20} height={20} />
|
||||||
|
Filter
|
||||||
|
{/* {isFilterActive && (
|
||||||
|
<Badge
|
||||||
|
className={{
|
||||||
|
badge:
|
||||||
|
'p-1.5 bg-[#FF3535] text-xs text-base-100 border border-base-300 rounded-lg',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{filterCount}
|
||||||
|
</Badge>
|
||||||
|
)} */}
|
||||||
|
</Button>
|
||||||
|
|
||||||
|
<Dropdown
|
||||||
|
align='end'
|
||||||
|
direction='bottom'
|
||||||
|
className={{
|
||||||
|
content:
|
||||||
|
'mt-1 rounded-xl border border-base-content/5 shadow-sm overflow-hidden',
|
||||||
|
}}
|
||||||
|
trigger={
|
||||||
|
<Button
|
||||||
|
variant='outline'
|
||||||
|
color='none'
|
||||||
|
className='px-3 py-2.5 text-sm text-base-content/50 border border-base-content/10 rounded-xl shadow-button-soft'
|
||||||
|
>
|
||||||
|
<div className='flex flex-row items-center gap-1.5'>
|
||||||
|
<Icon
|
||||||
|
icon='heroicons:cloud-arrow-down'
|
||||||
|
width={20}
|
||||||
|
height={20}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<span>Export</span>
|
||||||
|
|
||||||
|
<div className='w-px self-stretch bg-base-content/10' />
|
||||||
|
|
||||||
|
<Icon
|
||||||
|
icon='heroicons:chevron-down'
|
||||||
|
width={14}
|
||||||
|
height={14}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</Button>
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<Button
|
||||||
|
variant='ghost'
|
||||||
|
color='none'
|
||||||
|
onClick={exportToExcelHandler}
|
||||||
|
isLoading={isLoadingExportingToExcel}
|
||||||
|
className='w-full p-3 justify-start text-sm text-base-content/50 font-semibold text-nowrap'
|
||||||
|
>
|
||||||
|
<Icon icon='heroicons:table-cells' width={20} height={20} />
|
||||||
|
Export to Excel
|
||||||
|
</Button>
|
||||||
|
</Dropdown>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<Table<ProjectFlock>
|
<Table<ProjectFlock>
|
||||||
@@ -448,26 +778,20 @@ const ProjectFlockTable = ({ refresh }: { refresh?: () => void }) => {
|
|||||||
setSorting={setSorting}
|
setSorting={setSorting}
|
||||||
rowSelection={rowSelection}
|
rowSelection={rowSelection}
|
||||||
setRowSelection={setRowSelection}
|
setRowSelection={setRowSelection}
|
||||||
|
withCheckbox
|
||||||
className={{
|
className={{
|
||||||
containerClassName: cn({
|
containerClassName: cn('p-3', {
|
||||||
'mb-40':
|
'w-full mb-20':
|
||||||
isResponseSuccess(projectFlocks) &&
|
isResponseSuccess(projectFlocks) &&
|
||||||
projectFlocks?.data?.length > 0,
|
projectFlocks?.data?.length === 0,
|
||||||
}),
|
}),
|
||||||
tableWrapperClassName: 'overflow-x-auto min-h-full!',
|
headerColumnClassName: 'text-nowrap',
|
||||||
tableClassName: 'font-inter w-full table-auto min-h-full!',
|
|
||||||
headerRowClassName: 'border-b border-b-gray-200',
|
|
||||||
headerColumnClassName:
|
|
||||||
'px-6 py-3 text-xs font-semibold text-gray-500 last:flex last:flex-row last:justify-end',
|
|
||||||
bodyRowClassName: 'border-b border-b-gray-200',
|
|
||||||
bodyColumnClassName:
|
|
||||||
'px-6 py-3 last:flex last:flex-row last:justify-end',
|
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<FloatingActionsButton
|
{/* <FloatingActionsButton
|
||||||
actions={[
|
actions={[
|
||||||
{
|
{
|
||||||
action: 'DETAIL',
|
action: 'DETAIL',
|
||||||
@@ -520,7 +844,7 @@ const ProjectFlockTable = ({ refresh }: { refresh?: () => void }) => {
|
|||||||
onClose={() => {
|
onClose={() => {
|
||||||
setRowSelection({});
|
setRowSelection({});
|
||||||
}}
|
}}
|
||||||
/>
|
/> */}
|
||||||
|
|
||||||
<ConfirmationModal
|
<ConfirmationModal
|
||||||
ref={deleteModal.ref}
|
ref={deleteModal.ref}
|
||||||
|
|||||||
+213
-208
@@ -94,230 +94,235 @@ const ProjectFlockClosingForm = ({
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<DrawerHeader
|
<section className='w-full h-full sm:w-[446px] overflow-y-auto'>
|
||||||
leftIcon='mdi:arrow-left'
|
<DrawerHeader
|
||||||
leftIconHref={`/production/project-flock/detail?projectFlockId=${projectFlock.id}`}
|
leftIcon='mdi:arrow-left'
|
||||||
subtitle={`Close ${projectFlock.flock_name}`}
|
leftIconHref={`/production/project-flock/detail?projectFlockId=${projectFlock.id}`}
|
||||||
></DrawerHeader>
|
subtitle={`Close ${projectFlock.flock_name}`}
|
||||||
|
></DrawerHeader>
|
||||||
|
|
||||||
{/* Informasi Kandang */}
|
{/* Informasi Kandang */}
|
||||||
<div className='divider'></div>
|
<div className='divider'></div>
|
||||||
<div className='px-4 pb-4 flex flex-col gap-4'>
|
<div className='px-4 pb-4 flex flex-col gap-4'>
|
||||||
<h2 className='text-2xl font-semibold'>Informasi Kandang</h2>
|
<h2 className='text-2xl font-semibold'>Informasi Kandang</h2>
|
||||||
|
|
||||||
{/* Badge Row */}
|
{/* Badge Row */}
|
||||||
<div className='flex flex-row gap-2'>
|
<div className='flex flex-row gap-2'>
|
||||||
<Badge
|
<Badge
|
||||||
variant='soft'
|
variant='soft'
|
||||||
color='success'
|
color='success'
|
||||||
className={{
|
className={{
|
||||||
badge: 'rounded-lg px-2',
|
badge: 'rounded-lg px-2',
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<Icon icon='mdi:circle' width={12} height={12} color='success' />{' '}
|
<Icon icon='mdi:circle' width={12} height={12} color='success' />{' '}
|
||||||
Aktif
|
Aktif
|
||||||
</Badge>
|
</Badge>
|
||||||
<div className='divider divider-horizontal p-0 m-0'></div>
|
<div className='divider divider-horizontal p-0 m-0'></div>
|
||||||
<Badge
|
<Badge
|
||||||
color='neutral'
|
color='neutral'
|
||||||
variant='soft'
|
variant='soft'
|
||||||
className={{ badge: 'rounded-lg px-2' }}
|
className={{ badge: 'rounded-lg px-2' }}
|
||||||
>
|
>
|
||||||
<Icon icon='mdi:home' width={12} height={12} />
|
<Icon icon='mdi:home' width={12} height={12} />
|
||||||
{` Kapasitas ${formatNumber(projectFlockKandang.kandang?.capacity)} Ekor`}
|
{` Kapasitas ${formatNumber(projectFlockKandang.kandang?.capacity)} Ekor`}
|
||||||
</Badge>
|
</Badge>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Information Grid */}
|
||||||
|
<div className='grid grid-cols-3 gap-4'>
|
||||||
|
{/* Area */}
|
||||||
|
<div
|
||||||
|
className='col-span-1 flex flex-row items-center text-gray-400 font-semibold gap-2
|
||||||
|
relative
|
||||||
|
before:content-[""] before:absolute before:left-[5px] before:top-[90%] before:bottom-[-100%] before:w-[1px] before:border-1 before:border-dashed before:border-gray-400'
|
||||||
|
>
|
||||||
|
<Icon width={14} height={14} icon='mdi:circle-slice-8' /> Area
|
||||||
|
</div>
|
||||||
|
<div className='col-span-2'>{projectFlock.area?.name}</div>
|
||||||
|
|
||||||
|
{/* Lokasi */}
|
||||||
|
<div
|
||||||
|
className='col-span-1 flex flex-row items-center text-gray-400 font-semibold gap-2
|
||||||
|
relative
|
||||||
|
before:content-[""] before:absolute before:left-[5px] before:top-[90%] before:bottom-[-100%] before:w-[1px] before:border-1 before:border-dashed before:border-gray-400'
|
||||||
|
>
|
||||||
|
<Icon width={14} height={14} icon='mdi:circle-slice-8' /> Lokasi
|
||||||
|
</div>
|
||||||
|
<div className='col-span-2'>{projectFlock.location?.name}</div>
|
||||||
|
|
||||||
|
{/* Kandang */}
|
||||||
|
<div
|
||||||
|
className='col-span-1 flex flex-row items-center text-gray-400 font-semibold gap-2
|
||||||
|
relative
|
||||||
|
before:content-[""] before:absolute before:left-[5px] before:top-[90%] before:bottom-[-100%] before:w-[1px] before:border-1 before:border-dashed before:border-gray-400'
|
||||||
|
>
|
||||||
|
<Icon width={14} height={14} icon='mdi:circle-slice-8' /> Kandang
|
||||||
|
</div>
|
||||||
|
<div className='col-span-2'>
|
||||||
|
{projectFlockKandang.kandang?.name}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Jumlah DOC */}
|
||||||
|
<div className='col-span-1 flex flex-row items-center text-gray-400 font-semibold gap-2'>
|
||||||
|
<Icon width={14} height={14} icon='mdi:circle-slice-8' /> Jumlah
|
||||||
|
DOC
|
||||||
|
</div>
|
||||||
|
<div className='col-span-2'>
|
||||||
|
{formatNumber(
|
||||||
|
projectFlockKandang.chickins?.reduce(
|
||||||
|
(total, chickin) => total + chickin.usage_qty,
|
||||||
|
0
|
||||||
|
) ?? 0
|
||||||
|
)}{' '}
|
||||||
|
Ekor
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Information Grid */}
|
{/* Table Biaya */}
|
||||||
<div className='grid grid-cols-3 gap-4'>
|
<div className='divider'></div>
|
||||||
{/* Area */}
|
<div className='px-4 pb-4'>
|
||||||
<div
|
<h2 className='text-2xl font-semibold'>Biaya</h2>
|
||||||
className='col-span-1 flex flex-row items-center text-gray-400 font-semibold gap-2
|
<Table<ClosingExpense>
|
||||||
relative
|
data={
|
||||||
before:content-[""] before:absolute before:left-[5px] before:top-[90%] before:bottom-[-100%] before:w-[1px] before:border-1 before:border-dashed before:border-gray-400'
|
isResponseSuccess(closingData) ? closingData.data?.expenses : []
|
||||||
>
|
}
|
||||||
<Icon width={14} height={14} icon='mdi:circle-slice-8' /> Area
|
columns={[
|
||||||
</div>
|
{
|
||||||
<div className='col-span-2'>{projectFlock.area?.name}</div>
|
header: 'PO Number',
|
||||||
|
accessorKey: 'po_number',
|
||||||
{/* Lokasi */}
|
|
||||||
<div
|
|
||||||
className='col-span-1 flex flex-row items-center text-gray-400 font-semibold gap-2
|
|
||||||
relative
|
|
||||||
before:content-[""] before:absolute before:left-[5px] before:top-[90%] before:bottom-[-100%] before:w-[1px] before:border-1 before:border-dashed before:border-gray-400'
|
|
||||||
>
|
|
||||||
<Icon width={14} height={14} icon='mdi:circle-slice-8' /> Lokasi
|
|
||||||
</div>
|
|
||||||
<div className='col-span-2'>{projectFlock.location?.name}</div>
|
|
||||||
|
|
||||||
{/* Kandang */}
|
|
||||||
<div
|
|
||||||
className='col-span-1 flex flex-row items-center text-gray-400 font-semibold gap-2
|
|
||||||
relative
|
|
||||||
before:content-[""] before:absolute before:left-[5px] before:top-[90%] before:bottom-[-100%] before:w-[1px] before:border-1 before:border-dashed before:border-gray-400'
|
|
||||||
>
|
|
||||||
<Icon width={14} height={14} icon='mdi:circle-slice-8' /> Kandang
|
|
||||||
</div>
|
|
||||||
<div className='col-span-2'>{projectFlockKandang.kandang?.name}</div>
|
|
||||||
|
|
||||||
{/* Jumlah DOC */}
|
|
||||||
<div className='col-span-1 flex flex-row items-center text-gray-400 font-semibold gap-2'>
|
|
||||||
<Icon width={14} height={14} icon='mdi:circle-slice-8' /> Jumlah DOC
|
|
||||||
</div>
|
|
||||||
<div className='col-span-2'>
|
|
||||||
{formatNumber(
|
|
||||||
projectFlockKandang.chickins?.reduce(
|
|
||||||
(total, chickin) => total + chickin.usage_qty,
|
|
||||||
0
|
|
||||||
) ?? 0
|
|
||||||
)}{' '}
|
|
||||||
Ekor
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Table Biaya */}
|
|
||||||
<div className='divider'></div>
|
|
||||||
<div className='px-4 pb-4'>
|
|
||||||
<h2 className='text-2xl font-semibold'>Biaya</h2>
|
|
||||||
<Table<ClosingExpense>
|
|
||||||
data={
|
|
||||||
isResponseSuccess(closingData) ? closingData.data?.expenses : []
|
|
||||||
}
|
|
||||||
columns={[
|
|
||||||
{
|
|
||||||
header: 'PO Number',
|
|
||||||
accessorKey: 'po_number',
|
|
||||||
},
|
|
||||||
{
|
|
||||||
header: 'Total',
|
|
||||||
accessorKey: 'total',
|
|
||||||
},
|
|
||||||
{
|
|
||||||
header: 'Status',
|
|
||||||
accessorKey: 'status',
|
|
||||||
cell(props) {
|
|
||||||
return (
|
|
||||||
<Badge
|
|
||||||
className={{
|
|
||||||
badge: 'rounded-lg',
|
|
||||||
}}
|
|
||||||
variant='soft'
|
|
||||||
color={
|
|
||||||
props.row.original.step < 5
|
|
||||||
? props.row.original.step == 1
|
|
||||||
? 'neutral'
|
|
||||||
: 'success'
|
|
||||||
: 'error'
|
|
||||||
}
|
|
||||||
>
|
|
||||||
{formatTitleCase(props.row.original.step_name)}
|
|
||||||
</Badge>
|
|
||||||
);
|
|
||||||
},
|
},
|
||||||
},
|
{
|
||||||
]}
|
header: 'Total',
|
||||||
className={{
|
accessorKey: 'total',
|
||||||
containerClassName: cn('my-4'),
|
},
|
||||||
tableWrapperClassName: 'overflow-x-auto min-h-full! max-w-120',
|
{
|
||||||
tableClassName: 'font-inter w-full table-sm min-h-full!',
|
header: 'Status',
|
||||||
headerRowClassName: 'border-b border-b-gray-200',
|
accessorKey: 'status',
|
||||||
headerColumnClassName:
|
cell(props) {
|
||||||
'px-3 py-3 text-xs font-semibold text-gray-500 last:flex last:flex-row last:justify-end',
|
return (
|
||||||
bodyRowClassName: 'border-b border-b-gray-200',
|
<Badge
|
||||||
bodyColumnClassName:
|
className={{
|
||||||
'px-3 py-3 last:flex last:flex-row last:justify-end',
|
badge: 'rounded-lg',
|
||||||
paginationClassName: 'hidden',
|
}}
|
||||||
}}
|
variant='soft'
|
||||||
/>
|
color={
|
||||||
{/* {errorExpense && (
|
props.row.original.step < 5
|
||||||
|
? props.row.original.step == 1
|
||||||
|
? 'neutral'
|
||||||
|
: 'success'
|
||||||
|
: 'error'
|
||||||
|
}
|
||||||
|
>
|
||||||
|
{formatTitleCase(props.row.original.step_name)}
|
||||||
|
</Badge>
|
||||||
|
);
|
||||||
|
},
|
||||||
|
},
|
||||||
|
]}
|
||||||
|
className={{
|
||||||
|
containerClassName: cn('my-4'),
|
||||||
|
tableWrapperClassName: 'overflow-x-auto min-h-full! max-w-120',
|
||||||
|
tableClassName: 'font-inter w-full table-sm min-h-full!',
|
||||||
|
headerRowClassName: 'border-b border-b-gray-200',
|
||||||
|
headerColumnClassName:
|
||||||
|
'px-3 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-3 py-3 last:flex last:flex-row last:justify-end',
|
||||||
|
paginationClassName: 'hidden',
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
{/* {errorExpense && (
|
||||||
<div className='text-center text-error text-sm'>
|
<div className='text-center text-error text-sm'>
|
||||||
*Pastikan semua biaya sudah selesai sebelum melakukan closing.
|
*Pastikan semua biaya sudah selesai sebelum melakukan closing.
|
||||||
</div>
|
</div>
|
||||||
)} */}
|
)} */}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Table Persediaan Gudang */}
|
{/* Table Persediaan Gudang */}
|
||||||
<div className='divider'></div>
|
<div className='divider'></div>
|
||||||
<div className='px-4 pb-4'>
|
<div className='px-4 pb-4'>
|
||||||
<h2 className='text-2xl font-semibold'>Persediaan Gudang</h2>
|
<h2 className='text-2xl font-semibold'>Persediaan Gudang</h2>
|
||||||
<Table<StockItem>
|
<Table<StockItem>
|
||||||
data={
|
data={
|
||||||
isResponseSuccess(closingData)
|
isResponseSuccess(closingData)
|
||||||
? closingData.data?.stock_remaining
|
? closingData.data?.stock_remaining
|
||||||
: []
|
: []
|
||||||
}
|
}
|
||||||
columns={[
|
columns={[
|
||||||
{
|
{
|
||||||
header: 'Product',
|
header: 'Product',
|
||||||
accessorKey: 'product_name',
|
accessorKey: 'product_name',
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
header: 'Kategori',
|
header: 'Kategori',
|
||||||
accessorKey: 'product_category',
|
accessorKey: 'product_category',
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
header: 'Quantity',
|
header: 'Quantity',
|
||||||
accessorKey: 'quantity',
|
accessorKey: 'quantity',
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
header: 'UOM',
|
header: 'UOM',
|
||||||
accessorKey: 'uom',
|
accessorKey: 'uom',
|
||||||
},
|
},
|
||||||
]}
|
]}
|
||||||
className={{
|
className={{
|
||||||
containerClassName: cn('my-4'),
|
containerClassName: cn('my-4'),
|
||||||
tableWrapperClassName: 'overflow-x-auto min-h-full! max-w-120',
|
tableWrapperClassName: 'overflow-x-auto min-h-full! max-w-120',
|
||||||
tableClassName: 'font-inter w-full table-sm min-h-full!',
|
tableClassName: 'font-inter w-full table-sm min-h-full!',
|
||||||
headerRowClassName: 'border-b border-b-gray-200',
|
headerRowClassName: 'border-b border-b-gray-200',
|
||||||
headerColumnClassName:
|
headerColumnClassName:
|
||||||
'px-3 py-3 text-xs font-semibold text-gray-500 last:flex last:flex-row last:justify-end',
|
'px-3 py-3 text-xs font-semibold text-gray-500 last:flex last:flex-row last:justify-end',
|
||||||
bodyRowClassName: 'border-b border-b-gray-200',
|
bodyRowClassName: 'border-b border-b-gray-200',
|
||||||
bodyColumnClassName:
|
bodyColumnClassName:
|
||||||
'px-3 py-3 last:flex last:flex-row last:justify-end',
|
'px-3 py-3 last:flex last:flex-row last:justify-end',
|
||||||
paginationClassName: 'hidden',
|
paginationClassName: 'hidden',
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
{/* {errorStock && (
|
{/* {errorStock && (
|
||||||
<div className='text-center text-error text-sm'>
|
<div className='text-center text-error text-sm'>
|
||||||
*Masih ada sisa stock yang belum dihabiskan.
|
*Masih ada sisa stock yang belum dihabiskan.
|
||||||
</div>
|
</div>
|
||||||
)} */}
|
)} */}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className='p-4 mt-6'>
|
<div className='p-4 mt-6'>
|
||||||
<RequirePermission permissions='lti.production.project_flock_kandangs.closing'>
|
<RequirePermission permissions='lti.production.project_flock_kandangs.closing'>
|
||||||
<Button
|
<Button
|
||||||
className='w-full'
|
className='w-full'
|
||||||
color='error'
|
color='error'
|
||||||
isLoading={isLoading}
|
isLoading={isLoading}
|
||||||
disabled={!isCanCloseValid}
|
disabled={!isCanCloseValid}
|
||||||
onClick={() => closeModal.openModal()}
|
onClick={() => closeModal.openModal()}
|
||||||
>
|
>
|
||||||
<Icon icon='mdi:checkbox-marked-circle-outline' />{' '}
|
<Icon icon='mdi:checkbox-marked-circle-outline' />{' '}
|
||||||
{isCanClose ? 'Close' : 'Unclose'}
|
{isCanClose ? 'Close' : 'Unclose'}
|
||||||
</Button>
|
</Button>
|
||||||
</RequirePermission>
|
</RequirePermission>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<ConfirmationModal
|
<ConfirmationModal
|
||||||
ref={closeModal.ref}
|
ref={closeModal.ref}
|
||||||
type='error'
|
type='error'
|
||||||
text={
|
text={
|
||||||
isCanClose
|
isCanClose
|
||||||
? 'Apakah kamu yakin ingin mengakhiri project ini ? *Pastikan persediaan produk di gudang terkait sudah kosong, dan BOP sudah selesai'
|
? 'Apakah kamu yakin ingin mengakhiri project ini ? *Pastikan persediaan produk di gudang terkait sudah kosong, dan BOP sudah selesai'
|
||||||
: 'Apakah kamu yakin ingin membuka kembali project ini ? *Project ini akan kembali ke status aktif'
|
: 'Apakah kamu yakin ingin membuka kembali project ini ? *Project ini akan kembali ke status aktif'
|
||||||
}
|
}
|
||||||
secondaryButton={{
|
secondaryButton={{
|
||||||
text: 'Tidak',
|
text: 'Tidak',
|
||||||
}}
|
}}
|
||||||
primaryButton={{
|
primaryButton={{
|
||||||
text: 'Ya',
|
text: 'Ya',
|
||||||
color: 'error',
|
color: 'error',
|
||||||
isLoading: isClosingLoading,
|
isLoading: isClosingLoading,
|
||||||
onClick: confirmationModalCloseClickHandler,
|
onClick: confirmationModalCloseClickHandler,
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
|
</section>
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -4,12 +4,7 @@ import Card from '@/components/Card';
|
|||||||
import { RadioGroup, RadioGroupItem } from '@/components/input/RadioInput';
|
import { RadioGroup, RadioGroupItem } from '@/components/input/RadioInput';
|
||||||
import Tooltip from '@/components/Tooltip';
|
import Tooltip from '@/components/Tooltip';
|
||||||
import DrawerHeader from '@/components/helper/drawer/DrawerHeader';
|
import DrawerHeader from '@/components/helper/drawer/DrawerHeader';
|
||||||
import {
|
import { cn, formatCurrency, formatDate, formatNumber } from '@/lib/helper';
|
||||||
formatCurrency,
|
|
||||||
formatDate,
|
|
||||||
formatNumber,
|
|
||||||
formatTitleCase,
|
|
||||||
} from '@/lib/helper';
|
|
||||||
import { ProjectFlock } from '@/types/api/production/project-flock';
|
import { ProjectFlock } from '@/types/api/production/project-flock';
|
||||||
import { Icon } from '@iconify/react';
|
import { Icon } from '@iconify/react';
|
||||||
import Link from 'next/link';
|
import Link from 'next/link';
|
||||||
@@ -20,16 +15,15 @@ import ConfirmationModal from '@/components/modal/ConfirmationModal';
|
|||||||
import { ProjectFlockApi } from '@/services/api/production/project-flock';
|
import { ProjectFlockApi } from '@/services/api/production/project-flock';
|
||||||
import { isResponseError, isResponseSuccess } from '@/lib/api-helper';
|
import { isResponseError, isResponseSuccess } from '@/lib/api-helper';
|
||||||
import toast from 'react-hot-toast';
|
import toast from 'react-hot-toast';
|
||||||
import ApprovalSteps, {
|
|
||||||
useApprovalSteps,
|
|
||||||
} from '@/components/pages/ApprovalSteps';
|
|
||||||
import {
|
|
||||||
PROJECT_FLOCK_APPROVAL_LINE,
|
|
||||||
PROJECT_FLOCK_KANDANGS_APPROVAL_LINE,
|
|
||||||
} from '@/config/approval-line';
|
|
||||||
import useSWR from 'swr';
|
import useSWR from 'swr';
|
||||||
import { ProjectFlockKandangApi } from '@/services/api/production';
|
|
||||||
import RequirePermission from '@/components/helper/RequirePermission';
|
import RequirePermission from '@/components/helper/RequirePermission';
|
||||||
|
import ApprovalStepsV2 from '@/components/helper/ApprovalStepsV2';
|
||||||
|
import { APPROVAL_WORKFLOWS } from '@/config/constant';
|
||||||
|
import Table from '@/components/Table';
|
||||||
|
import { ProjectFlockFormConfirmationTableType } from '../form/ProjectFlockForm';
|
||||||
|
import { ColumnDef } from '@tanstack/react-table';
|
||||||
|
import StatusBadge from '@/components/helper/StatusBadge';
|
||||||
|
import { ProjectFlockKandangApi } from '@/services/api/production/project-flock-kandang';
|
||||||
|
|
||||||
const ProjectFlockDetail = ({
|
const ProjectFlockDetail = ({
|
||||||
projectFlock,
|
projectFlock,
|
||||||
@@ -40,7 +34,7 @@ const ProjectFlockDetail = ({
|
|||||||
const deleteModal = useModal();
|
const deleteModal = useModal();
|
||||||
const [isDeleteLoading, setIsDeleteLoading] = useState(false);
|
const [isDeleteLoading, setIsDeleteLoading] = useState(false);
|
||||||
const [openBudgets, setOpenBudget] = useState(false);
|
const [openBudgets, setOpenBudget] = useState(false);
|
||||||
const [selectedKandangId, setSelectedKamdangId] = useState<string | null>(
|
const [selectedKandangId, setSelectedKandangId] = useState<string | null>(
|
||||||
null
|
null
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -61,30 +55,94 @@ const ProjectFlockDetail = ({
|
|||||||
: null
|
: null
|
||||||
);
|
);
|
||||||
|
|
||||||
const {
|
const { data: projectFlockApprovalResponse } = useSWR(
|
||||||
approvals,
|
projectFlock.id ? ['approval-project-flock', projectFlock.id] : undefined,
|
||||||
isLoading: approvalsLoading,
|
([, id]) => ProjectFlockApi.getApprovalLineHistory(Number(id))
|
||||||
refresh: refreshApprovals,
|
);
|
||||||
} = useApprovalSteps({
|
|
||||||
latestApproval: projectFlock?.approval,
|
|
||||||
approvalLines: PROJECT_FLOCK_APPROVAL_LINE,
|
|
||||||
moduleName: 'PROJECT_FLOCKS',
|
|
||||||
moduleId: projectFlock?.id?.toString() ?? '',
|
|
||||||
});
|
|
||||||
|
|
||||||
const { approvals: kandangApprovals, isLoading: kandangApprovalsLoading } =
|
const projectFlockApproval = isResponseSuccess(projectFlockApprovalResponse)
|
||||||
useApprovalSteps({
|
? projectFlockApprovalResponse.data
|
||||||
latestApproval:
|
: undefined;
|
||||||
selectedKandangId && isResponseSuccess(projectFlockKandang)
|
|
||||||
? projectFlockKandang?.data?.approval
|
const { data: projectFlockKandangApprovalResponse } = useSWR(
|
||||||
: undefined,
|
selectedKandang?.project_flock_kandang_id
|
||||||
approvalLines: PROJECT_FLOCK_KANDANGS_APPROVAL_LINE,
|
? [
|
||||||
moduleName: 'PROJECT_FLOCK_KANDANGS',
|
'approval-project-flock-kandang',
|
||||||
moduleId:
|
selectedKandang?.project_flock_kandang_id,
|
||||||
selectedKandangId && isResponseSuccess(projectFlockKandang)
|
]
|
||||||
? projectFlockKandang?.data?.id?.toString()
|
: undefined,
|
||||||
: '',
|
([, id]) => ProjectFlockKandangApi.getApprovalLineHistory(Number(id))
|
||||||
});
|
);
|
||||||
|
|
||||||
|
const projectFlockKandangApproval = isResponseSuccess(
|
||||||
|
projectFlockKandangApprovalResponse
|
||||||
|
)
|
||||||
|
? projectFlockKandangApprovalResponse.data
|
||||||
|
: undefined;
|
||||||
|
|
||||||
|
const confirmationTableColumns: ColumnDef<ProjectFlockFormConfirmationTableType>[] =
|
||||||
|
[
|
||||||
|
{
|
||||||
|
header: 'Label',
|
||||||
|
accessorKey: 'label',
|
||||||
|
enableSorting: false,
|
||||||
|
cell: ({ row }) => {
|
||||||
|
const isSubRow = row.depth > 0;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
{!isSubRow && row.original.label}
|
||||||
|
|
||||||
|
{isSubRow && (
|
||||||
|
<div
|
||||||
|
className={cn('w-full min-h-full flex items-stretch gap-0')}
|
||||||
|
>
|
||||||
|
<div className='w-px mx-4 bg-base-content/10' />
|
||||||
|
<span className='p-3'>{row.original.label}</span>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
header: 'Value',
|
||||||
|
accessorKey: 'value',
|
||||||
|
enableSorting: false,
|
||||||
|
cell: ({ row }) => row.original.value,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
const confirmationTableData: ProjectFlockFormConfirmationTableType[] = [
|
||||||
|
{
|
||||||
|
label: 'Tanggal',
|
||||||
|
value: formatDate(projectFlock.created_at, 'DD MMMM YYYY'),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'Area',
|
||||||
|
value: projectFlock.area.name ?? '-',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'Lokasi',
|
||||||
|
value: projectFlock.location.name ?? '-',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'Flock',
|
||||||
|
value: projectFlock.flock_name ?? '-',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'Kategori',
|
||||||
|
value: projectFlock.category ?? '-',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'Standar Produksi',
|
||||||
|
value: projectFlock.production_standard.name ?? '-',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'Periode',
|
||||||
|
value: projectFlock.period ?? '-',
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
const confirmationModalDeleteClickHandler = async () => {
|
const confirmationModalDeleteClickHandler = async () => {
|
||||||
setIsDeleteLoading(true);
|
setIsDeleteLoading(true);
|
||||||
@@ -104,12 +162,14 @@ const ProjectFlockDetail = ({
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<div className='h-full w-full flex flex-col gap-4'>
|
<div className='h-full w-full flex flex-col overflow-x-hidden overflow-y-auto'>
|
||||||
{/* Header */}
|
{/* Header */}
|
||||||
<DrawerHeader
|
<DrawerHeader
|
||||||
leftIcon='mdi:close'
|
leftIcon='heroicons:chevron-left'
|
||||||
leftIconHref='/production/project-flock'
|
leftIconHref='/production/project-flock'
|
||||||
subtitle={`Created On ${formatDate(projectFlock.created_at, 'MMM DD, YYYY')}`}
|
leftIconClassName='hover:text-gray-400'
|
||||||
|
subtitle='Detail Flock'
|
||||||
|
className='sticky top-0 z-10 bg-base-100'
|
||||||
>
|
>
|
||||||
<RequirePermission permissions='lti.production.project_flocks.update'>
|
<RequirePermission permissions='lti.production.project_flocks.update'>
|
||||||
<Link
|
<Link
|
||||||
@@ -118,7 +178,7 @@ const ProjectFlockDetail = ({
|
|||||||
>
|
>
|
||||||
<Tooltip content='Edit' position='bottom'>
|
<Tooltip content='Edit' position='bottom'>
|
||||||
<Button variant='link' className='p-0 text-neutral'>
|
<Button variant='link' className='p-0 text-neutral'>
|
||||||
<Icon icon='mdi:square-edit-outline' width={20} height={20} />
|
<Icon icon='heroicons:pencil-square' width={20} height={20} />
|
||||||
</Button>
|
</Button>
|
||||||
</Tooltip>
|
</Tooltip>
|
||||||
</Link>
|
</Link>
|
||||||
@@ -132,332 +192,224 @@ const ProjectFlockDetail = ({
|
|||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<Tooltip content='Hapus' position='bottom'>
|
<Tooltip content='Hapus' position='bottom'>
|
||||||
<Icon icon='mdi:trash-can-outline' width={20} height={20} />
|
<Icon icon='heroicons:trash' width={20} height={20} />
|
||||||
</Tooltip>
|
</Tooltip>
|
||||||
</Button>
|
</Button>
|
||||||
</RequirePermission>
|
</RequirePermission>
|
||||||
</DrawerHeader>
|
</DrawerHeader>
|
||||||
|
|
||||||
{/* Informasi Umum */}
|
<ApprovalStepsV2
|
||||||
<div className='border-t-1 border-gray-300'>
|
approvals={projectFlockApproval}
|
||||||
<div className='p-4 flex flex-col gap-4'>
|
steps={APPROVAL_WORKFLOWS.PROJECT_FLOCKS}
|
||||||
<h2 className='text-2xl font-semibold'>Informasi Umum</h2>
|
/>
|
||||||
{/* Status Approval */}
|
|
||||||
{approvals && !approvalsLoading && (
|
|
||||||
<div className='text-sm my-3'>
|
|
||||||
<ApprovalSteps approvals={approvals} />
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
{/* Badge Row */}
|
|
||||||
<div className='flex flex-row gap-2'>
|
|
||||||
<Badge
|
|
||||||
variant='soft'
|
|
||||||
color={
|
|
||||||
projectFlock.approval?.step_number == 1
|
|
||||||
? 'neutral'
|
|
||||||
: projectFlock.approval?.step_number == 2
|
|
||||||
? 'primary'
|
|
||||||
: projectFlock.approval?.step_number == 3
|
|
||||||
? 'success'
|
|
||||||
: undefined
|
|
||||||
}
|
|
||||||
className={{
|
|
||||||
badge: 'rounded-lg px-2',
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<Icon
|
|
||||||
icon='mdi:circle'
|
|
||||||
width={12}
|
|
||||||
height={12}
|
|
||||||
color={
|
|
||||||
projectFlock.approval?.step_number == 1
|
|
||||||
? 'neutral'
|
|
||||||
: projectFlock.approval?.step_number == 2
|
|
||||||
? 'primary'
|
|
||||||
: projectFlock.approval?.step_number == 3
|
|
||||||
? 'success'
|
|
||||||
: undefined
|
|
||||||
}
|
|
||||||
/>{' '}
|
|
||||||
{projectFlock.approval?.step_name}
|
|
||||||
</Badge>
|
|
||||||
<div className='divider divider-horizontal p-0 m-0'></div>
|
|
||||||
<Badge
|
|
||||||
color='neutral'
|
|
||||||
variant='soft'
|
|
||||||
className={{ badge: 'rounded-lg px-2' }}
|
|
||||||
>
|
|
||||||
<Icon icon='mdi:bookmark' width={12} height={12} />
|
|
||||||
{` ${formatTitleCase(projectFlock.category ?? '')}`}
|
|
||||||
</Badge>
|
|
||||||
</div>
|
|
||||||
{/* Information Grid */}
|
|
||||||
<div className='grid grid-cols-3 gap-4'>
|
|
||||||
<div className='col-span-1 flex flex-row items-center text-gray-400 font-semibold gap-2'>
|
|
||||||
<Icon width={14} height={14} icon='mdi:account' /> Submitted
|
|
||||||
</div>
|
|
||||||
<div className='col-span-2'>
|
|
||||||
<Badge
|
|
||||||
variant='soft'
|
|
||||||
color='neutral'
|
|
||||||
className={{
|
|
||||||
badge: 'rounded-lg px-2',
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<Icon icon='mdi:account-circle' width={14} height={14} />{' '}
|
|
||||||
{projectFlock.created_user?.name}
|
|
||||||
</Badge>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* BARIS 1 */}
|
<div className='w-full p-4 flex flex-col gap-3 border-b border-base-content/10'>
|
||||||
<div
|
<h4 className='text-base font-medium text-base-content/50 font-roboto'>
|
||||||
className='col-span-1 flex flex-row items-center text-gray-400 font-semibold gap-2
|
Informasi Umum
|
||||||
relative
|
</h4>
|
||||||
before:content-[""] before:absolute before:left-[5px] before:top-[90%] before:bottom-[-100%] before:w-[1px] before:border-1 before:border-dashed before:border-gray-400'
|
|
||||||
>
|
|
||||||
<Icon width={14} height={14} icon='mdi:circle-slice-8' /> Area
|
|
||||||
</div>
|
|
||||||
<div className='col-span-2'>{projectFlock?.area?.name}</div>
|
|
||||||
|
|
||||||
{/* BARIS 2 */}
|
<Table<ProjectFlockFormConfirmationTableType>
|
||||||
<div
|
columns={confirmationTableColumns}
|
||||||
className='col-span-1 flex flex-row items-center text-gray-400 font-semibold gap-2
|
data={confirmationTableData}
|
||||||
relative
|
withPagination={false}
|
||||||
before:content-[""] before:absolute before:left-[5px] before:top-[90%] before:bottom-[-100%] before:w-[1px] before:border-1 before:border-dashed before:border-gray-400'
|
pageSize={10000}
|
||||||
>
|
expanded={true}
|
||||||
<Icon width={14} height={14} icon='mdi:circle-slice-8' /> Lokasi
|
getSubRows={(row) => row.subRows}
|
||||||
</div>
|
className={{
|
||||||
<div className='col-span-2'>{projectFlock?.location?.name}</div>
|
headerRowClassName: 'border-b border-base-content/10',
|
||||||
|
bodyRowClassName: 'border-none',
|
||||||
<div
|
bodySubRowClassName: () => 'border-none',
|
||||||
className='col-span-1 flex flex-row items-center text-gray-400 font-semibold gap-2
|
bodySubRowColumnClassName: () => 'first:p-0',
|
||||||
relative
|
}}
|
||||||
before:content-[""] before:absolute before:left-[5px] before:top-[90%] before:bottom-[-100%] before:w-[1px] before:border-1 before:border-dashed before:border-gray-400'
|
/>
|
||||||
>
|
|
||||||
<Icon width={14} height={14} icon='mdi:circle-slice-8' /> FCR
|
|
||||||
</div>
|
|
||||||
<div className='col-span-2'>{projectFlock?.fcr?.name}</div>
|
|
||||||
|
|
||||||
<div
|
|
||||||
className='col-span-1 flex flex-row items-center text-gray-400 font-semibold gap-2
|
|
||||||
relative
|
|
||||||
before:content-[""] before:absolute before:left-[5px] before:top-[90%] before:bottom-[-100%] before:w-[1px] before:border-1 before:border-dashed before:border-gray-400'
|
|
||||||
>
|
|
||||||
<Icon width={14} height={14} icon='mdi:circle-slice-8' />{' '}
|
|
||||||
Standard
|
|
||||||
</div>
|
|
||||||
<div className='col-span-2'>
|
|
||||||
{projectFlock?.production_standard?.name ?? '-'}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* BARIS 3 (Terakhir - TIDAK PERLU garis di bawahnya) */}
|
|
||||||
<div className='col-span-1 flex flex-row items-center text-gray-400 font-semibold gap-2'>
|
|
||||||
<Icon width={14} height={14} icon='mdi:circle-slice-8' />{' '}
|
|
||||||
Kategori
|
|
||||||
</div>
|
|
||||||
<div className='col-span-2'>
|
|
||||||
{formatTitleCase(projectFlock.category ?? '')}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Kandang Aktif */}
|
<div className='w-full p-4 flex flex-col gap-3 border-b border-base-content/10'>
|
||||||
<div className='border-t-1 border-gray-300'>
|
<h4 className='text-base font-medium text-base-content/50 font-roboto'>
|
||||||
<div className='p-4 flex flex-col gap-4'>
|
Kandang Aktif
|
||||||
<h2 className='text-2xl font-semibold'>Kandang Aktif</h2>
|
</h4>
|
||||||
{kandangApprovals && !kandangApprovalsLoading && (
|
|
||||||
<ApprovalSteps approvals={kandangApprovals} />
|
|
||||||
)}
|
|
||||||
{/* Badge Row */}
|
|
||||||
<div className='flex flex-row gap-2'>
|
|
||||||
<Badge
|
|
||||||
variant='soft'
|
|
||||||
color={'primary'}
|
|
||||||
className={{
|
|
||||||
badge: 'rounded-lg px-2',
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<Icon
|
|
||||||
icon='mdi:circle'
|
|
||||||
width={12}
|
|
||||||
height={12}
|
|
||||||
color={'primary'}
|
|
||||||
/>{' '}
|
|
||||||
Kandang Aktif ({projectFlock.kandangs?.length})
|
|
||||||
</Badge>
|
|
||||||
<div className='divider divider-horizontal p-0 m-0'></div>
|
|
||||||
<Badge
|
|
||||||
color='neutral'
|
|
||||||
variant='soft'
|
|
||||||
className={{ badge: 'rounded-lg px-2 cursor-pointer' }}
|
|
||||||
onClick={() => {
|
|
||||||
setOpenBudget(!openBudgets);
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
{` ${formatCurrency(
|
|
||||||
(projectFlock.project_budgets ?? []).reduce(
|
|
||||||
(acc, curr) => acc + curr.price * curr.qty,
|
|
||||||
0
|
|
||||||
)
|
|
||||||
)}`}
|
|
||||||
<Icon
|
|
||||||
icon={`mdi:${openBudgets ? 'eye' : 'eye-off'}`}
|
|
||||||
width={12}
|
|
||||||
height={12}
|
|
||||||
/>
|
|
||||||
</Badge>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Card List Project Budgets */}
|
<div className='flex flex-row gap-2'>
|
||||||
{openBudgets &&
|
<StatusBadge
|
||||||
(projectFlock.project_budgets ?? []).map((budget) => (
|
color='info'
|
||||||
<Card
|
text={`Kandang Aktif (${projectFlock.kandangs?.length})`}
|
||||||
key={budget.id}
|
className={{ badge: 'w-fit text-nowrap' }}
|
||||||
variant='bordered'
|
/>
|
||||||
className={{
|
|
||||||
wrapper: 'w-full',
|
|
||||||
body: 'p-3',
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<div className='flex flex-col gap-6'>
|
|
||||||
<div className='flex flex-row justify-between items-center'>
|
|
||||||
<div className='flex flex-row gap-2 items-center text-gray-400'>
|
|
||||||
<Icon icon={'mdi:tag'} width={14} height={14} />{' '}
|
|
||||||
<span>Jenis Produk</span>
|
|
||||||
</div>
|
|
||||||
<div className='text-end text-gray-500'>
|
|
||||||
{budget?.nonstock?.name}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div className='flex flex-row justify-between items-center'>
|
|
||||||
<div className='flex flex-row gap-2 items-center text-gray-400'>
|
|
||||||
<Icon icon={'mdi:tag'} width={14} height={14} />{' '}
|
|
||||||
<span>Nama Satuan</span>
|
|
||||||
</div>
|
|
||||||
<div className='text-end text-gray-500'>
|
|
||||||
{budget?.nonstock?.uom?.name}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div className='flex flex-row justify-between items-center'>
|
|
||||||
<div className='flex flex-row gap-2 items-center text-gray-400'>
|
|
||||||
<Icon
|
|
||||||
icon={'mdi:file-multiple'}
|
|
||||||
width={14}
|
|
||||||
height={14}
|
|
||||||
/>{' '}
|
|
||||||
<span>Jumlah Pembelian</span>
|
|
||||||
</div>
|
|
||||||
<div className='text-end text-gray-500'>
|
|
||||||
{formatNumber(budget.qty)}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div className='flex flex-row justify-between items-center'>
|
|
||||||
<div className='flex flex-row gap-2 items-center text-gray-400'>
|
|
||||||
<Icon icon={'mdi:file'} width={14} height={14} />{' '}
|
|
||||||
<span>Harga Satuan</span>
|
|
||||||
</div>
|
|
||||||
<div className='text-end text-gray-500'>
|
|
||||||
{formatCurrency(budget.price)}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div className='flex flex-row justify-between items-center'>
|
|
||||||
<div className='flex flex-row gap-2 items-center text-gray-400'>
|
|
||||||
<Icon icon={'mdi:calculator'} width={14} height={14} />{' '}
|
|
||||||
<span>Total Harga</span>
|
|
||||||
</div>
|
|
||||||
<div className='text-end text-gray-500'>
|
|
||||||
{formatCurrency(budget.price * budget.qty)}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</Card>
|
|
||||||
))}
|
|
||||||
|
|
||||||
{/* Card Kandangs */}
|
<StatusBadge
|
||||||
<Card
|
color='neutral'
|
||||||
variant='bordered'
|
onClick={() => {
|
||||||
className={{
|
setOpenBudget(!openBudgets);
|
||||||
wrapper: 'w-full',
|
|
||||||
body: 'p-3',
|
|
||||||
}}
|
}}
|
||||||
>
|
text={
|
||||||
<RadioGroup
|
<>
|
||||||
name='gender'
|
{` ${formatCurrency(
|
||||||
|
(projectFlock.project_budgets ?? []).reduce(
|
||||||
|
(acc, curr) => acc + curr.price * curr.qty,
|
||||||
|
0
|
||||||
|
)
|
||||||
|
)}`}
|
||||||
|
<Icon
|
||||||
|
icon={`mdi:${openBudgets ? 'eye' : 'eye-off'}`}
|
||||||
|
width={12}
|
||||||
|
height={12}
|
||||||
|
/>
|
||||||
|
</>
|
||||||
|
}
|
||||||
|
className={{ badge: 'w-fit text-nowrap cursor-pointer' }}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Card List Project Budgets */}
|
||||||
|
{openBudgets &&
|
||||||
|
(projectFlock.project_budgets ?? []).map((budget) => (
|
||||||
|
<Card
|
||||||
|
key={budget.id}
|
||||||
|
variant='bordered'
|
||||||
className={{
|
className={{
|
||||||
radioWrapper: 'grid grid-cols-1 gap-6',
|
wrapper: 'w-full rounded-lg',
|
||||||
|
body: 'p-3',
|
||||||
}}
|
}}
|
||||||
onChange={(e) => setSelectedKamdangId(e.target.value)}
|
|
||||||
value={selectedKandangId?.toString()}
|
|
||||||
size='md'
|
|
||||||
color='neutral'
|
|
||||||
disabled={projectFlock?.approval?.step_number == 1}
|
|
||||||
>
|
>
|
||||||
{projectFlock.kandangs?.map((kandang) => (
|
<div className='flex flex-col gap-6'>
|
||||||
<div
|
<div className='flex flex-row justify-between items-center'>
|
||||||
key={kandang.id}
|
<div className='flex flex-row gap-2 items-center text-gray-400'>
|
||||||
className={`grid grid-cols-2 gap-6 cursor-pointer hover:text-gray-800`}
|
<Icon icon={'mdi:tag'} width={14} height={14} />{' '}
|
||||||
onClick={() =>
|
<span>Jenis Produk</span>
|
||||||
projectFlock?.approval?.step_number > 1 &&
|
</div>
|
||||||
setSelectedKamdangId(kandang?.id?.toString())
|
<div className='text-end text-gray-500'>
|
||||||
}
|
{budget?.nonstock?.name}
|
||||||
>
|
|
||||||
<RadioGroupItem
|
|
||||||
value={kandang?.id?.toString()}
|
|
||||||
label={kandang?.name}
|
|
||||||
disabled={projectFlock?.approval?.step_number == 1}
|
|
||||||
/>
|
|
||||||
<div className='text-end'>
|
|
||||||
<Badge
|
|
||||||
className={{
|
|
||||||
badge: 'rounded-lg',
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
Kapasitas {kandang?.capacity} Ekor
|
|
||||||
</Badge>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
))}
|
<div className='flex flex-row justify-between items-center'>
|
||||||
</RadioGroup>
|
<div className='flex flex-row gap-2 items-center text-gray-400'>
|
||||||
</Card>
|
<Icon icon={'mdi:tag'} width={14} height={14} />{' '}
|
||||||
<div className='grid grid-cols-4 gap-3'>
|
<span>Nama Satuan</span>
|
||||||
<RequirePermission permissions='lti.production.chickins.detail'>
|
</div>
|
||||||
<Link
|
<div className='text-end text-gray-500'>
|
||||||
href={`/production/project-flock/chickin/add/kandang?projectFlockKandangId=${selectedKandang?.project_flock_kandang_id}&projectFlockId=${projectFlock.id}`}
|
{budget?.nonstock?.uom?.name}
|
||||||
className='m-0 p-0'
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className='flex flex-row justify-between items-center'>
|
||||||
|
<div className='flex flex-row gap-2 items-center text-gray-400'>
|
||||||
|
<Icon icon={'mdi:file-multiple'} width={14} height={14} />{' '}
|
||||||
|
<span>Jumlah Pembelian</span>
|
||||||
|
</div>
|
||||||
|
<div className='text-end text-gray-500'>
|
||||||
|
{formatNumber(budget.qty)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className='flex flex-row justify-between items-center'>
|
||||||
|
<div className='flex flex-row gap-2 items-center text-gray-400'>
|
||||||
|
<Icon icon={'mdi:file'} width={14} height={14} />{' '}
|
||||||
|
<span>Harga Satuan</span>
|
||||||
|
</div>
|
||||||
|
<div className='text-end text-gray-500'>
|
||||||
|
{formatCurrency(budget.price)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className='flex flex-row justify-between items-center'>
|
||||||
|
<div className='flex flex-row gap-2 items-center text-gray-400'>
|
||||||
|
<Icon icon={'mdi:calculator'} width={14} height={14} />{' '}
|
||||||
|
<span>Total Harga</span>
|
||||||
|
</div>
|
||||||
|
<div className='text-end text-gray-500'>
|
||||||
|
{formatCurrency(budget.price * budget.qty)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</Card>
|
||||||
|
))}
|
||||||
|
|
||||||
|
{/* Card Kandangs */}
|
||||||
|
<Card
|
||||||
|
variant='bordered'
|
||||||
|
className={{
|
||||||
|
wrapper: 'w-full rounded-lg',
|
||||||
|
body: 'p-3',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<RadioGroup
|
||||||
|
name='gender'
|
||||||
|
className={{
|
||||||
|
radioWrapper: 'grid grid-cols-1 gap-6',
|
||||||
|
}}
|
||||||
|
onChange={(e) => setSelectedKandangId(e.target.value)}
|
||||||
|
value={selectedKandangId?.toString()}
|
||||||
|
size='md'
|
||||||
|
color='neutral'
|
||||||
|
disabled={projectFlock?.approval?.step_number == 1}
|
||||||
|
>
|
||||||
|
{projectFlock.kandangs?.map((kandang) => (
|
||||||
|
<div
|
||||||
|
key={kandang.id}
|
||||||
|
className={`grid grid-cols-2 gap-6 cursor-pointer hover:text-gray-800`}
|
||||||
|
onClick={() =>
|
||||||
|
projectFlock?.approval?.step_number > 1 &&
|
||||||
|
setSelectedKandangId(kandang?.id?.toString())
|
||||||
|
}
|
||||||
>
|
>
|
||||||
<Button
|
<RadioGroupItem
|
||||||
className='w-full px-2 py-1 text-sm'
|
value={kandang?.id?.toString()}
|
||||||
variant='outline'
|
label={kandang?.name}
|
||||||
color='success'
|
disabled={projectFlock?.approval?.step_number == 1}
|
||||||
disabled={
|
/>
|
||||||
!selectedKandangId ||
|
<div className='text-end'>
|
||||||
projectFlock?.approval?.step_number == 1
|
<Badge
|
||||||
}
|
className={{
|
||||||
>
|
badge: 'rounded-lg',
|
||||||
Chickin <Icon icon='mdi:checkbox-marked-outline' />
|
}}
|
||||||
</Button>
|
>
|
||||||
</Link>
|
Kapasitas {kandang?.capacity} Ekor
|
||||||
</RequirePermission>
|
</Badge>
|
||||||
<RequirePermission permissions='lti.production.project_flock_kandangs.closing.detail'>
|
</div>
|
||||||
<Link
|
</div>
|
||||||
href={`/production/project-flock/closing?projectFlockId=${projectFlock.id}&projectFlockKandangId=${selectedKandang?.project_flock_kandang_id}`}
|
))}
|
||||||
className='m-0 p-0'
|
</RadioGroup>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
<ApprovalStepsV2
|
||||||
|
approvals={projectFlockKandangApproval}
|
||||||
|
steps={APPROVAL_WORKFLOWS.PROJECT_FLOCK_KANDANGS}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<div className='grid grid-cols-4 gap-3'>
|
||||||
|
<RequirePermission permissions='lti.production.chickins.detail'>
|
||||||
|
<Link
|
||||||
|
href={`/production/project-flock/chickin/add/kandang?projectFlockKandangId=${selectedKandang?.project_flock_kandang_id}&projectFlockId=${projectFlock.id}`}
|
||||||
|
className='m-0 p-0'
|
||||||
|
>
|
||||||
|
<Button
|
||||||
|
className='w-full px-2 py-1 text-sm'
|
||||||
|
variant='outline'
|
||||||
|
color='success'
|
||||||
|
disabled={
|
||||||
|
!selectedKandangId ||
|
||||||
|
projectFlock?.approval?.step_number == 1
|
||||||
|
}
|
||||||
>
|
>
|
||||||
<Button
|
Chickin <Icon icon='mdi:checkbox-marked-outline' />
|
||||||
className='w-full px-2 py-1 text-sm'
|
</Button>
|
||||||
variant='outline'
|
</Link>
|
||||||
color='error'
|
</RequirePermission>
|
||||||
disabled={
|
<RequirePermission permissions='lti.production.project_flock_kandangs.closing.detail'>
|
||||||
!selectedKandangId ||
|
<Link
|
||||||
projectFlock?.approval?.step_number == 1
|
href={`/production/project-flock/closing?projectFlockId=${projectFlock.id}&projectFlockKandangId=${selectedKandang?.project_flock_kandang_id}`}
|
||||||
}
|
className='m-0 p-0'
|
||||||
>
|
>
|
||||||
Close <Icon icon='mdi:checkbox-marked-circle-outline' />
|
<Button
|
||||||
</Button>
|
className='w-full px-2 py-1 text-sm'
|
||||||
</Link>
|
variant='outline'
|
||||||
</RequirePermission>
|
color='error'
|
||||||
</div>
|
disabled={
|
||||||
|
!selectedKandangId ||
|
||||||
|
projectFlock?.approval?.step_number == 1
|
||||||
|
}
|
||||||
|
>
|
||||||
|
Close <Icon icon='mdi:checkbox-marked-circle-outline' />
|
||||||
|
</Button>
|
||||||
|
</Link>
|
||||||
|
</RequirePermission>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -2,6 +2,7 @@
|
|||||||
|
|
||||||
import Badge from '@/components/Badge';
|
import Badge from '@/components/Badge';
|
||||||
import Card from '@/components/Card';
|
import Card from '@/components/Card';
|
||||||
|
import StatusBadge from '@/components/helper/StatusBadge';
|
||||||
import CheckboxInput from '@/components/input/CheckboxInput';
|
import CheckboxInput from '@/components/input/CheckboxInput';
|
||||||
import PillBadge from '@/components/PillBadge';
|
import PillBadge from '@/components/PillBadge';
|
||||||
import Table from '@/components/Table';
|
import Table from '@/components/Table';
|
||||||
@@ -32,6 +33,14 @@ const ProjectFlockKandangTable = ({
|
|||||||
initialValues?: ProjectFlock;
|
initialValues?: ProjectFlock;
|
||||||
formType: 'add' | 'edit' | 'detail';
|
formType: 'add' | 'edit' | 'detail';
|
||||||
}) => {
|
}) => {
|
||||||
|
const availableKandang = listKandang.filter(
|
||||||
|
(kandang) => kandang.status == 'NON_ACTIVE'
|
||||||
|
).length;
|
||||||
|
|
||||||
|
const unavailableKandang = listKandang.filter(
|
||||||
|
(kandang) => kandang.status != 'NON_ACTIVE'
|
||||||
|
).length;
|
||||||
|
|
||||||
// Fungsi untuk menangani perubahan checkbox
|
// Fungsi untuk menangani perubahan checkbox
|
||||||
const handleCheckboxChange = (kandang: Kandang, isChecked: boolean) => {
|
const handleCheckboxChange = (kandang: Kandang, isChecked: boolean) => {
|
||||||
// Hanya izinkan perubahan jika tidak dalam mode 'detail'
|
// Hanya izinkan perubahan jika tidak dalam mode 'detail'
|
||||||
@@ -57,48 +66,30 @@ const ProjectFlockKandangTable = ({
|
|||||||
{listKandang.length > 0 ? (
|
{listKandang.length > 0 ? (
|
||||||
<>
|
<>
|
||||||
{/* ... Bagian Badge Status ... */}
|
{/* ... Bagian Badge Status ... */}
|
||||||
<div className='flex flex-row mb-4'>
|
<div className='w-fit flex flex-row items-stretch gap-3 mb-3'>
|
||||||
<Badge
|
<StatusBadge
|
||||||
variant='soft'
|
color='info'
|
||||||
color='primary'
|
text={`Tersedia (${availableKandang})`}
|
||||||
className={{
|
className={{ badge: 'text-nowrap' }}
|
||||||
badge: 'rounded-lg px-2',
|
/>
|
||||||
}}
|
|
||||||
>
|
<div className='w-px border-none bg-base-content/10' />
|
||||||
<Icon icon='mdi:circle' width={12} height={12} />
|
|
||||||
Tersedia (
|
<StatusBadge
|
||||||
{
|
|
||||||
listKandang.filter((kandang) => kandang.status == 'NON_ACTIVE')
|
|
||||||
.length
|
|
||||||
}
|
|
||||||
)
|
|
||||||
</Badge>
|
|
||||||
<div className='divider divider-horizontal mx-1'></div>
|
|
||||||
<Badge
|
|
||||||
variant='soft'
|
|
||||||
color='neutral'
|
color='neutral'
|
||||||
className={{
|
text={`Tidak Tersedia (${unavailableKandang})`}
|
||||||
badge: 'rounded-lg px-2',
|
className={{ badge: 'text-nowrap' }}
|
||||||
}}
|
/>
|
||||||
>
|
|
||||||
<Icon icon='mdi:circle' width={12} height={12} />
|
|
||||||
Tidak Tersedia (
|
|
||||||
{
|
|
||||||
listKandang.filter((kandang) => kandang.status != 'NON_ACTIVE')
|
|
||||||
.length
|
|
||||||
}
|
|
||||||
)
|
|
||||||
</Badge>
|
|
||||||
</div>
|
</div>
|
||||||
{/* --- */}
|
{/* --- */}
|
||||||
<Card
|
<Card
|
||||||
variant='bordered'
|
variant='bordered'
|
||||||
className={{
|
className={{
|
||||||
wrapper: 'w-full rounded-lg',
|
wrapper: 'w-full rounded-xl border border-base-content/5',
|
||||||
body: 'p-4',
|
body: 'p-0',
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<div className='flex flex-col gap-4 w-full'>
|
<div className='flex flex-col w-full'>
|
||||||
{listKandang.map((kandang, index) => {
|
{listKandang.map((kandang, index) => {
|
||||||
const kandangIdString =
|
const kandangIdString =
|
||||||
kandang.id?.toString() ?? `temp-${index}`;
|
kandang.id?.toString() ?? `temp-${index}`;
|
||||||
@@ -112,28 +103,36 @@ const ProjectFlockKandangTable = ({
|
|||||||
formType == 'detail' || kandang.status != 'NON_ACTIVE';
|
formType == 'detail' || kandang.status != 'NON_ACTIVE';
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div key={index} className='flex flex-row justify-between'>
|
<div
|
||||||
|
key={index}
|
||||||
|
className='w-full p-3 flex flex-row items-center justify-between'
|
||||||
|
>
|
||||||
<CheckboxInput
|
<CheckboxInput
|
||||||
name={`kandang-${kandang.id}`} // Nama unik untuk setiap checkbox
|
name={`kandang-${kandang.id}`} // Nama unik untuk setiap checkbox
|
||||||
label={kandang.name}
|
label={kandang.name}
|
||||||
checked={isSelected}
|
checked={isSelected}
|
||||||
disabled={isDisabled}
|
disabled={isDisabled}
|
||||||
|
size='md'
|
||||||
onChange={(e) =>
|
onChange={(e) =>
|
||||||
handleCheckboxChange(kandang, e.currentTarget.checked)
|
handleCheckboxChange(kandang, e.currentTarget.checked)
|
||||||
}
|
}
|
||||||
/>
|
classNames={{
|
||||||
<Badge
|
inputWrapper: cn('gap-3 text-base-content/50', {
|
||||||
variant='soft'
|
'text-base-content/20': isDisabled,
|
||||||
color={
|
}),
|
||||||
kandang.status == 'NON_ACTIVE' ? 'primary' : 'neutral'
|
label: 'cursor-pointer',
|
||||||
}
|
checkbox: cn({
|
||||||
className={{
|
'bg-base-200 border border-base-content/10 opacity-100':
|
||||||
badge: 'rounded-lg px-2',
|
isDisabled,
|
||||||
|
}),
|
||||||
}}
|
}}
|
||||||
>
|
/>
|
||||||
<Icon icon='mdi:circle' width={12} height={12} />
|
|
||||||
{kandang.status != 'NON_ACTIVE' && 'Tidak'} Tersedia
|
<StatusBadge
|
||||||
</Badge>
|
color={!isDisabled ? 'info' : 'neutral'}
|
||||||
|
text={!isDisabled ? 'Tersedia' : 'Tidak Tersedia'}
|
||||||
|
className={{ badge: 'w-fit' }}
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
})}
|
})}
|
||||||
|
|||||||
@@ -7,14 +7,12 @@ import React, {
|
|||||||
useEffect,
|
useEffect,
|
||||||
useRef,
|
useRef,
|
||||||
} from 'react';
|
} from 'react';
|
||||||
import { RefObject } from 'react';
|
|
||||||
import useSWR from 'swr';
|
import useSWR from 'swr';
|
||||||
import { Icon } from '@iconify/react';
|
import { Icon } from '@iconify/react';
|
||||||
import { SortingState, CellContext } from '@tanstack/react-table';
|
import { SortingState, CellContext } from '@tanstack/react-table';
|
||||||
import { cn, formatDate, formatNumber } from '@/lib/helper';
|
import { cn, formatDate, formatNumber } from '@/lib/helper';
|
||||||
import RequirePermission from '@/components/helper/RequirePermission';
|
import RequirePermission from '@/components/helper/RequirePermission';
|
||||||
import { useModal } from '@/components/Modal';
|
import { useModal } from '@/components/Modal';
|
||||||
import Modal from '@/components/Modal';
|
|
||||||
import Button from '@/components/Button';
|
import Button from '@/components/Button';
|
||||||
import ConfirmationModal from '@/components/modal/ConfirmationModal';
|
import ConfirmationModal from '@/components/modal/ConfirmationModal';
|
||||||
import ConfirmationModalWithNotes from '@/components/modal/ConfirmationModalWithNotes';
|
import ConfirmationModalWithNotes from '@/components/modal/ConfirmationModalWithNotes';
|
||||||
@@ -28,14 +26,51 @@ import RowCollapseOptions from '@/components/table/RowCollapseOptions';
|
|||||||
import RowOptionsMenuWrapper from '@/components/table/RowOptionsMenuWrapper';
|
import RowOptionsMenuWrapper from '@/components/table/RowOptionsMenuWrapper';
|
||||||
import { type Recording } from '@/types/api/production/recording';
|
import { type Recording } from '@/types/api/production/recording';
|
||||||
import { RecordingApi } from '@/services/api/production';
|
import { RecordingApi } from '@/services/api/production';
|
||||||
import { ApprovalApi } from '@/services/api/approval';
|
|
||||||
import { isResponseSuccess } from '@/lib/api-helper';
|
import { isResponseSuccess } from '@/lib/api-helper';
|
||||||
import { useTableFilter } from '@/services/hooks/useTableFilter';
|
import { useTableFilter } from '@/services/hooks/useTableFilter';
|
||||||
import toast from 'react-hot-toast';
|
import toast from 'react-hot-toast';
|
||||||
import Badge from '@/components/Badge';
|
import Badge from '@/components/Badge';
|
||||||
|
import StatusBadge from '@/components/helper/StatusBadge';
|
||||||
import CheckboxInput from '@/components/input/CheckboxInput';
|
import CheckboxInput from '@/components/input/CheckboxInput';
|
||||||
import { useUiStore } from '@/stores/ui/ui.store';
|
import { useUiStore } from '@/stores/ui/ui.store';
|
||||||
import { BaseApproval, BaseApiResponse } from '@/types/api/api-general';
|
import { Color } from '@/types/theme';
|
||||||
|
|
||||||
|
// ===== STATUS BADGE UTILITIES =====
|
||||||
|
const statusTextMap: Record<string, string> = {
|
||||||
|
APPROVED: 'Disetujui',
|
||||||
|
Disetujui: 'Disetujui',
|
||||||
|
REJECTED: 'Ditolak',
|
||||||
|
Ditolak: 'Ditolak',
|
||||||
|
CREATED: 'Dibuat',
|
||||||
|
UPDATED: 'Diperbarui',
|
||||||
|
};
|
||||||
|
|
||||||
|
const getStatusText = (status: string): string => {
|
||||||
|
return statusTextMap[status] || status;
|
||||||
|
};
|
||||||
|
|
||||||
|
const statusBadgeColorMap: Record<string, Color> = {
|
||||||
|
APPROVED: 'success',
|
||||||
|
Disetujui: 'success',
|
||||||
|
approved: 'success',
|
||||||
|
disetujui: 'success',
|
||||||
|
REJECTED: 'error',
|
||||||
|
Ditolak: 'error',
|
||||||
|
rejected: 'error',
|
||||||
|
ditolak: 'error',
|
||||||
|
CREATED: 'neutral',
|
||||||
|
Dibuat: 'neutral',
|
||||||
|
created: 'neutral',
|
||||||
|
dibuat: 'neutral',
|
||||||
|
UPDATED: 'warning',
|
||||||
|
Diperbarui: 'warning',
|
||||||
|
updated: 'warning',
|
||||||
|
diperbarui: 'warning',
|
||||||
|
};
|
||||||
|
|
||||||
|
const getStatusBadgeColor = (status: string): Color => {
|
||||||
|
return statusBadgeColorMap[status] || 'neutral';
|
||||||
|
};
|
||||||
|
|
||||||
const RowOptionsMenu = ({
|
const RowOptionsMenu = ({
|
||||||
type = 'dropdown',
|
type = 'dropdown',
|
||||||
@@ -135,221 +170,6 @@ const RowOptionsMenu = ({
|
|||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
const ApprovalHistoryModal = ({
|
|
||||||
ref,
|
|
||||||
currentApproval,
|
|
||||||
module_name = 'RECORDINGS',
|
|
||||||
module_id,
|
|
||||||
}: {
|
|
||||||
ref: RefObject<HTMLDialogElement | null>;
|
|
||||||
currentApproval?: BaseApproval;
|
|
||||||
module_name?: string;
|
|
||||||
module_id?: number | undefined;
|
|
||||||
}) => {
|
|
||||||
const [isModalOpen, setIsModalOpen] = useState(false);
|
|
||||||
|
|
||||||
const approvalHistoryUrl = useMemo(() => {
|
|
||||||
if (!isModalOpen) return null;
|
|
||||||
const params = new URLSearchParams({
|
|
||||||
module_name: module_name,
|
|
||||||
group_step_number: 'true',
|
|
||||||
});
|
|
||||||
|
|
||||||
if (module_id) {
|
|
||||||
params.append('module_id', module_id.toString());
|
|
||||||
}
|
|
||||||
|
|
||||||
return `${ApprovalApi.basePath}?${params.toString()}`;
|
|
||||||
}, [module_name, module_id, isModalOpen]);
|
|
||||||
|
|
||||||
type GroupedApprovalResponse = {
|
|
||||||
step_number: number;
|
|
||||||
step_name: string;
|
|
||||||
approvals: BaseApproval[];
|
|
||||||
};
|
|
||||||
|
|
||||||
const fetchGroupedApprovals = async (
|
|
||||||
url: string
|
|
||||||
): Promise<BaseApiResponse<GroupedApprovalResponse[]>> => {
|
|
||||||
return (await ApprovalApi.getAllFetcher(url)) as BaseApiResponse<
|
|
||||||
GroupedApprovalResponse[]
|
|
||||||
>;
|
|
||||||
};
|
|
||||||
|
|
||||||
const { data: approvalHistoryData, isLoading } = useSWR<
|
|
||||||
BaseApiResponse<GroupedApprovalResponse[]>
|
|
||||||
>(approvalHistoryUrl, fetchGroupedApprovals);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
const checkModalOpen = () => {
|
|
||||||
const isOpen = ref.current?.open || false;
|
|
||||||
setIsModalOpen(isOpen);
|
|
||||||
};
|
|
||||||
|
|
||||||
checkModalOpen();
|
|
||||||
|
|
||||||
const observer = new MutationObserver(checkModalOpen);
|
|
||||||
if (ref.current) {
|
|
||||||
observer.observe(ref.current, {
|
|
||||||
attributes: true,
|
|
||||||
attributeFilter: ['open'],
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
return () => observer.disconnect();
|
|
||||||
}, [ref]);
|
|
||||||
|
|
||||||
const approvalHistory = useMemo(() => {
|
|
||||||
if (!approvalHistoryData || approvalHistoryData.status !== 'success')
|
|
||||||
return [];
|
|
||||||
|
|
||||||
const groupedData = approvalHistoryData.data || [];
|
|
||||||
const flattenedApprovals: BaseApproval[] = [];
|
|
||||||
|
|
||||||
groupedData.forEach((group) => {
|
|
||||||
group.approvals.forEach((approval) => {
|
|
||||||
flattenedApprovals.push(approval);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
return flattenedApprovals;
|
|
||||||
}, [approvalHistoryData]);
|
|
||||||
|
|
||||||
const closeModalHandler = () => {
|
|
||||||
ref.current?.close();
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Modal ref={ref} className={{ modalBox: 'max-w-2xl' }}>
|
|
||||||
<div className='w-full flex flex-col gap-6'>
|
|
||||||
{/* Header */}
|
|
||||||
<div className='flex items-center justify-between'>
|
|
||||||
<h2 className='text-xl font-bold'>Riwayat Approval</h2>
|
|
||||||
<Button
|
|
||||||
onClick={closeModalHandler}
|
|
||||||
variant='ghost'
|
|
||||||
className='btn-circle btn-sm p-0'
|
|
||||||
>
|
|
||||||
<Icon icon='mdi:close' width={20} height={20} />
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{isLoading ? (
|
|
||||||
<div className='flex justify-center py-8'>
|
|
||||||
<span className='loading loading-spinner loading-lg'></span>
|
|
||||||
</div>
|
|
||||||
) : (
|
|
||||||
<>
|
|
||||||
{/* Current Status */}
|
|
||||||
{currentApproval && (
|
|
||||||
<div className='bg-base-200 rounded-lg p-4'>
|
|
||||||
<h3 className='font-semibold mb-2'>Status Saat Ini</h3>
|
|
||||||
<div className='flex items-center gap-3'>
|
|
||||||
<Badge
|
|
||||||
variant='soft'
|
|
||||||
color={
|
|
||||||
currentApproval.action === 'APPROVED'
|
|
||||||
? 'success'
|
|
||||||
: currentApproval.action === 'REJECTED'
|
|
||||||
? 'error'
|
|
||||||
: currentApproval.action === 'UPDATED'
|
|
||||||
? 'warning'
|
|
||||||
: 'info'
|
|
||||||
}
|
|
||||||
>
|
|
||||||
{currentApproval.step_name}
|
|
||||||
</Badge>
|
|
||||||
<span className='text-sm text-gray-600'>
|
|
||||||
{currentApproval.action === 'APPROVED' && 'Disetujui'}
|
|
||||||
{currentApproval.action === 'REJECTED' && 'Ditolak'}
|
|
||||||
{currentApproval.action === 'CREATED' && 'Dibuat'}
|
|
||||||
{currentApproval.action === 'UPDATED' && 'Diperbarui'}
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
{currentApproval.notes && (
|
|
||||||
<p className='mt-2 text-sm text-gray-600'>
|
|
||||||
<span className='font-medium'>Catatan:</span>{' '}
|
|
||||||
{currentApproval.notes}
|
|
||||||
</p>
|
|
||||||
)}
|
|
||||||
<p className='mt-1 text-xs text-gray-500'>
|
|
||||||
Oleh: {currentApproval.action_by.name} •{' '}
|
|
||||||
{formatDate(currentApproval.action_at, 'DD MMMM YYYY HH:mm')}
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* Full History */}
|
|
||||||
{approvalHistory.length > 0 && (
|
|
||||||
<div className='space-y-4'>
|
|
||||||
<h3 className='font-semibold'>Riwayat Lengkap</h3>
|
|
||||||
<div className='overflow-x-auto'>
|
|
||||||
<table className='table table-sm'>
|
|
||||||
<thead>
|
|
||||||
<tr>
|
|
||||||
<th>Tahap</th>
|
|
||||||
<th>Aksi</th>
|
|
||||||
<th>Catatan</th>
|
|
||||||
<th>Oleh</th>
|
|
||||||
<th>Waktu</th>
|
|
||||||
</tr>
|
|
||||||
</thead>
|
|
||||||
<tbody>
|
|
||||||
{approvalHistory
|
|
||||||
.sort(
|
|
||||||
(a: BaseApproval, b: BaseApproval) =>
|
|
||||||
new Date(b.action_at).getTime() -
|
|
||||||
new Date(a.action_at).getTime()
|
|
||||||
)
|
|
||||||
.map((approval: BaseApproval, index: number) => (
|
|
||||||
<tr key={index}>
|
|
||||||
<td>{approval.step_name}</td>
|
|
||||||
<td>
|
|
||||||
<Badge
|
|
||||||
variant='soft'
|
|
||||||
color={
|
|
||||||
approval.action === 'APPROVED'
|
|
||||||
? 'success'
|
|
||||||
: approval.action === 'REJECTED'
|
|
||||||
? 'error'
|
|
||||||
: approval.action === 'UPDATED'
|
|
||||||
? 'warning'
|
|
||||||
: 'info'
|
|
||||||
}
|
|
||||||
size='sm'
|
|
||||||
>
|
|
||||||
{approval.action === 'APPROVED' && 'Disetujui'}
|
|
||||||
{approval.action === 'REJECTED' && 'Ditolak'}
|
|
||||||
{approval.action === 'CREATED' && 'Dibuat'}
|
|
||||||
{approval.action === 'UPDATED' && 'Diperbarui'}
|
|
||||||
</Badge>
|
|
||||||
</td>
|
|
||||||
<td className='max-w-xs'>
|
|
||||||
<div className='truncate'>
|
|
||||||
{approval.notes || '-'}
|
|
||||||
</div>
|
|
||||||
</td>
|
|
||||||
<td>{approval.action_by.name}</td>
|
|
||||||
<td className='text-xs'>
|
|
||||||
{formatDate(
|
|
||||||
approval.action_at,
|
|
||||||
'DD MMMM YYYY HH:mm'
|
|
||||||
)}
|
|
||||||
</td>
|
|
||||||
</tr>
|
|
||||||
))}
|
|
||||||
</tbody>
|
|
||||||
</table>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</Modal>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
const RecordingTable = () => {
|
const RecordingTable = () => {
|
||||||
const { searchValue, setSearchValue, resetSearchValue } = useUiStore();
|
const { searchValue, setSearchValue, resetSearchValue } = useUiStore();
|
||||||
const previousPathRef = useRef<string | null>(null);
|
const previousPathRef = useRef<string | null>(null);
|
||||||
@@ -395,7 +215,6 @@ const RecordingTable = () => {
|
|||||||
const singleDeleteModal = useModal();
|
const singleDeleteModal = useModal();
|
||||||
const approveModal = useModal();
|
const approveModal = useModal();
|
||||||
const rejectModal = useModal();
|
const rejectModal = useModal();
|
||||||
const approvalHistoryModal = useModal();
|
|
||||||
|
|
||||||
const {
|
const {
|
||||||
data: recordings,
|
data: recordings,
|
||||||
@@ -561,12 +380,11 @@ const RecordingTable = () => {
|
|||||||
<RequirePermission permissions='lti.production.recording.create'>
|
<RequirePermission permissions='lti.production.recording.create'>
|
||||||
<Button
|
<Button
|
||||||
href='/production/recording/add'
|
href='/production/recording/add'
|
||||||
variant='outline'
|
|
||||||
color='primary'
|
color='primary'
|
||||||
className='w-full sm:w-fit'
|
className='px-3 py-2.5 w-fit text-sm text-base-100 rounded-lg shadow-sm'
|
||||||
>
|
>
|
||||||
<Icon icon='ic:round-plus' width={24} height={24} />
|
<Icon icon='heroicons:plus' width={20} height={20} />
|
||||||
Tambah
|
Add Recording
|
||||||
</Button>
|
</Button>
|
||||||
</RequirePermission>
|
</RequirePermission>
|
||||||
|
|
||||||
@@ -1032,32 +850,19 @@ const RecordingTable = () => {
|
|||||||
const approval = props.row.original.approval;
|
const approval = props.row.original.approval;
|
||||||
if (!approval) return '-';
|
if (!approval) return '-';
|
||||||
|
|
||||||
const statusColor =
|
const status = approval.action;
|
||||||
approval.action === 'APPROVED'
|
const statusColor = getStatusBadgeColor(status);
|
||||||
? 'success'
|
|
||||||
: approval.action === 'REJECTED'
|
|
||||||
? 'error'
|
|
||||||
: approval.action === 'UPDATED'
|
|
||||||
? 'warning'
|
|
||||||
: 'info';
|
|
||||||
|
|
||||||
const openApprovalHistory = () => {
|
const statusText = approval.step_name || getStatusText(status);
|
||||||
setSelectedRecording(props.row.original);
|
|
||||||
approvalHistoryModal.openModal();
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Badge
|
<StatusBadge
|
||||||
variant='soft'
|
|
||||||
color={statusColor}
|
color={statusColor}
|
||||||
|
text={statusText}
|
||||||
className={{
|
className={{
|
||||||
badge:
|
badge: 'whitespace-nowrap',
|
||||||
'cursor-pointer hover:opacity-80 transition-opacity whitespace-nowrap',
|
|
||||||
}}
|
}}
|
||||||
onClick={openApprovalHistory}
|
/>
|
||||||
>
|
|
||||||
{approval.step_name || approval.action}
|
|
||||||
</Badge>
|
|
||||||
);
|
);
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
@@ -1208,7 +1013,10 @@ const RecordingTable = () => {
|
|||||||
text={`Apakah anda yakin ingin approve data recording ini (${eligibleRowIds.length} data dari ${selectedRowIds.length} yang dipilih)?`}
|
text={`Apakah anda yakin ingin approve data recording ini (${eligibleRowIds.length} data dari ${selectedRowIds.length} yang dipilih)?`}
|
||||||
secondaryButton={{
|
secondaryButton={{
|
||||||
text: 'Tidak',
|
text: 'Tidak',
|
||||||
onClick: () => setApprovalNotes(''),
|
onClick: () => {
|
||||||
|
setApprovalNotes('');
|
||||||
|
approveModal.closeModal();
|
||||||
|
},
|
||||||
}}
|
}}
|
||||||
primaryButton={{
|
primaryButton={{
|
||||||
text: 'Ya',
|
text: 'Ya',
|
||||||
@@ -1226,7 +1034,10 @@ const RecordingTable = () => {
|
|||||||
text={`Apakah anda yakin ingin reject data recording ini (${eligibleRowIds.length} data dari ${selectedRowIds.length} yang dipilih)?`}
|
text={`Apakah anda yakin ingin reject data recording ini (${eligibleRowIds.length} data dari ${selectedRowIds.length} yang dipilih)?`}
|
||||||
secondaryButton={{
|
secondaryButton={{
|
||||||
text: 'Tidak',
|
text: 'Tidak',
|
||||||
onClick: () => setApprovalNotes(''),
|
onClick: () => {
|
||||||
|
setApprovalNotes('');
|
||||||
|
rejectModal.closeModal();
|
||||||
|
},
|
||||||
}}
|
}}
|
||||||
primaryButton={{
|
primaryButton={{
|
||||||
text: 'Ya',
|
text: 'Ya',
|
||||||
@@ -1237,13 +1048,6 @@ const RecordingTable = () => {
|
|||||||
placeholder='(Opsional) Tambahkan catatan untuk reject ini...'
|
placeholder='(Opsional) Tambahkan catatan untuk reject ini...'
|
||||||
rows={3}
|
rows={3}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<ApprovalHistoryModal
|
|
||||||
ref={approvalHistoryModal.ref}
|
|
||||||
currentApproval={selectedRecording?.approval}
|
|
||||||
module_name={'RECORDINGS'}
|
|
||||||
module_id={selectedRecording?.id}
|
|
||||||
/>
|
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -99,6 +99,7 @@ const TransferToLayingFormModal = () => {
|
|||||||
{
|
{
|
||||||
category: 'GROWING',
|
category: 'GROWING',
|
||||||
transfer_context: 'transfer_to_laying',
|
transfer_context: 'transfer_to_laying',
|
||||||
|
is_approved: 'true',
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -116,6 +117,7 @@ const TransferToLayingFormModal = () => {
|
|||||||
'search',
|
'search',
|
||||||
{
|
{
|
||||||
category: 'LAYING',
|
category: 'LAYING',
|
||||||
|
is_approved: 'true',
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|||||||
@@ -1058,7 +1058,7 @@ const UniformityTable = () => {
|
|||||||
iconPosition='left'
|
iconPosition='left'
|
||||||
text='Data Berhasil Ditambahkan'
|
text='Data Berhasil Ditambahkan'
|
||||||
subtitleText='Data uniformity telah berhasil disimpan.'
|
subtitleText='Data uniformity telah berhasil disimpan.'
|
||||||
closeOnBackdrop={false}
|
closeOnBackdrop={true}
|
||||||
primaryButton={{
|
primaryButton={{
|
||||||
text: 'Ok',
|
text: 'Ok',
|
||||||
color: 'primary',
|
color: 'primary',
|
||||||
@@ -1089,6 +1089,7 @@ const UniformityTable = () => {
|
|||||||
ref={singleDeleteModal.ref}
|
ref={singleDeleteModal.ref}
|
||||||
type='error'
|
type='error'
|
||||||
iconPosition='left'
|
iconPosition='left'
|
||||||
|
closeOnBackdrop={true}
|
||||||
text={`Delete This Data?`}
|
text={`Delete This Data?`}
|
||||||
subtitleText='Are you sure you want to delete this data?'
|
subtitleText='Are you sure you want to delete this data?'
|
||||||
secondaryButton={{
|
secondaryButton={{
|
||||||
@@ -1113,6 +1114,7 @@ const UniformityTable = () => {
|
|||||||
ref={singleApproveModal.ref}
|
ref={singleApproveModal.ref}
|
||||||
type='success'
|
type='success'
|
||||||
iconPosition='left'
|
iconPosition='left'
|
||||||
|
closeOnBackdrop={true}
|
||||||
text='Approve This Submission?'
|
text='Approve This Submission?'
|
||||||
subtitleText='Are you sure you want to approve this submission?'
|
subtitleText='Are you sure you want to approve this submission?'
|
||||||
secondaryButton={{
|
secondaryButton={{
|
||||||
@@ -1129,15 +1131,12 @@ const UniformityTable = () => {
|
|||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<div className='flex flex-col gap-4'>
|
<div className='flex flex-col gap-4'>
|
||||||
{selectedRowIds.length === 1 ? (
|
{selectedUniformities.map((uniformity) => (
|
||||||
<UniformityConfirmationPreview
|
<UniformityConfirmationPreview
|
||||||
uniformity={selectedUniformities[0]}
|
key={uniformity.id}
|
||||||
|
uniformity={uniformity}
|
||||||
/>
|
/>
|
||||||
) : (
|
))}
|
||||||
<div className='text-center text-gray-500'>
|
|
||||||
{selectedRowIds.length} data dipilih
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
</div>
|
||||||
</ConfirmationModal>
|
</ConfirmationModal>
|
||||||
|
|
||||||
@@ -1145,8 +1144,13 @@ const UniformityTable = () => {
|
|||||||
ref={bulkApproveModal.ref}
|
ref={bulkApproveModal.ref}
|
||||||
type='success'
|
type='success'
|
||||||
iconPosition='left'
|
iconPosition='left'
|
||||||
|
closeOnBackdrop={true}
|
||||||
text={`Approve This Submission?`}
|
text={`Approve This Submission?`}
|
||||||
subtitleText={`Are you sure you want to approve this submission? (${selectedRowIds.length} data)`}
|
subtitleText={
|
||||||
|
selectedRowIds.length === 1
|
||||||
|
? 'Are you sure you want to approve this submission?'
|
||||||
|
: `Are you sure you want to approve these submissions? (${selectedRowIds.length} data)`
|
||||||
|
}
|
||||||
secondaryButton={{
|
secondaryButton={{
|
||||||
text: 'Cancel',
|
text: 'Cancel',
|
||||||
}}
|
}}
|
||||||
@@ -1161,7 +1165,12 @@ const UniformityTable = () => {
|
|||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<div className='flex flex-col gap-4'>
|
<div className='flex flex-col gap-4'>
|
||||||
<UniformityConfirmationPreview uniformity={selectedUniformity} />
|
{selectedUniformities.map((uniformity) => (
|
||||||
|
<UniformityConfirmationPreview
|
||||||
|
key={uniformity.id}
|
||||||
|
uniformity={uniformity}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
</div>
|
</div>
|
||||||
</ConfirmationModal>
|
</ConfirmationModal>
|
||||||
|
|
||||||
@@ -1169,6 +1178,7 @@ const UniformityTable = () => {
|
|||||||
ref={singleRejectModal.ref}
|
ref={singleRejectModal.ref}
|
||||||
type='error'
|
type='error'
|
||||||
iconPosition='left'
|
iconPosition='left'
|
||||||
|
closeOnBackdrop={true}
|
||||||
text='Reject This Submission?'
|
text='Reject This Submission?'
|
||||||
subtitleText='Are you sure you want to reject this submission?'
|
subtitleText='Are you sure you want to reject this submission?'
|
||||||
secondaryButton={{
|
secondaryButton={{
|
||||||
@@ -1185,15 +1195,12 @@ const UniformityTable = () => {
|
|||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<div className='flex flex-col gap-4'>
|
<div className='flex flex-col gap-4'>
|
||||||
{selectedRowIds.length === 1 ? (
|
{selectedUniformities.map((uniformity) => (
|
||||||
<UniformityConfirmationPreview
|
<UniformityConfirmationPreview
|
||||||
uniformity={selectedUniformities[0]}
|
key={uniformity.id}
|
||||||
|
uniformity={uniformity}
|
||||||
/>
|
/>
|
||||||
) : (
|
))}
|
||||||
<div className='text-center text-gray-500'>
|
|
||||||
{selectedRowIds.length} data dipilih
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
</div>
|
||||||
</ConfirmationModal>
|
</ConfirmationModal>
|
||||||
|
|
||||||
@@ -1201,8 +1208,13 @@ const UniformityTable = () => {
|
|||||||
ref={bulkRejectModal.ref}
|
ref={bulkRejectModal.ref}
|
||||||
type='error'
|
type='error'
|
||||||
iconPosition='left'
|
iconPosition='left'
|
||||||
|
closeOnBackdrop={true}
|
||||||
text={`Reject This Submission?`}
|
text={`Reject This Submission?`}
|
||||||
subtitleText={`Are you sure you want to reject this submission? (${selectedRowIds.length} data)`}
|
subtitleText={
|
||||||
|
selectedRowIds.length === 1
|
||||||
|
? 'Are you sure you want to reject this submission?'
|
||||||
|
: `Are you sure you want to reject these submissions? (${selectedRowIds.length} data)`
|
||||||
|
}
|
||||||
secondaryButton={{
|
secondaryButton={{
|
||||||
text: 'Cancel',
|
text: 'Cancel',
|
||||||
}}
|
}}
|
||||||
@@ -1217,15 +1229,12 @@ const UniformityTable = () => {
|
|||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<div className='flex flex-col gap-4'>
|
<div className='flex flex-col gap-4'>
|
||||||
{selectedRowIds.length === 1 ? (
|
{selectedUniformities.map((uniformity) => (
|
||||||
<UniformityConfirmationPreview
|
<UniformityConfirmationPreview
|
||||||
uniformity={selectedUniformities[0]}
|
key={uniformity.id}
|
||||||
|
uniformity={uniformity}
|
||||||
/>
|
/>
|
||||||
) : (
|
))}
|
||||||
<div className='text-center text-gray-500'>
|
|
||||||
{selectedRowIds.length} data dipilih
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
</div>
|
||||||
</ConfirmationModal>
|
</ConfirmationModal>
|
||||||
|
|
||||||
|
|||||||
@@ -16,7 +16,8 @@ import RowDropdownOptions from '@/components/table/RowDropdownOptions';
|
|||||||
import RowCollapseOptions from '@/components/table/RowCollapseOptions';
|
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 Badge from '@/components/Badge';
|
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';
|
||||||
@@ -25,6 +26,44 @@ import { useTableFilter } from '@/services/hooks/useTableFilter';
|
|||||||
import { ROWS_OPTIONS } from '@/config/constant';
|
import { ROWS_OPTIONS } from '@/config/constant';
|
||||||
import { Purchase } from '@/types/api/purchase/purchase';
|
import { Purchase } from '@/types/api/purchase/purchase';
|
||||||
import { PurchaseApi } from '@/services/api/purchase';
|
import { PurchaseApi } from '@/services/api/purchase';
|
||||||
|
import { Color } from '@/types/theme';
|
||||||
|
|
||||||
|
// ===== STATUS BADGE UTILITIES =====
|
||||||
|
const statusTextMap: Record<string, string> = {
|
||||||
|
APPROVED: 'Disetujui',
|
||||||
|
Disetujui: 'Disetujui',
|
||||||
|
REJECTED: 'Ditolak',
|
||||||
|
Ditolak: 'Ditolak',
|
||||||
|
CREATED: 'Dibuat',
|
||||||
|
UPDATED: 'Diperbarui',
|
||||||
|
};
|
||||||
|
|
||||||
|
const getStatusText = (status: string): string => {
|
||||||
|
return statusTextMap[status] || status;
|
||||||
|
};
|
||||||
|
|
||||||
|
const statusBadgeColorMap: Record<string, Color> = {
|
||||||
|
APPROVED: 'success',
|
||||||
|
Disetujui: 'success',
|
||||||
|
approved: 'success',
|
||||||
|
disetujui: 'success',
|
||||||
|
REJECTED: 'error',
|
||||||
|
Ditolak: 'error',
|
||||||
|
rejected: 'error',
|
||||||
|
ditolak: 'error',
|
||||||
|
CREATED: 'neutral',
|
||||||
|
Dibuat: 'neutral',
|
||||||
|
created: 'neutral',
|
||||||
|
dibuat: 'neutral',
|
||||||
|
UPDATED: 'warning',
|
||||||
|
Diperbarui: 'warning',
|
||||||
|
updated: 'warning',
|
||||||
|
diperbarui: 'warning',
|
||||||
|
};
|
||||||
|
|
||||||
|
const getStatusBadgeColor = (status: string): Color => {
|
||||||
|
return statusBadgeColorMap[status] || 'neutral';
|
||||||
|
};
|
||||||
|
|
||||||
// ===== INTERFACES =====
|
// ===== INTERFACES =====
|
||||||
interface RowOptionsMenuProps {
|
interface RowOptionsMenuProps {
|
||||||
@@ -120,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>[] = [
|
||||||
{
|
{
|
||||||
@@ -130,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',
|
||||||
@@ -142,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) => {
|
||||||
@@ -160,48 +284,42 @@ const PurchaseTable = () => {
|
|||||||
const approval = props.row.original.latest_approval;
|
const approval = props.row.original.latest_approval;
|
||||||
if (!approval) return '-';
|
if (!approval) return '-';
|
||||||
|
|
||||||
const isRejected = approval.action === 'REJECTED';
|
const status = approval.action;
|
||||||
|
|
||||||
let statusColor:
|
let statusColor: Color = 'neutral';
|
||||||
| 'warning'
|
|
||||||
| 'success'
|
|
||||||
| 'neutral'
|
|
||||||
| 'error'
|
|
||||||
| 'primary'
|
|
||||||
| 'info' = 'neutral';
|
|
||||||
|
|
||||||
switch (approval.step_number) {
|
if (status === 'REJECTED') {
|
||||||
case 1:
|
statusColor = getStatusBadgeColor(status);
|
||||||
statusColor = 'neutral';
|
} else {
|
||||||
break;
|
switch (approval.step_number) {
|
||||||
case 2:
|
case 1:
|
||||||
statusColor = 'primary';
|
statusColor = 'neutral';
|
||||||
break;
|
break;
|
||||||
case 3:
|
case 2:
|
||||||
statusColor = 'info';
|
statusColor = 'primary';
|
||||||
break;
|
break;
|
||||||
case 4:
|
case 3:
|
||||||
statusColor = 'warning';
|
statusColor = 'info';
|
||||||
break;
|
break;
|
||||||
case 5:
|
case 4:
|
||||||
statusColor = 'success';
|
statusColor = 'warning';
|
||||||
break;
|
break;
|
||||||
|
case 5:
|
||||||
|
statusColor = 'success';
|
||||||
|
break;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (isRejected) {
|
const statusText = approval.step_name || getStatusText(status);
|
||||||
statusColor = 'error';
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Badge
|
<StatusBadge
|
||||||
variant='soft'
|
|
||||||
color={statusColor}
|
color={statusColor}
|
||||||
|
text={statusText}
|
||||||
className={{
|
className={{
|
||||||
badge: 'whitespace-nowrap',
|
badge: 'whitespace-nowrap max-w-max w-fit',
|
||||||
}}
|
}}
|
||||||
>
|
/>
|
||||||
{isRejected ? 'Ditolak' : approval.step_name}
|
|
||||||
</Badge>
|
|
||||||
);
|
);
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
@@ -287,23 +405,32 @@ const PurchaseTable = () => {
|
|||||||
<RequirePermission permissions='lti.purchase.create'>
|
<RequirePermission permissions='lti.purchase.create'>
|
||||||
<Button
|
<Button
|
||||||
href='/purchase/add'
|
href='/purchase/add'
|
||||||
variant='outline'
|
|
||||||
color='primary'
|
color='primary'
|
||||||
className='w-full sm:w-fit'
|
className='px-3 py-2.5 w-fit text-sm text-base-100 rounded-lg shadow-sm'
|
||||||
>
|
>
|
||||||
<Icon icon='ic:round-plus' width={24} height={24} />
|
<Icon icon='heroicons:plus' width={20} height={20} />
|
||||||
Tambah
|
Add Purchase
|
||||||
</Button>
|
</Button>
|
||||||
</RequirePermission>
|
</RequirePermission>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<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>
|
||||||
@@ -369,6 +496,7 @@ const PurchaseTable = () => {
|
|||||||
text={`Apakah anda yakin ingin menghapus data permintaan pembelian ini?`}
|
text={`Apakah anda yakin ingin menghapus data permintaan pembelian ini?`}
|
||||||
secondaryButton={{
|
secondaryButton={{
|
||||||
text: 'Tidak',
|
text: 'Tidak',
|
||||||
|
onClick: () => deleteModal.closeModal(),
|
||||||
}}
|
}}
|
||||||
primaryButton={{
|
primaryButton={{
|
||||||
text: 'Ya',
|
text: 'Ya',
|
||||||
@@ -377,6 +505,15 @@ const PurchaseTable = () => {
|
|||||||
onClick: confirmationModalDeleteClickHandler,
|
onClick: confirmationModalDeleteClickHandler,
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
|
{invoicePurchaseData && (
|
||||||
|
<div className='hidden'>
|
||||||
|
<PurchaseOrderInvoice
|
||||||
|
data={invoicePurchaseData}
|
||||||
|
triggerDownloadOnMount={true}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -105,6 +105,7 @@ const PurchaseOrderDetail = ({
|
|||||||
const [rowSelection, setRowSelection] = useState<Record<string, boolean>>({});
|
const [rowSelection, setRowSelection] = useState<Record<string, boolean>>({});
|
||||||
const [isDeleteLoading, setIsDeleteLoading] = useState(false);
|
const [isDeleteLoading, setIsDeleteLoading] = useState(false);
|
||||||
const [selectedItem, setSelectedItem] = useState<PurchaseItem | null>(null);
|
const [selectedItem, setSelectedItem] = useState<PurchaseItem | null>(null);
|
||||||
|
const [, setApprovalNotes] = useState('');
|
||||||
|
|
||||||
const selectedRowIds = Object.keys(rowSelection).map((item) =>
|
const selectedRowIds = Object.keys(rowSelection).map((item) =>
|
||||||
parseInt(item)
|
parseInt(item)
|
||||||
@@ -207,12 +208,15 @@ const PurchaseOrderDetail = ({
|
|||||||
|
|
||||||
switch (approvalStep) {
|
switch (approvalStep) {
|
||||||
case 1:
|
case 1:
|
||||||
|
setApprovalNotes('');
|
||||||
staffApprovalModal.openModal();
|
staffApprovalModal.openModal();
|
||||||
break;
|
break;
|
||||||
case 2:
|
case 2:
|
||||||
|
setApprovalNotes('');
|
||||||
confirmationModalWithNotes.openModal();
|
confirmationModalWithNotes.openModal();
|
||||||
break;
|
break;
|
||||||
case 3:
|
case 3:
|
||||||
|
setApprovalNotes('');
|
||||||
acceptApprovalModal.openModal();
|
acceptApprovalModal.openModal();
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
@@ -225,12 +229,15 @@ const PurchaseOrderDetail = ({
|
|||||||
|
|
||||||
switch (approvalStep) {
|
switch (approvalStep) {
|
||||||
case 1:
|
case 1:
|
||||||
|
setApprovalNotes('');
|
||||||
staffRejectionModal.openModal();
|
staffRejectionModal.openModal();
|
||||||
break;
|
break;
|
||||||
case 2:
|
case 2:
|
||||||
|
setApprovalNotes('');
|
||||||
managerRejectionModal.openModal();
|
managerRejectionModal.openModal();
|
||||||
break;
|
break;
|
||||||
case 3:
|
case 3:
|
||||||
|
setApprovalNotes('');
|
||||||
acceptRejectionModal.openModal();
|
acceptRejectionModal.openModal();
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
@@ -406,6 +413,56 @@ const PurchaseOrderDetail = ({
|
|||||||
refetchData,
|
refetchData,
|
||||||
]);
|
]);
|
||||||
|
|
||||||
|
// ===== APPROVAL/REJECTION HANDLERS =====
|
||||||
|
const managerApprovalHandler = async (notes: string) => {
|
||||||
|
const payload: CreateManagerApprovalRequestPayload = {
|
||||||
|
action: 'APPROVED',
|
||||||
|
notes: notes || null,
|
||||||
|
};
|
||||||
|
|
||||||
|
await createManagerApprovalHandler(payload);
|
||||||
|
await refreshApprovals();
|
||||||
|
await refetchData?.();
|
||||||
|
setApprovalNotes('');
|
||||||
|
confirmationModalWithNotes.closeModal();
|
||||||
|
};
|
||||||
|
|
||||||
|
const staffRejectionHandler = async (notes: string) => {
|
||||||
|
const payload: CreateStaffApprovalRequestPayload = {
|
||||||
|
action: 'REJECTED',
|
||||||
|
notes: notes || null,
|
||||||
|
};
|
||||||
|
|
||||||
|
await createStaffApprovalHandler(payload);
|
||||||
|
await refetchData?.();
|
||||||
|
setApprovalNotes('');
|
||||||
|
staffRejectionModal.closeModal();
|
||||||
|
};
|
||||||
|
|
||||||
|
const acceptRejectionHandler = async (notes: string) => {
|
||||||
|
const payload: CreateAcceptApprovalRequestPayload = {
|
||||||
|
action: 'REJECTED',
|
||||||
|
notes: notes || null,
|
||||||
|
};
|
||||||
|
|
||||||
|
await createAcceptApprovalHandler(payload);
|
||||||
|
await refetchData?.();
|
||||||
|
setApprovalNotes('');
|
||||||
|
acceptRejectionModal.closeModal();
|
||||||
|
};
|
||||||
|
|
||||||
|
const managerRejectionHandler = async (notes: string) => {
|
||||||
|
const payload: CreateManagerApprovalRequestPayload = {
|
||||||
|
action: 'REJECTED',
|
||||||
|
notes: notes || null,
|
||||||
|
};
|
||||||
|
|
||||||
|
await createManagerApprovalHandler(payload);
|
||||||
|
await refetchData?.();
|
||||||
|
setApprovalNotes('');
|
||||||
|
managerRejectionModal.closeModal();
|
||||||
|
};
|
||||||
|
|
||||||
if (!initialValues) {
|
if (!initialValues) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
@@ -969,20 +1026,14 @@ const PurchaseOrderDetail = ({
|
|||||||
primaryButton={{
|
primaryButton={{
|
||||||
text: 'Ya, Lanjutkan',
|
text: 'Ya, Lanjutkan',
|
||||||
color: 'success',
|
color: 'success',
|
||||||
onClick: async (notes) => {
|
onClick: managerApprovalHandler,
|
||||||
const payload: CreateManagerApprovalRequestPayload = {
|
|
||||||
action: 'APPROVED',
|
|
||||||
notes: notes || null,
|
|
||||||
};
|
|
||||||
|
|
||||||
await createManagerApprovalHandler(payload);
|
|
||||||
await refreshApprovals();
|
|
||||||
await refetchData?.();
|
|
||||||
confirmationModalWithNotes.closeModal();
|
|
||||||
},
|
|
||||||
}}
|
}}
|
||||||
secondaryButton={{
|
secondaryButton={{
|
||||||
text: 'Batal',
|
text: 'Batal',
|
||||||
|
onClick: () => {
|
||||||
|
setApprovalNotes('');
|
||||||
|
confirmationModalWithNotes.closeModal();
|
||||||
|
},
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
@@ -1071,19 +1122,14 @@ const PurchaseOrderDetail = ({
|
|||||||
primaryButton={{
|
primaryButton={{
|
||||||
text: 'Ya, Tolak',
|
text: 'Ya, Tolak',
|
||||||
color: 'error',
|
color: 'error',
|
||||||
onClick: async (notes) => {
|
onClick: staffRejectionHandler,
|
||||||
const payload: CreateStaffApprovalRequestPayload = {
|
|
||||||
action: 'REJECTED',
|
|
||||||
notes: notes || null,
|
|
||||||
};
|
|
||||||
|
|
||||||
await createStaffApprovalHandler(payload);
|
|
||||||
await refetchData?.();
|
|
||||||
staffRejectionModal.closeModal();
|
|
||||||
},
|
|
||||||
}}
|
}}
|
||||||
secondaryButton={{
|
secondaryButton={{
|
||||||
text: 'Batal',
|
text: 'Batal',
|
||||||
|
onClick: () => {
|
||||||
|
setApprovalNotes('');
|
||||||
|
staffRejectionModal.closeModal();
|
||||||
|
},
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
@@ -1098,19 +1144,14 @@ const PurchaseOrderDetail = ({
|
|||||||
primaryButton={{
|
primaryButton={{
|
||||||
text: 'Ya, Tolak',
|
text: 'Ya, Tolak',
|
||||||
color: 'error',
|
color: 'error',
|
||||||
onClick: async (notes) => {
|
onClick: acceptRejectionHandler,
|
||||||
const payload: CreateAcceptApprovalRequestPayload = {
|
|
||||||
action: 'REJECTED',
|
|
||||||
notes: notes || null,
|
|
||||||
};
|
|
||||||
|
|
||||||
await createAcceptApprovalHandler(payload);
|
|
||||||
await refetchData?.();
|
|
||||||
acceptRejectionModal.closeModal();
|
|
||||||
},
|
|
||||||
}}
|
}}
|
||||||
secondaryButton={{
|
secondaryButton={{
|
||||||
text: 'Batal',
|
text: 'Batal',
|
||||||
|
onClick: () => {
|
||||||
|
setApprovalNotes('');
|
||||||
|
acceptRejectionModal.closeModal();
|
||||||
|
},
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
@@ -1125,19 +1166,14 @@ const PurchaseOrderDetail = ({
|
|||||||
primaryButton={{
|
primaryButton={{
|
||||||
text: 'Ya, Tolak',
|
text: 'Ya, Tolak',
|
||||||
color: 'error',
|
color: 'error',
|
||||||
onClick: async (notes) => {
|
onClick: managerRejectionHandler,
|
||||||
const payload: CreateManagerApprovalRequestPayload = {
|
|
||||||
action: 'REJECTED',
|
|
||||||
notes: notes || null,
|
|
||||||
};
|
|
||||||
|
|
||||||
await createManagerApprovalHandler(payload);
|
|
||||||
await refetchData?.();
|
|
||||||
managerRejectionModal.closeModal();
|
|
||||||
},
|
|
||||||
}}
|
}}
|
||||||
secondaryButton={{
|
secondaryButton={{
|
||||||
text: 'Batal',
|
text: 'Batal',
|
||||||
|
onClick: () => {
|
||||||
|
setApprovalNotes('');
|
||||||
|
managerRejectionModal.closeModal();
|
||||||
|
},
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
|
|||||||
@@ -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
|
||||||
|
|||||||
@@ -190,8 +190,6 @@ const DailyMarketingsTable = ({
|
|||||||
];
|
];
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
// console.log({ sorting });
|
|
||||||
|
|
||||||
if (sorting.length === 1) {
|
if (sorting.length === 1) {
|
||||||
onFilterByChange(sorting[0].id);
|
onFilterByChange(sorting[0].id);
|
||||||
onSortByChange(sorting[0].desc ? 'desc' : 'asc');
|
onSortByChange(sorting[0].desc ? 'desc' : 'asc');
|
||||||
|
|||||||
@@ -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>
|
||||||
|
|||||||
@@ -36,7 +36,6 @@ import SelectInputRadio from '@/components/input/SelectInputRadio';
|
|||||||
import { useFinanceTabStore } from '@/stores/finance-tab/finance-tab.store';
|
import { useFinanceTabStore } from '@/stores/finance-tab/finance-tab.store';
|
||||||
import StatusBadge from '@/components/helper/StatusBadge';
|
import StatusBadge from '@/components/helper/StatusBadge';
|
||||||
import DebtSupplierSkeleton from '@/components/pages/report/finance/skeleton/DebtSupplierSkeleton';
|
import DebtSupplierSkeleton from '@/components/pages/report/finance/skeleton/DebtSupplierSkeleton';
|
||||||
import DataStateSkeleton from '@/components/helper/skeleton/DataStateSkeleton';
|
|
||||||
|
|
||||||
const dueStatus: Record<string, Color> = {
|
const dueStatus: Record<string, Color> = {
|
||||||
'Sudah Jatuh Tempo': 'error',
|
'Sudah Jatuh Tempo': 'error',
|
||||||
@@ -60,7 +59,15 @@ const getPillBadge = (
|
|||||||
? dueStatus[statusText] || 'neutral'
|
? dueStatus[statusText] || 'neutral'
|
||||||
: paymentStatus[statusText] || 'neutral';
|
: paymentStatus[statusText] || 'neutral';
|
||||||
|
|
||||||
return <StatusBadge color={color as Color} text={statusText} />;
|
return (
|
||||||
|
<StatusBadge
|
||||||
|
color={color as Color}
|
||||||
|
text={statusText}
|
||||||
|
className={{
|
||||||
|
badge: 'w-fit',
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
interface DebtSupplierTabProps {
|
interface DebtSupplierTabProps {
|
||||||
@@ -466,7 +473,9 @@ const DebtSupplierTab = ({ tabId }: DebtSupplierTabProps) => {
|
|||||||
footer: () => {
|
footer: () => {
|
||||||
const value = supplier?.total.total_price;
|
const value = supplier?.total.total_price;
|
||||||
return (
|
return (
|
||||||
<div className={`text-right ${value || 0 < 0 ? 'text-red-500' : ''}`}>
|
<div
|
||||||
|
className={`text-right ${value && value < 0 ? 'text-red-500' : ''}`}
|
||||||
|
>
|
||||||
{formatCurrency(value || 0)}
|
{formatCurrency(value || 0)}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
@@ -488,7 +497,9 @@ const DebtSupplierTab = ({ tabId }: DebtSupplierTabProps) => {
|
|||||||
footer: () => {
|
footer: () => {
|
||||||
const value = supplier?.total.payment_price;
|
const value = supplier?.total.payment_price;
|
||||||
return (
|
return (
|
||||||
<div className={`text-right ${value || 0 < 0 ? 'text-red-500' : ''}`}>
|
<div
|
||||||
|
className={`text-right ${value && value < 0 ? 'text-red-500' : ''}`}
|
||||||
|
>
|
||||||
{formatCurrency(value || 0)}
|
{formatCurrency(value || 0)}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
@@ -510,7 +521,9 @@ const DebtSupplierTab = ({ tabId }: DebtSupplierTabProps) => {
|
|||||||
footer: () => {
|
footer: () => {
|
||||||
const value = supplier?.total.debt_price;
|
const value = supplier?.total.debt_price;
|
||||||
return (
|
return (
|
||||||
<div className={`text-right ${value || 0 < 0 ? 'text-red-500' : ''}`}>
|
<div
|
||||||
|
className={`text-right ${value && value < 0 ? 'text-red-500' : ''}`}
|
||||||
|
>
|
||||||
{formatCurrency(value || 0)}
|
{formatCurrency(value || 0)}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -242,9 +242,6 @@ const ProductionResultContent = () => {
|
|||||||
console.error(error);
|
console.error(error);
|
||||||
toast.error('Gagal melakukan export laporan hasil produksi! Coba lagi.');
|
toast.error('Gagal melakukan export laporan hasil produksi! Coba lagi.');
|
||||||
}
|
}
|
||||||
// await ProductionResultReportApi.exportProductionResultToPdf(
|
|
||||||
// projectFlockKandangs
|
|
||||||
// );
|
|
||||||
|
|
||||||
setIsLoadingExportingToPdf(false);
|
setIsLoadingExportingToPdf(false);
|
||||||
};
|
};
|
||||||
@@ -268,7 +265,12 @@ const ProductionResultContent = () => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
setProjectFlockKandangs([projectFlockKandangResponse.data]);
|
setProjectFlockKandangs([projectFlockKandangResponse.data]);
|
||||||
setProjectFlockKandangMetadata(projectFlockKandangResponse.meta);
|
setProjectFlockKandangMetadata({
|
||||||
|
page: 1,
|
||||||
|
limit: 10,
|
||||||
|
total_pages: 1,
|
||||||
|
total_results: 1,
|
||||||
|
});
|
||||||
setIsLoadingSearch(false);
|
setIsLoadingSearch(false);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|||||||
+42
-5
@@ -446,6 +446,24 @@ export const APPROVAL_WORKFLOWS = {
|
|||||||
step_number: 2,
|
step_number: 2,
|
||||||
step_name: 'Aktif',
|
step_name: 'Aktif',
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
step_number: 3,
|
||||||
|
step_name: 'Selesai',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
PROJECT_FLOCK_KANDANGS: [
|
||||||
|
{
|
||||||
|
step_number: 1,
|
||||||
|
step_name: 'Pengajuan',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
step_number: 2,
|
||||||
|
step_name: 'Disetujui',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
step_number: 3,
|
||||||
|
step_name: 'Selesai',
|
||||||
|
},
|
||||||
],
|
],
|
||||||
RECORDINGS: [
|
RECORDINGS: [
|
||||||
{
|
{
|
||||||
@@ -495,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',
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
|
|
||||||
|
|||||||
@@ -658,16 +658,6 @@ export function DailyChecklistContent() {
|
|||||||
) => {
|
) => {
|
||||||
const taskId = taskIdsByPhaseActivityId[activityId];
|
const taskId = taskIdsByPhaseActivityId[activityId];
|
||||||
|
|
||||||
// console.log('[CHECKBOX] Click detected:', {
|
|
||||||
// activityId,
|
|
||||||
// employeeId,
|
|
||||||
// checked,
|
|
||||||
// taskId,
|
|
||||||
// hasTaskId: !!taskId,
|
|
||||||
// checklistStatus,
|
|
||||||
// isChecklistStatusDraft,
|
|
||||||
// });
|
|
||||||
|
|
||||||
if (!taskId) {
|
if (!taskId) {
|
||||||
console.error('[CHECKBOX] No taskId found for activityId:', activityId);
|
console.error('[CHECKBOX] No taskId found for activityId:', activityId);
|
||||||
console.error('[CHECKBOX] Available taskIds:', taskIdsByPhaseActivityId);
|
console.error('[CHECKBOX] Available taskIds:', taskIdsByPhaseActivityId);
|
||||||
@@ -695,10 +685,7 @@ export function DailyChecklistContent() {
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
// console.log(
|
|
||||||
// '[CHECKBOX] State updated optimistically:',
|
|
||||||
// updated[taskId]?.[employeeId]
|
|
||||||
// );
|
|
||||||
return updated;
|
return updated;
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -710,8 +697,6 @@ export function DailyChecklistContent() {
|
|||||||
note: assignments[taskId]?.[employeeId]?.note || null,
|
note: assignments[taskId]?.[employeeId]?.note || null,
|
||||||
};
|
};
|
||||||
|
|
||||||
// console.log('[CHECKBOX] Saving to database:', payload);
|
|
||||||
|
|
||||||
const checkOrUncheckAssignmentRes =
|
const checkOrUncheckAssignmentRes =
|
||||||
await DailyChecklistApi.checkOrUncheckAssignment(payload);
|
await DailyChecklistApi.checkOrUncheckAssignment(payload);
|
||||||
|
|
||||||
@@ -735,8 +720,6 @@ export function DailyChecklistContent() {
|
|||||||
}));
|
}));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// console.log('[CHECKBOX] Saved successfully');
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleNoteChange = async (
|
const handleNoteChange = async (
|
||||||
@@ -1247,8 +1230,6 @@ export function DailyChecklistContent() {
|
|||||||
})
|
})
|
||||||
);
|
);
|
||||||
|
|
||||||
console.log(activities);
|
|
||||||
|
|
||||||
activities.forEach((activity, index) => {
|
activities.forEach((activity, index) => {
|
||||||
const taskId =
|
const taskId =
|
||||||
taskIdsByPhaseActivityId[activity.id];
|
taskIdsByPhaseActivityId[activity.id];
|
||||||
|
|||||||
+25
-20
@@ -36,6 +36,7 @@ import { ColumnDef } from '@tanstack/react-table';
|
|||||||
import { useSelect } from '@/components/input/SelectInput';
|
import { useSelect } from '@/components/input/SelectInput';
|
||||||
import { KandangApi } from '@/services/api/master-data';
|
import { KandangApi } from '@/services/api/master-data';
|
||||||
import DebouncedTextInput from '@/components/input/DebouncedTextInput';
|
import DebouncedTextInput from '@/components/input/DebouncedTextInput';
|
||||||
|
import RequirePermission from '@/components/helper/RequirePermission';
|
||||||
|
|
||||||
interface Kandang {
|
interface Kandang {
|
||||||
id: string;
|
id: string;
|
||||||
@@ -389,19 +390,21 @@ export function ListDailyChecklistContent() {
|
|||||||
</Button>
|
</Button>
|
||||||
|
|
||||||
{row.original.status === 'DRAFT' && (
|
{row.original.status === 'DRAFT' && (
|
||||||
<Button
|
<RequirePermission permissions='lti.daily_checklist.create'>
|
||||||
size='sm'
|
<Button
|
||||||
variant='outline'
|
size='sm'
|
||||||
onClick={() => handleEdit(row.original)}
|
variant='outline'
|
||||||
className='border-gray-200 text-gray-700 hover:bg-gray-50'
|
onClick={() => handleEdit(row.original)}
|
||||||
>
|
className='border-gray-200 text-gray-700 hover:bg-gray-50'
|
||||||
<Edit className='w-4 h-4 mr-1' />
|
>
|
||||||
Edit
|
<Edit className='w-4 h-4 mr-1' />
|
||||||
</Button>
|
Edit
|
||||||
|
</Button>
|
||||||
|
</RequirePermission>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{row.original.status === 'SUBMITTED' && (
|
{row.original.status === 'SUBMITTED' && (
|
||||||
<>
|
<RequirePermission permissions='lti.daily_checklist.create'>
|
||||||
<Button
|
<Button
|
||||||
size='sm'
|
size='sm'
|
||||||
onClick={() => handleApprove(row.original)}
|
onClick={() => handleApprove(row.original)}
|
||||||
@@ -419,19 +422,21 @@ export function ListDailyChecklistContent() {
|
|||||||
<XCircle className='w-4 h-4 mr-1' />
|
<XCircle className='w-4 h-4 mr-1' />
|
||||||
Reject
|
Reject
|
||||||
</Button>
|
</Button>
|
||||||
</>
|
</RequirePermission>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{row.original.status === 'DRAFT' && (
|
{row.original.status === 'DRAFT' && (
|
||||||
<Button
|
<RequirePermission permissions='lti.daily_checklist.create'>
|
||||||
size='sm'
|
<Button
|
||||||
variant='destructive'
|
size='sm'
|
||||||
onClick={() => handleDelete(row.original)}
|
variant='destructive'
|
||||||
className='bg-red-600 hover:bg-red-700 text-white'
|
onClick={() => handleDelete(row.original)}
|
||||||
>
|
className='bg-red-600 hover:bg-red-700 text-white'
|
||||||
<Trash2 className='w-4 h-4 mr-1' />
|
>
|
||||||
Hapus
|
<Trash2 className='w-4 h-4 mr-1' />
|
||||||
</Button>
|
Hapus
|
||||||
|
</Button>
|
||||||
|
</RequirePermission>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
),
|
),
|
||||||
|
|||||||
+25
-24
@@ -17,12 +17,13 @@ import {
|
|||||||
DialogFooter,
|
DialogFooter,
|
||||||
} from '@/figma-make/components/base/dialog';
|
} from '@/figma-make/components/base/dialog';
|
||||||
import { toast } from 'sonner';
|
import { toast } from 'sonner';
|
||||||
import { useRouter, useSearchParams } from 'next/navigation';
|
import { notFound, useRouter, useSearchParams } from 'next/navigation';
|
||||||
import { DailyChecklistApi } from '@/services/api/daily-checklist/daily-checklist';
|
import { DailyChecklistApi } from '@/services/api/daily-checklist/daily-checklist';
|
||||||
import { isResponseError } from '@/lib/api-helper';
|
import { isResponseError } from '@/lib/api-helper';
|
||||||
import Link from 'next/link';
|
import Link from 'next/link';
|
||||||
import { Icon } from '@iconify/react';
|
import { Icon } from '@iconify/react';
|
||||||
import { Document } from '@/types/api/api-general';
|
import { Document } from '@/types/api/api-general';
|
||||||
|
import RequirePermission from '@/components/helper/RequirePermission';
|
||||||
|
|
||||||
interface ChecklistDetailRow {
|
interface ChecklistDetailRow {
|
||||||
checklist_id: string;
|
checklist_id: string;
|
||||||
@@ -139,6 +140,8 @@ export function DetailDailyChecklistContent() {
|
|||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (checklistId) {
|
if (checklistId) {
|
||||||
fetchChecklistDetail();
|
fetchChecklistDetail();
|
||||||
|
} else {
|
||||||
|
router.push('/404');
|
||||||
}
|
}
|
||||||
}, [checklistId]);
|
}, [checklistId]);
|
||||||
|
|
||||||
@@ -593,25 +596,27 @@ export function DetailDailyChecklistContent() {
|
|||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
{header.status === 'SUBMITTED' && (
|
{header.status === 'SUBMITTED' && (
|
||||||
<div className='flex gap-2'>
|
<RequirePermission permissions='lti.daily_checklist.create'>
|
||||||
<Button
|
<div className='flex gap-2'>
|
||||||
onClick={handleApprove}
|
<Button
|
||||||
disabled={actionLoading}
|
onClick={handleApprove}
|
||||||
className='bg-green-600 hover:bg-green-700 text-white'
|
disabled={actionLoading}
|
||||||
>
|
className='bg-green-600 hover:bg-green-700 text-white'
|
||||||
<CheckCircle className='w-4 h-4 mr-2' />
|
>
|
||||||
Approve
|
<CheckCircle className='w-4 h-4 mr-2' />
|
||||||
</Button>
|
Approve
|
||||||
<Button
|
</Button>
|
||||||
onClick={handleReject}
|
<Button
|
||||||
disabled={actionLoading}
|
onClick={handleReject}
|
||||||
variant='destructive'
|
disabled={actionLoading}
|
||||||
className='bg-red-600 hover:bg-red-700 text-white'
|
variant='destructive'
|
||||||
>
|
className='bg-red-600 hover:bg-red-700 text-white'
|
||||||
<XCircle className='w-4 h-4 mr-2' />
|
>
|
||||||
Reject
|
<XCircle className='w-4 h-4 mr-2' />
|
||||||
</Button>
|
Reject
|
||||||
</div>
|
</Button>
|
||||||
|
</div>
|
||||||
|
</RequirePermission>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -799,10 +804,6 @@ export function DetailDailyChecklistContent() {
|
|||||||
? 'pl-12'
|
? 'pl-12'
|
||||||
: 'pl-8';
|
: 'pl-8';
|
||||||
|
|
||||||
console.log({
|
|
||||||
activity,
|
|
||||||
});
|
|
||||||
|
|
||||||
rows.push(
|
rows.push(
|
||||||
<tr
|
<tr
|
||||||
key={`activity-${activity.id}-${index}`}
|
key={`activity-${activity.id}-${index}`}
|
||||||
|
|||||||
@@ -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;
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
|
import { isResponseError } from '@/lib/api-helper';
|
||||||
import { BaseApiService } from '@/services/api/base';
|
import { BaseApiService } from '@/services/api/base';
|
||||||
import { httpClient } from '@/services/http/client';
|
import { httpClient, httpClientFetcher } from '@/services/http/client';
|
||||||
import { BaseApiResponse } from '@/types/api/api-general';
|
import { BaseApiResponse } from '@/types/api/api-general';
|
||||||
import {
|
import {
|
||||||
Marketing,
|
Marketing,
|
||||||
@@ -8,6 +9,9 @@ import {
|
|||||||
CreateDeliveryOrderPayload,
|
CreateDeliveryOrderPayload,
|
||||||
UpdateDeliveryOrderPayload,
|
UpdateDeliveryOrderPayload,
|
||||||
} from '@/types/api/marketing/marketing';
|
} from '@/types/api/marketing/marketing';
|
||||||
|
import toast from 'react-hot-toast';
|
||||||
|
import * as XLSX from 'xlsx';
|
||||||
|
import { formatCurrency, formatDate, formatTitleCase } from '@/lib/helper';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 💡 Helper untuk membuat respons dummy
|
* 💡 Helper untuk membuat respons dummy
|
||||||
@@ -97,6 +101,78 @@ export class SalesOrderService extends BaseApiService<
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
class MarketingExportService extends BaseApiService<
|
||||||
|
Marketing,
|
||||||
|
unknown,
|
||||||
|
unknown
|
||||||
|
> {
|
||||||
|
constructor(basePath: string = '/marketing') {
|
||||||
|
super(basePath);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Export to Excel
|
||||||
|
*/
|
||||||
|
async exportToExcel(initialQueryString: string) {
|
||||||
|
const params = new URLSearchParams(initialQueryString);
|
||||||
|
const queryString = `?${params.toString()}`;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const marketingData = await httpClientFetcher<
|
||||||
|
BaseApiResponse<Marketing[]>
|
||||||
|
>(`${this.basePath}${queryString}`);
|
||||||
|
|
||||||
|
if (isResponseError(marketingData)) {
|
||||||
|
toast.error('Gagal melakukan export marketing! Coba lagi.');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const rows = marketingData.data;
|
||||||
|
|
||||||
|
const formattedRows = [];
|
||||||
|
|
||||||
|
for (let i = 0; i < rows.length; i++) {
|
||||||
|
const row = rows[i];
|
||||||
|
const approval = row.latest_approval;
|
||||||
|
const isRejected = approval?.action === 'REJECTED';
|
||||||
|
|
||||||
|
// Calculate grand total from sales_order products
|
||||||
|
const grandTotal =
|
||||||
|
row.sales_order
|
||||||
|
?.map((product) => product.total_price)
|
||||||
|
.reduce((a, b) => a + b, 0) ?? 0;
|
||||||
|
|
||||||
|
// Get product names
|
||||||
|
const products =
|
||||||
|
row.sales_order
|
||||||
|
?.map((product) => product.product_warehouse?.product?.name)
|
||||||
|
.filter(Boolean)
|
||||||
|
.join(', ') ?? '';
|
||||||
|
|
||||||
|
formattedRows.push({
|
||||||
|
'No. Order': row.so_number,
|
||||||
|
Tanggal: formatDate(row.so_date, 'DD-MM-YYYY'),
|
||||||
|
Status: isRejected
|
||||||
|
? 'Ditolak'
|
||||||
|
: formatTitleCase(approval?.step_name || ''),
|
||||||
|
Customer: row.customer?.name || '',
|
||||||
|
'Grand Total': formatCurrency(grandTotal),
|
||||||
|
Products: products,
|
||||||
|
Notes: row.notes || '',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const ws = XLSX.utils.json_to_sheet(formattedRows);
|
||||||
|
const wb = XLSX.utils.book_new();
|
||||||
|
XLSX.utils.book_append_sheet(wb, ws, 'marketing');
|
||||||
|
|
||||||
|
// triggers download in browser
|
||||||
|
XLSX.writeFile(wb, 'marketing.xlsx');
|
||||||
|
} catch (error) {
|
||||||
|
toast.error('Gagal melakukan export marketing! Coba lagi.');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
export const SalesOrderApi = new SalesOrderService('/marketing/sales-orders');
|
export const SalesOrderApi = new SalesOrderService('/marketing/sales-orders');
|
||||||
export const DeliveryOrderApi = new BaseApiService<
|
export const DeliveryOrderApi = new BaseApiService<
|
||||||
@@ -104,6 +180,4 @@ export const DeliveryOrderApi = new BaseApiService<
|
|||||||
CreateDeliveryOrderPayload,
|
CreateDeliveryOrderPayload,
|
||||||
UpdateDeliveryOrderPayload
|
UpdateDeliveryOrderPayload
|
||||||
>('/marketing/delivery-orders');
|
>('/marketing/delivery-orders');
|
||||||
export const MarketingApi = new BaseApiService<Marketing, unknown, unknown>(
|
export const MarketingApi = new MarketingExportService('/marketing');
|
||||||
'/marketing'
|
|
||||||
);
|
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ import {
|
|||||||
ClosingProjectFlockKandangPayload,
|
ClosingProjectFlockKandangPayload,
|
||||||
CheckClosingResponse,
|
CheckClosingResponse,
|
||||||
} from '@/types/api/production/project-flock-kandang';
|
} from '@/types/api/production/project-flock-kandang';
|
||||||
import { BaseApiResponse } from '@/types/api/api-general';
|
import { Approvals, BaseApiResponse } from '@/types/api/api-general';
|
||||||
import { httpClient } from '@/services/http/client';
|
import { httpClient } from '@/services/http/client';
|
||||||
import axios from 'axios';
|
import axios from 'axios';
|
||||||
|
|
||||||
@@ -181,6 +181,33 @@ export class ProjectFlockKandangService extends BaseApiService<
|
|||||||
return undefined;
|
return undefined;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async getApprovalLineHistory(
|
||||||
|
id: number,
|
||||||
|
page: number = 1,
|
||||||
|
limit: number = 100
|
||||||
|
) {
|
||||||
|
try {
|
||||||
|
const approvalHistoryRes = await httpClient<Approvals>('/approvals', {
|
||||||
|
query: {
|
||||||
|
module_name: 'PROJECT_FLOCK_KANDANGS',
|
||||||
|
module_id: id,
|
||||||
|
group_step_number: 'false',
|
||||||
|
page,
|
||||||
|
limit,
|
||||||
|
order_by_date: 'ASC',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
return approvalHistoryRes;
|
||||||
|
} catch (error) {
|
||||||
|
if (axios.isAxiosError<Approvals>(error)) {
|
||||||
|
return error.response?.data;
|
||||||
|
}
|
||||||
|
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export const ProjectFlockKandangApi = new ProjectFlockKandangService(
|
export const ProjectFlockKandangApi = new ProjectFlockKandangService(
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import {
|
|||||||
} from '@/types/api/production/project-flock';
|
} from '@/types/api/production/project-flock';
|
||||||
import { BaseApiService } from '@/services/api/base';
|
import { BaseApiService } from '@/services/api/base';
|
||||||
import {
|
import {
|
||||||
|
Approvals,
|
||||||
BaseApiResponse,
|
BaseApiResponse,
|
||||||
BaseGroupedApproval,
|
BaseGroupedApproval,
|
||||||
ErrorApiResponse,
|
ErrorApiResponse,
|
||||||
@@ -53,6 +54,33 @@ export class ProjectFlockService extends BaseApiService<
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async getApprovalLineHistory(
|
||||||
|
id: number,
|
||||||
|
page: number = 1,
|
||||||
|
limit: number = 100
|
||||||
|
) {
|
||||||
|
try {
|
||||||
|
const approvalHistoryRes = await httpClient<Approvals>('/approvals', {
|
||||||
|
query: {
|
||||||
|
module_name: 'PROJECT_FLOCKS',
|
||||||
|
module_id: id,
|
||||||
|
group_step_number: 'false',
|
||||||
|
page,
|
||||||
|
limit,
|
||||||
|
order_by_date: 'ASC',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
return approvalHistoryRes;
|
||||||
|
} catch (error) {
|
||||||
|
if (axios.isAxiosError<Approvals>(error)) {
|
||||||
|
return error.response?.data;
|
||||||
|
}
|
||||||
|
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Lookup for Project Flock Kandang
|
* Lookup for Project Flock Kandang
|
||||||
*/
|
*/
|
||||||
|
|||||||
@@ -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,
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import { useState } from 'react';
|
|||||||
interface UseFormikErrorListOptions {
|
interface UseFormikErrorListOptions {
|
||||||
onBeforeSubmit?: (e: React.FormEvent<HTMLFormElement>) => boolean | void;
|
onBeforeSubmit?: (e: React.FormEvent<HTMLFormElement>) => boolean | void;
|
||||||
onAfterValidation?: () => void | Promise<void>;
|
onAfterValidation?: () => void | Promise<void>;
|
||||||
|
onAfterSubmit?: () => void | Promise<void>;
|
||||||
}
|
}
|
||||||
|
|
||||||
export const useFormikErrorList = <T>(
|
export const useFormikErrorList = <T>(
|
||||||
@@ -49,6 +50,11 @@ export const useFormikErrorList = <T>(
|
|||||||
|
|
||||||
// Submit form
|
// Submit form
|
||||||
formik.handleSubmit();
|
formik.handleSubmit();
|
||||||
|
|
||||||
|
// Call onAfterSubmit callback if validation passed
|
||||||
|
if (options?.onAfterSubmit) {
|
||||||
|
await options.onAfterSubmit();
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const close = () => {
|
const close = () => {
|
||||||
|
|||||||
+21
@@ -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 = {
|
||||||
@@ -82,6 +88,15 @@ export type MarketingDeliveryProducts = {
|
|||||||
|
|
||||||
export type Marketing = BaseMetadata & BaseMarketing;
|
export type Marketing = BaseMetadata & BaseMarketing;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Filter Data Types
|
||||||
|
*/
|
||||||
|
export type MarketingFilter = {
|
||||||
|
product_ids: number[];
|
||||||
|
status: string;
|
||||||
|
customer_id: number;
|
||||||
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Base Data Payload
|
* Base Data Payload
|
||||||
*/
|
*/
|
||||||
@@ -101,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;
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
Vendored
+14
-4
@@ -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;
|
||||||
|
|||||||
Reference in New Issue
Block a user