Files
irrlichtandClaude Opus 5.5 ddeca63ae9 Refactoring: cmd/kver + internal-Pakete statt package main
Aufteilung nach Zuständigkeit (httpapi, account, linkpreview, charts,
impression, media, database, apperr), Abhängigkeiten per Konstruktor
statt globalem Zustand, Worker mit Context-gesteuertem Lebenszyklus.
Lange Funktionen aufgeteilt, ignorierte Fehler behandelt bzw. geloggt,
Schema als schema.sql eingebettet.

Logs jetzt strukturiert (slog) ohne Client-IP und Query-String.
Tests laufen parallel mit eigenem Schema je Test; neue Tests für
account, media und apperr.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01TiXsPUqw7oeomZ8wZrQW5q
2026-10-09 19:44:34 +02:00

306 lines
8.8 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package charts
import (
"fmt"
"html"
"math"
"strconv"
"strings"
"time"
)
var weekdayNames = [7]string{"Mo", "Di", "Mi", "Do", "Fr", "Sa", "So"}
var weekdayLong = [7]string{"Montag", "Dienstag", "Mittwoch", "Donnerstag", "Freitag", "Samstag", "Sonntag"}
// hourRanges: "9–10 Uhr" für die Infozeile.
func hourRanges() []string {
l := make([]string, 24)
for i := range l {
l[i] = fmt.Sprintf("%d–%d Uhr", i, i+1)
}
return l
}
func hourLabels() []string {
l := make([]string, 24)
for i := range l {
l[i] = strconv.Itoa(i)
}
return l
}
// --- SVG ---
// Maße im viewBox-Raum. narrow entspricht der schmalen Inhaltsspalte (600 px),
// wide der breiten Statistik-Seite (1200 px); bis dorthin wird 1:1 gezeichnet,
// darunter skaliert das SVG mit.
type size struct{ w, h int }
var (
narrow = size{600, 240}
wide = size{1200, 300}
)
const (
padLeft = 44
padRight = 12
padTop = 12
padBottom = 26
fontSize = 13
)
const colorGrid = "#ddd"
// colorStack sind die Füllfarben der Stapel, Reihenfolge wie postKinds.
var colorStack = [2]string{"#444", "#aaa"}
type svg struct{ strings.Builder }
// f hängt formatierten Text an; Schreiben in einen strings.Builder scheitert nie.
func (b *svg) f(format string, a ...any) { _, _ = fmt.Fprintf(b, format, a...) }
func svgOpen(b *svg, sz size, label string) {
b.f(`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 %d %d" role="img" aria-label="%s" font-size="%d" fill="black">`,
sz.w, sz.h, html.EscapeString(label), fontSize)
}
func emptyChart(sz size, label string) string {
var b svg
svgOpen(&b, sz, label)
b.f(`<text x="%d" y="%d" text-anchor="middle" fill="gray">Noch keine Daten.</text></svg>`, sz.w/2, sz.h/2)
return b.String()
}
// niceScale wählt eine runde Schrittweite (1, 2, 5 × 10^k) für etwa vier
// Gitterlinien und die darauf aufgerundete Obergrenze.
func niceScale(max float64) (step, top float64) {
if max <= 0 {
max = 1
}
raw := max / 4
mag := math.Pow(10, math.Floor(math.Log10(raw)))
step = 10 * mag
for _, m := range []float64{1, 2, 5} {
if m*mag >= raw {
step = m * mag
break
}
}
return step, math.Ceil(max/step-1e-9) * step
}
// fmtNum schreibt eine Zahl mit höchstens zwei Nachkommastellen und
// deutschem Komma.
func fmtNum(v float64) string {
return strings.Replace(strconv.FormatFloat(math.Round(v*100)/100, 'f', -1, 64), ".", ",", 1)
}
// yAxis zeichnet Gitterlinien mit Beschriftung und liefert die Abbildung
// Wert -> y-Koordinate.
func yAxis(b *svg, sz size, max float64, top int) func(float64) float64 {
step, maxV := niceScale(max)
bottom := float64(sz.h - padBottom)
y := func(v float64) float64 { return bottom - v/maxV*(bottom-float64(top)) }
for v := 0.0; v <= maxV+step/2; v += step {
yy := y(v)
color := colorGrid
if v == 0 {
color = "black"
}
b.f(`<line x1="%d" y1="%.1f" x2="%d" y2="%.1f" stroke="%s"/>`, padLeft, yy, sz.w-padRight, yy, color)
b.f(`<text x="%d" y="%.1f" text-anchor="end">%s</text>`, padLeft-6, yy+4, fmtNum(v))
}
return y
}
func maxOf(vals []float64) float64 {
m := 0.0
for _, v := range vals {
m = math.Max(m, v)
}
return m
}
// series ist eine Tagesreihe für lineChart.
type series struct {
label, unit string
days []time.Time
vals []float64
}
// lineChart zeichnet eine Tagesreihe als Linie. Alle Tage seit Beginn werden
// auf die volle Breite gestaucht; unsichtbare Streifen je Tag tragen den
// Tooltip (<title>), denselben Text in data-tip für die Infozeile unter dem
// Diagramm (StatsPage.tsx) und eine senkrechte Markierung.
func lineChart(sz size, s series) string {
if len(s.days) == 0 {
return emptyChart(sz, s.label)
}
days, vals := s.days, s.vals
var b svg
svgOpen(&b, sz, s.label)
y := yAxis(&b, sz, maxOf(vals), padTop)
plotW := float64(sz.w - padLeft - padRight)
n := len(days)
x := func(i int) float64 {
if n == 1 {
return padLeft + plotW/2
}
return padLeft + float64(i)*plotW/float64(n-1)
}
bottom := sz.h - padBottom
for _, i := range dateTicks(days) {
xx := x(i)
b.f(`<line x1="%.1f" y1="%d" x2="%.1f" y2="%d" stroke="black"/>`, xx, bottom, xx, bottom+4)
tx := math.Min(math.Max(xx, padLeft+16), float64(sz.w-padRight-16))
b.f(`<text x="%.1f" y="%d" text-anchor="middle">%s</text>`, tx, bottom+18, dateTickLabel(days[i]))
}
var pts strings.Builder
for i, v := range vals {
fmt.Fprintf(&pts, "%.1f,%.1f ", x(i), y(v))
}
if n == 1 {
b.f(`<circle cx="%.1f" cy="%.1f" r="3"/>`, x(0), y(vals[0]))
} else {
b.f(`<polyline points="%s" fill="none" stroke="black" stroke-width="1.5" stroke-linejoin="round"/>`,
strings.TrimSpace(pts.String()))
}
slot := plotW / float64(max(n-1, 1))
for i, d := range days {
tip := fmt.Sprintf("%s, %s: %s %s", weekdayNames[isoWeekday(d)], d.Format("02.01.2006"), fmtNum(vals[i]), s.unit)
// Die Markierungslinie ist versteckt; das CSS zeigt sie beim Hovern
// über den Streifen (.chart g:hover .mark).
b.f(`<g data-tip="%s"><title>%s</title><rect x="%.1f" y="%d" width="%.1f" height="%d" fill="transparent"/>`,
tip, tip, x(i)-slot/2, padTop, slot, bottom-padTop)
b.f(`<line class="mark" x1="%.1f" y1="%d" x2="%.1f" y2="%d" stroke="black" visibility="hidden" pointer-events="none"/></g>`,
x(i), padTop, x(i), bottom)
}
b.f(`</svg>`)
return b.String()
}
var monthNames = [12]string{"Jan", "Feb", "Mär", "Apr", "Mai", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Dez"}
const maxTicks = 8
// dateTicks wählt die beschrifteten Tage: Monatsanfänge, bei langen Reihen
// nur jedes Quartal, Halbjahr oder Jahr; bei Reihen unter zwei Monaten die
// Montage. Höchstens maxTicks Beschriftungen.
func dateTicks(days []time.Time) []int {
if months := indicesWhere(days, func(d time.Time) bool { return d.Day() == 1 }); len(months) >= 2 {
for _, step := range []int{1, 3, 6} {
if picked := everyNthMonth(days, months, step); len(picked) <= maxTicks {
return picked
}
}
return everyNthMonth(days, months, 12)
}
mondays := indicesWhere(days, func(d time.Time) bool { return d.Weekday() == time.Monday })
for len(mondays) > maxTicks {
mondays = everyOther(mondays)
}
return mondays
}
func indicesWhere(days []time.Time, match func(time.Time) bool) []int {
var idx []int
for i, d := range days {
if match(d) {
idx = append(idx, i)
}
}
return idx
}
// everyNthMonth behält die Monatsanfänge jedes step-ten Monats, gezählt ab
// Januar (step 3: Quartalsanfänge).
func everyNthMonth(days []time.Time, months []int, step int) []int {
var picked []int
for _, i := range months {
if (int(days[i].Month())-1)%step == 0 {
picked = append(picked, i)
}
}
return picked
}
func everyOther(idx []int) []int {
var half []int
for j := 0; j < len(idx); j += 2 {
half = append(half, idx[j])
}
return half
}
// dateTickLabel: "02.10." bei Wochen-Ticks, sonst Monatsname; der Januar
// zeigt stattdessen die Jahreszahl.
func dateTickLabel(d time.Time) string {
if d.Day() != 1 {
return d.Format("02.01.")
}
if d.Month() == time.January {
return strconv.Itoa(d.Year())
}
return monthNames[d.Month()-1]
}
// bars sind Kategorien mit je Ø Threads und Antworten für stackedBars.
type bars struct {
label string
labels []string // Achsenbeschriftung
tipLabels []string // Kategorie im Tooltip
vals [][2]float64
}
// stackedBars zeichnet Ø Threads (unten) und Antworten (oben) je Kategorie
// als gestapelte Säulen mit Legende.
func stackedBars(sz size, bs bars) string {
vals := bs.vals
totals := make([]float64, len(vals))
for i, v := range vals {
totals[i] = v[0] + v[1]
}
if maxOf(totals) == 0 {
return emptyChart(sz, bs.label)
}
var b svg
svgOpen(&b, sz, bs.label)
top := padTop + 20
x0 := padLeft + 4
for k, name := range postKinds {
b.f(`<rect x="%d" y="%d" width="11" height="11" fill="%s"/>`, x0, padTop-2, colorStack[k])
b.f(`<text x="%d" y="%d">%s</text>`, x0+16, padTop+8, name)
x0 += 16 + 9*len(name) + 16
}
y := yAxis(&b, sz, maxOf(totals), top)
bottom := float64(sz.h - padBottom)
slot := float64(sz.w-padLeft-padRight) / float64(len(vals))
barW := slot * 0.7
for i, v := range vals {
x := padLeft + float64(i)*slot + (slot-barW)/2
tip := html.EscapeString(fmt.Sprintf("%s: Ø %s Beiträge pro Tag (%s Threads, %s Antworten)",
bs.tipLabels[i], fmtNum(totals[i]), fmtNum(v[0]), fmtNum(v[1])))
b.f(`<g data-tip="%s"><title>%s</title>`, tip, tip)
// Unsichtbare volle Säule, damit auch kurze Balken gut zu treffen sind.
b.f(`<rect x="%.1f" y="%d" width="%.1f" height="%.1f" fill="transparent"/>`,
padLeft+float64(i)*slot, top, slot, bottom-float64(top))
base := 0.0
for k := range postKinds {
if v[k] > 0 {
b.f(`<rect x="%.1f" y="%.1f" width="%.1f" height="%.1f" fill="%s"/>`,
x, y(base+v[k]), barW, y(base)-y(base+v[k]), colorStack[k])
}
base += v[k]
}
b.f(`</g>`)
b.f(`<text x="%.1f" y="%.0f" text-anchor="middle">%s</text>`, x+barW/2, bottom+18, html.EscapeString(bs.labels[i]))
}
b.f(`</svg>`)
return b.String()
}