feat(erinnerungen): e-mail, wenn ein wunschlisten-termin naeher rueckt

Ruecken Termin und offene Wuensche zusammen, geht eine Nachricht an den
Besitzer der Liste - standardmaessig 14 Tage vorher, hoechstens einmal
pro Woche je Liste. Ist alles reserviert, bleibt es still: eine
Erinnerung ohne Handlungsbedarf ist nur Laerm.

Der Zeitplan haengt an Next' instrumentation-Hook und prueft stuendlich,
nicht taeglich - so kann ein Neustart keinen Tag ueberspringen, und die
Sperrfrist je Liste verhindert trotzdem Mehrfachversand. Der Zeitstempel
wird erst nach erfolgreichem Versand gesetzt, damit ein Fehlversuch
wiederholt wird.

Ohne SMTP_HOST und SMTP_FROM ist die Funktion komplett aus: kein
Zeitplan, kein Versand, und die Verwaltungsseite erklaert stattdessen,
was in die .env gehoert. Mit Konfiguration gibt es dort Knoepfe fuer
Verbindungstest, Testnachricht und sofortige Pruefung.

12 Tests fuer die Entscheidungsregeln. Einer davon hat einen echten
Fehler gefunden: die Sperrfrist rechnete mit umgedrehtem Vorzeichen und
haette jede Erinnerung dauerhaft unterdrueckt.

Refs Phase 3

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
unknown
2026-09-07 09:22:29 +02:00
co-authored by Claude Opus 5
parent 91fb66b13b
commit 0d08df0bff
17 changed files with 2884 additions and 1 deletions
+13
View File
@@ -32,3 +32,16 @@ TZ=Europe/Berlin
# und Bild werden uebernommen. Ohne Key funktioniert alles manuell weiter. # und Bild werden uebernommen. Ohne Key funktioniert alles manuell weiter.
# Kostenlos anlegen: https://rebrickable.com/api/ (Konto -> Settings -> API) # Kostenlos anlegen: https://rebrickable.com/api/ (Konto -> Settings -> API)
# REBRICKABLE_API_KEY= # REBRICKABLE_API_KEY=
# Optional: Mailversand fuer Erinnerungen an Wunschlisten-Termine. Ohne
# SMTP_HOST und SMTP_FROM sind Erinnerungen komplett aus - alles andere
# funktioniert unveraendert.
# SMTP_HOST=mail.example.de
# SMTP_PORT=587
# SMTP_SECURE=false
# SMTP_USER=bricktrack@example.de
# SMTP_PASSWORD=
# SMTP_FROM=Bricktrack <bricktrack@example.de>
# Wie viele Tage vor dem Termin erinnert wird (Standard: 14).
# REMINDER_DAYS_BEFORE=14
+1
View File
@@ -0,0 +1 @@
ALTER TABLE `wishlist` ADD `last_reminder_at` integer;
File diff suppressed because it is too large Load Diff
+7
View File
@@ -22,6 +22,13 @@
"when": 1788765229376, "when": 1788765229376,
"tag": "0002_aspiring_whiplash", "tag": "0002_aspiring_whiplash",
"breakpoints": true "breakpoints": true
},
{
"idx": 3,
"version": "6",
"when": 1788765478965,
"tag": "0003_powerful_sally_floyd",
"breakpoints": true
} }
] ]
} }
+2
View File
@@ -36,6 +36,7 @@
"lucide-react": "^1.41.0", "lucide-react": "^1.41.0",
"next": "15.5.25", "next": "15.5.25",
"next-themes": "^0.4.6", "next-themes": "^0.4.6",
"nodemailer": "^10.0.0",
"pdfjs-dist": "^6.3.289", "pdfjs-dist": "^6.3.289",
"radix-ui": "^1.6.7", "radix-ui": "^1.6.7",
"react": "19.1.0", "react": "19.1.0",
@@ -52,6 +53,7 @@
"@tailwindcss/postcss": "^4", "@tailwindcss/postcss": "^4",
"@types/better-sqlite3": "^9.6.0", "@types/better-sqlite3": "^9.6.0",
"@types/node": "^20", "@types/node": "^20",
"@types/nodemailer": "^8.0.1",
"@types/react": "^19", "@types/react": "^19",
"@types/react-dom": "^19", "@types/react-dom": "^19",
"dotenv": "^17.4.2", "dotenv": "^17.4.2",
+19
View File
@@ -47,6 +47,9 @@ importers:
next-themes: next-themes:
specifier: ^0.4.6 specifier: ^0.4.6
version: 0.4.6(react-dom@19.1.0(react@19.1.0))(react@19.1.0) version: 0.4.6(react-dom@19.1.0(react@19.1.0))(react@19.1.0)
nodemailer:
specifier: ^10.0.0
version: 10.0.0
pdfjs-dist: pdfjs-dist:
specifier: ^6.3.289 specifier: ^6.3.289
version: 6.3.289 version: 6.3.289
@@ -90,6 +93,9 @@ importers:
'@types/node': '@types/node':
specifier: ^20 specifier: ^20
version: 20.19.43 version: 20.19.43
'@types/nodemailer':
specifier: ^8.0.1
version: 8.0.1
'@types/react': '@types/react':
specifier: ^19 specifier: ^19
version: 19.2.18 version: 19.2.18
@@ -2262,6 +2268,9 @@ packages:
'@types/node@20.19.43': '@types/node@20.19.43':
resolution: {integrity: sha512-6oYBAi5ikg4Pl+kGsoYtawUMBT2zZMCvPNF7pVLnHZfd1zf38DRiWn/gT01RYCdUqkv7Fhr+C9ot4/tb+2sVvA==} resolution: {integrity: sha512-6oYBAi5ikg4Pl+kGsoYtawUMBT2zZMCvPNF7pVLnHZfd1zf38DRiWn/gT01RYCdUqkv7Fhr+C9ot4/tb+2sVvA==}
'@types/nodemailer@8.0.1':
resolution: {integrity: sha512-PxpaInm8V1JQDd4j0ds5HfvWQk8JupS1C0Picb96QJsrrRDjBH+DlK7L4ZdNSqNULhiZRQHc40nLVShaGxXAMw==}
'@types/react-dom@19.2.7': '@types/react-dom@19.2.7':
resolution: {integrity: sha512-I8bPpDLcHBv1qiIiXDCy71Rt8eQDKJP0sMSWJphDdAcdqiJ1sGpZamavoEIRZmYzjia9LuEb2HlYdDpmoENpvQ==} resolution: {integrity: sha512-I8bPpDLcHBv1qiIiXDCy71Rt8eQDKJP0sMSWJphDdAcdqiJ1sGpZamavoEIRZmYzjia9LuEb2HlYdDpmoENpvQ==}
peerDependencies: peerDependencies:
@@ -4135,6 +4144,10 @@ packages:
resolution: {integrity: sha512-YHs7BmmcsdAI5Ozuf8JZo6PT0mv2GIWC9vMfvUC3dp65M8hn7Ux8CPL+2oBI7juNuj9d0ndhTcznq2ODBps9cQ==} resolution: {integrity: sha512-YHs7BmmcsdAI5Ozuf8JZo6PT0mv2GIWC9vMfvUC3dp65M8hn7Ux8CPL+2oBI7juNuj9d0ndhTcznq2ODBps9cQ==}
engines: {node: '>=18'} engines: {node: '>=18'}
nodemailer@10.0.0:
resolution: {integrity: sha512-wdv+hXBg0iIPIOf108FaZyTxqjQpCvQeAJt9pHHTooPy/y3vQtI9eiImM9AIVKR3e/0FeMA1oueNfBjFJcaK+Q==}
engines: {node: '>=20.0.0'}
npm-run-path@4.0.1: npm-run-path@4.0.1:
resolution: {integrity: sha512-S48WzZW777zhNIrn7gxOlISNAqi9ZC/uQFnRdbeIHhZhCA6UqpkOT8T1G7BvfdgP4Er8gF4sUbaS0i7QvIfCWw==} resolution: {integrity: sha512-S48WzZW777zhNIrn7gxOlISNAqi9ZC/uQFnRdbeIHhZhCA6UqpkOT8T1G7BvfdgP4Er8gF4sUbaS0i7QvIfCWw==}
engines: {node: '>=8'} engines: {node: '>=8'}
@@ -6950,6 +6963,10 @@ snapshots:
dependencies: dependencies:
undici-types: 6.21.0 undici-types: 6.21.0
'@types/nodemailer@8.0.1':
dependencies:
'@types/node': 20.19.43
'@types/react-dom@19.2.7(@types/react@19.2.18)': '@types/react-dom@19.2.7(@types/react@19.2.18)':
dependencies: dependencies:
'@types/react': 19.2.18 '@types/react': 19.2.18
@@ -8805,6 +8822,8 @@ snapshots:
node-releases@2.0.54: {} node-releases@2.0.54: {}
nodemailer@10.0.0: {}
npm-run-path@4.0.1: npm-run-path@4.0.1:
dependencies: dependencies:
path-key: 3.1.1 path-key: 3.1.1
@@ -0,0 +1,51 @@
'use server';
import { revalidatePath } from 'next/cache';
import { actionData, actionError, type ActionResult } from '@/lib/action-result';
import { env } from '@/env';
import { sendMail, verifyMailConnection } from '@/lib/mailer';
import { runReminderJob, type ReminderRun } from '@/lib/reminder-job';
import { requireAdmin } from '@/lib/session';
export async function testMailConnection(): Promise<ActionResult> {
await requireAdmin();
const result = await verifyMailConnection();
return result.ok ? { ok: true } : actionError(result.error);
}
export async function sendTestMail(): Promise<ActionResult> {
const admin = await requireAdmin();
if (!env.isMailConfigured) {
return actionError('Es ist kein SMTP-Server konfiguriert.');
}
const result = await sendMail({
to: admin.email,
subject: 'Bricktrack: Testnachricht',
text: [
'Das hat geklappt.',
'',
'Wenn diese Nachricht ankommt, funktionieren auch die Erinnerungen zu',
'Wunschlisten-Terminen.',
'',
env.BASE_URL,
].join('\n'),
});
return result.ok ? { ok: true } : actionError(result.error);
}
/** Runs the check immediately instead of waiting for the next hour. */
export async function runRemindersNow(): Promise<ActionResult<ReminderRun>> {
await requireAdmin();
if (!env.isMailConfigured) {
return actionError('Es ist kein SMTP-Server konfiguriert.');
}
const run = await runReminderJob();
revalidatePath('/verwaltung/erinnerungen');
return actionData(run);
}
@@ -0,0 +1,51 @@
import type { Metadata } from 'next';
import { eq, sql } from 'drizzle-orm';
import { db } from '@/db';
import { wishlist } from '@/db/schema';
import { env } from '@/env';
import {
ReminderSettings,
type ReminderListRow,
} from '@/components/verwaltung/reminder-settings';
import { daysUntil } from '@/lib/reminders';
import { requireAdmin } from '@/lib/session';
export const metadata: Metadata = { title: 'Erinnerungen' };
export default async function ErinnerungenPage() {
const admin = await requireAdmin();
const openItems = sql<number>`(
select count(*) from wishlist_item wi
where wi.wishlist_id = ${wishlist.id}
and wi.reserved_at is null
and wi.fulfilled_at is null
)`.mapWith(Number);
const now = new Date();
const lists: ReminderListRow[] = db
.select({
id: wishlist.id,
title: wishlist.title,
eventDate: wishlist.eventDate,
lastReminderAt: wishlist.lastReminderAt,
openItemCount: openItems,
})
.from(wishlist)
.where(eq(wishlist.ownerUserId, admin.id))
.all()
.filter((row) => row.eventDate !== null)
.map((row) => ({
...row,
daysLeft: row.eventDate ? daysUntil(row.eventDate, now) : null,
}))
.sort((a, b) => (a.daysLeft ?? 0) - (b.daysLeft ?? 0));
return (
<ReminderSettings
configured={env.isMailConfigured}
daysBefore={env.REMINDER_DAYS_BEFORE}
lists={lists}
/>
);
}
@@ -0,0 +1,166 @@
'use client';
import { useState, useTransition } from 'react';
import { BellRing, Loader2, Mail, PlugZap } from 'lucide-react';
import { toast } from 'sonner';
import {
runRemindersNow,
sendTestMail,
testMailConnection,
} from '@/app/(app)/verwaltung/erinnerungen/actions';
import { formatDate } from '@/lib/format';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
export type ReminderListRow = {
id: string;
title: string;
eventDate: Date | null;
openItemCount: number;
lastReminderAt: Date | null;
daysLeft: number | null;
};
export function ReminderSettings({
configured,
daysBefore,
lists,
}: {
configured: boolean;
daysBefore: number;
lists: ReminderListRow[];
}) {
const [pending, startTransition] = useTransition();
const [busy, setBusy] = useState<'verify' | 'test' | 'run' | null>(null);
function run(kind: 'verify' | 'test' | 'run') {
setBusy(kind);
startTransition(async () => {
if (kind === 'verify') {
const result = await testMailConnection();
if (result.ok) toast.success('Der SMTP-Server antwortet.');
else toast.error(result.error);
}
if (kind === 'test') {
const result = await sendTestMail();
if (result.ok) toast.success('Testnachricht verschickt. Schau in dein Postfach.');
else toast.error(result.error);
}
if (kind === 'run') {
const result = await runRemindersNow();
if (!result.ok) {
toast.error(result.error);
} else if (result.data.sent === 0 && result.data.failures.length === 0) {
toast.info('Nichts zu tun – gerade steht keine Erinnerung an.');
} else {
toast.success(
`${result.data.sent} Erinnerung(en) verschickt, ${result.data.failures.length} fehlgeschlagen.`,
);
}
}
setBusy(null);
});
}
return (
<div className="space-y-6">
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<BellRing className="size-5 text-primary" aria-hidden />
Erinnerungen
</CardTitle>
<CardDescription>
Rückt der Termin einer Wunschliste näher und stehen noch Wünsche offen, geht eine
Nachricht an dich raus – {daysBefore} Tage vorher, höchstens einmal pro Woche je Liste.
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
{configured ? (
<div className="flex flex-wrap gap-2">
<Button variant="outline" onClick={() => run('verify')} disabled={pending}>
{busy === 'verify' ? <Loader2 className="animate-spin" /> : <PlugZap />}
Verbindung prüfen
</Button>
<Button variant="outline" onClick={() => run('test')} disabled={pending}>
{busy === 'test' ? <Loader2 className="animate-spin" /> : <Mail />}
Testnachricht an mich
</Button>
<Button onClick={() => run('run')} disabled={pending}>
{busy === 'run' ? <Loader2 className="animate-spin" /> : <BellRing />}
Jetzt prüfen
</Button>
</div>
) : (
<div className="space-y-2 rounded-lg border border-dashed border-border p-4 text-sm text-muted-foreground">
<p>
Es ist kein Mailversand eingerichtet – Erinnerungen sind damit aus, alles andere
funktioniert unverändert.
</p>
<p>Zum Aktivieren in die .env eintragen und den Container neu starten:</p>
<pre className="overflow-x-auto rounded-md bg-muted p-3 font-mono text-xs">
{`SMTP_HOST=mail.example.de
SMTP_PORT=587
SMTP_USER=bricktrack@example.de
SMTP_PASSWORD=…
SMTP_FROM=Bricktrack <bricktrack@example.de>`}
</pre>
</div>
)}
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle>Wunschlisten mit Termin</CardTitle>
<CardDescription>
Nur Listen mit Termin können erinnert werden. Ist alles reserviert, bleibt es still.
</CardDescription>
</CardHeader>
<CardContent>
{lists.length === 0 ? (
<p className="text-sm text-muted-foreground">
Keine Wunschliste hat bisher einen Termin.
</p>
) : (
<ul className="divide-y divide-border rounded-lg border border-border">
{lists.map((list) => (
<li key={list.id} className="flex items-center gap-3 p-3">
<div className="min-w-0 flex-1">
<p className="truncate text-sm font-medium">{list.title}</p>
<p className="text-xs text-muted-foreground">
{list.eventDate ? formatDate(list.eventDate) : 'ohne Termin'}
{list.lastReminderAt
? ` · zuletzt erinnert am ${formatDate(list.lastReminderAt)}`
: ''}
</p>
</div>
{list.openItemCount > 0 ? (
<Badge variant="outline">{list.openItemCount} offen</Badge>
) : (
<Badge className="bg-emerald-600 text-white hover:bg-emerald-600">
Alles vergeben
</Badge>
)}
{list.daysLeft !== null && list.daysLeft >= 0 ? (
<Badge variant="secondary">
{list.daysLeft === 0 ? 'heute' : `in ${list.daysLeft} Tagen`}
</Badge>
) : (
<Badge variant="outline">vorbei</Badge>
)}
</li>
))}
</ul>
)}
</CardContent>
</Card>
</div>
);
}
@@ -10,6 +10,7 @@ const tabs = [
{ href: '/verwaltung/themen', label: 'Themen', adminOnly: false }, { href: '/verwaltung/themen', label: 'Themen', adminOnly: false },
{ href: '/verwaltung/standorte', label: 'Standorte', adminOnly: false }, { href: '/verwaltung/standorte', label: 'Standorte', adminOnly: false },
{ href: '/verwaltung/einladungen', label: 'Einladungen', adminOnly: true }, { href: '/verwaltung/einladungen', label: 'Einladungen', adminOnly: true },
{ href: '/verwaltung/erinnerungen', label: 'Erinnerungen', adminOnly: true },
{ href: '/verwaltung/daten', label: 'Daten', adminOnly: true }, { href: '/verwaltung/daten', label: 'Daten', adminOnly: true },
] as const; ] as const;
+2
View File
@@ -29,6 +29,8 @@ export const wishlist = sqliteTable(
surpriseMode: integer('surprise_mode', { mode: 'boolean' }).notNull().default(false), surpriseMode: integer('surprise_mode', { mode: 'boolean' }).notNull().default(false),
/** Message shown to the gift givers, e.g. "Bitte keine Doppelungen". */ /** Message shown to the gift givers, e.g. "Bitte keine Doppelungen". */
note: text('note'), note: text('note'),
/** When the owner was last reminded - keeps a nag from becoming a flood. */
lastReminderAt: integer('last_reminder_at', { mode: 'timestamp' }),
createdAt: integer('created_at', { mode: 'timestamp' }).notNull(), createdAt: integer('created_at', { mode: 'timestamp' }).notNull(),
updatedAt: integer('updated_at', { mode: 'timestamp' }).notNull(), updatedAt: integer('updated_at', { mode: 'timestamp' }).notNull(),
}, },
+22 -1
View File
@@ -27,8 +27,26 @@ const schema = z.object({
/** Upload size limit per file, in megabytes. */ /** Upload size limit per file, in megabytes. */
MAX_UPLOAD_MB: z.coerce.number().int().positive().max(200).default(25), MAX_UPLOAD_MB: z.coerce.number().int().positive().max(200).default(25),
/** Optional, phase 2: Rebrickable set import. Import stays disabled without it. */ /** Optional: Rebrickable set import. Import stays disabled without it. */
REBRICKABLE_API_KEY: z.string().min(1).optional(), REBRICKABLE_API_KEY: z.string().min(1).optional(),
/**
* Optional: outgoing mail for wishlist reminders. Without SMTP_HOST the
* whole reminder feature stays switched off - nothing is scheduled, nothing
* is sent.
*/
SMTP_HOST: z.string().min(1).optional(),
SMTP_PORT: z.coerce.number().int().min(1).max(65535).default(587),
SMTP_SECURE: z
.enum(['true', 'false'])
.default('false')
.transform((value) => value === 'true'),
SMTP_USER: z.string().min(1).optional(),
SMTP_PASSWORD: z.string().min(1).optional(),
SMTP_FROM: z.string().min(1).optional(),
/** How many days before the event a reminder goes out. */
REMINDER_DAYS_BEFORE: z.coerce.number().int().min(1).max(90).default(14),
}); });
/** /**
@@ -82,6 +100,9 @@ export const env = {
MAX_UPLOAD_BYTES: raw.MAX_UPLOAD_MB * 1024 * 1024, MAX_UPLOAD_BYTES: raw.MAX_UPLOAD_MB * 1024 * 1024,
isProduction: raw.NODE_ENV === 'production', isProduction: raw.NODE_ENV === 'production',
/** Reminders need a host and a sender; everything else has a default. */
isMailConfigured: Boolean(raw.SMTP_HOST && raw.SMTP_FROM),
} as const; } as const;
export type Env = typeof env; export type Env = typeof env;
+15
View File
@@ -0,0 +1,15 @@
/**
* Runs once when the server starts.
*
* Next calls this before handling the first request, which is the one place a
* long-lived background task can be started from.
*/
export async function register() {
// Only in the Node runtime - the edge runtime has no timers that survive,
// and the dev server would start a second scheduler on every reload.
if (process.env.NEXT_RUNTIME !== 'nodejs') return;
if (process.env.NODE_ENV !== 'production') return;
const { startReminderScheduler } = await import('@/lib/reminder-job');
startReminderScheduler();
}
+77
View File
@@ -0,0 +1,77 @@
import 'server-only';
import nodemailer, { type Transporter } from 'nodemailer';
import { env } from '@/env';
/**
* Outgoing mail.
*
* Entirely optional: without SMTP_HOST and SMTP_FROM nothing is scheduled and
* nothing is sent. The app never depends on mail working.
*/
let transporter: Transporter | null = null;
function getTransporter(): Transporter | null {
if (!env.isMailConfigured) return null;
if (transporter) return transporter;
transporter = nodemailer.createTransport({
host: env.SMTP_HOST,
port: env.SMTP_PORT,
// Implicit TLS on 465, STARTTLS on 587 - the usual pair.
secure: env.SMTP_SECURE || env.SMTP_PORT === 465,
auth:
env.SMTP_USER && env.SMTP_PASSWORD
? { user: env.SMTP_USER, pass: env.SMTP_PASSWORD }
: undefined,
});
return transporter;
}
export type MailResult = { ok: true } | { ok: false; error: string };
export async function sendMail(input: {
to: string;
subject: string;
text: string;
}): Promise<MailResult> {
const transport = getTransporter();
if (!transport) {
return { ok: false, error: 'Es ist kein SMTP-Server konfiguriert.' };
}
try {
await transport.sendMail({
from: env.SMTP_FROM,
to: input.to,
subject: input.subject,
text: input.text,
});
return { ok: true };
} catch (error) {
console.error('[mail] Versand fehlgeschlagen', error);
return {
ok: false,
error: error instanceof Error ? error.message : 'Der Versand ist fehlgeschlagen.',
};
}
}
/** Checks the connection without sending anything. */
export async function verifyMailConnection(): Promise<MailResult> {
const transport = getTransporter();
if (!transport) {
return { ok: false, error: 'Es ist kein SMTP-Server konfiguriert.' };
}
try {
await transport.verify();
return { ok: true };
} catch (error) {
return {
ok: false,
error: error instanceof Error ? error.message : 'Der Server antwortet nicht.',
};
}
}
+141
View File
@@ -0,0 +1,141 @@
import 'server-only';
import { eq, sql } from 'drizzle-orm';
import { db } from '@/db';
import { user, wishlist } from '@/db/schema';
import { env } from '@/env';
import { sendMail } from './mailer';
import {
reminderSubject,
reminderText,
shouldRemind,
type RemindableWishlist,
} from './reminders';
/**
* Sends the due wishlist reminders.
*
* Run from the hourly scheduler and from the "jetzt prüfen" button. Sending is
* recorded on the list, so a second run within the week stays quiet.
*/
export type ReminderRun = {
checked: number;
sent: number;
skipped: number;
failures: Array<{ title: string; error: string }>;
};
type Candidate = RemindableWishlist & {
ownerEmail: string;
ownerName: string;
shareToken: string;
isPublic: boolean;
};
function loadCandidates(): Candidate[] {
const openItems = sql<number>`(
select count(*) from wishlist_item wi
where wi.wishlist_id = ${wishlist.id}
and wi.reserved_at is null
and wi.fulfilled_at is null
)`.mapWith(Number);
return db
.select({
id: wishlist.id,
title: wishlist.title,
eventDate: wishlist.eventDate,
lastReminderAt: wishlist.lastReminderAt,
shareToken: wishlist.shareToken,
isPublic: wishlist.isPublic,
ownerEmail: user.email,
ownerName: user.name,
openItemCount: openItems,
})
.from(wishlist)
.innerJoin(user, eq(user.id, wishlist.ownerUserId))
.all();
}
export async function runReminderJob(now = new Date()): Promise<ReminderRun> {
const result: ReminderRun = { checked: 0, sent: 0, skipped: 0, failures: [] };
if (!env.isMailConfigured) return result;
const candidates = loadCandidates();
result.checked = candidates.length;
for (const candidate of candidates) {
const decision = shouldRemind(candidate, {
now,
daysBefore: env.REMINDER_DAYS_BEFORE,
});
if (!decision.remind) {
result.skipped += 1;
continue;
}
const mail = await sendMail({
to: candidate.ownerEmail,
subject: reminderSubject(candidate, decision.daysLeft),
text: reminderText({
title: candidate.title,
daysLeft: decision.daysLeft,
openItemCount: candidate.openItemCount,
shareUrl: candidate.isPublic
? `${env.BASE_URL}/w/${candidate.shareToken}`
: '(Teilen ist für diese Liste ausgeschaltet)',
appUrl: `${env.BASE_URL}/wunschlisten/${candidate.id}`,
}),
});
if (!mail.ok) {
result.failures.push({ title: candidate.title, error: mail.error });
continue;
}
// Only after a successful send - a failed attempt must be retried.
db.update(wishlist)
.set({ lastReminderAt: now })
.where(eq(wishlist.id, candidate.id))
.run();
result.sent += 1;
}
return result;
}
const HOUR_MS = 60 * 60 * 1000;
/**
* Starts the hourly check.
*
* Hourly rather than daily so a restart cannot skip a day, and the per-list
* cooldown keeps that from turning into repeated mail.
*/
export function startReminderScheduler(): void {
if (!env.isMailConfigured) {
console.log('[reminders] Kein SMTP konfiguriert - Erinnerungen sind aus.');
return;
}
console.log(
`[reminders] Aktiv: Erinnerung ${env.REMINDER_DAYS_BEFORE} Tage vor dem Termin, stuendliche Pruefung.`,
);
const tick = () => {
void runReminderJob()
.then((run) => {
if (run.sent > 0 || run.failures.length > 0) {
console.log(
`[reminders] ${run.sent} verschickt, ${run.failures.length} fehlgeschlagen.`,
);
}
})
.catch((error) => console.error('[reminders] Durchlauf fehlgeschlagen', error));
};
// A short delay so the first check does not compete with the app's start-up.
setTimeout(tick, 60_000).unref?.();
setInterval(tick, HOUR_MS).unref?.();
}
+91
View File
@@ -0,0 +1,91 @@
/**
* When to remind someone about a wishlist.
*
* Pure rules, no database and no mail: a reminder that arrives at the wrong
* moment is worse than none, so this is the part that gets tested.
*/
export type RemindableWishlist = {
id: string;
title: string;
eventDate: Date | null;
openItemCount: number;
lastReminderAt: Date | null;
};
export type ReminderDecision =
| { remind: true; daysLeft: number }
| { remind: false; reason: 'no-date' | 'too-early' | 'past' | 'nothing-open' | 'already-sent' };
/** Whole days between two points, ignoring the time of day. */
export function daysUntil(target: Date, now: Date): number {
const startOfTarget = Date.UTC(target.getFullYear(), target.getMonth(), target.getDate());
const startOfNow = Date.UTC(now.getFullYear(), now.getMonth(), now.getDate());
return Math.round((startOfTarget - startOfNow) / 86_400_000);
}
/**
* A reminder goes out when the date is close, something is still unclaimed,
* and we have not just written about it.
*/
export function shouldRemind(
list: RemindableWishlist,
options: { now: Date; daysBefore: number; minDaysBetween?: number },
): ReminderDecision {
const minDaysBetween = options.minDaysBetween ?? 7;
if (!list.eventDate) return { remind: false, reason: 'no-date' };
const daysLeft = daysUntil(list.eventDate, options.now);
// The day itself still counts - a morning reminder can save the afternoon.
if (daysLeft < 0) return { remind: false, reason: 'past' };
if (daysLeft > options.daysBefore) return { remind: false, reason: 'too-early' };
// Nothing open means everything is taken care of; silence is the right answer.
if (list.openItemCount <= 0) return { remind: false, reason: 'nothing-open' };
if (list.lastReminderAt) {
// daysUntil(now, lastReminderAt) reads as "days from the last reminder
// until now", which is exactly the age of that reminder.
const daysSinceLast = daysUntil(options.now, list.lastReminderAt);
if (daysSinceLast < minDaysBetween) return { remind: false, reason: 'already-sent' };
}
return { remind: true, daysLeft };
}
/** German subject line, because that is what lands in the inbox. */
export function reminderSubject(list: RemindableWishlist, daysLeft: number): string {
if (daysLeft === 0) return `Heute: ${list.title}`;
if (daysLeft === 1) return `Morgen: ${list.title}`;
return `In ${daysLeft} Tagen: ${list.title}`;
}
export function reminderText(input: {
title: string;
daysLeft: number;
openItemCount: number;
shareUrl: string;
appUrl: string;
}): string {
const when =
input.daysLeft === 0
? 'ist heute'
: input.daysLeft === 1
? 'ist morgen'
: `ist in ${input.daysLeft} Tagen`;
const open =
input.openItemCount === 1
? 'steht noch 1 Wunsch offen'
: `stehen noch ${input.openItemCount} Wünsche offen`;
return [
`Der Termin für „${input.title}" ${when}, und auf der Liste ${open}.`,
'',
`Liste ansehen: ${input.appUrl}`,
`Zum Teilen: ${input.shareUrl}`,
'',
'Diese Erinnerung kommt von deinem eigenen Bricktrack.',
].join('\n');
}
+131
View File
@@ -0,0 +1,131 @@
import { describe, expect, it } from 'vitest';
import {
daysUntil,
reminderSubject,
reminderText,
shouldRemind,
type RemindableWishlist,
} from '@/lib/reminders';
const now = new Date('2026-12-10T09:00:00');
const on = (iso: string) => new Date(`${iso}T00:00:00`);
function list(overrides: Partial<RemindableWishlist> = {}): RemindableWishlist {
return {
id: 'w-1',
title: 'Weihnachten 2026',
eventDate: on('2026-12-24'),
openItemCount: 3,
lastReminderAt: null,
...overrides,
};
}
describe('Tage bis zum Termin', () => {
it('zaehlt ganze Tage, unabhaengig von der Uhrzeit', () => {
expect(daysUntil(on('2026-12-24'), now)).toBe(14);
expect(daysUntil(on('2026-12-10'), now)).toBe(0);
expect(daysUntil(on('2026-12-09'), now)).toBe(-1);
});
});
describe('Wann erinnert wird', () => {
it('erinnert, wenn der Termin im Fenster liegt und etwas offen ist', () => {
const decision = shouldRemind(list(), { now, daysBefore: 14 });
expect(decision).toEqual({ remind: true, daysLeft: 14 });
});
it('schweigt, solange der Termin weit weg ist', () => {
const decision = shouldRemind(list({ eventDate: on('2027-06-01') }), {
now,
daysBefore: 14,
});
expect(decision).toEqual({ remind: false, reason: 'too-early' });
});
it('erinnert am Tag selbst noch', () => {
const decision = shouldRemind(list({ eventDate: on('2026-12-10') }), {
now,
daysBefore: 14,
});
expect(decision).toEqual({ remind: true, daysLeft: 0 });
});
it('schweigt, wenn der Termin vorbei ist', () => {
const decision = shouldRemind(list({ eventDate: on('2026-12-01') }), {
now,
daysBefore: 14,
});
expect(decision).toEqual({ remind: false, reason: 'past' });
});
it('schweigt ohne Termin', () => {
const decision = shouldRemind(list({ eventDate: null }), { now, daysBefore: 14 });
expect(decision).toEqual({ remind: false, reason: 'no-date' });
});
it('schweigt, wenn alles reserviert ist', () => {
const decision = shouldRemind(list({ openItemCount: 0 }), { now, daysBefore: 14 });
expect(decision).toEqual({ remind: false, reason: 'nothing-open' });
});
it('wiederholt sich nicht innerhalb einer Woche', () => {
const decision = shouldRemind(list({ lastReminderAt: on('2026-12-08') }), {
now,
daysBefore: 14,
});
expect(decision).toEqual({ remind: false, reason: 'already-sent' });
});
it('erinnert wieder, wenn die Sperrfrist vorbei ist', () => {
const decision = shouldRemind(list({ lastReminderAt: on('2026-12-01') }), {
now,
daysBefore: 14,
});
expect(decision).toMatchObject({ remind: true });
});
});
describe('Betreff und Text', () => {
it('formuliert die Naehe im Betreff', () => {
expect(reminderSubject(list(), 0)).toBe('Heute: Weihnachten 2026');
expect(reminderSubject(list(), 1)).toBe('Morgen: Weihnachten 2026');
expect(reminderSubject(list(), 5)).toBe('In 5 Tagen: Weihnachten 2026');
});
it('nennt Termin, offene Wuensche und beide Links', () => {
const text = reminderText({
title: 'Weihnachten 2026',
daysLeft: 3,
openItemCount: 2,
shareUrl: 'https://bricktrack.example.de/w/abc',
appUrl: 'https://bricktrack.example.de/wunschlisten/w-1',
});
expect(text).toContain('ist in 3 Tagen');
expect(text).toContain('stehen noch 2 Wünsche offen');
expect(text).toContain('https://bricktrack.example.de/w/abc');
expect(text).toContain('https://bricktrack.example.de/wunschlisten/w-1');
});
it('bleibt im Singular, wenn nur ein Wunsch offen ist', () => {
const text = reminderText({
title: 'Geburtstag',
daysLeft: 1,
openItemCount: 1,
shareUrl: 'x',
appUrl: 'y',
});
expect(text).toContain('ist morgen');
expect(text).toContain('steht noch 1 Wunsch offen');
});
});