Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7ac598ea81 | ||
|
|
075b42584a | ||
|
|
8c872b240a | ||
|
|
0e51df7bad | ||
|
|
b53ee828ba |
+48
-1
@@ -7,6 +7,52 @@ die Versionierung [Semantic Versioning](https://semver.org/lang/de/).
|
|||||||
|
|
||||||
## [Unveröffentlicht]
|
## [Unveröffentlicht]
|
||||||
|
|
||||||
|
## [0.5.0] — 2026-09-01
|
||||||
|
|
||||||
|
Übersicht, Kalender und Statistik.
|
||||||
|
|
||||||
|
### Hinzugefügt
|
||||||
|
|
||||||
|
- **Übersicht** mit „Weiterschauen" (laufende Serien samt nächster Episode,
|
||||||
|
Fortschritt und „+1 Episode" direkt aus der Kachel), den Ausstrahlungen der
|
||||||
|
nächsten vier Wochen und den Watchlist-Titeln, die zuletzt auf einem Dienst
|
||||||
|
verfügbar geworden sind.
|
||||||
|
- **Kalender** als Monatsraster mit Blättern und Sprung zum heutigen Tag,
|
||||||
|
darunter die Termine des Monats als Liste. Ausgezeichnet als Tabelle — ein
|
||||||
|
Kalender *ist* eine Tabelle, und mit Screenreader wird daraus dann
|
||||||
|
„Woche 3, Donnerstag, 24." statt einer ununterscheidbaren Kachelwüste.
|
||||||
|
- **Statistikseite** mit Gesamtschauzeit, Episoden und Filmen je Monat als
|
||||||
|
Diagramm, Verteilung nach Streamingdienst und Genre, Jahresrückblick
|
||||||
|
(„2026 in Zahlen") sowie den Listen „wo die meiste Zeit hinging" und
|
||||||
|
„deine besten Bewertungen". Alles aus den Sichtungen gerechnet, Rewatches
|
||||||
|
zählen mit.
|
||||||
|
- **Diagramme als handgeschriebenes SVG** — ohne Chart-Bibliothek, dafür an
|
||||||
|
den Design-Tokens. Die beiden Serienfarben sind abgedunkelte Varianten der
|
||||||
|
Signaturfarben; sie bestehen in **beiden** Farbschemata die Prüfungen auf
|
||||||
|
Helligkeitsband, Sättigung, Farbfehlsichtigkeit und Kontrast. Die vollen
|
||||||
|
Signaturtöne wären auf dunklem Grund zu hell. Legende, Achsenwerte,
|
||||||
|
Tooltip beim Überfahren und eine für Screenreader hinterlegte Tabelle
|
||||||
|
sorgen dafür, dass die Aussage nie allein an der Farbe hängt.
|
||||||
|
- Markenfarben der Streamingdienste in der Verteilung, aber nur, wenn sie auf
|
||||||
|
hellem *und* dunklem Grund mindestens 3:1 erreichen — sonst der geprüfte
|
||||||
|
Standardton.
|
||||||
|
- **7 weitere Tests** für Gesamtzahlen, Monatsgruppierung, Jahresrückblick,
|
||||||
|
„Weiterschauen" und den Kalenderzeitraum.
|
||||||
|
|
||||||
|
### Behoben
|
||||||
|
|
||||||
|
- Das Monatsdiagramm blieb leer, obwohl Sichtungen vorlagen: `date_trunc`
|
||||||
|
liefert Mitternacht in der Zeitzone der Datenbanksitzung, JavaScript legte
|
||||||
|
beim Abgleich die lokale Zone an — zwei Stunden Versatz genügten, damit kein
|
||||||
|
einziger Monatsschlüssel mehr passte. Der Schlüssel kommt jetzt als Text
|
||||||
|
(„2026-04") aus der Datenbank.
|
||||||
|
- Eine laufende Serie, bei der man auf dem Stand ist, gilt als „abgeschlossen"
|
||||||
|
und verschwand damit aus dem Kalender — dabei will man die nächste Folge
|
||||||
|
dort erst recht sehen. Jetzt fällt nur Abgebrochenes heraus.
|
||||||
|
- Der SVG-Titel des Diagramms brach die Hydration: React behandelt `<title>`
|
||||||
|
als Dokument-Metadatum und hebt es aus dem SVG heraus. Die Beschriftung
|
||||||
|
hängt jetzt als `aria-label` am `<svg>`.
|
||||||
|
|
||||||
## [0.4.0] — 2026-09-01
|
## [0.4.0] — 2026-09-01
|
||||||
|
|
||||||
Universen: zusammengehörige Titel, mehrere Reihenfolgen, ein Gesamtfortschritt.
|
Universen: zusammengehörige Titel, mehrere Reihenfolgen, ein Gesamtfortschritt.
|
||||||
@@ -168,7 +214,8 @@ Erste lauffähige Etappe: Gerüst, Marke, Datenmodell und Anmeldung.
|
|||||||
dass weitere Sprachen als zusätzliche Datei dazukommen können.
|
dass weitere Sprachen als zusätzliche Datei dazukommen können.
|
||||||
- **Seed-Skript** mit Demo-Konten sowie README und Design-Dokumentation.
|
- **Seed-Skript** mit Demo-Konten sowie README und Design-Dokumentation.
|
||||||
|
|
||||||
[Unveröffentlicht]: https://git.wilde-server.de/florian.wilde/flimmer/compare/v0.4.0...HEAD
|
[Unveröffentlicht]: https://git.wilde-server.de/florian.wilde/flimmer/compare/v0.5.0...HEAD
|
||||||
|
[0.5.0]: https://git.wilde-server.de/florian.wilde/flimmer/releases/tag/v0.5.0
|
||||||
[0.4.0]: https://git.wilde-server.de/florian.wilde/flimmer/releases/tag/v0.4.0
|
[0.4.0]: https://git.wilde-server.de/florian.wilde/flimmer/releases/tag/v0.4.0
|
||||||
[0.3.0]: https://git.wilde-server.de/florian.wilde/flimmer/releases/tag/v0.3.0
|
[0.3.0]: https://git.wilde-server.de/florian.wilde/flimmer/releases/tag/v0.3.0
|
||||||
[0.2.0]: https://git.wilde-server.de/florian.wilde/flimmer/releases/tag/v0.2.0
|
[0.2.0]: https://git.wilde-server.de/florian.wilde/flimmer/releases/tag/v0.2.0
|
||||||
|
|||||||
@@ -62,6 +62,19 @@ Alle Zeiten per `date`-Befehl erfasst (Europe/Berlin), nicht geschätzt.
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
## Etappe 5 — Dashboard, Kalender, Statistiken (v0.5.0)
|
||||||
|
|
||||||
|
| # | Start | Ende | Dauer | Arbeitsschritt |
|
||||||
|
|---|---|---|---|---|
|
||||||
|
| 5.1 | 19:39 | 19:43 | 4 min | Auswertungsschicht: Weiterschauen, kommende Episoden, neu verfügbar, Gesamtzahlen, Monatsverlauf, Verteilungen, Jahresrückblick |
|
||||||
|
| 5.2 | 19:43 | 19:46 | 3 min | Diagrammfarben gegen die Prüfungen auf Helligkeit, Sättigung, Farbfehlsichtigkeit und Kontrast gerechnet; SVG-Diagramme und Verteilungsbalken gebaut |
|
||||||
|
| 5.3 | 19:46 | 19:50 | 4 min | Seiten für Übersicht, Kalender und Statistik |
|
||||||
|
| 5.4 | 19:50 | 19:54 | 4 min | Drei Fehler gefunden und behoben: leeres Monatsdiagramm durch Zeitzonenversatz, Hydrationsbruch durch SVG-Titel, Kalender ohne abgeschlossene Serien; 7 Tests nachgezogen |
|
||||||
|
|
||||||
|
**Etappe 5 gesamt: 15 min** (2026-09-01, 19:39 – 19:54)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
## Gesamtübersicht
|
## Gesamtübersicht
|
||||||
|
|
||||||
| Etappe | Version | Dauer |
|
| Etappe | Version | Dauer |
|
||||||
@@ -70,5 +83,6 @@ Alle Zeiten per `date`-Befehl erfasst (Europe/Berlin), nicht geschätzt.
|
|||||||
| 2 — TMDB-Anbindung | 0.2.0 | 14 min |
|
| 2 — TMDB-Anbindung | 0.2.0 | 14 min |
|
||||||
| 3 — Kern-Tracking | 0.3.0 | 24 min |
|
| 3 — Kern-Tracking | 0.3.0 | 24 min |
|
||||||
| 4 — Universen | 0.4.0 | 14 min |
|
| 4 — Universen | 0.4.0 | 14 min |
|
||||||
|
| 5 — Dashboard, Kalender, Statistik | 0.5.0 | 15 min |
|
||||||
|
|
||||||
**Bisher gesamt: 90 min**
|
**Bisher gesamt: 105 min**
|
||||||
|
|||||||
+1
-1
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "flimmer",
|
"name": "flimmer",
|
||||||
"version": "0.4.0",
|
"version": "0.5.0",
|
||||||
"private": true,
|
"private": true,
|
||||||
"description": "Flimmer — selbst hostbarer Serien- und Film-Tracker",
|
"description": "Flimmer — selbst hostbarer Serien- und Film-Tracker",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
|
|||||||
@@ -0,0 +1,45 @@
|
|||||||
|
# Flimmer 0.5.0
|
||||||
|
|
||||||
|
Übersicht, Kalender und Statistik.
|
||||||
|
|
||||||
|
### Hinzugefügt
|
||||||
|
|
||||||
|
- **Übersicht** mit „Weiterschauen" (laufende Serien samt nächster Episode,
|
||||||
|
Fortschritt und „+1 Episode" direkt aus der Kachel), den Ausstrahlungen der
|
||||||
|
nächsten vier Wochen und den Watchlist-Titeln, die zuletzt auf einem Dienst
|
||||||
|
verfügbar geworden sind.
|
||||||
|
- **Kalender** als Monatsraster mit Blättern und Sprung zum heutigen Tag,
|
||||||
|
darunter die Termine des Monats als Liste. Ausgezeichnet als Tabelle — ein
|
||||||
|
Kalender *ist* eine Tabelle, und mit Screenreader wird daraus dann
|
||||||
|
„Woche 3, Donnerstag, 24." statt einer ununterscheidbaren Kachelwüste.
|
||||||
|
- **Statistikseite** mit Gesamtschauzeit, Episoden und Filmen je Monat als
|
||||||
|
Diagramm, Verteilung nach Streamingdienst und Genre, Jahresrückblick
|
||||||
|
(„2026 in Zahlen") sowie den Listen „wo die meiste Zeit hinging" und
|
||||||
|
„deine besten Bewertungen". Alles aus den Sichtungen gerechnet, Rewatches
|
||||||
|
zählen mit.
|
||||||
|
- **Diagramme als handgeschriebenes SVG** — ohne Chart-Bibliothek, dafür an
|
||||||
|
den Design-Tokens. Die beiden Serienfarben sind abgedunkelte Varianten der
|
||||||
|
Signaturfarben; sie bestehen in **beiden** Farbschemata die Prüfungen auf
|
||||||
|
Helligkeitsband, Sättigung, Farbfehlsichtigkeit und Kontrast. Die vollen
|
||||||
|
Signaturtöne wären auf dunklem Grund zu hell. Legende, Achsenwerte,
|
||||||
|
Tooltip beim Überfahren und eine für Screenreader hinterlegte Tabelle
|
||||||
|
sorgen dafür, dass die Aussage nie allein an der Farbe hängt.
|
||||||
|
- Markenfarben der Streamingdienste in der Verteilung, aber nur, wenn sie auf
|
||||||
|
hellem *und* dunklem Grund mindestens 3:1 erreichen — sonst der geprüfte
|
||||||
|
Standardton.
|
||||||
|
- **7 weitere Tests** für Gesamtzahlen, Monatsgruppierung, Jahresrückblick,
|
||||||
|
„Weiterschauen" und den Kalenderzeitraum.
|
||||||
|
|
||||||
|
### Behoben
|
||||||
|
|
||||||
|
- Das Monatsdiagramm blieb leer, obwohl Sichtungen vorlagen: `date_trunc`
|
||||||
|
liefert Mitternacht in der Zeitzone der Datenbanksitzung, JavaScript legte
|
||||||
|
beim Abgleich die lokale Zone an — zwei Stunden Versatz genügten, damit kein
|
||||||
|
einziger Monatsschlüssel mehr passte. Der Schlüssel kommt jetzt als Text
|
||||||
|
(„2026-04") aus der Datenbank.
|
||||||
|
- Eine laufende Serie, bei der man auf dem Stand ist, gilt als „abgeschlossen"
|
||||||
|
und verschwand damit aus dem Kalender — dabei will man die nächste Folge
|
||||||
|
dort erst recht sehen. Jetzt fällt nur Abgebrochenes heraus.
|
||||||
|
- Der SVG-Titel des Diagramms brach die Hydration: React behandelt `<title>`
|
||||||
|
als Dokument-Metadatum und hebt es aus dem SVG heraus. Die Beschriftung
|
||||||
|
hängt jetzt als `aria-label` am `<svg>`.
|
||||||
@@ -0,0 +1,127 @@
|
|||||||
|
import Link from "next/link";
|
||||||
|
import type { Metadata } from "next";
|
||||||
|
import { requireUser } from "@/lib/auth";
|
||||||
|
import { getSettings } from "@/lib/settings";
|
||||||
|
import { getUpcomingEpisodes } from "@/lib/stats";
|
||||||
|
import { AppShell } from "@/components/AppShell";
|
||||||
|
import { CalendarMonth } from "@/components/CalendarMonth";
|
||||||
|
import { episodeCode, formatDateLong } from "@/lib/labels";
|
||||||
|
|
||||||
|
export const metadata: Metadata = { title: "Kalender" };
|
||||||
|
|
||||||
|
/** Monatsangabe aus der URL („2026-09") oder der laufende Monat. */
|
||||||
|
function parseMonth(value: string | undefined): Date {
|
||||||
|
const match = value?.match(/^(\d{4})-(\d{2})$/);
|
||||||
|
if (match) {
|
||||||
|
const year = Number(match[1]);
|
||||||
|
const month = Number(match[2]) - 1;
|
||||||
|
if (year >= 1900 && year <= 2200 && month >= 0 && month <= 11) {
|
||||||
|
return new Date(year, month, 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const now = new Date();
|
||||||
|
return new Date(now.getFullYear(), now.getMonth(), 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
function monthParam(date: Date): string {
|
||||||
|
return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export default async function CalendarPage({
|
||||||
|
searchParams,
|
||||||
|
}: {
|
||||||
|
searchParams: Promise<{ monat?: string }>;
|
||||||
|
}) {
|
||||||
|
const user = await requireUser("/kalender");
|
||||||
|
const settings = await getSettings();
|
||||||
|
const params = await searchParams;
|
||||||
|
|
||||||
|
const month = parseMonth(params.monat);
|
||||||
|
const from = new Date(month.getFullYear(), month.getMonth(), 1);
|
||||||
|
// Das Raster reicht in den Vor- und Folgemonat hinein — die Termine auch.
|
||||||
|
const gridFrom = new Date(from.getTime() - 7 * 86_400_000);
|
||||||
|
const gridTo = new Date(from.getFullYear(), from.getMonth() + 1, 7);
|
||||||
|
|
||||||
|
const episodes = await getUpcomingEpisodes(user.id, gridFrom, gridTo);
|
||||||
|
const inMonth = episodes.filter((episode) => episode.airDate.getMonth() === month.getMonth());
|
||||||
|
|
||||||
|
const previous = new Date(month.getFullYear(), month.getMonth() - 1, 1);
|
||||||
|
const next = new Date(month.getFullYear(), month.getMonth() + 1, 1);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<AppShell user={user} instanceName={settings.instanceName}>
|
||||||
|
<header className="mb-5 flex flex-wrap items-end justify-between gap-3">
|
||||||
|
<div>
|
||||||
|
<h1 className="text-2xl font-semibold tracking-tight sm:text-3xl">Kalender</h1>
|
||||||
|
<p className="mt-1 text-sm text-[var(--fl-muted)]">
|
||||||
|
Ausstrahlungstermine der Serien in deiner Bibliothek.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<nav className="flex items-center gap-2" aria-label="Monat wechseln">
|
||||||
|
<Link
|
||||||
|
href={`/kalender?monat=${monthParam(previous)}`}
|
||||||
|
className="fl-btn fl-btn-ghost px-3 py-1.5 text-sm"
|
||||||
|
aria-label={`Zum ${previous.toLocaleDateString("de-DE", { month: "long", year: "numeric" })}`}
|
||||||
|
>
|
||||||
|
←
|
||||||
|
</Link>
|
||||||
|
<span className="min-w-40 text-center font-medium">
|
||||||
|
{month.toLocaleDateString("de-DE", { month: "long", year: "numeric" })}
|
||||||
|
</span>
|
||||||
|
<Link
|
||||||
|
href={`/kalender?monat=${monthParam(next)}`}
|
||||||
|
className="fl-btn fl-btn-ghost px-3 py-1.5 text-sm"
|
||||||
|
aria-label={`Zum ${next.toLocaleDateString("de-DE", { month: "long", year: "numeric" })}`}
|
||||||
|
>
|
||||||
|
→
|
||||||
|
</Link>
|
||||||
|
<Link href="/kalender" className="ml-1 text-sm text-[var(--fl-faint)] hover:text-[var(--fl-text)]">
|
||||||
|
Heute
|
||||||
|
</Link>
|
||||||
|
</nav>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<div className="fl-card overflow-x-auto p-3 sm:p-4">
|
||||||
|
<div className="min-w-[44rem]">
|
||||||
|
<CalendarMonth month={month} episodes={episodes} />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<section className="mt-6" aria-labelledby="liste">
|
||||||
|
<h2 id="liste" className="mb-3 text-lg font-semibold">
|
||||||
|
Termine im {month.toLocaleDateString("de-DE", { month: "long" })}
|
||||||
|
</h2>
|
||||||
|
|
||||||
|
{inMonth.length === 0 ? (
|
||||||
|
<div className="fl-card p-6 text-center text-sm text-[var(--fl-muted)]">
|
||||||
|
In diesem Monat läuft nichts aus deiner Bibliothek.
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<ol className="fl-card divide-y divide-[var(--fl-border)]">
|
||||||
|
{inMonth.map((episode) => (
|
||||||
|
<li key={episode.episodeId} className="flex flex-wrap items-center gap-x-3 gap-y-1 px-4 py-3">
|
||||||
|
<span className="w-52 shrink-0 text-sm text-[var(--fl-faint)]">
|
||||||
|
{formatDateLong(episode.airDate)}
|
||||||
|
</span>
|
||||||
|
<Link
|
||||||
|
href={`/titel/${episode.titleId}`}
|
||||||
|
className="min-w-0 flex-1 text-sm hover:text-[var(--fl-accent)]"
|
||||||
|
>
|
||||||
|
<span className="font-medium">{episode.title}</span>
|
||||||
|
<span className="ml-2 font-mono text-xs text-[var(--fl-faint)]">
|
||||||
|
{episodeCode(episode.seasonNumber, episode.episodeNumber)}
|
||||||
|
</span>
|
||||||
|
<span className="ml-2 text-[var(--fl-muted)]">{episode.name}</span>
|
||||||
|
</Link>
|
||||||
|
{episode.runtime && (
|
||||||
|
<span className="shrink-0 text-xs text-[var(--fl-faint)]">{episode.runtime} min</span>
|
||||||
|
)}
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ol>
|
||||||
|
)}
|
||||||
|
</section>
|
||||||
|
</AppShell>
|
||||||
|
);
|
||||||
|
}
|
||||||
+201
-55
@@ -2,82 +2,228 @@ import Link from "next/link";
|
|||||||
import { requireUser } from "@/lib/auth";
|
import { requireUser } from "@/lib/auth";
|
||||||
import { getSettings } from "@/lib/settings";
|
import { getSettings } from "@/lib/settings";
|
||||||
import { env } from "@/lib/env";
|
import { env } from "@/lib/env";
|
||||||
|
import {
|
||||||
|
getContinueWatching,
|
||||||
|
getNewlyAvailable,
|
||||||
|
getUpcomingEpisodes,
|
||||||
|
} from "@/lib/stats";
|
||||||
|
import { prisma } from "@/lib/db";
|
||||||
|
import { episodeCode, formatDate, formatRelative, isUpcoming } from "@/lib/labels";
|
||||||
import { AppShell } from "@/components/AppShell";
|
import { AppShell } from "@/components/AppShell";
|
||||||
import { FlimmerMark } from "@/components/brand/FlimmerLogo";
|
import { Poster } from "@/components/Poster";
|
||||||
|
import { ProgressBar } from "@/components/ProgressBar";
|
||||||
|
import { QuickWatch } from "@/components/library/QuickWatch";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Übersichtsseite.
|
* Übersicht: der Einstieg für „was schaue ich als Nächstes".
|
||||||
*
|
*
|
||||||
* In dieser Etappe steht hier die Begrüßung und der Hinweis auf die nächsten
|
* Drei Fragen, drei Bereiche — weiterschauen, was demnächst kommt, was auf der
|
||||||
* Schritte; ab Etappe 5 ziehen „Weiterschauen", Kalender und Neuzugänge ein.
|
* Watchlist verfügbar geworden ist.
|
||||||
*/
|
*/
|
||||||
export default async function DashboardPage() {
|
export default async function DashboardPage() {
|
||||||
const user = await requireUser();
|
const user = await requireUser();
|
||||||
const settings = await getSettings();
|
const settings = await getSettings();
|
||||||
|
|
||||||
|
const now = new Date();
|
||||||
|
const inFourWeeks = new Date(now.getTime() + 28 * 86_400_000);
|
||||||
|
|
||||||
|
const [continueItems, upcoming, available, libraryCount] = await Promise.all([
|
||||||
|
getContinueWatching(user.id, 8),
|
||||||
|
getUpcomingEpisodes(user.id, now, inFourWeeks),
|
||||||
|
getNewlyAvailable(user.id, user.region),
|
||||||
|
prisma.libraryEntry.count({ where: { userId: user.id, deletedAt: null } }),
|
||||||
|
]);
|
||||||
|
|
||||||
|
if (libraryCount === 0) {
|
||||||
|
return (
|
||||||
|
<AppShell user={user} instanceName={settings.instanceName}>
|
||||||
|
<EmptyStart tmdbReady={env.tmdb.isConfigured} name={user.name} />
|
||||||
|
</AppShell>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<AppShell user={user} instanceName={settings.instanceName}>
|
<AppShell user={user} instanceName={settings.instanceName}>
|
||||||
<section className="fl-card relative overflow-hidden p-6 sm:p-10">
|
<h1 className="sr-only">Übersicht</h1>
|
||||||
<div
|
|
||||||
aria-hidden
|
|
||||||
className="pointer-events-none absolute -right-24 -top-32 h-72 w-72 rounded-full opacity-30 blur-3xl"
|
|
||||||
style={{ backgroundImage: "var(--fl-gradient)" }}
|
|
||||||
/>
|
|
||||||
<div className="relative">
|
|
||||||
<FlimmerMark className="h-12 w-12" />
|
|
||||||
<h1 className="mt-4 text-3xl font-semibold tracking-tight sm:text-4xl">
|
|
||||||
Hallo {user.name.split(" ")[0]}.
|
|
||||||
</h1>
|
|
||||||
<p className="mt-2 max-w-xl text-[var(--fl-muted)]">
|
|
||||||
Schön, dass du da bist. Sobald du deinen ersten Titel hinzufügst, findest du hier
|
|
||||||
deine laufenden Serien, die nächsten Episoden und was auf deiner Watchlist gerade
|
|
||||||
verfügbar geworden ist.
|
|
||||||
</p>
|
|
||||||
|
|
||||||
<div className="mt-6 flex flex-wrap gap-3">
|
<section aria-labelledby="weiterschauen">
|
||||||
<Link href="/suche" className="fl-btn fl-btn-primary">
|
<div className="mb-3 flex items-baseline justify-between gap-3">
|
||||||
Titel suchen und hinzufügen
|
<h2 id="weiterschauen" className="text-lg font-semibold">
|
||||||
</Link>
|
Weiterschauen
|
||||||
<Link href="/bibliothek" className="fl-btn fl-btn-ghost">
|
</h2>
|
||||||
Zur Bibliothek
|
<Link href="/bibliothek?status=WATCHING" className="text-sm text-[var(--fl-faint)] hover:text-[var(--fl-text)]">
|
||||||
|
Alle laufenden
|
||||||
|
</Link>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{continueItems.length === 0 ? (
|
||||||
|
<div className="fl-card p-6 text-center text-sm text-[var(--fl-muted)]">
|
||||||
|
Gerade läuft nichts. Setz eine Serie auf „Schaue gerade", dann steht sie hier.
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<ul className="grid grid-cols-1 gap-3 sm:grid-cols-2 xl:grid-cols-3">
|
||||||
|
{continueItems.map((item) => (
|
||||||
|
<li key={item.entryId} className="fl-card flex gap-3 p-3">
|
||||||
|
<Link href={`/titel/${item.titleId}`} className="w-16 shrink-0 sm:w-20">
|
||||||
|
<Poster path={item.posterPath} alt={item.title} size="w185" />
|
||||||
|
</Link>
|
||||||
|
|
||||||
|
<div className="flex min-w-0 flex-1 flex-col">
|
||||||
|
<Link href={`/titel/${item.titleId}`} className="truncate font-medium hover:text-[var(--fl-accent)]">
|
||||||
|
{item.title}
|
||||||
|
</Link>
|
||||||
|
|
||||||
|
{item.next && (
|
||||||
|
<p className="mt-0.5 truncate text-sm">
|
||||||
|
<span className="fl-gradient-text font-mono font-semibold">
|
||||||
|
{episodeCode(item.next.seasonNumber, item.next.episodeNumber)}
|
||||||
|
</span>{" "}
|
||||||
|
<span className="text-[var(--fl-muted)]">{item.next.name}</span>
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<p className="mt-0.5 text-xs text-[var(--fl-faint)]">
|
||||||
|
{item.watched} von {item.total} Episoden
|
||||||
|
{item.lastWatchedAt ? ` · zuletzt ${formatRelative(item.lastWatchedAt)}` : ""}
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<div className="mt-2">
|
||||||
|
<ProgressBar
|
||||||
|
percent={item.percent}
|
||||||
|
label={`${item.watched} von ${item.total} Episoden gesehen`}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="mt-2.5">
|
||||||
|
{item.next && isUpcoming(item.next.airDate) ? (
|
||||||
|
<p className="text-xs text-[var(--fl-faint)]">
|
||||||
|
Nächste Episode erst am {formatDate(item.next.airDate)}
|
||||||
|
</p>
|
||||||
|
) : (
|
||||||
|
<QuickWatch entryId={item.entryId} />
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
)}
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<div className="mt-8 grid gap-6 lg:grid-cols-2">
|
||||||
|
<section aria-labelledby="demnaechst">
|
||||||
|
<div className="mb-3 flex items-baseline justify-between gap-3">
|
||||||
|
<h2 id="demnaechst" className="text-lg font-semibold">
|
||||||
|
Demnächst
|
||||||
|
</h2>
|
||||||
|
<Link href="/kalender" className="text-sm text-[var(--fl-faint)] hover:text-[var(--fl-text)]">
|
||||||
|
Zum Kalender
|
||||||
</Link>
|
</Link>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{!env.tmdb.isConfigured && (
|
<div className="fl-card p-4">
|
||||||
<p className="mt-6 max-w-xl rounded-xl border border-[color-mix(in_oklab,var(--fl-warning)_40%,transparent)] bg-[color-mix(in_oklab,var(--fl-warning)_10%,transparent)] px-3 py-2 text-sm text-[var(--fl-warning)]">
|
{upcoming.length === 0 ? (
|
||||||
Es ist noch kein TMDB-Schlüssel hinterlegt. Ohne ihn findet die Suche keine
|
<p className="text-sm text-[var(--fl-muted)]">
|
||||||
Metadaten — trage <code>TMDB_API_KEY</code> in der <code>.env</code> ein und starte
|
In den nächsten vier Wochen ist keine Episode deiner Serien angekündigt.
|
||||||
die Instanz neu.
|
</p>
|
||||||
</p>
|
) : (
|
||||||
)}
|
<ol className="space-y-2.5">
|
||||||
</div>
|
{upcoming.slice(0, 6).map((episode) => (
|
||||||
</section>
|
<li key={episode.episodeId} className="flex items-center gap-3">
|
||||||
|
<span className="w-20 shrink-0 text-xs text-[var(--fl-faint)]">
|
||||||
|
{formatDate(episode.airDate)}
|
||||||
|
</span>
|
||||||
|
<Link
|
||||||
|
href={`/titel/${episode.titleId}`}
|
||||||
|
className="min-w-0 flex-1 truncate text-sm hover:text-[var(--fl-accent)]"
|
||||||
|
>
|
||||||
|
<span className="font-medium">{episode.title}</span>
|
||||||
|
<span className="ml-1.5 font-mono text-xs text-[var(--fl-faint)]">
|
||||||
|
{episodeCode(episode.seasonNumber, episode.episodeNumber)}
|
||||||
|
</span>
|
||||||
|
</Link>
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ol>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
<div className="mt-6 grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
|
<section aria-labelledby="verfuegbar">
|
||||||
<PlaceholderCard
|
<h2 id="verfuegbar" className="mb-3 text-lg font-semibold">
|
||||||
title="Weiterschauen"
|
Neu verfügbar
|
||||||
text="Deine laufenden Serien mit der jeweils nächsten Episode."
|
</h2>
|
||||||
/>
|
|
||||||
<PlaceholderCard
|
<div className="fl-card p-4">
|
||||||
title="Demnächst"
|
{available.length === 0 ? (
|
||||||
text="Kalender der Episoden, die in den nächsten Wochen ausgestrahlt werden."
|
<p className="text-sm text-[var(--fl-muted)]">
|
||||||
/>
|
Auf deiner Watchlist ist zuletzt nichts neu dazugekommen. Sobald ein Titel auf
|
||||||
<PlaceholderCard
|
einem Dienst in {user.region} auftaucht, steht er hier.
|
||||||
title="Neu verfügbar"
|
</p>
|
||||||
text="Watchlist-Titel, die auf einem deiner Dienste aufgetaucht sind."
|
) : (
|
||||||
/>
|
<ul className="space-y-3">
|
||||||
|
{available.slice(0, 5).map((item) => (
|
||||||
|
<li key={item.titleId} className="flex items-center gap-3">
|
||||||
|
<Link href={`/titel/${item.titleId}`} className="w-10 shrink-0">
|
||||||
|
<Poster path={item.posterPath} alt={item.title} size="w154" />
|
||||||
|
</Link>
|
||||||
|
<div className="min-w-0 flex-1">
|
||||||
|
<Link
|
||||||
|
href={`/titel/${item.titleId}`}
|
||||||
|
className="block truncate text-sm font-medium hover:text-[var(--fl-accent)]"
|
||||||
|
>
|
||||||
|
{item.title}
|
||||||
|
</Link>
|
||||||
|
<p className="truncate text-xs text-[var(--fl-faint)]">
|
||||||
|
{item.providers.map((provider) => provider.name).join(", ")} ·{" "}
|
||||||
|
{formatRelative(item.since)}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
</div>
|
</div>
|
||||||
</AppShell>
|
</AppShell>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function PlaceholderCard({ title, text }: { title: string; text: string }) {
|
function EmptyStart({ name, tmdbReady }: { name: string; tmdbReady: boolean }) {
|
||||||
return (
|
return (
|
||||||
<div className="fl-card p-5">
|
<section className="fl-card relative overflow-hidden p-6 sm:p-10">
|
||||||
<h2 className="text-sm font-semibold tracking-wide text-[var(--fl-muted)] uppercase">
|
<div
|
||||||
{title}
|
aria-hidden
|
||||||
</h2>
|
className="pointer-events-none absolute -right-24 -top-32 h-72 w-72 rounded-full opacity-30 blur-3xl"
|
||||||
<p className="mt-2 text-sm text-[var(--fl-faint)]">{text}</p>
|
style={{ backgroundImage: "var(--fl-gradient)" }}
|
||||||
</div>
|
/>
|
||||||
|
<div className="relative">
|
||||||
|
<h1 className="text-3xl font-semibold tracking-tight sm:text-4xl">
|
||||||
|
Hallo {name.split(" ")[0]}.
|
||||||
|
</h1>
|
||||||
|
<p className="mt-2 max-w-xl text-[var(--fl-muted)]">
|
||||||
|
Deine Bibliothek ist noch leer. Such dir eine Serie oder einen Film — danach findest du
|
||||||
|
hier, was als Nächstes dran ist, welche Episoden demnächst kommen und was auf deiner
|
||||||
|
Watchlist verfügbar geworden ist.
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<div className="mt-6 flex flex-wrap gap-3">
|
||||||
|
<Link href="/suche" className="fl-btn fl-btn-primary">
|
||||||
|
Titel suchen
|
||||||
|
</Link>
|
||||||
|
<Link href="/titel/neu" className="fl-btn fl-btn-ghost">
|
||||||
|
Titel selbst anlegen
|
||||||
|
</Link>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{!tmdbReady && (
|
||||||
|
<p className="mt-6 max-w-xl rounded-xl border border-[color-mix(in_oklab,var(--fl-warning)_40%,transparent)] bg-[color-mix(in_oklab,var(--fl-warning)_10%,transparent)] px-3 py-2 text-sm text-[var(--fl-warning)]">
|
||||||
|
Es ist noch kein TMDB-Schlüssel hinterlegt. Ohne ihn findet die Suche keine Metadaten —
|
||||||
|
trage <code>TMDB_API_KEY</code> in der <code>.env</code> ein und starte die Instanz neu.
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,267 @@
|
|||||||
|
import Link from "next/link";
|
||||||
|
import type { Metadata } from "next";
|
||||||
|
import { requireUser } from "@/lib/auth";
|
||||||
|
import { getSettings } from "@/lib/settings";
|
||||||
|
import {
|
||||||
|
getActiveYears,
|
||||||
|
getGenreDistribution,
|
||||||
|
getMonthlyActivity,
|
||||||
|
getMostWatched,
|
||||||
|
getProviderDistribution,
|
||||||
|
getTopRated,
|
||||||
|
getTotals,
|
||||||
|
getYearReview,
|
||||||
|
} from "@/lib/stats";
|
||||||
|
import { formatMinutes } from "@/lib/labels";
|
||||||
|
import { AppShell } from "@/components/AppShell";
|
||||||
|
import { Poster } from "@/components/Poster";
|
||||||
|
import { DistributionBars, MonthlyChart } from "@/components/stats/Charts";
|
||||||
|
|
||||||
|
export const metadata: Metadata = { title: "Statistik" };
|
||||||
|
|
||||||
|
export default async function StatsPage({
|
||||||
|
searchParams,
|
||||||
|
}: {
|
||||||
|
searchParams: Promise<{ jahr?: string }>;
|
||||||
|
}) {
|
||||||
|
const user = await requireUser("/statistik");
|
||||||
|
const settings = await getSettings();
|
||||||
|
const params = await searchParams;
|
||||||
|
|
||||||
|
const years = await getActiveYears(user.id);
|
||||||
|
const requested = Number.parseInt(params.jahr ?? "", 10);
|
||||||
|
const year = years.includes(requested) ? requested : (years[0] ?? new Date().getFullYear());
|
||||||
|
|
||||||
|
const [totals, monthly, providers, genres, topRated, mostWatched, review] = await Promise.all([
|
||||||
|
getTotals(user.id),
|
||||||
|
getMonthlyActivity(user.id, 12),
|
||||||
|
getProviderDistribution(user.id),
|
||||||
|
getGenreDistribution(user.id),
|
||||||
|
getTopRated(user.id, 5),
|
||||||
|
getMostWatched(user.id, 5),
|
||||||
|
getYearReview(user.id, year),
|
||||||
|
]);
|
||||||
|
|
||||||
|
if (totals.minutes === 0 && totals.episodes === 0 && totals.movies === 0) {
|
||||||
|
return (
|
||||||
|
<AppShell user={user} instanceName={settings.instanceName}>
|
||||||
|
<header className="mb-5">
|
||||||
|
<h1 className="text-2xl font-semibold tracking-tight sm:text-3xl">Statistik</h1>
|
||||||
|
</header>
|
||||||
|
<div className="fl-card p-8 text-center">
|
||||||
|
<p className="mx-auto max-w-md text-[var(--fl-muted)]">
|
||||||
|
Noch keine Sichtungen. Sobald du die erste Episode abhakst, entstehen hier
|
||||||
|
Schauzeit, Verteilungen und der Jahresrückblick.
|
||||||
|
</p>
|
||||||
|
<Link href="/bibliothek" className="fl-btn fl-btn-primary mt-4">
|
||||||
|
Zur Bibliothek
|
||||||
|
</Link>
|
||||||
|
</div>
|
||||||
|
</AppShell>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const days = totals.minutes / (60 * 24);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<AppShell user={user} instanceName={settings.instanceName}>
|
||||||
|
<header className="mb-6">
|
||||||
|
<h1 className="text-2xl font-semibold tracking-tight sm:text-3xl">Statistik</h1>
|
||||||
|
<p className="mt-1 text-sm text-[var(--fl-muted)]">
|
||||||
|
Alles gerechnet aus deinen Sichtungen — Rewatches zählen mit.
|
||||||
|
</p>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<section className="fl-card mb-6 p-5 sm:p-7" aria-label="Gesamtschauzeit">
|
||||||
|
<p className="text-sm font-medium text-[var(--fl-muted)]">Gesamte Schauzeit</p>
|
||||||
|
<p className="fl-gradient-text mt-1 text-5xl font-semibold tabular-nums sm:text-6xl">
|
||||||
|
{Math.round(totals.minutes / 60).toLocaleString("de-DE")} h
|
||||||
|
</p>
|
||||||
|
<p className="mt-1 text-sm text-[var(--fl-muted)]">
|
||||||
|
{formatMinutes(totals.minutes)} · das sind {days.toFixed(1).replace(".", ",")} Tage am Stück
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<dl className="mt-5 grid grid-cols-2 gap-4 sm:grid-cols-4">
|
||||||
|
<Stat label="Episoden" value={totals.episodes.toLocaleString("de-DE")} />
|
||||||
|
<Stat label="Filme" value={totals.movies.toLocaleString("de-DE")} />
|
||||||
|
<Stat label="Abgeschlossen" value={totals.titlesCompleted.toLocaleString("de-DE")} />
|
||||||
|
<Stat
|
||||||
|
label="In der Bibliothek"
|
||||||
|
value={`${totals.seriesCount} Serien · ${totals.movieCount} Filme`}
|
||||||
|
/>
|
||||||
|
</dl>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section className="fl-card mb-6 p-5" aria-labelledby="verlauf">
|
||||||
|
<h2 id="verlauf" className="mb-1 text-lg font-semibold">
|
||||||
|
Die letzten zwölf Monate
|
||||||
|
</h2>
|
||||||
|
<p className="mb-4 text-sm text-[var(--fl-muted)]">
|
||||||
|
Abgehakte Episoden und Filme je Monat.
|
||||||
|
</p>
|
||||||
|
<MonthlyChart points={monthly.map(({ label, episodes, movies, minutes }) => ({ label, episodes, movies, minutes }))} />
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<div className="mb-6 grid gap-6 lg:grid-cols-2">
|
||||||
|
<section className="fl-card p-5" aria-labelledby="dienste">
|
||||||
|
<h2 id="dienste" className="mb-1 text-lg font-semibold">
|
||||||
|
Nach Streamingdienst
|
||||||
|
</h2>
|
||||||
|
<p className="mb-4 text-sm text-[var(--fl-muted)]">
|
||||||
|
Wo du tatsächlich geschaut hast — aus dem Feld „wo schaue ich das".
|
||||||
|
</p>
|
||||||
|
<DistributionBars
|
||||||
|
rows={providers.slice(0, 8)}
|
||||||
|
emptyText="Noch keine Sichtung einem Dienst zugeordnet."
|
||||||
|
useBrandColors
|
||||||
|
/>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section className="fl-card p-5" aria-labelledby="genres">
|
||||||
|
<h2 id="genres" className="mb-1 text-lg font-semibold">
|
||||||
|
Nach Genre
|
||||||
|
</h2>
|
||||||
|
<p className="mb-4 text-sm text-[var(--fl-muted)]">
|
||||||
|
Titel mit mehreren Genres zählen in jedem mit.
|
||||||
|
</p>
|
||||||
|
<DistributionBars rows={genres.slice(0, 8)} emptyText="Noch keine Genres erfasst." />
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<section className="fl-card mb-6 p-5" aria-labelledby="rueckblick">
|
||||||
|
<div className="mb-4 flex flex-wrap items-center justify-between gap-3">
|
||||||
|
<h2 id="rueckblick" className="text-lg font-semibold">
|
||||||
|
{review.year} in Zahlen
|
||||||
|
</h2>
|
||||||
|
{years.length > 1 && (
|
||||||
|
<div className="flex flex-wrap gap-1.5" role="group" aria-label="Jahr wählen">
|
||||||
|
{years.slice(0, 6).map((entry) => (
|
||||||
|
<Link
|
||||||
|
key={entry}
|
||||||
|
href={`/statistik?jahr=${entry}`}
|
||||||
|
aria-current={entry === review.year ? "true" : undefined}
|
||||||
|
className="rounded-full border px-3 py-1 text-sm font-medium transition-colors"
|
||||||
|
style={
|
||||||
|
entry === review.year
|
||||||
|
? {
|
||||||
|
backgroundImage: "var(--fl-gradient)",
|
||||||
|
color: "var(--fl-on-accent)",
|
||||||
|
borderColor: "transparent",
|
||||||
|
}
|
||||||
|
: { borderColor: "var(--fl-border)", color: "var(--fl-muted)" }
|
||||||
|
}
|
||||||
|
>
|
||||||
|
{entry}
|
||||||
|
</Link>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<dl className="grid grid-cols-2 gap-4 sm:grid-cols-3 lg:grid-cols-5">
|
||||||
|
<Stat label="Schauzeit" value={formatMinutes(review.minutes)} />
|
||||||
|
<Stat label="Episoden" value={review.episodes.toLocaleString("de-DE")} />
|
||||||
|
<Stat label="Filme" value={review.movies.toLocaleString("de-DE")} />
|
||||||
|
<Stat label="Neu angefangen" value={review.titlesStarted.toLocaleString("de-DE")} />
|
||||||
|
<Stat label="Abgeschlossen" value={review.titlesCompleted.toLocaleString("de-DE")} />
|
||||||
|
</dl>
|
||||||
|
|
||||||
|
<div className="mt-5 grid gap-4 sm:grid-cols-2">
|
||||||
|
{review.busiestMonth && (
|
||||||
|
<p className="rounded-xl border border-[var(--fl-border)] p-3 text-sm">
|
||||||
|
<span className="text-[var(--fl-faint)]">Stärkster Monat: </span>
|
||||||
|
<span className="font-medium">{review.busiestMonth.label}</span>
|
||||||
|
<span className="text-[var(--fl-muted)]">
|
||||||
|
{" "}
|
||||||
|
mit {formatMinutes(review.busiestMonth.minutes)}
|
||||||
|
</span>
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
{review.topTitle && (
|
||||||
|
<p className="rounded-xl border border-[var(--fl-border)] p-3 text-sm">
|
||||||
|
<span className="text-[var(--fl-faint)]">Die meiste Zeit ging an: </span>
|
||||||
|
<Link href={`/titel/${review.topTitle.titleId}`} className="font-medium hover:text-[var(--fl-accent)]">
|
||||||
|
{review.topTitle.title}
|
||||||
|
</Link>
|
||||||
|
<span className="text-[var(--fl-muted)]"> ({formatMinutes(review.topTitle.minutes)})</span>
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<div className="grid gap-6 lg:grid-cols-2">
|
||||||
|
<TitleList
|
||||||
|
id="meistzeit"
|
||||||
|
heading="Wo die meiste Zeit hinging"
|
||||||
|
items={mostWatched}
|
||||||
|
renderMeta={(item) => formatMinutes(item.minutes)}
|
||||||
|
emptyText="Noch nichts gesehen."
|
||||||
|
/>
|
||||||
|
<TitleList
|
||||||
|
id="bestbewertet"
|
||||||
|
heading="Deine besten Bewertungen"
|
||||||
|
items={topRated}
|
||||||
|
renderMeta={(item) => (item.rating ? `${item.rating}/10` : "—")}
|
||||||
|
emptyText="Noch nichts bewertet."
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</AppShell>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function Stat({ label, value }: { label: string; value: string }) {
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
<dt className="text-xs uppercase tracking-wide text-[var(--fl-faint)]">{label}</dt>
|
||||||
|
<dd className="mt-0.5 text-lg font-semibold tabular-nums">{value}</dd>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function TitleList({
|
||||||
|
id,
|
||||||
|
heading,
|
||||||
|
items,
|
||||||
|
renderMeta,
|
||||||
|
emptyText,
|
||||||
|
}: {
|
||||||
|
id: string;
|
||||||
|
heading: string;
|
||||||
|
items: { titleId: string; title: string; posterPath: string | null; rating: number | null; minutes: number; type: string }[];
|
||||||
|
renderMeta: (item: { rating: number | null; minutes: number }) => string;
|
||||||
|
emptyText: string;
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<section className="fl-card p-5" aria-labelledby={id}>
|
||||||
|
<h2 id={id} className="mb-4 text-lg font-semibold">
|
||||||
|
{heading}
|
||||||
|
</h2>
|
||||||
|
|
||||||
|
{items.length === 0 ? (
|
||||||
|
<p className="text-sm text-[var(--fl-faint)]">{emptyText}</p>
|
||||||
|
) : (
|
||||||
|
<ol className="space-y-3">
|
||||||
|
{items.map((item, index) => (
|
||||||
|
<li key={item.titleId} className="flex items-center gap-3">
|
||||||
|
<span className="w-4 shrink-0 text-right font-mono text-sm text-[var(--fl-faint)]">
|
||||||
|
{index + 1}
|
||||||
|
</span>
|
||||||
|
<Link href={`/titel/${item.titleId}`} className="w-10 shrink-0">
|
||||||
|
<Poster path={item.posterPath} alt={item.title} size="w154" />
|
||||||
|
</Link>
|
||||||
|
<Link
|
||||||
|
href={`/titel/${item.titleId}`}
|
||||||
|
className="min-w-0 flex-1 truncate text-sm font-medium hover:text-[var(--fl-accent)]"
|
||||||
|
>
|
||||||
|
{item.title}
|
||||||
|
</Link>
|
||||||
|
<span className="shrink-0 text-sm tabular-nums text-[var(--fl-muted)]">
|
||||||
|
{renderMeta(item)}
|
||||||
|
</span>
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ol>
|
||||||
|
)}
|
||||||
|
</section>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,138 @@
|
|||||||
|
import Link from "next/link";
|
||||||
|
import { clsx } from "clsx";
|
||||||
|
import { episodeCode } from "@/lib/labels";
|
||||||
|
import type { UpcomingEpisode } from "@/lib/stats";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Monatsraster mit den Ausstrahlungsterminen.
|
||||||
|
*
|
||||||
|
* Bewusst als Tabelle ausgezeichnet: ein Kalender *ist* eine Tabelle, und mit
|
||||||
|
* Screenreader wird daraus dann „Woche 3, Donnerstag, 14." statt einer
|
||||||
|
* ununterscheidbaren Kachelwüste.
|
||||||
|
*/
|
||||||
|
|
||||||
|
const WEEKDAYS = ["Mo", "Di", "Mi", "Do", "Fr", "Sa", "So"];
|
||||||
|
|
||||||
|
function startOfGrid(month: Date): Date {
|
||||||
|
const first = new Date(month.getFullYear(), month.getMonth(), 1);
|
||||||
|
// Montag als Wochenanfang: Sonntag (0) wird zu 6.
|
||||||
|
const weekday = (first.getDay() + 6) % 7;
|
||||||
|
return new Date(first.getFullYear(), first.getMonth(), 1 - weekday);
|
||||||
|
}
|
||||||
|
|
||||||
|
function isSameDay(a: Date, b: Date): boolean {
|
||||||
|
return (
|
||||||
|
a.getFullYear() === b.getFullYear() &&
|
||||||
|
a.getMonth() === b.getMonth() &&
|
||||||
|
a.getDate() === b.getDate()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function CalendarMonth({
|
||||||
|
month,
|
||||||
|
episodes,
|
||||||
|
}: {
|
||||||
|
month: Date;
|
||||||
|
episodes: UpcomingEpisode[];
|
||||||
|
}) {
|
||||||
|
const today = new Date();
|
||||||
|
const start = startOfGrid(month);
|
||||||
|
|
||||||
|
// Sechs Wochen zeigen immer den ganzen Monat, egal auf welchen Tag er fällt.
|
||||||
|
const days = Array.from({ length: 42 }, (_, index) => {
|
||||||
|
const date = new Date(start);
|
||||||
|
date.setDate(start.getDate() + index);
|
||||||
|
return date;
|
||||||
|
});
|
||||||
|
|
||||||
|
const byDay = new Map<string, UpcomingEpisode[]>();
|
||||||
|
for (const episode of episodes) {
|
||||||
|
const key = episode.airDate.toDateString();
|
||||||
|
const list = byDay.get(key);
|
||||||
|
if (list) list.push(episode);
|
||||||
|
else byDay.set(key, [episode]);
|
||||||
|
}
|
||||||
|
|
||||||
|
const weeks = Array.from({ length: 6 }, (_, index) => days.slice(index * 7, index * 7 + 7));
|
||||||
|
|
||||||
|
return (
|
||||||
|
<table className="w-full table-fixed border-collapse">
|
||||||
|
<caption className="sr-only">
|
||||||
|
Ausstrahlungstermine im {month.toLocaleDateString("de-DE", { month: "long", year: "numeric" })}
|
||||||
|
</caption>
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
{WEEKDAYS.map((day) => (
|
||||||
|
<th
|
||||||
|
key={day}
|
||||||
|
scope="col"
|
||||||
|
className="pb-2 text-xs font-semibold uppercase tracking-wide text-[var(--fl-faint)]"
|
||||||
|
>
|
||||||
|
{day}
|
||||||
|
</th>
|
||||||
|
))}
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{weeks.map((week, weekIndex) => (
|
||||||
|
<tr key={weekIndex}>
|
||||||
|
{week.map((date) => {
|
||||||
|
const inMonth = date.getMonth() === month.getMonth();
|
||||||
|
const isToday = isSameDay(date, today);
|
||||||
|
const list = byDay.get(date.toDateString()) ?? [];
|
||||||
|
|
||||||
|
return (
|
||||||
|
<td
|
||||||
|
key={date.toISOString()}
|
||||||
|
className={clsx(
|
||||||
|
"h-24 border border-[var(--fl-border)] p-1 align-top sm:h-28",
|
||||||
|
!inMonth && "opacity-40",
|
||||||
|
)}
|
||||||
|
style={
|
||||||
|
list.length > 0
|
||||||
|
? { backgroundColor: "color-mix(in oklab, var(--fl-magenta) 7%, transparent)" }
|
||||||
|
: undefined
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<span
|
||||||
|
className={clsx(
|
||||||
|
"mb-1 inline-flex h-5 min-w-5 items-center justify-center rounded-full px-1 text-xs tabular-nums",
|
||||||
|
isToday
|
||||||
|
? "font-semibold text-[var(--fl-on-accent)]"
|
||||||
|
: "text-[var(--fl-faint)]",
|
||||||
|
)}
|
||||||
|
style={isToday ? { backgroundImage: "var(--fl-gradient)" } : undefined}
|
||||||
|
>
|
||||||
|
{date.getDate()}
|
||||||
|
</span>
|
||||||
|
|
||||||
|
<ul className="space-y-0.5">
|
||||||
|
{list.slice(0, 3).map((episode) => (
|
||||||
|
<li key={episode.episodeId}>
|
||||||
|
<Link
|
||||||
|
href={`/titel/${episode.titleId}`}
|
||||||
|
title={`${episode.title} — ${episodeCode(episode.seasonNumber, episode.episodeNumber)} ${episode.name}`}
|
||||||
|
className="block truncate rounded px-1 py-0.5 text-[0.7rem] leading-tight text-[var(--fl-text)] transition-colors hover:bg-[var(--fl-surface-2)]"
|
||||||
|
>
|
||||||
|
<span className="font-mono text-[var(--fl-accent)]">
|
||||||
|
{episodeCode(episode.seasonNumber, episode.episodeNumber)}
|
||||||
|
</span>{" "}
|
||||||
|
{episode.title}
|
||||||
|
</Link>
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
{list.length > 3 && (
|
||||||
|
<li className="px-1 text-[0.7rem] text-[var(--fl-faint)]">
|
||||||
|
+ {list.length - 3} weitere
|
||||||
|
</li>
|
||||||
|
)}
|
||||||
|
</ul>
|
||||||
|
</td>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</tr>
|
||||||
|
))}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useTransition } from "react";
|
||||||
|
import { useRouter } from "next/navigation";
|
||||||
|
import { undoAction, watchNextAction } from "@/app/actions/library";
|
||||||
|
import { useToasts } from "@/components/Toasts";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* „+1 Episode" für die Übersicht — derselbe Griff wie auf der Detailseite,
|
||||||
|
* nur ohne Kontext drumherum.
|
||||||
|
*/
|
||||||
|
export function QuickWatch({ entryId }: { entryId: string }) {
|
||||||
|
const router = useRouter();
|
||||||
|
const { report } = useToasts();
|
||||||
|
const [pending, startTransition] = useTransition();
|
||||||
|
|
||||||
|
async function undo(watchIds: string[]) {
|
||||||
|
await undoAction(entryId, watchIds);
|
||||||
|
router.refresh();
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
disabled={pending}
|
||||||
|
onClick={() =>
|
||||||
|
startTransition(async () => {
|
||||||
|
const result = await watchNextAction(entryId);
|
||||||
|
report(result, (ids) => undo(ids));
|
||||||
|
router.refresh();
|
||||||
|
})
|
||||||
|
}
|
||||||
|
className="fl-btn fl-btn-ghost px-3 py-1.5 text-sm"
|
||||||
|
>
|
||||||
|
+1 Episode
|
||||||
|
</button>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,373 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useState } from "react";
|
||||||
|
import { clsx } from "clsx";
|
||||||
|
import { formatMinutes } from "@/lib/labels";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Diagramme der Statistikseite.
|
||||||
|
*
|
||||||
|
* Handgeschriebenes SVG statt einer Chart-Bibliothek: die Diagramme sind
|
||||||
|
* schlicht, sollen sich an die Design-Tokens halten und in beiden Farbschemata
|
||||||
|
* funktionieren — dafür lohnt keine Abhängigkeit mit eigenem Versionsrhythmus.
|
||||||
|
*
|
||||||
|
* Farbwahl: Die beiden Serienfarben sind abgedunkelte Varianten der
|
||||||
|
* Signaturfarben. Sie erfüllen in **beiden** Modi die Prüfungen auf
|
||||||
|
* Helligkeitsband, Farbsättigung, Farbfehlsichtigkeit (schlechtestes Paar
|
||||||
|
* ΔE 12,1 unter Deuteranopie) und Kontrast zum Untergrund. Die vollen
|
||||||
|
* Signaturtöne wären auf dunklem Grund zu hell und fielen durch.
|
||||||
|
*/
|
||||||
|
|
||||||
|
export const SERIES_COLORS = {
|
||||||
|
episodes: "#c47a18",
|
||||||
|
movies: "#d92d78",
|
||||||
|
} as const;
|
||||||
|
|
||||||
|
/** Ein Ton für Balken, die nur eine Größe zeigen (keine Identität). */
|
||||||
|
const SINGLE_HUE = "#c47a18";
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Säulen je Monat
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
export type MonthlyPointData = {
|
||||||
|
label: string;
|
||||||
|
episodes: number;
|
||||||
|
movies: number;
|
||||||
|
minutes: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
/** Rundet die Achsenspitze auf einen glatten Wert auf. */
|
||||||
|
function niceMax(value: number): number {
|
||||||
|
if (value <= 0) return 4;
|
||||||
|
const magnitude = 10 ** Math.floor(Math.log10(value));
|
||||||
|
for (const step of [1, 2, 2.5, 5, 10]) {
|
||||||
|
const candidate = step * magnitude;
|
||||||
|
if (candidate >= value) return candidate;
|
||||||
|
}
|
||||||
|
return 10 * magnitude;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function MonthlyChart({ points }: { points: MonthlyPointData[] }) {
|
||||||
|
const [active, setActive] = useState<number | null>(null);
|
||||||
|
|
||||||
|
const max = niceMax(Math.max(1, ...points.map((point) => point.episodes + point.movies)));
|
||||||
|
const ticks = [0, max / 2, max];
|
||||||
|
|
||||||
|
// Breites Seitenverhältnis: das SVG füllt die Karte und bleibt trotzdem flach.
|
||||||
|
const width = 1100;
|
||||||
|
const height = 260;
|
||||||
|
const padding = { top: 12, right: 8, bottom: 28, left: 38 };
|
||||||
|
const plotWidth = width - padding.left - padding.right;
|
||||||
|
const plotHeight = height - padding.top - padding.bottom;
|
||||||
|
|
||||||
|
const band = plotWidth / Math.max(1, points.length);
|
||||||
|
const barWidth = Math.min(24, band - 10);
|
||||||
|
const scale = (value: number) => (value / max) * plotHeight;
|
||||||
|
|
||||||
|
const total = points.reduce((sum, point) => sum + point.episodes + point.movies, 0);
|
||||||
|
if (total === 0) {
|
||||||
|
return (
|
||||||
|
<p className="py-8 text-center text-sm text-[var(--fl-faint)]">
|
||||||
|
In den letzten zwölf Monaten wurde noch nichts abgehakt.
|
||||||
|
</p>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<figure className="m-0">
|
||||||
|
<Legend
|
||||||
|
items={[
|
||||||
|
{ label: "Episoden", color: SERIES_COLORS.episodes },
|
||||||
|
{ label: "Filme", color: SERIES_COLORS.movies },
|
||||||
|
]}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<div className="relative mt-2 overflow-x-auto">
|
||||||
|
<svg
|
||||||
|
viewBox={`0 0 ${width} ${height}`}
|
||||||
|
className="h-auto w-full min-w-[32rem]"
|
||||||
|
role="img"
|
||||||
|
// Bewusst aria-label statt eines <title>-Kindes: React behandelt
|
||||||
|
// <title> als Dokument-Metadatum und hebt es aus dem SVG heraus —
|
||||||
|
// das brach die Hydration.
|
||||||
|
aria-label={`Gesehene Episoden und Filme je Monat in den letzten ${points.length} Monaten`}
|
||||||
|
onMouseLeave={() => setActive(null)}
|
||||||
|
>
|
||||||
|
{ticks.map((tick) => {
|
||||||
|
const y = padding.top + plotHeight - scale(tick);
|
||||||
|
return (
|
||||||
|
<g key={tick}>
|
||||||
|
<line
|
||||||
|
x1={padding.left}
|
||||||
|
x2={width - padding.right}
|
||||||
|
y1={y}
|
||||||
|
y2={y}
|
||||||
|
stroke="var(--fl-border)"
|
||||||
|
strokeWidth="1"
|
||||||
|
/>
|
||||||
|
<text
|
||||||
|
x={padding.left - 8}
|
||||||
|
y={y + 4}
|
||||||
|
textAnchor="end"
|
||||||
|
className="fill-[var(--fl-faint)] text-[11px] tabular-nums"
|
||||||
|
>
|
||||||
|
{Math.round(tick)}
|
||||||
|
</text>
|
||||||
|
</g>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
|
||||||
|
{points.map((point, index) => {
|
||||||
|
const x = padding.left + index * band + (band - barWidth) / 2;
|
||||||
|
const episodeHeight = scale(point.episodes);
|
||||||
|
const movieHeight = scale(point.movies);
|
||||||
|
const baseline = padding.top + plotHeight;
|
||||||
|
const isActive = active === index;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<g
|
||||||
|
key={point.label + index}
|
||||||
|
onMouseEnter={() => setActive(index)}
|
||||||
|
onFocus={() => setActive(index)}
|
||||||
|
tabIndex={0}
|
||||||
|
className="outline-none"
|
||||||
|
>
|
||||||
|
{/* Großzügige Trefferfläche — der Balken selbst ist schmal. */}
|
||||||
|
<rect
|
||||||
|
x={padding.left + index * band}
|
||||||
|
y={padding.top}
|
||||||
|
width={band}
|
||||||
|
height={plotHeight}
|
||||||
|
fill={isActive ? "var(--fl-surface-2)" : "transparent"}
|
||||||
|
opacity={isActive ? 0.6 : 0}
|
||||||
|
/>
|
||||||
|
|
||||||
|
{point.episodes > 0 && (
|
||||||
|
<rect
|
||||||
|
x={x}
|
||||||
|
y={baseline - episodeHeight}
|
||||||
|
width={barWidth}
|
||||||
|
height={episodeHeight}
|
||||||
|
rx={point.movies > 0 ? 0 : 4}
|
||||||
|
fill={SERIES_COLORS.episodes}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
{point.movies > 0 && (
|
||||||
|
<rect
|
||||||
|
x={x}
|
||||||
|
// 2 px Fuge in Untergrundfarbe zwischen den Segmenten
|
||||||
|
y={baseline - episodeHeight - movieHeight - (point.episodes > 0 ? 2 : 0)}
|
||||||
|
width={barWidth}
|
||||||
|
height={movieHeight}
|
||||||
|
rx={4}
|
||||||
|
fill={SERIES_COLORS.movies}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<text
|
||||||
|
x={padding.left + index * band + band / 2}
|
||||||
|
y={height - 8}
|
||||||
|
textAnchor="middle"
|
||||||
|
className={clsx(
|
||||||
|
"text-[11px]",
|
||||||
|
isActive ? "fill-[var(--fl-text)]" : "fill-[var(--fl-faint)]",
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{point.label}
|
||||||
|
</text>
|
||||||
|
</g>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</svg>
|
||||||
|
|
||||||
|
{active !== null && points[active] && (
|
||||||
|
<Tooltip
|
||||||
|
title={points[active].label}
|
||||||
|
rows={[
|
||||||
|
{ label: "Episoden", value: String(points[active].episodes), color: SERIES_COLORS.episodes },
|
||||||
|
{ label: "Filme", value: String(points[active].movies), color: SERIES_COLORS.movies },
|
||||||
|
{ label: "Schauzeit", value: formatMinutes(points[active].minutes) },
|
||||||
|
]}
|
||||||
|
position={active / Math.max(1, points.length - 1)}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<figcaption className="sr-only">
|
||||||
|
<table>
|
||||||
|
<caption>Gesehene Episoden und Filme je Monat</caption>
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th scope="col">Monat</th>
|
||||||
|
<th scope="col">Episoden</th>
|
||||||
|
<th scope="col">Filme</th>
|
||||||
|
<th scope="col">Schauzeit</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{points.map((point, index) => (
|
||||||
|
<tr key={point.label + index}>
|
||||||
|
<th scope="row">{point.label}</th>
|
||||||
|
<td>{point.episodes}</td>
|
||||||
|
<td>{point.movies}</td>
|
||||||
|
<td>{formatMinutes(point.minutes)}</td>
|
||||||
|
</tr>
|
||||||
|
))}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</figcaption>
|
||||||
|
</figure>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function Tooltip({
|
||||||
|
title,
|
||||||
|
rows,
|
||||||
|
position,
|
||||||
|
}: {
|
||||||
|
title: string;
|
||||||
|
rows: { label: string; value: string; color?: string }[];
|
||||||
|
position: number;
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
role="status"
|
||||||
|
className="pointer-events-none absolute top-0 z-10 min-w-[9rem] -translate-x-1/2 rounded-xl border border-[var(--fl-border)] bg-[var(--fl-surface-solid)] px-3 py-2 text-xs shadow-[var(--fl-shadow)]"
|
||||||
|
style={{ left: `${12 + position * 76}%` }}
|
||||||
|
>
|
||||||
|
<p className="mb-1 font-semibold">{title}</p>
|
||||||
|
{rows.map((row) => (
|
||||||
|
<p key={row.label} className="flex items-center gap-1.5 text-[var(--fl-muted)]">
|
||||||
|
{row.color && (
|
||||||
|
<span
|
||||||
|
aria-hidden
|
||||||
|
className="h-2 w-2 shrink-0 rounded-full"
|
||||||
|
style={{ backgroundColor: row.color }}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
<span className="flex-1">{row.label}</span>
|
||||||
|
<span className="font-medium tabular-nums text-[var(--fl-text)]">{row.value}</span>
|
||||||
|
</p>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function Legend({ items }: { items: { label: string; color: string }[] }) {
|
||||||
|
return (
|
||||||
|
<ul className="flex flex-wrap gap-4 text-xs text-[var(--fl-muted)]">
|
||||||
|
{items.map((item) => (
|
||||||
|
<li key={item.label} className="flex items-center gap-1.5">
|
||||||
|
<span
|
||||||
|
aria-hidden
|
||||||
|
className="h-2.5 w-2.5 rounded-sm"
|
||||||
|
style={{ backgroundColor: item.color }}
|
||||||
|
/>
|
||||||
|
{item.label}
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Liegende Balken für Verteilungen
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
export type DistributionRow = {
|
||||||
|
label: string;
|
||||||
|
minutes: number;
|
||||||
|
count: number;
|
||||||
|
/** Markenfarbe eines Dienstes; wird nur genutzt, wenn sie kontrastreich genug ist. */
|
||||||
|
color?: string | null;
|
||||||
|
};
|
||||||
|
|
||||||
|
/** Relative Leuchtdichte nach WCAG — für die Kontrastprüfung der Markenfarben. */
|
||||||
|
function luminance(hex: string): number | null {
|
||||||
|
const match = /^#([0-9a-f]{6})$/i.exec(hex.trim());
|
||||||
|
if (!match?.[1]) return null;
|
||||||
|
const value = Number.parseInt(match[1], 16);
|
||||||
|
const channels = [(value >> 16) & 255, (value >> 8) & 255, value & 255].map((raw) => {
|
||||||
|
const c = raw / 255;
|
||||||
|
return c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4;
|
||||||
|
});
|
||||||
|
return 0.2126 * channels[0]! + 0.7152 * channels[1]! + 0.0722 * channels[2]!;
|
||||||
|
}
|
||||||
|
|
||||||
|
function contrast(hex: string, surfaceLuminance: number): number | null {
|
||||||
|
const value = luminance(hex);
|
||||||
|
if (value === null) return null;
|
||||||
|
const lighter = Math.max(value, surfaceLuminance);
|
||||||
|
const darker = Math.min(value, surfaceLuminance);
|
||||||
|
return (lighter + 0.05) / (darker + 0.05);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Leuchtdichte der beiden Untergründe (--fl-bg in dunkel und hell). */
|
||||||
|
const SURFACE_DARK = 0.0055;
|
||||||
|
const SURFACE_LIGHT = 0.9;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Eine Markenfarbe wird nur benutzt, wenn sie auf **beiden** Untergründen
|
||||||
|
* mindestens 3:1 erreicht. So bleibt die Wahl unabhängig vom eingestellten
|
||||||
|
* Farbschema — sonst müsste die Komponente den Theme-Wechsel mitverfolgen und
|
||||||
|
* liefe Gefahr, beim ersten Rendern etwas anderes zu zeigen als der Server.
|
||||||
|
*/
|
||||||
|
function safeBrandColor(hex: string | null | undefined): string | null {
|
||||||
|
if (!hex) return null;
|
||||||
|
const dark = contrast(hex, SURFACE_DARK);
|
||||||
|
const light = contrast(hex, SURFACE_LIGHT);
|
||||||
|
if (dark === null || light === null) return null;
|
||||||
|
return dark >= 3 && light >= 3 ? hex : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function DistributionBars({
|
||||||
|
rows,
|
||||||
|
emptyText,
|
||||||
|
useBrandColors = false,
|
||||||
|
}: {
|
||||||
|
rows: DistributionRow[];
|
||||||
|
emptyText: string;
|
||||||
|
/**
|
||||||
|
* Streamingdienste tragen ihre Markenfarbe — das ist ihre Identität und
|
||||||
|
* zieht sich durchs ganze UI. Zu dunkle oder zu blasse Marken fallen
|
||||||
|
* automatisch auf den geprüften Standardton zurück, sonst verschwände der
|
||||||
|
* Balken je nach Farbschema.
|
||||||
|
*/
|
||||||
|
useBrandColors?: boolean;
|
||||||
|
}) {
|
||||||
|
if (rows.length === 0) {
|
||||||
|
return <p className="py-6 text-center text-sm text-[var(--fl-faint)]">{emptyText}</p>;
|
||||||
|
}
|
||||||
|
|
||||||
|
const max = Math.max(...rows.map((row) => row.minutes), 1);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<ul className="space-y-2.5">
|
||||||
|
{rows.map((row) => {
|
||||||
|
const brand = useBrandColors ? safeBrandColor(row.color) : null;
|
||||||
|
const color = brand ?? SINGLE_HUE;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<li key={row.label}>
|
||||||
|
<div className="mb-1 flex items-baseline justify-between gap-3 text-sm">
|
||||||
|
<span className="min-w-0 truncate text-[var(--fl-text)]">{row.label}</span>
|
||||||
|
<span className="shrink-0 tabular-nums text-[var(--fl-muted)]">
|
||||||
|
{formatMinutes(row.minutes)}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<div className="h-2.5 w-full overflow-hidden rounded-full bg-[var(--fl-surface-2)]">
|
||||||
|
<div
|
||||||
|
className="h-full rounded-full transition-[width] duration-500"
|
||||||
|
style={{
|
||||||
|
width: `${Math.max(2, (row.minutes / max) * 100)}%`,
|
||||||
|
backgroundColor: color,
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</li>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</ul>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,557 @@
|
|||||||
|
import "server-only";
|
||||||
|
import { prisma } from "./db";
|
||||||
|
import { SPECIALS_SEASON } from "./catalog";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Auswertungen für Übersicht, Kalender und Statistik.
|
||||||
|
*
|
||||||
|
* Alles wird aus den Sichtungen (`Watch`) berechnet — es gibt keine
|
||||||
|
* fortgeschriebenen Zähler, die auseinanderlaufen könnten. Wo es auf Tempo
|
||||||
|
* ankommt, laufen die Abfragen als SQL, weil Prisma für Zeitreihen keine
|
||||||
|
* Gruppierung nach Monat kennt.
|
||||||
|
*/
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Übersicht
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
export type ContinueItem = {
|
||||||
|
entryId: string;
|
||||||
|
titleId: string;
|
||||||
|
title: string;
|
||||||
|
posterPath: string | null;
|
||||||
|
watched: number;
|
||||||
|
total: number;
|
||||||
|
percent: number;
|
||||||
|
lastWatchedAt: Date | null;
|
||||||
|
next: {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
seasonNumber: number;
|
||||||
|
episodeNumber: number;
|
||||||
|
airDate: Date | null;
|
||||||
|
runtime: number | null;
|
||||||
|
} | null;
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* „Weiterschauen": laufende Serien, zuletzt angefasste zuerst.
|
||||||
|
* Serien ohne offene Episode fallen heraus — die sind durch.
|
||||||
|
*/
|
||||||
|
export async function getContinueWatching(userId: string, limit = 12): Promise<ContinueItem[]> {
|
||||||
|
const entries = await prisma.libraryEntry.findMany({
|
||||||
|
where: {
|
||||||
|
userId,
|
||||||
|
deletedAt: null,
|
||||||
|
status: { in: ["WATCHING", "PAUSED"] },
|
||||||
|
title: { type: "SERIES" },
|
||||||
|
},
|
||||||
|
orderBy: { updatedAt: "desc" },
|
||||||
|
take: limit * 2,
|
||||||
|
select: {
|
||||||
|
id: true,
|
||||||
|
titleId: true,
|
||||||
|
currentRun: true,
|
||||||
|
updatedAt: true,
|
||||||
|
title: { select: { title: true, posterPath: true, episodeCount: true } },
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
if (entries.length === 0) return [];
|
||||||
|
|
||||||
|
const items: ContinueItem[] = [];
|
||||||
|
|
||||||
|
for (const entry of entries) {
|
||||||
|
const [watched, next, lastWatch] = await Promise.all([
|
||||||
|
prisma.watch.count({
|
||||||
|
where: {
|
||||||
|
userId,
|
||||||
|
entryId: entry.id,
|
||||||
|
run: entry.currentRun,
|
||||||
|
episode: { seasonNumber: { gt: SPECIALS_SEASON } },
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
prisma.episode.findFirst({
|
||||||
|
where: {
|
||||||
|
titleId: entry.titleId,
|
||||||
|
seasonNumber: { gt: SPECIALS_SEASON },
|
||||||
|
watches: { none: { userId, run: entry.currentRun } },
|
||||||
|
},
|
||||||
|
orderBy: [{ seasonNumber: "asc" }, { episodeNumber: "asc" }],
|
||||||
|
select: {
|
||||||
|
id: true,
|
||||||
|
name: true,
|
||||||
|
seasonNumber: true,
|
||||||
|
episodeNumber: true,
|
||||||
|
airDate: true,
|
||||||
|
runtime: true,
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
prisma.watch.findFirst({
|
||||||
|
where: { userId, entryId: entry.id, run: entry.currentRun },
|
||||||
|
orderBy: { watchedAt: "desc" },
|
||||||
|
select: { watchedAt: true },
|
||||||
|
}),
|
||||||
|
]);
|
||||||
|
|
||||||
|
if (!next) continue;
|
||||||
|
|
||||||
|
const total = entry.title.episodeCount;
|
||||||
|
items.push({
|
||||||
|
entryId: entry.id,
|
||||||
|
titleId: entry.titleId,
|
||||||
|
title: entry.title.title,
|
||||||
|
posterPath: entry.title.posterPath,
|
||||||
|
watched,
|
||||||
|
total,
|
||||||
|
percent: total > 0 ? Math.round((watched / total) * 100) : 0,
|
||||||
|
lastWatchedAt: lastWatch?.watchedAt ?? null,
|
||||||
|
next,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (items.length >= limit) break;
|
||||||
|
}
|
||||||
|
|
||||||
|
return items;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type UpcomingEpisode = {
|
||||||
|
episodeId: string;
|
||||||
|
titleId: string;
|
||||||
|
title: string;
|
||||||
|
posterPath: string | null;
|
||||||
|
name: string;
|
||||||
|
seasonNumber: number;
|
||||||
|
episodeNumber: number;
|
||||||
|
airDate: Date;
|
||||||
|
runtime: number | null;
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Kommende Episoden getrackter Serien.
|
||||||
|
*
|
||||||
|
* „Getrackt" heißt: in der Bibliothek und nicht abgebrochen. Abgeschlossene
|
||||||
|
* Serien bleiben bewusst drin — wer bei einer laufenden Serie auf dem Stand
|
||||||
|
* ist, gilt als „abgeschlossen" und will die nächste Folge erst recht im
|
||||||
|
* Kalender sehen. Nur Abgebrochenes fällt heraus.
|
||||||
|
*/
|
||||||
|
export async function getUpcomingEpisodes(
|
||||||
|
userId: string,
|
||||||
|
from: Date,
|
||||||
|
to: Date,
|
||||||
|
): Promise<UpcomingEpisode[]> {
|
||||||
|
const episodes = await prisma.episode.findMany({
|
||||||
|
where: {
|
||||||
|
airDate: { gte: from, lte: to },
|
||||||
|
seasonNumber: { gt: SPECIALS_SEASON },
|
||||||
|
title: {
|
||||||
|
entries: {
|
||||||
|
some: { userId, deletedAt: null, status: { not: "DROPPED" } },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
orderBy: [{ airDate: "asc" }, { seasonNumber: "asc" }, { episodeNumber: "asc" }],
|
||||||
|
select: {
|
||||||
|
id: true,
|
||||||
|
name: true,
|
||||||
|
seasonNumber: true,
|
||||||
|
episodeNumber: true,
|
||||||
|
airDate: true,
|
||||||
|
runtime: true,
|
||||||
|
title: { select: { id: true, title: true, posterPath: true } },
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
return episodes.flatMap((episode) =>
|
||||||
|
episode.airDate
|
||||||
|
? [
|
||||||
|
{
|
||||||
|
episodeId: episode.id,
|
||||||
|
titleId: episode.title.id,
|
||||||
|
title: episode.title.title,
|
||||||
|
posterPath: episode.title.posterPath,
|
||||||
|
name: episode.name,
|
||||||
|
seasonNumber: episode.seasonNumber,
|
||||||
|
episodeNumber: episode.episodeNumber,
|
||||||
|
airDate: episode.airDate,
|
||||||
|
runtime: episode.runtime,
|
||||||
|
},
|
||||||
|
]
|
||||||
|
: [],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export type AvailableItem = {
|
||||||
|
titleId: string;
|
||||||
|
title: string;
|
||||||
|
posterPath: string | null;
|
||||||
|
providers: { name: string; color: string | null }[];
|
||||||
|
since: Date;
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Watchlist-Titel, die seit Kurzem auf einem Dienst verfügbar sind.
|
||||||
|
* Grundlage ist `firstSeenAt` der Verfügbarkeit — das steht seit dem ersten
|
||||||
|
* Abgleich fest und wandert nicht bei jedem Sync weiter.
|
||||||
|
*/
|
||||||
|
export async function getNewlyAvailable(
|
||||||
|
userId: string,
|
||||||
|
region: string,
|
||||||
|
sinceDays = 30,
|
||||||
|
): Promise<AvailableItem[]> {
|
||||||
|
const since = new Date(Date.now() - sinceDays * 86_400_000);
|
||||||
|
|
||||||
|
const rows = await prisma.titleProvider.findMany({
|
||||||
|
where: {
|
||||||
|
region,
|
||||||
|
kind: { in: ["FLATRATE", "FREE", "ADS"] },
|
||||||
|
firstSeenAt: { gte: since },
|
||||||
|
title: { entries: { some: { userId, deletedAt: null, status: "WATCHLIST" } } },
|
||||||
|
},
|
||||||
|
orderBy: { firstSeenAt: "desc" },
|
||||||
|
select: {
|
||||||
|
firstSeenAt: true,
|
||||||
|
provider: { select: { name: true, color: true } },
|
||||||
|
title: { select: { id: true, title: true, posterPath: true } },
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const byTitle = new Map<string, AvailableItem>();
|
||||||
|
for (const row of rows) {
|
||||||
|
const existing = byTitle.get(row.title.id);
|
||||||
|
if (existing) {
|
||||||
|
if (!existing.providers.some((provider) => provider.name === row.provider.name)) {
|
||||||
|
existing.providers.push(row.provider);
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
byTitle.set(row.title.id, {
|
||||||
|
titleId: row.title.id,
|
||||||
|
title: row.title.title,
|
||||||
|
posterPath: row.title.posterPath,
|
||||||
|
providers: [row.provider],
|
||||||
|
since: row.firstSeenAt,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return [...byTitle.values()];
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Statistik
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
export type Totals = {
|
||||||
|
minutes: number;
|
||||||
|
episodes: number;
|
||||||
|
movies: number;
|
||||||
|
titlesCompleted: number;
|
||||||
|
seriesCount: number;
|
||||||
|
movieCount: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
export async function getTotals(userId: string): Promise<Totals> {
|
||||||
|
const [minutes, episodes, movies, completed, byType] = await Promise.all([
|
||||||
|
prisma.watch.aggregate({ where: { userId }, _sum: { minutes: true } }),
|
||||||
|
prisma.watch.count({ where: { userId, episodeId: { not: null } } }),
|
||||||
|
prisma.watch.count({ where: { userId, episodeId: null } }),
|
||||||
|
prisma.libraryEntry.count({ where: { userId, deletedAt: null, status: "COMPLETED" } }),
|
||||||
|
prisma.libraryEntry.groupBy({
|
||||||
|
by: ["titleId"],
|
||||||
|
where: { userId, deletedAt: null },
|
||||||
|
_count: { _all: true },
|
||||||
|
}),
|
||||||
|
]);
|
||||||
|
|
||||||
|
const typeCounts = await prisma.title.groupBy({
|
||||||
|
by: ["type"],
|
||||||
|
where: { id: { in: byType.map((row) => row.titleId) } },
|
||||||
|
_count: { _all: true },
|
||||||
|
});
|
||||||
|
|
||||||
|
return {
|
||||||
|
minutes: minutes._sum.minutes ?? 0,
|
||||||
|
episodes,
|
||||||
|
movies,
|
||||||
|
titlesCompleted: completed,
|
||||||
|
seriesCount: typeCounts.find((row) => row.type === "SERIES")?._count._all ?? 0,
|
||||||
|
movieCount: typeCounts.find((row) => row.type === "MOVIE")?._count._all ?? 0,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export type MonthlyPoint = {
|
||||||
|
/** Monatsanfang */
|
||||||
|
month: Date;
|
||||||
|
label: string;
|
||||||
|
episodes: number;
|
||||||
|
movies: number;
|
||||||
|
minutes: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
/** Aktivität je Monat, lückenlos — auch Monate ohne Sichtung erscheinen. */
|
||||||
|
export async function getMonthlyActivity(userId: string, months = 12): Promise<MonthlyPoint[]> {
|
||||||
|
const start = new Date();
|
||||||
|
start.setDate(1);
|
||||||
|
start.setHours(0, 0, 0, 0);
|
||||||
|
start.setMonth(start.getMonth() - (months - 1));
|
||||||
|
|
||||||
|
// Der Monatsschlüssel kommt als Text aus der Datenbank („2026-04").
|
||||||
|
// Ein Zeitstempel würde hier schiefgehen: date_trunc liefert Mitternacht in
|
||||||
|
// der Sitzungszeitzone, JS legt beim Vergleich die lokale Zone an — zwei
|
||||||
|
// Stunden Versatz genügen, damit kein einziger Schlüssel mehr passt.
|
||||||
|
const rows = await prisma.$queryRaw<
|
||||||
|
{ month: string; episodes: bigint; movies: bigint; minutes: bigint | null }[]
|
||||||
|
>`
|
||||||
|
SELECT
|
||||||
|
to_char(date_trunc('month', "watchedAt"), 'YYYY-MM') AS month,
|
||||||
|
count(*) FILTER (WHERE "episodeId" IS NOT NULL) AS episodes,
|
||||||
|
count(*) FILTER (WHERE "episodeId" IS NULL) AS movies,
|
||||||
|
sum("minutes") AS minutes
|
||||||
|
FROM "Watch"
|
||||||
|
WHERE "userId" = ${userId} AND "watchedAt" >= ${start}
|
||||||
|
GROUP BY 1
|
||||||
|
ORDER BY 1
|
||||||
|
`;
|
||||||
|
|
||||||
|
const byMonth = new Map(rows.map((row) => [row.month, row]));
|
||||||
|
const points: MonthlyPoint[] = [];
|
||||||
|
|
||||||
|
for (let index = 0; index < months; index += 1) {
|
||||||
|
const month = new Date(start);
|
||||||
|
month.setMonth(start.getMonth() + index);
|
||||||
|
const key = `${month.getFullYear()}-${String(month.getMonth() + 1).padStart(2, "0")}`;
|
||||||
|
const row = byMonth.get(key);
|
||||||
|
|
||||||
|
points.push({
|
||||||
|
month,
|
||||||
|
label: month.toLocaleDateString("de-DE", { month: "short" }),
|
||||||
|
episodes: Number(row?.episodes ?? 0),
|
||||||
|
movies: Number(row?.movies ?? 0),
|
||||||
|
minutes: Number(row?.minutes ?? 0),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return points;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type Slice = { label: string; minutes: number; count: number; color: string | null };
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Verteilung der Schauzeit nach Streamingdienst.
|
||||||
|
* Grundlage ist das Feld „wo schaue ich das" — es sagt, wo tatsächlich
|
||||||
|
* geschaut wurde, nicht bloß, wo es verfügbar wäre.
|
||||||
|
*/
|
||||||
|
export async function getProviderDistribution(userId: string): Promise<Slice[]> {
|
||||||
|
const rows = await prisma.$queryRaw<{ label: string; minutes: bigint; count: bigint }[]>`
|
||||||
|
SELECT
|
||||||
|
coalesce(nullif(e."whereToWatch", ''), 'Ohne Angabe') AS label,
|
||||||
|
sum(w."minutes") AS minutes,
|
||||||
|
count(*) AS count
|
||||||
|
FROM "Watch" w
|
||||||
|
JOIN "LibraryEntry" e ON e."id" = w."entryId"
|
||||||
|
WHERE w."userId" = ${userId}
|
||||||
|
GROUP BY 1
|
||||||
|
ORDER BY minutes DESC
|
||||||
|
`;
|
||||||
|
|
||||||
|
const providers = await prisma.watchProvider.findMany({ select: { name: true, color: true } });
|
||||||
|
const colorByName = new Map(providers.map((provider) => [provider.name, provider.color]));
|
||||||
|
|
||||||
|
return rows.map((row) => ({
|
||||||
|
label: row.label,
|
||||||
|
minutes: Number(row.minutes ?? 0),
|
||||||
|
count: Number(row.count),
|
||||||
|
color: colorByName.get(row.label) ?? null,
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Verteilung der Schauzeit nach Genre. Mehrfachnennungen zählen mehrfach. */
|
||||||
|
export async function getGenreDistribution(userId: string): Promise<Slice[]> {
|
||||||
|
const rows = await prisma.$queryRaw<{ label: string; minutes: bigint; count: bigint }[]>`
|
||||||
|
SELECT
|
||||||
|
genre AS label,
|
||||||
|
sum(w."minutes") AS minutes,
|
||||||
|
count(*) AS count
|
||||||
|
FROM "Watch" w
|
||||||
|
JOIN "Title" t ON t."id" = w."titleId"
|
||||||
|
CROSS JOIN LATERAL unnest(t."genres") AS genre
|
||||||
|
WHERE w."userId" = ${userId}
|
||||||
|
GROUP BY 1
|
||||||
|
ORDER BY minutes DESC
|
||||||
|
LIMIT 12
|
||||||
|
`;
|
||||||
|
|
||||||
|
return rows.map((row) => ({
|
||||||
|
label: row.label,
|
||||||
|
minutes: Number(row.minutes ?? 0),
|
||||||
|
count: Number(row.count),
|
||||||
|
color: null,
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
export type TopTitle = {
|
||||||
|
titleId: string;
|
||||||
|
title: string;
|
||||||
|
posterPath: string | null;
|
||||||
|
rating: number | null;
|
||||||
|
minutes: number;
|
||||||
|
type: "SERIES" | "MOVIE";
|
||||||
|
};
|
||||||
|
|
||||||
|
/** Bestbewertete Titel. */
|
||||||
|
export async function getTopRated(userId: string, limit = 6): Promise<TopTitle[]> {
|
||||||
|
const entries = await prisma.libraryEntry.findMany({
|
||||||
|
where: { userId, deletedAt: null, rating: { not: null } },
|
||||||
|
orderBy: [{ rating: "desc" }, { updatedAt: "desc" }],
|
||||||
|
take: limit,
|
||||||
|
select: {
|
||||||
|
rating: true,
|
||||||
|
title: { select: { id: true, title: true, posterPath: true, type: true } },
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
return entries.map((entry) => ({
|
||||||
|
titleId: entry.title.id,
|
||||||
|
title: entry.title.title,
|
||||||
|
posterPath: entry.title.posterPath,
|
||||||
|
rating: entry.rating,
|
||||||
|
minutes: 0,
|
||||||
|
type: entry.title.type,
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Titel mit der meisten investierten Zeit. */
|
||||||
|
export async function getMostWatched(userId: string, limit = 6): Promise<TopTitle[]> {
|
||||||
|
const rows = await prisma.watch.groupBy({
|
||||||
|
by: ["titleId"],
|
||||||
|
where: { userId },
|
||||||
|
_sum: { minutes: true },
|
||||||
|
orderBy: { _sum: { minutes: "desc" } },
|
||||||
|
take: limit,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (rows.length === 0) return [];
|
||||||
|
|
||||||
|
const titles = await prisma.title.findMany({
|
||||||
|
where: { id: { in: rows.map((row) => row.titleId) } },
|
||||||
|
select: { id: true, title: true, posterPath: true, type: true },
|
||||||
|
});
|
||||||
|
const byId = new Map(titles.map((title) => [title.id, title]));
|
||||||
|
|
||||||
|
return rows.flatMap((row) => {
|
||||||
|
const title = byId.get(row.titleId);
|
||||||
|
return title
|
||||||
|
? [
|
||||||
|
{
|
||||||
|
titleId: title.id,
|
||||||
|
title: title.title,
|
||||||
|
posterPath: title.posterPath,
|
||||||
|
rating: null,
|
||||||
|
minutes: row._sum.minutes ?? 0,
|
||||||
|
type: title.type,
|
||||||
|
},
|
||||||
|
]
|
||||||
|
: [];
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export type YearReview = {
|
||||||
|
year: number;
|
||||||
|
minutes: number;
|
||||||
|
episodes: number;
|
||||||
|
movies: number;
|
||||||
|
titlesStarted: number;
|
||||||
|
titlesCompleted: number;
|
||||||
|
busiestMonth: { label: string; minutes: number } | null;
|
||||||
|
topTitle: TopTitle | null;
|
||||||
|
};
|
||||||
|
|
||||||
|
/** „Das Jahr in Zahlen". */
|
||||||
|
export async function getYearReview(userId: string, year: number): Promise<YearReview> {
|
||||||
|
const from = new Date(Date.UTC(year, 0, 1));
|
||||||
|
const to = new Date(Date.UTC(year + 1, 0, 1));
|
||||||
|
|
||||||
|
const [aggregate, episodes, movies, started, completed, months, top] = await Promise.all([
|
||||||
|
prisma.watch.aggregate({
|
||||||
|
where: { userId, watchedAt: { gte: from, lt: to } },
|
||||||
|
_sum: { minutes: true },
|
||||||
|
}),
|
||||||
|
prisma.watch.count({
|
||||||
|
where: { userId, watchedAt: { gte: from, lt: to }, episodeId: { not: null } },
|
||||||
|
}),
|
||||||
|
prisma.watch.count({ where: { userId, watchedAt: { gte: from, lt: to }, episodeId: null } }),
|
||||||
|
prisma.libraryEntry.count({ where: { userId, startedAt: { gte: from, lt: to } } }),
|
||||||
|
prisma.libraryEntry.count({ where: { userId, finishedAt: { gte: from, lt: to } } }),
|
||||||
|
prisma.$queryRaw<{ month: string; minutes: bigint }[]>`
|
||||||
|
SELECT to_char(date_trunc('month', "watchedAt"), 'YYYY-MM') AS month, sum("minutes") AS minutes
|
||||||
|
FROM "Watch"
|
||||||
|
WHERE "userId" = ${userId} AND "watchedAt" >= ${from} AND "watchedAt" < ${to}
|
||||||
|
GROUP BY 1
|
||||||
|
ORDER BY minutes DESC
|
||||||
|
LIMIT 1
|
||||||
|
`,
|
||||||
|
prisma.watch.groupBy({
|
||||||
|
by: ["titleId"],
|
||||||
|
where: { userId, watchedAt: { gte: from, lt: to } },
|
||||||
|
_sum: { minutes: true },
|
||||||
|
orderBy: { _sum: { minutes: "desc" } },
|
||||||
|
take: 1,
|
||||||
|
}),
|
||||||
|
]);
|
||||||
|
|
||||||
|
const busiest = months[0];
|
||||||
|
const topTitleRow = top[0];
|
||||||
|
const topTitle = topTitleRow
|
||||||
|
? await prisma.title.findUnique({
|
||||||
|
where: { id: topTitleRow.titleId },
|
||||||
|
select: { id: true, title: true, posterPath: true, type: true },
|
||||||
|
})
|
||||||
|
: null;
|
||||||
|
|
||||||
|
return {
|
||||||
|
year,
|
||||||
|
minutes: aggregate._sum.minutes ?? 0,
|
||||||
|
episodes,
|
||||||
|
movies,
|
||||||
|
titlesStarted: started,
|
||||||
|
titlesCompleted: completed,
|
||||||
|
busiestMonth: busiest
|
||||||
|
? {
|
||||||
|
label: monthLabel(busiest.month),
|
||||||
|
minutes: Number(busiest.minutes ?? 0),
|
||||||
|
}
|
||||||
|
: null,
|
||||||
|
topTitle:
|
||||||
|
topTitle && topTitleRow
|
||||||
|
? {
|
||||||
|
titleId: topTitle.id,
|
||||||
|
title: topTitle.title,
|
||||||
|
posterPath: topTitle.posterPath,
|
||||||
|
rating: null,
|
||||||
|
minutes: topTitleRow._sum.minutes ?? 0,
|
||||||
|
type: topTitle.type,
|
||||||
|
}
|
||||||
|
: null,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** „2026-04" → „April 2026" */
|
||||||
|
function monthLabel(key: string): string {
|
||||||
|
const [year, month] = key.split("-").map(Number);
|
||||||
|
if (!year || !month) return key;
|
||||||
|
return new Date(year, month - 1, 1).toLocaleDateString("de-DE", {
|
||||||
|
month: "long",
|
||||||
|
year: "numeric",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Jahre, in denen überhaupt etwas gesehen wurde — für die Jahresauswahl. */
|
||||||
|
export async function getActiveYears(userId: string): Promise<number[]> {
|
||||||
|
const rows = await prisma.$queryRaw<{ year: number }[]>`
|
||||||
|
SELECT DISTINCT extract(year FROM "watchedAt")::int AS year
|
||||||
|
FROM "Watch"
|
||||||
|
WHERE "userId" = ${userId}
|
||||||
|
ORDER BY year DESC
|
||||||
|
`;
|
||||||
|
return rows.map((row) => row.year);
|
||||||
|
}
|
||||||
@@ -0,0 +1,177 @@
|
|||||||
|
import "./setup";
|
||||||
|
|
||||||
|
import assert from "node:assert/strict";
|
||||||
|
import test, { after, before } from "node:test";
|
||||||
|
|
||||||
|
import { installTmdbStub, SERIES_ID, MOVIE_ID } from "./fixtures/tmdb";
|
||||||
|
import { prisma } from "../src/lib/db";
|
||||||
|
import { importMovie, importSeries } from "../src/lib/catalog";
|
||||||
|
import { addToLibrary, markEpisodesWatched, markMovieWatched } from "../src/lib/library";
|
||||||
|
import {
|
||||||
|
getContinueWatching,
|
||||||
|
getMonthlyActivity,
|
||||||
|
getTotals,
|
||||||
|
getUpcomingEpisodes,
|
||||||
|
getYearReview,
|
||||||
|
} from "../src/lib/stats";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Prüft die Auswertungen. Besonderes Augenmerk auf die Monatsgruppierung:
|
||||||
|
* dort führte ein Zeitzonenversatz zwischen Datenbank und JavaScript einmal
|
||||||
|
* dazu, dass das Diagramm leer blieb, obwohl Sichtungen vorlagen.
|
||||||
|
*/
|
||||||
|
|
||||||
|
const stub = installTmdbStub();
|
||||||
|
const TEST_EMAIL = "test-stats@flimmer.invalid";
|
||||||
|
|
||||||
|
let userId: string;
|
||||||
|
let entryId: string;
|
||||||
|
let seriesTitleId: string;
|
||||||
|
|
||||||
|
async function cleanup() {
|
||||||
|
await prisma.user.deleteMany({ where: { email: TEST_EMAIL } });
|
||||||
|
await prisma.title.deleteMany({ where: { tmdbId: { gte: 999000, lt: 1000000 } } });
|
||||||
|
}
|
||||||
|
|
||||||
|
before(async () => {
|
||||||
|
await cleanup();
|
||||||
|
userId = (
|
||||||
|
await prisma.user.create({ data: { email: TEST_EMAIL, name: "Statistik" }, select: { id: true } })
|
||||||
|
).id;
|
||||||
|
|
||||||
|
seriesTitleId = (await importSeries(SERIES_ID, { region: "DE" })).id;
|
||||||
|
const movieTitleId = (await importMovie(MOVIE_ID, "DE")).id;
|
||||||
|
|
||||||
|
const entry = await addToLibrary(userId, seriesTitleId, "WATCHING");
|
||||||
|
entryId = entry.id;
|
||||||
|
|
||||||
|
const episodes = await prisma.episode.findMany({
|
||||||
|
where: { titleId: seriesTitleId, seasonNumber: { gt: 0 } },
|
||||||
|
orderBy: [{ seasonNumber: "asc" }, { episodeNumber: "asc" }],
|
||||||
|
select: { id: true },
|
||||||
|
});
|
||||||
|
|
||||||
|
// Drei Episoden: heute, vor einem Monat, vor zwei Monaten.
|
||||||
|
for (const [index, episode] of episodes.slice(0, 3).entries()) {
|
||||||
|
const when = new Date();
|
||||||
|
when.setMonth(when.getMonth() - index);
|
||||||
|
when.setHours(20, 30, 0, 0);
|
||||||
|
await markEpisodesWatched(userId, entry.id, [episode.id], when);
|
||||||
|
}
|
||||||
|
|
||||||
|
const movieEntry = await addToLibrary(userId, movieTitleId, "WATCHING");
|
||||||
|
await markMovieWatched(userId, movieEntry.id, new Date());
|
||||||
|
});
|
||||||
|
|
||||||
|
after(async () => {
|
||||||
|
await cleanup();
|
||||||
|
stub.restore();
|
||||||
|
await prisma.$disconnect();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("Gesamtzahlen zählen Episoden und Filme getrennt", async () => {
|
||||||
|
const totals = await getTotals(userId);
|
||||||
|
|
||||||
|
assert.equal(totals.episodes, 3);
|
||||||
|
assert.equal(totals.movies, 1);
|
||||||
|
// 52 + 47 + 48 aus den Episoden, 118 aus dem Film
|
||||||
|
assert.equal(totals.minutes, 52 + 47 + 48 + 118);
|
||||||
|
assert.equal(totals.seriesCount, 1);
|
||||||
|
assert.equal(totals.movieCount, 1);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("Monatsverlauf ordnet Sichtungen dem richtigen Monat zu", async () => {
|
||||||
|
const points = await getMonthlyActivity(userId, 12);
|
||||||
|
|
||||||
|
assert.equal(points.length, 12);
|
||||||
|
|
||||||
|
const total = points.reduce((sum, point) => sum + point.episodes + point.movies, 0);
|
||||||
|
assert.equal(total, 4, "keine Sichtung fällt beim Gruppieren durchs Raster");
|
||||||
|
|
||||||
|
const current = points[points.length - 1];
|
||||||
|
assert.ok(current);
|
||||||
|
assert.equal(current.episodes, 1, "die Sichtung von heute liegt im laufenden Monat");
|
||||||
|
assert.equal(current.movies, 1);
|
||||||
|
|
||||||
|
const previous = points[points.length - 2];
|
||||||
|
assert.equal(previous?.episodes, 1, "die Sichtung von vor einem Monat liegt im Vormonat");
|
||||||
|
|
||||||
|
// Lückenlos: auch Monate ohne Sichtung sind vertreten.
|
||||||
|
assert.ok(points.some((point) => point.episodes === 0 && point.movies === 0));
|
||||||
|
});
|
||||||
|
|
||||||
|
test("Jahresrückblick fasst das laufende Jahr zusammen", async () => {
|
||||||
|
const review = await getYearReview(userId, new Date().getFullYear());
|
||||||
|
|
||||||
|
assert.ok(review.minutes > 0);
|
||||||
|
assert.ok(review.episodes >= 1);
|
||||||
|
assert.equal(review.movies, 1);
|
||||||
|
assert.ok(review.busiestMonth, "der stärkste Monat wird benannt");
|
||||||
|
assert.match(
|
||||||
|
review.busiestMonth!.label,
|
||||||
|
/\d{4}$/,
|
||||||
|
"die Beschriftung endet auf die Jahreszahl, nicht auf einen rohen Zeitstempel",
|
||||||
|
);
|
||||||
|
assert.ok(review.topTitle);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("Weiterschauen nennt die nächste offene Episode", async () => {
|
||||||
|
const items = await getContinueWatching(userId, 10);
|
||||||
|
const series = items.find((item) => item.titleId === seriesTitleId);
|
||||||
|
|
||||||
|
assert.ok(series, "die laufende Serie steht in der Liste");
|
||||||
|
assert.equal(series.watched, 3);
|
||||||
|
assert.equal(series.total, 5);
|
||||||
|
assert.equal(series.next?.episodeNumber, 1);
|
||||||
|
assert.equal(series.next?.seasonNumber, 2, "nach Staffel 1 kommt Staffel 2");
|
||||||
|
assert.ok(series.lastWatchedAt);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("Weiterschauen lässt durchgeschaute Serien weg", async () => {
|
||||||
|
const episodes = await prisma.episode.findMany({
|
||||||
|
where: { titleId: seriesTitleId, seasonNumber: { gt: 0 } },
|
||||||
|
select: { id: true },
|
||||||
|
});
|
||||||
|
await markEpisodesWatched(userId, entryId, episodes.map((episode) => episode.id));
|
||||||
|
|
||||||
|
const items = await getContinueWatching(userId, 10);
|
||||||
|
assert.equal(
|
||||||
|
items.find((item) => item.titleId === seriesTitleId),
|
||||||
|
undefined,
|
||||||
|
"wo nichts mehr offen ist, gibt es auch nichts weiterzuschauen",
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("Kalender liefert nur Episoden im gefragten Zeitraum", async () => {
|
||||||
|
// Die Fixture hat eine Episode am 08.01.2099. Der vorige Test hat die Serie
|
||||||
|
// auf „Abgeschlossen" gebracht — sie muss trotzdem im Kalender stehen, denn
|
||||||
|
// bei einer laufenden Serie heißt „abgeschlossen" nur: auf dem Stand.
|
||||||
|
const episodes = await getUpcomingEpisodes(
|
||||||
|
userId,
|
||||||
|
new Date("2098-12-01T00:00:00.000Z"),
|
||||||
|
new Date("2099-03-01T00:00:00.000Z"),
|
||||||
|
);
|
||||||
|
assert.equal(episodes.length, 1);
|
||||||
|
assert.equal(episodes[0]?.seasonNumber, 2);
|
||||||
|
assert.equal(episodes[0]?.episodeNumber, 2);
|
||||||
|
|
||||||
|
const empty = await getUpcomingEpisodes(
|
||||||
|
userId,
|
||||||
|
new Date("2050-01-01T00:00:00.000Z"),
|
||||||
|
new Date("2050-12-31T00:00:00.000Z"),
|
||||||
|
);
|
||||||
|
assert.equal(empty.length, 0, "außerhalb des Zeitraums kommt nichts");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("Abgebrochenes taucht im Kalender nicht mehr auf", async () => {
|
||||||
|
await prisma.libraryEntry.update({ where: { id: entryId }, data: { status: "DROPPED" } });
|
||||||
|
|
||||||
|
const episodes = await getUpcomingEpisodes(
|
||||||
|
userId,
|
||||||
|
new Date("2098-12-01T00:00:00.000Z"),
|
||||||
|
new Date("2099-03-01T00:00:00.000Z"),
|
||||||
|
);
|
||||||
|
assert.equal(episodes.length, 0, "wer abgebrochen hat, braucht keine Erinnerung");
|
||||||
|
|
||||||
|
await prisma.libraryEntry.update({ where: { id: entryId }, data: { status: "COMPLETED" } });
|
||||||
|
});
|
||||||
Reference in New Issue
Block a user