Merge branch 'feat/FE/US-164/expense-realization' into 'development'

[FEAT/FE][US#164] Expense Realization

See merge request mbugroup/lti-web-client!67
This commit is contained in:
Adnan Zahir
2025-11-28 15:40:33 +07:00
25 changed files with 3976 additions and 2119 deletions
Binary file not shown.

After

Width:  |  Height:  |  Size: 28 KiB

+6 -4
View File
@@ -34,13 +34,15 @@ const ExpenseEditPage = () => {
return;
}
const isExpenseRejectedOrApproved =
const isExpenseCanBeEdited =
!isLoadingExpense &&
isResponseSuccess(expense) &&
(expense.data.approval.action === 'REJECTED' ||
expense.data.approval.step_number === 5);
expense.data.latest_approval.step_number !== 5 &&
(expense.data.latest_approval.step_number === 1 ||
expense.data.latest_approval.step_number === 2 ||
expense.data.latest_approval.step_number === 3);
if (isExpenseRejectedOrApproved) {
if (!isLoadingExpense && !isExpenseCanBeEdited) {
router.back();
return;
}
+62
View File
@@ -0,0 +1,62 @@
'use client';
import { useRouter, useSearchParams } from 'next/navigation';
import useSWR from 'swr';
import ExpenseRealizationForm from '@/components/pages/expense/form/ExpenseRealizationForm';
import { ExpenseApi } from '@/services/api/expense';
import { isResponseError, isResponseSuccess } from '@/lib/api-helper';
const ExpenseRealizationEditPage = () => {
const router = useRouter();
const searchParams = useSearchParams();
const expenseId = searchParams.get('expenseId');
const { data: expense, isLoading: isLoadingExpense } = useSWR(
expenseId,
(id: number) => ExpenseApi.getSingle(id)
);
if (!expenseId) {
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 (!isLoadingExpense && (!expense || isResponseError(expense))) {
router.replace('/404');
return;
}
const isExpenseRealizationCanBeEdited =
!isLoadingExpense &&
isResponseSuccess(expense) &&
expense.data.latest_approval.action !== 'REJECTED' &&
(expense.data.latest_approval.step_number === 4 ||
expense.data.latest_approval.step_number === 5);
if (!isLoadingExpense && !isExpenseRealizationCanBeEdited) {
router.back();
return;
}
return (
<div className='w-full p-4 flex flex-row justify-center'>
{isLoadingExpense && (
<span className='loading loading-spinner loading-xl' />
)}
{!isLoadingExpense && isResponseSuccess(expense) && (
<ExpenseRealizationForm type='edit' initialValues={expense.data} />
)}
</div>
);
};
export default ExpenseRealizationEditPage;
+11
View File
@@ -0,0 +1,11 @@
import SuspenseHelper from '@/components/helper/SuspenseHelper';
const Layout = ({
children,
}: Readonly<{
children: React.ReactNode;
}>) => {
return <SuspenseHelper>{children}</SuspenseHelper>;
};
export default Layout;
+67
View File
@@ -0,0 +1,67 @@
'use client';
import { useRouter, useSearchParams } from 'next/navigation';
import useSWR from 'swr';
import ExpenseRealizationForm from '@/components/pages/expense/form/ExpenseRealizationForm';
import { ExpenseApi } from '@/services/api/expense';
import { isResponseError, isResponseSuccess } from '@/lib/api-helper';
const ExpenseRealization = () => {
const router = useRouter();
const searchParams = useSearchParams();
const expenseId = searchParams.get('expenseId');
const { data: expense, isLoading: isLoadingExpense } = useSWR(
expenseId,
(id: number) => ExpenseApi.getSingle(id)
);
if (!expenseId) {
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 (!isLoadingExpense && (!expense || isResponseError(expense))) {
router.replace('/404');
return;
}
const isExpenseCanBeRealized =
isResponseSuccess(expense) &&
expense.data.latest_approval.action !== 'REJECTED' &&
expense.data.latest_approval.step_number === 3;
if (isResponseSuccess(expense) && !isExpenseCanBeRealized) {
if (typeof window !== 'undefined') {
router.back();
}
return (
<div className='w-full flex flex-row justify-center items-center p-4'>
<span className='loading loading-spinner loading-xl' />
</div>
);
}
return (
<div className='w-full p-4 flex flex-row justify-center'>
{isLoadingExpense && (
<span className='loading loading-spinner loading-xl' />
)}
{!isLoadingExpense && isResponseSuccess(expense) && (
<ExpenseRealizationForm initialValues={expense.data} />
)}
</div>
);
};
export default ExpenseRealization;
+23 -2
View File
@@ -1,16 +1,38 @@
'use client';
import toast from 'react-hot-toast';
import { useRouter } from 'next/navigation';
import { Icon } from '@iconify/react';
import Menu from '@/components/menu/Menu';
import MenuItem from '@/components/menu/MenuItem';
import Button from '@/components/Button';
import { useAuth } from '@/services/hooks/useAuth';
import { AuthApi } from '@/services/api/auth';
import { isResponseError } from '@/lib/api-helper';
interface NavbarProps {
title: string;
toggleSidebar?: () => void;
}
const Navbar = ({ title, toggleSidebar }: NavbarProps) => {
const { setUser } = useAuth();
const router = useRouter();
const logoutClickHandler = async () => {
const logoutRes = await AuthApi.logout();
if (isResponseError(logoutRes)) {
toast.error('Gagal logout! Coba lagi!');
return;
}
setUser(undefined);
router.replace(process.env.NEXT_PUBLIC_SSO_LOGIN_URL as string);
};
return (
<div className='navbar px-4 bg-base-100 shadow-sm'>
<div className='flex-1'>
@@ -42,8 +64,7 @@ const Navbar = ({ title, toggleSidebar }: NavbarProps) => {
</div>
<Menu className='dropdown-content w-52 mt-3 p-2 bg-base-100 shadow rounded-box menu-sm'>
<MenuItem title='Settings' href='#' />
<MenuItem title='Logout' href='#' />
<MenuItem title='Logout' onClick={logoutClickHandler} />
</Menu>
</div>
</div>
+33 -166
View File
@@ -6,147 +6,9 @@ import useSWRImmutable from 'swr/immutable';
import { useAuth } from '@/services/hooks/useAuth';
import { httpClientFetcher, SWRHttpKey } from '@/services/http/client';
import { isResponseSuccess } from '@/lib/api-helper';
import { GetMeResponse } from '@/types/api/api-general';
// TODO: delete this later, DONT HARDCODE USER DATA
const DUMMY_USER = {
id: 1,
email: 'admin@mbugroup.id',
npk: '0001',
name: 'Super Admin',
image: null,
created_at: '2025-09-30T03:24:20.899229Z',
updated_at: '2025-09-30T03:24:20.899229Z',
roles: [
{
id: 1,
key: 'mbu.super_admin',
name: 'MBU Administrator',
client: {
id: 1,
name: 'PT Mitra Berlian Unggas',
alias: 'MBU',
},
permissions: [
{
id: 1,
name: 'mbu:purchase:read',
action: 'read',
client: {
id: 1,
name: 'PT Mitra Berlian Unggas',
alias: 'MBU',
},
},
{
id: 2,
name: 'mbu:purchase:create',
action: 'create',
client: {
id: 1,
name: 'PT Mitra Berlian Unggas',
alias: 'MBU',
},
},
{
id: 3,
name: 'mbu:purchase:approve',
action: 'approve',
client: {
id: 1,
name: 'PT Mitra Berlian Unggas',
alias: 'MBU',
},
},
],
},
{
id: 2,
key: 'lti.super_admin',
name: 'LTI Administrator',
client: {
id: 2,
name: 'PT Lumbung Telur Indonesia',
alias: 'LTI',
},
permissions: [
{
id: 4,
name: 'lti:purchase:read',
action: 'read',
client: {
id: 2,
name: 'PT Lumbung Telur Indonesia',
alias: 'LTI',
},
},
{
id: 5,
name: 'lti:purchase:create',
action: 'create',
client: {
id: 2,
name: 'PT Lumbung Telur Indonesia',
alias: 'LTI',
},
},
{
id: 6,
name: 'lti:purchase:approve',
action: 'approve',
client: {
id: 2,
name: 'PT Lumbung Telur Indonesia',
alias: 'LTI',
},
},
],
},
{
id: 3,
key: 'manbu.super_admin',
name: 'MANBU Administrator',
client: {
id: 3,
name: 'PT Mandiri Berlian Unggas',
alias: 'MANBU',
},
permissions: [
{
id: 7,
name: 'manbu:purchase:read',
action: 'read',
client: {
id: 3,
name: 'PT Mandiri Berlian Unggas',
alias: 'MANBU',
},
},
{
id: 8,
name: 'manbu:purchase:create',
action: 'create',
client: {
id: 3,
name: 'PT Mandiri Berlian Unggas',
alias: 'MANBU',
},
},
{
id: 9,
name: 'manbu:purchase:approve',
action: 'approve',
client: {
id: 3,
name: 'PT Mandiri Berlian Unggas',
alias: 'MANBU',
},
},
],
},
],
};
import { isResponseError, isResponseSuccess } from '@/lib/api-helper';
import { BaseApiResponse, GetMeResponse } from '@/types/api/api-general';
import { AxiosError } from 'axios';
interface RequireAuthProps {
children?: ReactNode;
@@ -156,17 +18,20 @@ const RequireAuth = ({ children }: RequireAuthProps) => {
const router = useRouter();
const { setUser, setIsLoadingUser } = useAuth();
const { data: userResponse, isLoading: isLoadingUserResponse } =
useSWRImmutable<GetMeResponse & { ok?: boolean }, unknown, SWRHttpKey>(
'/auth/sso/userinfo',
httpClientFetcher,
{
shouldRetryOnError: false,
revalidateOnFocus: false,
revalidateOnReconnect: false,
refreshInterval: 0,
}
);
const {
data: userResponse,
isLoading: isLoadingUserResponse,
error: userErrorResponse,
} = useSWRImmutable<
GetMeResponse & { ok?: boolean },
AxiosError<BaseApiResponse>,
SWRHttpKey
>('/sso/userinfo', httpClientFetcher, {
shouldRetryOnError: false,
revalidateOnFocus: false,
revalidateOnReconnect: false,
refreshInterval: 0,
});
useEffect(() => {
setIsLoadingUser(isLoadingUserResponse);
@@ -175,23 +40,25 @@ const RequireAuth = ({ children }: RequireAuthProps) => {
useEffect(() => {
if (isResponseSuccess(userResponse)) {
setUser(userResponse.data);
} else {
// router.replace(process.env.NEXT_PUBLIC_SSO_LOGIN_URL as string);
// TODO: remove this later, DONT HARDCODE USER DATA
setUser(DUMMY_USER);
} else if (
isResponseError(userErrorResponse?.response?.data) &&
typeof window !== 'undefined'
) {
router.replace(
`${process.env.NEXT_PUBLIC_SSO_LOGIN_URL as string}?redirect_url=${window.location.href}`
);
}
}, [userResponse, setIsLoadingUser, setUser]);
}, [userResponse, userErrorResponse, setIsLoadingUser, setUser]);
// TODO: uncomment this later
// if (isLoadingUserResponse && !userResponse) {
// return (
// <div className='w-full flex flex-row justify-center items-center p-4'>
// <span className='loading loading-spinner loading-xl' />
// </div>
// );
// }
if (isLoadingUserResponse && !userResponse && !userErrorResponse) {
return (
<div className='w-full flex flex-row justify-center items-center p-4'>
<span className='loading loading-spinner loading-xl' />
</div>
);
}
return <>{children}</>;
return <>{isResponseSuccess(userResponse) && children}</>;
};
export default RequireAuth;
+53 -19
View File
@@ -18,6 +18,7 @@ import { useCallback, useMemo } from 'react';
export type ApprovalStepStatus = 'APPROVED' | 'REJECTED' | 'WAITING' | 'IDLE';
export type ApprovalStepLog = {
action: string;
action_by?: string;
date?: string;
notes?: string | null;
@@ -65,28 +66,55 @@ const ApprovalSteps = ({ approvals }: ApprovalStepsProps) => {
position='right'
className={{
wrapper: 'md:tooltip-bottom',
content: 'p-0 rounded overflow-hidden',
}}
content={
<>
{approval.logs && approval.logs.length > 0 && (
<div className='flex flex-col gap-2'>
{approval.logs?.map((approvalLog, logIdx) => (
<div
key={logIdx}
className='flex flex-col text-base text-start'
>
{approvalLog.date && (
<span>
{formatDate(
approvalLog.date,
'YYYY-MM-DD, HH:mm:ss'
)}
</span>
)}
<span>Oleh: {approvalLog.action_by ?? '-'}</span>
<span>Catatan: {approvalLog.notes ?? '-'}</span>
</div>
))}
<div className='flex flex-col gap-0'>
{approval.logs?.map((approvalLog, logIdx) => {
const action =
approvalLog.action === 'CREATED'
? 'Dibuat'
: approvalLog.action === 'UPDATED'
? 'Diperbarui'
: approvalLog.action === 'APPROVED'
? 'Disetujui'
: approvalLog.action === 'REJECTED'
? 'Ditolak'
: '-';
return (
<div
key={logIdx}
className={cn(
'p-2 flex flex-col text-base text-start',
{
'bg-success text-success-content':
approvalLog.action === 'APPROVED',
'bg-error text-error-content':
approvalLog.action === 'REJECTED',
'bg-info text-info-content':
approvalLog.action === 'CREATED',
'bg-warning text-warning-content':
approvalLog.action === 'UPDATED',
}
)}
>
{approvalLog.date && (
<span>
{formatDate(
approvalLog.date,
'YYYY-MM-DD, HH:mm:ss'
)}
</span>
)}
<span>Aksi: {action}</span>
<span>Oleh: {approvalLog.action_by ?? '-'}</span>
<span>Catatan: {approvalLog.notes ?? '-'}</span>
</div>
);
})}
</div>
)}
</>
@@ -130,6 +158,8 @@ export const formatGroupedApprovalsToApprovalSteps = (
const lastStepNumber =
groupedApprovals[groupedApprovals.length - 1]?.step_number;
const isLatestApprovalRejected = latestApproval.action === 'REJECTED';
if (!approvalGroup && currentStepNumber <= lastStepNumber) {
throw new Error(
`Approval dengan ${approvalLineItem.step_name} tidak ditemukan!`
@@ -172,7 +202,10 @@ export const formatGroupedApprovalsToApprovalSteps = (
break;
}
}
} else if (approvalGroup.step_number === latestApproval.step_number + 1) {
} else if (
approvalGroup.step_number === latestApproval.step_number + 1 &&
!isLatestApprovalRejected
) {
approvalStatus = 'WAITING';
} else {
approvalStatus = 'IDLE';
@@ -183,6 +216,7 @@ export const formatGroupedApprovalsToApprovalSteps = (
action_by: approval.action_by.name,
date: approval.action_at,
notes: approval.notes,
action: approval.action,
}))
: [];
+34 -465
View File
@@ -1,157 +1,45 @@
'use client';
import { useState } from 'react';
import toast from 'react-hot-toast';
import { useRouter } from 'next/navigation';
import { useFormik } from 'formik';
import { useMemo, useState } from 'react';
import Link from 'next/link';
import { Icon } from '@iconify/react';
import Button from '@/components/Button';
import { useModal } from '@/components/Modal';
import ConfirmationModal from '@/components/modal/ConfirmationModal';
import ConfirmationModalWithNotes from '@/components/modal/ConfirmationModalWithNotes';
import RealizationStatusBadge from '@/components/pages/expense/RealizationStatusBadge';
import ExpenseStatusBadge from '@/components/pages/expense/ExpenseStatusBadge';
import DropFileInput from '@/components/input/DropFileInput';
import Tabs from '@/components/Tabs';
import ExpenseRequestContent from '@/components/pages/expense/ExpenseRequestContent';
import ExpenseRealizationContent from '@/components/pages/expense/ExpenseRealizationContent';
import { Expense } from '@/types/api/expense';
import { formatCurrency, formatDate } from '@/lib/helper';
import { ExpenseApi } from '@/services/api/expense';
import { isResponseSuccess } from '@/lib/api-helper';
import { ACCEPTED_FILE_TYPE } from '@/config/constant';
import {
UploadRequestDocumentsFormSchema,
UploadRequestDocumentsFormValues,
} from '@/components/pages/expense/form/ExpenseRequestForm.schema';
interface ExpenseDetailProps {
initialValues?: Expense;
}
const ExpenseDetail: React.FC<ExpenseDetailProps> = ({ initialValues }) => {
const router = useRouter();
const [activeTab, setActiveTab] = useState<string>('request');
// Modal hooks
const deleteModal = useModal();
const approveModal = useModal();
const rejectModal = useModal();
const expenseDetailTabs = useMemo(() => {
const validTabs = [
{
id: 'request',
label: 'Pengajuan',
content: <ExpenseRequestContent initialValues={initialValues} />,
},
];
// Modal loading state
const [isDeleteLoading, setIsDeleteLoading] = useState(false);
const [isApproveLoading, setIsApproveLoading] = useState(false);
const [isRejectLoading, setIsRejectLoading] = useState(false);
const isLatestApprovalRejectedOrDone =
initialValues?.approval &&
(initialValues.approval.action === 'REJECTED' ||
initialValues.approval.step_number === 5);
const formik = useFormik<UploadRequestDocumentsFormValues>({
initialValues: {
request_documents: [],
},
validationSchema: UploadRequestDocumentsFormSchema,
onSubmit: async (values) => {
const addRequestDocumentsRes = await ExpenseApi.uploadRequestDocuments(
initialValues?.id as number,
values.request_documents
);
if (isResponseSuccess(addRequestDocumentsRes)) {
toast.success(addRequestDocumentsRes.message);
window.location.reload();
} else {
toast.error(String(addRequestDocumentsRes?.message));
}
},
});
const deleteExpenseClickHandler = () => {
deleteModal.openModal();
};
const approveClickHandler = () => {
approveModal.openModal();
};
const rejectClickHandler = () => {
rejectModal.openModal();
};
// Modal confirm click handler
const confirmationModalDeleteClickHandler = async () => {
setIsDeleteLoading(true);
try {
await ExpenseApi.delete(initialValues?.id as number);
toast.success('Berhasil menghapus data biaya operasional!');
router.push('/expense');
} catch (error) {
toast.error('Gagal menghapus data biaya operasional!');
} finally {
deleteModal.closeModal();
setIsDeleteLoading(false);
}
};
const confirmationModalApproveClickHandler = async (notes: string) => {
setIsApproveLoading(true);
const approveResponse = await ExpenseApi.approve(
initialValues?.id as number,
notes
);
if (isResponseSuccess(approveResponse)) {
approveModal.closeModal();
toast.success('Berhasil approve pengajuan biaya operasional!');
router.push('/expense');
} else {
approveModal.closeModal();
toast.error('Gagal approve pengajuan biaya operasional!');
if (
initialValues?.latest_approval &&
initialValues?.latest_approval.step_number >= 4 &&
initialValues.latest_approval.action !== 'REJECTED'
) {
validTabs.push({
id: 'realization',
label: 'Realisasi',
content: <ExpenseRealizationContent initialValues={initialValues} />,
});
}
setIsApproveLoading(false);
};
const confirmationModalRejectClickHandler = async (notes: string) => {
setIsRejectLoading(true);
const rejectResponse = await ExpenseApi.reject(
initialValues?.id as number,
notes
);
if (isResponseSuccess(rejectResponse)) {
rejectModal.closeModal();
toast.success('Berhasil reject pengajuan biaya operasional!');
router.push('/expense');
} else {
rejectModal.closeModal();
toast.error('Gagal reject pengajuan biaya operasional!');
}
setIsRejectLoading(false);
};
const requestDocumentsChangeHandler = (val: File[]) => {
formik.setFieldTouched('request_documents', true);
formik.setFieldValue('request_documents', val);
};
const requestDocumentsDeleteHandler = (deletedFileIdx: number) => {
const newRequestDocuments = formik.values.request_documents;
newRequestDocuments?.splice(deletedFileIdx, 1);
formik.setFieldValue('request_documents', newRequestDocuments);
};
return validTabs;
}, [initialValues]);
return (
<>
@@ -171,335 +59,16 @@ const ExpenseDetail: React.FC<ExpenseDetailProps> = ({ initialValues }) => {
</h1>
</header>
<div className='w-full mt-4 flex flex-col gap-4'>
{/* TODO: apply RBAC */}
{!isLatestApprovalRejectedOrDone && (
<div className='w-full max-w-3xl mx-auto flex flex-row justify-end gap-2'>
<Button
variant='outline'
color='success'
onClick={approveClickHandler}
className='w-full sm:w-fit'
>
<Icon icon='material-symbols:check' width={24} height={24} />
Approve
</Button>
<Button
variant='outline'
color='error'
onClick={rejectClickHandler}
className='w-full sm:w-fit'
>
<Icon icon='material-symbols:close' width={24} height={24} />
Reject
</Button>
<Button
type='button'
color='warning'
href={`/expense/detail/edit/?expenseId=${initialValues?.id}`}
className='px-4 ml-2'
>
<Icon icon='mdi:pencil-outline' width={24} height={24} />
Edit
</Button>
<Button
type='button'
color='error'
onClick={deleteExpenseClickHandler}
className='px-4'
>
<Icon
icon='material-symbols:delete-outline-rounded'
width={24}
height={24}
className='justify-start text-sm'
/>
Delete
</Button>
</div>
)}
{/* TODO: add and integrate ApprovalSteps component with API */}
<div className='overflow-x-auto w-full max-w-3xl mx-auto'>
<table className='table table-sm table-zebra'>
<tbody>
<tr>
<th>Nomor PO</th>
<th>:</th>
<td>{initialValues?.po_number ?? '-'}</td>
</tr>
<tr>
<th>Nomor Referensi</th>
<th>:</th>
<td>{initialValues?.reference_number}</td>
</tr>
<tr>
<th>Lokasi</th>
<th>:</th>
<td>{initialValues?.location.name}</td>
</tr>
<tr>
<th>Kandang</th>
<th>:</th>
<td>
{initialValues?.kandangs
.map((item) => item.name)
.join(', ')}
</td>
</tr>
<tr>
<th>Vendor</th>
<th>:</th>
<td>{initialValues?.vendor.name}</td>
</tr>
<tr>
<th>Tanggal Transaksi</th>
<th>:</th>
<td>
{formatDate(
initialValues?.transaction_date,
'DD MMMM YYYY'
)}
</td>
</tr>
<tr>
<th>Tanggal Realisasi</th>
<th>:</th>
<td>
{initialValues?.realization_date
? formatDate(
initialValues?.realization_date,
'DD MMMM YYYY'
)
: '-'}
</td>
</tr>
<tr>
<th>Nama Pengaju</th>
<th>:</th>
<td>{initialValues?.created_user.name}</td>
</tr>
<tr>
<th>Nominal Biaya</th>
<th>:</th>
<td>{formatCurrency(initialValues?.nominal ?? 0)}</td>
</tr>
<tr>
<th>Nominal Sudah Bayar</th>
<th>:</th>
<td>{formatCurrency(initialValues?.paid ?? 0)}</td>
</tr>
<tr>
<th>Nominal Sisa Bayar</th>
<th>:</th>
<td>{formatCurrency(initialValues?.remaining_cost ?? 0)}</td>
</tr>
<tr>
<th>Status Pencairan</th>
<th>:</th>
<td>
<RealizationStatusBadge
approval={initialValues?.approval}
/>
</td>
</tr>
<tr>
<th>Status Biaya</th>
<th>:</th>
<td>
<ExpenseStatusBadge approval={initialValues?.approval} />
</td>
</tr>
<tr>
<th>Dokumen Pengajuan</th>
<th>:</th>
<td>
<div>
{initialValues?.request_documents.length === 0 && '-'}
{initialValues?.request_documents &&
initialValues?.request_documents.length > 0 && (
<ul className='list-disc'>
{initialValues?.request_documents.map(
(requestDocument, requestDocumentIdx) => (
<li key={requestDocumentIdx}>
<Link
href={requestDocument.url}
target='_blank'
rel='noopener noreferrer'
className='text-blue-500 underline'
>
{requestDocument.name}{' '}
<Icon
icon='cuida:open-in-new-tab-outline'
width={12}
height={12}
className='inline'
/>
</Link>
</li>
)
)}
</ul>
)}
</div>
<div className='flex flex-col gap-2'>
<DropFileInput
name='request_documents'
values={formik.values.request_documents}
onChange={requestDocumentsChangeHandler}
onDelete={requestDocumentsDeleteHandler}
accept={{
...ACCEPTED_FILE_TYPE.PDF,
...ACCEPTED_FILE_TYPE.IMAGE,
}}
maxFiles={10}
className={{
wrapper: 'mt-2',
inputWrapper: 'flex items-center',
}}
/>
{formik.values.request_documents &&
formik.values.request_documents.length > 0 && (
<Button
onClick={formik.submitForm}
disabled={formik.isSubmitting}
isLoading={formik.isSubmitting}
className='w-fit self-end'
>
<Icon icon='ic:round-plus' width={24} height={24} />
Tambah
</Button>
)}
</div>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<div className='w-full max-w-5xl mt-8 mx-auto'>
<h2 className='font-bold text-xl text-center'>
Rincian Pengajuan Biaya Operasional
</h2>
<div className='w-full mt-2 flex flex-col gap-4'>
{initialValues?.kandang_expenses.map(
(kandangExpense, kandangExpenseIdx) => {
let expenseGrandTotal = 0;
kandangExpense.expenses.forEach(
(item) => (expenseGrandTotal += item.total_expense)
);
return (
<div
key={kandangExpenseIdx}
className='overflow-x-auto w-full mx-auto'
>
<table className='table table-sm table-zebra'>
<thead>
<tr>
<th
colSpan={5}
className='font-bold text-center text-base-content text-lg'
>
Biaya {kandangExpense.kandang.name}
</th>
</tr>
<tr>
<th>Nonstock</th>
<th>Total Kuantitas</th>
<th>Total Biaya</th>
<th>Catatan</th>
</tr>
</thead>
<tbody>
{kandangExpense.expenses.map(
(expenseItem, expenseIdx) => (
<tr key={expenseIdx}>
<td>{expenseItem.nonstock.name}</td>
<td>{expenseItem.total_quantity}</td>
<td>
{formatCurrency(expenseItem.total_expense)}
</td>
<td className='w-xs'>
{expenseItem.notes ?? '-'}
</td>
</tr>
)
)}
</tbody>
<tfoot>
<tr className='border-y'>
<th colSpan={2} className='text-right'>
Total Biaya Keseluruhan:
</th>
<th colSpan={2}>
{formatCurrency(expenseGrandTotal)}
</th>
</tr>
</tfoot>
</table>
</div>
);
}
)}
</div>
</div>
<Tabs
activeTabId={activeTab}
onTabChange={setActiveTab}
tabs={expenseDetailTabs}
variant='lifted'
className={{
wrapper: 'max-w-5xl mx-auto mt-4',
}}
/>
</section>
<ConfirmationModal
ref={deleteModal.ref}
type='error'
text='Apakah anda yakin ingin menghapus data transfer ke laying ini?'
secondaryButton={{
text: 'Tidak',
}}
primaryButton={{
text: 'Ya',
color: 'error',
isLoading: isDeleteLoading,
onClick: confirmationModalDeleteClickHandler,
}}
/>
<ConfirmationModalWithNotes
ref={approveModal.ref}
type='success'
text='Apakah anda yakin ingin approve data transfer ke laying ini?'
secondaryButton={{
text: 'Tidak',
}}
primaryButton={{
text: 'Ya',
color: 'success',
isLoading: isApproveLoading,
onClick: confirmationModalApproveClickHandler,
}}
/>
<ConfirmationModalWithNotes
ref={rejectModal.ref}
type='error'
text='Apakah anda yakin ingin reject data transfer ke laying ini?'
secondaryButton={{
text: 'Tidak',
}}
primaryButton={{
text: 'Ya',
color: 'error',
isLoading: isRejectLoading,
onClick: confirmationModalRejectClickHandler,
}}
/>
</>
);
};
@@ -0,0 +1,327 @@
import { useFormik } from 'formik';
import toast from 'react-hot-toast';
import Link from 'next/link';
import { Icon } from '@iconify/react';
import Button from '@/components/Button';
import Card from '@/components/Card';
import DropFileInput from '@/components/input/DropFileInput';
import { Expense } from '@/types/api/expense';
import { formatCurrency, formatDate } from '@/lib/helper';
import {
UploadRequestDocumentsFormSchema,
UploadRequestDocumentsFormValues,
} from '@/components/pages/expense/form/ExpenseRequestForm.schema';
import { ExpenseApi } from '@/services/api/expense';
import { isResponseSuccess } from '@/lib/api-helper';
import { ACCEPTED_FILE_TYPE } from '@/config/constant';
interface ExpenseRealizationContentProps {
initialValues?: Expense;
}
const ExpenseRealizationContent = ({
initialValues,
}: ExpenseRealizationContentProps) => {
const formik = useFormik<UploadRequestDocumentsFormValues>({
initialValues: {
documents: [],
},
validationSchema: UploadRequestDocumentsFormSchema,
onSubmit: async (values) => {
const addRealizationDocumentsRes =
await ExpenseApi.uploadRealizationDocuments(
initialValues?.id as number,
values.documents
);
if (isResponseSuccess(addRealizationDocumentsRes)) {
toast.success(addRealizationDocumentsRes.message);
window.location.reload();
} else {
toast.error(String(addRealizationDocumentsRes?.message));
}
},
});
const realizationDocumentsChangeHandler = (val: File[]) => {
formik.setFieldTouched('documents', true);
formik.setFieldValue('documents', val);
};
const realizationDocumentsDeleteHandler = (deletedFileIdx: number) => {
const newRealizationDocuments = formik.values.documents;
newRealizationDocuments?.splice(deletedFileIdx, 1);
formik.setFieldValue('documents', newRealizationDocuments);
};
return (
<div>
<div className='w-full max-w-5xl mx-auto flex flex-col sm:flex-row justify-end gap-2'>
<div className='w-full sm:w-fit sm:ml-2 flex flex-row gap-2 items-center'>
{/* TODO: apply RBAC */}
<Button
type='button'
color='warning'
href={`/expense/realization/edit/?expenseId=${initialValues?.id}`}
className='px-4 grow sm:grow-0'
>
<Icon icon='mdi:pencil-outline' width={24} height={24} />
Edit Realisasi
</Button>
</div>
</div>
<div className='overflow-x-auto w-full max-w-5xl mx-auto'>
<table className='table table-sm table-zebra'>
<tbody>
<tr>
<th>Tanggal Realisasi</th>
<th>:</th>
<td>
{initialValues?.realization_date
? formatDate(initialValues?.realization_date, 'DD MMMM YYYY')
: '-'}
</td>
</tr>
<tr>
<th>Dokumen Realisasi</th>
<th>:</th>
<td>
<div>
{!initialValues?.realization_docs ||
(initialValues?.realization_docs &&
initialValues?.realization_docs.length === 0 &&
'-')}
{initialValues?.realization_docs &&
initialValues?.realization_docs.length > 0 && (
<ul className='list-disc'>
{initialValues?.realization_docs.map(
(realizationDocument, realizationDocumentIdx) => (
<li key={realizationDocumentIdx}>
<Link
href={realizationDocument.path}
target='_blank'
rel='noopener noreferrer'
className='text-blue-500 underline'
>
{realizationDocument.path}{' '}
<Icon
icon='cuida:open-in-new-tab-outline'
width={12}
height={12}
className='inline'
/>
</Link>
</li>
)
)}
</ul>
)}
</div>
<div className='flex flex-col gap-2'>
<DropFileInput
name='documents'
values={formik.values.documents}
onChange={realizationDocumentsChangeHandler}
onDelete={realizationDocumentsDeleteHandler}
accept={{
...ACCEPTED_FILE_TYPE.PDF,
...ACCEPTED_FILE_TYPE.IMAGE,
}}
maxFiles={10}
className={{
wrapper: 'mt-2',
inputWrapper: 'flex items-center',
}}
/>
{formik.values.documents &&
formik.values.documents.length > 0 && (
<Button
onClick={formik.submitForm}
disabled={formik.isSubmitting}
isLoading={formik.isSubmitting}
className='w-fit self-end'
>
<Icon icon='ic:round-plus' width={24} height={24} />
Tambah
</Button>
)}
</div>
</td>
</tr>
</tbody>
</table>
</div>
<div className='w-full max-w-5xl mt-8 mx-auto'>
<div className='flex flex-row gap-4'>
<Card variant='bordered' size='sm' className={{ wrapper: 'grow' }}>
<div className='w-full flex flex-col gap-2'>
<h3 className='text-sm'>Nominal Pengajuan</h3>
<span className='text-xl'>
{formatCurrency(initialValues?.total_pengajuan as number)}
</span>
<span className='text-sm'>
Terbayar{' '}
{formatCurrency(initialValues?.total_realisasi as number)}
</span>
</div>
</Card>
<Card variant='bordered' size='sm' className={{ wrapper: 'grow' }}>
<div className='w-full flex flex-col gap-2'>
<h3 className='text-sm'>Nominal Realisasi</h3>
<span className='text-xl'>
{formatCurrency(initialValues?.total_realisasi as number)}
</span>
<span className='text-sm'>
Selisih{' '}
{formatCurrency(
(initialValues?.total_realisasi as number) -
(initialValues?.total_pengajuan as number)
)}
</span>
</div>
</Card>
</div>
</div>
<div className='w-full max-w-5xl mt-8 mx-auto'>
<h2 className='font-bold text-xl text-center'>
Rincian Pengajuan Biaya Operasional
</h2>
<div className='w-full mt-2 flex flex-col gap-4'>
{initialValues?.kandangs.map((kandangExpense, kandangExpenseIdx) => {
let expenseGrandTotal = 0;
kandangExpense.pengajuans?.forEach(
(item) => (expenseGrandTotal += item.total_price)
);
return (
<div
key={kandangExpenseIdx}
className='overflow-x-auto w-full mx-auto'
>
<table className='table table-sm table-zebra'>
<thead>
<tr>
<th
colSpan={5}
className='font-bold text-center text-base-content text-lg'
>
Biaya {kandangExpense.name}
</th>
</tr>
<tr>
<th>Nonstock</th>
<th>Total Kuantitas</th>
<th>Total Biaya</th>
<th>Catatan</th>
</tr>
</thead>
<tbody>
{kandangExpense.pengajuans?.map(
(pengajuanItem, pengajuanIdx) => (
<tr key={pengajuanIdx}>
<td>{pengajuanItem.nonstock.name}</td>
<td>{pengajuanItem.qty}</td>
<td>{formatCurrency(pengajuanItem.total_price)}</td>
<td className='w-xs'>{pengajuanItem.note ?? '-'}</td>
</tr>
)
)}
</tbody>
<tfoot>
<tr className='border-y'>
<th colSpan={2} className='text-right'>
Total Biaya Keseluruhan:
</th>
<th colSpan={2}>{formatCurrency(expenseGrandTotal)}</th>
</tr>
</tfoot>
</table>
</div>
);
})}
</div>
</div>
<div className='w-full max-w-5xl mt-8 mx-auto'>
<h2 className='font-bold text-xl text-center'>
Rincian Realisasi Biaya Operasional
</h2>
<div className='w-full mt-2 flex flex-col gap-4'>
{initialValues?.kandangs.map((kandangExpense, kandangExpenseIdx) => {
let expenseGrandTotal = 0;
kandangExpense.realisasi?.forEach(
(item) => (expenseGrandTotal += item.total_price)
);
return (
<div
key={kandangExpenseIdx}
className='overflow-x-auto w-full mx-auto'
>
<table className='table table-sm table-zebra'>
<thead>
<tr>
<th
colSpan={5}
className='font-bold text-center text-base-content text-lg'
>
Biaya {kandangExpense.name}
</th>
</tr>
<tr>
<th>Nonstock</th>
<th>Total Kuantitas</th>
<th>Total Biaya</th>
<th>Catatan</th>
</tr>
</thead>
<tbody>
{kandangExpense.realisasi?.map(
(realisasiItem, realisasiIdx) => (
<tr key={realisasiIdx}>
<td>{realisasiItem.nonstock.name}</td>
<td>{realisasiItem.qty}</td>
<td>{formatCurrency(realisasiItem.total_price)}</td>
<td className='w-xs'>{realisasiItem.note ?? '-'}</td>
</tr>
)
)}
</tbody>
<tfoot>
<tr className='border-y'>
<th colSpan={2} className='text-right'>
Total Biaya Keseluruhan:
</th>
<th colSpan={2}>{formatCurrency(expenseGrandTotal)}</th>
</tr>
</tfoot>
</table>
</div>
);
})}
</div>
</div>
</div>
);
};
export default ExpenseRealizationContent;
@@ -0,0 +1,655 @@
'use client';
import { useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import { useFormik } from 'formik';
import useSWR from 'swr';
import toast from 'react-hot-toast';
import { Icon } from '@iconify/react';
import Link from 'next/link';
import Button from '@/components/Button';
import RealizationStatusBadge from '@/components/pages/expense/RealizationStatusBadge';
import ExpenseStatusBadge from '@/components/pages/expense/ExpenseStatusBadge';
import DropFileInput from '@/components/input/DropFileInput';
import ApprovalSteps, {
useApprovalSteps,
} from '@/components/pages/ApprovalSteps';
import { useModal } from '@/components/Modal';
import ConfirmationModal from '@/components/modal/ConfirmationModal';
import ConfirmationModalWithNotes from '@/components/modal/ConfirmationModalWithNotes';
import ExpensePDFPreviewButton from '@/components/pages/expense//pdf/ExpensePDFButton';
import { Expense } from '@/types/api/expense';
import { formatCurrency, formatDate } from '@/lib/helper';
import {
UploadRequestDocumentsFormSchema,
UploadRequestDocumentsFormValues,
} from '@/components/pages/expense/form/ExpenseRequestForm.schema';
import { ACCEPTED_FILE_TYPE } from '@/config/constant';
import { ExpenseApi } from '@/services/api/expense';
import { isResponseSuccess } from '@/lib/api-helper';
import { EXPENSE_REQUEST_APPROVAL_LINE } from '@/config/approval-line';
import { BaseApiResponse } from '@/types/api/api-general';
interface ExpenseRequestContentProps {
initialValues?: Expense;
}
const ExpenseRequestContent = ({
initialValues,
}: ExpenseRequestContentProps) => {
const router = useRouter();
const { approvals: approvalHistory, isLoading: isLoadingApprovalHistory } =
useApprovalSteps({
latestApproval: initialValues?.latest_approval,
approvalLines: EXPENSE_REQUEST_APPROVAL_LINE,
moduleName: 'EXPENSES',
moduleId: initialValues?.id.toString() ?? '',
params: {
page: 1,
limit: 100,
},
});
const isLatestApprovalRejected =
initialValues?.latest_approval.action === 'REJECTED';
const isLatestApprovalRejectedOrDone =
isLatestApprovalRejected ||
initialValues?.latest_approval.step_number === 5;
const isCurrentApprovalOnManager =
!isLatestApprovalRejected &&
initialValues?.latest_approval.step_number === 1;
const isCurrentApprovalOnFinance =
!isLatestApprovalRejected &&
initialValues?.latest_approval.step_number === 2;
const isCurrentApprovalOnRealization =
!isLatestApprovalRejected &&
initialValues?.latest_approval.step_number === 4;
const showEditButton =
initialValues?.latest_approval.step_number !== 5 &&
(initialValues?.latest_approval.step_number === 1 ||
initialValues?.latest_approval.step_number === 2 ||
initialValues?.latest_approval.step_number === 3);
const showRejectButton =
!isLatestApprovalRejected &&
(initialValues?.latest_approval.step_number === 1 ||
initialValues?.latest_approval.step_number === 2);
const isExpenseCanBeRealized =
!isLatestApprovalRejected &&
initialValues?.latest_approval.step_number === 3;
// Modal hooks
const deleteModal = useModal();
const completeModal = useModal();
const approveModal = useModal();
const rejectModal = useModal();
// Modal loading state
const [isDeleteLoading, setIsDeleteLoading] = useState(false);
const [isCompleteLoading, setIsCompleteLoading] = useState(false);
const [isApproveLoading, setIsApproveLoading] = useState(false);
const [isRejectLoading, setIsRejectLoading] = useState(false);
const formik = useFormik<UploadRequestDocumentsFormValues>({
initialValues: {
documents: [],
},
validationSchema: UploadRequestDocumentsFormSchema,
onSubmit: async (values) => {
const addRequestDocumentsRes = await ExpenseApi.uploadRequestDocuments(
initialValues?.id as number,
values.documents
);
if (isResponseSuccess(addRequestDocumentsRes)) {
toast.success(addRequestDocumentsRes.message);
window.location.reload();
} else {
toast.error(String(addRequestDocumentsRes?.message));
}
},
});
const deleteExpenseClickHandler = () => {
deleteModal.openModal();
};
const completeExpenseClickHandler = () => {
completeModal.openModal();
};
const approveClickHandler = () => {
approveModal.openModal();
};
const rejectClickHandler = () => {
rejectModal.openModal();
};
// Modal confirm click handler
const confirmationModalDeleteClickHandler = async () => {
setIsDeleteLoading(true);
try {
await ExpenseApi.delete(initialValues?.id as number);
toast.success('Berhasil menghapus data biaya operasional!');
router.push('/expense');
} catch (error) {
toast.error('Gagal menghapus data biaya operasional!');
} finally {
deleteModal.closeModal();
setIsDeleteLoading(false);
}
};
const confirmationModalCompleteClickHandler = async () => {
setIsCompleteLoading(true);
const completeRes = await ExpenseApi.complete(initialValues?.id as number);
if (isResponseSuccess(completeRes)) {
toast.success(completeRes.message);
router.push('/expense');
} else {
toast.error(completeRes?.message as string);
}
completeModal.closeModal();
setIsCompleteLoading(false);
};
const confirmationModalApproveClickHandler = async (notes: string) => {
setIsApproveLoading(true);
let approveResponse: BaseApiResponse<Expense> | undefined = undefined;
if (isCurrentApprovalOnManager) {
approveResponse = await ExpenseApi.approveManager(
initialValues.id,
notes
);
}
if (isCurrentApprovalOnFinance) {
approveResponse = await ExpenseApi.approveFinance(
initialValues.id,
notes
);
}
if (isResponseSuccess(approveResponse)) {
approveModal.closeModal();
toast.success(approveResponse?.message);
router.push('/expense');
} else {
approveModal.closeModal();
toast.error(approveResponse?.message as string);
}
setIsApproveLoading(false);
};
const confirmationModalRejectClickHandler = async (notes: string) => {
setIsRejectLoading(true);
let rejectResponse: BaseApiResponse<Expense> | undefined = undefined;
if (isCurrentApprovalOnManager) {
rejectResponse = await ExpenseApi.rejectManager(initialValues.id, notes);
}
if (isCurrentApprovalOnFinance) {
rejectResponse = await ExpenseApi.rejectFinance(initialValues.id, notes);
}
if (isResponseSuccess(rejectResponse)) {
rejectModal.closeModal();
toast.success(rejectResponse.message);
router.push('/expense');
} else {
rejectModal.closeModal();
toast.error(rejectResponse?.message as string);
}
setIsRejectLoading(false);
};
const requestDocumentsChangeHandler = (val: File[]) => {
formik.setFieldTouched('documents', true);
formik.setFieldValue('documents', val);
};
const requestDocumentsDeleteHandler = (deletedFileIdx: number) => {
const newRequestDocuments = formik.values.documents;
newRequestDocuments?.splice(deletedFileIdx, 1);
formik.setFieldValue('documents', newRequestDocuments);
};
return (
<>
<div>
{initialValues && !isLoadingApprovalHistory && approvalHistory && (
<div className='w-full max-w-5xl my-4 mx-auto'>
<ApprovalSteps approvals={approvalHistory} />
</div>
)}
<div className='w-full mt-4 flex flex-col gap-4'>
{/* TODO: apply RBAC */}
<div className='w-full max-w-5xl mx-auto flex flex-col sm:flex-row justify-end gap-2'>
{isCurrentApprovalOnManager && (
<Button
variant='outline'
color='info'
onClick={approveClickHandler}
className='w-full sm:w-fit'
>
<Icon icon='lucide-lab:farm' width={24} height={24} />
Approve Manager
</Button>
)}
{isCurrentApprovalOnFinance && (
<Button
variant='outline'
color='success'
onClick={approveClickHandler}
className='w-full sm:w-fit'
>
<Icon icon='tdesign:money' width={24} height={24} />
Approve Finance
</Button>
)}
{isCurrentApprovalOnRealization && (
<Button
variant='outline'
color='success'
onClick={completeExpenseClickHandler}
className='w-full sm:w-fit'
>
<Icon
icon='material-symbols:done-all-rounded'
width={24}
height={24}
/>
Selesai
</Button>
)}
{showRejectButton && (
<Button
variant='outline'
color='error'
onClick={rejectClickHandler}
className='w-full:w-fit'
>
<Icon icon='material-symbols:close' width={24} height={24} />
Reject
</Button>
)}
{isExpenseCanBeRealized && (
<Button
variant='outline'
color='info'
href={`/expense/realization/?expenseId=${initialValues?.id}`}
className='w-full sm:w-fit'
>
<Icon
icon='material-symbols:money-bag-rounded'
width={24}
height={24}
/>
Realisasi
</Button>
)}
<div className='w-full sm:w-fit sm:ml-2 flex flex-row gap-2 items-center'>
{showEditButton && (
<Button
type='button'
color='warning'
href={`/expense/detail/edit/?expenseId=${initialValues?.id}`}
className='px-4 grow sm:grow-0'
>
<Icon icon='mdi:pencil-outline' width={24} height={24} />
Edit
</Button>
)}
<Button
type='button'
color='error'
onClick={deleteExpenseClickHandler}
className='px-4 grow sm:grow-0'
>
<Icon
icon='material-symbols:delete-outline-rounded'
width={24}
height={24}
className='justify-start text-sm'
/>
Delete
</Button>
</div>
</div>
<div className='overflow-x-auto w-full max-w-5xl mx-auto'>
<table className='table table-sm table-zebra'>
<tbody>
<tr>
<th>Nomor PO</th>
<th>:</th>
<td>
{!initialValues?.po_number && '-'}
{initialValues?.po_number && (
<ExpensePDFPreviewButton expense={initialValues} />
)}
</td>
</tr>
<tr>
<th>Nomor Referensi</th>
<th>:</th>
<td>{initialValues?.reference_number}</td>
</tr>
<tr>
<th>Kategori</th>
<th>:</th>
<td>
{initialValues?.category === 'BOP'
? 'Biaya Operasional'
: 'Non Biaya Operasional'}
</td>
</tr>
<tr>
<th>Lokasi</th>
<th>:</th>
<td>{initialValues?.location.name}</td>
</tr>
<tr>
<th>Kandang</th>
<th>:</th>
<td>
{initialValues?.kandangs
.map((item) => item.name)
.join(', ')}
</td>
</tr>
<tr>
<th>Vendor</th>
<th>:</th>
<td>{initialValues?.supplier.name}</td>
</tr>
<tr>
<th>Tanggal Transaksi</th>
<th>:</th>
<td>
{formatDate(initialValues?.expense_date, 'DD MMMM YYYY')}
</td>
</tr>
<tr>
<th>Tanggal Realisasi</th>
<th>:</th>
<td>
{initialValues?.realization_date
? formatDate(
initialValues?.realization_date,
'DD MMMM YYYY'
)
: '-'}
</td>
</tr>
<tr>
<th>Nama Pengaju</th>
<th>:</th>
<td>{initialValues?.created_user.name}</td>
</tr>
<tr>
<th>Nominal Biaya</th>
<th>:</th>
<td>{formatCurrency(initialValues?.grand_total ?? 0)}</td>
</tr>
<tr>
<th>Status Pencairan</th>
<th>:</th>
<td>
<RealizationStatusBadge
approval={initialValues?.latest_approval}
/>
</td>
</tr>
<tr>
<th>Status Biaya</th>
<th>:</th>
<td>
<ExpenseStatusBadge
approval={initialValues?.latest_approval}
/>
</td>
</tr>
<tr>
<th>Dokumen Pengajuan</th>
<th>:</th>
<td>
<div>
{!initialValues?.documents ||
(initialValues?.documents &&
initialValues?.documents.length === 0 &&
'-')}
{initialValues?.documents &&
initialValues?.documents.length > 0 && (
<ul className='list-disc'>
{initialValues?.documents.map(
(requestDocument, requestDocumentIdx) => (
<li key={requestDocumentIdx}>
<Link
href={requestDocument.path}
target='_blank'
rel='noopener noreferrer'
className='text-blue-500 underline'
>
{requestDocument.path}{' '}
<Icon
icon='cuida:open-in-new-tab-outline'
width={12}
height={12}
className='inline'
/>
</Link>
</li>
)
)}
</ul>
)}
</div>
<div className='flex flex-col gap-2'>
<DropFileInput
name='documents'
values={formik.values.documents}
onChange={requestDocumentsChangeHandler}
onDelete={requestDocumentsDeleteHandler}
accept={{
...ACCEPTED_FILE_TYPE.PDF,
...ACCEPTED_FILE_TYPE.IMAGE,
}}
maxFiles={10}
className={{
wrapper: 'mt-2',
inputWrapper: 'flex items-center',
}}
/>
{formik.values.documents &&
formik.values.documents.length > 0 && (
<Button
onClick={formik.submitForm}
disabled={formik.isSubmitting}
isLoading={formik.isSubmitting}
className='w-fit self-end'
>
<Icon icon='ic:round-plus' width={24} height={24} />
Tambah
</Button>
)}
</div>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<div className='w-full max-w-5xl mt-8 mx-auto'>
<h2 className='font-bold text-xl text-center'>
Rincian Pengajuan Biaya Operasional
</h2>
<div className='w-full mt-2 flex flex-col gap-4'>
{initialValues?.kandangs.map(
(kandangExpense, kandangExpenseIdx) => {
let expenseGrandTotal = 0;
kandangExpense.pengajuans?.forEach(
(item) => (expenseGrandTotal += item.total_price)
);
return (
<div
key={kandangExpenseIdx}
className='overflow-x-auto w-full mx-auto'
>
<table className='table table-sm table-zebra'>
<thead>
<tr>
<th
colSpan={5}
className='font-bold text-center text-base-content text-lg'
>
Biaya {kandangExpense.name}
</th>
</tr>
<tr>
<th>Nonstock</th>
<th>Total Kuantitas</th>
<th>Total Biaya</th>
<th>Catatan</th>
</tr>
</thead>
<tbody>
{kandangExpense.pengajuans?.map(
(pengajuanItem, pengajuanIdx) => (
<tr key={pengajuanIdx}>
<td>{pengajuanItem.nonstock.name}</td>
<td>{pengajuanItem.qty}</td>
<td>
{formatCurrency(pengajuanItem.total_price)}
</td>
<td className='w-xs'>
{pengajuanItem.note ?? '-'}
</td>
</tr>
)
)}
</tbody>
<tfoot>
<tr className='border-y'>
<th colSpan={2} className='text-right'>
Total Biaya Keseluruhan:
</th>
<th colSpan={2}>
{formatCurrency(expenseGrandTotal)}
</th>
</tr>
</tfoot>
</table>
</div>
);
}
)}
</div>
</div>
</div>
<ConfirmationModal
ref={deleteModal.ref}
type='error'
text='Apakah anda yakin ingin menghapus data biaya operasional ini?'
secondaryButton={{
text: 'Tidak',
}}
primaryButton={{
text: 'Ya',
color: 'error',
isLoading: isDeleteLoading,
onClick: confirmationModalDeleteClickHandler,
}}
/>
<ConfirmationModal
ref={completeModal.ref}
type='success'
text='Apakah anda yakin ingin menyelesaikan biaya operasional ini?'
secondaryButton={{
text: 'Tidak',
}}
primaryButton={{
text: 'Ya',
color: 'success',
isLoading: isCompleteLoading,
onClick: confirmationModalCompleteClickHandler,
}}
/>
<ConfirmationModalWithNotes
ref={approveModal.ref}
type='success'
text='Apakah anda yakin ingin approve data biaya operasional ini?'
secondaryButton={{
text: 'Tidak',
}}
primaryButton={{
text: 'Ya',
color: 'success',
isLoading: isApproveLoading,
onClick: confirmationModalApproveClickHandler,
}}
/>
<ConfirmationModalWithNotes
ref={rejectModal.ref}
type='error'
text='Apakah anda yakin ingin reject data biaya operasional ini?'
secondaryButton={{
text: 'Tidak',
}}
primaryButton={{
text: 'Ya',
color: 'error',
isLoading: isRejectLoading,
onClick: confirmationModalRejectClickHandler,
}}
/>
</>
);
};
export default ExpenseRequestContent;
+178 -104
View File
@@ -1,6 +1,6 @@
'use client';
import { ChangeEventHandler, useEffect, useState } from 'react';
import { ChangeEventHandler, useEffect, useMemo, useState } from 'react';
import useSWR from 'swr';
import {
CellContext,
@@ -31,13 +31,14 @@ import DateInput from '@/components/input/DateInput';
import { Expense } from '@/types/api/expense';
import { ExpenseApi } from '@/services/api/expense';
import { cn, formatCurrency } from '@/lib/helper';
import { cn, formatCurrency, formatDate } from '@/lib/helper';
import { isResponseSuccess } from '@/lib/api-helper';
import { useTableFilter } from '@/services/hooks/useTableFilter';
import { ROWS_OPTIONS } from '@/config/constant';
import { LocationApi, SupplierApi } from '@/services/api/master-data';
import { Location } from '@/types/api/master-data/location';
import { Supplier } from '@/types/api/master-data/supplier';
import { BaseApiResponse } from '@/types/api/api-general';
const RowOptionsMenu = ({
type = 'dropdown',
@@ -53,66 +54,57 @@ const RowOptionsMenu = ({
deleteClickHandler: () => void;
}) => {
const showEditButton =
props.row.original.approval.action !== 'REJECTED' &&
props.row.original.approval.step_number !== 5 &&
props.row.original.approval.action !== 'APPROVED';
const showDeleteButton = showEditButton;
props.row.original.latest_approval.step_number !== 5 &&
(props.row.original.latest_approval.step_number === 1 ||
props.row.original.latest_approval.step_number === 2 ||
props.row.original.latest_approval.step_number === 3);
// TODO: apply RBAC
const showApproveButton = showEditButton;
const showRejectButton = showEditButton;
const showRealizationButton =
props.row.original.latest_approval.action !== 'REJECTED' &&
props.row.original.latest_approval.step_number === 3;
return (
<RowOptionsMenuWrapper type={type}>
<Button
href={`/expense/detail/?expenseId=${props.row.original.id}`}
variant='ghost'
color='primary'
className='justify-start text-sm'
>
<Icon icon='mdi:eye-outline' width={16} height={16} />
Detail
</Button>
{showEditButton && (
<div className='w-full max-h-40 overflow-auto flex flex-col gap-1'>
<Button
href={`/expense/detail/edit/?expenseId=${props.row.original.id}`}
href={`/expense/detail/?expenseId=${props.row.original.id}`}
variant='ghost'
color='warning'
color='primary'
className='justify-start text-sm'
>
<Icon icon='material-symbols:edit-outline' width={16} height={16} />
Edit
<Icon icon='mdi:eye-outline' width={16} height={16} />
Detail
</Button>
)}
{/* TODO: apply RBAC */}
{showApproveButton && (
<Button
variant='ghost'
color='success'
onClick={approveClickHandler}
className='justify-start text-sm'
>
<Icon icon='material-symbols:check' width={24} height={24} />
Approve
</Button>
)}
{showEditButton && (
<Button
href={`/expense/detail/edit/?expenseId=${props.row.original.id}`}
variant='ghost'
color='warning'
className='justify-start text-sm'
>
<Icon icon='material-symbols:edit-outline' width={16} height={16} />
Edit
</Button>
)}
{showRejectButton && (
<Button
variant='ghost'
color='error'
onClick={rejectClickHandler}
className='justify-start text-sm'
>
<Icon icon='material-symbols:close' width={24} height={24} />
Reject
</Button>
)}
{showRealizationButton && (
<Button
href={`/expense/realization/?expenseId=${props.row.original.id}`}
variant='ghost'
color='info'
className='justify-start text-sm text-info focus-visible:text-info-content hover:text-info-content'
>
<Icon
icon='material-symbols:money-bag-rounded'
width={16}
height={16}
/>
Realisasi
</Button>
)}
{showDeleteButton && (
<Button
onClick={deleteClickHandler}
variant='ghost'
@@ -127,7 +119,7 @@ const RowOptionsMenu = ({
/>
Delete
</Button>
)}
</div>
</RowOptionsMenuWrapper>
);
};
@@ -178,6 +170,7 @@ const ExpensesTable = () => {
undefined
);
const [isDeleteLoading, setIsDeleteLoading] = useState(false);
const [isCompleteLoading, setIsCompleteLoading] = useState(false);
const [isApproveLoading, setIsApproveLoading] = useState(false);
const [isRejectLoading, setIsRejectLoading] = useState(false);
@@ -187,6 +180,57 @@ const ExpensesTable = () => {
parseInt(item)
);
const isAllSelectedRowLatestApprovalOnManager = useMemo(() => {
return selectedRowIds.every((rowId) => {
if (!isResponseSuccess(expenses)) return false;
const expenseItem = expenses.data.find((item) => item.id === rowId);
const isLatestApprovalRejected =
expenseItem?.latest_approval.action === 'REJECTED';
const isCurrentApprovalOnManager =
!isLatestApprovalRejected &&
expenseItem?.latest_approval.step_number === 1;
return isCurrentApprovalOnManager;
});
}, [expenses, selectedRowIds]);
const isAllSelectedRowLatestApprovalOnFinance = useMemo(() => {
return selectedRowIds.every((rowId) => {
if (!isResponseSuccess(expenses)) return false;
const expenseItem = expenses.data.find((item) => item.id === rowId);
const isLatestApprovalRejected =
expenseItem?.latest_approval.action === 'REJECTED';
const isCurrentApprovalOnFinance =
!isLatestApprovalRejected &&
expenseItem?.latest_approval.step_number === 2;
return isCurrentApprovalOnFinance;
});
}, [expenses, selectedRowIds]);
const isAllSelectedRowLatestApprovalOnRealization = useMemo(() => {
return selectedRowIds.every((rowId) => {
if (!isResponseSuccess(expenses)) return false;
const expenseItem = expenses.data.find((item) => item.id === rowId);
const isLatestApprovalRejected =
expenseItem?.latest_approval.action === 'REJECTED';
const isCurrentApprovalOnRealization =
!isLatestApprovalRejected &&
expenseItem?.latest_approval.step_number === 4;
return isCurrentApprovalOnRealization;
});
}, [expenses, selectedRowIds]);
const expensesColumns: ColumnDef<Expense>[] = [
{
id: 'select',
@@ -202,7 +246,8 @@ const ExpensesTable = () => {
),
cell: ({ row }) => {
const isCheckboxDisabled =
!row.getCanSelect() || row.original.approval.action === 'REJECTED';
!row.getCanSelect() ||
row.original.latest_approval.action === 'REJECTED';
return (
<div>
@@ -218,61 +263,52 @@ const ExpensesTable = () => {
},
},
{
accessorKey: 'transaction_date',
accessorKey: 'expense_date',
header: 'Tanggal Pengajuan',
cell: (props) =>
props.row.original.expense_date
? formatDate(props.row.original.expense_date, 'DD MMM YYYY')
: '-',
},
{
accessorKey: 'realization_date',
header: 'Tanggal Realisasi',
cell: (props) => props.getValue() ?? '-',
cell: (props) =>
props.row.original.realization_date
? formatDate(props.row.original.realization_date, 'DD MMM YYYY')
: '-',
},
{
accessorKey: 'location',
header: 'Lokasi',
cell: (props) => props.row.original.location.name ?? '-',
cell: (props) => props.row.original.location?.name ?? '-',
},
{
accessorFn: (row) => row.created_user.name ?? '-',
header: 'Nama Pengaju',
},
{
accessorFn: (row) => row.vendor.name ?? '-',
accessorFn: (row) => row.supplier.name ?? '-',
header: 'Vendor',
},
{
accessorKey: 'nominal',
accessorKey: 'grand_total',
header: 'Nominal',
cell: (props) =>
props.row.original.nominal
? `Rp${formatCurrency(props.row.original.nominal)}`
: '-',
},
{
accessorKey: 'paid',
header: 'Sudah Bayar',
cell: (props) =>
props.row.original.paid
? `Rp${formatCurrency(props.row.original.paid)}`
: '-',
},
{
accessorKey: 'remaining_cost',
header: 'Sisa Bayar',
cell: (props) =>
props.row.original.remaining_cost
? `Rp${formatCurrency(props.row.original.remaining_cost)}`
props.row.original.grand_total
? formatCurrency(props.row.original.grand_total)
: '-',
},
{
header: 'Status Pencairan',
cell: (props) => (
<RealizationStatusBadge approval={props.row.original.approval} />
<RealizationStatusBadge approval={props.row.original.latest_approval} />
),
},
{
header: 'Status BOP',
cell: (props) => (
<ExpenseStatusBadge approval={props.row.original.approval} />
<ExpenseStatusBadge approval={props.row.original.latest_approval} />
),
},
{
@@ -283,7 +319,7 @@ const ExpensesTable = () => {
const currentRowRelativeIndex =
currentPageRows.findIndex((r) => r.id === props.row.id) + 1;
const isLast2Rows = currentRowRelativeIndex > currentPageSize - 2;
const isLast2Rows = currentRowRelativeIndex > currentPageSize - 3;
const approveClickHandler = () => {
setSelectedExpense(props.row.original);
@@ -314,7 +350,7 @@ const ExpensesTable = () => {
return (
<>
{currentPageSize > 2 && (
{currentPageSize > 3 && (
<RowDropdownOptions isLast2Rows={isLast2Rows}>
<RowOptionsMenu
type='dropdown'
@@ -326,10 +362,10 @@ const ExpensesTable = () => {
</RowDropdownOptions>
)}
{currentPageSize <= 2 && (
{currentPageSize <= 3 && (
<RowCollapseOptions>
<RowOptionsMenu
type='dropdown'
type='collapse'
props={props}
approveClickHandler={approveClickHandler}
rejectClickHandler={rejectClickHandler}
@@ -346,9 +382,20 @@ const ExpensesTable = () => {
const tableEnableRowSelectionHandler: (row: Row<Expense>) => boolean = (
row
) => {
return row.original.approval.action !== 'REJECTED';
return (
row.original.latest_approval.action !== 'REJECTED' &&
row.original.latest_approval.step_number !== 5
);
};
// const bulkApproveClickHandler = () => {
// approveModal.openModal();
// };
// const bulkRejectClickHandler = () => {
// rejectModal.openModal();
// };
const bulkApproveClickHandler = () => {
approveModal.openModal();
};
@@ -371,17 +418,26 @@ const ExpensesTable = () => {
const confirmationModalApproveClickHandler = async (notes: string) => {
setIsApproveLoading(true);
const bulkApproveResponse = await ExpenseApi.bulkApprove(
selectedRowIds,
notes
);
let bulkApproveResponse: BaseApiResponse<Expense> | undefined = undefined;
if (isAllSelectedRowLatestApprovalOnManager) {
bulkApproveResponse = await ExpenseApi.bulkApproveManager(
selectedRowIds,
notes
);
} else if (isAllSelectedRowLatestApprovalOnFinance) {
bulkApproveResponse = await ExpenseApi.bulkApproveFinance(
selectedRowIds,
notes
);
}
if (isResponseSuccess(bulkApproveResponse)) {
refreshExpenses();
approveModal.closeModal();
toast.success(
`Berhasil approve ${selectedRowIds.length} data transfer ke laying!`
`Berhasil approve ${selectedRowIds.length} data biaya operasional!`
);
setRowSelection({});
@@ -389,7 +445,7 @@ const ExpensesTable = () => {
approveModal.closeModal();
toast.error(
`Gagal approve ${selectedRowIds.length} data transfer ke laying!`
`Gagal approve ${selectedRowIds.length} data biaya operasional!`
);
}
@@ -399,24 +455,33 @@ const ExpensesTable = () => {
const confirmationModalRejectClickHandler = async (notes: string) => {
setIsRejectLoading(true);
const bulkRejectResponse = await ExpenseApi.bulkReject(
selectedRowIds,
notes
);
let bulkRejectResponse: BaseApiResponse<Expense> | undefined = undefined;
if (isAllSelectedRowLatestApprovalOnManager) {
bulkRejectResponse = await ExpenseApi.bulkRejectManager(
selectedRowIds,
notes
);
} else if (isAllSelectedRowLatestApprovalOnFinance) {
bulkRejectResponse = await ExpenseApi.bulkRejectFinance(
selectedRowIds,
notes
);
}
if (isResponseSuccess(bulkRejectResponse)) {
refreshExpenses();
rejectModal.closeModal();
toast.success(
`Berhasil reject ${selectedRowIds.length} data transfer ke laying!`
`Berhasil reject ${selectedRowIds.length} data biaya operasional!`
);
setRowSelection({});
} else {
rejectModal.closeModal();
toast.error(
`Gagal reject ${selectedRowIds.length} data transfer ke laying!`
`Gagal reject ${selectedRowIds.length} data biaya operasional!`
);
}
@@ -506,27 +571,36 @@ const ExpensesTable = () => {
{selectedRowIds.length > 0 && (
<>
{/* TODO: apply RBAC */}
<Button
variant='outline'
color='info'
onClick={bulkApproveClickHandler}
disabled={!isAllSelectedRowLatestApprovalOnManager}
className='w-full sm:w-fit'
>
<Icon icon='lucide-lab:farm' width={24} height={24} />
Approve Manager
</Button>
<Button
variant='outline'
color='success'
onClick={bulkApproveClickHandler}
disabled={selectedRowIds.length === 0}
disabled={!isAllSelectedRowLatestApprovalOnFinance}
className='w-full sm:w-fit'
>
<Icon
icon='material-symbols:check'
width={24}
height={24}
/>
Approve
<Icon icon='tdesign:money' width={24} height={24} />
Approve Finance
</Button>
<Button
variant='outline'
color='error'
onClick={bulkRejectClickHandler}
disabled={selectedRowIds.length === 0}
disabled={
!isAllSelectedRowLatestApprovalOnManager &&
!isAllSelectedRowLatestApprovalOnFinance
}
className='w-full sm:w-fit'
>
<Icon
@@ -666,7 +740,7 @@ const ExpensesTable = () => {
<ConfirmationModalWithNotes
ref={approveModal.ref}
type='success'
text={`Apakah anda yakin ingin approve data biaya operasional ini (${selectedRowIds.length} data)?`}
text='Apakah anda yakin ingin approve data biaya operasional ini?'
secondaryButton={{
text: 'Tidak',
}}
@@ -681,7 +755,7 @@ const ExpensesTable = () => {
<ConfirmationModalWithNotes
ref={rejectModal.ref}
type='error'
text={`Apakah anda yakin ingin reject data biaya operasional ini (${selectedRowIds.length} data)?`}
text='Apakah anda yakin ingin reject data biaya operasional ini?'
secondaryButton={{
text: 'Tidak',
}}
@@ -0,0 +1,181 @@
import * as Yup from 'yup';
import { Expense } from '@/types/api/expense';
import { formatDate } from '@/lib/helper';
type ExpenseRealizationFormSchemaType = {
category?: {
value: 'BOP' | 'NON-BOP';
label: 'BOP' | 'NON-BOP';
};
location?: {
value: number;
label: string;
};
realization_date?: string;
kandangs?: { id: number; name: string }[];
supplier?: {
value: number;
label: string;
};
existing_documents?: { name: string; url: string }[];
documents?: File[];
realizations: {
kandang_id: number;
cost_items: {
nonstock?: {
value: number;
label: string;
};
quantity?: number;
total_cost?: number;
notes?: string;
}[];
}[];
};
export const ExpenseRealizationFormSchema: Yup.ObjectSchema<ExpenseRealizationFormSchemaType> =
Yup.object({
category: Yup.object({
value: Yup.string().oneOf(['BOP', 'NON-BOP']).required(),
label: Yup.string().oneOf(['BOP', 'NON-BOP']).required(),
}).required('Kategori wajib diisi!'),
location: Yup.object({
value: Yup.number().min(1).required(),
label: Yup.string().required(),
}).required('Lokasi wajib diisi!'),
realization_date: Yup.string().required('Tanggal transaksi wajib diisi!'),
kandangs: Yup.array()
.of(
Yup.object({
id: Yup.number().required('Kandang wajib dipilih!'),
name: Yup.string().required('Kandang wajib dipilih!'),
})
)
.min(1, 'Kandang wajib dipilih!')
.required('Kandang wajib dipilih!'),
supplier: Yup.object({
value: Yup.number().min(1).required(),
label: Yup.string().required(),
}).required('Vendor wajib diisi!'),
existing_documents: Yup.array().of(
Yup.object({
name: Yup.string().required(),
url: Yup.string().required(),
})
),
documents: Yup.array().of(Yup.mixed<File>().required()).optional(),
realizations: Yup.array()
.of(
Yup.object({
kandang_id: Yup.number().min(1, 'Wajib memilih kandang!').required(),
cost_items: Yup.array()
.of(
Yup.object({
nonstock: Yup.object({
value: Yup.number().min(1).required(),
label: Yup.string().required(),
}).required('Nonstock wajib diisi!'),
quantity: Yup.number().required('Total kuantitas wajib diisi!'),
total_cost: Yup.number().required('Total biaya wajib diisi!'),
notes: Yup.string(),
})
)
.min(1, 'Kandang harus memiliki setidaknya 1 biaya!')
.required('Biaya kandang wajib diisi!'),
})
)
.min(1, 'Biaya kandang wajib diisi!')
.required('Biaya kandang wajib diisi!'),
});
export const UpdateExpenseRealizationFormSchema = ExpenseRealizationFormSchema;
export const UploadRealizationDocumentsFormSchema = Yup.object({
realization_documents: Yup.array()
.of(Yup.mixed<File>().required())
.required(),
});
export type ExpenseRealizationFormValues = Yup.InferType<
typeof ExpenseRealizationFormSchema
>;
export type UploadRealizationDocumentsFormValues = Yup.InferType<
typeof UploadRealizationDocumentsFormSchema
>;
export const getExpenseRealizationFormInitialValues = (
initialValues?: Expense
): ExpenseRealizationFormValues => {
return {
category: initialValues?.category
? {
value: initialValues.category,
label: initialValues.category,
}
: undefined,
location: initialValues?.location
? {
value: initialValues.location.id,
label: initialValues.location.name,
}
: undefined,
realization_date: initialValues?.realization_date
? formatDate(initialValues?.realization_date, 'YYYY-MM-DD')
: undefined,
kandangs: initialValues?.kandangs.map((kandang) => ({
id: kandang.kandang_id,
name: kandang.name,
})),
supplier: initialValues?.supplier
? {
value: initialValues.supplier.id,
label: initialValues.supplier.name,
}
: undefined,
existing_documents: initialValues?.realization_docs?.map((doc) => ({
name: doc.path,
url: doc.path,
})),
documents: [],
realizations: initialValues?.kandangs
? initialValues.kandangs.map((kandangExpense) => {
const costItemsInitialValue = kandangExpense.realisasi
? kandangExpense.realisasi.map((realisasiItem, realisasiIdx) => {
return {
nonstock: {
value: kandangExpense.pengajuans?.[realisasiIdx]
.id as number,
label: realisasiItem.nonstock.name,
},
quantity: realisasiItem.qty,
total_cost: realisasiItem.total_price,
notes: realisasiItem.note,
};
})
: kandangExpense.pengajuans
? kandangExpense.pengajuans.map((expenseItem) => ({
nonstock: {
value: expenseItem.id,
label: expenseItem.nonstock.name,
},
quantity: expenseItem.qty,
total_cost: expenseItem.total_price,
notes: expenseItem.note,
}))
: [];
return {
kandang_id: kandangExpense.kandang_id,
cost_items: costItemsInitialValue,
};
})
: [],
};
};
@@ -0,0 +1,410 @@
'use client';
import { useCallback, useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import { useFormik } from 'formik';
import toast from 'react-hot-toast';
import Link from 'next/link';
import { Icon } from '@iconify/react';
import Button from '@/components/Button';
import SelectInput, {
OptionType,
useSelect,
} from '@/components/input/SelectInput';
import DateInput from '@/components/input/DateInput';
import DropFileInput from '@/components/input/DropFileInput';
import ExpenseKandangsTable from '@/components/pages/expense/form/ExpenseKandangsTable';
import ExpenseRealizationKandangDetailExpense from '@/components/pages/expense/form/ExpenseRealizationKandangDetailExpense';
import {
CreateExpenseRealizationPayload,
Expense,
UpdateExpenseRealizationPayload,
} from '@/types/api/expense';
import {
ExpenseRealizationFormSchema,
ExpenseRealizationFormValues,
getExpenseRealizationFormInitialValues,
UpdateExpenseRealizationFormSchema,
} from '@/components/pages/expense/form/ExpenseRealizationForm.schema';
import { ExpenseApi } from '@/services/api/expense';
import { isResponseError } from '@/lib/api-helper';
import { LocationApi, SupplierApi } from '@/services/api/master-data';
import { Supplier } from '@/types/api/master-data/supplier';
import { ACCEPTED_FILE_TYPE } from '@/config/constant';
import { cn } from '@/lib/helper';
interface ExpenseRealizationFormProps {
type?: 'add' | 'edit' | 'detail';
initialValues?: Expense;
}
const ExpenseRealizationForm = ({
type = 'add',
initialValues,
}: ExpenseRealizationFormProps) => {
const router = useRouter();
const [expenseFormErrorMessage, setExpenseFormErrorMessage] = useState('');
const createExpenseHandler = useCallback(
async (payload: CreateExpenseRealizationPayload) => {
const createExpenseRes = await ExpenseApi.createRealization(
initialValues?.id as number,
ExpenseApi.convertExpenseRealizationPayloadToFormData(payload)
);
if (isResponseError(createExpenseRes)) {
setExpenseFormErrorMessage(createExpenseRes.message);
return;
}
toast.success(createExpenseRes?.message as string);
router.push('/expense');
},
[router]
);
const updateExpenseHandler = useCallback(
async (expenseId: number, payload: UpdateExpenseRealizationPayload) => {
const updateExpenseRes = await ExpenseApi.updateRealization(
expenseId,
ExpenseApi.convertExpenseRealizationPayloadToFormData(payload)
);
if (updateExpenseRes?.status === 'error') {
setExpenseFormErrorMessage(updateExpenseRes.message);
return;
}
toast.success(updateExpenseRes?.message as string);
router.refresh();
router.push('/expense');
},
[router]
);
const formik = useFormik<ExpenseRealizationFormValues>({
initialValues: getExpenseRealizationFormInitialValues(initialValues),
validationSchema:
type === 'edit'
? UpdateExpenseRealizationFormSchema
: ExpenseRealizationFormSchema,
onSubmit: async (values) => {
setExpenseFormErrorMessage('');
const realizations: CreateExpenseRealizationPayload['realizations'] = [];
values.realizations.forEach((realization) => {
realization.cost_items.forEach((costItem) => {
const unitPrice =
parseFloat(String(costItem.total_cost)) /
parseFloat(String(costItem.quantity));
const realizationItem = {
expense_nonstock_id: costItem.nonstock?.value as number,
qty: parseFloat(String(costItem.quantity)) as number,
unit_price: unitPrice,
total_price: parseFloat(String(costItem.total_cost)) as number,
notes: costItem.notes ?? '',
};
realizations.push(realizationItem);
});
});
const expensePayload: CreateExpenseRealizationPayload = {
realization_date: values.realization_date as string,
documents: values.documents as File[],
realizations,
};
switch (type) {
case 'add':
await createExpenseHandler(expensePayload);
break;
case 'edit':
await updateExpenseHandler(
initialValues?.id as number,
expensePayload
);
break;
}
},
});
const { setValues: formikSetValues } = formik;
const {
setInputValue: setLocationInputValue,
options: locationOptions,
isLoadingOptions: isLoadingLocationOptions,
} = useSelect<Location>(LocationApi.basePath, 'id', 'name');
const {
setInputValue: setVendorInputValue,
options: vendorOptions,
isLoadingOptions: isLoadingVendorOptions,
} = useSelect<Supplier>(SupplierApi.basePath, 'id', 'name');
const locationChangeHandler = (val: OptionType | OptionType[] | null) => {
formik.setFieldTouched('location', true);
formik.setFieldValue('location', val);
formik.setFieldValue('kandangs', []);
formik.setFieldValue('realizations', []);
};
const kandangsChangeHandler = (kandangs: { id: number; name: string }[]) => {
formik.setFieldTouched('kandangs', true);
formik.setFieldValue('kandangs', kandangs);
const newRealizations = [...(formik.values.realizations ?? [])];
// add new realizations
kandangs.forEach((kandangItem) => {
const isKandangExistInRealization = newRealizations.find(
(realizationItem) => realizationItem.kandang_id === kandangItem.id
);
if (isKandangExistInRealization) return;
newRealizations.push({
kandang_id: kandangItem.id,
cost_items: [
{
nonstock: undefined,
quantity: undefined,
total_cost: undefined,
notes: '',
},
],
});
});
// prune realizations
const kandangIds = new Set(kandangs.map((kandang) => kandang.id));
const deletedRealizationsIdx: number[] = [];
newRealizations.forEach((realization, idx) => {
const isRealizationValid = kandangIds.has(realization.kandang_id);
if (!isRealizationValid) {
deletedRealizationsIdx.push(idx);
}
});
deletedRealizationsIdx.forEach((deletedRealizationIdx) => {
newRealizations.splice(deletedRealizationIdx, 1);
});
formik.setFieldValue('realizations', newRealizations);
};
const vendorChangeHandler = (val: OptionType | OptionType[] | null) => {
formik.setFieldTouched('vendor', true);
formik.setFieldValue('vendor', val);
};
const realizationDocumentsChangeHandler = (val: File[]) => {
formik.setFieldTouched('documents', true);
formik.setFieldValue('documents', val);
};
const realizationDocumentsDeleteHandler = (deletedFileIdx: number) => {
const newRequestDocuments = formik.values.documents;
newRequestDocuments?.splice(deletedFileIdx, 1);
formik.setFieldValue('documents', newRequestDocuments);
};
useEffect(() => {
formikSetValues(getExpenseRealizationFormInitialValues(initialValues));
}, [formikSetValues, getExpenseRealizationFormInitialValues, initialValues]);
return (
<section className='w-full max-w-5xl'>
<header className='flex flex-col gap-4'>
<Button
href='/expense'
variant='link'
className='w-fit p-0 text-primary'
>
<Icon icon='uil:arrow-left' width={24} height={24} />
Kembali
</Button>
<h1 className='text-2xl font-bold text-center'>
Realisasi Biaya Operasional
</h1>
</header>
<form
onSubmit={formik.handleSubmit}
onReset={formik.handleReset}
className='w-full mt-8 flex flex-col gap-6'
>
<div className='grid grid-cols-12 gap-4'>
<SelectInput
label='Lokasi'
required
placeholder='Pilih Lokasi'
value={formik.values.location}
onChange={locationChangeHandler}
options={locationOptions}
isLoading={isLoadingLocationOptions}
onInputChange={setLocationInputValue}
isDisabled
className={{ wrapper: 'col-span-12 sm:col-span-6' }}
/>
<DateInput
name='realization_date'
label='Tanggal Realisasi'
required
value={formik.values.realization_date}
onChange={formik.handleChange}
className={{
wrapper: 'col-span-12 sm:col-span-6',
}}
/>
<ExpenseKandangsTable
type='detail'
locationId={formik.values.location?.value}
selectedKandangs={formik.values.kandangs ?? []}
onChange={kandangsChangeHandler}
className={{
wrapper: 'w-full col-span-12',
}}
/>
<SelectInput
label='Vendor'
required
placeholder='Pilih Vendor'
value={formik.values.supplier}
onChange={vendorChangeHandler}
options={vendorOptions}
isLoading={isLoadingVendorOptions}
onInputChange={setVendorInputValue}
isDisabled
className={{ wrapper: 'col-span-12' }}
/>
<DropFileInput
label='Dokumen Realisasi'
name='documents'
values={formik.values.documents}
onChange={realizationDocumentsChangeHandler}
onDelete={realizationDocumentsDeleteHandler}
accept={{
...ACCEPTED_FILE_TYPE.PDF,
...ACCEPTED_FILE_TYPE.IMAGE,
}}
className={{
wrapper: 'col-span-12',
inputWrapper: 'h-12 flex items-center',
}}
/>
{formik.values.existing_documents &&
formik.values.existing_documents.length > 0 && (
<div className='w-full col-span-12'>
<ul className='pl-4 list-disc'>
{formik.values.existing_documents.map(
(existingDocument, existingDocumentIdx) => (
<li key={existingDocumentIdx}>
<Link
href={existingDocument.url}
target='_blank'
rel='noopener noreferrer'
className='text-blue-500 underline'
>
{existingDocument.name}{' '}
<Icon
icon='cuida:open-in-new-tab-outline'
width={12}
height={12}
className='inline'
/>
</Link>
</li>
)
)}
</ul>
</div>
)}
<ExpenseRealizationKandangDetailExpense
formik={formik}
className={{
wrapper: 'col-span-12',
}}
/>
</div>
{expenseFormErrorMessage && (
<div role='alert' className='alert alert-error w-full'>
<Icon
icon='material-symbols:error-outline'
width={24}
height={24}
/>
<span>{expenseFormErrorMessage}</span>
</div>
)}
<div className='flex flex-row justify-between gap-2 flex-wrap'>
{type !== 'add' && (
<div className='flex flex-row justify-start gap-2'>
{type !== 'edit' && (
<Button
type='button'
color='warning'
href={`/expense/detail/edit/?expenseId=${initialValues?.id}`}
className='px-4'
>
<Icon
icon='material-symbols:edit-outline'
width={24}
height={24}
className='justify-start text-sm'
/>
Edit
</Button>
)}
</div>
)}
{type !== 'detail' && (
<div
className={cn('flex flex-row justify-end gap-2', {
'w-full': type === 'add',
})}
>
<Button type='reset' color='warning' className='px-4'>
Reset
</Button>
<Button
type='submit'
color='primary'
isLoading={formik.isSubmitting}
disabled={!formik.isValid || formik.isSubmitting}
className='px-4'
>
Submit
</Button>
</div>
)}
</div>
</form>
</section>
);
};
export default ExpenseRealizationForm;
@@ -0,0 +1,224 @@
'use client';
import { FormikContextType } from 'formik';
import Card from '@/components/Card';
import SelectInput, {
OptionType,
useSelect,
} from '@/components/input/SelectInput';
import NumberInput from '@/components/input/NumberInput';
import TextInput from '@/components/input/TextInput';
import { ExpenseRealizationFormValues } from '@/components/pages/expense/form/ExpenseRealizationForm.schema';
import { cn } from '@/lib/helper';
import { NonstockApi } from '@/services/api/master-data';
import { Nonstock } from '@/types/api/master-data/nonstock';
interface ExpenseRealizationKandangDetailExpenseProps {
type?: 'add' | 'edit' | 'detail';
formik: FormikContextType<ExpenseRealizationFormValues>;
className?: {
wrapper?: string;
};
}
const ExpenseRealizationKandangDetailExpense: React.FC<
ExpenseRealizationKandangDetailExpenseProps
> = ({ type, formik, className }) => {
const {
setInputValue: setNonstockInputValue,
options: nonstockOptions,
isLoadingOptions: isLoadingNonstockOptions,
} = useSelect<Nonstock>(NonstockApi.basePath, 'id', 'name');
const nonstockChangeHandler = (
kandangExpenseIdx: number,
costItemIdx: number,
val: OptionType | OptionType[] | null
) => {
formik.setFieldTouched(
`realizations[${kandangExpenseIdx}].cost_items[${costItemIdx}].nonstock`,
true
);
formik.setFieldValue(
`realizations[${kandangExpenseIdx}].cost_items[${costItemIdx}].nonstock`,
val
);
};
const isExpenseRepeaterInputError = (
column: 'nonstock' | 'quantity' | 'total_cost' | 'notes',
kandangExpenseIdx: number,
expenseIdx: number
) => {
return (
formik.touched.realizations?.[kandangExpenseIdx]?.cost_items?.[
expenseIdx
]?.[column] &&
Boolean(
formik.errors.realizations?.[kandangExpenseIdx] instanceof Object &&
formik.errors.realizations?.[kandangExpenseIdx].cost_items?.[
expenseIdx
] instanceof Object &&
formik.errors.realizations?.[kandangExpenseIdx].cost_items?.[
expenseIdx
]?.[column]
)
);
};
return (
<Card
className={{
wrapper: cn('w-full', className?.wrapper),
body: 'p-4 shadow',
}}
>
<div className='mb-4 text-center'>
<h4 className='font-bold text-xl'>
Rincian Realisasi Biaya Operasional
</h4>
</div>
<div className='w-full flex flex-col gap-6'>
{formik.values.realizations.length === 0 && (
<div>
<p className='text-sm text-gray-400 text-center'>
Pilih kandang terlebih dahulu!
</p>
</div>
)}
{formik.values.realizations.map((kandangExpense, kandangExpenseIdx) => {
const kandangName = formik.values.kandangs?.find(
(kandang) => kandang.id === kandangExpense.kandang_id
);
return (
kandangName?.name && (
<div
key={`kandangExpense-${kandangExpenseIdx}`}
className='w-full flex flex-col gap-4'
>
<div>
<h5 className='mb-2 text-lg font-bold text-center'>
Biaya {kandangName?.name}
</h5>
<div className='overflow-x-auto'>
<table className='table'>
<thead>
<tr>
<th>Nonstock</th>
<th>Total Kuantitas</th>
<th>Total Biaya</th>
<th>Catatan</th>
</tr>
</thead>
<tbody>
{kandangExpense.cost_items.map(
(expenseItem, expenseIdx) => (
<tr key={`expense-${expenseIdx}`}>
<td className='p-2'>
<SelectInput
placeholder='Pilih Nonstock'
value={expenseItem.nonstock}
onChange={(val) => {
nonstockChangeHandler(
kandangExpenseIdx,
expenseIdx,
val
);
}}
options={nonstockOptions}
isLoading={isLoadingNonstockOptions}
onInputChange={setNonstockInputValue}
className={{ wrapper: 'min-w-48' }}
isDisabled
/>
</td>
<td className='p-2'>
<NumberInput
required
name={`realizations[${kandangExpenseIdx}].cost_items[${expenseIdx}].quantity`}
placeholder='Masukkan Total Kuantitas'
value={
formik.values.realizations[
kandangExpenseIdx
].cost_items[expenseIdx].quantity ?? ''
}
onChange={formik.handleChange}
onBlur={formik.handleBlur}
isError={isExpenseRepeaterInputError(
'quantity',
kandangExpenseIdx,
expenseIdx
)}
className={{ wrapper: 'min-w-24' }}
/>
</td>
<td className='p-2'>
<NumberInput
name={`realizations[${kandangExpenseIdx}].cost_items[${expenseIdx}].total_cost`}
placeholder='Masukkan Total Biaya'
value={
formik.values.realizations[
kandangExpenseIdx
].cost_items[expenseIdx].total_cost ?? ''
}
onChange={formik.handleChange}
onBlur={formik.handleBlur}
isError={isExpenseRepeaterInputError(
'total_cost',
kandangExpenseIdx,
expenseIdx
)}
inputPrefix={
<span className='text-gray-600 font-medium'>
Rp
</span>
}
className={{ wrapper: 'min-w-24' }}
/>
</td>
<td className='p-2'>
<TextInput
name={`realizations[${kandangExpenseIdx}].cost_items[${expenseIdx}].notes`}
placeholder='Tuliskan catatan'
value={
formik.values.realizations[
kandangExpenseIdx
].cost_items[expenseIdx].notes ?? ''
}
onChange={formik.handleChange}
onBlur={formik.handleBlur}
isError={isExpenseRepeaterInputError(
'notes',
kandangExpenseIdx,
expenseIdx
)}
className={{ wrapper: 'min-w-24' }}
/>
</td>
</tr>
)
)}
</tbody>
</table>
</div>
</div>
</div>
)
);
})}
</div>
</Card>
);
};
export default ExpenseRealizationKandangDetailExpense;
@@ -3,27 +3,32 @@ import { Expense } from '@/types/api/expense';
import { formatDate } from '@/lib/helper';
type ExpenseFormSchemaType = {
category?: {
value: 'BOP' | 'NON-BOP';
label: 'BOP' | 'NON-BOP';
};
location?: {
value: number;
label: string;
};
transaction_date?: string;
kandangs?: { id: number; name: string }[];
vendor?: {
supplier?: {
value: number;
label: string;
};
existing_documents?: { name: string; url: string }[];
request_documents?: File[];
kandangExpenses: {
kandangId: number;
expenses: {
existing_documents?: { id: number; name: string; url: string }[];
deleted_documents?: number[];
documents?: File[];
cost_per_kandangs: {
kandang_id: number;
cost_items: {
nonstock?: {
value: number;
label: string;
};
totalQuantity?: number;
totalExpense?: number;
quantity?: number;
total_cost?: number;
notes?: string;
}[];
}[];
@@ -31,6 +36,11 @@ type ExpenseFormSchemaType = {
export const ExpenseRequestFormSchema: Yup.ObjectSchema<ExpenseFormSchemaType> =
Yup.object({
category: Yup.object({
value: Yup.string().oneOf(['BOP', 'NON-BOP']).required(),
label: Yup.string().oneOf(['BOP', 'NON-BOP']).required(),
}).required('Kategori wajib diisi!'),
location: Yup.object({
value: Yup.number().min(1).required(),
label: Yup.string().required(),
@@ -47,35 +57,36 @@ export const ExpenseRequestFormSchema: Yup.ObjectSchema<ExpenseFormSchemaType> =
.min(1, 'Kandang wajib dipilih!')
.required('Kandang wajib dipilih!'),
vendor: Yup.object({
supplier: Yup.object({
value: Yup.number().min(1).required(),
label: Yup.string().required(),
}).required('Vendor wajib diisi!'),
existing_documents: Yup.array().of(
Yup.object({
id: Yup.number().required(),
name: Yup.string().required(),
url: Yup.string().required(),
})
),
request_documents: Yup.array().of(Yup.mixed<File>().required()).optional(),
deleted_documents: Yup.array().of(Yup.number().required()).optional(),
kandangExpenses: Yup.array()
documents: Yup.array().of(Yup.mixed<File>().required()).optional(),
cost_per_kandangs: Yup.array()
.of(
Yup.object({
kandangId: Yup.number().min(1, 'Wajib memilih kandang!').required(),
expenses: Yup.array()
kandang_id: Yup.number().min(1, 'Wajib memilih kandang!').required(),
cost_items: Yup.array()
.of(
Yup.object({
nonstock: Yup.object({
value: Yup.number().min(1).required(),
label: Yup.string().required(),
}).required('Nonstock wajib diisi!'),
totalQuantity: Yup.number().required(
'Total kuantitas wajib diisi!'
),
totalExpense: Yup.number().required('Total biaya wajib diisi!'),
quantity: Yup.number().required('Total kuantitas wajib diisi!'),
total_cost: Yup.number().required('Total biaya wajib diisi!'),
notes: Yup.string(),
})
)
@@ -90,7 +101,7 @@ export const ExpenseRequestFormSchema: Yup.ObjectSchema<ExpenseFormSchemaType> =
export const UpdateExpenseRequestFormSchema = ExpenseRequestFormSchema;
export const UploadRequestDocumentsFormSchema = Yup.object({
request_documents: Yup.array().of(Yup.mixed<File>().required()).required(),
documents: Yup.array().of(Yup.mixed<File>().required()).required(),
});
export type ExpenseRequestFormValues = Yup.InferType<
@@ -105,39 +116,52 @@ export const getExpenseFormInitialValues = (
initialValues?: Expense
): ExpenseRequestFormValues => {
return {
category: initialValues?.category
? {
value: initialValues.category,
label: initialValues.category,
}
: undefined,
location: initialValues?.location
? {
value: initialValues.location.id,
label: initialValues.location.name,
}
: undefined,
transaction_date: initialValues?.transaction_date
? formatDate(initialValues.transaction_date, 'YYYY-MM-DD')
transaction_date: initialValues?.expense_date
? formatDate(initialValues.expense_date, 'YYYY-MM-DD')
: undefined,
kandangs: initialValues?.kandangs.map((kandang) => ({
id: kandang.id,
id: kandang.kandang_id,
name: kandang.name,
})),
vendor: initialValues?.vendor
supplier: initialValues?.supplier
? {
value: initialValues.vendor.id,
label: initialValues.vendor.name,
value: initialValues.supplier.id,
label: initialValues.supplier.name,
}
: undefined,
existing_documents: initialValues?.request_documents,
request_documents: [],
kandangExpenses: initialValues?.kandang_expenses
? initialValues.kandang_expenses.map((kandangExpense) => ({
kandangId: kandangExpense.kandang.id,
expenses: kandangExpense.expenses.map((expenseItem) => ({
nonstock: {
value: expenseItem.nonstock.id,
label: expenseItem.nonstock.name,
},
totalQuantity: expenseItem.total_quantity,
totalExpense: expenseItem.total_expense,
notes: expenseItem.notes,
})),
existing_documents: initialValues?.documents?.map((doc) => ({
id: doc.id,
name: doc.path,
url: doc.path,
})),
deleted_documents: [],
documents: [],
cost_per_kandangs: initialValues?.kandangs
? initialValues.kandangs.map((kandangExpense) => ({
kandang_id: kandangExpense.kandang_id,
cost_items: kandangExpense.pengajuans
? kandangExpense.pengajuans.map((expenseItem) => ({
nonstock: {
value: expenseItem.nonstock.id,
label: expenseItem.nonstock.name,
},
quantity: expenseItem.qty,
total_cost: expenseItem.total_price,
notes: expenseItem.note,
}))
: [],
}))
: [],
};
@@ -42,7 +42,6 @@ interface ExpenseFormProps {
initialValues?: Expense;
}
// TODO: integrate this with real API
const ExpenseRequestForm = ({
type = 'add',
initialValues,
@@ -59,7 +58,7 @@ const ExpenseRequestForm = ({
const createExpenseHandler = useCallback(
async (payload: CreateExpensePayload) => {
const createExpenseRes = await ExpenseApi.create(
ExpenseApi.convertPayloadToFormData(payload)
ExpenseApi.convertExpenseRequestPayloadToFormData(payload)
);
if (isResponseError(createExpenseRes)) {
@@ -74,10 +73,15 @@ const ExpenseRequestForm = ({
);
const updateExpenseHandler = useCallback(
async (expenseId: number, payload: UpdateExpensePayload) => {
async (
expenseId: number,
payload: UpdateExpensePayload,
deletedDocumentIds: number[]
) => {
const updateExpenseRes = await ExpenseApi.update(
expenseId,
ExpenseApi.convertPayloadToFormData(payload)
ExpenseApi.convertExpenseRequestUpdatePayloadToFormData(payload),
deletedDocumentIds
);
if (updateExpenseRes?.status === 'error') {
@@ -102,20 +106,17 @@ const ExpenseRequestForm = ({
setExpenseFormErrorMessage('');
const expensePayload: CreateExpensePayload = {
locationId: values.location?.value as number,
kandangIds: values.kandangs
? values.kandangs.map((item) => item.id)
: [],
transaction_date: values.transaction_date as string,
vendorId: values.vendor?.value as number,
request_documents: values.request_documents as File[],
kandang_expenses: values.kandangExpenses.map((kandangExpense) => ({
kandangId: kandangExpense.kandangId,
expenses: kandangExpense.expenses.map((expenseItem) => ({
nonstockId: expenseItem.nonstock?.value as number,
total_quantity: expenseItem.totalQuantity as number,
total_expense: expenseItem.totalExpense as number,
notes: expenseItem.notes,
category: formik.values.category?.value as 'BOP' | 'NON-BOP',
transaction_date: values?.transaction_date as string,
supplier_id: values.supplier?.value as number,
documents: values.documents as File[],
cost_per_kandangs: values.cost_per_kandangs.map((costPerKandang) => ({
kandang_id: costPerKandang.kandang_id,
cost_items: costPerKandang.cost_items.map((costItem) => ({
nonstock_id: costItem.nonstock?.value as number,
quantity: parseFloat(String(costItem.quantity)) as number,
total_cost: parseFloat(String(costItem.total_cost)) as number,
notes: costItem.notes ?? '',
})),
})),
};
@@ -126,9 +127,28 @@ const ExpenseRequestForm = ({
break;
case 'edit':
const expenseUpdatePayload: UpdateExpensePayload = {
category: formik.values.category?.value as 'BOP' | 'NON-BOP',
transaction_date: values?.transaction_date as string,
supplier_id: values.supplier?.value as number,
documents: values.documents as File[],
cost_per_kandang: values.cost_per_kandangs.map(
(costPerKandang) => ({
kandang_id: costPerKandang.kandang_id,
cost_items: costPerKandang.cost_items.map((costItem) => ({
nonstock_id: costItem.nonstock?.value as number,
quantity: parseFloat(String(costItem.quantity)) as number,
total_cost: parseFloat(String(costItem.total_cost)) as number,
notes: costItem.notes ?? '',
})),
})
),
};
await updateExpenseHandler(
initialValues?.id as number,
expensePayload
expenseUpdatePayload,
formik.values.deleted_documents ?? []
);
break;
}
@@ -145,72 +165,103 @@ const ExpenseRequestForm = ({
const {
setInputValue: setVendorInputValue,
options: vendorOptions,
options: supplierOptions,
isLoadingOptions: isLoadingVendorOptions,
} = useSelect<Supplier>(SupplierApi.basePath, 'id', 'name');
const categoryChangeHandler = (val: OptionType | OptionType[] | null) => {
formik.setFieldTouched('category', true);
formik.setFieldValue('category', val);
};
const locationChangeHandler = (val: OptionType | OptionType[] | null) => {
formik.setFieldTouched('location', true);
formik.setFieldValue('location', val);
formik.setFieldValue('kandangs', []);
formik.setFieldValue('kandangExpenses', []);
formik.setFieldValue('cost_per_kandangs', []);
};
const kandangsChangeHandler = (kandangs: { id: number; name: string }[]) => {
formik.setFieldTouched('kandangs', true);
formik.setFieldValue('kandangs', kandangs);
const newKandangExpenses = [...(formik.values.kandangExpenses ?? [])];
const newCostPerKandangs = [...(formik.values.cost_per_kandangs ?? [])];
// add new kandangExpenses
// add new cost_per_kandangs
kandangs.forEach((kandangItem) => {
const isKandangExistInKandangExpense = newKandangExpenses.find(
(kandangExpenseItem) => kandangExpenseItem.kandangId === kandangItem.id
const isKandangExistInCostPerKandangs = newCostPerKandangs.find(
(costPerKandangItem) => costPerKandangItem.kandang_id === kandangItem.id
);
if (isKandangExistInKandangExpense) return;
if (isKandangExistInCostPerKandangs) return;
newKandangExpenses.push({
kandangId: kandangItem.id,
expenses: [
newCostPerKandangs.push({
kandang_id: kandangItem.id,
cost_items: [
{
nonstock: undefined,
totalExpense: undefined,
totalQuantity: undefined,
quantity: undefined,
total_cost: undefined,
notes: '',
},
],
});
});
// prune kandangExpenses
// prune cost_per_kandangs
const kandangIds = new Set(kandangs.map((kandang) => kandang.id));
const deletedKandangExpensesIdx: number[] = [];
const deletedCostPerKandangsIdx: number[] = [];
newKandangExpenses.forEach((kandangExpense, idx) => {
const isKandangExpenseValid = kandangIds.has(kandangExpense.kandangId);
newCostPerKandangs.forEach((costPerKandang, idx) => {
const isCostPerKandangValid = kandangIds.has(costPerKandang.kandang_id);
if (!isKandangExpenseValid) {
deletedKandangExpensesIdx.push(idx);
if (!isCostPerKandangValid) {
deletedCostPerKandangsIdx.push(idx);
}
});
deletedKandangExpensesIdx.forEach((deletedKandangExpenseIdx) => {
newKandangExpenses.splice(deletedKandangExpenseIdx, 1);
deletedCostPerKandangsIdx.forEach((deletedCostPerKandangIdx) => {
newCostPerKandangs.splice(deletedCostPerKandangIdx, 1);
});
formik.setFieldValue('kandangExpenses', newKandangExpenses);
formik.setFieldValue('cost_per_kandangs', newCostPerKandangs);
};
const vendorChangeHandler = (val: OptionType | OptionType[] | null) => {
formik.setFieldTouched('vendor', true);
formik.setFieldValue('vendor', val);
const supplierChangeHandler = (val: OptionType | OptionType[] | null) => {
formik.setFieldTouched('supplier', true);
formik.setFieldValue('supplier', val);
};
const requestDocumentsChangeHandler = (val: File[]) => {
formik.setFieldTouched('request_documents', true);
formik.setFieldValue('request_documents', val);
formik.setFieldTouched('documents', true);
formik.setFieldValue('documents', val);
};
const requestDocumentsDeleteHandler = (deletedFileIdx: number) => {
const newRequestDocuments = formik.values.documents;
newRequestDocuments?.splice(deletedFileIdx, 1);
formik.setFieldValue('documents', newRequestDocuments);
};
const deleteDocumentClickHandler = (
deletedDocumentIdx: number,
deletedDocumentId: number
) => {
const newDeletedDocumentIds = [...(formik.values.deleted_documents ?? [])];
const newExistingDocuments = [
...(formik.values.existing_documents ?? []),
].filter((_, idx) => idx !== deletedDocumentIdx);
newDeletedDocumentIds.push(deletedDocumentId);
formik.setFieldTouched('deleted_documents', true);
formik.setFieldValue('deleted_documents', newDeletedDocumentIds);
formik.setFieldTouched('existing_documents', true);
formik.setFieldValue('existing_documents', newExistingDocuments);
};
const deleteExpenseClickHandler = () => {
@@ -269,6 +320,25 @@ const ExpenseRequestForm = ({
className='w-full mt-8 flex flex-col gap-6'
>
<div className='grid grid-cols-12 gap-4'>
<SelectInput
label='Kategori'
required
placeholder='Pilih Kategori'
value={formik.values.category}
onChange={categoryChangeHandler}
options={[
{
value: 'BOP',
label: 'BOP',
},
{
value: 'NON-BOP',
label: 'NON-BOP',
},
]}
className={{ wrapper: 'col-span-12 sm:col-span-4' }}
/>
<SelectInput
label='Lokasi'
required
@@ -278,7 +348,7 @@ const ExpenseRequestForm = ({
options={locationOptions}
isLoading={isLoadingLocationOptions}
onInputChange={setLocationInputValue}
className={{ wrapper: 'col-span-12 sm:col-span-6' }}
className={{ wrapper: 'col-span-12 sm:col-span-4' }}
/>
<DateInput
@@ -288,7 +358,7 @@ const ExpenseRequestForm = ({
value={formik.values.transaction_date}
onChange={formik.handleChange}
className={{
wrapper: 'col-span-12 sm:col-span-6',
wrapper: 'col-span-12 sm:col-span-4',
}}
/>
@@ -306,9 +376,9 @@ const ExpenseRequestForm = ({
label='Vendor'
required
placeholder='Pilih Vendor'
value={formik.values.vendor}
onChange={vendorChangeHandler}
options={vendorOptions}
value={formik.values.supplier}
onChange={supplierChangeHandler}
options={supplierOptions}
isLoading={isLoadingVendorOptions}
onInputChange={setVendorInputValue}
className={{ wrapper: 'col-span-12' }}
@@ -316,9 +386,10 @@ const ExpenseRequestForm = ({
<DropFileInput
label='Dokumen Pengajuan'
name='request_documents'
values={formik.values.request_documents}
name='documents'
values={formik.values.documents}
onChange={requestDocumentsChangeHandler}
onDelete={requestDocumentsDeleteHandler}
accept={{
...ACCEPTED_FILE_TYPE.PDF,
...ACCEPTED_FILE_TYPE.IMAGE,
@@ -336,20 +407,41 @@ const ExpenseRequestForm = ({
{formik.values.existing_documents.map(
(existingDocument, existingDocumentIdx) => (
<li key={existingDocumentIdx}>
<Link
href={existingDocument.url}
target='_blank'
rel='noopener noreferrer'
className='text-blue-500 underline'
>
{existingDocument.name}{' '}
<Icon
icon='cuida:open-in-new-tab-outline'
width={12}
height={12}
className='inline'
/>
</Link>
<div className='w-full flex flex-wrap justify-between'>
<Link
href={existingDocument.url}
target='_blank'
rel='noopener noreferrer'
className='text-blue-500 underline'
>
{existingDocument.name}{' '}
<Icon
icon='cuida:open-in-new-tab-outline'
width={12}
height={12}
className='inline'
/>
</Link>
<Button
type='button'
variant='ghost'
color='error'
onClick={() => {
deleteDocumentClickHandler(
existingDocumentIdx,
existingDocument.id
);
}}
className='p-1 rounded-full text-error focus-visible:text-error-content hover:text-error-content'
>
<Icon
icon='fluent:delete-12-regular'
width={20}
height={20}
/>
</Button>
</div>
</li>
)
)}
@@ -402,6 +494,17 @@ const ExpenseRequestForm = ({
</div>
)}
{expenseFormErrorMessage && (
<div role='alert' className='alert alert-error w-full'>
<Icon
icon='material-symbols:error-outline'
width={24}
height={24}
/>
<span>{expenseFormErrorMessage}</span>
</div>
)}
{type !== 'detail' && (
<div
className={cn('flex flex-row justify-end gap-2', {
@@ -424,17 +527,6 @@ const ExpenseRequestForm = ({
</div>
)}
</div>
{expenseFormErrorMessage && (
<div role='alert' className='alert alert-error'>
<Icon
icon='material-symbols:error-outline'
width={24}
height={24}
/>
<span>{expenseFormErrorMessage}</span>
</div>
)}
</form>
</section>
@@ -41,28 +41,28 @@ const ExpenseRequestKandangDetailExpense: React.FC<
val: OptionType | OptionType[] | null
) => {
formik.setFieldTouched(
`kandangExpenses[${kandangExpenseIdx}].expenses[${expenseIdx}].nonstock`,
`cost_per_kandangs[${kandangExpenseIdx}].cost_items[${expenseIdx}].nonstock`,
true
);
formik.setFieldValue(
`kandangExpenses[${kandangExpenseIdx}].expenses[${expenseIdx}].nonstock`,
`cost_per_kandangs[${kandangExpenseIdx}].cost_items[${expenseIdx}].nonstock`,
val
);
};
const addExpenseItemHandler = (kandangExpenseIdx: number) => {
const newExpensesValue = [
...formik.values.kandangExpenses[kandangExpenseIdx].expenses,
...formik.values.cost_per_kandangs[kandangExpenseIdx].cost_items,
{
nonstock: undefined,
totalExpense: undefined,
totalQuantity: undefined,
total_cost: undefined,
quantity: undefined,
notes: '',
},
];
formik.setFieldValue(
`kandangExpenses[${kandangExpenseIdx}].expenses`,
`cost_per_kandangs[${kandangExpenseIdx}].cost_items`,
newExpensesValue
);
};
@@ -71,27 +71,28 @@ const ExpenseRequestKandangDetailExpense: React.FC<
kandangExpenseIdx: number,
expenseIdx: number
) => {
const path = `kandangExpenses[${kandangExpenseIdx}].expenses`;
const path = `cost_per_kandangs[${kandangExpenseIdx}].cost_items`;
// trims values, errors, and touched at expenseIdx
removeArrayItemAndSync(formik, path, expenseIdx);
};
const isExpenseRepeaterInputError = (
column: 'nonstock' | 'totalQuantity' | 'totalExpense' | 'notes',
column: 'nonstock' | 'quantity' | 'total_cost' | 'notes',
kandangExpenseIdx: number,
expenseIdx: number
) => {
return (
formik.touched.kandangExpenses?.[kandangExpenseIdx]?.expenses?.[
formik.touched.cost_per_kandangs?.[kandangExpenseIdx]?.cost_items?.[
expenseIdx
]?.[column] &&
Boolean(
formik.errors.kandangExpenses?.[kandangExpenseIdx] instanceof Object &&
formik.errors.kandangExpenses?.[kandangExpenseIdx].expenses?.[
formik.errors.cost_per_kandangs?.[kandangExpenseIdx] instanceof
Object &&
formik.errors.cost_per_kandangs?.[kandangExpenseIdx].cost_items?.[
expenseIdx
] instanceof Object &&
formik.errors.kandangExpenses?.[kandangExpenseIdx].expenses?.[
formik.errors.cost_per_kandangs?.[kandangExpenseIdx].cost_items?.[
expenseIdx
]?.[column]
)
@@ -112,7 +113,8 @@ const ExpenseRequestKandangDetailExpense: React.FC<
</div>
<div className='w-full flex flex-col gap-6'>
{formik.values.kandangExpenses.length === 0 && (
{(formik.values.cost_per_kandangs.length === 0 ||
!formik.values.supplier?.value) && (
<div>
<p className='text-sm text-gray-400 text-center'>
Pilih kandang terlebih dahulu!
@@ -120,168 +122,171 @@ const ExpenseRequestKandangDetailExpense: React.FC<
</div>
)}
{formik.values.kandangExpenses.map(
(kandangExpense, kandangExpenseIdx) => {
const kandangName = formik.values.kandangs?.find(
(kandang) => kandang.id === kandangExpense.kandangId
);
{formik.values.cost_per_kandangs.length > 0 &&
formik.values.supplier?.value &&
formik.values.cost_per_kandangs.map(
(kandangExpense, kandangExpenseIdx) => {
const kandangName = formik.values.kandangs?.find(
(kandang) => kandang.id === kandangExpense.kandang_id
);
return (
kandangName?.name && (
<div
key={`kandangExpense-${kandangExpenseIdx}`}
className='w-full flex flex-col gap-4'
>
<div>
<h5 className='mb-2 text-lg font-bold text-center'>
Biaya {kandangName?.name}
</h5>
return (
kandangName?.name && (
<div
key={`kandangExpense-${kandangExpenseIdx}`}
className='w-full flex flex-col gap-4'
>
<div>
<h5 className='mb-2 text-lg font-bold text-center'>
Biaya {kandangName?.name}
</h5>
<div className='overflow-x-auto'>
<table className='table'>
<thead>
<tr>
<th>Nonstock</th>
<th>Total Kuantitas</th>
<th>Total Biaya</th>
<th>Catatan</th>
{type !== 'detail' && <th>Aksi</th>}
</tr>
</thead>
<div className='overflow-x-auto'>
<table className='table'>
<thead>
<tr>
<th>Nonstock</th>
<th>Total Kuantitas</th>
<th>Total Biaya</th>
<th>Catatan</th>
{type !== 'detail' && <th>Aksi</th>}
</tr>
</thead>
<tbody>
{kandangExpense.expenses.map(
(expenseItem, expenseIdx) => (
<tr key={`expense-${expenseIdx}`}>
<td className='p-2'>
<SelectInput
placeholder='Pilih Nonstock'
value={expenseItem.nonstock}
onChange={(val) => {
nonstockChangeHandler(
kandangExpenseIdx,
expenseIdx,
val
);
}}
options={nonstockOptions}
isLoading={isLoadingNonstockOptions}
onInputChange={setNonstockInputValue}
className={{ wrapper: 'min-w-48' }}
/>
</td>
<td className='p-2'>
<NumberInput
required
name={`kandangExpenses[${kandangExpenseIdx}].expenses[${expenseIdx}].totalQuantity`}
placeholder='Masukkan Total Kuantitas'
value={
formik.values.kandangExpenses[
kandangExpenseIdx
].expenses[expenseIdx].totalQuantity ?? ''
}
onChange={formik.handleChange}
onBlur={formik.handleBlur}
isError={isExpenseRepeaterInputError(
'totalQuantity',
kandangExpenseIdx,
expenseIdx
)}
className={{ wrapper: 'min-w-24' }}
/>
</td>
<td className='p-2'>
<NumberInput
name={`kandangExpenses[${kandangExpenseIdx}].expenses[${expenseIdx}].totalExpense`}
placeholder='Masukkan Total Biaya'
value={
formik.values.kandangExpenses[
kandangExpenseIdx
].expenses[expenseIdx].totalExpense ?? ''
}
onChange={formik.handleChange}
onBlur={formik.handleBlur}
isError={isExpenseRepeaterInputError(
'totalExpense',
kandangExpenseIdx,
expenseIdx
)}
inputPrefix={
<span className='text-gray-600 font-medium'>
Rp
</span>
}
className={{ wrapper: 'min-w-24' }}
/>
</td>
<td className='p-2'>
<TextInput
name={`kandangExpenses[${kandangExpenseIdx}].expenses[${expenseIdx}].notes`}
placeholder='Tuliskan catatan'
value={
formik.values.kandangExpenses[
kandangExpenseIdx
].expenses[expenseIdx].notes ?? ''
}
onChange={formik.handleChange}
onBlur={formik.handleBlur}
isError={isExpenseRepeaterInputError(
'notes',
kandangExpenseIdx,
expenseIdx
)}
className={{ wrapper: 'min-w-24' }}
/>
</td>
{type !== 'detail' && (
<td>
<Button
type='button'
color='error'
onClick={() =>
deleteExpenseItemHandler(
<tbody>
{kandangExpense.cost_items.map(
(expenseItem, expenseIdx) => (
<tr key={`expense-${expenseIdx}`}>
<td className='p-2'>
<SelectInput
placeholder='Pilih Nonstock'
value={expenseItem.nonstock}
onChange={(val) => {
nonstockChangeHandler(
kandangExpenseIdx,
expenseIdx
)
}
>
<Icon
icon='material-symbols:delete-outline-rounded'
width={24}
height={24}
/>
</Button>
expenseIdx,
val
);
}}
options={nonstockOptions}
isLoading={isLoadingNonstockOptions}
onInputChange={setNonstockInputValue}
className={{ wrapper: 'min-w-48' }}
/>
</td>
)}
</tr>
)
)}
</tbody>
</table>
</div>
</div>
{type !== 'detail' && (
<Button
type='button'
variant='outline'
color='success'
onClick={() => addExpenseItemHandler(kandangExpenseIdx)}
className='w-fit mx-auto'
>
<Icon icon='ic:round-plus' width={24} height={24} />{' '}
Tambah
</Button>
)}
</div>
)
);
}
)}
<td className='p-2'>
<NumberInput
required
name={`cost_per_kandangs[${kandangExpenseIdx}].cost_items[${expenseIdx}].quantity`}
placeholder='Masukkan Total Kuantitas'
value={
formik.values.cost_per_kandangs[
kandangExpenseIdx
].cost_items[expenseIdx].quantity ?? ''
}
onChange={formik.handleChange}
onBlur={formik.handleBlur}
isError={isExpenseRepeaterInputError(
'quantity',
kandangExpenseIdx,
expenseIdx
)}
className={{ wrapper: 'min-w-24' }}
/>
</td>
<td className='p-2'>
<NumberInput
name={`cost_per_kandangs[${kandangExpenseIdx}].cost_items[${expenseIdx}].total_cost`}
placeholder='Masukkan Total Biaya'
value={
formik.values.cost_per_kandangs[
kandangExpenseIdx
].cost_items[expenseIdx].total_cost ??
''
}
onChange={formik.handleChange}
onBlur={formik.handleBlur}
isError={isExpenseRepeaterInputError(
'total_cost',
kandangExpenseIdx,
expenseIdx
)}
inputPrefix={
<span className='text-gray-600 font-medium'>
Rp
</span>
}
className={{ wrapper: 'min-w-24' }}
/>
</td>
<td className='p-2'>
<TextInput
name={`cost_per_kandangs[${kandangExpenseIdx}].cost_items[${expenseIdx}].notes`}
placeholder='Tuliskan catatan'
value={
formik.values.cost_per_kandangs[
kandangExpenseIdx
].cost_items[expenseIdx].notes ?? ''
}
onChange={formik.handleChange}
onBlur={formik.handleBlur}
isError={isExpenseRepeaterInputError(
'notes',
kandangExpenseIdx,
expenseIdx
)}
className={{ wrapper: 'min-w-24' }}
/>
</td>
{type !== 'detail' && (
<td>
<Button
type='button'
color='error'
onClick={() =>
deleteExpenseItemHandler(
kandangExpenseIdx,
expenseIdx
)
}
>
<Icon
icon='material-symbols:delete-outline-rounded'
width={24}
height={24}
/>
</Button>
</td>
)}
</tr>
)
)}
</tbody>
</table>
</div>
</div>
{type !== 'detail' && (
<Button
type='button'
variant='outline'
color='success'
onClick={() => addExpenseItemHandler(kandangExpenseIdx)}
className='w-fit mx-auto'
>
<Icon icon='ic:round-plus' width={24} height={24} />{' '}
Tambah
</Button>
)}
</div>
)
);
}
)}
</div>
</Card>
);
@@ -0,0 +1,651 @@
'use client';
import {
Document,
Image,
Link,
Page,
StyleSheet,
Text,
View,
} from '@react-pdf/renderer';
import { Expense } from '@/types/api/expense';
import { formatCurrency, formatDate, formatNumber } from '@/lib/helper';
interface ExpensePDFProps {
expense?: Expense;
}
const ExpensePDFStyle = StyleSheet.create({
page: {
paddingTop: 24,
paddingBottom: 64,
paddingHorizontal: 32,
},
companyInfoHeader: {
width: '100%',
display: 'flex',
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'flex-start',
marginBottom: 8,
},
companyLogo: {
width: 64,
height: 'auto',
},
companyInfoHeaderDate: {
paddingTop: 8,
fontSize: 12,
},
companyName: {
fontSize: 12,
fontWeight: 'bold',
marginBottom: 4,
},
companyAddress: {
fontSize: 8,
maxWidth: 400,
marginBottom: 10,
},
title: {
marginTop: 16,
fontSize: 16,
lineHeight: '150%',
textAlign: 'center',
fontFamily: 'Times-Roman',
fontWeight: 'bold',
},
footer: {
width: '100%',
display: 'flex',
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
paddingHorizontal: 32,
position: 'absolute',
fontSize: 10,
bottom: 30,
left: 0,
right: 0,
textAlign: 'center',
color: 'grey',
},
// wrapper
generalInfoTable: {
width: '100%',
marginTop: 8,
borderWidth: 1,
borderColor: '#000000',
borderBottomWidth: 0,
fontSize: 12,
},
generalInfoTableRow: {
flexDirection: 'row',
borderBottomWidth: 1,
borderBottomColor: '#000000',
},
// columns
generalInfoTableColLabel: {
width: '30%',
paddingVertical: 6,
paddingHorizontal: 8,
},
generalInfoTableColSeparator: {
width: '3%',
justifyContent: 'center',
alignItems: 'center',
paddingVertical: 6,
},
generalInfoTableColValue: {
width: '67%',
paddingVertical: 6,
paddingHorizontal: 8,
},
generalInfoTableLabelText: {
fontWeight: 'bold',
},
generalInfoTableValueText: {},
// expense detail table
expenseDetailContainer: {
width: '100%',
marginTop: 12,
},
expenseDetailTitle: {
fontSize: 14,
lineHeight: '150%',
fontFamily: 'Times-Roman',
fontWeight: 'bold',
textAlign: 'center',
},
kandangExpenseContainer: {
width: '100%',
marginTop: 8,
},
kandangExpenseTitle: {
fontSize: 14,
lineHeight: '150%',
fontFamily: 'Times-Roman',
fontWeight: 'bold',
textAlign: 'center',
},
kandangExpenseTable: {
width: '100%',
marginTop: 8,
borderWidth: 1,
borderColor: '#000000',
borderBottomWidth: 0,
fontSize: 12,
},
kandangExpenseTableRow: {
flexDirection: 'row',
borderBottomWidth: 1,
borderBottomColor: '#000000',
},
kandangExpenseTableColLabel: {
width: '20%',
paddingVertical: 6,
paddingHorizontal: 8,
},
kandangExpenseTableColLabelBorderRight: {
borderRight: '1px solid #000000',
},
kandangExpenseTableColNonstock: {
width: '20%',
},
kandangExpenseTableColNote: {
width: '40%',
},
kandangExpenseHeaderLabelText: {
fontWeight: 'bold',
},
kandangExpenseLabelText: {
fontSize: 10,
},
kandangExpenseTableFooterColTotalExpenseCaption: {
width: '40%',
paddingVertical: 6,
paddingHorizontal: 8,
textAlign: 'right',
},
kandangExpenseTableFooterColTotalExpenseValue: {
width: '60%',
paddingVertical: 6,
paddingHorizontal: 8,
},
// utils
doubleDivider: {
width: '100%',
height: 6,
borderTop: '2px solid black',
borderBottom: '2px solid black',
},
});
const ExpensePDF = ({ expense }: ExpensePDFProps) => {
const isLatestApprovalRejected =
expense?.latest_approval?.action === 'REJECTED';
const isExpenseRealized =
expense?.latest_approval?.step_number &&
expense?.latest_approval.step_number >= 4;
const realizationStatus = isExpenseRealized
? 'Sudah Realisasi'
: 'Belum Realisasi';
const rows = [
{ label: 'Nomor PO', value: expense?.po_number },
{ label: 'Nomor Referensi', value: expense?.reference_number },
{
label: 'Kategori',
value:
expense?.category === 'BOP'
? 'Biaya Operasional'
: expense?.category === 'NON-BOP'
? 'Non Biaya Operasional'
: '',
},
{ label: 'Lokasi', value: expense?.location.name },
{
label: 'Kandang',
value: expense?.kandangs.map((item) => item.name).join(', '),
},
{ label: 'Vendor', value: expense?.supplier.name },
{
label: 'Tanggal Transaksi',
value: formatDate(expense?.expense_date, 'DD MMMM YYYY'),
},
{
label: 'Tanggal Realisasi',
value: expense?.realization_date
? formatDate(expense?.realization_date, 'DD MMMM YYYY')
: '-',
},
{ label: 'Nama Pengaju', value: expense?.created_user.name },
{
label: 'Nominal Biaya',
value: formatCurrency(expense?.grand_total ?? 0),
},
{
label: 'Nominal Pengajuan',
value: formatCurrency(expense?.total_pengajuan ?? 0),
},
{
label: 'Nominal Realisasi',
value: expense?.total_realisasi
? formatCurrency(expense?.total_realisasi ?? 0)
: '-',
},
{ label: 'Status Pencairan', value: realizationStatus },
{
label: 'Status Biaya',
value: isLatestApprovalRejected
? 'Ditolak'
: expense?.latest_approval?.step_name,
},
];
return (
<Document>
<Page style={ExpensePDFStyle.page}>
<View>
<View style={ExpensePDFStyle.companyInfoHeader}>
<Image
style={ExpensePDFStyle.companyLogo}
src='/assets/img/lti-logo.png'
/>
<Text style={ExpensePDFStyle.companyInfoHeaderDate}>
{formatDate(Date.now(), 'DD MMMM YYYY')}
</Text>
</View>
<View>
<Text style={ExpensePDFStyle.companyName}>
PT LUMBUNG TELUR INDONESIA
</Text>
<Text style={ExpensePDFStyle.companyAddress}>
SOHO Building Lt.3 (Paris Van Java), Jalan Karang Tinggal, Kel.
Cipedes, Kec. Sukajadi, Kota Bandung 40162
</Text>
<View style={ExpensePDFStyle.doubleDivider} />
</View>
</View>
<Text style={ExpensePDFStyle.title}>
Laporan{' '}
{expense?.category === 'BOP'
? 'Biaya Operasional'
: 'Non-Biaya Operasional'}{' '}
{expense?.po_number}
</Text>
{/* General info table */}
<View style={ExpensePDFStyle.generalInfoTable}>
{rows.map((row) => (
<View style={ExpensePDFStyle.generalInfoTableRow} key={row.label}>
<View style={ExpensePDFStyle.generalInfoTableColLabel}>
<Text style={ExpensePDFStyle.generalInfoTableLabelText}>
{row.label}
</Text>
</View>
<View style={ExpensePDFStyle.generalInfoTableColSeparator}>
<Text>:</Text>
</View>
<View style={ExpensePDFStyle.generalInfoTableColValue}>
<Text style={ExpensePDFStyle.generalInfoTableValueText}>
{row.value}
</Text>
</View>
</View>
))}
</View>
{/* Detail expense request */}
<View
minPresenceAhead={80}
style={ExpensePDFStyle.expenseDetailContainer}
>
<Text style={ExpensePDFStyle.expenseDetailTitle}>
Rincian Pengajuan Biaya Operasional
</Text>
{expense?.kandangs.map((kandangExpense, kandangExpenseIdx) => {
let expenseRequestTotal = 0;
kandangExpense.pengajuans?.forEach(
(item) => (expenseRequestTotal += item.total_price)
);
return (
<View
key={kandangExpenseIdx}
style={ExpensePDFStyle.kandangExpenseContainer}
>
<Text style={ExpensePDFStyle.kandangExpenseTitle}>
{kandangExpense.name}
</Text>
<View style={ExpensePDFStyle.kandangExpenseTable}>
<View style={[ExpensePDFStyle.kandangExpenseTableRow]}>
<View
style={[
ExpensePDFStyle.kandangExpenseTableColLabel,
ExpensePDFStyle.kandangExpenseTableColLabelBorderRight,
ExpensePDFStyle.kandangExpenseTableColNonstock,
]}
>
<Text
style={ExpensePDFStyle.kandangExpenseHeaderLabelText}
>
Nonstock
</Text>
</View>
<View
style={[
ExpensePDFStyle.kandangExpenseTableColLabel,
ExpensePDFStyle.kandangExpenseTableColLabelBorderRight,
]}
>
<Text
style={ExpensePDFStyle.kandangExpenseHeaderLabelText}
>
Kuantitas
</Text>
</View>
<View
style={[
ExpensePDFStyle.kandangExpenseTableColLabel,
ExpensePDFStyle.kandangExpenseTableColLabelBorderRight,
]}
>
<Text
style={ExpensePDFStyle.kandangExpenseHeaderLabelText}
>
Total Biaya
</Text>
</View>
<View
style={[
ExpensePDFStyle.kandangExpenseTableColLabel,
ExpensePDFStyle.kandangExpenseTableColNote,
]}
>
<Text
style={ExpensePDFStyle.kandangExpenseHeaderLabelText}
>
Catatan
</Text>
</View>
</View>
{kandangExpense.pengajuans?.map((pengajuan, pengajuanIdx) => (
<View
key={pengajuanIdx}
style={ExpensePDFStyle.kandangExpenseTableRow}
>
<View
style={[
ExpensePDFStyle.kandangExpenseTableColLabel,
ExpensePDFStyle.kandangExpenseTableColLabelBorderRight,
ExpensePDFStyle.kandangExpenseTableColNonstock,
]}
>
<Text style={ExpensePDFStyle.kandangExpenseLabelText}>
{pengajuan.nonstock.name}
</Text>
</View>
<View
style={[
ExpensePDFStyle.kandangExpenseTableColLabel,
ExpensePDFStyle.kandangExpenseTableColLabelBorderRight,
]}
>
<Text style={ExpensePDFStyle.kandangExpenseLabelText}>
{formatNumber(pengajuan.qty)}
</Text>
</View>
<View
style={[
ExpensePDFStyle.kandangExpenseTableColLabel,
ExpensePDFStyle.kandangExpenseTableColLabelBorderRight,
]}
>
<Text style={ExpensePDFStyle.kandangExpenseLabelText}>
{formatCurrency(pengajuan.total_price)}
</Text>
</View>
<View
style={[
ExpensePDFStyle.kandangExpenseTableColLabel,
ExpensePDFStyle.kandangExpenseTableColNote,
]}
>
<Text style={ExpensePDFStyle.kandangExpenseLabelText}>
{pengajuan.note}
</Text>
</View>
</View>
))}
<View style={[ExpensePDFStyle.kandangExpenseTableRow]}>
<View
style={[
ExpensePDFStyle.kandangExpenseTableFooterColTotalExpenseCaption,
ExpensePDFStyle.kandangExpenseTableColLabelBorderRight,
]}
>
<Text
style={ExpensePDFStyle.kandangExpenseHeaderLabelText}
>
Total Biaya Keseluruhan
</Text>
</View>
<View
style={[
ExpensePDFStyle.kandangExpenseTableFooterColTotalExpenseValue,
]}
>
<Text
style={ExpensePDFStyle.kandangExpenseHeaderLabelText}
>
{formatCurrency(expenseRequestTotal)}
</Text>
</View>
</View>
</View>
</View>
);
})}
</View>
{/* Detail expense realization */}
<View
minPresenceAhead={80}
style={ExpensePDFStyle.expenseDetailContainer}
>
<Text style={ExpensePDFStyle.expenseDetailTitle}>
Rincian Realisasi Biaya Operasional
</Text>
{expense?.kandangs.map((kandangExpense, kandangExpenseIdx) => {
let expenseRealizationTotal = 0;
kandangExpense.realisasi?.forEach(
(item) => (expenseRealizationTotal += item.total_price)
);
return (
<View
key={kandangExpenseIdx}
style={ExpensePDFStyle.kandangExpenseContainer}
>
<Text style={ExpensePDFStyle.kandangExpenseTitle}>
{kandangExpense.name}
</Text>
<View style={ExpensePDFStyle.kandangExpenseTable}>
<View style={[ExpensePDFStyle.kandangExpenseTableRow]}>
<View
style={[
ExpensePDFStyle.kandangExpenseTableColLabel,
ExpensePDFStyle.kandangExpenseTableColLabelBorderRight,
ExpensePDFStyle.kandangExpenseTableColNonstock,
]}
>
<Text
style={ExpensePDFStyle.kandangExpenseHeaderLabelText}
>
Nonstock
</Text>
</View>
<View
style={[
ExpensePDFStyle.kandangExpenseTableColLabel,
ExpensePDFStyle.kandangExpenseTableColLabelBorderRight,
]}
>
<Text
style={ExpensePDFStyle.kandangExpenseHeaderLabelText}
>
Kuantitas
</Text>
</View>
<View
style={[
ExpensePDFStyle.kandangExpenseTableColLabel,
ExpensePDFStyle.kandangExpenseTableColLabelBorderRight,
]}
>
<Text
style={ExpensePDFStyle.kandangExpenseHeaderLabelText}
>
Total Biaya
</Text>
</View>
<View
style={[
ExpensePDFStyle.kandangExpenseTableColLabel,
ExpensePDFStyle.kandangExpenseTableColNote,
]}
>
<Text
style={ExpensePDFStyle.kandangExpenseHeaderLabelText}
>
Catatan
</Text>
</View>
</View>
{kandangExpense.realisasi?.map((realisasi, realisasiIdx) => (
<View
key={realisasiIdx}
style={ExpensePDFStyle.kandangExpenseTableRow}
>
<View
style={[
ExpensePDFStyle.kandangExpenseTableColLabel,
ExpensePDFStyle.kandangExpenseTableColLabelBorderRight,
ExpensePDFStyle.kandangExpenseTableColNonstock,
]}
>
<Text style={ExpensePDFStyle.kandangExpenseLabelText}>
{realisasi.nonstock.name}
</Text>
</View>
<View
style={[
ExpensePDFStyle.kandangExpenseTableColLabel,
ExpensePDFStyle.kandangExpenseTableColLabelBorderRight,
]}
>
<Text style={ExpensePDFStyle.kandangExpenseLabelText}>
{formatNumber(realisasi.qty)}
</Text>
</View>
<View
style={[
ExpensePDFStyle.kandangExpenseTableColLabel,
ExpensePDFStyle.kandangExpenseTableColLabelBorderRight,
]}
>
<Text style={ExpensePDFStyle.kandangExpenseLabelText}>
{formatCurrency(realisasi.total_price)}
</Text>
</View>
<View
style={[
ExpensePDFStyle.kandangExpenseTableColLabel,
ExpensePDFStyle.kandangExpenseTableColNote,
]}
>
<Text style={ExpensePDFStyle.kandangExpenseLabelText}>
{realisasi.note}
</Text>
</View>
</View>
))}
<View style={[ExpensePDFStyle.kandangExpenseTableRow]}>
<View
style={[
ExpensePDFStyle.kandangExpenseTableFooterColTotalExpenseCaption,
ExpensePDFStyle.kandangExpenseTableColLabelBorderRight,
]}
>
<Text
style={ExpensePDFStyle.kandangExpenseHeaderLabelText}
>
Total Biaya Keseluruhan
</Text>
</View>
<View
style={[
ExpensePDFStyle.kandangExpenseTableFooterColTotalExpenseValue,
]}
>
<Text
style={ExpensePDFStyle.kandangExpenseHeaderLabelText}
>
{formatCurrency(expenseRealizationTotal)}
</Text>
</View>
</View>
</View>
</View>
);
})}
</View>
<View style={ExpensePDFStyle.footer} fixed>
<Link
src={`${process.env.NEXT_PUBLIC_LTI_URL}expense/detail?expenseId=${expense?.id}`}
>
{expense?.po_number}
</Link>
<Text
render={({ pageNumber, totalPages }) =>
`${pageNumber} / ${totalPages}`
}
fixed
/>
</View>
</Page>
</Document>
);
};
export default ExpensePDF;
@@ -0,0 +1,53 @@
'use client';
import { pdf } from '@react-pdf/renderer';
import Button from '@/components/Button';
import { Icon } from '@iconify/react';
import ExpensePDF from '@/components/pages/expense/pdf/ExpensePDF';
import { Expense } from '@/types/api/expense';
interface ExpensePDFPreviewButtonProps {
expense?: Expense;
}
const ExpensePDFPreviewButton = ({ expense }: ExpensePDFPreviewButtonProps) => {
const openPdf = async () => {
const expensePdfBlob = await pdf(<ExpensePDF expense={expense} />).toBlob();
const expensePdfUrl = URL.createObjectURL(expensePdfBlob);
window.open(expensePdfUrl, '_blank');
};
const downloadPdf = async () => {
const blob = await pdf(<ExpensePDF expense={expense} />).toBlob();
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = `${expense?.po_number}.pdf`;
link.click();
URL.revokeObjectURL(url);
};
return (
<div className='w-fit flex flex-col'>
<Button onClick={downloadPdf} className='text-xs'>
<Icon icon='bx:file' width={16} height={16} />
{expense?.po_number}
</Button>
<Button
onClick={openPdf}
variant='link'
className='p-0 mt-1 text-xs justify-start'
>
Lihat Dokumen
</Button>
</div>
);
};
export default ExpensePDFPreviewButton;
+1 -1
View File
@@ -123,7 +123,7 @@ export const EXPENSE_REQUEST_APPROVAL_LINE: ApprovalLine = [
},
{
step_number: 2,
step_name: 'Approval Manager Area',
step_name: 'Approval Manager',
},
{
step_number: 3,
+23
View File
@@ -0,0 +1,23 @@
import axios from 'axios';
import { httpClient } from '@/services/http/client';
import { BaseApiResponse, LogoutResponse } from '@/types/api/api-general';
export class AuthApiService {
async logout() {
try {
const logoutRes = await httpClient<LogoutResponse>(`/sso/logout`, {
method: 'POST',
});
return logoutRes;
} catch (error) {
if (axios.isAxiosError<BaseApiResponse>(error)) {
return error.response?.data;
}
return undefined;
}
}
}
export const AuthApi = new AuthApiService();
+477 -1037
View File
File diff suppressed because it is too large Load Diff
+13 -1
View File
@@ -1,10 +1,22 @@
import axios from 'axios';
import type { AxiosRequestConfig } from 'axios';
import type { AxiosError, AxiosRequestConfig } from 'axios';
import { RequestOptions } from '@/services/http/base';
const BASE_URL = process.env.NEXT_PUBLIC_API_BASE_URL ?? '';
const axiosClient = axios.create({ baseURL: BASE_URL, timeout: 10_000 });
axiosClient.interceptors.response.use(
(response) => response,
(error: AxiosError) => {
if (error.response?.status === 401) {
const ssoLoginUrl = `${process.env.NEXT_PUBLIC_SSO_LOGIN_URL as string}?redirect_url=${window.location.href}`;
window.location.href = ssoLoginUrl;
}
return Promise.reject(error);
}
);
export async function httpClient<T, B = unknown>(
path: string,
opts: RequestOptions<B> = {}
+89 -36
View File
@@ -1,54 +1,107 @@
import { BaseApproval, BaseMetadata } from '@/types/api/api-general';
import { Location } from '@/types/api/master-data/location';
import { Kandang } from '@/types/api/master-data/kandang';
import { Supplier } from '@/types/api/master-data/supplier';
import { Nonstock } from '@/types/api/master-data/nonstock';
import { BaseLocation, Location } from '@/types/api/master-data/location';
import { BaseKandang, Kandang } from '@/types/api/master-data/kandang';
import { BaseSupplier, Supplier } from '@/types/api/master-data/supplier';
import { BaseNonstock, Nonstock } from '@/types/api/master-data/nonstock';
import { BaseUser } from '@/types/api/user';
export type BaseExpense = {
id: number;
reference_number: string;
po_number?: string;
location: Location;
transaction_date: string;
realization_date?: string;
kandangs: Kandang[];
vendor: Supplier;
request_documents: {
name: string;
url: string;
po_number: string | null;
category: 'BOP' | 'NON-BOP';
documents?: {
id: number;
path: string;
}[];
kandang_expenses: {
kandang: Kandang;
expenses: {
nonstock: Nonstock;
total_quantity: number;
total_expense: number;
notes?: string;
realization_docs?: {
id: number;
path: string;
}[];
expense_date: string;
realization_date?: string;
grand_total: number;
location: BaseLocation;
supplier: BaseSupplier;
kandangs: {
id: number;
kandang_id: number;
name: string;
pengajuans?: {
id: number;
qty: number;
unit_price: number;
total_price: number;
note?: string;
nonstock: Pick<BaseNonstock, 'id' | 'name' | 'flags'>;
project_flock_kandang: {
id: number;
kandang_id: number;
};
}[];
realisasi?: {
id: number;
qty: number;
unit_price: number;
total_price: number;
date: string;
note?: string;
nonstock: Pick<BaseNonstock, 'id' | 'name' | 'flags'>;
project_flock_kandang: {
id: number;
kandang_id: number;
};
}[];
}[];
nominal: number;
paid?: number;
remaining_cost?: number;
approval: BaseApproval;
total_pengajuan: number;
total_realisasi: number;
latest_approval: BaseApproval;
};
export type Expense = BaseMetadata & BaseExpense;
export type CreateExpensePayload = {
locationId: number;
category: 'BOP' | 'NON-BOP';
transaction_date: string;
kandangIds: number[];
vendorId: number;
request_documents: File[];
kandang_expenses: {
kandangId: number;
expenses: {
nonstockId: number;
total_quantity: number;
total_expense: number;
notes?: string;
supplier_id: number;
documents: File[];
cost_per_kandangs: {
kandang_id: number;
cost_items: {
nonstock_id: number;
quantity: number;
total_cost: number;
notes: string;
}[];
}[];
};
export type UpdateExpensePayload = CreateExpensePayload;
export type UpdateExpensePayload = {
category: 'BOP' | 'NON-BOP';
transaction_date: string;
supplier_id: number;
documents: File[];
cost_per_kandang: {
kandang_id: number;
cost_items: {
nonstock_id: number;
quantity: number;
total_cost: number;
notes: string;
}[];
}[];
};
export type CreateExpenseRealizationPayload = {
realization_date: string;
documents: File[];
realizations: {
expense_nonstock_id: number;
qty: number;
unit_price: number;
total_price: number;
notes: string;
}[];
};
export type UpdateExpenseRealizationPayload = CreateExpenseRealizationPayload;