ifixkart-admin/app/(admin)/reports/page.tsx

148 lines
6 KiB
TypeScript

'use client';
import { useState } from 'react';
import {
FileSpreadsheet,
FileText,
FileCode,
Loader2,
} from 'lucide-react';
import { API_BASE_URL } from '@/services/api/config';
import { toast } from 'sonner';
import { CustomSelect } from '@/components/ui/CustomSelect';
interface ReportCategoryOption {
id: string;
name: string;
columns: string[];
}
const REPORT_CATEGORIES: ReportCategoryOption[] = [
{
id: 'sales',
name: 'Sales & Revenue Ledger',
columns: ['Order ID', 'Customer Name', 'Phone', 'Items Count', 'Total', 'Discount', 'Shipping', 'Final Amount', 'Order Status', 'Payment Status'],
},
{
id: 'inventory',
name: 'Inventory & Stock Valuation',
columns: ['Product ID', 'Product Name', 'SKU', 'Category', 'Brand', 'Stock Qty', 'Cost Price', 'Selling Price', 'Valuation (INR)'],
},
{
id: 'repairs',
name: 'Service & Repair Operations',
columns: ['Ticket No', 'Customer Name', 'Phone', 'Device Model', 'Assigned Tech', 'Stage', 'Type', 'Estimated (INR)', 'Date'],
},
{
id: 'logistics',
name: 'Logistics & Shipping Deliveries',
columns: ['Order ID', 'Customer Name', 'City', 'State', 'Pincode', 'Fulfillment', 'Payment Status', 'Shipping Cost', 'Created At'],
},
{
id: 'employee_activity',
name: 'Employee Operational Activity',
columns: ['User ID', 'Staff Name', 'Email', 'Role', 'Leads Handled', 'Deals Managed', 'Tasks Completed', 'Status'],
},
];
const shell =
'crm-radius-section border border-border bg-card shadow-[0_1px_3px_rgba(16,24,40,0.06)] min-w-0';
const primaryButton =
'inline-flex items-center justify-center gap-1.5 h-9 px-3 crm-radius-control bg-primary hover:bg-primary/90 text-white text-[13px] font-semibold cursor-pointer disabled:opacity-50';
export default function ReportsHubPage() {
const [selectedCategory, setSelectedCategory] = useState<string>('sales');
const [downloadingFormat, setDownloadingFormat] = useState<string | null>(null);
const activeCategory = REPORT_CATEGORIES.find(c => c.id === selectedCategory) || REPORT_CATEGORIES[0];
const handleDownload = async (format: 'excel' | 'csv' | 'pdf') => {
try {
setDownloadingFormat(format);
toast.info(`Preparing ${activeCategory.name} in ${format.toUpperCase()} format...`);
const url = `${API_BASE_URL}/api/v1/reports/export?category=${selectedCategory}&format=${format}`;
const res = await fetch(url);
if (!res.ok) {
throw new Error(`Server responded with status ${res.status}`);
}
const blob = await res.blob();
const ext = format === 'excel' ? 'xlsx' : format;
const filename = `ifixkart_${selectedCategory}_report_${Date.now()}.${ext}`;
const link = document.createElement('a');
link.href = URL.createObjectURL(blob);
link.download = filename;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
toast.success(`${activeCategory.name} downloaded successfully!`);
} catch (err: unknown) {
console.error('Download error:', err);
toast.error(`Failed to export ${format.toUpperCase()} report. Please try again.`);
} finally {
setDownloadingFormat(null);
}
};
return (
<div className="flex flex-col gap-5 min-w-0">
<div className="flex items-center gap-2 min-w-0">
<h1 className="text-lg font-semibold text-foreground">Reports</h1>
<span className="inline-flex items-center justify-center min-w-5 h-5 px-1.5 crm-radius-toggle bg-primary/10 text-primary text-[11px] font-semibold leading-none">
{REPORT_CATEGORIES.length}
</span>
</div>
<div className={shell}>
<div className="px-4 py-3 border-b border-border flex flex-col lg:flex-row lg:items-center justify-between gap-3">
<div className="min-w-0 w-full sm:w-72">
<CustomSelect
value={selectedCategory}
onChange={setSelectedCategory}
aria-label="Report"
options={REPORT_CATEGORIES.map((cat) => ({ value: cat.id, label: cat.name }))}
/>
</div>
<div className="flex flex-wrap items-center gap-2">
<button type="button" onClick={() => handleDownload('excel')} disabled={!!downloadingFormat} className={primaryButton}>
{downloadingFormat === 'excel' ? <Loader2 className="w-3.5 h-3.5 animate-spin" /> : <FileSpreadsheet className="w-3.5 h-3.5" />}
{downloadingFormat === 'excel' ? 'Exporting...' : 'Excel'}
</button>
<button type="button" onClick={() => handleDownload('csv')} disabled={!!downloadingFormat} className={primaryButton}>
{downloadingFormat === 'csv' ? <Loader2 className="w-3.5 h-3.5 animate-spin" /> : <FileCode className="w-3.5 h-3.5" />}
{downloadingFormat === 'csv' ? 'Exporting...' : 'CSV'}
</button>
<button type="button" onClick={() => handleDownload('pdf')} disabled={!!downloadingFormat} className={primaryButton}>
{downloadingFormat === 'pdf' ? <Loader2 className="w-3.5 h-3.5 animate-spin" /> : <FileText className="w-3.5 h-3.5" />}
{downloadingFormat === 'pdf' ? 'Exporting...' : 'PDF'}
</button>
</div>
</div>
<div className="overflow-x-auto">
<table className="crm-data-table min-w-[860px]">
<thead>
<tr className="border-b border-border">
{activeCategory.columns.map((column) => (
<th key={column} className="px-4 py-2.5 text-left font-medium text-muted-foreground whitespace-nowrap">
{column}
</th>
))}
</tr>
</thead>
<tbody>
<tr>
<td colSpan={activeCategory.columns.length} className="px-4 py-16 text-center text-[13px] text-muted-foreground whitespace-normal">
Export downloads this report.
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
);
}