pelagia-portal/App/components/reports/charts.tsx
Hardik 34143b5e75
Some checks failed
PR checks / checks (pull_request) Failing after 15s
PR checks / integration (pull_request) Successful in 41s
fix(reports): chart series all rendered one colour (RSC boundary bug)
The comparison charts (and detail-page breakdown swatches) rendered every
series in recharts' default colour instead of the per-item palette.

Root cause: `SERIES_COLORS` was defined in `components/reports/charts.tsx`,
which is a "use client" module. The report **pages are server components** and
imported the palette from it. A plain value imported from a client module into
a server component is a client-reference proxy, not the real array — so
`SERIES_COLORS[i % SERIES_COLORS.length]` was `SERIES_COLORS[NaN]` → undefined,
every line got `stroke={undefined}`, and recharts fell back to #3182bd. (The
literal `strokeWidth={2}` still applied, which is why only the colour was wrong.
It passed jsdom tests because those import the array directly, not across the
RSC boundary.)

Fix: move the palette to a dependency-free shared module `lib/report-colors.ts`
(no "use client", no server-only imports) that resolves to the real array in
both server and client graphs. `charts.tsx` and all four report pages import it
from there. It can't live in `lib/reports.ts` (that imports Prisma `db`, which
must not enter the client bundle).

Verified in a real browser: line strokes now cycle the 10-colour palette
(#2563eb, #16a34a, …) instead of a uniform #3182bd.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-24 12:31:40 +05:30

150 lines
6.3 KiB
TypeScript

"use client";
import {
LineChart,
Line,
BarChart,
Bar,
XAxis,
YAxis,
Tooltip,
Legend,
ResponsiveContainer,
CartesianGrid,
Cell,
} from "recharts";
import { SERIES_COLORS } from "@/lib/report-colors";
// Re-exported for back-compat; new server-component code should import the
// palette from "@/lib/report-colors" directly (see that file for why).
export { SERIES_COLORS };
/** Compact Indian-currency formatter for axis ticks / tooltips (₹..K / ₹..L / ₹..Cr). */
export function formatINRShort(n: number): string {
const a = Math.abs(n);
if (a >= 1_00_00_000) return `${(n / 1_00_00_000).toFixed(1)}Cr`;
if (a >= 1_00_000) return `${(n / 1_00_000).toFixed(1)}L`;
if (a >= 1_000) return `${(n / 1_000).toFixed(0)}K`;
return `${n.toFixed(0)}`;
}
function fullINR(n: number): string {
return n.toLocaleString("en-IN", { style: "currency", currency: "INR", maximumFractionDigits: 0 });
}
export interface Series {
key: string;
color: string;
}
interface ComparisonProps {
kind: "lines" | "bars";
data: Record<string, string | number>[];
xKey: string;
series: Series[];
height?: number;
}
/** Multi-series comparison: monthly trend lines, or year-over-year grouped bars. */
export function ComparisonChart({ kind, data, xKey, series, height = 340 }: ComparisonProps) {
const axis = { tick: { fontSize: 11, fill: "#737373" }, tickLine: false, axisLine: false } as const;
return (
<ResponsiveContainer width="100%" height={height}>
{kind === "lines" ? (
<LineChart data={data} margin={{ top: 8, right: 12, bottom: 4, left: 8 }}>
<CartesianGrid strokeDasharray="3 3" stroke="#f0f0f0" vertical={false} />
<XAxis dataKey={xKey} {...axis} />
<YAxis tickFormatter={formatINRShort} width={56} {...axis} />
<Tooltip formatter={(v: number, name) => [fullINR(Number(v)), name]} />
<Legend wrapperStyle={{ fontSize: 11 }} iconType="plainline" />
{series.map((s) => (
<Line key={s.key} type="monotone" dataKey={s.key} stroke={s.color} strokeWidth={2} dot={{ r: 2 }} activeDot={{ r: 5 }} />
))}
</LineChart>
) : (
<BarChart data={data} margin={{ top: 8, right: 12, bottom: 4, left: 8 }}>
<CartesianGrid strokeDasharray="3 3" stroke="#f0f0f0" vertical={false} />
<XAxis dataKey={xKey} {...axis} />
<YAxis tickFormatter={formatINRShort} width={56} {...axis} />
<Tooltip formatter={(v: number, name) => [fullINR(Number(v)), name]} cursor={{ fill: "#f5f5f5" }} />
<Legend wrapperStyle={{ fontSize: 11 }} />
{series.map((s) => (
<Bar key={s.key} dataKey={s.key} fill={s.color} radius={[3, 3, 0, 0]} />
))}
</BarChart>
)}
</ResponsiveContainer>
);
}
interface TrendProps {
kind: "line" | "bar";
data: { label: string; value: number }[];
height?: number;
}
/** Single-series spend trend (monthly line or yearly bar). */
export function TrendChart({ kind, data, height = 300 }: TrendProps) {
const axis = { tick: { fontSize: 11, fill: "#737373" }, tickLine: false, axisLine: false } as const;
return (
<ResponsiveContainer width="100%" height={height}>
{kind === "line" ? (
<LineChart data={data} margin={{ top: 8, right: 12, bottom: 4, left: 8 }}>
<CartesianGrid strokeDasharray="3 3" stroke="#f0f0f0" vertical={false} />
<XAxis dataKey="label" {...axis} />
<YAxis tickFormatter={formatINRShort} width={56} {...axis} />
<Tooltip formatter={(v: number) => [fullINR(Number(v)), "Spend"]} />
<Line type="monotone" dataKey="value" stroke="#2563eb" strokeWidth={2} dot={{ r: 3 }} fill="rgba(37,99,235,0.08)" />
</LineChart>
) : (
<BarChart data={data} margin={{ top: 8, right: 12, bottom: 4, left: 8 }}>
<CartesianGrid strokeDasharray="3 3" stroke="#f0f0f0" vertical={false} />
<XAxis dataKey="label" {...axis} />
<YAxis tickFormatter={formatINRShort} width={56} {...axis} />
<Tooltip formatter={(v: number) => [fullINR(Number(v)), "Spend"]} cursor={{ fill: "#f5f5f5" }} />
<Bar dataKey="value" fill="#2563eb" radius={[4, 4, 0, 0]} />
</BarChart>
)}
</ResponsiveContainer>
);
}
/** Horizontal top-N breakdown bars (each bar its own colour). */
export function BreakdownChart({ data, height = 300 }: { data: { label: string; value: number }[]; height?: number }) {
const trimmed = data.map((d) => ({ ...d, short: d.label.length > 22 ? d.label.slice(0, 21) + "…" : d.label }));
return (
<ResponsiveContainer width="100%" height={height}>
<BarChart layout="vertical" data={trimmed} margin={{ top: 4, right: 16, bottom: 4, left: 8 }}>
<CartesianGrid strokeDasharray="3 3" stroke="#f0f0f0" horizontal={false} />
<XAxis type="number" tickFormatter={formatINRShort} tick={{ fontSize: 11, fill: "#737373" }} tickLine={false} axisLine={false} />
<YAxis type="category" dataKey="short" width={140} tick={{ fontSize: 11, fill: "#525252" }} tickLine={false} axisLine={false} />
<Tooltip formatter={(v: number) => [fullINR(Number(v)), "Spend"]} cursor={{ fill: "#f5f5f5" }} />
<Bar dataKey="value" radius={[0, 4, 4, 0]}>
{trimmed.map((_, i) => (
<Cell key={i} fill={SERIES_COLORS[i % SERIES_COLORS.length]} />
))}
</Bar>
</BarChart>
</ResponsiveContainer>
);
}
/** Tiny inline trend sparkline (plain SVG — no chart library needed per row). */
export function Sparkline({ values, width = 90, height = 28 }: { values: number[]; width?: number; height?: number }) {
if (values.length < 2) return <svg width={width} height={height} />;
const max = Math.max(...values);
const min = Math.min(...values);
const pad = 3;
const span = max - min || 1;
const pts = values.map((v, i) => {
const x = pad + (i / (values.length - 1)) * (width - 2 * pad);
const y = height - pad - ((v - min) / span) * (height - 2 * pad);
return `${x.toFixed(1)},${y.toFixed(1)}`;
});
const last = pts[pts.length - 1].split(",");
return (
<svg width={width} height={height} className="overflow-visible">
<polyline points={pts.join(" ")} fill="none" stroke="#2563eb" strokeWidth={1.5} />
<circle cx={last[0]} cy={last[1]} r={2} fill="#2563eb" />
</svg>
);
}