2026-02-26 20:50:12 +07:00

582 lines
24 KiB
TypeScript

'use client'
import {
useProductSalesAnalytics,
useProfitLossAnalytics,
useSalesAnalytics,
usePaymentAnalytics,
useCategoryAnalytics
} from '@/services/queries/analytics'
import { useOutletById } from '@/services/queries/outlets'
import { generateExcel } from '@/utils/excelGenerator'
import { generatePDF } from '@/utils/pdfGenerator'
import { formatCurrency, formatDate, formatDateDDMMYYYY, formatDatetime } from '@/utils/transform'
import ReportGeneratorComponent from '@/views/dashboards/daily-report/report-generator'
import ReportHeader from '@/views/dashboards/daily-report/report-header'
import React, { useEffect, useRef, useState } from 'react'
// Dummy HPP values — ganti dengan data real nantinya
const DUMMY_STD_HPP = 30 // % — ganti dengan data real nantinya
const DUMMY_REAL_HPP = 0 // % — ganti dengan kalkulasi real nantinya
const getHppStatus = (stdHpp: number, realHpp: number): 'Sehat' | 'Tidak Sehat' =>
realHpp <= stdHpp ? 'Sehat' : 'Tidak Sehat'
const StatusBadge = ({ status }: { status: 'Sehat' | 'Tidak Sehat' }) => (
<span
className={`inline-block px-3 py-1 rounded-full text-base font-bold ${
status === 'Sehat' ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'
}`}
>
{status}
</span>
)
const DailyPOSReport = () => {
const reportRef = useRef<HTMLDivElement | null>(null)
const [isGeneratingExcel, setIsGeneratingExcel] = useState(false)
const [now, setNow] = useState(new Date())
const [selectedDate, setSelectedDate] = useState(new Date())
const [dateRange, setDateRange] = useState({
startDate: new Date(),
endDate: new Date()
})
const [filterType, setFilterType] = useState<'single' | 'range'>('single')
const [isGeneratingPDF, setIsGeneratingPDF] = useState(false)
// PDF Font Size Configuration
const PDF_FONT_SIZES = {
heading: 18,
subheading: 16,
tableContent: 12,
tableHeader: 12,
tableFooter: 12,
grandTotal: 14,
footer: 11
}
// PDF Spacing Configuration
const PDF_SPACING = {
cellPadding: 5,
cellPaddingLarge: 6,
sectionGap: 20,
headerGap: 15
}
const getDateParams = () => {
if (filterType === 'single') {
return {
date_from: formatDateDDMMYYYY(selectedDate),
date_to: formatDateDDMMYYYY(selectedDate)
}
} else {
return {
date_from: formatDateDDMMYYYY(dateRange.startDate),
date_to: formatDateDDMMYYYY(dateRange.endDate)
}
}
}
const dateParams = getDateParams()
const today = new Date()
const sevenDaysAgo = new Date()
sevenDaysAgo.setDate(today.getDate() - 7)
const { data: outlet } = useOutletById()
const { data: profitLoss7Days } = useProfitLossAnalytics({
date_from: formatDateDDMMYYYY(sevenDaysAgo),
date_to: formatDateDDMMYYYY(today)
})
const { data: profitLoss } = useProfitLossAnalytics(dateParams)
const { data: products } = useProductSalesAnalytics(dateParams)
const { data: paymentAnalytics } = usePaymentAnalytics(dateParams)
const { data: category } = useCategoryAnalytics(dateParams)
const productSummary = {
totalQuantitySold: products?.data?.reduce((sum, item) => sum + (item?.quantity_sold || 0), 0) || 0,
totalRevenue: products?.data?.reduce((sum, item) => sum + (item?.revenue || 0), 0) || 0,
totalOrders: products?.data?.reduce((sum, item) => sum + (item?.order_count || 0), 0) || 0
}
const categorySummary = {
totalRevenue: category?.data?.reduce((sum, item) => sum + (item?.total_revenue || 0), 0) || 0,
orderCount: category?.data?.reduce((sum, item) => sum + (item?.order_count || 0), 0) || 0,
productCount: category?.data?.reduce((sum, item) => sum + (item?.product_count || 0), 0) || 0,
totalQuantity: category?.data?.reduce((sum, item) => sum + (item?.total_quantity || 0), 0) || 0
}
useEffect(() => {
setNow(new Date())
}, [])
const formatDateForInput = (date: Date) => {
return date.toISOString().split('T')[0]
}
const getReportPeriodText = () => {
if (filterType === 'single') {
return `${formatDateDDMMYYYY(selectedDate)} - ${formatDateDDMMYYYY(selectedDate)}`
} else {
return `${formatDateDDMMYYYY(dateRange.startDate)} - ${formatDateDDMMYYYY(dateRange.endDate)}`
}
}
const getReportTitle = () => {
return 'Laporan Transaksi'
}
const handleGeneratePDF = async () => {
setIsGeneratingPDF(true)
try {
await generatePDF({
reportRef,
outlet,
profitLoss,
products,
paymentAnalytics,
category,
productSummary,
categorySummary,
filterType,
selectedDate,
dateRange,
now
})
} catch (error) {
console.error('Error generating PDF:', error)
alert(`Terjadi kesalahan saat membuat PDF: ${error}`)
} finally {
setIsGeneratingPDF(false)
}
}
const handleGenerateExcel = async () => {
setIsGeneratingExcel(true)
try {
await generateExcel({
outlet,
profitLoss,
products,
paymentAnalytics,
category,
productSummary,
categorySummary,
filterType,
selectedDate,
dateRange
})
} catch (error) {
console.error('Error generating Excel:', error)
alert(`Terjadi kesalahan saat membuat Excel: ${error}`)
} finally {
setIsGeneratingExcel(false)
}
}
const LoadingOverlay = ({ isVisible, message = 'Generating PDF...' }: { isVisible: boolean; message?: string }) => {
if (!isVisible) return null
return (
<div className='fixed inset-0 z-50 flex items-center justify-center bg-black bg-opacity-50 backdrop-blur-sm'>
<div className='bg-white rounded-lg shadow-xl p-8 max-w-sm w-full mx-4'>
<div className='text-center'>
<div className='inline-block animate-spin rounded-full h-12 w-12 border-4 border-gray-200 border-t-purple-600 mb-4'></div>
<h3 className='text-lg font-semibold text-gray-800 mb-2'>{message}</h3>
<p className='text-sm text-gray-600'>Mohon tunggu, proses ini mungkin membutuhkan beberapa detik...</p>
<div className='mt-6 space-y-2'>
<div className='flex items-center text-xs text-gray-500'>
<div className='w-2 h-2 bg-green-500 rounded-full mr-2 flex-shrink-0'></div>
<span>Capturing report content</span>
</div>
<div className='flex items-center text-xs text-gray-500'>
<div className='w-2 h-2 bg-blue-500 rounded-full mr-2 flex-shrink-0 animate-pulse'></div>
<span>Processing pages</span>
</div>
<div className='flex items-center text-xs text-gray-500'>
<div className='w-2 h-2 bg-gray-300 rounded-full mr-2 flex-shrink-0'></div>
<span>Finalizing PDF</span>
</div>
</div>
</div>
</div>
</div>
)
}
// Group products by category
const groupedProducts =
products?.data?.reduce(
(acc, item) => {
const categoryName = item.category_name || 'Tidak Berkategori'
if (!acc[categoryName]) {
acc[categoryName] = []
}
acc[categoryName].push(item)
return acc
},
{} as Record<string, any[]>
) || {}
return (
<div className='min-h-screen'>
<LoadingOverlay isVisible={isGeneratingPDF} message='Membuat PDF Laporan...' />
<ReportGeneratorComponent
reportTitle='Laporan Penjualan'
filterType={filterType}
selectedDate={selectedDate}
dateRange={dateRange}
onFilterTypeChange={setFilterType}
onSingleDateChange={setSelectedDate}
onDateRangeChange={setDateRange}
onGeneratePDF={handleGeneratePDF}
onGenerateExcel={handleGenerateExcel}
isGeneratingExcel={isGeneratingExcel}
/>
<div ref={reportRef} className='max-w-4xl mx-auto bg-white min-h-[297mm]' style={{ width: '210mm' }}>
{/* Wrap header in a section for easy capture */}
<div className='report-header-section'>
<ReportHeader
outlet={outlet}
reportTitle={getReportTitle()}
reportSubtitle='Laporan Bulanan'
brandName='Apskel'
brandColor='#36175e'
periode={getReportPeriodText()}
/>
</div>
{/* Performance Summary */}
<div className='p-8'>
<h3 className='text-3xl font-bold mb-8' style={{ color: '#36175e' }}>
Ringkasan
</h3>
<div className='space-y-5'>
<div className='flex justify-between items-center py-3 border-b border-gray-200'>
<span className='text-xl text-gray-700'>Total Penjualan</span>
<span className='text-xl font-semibold text-gray-800'>
{formatCurrency(profitLoss?.summary.total_revenue ?? 0)}
</span>
</div>
<div className='flex justify-between items-center py-3 border-b border-gray-200'>
<span className='text-xl text-gray-700'>Total Diskon</span>
<span className='text-xl font-semibold text-gray-800'>
{formatCurrency(profitLoss?.summary.total_discount ?? 0)}
</span>
</div>
<div className='flex justify-between items-center py-3 border-b border-gray-200'>
<span className='text-xl text-gray-700'>Total Pajak</span>
<span className='text-xl font-semibold text-gray-800'>
{formatCurrency(profitLoss?.summary.total_tax ?? 0)}
</span>
</div>
<div className='flex justify-between items-center py-3 border-b border-gray-200'>
<span className='text-xl text-gray-700'>Service Charge</span>
<span className='text-xl font-semibold text-gray-800'>{formatCurrency(0)}</span>
</div>
<div className='flex justify-between items-center py-3 border-b-2 border-gray-300'>
<span className='text-xl text-gray-700 font-bold'>Total</span>
<span className='text-xl font-bold text-gray-800'>
{formatCurrency(profitLoss?.summary.total_revenue ?? 0)}
</span>
</div>
</div>
</div>
{/* Invoice */}
<div className='px-8 pb-8'>
<h3 className='text-3xl font-bold mb-8' style={{ color: '#36175e' }}>
Invoice
</h3>
<div className='space-y-5'>
<div className='flex justify-between items-center py-3 border-b border-gray-200'>
<span className='text-xl text-gray-700'>Total Invoice</span>
<span className='text-xl font-semibold text-gray-800'>{profitLoss?.summary.total_orders ?? 0}</span>
</div>
</div>
</div>
{/* Payment Method Summary */}
<div className='px-8 pb-8'>
<h3 className='text-3xl font-bold mb-8' style={{ color: '#36175e' }}>
Ringkasan Metode Pembayaran
</h3>
<div className='bg-gray-50 rounded-lg border border-gray-200 overflow-hidden'>
<table className='w-full'>
<thead>
<tr className='text-gray-800 border-b-2 border-gray-300'>
<th className='text-left text-xl p-4 font-semibold'>Metode Pembayaran</th>
<th className='text-center text-xl p-4 font-semibold'>Tipe</th>
<th className='text-center text-xl p-4 font-semibold'>Jumlah Order</th>
<th className='text-right text-xl p-4 font-semibold'>Total Amount</th>
<th className='text-center text-xl p-4 font-semibold'>Persentase</th>
</tr>
</thead>
<tbody>
{paymentAnalytics?.data?.map((payment, index) => (
<tr key={index} className={index % 2 === 0 ? 'bg-white' : 'bg-gray-50'}>
<td className='p-4 text-xl font-medium text-gray-800'>{payment.payment_method_name}</td>
<td className='p-4 text-center'>
<span
className={`px-3 py-1 rounded-full text-lg font-medium ${
payment.payment_method_type === 'cash'
? 'bg-green-100 text-green-800'
: 'bg-blue-100 text-blue-800'
}`}
>
{payment.payment_method_type.toUpperCase()}
</span>
</td>
<td className='p-4 text-xl text-center text-gray-700'>{payment.order_count}</td>
<td className='p-4 text-xl text-right font-semibold text-gray-800'>
{formatCurrency(payment.total_amount)}
</td>
<td className='p-4 text-xl text-center font-medium' style={{ color: '#36175e' }}>
{(payment.percentage ?? 0).toFixed(1)}%
</td>
</tr>
)) || []}
</tbody>
<tfoot>
<tr className='text-gray-800 border-t-2 border-gray-300'>
<td className='p-4 text-xl font-bold'>TOTAL</td>
<td className='p-4'></td>
<td className='p-4 text-xl text-center font-bold'>{paymentAnalytics?.summary.total_orders ?? 0}</td>
<td className='p-4 text-xl text-right font-bold'>
{formatCurrency(paymentAnalytics?.summary.total_amount ?? 0)}
</td>
<td className='p-4 text-center font-bold'></td>
</tr>
</tfoot>
</table>
</div>
</div>
{/* Category Summary — +3 kolom baru */}
<div className='px-8 pb-8'>
<h3 className='text-3xl font-bold mb-8' style={{ color: '#36175e' }}>
Ringkasan Kategori
</h3>
<div className='bg-gray-50 rounded-lg border border-gray-200 overflow-hidden'>
<table className='w-full'>
<thead>
<tr className='text-gray-800 border-b-2 border-gray-300'>
<th className='text-left text-xl p-4 font-semibold'>Nama</th>
<th className='text-center text-xl p-4 font-semibold'>Qty</th>
<th className='text-right text-xl p-4 font-semibold'>Pendapatan</th>
<th className='text-center text-xl p-4 font-semibold'>% Std HPP</th>
<th className='text-center text-xl p-4 font-semibold'>% Real HPP</th>
<th className='text-center text-xl p-4 font-semibold'>Status</th>
</tr>
</thead>
<tbody>
{category?.data?.map((c, index) => {
const stdHpp = DUMMY_STD_HPP
const realHpp = DUMMY_REAL_HPP
const status = getHppStatus(stdHpp, realHpp)
return (
<tr key={index} className={index % 2 === 0 ? 'bg-white' : 'bg-gray-50'}>
<td className='p-4 text-xl font-medium text-gray-800'>{c.category_name}</td>
<td className='p-4 text-xl text-center text-gray-700'>{c.total_quantity}</td>
<td className='p-4 text-xl text-right font-semibold' style={{ color: '#36175e' }}>
{formatCurrency(c.total_revenue)}
</td>
<td className='p-4 text-xl text-center text-gray-700'>{stdHpp}%</td>
<td className='p-4 text-xl text-center text-gray-700'>{realHpp}%</td>
<td className='p-4 text-center'>
<StatusBadge status={status} />
</td>
</tr>
)
}) || []}
</tbody>
<tfoot>
<tr className='text-gray-800 border-t-2 border-gray-300'>
<td className='p-4 text-xl font-bold'>TOTAL</td>
<td className='p-4 text-xl text-center font-bold'>{categorySummary?.totalQuantity ?? 0}</td>
<td className='p-4 text-xl text-right font-bold'>
{formatCurrency(categorySummary?.totalRevenue ?? 0)}
</td>
<td className='p-4'></td>
<td className='p-4'></td>
<td className='p-4'></td>
</tr>
</tfoot>
</table>
</div>
</div>
{/* Product Summary — +3 kolom baru */}
<div className='px-8 pb-8'>
<h3 className='text-3xl font-bold mb-8' style={{ color: '#36175e' }}>
Ringkasan Item Per Kategori
</h3>
<div className='space-y-12'>
{Object.keys(groupedProducts)
.sort((a, b) => {
const productsA = groupedProducts[a]
const productsB = groupedProducts[b]
const orderA = productsA[0]?.category_order ?? 999
const orderB = productsB[0]?.category_order ?? 999
return orderA - orderB
})
.map((categoryName, catIndex) => {
const categoryProducts = groupedProducts[categoryName].sort((a, b) => {
const skuA = a.product_sku || ''
const skuB = b.product_sku || ''
return skuA.localeCompare(skuB)
})
const categoryTotalQty = categoryProducts.reduce((sum, item) => sum + (item.quantity_sold || 0), 0)
const categoryTotalRevenue = categoryProducts.reduce((sum, item) => sum + (item.revenue || 0), 0)
return (
<div key={categoryName} style={{ display: 'block', marginBottom: '70px' }}>
<h4
className='text-2xl font-bold mb-0 px-4 py-4 bg-gray-100 rounded-t-lg'
style={{ color: '#36175e' }}
>
{categoryName.toUpperCase()}
</h4>
<div className='bg-gray-50 rounded-b-lg border-l-2 border-r-2 border-b-2 border-gray-300'>
<table
className='w-full'
style={{ borderCollapse: 'collapse', tableLayout: 'fixed', width: '100%' }}
>
<colgroup>
<col style={{ width: '28%' }} />
<col style={{ width: '10%' }} />
<col style={{ width: '22%' }} />
<col style={{ width: '13%' }} />
<col style={{ width: '13%' }} />
<col style={{ width: '14%' }} />
</colgroup>
<thead>
<tr className='text-gray-800 border-b-2 border-gray-300 bg-gray-100'>
<th className='text-left text-xl p-5 font-semibold border-r border-gray-300'>Produk</th>
<th className='text-center text-xl p-5 font-semibold border-r border-gray-300'>Qty</th>
<th className='text-right text-xl p-5 font-semibold border-r border-gray-300'>
Pendapatan
</th>
<th className='text-center text-xl p-5 font-semibold border-r border-gray-300'>
% Std HPP
</th>
<th className='text-center text-xl p-5 font-semibold border-r border-gray-300'>
% Real HPP
</th>
<th className='text-center text-xl p-5 font-semibold'>Status</th>
</tr>
</thead>
<tbody>
{categoryProducts.map((item, index) => {
const stdHpp = DUMMY_STD_HPP
const realHpp = DUMMY_REAL_HPP
const status = getHppStatus(stdHpp, realHpp)
return (
<tr key={index} className={index % 2 === 0 ? 'bg-white' : 'bg-gray-50'}>
<td className='p-5 text-xl font-medium text-gray-800 border-r border-gray-200'>
{item.product_name}
</td>
<td className='p-5 text-xl text-center text-gray-700 border-r border-gray-200'>
{item.quantity_sold}
</td>
<td className='p-5 text-xl text-right font-semibold text-gray-800 border-r border-gray-200'>
{formatCurrency(item.revenue)}
</td>
<td className='p-5 text-xl text-center text-gray-700 border-r border-gray-200'>
{stdHpp}%
</td>
<td className='p-5 text-xl text-center text-gray-700 border-r border-gray-200'>
{realHpp}%
</td>
<td className='p-5 text-center'>
<StatusBadge status={status} />
</td>
</tr>
)
})}
</tbody>
<tfoot>
<tr className='bg-gray-200 border-t-2 border-gray-400'>
<td className='p-5 text-xl font-bold text-gray-800 border-r border-gray-400'>
Subtotal {categoryName}
</td>
<td className='p-5 text-xl text-center font-bold text-gray-800 border-r border-gray-400'>
{categoryTotalQty}
</td>
<td className='p-5 text-xl text-right font-bold text-gray-800 border-r border-gray-400'>
{formatCurrency(categoryTotalRevenue)}
</td>
<td className='p-5 border-r border-gray-400'></td>
<td className='p-5 border-r border-gray-400'></td>
<td className='p-5'></td>
</tr>
</tfoot>
</table>
</div>
</div>
)
})}
{/* Grand Total */}
<div className='bg-purple-50 rounded-lg border-2 border-purple-300 mt-6'>
<table className='w-full' style={{ borderCollapse: 'collapse', tableLayout: 'fixed' }}>
<colgroup>
<col style={{ width: '28%' }} />
<col style={{ width: '10%' }} />
<col style={{ width: '22%' }} />
<col style={{ width: '13%' }} />
<col style={{ width: '13%' }} />
<col style={{ width: '14%' }} />
</colgroup>
<tfoot>
<tr className='text-gray-800'>
<td className='p-5 text-2xl font-bold border-r-2 border-purple-300' style={{ color: '#36175e' }}>
TOTAL KESELURUHAN
</td>
<td
className='p-5 text-2xl text-center font-bold border-r-2 border-purple-300'
style={{ color: '#36175e' }}
>
{productSummary.totalQuantitySold ?? 0}
</td>
<td
className='p-5 text-2xl text-right font-bold border-r-2 border-purple-300'
style={{ color: '#36175e' }}
>
{formatCurrency(productSummary.totalRevenue ?? 0)}
</td>
<td className='p-5 border-r-2 border-purple-300'></td>
<td className='p-5 border-r-2 border-purple-300'></td>
<td className='p-5'></td>
</tr>
</tfoot>
</table>
</div>
</div>
</div>
{/* Footer */}
<div className='px-8 py-6 border-t-2 border-gray-200 mt-8'>
<div className='flex justify-between items-center text-base text-gray-600'>
<p>© 2025 Apskel - Sistem POS Terpadu</p>
<p></p>
<p>Dicetak pada: {now.toLocaleDateString('id-ID')}</p>
</div>
</div>
</div>
</div>
)
}
export default DailyPOSReport