Release 2.4.1: import older Immich albums into the calendar
- Admin calendar: "Ältere Alben übernehmen" lists albums named "Titel | TT.MM.JJJJ" without an event (preview, all preselected, optional category) and creates linked events in one transaction. Albums without a date suffix are never offered. - Editorials now see all past events; the past list is collapsible and a click in the month view opens it. - Release notes 2.4.1 seeded (migration 0010). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
cba70310f9
commit
8748cc1098
16 files changed
+3025
-78
No files matched your search
@@ -27,7 +27,7 @@ Kalender/Selbstbedienung/Sortierung/Beschreibung: `2.1.0`,
|
||||
Dateiname-Suche: `2.1.1`, Statistik/Collab/Rechnungsversand: `2.2.0`,
|
||||
Quartalsabrechnung + Sakani-Formulare: `2.2.1`, Versionshistorie: `2.2.2`,
|
||||
Kategorien/Vormerken/Monatskalender/Dashboard: `2.3.0`,
|
||||
Mehrfach-Download/Toasts/Sakani-Feinschliff: `2.4.0`).
|
||||
Mehrfach-Download/Toasts/Sakani-Feinschliff: `2.4.0`, Album-Import im Kalender: `2.4.1`).
|
||||
|
||||
## Sicherheit (bei jeder Änderung mitprüfen)
|
||||
|
||||
|
||||
@@ -100,4 +100,5 @@ Redaktionen können Bilder durchsuchen, einen Leuchtkasten verwenden, Bilder her
|
||||
- **Albenübersicht:** Blog-Listing-Optik (randloses 3:2-Cover, Anzahl, Titel, Beschreibung); Cover ist dekorativ (`alt=""`), der Titel im Link benennt es. Skeletons hinter Covern/Fotokacheln und in `loading.tsx`.
|
||||
- **Registrierung:** `RegistrationSteps` (Sakani `Stepper`, mobil vertikal). Die Bestätigungsmail führt auf `/registrieren/bestaetigt?schritt=freigabe` (Schritt 3), das Formular auf die Seite ohne Parameter (Schritt 2).
|
||||
- **Redaktionen:** `EditorialsTable` (Client, Sakani `Table` + Suche + Statusfilter; "Alle" ohne Archivierte). **Audit:** Ereignis als Auswahl der vorhandenen Typen (`selectDistinct`), deutsche Bezeichnungen (`EVENT_LABELS` in `src/app/admin/audit/page.tsx`, neue Audit-Typen dort ergänzen), Details aufklappbar.
|
||||
- **Album-Import (2.4.1):** `/admin/kalender` → "Ältere Alben übernehmen". `parseAlbumEventName` (`event-albums.ts`) liest `Titel | TT.MM.JJJJ`; `listImportableAlbums` bietet nur datierte Alben ohne passenden Termin an (private Alben ohne Datum nie), `importAlbums` rechnet die Liste serverseitig neu, legt Termine mit expliziter `immich_album_id` in einer Transaktion an (max. 500), optional mit Kategorie, Audit `calendar_events_imported`. Redaktionen sehen seitdem ALLE vergangenen Termine (kein 30-Tage-Fenster mehr); die Liste "Vergangene Termine" ist einklappbar, ein Klick im Monatskalender öffnet sie.
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
-- Custom SQL migration file, put your code below! --
|
||||
INSERT INTO "release_notes" ("version", "audience", "body", "created_by_user_id")
|
||||
VALUES
|
||||
('2.4.1', 'admin', 'Ältere Alben übernehmen: Unter Kalender zeigt „Alben aus Immich anzeigen“ alle Alben im Format „Titel | TT.MM.JJJJ“, die noch keinen Termin haben. Auswählen, optional eine Kategorie setzen und übernehmen; Titel und Datum kommen aus dem Albumnamen.', NULL),
|
||||
('2.4.1', 'editorial', 'Im Kalender stehen jetzt auch ältere Spiele. Sie können sie wie neue mit „Zu meinen Alben hinzufügen“ freischalten.', NULL)
|
||||
ON CONFLICT ("version", "audience") DO NOTHING;
|
||||
File diff suppressed because it is too large.
Load diff
@@ -71,6 +71,13 @@
|
||||
"when": 1796079496182,
|
||||
"tag": "0009_release_notes_2_4_0",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 10,
|
||||
"version": "7",
|
||||
"when": 1796081618450,
|
||||
"tag": "0010_release_notes_2_4_1",
|
||||
"breakpoints": true
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
"use client";
|
||||
|
||||
import { useMemo, useState, useTransition } from "react";
|
||||
import { Badge, Button, Checkbox } from "@sakaniui/react";
|
||||
import { IconDownload } from "@sakaniui/react/icons";
|
||||
|
||||
import { notifyResult } from "@/components/ui/feedback";
|
||||
import { Card, FormSelect } from "@/components/ui/sakani";
|
||||
import type { ImportableAlbum } from "@/modules/calendar/service";
|
||||
|
||||
import type { CalendarActionResult } from "./actions";
|
||||
|
||||
const dateFormat = new Intl.DateTimeFormat("de-DE", { dateStyle: "medium", timeZone: "UTC" });
|
||||
|
||||
/**
|
||||
* Older Immich albums ("Titel | TT.MM.JJJJ") without an event: preview with
|
||||
* everything preselected, untick what should stay out, pick a category.
|
||||
*/
|
||||
export function AlbumImport({
|
||||
albums,
|
||||
categories,
|
||||
action,
|
||||
}: Readonly<{
|
||||
albums: ImportableAlbum[];
|
||||
categories: Array<{ id: string; name: string }>;
|
||||
action: (state: CalendarActionResult, formData: FormData) => Promise<CalendarActionResult>;
|
||||
}>) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const [excluded, setExcluded] = useState<ReadonlySet<string>>(new Set());
|
||||
const [pending, startTransition] = useTransition();
|
||||
const selected = useMemo(() => albums.filter((album) => !excluded.has(album.albumId)), [albums, excluded]);
|
||||
|
||||
const toggle = (albumId: string, checked: boolean) =>
|
||||
setExcluded((previous) => {
|
||||
const next = new Set(previous);
|
||||
if (checked) next.delete(albumId);
|
||||
else next.add(albumId);
|
||||
return next;
|
||||
});
|
||||
|
||||
const submit = (formData: FormData) => {
|
||||
for (const album of selected) formData.append("albumId", album.albumId);
|
||||
startTransition(async () => {
|
||||
const result = await action({ ok: true, message: "" }, formData);
|
||||
notifyResult(result);
|
||||
if (result.ok) {
|
||||
setOpen(false);
|
||||
setExcluded(new Set());
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<Card
|
||||
description={
|
||||
albums.length === 0
|
||||
? "Alle Alben im Format „Titel | TT.MM.JJJJ“ haben bereits einen Termin."
|
||||
: `${albums.length} ${albums.length === 1 ? "Album" : "Alben"} im Format „Titel | TT.MM.JJJJ“ ohne Termin gefunden. Titel und Datum werden aus dem Albumnamen übernommen.`
|
||||
}
|
||||
title="Ältere Alben übernehmen"
|
||||
>
|
||||
{albums.length > 0 && !open ? (
|
||||
<div>
|
||||
<Button leftIcon={<IconDownload size={16} />} onClick={() => setOpen(true)} type="button" variant="secondary">
|
||||
Alben aus Immich anzeigen
|
||||
</Button>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{open ? (
|
||||
<form action={submit} className="flex flex-col gap-4">
|
||||
<div className="flex flex-wrap items-center gap-3 text-sm">
|
||||
<Button onClick={() => setExcluded(new Set())} size="sm" type="button" variant="ghost">
|
||||
Alle auswählen
|
||||
</Button>
|
||||
<Button
|
||||
onClick={() => setExcluded(new Set(albums.map((album) => album.albumId)))}
|
||||
size="sm"
|
||||
type="button"
|
||||
variant="ghost"
|
||||
>
|
||||
Keine
|
||||
</Button>
|
||||
<Badge variant="info">{selected.length} ausgewählt</Badge>
|
||||
</div>
|
||||
<ul className="flex max-h-96 flex-col divide-y divide-[var(--color-border-subtle)] overflow-y-auto rounded-[var(--radius-xl)] border border-[var(--color-border-subtle)]">
|
||||
{albums.map((album) => (
|
||||
<li className="flex items-center justify-between gap-4 px-3 py-2.5" key={album.albumId}>
|
||||
<Checkbox
|
||||
checked={!excluded.has(album.albumId)}
|
||||
description={`${dateFormat.format(new Date(`${album.eventDate}T00:00:00Z`))} · ${album.assetCount} Fotos`}
|
||||
disabled={pending}
|
||||
label={album.title}
|
||||
onChange={(event) => toggle(album.albumId, event.target.checked)}
|
||||
/>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
<div className="sm:max-w-xs">
|
||||
<FormSelect
|
||||
label="Kategorie für alle übernommenen Termine"
|
||||
name="categoryId"
|
||||
options={[
|
||||
{ label: "Ohne Kategorie", value: "" },
|
||||
...categories.map((category) => ({ label: category.name, value: category.id })),
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex flex-wrap gap-3">
|
||||
<Button disabled={pending || selected.length === 0} loading={pending} type="submit">
|
||||
{selected.length === 1 ? "1 Termin übernehmen" : `${selected.length} Termine übernehmen`}
|
||||
</Button>
|
||||
<Button disabled={pending} onClick={() => setOpen(false)} type="button" variant="ghost">
|
||||
Abbrechen
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
) : null}
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -46,6 +46,28 @@ export async function createCalendarEventAction(
|
||||
};
|
||||
}
|
||||
|
||||
/** Imports selected older Immich albums as calendar events. */
|
||||
export async function importAlbumsAction(
|
||||
_prevState: CalendarActionResult,
|
||||
formData: FormData,
|
||||
): Promise<CalendarActionResult> {
|
||||
const principal = await requireAdmin(new Headers(await headers()));
|
||||
const albumIds = formData.getAll("albumId").filter((value): value is string => typeof value === "string");
|
||||
const categoryId = formData.get("categoryId");
|
||||
try {
|
||||
const { imported } = await calendarService.importAlbums({
|
||||
albumIds,
|
||||
categoryId: typeof categoryId === "string" && categoryId ? categoryId : null,
|
||||
adminUserId: principal.userId,
|
||||
});
|
||||
revalidatePath("/admin/kalender");
|
||||
revalidatePath("/redaktion/kalender");
|
||||
return { ok: true, message: imported === 1 ? "1 Termin übernommen." : `${imported} Termine übernommen.` };
|
||||
} catch (error) {
|
||||
return { ok: false, message: calendarErrorMessage(error) };
|
||||
}
|
||||
}
|
||||
|
||||
export async function deleteCalendarEventAction(
|
||||
_prevState: CalendarActionResult,
|
||||
formData: FormData,
|
||||
@@ -75,6 +97,7 @@ function calendarErrorMessage(error: unknown): string {
|
||||
INVALID_EVENT_DATE: "Bitte wählen Sie ein gültiges Datum.",
|
||||
INVALID_ALBUM: "Das gewählte Album existiert nicht mehr in Immich.",
|
||||
INVALID_CATEGORY: "Die gewählte Kategorie existiert nicht mehr.",
|
||||
NOTHING_TO_IMPORT: "Bitte mindestens ein Album auswählen, das noch keinen Termin hat.",
|
||||
EVENT_NOT_FOUND: "Dieser Termin existiert nicht mehr.",
|
||||
RESERVATION_NOT_FOUND: "Diese Vormerkung existiert nicht mehr.",
|
||||
IMMICH_UNAVAILABLE: "Immich ist gerade nicht erreichbar. Bitte später erneut versuchen.",
|
||||
|
||||
@@ -13,14 +13,16 @@ import { immichClient } from "@/modules/immich/client";
|
||||
import { requireAdminPage } from "../access";
|
||||
import { CalendarEventForm } from "./CalendarEventForm";
|
||||
import { DeleteCalendarEventButton } from "./DeleteCalendarEventButton";
|
||||
import { createCalendarEventAction, deleteCalendarEventAction } from "./actions";
|
||||
import { AlbumImport } from "./AlbumImport";
|
||||
import { createCalendarEventAction, deleteCalendarEventAction, importAlbumsAction } from "./actions";
|
||||
|
||||
export default async function AdminCalendarPage() {
|
||||
await requireAdminPage();
|
||||
const [{ events, immichUnavailable }, albums, categories] = await Promise.all([
|
||||
const [{ events, immichUnavailable }, albums, categories, importable] = await Promise.all([
|
||||
calendarService.listAdminEvents(),
|
||||
immichClient.listAlbums().catch(() => []),
|
||||
categoryService.listCategories(),
|
||||
calendarService.listImportableAlbums(),
|
||||
]);
|
||||
const today = isoDateInBerlin(new Date());
|
||||
|
||||
@@ -43,6 +45,14 @@ export default async function AdminCalendarPage() {
|
||||
defaultEventDate={today}
|
||||
/>
|
||||
|
||||
{importable.immichUnavailable ? null : (
|
||||
<AlbumImport
|
||||
action={importAlbumsAction}
|
||||
albums={importable.albums}
|
||||
categories={categories.map((category) => ({ id: category.id, name: category.name }))}
|
||||
/>
|
||||
)}
|
||||
|
||||
{immichUnavailable ? (
|
||||
<Alert
|
||||
color="warning"
|
||||
|
||||
@@ -72,6 +72,7 @@ function calendarErrorMessage(error: unknown): string {
|
||||
INVALID_EVENT_DATE: "Ungültiger Termin.",
|
||||
INVALID_ALBUM: "Ungültiger Termin.",
|
||||
INVALID_CATEGORY: "Ungültiger Termin.",
|
||||
NOTHING_TO_IMPORT: "Ungültiger Termin.",
|
||||
EVENT_NOT_FOUND: "Dieser Termin existiert nicht mehr.",
|
||||
RESERVATION_NOT_FOUND: "Diese Vormerkung gibt es nicht mehr. Das Album ist vermutlich schon freigeschaltet.",
|
||||
IMMICH_UNAVAILABLE: "Das Bildarchiv ist gerade nicht erreichbar. Bitte später erneut versuchen.",
|
||||
|
||||
@@ -4,7 +4,7 @@ import { PageHeader } from "@/components/ui/page-header";
|
||||
import { Alert, Badge, Card, EmptyState } from "@/components/ui/sakani";
|
||||
import { formatIsoDateGerman, isoDateInBerlin } from "@/modules/announcements/service";
|
||||
import { categoryService } from "@/modules/calendar/categories";
|
||||
import { calendarService } from "@/modules/calendar/service";
|
||||
import { calendarService, type EditorialCalendarEvent } from "@/modules/calendar/service";
|
||||
|
||||
import { requireEditorial } from "../access";
|
||||
import { EventAccessAction } from "./EventAccessAction";
|
||||
@@ -13,7 +13,7 @@ import { reserveEventAction, unreserveEventAction } from "./actions";
|
||||
export default async function EditorialCalendarPage() {
|
||||
const principal = await requireEditorial();
|
||||
const [{ events, immichUnavailable }, categories] = await Promise.all([
|
||||
calendarService.listEditorialEvents(principal.editorialId, new Date()),
|
||||
calendarService.listEditorialEvents(principal.editorialId),
|
||||
categoryService.listCategories(),
|
||||
]);
|
||||
const today = isoDateInBerlin(new Date());
|
||||
@@ -59,53 +59,68 @@ export default async function EditorialCalendarPage() {
|
||||
/>
|
||||
</Card>
|
||||
|
||||
{[
|
||||
{ id: "upcoming", title: "Kommende Termine", list: upcoming },
|
||||
{ id: "past", title: "Vergangene Termine", list: past },
|
||||
]
|
||||
.filter((group) => group.list.length > 0)
|
||||
.map((group) => (
|
||||
<section aria-labelledby={`calendar-${group.id}`} className="flex flex-col gap-3" key={group.id}>
|
||||
<h2 className="text-xl font-semibold" id={`calendar-${group.id}`}>
|
||||
{group.title}
|
||||
</h2>
|
||||
<ul className="flex flex-col gap-3">
|
||||
{group.list.map((event) => (
|
||||
<li
|
||||
className="flex flex-col justify-between gap-4 rounded-xl border border-[var(--color-border-subtle)] bg-[var(--color-bg-surface)] p-4 outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-border-focus)] lg:flex-row lg:items-center"
|
||||
id={`termin-${event.id}`}
|
||||
key={event.id}
|
||||
tabIndex={-1}
|
||||
>
|
||||
<div className="flex min-w-0 flex-col gap-1">
|
||||
<p className="flex flex-wrap items-center gap-2 font-semibold">
|
||||
{event.title}
|
||||
{event.eventDate < today ? <Badge>vorbei</Badge> : null}
|
||||
</p>
|
||||
<p className="flex flex-wrap items-center gap-x-2 gap-y-1 text-xs text-[var(--color-fg-muted)]">
|
||||
<span>{formatIsoDateGerman(event.eventDate)}</span>
|
||||
{event.category ? (
|
||||
<span className="flex items-center gap-1.5">
|
||||
· <CategoryDot color={event.category.color} /> {event.category.name}
|
||||
</span>
|
||||
) : null}
|
||||
{event.album ? null : <span>· Album noch nicht angelegt</span>}
|
||||
</p>
|
||||
</div>
|
||||
<EventAccessAction
|
||||
access={event.access}
|
||||
albumId={event.album?.id ?? null}
|
||||
eventId={event.id}
|
||||
reserveAction={reserveEventAction}
|
||||
unreserveAction={unreserveEventAction}
|
||||
/>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</section>
|
||||
))}
|
||||
{upcoming.length > 0 ? (
|
||||
<section aria-labelledby="calendar-upcoming" className="flex flex-col gap-3">
|
||||
<h2 className="text-xl font-semibold" id="calendar-upcoming">
|
||||
Kommende Termine
|
||||
</h2>
|
||||
<EventList events={upcoming} today={today} />
|
||||
</section>
|
||||
) : null}
|
||||
{past.length > 0 ? (
|
||||
// Imported older albums can make this long; the month view shows
|
||||
// them too, and a click there opens this section (event-month.tsx).
|
||||
<details className="group" open={upcoming.length === 0}>
|
||||
<summary className="flex cursor-pointer list-none items-center gap-2 text-xl font-semibold">
|
||||
<span aria-hidden="true" className="transition-transform group-open:rotate-90">›</span>
|
||||
Vergangene Termine ({past.length})
|
||||
</summary>
|
||||
<div className="mt-3">
|
||||
<EventList events={past} today={today} />
|
||||
</div>
|
||||
</details>
|
||||
) : null}
|
||||
</>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
function EventList({ events, today }: Readonly<{ events: EditorialCalendarEvent[]; today: string }>) {
|
||||
return (
|
||||
<ul className="flex flex-col gap-3">
|
||||
{events.map((event) => (
|
||||
<li
|
||||
className="flex flex-col justify-between gap-4 rounded-xl border border-[var(--color-border-subtle)] bg-[var(--color-bg-surface)] p-4 outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-border-focus)] lg:flex-row lg:items-center"
|
||||
id={`termin-${event.id}`}
|
||||
key={event.id}
|
||||
tabIndex={-1}
|
||||
>
|
||||
<div className="flex min-w-0 flex-col gap-1">
|
||||
<p className="flex flex-wrap items-center gap-2 font-semibold">
|
||||
{event.title}
|
||||
{event.eventDate < today ? <Badge>vorbei</Badge> : null}
|
||||
</p>
|
||||
<p className="flex flex-wrap items-center gap-x-2 gap-y-1 text-xs text-[var(--color-fg-muted)]">
|
||||
<span>{formatIsoDateGerman(event.eventDate)}</span>
|
||||
{event.category ? (
|
||||
<span className="flex items-center gap-1.5">
|
||||
· <CategoryDot color={event.category.color} /> {event.category.name}
|
||||
</span>
|
||||
) : null}
|
||||
{event.album ? null : <span>· Album noch nicht angelegt</span>}
|
||||
</p>
|
||||
</div>
|
||||
<EventAccessAction
|
||||
access={event.access}
|
||||
albumId={event.album?.id ?? null}
|
||||
eventId={event.id}
|
||||
reserveAction={reserveEventAction}
|
||||
unreserveAction={unreserveEventAction}
|
||||
/>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -50,6 +50,8 @@ export function EventMonth({ events }: Readonly<{ events: MonthEvent[] }>) {
|
||||
onDateChange={setMonth}
|
||||
onEventClick={(event) => {
|
||||
const target = document.getElementById(`termin-${event.id}`);
|
||||
const section = target?.closest("details");
|
||||
if (section) section.open = true;
|
||||
target?.scrollIntoView({ behavior: "smooth", block: "center" });
|
||||
target?.focus({ preventScroll: true });
|
||||
}}
|
||||
|
||||
@@ -9,16 +9,18 @@ import { IconCheck } from "@sakaniui/react/icons";
|
||||
// then sees the popup once more. ponytail: only the latest release is kept;
|
||||
// add a history list when users ask for older notes.
|
||||
export const RELEASE = {
|
||||
version: "2.4",
|
||||
version: "2.4.1",
|
||||
title: "Mehrfach-Download und neuer Feinschliff",
|
||||
notes: {
|
||||
redaktion: [
|
||||
"ZIP-Download vom Merkzettel: Alle Bilder laufen als neue Nutzung. Nur bei Bildern, die Sie schon geladen haben, wählen Sie zwischen neuer Nutzung und kostenloser Wiederholung.",
|
||||
"Albenübersicht mit großen Vorschaubildern, Seitenzahlen unter den Fotos und Ladeanimationen.",
|
||||
"Bestätigungen und Hinweise erscheinen als kurze Meldung unten rechts.",
|
||||
"Im Kalender stehen jetzt auch ältere Spiele; Sie können sie wie neue zu Ihren Alben hinzufügen.",
|
||||
"Seit 2.3: Kalender als Monatsansicht mit „Zu meinen Alben hinzufügen“.",
|
||||
],
|
||||
admin: [
|
||||
"Ältere Alben übernehmen: Im Kalender zeigt „Alben aus Immich anzeigen“ alle Alben im Format „Titel | TT.MM.JJJJ“ ohne Termin; auswählen, Kategorie setzen, übernehmen.",
|
||||
"Speichern und Ändern bestätigt das Portal mit einer kurzen Meldung; Fehler bei Abrechnungen sind verständlich formuliert.",
|
||||
"Redaktionen als Tabelle mit Suche, Statusfilter und offenen Beträgen.",
|
||||
"Audit-Protokoll mit Ereignisauswahl, lesbaren Bezeichnungen und aufklappbaren Details.",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { expect, test } from "vitest";
|
||||
|
||||
import { expectedAlbumNames, germanEventDate, matchEventAlbum } from "./event-albums";
|
||||
import { expectedAlbumNames, germanEventDate, matchEventAlbum, parseAlbumEventName } from "./event-albums";
|
||||
|
||||
const matchAlbum = { id: "2222222b-2222-4222-8222-22222222222b", albumName: "Hamburger SV - VfL Wolfsburg | 12.09.2026" };
|
||||
const eventAlbum = { id: "3333333c-3333-4333-8333-33333333333c", albumName: "DFB-Pokal Finale" };
|
||||
@@ -55,3 +55,15 @@ test("matchEventAlbum falls back to name matching when the explicit album is gon
|
||||
};
|
||||
expect(matchEventAlbum(event, [matchAlbum])).toEqual(matchAlbum);
|
||||
});
|
||||
|
||||
test("parseAlbumEventName reads title and date from the album name", () => {
|
||||
expect(parseAlbumEventName("Hamburger SV - VfL Wolfsburg | 12.12.2026")).toEqual({
|
||||
title: "Hamburger SV - VfL Wolfsburg",
|
||||
eventDate: "2026-12-12",
|
||||
});
|
||||
expect(parseAlbumEventName(" Finale|01.02.2024 ")).toEqual({ title: "Finale", eventDate: "2024-02-01" });
|
||||
expect(parseAlbumEventName("Privaturlaub Sylt")).toBeNull();
|
||||
expect(parseAlbumEventName("Kaputt | 31.02.2026")).toBeNull();
|
||||
expect(parseAlbumEventName(" | 12.12.2026")).toBeNull();
|
||||
});
|
||||
|
||||
@@ -44,3 +44,21 @@ export function matchEventAlbum<T extends LinkableAlbum>(
|
||||
const names = new Set(expectedAlbumNames(event.title, event.eventDate));
|
||||
return albums.find((album) => names.has(album.albumName.trim())) ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads "{Titel} | {TT.MM.JJJJ}" back into an event (album import). Albums
|
||||
* without a valid date suffix (e.g. private ones) return null and are never
|
||||
* offered for import.
|
||||
*/
|
||||
export function parseAlbumEventName(albumName: string): { title: string; eventDate: string } | null {
|
||||
const match = /^(.+?)\s*\|\s*(\d{2})\.(\d{2})\.(\d{4})\s*$/.exec(albumName.trim());
|
||||
if (!match) return null;
|
||||
const [, rawTitle, day, month, year] = match;
|
||||
const date = new Date(Date.UTC(Number(year), Number(month) - 1, Number(day)));
|
||||
if (date.getUTCFullYear() !== Number(year) || date.getUTCMonth() !== Number(month) - 1 || date.getUTCDate() !== Number(day)) {
|
||||
return null;
|
||||
}
|
||||
const title = rawTitle.trim();
|
||||
return title ? { title, eventDate: `${year}-${month}-${day}` } : null;
|
||||
}
|
||||
|
||||
@@ -63,6 +63,19 @@ function setup(options: {
|
||||
events.push(created);
|
||||
return created;
|
||||
},
|
||||
async insertEvents(rows) {
|
||||
for (const [index, row] of rows.entries()) {
|
||||
events.push(
|
||||
event({
|
||||
id: `9999999${index}-9999-4999-8999-999999999999`,
|
||||
title: row.title,
|
||||
eventDate: row.eventDate,
|
||||
immichAlbumId: row.immichAlbumId,
|
||||
}),
|
||||
);
|
||||
}
|
||||
return rows.length;
|
||||
},
|
||||
async getEvent(id) {
|
||||
return events.find((candidate) => candidate.id === id) ?? null;
|
||||
},
|
||||
@@ -271,7 +284,7 @@ test("matchesAutoRule matches keywords inside title or album name, ignoring case
|
||||
expect(matchesAutoRule([" "], ["anything"])).toBe(false);
|
||||
});
|
||||
|
||||
test("listEditorialEvents derives access per event and keeps the past window", async () => {
|
||||
test("listEditorialEvents derives access per event and keeps past events", async () => {
|
||||
const oldEvent = event({ id: "7777777a-7777-4777-8777-77777777777a", eventDate: "2026-01-01" });
|
||||
const futureEvent = event({ id: "8888888b-8888-4888-8888-88888888888b", title: "Volleyball Finale", eventDate: "2026-09-20" });
|
||||
const { service } = setup({
|
||||
@@ -279,25 +292,20 @@ test("listEditorialEvents derives access per event and keeps the past window", a
|
||||
grantSources: [{ immichAlbumId: albumUuid, source: "auto_rule" }],
|
||||
reservations: [{ eventId: futureEvent.id, editorialId: editorialUuid, grantedAt: null }],
|
||||
});
|
||||
const { events, immichUnavailable } = await service.listEditorialEvents(
|
||||
editorialUuid,
|
||||
new Date("2026-09-10T08:00:00.000Z"),
|
||||
);
|
||||
const { events, immichUnavailable } = await service.listEditorialEvents(editorialUuid);
|
||||
expect(immichUnavailable).toBe(false);
|
||||
// The January event is outside the 30-day past window.
|
||||
// Older events stay listed (imported albums remain reservable).
|
||||
expect(events.map((row) => [row.id, row.access])).toEqual([
|
||||
[oldEvent.id, "available"],
|
||||
[eventUuid, "auto_granted"],
|
||||
[futureEvent.id, "reserved"],
|
||||
]);
|
||||
expect(events[0].album).toEqual({ id: albumUuid, albumName: matchAlbum.albumName });
|
||||
expect(events.find((row) => row.id === eventUuid)!.album).toEqual({ id: albumUuid, albumName: matchAlbum.albumName });
|
||||
});
|
||||
|
||||
test("listEditorialEvents degrades gracefully when Immich is down", async () => {
|
||||
const { service } = setup({ albums: null, keywords: ["Wolfsburg"] });
|
||||
const { events, immichUnavailable } = await service.listEditorialEvents(
|
||||
editorialUuid,
|
||||
new Date("2026-09-10T08:00:00.000Z"),
|
||||
);
|
||||
const { events, immichUnavailable } = await service.listEditorialEvents(editorialUuid);
|
||||
expect(immichUnavailable).toBe(true);
|
||||
expect(events[0].album).toBeNull();
|
||||
// The keyword still matches the title, so the auto rule will deliver the album.
|
||||
@@ -309,3 +317,51 @@ test("listAdminEvents attaches reservations per event", async () => {
|
||||
const { events } = await service.listAdminEvents();
|
||||
expect(events[0].reservations).toEqual([{ editorialId: editorialUuid, editorialName: "Kicker Daily", grantedAt: null }]);
|
||||
});
|
||||
|
||||
const olderAlbum: ImmichAlbumSummary = {
|
||||
id: "aaaaaaa1-aaaa-4aaa-8aaa-aaaaaaaaaaa1",
|
||||
albumName: "VfB Lübeck - Holstein Kiel | 03.05.2025",
|
||||
description: null,
|
||||
albumThumbnailAssetId: null,
|
||||
assetCount: 12,
|
||||
};
|
||||
const privateAlbum: ImmichAlbumSummary = { ...olderAlbum, id: "bbbbbbb2-bbbb-4bbb-8bbb-bbbbbbbbbbb2", albumName: "Privaturlaub Sylt" };
|
||||
|
||||
test("listImportableAlbums offers dated albums without an event, newest first", async () => {
|
||||
const newer = { ...olderAlbum, id: "ccccccc3-cccc-4ccc-8ccc-ccccccccccc3", albumName: "Pokalfinale | 20.05.2026" };
|
||||
const { service } = setup({ albums: [matchAlbum, olderAlbum, privateAlbum, newer] });
|
||||
const { albums } = await service.listImportableAlbums();
|
||||
// matchAlbum already belongs to the default event; the private album has no date.
|
||||
expect(albums.map((album) => [album.title, album.eventDate])).toEqual([
|
||||
["Pokalfinale", "2026-05-20"],
|
||||
["VfB Lübeck - Holstein Kiel", "2025-05-03"],
|
||||
]);
|
||||
});
|
||||
|
||||
test("importAlbums creates linked events only for importable albums and audits", async () => {
|
||||
const { service, events, audit } = setup({ albums: [matchAlbum, olderAlbum, privateAlbum] });
|
||||
const result = await service.importAlbums({
|
||||
albumIds: [olderAlbum.id, privateAlbum.id, matchAlbum.id],
|
||||
categoryId: null,
|
||||
adminUserId: userUuid,
|
||||
});
|
||||
expect(result).toEqual({ imported: 1 });
|
||||
expect(events.at(-1)).toMatchObject({ title: "VfB Lübeck - Holstein Kiel", eventDate: "2025-05-03", immichAlbumId: olderAlbum.id });
|
||||
expect(audit.writeAudit).toHaveBeenCalledWith(expect.objectContaining({ type: "calendar_events_imported" }));
|
||||
// A second run finds nothing left to import.
|
||||
await expect(
|
||||
service.importAlbums({ albumIds: [olderAlbum.id], categoryId: null, adminUserId: userUuid }),
|
||||
).rejects.toMatchObject({ code: "NOTHING_TO_IMPORT" });
|
||||
});
|
||||
|
||||
test("importAlbums rejects bad categories and an unreachable Immich", async () => {
|
||||
const { service } = setup({ albums: [olderAlbum] });
|
||||
await expect(
|
||||
service.importAlbums({ albumIds: [olderAlbum.id], categoryId: "nope", adminUserId: userUuid }),
|
||||
).rejects.toMatchObject({ code: "INVALID_CATEGORY" });
|
||||
const down = setup({ albums: null });
|
||||
await expect(
|
||||
down.service.importAlbums({ albumIds: [olderAlbum.id], categoryId: null, adminUserId: userUuid }),
|
||||
).rejects.toMatchObject({ code: "IMMICH_UNAVAILABLE" });
|
||||
});
|
||||
|
||||
+103
-15
@@ -14,11 +14,7 @@ import {
|
||||
} from "@/db/schema";
|
||||
import type * as schema from "@/db/schema";
|
||||
import { albumGrantService, AlbumGrantError } from "@/modules/albums/grants";
|
||||
import {
|
||||
isoDateInBerlin,
|
||||
isValidIsoDate,
|
||||
shiftIsoDate,
|
||||
} from "@/modules/announcements/service";
|
||||
import { isValidIsoDate } from "@/modules/announcements/service";
|
||||
import { writeAudit } from "@/modules/audit/write";
|
||||
import { immichClient } from "@/modules/immich/client";
|
||||
import type { ImmichClient } from "@/modules/immich/types";
|
||||
@@ -31,11 +27,11 @@ import {
|
||||
|
||||
import type { EventCategory } from "./categories";
|
||||
import type { CategoryColor } from "./colors";
|
||||
import { matchEventAlbum } from "./event-albums";
|
||||
import { matchEventAlbum, parseAlbumEventName } from "./event-albums";
|
||||
|
||||
export const CALENDAR_EVENT_MAX_TITLE_LENGTH = 200;
|
||||
/** Past events stay visible (and reservable) for this many days. */
|
||||
export const CALENDAR_PAST_DAYS = 30;
|
||||
/** Upper bound for one album import, so one click cannot create thousands of rows. */
|
||||
export const CALENDAR_IMPORT_MAX = 500;
|
||||
|
||||
export type CalendarEvent = {
|
||||
id: string;
|
||||
@@ -60,6 +56,9 @@ export type EditorialCalendarEvent = CalendarEvent & {
|
||||
access: EventAccessState;
|
||||
};
|
||||
|
||||
/** An Immich album named "{Titel} | {TT.MM.JJJJ}" that has no calendar event yet. */
|
||||
export type ImportableAlbum = { albumId: string; albumName: string; title: string; eventDate: string; assetCount: number };
|
||||
|
||||
export type AdminCalendarEvent = CalendarEvent & {
|
||||
album: LinkedAlbum | null;
|
||||
reservations: Array<{ editorialId: string; editorialName: string; grantedAt: Date | null }>;
|
||||
@@ -70,6 +69,7 @@ export type CalendarError =
|
||||
| "INVALID_EVENT_DATE"
|
||||
| "INVALID_ALBUM"
|
||||
| "INVALID_CATEGORY"
|
||||
| "NOTHING_TO_IMPORT"
|
||||
| "EVENT_NOT_FOUND"
|
||||
| "RESERVATION_NOT_FOUND"
|
||||
| "IMMICH_UNAVAILABLE"
|
||||
@@ -115,6 +115,9 @@ export type CalendarRepository = {
|
||||
categoryId: string | null;
|
||||
adminUserId: string;
|
||||
}): Promise<CalendarEvent>;
|
||||
insertEvents(
|
||||
rows: Array<{ title: string; eventDate: string; immichAlbumId: string; categoryId: string | null; adminUserId: string }>,
|
||||
): Promise<number>;
|
||||
getEvent(id: string): Promise<CalendarEvent | null>;
|
||||
listEvents(): Promise<CalendarEvent[]>;
|
||||
deleteEvent(id: string): Promise<CalendarEvent | null>;
|
||||
@@ -180,6 +183,28 @@ export function createCalendarService({
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Albums named "{Titel} | {TT.MM.JJJJ}" without a calendar event yet,
|
||||
* newest first. Albums without a date suffix never appear here.
|
||||
*/
|
||||
async function listImportableAlbums(): Promise<{ albums: ImportableAlbum[]; immichUnavailable: boolean }> {
|
||||
const [albums, events] = await Promise.all([loadAlbumsOrNull(), repository.listEvents()]);
|
||||
if (!albums) return { albums: [], immichUnavailable: true };
|
||||
const linked = new Set(
|
||||
events
|
||||
.map((event) => matchEventAlbum(event, albums)?.id.toLowerCase())
|
||||
.filter((id): id is string => Boolean(id)),
|
||||
);
|
||||
const importable = albums.flatMap((album) => {
|
||||
if (linked.has(album.id.toLowerCase())) return [];
|
||||
const parsed = parseAlbumEventName(album.albumName);
|
||||
if (!parsed || parsed.title.length > CALENDAR_EVENT_MAX_TITLE_LENGTH) return [];
|
||||
return [{ albumId: album.id, albumName: album.albumName, assetCount: album.assetCount, ...parsed }];
|
||||
});
|
||||
importable.sort((a, b) => b.eventDate.localeCompare(a.eventDate) || a.title.localeCompare(b.title));
|
||||
return { albums: importable, immichUnavailable: false };
|
||||
}
|
||||
|
||||
return {
|
||||
async createEvent(input: {
|
||||
title: string;
|
||||
@@ -278,13 +303,13 @@ export function createCalendarService({
|
||||
});
|
||||
},
|
||||
|
||||
/** Editorial calendar: upcoming events plus the recent past window. */
|
||||
/**
|
||||
* Editorial calendar: every event, past ones included (imported older
|
||||
* albums stay reservable).
|
||||
*/
|
||||
async listEditorialEvents(
|
||||
editorialId: string,
|
||||
now: Date,
|
||||
): Promise<{ events: EditorialCalendarEvent[]; immichUnavailable: boolean }> {
|
||||
const today = isoDateInBerlin(now);
|
||||
const minDate = shiftIsoDate(today, -CALENDAR_PAST_DAYS);
|
||||
const [allEvents, albums, grantSources, reservations, keywords] = await Promise.all([
|
||||
repository.listEvents(),
|
||||
loadAlbumsOrNull(),
|
||||
@@ -295,9 +320,7 @@ export function createCalendarService({
|
||||
const sourceByAlbum = new Map(grantSources.map((grant) => [grant.immichAlbumId.toLowerCase(), grant.source]));
|
||||
const pending = new Set(reservations.filter((row) => row.grantedAt === null).map((row) => row.eventId));
|
||||
|
||||
const events = allEvents
|
||||
.filter((event) => event.eventDate >= minDate)
|
||||
.map((event) => {
|
||||
const events = allEvents.map((event) => {
|
||||
const album = albums ? matchEventAlbum(event, albums) : null;
|
||||
return {
|
||||
...event,
|
||||
@@ -312,6 +335,53 @@ export function createCalendarService({
|
||||
return { events, immichUnavailable: albums === null };
|
||||
},
|
||||
|
||||
/**
|
||||
* Creates one event per selected album, linked explicitly to it. The
|
||||
* candidate list is recomputed here, so only importable albums count.
|
||||
*/
|
||||
listImportableAlbums,
|
||||
|
||||
async importAlbums(input: {
|
||||
albumIds: string[];
|
||||
categoryId: string | null;
|
||||
adminUserId: string;
|
||||
}): Promise<{ imported: number }> {
|
||||
if (input.categoryId && !UUID_PATTERN.test(input.categoryId)) {
|
||||
throw new CalendarServiceError("INVALID_CATEGORY");
|
||||
}
|
||||
const { albums, immichUnavailable } = await listImportableAlbums();
|
||||
if (immichUnavailable) throw new CalendarServiceError("IMMICH_UNAVAILABLE");
|
||||
const wanted = new Set(input.albumIds.map((id) => id.toLowerCase()));
|
||||
const selected = albums.filter((album) => wanted.has(album.albumId.toLowerCase())).slice(0, CALENDAR_IMPORT_MAX);
|
||||
if (selected.length === 0) throw new CalendarServiceError("NOTHING_TO_IMPORT");
|
||||
|
||||
let imported: number;
|
||||
try {
|
||||
imported = await repository.insertEvents(
|
||||
selected.map((album) => ({
|
||||
title: album.title,
|
||||
eventDate: album.eventDate,
|
||||
immichAlbumId: album.albumId,
|
||||
categoryId: input.categoryId,
|
||||
adminUserId: input.adminUserId,
|
||||
})),
|
||||
);
|
||||
} catch (error) {
|
||||
if (postgresCode(error) === "23503") throw new CalendarServiceError("INVALID_CATEGORY");
|
||||
throw error;
|
||||
}
|
||||
|
||||
await audit.writeAudit({
|
||||
type: "calendar_events_imported",
|
||||
actorUserId: input.adminUserId,
|
||||
actorType: "admin",
|
||||
entityType: "calendar_event",
|
||||
entityId: "import",
|
||||
metadata: { count: imported, categoryId: input.categoryId, albumIds: selected.map((album) => album.albumId) },
|
||||
});
|
||||
return { imported };
|
||||
},
|
||||
|
||||
/** Admin overview: every event with its linked album and all reservations. */
|
||||
async listAdminEvents(): Promise<{ events: AdminCalendarEvent[]; immichUnavailable: boolean }> {
|
||||
const [allEvents, albums, reservations] = await Promise.all([
|
||||
@@ -493,6 +563,24 @@ export function createCalendarRepository(database: NodePgDatabase<typeof schema>
|
||||
return toEvent(created);
|
||||
},
|
||||
|
||||
async insertEvents(rows) {
|
||||
return database.transaction(async (transaction) => {
|
||||
const inserted = await transaction
|
||||
.insert(calendarEvents)
|
||||
.values(
|
||||
rows.map((row) => ({
|
||||
title: row.title,
|
||||
eventDate: row.eventDate,
|
||||
immichAlbumId: row.immichAlbumId,
|
||||
categoryId: row.categoryId,
|
||||
createdByUserId: row.adminUserId,
|
||||
})),
|
||||
)
|
||||
.returning({ id: calendarEvents.id });
|
||||
return inserted.length;
|
||||
});
|
||||
},
|
||||
|
||||
async getEvent(id) {
|
||||
const [row] = await selectEvents().where(eq(calendarEvents.id, id)).limit(1);
|
||||
return row ? toEvent(row) : null;
|
||||
|
||||
Reference in new issue
Block a user