2025-10-06 17:05:11 +07:00

561 lines
22 KiB
TypeScript

'use client'
import {
useProductSalesAnalytics,
useProfitLossAnalytics,
useSalesAnalytics,
usePaymentAnalytics,
useCategoryAnalytics
} from '@/services/queries/analytics'
import { useOutletById } from '@/services/queries/outlets'
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'
const DailyPOSReport = () => {
const reportRef = useRef<HTMLDivElement | null>(null)
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)
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 { data: outlet } = useOutletById()
const { data: sales } = useSalesAnalytics(dateParams)
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 = () => {
if (filterType === 'single') {
return 'Laporan Transaksi'
} else {
return `Laporan Transaksi`
}
}
const handleGeneratePDF = async () => {
const reportElement = reportRef.current
if (!reportElement) {
alert('Report element tidak ditemukan')
return
}
setIsGeneratingPDF(true)
try {
const jsPDF = (await import('jspdf')).default
const html2canvas = (await import('html2canvas')).default
const originalOverflow = reportElement.style.overflow
reportElement.style.overflow = 'visible'
await new Promise(resolve => setTimeout(resolve, 300))
const canvas = await html2canvas(reportElement, {
scale: 1.5,
useCORS: true,
allowTaint: true,
backgroundColor: '#ffffff',
logging: false,
removeContainer: true,
imageTimeout: 0,
height: reportElement.scrollHeight,
width: reportElement.scrollWidth,
scrollX: 0,
scrollY: 0,
windowWidth: Math.max(reportElement.scrollWidth, window.innerWidth),
windowHeight: Math.max(reportElement.scrollHeight, window.innerHeight)
})
reportElement.style.overflow = originalOverflow
const pdf = new jsPDF({
orientation: 'portrait',
unit: 'mm',
format: 'a4',
compress: true
})
const pdfWidth = 210
const pdfHeight = 297
const margin = 5
const availableWidth = pdfWidth - 2 * margin
const availableHeight = pdfHeight - 2 * margin
const imgWidth = availableWidth
const imgHeight = (canvas.height * availableWidth) / canvas.width
let yPosition = margin
let sourceY = 0
let pageCount = 1
let remainingHeight = imgHeight
while (remainingHeight > 0) {
if (pageCount > 1) {
pdf.addPage()
yPosition = margin
}
const heightForThisPage = Math.min(remainingHeight, availableHeight)
const sourceHeight = (heightForThisPage * canvas.height) / imgHeight
const tempCanvas = document.createElement('canvas')
const tempCtx = tempCanvas.getContext('2d')
if (!tempCtx) {
throw new Error('Unable to get 2D context from canvas')
}
tempCanvas.width = canvas.width
tempCanvas.height = sourceHeight
tempCtx.drawImage(canvas, 0, sourceY, canvas.width, sourceHeight, 0, 0, canvas.width, sourceHeight)
const pageImageData = tempCanvas.toDataURL('image/jpeg', 0.9)
pdf.addImage(pageImageData, 'JPEG', margin, yPosition, imgWidth, heightForThisPage)
sourceY += sourceHeight
remainingHeight -= heightForThisPage
pageCount++
if (pageCount > 20) {
console.warn('Too many pages, breaking loop')
break
}
}
pdf.setProperties({
title: getReportTitle(),
subject: 'Transaction Report',
author: 'Apskel POS System',
creator: 'Apskel'
})
const fileName =
filterType === 'single'
? `laporan-transaksi-${formatDateForInput(selectedDate)}.pdf`
: `laporan-transaksi-${formatDateForInput(dateRange.startDate)}-to-${formatDateForInput(dateRange.endDate)}.pdf`
pdf.save(fileName)
} catch (error) {
console.error('Error generating PDF:', error)
alert(`Terjadi kesalahan saat membuat PDF: ${error}`)
} finally {
setIsGeneratingPDF(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}
/>
<div ref={reportRef} className='max-w-4xl mx-auto bg-white min-h-[297mm]' style={{ width: '210mm' }}>
<ReportHeader
outlet={outlet}
reportTitle={getReportTitle()}
reportSubtitle='Laporan Bulanan'
brandName='Apskel'
brandColor='#36175e'
periode={getReportPeriodText()}
/>
{/* 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-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 */}
<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>
</tr>
</thead>
<tbody>
{category?.data?.map((c, index) => (
<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>
</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>
</tr>
</tfoot>
</table>
</div>
</div>
{/* Product Summary - Dipisah per kategori dengan tabel terpisah */}
<div className='px-8 pb-8'>
<h3 className='text-3xl font-bold mb-8 pb-4' style={{ color: '#36175e', pageBreakAfter: 'avoid' }}>
Ringkasan Item Per Kategori
</h3>
<div className='space-y-12'>
{Object.keys(groupedProducts)
.sort()
.map(categoryName => {
const categoryProducts = groupedProducts[categoryName]
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}
className='mb-12 break-inside-avoid'
style={{
pageBreakInside: 'avoid',
breakInside: 'avoid',
display: 'block',
marginTop: '24px',
marginBottom: '24px',
paddingTop: '12px',
paddingBottom: '12px'
}}
>
{/* Category Title */}
<h4
className='text-2xl font-bold mb-0 px-4 py-4 bg-gray-100 rounded-t-lg'
style={{
color: '#36175e',
pageBreakAfter: 'avoid',
breakAfter: 'avoid'
}}
>
{categoryName.toUpperCase()}
</h4>
{/* Category Table */}
<div
className='bg-gray-50 rounded-b-lg border-l-2 border-r-2 border-b-2 border-gray-300'
style={{
pageBreakInside: 'avoid',
breakInside: 'avoid'
}}
>
<table className='w-full' style={{ borderCollapse: 'collapse', tableLayout: 'fixed' }}>
<colgroup>
<col style={{ width: '50%' }} />
<col style={{ width: '20%' }} />
<col style={{ width: '30%' }} />
</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'>Pendapatan</th>
</tr>
</thead>
<tbody>
{categoryProducts.map((item, index) => (
<tr
key={index}
className={index % 2 === 0 ? 'bg-white' : 'bg-gray-50'}
style={{ pageBreakInside: 'avoid' }}
>
<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'>
{formatCurrency(item.revenue)}
</td>
</tr>
))}
</tbody>
<tfoot>
<tr className='bg-gray-200 border-t-2 border-gray-400' style={{ pageBreakInside: 'avoid' }}>
<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'>
{formatCurrency(categoryTotalRevenue)}
</td>
</tr>
</tfoot>
</table>
</div>
</div>
)
})}
{/* Grand Total */}
<div
className='bg-purple-50 rounded-lg border-2 border-purple-300 mt-6'
style={{
pageBreakInside: 'avoid',
breakInside: 'avoid'
}}
>
<table className='w-full' style={{ borderCollapse: 'collapse' }}>
<tfoot>
<tr className='text-gray-800'>
<td
className='p-5 text-2xl font-bold border-r-2 border-purple-300'
style={{ width: '50%', color: '#36175e' }}
>
TOTAL KESELURUHAN
</td>
<td
className='p-5 text-2xl text-center font-bold border-r-2 border-purple-300'
style={{ width: '20%', color: '#36175e' }}
>
{productSummary.totalQuantitySold ?? 0}
</td>
<td className='p-5 text-2xl text-right font-bold' style={{ width: '30%', color: '#36175e' }}>
{formatCurrency(productSummary.totalRevenue ?? 0)}
</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