feat: report inventory
This commit is contained in:
parent
e2f18ac9bb
commit
16ad569297
@ -0,0 +1,317 @@
|
||||
'use client'
|
||||
|
||||
import { useInventoryAnalytics } from '@/services/queries/analytics'
|
||||
import { useOutletById } from '@/services/queries/outlets'
|
||||
import { formatDateDDMMYYYY } from '@/utils/transform'
|
||||
import ReportGeneratorComponent from '@/views/dashboards/daily-report/report-generator'
|
||||
import ReportHeader from '@/views/dashboards/daily-report/report-header'
|
||||
import { useRef, useState } from 'react'
|
||||
const ExportInventoryPage = () => {
|
||||
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') // 'single' or 'range'
|
||||
|
||||
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: inventory } = useInventoryAnalytics(dateParams)
|
||||
|
||||
const handleGeneratePDF = async () => {
|
||||
const reportElement = reportRef.current
|
||||
|
||||
try {
|
||||
// Import jsPDF dan html2canvas
|
||||
const jsPDF = (await import('jspdf')).default
|
||||
const html2canvas = (await import('html2canvas')).default
|
||||
|
||||
// Optimized canvas capture dengan scale lebih rendah
|
||||
const canvas = await html2canvas(reportElement!, {
|
||||
scale: 1.5, // Reduced from 2 to 1.5
|
||||
useCORS: true,
|
||||
allowTaint: true,
|
||||
backgroundColor: '#ffffff',
|
||||
logging: false, // Disable logging for performance
|
||||
removeContainer: true, // Clean up after capture
|
||||
imageTimeout: 0, // No timeout for image loading
|
||||
height: reportElement!.scrollHeight,
|
||||
width: reportElement!.scrollWidth
|
||||
})
|
||||
|
||||
// Compress canvas using JPEG with quality setting
|
||||
const imgData = canvas.toDataURL('image/jpeg', 0.85) // JPEG with 85% quality instead of PNG
|
||||
|
||||
// Create PDF with compression
|
||||
const pdf = new jsPDF({
|
||||
orientation: 'portrait',
|
||||
unit: 'mm',
|
||||
format: 'a4',
|
||||
compress: true // Enable built-in compression
|
||||
})
|
||||
|
||||
const imgWidth = 210
|
||||
const pageHeight = 295
|
||||
const imgHeight = (canvas.height * imgWidth) / canvas.width
|
||||
let heightLeft = imgHeight
|
||||
let position = 0
|
||||
|
||||
// Add first page with compressed image
|
||||
pdf.addImage(imgData, 'JPEG', 0, position, imgWidth, imgHeight, '', 'FAST') // Use FAST compression
|
||||
heightLeft -= pageHeight
|
||||
|
||||
// Handle multiple pages if needed
|
||||
while (heightLeft >= 0) {
|
||||
position = heightLeft - imgHeight
|
||||
pdf.addPage()
|
||||
pdf.addImage(imgData, 'JPEG', 0, position, imgWidth, imgHeight, '', 'FAST')
|
||||
heightLeft -= pageHeight
|
||||
}
|
||||
|
||||
// Additional compression options
|
||||
pdf.setProperties({
|
||||
title: `Laporan Inventori`,
|
||||
subject: 'Laporan Inventori',
|
||||
author: 'Apskel POS System',
|
||||
creator: 'Apskel'
|
||||
})
|
||||
|
||||
// Save with optimized settings
|
||||
const fileName =
|
||||
filterType === 'single'
|
||||
? `laporan-inventory-${formatDateForInput(selectedDate)}.pdf`
|
||||
: `laporan-inventory-${formatDateForInput(dateRange.startDate)}-to-${formatDateForInput(dateRange.endDate)}.pdf`
|
||||
|
||||
pdf.save(fileName, {
|
||||
returnPromise: true
|
||||
})
|
||||
|
||||
// Clean up canvas to free memory
|
||||
canvas.width = canvas.height = 0
|
||||
} catch (error) {
|
||||
console.error('Error generating PDF:', error)
|
||||
alert('Terjadi kesalahan saat membuat PDF. Pastikan jsPDF dan html2canvas sudah terinstall.')
|
||||
}
|
||||
}
|
||||
|
||||
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 productSummary = {
|
||||
totalQuantity: inventory?.products?.reduce((sum, item) => sum + (item?.quantity || 0), 0) || 0,
|
||||
totalIn: inventory?.products?.reduce((sum, item) => sum + (item?.total_in || 0), 0) || 0,
|
||||
totalOut: inventory?.products?.reduce((sum, item) => sum + (item?.total_out || 0), 0) || 0
|
||||
}
|
||||
|
||||
const ingredientSummary = {
|
||||
totalQuantity: inventory?.ingredients?.reduce((sum, item) => sum + (item?.quantity || 0), 0) || 0,
|
||||
totalIn: inventory?.ingredients?.reduce((sum, item) => sum + (item?.total_in || 0), 0) || 0,
|
||||
totalOut: inventory?.ingredients?.reduce((sum, item) => sum + (item?.total_out || 0), 0) || 0
|
||||
}
|
||||
|
||||
return (
|
||||
<div className='min-h-screen'>
|
||||
{/* Control Panel */}
|
||||
<ReportGeneratorComponent
|
||||
// Props wajib
|
||||
reportTitle='Laporan Inventori'
|
||||
filterType={filterType}
|
||||
selectedDate={selectedDate}
|
||||
dateRange={dateRange}
|
||||
onFilterTypeChange={setFilterType}
|
||||
onSingleDateChange={setSelectedDate}
|
||||
onDateRangeChange={setDateRange}
|
||||
onGeneratePDF={handleGeneratePDF}
|
||||
// Props opsional
|
||||
// isGenerating={isGenerating}
|
||||
// customQuickActions={customQuickActions}
|
||||
// labels={customLabels}
|
||||
/>
|
||||
<div ref={reportRef} className='max-w-4xl mx-auto bg-white min-h-[297mm]' style={{ width: '210mm' }}>
|
||||
{/* Header */}
|
||||
<ReportHeader
|
||||
outlet={outlet}
|
||||
reportTitle='Laporan Inventori'
|
||||
reportSubtitle='Laporan'
|
||||
brandName='Apskel'
|
||||
brandColor='#36175e'
|
||||
periode={getReportPeriodText()}
|
||||
/>
|
||||
|
||||
{/* Ringkasan */}
|
||||
<div className='p-8'>
|
||||
<h3 className='text-xl font-bold mb-6' style={{ color: '#36175e' }}>
|
||||
1. Ringkasan
|
||||
</h3>
|
||||
|
||||
<div className='grid grid-cols-2 gap-6'>
|
||||
<div className='space-y-4'>
|
||||
<div className='flex justify-between items-center py-2 border-b border-gray-200'>
|
||||
<span className='text-gray-700'>Total Item</span>
|
||||
<span className='font-semibold text-gray-800'>{inventory?.summary.total_products}</span>
|
||||
</div>
|
||||
<div className='flex justify-between items-center py-2 border-b border-gray-200'>
|
||||
<span className='text-gray-700'>Total Item Masuk</span>
|
||||
<span className='font-semibold text-gray-800'>{inventory?.summary.low_stock_products}</span>
|
||||
</div>
|
||||
<div className='flex justify-between items-center py-2 border-b border-gray-200'>
|
||||
<span className='text-gray-700'>Total Item Keluar</span>
|
||||
<span className='font-semibold text-gray-800'>{inventory?.summary.zero_stock_products}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className='space-y-4'>
|
||||
<div className='flex justify-between items-center py-2 border-b border-gray-200'>
|
||||
<span className='text-gray-700'>Total Ingredient</span>
|
||||
<span className='font-semibold text-gray-800'>{inventory?.summary.total_ingredients}</span>
|
||||
</div>
|
||||
<div className='flex justify-between items-center py-2 border-b border-gray-200'>
|
||||
<span className='text-gray-700'>Total Ingredient Masuk</span>
|
||||
<span className='font-semibold text-gray-800'>{inventory?.summary.low_stock_ingredients}</span>
|
||||
</div>
|
||||
<div className='flex justify-between items-center py-2 border-b border-gray-200'>
|
||||
<span className='text-gray-700'>Total Ingredient Keluar</span>
|
||||
<span className='font-semibold text-gray-800'>{inventory?.summary.zero_stock_ingredients}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Item */}
|
||||
<div className='px-8 pb-8'>
|
||||
<h3 className='text-xl font-bold mb-6' style={{ color: '#36175e' }}>
|
||||
2. Item
|
||||
</h3>
|
||||
|
||||
<div className='bg-gray-50 rounded-lg border border-gray-200 overflow-hidden'>
|
||||
<table className='w-full'>
|
||||
<thead>
|
||||
<tr style={{ backgroundColor: '#36175e' }} className='text-white'>
|
||||
<th className='text-left p-3 font-semibold'>Nama</th>
|
||||
<th className='text-center p-3 font-semibold'>Kategori</th>
|
||||
<th className='text-center p-3 font-semibold'>Stock</th>
|
||||
<th className='text-center p-3 font-semibold'>Masuk</th>
|
||||
<th className='text-center p-3 font-semibold'>Keluar</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{inventory?.products?.map((product, index) => {
|
||||
let rowClass = index % 2 === 0 ? 'bg-white' : 'bg-gray-50'
|
||||
|
||||
if (product.is_zero_stock) {
|
||||
rowClass = 'bg-red-300' // Merah untuk stok habis
|
||||
} else if (product.is_low_stock) {
|
||||
rowClass = 'bg-yellow-300' // Kuning untuk stok sedikit
|
||||
}
|
||||
return (
|
||||
<tr key={index} className={rowClass}>
|
||||
<td className='p-3 font-medium text-gray-800'>{product.product_name}</td>
|
||||
<td className='p-3 font-medium text-gray-800'>{product.category_name}</td>
|
||||
|
||||
<td className='p-3 text-center text-gray-700'>{product.quantity}</td>
|
||||
<td className='p-3 text-center text-gray-700'>{product.total_in}</td>
|
||||
<td className='p-3 text-center text-gray-700'>{product.total_out}</td>
|
||||
</tr>
|
||||
)
|
||||
}) || []}
|
||||
</tbody>
|
||||
<tfoot>
|
||||
<tr style={{ backgroundColor: '#36175e' }} className='text-white'>
|
||||
<td className='p-3 font-bold'>TOTAL</td>
|
||||
<td className='p-3'></td>
|
||||
<td className='p-3 text-center font-bold'>{productSummary.totalQuantity ?? 0}</td>
|
||||
<td className='p-3 text-center font-bold'>{productSummary.totalIn ?? 0}</td>
|
||||
<td className='p-3 text-center font-bold'>{productSummary.totalOut ?? 0}</td>
|
||||
</tr>
|
||||
</tfoot>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Ingredient */}
|
||||
<div className='px-8 pb-8'>
|
||||
<h3 className='text-xl font-bold mb-6' style={{ color: '#36175e' }}>
|
||||
3. Ingredient
|
||||
</h3>
|
||||
|
||||
<div className='bg-gray-50 rounded-lg border border-gray-200 overflow-hidden'>
|
||||
<table className='w-full'>
|
||||
<thead>
|
||||
<tr style={{ backgroundColor: '#36175e' }} className='text-white'>
|
||||
<th className='text-left p-3 font-semibold'>Nama</th>
|
||||
<th className='text-center p-3 font-semibold'>Stock</th>
|
||||
<th className='text-center p-3 font-semibold'>Masuk</th>
|
||||
<th className='text-center p-3 font-semibold'>Keluar</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{inventory?.ingredients?.map((ingredient, index) => {
|
||||
let rowClass = index % 2 === 0 ? 'bg-white' : 'bg-gray-50'
|
||||
|
||||
if (ingredient.is_zero_stock) {
|
||||
rowClass = 'bg-red-300' // Merah untuk stok habis
|
||||
} else if (ingredient.is_low_stock) {
|
||||
rowClass = 'bg-yellow-300' // Kuning untuk stok sedikit
|
||||
}
|
||||
return (
|
||||
<tr key={index} className={rowClass}>
|
||||
<td className='p-3 font-medium text-gray-800'>{ingredient.ingredient_name}</td>
|
||||
<td className='p-3 text-center text-gray-700'>{ingredient.quantity}</td>
|
||||
<td className='p-3 text-center text-gray-700'>{ingredient.total_in}</td>
|
||||
<td className='p-3 text-center text-gray-700'>{ingredient.total_out}</td>
|
||||
</tr>
|
||||
)
|
||||
}) || []}
|
||||
</tbody>
|
||||
<tfoot>
|
||||
<tr style={{ backgroundColor: '#36175e' }} className='text-white'>
|
||||
<td className='p-3 font-bold'>TOTAL</td>
|
||||
<td className='p-3 text-center font-bold'>{ingredientSummary.totalQuantity ?? 0}</td>
|
||||
<td className='p-3 text-center font-bold'>{ingredientSummary.totalIn ?? 0}</td>
|
||||
<td className='p-3 text-center font-bold'>{ingredientSummary.totalOut ?? 0}</td>
|
||||
</tr>
|
||||
</tfoot>
|
||||
</table>
|
||||
</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-sm 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 ExportInventoryPage
|
||||
@ -2,6 +2,7 @@ import { useQuery } from '@tanstack/react-query'
|
||||
import {
|
||||
CategoryReport,
|
||||
DashboardReport,
|
||||
InventoryReport,
|
||||
PaymentReport,
|
||||
ProductSalesReport,
|
||||
ProfitLossReport,
|
||||
@ -194,3 +195,43 @@ export function useCategoryAnalytics(params: AnalyticQueryParams = {}) {
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
export function useInventoryAnalytics(params: AnalyticQueryParams = {}) {
|
||||
const today = new Date()
|
||||
const monthAgo = new Date()
|
||||
monthAgo.setDate(today.getDate() - 30)
|
||||
|
||||
const defaultDateTo = formatDateDDMMYYYY(today)
|
||||
const defaultDateFrom = formatDateDDMMYYYY(monthAgo)
|
||||
|
||||
const { date_from = defaultDateFrom, date_to = defaultDateTo, ...filters } = params
|
||||
|
||||
const user = (() => {
|
||||
try {
|
||||
return JSON.parse(localStorage.getItem('user') || '{}')
|
||||
} catch {
|
||||
return {}
|
||||
}
|
||||
})()
|
||||
|
||||
const outletId = user?.outlet_id //
|
||||
|
||||
return useQuery<InventoryReport>({
|
||||
queryKey: ['analytics-inventory', { date_from, date_to, ...filters }],
|
||||
queryFn: async () => {
|
||||
const queryParams = new URLSearchParams()
|
||||
|
||||
queryParams.append('date_from', date_from)
|
||||
queryParams.append('date_to', date_to)
|
||||
|
||||
Object.entries(filters).forEach(([key, value]) => {
|
||||
if (value !== undefined && value !== null && value !== '') {
|
||||
queryParams.append(key, value.toString())
|
||||
}
|
||||
})
|
||||
|
||||
const res = await api.get(`/inventory/report/details/${outletId}?${queryParams.toString()}`)
|
||||
return res.data.data
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@ -172,3 +172,56 @@ export interface CategoryDataReport {
|
||||
product_count: number
|
||||
order_count: number
|
||||
}
|
||||
|
||||
export interface InventoryReport {
|
||||
summary: InventorySummaryReport
|
||||
products: InventoryProductReport[]
|
||||
ingredients: InventoryIngredientReport[]
|
||||
}
|
||||
|
||||
export interface InventorySummaryReport {
|
||||
total_products: number
|
||||
total_ingredients: number
|
||||
total_value: number
|
||||
low_stock_products: number
|
||||
low_stock_ingredients: number
|
||||
zero_stock_products: number
|
||||
zero_stock_ingredients: number
|
||||
total_sold_products: number
|
||||
total_sold_ingredients: number
|
||||
outlet_id: string
|
||||
outlet_name: string
|
||||
generated_at: string
|
||||
}
|
||||
|
||||
export interface InventoryProductReport {
|
||||
id: string
|
||||
product_id: string
|
||||
product_name: string
|
||||
category_name: string
|
||||
quantity: number
|
||||
reorder_level: number
|
||||
unit_cost: number
|
||||
total_value: number
|
||||
total_in: number
|
||||
total_out: number
|
||||
is_low_stock: boolean
|
||||
is_zero_stock: boolean
|
||||
updated_at: string
|
||||
}
|
||||
|
||||
export interface InventoryIngredientReport {
|
||||
id: string
|
||||
ingredient_id: string
|
||||
ingredient_name: string
|
||||
unit_name: string
|
||||
quantity: number
|
||||
reorder_level: number
|
||||
unit_cost: number
|
||||
total_value: number
|
||||
total_in: number
|
||||
total_out: number
|
||||
is_low_stock: boolean
|
||||
is_zero_stock: boolean
|
||||
updated_at: string
|
||||
}
|
||||
|
||||
@ -41,6 +41,10 @@ import { useInventoriesMutation } from '../../../../../services/mutations/invent
|
||||
import { useInventories } from '../../../../../services/queries/inventories'
|
||||
import { Inventory } from '../../../../../types/services/inventory'
|
||||
import AddStockDrawer from './AddStockDrawer'
|
||||
import Link from 'next/link'
|
||||
import { getLocalizedUrl } from '@/utils/i18n'
|
||||
import { Locale } from '@/configs/i18n'
|
||||
import { useParams } from 'next/navigation'
|
||||
|
||||
declare module '@tanstack/table-core' {
|
||||
interface FilterFns {
|
||||
@ -109,6 +113,9 @@ const StockListTable = () => {
|
||||
const [addInventoryOpen, setAddInventoryOpen] = useState(false)
|
||||
const [search, setSearch] = useState('')
|
||||
|
||||
// Hooks
|
||||
const { lang: locale } = useParams()
|
||||
|
||||
// Fetch products with pagination and search
|
||||
const { data, isLoading, error, isFetching } = useInventories({
|
||||
page: currentPage,
|
||||
@ -259,14 +266,16 @@ const StockListTable = () => {
|
||||
<MenuItem value='25'>25</MenuItem>
|
||||
<MenuItem value='50'>50</MenuItem>
|
||||
</CustomTextField>
|
||||
<Button
|
||||
color='secondary'
|
||||
variant='tonal'
|
||||
className='max-sm:is-full is-auto'
|
||||
startIcon={<i className='tabler-upload' />}
|
||||
>
|
||||
Export
|
||||
</Button>
|
||||
<Link href={getLocalizedUrl(`/apps/inventory/stock/export`, locale as Locale)}>
|
||||
<Button
|
||||
color='secondary'
|
||||
variant='tonal'
|
||||
className='max-sm:is-full is-auto'
|
||||
startIcon={<i className='tabler-upload' />}
|
||||
>
|
||||
Export
|
||||
</Button>
|
||||
</Link>
|
||||
<Button
|
||||
variant='contained'
|
||||
className='max-sm:is-full'
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user