268 lines
9.7 KiB
TypeScript
268 lines
9.7 KiB
TypeScript
import React from 'react';
|
||
import { reportDayToDate } from '../../utils/reportDay.ts';
|
||
|
||
/**
|
||
* Identity block printed at the top of every exported AI Insight PDF.
|
||
*
|
||
* Hidden on screen and revealed only while html2canvas photographs the card
|
||
* (see `revealPdfHeaders`), because the on-screen card already sits under
|
||
* headings and a coop picker that state all of this — but the PDF travels on
|
||
* its own, and a report that does not say WHEN, WHERE and WHICH PERIOD it
|
||
* covers cannot be filed or checked later.
|
||
*/
|
||
|
||
export const PDF_HEADER_CLASS = 'pdf-report-header';
|
||
|
||
/** Human period label from the dashboard's report scope. */
|
||
export const describeReportPeriod = (
|
||
reportType: 'daily' | 'weekly' | 'end_cycle',
|
||
reportPeriod?: string | null
|
||
): string => {
|
||
if (reportType === 'weekly') {
|
||
return reportPeriod ? `Laporan Mingguan — ${reportPeriod}` : 'Laporan Mingguan';
|
||
}
|
||
if (reportType === 'end_cycle') return 'Laporan Akhir Siklus';
|
||
// A daily report can now name a past day, so the header must say which one —
|
||
// otherwise two reports for different days print identical titles.
|
||
return reportPeriod ? `Laporan Harian — ${reportPeriod}` : 'Laporan Harian';
|
||
};
|
||
|
||
/** Same, for the cards that use the harian/mingguan toggle instead. */
|
||
export const describeTimeframePeriod = (
|
||
timeframe: 'harian' | 'mingguan',
|
||
rangeLabel?: string | null
|
||
): string => {
|
||
const base = timeframe === 'harian' ? 'Laporan Harian' : 'Laporan Mingguan';
|
||
return rangeLabel ? `${base} — ${rangeLabel}` : base;
|
||
};
|
||
|
||
/**
|
||
* "Kandang Atas", or the combined label when the admin has not narrowed to one
|
||
* coop. Named explicitly rather than just "Semua Kandang" so a reader of the
|
||
* PDF knows exactly which flocks the figures add up.
|
||
*/
|
||
export const describeKandangScope = (
|
||
kandangs: Array<{ id?: number; name?: string }> | undefined,
|
||
kandangId: number | string | null | undefined
|
||
): string => {
|
||
const list = kandangs || [];
|
||
if (kandangId === null || kandangId === undefined || kandangId === '') {
|
||
const names = list
|
||
.map((k) => (k.name || '').replace(/^Kandang\s+/i, '').trim())
|
||
.filter(Boolean);
|
||
return names.length > 0 ? `Semua Kandang (${names.join(' + ')})` : 'Semua Kandang';
|
||
}
|
||
const match = list.find((k) => k.id?.toString() === kandangId.toString());
|
||
return match?.name || `Kandang ${kandangId}`;
|
||
};
|
||
|
||
/**
|
||
* Calendar date of a given cycle day, so the PDF carries a real date and not
|
||
* only "hari ke-48" — which means nothing to whoever reads the file later.
|
||
* Day 0 is the cycle's start date (Hitung Ayam index).
|
||
*/
|
||
export const cycleDayToDate = (
|
||
startDate: Date | string | null | undefined,
|
||
day: number | null | undefined
|
||
): Date | null => {
|
||
if (!startDate || day == null || !Number.isFinite(day) || day < 0) return null;
|
||
const start = startDate instanceof Date ? startDate : new Date(startDate);
|
||
if (Number.isNaN(start.getTime())) return null;
|
||
return reportDayToDate(start, day);
|
||
};
|
||
|
||
const shortDate = (value: Date | null): string =>
|
||
value
|
||
? value.toLocaleDateString('id-ID', { day: 'numeric', month: 'short', year: 'numeric' })
|
||
: '';
|
||
|
||
/**
|
||
* "22 Jul 2026" for a single day, "16 Jul 2026 – 22 Jul 2026" for a range.
|
||
* Returns null when the cycle start is unknown, so the caller simply omits it
|
||
* rather than printing a guessed date.
|
||
*/
|
||
export const describeDataDates = (
|
||
startDate: Date | string | null | undefined,
|
||
fromDay: number | null | undefined,
|
||
toDay?: number | null
|
||
): string | null => {
|
||
const from = cycleDayToDate(startDate, fromDay);
|
||
if (!from) return null;
|
||
const to =
|
||
toDay != null && toDay !== fromDay ? cycleDayToDate(startDate, toDay) : null;
|
||
return to ? `${shortDate(from)} – ${shortDate(to)}` : shortDate(from);
|
||
};
|
||
|
||
/** Pull the day numbers out of labels like "hari ke-42 s/d ke-48". */
|
||
export const parseDayRangeLabel = (
|
||
label: string | null | undefined
|
||
): { fromDay: number | null; toDay: number | null } => {
|
||
if (!label) return { fromDay: null, toDay: null };
|
||
const numbers = label.match(/\d+/g);
|
||
if (!numbers || numbers.length === 0) return { fromDay: null, toDay: null };
|
||
const first = parseInt(numbers[0] ?? '', 10);
|
||
const last = parseInt(numbers[numbers.length - 1] ?? '', 10);
|
||
if (!Number.isFinite(first)) return { fromDay: null, toDay: null };
|
||
return { fromDay: first, toDay: numbers.length > 1 ? last : null };
|
||
};
|
||
|
||
/** ISO dates for filenames: sorts chronologically in a file manager. */
|
||
export const isoDataDates = (
|
||
startDate: Date | string | null | undefined,
|
||
fromDay: number | null | undefined,
|
||
toDay?: number | null
|
||
): string | null => {
|
||
// Built from LOCAL parts, not toISOString(): in WIB (+7) midnight local is
|
||
// 17:00 UTC the previous day, so the UTC form printed a filename dated one
|
||
// day earlier than the header inside the very same PDF.
|
||
const iso = (value: Date | null) =>
|
||
value
|
||
? `${value.getFullYear()}-${String(value.getMonth() + 1).padStart(2, '0')}-${String(
|
||
value.getDate()
|
||
).padStart(2, '0')}`
|
||
: null;
|
||
const from = iso(cycleDayToDate(startDate, fromDay));
|
||
if (!from) return null;
|
||
const to =
|
||
toDay != null && toDay !== fromDay ? iso(cycleDayToDate(startDate, toDay)) : null;
|
||
return to ? `${from}_sd_${to}` : from;
|
||
};
|
||
|
||
/** Filename-safe: no spaces, punctuation, or accents. */
|
||
const slug = (value: string): string =>
|
||
value
|
||
.normalize('NFD')
|
||
.replace(/[̀-ͯ]/g, '')
|
||
.replace(/[^a-zA-Z0-9]+/g, '-')
|
||
.replace(/^-+|-+$/g, '');
|
||
|
||
/**
|
||
* Filename carrying the same identity as the printed header.
|
||
*
|
||
* The old names were `AI_Insight_HitungAyam_Hari_48.pdf` — two reports from
|
||
* different coops, or the daily and weekly view of the same day, collided on
|
||
* one name and silently overwrote each other in the downloads folder.
|
||
*/
|
||
export const buildPdfFilename = (parts: {
|
||
/** "Dashboard", "Hitung-Ayam", or the topic key. */
|
||
reportName: string;
|
||
area: string;
|
||
kandangLabel: string;
|
||
/** "Harian", "Mingguan-Minggu-6", "Akhir-Siklus". */
|
||
periodSlug: string;
|
||
/** From `isoDataDates`. */
|
||
isoDates?: string | null;
|
||
/** Default AI Insight prefix. Daily report uses "Laporan". */
|
||
prefix?: string;
|
||
}): string => {
|
||
const segments = [
|
||
parts.prefix || 'AI-Insight',
|
||
slug(parts.reportName),
|
||
slug(parts.area),
|
||
slug(parts.kandangLabel),
|
||
slug(parts.periodSlug),
|
||
parts.isoDates || null,
|
||
].filter(Boolean);
|
||
return `${segments.join('_')}.pdf`;
|
||
};
|
||
|
||
/** Compact period token for filenames, matching `describeReportPeriod`. */
|
||
export const reportPeriodSlug = (
|
||
reportType: 'daily' | 'weekly' | 'end_cycle',
|
||
reportPeriod?: string | null
|
||
): string => {
|
||
if (reportType === 'weekly') return reportPeriod ? `Mingguan-${reportPeriod}` : 'Mingguan';
|
||
if (reportType === 'end_cycle') return 'Akhir-Siklus';
|
||
// Keeps one file per day instead of every day overwriting "…-Harian.pdf".
|
||
return reportPeriod ? `Harian-${reportPeriod}` : 'Harian';
|
||
};
|
||
|
||
const formatDate = (value?: Date | string | null): string => {
|
||
if (!value) return '';
|
||
const date = value instanceof Date ? value : new Date(value);
|
||
if (Number.isNaN(date.getTime())) return '';
|
||
return date.toLocaleDateString('id-ID', { day: 'numeric', month: 'long', year: 'numeric' });
|
||
};
|
||
|
||
interface PdfReportHeaderProps {
|
||
/** e.g. "AI Insight — Hitung Ayam" */
|
||
title: string;
|
||
/** e.g. "Sukawarna" */
|
||
area: string;
|
||
/** e.g. "Kandang Atas" or "Semua Kandang (Atas + Bawah)" */
|
||
kandangLabel: string;
|
||
/** e.g. "Laporan Mingguan — Minggu 6" */
|
||
periodLabel: string;
|
||
/** Cycle the data belongs to. */
|
||
cycleId?: string | null;
|
||
/** Calendar range the data covers, when the card knows it. */
|
||
dataDateLabel?: string | null;
|
||
/** Extra print-only lines just below the identity block (e.g. final FCR/EEF). */
|
||
children?: React.ReactNode;
|
||
}
|
||
|
||
export const PdfReportHeader: React.FC<PdfReportHeaderProps> = ({
|
||
title,
|
||
area,
|
||
kandangLabel,
|
||
periodLabel,
|
||
cycleId,
|
||
dataDateLabel,
|
||
children,
|
||
}) => (
|
||
<div
|
||
className={PDF_HEADER_CLASS}
|
||
style={{ display: 'none' }}
|
||
// Printed, never read by screen readers on the live page.
|
||
aria-hidden="true"
|
||
>
|
||
<div
|
||
style={{
|
||
borderBottom: '2px solid #7c3aed',
|
||
paddingBottom: '10px',
|
||
marginBottom: '14px',
|
||
}}
|
||
>
|
||
<div style={{ fontSize: '17px', fontWeight: 700, color: '#111827' }}>{title}</div>
|
||
<div style={{ fontSize: '13px', color: '#374151', marginTop: '5px' }}>
|
||
<strong>Lokasi:</strong> {area} — {kandangLabel}
|
||
</div>
|
||
<div style={{ fontSize: '13px', color: '#374151', marginTop: '2px' }}>
|
||
{/* Deliberately no cycle-day here: it is the cycle's CURRENT day, which
|
||
for a weekly or end-cycle report belongs to a different span than
|
||
the dates beside it — "Minggu 3 (hari ke-48) 5–11 Jun" read as a
|
||
contradiction. The calendar range is the honest answer. */}
|
||
<strong>Periode:</strong> {periodLabel}
|
||
{dataDateLabel ? ` · ${dataDateLabel}` : ''}
|
||
</div>
|
||
{cycleId ? (
|
||
<div style={{ fontSize: '12px', color: '#6b7280', marginTop: '2px' }}>
|
||
<strong>Siklus:</strong> {cycleId}
|
||
</div>
|
||
) : null}
|
||
<div style={{ fontSize: '12px', color: '#6b7280', marginTop: '2px' }}>
|
||
Dicetak: {formatDate(new Date())}
|
||
</div>
|
||
{children ? (
|
||
<div style={{ fontSize: '22px', color: '#111827', marginTop: '12px', fontWeight: 700 }}>
|
||
{children}
|
||
</div>
|
||
) : null}
|
||
</div>
|
||
</div>
|
||
);
|
||
|
||
/**
|
||
* Un-hide the header inside html2canvas's cloned DOM.
|
||
*
|
||
* html2canvas photographs a detached clone, so flipping display here shows the
|
||
* block in the PDF without it ever flashing on the live page.
|
||
*/
|
||
export const revealPdfHeaders = (clonedElement: HTMLElement): void => {
|
||
clonedElement.querySelectorAll<HTMLElement>(`.${PDF_HEADER_CLASS}`).forEach((node) => {
|
||
node.style.display = 'block';
|
||
});
|
||
};
|
||
|
||
export default PdfReportHeader;
|