mirror of
https://gitlab.com/mbugroup/lti-web-client.git
synced 2026-05-20 05:22:02 +00:00
feat(FE): adding export xlsx for report expense, change report data fetching, adding progress bar
This commit is contained in:
Generated
+21
-8
@@ -15,7 +15,7 @@
|
||||
"clsx": "^2.1.1",
|
||||
"formik": "^2.4.6",
|
||||
"moment": "^2.30.1",
|
||||
"next": "15.5.7",
|
||||
"next": "15.5.9",
|
||||
"react": "19.1.0",
|
||||
"react-day-picker": "^9.11.1",
|
||||
"react-dom": "19.1.0",
|
||||
@@ -26,6 +26,7 @@
|
||||
"swr": "^2.3.6",
|
||||
"tailwind-merge": "^3.3.1",
|
||||
"use-debounce": "^10.0.6",
|
||||
"xlsx": "https://cdn.sheetjs.com/xlsx-0.20.3/xlsx-0.20.3.tgz",
|
||||
"yup": "^1.7.0",
|
||||
"zustand": "^5.0.8"
|
||||
},
|
||||
@@ -1082,9 +1083,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@next/env": {
|
||||
"version": "15.5.7",
|
||||
"resolved": "https://registry.npmjs.org/@next/env/-/env-15.5.7.tgz",
|
||||
"integrity": "sha512-4h6Y2NyEkIEN7Z8YxkA27pq6zTkS09bUSYC0xjd0NpwFxjnIKeZEeH591o5WECSmjpUhLn3H2QLJcDye3Uzcvg==",
|
||||
"version": "15.5.9",
|
||||
"resolved": "https://registry.npmjs.org/@next/env/-/env-15.5.9.tgz",
|
||||
"integrity": "sha512-4GlTZ+EJM7WaW2HEZcyU317tIQDjkQIyENDLxYJfSWlfqguN+dHkZgyQTV/7ykvobU7yEH5gKvreNrH4B6QgIg==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@next/eslint-plugin-next": {
|
||||
@@ -5654,12 +5655,12 @@
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/next": {
|
||||
"version": "15.5.7",
|
||||
"resolved": "https://registry.npmjs.org/next/-/next-15.5.7.tgz",
|
||||
"integrity": "sha512-+t2/0jIJ48kUpGKkdlhgkv+zPTEOoXyr60qXe68eB/pl3CMJaLeIGjzp5D6Oqt25hCBiBTt8wEeeAzfJvUKnPQ==",
|
||||
"version": "15.5.9",
|
||||
"resolved": "https://registry.npmjs.org/next/-/next-15.5.9.tgz",
|
||||
"integrity": "sha512-agNLK89seZEtC5zUHwtut0+tNrc0Xw4FT/Dg+B/VLEo9pAcS9rtTKpek3V6kVcVwsB2YlqMaHdfZL4eLEVYuCg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@next/env": "15.5.7",
|
||||
"@next/env": "15.5.9",
|
||||
"@swc/helpers": "0.5.15",
|
||||
"caniuse-lite": "^1.0.30001579",
|
||||
"postcss": "8.4.31",
|
||||
@@ -7525,6 +7526,18 @@
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/xlsx": {
|
||||
"version": "0.20.3",
|
||||
"resolved": "https://cdn.sheetjs.com/xlsx-0.20.3/xlsx-0.20.3.tgz",
|
||||
"integrity": "sha512-oLDq3jw7AcLqKWH2AhCpVTZl8mf6X2YReP+Neh0SJUzV/BdZYjth94tG5toiMB1PPrYtxOCfaoUCkvtuH+3AJA==",
|
||||
"license": "Apache-2.0",
|
||||
"bin": {
|
||||
"xlsx": "bin/xlsx.njs"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=0.8"
|
||||
}
|
||||
},
|
||||
"node_modules/yaml": {
|
||||
"version": "1.10.2",
|
||||
"resolved": "https://registry.npmjs.org/yaml/-/yaml-1.10.2.tgz",
|
||||
|
||||
+2
-1
@@ -18,7 +18,7 @@
|
||||
"clsx": "^2.1.1",
|
||||
"formik": "^2.4.6",
|
||||
"moment": "^2.30.1",
|
||||
"next": "15.5.7",
|
||||
"next": "15.5.9",
|
||||
"react": "19.1.0",
|
||||
"react-day-picker": "^9.11.1",
|
||||
"react-dom": "19.1.0",
|
||||
@@ -29,6 +29,7 @@
|
||||
"swr": "^2.3.6",
|
||||
"tailwind-merge": "^3.3.1",
|
||||
"use-debounce": "^10.0.6",
|
||||
"xlsx": "https://cdn.sheetjs.com/xlsx-0.20.3/xlsx-0.20.3.tgz",
|
||||
"yup": "^1.7.0",
|
||||
"zustand": "^5.0.8"
|
||||
},
|
||||
|
||||
@@ -1,48 +1,11 @@
|
||||
'use client';
|
||||
|
||||
import { useState } from 'react';
|
||||
import useSWR from 'swr';
|
||||
import ReportExpenseTable from '@/components/pages/report/expense/ReportExpenseTable';
|
||||
import { ReportExpenseApi } from '@/services/api/report';
|
||||
import { isResponseSuccess } from '@/lib/api-helper';
|
||||
import { ReportExpenseSearchParams } from '@/types/api/report/report-expense';
|
||||
|
||||
const ReportExpense = () => {
|
||||
const [params, setParams] = useState<ReportExpenseSearchParams>({
|
||||
locationId: null,
|
||||
supplierId: null,
|
||||
kandangId: null,
|
||||
nonstockId: null,
|
||||
realizationDate: null,
|
||||
category: null,
|
||||
search: '',
|
||||
});
|
||||
|
||||
const reportUrl = `${ReportExpenseApi.basePath}?${new URLSearchParams({
|
||||
location_id: params.locationId ?? '',
|
||||
supplier_id: params.supplierId ?? '',
|
||||
kandang_id: params.kandangId ?? '',
|
||||
nonstock_id: params.nonstockId ?? '',
|
||||
realization_date: params.realizationDate ?? '',
|
||||
category: params.category ?? '',
|
||||
search: params.search,
|
||||
})}`;
|
||||
const { data: reportExpenses } = useSWR(reportUrl, () =>
|
||||
ReportExpenseApi.getAllFetcher(reportUrl)
|
||||
);
|
||||
|
||||
const onSearch = (searchParams: ReportExpenseSearchParams) => {
|
||||
setParams(searchParams);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className='w-full p-4'>
|
||||
<ReportExpenseTable
|
||||
reportExpenses={
|
||||
isResponseSuccess(reportExpenses) ? reportExpenses.data : []
|
||||
}
|
||||
onSearch={onSearch}
|
||||
/>
|
||||
<ReportExpenseTable />
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
import Badge from '@/components/Badge';
|
||||
import { useState, useMemo, useCallback } from 'react';
|
||||
import { ChangeEventHandler } from 'react';
|
||||
import useSWR from 'swr';
|
||||
import Button from '@/components/Button';
|
||||
import Card from '@/components/Card';
|
||||
import DateInput from '@/components/input/DateInput';
|
||||
import DebouncedTextInput from '@/components/input/DebouncedTextInput';
|
||||
import NumberInput from '@/components/input/NumberInput';
|
||||
import SelectInput, {
|
||||
OptionType,
|
||||
useSelect,
|
||||
@@ -12,56 +13,517 @@ import ExpenseStatusBadge from '@/components/pages/expense/ExpenseStatusBadge';
|
||||
import RealizationStatusBadge from '@/components/pages/expense/RealizationStatusBadge';
|
||||
import Table, { TABLE_DEFAULT_STYLING } from '@/components/Table';
|
||||
import { cn, formatCurrency, formatDate } from '@/lib/helper';
|
||||
import {
|
||||
ReportExpense,
|
||||
ReportExpenseSearchParams,
|
||||
} from '@/types/api/report/report-expense';
|
||||
import { ReportExpense } from '@/types/api/report/report-expense';
|
||||
import { Icon } from '@iconify/react';
|
||||
import { ColumnDef } from '@tanstack/react-table';
|
||||
import { useMemo, useState } from 'react';
|
||||
import ReportExpenseExport from '@/components/pages/report/expense/pdf/ReportExpenseExport';
|
||||
import { ReportExpenseApi } from '@/services/api/report';
|
||||
import { isResponseSuccess } from '@/lib/api-helper';
|
||||
import { useTableFilter } from '@/services/hooks/useTableFilter';
|
||||
import Pagination from '@/components/Pagination';
|
||||
import Dropdown from '@/components/dropdown/Dropdown';
|
||||
import Menu from '@/components/menu/Menu';
|
||||
import MenuItem from '@/components/menu/MenuItem';
|
||||
import * as XLSX from 'xlsx';
|
||||
import { generateReportExpensePDF } from './pdf/ReportExpenseExport';
|
||||
import toast from 'react-hot-toast';
|
||||
|
||||
const ReportExpenseTable = ({
|
||||
reportExpenses,
|
||||
onSearch,
|
||||
}: {
|
||||
reportExpenses: ReportExpense[];
|
||||
onSearch: (params: ReportExpenseSearchParams) => void;
|
||||
}) => {
|
||||
const [selectedLocation, setSelectedLocation] = useState<OptionType | null>(
|
||||
null
|
||||
);
|
||||
const [selectedSupplier, setSelectedSupplier] = useState<OptionType | null>(
|
||||
null
|
||||
);
|
||||
const [selectedCategory, setSelectedCategory] = useState<OptionType | null>(
|
||||
null
|
||||
);
|
||||
const [selectedKandang, setSelectedKandang] = useState<OptionType | null>(
|
||||
null
|
||||
);
|
||||
const [selectedNonstock, setSelectedNonstock] = useState<OptionType | null>(
|
||||
null
|
||||
);
|
||||
const [search, setSearch] = useState('');
|
||||
const [realizationDate, setRealizationDate] = useState<string | null>(null);
|
||||
const ReportExpenseTable = () => {
|
||||
// ===== STATE MANAGEMENT =====
|
||||
const [isPdfExportLoading, setIsPdfExportLoading] = useState(false);
|
||||
const [isExcelExportLoading, setIsExcelExportLoading] = useState(false);
|
||||
const [dropdownOpen, setDropdownOpen] = useState(false);
|
||||
const [pdfProgress, setPdfProgress] = useState(0);
|
||||
const [excelProgress, setExcelProgress] = useState(0);
|
||||
const isAnyExportLoading = isPdfExportLoading || isExcelExportLoading;
|
||||
|
||||
// ===== SUBMISSION STATE =====
|
||||
const [isSubmitted, setIsSubmitted] = useState(false);
|
||||
|
||||
// ===== TABLE FILTER STATE =====
|
||||
const {
|
||||
state: filterState,
|
||||
updateFilter,
|
||||
setPage,
|
||||
setPageSize,
|
||||
reset: resetFilterState,
|
||||
toQueryString,
|
||||
} = useTableFilter({
|
||||
initial: {
|
||||
location_id: '',
|
||||
supplier_id: '',
|
||||
kandang_id: '',
|
||||
nonstock_id: '',
|
||||
realization_date: '',
|
||||
category: '',
|
||||
search: '',
|
||||
},
|
||||
paramMap: {
|
||||
page: 'page',
|
||||
pageSize: 'limit',
|
||||
},
|
||||
});
|
||||
|
||||
// ===== SELECT OPTIONS =====
|
||||
const { options: optionsLocation, isLoadingOptions: isLoadingLocation } =
|
||||
useSelect(`/master-data/locations`, 'id', 'name');
|
||||
const { options: optionsSupplier, isLoadingOptions: isLoadingSupplier } =
|
||||
useSelect(`/master-data/suppliers`, 'id', 'name');
|
||||
const { options: optionsKandang, isLoadingOptions: isLoadingKandang } =
|
||||
useSelect(`/master-data/kandangs`, 'id', 'name', '', {
|
||||
location_id: selectedLocation?.value.toString() || '',
|
||||
location_id: filterState.location_id,
|
||||
});
|
||||
const { options: optionsNonstock, isLoadingOptions: isLoadingNonstock } =
|
||||
useSelect(`/master-data/nonstocks`, 'id', 'name');
|
||||
|
||||
const categoryOptions = useMemo(
|
||||
() => [
|
||||
{ value: 'BOP', label: 'BOP' },
|
||||
{ value: 'NON-BOP', label: 'Non BOP' },
|
||||
],
|
||||
[]
|
||||
);
|
||||
|
||||
// Mendapatkan value option select dari filter state
|
||||
const selectedLocation = useMemo(
|
||||
() =>
|
||||
optionsLocation.find(
|
||||
(opt) => String(opt.value) === filterState.location_id
|
||||
) || null,
|
||||
[optionsLocation, filterState.location_id]
|
||||
);
|
||||
const selectedSupplier = useMemo(
|
||||
() =>
|
||||
optionsSupplier.find(
|
||||
(opt) => String(opt.value) === filterState.supplier_id
|
||||
) || null,
|
||||
[optionsSupplier, filterState.supplier_id]
|
||||
);
|
||||
const selectedKandang = useMemo(
|
||||
() =>
|
||||
optionsKandang.find(
|
||||
(opt) => String(opt.value) === filterState.kandang_id
|
||||
) || null,
|
||||
[optionsKandang, filterState.kandang_id]
|
||||
);
|
||||
const selectedNonstock = useMemo(
|
||||
() =>
|
||||
optionsNonstock.find(
|
||||
(opt) => String(opt.value) === filterState.nonstock_id
|
||||
) || null,
|
||||
[optionsNonstock, filterState.nonstock_id]
|
||||
);
|
||||
const selectedCategory = useMemo(
|
||||
() =>
|
||||
categoryOptions.find((opt) => opt.value === filterState.category) || null,
|
||||
[categoryOptions, filterState.category]
|
||||
);
|
||||
|
||||
// ===== FILTER CHANGE HANDLERS =====
|
||||
const locationChangeHandler = useCallback(
|
||||
(val: OptionType | OptionType[] | null) => {
|
||||
const option = val as OptionType;
|
||||
updateFilter('location_id', option ? String(option.value) : '');
|
||||
updateFilter('kandang_id', '');
|
||||
setIsSubmitted(false);
|
||||
},
|
||||
[updateFilter]
|
||||
);
|
||||
|
||||
const kandangChangeHandler = useCallback(
|
||||
(val: OptionType | OptionType[] | null) => {
|
||||
const option = val as OptionType;
|
||||
updateFilter('kandang_id', option ? String(option.value) : '');
|
||||
setIsSubmitted(false);
|
||||
},
|
||||
[updateFilter]
|
||||
);
|
||||
|
||||
const supplierChangeHandler = useCallback(
|
||||
(val: OptionType | OptionType[] | null) => {
|
||||
const option = val as OptionType;
|
||||
updateFilter('supplier_id', option ? String(option.value) : '');
|
||||
setIsSubmitted(false);
|
||||
},
|
||||
[updateFilter]
|
||||
);
|
||||
|
||||
const nonstockChangeHandler = useCallback(
|
||||
(val: OptionType | OptionType[] | null) => {
|
||||
const option = val as OptionType;
|
||||
updateFilter('nonstock_id', option ? String(option.value) : '');
|
||||
setIsSubmitted(false);
|
||||
},
|
||||
[updateFilter]
|
||||
);
|
||||
|
||||
const categoryChangeHandler = useCallback(
|
||||
(val: OptionType | OptionType[] | null) => {
|
||||
const option = val as OptionType;
|
||||
updateFilter('category', option ? String(option.value) : '');
|
||||
setIsSubmitted(false);
|
||||
},
|
||||
[updateFilter]
|
||||
);
|
||||
|
||||
const realizationDateChangeHandler = useCallback<
|
||||
ChangeEventHandler<HTMLInputElement>
|
||||
>(
|
||||
(e) => {
|
||||
updateFilter('realization_date', e.target.value || '');
|
||||
setIsSubmitted(false);
|
||||
},
|
||||
[updateFilter]
|
||||
);
|
||||
|
||||
const searchChangeHandler = useCallback(
|
||||
(e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
updateFilter('search', e.target.value);
|
||||
setIsSubmitted(false);
|
||||
},
|
||||
[updateFilter]
|
||||
);
|
||||
|
||||
// ===== RESET FILTERS =====
|
||||
const resetFilters = useCallback(() => {
|
||||
resetFilterState();
|
||||
setIsSubmitted(false);
|
||||
}, [resetFilterState]);
|
||||
|
||||
// ===== SUBMIT HANDLER =====
|
||||
const handleSubmit = useCallback(() => {
|
||||
setIsSubmitted(true);
|
||||
setPage(1);
|
||||
}, [setPage]);
|
||||
|
||||
// ===== DATA FETCHING FOR TABLE =====
|
||||
const { data: reportExpenseResponse, isLoading } = useSWR(
|
||||
isSubmitted
|
||||
? () => {
|
||||
return ['report-expense', toQueryString()];
|
||||
}
|
||||
: null,
|
||||
([, query]) => {
|
||||
const endpoint = `${ReportExpenseApi.basePath}${query}`;
|
||||
return ReportExpenseApi.getAllFetcher(endpoint);
|
||||
}
|
||||
);
|
||||
|
||||
const data: ReportExpense[] = useMemo(
|
||||
() =>
|
||||
isResponseSuccess(reportExpenseResponse)
|
||||
? (reportExpenseResponse?.data as ReportExpense[]) || []
|
||||
: [],
|
||||
[reportExpenseResponse]
|
||||
);
|
||||
|
||||
const meta = useMemo(
|
||||
() =>
|
||||
isResponseSuccess(reportExpenseResponse) && reportExpenseResponse.meta
|
||||
? reportExpenseResponse.meta
|
||||
: null,
|
||||
[reportExpenseResponse]
|
||||
);
|
||||
|
||||
// ===== EXPORT DATA FETCHER =====
|
||||
const reportExpenseExport = useCallback(async (): Promise<
|
||||
ReportExpense[] | null
|
||||
> => {
|
||||
const params = new URLSearchParams(toQueryString().replace('?', ''));
|
||||
params.set('limit', 'limit');
|
||||
params.set('page', '1');
|
||||
|
||||
const endpoint = `${ReportExpenseApi.basePath}?${params.toString()}`;
|
||||
const response = await ReportExpenseApi.getAllFetcher(endpoint);
|
||||
|
||||
return isResponseSuccess(response) ? response.data : null;
|
||||
}, [toQueryString]);
|
||||
|
||||
// ===== EXPORT HANDLERS =====
|
||||
const handleExportPdf = useCallback(async () => {
|
||||
if (isPdfExportLoading) return;
|
||||
setIsPdfExportLoading(true);
|
||||
setPdfProgress(0);
|
||||
|
||||
await new Promise((resolve) =>
|
||||
requestAnimationFrame(() => resolve(undefined))
|
||||
);
|
||||
|
||||
try {
|
||||
// Stage 1: Fetching data (0-20%)
|
||||
setPdfProgress(10);
|
||||
await new Promise((resolve) => setTimeout(resolve, 50));
|
||||
|
||||
const allData = await reportExpenseExport();
|
||||
if (!allData || allData.length === 0) {
|
||||
toast.error('Tidak ada data untuk diekspor.');
|
||||
setIsPdfExportLoading(false);
|
||||
setPdfProgress(0);
|
||||
return;
|
||||
}
|
||||
|
||||
// Stage 2: Data fetched - langsung loncat ke progress tinggi
|
||||
setPdfProgress(30);
|
||||
await new Promise((resolve) => setTimeout(resolve, 50));
|
||||
const progressInterval = setInterval(() => {
|
||||
setPdfProgress((prev) => {
|
||||
// Increment kecil dan random antara 0.5-2%
|
||||
const increment = Math.random() * 1.5 + 0.5;
|
||||
const newProgress = Math.min(prev + increment, 50);
|
||||
return newProgress;
|
||||
});
|
||||
}, 300); // Update setiap 300ms
|
||||
|
||||
const pdfParams = {
|
||||
location_name: selectedLocation?.label,
|
||||
supplier_name: selectedSupplier?.label,
|
||||
kandang_name: selectedKandang?.label,
|
||||
nonstock_name: selectedNonstock?.label,
|
||||
category: selectedCategory?.label,
|
||||
realization_date: filterState.realization_date,
|
||||
search: filterState.search,
|
||||
};
|
||||
|
||||
setDropdownOpen(false);
|
||||
|
||||
// Stage 3: Langsung loncat ke 80-85% untuk menghindari stuck
|
||||
const baseProgress = 80 + Math.floor(Math.random() * 16); // Random 80-85%
|
||||
setPdfProgress(baseProgress);
|
||||
await new Promise((resolve) => setTimeout(resolve, 100));
|
||||
|
||||
// Stage 4: Berikan jeda untuk UI update
|
||||
await new Promise((resolve) =>
|
||||
requestAnimationFrame(() => resolve(undefined))
|
||||
);
|
||||
|
||||
// Proses PDF yang sebenarnya
|
||||
await generateReportExpensePDF(allData, pdfParams);
|
||||
|
||||
clearInterval(progressInterval);
|
||||
|
||||
// Stage 5: Finalizing (98-100%)
|
||||
setPdfProgress(99);
|
||||
await new Promise((resolve) => setTimeout(resolve, 100));
|
||||
|
||||
setPdfProgress(100);
|
||||
toast.success('PDF berhasil dibuat dan diunduh.');
|
||||
|
||||
// Reset progress setelah selesai
|
||||
setTimeout(() => setPdfProgress(0), 500);
|
||||
} catch (error) {
|
||||
console.error('PDF Export Error:', error);
|
||||
toast.error('Gagal membuat PDF. Silakan coba lagi.');
|
||||
setPdfProgress(0);
|
||||
} finally {
|
||||
setIsPdfExportLoading(false);
|
||||
}
|
||||
}, [
|
||||
reportExpenseExport,
|
||||
selectedLocation,
|
||||
selectedSupplier,
|
||||
selectedKandang,
|
||||
selectedNonstock,
|
||||
selectedCategory,
|
||||
filterState.realization_date,
|
||||
filterState.search,
|
||||
]);
|
||||
|
||||
const handleExportExcel = useCallback(async () => {
|
||||
if (isExcelExportLoading) return;
|
||||
setIsExcelExportLoading(true);
|
||||
setExcelProgress(0);
|
||||
setDropdownOpen(false);
|
||||
|
||||
await new Promise((resolve) =>
|
||||
requestAnimationFrame(() => resolve(undefined))
|
||||
);
|
||||
|
||||
try {
|
||||
// Stage 1: Fetching data (0-20%)
|
||||
setExcelProgress(15);
|
||||
await new Promise((resolve) => setTimeout(resolve, 50));
|
||||
|
||||
const allDataForExport = await reportExpenseExport();
|
||||
|
||||
if (!allDataForExport || allDataForExport.length === 0) {
|
||||
toast.error('Tidak ada data untuk diekspor.');
|
||||
setIsExcelExportLoading(false);
|
||||
setExcelProgress(0);
|
||||
return;
|
||||
}
|
||||
|
||||
// Stage 2: Data fetched (20-40%)
|
||||
setExcelProgress(30);
|
||||
await new Promise((resolve) => setTimeout(resolve, 50));
|
||||
|
||||
// Stage 3: Grouping data (40-60%)
|
||||
setExcelProgress(50);
|
||||
const groupedBySupplier: Record<string, ReportExpense[]> = {};
|
||||
allDataForExport.forEach((item) => {
|
||||
const supplierName = item.supplier?.name || 'Unknown Supplier';
|
||||
if (!groupedBySupplier[supplierName]) {
|
||||
groupedBySupplier[supplierName] = [];
|
||||
}
|
||||
groupedBySupplier[supplierName].push(item);
|
||||
});
|
||||
|
||||
await new Promise((resolve) => setTimeout(resolve, 50));
|
||||
|
||||
// Stage 4: Creating workbook (60-80%)
|
||||
setExcelProgress(70);
|
||||
const workbook = XLSX.utils.book_new();
|
||||
|
||||
const supplierEntries = Object.entries(groupedBySupplier);
|
||||
const totalSuppliers = supplierEntries.length;
|
||||
|
||||
for (let i = 0; i < supplierEntries.length; i++) {
|
||||
const [supplierName, supplierData] = supplierEntries[i];
|
||||
|
||||
// Update progress per supplier
|
||||
const progressIncrement = (20 / totalSuppliers) * (i + 1);
|
||||
setExcelProgress(70 + progressIncrement);
|
||||
|
||||
const totals = supplierData.reduce(
|
||||
(acc, item) => ({
|
||||
qty_pengajuan: acc.qty_pengajuan + (item.pengajuan?.qty || 0),
|
||||
total_pengajuan:
|
||||
acc.total_pengajuan +
|
||||
(item.pengajuan?.qty || 0) * (item.pengajuan?.price || 0),
|
||||
qty_realisasi: acc.qty_realisasi + (item.realisasi?.qty || 0),
|
||||
total_realisasi:
|
||||
acc.total_realisasi +
|
||||
(item.realisasi?.qty || 0) * (item.realisasi?.price || 0),
|
||||
}),
|
||||
{
|
||||
qty_pengajuan: 0,
|
||||
total_pengajuan: 0,
|
||||
qty_realisasi: 0,
|
||||
total_realisasi: 0,
|
||||
}
|
||||
);
|
||||
|
||||
const excelData = supplierData.map((item, index) => ({
|
||||
No: index + 1,
|
||||
'No. PO': item.po_number || '',
|
||||
'No. Referensi': item.reference_number || '',
|
||||
'Tanggal Realisasi': item.realization_date
|
||||
? formatDate(item.realization_date, 'DD MMM YYYY')
|
||||
: '',
|
||||
'Tanggal Transaksi': item.transaction_date
|
||||
? formatDate(item.transaction_date, 'DD MMM YYYY')
|
||||
: '',
|
||||
Kategori: item.category || '',
|
||||
Produk: item.pengajuan?.nonstock?.name || '',
|
||||
Lokasi: item.kandang?.location?.name || '',
|
||||
Kandang: item.kandang?.name || '',
|
||||
'Qty Pengajuan': item.pengajuan?.qty || 0,
|
||||
'Harga Pengajuan': item.pengajuan?.price || 0,
|
||||
'Total Pengajuan':
|
||||
(item.pengajuan?.qty || 0) * (item.pengajuan?.price || 0),
|
||||
'Qty Realisasi': item.realisasi?.qty || 0,
|
||||
'Harga Realisasi': item.realisasi?.price || 0,
|
||||
'Total Realisasi':
|
||||
(item.realisasi?.qty || 0) * (item.realisasi?.price || 0),
|
||||
'Status Pencairan': item.latest_approval?.step_name || '',
|
||||
}));
|
||||
|
||||
excelData.push({
|
||||
No: 'Total' as unknown as number,
|
||||
'No. PO': '',
|
||||
'No. Referensi': '',
|
||||
'Tanggal Realisasi': '',
|
||||
'Tanggal Transaksi': '',
|
||||
Kategori: '',
|
||||
Produk: '',
|
||||
Lokasi: '',
|
||||
Kandang: '',
|
||||
'Qty Pengajuan': totals.qty_pengajuan,
|
||||
'Harga Pengajuan': 0,
|
||||
'Total Pengajuan': totals.total_pengajuan,
|
||||
'Qty Realisasi': totals.qty_realisasi,
|
||||
'Harga Realisasi': 0,
|
||||
'Total Realisasi': totals.total_realisasi,
|
||||
'Status Pencairan': '',
|
||||
});
|
||||
|
||||
const worksheet = XLSX.utils.json_to_sheet(excelData);
|
||||
const colWidths = [
|
||||
{ wch: 5 }, // No
|
||||
{ wch: 20 }, // No. PO
|
||||
{ wch: 20 }, // No. Referensi
|
||||
{ wch: 15 }, // Tanggal Realisasi
|
||||
{ wch: 15 }, // Tanggal Transaksi
|
||||
{ wch: 15 }, // Kategori
|
||||
{ wch: 30 }, // Produk
|
||||
{ wch: 20 }, // Lokasi
|
||||
{ wch: 15 }, // Kandang
|
||||
{ wch: 15 }, // Qty Pengajuan
|
||||
{ wch: 15 }, // Harga Pengajuan
|
||||
{ wch: 20 }, // Total Pengajuan
|
||||
{ wch: 15 }, // Qty Realisasi
|
||||
{ wch: 15 }, // Harga Realisasi
|
||||
{ wch: 20 }, // Total Realisasi
|
||||
{ wch: 20 }, // Status Pencairan
|
||||
];
|
||||
worksheet['!cols'] = colWidths;
|
||||
|
||||
const sheetName = supplierName.slice(0, 31);
|
||||
XLSX.utils.book_append_sheet(workbook, worksheet, sheetName);
|
||||
|
||||
// Small delay to allow UI update
|
||||
if (i < supplierEntries.length - 1) {
|
||||
await new Promise((resolve) => setTimeout(resolve, 10));
|
||||
}
|
||||
}
|
||||
|
||||
// Stage 5: Writing file (90-100%)
|
||||
setExcelProgress(95);
|
||||
await new Promise((resolve) => setTimeout(resolve, 50));
|
||||
|
||||
const filename = `Laporan-BOP-${formatDate(new Date(), 'YYYY-MM-DD-HHmm')}.xlsx`;
|
||||
XLSX.writeFile(workbook, filename);
|
||||
|
||||
setExcelProgress(100);
|
||||
toast.success('Excel berhasil dibuat dan diunduh.');
|
||||
|
||||
// Reset progress
|
||||
setTimeout(() => setExcelProgress(0), 500);
|
||||
} catch (error) {
|
||||
console.error('Excel Export Error:', error);
|
||||
toast.error('Gagal membuat Excel. Silakan coba lagi.');
|
||||
setExcelProgress(0);
|
||||
} finally {
|
||||
setIsExcelExportLoading(false);
|
||||
}
|
||||
}, [isExcelExportLoading, reportExpenseExport]);
|
||||
|
||||
// ===== PAGINATION HANDLERS =====
|
||||
const handlePageChange = (page: number) => {
|
||||
setPage(page);
|
||||
};
|
||||
|
||||
const handleRowChange = (pageSize: number) => {
|
||||
setPageSize(pageSize);
|
||||
};
|
||||
|
||||
const handleNextPage = () => {
|
||||
if (meta && filterState.page < meta.total_pages) {
|
||||
setPage(filterState.page + 1);
|
||||
}
|
||||
};
|
||||
|
||||
const handlePrevPage = () => {
|
||||
if (filterState.page > 1) {
|
||||
setPage(filterState.page - 1);
|
||||
}
|
||||
};
|
||||
|
||||
// ===== TABLE COLUMNS DEFINITION =====
|
||||
const columns = useMemo((): ColumnDef<ReportExpense>[] => {
|
||||
return [
|
||||
{
|
||||
header: 'No',
|
||||
accessorFn: (_, index) => index + 1,
|
||||
accessorFn: (_, index) =>
|
||||
(filterState.page - 1) * filterState.pageSize + index + 1,
|
||||
},
|
||||
{
|
||||
header: 'No. PO',
|
||||
@@ -75,14 +537,14 @@ const ReportExpenseTable = ({
|
||||
header: 'Tanggal Realisasi',
|
||||
accessorKey: 'realization_date',
|
||||
cell: ({ row }) => {
|
||||
return formatDate(row.original.realization_date, 'DD MMM, YYYY');
|
||||
return formatDate(row.original?.realization_date, 'DD MMM, YYYY');
|
||||
},
|
||||
},
|
||||
{
|
||||
header: 'Tanggal Transaksi',
|
||||
accessorKey: 'transaction_date',
|
||||
cell: ({ row }) => {
|
||||
return formatDate(row.original.transaction_date, 'DD MMM, YYYY');
|
||||
return formatDate(row.original?.transaction_date, 'DD MMM, YYYY');
|
||||
},
|
||||
},
|
||||
{
|
||||
@@ -91,19 +553,19 @@ const ReportExpenseTable = ({
|
||||
},
|
||||
{
|
||||
header: 'Produk',
|
||||
accessorFn: (row) => row.pengajuan.nonstock.name,
|
||||
accessorFn: (row) => row.pengajuan?.nonstock?.name,
|
||||
},
|
||||
{
|
||||
header: 'Supplier',
|
||||
accessorFn: (row) => row.supplier.name,
|
||||
accessorFn: (row) => row.supplier?.name,
|
||||
},
|
||||
{
|
||||
header: 'Lokasi',
|
||||
accessorFn: (row) => row.kandang.location.name,
|
||||
accessorFn: (row) => row.kandang?.location?.name,
|
||||
},
|
||||
{
|
||||
header: 'Kandang',
|
||||
accessorFn: (row) => row.kandang.name,
|
||||
accessorFn: (row) => row.kandang?.name,
|
||||
},
|
||||
{
|
||||
header: 'Pengajuan',
|
||||
@@ -111,23 +573,26 @@ const ReportExpenseTable = ({
|
||||
{
|
||||
header: 'Qty',
|
||||
id: 'qty_pengajuan',
|
||||
accessorFn: (row) => row.pengajuan.qty,
|
||||
accessorFn: (row) => row.pengajuan?.qty,
|
||||
cell: ({ row }) =>
|
||||
row.original.pengajuan.qty.toLocaleString('id-ID'),
|
||||
row.original.pengajuan?.qty?.toLocaleString('id-ID') || '0',
|
||||
},
|
||||
{
|
||||
header: 'Harga',
|
||||
id: 'harga_pengajuan',
|
||||
accessorFn: (row) => row.pengajuan.price,
|
||||
cell: ({ row }) => formatCurrency(row.original.pengajuan.price),
|
||||
accessorFn: (row) => row.pengajuan?.price,
|
||||
cell: ({ row }) =>
|
||||
formatCurrency(row.original.pengajuan?.price || 0),
|
||||
},
|
||||
{
|
||||
header: 'Total',
|
||||
id: 'total_pengajuan',
|
||||
accessorFn: (row) => row.pengajuan.qty * row.pengajuan.price,
|
||||
accessorFn: (row) =>
|
||||
(row.pengajuan?.qty || 0) * (row.pengajuan?.price || 0),
|
||||
cell: ({ row }) => {
|
||||
const total =
|
||||
row.original.pengajuan.qty * row.original.pengajuan.price;
|
||||
(row.original.pengajuan?.qty || 0) *
|
||||
(row.original.pengajuan?.price || 0);
|
||||
return formatCurrency(total);
|
||||
},
|
||||
},
|
||||
@@ -139,23 +604,26 @@ const ReportExpenseTable = ({
|
||||
{
|
||||
header: 'Qty',
|
||||
id: 'qty_realisasi',
|
||||
accessorFn: (row) => row.realisasi.qty,
|
||||
accessorFn: (row) => row.realisasi?.qty,
|
||||
cell: ({ row }) =>
|
||||
row.original.realisasi.qty.toLocaleString('id-ID'),
|
||||
row.original.realisasi?.qty?.toLocaleString('id-ID') || '0',
|
||||
},
|
||||
{
|
||||
header: 'Harga',
|
||||
id: 'harga_realisasi',
|
||||
accessorFn: (row) => row.realisasi.price,
|
||||
cell: ({ row }) => formatCurrency(row.original.realisasi.price),
|
||||
accessorFn: (row) => row.realisasi?.price,
|
||||
cell: ({ row }) =>
|
||||
formatCurrency(row.original.realisasi?.price || 0),
|
||||
},
|
||||
{
|
||||
header: 'Total',
|
||||
id: 'total_realisasi',
|
||||
accessorFn: (row) => row.realisasi.qty * row.realisasi.price,
|
||||
accessorFn: (row) =>
|
||||
(row.realisasi?.qty || 0) * (row.realisasi?.price || 0),
|
||||
cell: ({ row }) => {
|
||||
const total =
|
||||
row.original.realisasi.qty * row.original.realisasi.price;
|
||||
(row.original.realisasi?.qty || 0) *
|
||||
(row.original.realisasi?.price || 0);
|
||||
return formatCurrency(total);
|
||||
},
|
||||
},
|
||||
@@ -165,55 +633,76 @@ const ReportExpenseTable = ({
|
||||
header: 'Status Pencairan',
|
||||
cell: (props) => (
|
||||
<RealizationStatusBadge
|
||||
approval={props.row.original.latest_approval}
|
||||
approval={props.row.original?.latest_approval}
|
||||
/>
|
||||
),
|
||||
},
|
||||
{
|
||||
header: 'Status BOP',
|
||||
cell: (props) => (
|
||||
<ExpenseStatusBadge approval={props.row.original.latest_approval} />
|
||||
<ExpenseStatusBadge approval={props.row.original?.latest_approval} />
|
||||
),
|
||||
},
|
||||
];
|
||||
}, []);
|
||||
|
||||
// Handle Search
|
||||
const handleSearch = () => {
|
||||
onSearch({
|
||||
search,
|
||||
realizationDate,
|
||||
locationId: selectedLocation?.value.toString() ?? '',
|
||||
kandangId: selectedKandang?.value.toString() ?? '',
|
||||
nonstockId: selectedNonstock?.value.toString() ?? '',
|
||||
supplierId: selectedSupplier?.value.toString() ?? '',
|
||||
category: selectedCategory?.value.toString() ?? '',
|
||||
});
|
||||
};
|
||||
const handleSearchInput = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
setSearch(e.target.value);
|
||||
};
|
||||
const handleReset = () => {
|
||||
setSearch('');
|
||||
setRealizationDate('');
|
||||
setSelectedLocation(null);
|
||||
setSelectedKandang(null);
|
||||
setSelectedNonstock(null);
|
||||
setSelectedSupplier(null);
|
||||
setSelectedCategory(null);
|
||||
onSearch({
|
||||
search: '',
|
||||
realizationDate: '',
|
||||
locationId: '',
|
||||
kandangId: '',
|
||||
nonstockId: '',
|
||||
supplierId: '',
|
||||
category: '',
|
||||
});
|
||||
};
|
||||
}, [filterState.page, filterState.pageSize]);
|
||||
|
||||
// ===== RENDER =====
|
||||
return (
|
||||
<div className='flex flex-col gap-4'>
|
||||
{isAnyExportLoading && (
|
||||
<div className='flex flex-col gap-2'>
|
||||
<progress
|
||||
className='progress progress-primary w-full'
|
||||
value={
|
||||
isPdfExportLoading
|
||||
? pdfProgress
|
||||
: isExcelExportLoading
|
||||
? excelProgress
|
||||
: 0
|
||||
}
|
||||
max='100'
|
||||
></progress>
|
||||
{((isPdfExportLoading && pdfProgress > 0) ||
|
||||
(isExcelExportLoading && excelProgress > 0)) && (
|
||||
<div className='text-sm text-center text-gray-600'>
|
||||
<div className='font-semibold'>
|
||||
{(() => {
|
||||
const currentProgress = isPdfExportLoading
|
||||
? pdfProgress
|
||||
: excelProgress;
|
||||
const exportType = isPdfExportLoading ? 'PDF' : 'Excel';
|
||||
|
||||
if (currentProgress < 20)
|
||||
return 'Mengambil data dari server...';
|
||||
if (currentProgress < 30) return 'Memproses data laporan...';
|
||||
if (currentProgress < 40)
|
||||
return `Menyiapkan struktur dokumen ${exportType}...`;
|
||||
if (currentProgress < 50)
|
||||
return 'Mengelompokkan data per supplier...';
|
||||
if (currentProgress < 70)
|
||||
return 'Merender tabel dan kalkulasi...';
|
||||
if (currentProgress < 96)
|
||||
return `Memformat dokumen ${exportType}...`;
|
||||
if (currentProgress < 100)
|
||||
return 'Menyelesaikan dan mengunduh...';
|
||||
return 'Selesai!';
|
||||
})()}{' '}
|
||||
{Math.round(isPdfExportLoading ? pdfProgress : excelProgress)}%
|
||||
</div>
|
||||
{((isPdfExportLoading && pdfProgress >= 35 && pdfProgress < 90) ||
|
||||
(isExcelExportLoading &&
|
||||
excelProgress >= 35 &&
|
||||
excelProgress < 90)) && (
|
||||
<div className='text-xs text-gray-500 mt-1'>
|
||||
{(isPdfExportLoading ? pdfProgress : excelProgress) < 96
|
||||
? 'Proses ini membutuhkan waktu lebih lama untuk data dalam jumlah besar. Mohon bersabar...'
|
||||
: 'Sedang memproses baris data. Hampir selesai...'}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
<Card
|
||||
title='Laporan Biaya Operasional'
|
||||
variant='bordered'
|
||||
@@ -221,22 +710,45 @@ const ReportExpenseTable = ({
|
||||
wrapper: 'w-full',
|
||||
}}
|
||||
footer={
|
||||
<div className='flex flex-row items-center justify-between gap-2'>
|
||||
<div>
|
||||
<ReportExpenseExport data={reportExpenses} />
|
||||
</div>
|
||||
<div className='flex flex-col gap-6'>
|
||||
<div className='flex flex-row items-center justify-end gap-2'>
|
||||
<div className='flex flex-row items-center gap-2'>
|
||||
<Button className='min-w-24' onClick={handleSearch}>
|
||||
<Button className='min-w-24' onClick={handleSubmit}>
|
||||
Cari
|
||||
</Button>
|
||||
<Button
|
||||
className='min-w-24'
|
||||
color='warning'
|
||||
onClick={handleReset}
|
||||
onClick={resetFilters}
|
||||
>
|
||||
Reset
|
||||
</Button>
|
||||
</div>
|
||||
<div>
|
||||
<Dropdown
|
||||
trigger={
|
||||
<Button
|
||||
color='success'
|
||||
className='min-w-24'
|
||||
isLoading={isAnyExportLoading}
|
||||
onClick={() => {
|
||||
setDropdownOpen(!dropdownOpen);
|
||||
}}
|
||||
>
|
||||
Export
|
||||
</Button>
|
||||
}
|
||||
align='end'
|
||||
direction='bottom'
|
||||
open={dropdownOpen}
|
||||
>
|
||||
<Menu className='w-32'>
|
||||
<MenuItem title='Excel' onClick={handleExportExcel} />
|
||||
<MenuItem title='PDF' onClick={handleExportPdf} />
|
||||
</Menu>
|
||||
</Dropdown>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
>
|
||||
@@ -248,10 +760,7 @@ const ReportExpenseTable = ({
|
||||
isLoading={isLoadingLocation}
|
||||
placeholder='Lokasi'
|
||||
value={selectedLocation}
|
||||
onChange={(option) => {
|
||||
setSelectedLocation(option as OptionType);
|
||||
setSelectedKandang(null);
|
||||
}}
|
||||
onChange={locationChangeHandler}
|
||||
/>
|
||||
<SelectInput
|
||||
isClearable
|
||||
@@ -260,7 +769,7 @@ const ReportExpenseTable = ({
|
||||
isLoading={isLoadingKandang}
|
||||
placeholder='Kandang'
|
||||
value={selectedKandang}
|
||||
onChange={(option) => setSelectedKandang(option as OptionType)}
|
||||
onChange={kandangChangeHandler}
|
||||
/>
|
||||
<SelectInput
|
||||
isClearable
|
||||
@@ -269,7 +778,7 @@ const ReportExpenseTable = ({
|
||||
isLoading={isLoadingSupplier}
|
||||
placeholder='Supplier'
|
||||
value={selectedSupplier}
|
||||
onChange={(option) => setSelectedSupplier(option as OptionType)}
|
||||
onChange={supplierChangeHandler}
|
||||
/>
|
||||
<SelectInput
|
||||
isClearable
|
||||
@@ -278,50 +787,79 @@ const ReportExpenseTable = ({
|
||||
isLoading={isLoadingNonstock}
|
||||
placeholder='Produk'
|
||||
value={selectedNonstock}
|
||||
onChange={(option) => setSelectedNonstock(option as OptionType)}
|
||||
onChange={nonstockChangeHandler}
|
||||
/>
|
||||
<SelectInput
|
||||
isClearable
|
||||
label='Kategori'
|
||||
options={[
|
||||
{
|
||||
value: 'BOP',
|
||||
label: 'BOP',
|
||||
},
|
||||
{
|
||||
value: 'NON-BOP',
|
||||
label: 'Non BOP',
|
||||
},
|
||||
]}
|
||||
options={categoryOptions}
|
||||
placeholder='Kategori'
|
||||
value={selectedCategory}
|
||||
onChange={(option) => setSelectedCategory(option as OptionType)}
|
||||
onChange={categoryChangeHandler}
|
||||
/>
|
||||
<DateInput
|
||||
label='Tanggal Realisasi'
|
||||
value={realizationDate as string}
|
||||
onChange={(e) => setRealizationDate(e.target.value)}
|
||||
value={filterState.realization_date}
|
||||
onChange={realizationDateChangeHandler}
|
||||
name='realization_date'
|
||||
placeholder='Tanggal Realisasi'
|
||||
/>
|
||||
<DebouncedTextInput
|
||||
label='Cari'
|
||||
name='search'
|
||||
value={search}
|
||||
onChange={handleSearchInput}
|
||||
value={filterState.search}
|
||||
onChange={searchChangeHandler}
|
||||
placeholder='Cari'
|
||||
startAdornment={<Icon icon='mdi:magnify' width={24} height={24} />}
|
||||
/>
|
||||
</div>
|
||||
</Card>
|
||||
|
||||
{/* ===== TABLE CONTENT ===== */}
|
||||
{!isSubmitted ? (
|
||||
<div className='mt-6 text-center text-gray-500'>
|
||||
Silakan pilih filter dan klik tombol Cari untuk menampilkan data.
|
||||
</div>
|
||||
) : isLoading ? (
|
||||
<div className='w-full flex flex-row justify-center items-center p-4'>
|
||||
<span className='loading loading-spinner loading-xl' />
|
||||
</div>
|
||||
) : data.length === 0 ? (
|
||||
<div className='mt-6 text-center text-gray-500'>
|
||||
Tidak ada data yang dapat ditampilkan...
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<Table<ReportExpense>
|
||||
columns={columns}
|
||||
data={reportExpenses}
|
||||
data={data}
|
||||
pageSize={10}
|
||||
className={{
|
||||
headerRowClassName: cn(TABLE_DEFAULT_STYLING, 'whitespace-nowrap'),
|
||||
containerClassName: 'mb-0',
|
||||
headerRowClassName: cn(
|
||||
TABLE_DEFAULT_STYLING,
|
||||
'whitespace-nowrap'
|
||||
),
|
||||
bodyRowClassName: cn(TABLE_DEFAULT_STYLING, 'whitespace-nowrap'),
|
||||
paginationClassName: 'hidden',
|
||||
}}
|
||||
/>
|
||||
{meta && (
|
||||
<div className='mt-6'>
|
||||
<Pagination
|
||||
currentPage={meta.page}
|
||||
totalItems={meta.total_results}
|
||||
onPageChange={handlePageChange}
|
||||
onRowChange={handleRowChange}
|
||||
onNextPage={handleNextPage}
|
||||
onPrevPage={handlePrevPage}
|
||||
rowOptions={[10, 25, 50, 100]}
|
||||
itemsPerPage={meta.limit}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -1,80 +1,57 @@
|
||||
import Button from '@/components/Button';
|
||||
import { ReportExpense } from '@/types/api/report/report-expense';
|
||||
import { Icon } from '@iconify/react';
|
||||
import { Document, Image, Page, pdf, Text, View } from '@react-pdf/renderer';
|
||||
import { useMemo, useState } from 'react';
|
||||
import { formatCurrency, formatDate } from '@/lib/helper';
|
||||
import pdfStyles from '@/components/pages/report/expense/pdf/styles/ReportExpenseStyles';
|
||||
import toast from 'react-hot-toast';
|
||||
import ExpenseStatusBadge from '@/components/pages/expense/ExpenseStatusBadge';
|
||||
|
||||
interface ReportExpenseExportProps {
|
||||
data: ReportExpense[];
|
||||
className?: string;
|
||||
export interface PDFParams {
|
||||
location_name?: string;
|
||||
supplier_name?: string;
|
||||
kandang_name?: string;
|
||||
nonstock_name?: string;
|
||||
category?: string;
|
||||
realization_date?: string;
|
||||
search?: string;
|
||||
}
|
||||
|
||||
const ReportExpenseExport = ({ data }: ReportExpenseExportProps) => {
|
||||
const [isGeneratingPDF, setIsGeneratingPDF] = useState(false);
|
||||
|
||||
const handleDownloadPDF = async () => {
|
||||
if (!data || data.length === 0) {
|
||||
toast.error('No report expense data available');
|
||||
return;
|
||||
const getStatusStyle = (action?: string) => {
|
||||
switch (action) {
|
||||
case 'APPROVED':
|
||||
return { backgroundColor: '#dcfce7' };
|
||||
case 'REJECTED':
|
||||
return { backgroundColor: '#fee2e2' };
|
||||
default:
|
||||
return { backgroundColor: '#fef3c7' };
|
||||
}
|
||||
setIsGeneratingPDF(true);
|
||||
try {
|
||||
const blob = await pdf(<PDFDocument data={data} />).toBlob();
|
||||
const url = URL.createObjectURL(blob);
|
||||
const link = document.createElement('a');
|
||||
link.href = url;
|
||||
link.download = `Laporan-BOP-${formatDate(new Date(), 'DD-MMM-YYYY')}.pdf`;
|
||||
document.body.appendChild(link);
|
||||
link.click();
|
||||
document.body.removeChild(link);
|
||||
URL.revokeObjectURL(url);
|
||||
} catch (error) {
|
||||
toast.error('Failed to generate PDF. Please try again.');
|
||||
return error;
|
||||
} finally {
|
||||
setIsGeneratingPDF(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Button
|
||||
color='error'
|
||||
className='min-w-32'
|
||||
onClick={handleDownloadPDF}
|
||||
isLoading={isGeneratingPDF}
|
||||
>
|
||||
<Icon icon='mdi:file-pdf-box' width={20} height={20} />
|
||||
Export PDF
|
||||
</Button>
|
||||
);
|
||||
};
|
||||
|
||||
export default ReportExpenseExport;
|
||||
|
||||
const PDFDocument = ({ data }: { data: ReportExpense[] }) => {
|
||||
const PDFDocument = ({
|
||||
data,
|
||||
params,
|
||||
}: {
|
||||
data: ReportExpense[];
|
||||
params: PDFParams;
|
||||
}) => {
|
||||
// Group data by supplier
|
||||
const groupedBySupplier = useMemo(() => {
|
||||
const groupedBySupplier = (() => {
|
||||
const groups: Record<string, ReportExpense[]> = {};
|
||||
data.forEach((item) => {
|
||||
const supplierName = item.supplier.name;
|
||||
const supplierName = item.supplier?.name || 'Unknown Supplier';
|
||||
if (!groups[supplierName]) {
|
||||
groups[supplierName] = [];
|
||||
}
|
||||
groups[supplierName].push(item);
|
||||
});
|
||||
return groups;
|
||||
}, [data]);
|
||||
})();
|
||||
|
||||
// Calculate grand totals
|
||||
const grandTotals = useMemo(() => {
|
||||
return data.reduce(
|
||||
const grandTotals = data.reduce(
|
||||
(acc, item) => {
|
||||
const pengajuanTotal = item.pengajuan.qty * item.pengajuan.price;
|
||||
const realisasiTotal = item.realisasi.qty * item.realisasi.price;
|
||||
const pengajuanTotal =
|
||||
(item.pengajuan?.qty || 0) * (item.pengajuan?.price || 0);
|
||||
const realisasiTotal =
|
||||
(item.realisasi?.qty || 0) * (item.realisasi?.price || 0);
|
||||
return {
|
||||
pengajuan: acc.pengajuan + pengajuanTotal,
|
||||
realisasi: acc.realisasi + realisasiTotal,
|
||||
@@ -82,7 +59,6 @@ const PDFDocument = ({ data }: { data: ReportExpense[] }) => {
|
||||
},
|
||||
{ pengajuan: 0, realisasi: 0 }
|
||||
);
|
||||
}, [data]);
|
||||
|
||||
return (
|
||||
<Document>
|
||||
@@ -111,15 +87,35 @@ const PDFDocument = ({ data }: { data: ReportExpense[] }) => {
|
||||
</View>
|
||||
</View>
|
||||
|
||||
{/* Filters Info if any */}
|
||||
{(params.location_name ||
|
||||
params.supplier_name ||
|
||||
params.realization_date) && (
|
||||
<View style={{ marginBottom: 10, fontSize: 8 }}>
|
||||
{params.location_name && (
|
||||
<Text>Lokasi: {params.location_name}</Text>
|
||||
)}
|
||||
{params.supplier_name && (
|
||||
<Text>Supplier: {params.supplier_name}</Text>
|
||||
)}
|
||||
{params.realization_date && (
|
||||
<Text>
|
||||
Tanggal Realisasi:{' '}
|
||||
{formatDate(params.realization_date, 'DD MMM YYYY')}
|
||||
</Text>
|
||||
)}
|
||||
</View>
|
||||
)}
|
||||
|
||||
{/* Grouped Tables by Supplier */}
|
||||
{Object.entries(groupedBySupplier).map(
|
||||
([supplierName, items], groupIndex) => {
|
||||
const supplierTotals = items.reduce(
|
||||
(acc, item) => {
|
||||
const pengajuanTotal =
|
||||
item.pengajuan.qty * item.pengajuan.price;
|
||||
(item.pengajuan?.qty || 0) * (item.pengajuan?.price || 0);
|
||||
const realisasiTotal =
|
||||
item.realisasi.qty * item.realisasi.price;
|
||||
(item.realisasi?.qty || 0) * (item.realisasi?.price || 0);
|
||||
return {
|
||||
pengajuan: acc.pengajuan + pengajuanTotal,
|
||||
realisasi: acc.realisasi + realisasiTotal,
|
||||
@@ -210,7 +206,7 @@ const PDFDocument = ({ data }: { data: ReportExpense[] }) => {
|
||||
<Text>Kandang</Text>
|
||||
</View>
|
||||
|
||||
{/* Pengajuan Group - spans 3 columns: XSmall + Medium + Medium */}
|
||||
{/* Pengajuan Group */}
|
||||
<View
|
||||
style={[
|
||||
pdfStyles.tableCellXSmallHeader,
|
||||
@@ -240,7 +236,7 @@ const PDFDocument = ({ data }: { data: ReportExpense[] }) => {
|
||||
<Text></Text>
|
||||
</View>
|
||||
|
||||
{/* Realisasi Group - spans 3 columns: XSmall + Medium + Medium */}
|
||||
{/* Realisasi Group */}
|
||||
<View
|
||||
style={[
|
||||
pdfStyles.tableCellXSmallHeader,
|
||||
@@ -340,9 +336,9 @@ const PDFDocument = ({ data }: { data: ReportExpense[] }) => {
|
||||
{/* Table Body */}
|
||||
{items.map((item, index) => {
|
||||
const pengajuanTotal =
|
||||
item.pengajuan.qty * item.pengajuan.price;
|
||||
(item.pengajuan?.qty || 0) * (item.pengajuan?.price || 0);
|
||||
const realisasiTotal =
|
||||
item.realisasi.qty * item.realisasi.price;
|
||||
(item.realisasi?.qty || 0) * (item.realisasi?.price || 0);
|
||||
|
||||
return (
|
||||
<View key={index} style={pdfStyles.tableRow}>
|
||||
@@ -350,10 +346,10 @@ const PDFDocument = ({ data }: { data: ReportExpense[] }) => {
|
||||
<Text>{index + 1}</Text>
|
||||
</View>
|
||||
<View style={pdfStyles.tableCellWrap}>
|
||||
<Text>{item.po_number}</Text>
|
||||
<Text>{item.po_number || '-'}</Text>
|
||||
</View>
|
||||
<View style={pdfStyles.tableCellWrap}>
|
||||
<Text>{item.reference_number}</Text>
|
||||
<Text>{item.reference_number || '-'}</Text>
|
||||
</View>
|
||||
<View style={pdfStyles.tableCellMedium}>
|
||||
<Text>
|
||||
@@ -366,54 +362,53 @@ const PDFDocument = ({ data }: { data: ReportExpense[] }) => {
|
||||
</Text>
|
||||
</View>
|
||||
<View style={pdfStyles.tableCellXSmall}>
|
||||
<Text>{item.category.split('-').join(' ')}</Text>
|
||||
<Text>
|
||||
{item.category?.split('-').join(' ') || '-'}
|
||||
</Text>
|
||||
</View>
|
||||
<View style={pdfStyles.tableCell}>
|
||||
<Text>{item.pengajuan.nonstock.name}</Text>
|
||||
<Text>{item.pengajuan?.nonstock?.name || '-'}</Text>
|
||||
</View>
|
||||
<View style={pdfStyles.tableCellSmall}>
|
||||
<Text>{item.kandang.location.name}</Text>
|
||||
<Text>{item.kandang?.location?.name || '-'}</Text>
|
||||
</View>
|
||||
<View style={pdfStyles.tableCellSmall}>
|
||||
<Text>{item.kandang.name}</Text>
|
||||
<Text>{item.kandang?.name || '-'}</Text>
|
||||
</View>
|
||||
<View style={pdfStyles.tableCellRightXSmall}>
|
||||
<Text>
|
||||
{item.pengajuan.qty.toLocaleString('id-ID')}
|
||||
{(item.pengajuan?.qty || 0).toLocaleString('id-ID')}
|
||||
</Text>
|
||||
</View>
|
||||
<View style={pdfStyles.tableCellRightMedium}>
|
||||
<Text>{formatCurrency(item.pengajuan.price)}</Text>
|
||||
<Text>
|
||||
{formatCurrency(item.pengajuan?.price || 0)}
|
||||
</Text>
|
||||
</View>
|
||||
<View style={pdfStyles.tableCellRightMedium}>
|
||||
<Text>{formatCurrency(pengajuanTotal)}</Text>
|
||||
</View>
|
||||
<View style={pdfStyles.tableCellRightXSmall}>
|
||||
<Text>
|
||||
{item.realisasi.qty.toLocaleString('id-ID')}
|
||||
{(item.realisasi?.qty || 0).toLocaleString('id-ID')}
|
||||
</Text>
|
||||
</View>
|
||||
<View style={pdfStyles.tableCellRightMedium}>
|
||||
<Text>{formatCurrency(item.realisasi.price)}</Text>
|
||||
<Text>
|
||||
{formatCurrency(item.realisasi?.price || 0)}
|
||||
</Text>
|
||||
</View>
|
||||
<View style={pdfStyles.tableCellRightMedium}>
|
||||
<Text>{formatCurrency(realisasiTotal)}</Text>
|
||||
</View>
|
||||
<View style={pdfStyles.tableCellMedium}>
|
||||
<Text
|
||||
style={{
|
||||
fontSize: 7,
|
||||
backgroundColor:
|
||||
item.latest_approval.action === 'APPROVED'
|
||||
? '#dcfce7'
|
||||
: item.latest_approval.action === 'REJECTED'
|
||||
? '#fee2e2'
|
||||
: '#fef3c7',
|
||||
padding: 2,
|
||||
borderRadius: 2,
|
||||
}}
|
||||
style={[
|
||||
{ fontSize: 7, padding: 2, borderRadius: 2 },
|
||||
getStatusStyle(item.latest_approval?.action),
|
||||
]}
|
||||
>
|
||||
{item.latest_approval.step_name}
|
||||
{item.latest_approval?.step_name || '-'}
|
||||
</Text>
|
||||
</View>
|
||||
</View>
|
||||
@@ -422,7 +417,6 @@ const PDFDocument = ({ data }: { data: ReportExpense[] }) => {
|
||||
|
||||
{/* Supplier Subtotal Row */}
|
||||
<View style={pdfStyles.grandTotalRow}>
|
||||
{/* Empty cells for columns before subtotal */}
|
||||
<View
|
||||
style={[
|
||||
pdfStyles.tableCellNarrow,
|
||||
@@ -526,7 +520,6 @@ const PDFDocument = ({ data }: { data: ReportExpense[] }) => {
|
||||
</Text>
|
||||
</View>
|
||||
|
||||
{/* Empty cell for Status BOP */}
|
||||
<View style={pdfStyles.tableCellMedium}>
|
||||
<Text></Text>
|
||||
</View>
|
||||
@@ -540,8 +533,7 @@ const PDFDocument = ({ data }: { data: ReportExpense[] }) => {
|
||||
{/* Grand Total Section */}
|
||||
<View style={pdfStyles.allocationSection}>
|
||||
<View
|
||||
style={[
|
||||
{
|
||||
style={{
|
||||
width: '30%',
|
||||
borderTopWidth: 1,
|
||||
borderTopColor: '#000000',
|
||||
@@ -549,8 +541,7 @@ const PDFDocument = ({ data }: { data: ReportExpense[] }) => {
|
||||
borderLeftWidth: 1,
|
||||
borderLeftColor: '#000000',
|
||||
borderLeftStyle: 'solid',
|
||||
},
|
||||
]}
|
||||
}}
|
||||
>
|
||||
<View style={pdfStyles.innerRow}>
|
||||
<View style={pdfStyles.tableCell}>
|
||||
@@ -589,3 +580,23 @@ const PDFDocument = ({ data }: { data: ReportExpense[] }) => {
|
||||
</Document>
|
||||
);
|
||||
};
|
||||
|
||||
export const generateReportExpensePDF = async (
|
||||
data: ReportExpense[],
|
||||
params: PDFParams
|
||||
): Promise<void> => {
|
||||
try {
|
||||
const doc = <PDFDocument data={data} params={params} />;
|
||||
const blob = await pdf(doc).toBlob();
|
||||
const url = URL.createObjectURL(blob);
|
||||
const link = document.createElement('a');
|
||||
link.href = url;
|
||||
link.download = `Laporan-BOP-${formatDate(new Date(), 'YYYY-MM-DD-HHmm')}.pdf`;
|
||||
document.body.appendChild(link);
|
||||
link.click();
|
||||
document.body.removeChild(link);
|
||||
URL.revokeObjectURL(url);
|
||||
} catch (error) {
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
+16
-11
@@ -6,17 +6,6 @@ export const MAIN_DRAWER_LINKS: SidebarMenuItem[] = [
|
||||
link: '/dashboard',
|
||||
icon: 'heroicons-outline:chart-bar-square',
|
||||
},
|
||||
{
|
||||
text: 'Laporan',
|
||||
link: '/report',
|
||||
icon: 'heroicons-outline:clipboard',
|
||||
submenu: [
|
||||
{
|
||||
text: 'Biaya Operasional',
|
||||
link: '/report/expense',
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
text: 'Produksi',
|
||||
link: '/production',
|
||||
@@ -56,6 +45,22 @@ export const MAIN_DRAWER_LINKS: SidebarMenuItem[] = [
|
||||
link: '/closing',
|
||||
icon: 'heroicons-outline:presentation-chart-bar',
|
||||
},
|
||||
{
|
||||
text: 'Laporan',
|
||||
link: '/report',
|
||||
icon: 'mdi:chart-box-outline',
|
||||
submenu: [
|
||||
{
|
||||
text: 'Logistik & Persediaan',
|
||||
link: '/report/logistic-stock',
|
||||
},
|
||||
{
|
||||
text: 'Biaya Operasional',
|
||||
link: '/report/expense',
|
||||
},
|
||||
],
|
||||
},
|
||||
|
||||
{
|
||||
text: 'Persediaan',
|
||||
link: '/inventory',
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,29 @@
|
||||
/**
|
||||
* Dummy data for ReportExpense[]
|
||||
* Generated from: report-expense.json
|
||||
*
|
||||
* This file is auto-generated. Do not edit manually.
|
||||
*/
|
||||
|
||||
import { BaseApiResponse } from '@/types/api/api-general';
|
||||
import dummyData from './reports-expense.dummy.json';
|
||||
import { ReportExpense } from '@/types/api/report/report-expense';
|
||||
|
||||
/**
|
||||
* Get dummy ReportExpense[] data
|
||||
* @returns Promise with BaseApiResponse containing ReportExpense[]
|
||||
*/
|
||||
export async function getDummyExpense(): Promise<
|
||||
BaseApiResponse<ReportExpense[]>
|
||||
> {
|
||||
return new Promise((resolve) => {
|
||||
setTimeout(() => {
|
||||
resolve({
|
||||
code: 200,
|
||||
status: 'success',
|
||||
message: 'Data retrieved successfully',
|
||||
data: dummyData as unknown as ReportExpense[],
|
||||
});
|
||||
}, 500);
|
||||
});
|
||||
}
|
||||
@@ -17,8 +17,8 @@ export class ReportExpenseApiService extends BaseApiService<
|
||||
endpoint: string
|
||||
): Promise<BaseApiResponse<ReportExpense[]>> {
|
||||
// TODO: Remove this block when backend is ready
|
||||
// const { dummyGetAllFetcher } = await import('@/dummy/report/expense.dummy');
|
||||
// return await dummyGetAllFetcher();
|
||||
// const { getDummyExpense } = await import('@/dummy/reports-expense.dummy');
|
||||
// return await getDummyExpense();
|
||||
|
||||
// Uncomment this when backend is ready
|
||||
return await httpClientFetcher<BaseApiResponse<ReportExpense[]>>(endpoint);
|
||||
|
||||
Reference in New Issue
Block a user