ReportsView.tsx
33.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
import React, { useCallback, useEffect, useMemo, useRef, useState } from "react";
import type { DateRange } from "react-day-picker";
import { Search, Download, Printer, Calendar as CalendarIcon, BarChart3, LineChart, ArrowUpRight, RefreshCw, FileText } from "lucide-react";
import { Button } from "../ui/button";
import { Input } from "../ui/input";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "../ui/table";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "../ui/select";
import { Popover, PopoverContent, PopoverTrigger } from "../ui/popover";
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "../ui/card";
import { Calendar } from "../ui/calendar";
import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, Line, LineChart as RechartsLineChart } from "recharts";
import { toast } from "sonner";
import { cn } from "../ui/utils";
import { skipCountForPage } from "../../lib/paginationQuery";
import { getLocations } from "../../services/locationService";
import { getPartners } from "../../services/partnerService";
import { getGroups } from "../../services/groupService";
import {
exportPrintLogExcel,
getLabelReport,
getReportsPrintLogList,
} from "../../services/reportsService";
import type { LocationDto } from "../../types/location";
import type { PartnerListItem } from "../../types/partner";
import type { GroupListItem } from "../../types/group";
import type { LabelReportData, ReportsPrintLogListItem } from "../../types/reports";
import { ApiError } from "../../lib/apiClient";
import { BACKEND_EMPTY_DISPLAY } from "../../lib/emptyDisplay";
import { useCategoryScopeAuth } from "../../hooks/useCategoryScopeAuth";
import {
Pagination,
PaginationContent,
PaginationItem,
PaginationLink,
PaginationNext,
PaginationPrevious,
} from "../ui/pagination";
const ALL = "all" as const;
function defaultDateRange(): { start: string; end: string } {
const end = new Date();
const start = new Date(end);
start.setDate(start.getDate() - 29);
return {
start: start.toISOString().slice(0, 10),
end: end.toISOString().slice(0, 10),
};
}
function parseIsoDate(value: string): Date | undefined {
const s = (value ?? "").trim();
if (!/^\d{4}-\d{2}-\d{2}$/.test(s)) return undefined;
const d = new Date(`${s}T00:00:00`);
if (Number.isNaN(d.getTime())) return undefined;
return d;
}
function formatIsoDate(value: Date): string {
const y = value.getFullYear();
const m = String(value.getMonth() + 1).padStart(2, "0");
const d = String(value.getDate()).padStart(2, "0");
return `${y}-${m}-${d}`;
}
function formatPrintedAt(raw: string): string {
const s = (raw ?? "").trim();
if (!s) return "None";
const d = new Date(s);
if (Number.isNaN(d.getTime())) return s;
return d.toLocaleString("en-US", {
year: "numeric",
month: "2-digit",
day: "2-digit",
hour: "numeric",
minute: "2-digit",
second: "2-digit",
hour12: true,
});
}
function toDisplay(v: string | null | undefined): string {
const s = (v ?? "").trim();
if (!s || s === BACKEND_EMPTY_DISPLAY) return "None";
return s;
}
function formatPct(n: number): string {
if (!Number.isFinite(n)) return "0%";
const sign = n > 0 ? "+" : "";
return `${sign}${n.toFixed(1)}%`;
}
function formatTrendLabel(iso: string): string {
const s = (iso ?? "").trim();
if (!s) return "";
const d = new Date(s);
if (Number.isNaN(d.getTime())) return s.length > 10 ? s.slice(0, 10) : s;
return d.toLocaleDateString("en-US", { month: "numeric", day: "numeric" });
}
/** Reports 筛选:单弹层 + range 日历,避免双日历布局问题 */
function PeriodRangePicker({
startDate,
endDate,
onRangeChange,
}: {
startDate: string;
endDate: string;
onRangeChange: (start: string, end: string) => void;
}) {
const [open, setOpen] = useState(false);
const selectedRange: DateRange | undefined = useMemo(() => {
const from = parseIsoDate(startDate);
const to = parseIsoDate(endDate);
if (from && to) return { from, to };
if (from) return { from, to: undefined };
return undefined;
}, [startDate, endDate]);
const label = `${startDate || "YYYY-MM-DD"} — ${endDate || "YYYY-MM-DD"}`;
return (
<div className="flex items-center gap-2 shrink-0" lang="en-US">
<span className="text-sm font-medium font-sans text-gray-900">Period Search:</span>
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger asChild>
<Button
type="button"
variant="outline"
className="h-10 min-w-[17rem] justify-start gap-2 rounded-md border border-gray-300 bg-white px-3 text-sm font-medium font-sans text-gray-900 hover:bg-gray-50"
>
<CalendarIcon className="h-4 w-4 shrink-0 text-gray-500" aria-hidden />
{label}
</Button>
</PopoverTrigger>
<PopoverContent className="w-auto p-0" align="start">
<Calendar
mode="range"
numberOfMonths={1}
defaultMonth={parseIsoDate(startDate) ?? parseIsoDate(endDate) ?? new Date()}
selected={selectedRange}
onSelect={(range) => {
if (!range?.from) return;
const s = formatIsoDate(range.from);
const e = range.to ? formatIsoDate(range.to) : s;
onRangeChange(s, e);
if (range.from && range.to) setOpen(false);
}}
initialFocus
/>
</PopoverContent>
</Popover>
</div>
);
}
/** Print Log 列表行统一字体 */
const PRINT_LOG_CELL = "border-r text-sm font-normal font-sans text-gray-900";
const PRINT_LOG_HEAD = "text-sm font-semibold font-sans text-gray-900 border-r";
function templateCell(template: string) {
const t = (template ?? "").trim();
if (!t) return "None";
if (t.endsWith(" !!!")) {
return (
<>
{t.slice(0, -4)}
<span className="text-red-600"> !!!</span>
</>
);
}
return t;
}
const EMPTY_LABEL_REPORT: LabelReportData = {
summary: {
totalLabelsPrinted: 0,
totalLabelsPrintedPrevPeriod: 0,
totalLabelsPrintedChangeRate: 0,
hottestCategoryName: "None",
hottestCategoryCount: 0,
topProductName: "None",
topProductCount: 0,
avgDailyPrints: 0,
avgDailyPrintsChangeRate: 0,
},
labelsByCategory: [],
printVolumeTrend: [],
mostUsedProducts: [],
};
export type ReportsViewProps = {
layoutReportsOpenKey?: number;
layoutReportsTargetTab?: "print-log" | "label-report";
};
export function ReportsView({
layoutReportsOpenKey = 0,
layoutReportsTargetTab = "label-report",
}: ReportsViewProps = {}) {
const scopeAuth = useCategoryScopeAuth();
const [activeTab, setActiveTab] = useState<"print-log" | "label-report">("print-log");
const lastAppliedLayoutKeyRef = useRef(0);
const [partners, setPartners] = useState<PartnerListItem[]>([]);
const [groups, setGroups] = useState<GroupListItem[]>([]);
const [locations, setLocations] = useState<LocationDto[]>([]);
const [partnerId, setPartnerId] = useState<string>(ALL);
const [groupId, setGroupId] = useState<string>(ALL);
const [locationId, setLocationId] = useState<string>(ALL);
const { start: defaultStart, end: defaultEnd } = defaultDateRange();
const [startDate, setStartDate] = useState<string>(defaultStart);
const [endDate, setEndDate] = useState<string>(defaultEnd);
const [keyword, setKeyword] = useState("");
const [debouncedKeyword, setDebouncedKeyword] = useState("");
const keywordTimerRef = useRef<number | null>(null);
const [printRows, setPrintRows] = useState<ReportsPrintLogListItem[]>([]);
const [printTotal, setPrintTotal] = useState(0);
const [printLoading, setPrintLoading] = useState(false);
const [pageIndex, setPageIndex] = useState(1);
const [pageSize] = useState(10);
const [labelData, setLabelData] = useState<LabelReportData | null>(null);
const [labelLoading, setLabelLoading] = useState(false);
const [exporting, setExporting] = useState(false);
const [filterMetaLoading, setFilterMetaLoading] = useState(true);
const printAbortRef = useRef<AbortController | null>(null);
const labelAbortRef = useRef<AbortController | null>(null);
useEffect(() => {
if (keywordTimerRef.current) window.clearTimeout(keywordTimerRef.current);
keywordTimerRef.current = window.setTimeout(() => setDebouncedKeyword(keyword.trim()), 300);
return () => {
if (keywordTimerRef.current) window.clearTimeout(keywordTimerRef.current);
};
}, [keyword]);
useEffect(() => {
if (layoutReportsOpenKey > 0 && layoutReportsOpenKey > lastAppliedLayoutKeyRef.current) {
lastAppliedLayoutKeyRef.current = layoutReportsOpenKey;
setActiveTab(layoutReportsTargetTab);
}
}, [layoutReportsOpenKey, layoutReportsTargetTab]);
const totalPages = Math.max(1, Math.ceil(printTotal / pageSize));
const effectivePartnerId = useMemo(() => {
if (scopeAuth.requireCompanySelection) return partnerId;
const fixed = scopeAuth.fixedPartnerId.trim();
return fixed || partnerId;
}, [scopeAuth.requireCompanySelection, scopeAuth.fixedPartnerId, partnerId]);
const partnerNameForQuery = useCallback((): string | undefined => {
if (effectivePartnerId === ALL) return undefined;
const p = partners.find((x) => x.id === effectivePartnerId);
return p?.partnerName?.trim() || undefined;
}, [effectivePartnerId, partners]);
const groupNameForQuery = useCallback((): string | undefined => {
if (groupId === ALL) return undefined;
const g = groups.find((x) => x.id === groupId);
return g?.groupName?.trim() || undefined;
}, [groupId, groups]);
const buildReportFilters = useCallback(
() => ({
partnerId: effectivePartnerId === ALL ? undefined : effectivePartnerId,
groupId: groupId === ALL ? undefined : groupId,
locationId: locationId === ALL ? undefined : locationId,
startDate: startDate.trim() || undefined,
endDate: endDate.trim() || undefined,
keyword: debouncedKeyword || undefined,
}),
[debouncedKeyword, effectivePartnerId, endDate, groupId, locationId, startDate]
);
useEffect(() => {
setPageIndex(1);
}, [debouncedKeyword, partnerId, groupId, locationId, startDate, endDate, activeTab, pageSize]);
useEffect(() => {
if (scopeAuth.requireCompanySelection) return;
const pid = scopeAuth.fixedPartnerId.trim();
if (pid) setPartnerId(pid);
}, [scopeAuth.requireCompanySelection, scopeAuth.fixedPartnerId]);
useEffect(() => {
let cancel = false;
const run = async () => {
setFilterMetaLoading(true);
try {
const tasks: [Promise<void>, Promise<void>] = [
(async () => {
if (!scopeAuth.requireCompanySelection) return;
const pRes = await getPartners({ skipCount: 1, maxResultCount: 500, state: true });
if (cancel) return;
setPartners(pRes.items ?? []);
})(),
(async () => {
const gRes = await getGroups({ skipCount: 1, maxResultCount: 500, state: true });
if (cancel) return;
setGroups(gRes.items ?? []);
})(),
];
await Promise.all(tasks);
} catch (e) {
if (!cancel) {
if (scopeAuth.requireCompanySelection) setPartners([]);
setGroups([]);
toast.error("Failed to load companies / regions.", {
description: e instanceof Error ? e.message : "Please try again.",
});
}
} finally {
if (!cancel) setFilterMetaLoading(false);
}
};
run();
return () => {
cancel = true;
};
}, [scopeAuth.requireCompanySelection]);
useEffect(() => {
let cancel = false;
const run = async () => {
try {
const res = await getLocations({
skipCount: 1,
maxResultCount: 2000,
partner: partnerNameForQuery(),
groupName: groupNameForQuery(),
state: true,
});
if (cancel) return;
setLocations(res.items ?? []);
} catch (e) {
if (!cancel) {
setLocations([]);
toast.error("Failed to load locations.", {
description: e instanceof Error ? e.message : "Please try again.",
});
}
}
};
run();
return () => {
cancel = true;
};
}, [groupNameForQuery, partnerNameForQuery, effectivePartnerId, groupId]);
useEffect(() => {
if (activeTab !== "print-log") return;
const run = async () => {
printAbortRef.current?.abort();
const ac = new AbortController();
printAbortRef.current = ac;
setPrintLoading(true);
const f = buildReportFilters();
try {
const res = await getReportsPrintLogList(
{
skipCount: skipCountForPage(pageIndex),
maxResultCount: pageSize,
sorting: "PrintedAt desc",
...f,
},
ac.signal
);
setPrintRows(res.items ?? []);
setPrintTotal(res.totalCount ?? 0);
} catch (e) {
if (e instanceof Error && e.name === "AbortError") return;
toast.error("Failed to load print log.", {
description: e instanceof Error ? e.message : "Please try again.",
});
setPrintRows([]);
setPrintTotal(0);
} finally {
if (!ac.signal.aborted) setPrintLoading(false);
}
};
void run();
return () => printAbortRef.current?.abort();
}, [activeTab, buildReportFilters, pageIndex, pageSize]);
useEffect(() => {
if (activeTab !== "label-report") return;
const run = async () => {
labelAbortRef.current?.abort();
const ac = new AbortController();
labelAbortRef.current = ac;
setLabelLoading(true);
const f = buildReportFilters();
try {
const data = await getLabelReport(f, ac.signal);
setLabelData(data);
} catch (e) {
if (e instanceof Error && e.name === "AbortError") return;
toast.error("Failed to load label report.", {
description: e instanceof Error ? e.message : "Please try again.",
});
setLabelData(EMPTY_LABEL_REPORT);
} finally {
if (!ac.signal.aborted) setLabelLoading(false);
}
};
void run();
return () => labelAbortRef.current?.abort();
}, [activeTab, buildReportFilters]);
const onPartnerChange = (v: string) => {
setPartnerId(v);
setGroupId(ALL);
setLocationId(ALL);
};
const onGroupChange = (v: string) => {
setGroupId(v);
setLocationId(ALL);
};
const handleExport = async () => {
const f = buildReportFilters();
setExporting(true);
try {
await exportPrintLogExcel({
...f,
skipCount: 1,
maxResultCount: 10,
sorting: "PrintedAt desc",
});
toast.success("Export ready", { description: "The Excel download should start shortly." });
} catch (e) {
const msg = e instanceof ApiError ? e.message : e instanceof Error ? e.message : "Please try again.";
toast.error("Export failed", { description: msg });
} finally {
setExporting(false);
}
};
const report = labelData ?? EMPTY_LABEL_REPORT;
const trendData = (report.printVolumeTrend ?? []).map((p) => ({
date: formatTrendLabel(p.date),
count: p.count,
}));
const categoryData = (report.labelsByCategory ?? []).map((c) => ({ name: c.name, count: c.count }));
return (
<div className="h-full flex flex-col">
<div className="pb-4">
<div className="flex flex-wrap items-center gap-3">
{scopeAuth.requireCompanySelection ? (
<Select value={partnerId} onValueChange={onPartnerChange} disabled={filterMetaLoading}>
<SelectTrigger className="w-[140px] h-10 rounded-md border border-gray-300 bg-white font-medium text-gray-900 shrink-0">
<SelectValue placeholder="Company" />
</SelectTrigger>
<SelectContent>
<SelectItem value={ALL}>All companies</SelectItem>
{partners.map((p) => (
<SelectItem key={p.id} value={p.id}>
{toDisplay(p.partnerName)}
</SelectItem>
))}
</SelectContent>
</Select>
) : null}
<Select
value={groupId}
onValueChange={onGroupChange}
disabled={filterMetaLoading || scopeAuth.loadingPartner}
>
<SelectTrigger className="w-[140px] h-10 rounded-md border border-gray-300 bg-white font-medium text-gray-900 shrink-0">
<SelectValue placeholder="Region" />
</SelectTrigger>
<SelectContent>
<SelectItem value={ALL}>All regions</SelectItem>
{groups
.filter((g) => (effectivePartnerId === ALL ? true : g.partnerId === effectivePartnerId))
.map((g) => (
<SelectItem key={g.id} value={g.id}>
{toDisplay(g.groupName)}
</SelectItem>
))}
</SelectContent>
</Select>
<Select
value={locationId}
onValueChange={setLocationId}
disabled={filterMetaLoading || scopeAuth.loadingPartner}
>
<SelectTrigger className="w-[160px] h-10 rounded-md border border-gray-300 bg-white font-medium text-gray-900 shrink-0">
<SelectValue placeholder="Location" />
</SelectTrigger>
<SelectContent>
<SelectItem value={ALL}>All locations</SelectItem>
{locations.map((loc) => (
<SelectItem key={loc.id} value={loc.id ?? ""}>
{toDisplay(loc.locationName) || toDisplay(loc.locationCode)}
</SelectItem>
))}
</SelectContent>
</Select>
<PeriodRangePicker
startDate={startDate}
endDate={endDate}
onRangeChange={(start, end) => {
setStartDate(start);
setEndDate(end);
}}
/>
<div
className="flex items-center w-64 rounded-md border border-gray-300 bg-white overflow-hidden shrink-0"
style={{ height: 40 }}
>
<Search className="h-4 w-4 text-gray-400 shrink-0 ml-3 pointer-events-none" />
<Input
value={keyword}
onChange={(e) => setKeyword(e.target.value)}
placeholder="Search Product or Category..."
className="flex-1 min-w-0 border-0 bg-transparent focus-visible:ring-0 focus-visible:ring-offset-0 py-2 px-2 h-full placeholder:text-gray-500"
/>
</div>
<div className="flex-1 min-w-2" />
{activeTab === "print-log" && (
<Button
type="button"
variant="outline"
className="h-10 border border-gray-300 rounded-md text-gray-900 bg-white hover:bg-gray-50 gap-2 shrink-0"
disabled={exporting}
onClick={() => void handleExport()}
>
<Download className="w-4 h-4" /> {exporting ? "Exporting…" : "Export Report"}
</Button>
)}
</div>
<div className="w-full border-b border-gray-200 mt-4">
<div className="flex overflow-x-auto w-fit">
<button
type="button"
onClick={() => setActiveTab("print-log")}
style={
activeTab === "print-log" ? { borderBottomWidth: 2, borderBottomStyle: "solid", borderBottomColor: "#2563eb" } : undefined
}
className={cn(
"px-4 py-2.5 text-sm font-medium whitespace-nowrap cursor-pointer transition-colors -mb-px border-b-2",
activeTab === "print-log" ? "text-blue-600" : "border-b-transparent text-gray-600 hover:text-gray-800"
)}
>
Print Log
</button>
<button
type="button"
onClick={() => setActiveTab("label-report")}
style={
activeTab === "label-report"
? { borderBottomWidth: 2, borderBottomStyle: "solid", borderBottomColor: "#2563eb" }
: undefined
}
className={cn(
"px-4 py-2.5 text-sm font-medium whitespace-nowrap cursor-pointer transition-colors -mb-px border-b-2",
activeTab === "label-report" ? "text-blue-600" : "border-b-transparent text-gray-600 hover:text-gray-800"
)}
>
Label Report
</button>
</div>
</div>
</div>
<div className="flex-1 overflow-auto pt-6">
{activeTab === "print-log" && (
<div className="space-y-4">
<div className="bg-white border border-gray-200 shadow-sm rounded-md overflow-hidden min-h-[200px]">
{printLoading && (
<div className="p-6 text-sm text-gray-500">Loading print log…</div>
)}
{!printLoading && (
<Table className="font-sans">
<TableHeader>
<TableRow className="bg-gray-100 hover:bg-gray-100">
<TableHead className={PRINT_LOG_HEAD}>Label ID</TableHead>
<TableHead className={PRINT_LOG_HEAD}>Product Name</TableHead>
<TableHead className={PRINT_LOG_HEAD}>Product Category</TableHead>
<TableHead className={PRINT_LOG_HEAD}>Label Category</TableHead>
<TableHead className={PRINT_LOG_HEAD}>Template</TableHead>
<TableHead className={PRINT_LOG_HEAD}>Printed at</TableHead>
<TableHead className={PRINT_LOG_HEAD}>Printed by</TableHead>
<TableHead className={PRINT_LOG_HEAD}>Location</TableHead>
<TableHead className={PRINT_LOG_HEAD}>Expiration</TableHead>
<TableHead className={`${PRINT_LOG_HEAD} text-center border-r-0`}>Action</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{printRows.length === 0 && (
<TableRow>
<TableCell colSpan={10} className={`text-center ${PRINT_LOG_CELL} border-r-0 py-10`}>
No print records
</TableCell>
</TableRow>
)}
{printRows.map((log) => (
<TableRow key={log.taskId + log.labelCode}>
<TableCell className={PRINT_LOG_CELL}>{toDisplay(log.labelCode)}</TableCell>
<TableCell className={PRINT_LOG_CELL}>{toDisplay(log.productName)}</TableCell>
<TableCell className={PRINT_LOG_CELL}>{toDisplay(log.productCategoryName)}</TableCell>
<TableCell className={PRINT_LOG_CELL}>{toDisplay(log.labelCategoryName)}</TableCell>
<TableCell className={PRINT_LOG_CELL}>{templateCell(log.templateText)}</TableCell>
<TableCell className={PRINT_LOG_CELL}>{formatPrintedAt(log.printedAt)}</TableCell>
<TableCell className={PRINT_LOG_CELL}>{toDisplay(log.printedByName)}</TableCell>
<TableCell className={PRINT_LOG_CELL}>{toDisplay(log.locationText)}</TableCell>
<TableCell className={PRINT_LOG_CELL}>{toDisplay(log.expiryDateText)}</TableCell>
<TableCell className="text-center text-sm font-normal font-sans text-gray-900">
<div
className="inline-flex h-8 items-center justify-center gap-1 rounded-md border border-gray-300 bg-white px-4 text-sm font-normal font-sans text-gray-900 shadow-sm select-none pointer-events-none"
aria-label="Reprint"
>
<Printer className="w-3 h-3 shrink-0 text-gray-700" aria-hidden />
<span>Reprint</span>
</div>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
)}
</div>
<div className="flex flex-col sm:flex-row sm:items-center sm:justify-end gap-2 text-sm text-gray-600">
<span>
{printTotal === 0
? "Showing 0 of 0"
: `Showing ${(pageIndex - 1) * pageSize + 1}–${Math.min(pageIndex * pageSize, printTotal)} of ${printTotal}`}
</span>
<Pagination className="mx-0 w-auto justify-end">
<PaginationContent>
<PaginationItem>
<PaginationPrevious
className={pageIndex <= 1 ? "pointer-events-none opacity-50" : "cursor-pointer"}
onClick={() => pageIndex > 1 && setPageIndex((p) => Math.max(1, p - 1))}
aria-disabled={pageIndex <= 1}
/>
</PaginationItem>
<PaginationItem>
<PaginationLink
className="cursor-default"
size="default"
isActive
onClick={(e) => e.preventDefault()}
>
Page {pageIndex} / {totalPages}
</PaginationLink>
</PaginationItem>
<PaginationItem>
<PaginationNext
className={pageIndex >= totalPages ? "pointer-events-none opacity-50" : "cursor-pointer"}
onClick={() => pageIndex < totalPages && setPageIndex((p) => Math.min(totalPages, p + 1))}
aria-disabled={pageIndex >= totalPages}
/>
</PaginationItem>
</PaginationContent>
</Pagination>
</div>
</div>
)}
{activeTab === "label-report" && (
<div className="space-y-6">
{labelLoading && <div className="text-sm text-gray-500">Loading label report…</div>}
{!labelLoading && (
<>
<div className="grid grid-cols-1 md:grid-cols-4 gap-4">
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">Total Labels Printed</CardTitle>
<FileText className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">{report.summary.totalLabelsPrinted.toLocaleString("en-US")}</div>
<p className="text-xs text-muted-foreground">
{formatPct(report.summary.totalLabelsPrintedChangeRate)} vs previous period
</p>
</CardContent>
</Card>
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">Most Printed Category</CardTitle>
<BarChart3 className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">{toDisplay(report.summary.hottestCategoryName)}</div>
<p className="text-xs text-muted-foreground">
{report.summary.hottestCategoryCount.toLocaleString("en-US")} label(s) in range
</p>
</CardContent>
</Card>
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">Top Product</CardTitle>
<ArrowUpRight className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">{toDisplay(report.summary.topProductName)}</div>
<p className="text-xs text-muted-foreground">
{report.summary.topProductCount.toLocaleString("en-US")} label(s) in range
</p>
</CardContent>
</Card>
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">Avg. Daily Prints</CardTitle>
<RefreshCw className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">
{Number.isFinite(report.summary.avgDailyPrints)
? report.summary.avgDailyPrints.toLocaleString("en-US", { maximumFractionDigits: 1 })
: "0"}
</div>
<p className="text-xs text-muted-foreground">
{formatPct(report.summary.avgDailyPrintsChangeRate)} vs previous period
</p>
</CardContent>
</Card>
</div>
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
<Card className="col-span-1">
<CardHeader>
<CardTitle>Labels by Category</CardTitle>
<CardDescription>Distribution of printed labels by label category in the selected range.</CardDescription>
</CardHeader>
<CardContent className="h-[300px]">
{categoryData.length === 0 ? (
<div className="h-full flex items-center justify-center text-sm text-gray-500">No data</div>
) : (
<ResponsiveContainer width="100%" height="100%">
<BarChart data={categoryData}>
<CartesianGrid strokeDasharray="3 3" vertical={false} />
<XAxis dataKey="name" fontSize={12} tickLine={false} axisLine={false} />
<YAxis fontSize={12} tickLine={false} axisLine={false} tickFormatter={(v) => `${v}`} />
<Tooltip />
<Bar dataKey="count" fill="#facc15" radius={[4, 4, 0, 0]} />
</BarChart>
</ResponsiveContainer>
)}
</CardContent>
</Card>
<Card className="col-span-1">
<CardHeader>
<CardTitle>Print Volume Trends</CardTitle>
<CardDescription>Daily print volume in the current filter window (up to 7 days).</CardDescription>
</CardHeader>
<CardContent className="h-[300px]">
{trendData.length === 0 ? (
<div className="h-full flex items-center justify-center text-sm text-gray-500">No data</div>
) : (
<ResponsiveContainer width="100%" height="100%">
<RechartsLineChart data={trendData}>
<CartesianGrid strokeDasharray="3 3" vertical={false} />
<XAxis dataKey="date" fontSize={12} tickLine={false} axisLine={false} />
<YAxis fontSize={12} tickLine={false} axisLine={false} />
<Tooltip />
<Line type="monotone" dataKey="count" stroke="#dc2626" strokeWidth={2} dot={{ r: 4 }} activeDot={{ r: 6 }} />
</RechartsLineChart>
</ResponsiveContainer>
)}
</CardContent>
</Card>
</div>
<Card>
<CardHeader>
<CardTitle>Most Used Products</CardTitle>
</CardHeader>
<CardContent>
<Table>
<TableHeader>
<TableRow>
<TableHead>Product Name</TableHead>
<TableHead>Category</TableHead>
<TableHead className="text-right">Total Printed</TableHead>
<TableHead className="text-right">Usage %</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{report.mostUsedProducts.length === 0 && (
<TableRow>
<TableCell colSpan={4} className="text-center text-sm text-gray-500">
No data
</TableCell>
</TableRow>
)}
{report.mostUsedProducts.map((row, i) => (
<TableRow key={`${row.productName}-${i}`}>
<TableCell className="font-medium">{toDisplay(row.productName)}</TableCell>
<TableCell>{toDisplay(row.categoryName)}</TableCell>
<TableCell className="text-right font-numeric">{row.totalPrinted.toLocaleString("en-US")}</TableCell>
<TableCell className="text-right font-numeric">
{Number.isFinite(row.usagePercent) ? `${row.usagePercent.toFixed(1)}%` : "—"}
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</CardContent>
</Card>
</>
)}
</div>
)}
</div>
</div>
);
}