Files
refusol-datalogging/frontend/src/components/Charts.jsx
T
bonaminandClaude Opus 5.5 0b74842560 feat(frontend): settings page, Greek translation, comparison and chart options
The end user is Greek and the owner wants to confirm at a glance that
every inverter is working without one cloud-shaded reading raising doubt.

- Settings page (gear in the header), stored on the server and shared
  by every viewer; saving asks for the API key once per device.
- Output comparison: latest reading or average of the last 3/5 (evens out
  a passing cloud); bar scale auto (round ceiling above the best) /
  highest = 100% / custom kW; percentage vs fleet median, best inverter
  or the custom kW.
- Power chart: 30 min to last month plus "last production run", a
  per-visit range picker on the card, optional light/strong smoothing.
  Series reporting slower than the chart bucket (INV5, every 5 min) are
  now interpolated across short gaps — on 1-min buckets their line used
  to vanish entirely; night gaps still break the line.
- Greek/English: per-device switch in the header, shared default in
  settings, Greek number/date formats; issue texts translated from
  code + params.
- AC voltage shown as phase (L-N) or line (L-L, x√3, matching the
  inverter screens); lifetime total says how many inverters it covers;
  the inverter's own status text appears on its card.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 18:15:38 +03:00

263 lines
8.4 KiB
React

import { useMemo } from 'react'
import {
Bar,
BarChart,
CartesianGrid,
Line,
LineChart,
ResponsiveContainer,
Tooltip,
XAxis,
YAxis,
} from 'recharts'
import { useThemeColors } from '../lib/colors'
import { dateTimeLabel, dayLabel, timeLabel } from '../lib/format'
import { useT } from '../lib/i18n'
export function Legend({ series }) {
if (series.length < 2) return null
return (
<ul className="flex flex-wrap gap-x-4 gap-y-1 text-xs text-ink-2">
{series.map((s) => (
<li key={s.key} className="inline-flex items-center gap-1.5">
<span className="h-0.5 w-3 rounded-full" style={{ background: s.color, height: 3 }} />
{s.name}
</li>
))}
</ul>
)
}
function TooltipBox({ title, rows, total }) {
const { t } = useT()
return (
<div className="card min-w-40 px-3 py-2 text-xs shadow-lg">
<div className="mb-1 font-medium text-ink-2">{title}</div>
<table className="w-full">
<tbody>
{rows.map((r) => (
<tr key={r.key}>
<td className="py-0.5 pr-3">
<span className="inline-flex items-center gap-1.5 text-ink-2">
<span className="inline-block h-2 w-2 rounded-full" style={{ background: r.color }} />
{r.name}
</span>
</td>
<td className="tnum py-0.5 text-right font-medium text-ink">{r.value}</td>
</tr>
))}
{total && (
<tr className="border-t border-line">
<td className="pt-1 pr-3 text-ink-2">{t('chart.total')}</td>
<td className="tnum pt-1 text-right font-semibold text-ink">{total}</td>
</tr>
)}
</tbody>
</table>
</div>
)
}
const axisTick = (c) => ({ fill: c.muted, fontSize: 11 })
// Silences up to this long are drawn through; longer ones (night, outage)
// break the line. Covers a unit reporting every ~5 min plus a missed cycle.
const BRIDGE_SECONDS = 900
const SMOOTHING_RADIUS = { off: 0, light: 1, strong: 3 }
/**
* Chart rows from API points: a gap row where the whole fleet went silent,
* values interpolated where one series reports less often than the bucket
* (INV5 every ~5 min on a 1-min chart would otherwise have no line at all),
* then an optional centred moving average. Interpolated values are flagged
* `<key>__est` so the tooltip can mark them.
*/
function prepare(points, keys, bucket, smoothing) {
const maxGap = Math.max(BRIDGE_SECONDS, (bucket || 0) * 2.5)
const rows = []
points.forEach((p, i) => {
if (i && p.t - points[i - 1].t > maxGap) rows.push({ t: points[i - 1].t + (bucket || 1) })
rows.push({ ...p })
})
for (const key of keys) {
let prev = -1
rows.forEach((r, i) => {
if (r[key] == null) return
if (prev >= 0 && i - prev > 1 && r.t - rows[prev].t <= maxGap) {
const a = rows[prev]
for (let j = prev + 1; j < i; j++) {
rows[j][key] = a[key] + ((r[key] - a[key]) * (rows[j].t - a.t)) / (r.t - a.t)
rows[j][`${key}__est`] = true
}
}
prev = i
})
}
const radius = SMOOTHING_RADIUS[smoothing] ?? 0
if (radius) {
for (const key of keys) {
const raw = rows.map((r) => r[key])
rows.forEach((r, i) => {
if (raw[i] == null) return
// Only neighbours on the same unbroken stretch of line
let sum = raw[i]
let n = 1
for (let j = i - 1; j >= i - radius && j >= 0 && raw[j] != null; j--) {
sum += raw[j]
n++
}
for (let j = i + 1; j <= i + radius && j < raw.length && raw[j] != null; j++) {
sum += raw[j]
n++
}
r[key] = sum / n
})
}
}
return rows
}
/**
* Lines over time. points: [{t: unix seconds, [series.key]: number}]
* series: [{key, name, color}]. Gaps (night, outages) stay gaps.
*/
export function TimeLines({
points,
series,
from,
to,
bucket,
format,
axisFormat,
height = 240,
showTotal = false,
smoothing = 'off',
}) {
const c = useThemeColors()
const span = to - from
const keys = series.map((s) => s.key).join(',')
const data = useMemo(() => prepare(points, keys.split(','), bucket, smoothing), [points, keys, bucket, smoothing])
return (
<div style={{ height }}>
<ResponsiveContainer width="100%" height="100%">
<LineChart data={data} margin={{ top: 8, right: 8, bottom: 0, left: 0 }}>
<CartesianGrid stroke={c.grid} vertical={false} />
<XAxis
dataKey="t"
type="number"
domain={[from, to]}
scale="time"
tickFormatter={(t) => timeLabel(t, span)}
tick={axisTick(c)}
stroke={c.axis}
tickLine={false}
minTickGap={28}
/>
<YAxis
tickFormatter={axisFormat ?? format}
tick={axisTick(c)}
axisLine={false}
tickLine={false}
width={48}
/>
<Tooltip
cursor={{ stroke: c.axis, strokeWidth: 1 }}
content={({ active, payload, label }) => {
if (!active || !payload?.length) return null
const row = payload[0].payload
const rows = series
.filter((s) => row[s.key] != null)
.map((s) => ({ ...s, value: (row[`${s.key}__est`] ? '≈ ' : '') + format(row[s.key]) }))
const total = showTotal
? format(series.reduce((sum, s) => sum + (payload[0].payload[s.key] ?? 0), 0))
: null
return <TooltipBox title={dateTimeLabel(label)} rows={rows} total={total} />
}}
/>
{series.map((s) => (
<Line
key={s.key}
dataKey={s.key}
name={s.name}
stroke={s.color}
strokeWidth={2}
type={smoothing === 'off' ? 'linear' : 'monotone'}
dot={false}
activeDot={{ r: 4, stroke: c.surface, strokeWidth: 2 }}
connectNulls={false}
isAnimationActive={false}
/>
))}
</LineChart>
</ResponsiveContainer>
</div>
)
}
/**
* Bars per day. days: [{day: 'YYYY-MM-DD', [series.key]: number}].
* Several series are stacked (the stack height is the day's total).
*/
export function DayBars({ days, series, format, axisFormat, height = 220 }) {
const c = useThemeColors()
const last = series.length - 1
return (
<div style={{ height }}>
<ResponsiveContainer width="100%" height="100%">
<BarChart data={days} margin={{ top: 8, right: 8, bottom: 0, left: 0 }} barCategoryGap="18%">
<CartesianGrid stroke={c.grid} vertical={false} />
<XAxis
dataKey="day"
tickFormatter={(d) => dayLabel(d)}
tick={axisTick(c)}
stroke={c.axis}
tickLine={false}
minTickGap={24}
/>
<YAxis
tickFormatter={axisFormat ?? format}
tick={axisTick(c)}
axisLine={false}
tickLine={false}
width={48}
/>
<Tooltip
cursor={{ fill: c.grid, opacity: 0.5 }}
content={({ active, payload, label }) => {
if (!active || !payload?.length) return null
const row = payload[0].payload
const rows = series.map((s) => ({ ...s, value: format(row[s.key]) }))
const total =
series.length > 1 ? format(series.reduce((sum, s) => sum + (row[s.key] ?? 0), 0)) : null
return <TooltipBox title={dayLabel(label, true)} rows={rows} total={total} />
}}
/>
{series.map((s, i) => (
<Bar
key={s.key}
dataKey={s.key}
name={s.name}
stackId="day"
fill={s.color}
stroke={series.length > 1 ? c.surface : undefined}
strokeWidth={series.length > 1 ? 1 : 0}
radius={i === last ? [3, 3, 0, 0] : 0}
isAnimationActive={false}
/>
))}
</BarChart>
</ResponsiveContainer>
</div>
)
}
export function EnergyFootnote({ estimated }) {
const { t } = useT()
return (
<div className="mt-1 flex justify-between gap-3 text-[11px] text-muted">
<span>{estimated && t('energy.footEstimated')}</span>
<span className="shrink-0">{t('energy.axis')}</span>
</div>
)
}