mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-16 07:13:29 +00:00
Initial release v1.0.0
HealthLog — personal health-tracking PWA with weight, blood pressure, pulse, mood tracking, medication compliance, Withings integration, doctor report PDF export, and Dracula-themed UI.
This commit is contained in:
commit
38309932f3
301 files changed
+60041
No files matched your search
@@ -0,0 +1,258 @@
|
||||
"use client";
|
||||
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import {
|
||||
Activity,
|
||||
AlertTriangle,
|
||||
Bug,
|
||||
CalendarCheck,
|
||||
Fingerprint,
|
||||
Flame,
|
||||
Heart,
|
||||
KeyRound,
|
||||
Loader2,
|
||||
LogIn,
|
||||
Pill,
|
||||
ShieldCheck,
|
||||
SkipForward,
|
||||
Star,
|
||||
Target,
|
||||
Trophy,
|
||||
type LucideIcon,
|
||||
} from "lucide-react";
|
||||
import { Progress } from "@/components/ui/progress";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { useAuth } from "@/hooks/use-auth";
|
||||
import { useTranslations } from "@/lib/i18n/context";
|
||||
import { formatDate } from "@/lib/format";
|
||||
import type {
|
||||
AchievementMetrics,
|
||||
AchievementProgress,
|
||||
AchievementSummary,
|
||||
} from "@/lib/gamification/achievements";
|
||||
|
||||
interface AchievementsData {
|
||||
summary: AchievementSummary;
|
||||
achievements: AchievementProgress[];
|
||||
metrics: AchievementMetrics;
|
||||
}
|
||||
|
||||
const iconMap: Record<string, LucideIcon> = {
|
||||
Activity,
|
||||
Flame,
|
||||
CalendarCheck,
|
||||
Pill,
|
||||
ShieldCheck,
|
||||
Target,
|
||||
Trophy,
|
||||
Heart,
|
||||
KeyRound,
|
||||
Fingerprint,
|
||||
LogIn,
|
||||
Bug,
|
||||
AlertTriangle,
|
||||
SkipForward,
|
||||
};
|
||||
|
||||
function formatMetric(
|
||||
format: AchievementProgress["format"],
|
||||
value: number,
|
||||
t: (key: string, params?: Record<string, string | number>) => string,
|
||||
) {
|
||||
if (format === "percent")
|
||||
return t("achievements.metricPercent", { count: value });
|
||||
if (format === "days") return t("achievements.metricDays", { count: value });
|
||||
return t("achievements.metricCount", { count: value });
|
||||
}
|
||||
|
||||
export default function AchievementsPage() {
|
||||
const { isAuthenticated, isLoading: authLoading } = useAuth();
|
||||
const { t } = useTranslations();
|
||||
|
||||
const { data, isLoading } = useQuery({
|
||||
queryKey: ["gamification", "achievements"],
|
||||
queryFn: async () => {
|
||||
const res = await fetch("/api/gamification/achievements");
|
||||
if (!res.ok) throw new Error("Failed to load achievements");
|
||||
const json = await res.json();
|
||||
return json.data as AchievementsData;
|
||||
},
|
||||
enabled: isAuthenticated,
|
||||
});
|
||||
|
||||
if (authLoading || isLoading) {
|
||||
return (
|
||||
<div className="flex items-center justify-center py-20">
|
||||
<Loader2 className="text-primary h-6 w-6 animate-spin" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (!isAuthenticated) {
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<h1 className="text-2xl font-bold tracking-tight">
|
||||
{t("achievements.title")}
|
||||
</h1>
|
||||
<p className="text-muted-foreground text-sm">
|
||||
{t("achievements.loginRequired")}
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const summary = data?.summary;
|
||||
const achievements = data?.achievements ?? [];
|
||||
const unlockedAchievements = achievements.filter((item) => item.unlocked);
|
||||
const remainingUnlocks = Math.max(
|
||||
0,
|
||||
(summary?.totalCount ?? 0) - (summary?.unlockedCount ?? 0),
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold tracking-tight">
|
||||
{t("achievements.title")}
|
||||
</h1>
|
||||
<p className="text-muted-foreground text-sm">
|
||||
{t("achievements.subtitle")}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
|
||||
<div className="bg-card border-border flex min-h-34 flex-col justify-between rounded-xl border p-5">
|
||||
<p className="text-muted-foreground text-sm">
|
||||
{t("achievements.points")}
|
||||
</p>
|
||||
<p className="text-4xl leading-none font-bold md:text-5xl">
|
||||
{summary?.earnedPoints ?? 0}
|
||||
<span className="text-muted-foreground ml-2 text-base font-medium">
|
||||
/ {summary?.totalPoints ?? 0}
|
||||
</span>
|
||||
</p>
|
||||
<Progress
|
||||
value={
|
||||
summary?.totalPoints
|
||||
? Math.round((summary.earnedPoints / summary.totalPoints) * 100)
|
||||
: 0
|
||||
}
|
||||
className="h-1.5"
|
||||
/>
|
||||
</div>
|
||||
<div className="bg-card border-border flex min-h-34 flex-col justify-between rounded-xl border p-5">
|
||||
<p className="text-muted-foreground text-sm">
|
||||
{t("achievements.unlocked")}
|
||||
</p>
|
||||
<p className="text-4xl leading-none font-bold md:text-5xl">
|
||||
{summary?.unlockedCount ?? 0}
|
||||
<span className="text-muted-foreground ml-2 text-base font-medium">
|
||||
/ {summary?.totalCount ?? 0}
|
||||
</span>
|
||||
</p>
|
||||
<p className="text-muted-foreground text-xs">
|
||||
{t("achievements.remainingUnlocks", { count: remainingUnlocks })}
|
||||
</p>
|
||||
</div>
|
||||
<div className="bg-card border-border min-h-34 rounded-xl border p-5 sm:col-span-2 lg:col-span-1">
|
||||
<p className="text-muted-foreground text-sm">
|
||||
{t("achievements.nextGoal")}
|
||||
</p>
|
||||
{summary?.nextAchievement ? (
|
||||
<div className="mt-3 space-y-2">
|
||||
<p className="text-base font-semibold">
|
||||
{t(summary.nextAchievement.titleKey)}
|
||||
</p>
|
||||
<p className="text-muted-foreground line-clamp-2 text-xs">
|
||||
{t(summary.nextAchievement.descriptionKey)}
|
||||
</p>
|
||||
<p className="text-muted-foreground text-xs leading-relaxed">
|
||||
{t("achievements.nextProgressLabel")}:{" "}
|
||||
{formatMetric(
|
||||
summary.nextAchievement.format,
|
||||
summary.nextAchievement.current,
|
||||
t,
|
||||
)}{" "}
|
||||
/{" "}
|
||||
{formatMetric(
|
||||
summary.nextAchievement.format,
|
||||
summary.nextAchievement.target,
|
||||
t,
|
||||
)}{" "}
|
||||
({summary.nextAchievement.progressPercent}%)
|
||||
</p>
|
||||
<p className="text-muted-foreground text-xs">
|
||||
{t("achievements.pointsValue", {
|
||||
points: summary.nextAchievement.points,
|
||||
})}
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
<p className="mt-2 text-sm font-medium">
|
||||
{t("achievements.allCompleted")}
|
||||
</p>
|
||||
)}
|
||||
<Progress
|
||||
value={summary?.nextAchievement?.progressPercent ?? 100}
|
||||
className="mt-3 h-1.5"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
|
||||
{unlockedAchievements.map((achievement) => {
|
||||
const Icon = iconMap[achievement.icon] ?? Star;
|
||||
|
||||
return (
|
||||
<div
|
||||
key={achievement.id}
|
||||
className="border-primary/30 from-primary/8 to-primary/0 rounded-xl border bg-gradient-to-br p-3"
|
||||
>
|
||||
<div className="mb-2 flex items-start justify-between gap-2">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="bg-primary/15 text-primary rounded-lg p-2">
|
||||
<Icon className="h-3.5 w-3.5" />
|
||||
</div>
|
||||
<div className="min-w-0">
|
||||
<h2 className="text-sm font-semibold">
|
||||
{t(achievement.titleKey)}
|
||||
</h2>
|
||||
<p className="text-muted-foreground line-clamp-2 text-xs">
|
||||
{t(achievement.descriptionKey)}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<Badge variant="default" className="shrink-0">
|
||||
{t("achievements.completed")}
|
||||
</Badge>
|
||||
</div>
|
||||
|
||||
<div className="text-muted-foreground mt-3 flex items-center justify-between text-xs">
|
||||
<span className="font-medium">
|
||||
{t("achievements.pointsValue", {
|
||||
points: achievement.points,
|
||||
})}
|
||||
</span>
|
||||
<span>
|
||||
{achievement.completedAt
|
||||
? t("achievements.completedOn", {
|
||||
date: formatDate(achievement.completedAt),
|
||||
})
|
||||
: t("achievements.goalReached")}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
{unlockedAchievements.length === 0 && (
|
||||
<div className="bg-card border-border rounded-xl border p-6 text-center">
|
||||
<p className="text-muted-foreground text-sm">
|
||||
{t("achievements.noneUnlockedYet")}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,56 @@
|
||||
import { prisma } from "@/lib/db";
|
||||
import { apiHandler, requireAdmin } from "@/lib/api-handler";
|
||||
import { apiSuccess } from "@/lib/api-response";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
import { NextRequest } from "next/server";
|
||||
import { z } from "zod/v4";
|
||||
|
||||
const paginationSchema = z.object({
|
||||
limit: z.coerce.number().int().min(1).max(500).default(100),
|
||||
offset: z.coerce.number().int().min(0).default(0),
|
||||
filter: z.enum(["auth", "all"]).default("auth"),
|
||||
});
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
/**
|
||||
* Admin endpoint: list all auth-related audit log entries across all users.
|
||||
* Supports filtering by action prefix and pagination.
|
||||
*/
|
||||
export const GET = apiHandler(async (request: NextRequest) => {
|
||||
await requireAdmin();
|
||||
annotate({ action: { name: "admin.audit-log.list" } });
|
||||
|
||||
const { searchParams } = new URL(request.url);
|
||||
const { limit, offset, filter } = paginationSchema.parse({
|
||||
limit: searchParams.get("limit") ?? undefined,
|
||||
offset: searchParams.get("offset") ?? undefined,
|
||||
filter: searchParams.get("filter") ?? undefined,
|
||||
});
|
||||
|
||||
const where =
|
||||
filter === "auth" ? { action: { startsWith: "auth." } } : undefined;
|
||||
|
||||
const [entries, total] = await Promise.all([
|
||||
prisma.auditLog.findMany({
|
||||
where,
|
||||
orderBy: { createdAt: "desc" },
|
||||
take: limit,
|
||||
skip: offset,
|
||||
select: {
|
||||
id: true,
|
||||
action: true,
|
||||
ipAddress: true,
|
||||
location: true,
|
||||
details: true,
|
||||
createdAt: true,
|
||||
user: {
|
||||
select: { id: true, username: true },
|
||||
},
|
||||
},
|
||||
}),
|
||||
prisma.auditLog.count({ where }),
|
||||
]);
|
||||
|
||||
return apiSuccess({ entries, meta: { total, limit, offset } });
|
||||
});
|
||||
@@ -0,0 +1,85 @@
|
||||
import { prisma } from "@/lib/db";
|
||||
import { apiHandler, requireAdmin } from "@/lib/api-handler";
|
||||
import { auditLog } from "@/lib/auth/audit";
|
||||
import { apiSuccess, apiError, getClientIp } from "@/lib/api-response";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
import { checkRateLimit, rateLimitHeaders } from "@/lib/rate-limit";
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
/**
|
||||
* Admin-only global wipe of all health/integration data.
|
||||
* Keeps users/passkeys so access to the app remains possible.
|
||||
*/
|
||||
export const DELETE = apiHandler(async (request: NextRequest) => {
|
||||
const ip = getClientIp(request);
|
||||
const rl = await checkRateLimit(`admin-data-delete:${ip}`, 5, 60 * 1000);
|
||||
if (!rl.allowed) {
|
||||
return NextResponse.json(
|
||||
{ data: null, error: "Rate limit exceeded" },
|
||||
{ status: 429, headers: rateLimitHeaders(rl) },
|
||||
);
|
||||
}
|
||||
|
||||
const { user } = await requireAdmin();
|
||||
annotate({ action: { name: "admin.data.delete" } });
|
||||
|
||||
let confirm = "";
|
||||
try {
|
||||
const body = await request.json();
|
||||
confirm = typeof body?.confirm === "string" ? body.confirm : "";
|
||||
} catch {
|
||||
return apiError("Ungültige Anfrage", 422);
|
||||
}
|
||||
|
||||
if (confirm !== "DELETE ALL") {
|
||||
return apiError("Bestätigung fehlt", 422);
|
||||
}
|
||||
|
||||
const result = await prisma.$transaction(async (tx) => {
|
||||
const measurements = await tx.measurement.deleteMany({});
|
||||
const intakeEvents = await tx.medicationIntakeEvent.deleteMany({});
|
||||
const medications = await tx.medication.deleteMany({});
|
||||
const apiTokens = await tx.apiToken.deleteMany({});
|
||||
const withingsConnections = await tx.withingsConnection.deleteMany({});
|
||||
const auditLogs = await tx.auditLog.deleteMany({});
|
||||
const authChallenges = await tx.authChallenge.deleteMany({});
|
||||
|
||||
await tx.user.updateMany({
|
||||
data: {
|
||||
heightCm: null,
|
||||
dateOfBirth: null,
|
||||
gender: null,
|
||||
openaiKeyEncrypted: null,
|
||||
insightsPrivacyMode: "aggregated",
|
||||
insightsCachedAt: null,
|
||||
insightsCachedText: null,
|
||||
telegramBotToken: null,
|
||||
telegramChatId: null,
|
||||
telegramEnabled: false,
|
||||
withingsClientIdEncrypted: null,
|
||||
withingsClientSecretEncrypted: null,
|
||||
onboardingCompletedAt: null,
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
measurements: measurements.count,
|
||||
intakeEvents: intakeEvents.count,
|
||||
medications: medications.count,
|
||||
apiTokens: apiTokens.count,
|
||||
withingsConnections: withingsConnections.count,
|
||||
auditLogs: auditLogs.count,
|
||||
authChallenges: authChallenges.count,
|
||||
};
|
||||
});
|
||||
|
||||
await auditLog("admin.data.clear", {
|
||||
userId: user.id,
|
||||
ipAddress: getClientIp(request),
|
||||
details: result,
|
||||
});
|
||||
|
||||
return apiSuccess({ cleared: true, ...result });
|
||||
});
|
||||
@@ -0,0 +1,44 @@
|
||||
import { apiHandler, requireAdmin } from "@/lib/api-handler";
|
||||
import { annotate, getEvent } from "@/lib/logging/context";
|
||||
import { apiError, apiSuccess } from "@/lib/api-response";
|
||||
import { getGlitchtipSettings } from "@/lib/monitoring-settings";
|
||||
import { sendGlitchtipEvent } from "@/lib/monitoring/glitchtip";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export const POST = apiHandler(async () => {
|
||||
await requireAdmin();
|
||||
annotate({ action: { name: "admin.monitoring.glitchtip-test" } });
|
||||
|
||||
const settings = await getGlitchtipSettings();
|
||||
if (!settings.glitchtipEnabled) {
|
||||
return apiError("Glitchtip ist deaktiviert", 422);
|
||||
}
|
||||
if (!settings.glitchtipDsn) {
|
||||
return apiError("Glitchtip DSN fehlt", 422);
|
||||
}
|
||||
|
||||
const delivery = await sendGlitchtipEvent({
|
||||
dsn: settings.glitchtipDsn,
|
||||
input: {
|
||||
environment: settings.glitchtipEnvironment || "production",
|
||||
message: "HealthLog Monitoring Test",
|
||||
level: "error",
|
||||
type: "HealthLogMonitoringTest",
|
||||
sourceTag: "healthlog-admin-test",
|
||||
},
|
||||
});
|
||||
|
||||
if (!delivery.ok) {
|
||||
getEvent()?.addWarning("Glitchtip test event rejected: " + delivery.method + " " + delivery.status + " " + delivery.details);
|
||||
return apiError(
|
||||
`Glitchtip-Testevent wurde abgelehnt (HTTP ${delivery.status ?? 502})`,
|
||||
502,
|
||||
);
|
||||
}
|
||||
|
||||
return apiSuccess({
|
||||
sent: true,
|
||||
message: "Glitchtip-Testevent wurde gesendet",
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,123 @@
|
||||
import { NextRequest } from "next/server";
|
||||
import { apiHandler, requireAdmin } from "@/lib/api-handler";
|
||||
import { annotate, getEvent } from "@/lib/logging/context";
|
||||
import { apiError, apiSuccess } from "@/lib/api-response";
|
||||
import { getPublicMonitoringSettings } from "@/lib/monitoring-settings";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
function resolveUmamiSendUrls(scriptUrl: string | null): string[] {
|
||||
if (!scriptUrl) return [];
|
||||
try {
|
||||
const parsed = new URL(scriptUrl);
|
||||
const origin = parsed.origin;
|
||||
const pathSegments = parsed.pathname.split("/").filter(Boolean);
|
||||
const segments = [...pathSegments];
|
||||
|
||||
if (segments.length > 0 && segments[segments.length - 1]?.includes(".")) {
|
||||
segments.pop();
|
||||
}
|
||||
|
||||
const prefix = segments.length > 0 ? `/${segments.join("/")}` : "";
|
||||
const candidates = [
|
||||
`${origin}${prefix}/api/send`,
|
||||
`${origin}/api/send`,
|
||||
`${origin}/umami/api/send`,
|
||||
];
|
||||
return Array.from(new Set(candidates));
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
function resolveAppUrl(request: NextRequest): URL {
|
||||
const configured =
|
||||
process.env.APP_URL ??
|
||||
process.env.NEXT_PUBLIC_APP_URL ??
|
||||
`https://${request.headers.get("host") ?? "localhost:3000"}`;
|
||||
|
||||
try {
|
||||
return new URL(configured);
|
||||
} catch {
|
||||
return new URL(
|
||||
`https://${request.headers.get("host") ?? "localhost:3000"}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export const POST = apiHandler(async (request: NextRequest) => {
|
||||
await requireAdmin();
|
||||
annotate({ action: { name: "admin.monitoring.umami-test" } });
|
||||
|
||||
const settings = await getPublicMonitoringSettings();
|
||||
if (!settings.umamiEnabled) {
|
||||
return apiError("Umami ist deaktiviert", 422);
|
||||
}
|
||||
if (!settings.umamiScriptUrl || !settings.umamiWebsiteId) {
|
||||
return apiError(
|
||||
"Umami Script-URL und Website-ID müssen konfiguriert sein",
|
||||
422,
|
||||
);
|
||||
}
|
||||
|
||||
const targetUrls = resolveUmamiSendUrls(settings.umamiScriptUrl);
|
||||
if (targetUrls.length === 0) {
|
||||
return apiError("Umami Script-URL ist ungültig", 422);
|
||||
}
|
||||
|
||||
const appUrl = resolveAppUrl(request);
|
||||
const payload = {
|
||||
type: "event",
|
||||
payload: {
|
||||
website: settings.umamiWebsiteId,
|
||||
hostname: appUrl.hostname,
|
||||
screen: "1920x1080",
|
||||
language: "de-DE",
|
||||
title: "HealthLog Monitoring Test",
|
||||
url: "/admin",
|
||||
referrer: "",
|
||||
name: "healthlog_monitoring_test",
|
||||
data: {
|
||||
source: "admin",
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
let lastStatus = 404;
|
||||
let lastDetails = "";
|
||||
|
||||
for (const targetUrl of targetUrls) {
|
||||
const upstream = await fetch(targetUrl, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"content-type": "application/json",
|
||||
"user-agent": "healthlog-admin-monitoring-test",
|
||||
},
|
||||
body: JSON.stringify(payload),
|
||||
cache: "no-store",
|
||||
});
|
||||
|
||||
if (upstream.ok) {
|
||||
return apiSuccess({
|
||||
sent: true,
|
||||
message: "Umami-Testevent wurde gesendet",
|
||||
});
|
||||
}
|
||||
|
||||
lastStatus = upstream.status;
|
||||
lastDetails = await upstream.text().catch(() => "");
|
||||
|
||||
// Try next candidate only for path misses.
|
||||
if (upstream.status === 404) {
|
||||
continue;
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
getEvent()?.addWarning("Umami test event rejected: " + lastStatus);
|
||||
return apiError(
|
||||
`Umami-Testevent wurde abgelehnt (HTTP ${lastStatus})`,
|
||||
502,
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,201 @@
|
||||
import { prisma } from "@/lib/db";
|
||||
import { apiHandler, requireAdmin } from "@/lib/api-handler";
|
||||
import { annotate, getEvent } from "@/lib/logging/context";
|
||||
import { apiSuccess } from "@/lib/api-response";
|
||||
import { parseScheduleRecurrence } from "@/lib/medication-schedule";
|
||||
import { dispatchNotification } from "@/lib/notifications/dispatcher";
|
||||
import { getUserTodayBounds, getDayOfWeekInTz } from "@/lib/timezone";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
function parseTimeToMinutes(value: string): number {
|
||||
const [h, m] = value.split(":").map(Number);
|
||||
if (!Number.isFinite(h) || !Number.isFinite(m)) return 0;
|
||||
return h * 60 + m;
|
||||
}
|
||||
|
||||
const dayLabels = ["So", "Mo", "Di", "Mi", "Do", "Fr", "Sa"];
|
||||
|
||||
interface ScheduleStatus {
|
||||
window: string;
|
||||
days: string;
|
||||
status: "open" | "late" | "threshold" | "missed" | "skipped";
|
||||
label: string;
|
||||
minutesPastEnd: number | null;
|
||||
notificationSent: boolean;
|
||||
}
|
||||
|
||||
interface MedicationResult {
|
||||
name: string;
|
||||
dose: string;
|
||||
user: string;
|
||||
timezone: string;
|
||||
localTime: string;
|
||||
dayOfWeek: string;
|
||||
notificationsEnabled: boolean;
|
||||
schedules: ScheduleStatus[];
|
||||
eventsToday: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* POST: Execute the reminder check — analyzes all medications AND sends
|
||||
* notifications for overdue schedules (late + missed). Returns detailed
|
||||
* results for display in the admin panel.
|
||||
*/
|
||||
export const POST = apiHandler(async () => {
|
||||
await requireAdmin();
|
||||
annotate({ action: { name: "admin.notifications.reminder-check" } });
|
||||
|
||||
const now = new Date();
|
||||
|
||||
const appSettings = await prisma.appSettings.findUnique({
|
||||
where: { id: "singleton" },
|
||||
select: { reminderMissedMinutes: true },
|
||||
});
|
||||
const missedMinutes = appSettings?.reminderMissedMinutes ?? 240;
|
||||
|
||||
const medications = await prisma.medication.findMany({
|
||||
where: { active: true },
|
||||
include: {
|
||||
schedules: true,
|
||||
user: { select: { id: true, username: true, timezone: true } },
|
||||
},
|
||||
});
|
||||
|
||||
const results: MedicationResult[] = [];
|
||||
let notificationsSent = 0;
|
||||
|
||||
for (const med of medications) {
|
||||
const userTz = med.user.timezone || "Europe/Berlin";
|
||||
const { start: todayStart, end: todayEnd } = getUserTodayBounds(
|
||||
now,
|
||||
userTz,
|
||||
);
|
||||
const currentTime = now.toLocaleTimeString("de-DE", {
|
||||
timeZone: userTz,
|
||||
hour: "2-digit",
|
||||
minute: "2-digit",
|
||||
hour12: false,
|
||||
});
|
||||
const todayDow = getDayOfWeekInTz(now, userTz);
|
||||
|
||||
const eventCount = await prisma.medicationIntakeEvent.count({
|
||||
where: {
|
||||
medicationId: med.id,
|
||||
userId: med.user.id,
|
||||
scheduledFor: { gte: todayStart, lte: todayEnd },
|
||||
},
|
||||
});
|
||||
|
||||
const scheduleStatuses: ScheduleStatus[] = [];
|
||||
let schedulesProcessed = 0;
|
||||
|
||||
const sortedSchedules = [...med.schedules].sort((a, b) =>
|
||||
a.windowStart.localeCompare(b.windowStart),
|
||||
);
|
||||
|
||||
for (const schedule of sortedSchedules) {
|
||||
const recurrence = parseScheduleRecurrence(schedule.daysOfWeek);
|
||||
const endMins = parseTimeToMinutes(schedule.windowEnd);
|
||||
const currentMins = parseTimeToMinutes(currentTime);
|
||||
const minutesPastEnd = currentMins - endMins;
|
||||
|
||||
const dayMatch =
|
||||
recurrence.daysOfWeek.length === 0 ||
|
||||
recurrence.daysOfWeek.includes(todayDow);
|
||||
|
||||
const daysInfo =
|
||||
recurrence.daysOfWeek.length > 0
|
||||
? recurrence.daysOfWeek.map((d) => dayLabels[d]).join(", ")
|
||||
: "Täglich";
|
||||
|
||||
let status: ScheduleStatus["status"];
|
||||
let label: string;
|
||||
let notificationSent = false;
|
||||
|
||||
if (!dayMatch) {
|
||||
status = "skipped";
|
||||
label = "Heute kein geplanter Tag";
|
||||
} else if (currentMins <= endMins) {
|
||||
status = "open";
|
||||
label = `Fenster noch offen (endet um ${schedule.windowEnd})`;
|
||||
} else if (minutesPastEnd <= missedMinutes) {
|
||||
status = "threshold";
|
||||
label = `Fenster vorbei seit ${minutesPastEnd} Min (Threshold: ${missedMinutes} Min)`;
|
||||
} else {
|
||||
status = "missed";
|
||||
label = `Missed-Threshold erreicht (${minutesPastEnd} Min > ${missedMinutes} Min)`;
|
||||
}
|
||||
|
||||
// Send notification for overdue schedules that haven't been taken
|
||||
const isOverdue = dayMatch && minutesPastEnd > 0;
|
||||
const hasEvent = eventCount > schedulesProcessed;
|
||||
|
||||
if (isOverdue && !hasEvent && med.notificationsEnabled) {
|
||||
const doseInfo = schedule.dose ?? med.dose;
|
||||
const timeWindow = `${schedule.windowStart}–${schedule.windowEnd}`;
|
||||
|
||||
try {
|
||||
if (status === "missed") {
|
||||
await dispatchNotification({
|
||||
eventType: "MEDICATION_REMINDER",
|
||||
userId: med.user.id,
|
||||
title: `Verpasst: ${med.name}`,
|
||||
message: `<b>${med.name}</b> (${doseInfo}, ${timeWindow}) wurde als verpasst markiert.`,
|
||||
metadata: { medicationId: med.id },
|
||||
});
|
||||
} else {
|
||||
await dispatchNotification({
|
||||
eventType: "MEDICATION_REMINDER",
|
||||
userId: med.user.id,
|
||||
title: `Erinnerung: ${med.name}`,
|
||||
message: `Erinnerung: <b>${med.name}</b> (${doseInfo}, ${timeWindow}) wurde noch nicht eingenommen. Seit ${minutesPastEnd} Min überfällig.`,
|
||||
metadata: { medicationId: med.id },
|
||||
});
|
||||
}
|
||||
notificationSent = true;
|
||||
notificationsSent++;
|
||||
} catch (err) {
|
||||
getEvent()?.addWarning("Notification failed for " + med.name + ": " + err);
|
||||
}
|
||||
}
|
||||
|
||||
if (dayMatch && minutesPastEnd > 0) {
|
||||
schedulesProcessed++;
|
||||
}
|
||||
|
||||
scheduleStatuses.push({
|
||||
window: `${schedule.windowStart}–${schedule.windowEnd}`,
|
||||
days: daysInfo,
|
||||
status,
|
||||
label,
|
||||
minutesPastEnd:
|
||||
dayMatch && currentMins > endMins ? minutesPastEnd : null,
|
||||
notificationSent,
|
||||
});
|
||||
}
|
||||
|
||||
results.push({
|
||||
name: med.name,
|
||||
dose: med.dose,
|
||||
user: med.user.username,
|
||||
timezone: userTz,
|
||||
localTime: currentTime,
|
||||
dayOfWeek: dayLabels[todayDow],
|
||||
notificationsEnabled: med.notificationsEnabled,
|
||||
schedules: scheduleStatuses,
|
||||
eventsToday: eventCount,
|
||||
});
|
||||
}
|
||||
|
||||
return apiSuccess({
|
||||
timestamp: now.toISOString(),
|
||||
missedThresholdMinutes: missedMinutes,
|
||||
medications: results,
|
||||
notificationsSent,
|
||||
message:
|
||||
results.length > 0
|
||||
? `${results.length} Medikamente geprüft, ${notificationsSent} Erinnerungen gesendet`
|
||||
: "Keine aktiven Medikamente gefunden",
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,184 @@
|
||||
import { prisma } from "@/lib/db";
|
||||
import { apiHandler, requireAdmin } from "@/lib/api-handler";
|
||||
import { annotate, getEvent } from "@/lib/logging/context";
|
||||
import { apiSuccess } from "@/lib/api-response";
|
||||
import { decrypt, encrypt } from "@/lib/crypto";
|
||||
import { sendViaTelegram } from "@/lib/notifications/senders/telegram";
|
||||
import { sendViaNtfy } from "@/lib/notifications/senders/ntfy";
|
||||
import { sendViaWebPush } from "@/lib/notifications/senders/web-push";
|
||||
import type {
|
||||
TelegramChannelConfig,
|
||||
NtfyChannelConfig,
|
||||
ChannelType,
|
||||
NotificationPayload,
|
||||
} from "@/lib/notifications/types";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
/**
|
||||
* Ensure legacy Telegram config (stored on User model) has a matching
|
||||
* NotificationChannel record. Returns true if a channel was created.
|
||||
*/
|
||||
async function ensureTelegramChannel(userId: string): Promise<boolean> {
|
||||
const existing = await prisma.notificationChannel.findUnique({
|
||||
where: { userId_type: { userId, type: "TELEGRAM" } },
|
||||
});
|
||||
if (existing) return false;
|
||||
|
||||
const user = await prisma.user.findUnique({
|
||||
where: { id: userId },
|
||||
select: {
|
||||
telegramBotToken: true,
|
||||
telegramChatId: true,
|
||||
telegramEnabled: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (
|
||||
!user?.telegramEnabled ||
|
||||
!user.telegramBotToken ||
|
||||
!user.telegramChatId
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const botToken = decrypt(user.telegramBotToken);
|
||||
const config = encrypt(
|
||||
JSON.stringify({ botToken, chatId: user.telegramChatId }),
|
||||
);
|
||||
|
||||
await prisma.notificationChannel.create({
|
||||
data: {
|
||||
userId,
|
||||
type: "TELEGRAM",
|
||||
enabled: true,
|
||||
config,
|
||||
},
|
||||
});
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
export const POST = apiHandler(async () => {
|
||||
const { user } = await requireAdmin();
|
||||
annotate({ action: { name: "admin.notifications.test" } });
|
||||
|
||||
// Auto-migrate legacy Telegram config before querying channels
|
||||
const migrated = await ensureTelegramChannel(user.id);
|
||||
if (migrated) {
|
||||
getEvent()?.addMeta("telegram_migrated", true);
|
||||
}
|
||||
|
||||
const channels = await prisma.notificationChannel.findMany({
|
||||
where: { userId: user.id, enabled: true },
|
||||
include: {
|
||||
preferences: { where: { eventType: "SYSTEM_ALERT" } },
|
||||
},
|
||||
});
|
||||
|
||||
if (channels.length === 0) {
|
||||
return apiSuccess({
|
||||
sent: false,
|
||||
message: "Keine aktivierten Benachrichtigungskanäle gefunden",
|
||||
results: [],
|
||||
});
|
||||
}
|
||||
|
||||
const payload: NotificationPayload = {
|
||||
eventType: "SYSTEM_ALERT",
|
||||
userId: user.id,
|
||||
title: "Test-Notification",
|
||||
message:
|
||||
"<b>HealthLog Test:</b> Wenn du diese Nachricht siehst, funktionieren deine Benachrichtigungen!",
|
||||
};
|
||||
|
||||
const results: Array<{
|
||||
channel: string;
|
||||
success: boolean;
|
||||
error?: string;
|
||||
}> = [];
|
||||
|
||||
for (const channel of channels) {
|
||||
const pref = channel.preferences[0];
|
||||
if (pref && !pref.enabled) {
|
||||
results.push({
|
||||
channel: channel.type,
|
||||
success: false,
|
||||
error: "SYSTEM_ALERT deaktiviert in Einstellungen",
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
const type = channel.type as ChannelType;
|
||||
let success = false;
|
||||
|
||||
switch (type) {
|
||||
case "TELEGRAM": {
|
||||
const config = JSON.parse(
|
||||
decrypt(channel.config),
|
||||
) as TelegramChannelConfig;
|
||||
const telegramResult = await sendViaTelegram(config, payload);
|
||||
success = telegramResult.ok;
|
||||
if (!success) {
|
||||
results.push({
|
||||
channel: "TELEGRAM",
|
||||
success: false,
|
||||
error: `Telegram API hat Fehler gemeldet (chatId: ${config.chatId})`,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
break;
|
||||
}
|
||||
case "NTFY": {
|
||||
const config = JSON.parse(
|
||||
decrypt(channel.config),
|
||||
) as NtfyChannelConfig;
|
||||
success = await sendViaNtfy(config, payload);
|
||||
if (!success) {
|
||||
results.push({
|
||||
channel: "NTFY",
|
||||
success: false,
|
||||
error: `Senden fehlgeschlagen (topic: ${config.topic})`,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
break;
|
||||
}
|
||||
case "WEB_PUSH": {
|
||||
success = await sendViaWebPush(user.id, payload);
|
||||
break;
|
||||
}
|
||||
default:
|
||||
results.push({
|
||||
channel: type,
|
||||
success: false,
|
||||
error: "Unbekannter Kanaltyp",
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
results.push({ channel: type, success });
|
||||
} catch (err) {
|
||||
results.push({
|
||||
channel: channel.type,
|
||||
success: false,
|
||||
error: err instanceof Error ? err.message : "Unbekannter Fehler",
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const successCount = results.filter((r) => r.success).length;
|
||||
const failCount = results.filter((r) => !r.success).length;
|
||||
|
||||
let message: string;
|
||||
if (failCount === 0) {
|
||||
message = `Alle ${successCount} Kanäle erfolgreich`;
|
||||
} else if (successCount === 0) {
|
||||
message = `Alle ${failCount} Kanäle fehlgeschlagen`;
|
||||
} else {
|
||||
message = `${successCount} erfolgreich, ${failCount} fehlgeschlagen`;
|
||||
}
|
||||
|
||||
return apiSuccess({ sent: successCount > 0, message, results });
|
||||
});
|
||||
@@ -0,0 +1,227 @@
|
||||
import { prisma } from "@/lib/db";
|
||||
import { apiHandler, requireAdmin } from "@/lib/api-handler";
|
||||
import { auditLog } from "@/lib/auth/audit";
|
||||
import { apiSuccess, apiError, getClientIp, safeJson } from "@/lib/api-response";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
import { encrypt } from "@/lib/crypto";
|
||||
import { adminSettingsSchema } from "@/lib/validations/admin";
|
||||
import { NextRequest } from "next/server";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export const GET = apiHandler(async () => {
|
||||
await requireAdmin();
|
||||
annotate({ action: { name: "admin.settings.get" } });
|
||||
|
||||
const settings = await prisma.appSettings.findUnique({
|
||||
where: { id: "singleton" },
|
||||
});
|
||||
|
||||
return apiSuccess({
|
||||
registrationEnabled: settings?.registrationEnabled ?? true,
|
||||
defaultLocale: settings?.defaultLocale ?? "de",
|
||||
telegramGlobal: settings?.telegramGlobal ?? true,
|
||||
ntfyGlobal: settings?.ntfyGlobal ?? true,
|
||||
webPushGlobal: settings?.webPushGlobal ?? true,
|
||||
webPushVapidPublicKey: settings?.webPushVapidPublicKey ?? null,
|
||||
webPushVapidSubject: settings?.webPushVapidSubject ?? null,
|
||||
webPushVapidConfigured: Boolean(
|
||||
settings?.webPushVapidPublicKey &&
|
||||
settings?.webPushVapidPrivateKeyEncrypted &&
|
||||
settings?.webPushVapidSubject,
|
||||
),
|
||||
apiGlobal: settings?.apiGlobal ?? true,
|
||||
umamiEnabled: settings?.umamiEnabled ?? false,
|
||||
umamiScriptUrl: settings?.umamiScriptUrl ?? null,
|
||||
umamiWebsiteId: settings?.umamiWebsiteId ?? null,
|
||||
glitchtipEnabled: settings?.glitchtipEnabled ?? false,
|
||||
glitchtipDsn: settings?.glitchtipDsn ?? null,
|
||||
glitchtipEnvironment: settings?.glitchtipEnvironment ?? "production",
|
||||
bugReportRepo: settings?.githubIssueRepo ?? null,
|
||||
bugReportConfigured: Boolean(
|
||||
settings?.githubIssueRepo && settings?.githubIssueTokenEncrypted,
|
||||
),
|
||||
reminderLateMinutes: settings?.reminderLateMinutes ?? 120,
|
||||
reminderMissedMinutes: settings?.reminderMissedMinutes ?? 240,
|
||||
moodLogGlobal: settings?.moodLogGlobal ?? true,
|
||||
});
|
||||
});
|
||||
|
||||
export const PUT = apiHandler(async (request: NextRequest) => {
|
||||
const { user } = await requireAdmin();
|
||||
annotate({ action: { name: "admin.settings.update" } });
|
||||
|
||||
const { data: body, error: jsonError } = await safeJson(request);
|
||||
|
||||
if (jsonError) return jsonError;
|
||||
const parsed = adminSettingsSchema.safeParse(body);
|
||||
if (!parsed.success) {
|
||||
return apiError(parsed.error.issues[0].message, 422);
|
||||
}
|
||||
|
||||
const data = parsed.data;
|
||||
const updates: Record<string, unknown> = {};
|
||||
const auditDetails: Record<string, unknown> = {};
|
||||
|
||||
// Boolean fields — direct mapping
|
||||
const booleanFields = [
|
||||
"registrationEnabled",
|
||||
"telegramGlobal",
|
||||
"ntfyGlobal",
|
||||
"webPushGlobal",
|
||||
"apiGlobal",
|
||||
"umamiEnabled",
|
||||
"glitchtipEnabled",
|
||||
"moodLogGlobal",
|
||||
] as const;
|
||||
for (const field of booleanFields) {
|
||||
if (data[field] !== undefined) {
|
||||
updates[field] = data[field];
|
||||
auditDetails[field] = data[field];
|
||||
}
|
||||
}
|
||||
|
||||
if (data.defaultLocale !== undefined) {
|
||||
updates.defaultLocale = data.defaultLocale;
|
||||
auditDetails.defaultLocale = data.defaultLocale;
|
||||
}
|
||||
|
||||
// String fields that map directly (with empty → null)
|
||||
if (data.webPushVapidPublicKey !== undefined) {
|
||||
const value = data.webPushVapidPublicKey.trim();
|
||||
updates.webPushVapidPublicKey = value || null;
|
||||
auditDetails.webPushVapidPublicKey = value ? "configured" : null;
|
||||
}
|
||||
|
||||
if (data.webPushVapidSubject !== undefined) {
|
||||
const value = data.webPushVapidSubject.trim();
|
||||
updates.webPushVapidSubject = value || null;
|
||||
auditDetails.webPushVapidSubject = value || null;
|
||||
}
|
||||
|
||||
// Encrypted fields
|
||||
if (data.webPushVapidPrivateKey !== undefined) {
|
||||
const value = data.webPushVapidPrivateKey.trim();
|
||||
if (value) {
|
||||
updates.webPushVapidPrivateKeyEncrypted = encrypt(value);
|
||||
auditDetails.webPushVapidPrivateKeyUpdated = true;
|
||||
}
|
||||
}
|
||||
if (data.clearWebPushVapidPrivateKey === true) {
|
||||
updates.webPushVapidPrivateKeyEncrypted = null;
|
||||
auditDetails.webPushVapidPrivateKeyUpdated = false;
|
||||
}
|
||||
|
||||
// URL fields with normalization
|
||||
if (data.umamiScriptUrl !== undefined) {
|
||||
const value = data.umamiScriptUrl.trim();
|
||||
if (!value) {
|
||||
updates.umamiScriptUrl = null;
|
||||
auditDetails.umamiScriptUrl = null;
|
||||
} else {
|
||||
const parsed = new URL(value);
|
||||
if (parsed.pathname === "/" || parsed.pathname === "") {
|
||||
parsed.pathname = "/script.js";
|
||||
}
|
||||
updates.umamiScriptUrl = parsed.toString();
|
||||
auditDetails.umamiScriptUrl = parsed.toString();
|
||||
}
|
||||
}
|
||||
|
||||
if (data.umamiWebsiteId !== undefined) {
|
||||
const value = data.umamiWebsiteId.trim();
|
||||
updates.umamiWebsiteId = value || null;
|
||||
auditDetails.umamiWebsiteId = value || null;
|
||||
}
|
||||
|
||||
if (data.glitchtipDsn !== undefined) {
|
||||
const value = data.glitchtipDsn.trim();
|
||||
if (!value) {
|
||||
updates.glitchtipDsn = null;
|
||||
auditDetails.glitchtipDsn = null;
|
||||
} else {
|
||||
updates.glitchtipDsn = new URL(value).toString();
|
||||
auditDetails.glitchtipDsn = "configured";
|
||||
}
|
||||
}
|
||||
|
||||
if (data.glitchtipEnvironment !== undefined) {
|
||||
const value = data.glitchtipEnvironment.trim();
|
||||
updates.glitchtipEnvironment = value || null;
|
||||
auditDetails.glitchtipEnvironment = value || null;
|
||||
}
|
||||
|
||||
// Bug report
|
||||
if (data.bugReportRepo !== undefined) {
|
||||
const repo = data.bugReportRepo.trim();
|
||||
updates.githubIssueRepo = repo || null;
|
||||
auditDetails.bugReportRepo = repo || null;
|
||||
}
|
||||
if (data.bugReportToken !== undefined) {
|
||||
const token = data.bugReportToken.trim();
|
||||
if (token) {
|
||||
updates.githubIssueTokenEncrypted = encrypt(token);
|
||||
auditDetails.bugReportTokenUpdated = true;
|
||||
}
|
||||
}
|
||||
if (data.clearBugReportToken === true) {
|
||||
updates.githubIssueTokenEncrypted = null;
|
||||
auditDetails.bugReportTokenUpdated = false;
|
||||
}
|
||||
|
||||
// Numeric thresholds
|
||||
if (data.reminderLateMinutes !== undefined) {
|
||||
updates.reminderLateMinutes = data.reminderLateMinutes;
|
||||
auditDetails.reminderLateMinutes = data.reminderLateMinutes;
|
||||
}
|
||||
if (data.reminderMissedMinutes !== undefined) {
|
||||
updates.reminderMissedMinutes = data.reminderMissedMinutes;
|
||||
auditDetails.reminderMissedMinutes = data.reminderMissedMinutes;
|
||||
}
|
||||
|
||||
if (Object.keys(updates).length === 0) {
|
||||
return apiError("Keine gültigen Felder", 422);
|
||||
}
|
||||
|
||||
const settings = await prisma.appSettings.upsert({
|
||||
where: { id: "singleton" },
|
||||
update: updates,
|
||||
create: { id: "singleton", ...updates },
|
||||
});
|
||||
|
||||
await auditLog("admin.settings.update", {
|
||||
userId: user.id,
|
||||
ipAddress: getClientIp(request),
|
||||
details: auditDetails,
|
||||
});
|
||||
|
||||
return apiSuccess({
|
||||
registrationEnabled: settings.registrationEnabled,
|
||||
defaultLocale: settings.defaultLocale,
|
||||
telegramGlobal: settings.telegramGlobal,
|
||||
ntfyGlobal: settings.ntfyGlobal,
|
||||
webPushGlobal: settings.webPushGlobal,
|
||||
webPushVapidPublicKey: settings.webPushVapidPublicKey,
|
||||
webPushVapidSubject: settings.webPushVapidSubject,
|
||||
webPushVapidConfigured: Boolean(
|
||||
settings.webPushVapidPublicKey &&
|
||||
settings.webPushVapidPrivateKeyEncrypted &&
|
||||
settings.webPushVapidSubject,
|
||||
),
|
||||
apiGlobal: settings.apiGlobal,
|
||||
umamiEnabled: settings.umamiEnabled,
|
||||
umamiScriptUrl: settings.umamiScriptUrl,
|
||||
umamiWebsiteId: settings.umamiWebsiteId,
|
||||
glitchtipEnabled: settings.glitchtipEnabled,
|
||||
glitchtipDsn: settings.glitchtipDsn,
|
||||
glitchtipEnvironment:
|
||||
settings.glitchtipEnvironment ?? "production",
|
||||
bugReportRepo: settings.githubIssueRepo,
|
||||
bugReportConfigured: Boolean(
|
||||
settings.githubIssueRepo && settings.githubIssueTokenEncrypted,
|
||||
),
|
||||
reminderLateMinutes: settings.reminderLateMinutes,
|
||||
reminderMissedMinutes: settings.reminderMissedMinutes,
|
||||
moodLogGlobal: settings.moodLogGlobal,
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,93 @@
|
||||
import { prisma } from "@/lib/db";
|
||||
import { apiHandler, requireAdmin } from "@/lib/api-handler";
|
||||
import { apiSuccess } from "@/lib/api-response";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
import { getWorkerStatus } from "@/lib/jobs/worker-status";
|
||||
import { readFileSync } from "node:fs";
|
||||
|
||||
// Build timestamp (set at build time via next.config)
|
||||
const BUILD_TIME = process.env.BUILD_TIMESTAMP || new Date().toISOString();
|
||||
const START_TIME = new Date().toISOString();
|
||||
|
||||
// Try to read git commit info
|
||||
let gitCommit = process.env.GIT_COMMIT ?? "unknown";
|
||||
try {
|
||||
const head = readFileSync(".git/HEAD", "utf-8").trim();
|
||||
if (head.startsWith("ref:")) {
|
||||
const ref = head.replace("ref: ", "");
|
||||
gitCommit = readFileSync(`.git/${ref}`, "utf-8").trim().slice(0, 8);
|
||||
} else {
|
||||
gitCommit = head.slice(0, 8);
|
||||
}
|
||||
} catch {
|
||||
// In Docker or production, .git may not exist
|
||||
}
|
||||
|
||||
export const GET = apiHandler(async () => {
|
||||
await requireAdmin();
|
||||
annotate({ action: { name: "admin.status" } });
|
||||
|
||||
const [
|
||||
userCount,
|
||||
measurementCount,
|
||||
medicationCount,
|
||||
intakeEventCount,
|
||||
tokenCount,
|
||||
sessionCount,
|
||||
appSettings,
|
||||
] = await Promise.all([
|
||||
prisma.user.count(),
|
||||
prisma.measurement.count(),
|
||||
prisma.medication.count(),
|
||||
prisma.medicationIntakeEvent.count(),
|
||||
prisma.apiToken.count({ where: { revoked: false } }),
|
||||
prisma.session.count(),
|
||||
prisma.appSettings.findUnique({ where: { id: "singleton" } }),
|
||||
]);
|
||||
|
||||
const umamiConfigured = Boolean(
|
||||
appSettings?.umamiScriptUrl && appSettings?.umamiWebsiteId,
|
||||
);
|
||||
const glitchtipConfigured = Boolean(appSettings?.glitchtipDsn);
|
||||
const webPushConfigured = Boolean(
|
||||
appSettings?.webPushVapidPublicKey &&
|
||||
appSettings?.webPushVapidPrivateKeyEncrypted &&
|
||||
appSettings?.webPushVapidSubject,
|
||||
);
|
||||
const bugReportConfigured = Boolean(
|
||||
appSettings?.githubIssueRepo && appSettings?.githubIssueTokenEncrypted,
|
||||
);
|
||||
|
||||
const workerStatus = getWorkerStatus();
|
||||
|
||||
return apiSuccess({
|
||||
version: process.env.npm_package_version ?? "0.1.0",
|
||||
nodeVersion: process.version,
|
||||
gitCommit,
|
||||
buildTime: BUILD_TIME,
|
||||
startTime: START_TIME,
|
||||
database: "connected",
|
||||
worker: workerStatus,
|
||||
counts: {
|
||||
users: userCount,
|
||||
measurements: measurementCount,
|
||||
medications: medicationCount,
|
||||
intakeEvents: intakeEventCount,
|
||||
activeTokens: tokenCount,
|
||||
activeSessions: sessionCount,
|
||||
},
|
||||
integrations: {
|
||||
umami: umamiConfigured
|
||||
? { configured: true, enabled: appSettings?.umamiEnabled ?? false }
|
||||
: null,
|
||||
glitchtip: glitchtipConfigured
|
||||
? {
|
||||
configured: true,
|
||||
enabled: appSettings?.glitchtipEnabled ?? false,
|
||||
}
|
||||
: null,
|
||||
webPush: webPushConfigured ? { configured: true } : null,
|
||||
bugReport: bugReportConfigured ? { configured: true } : null,
|
||||
},
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,29 @@
|
||||
import { prisma } from "@/lib/db";
|
||||
import { apiHandler, requireAdmin } from "@/lib/api-handler";
|
||||
import { apiSuccess } from "@/lib/api-response";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export const GET = apiHandler(async () => {
|
||||
await requireAdmin();
|
||||
annotate({ action: { name: "admin.tokens.list" } });
|
||||
|
||||
const tokens = await prisma.apiToken.findMany({
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
permissions: true,
|
||||
lastUsedAt: true,
|
||||
expiresAt: true,
|
||||
createdAt: true,
|
||||
revoked: true,
|
||||
user: {
|
||||
select: { id: true, username: true },
|
||||
},
|
||||
},
|
||||
orderBy: { createdAt: "desc" },
|
||||
});
|
||||
|
||||
return apiSuccess(tokens);
|
||||
});
|
||||
@@ -0,0 +1,65 @@
|
||||
import { prisma } from "@/lib/db";
|
||||
import { apiHandler, requireAdmin } from "@/lib/api-handler";
|
||||
import { hashPassword, checkPasswordStrength } from "@/lib/auth/password";
|
||||
import { auditLog } from "@/lib/auth/audit";
|
||||
import { apiSuccess, apiError, getClientIp, safeJson } from "@/lib/api-response";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
import { checkRateLimit, rateLimitHeaders } from "@/lib/rate-limit";
|
||||
import { destroyAllSessions } from "@/lib/auth/session";
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
|
||||
export const POST = apiHandler(async (
|
||||
request: NextRequest,
|
||||
{ params }: { params: Promise<{ id: string }> },
|
||||
) => {
|
||||
const ip = getClientIp(request);
|
||||
const rl = await checkRateLimit(`admin-reset-pw:${ip}`, 10, 60 * 1000);
|
||||
if (!rl.allowed) {
|
||||
return NextResponse.json(
|
||||
{ data: null, error: "Rate limit exceeded" },
|
||||
{ status: 429, headers: rateLimitHeaders(rl) },
|
||||
);
|
||||
}
|
||||
|
||||
const { user } = await requireAdmin();
|
||||
|
||||
const { id } = await params;
|
||||
annotate({ action: { name: "admin.users.reset-password", entity_type: "user", entity_id: id } });
|
||||
|
||||
const { data: body, error: jsonError } = await safeJson(request);
|
||||
|
||||
if (jsonError) return jsonError;
|
||||
const { password } = body as { password?: string };
|
||||
|
||||
if (!password || typeof password !== "string") {
|
||||
return apiError("Passwort erforderlich", 422);
|
||||
}
|
||||
|
||||
const target = await prisma.user.findUnique({ where: { id } });
|
||||
if (!target) return apiError("Benutzer nicht gefunden", 404);
|
||||
|
||||
const strength = checkPasswordStrength(password, [target.username]);
|
||||
if (!strength.isAcceptable) {
|
||||
return apiError(
|
||||
strength.feedback[0] || "Passwort zu schwach (Score < 3)",
|
||||
422,
|
||||
);
|
||||
}
|
||||
|
||||
const passwordHash = await hashPassword(password);
|
||||
await prisma.user.update({
|
||||
where: { id },
|
||||
data: { passwordHash },
|
||||
});
|
||||
|
||||
// Invalidate all sessions of the target user
|
||||
await destroyAllSessions(id);
|
||||
|
||||
await auditLog("admin.user.reset-password", {
|
||||
userId: user.id,
|
||||
ipAddress: getClientIp(request),
|
||||
details: { targetUserId: id },
|
||||
});
|
||||
|
||||
return apiSuccess({ success: true });
|
||||
});
|
||||
@@ -0,0 +1,68 @@
|
||||
import { prisma } from "@/lib/db";
|
||||
import { apiHandler, requireAdmin } from "@/lib/api-handler";
|
||||
import { auditLog } from "@/lib/auth/audit";
|
||||
import { apiSuccess, apiError, getClientIp, safeJson } from "@/lib/api-response";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
import { NextRequest } from "next/server";
|
||||
import { z } from "zod/v4";
|
||||
|
||||
const updateUserSchema = z.object({
|
||||
username: z.string().min(3).max(30).optional(),
|
||||
email: z.string().email().nullable().optional(),
|
||||
role: z.enum(["ADMIN", "USER"]).optional(),
|
||||
});
|
||||
|
||||
export const PUT = apiHandler(async (
|
||||
request: NextRequest,
|
||||
{ params }: { params: Promise<{ id: string }> },
|
||||
) => {
|
||||
const { user } = await requireAdmin();
|
||||
|
||||
const { id } = await params;
|
||||
annotate({ action: { name: "admin.users.update", entity_type: "user", entity_id: id } });
|
||||
|
||||
const { data: body, error: jsonError } = await safeJson(request);
|
||||
|
||||
if (jsonError) return jsonError;
|
||||
const parsed = updateUserSchema.safeParse(body);
|
||||
if (!parsed.success) {
|
||||
return apiError(parsed.error.issues[0].message, 422);
|
||||
}
|
||||
|
||||
const target = await prisma.user.findUnique({ where: { id } });
|
||||
if (!target) return apiError("Benutzer nicht gefunden", 404);
|
||||
|
||||
// Prevent removing the last admin
|
||||
if (parsed.data.role === "USER" && target.role === "ADMIN") {
|
||||
const adminCount = await prisma.user.count({ where: { role: "ADMIN" } });
|
||||
if (adminCount <= 1) {
|
||||
return apiError("Der letzte Admin kann nicht degradiert werden", 400);
|
||||
}
|
||||
}
|
||||
|
||||
const updatedUser = await prisma.user.update({
|
||||
where: { id },
|
||||
data: {
|
||||
...(parsed.data.username !== undefined && {
|
||||
username: parsed.data.username,
|
||||
}),
|
||||
...(parsed.data.email !== undefined && { email: parsed.data.email }),
|
||||
...(parsed.data.role !== undefined && { role: parsed.data.role }),
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
username: true,
|
||||
email: true,
|
||||
role: true,
|
||||
createdAt: true,
|
||||
},
|
||||
});
|
||||
|
||||
await auditLog("admin.user.update", {
|
||||
userId: user.id,
|
||||
ipAddress: getClientIp(request),
|
||||
details: { targetUserId: id, changes: parsed.data },
|
||||
});
|
||||
|
||||
return apiSuccess(updatedUser);
|
||||
});
|
||||
@@ -0,0 +1,34 @@
|
||||
import { prisma } from "@/lib/db";
|
||||
import { apiHandler, requireAdmin } from "@/lib/api-handler";
|
||||
import { apiSuccess } from "@/lib/api-response";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export const GET = apiHandler(async () => {
|
||||
await requireAdmin();
|
||||
annotate({ action: { name: "admin.users.list" } });
|
||||
|
||||
const users = await prisma.user.findMany({
|
||||
select: {
|
||||
id: true,
|
||||
username: true,
|
||||
email: true,
|
||||
role: true,
|
||||
createdAt: true,
|
||||
_count: { select: { passkeys: true } },
|
||||
},
|
||||
orderBy: { createdAt: "asc" },
|
||||
});
|
||||
|
||||
return apiSuccess(
|
||||
users.map((u) => ({
|
||||
id: u.id,
|
||||
username: u.username,
|
||||
email: u.email,
|
||||
role: u.role,
|
||||
createdAt: u.createdAt,
|
||||
passkeyCount: u._count.passkeys,
|
||||
})),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,118 @@
|
||||
import { prisma } from "@/lib/db";
|
||||
import { apiHandler, requireAuth } from "@/lib/api-handler";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
import { apiSuccess } from "@/lib/api-response";
|
||||
import { summarize, type DataPoint } from "@/lib/analytics/trends";
|
||||
import { getBpTargets } from "@/lib/analytics/bp-targets";
|
||||
import type { MeasurementType } from "@/generated/prisma/client";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export const GET = apiHandler(async () => {
|
||||
const { user } = await requireAuth();
|
||||
annotate({ action: { name: "analytics.get" } });
|
||||
|
||||
const types: MeasurementType[] = [
|
||||
"WEIGHT",
|
||||
"BLOOD_PRESSURE_SYS",
|
||||
"BLOOD_PRESSURE_DIA",
|
||||
"PULSE",
|
||||
"BODY_FAT",
|
||||
"SLEEP_DURATION",
|
||||
"ACTIVITY_STEPS",
|
||||
];
|
||||
|
||||
const measurementsByType = await Promise.all(
|
||||
types.map((type) =>
|
||||
prisma.measurement
|
||||
.findMany({
|
||||
where: { userId: user.id, type },
|
||||
orderBy: { measuredAt: "asc" },
|
||||
select: { value: true, measuredAt: true },
|
||||
})
|
||||
.then((measurements) => ({
|
||||
type,
|
||||
summary: summarize(
|
||||
measurements.map(
|
||||
(m): DataPoint => ({
|
||||
date: m.measuredAt,
|
||||
value: m.value,
|
||||
}),
|
||||
),
|
||||
),
|
||||
})),
|
||||
),
|
||||
);
|
||||
|
||||
const results: Record<string, ReturnType<typeof summarize>> = {};
|
||||
for (const { type, summary } of measurementsByType) {
|
||||
results[type] = summary;
|
||||
}
|
||||
|
||||
// BMI calculation
|
||||
let bmi: number | null = null;
|
||||
if (user.heightCm && results.WEIGHT?.latest) {
|
||||
const heightM = user.heightCm / 100;
|
||||
bmi = Math.round((results.WEIGHT.latest / (heightM * heightM)) * 10) / 10;
|
||||
}
|
||||
|
||||
// BP in-target percentage (auto-calculated from date of birth)
|
||||
let bpInTargetPct: number | null = null;
|
||||
const bpTargets = getBpTargets(user.dateOfBirth);
|
||||
if (bpTargets) {
|
||||
const thirtyDaysAgo = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000);
|
||||
const [sysData, diaData] = await Promise.all([
|
||||
prisma.measurement.findMany({
|
||||
where: {
|
||||
userId: user.id,
|
||||
type: "BLOOD_PRESSURE_SYS",
|
||||
measuredAt: { gte: thirtyDaysAgo },
|
||||
},
|
||||
select: { measuredAt: true, value: true },
|
||||
}),
|
||||
prisma.measurement.findMany({
|
||||
where: {
|
||||
userId: user.id,
|
||||
type: "BLOOD_PRESSURE_DIA",
|
||||
measuredAt: { gte: thirtyDaysAgo },
|
||||
},
|
||||
select: { measuredAt: true, value: true },
|
||||
}),
|
||||
]);
|
||||
|
||||
if (sysData.length > 0 && diaData.length > 0) {
|
||||
let inTarget = 0;
|
||||
for (const sys of sysData) {
|
||||
const closestDia = diaData.reduce((closest, dia) =>
|
||||
Math.abs(dia.measuredAt.getTime() - sys.measuredAt.getTime()) <
|
||||
Math.abs(closest.measuredAt.getTime() - sys.measuredAt.getTime())
|
||||
? dia
|
||||
: closest,
|
||||
);
|
||||
const timeDiff = Math.abs(
|
||||
closestDia.measuredAt.getTime() - sys.measuredAt.getTime(),
|
||||
);
|
||||
if (timeDiff < 5 * 60 * 1000) {
|
||||
if (
|
||||
sys.value >= bpTargets.sysLow &&
|
||||
sys.value <= bpTargets.sysHigh &&
|
||||
closestDia.value >= bpTargets.diaLow &&
|
||||
closestDia.value <= bpTargets.diaHigh
|
||||
) {
|
||||
inTarget++;
|
||||
}
|
||||
}
|
||||
}
|
||||
bpInTargetPct =
|
||||
sysData.length > 0
|
||||
? Math.round((inTarget / sysData.length) * 100)
|
||||
: null;
|
||||
}
|
||||
}
|
||||
|
||||
return apiSuccess({
|
||||
summaries: results,
|
||||
bmi,
|
||||
bpInTargetPct,
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,46 @@
|
||||
import { prisma } from "@/lib/db";
|
||||
import { apiHandler, requireAuth } from "@/lib/api-handler";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
import { apiSuccess } from "@/lib/api-response";
|
||||
import { NextRequest } from "next/server";
|
||||
|
||||
/**
|
||||
* Get audit log entries for the current user.
|
||||
* Query params: limit (default 50, max 200), offset (default 0)
|
||||
*/
|
||||
export const GET = apiHandler(async (request: NextRequest) => {
|
||||
const { user } = await requireAuth();
|
||||
annotate({ action: { name: "audit-log.list" } });
|
||||
|
||||
const { searchParams } = new URL(request.url);
|
||||
const limit = Math.min(
|
||||
Math.max(1, parseInt(searchParams.get("limit") ?? "50", 10) || 50),
|
||||
200,
|
||||
);
|
||||
const offset = Math.max(
|
||||
0,
|
||||
parseInt(searchParams.get("offset") ?? "0", 10) || 0,
|
||||
);
|
||||
|
||||
const [entries, total] = await Promise.all([
|
||||
prisma.auditLog.findMany({
|
||||
where: { userId: user.id },
|
||||
orderBy: { createdAt: "desc" },
|
||||
take: limit,
|
||||
skip: offset,
|
||||
select: {
|
||||
id: true,
|
||||
action: true,
|
||||
ipAddress: true,
|
||||
location: true,
|
||||
details: true,
|
||||
createdAt: true,
|
||||
},
|
||||
}),
|
||||
prisma.auditLog.count({
|
||||
where: { userId: user.id },
|
||||
}),
|
||||
]);
|
||||
|
||||
return apiSuccess({ entries, meta: { total, limit, offset } });
|
||||
});
|
||||
@@ -0,0 +1,80 @@
|
||||
import { prisma } from "@/lib/db";
|
||||
import { loginPasswordSchema } from "@/lib/validations/auth";
|
||||
import { verifyPassword } from "@/lib/auth/password";
|
||||
import { createSession } from "@/lib/auth/session";
|
||||
import { auditLog } from "@/lib/auth/audit";
|
||||
import { apiSuccess, apiError, getClientIp, safeJson } from "@/lib/api-response";
|
||||
import { checkRateLimit, rateLimitHeaders } from "@/lib/rate-limit";
|
||||
import { ensureDbCompatibility } from "@/lib/db-compat";
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { apiHandler } from "@/lib/api-handler";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
|
||||
export const POST = apiHandler(async (request: NextRequest) => {
|
||||
const ip = getClientIp(request) ?? "unknown";
|
||||
const rl = await checkRateLimit(`auth:login:${ip}`, 5, 15 * 60 * 1000);
|
||||
if (!rl.allowed) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
data: null,
|
||||
error: "Zu viele Anmeldeversuche. Bitte später erneut versuchen.",
|
||||
},
|
||||
{ status: 429, headers: rateLimitHeaders(rl) },
|
||||
);
|
||||
}
|
||||
|
||||
await ensureDbCompatibility();
|
||||
|
||||
const { data: body, error: jsonError } = await safeJson(request);
|
||||
|
||||
if (jsonError) return jsonError;
|
||||
const parsed = loginPasswordSchema.safeParse(body);
|
||||
|
||||
if (!parsed.success) {
|
||||
return apiError("Ungültige Anmeldedaten", 422);
|
||||
}
|
||||
|
||||
const { email, password } = parsed.data;
|
||||
const identifier = email.trim();
|
||||
|
||||
const user = await prisma.user.findFirst({
|
||||
where: {
|
||||
OR: [
|
||||
{ email: { equals: identifier, mode: "insensitive" } },
|
||||
{ username: { equals: identifier, mode: "insensitive" } },
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
if (!user || !user.passwordHash) {
|
||||
await auditLog("auth.login.failed", {
|
||||
ipAddress: ip,
|
||||
details: { identifier, reason: "user_not_found_or_no_password" },
|
||||
});
|
||||
return apiError("Ungültige Anmeldedaten", 401);
|
||||
}
|
||||
|
||||
const valid = await verifyPassword(user.passwordHash, password);
|
||||
if (!valid) {
|
||||
await auditLog("auth.login.failed", {
|
||||
userId: user.id,
|
||||
ipAddress: ip,
|
||||
details: { reason: "invalid_password" },
|
||||
});
|
||||
return apiError("Ungültige Anmeldedaten", 401);
|
||||
}
|
||||
|
||||
const ua = request.headers.get("user-agent");
|
||||
await createSession(user.id, ip, ua);
|
||||
|
||||
await auditLog("auth.login.password", {
|
||||
userId: user.id,
|
||||
ipAddress: ip,
|
||||
});
|
||||
|
||||
annotate({ action: { name: "auth.login.password" } });
|
||||
|
||||
return apiSuccess({
|
||||
user: { id: user.id, username: user.username },
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,12 @@
|
||||
import { destroySession } from "@/lib/auth/session";
|
||||
import { apiSuccess } from "@/lib/api-response";
|
||||
import { apiHandler } from "@/lib/api-handler";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
|
||||
export const POST = apiHandler(async () => {
|
||||
await destroySession();
|
||||
|
||||
annotate({ action: { name: "auth.logout" } });
|
||||
|
||||
return apiSuccess({ loggedOut: true });
|
||||
});
|
||||
@@ -0,0 +1,25 @@
|
||||
import { apiSuccess } from "@/lib/api-response";
|
||||
import { getGravatarUrl } from "@/lib/gravatar";
|
||||
import { apiHandler, requireAuth } from "@/lib/api-handler";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export const GET = apiHandler(async () => {
|
||||
const { user } = await requireAuth();
|
||||
|
||||
annotate({ action: { name: "auth.me" } });
|
||||
|
||||
return apiSuccess({
|
||||
id: user.id,
|
||||
username: user.username,
|
||||
email: user.email,
|
||||
role: user.role ?? "USER",
|
||||
heightCm: user.heightCm,
|
||||
dateOfBirth: user.dateOfBirth,
|
||||
gender: user.gender,
|
||||
timezone: user.timezone,
|
||||
onboardingCompletedAt: user.onboardingCompletedAt,
|
||||
gravatarUrl: user.email ? getGravatarUrl(user.email) : null,
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,30 @@
|
||||
import { createAuthenticationOptions } from "@/lib/auth/passkey";
|
||||
import { apiSuccess, getClientIp } from "@/lib/api-response";
|
||||
import { checkRateLimit, rateLimitHeaders } from "@/lib/rate-limit";
|
||||
import { NextResponse } from "next/server";
|
||||
import { apiHandler } from "@/lib/api-handler";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
|
||||
export const POST = apiHandler(async (request: Request) => {
|
||||
const ip = getClientIp(request) ?? "unknown";
|
||||
const rl = await checkRateLimit(
|
||||
`auth:passkey-login-options:${ip}`,
|
||||
10,
|
||||
15 * 60 * 1000,
|
||||
);
|
||||
if (!rl.allowed) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
data: null,
|
||||
error: "Zu viele Passkey-Anfragen. Bitte später erneut versuchen.",
|
||||
},
|
||||
{ status: 429, headers: rateLimitHeaders(rl) },
|
||||
);
|
||||
}
|
||||
|
||||
const { options, challengeId } = await createAuthenticationOptions();
|
||||
|
||||
annotate({ action: { name: "auth.passkey.login-options" } });
|
||||
|
||||
return apiSuccess({ options, challengeId });
|
||||
});
|
||||
@@ -0,0 +1,65 @@
|
||||
import { verifyAuthentication } from "@/lib/auth/passkey";
|
||||
import { createSession } from "@/lib/auth/session";
|
||||
import { auditLog } from "@/lib/auth/audit";
|
||||
import { apiSuccess, apiError, getClientIp, safeJson } from "@/lib/api-response";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { ensureDbCompatibility } from "@/lib/db-compat";
|
||||
import { checkRateLimit } from "@/lib/rate-limit";
|
||||
import { NextRequest } from "next/server";
|
||||
import { apiHandler } from "@/lib/api-handler";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
|
||||
export const POST = apiHandler(async (request: NextRequest) => {
|
||||
await ensureDbCompatibility();
|
||||
|
||||
const ip = getClientIp(request);
|
||||
const rl = await checkRateLimit(`auth:passkey-verify:${ip}`, 10, 15 * 60 * 1000);
|
||||
if (!rl.allowed) {
|
||||
return apiError("Zu viele Versuche. Bitte 15 Minuten warten.", 429);
|
||||
}
|
||||
|
||||
const { data: body, error: jsonError } = await safeJson<Record<string, unknown>>(request);
|
||||
|
||||
if (jsonError) return jsonError;
|
||||
const challengeId = body.challengeId as string | undefined;
|
||||
const credential = body.credential;
|
||||
|
||||
if (!challengeId || !credential) {
|
||||
return apiError("challengeId und credential erforderlich", 422);
|
||||
}
|
||||
|
||||
const { verification, passkey } = await verifyAuthentication(
|
||||
challengeId,
|
||||
credential,
|
||||
);
|
||||
|
||||
if (!verification.verified) {
|
||||
await auditLog("auth.login.failed", {
|
||||
ipAddress: ip,
|
||||
details: { reason: "passkey_verification_failed" },
|
||||
});
|
||||
return apiError("Passkey-Verifizierung fehlgeschlagen", 401);
|
||||
}
|
||||
|
||||
const user = await prisma.user.findUnique({
|
||||
where: { id: passkey.userId },
|
||||
});
|
||||
|
||||
if (!user) {
|
||||
return apiError("Benutzer nicht gefunden", 404);
|
||||
}
|
||||
|
||||
const ua = request.headers.get("user-agent");
|
||||
await createSession(user.id, ip, ua);
|
||||
|
||||
await auditLog("auth.login.passkey", {
|
||||
userId: user.id,
|
||||
ipAddress: ip,
|
||||
});
|
||||
|
||||
annotate({ action: { name: "auth.login.passkey" } });
|
||||
|
||||
return apiSuccess({
|
||||
user: { id: user.id, username: user.username },
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,17 @@
|
||||
import { createRegistrationOptions } from "@/lib/auth/passkey";
|
||||
import { apiSuccess } from "@/lib/api-response";
|
||||
import { apiHandler, requireAuth } from "@/lib/api-handler";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
|
||||
export const POST = apiHandler(async () => {
|
||||
const { user } = await requireAuth();
|
||||
|
||||
const { options, challengeId } = await createRegistrationOptions(
|
||||
user.id,
|
||||
user.email ?? user.username,
|
||||
);
|
||||
|
||||
annotate({ action: { name: "auth.passkey.register-options" } });
|
||||
|
||||
return apiSuccess({ options, challengeId });
|
||||
});
|
||||
@@ -0,0 +1,50 @@
|
||||
import { prisma } from "@/lib/db";
|
||||
import { verifyRegistration } from "@/lib/auth/passkey";
|
||||
import { auditLog } from "@/lib/auth/audit";
|
||||
import { apiSuccess, apiError, getClientIp, safeJson } from "@/lib/api-response";
|
||||
import { NextRequest } from "next/server";
|
||||
import { apiHandler, requireAuth } from "@/lib/api-handler";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
|
||||
export const POST = apiHandler(async (request: NextRequest) => {
|
||||
const { user } = await requireAuth();
|
||||
|
||||
const { data: body, error: jsonError } = await safeJson<Record<string, unknown>>(request);
|
||||
|
||||
if (jsonError) return jsonError;
|
||||
const challengeId = body.challengeId as string | undefined;
|
||||
const credential = body.credential as Record<string, unknown> | undefined;
|
||||
|
||||
if (!challengeId || !credential) {
|
||||
return apiError("challengeId und credential erforderlich", 422);
|
||||
}
|
||||
|
||||
const verification = await verifyRegistration(challengeId, credential);
|
||||
|
||||
if (!verification.verified || !verification.registrationInfo) {
|
||||
return apiError("Passkey-Verifizierung fehlgeschlagen", 400);
|
||||
}
|
||||
|
||||
const { registrationInfo } = verification;
|
||||
|
||||
await prisma.passkey.create({
|
||||
data: {
|
||||
userId: user.id,
|
||||
credentialId: registrationInfo.credential.id,
|
||||
credentialPublicKey: Buffer.from(registrationInfo.credential.publicKey),
|
||||
counter: BigInt(registrationInfo.credential.counter),
|
||||
credentialDeviceType: registrationInfo.credentialDeviceType,
|
||||
credentialBackedUp: registrationInfo.credentialBackedUp,
|
||||
transports: ((credential.response as Record<string, unknown> | undefined)?.transports as string[]) ?? [],
|
||||
},
|
||||
});
|
||||
|
||||
await auditLog("auth.passkey.register", {
|
||||
userId: user.id,
|
||||
ipAddress: getClientIp(request),
|
||||
});
|
||||
|
||||
annotate({ action: { name: "auth.passkey.register" } });
|
||||
|
||||
return apiSuccess({ verified: true });
|
||||
});
|
||||
@@ -0,0 +1,48 @@
|
||||
import { prisma } from "@/lib/db";
|
||||
import { auditLog } from "@/lib/auth/audit";
|
||||
import { apiSuccess, apiError, getClientIp } from "@/lib/api-response";
|
||||
import { NextRequest } from "next/server";
|
||||
import { apiHandler, requireAuth } from "@/lib/api-handler";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
|
||||
export const DELETE = apiHandler(async (
|
||||
request: NextRequest,
|
||||
{ params }: { params: Promise<{ id: string }> },
|
||||
) => {
|
||||
const { user } = await requireAuth();
|
||||
|
||||
const { id } = await params;
|
||||
|
||||
const passkey = await prisma.passkey.findUnique({
|
||||
where: { id },
|
||||
});
|
||||
|
||||
if (!passkey || passkey.userId !== user.id) {
|
||||
return apiError("Passkey nicht gefunden", 404);
|
||||
}
|
||||
|
||||
// Check: at least 1 auth method must remain
|
||||
const passkeyCount = await prisma.passkey.count({
|
||||
where: { userId: user.id },
|
||||
});
|
||||
const hasPassword = !!user.passwordHash;
|
||||
|
||||
if (passkeyCount <= 1 && !hasPassword) {
|
||||
return apiError(
|
||||
"Kann nicht gelöscht werden — es muss mindestens eine Anmeldemethode bestehen bleiben",
|
||||
400,
|
||||
);
|
||||
}
|
||||
|
||||
await prisma.passkey.delete({ where: { id } });
|
||||
|
||||
await auditLog("auth.passkey.delete", {
|
||||
userId: user.id,
|
||||
ipAddress: getClientIp(request),
|
||||
details: { passkeyId: id, passkeyName: passkey.name },
|
||||
});
|
||||
|
||||
annotate({ action: { name: "auth.passkey.delete" } });
|
||||
|
||||
return apiSuccess({ success: true });
|
||||
});
|
||||
@@ -0,0 +1,26 @@
|
||||
import { prisma } from "@/lib/db";
|
||||
import { apiSuccess } from "@/lib/api-response";
|
||||
import { apiHandler, requireAuth } from "@/lib/api-handler";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export const GET = apiHandler(async () => {
|
||||
const { user } = await requireAuth();
|
||||
|
||||
const passkeys = await prisma.passkey.findMany({
|
||||
where: { userId: user.id },
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
credentialDeviceType: true,
|
||||
credentialBackedUp: true,
|
||||
createdAt: true,
|
||||
},
|
||||
orderBy: { createdAt: "desc" },
|
||||
});
|
||||
|
||||
annotate({ action: { name: "auth.passkeys.list" } });
|
||||
|
||||
return apiSuccess(passkeys);
|
||||
});
|
||||
@@ -0,0 +1,92 @@
|
||||
import { NextRequest } from "next/server";
|
||||
import { prisma } from "@/lib/db";
|
||||
import {
|
||||
verifyPassword,
|
||||
hashPassword,
|
||||
checkPasswordStrength,
|
||||
} from "@/lib/auth/password";
|
||||
import { changePasswordSchema } from "@/lib/validations/auth";
|
||||
import { auditLog } from "@/lib/auth/audit";
|
||||
import { apiSuccess, apiError, getClientIp, safeJson } from "@/lib/api-response";
|
||||
import { checkRateLimit } from "@/lib/rate-limit";
|
||||
import { apiHandler, requireAuth } from "@/lib/api-handler";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
import { destroyAllSessions, createSession } from "@/lib/auth/session";
|
||||
|
||||
export const POST = apiHandler(async (request: NextRequest) => {
|
||||
const { user } = await requireAuth();
|
||||
|
||||
const rl = await checkRateLimit(
|
||||
`auth:password:${user.id}`,
|
||||
5,
|
||||
15 * 60 * 1000,
|
||||
);
|
||||
if (!rl.allowed) {
|
||||
return apiError(
|
||||
"Zu viele Versuche. Bitte 15 Minuten warten.",
|
||||
429,
|
||||
);
|
||||
}
|
||||
|
||||
const { data: body, error: jsonError } = await safeJson(request);
|
||||
|
||||
if (jsonError) return jsonError;
|
||||
const parsed = changePasswordSchema.safeParse(body);
|
||||
if (!parsed.success) {
|
||||
return apiError(parsed.error.issues[0].message, 422);
|
||||
}
|
||||
|
||||
const { currentPassword, newPassword } = parsed.data;
|
||||
if (!user.passwordHash) {
|
||||
return apiError("Für dieses Konto ist kein Passwort gesetzt", 400);
|
||||
}
|
||||
|
||||
const currentValid = await verifyPassword(
|
||||
user.passwordHash,
|
||||
currentPassword,
|
||||
);
|
||||
if (!currentValid) {
|
||||
return apiError("Aktuelles Passwort ist falsch", 401);
|
||||
}
|
||||
|
||||
if (currentPassword === newPassword) {
|
||||
return apiError(
|
||||
"Neues Passwort muss sich vom aktuellen unterscheiden",
|
||||
422,
|
||||
);
|
||||
}
|
||||
|
||||
const strength = checkPasswordStrength(newPassword, [
|
||||
user.username,
|
||||
user.email ?? "",
|
||||
]);
|
||||
if (!strength.isAcceptable) {
|
||||
return apiError(
|
||||
strength.feedback[0] || "Passwort zu schwach (Score < 3)",
|
||||
422,
|
||||
);
|
||||
}
|
||||
|
||||
const newHash = await hashPassword(newPassword);
|
||||
await prisma.user.update({
|
||||
where: { id: user.id },
|
||||
data: { passwordHash: newHash },
|
||||
});
|
||||
|
||||
// Invalidate all existing sessions and create a fresh one
|
||||
await destroyAllSessions(user.id);
|
||||
await createSession(
|
||||
user.id,
|
||||
getClientIp(request),
|
||||
request.headers.get("user-agent"),
|
||||
);
|
||||
|
||||
await auditLog("auth.password.change", {
|
||||
userId: user.id,
|
||||
ipAddress: getClientIp(request),
|
||||
});
|
||||
|
||||
annotate({ action: { name: "auth.password.change" } });
|
||||
|
||||
return apiSuccess({ changed: true });
|
||||
});
|
||||
@@ -0,0 +1,62 @@
|
||||
import { prisma } from "@/lib/db";
|
||||
import { profileSchema } from "@/lib/validations/auth";
|
||||
import { auditLog } from "@/lib/auth/audit";
|
||||
import { apiSuccess, apiError, getClientIp, safeJson } from "@/lib/api-response";
|
||||
import { NextRequest } from "next/server";
|
||||
import { apiHandler, requireAuth } from "@/lib/api-handler";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
|
||||
export const PUT = apiHandler(async (request: NextRequest) => {
|
||||
const { user } = await requireAuth();
|
||||
|
||||
const { data: body, error: jsonError } = await safeJson(request);
|
||||
|
||||
if (jsonError) return jsonError;
|
||||
const parsed = profileSchema.safeParse(body);
|
||||
|
||||
if (!parsed.success) {
|
||||
return apiError(parsed.error.issues[0].message, 422);
|
||||
}
|
||||
|
||||
const data = parsed.data;
|
||||
const normalizedEmail = data.email ? data.email.trim().toLowerCase() : null;
|
||||
|
||||
if (data.email !== undefined && normalizedEmail) {
|
||||
const existingUser = await prisma.user.findUnique({
|
||||
where: { email: normalizedEmail },
|
||||
select: { id: true },
|
||||
});
|
||||
|
||||
if (existingUser && existingUser.id !== user.id) {
|
||||
return apiError("E-Mail-Adresse wird bereits verwendet", 409);
|
||||
}
|
||||
}
|
||||
|
||||
const updatedUser = await prisma.user.update({
|
||||
where: { id: user.id },
|
||||
data: {
|
||||
...(data.email !== undefined ? { email: normalizedEmail } : {}),
|
||||
heightCm: data.heightCm ?? null,
|
||||
dateOfBirth: data.dateOfBirth ? new Date(data.dateOfBirth) : null,
|
||||
...(data.gender !== undefined ? { gender: data.gender } : {}),
|
||||
},
|
||||
});
|
||||
|
||||
await auditLog("profile.update", {
|
||||
userId: updatedUser.id,
|
||||
ipAddress: getClientIp(request),
|
||||
});
|
||||
|
||||
annotate({ action: { name: "auth.profile.update" } });
|
||||
|
||||
return apiSuccess({
|
||||
id: updatedUser.id,
|
||||
username: updatedUser.username,
|
||||
email: updatedUser.email,
|
||||
role: updatedUser.role,
|
||||
heightCm: updatedUser.heightCm,
|
||||
dateOfBirth: updatedUser.dateOfBirth,
|
||||
gender: updatedUser.gender,
|
||||
timezone: updatedUser.timezone,
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,109 @@
|
||||
import { prisma } from "@/lib/db";
|
||||
import { registerSchema } from "@/lib/validations/auth";
|
||||
import { hashPassword, checkPasswordStrength } from "@/lib/auth/password";
|
||||
import { createSession } from "@/lib/auth/session";
|
||||
import { auditLog } from "@/lib/auth/audit";
|
||||
import { apiSuccess, apiError, getClientIp, safeJson } from "@/lib/api-response";
|
||||
import { checkRateLimit, rateLimitHeaders } from "@/lib/rate-limit";
|
||||
import { ensureDbCompatibility } from "@/lib/db-compat";
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { apiHandler } from "@/lib/api-handler";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
|
||||
export const POST = apiHandler(async (request: NextRequest) => {
|
||||
const ip = getClientIp(request) ?? "unknown";
|
||||
const rl = await checkRateLimit(`auth:register:${ip}`, 5, 15 * 60 * 1000);
|
||||
if (!rl.allowed) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
data: null,
|
||||
error:
|
||||
"Zu viele Registrierungsversuche. Bitte später erneut versuchen.",
|
||||
},
|
||||
{ status: 429, headers: rateLimitHeaders(rl) },
|
||||
);
|
||||
}
|
||||
|
||||
await ensureDbCompatibility();
|
||||
|
||||
const userCount = await prisma.user.count();
|
||||
|
||||
// Check if registration is enabled.
|
||||
// Safety valve: when there are zero users, always allow bootstrap registration.
|
||||
let registrationEnabled = true;
|
||||
try {
|
||||
const settings = await prisma.appSettings.findUnique({
|
||||
where: { id: "singleton" },
|
||||
});
|
||||
if (settings && !settings.registrationEnabled && userCount > 0) {
|
||||
registrationEnabled = false;
|
||||
}
|
||||
} catch {
|
||||
// Table may not exist yet; allow registration
|
||||
}
|
||||
if (!registrationEnabled) {
|
||||
return apiError("Registrierung ist deaktiviert", 403);
|
||||
}
|
||||
|
||||
const { data: body, error: jsonError } = await safeJson(request);
|
||||
|
||||
if (jsonError) return jsonError;
|
||||
const parsed = registerSchema.safeParse(body);
|
||||
|
||||
if (!parsed.success) {
|
||||
return apiError(parsed.error.issues[0].message, 422);
|
||||
}
|
||||
|
||||
const { email, username, password } = parsed.data;
|
||||
|
||||
// Check if email or username already taken (unified message to prevent enumeration)
|
||||
const [existingEmail, existingUsername] = await Promise.all([
|
||||
prisma.user.findUnique({ where: { email } }),
|
||||
prisma.user.findUnique({ where: { username } }),
|
||||
]);
|
||||
if (existingEmail || existingUsername) {
|
||||
return apiError("Benutzername oder E-Mail-Adresse bereits vergeben", 409);
|
||||
}
|
||||
|
||||
// Validate password strength
|
||||
const strength = checkPasswordStrength(password, [username, email]);
|
||||
if (!strength.isAcceptable) {
|
||||
return apiError(
|
||||
strength.feedback[0] || "Passwort zu schwach (Score < 3)",
|
||||
422,
|
||||
);
|
||||
}
|
||||
const passwordHash = await hashPassword(password);
|
||||
|
||||
// First user becomes admin
|
||||
const role = userCount === 0 ? "ADMIN" : "USER";
|
||||
|
||||
// Create user
|
||||
const user = await prisma.user.create({
|
||||
data: {
|
||||
email,
|
||||
username,
|
||||
passwordHash,
|
||||
role,
|
||||
},
|
||||
});
|
||||
|
||||
// Create session immediately
|
||||
const ua = request.headers.get("user-agent");
|
||||
await createSession(user.id, ip, ua);
|
||||
|
||||
await auditLog("auth.register", {
|
||||
userId: user.id,
|
||||
ipAddress: ip,
|
||||
details: { method: "password" },
|
||||
});
|
||||
|
||||
annotate({ action: { name: "auth.register" } });
|
||||
|
||||
return apiSuccess(
|
||||
{
|
||||
user: { id: user.id, username: user.username, email: user.email },
|
||||
},
|
||||
201,
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,24 @@
|
||||
import { prisma } from "@/lib/db";
|
||||
import { apiSuccess } from "@/lib/api-response";
|
||||
import { apiHandler } from "@/lib/api-handler";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export const GET = apiHandler(async () => {
|
||||
try {
|
||||
const settings = await prisma.appSettings.findUnique({
|
||||
where: { id: "singleton" },
|
||||
});
|
||||
|
||||
annotate({ action: { name: "auth.registration-status" } });
|
||||
|
||||
return apiSuccess({
|
||||
registrationEnabled: settings?.registrationEnabled ?? true,
|
||||
});
|
||||
} catch {
|
||||
// Fail closed on backend errors.
|
||||
annotate({ action: { name: "auth.registration-status" } });
|
||||
return apiSuccess({ registrationEnabled: false });
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,157 @@
|
||||
import { apiHandler, requireAuth } from "@/lib/api-handler";
|
||||
import { annotate, getEvent } from "@/lib/logging/context";
|
||||
import { apiSuccess, apiError, getClientIp, safeJson } from "@/lib/api-response";
|
||||
import { checkRateLimit } from "@/lib/rate-limit";
|
||||
import { auditLog } from "@/lib/auth/audit";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { decrypt } from "@/lib/crypto";
|
||||
import { NextRequest } from "next/server";
|
||||
import { z } from "zod/v4";
|
||||
|
||||
const bugReportSchema = z.object({
|
||||
description: z.string().min(10, "Beschreibung zu kurz").max(5000),
|
||||
screenshot: z
|
||||
.string()
|
||||
.max(7_000_000, "Screenshot zu groß (max. 5 MB)")
|
||||
.optional(),
|
||||
});
|
||||
|
||||
export const POST = apiHandler(async (request: NextRequest) => {
|
||||
const { user } = await requireAuth();
|
||||
|
||||
const rl = await checkRateLimit(`bugreport:${user.id}`, 3, 60 * 60 * 1000);
|
||||
if (!rl.allowed) {
|
||||
return apiError("Maximal 3 Bugreports pro Stunde", 429);
|
||||
}
|
||||
|
||||
annotate({ action: { name: "bugreport.submit" } });
|
||||
|
||||
const appSettings = await prisma.appSettings.findUnique({
|
||||
where: { id: "singleton" },
|
||||
select: {
|
||||
githubIssueTokenEncrypted: true,
|
||||
githubIssueRepo: true,
|
||||
},
|
||||
});
|
||||
|
||||
let configuredToken: string | null = null;
|
||||
if (appSettings?.githubIssueTokenEncrypted) {
|
||||
try {
|
||||
configuredToken = decrypt(appSettings.githubIssueTokenEncrypted);
|
||||
} catch (err) {
|
||||
getEvent()?.addWarning("Failed to decrypt GitHub issue token");
|
||||
}
|
||||
}
|
||||
|
||||
const ghToken = configuredToken || process.env.GITHUB_ISSUE_TOKEN;
|
||||
const ghRepo = appSettings?.githubIssueRepo || process.env.GITHUB_ISSUE_REPO; // e.g. "owner/repo"
|
||||
|
||||
if (!ghToken || !ghRepo) {
|
||||
return apiError(
|
||||
"Bugreport ist nicht konfiguriert (GitHub-Issue-Token/Repository in Admin-Einstellungen fehlt)",
|
||||
500,
|
||||
);
|
||||
}
|
||||
|
||||
const { data: body, error: jsonError } = await safeJson(request);
|
||||
|
||||
if (jsonError) return jsonError;
|
||||
const parsed = bugReportSchema.safeParse(body);
|
||||
if (!parsed.success) {
|
||||
return apiError(parsed.error.issues[0].message, 422);
|
||||
}
|
||||
|
||||
const { description, screenshot } = parsed.data;
|
||||
|
||||
const dateStr = new Date().toLocaleString("de-DE", {
|
||||
timeZone: "Europe/Berlin",
|
||||
});
|
||||
const title = `Bug Report – ${dateStr}`;
|
||||
|
||||
// Sanitize user-provided content for GitHub markdown
|
||||
const safeUsername = user.username.replace(/[`*_~<>\[\]|]/g, "");
|
||||
const safeDescription = description
|
||||
.replace(/```/g, "\\`\\`\\`")
|
||||
.slice(0, 5000);
|
||||
|
||||
// Build issue body
|
||||
let issueBody = `**Gemeldet von:** ${safeUsername}\n`;
|
||||
issueBody += `**Datum:** ${dateStr}\n\n`;
|
||||
issueBody += `## Beschreibung\n\n${safeDescription}\n`;
|
||||
issueBody += `\n---\n*Erstellt über die HealthLog Bugreport-Funktion*`;
|
||||
|
||||
// If screenshot provided, upload to GitHub as a gist or include as base64
|
||||
// For simplicity, we'll note there's a screenshot but GitHub issues don't support inline base64
|
||||
if (screenshot) {
|
||||
issueBody += `\n\n**Screenshot:** Ein Screenshot wurde angehängt (siehe Kommentar).`;
|
||||
}
|
||||
|
||||
// Create the issue
|
||||
const issueRes = await fetch(
|
||||
`https://api.github.com/repos/${ghRepo}/issues`,
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
Authorization: `Bearer ${ghToken}`,
|
||||
"Content-Type": "application/json",
|
||||
Accept: "application/vnd.github.v3+json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
title: `[Bug] ${title}`,
|
||||
body: issueBody,
|
||||
labels: ["bug", "user-reported"],
|
||||
}),
|
||||
},
|
||||
);
|
||||
|
||||
if (!issueRes.ok) {
|
||||
const errBody = await issueRes.text();
|
||||
getEvent()?.addWarning("GitHub issue creation failed: " + errBody);
|
||||
return apiError("Issue konnte nicht erstellt werden", 500);
|
||||
}
|
||||
|
||||
const issue = (await issueRes.json()) as {
|
||||
number: number;
|
||||
html_url: string;
|
||||
};
|
||||
|
||||
// If screenshot, upload as a comment
|
||||
if (screenshot) {
|
||||
// Extract just the base64 part
|
||||
const base64Data = screenshot.replace(/^data:image\/\w+;base64,/, "");
|
||||
const ext = screenshot.startsWith("data:image/png") ? "png" : "jpg";
|
||||
|
||||
// Upload screenshot as issue comment with embedded image
|
||||
// GitHub doesn't support base64 in comments, so we note the limitation
|
||||
const commentBody = `### Screenshot\n\n}...)\n\n*Hinweis: Der vollständige Screenshot wurde aus Größengründen gekürzt. Bitte den Nutzer direkt kontaktieren.*`;
|
||||
|
||||
await fetch(
|
||||
`https://api.github.com/repos/${ghRepo}/issues/${issue.number}/comments`,
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
Authorization: `Bearer ${ghToken}`,
|
||||
"Content-Type": "application/json",
|
||||
Accept: "application/vnd.github.v3+json",
|
||||
},
|
||||
body: JSON.stringify({ body: commentBody }),
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
await auditLog("bugreport.submit", {
|
||||
userId: user.id,
|
||||
ipAddress: getClientIp(request),
|
||||
details: {
|
||||
issueNumber: issue.number,
|
||||
hasScreenshot: Boolean(screenshot),
|
||||
},
|
||||
});
|
||||
|
||||
annotate({ meta: { issue_number: issue.number } });
|
||||
|
||||
return apiSuccess({
|
||||
issueNumber: issue.number,
|
||||
issueUrl: issue.html_url,
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,171 @@
|
||||
import { prisma } from "@/lib/db";
|
||||
import { apiHandler, requireAuth } from "@/lib/api-handler";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
import { auditLog } from "@/lib/auth/audit";
|
||||
import { apiSuccess, apiError, getClientIp, safeJson } from "@/lib/api-response";
|
||||
import { checkRateLimit } from "@/lib/rate-limit";
|
||||
import { NextRequest } from "next/server";
|
||||
|
||||
/**
|
||||
* Collect data for doctor report PDF generation (client-side).
|
||||
* Returns aggregated health data for the specified time range.
|
||||
*/
|
||||
export const POST = apiHandler(async (request: NextRequest) => {
|
||||
const { user } = await requireAuth();
|
||||
annotate({ action: { name: "doctor-report.generate" } });
|
||||
|
||||
const rl = await checkRateLimit(`doctor-report:${user.id}`, 10, 60 * 60 * 1000);
|
||||
if (!rl.allowed) {
|
||||
return apiError("Maximal 10 Reports pro Stunde", 429);
|
||||
}
|
||||
|
||||
const { data: body, error: jsonError } = await safeJson(request);
|
||||
|
||||
if (jsonError) return jsonError;
|
||||
const rawDays = (body as Record<string, unknown>)?.days;
|
||||
const days =
|
||||
typeof rawDays === "number" && Number.isInteger(rawDays) && rawDays >= 1 && rawDays <= 365
|
||||
? rawDays
|
||||
: 90;
|
||||
const since = new Date();
|
||||
since.setDate(since.getDate() - days);
|
||||
|
||||
const userId = user.id;
|
||||
|
||||
const [measurements, medications, intakeEvents, moodEntries, userProfile] =
|
||||
await Promise.all([
|
||||
prisma.measurement.findMany({
|
||||
where: { userId, measuredAt: { gte: since } },
|
||||
orderBy: { measuredAt: "asc" },
|
||||
}),
|
||||
prisma.medication.findMany({
|
||||
where: { userId, active: true },
|
||||
include: { schedules: true },
|
||||
}),
|
||||
prisma.medicationIntakeEvent.findMany({
|
||||
where: { userId, scheduledFor: { gte: since } },
|
||||
include: { medication: { select: { name: true } } },
|
||||
orderBy: { scheduledFor: "asc" },
|
||||
}),
|
||||
prisma.moodEntry.findMany({
|
||||
where: { userId, moodLoggedAt: { gte: since } },
|
||||
orderBy: { moodLoggedAt: "asc" },
|
||||
}),
|
||||
prisma.user.findUnique({
|
||||
where: { id: userId },
|
||||
select: {
|
||||
username: true,
|
||||
dateOfBirth: true,
|
||||
gender: true,
|
||||
heightCm: true,
|
||||
},
|
||||
}),
|
||||
]);
|
||||
|
||||
// Group measurements by type
|
||||
const byType: Record<
|
||||
string,
|
||||
Array<{ value: number; measuredAt: string }>
|
||||
> = {};
|
||||
for (const m of measurements) {
|
||||
if (!byType[m.type]) byType[m.type] = [];
|
||||
byType[m.type].push({
|
||||
value: m.value,
|
||||
measuredAt: m.measuredAt.toISOString(),
|
||||
});
|
||||
}
|
||||
|
||||
// Calculate stats per type
|
||||
const stats: Record<
|
||||
string,
|
||||
{ avg: number; min: number; max: number; count: number; latest: number }
|
||||
> = {};
|
||||
for (const [type, entries] of Object.entries(byType)) {
|
||||
const values = entries.map((e) => e.value);
|
||||
stats[type] = {
|
||||
avg: values.reduce((a, b) => a + b, 0) / values.length,
|
||||
min: Math.min(...values),
|
||||
max: Math.max(...values),
|
||||
count: values.length,
|
||||
latest: values[values.length - 1],
|
||||
};
|
||||
}
|
||||
|
||||
// Medication compliance
|
||||
const complianceByMed: Record<
|
||||
string,
|
||||
{ total: number; taken: number; skipped: number; missed: number }
|
||||
> = {};
|
||||
for (const event of intakeEvents) {
|
||||
const name = event.medication.name;
|
||||
if (!complianceByMed[name]) {
|
||||
complianceByMed[name] = { total: 0, taken: 0, skipped: 0, missed: 0 };
|
||||
}
|
||||
complianceByMed[name].total++;
|
||||
if (event.takenAt) {
|
||||
complianceByMed[name].taken++;
|
||||
} else if (event.skipped) {
|
||||
complianceByMed[name].skipped++;
|
||||
} else {
|
||||
complianceByMed[name].missed++;
|
||||
}
|
||||
}
|
||||
|
||||
// Mood summary
|
||||
const moodScores = moodEntries.map((e) => e.score);
|
||||
const moodSummary =
|
||||
moodScores.length > 0
|
||||
? {
|
||||
avg: moodScores.reduce((a, b) => a + b, 0) / moodScores.length,
|
||||
min: Math.min(...moodScores),
|
||||
max: Math.max(...moodScores),
|
||||
count: moodScores.length,
|
||||
distribution: {
|
||||
1: moodScores.filter((s) => s === 1).length,
|
||||
2: moodScores.filter((s) => s === 2).length,
|
||||
3: moodScores.filter((s) => s === 3).length,
|
||||
4: moodScores.filter((s) => s === 4).length,
|
||||
5: moodScores.filter((s) => s === 5).length,
|
||||
},
|
||||
}
|
||||
: null;
|
||||
|
||||
// BMI
|
||||
const weightStats = stats.WEIGHT;
|
||||
const bmi =
|
||||
weightStats && userProfile?.heightCm
|
||||
? weightStats.latest / (userProfile.heightCm / 100) ** 2
|
||||
: null;
|
||||
|
||||
await auditLog("doctor-report.generate", {
|
||||
userId,
|
||||
ipAddress: getClientIp(request),
|
||||
details: { days },
|
||||
});
|
||||
|
||||
annotate({ meta: { report_days: days } });
|
||||
|
||||
return apiSuccess({
|
||||
period: { days, since: since.toISOString() },
|
||||
patient: {
|
||||
username: userProfile?.username ?? null,
|
||||
dateOfBirth: userProfile?.dateOfBirth ?? null,
|
||||
gender: userProfile?.gender ?? null,
|
||||
heightCm: userProfile?.heightCm ?? null,
|
||||
},
|
||||
measurements: byType,
|
||||
stats,
|
||||
bmi: bmi ? Math.round(bmi * 10) / 10 : null,
|
||||
compliance: complianceByMed,
|
||||
medications: medications.map((m) => ({
|
||||
name: m.name,
|
||||
dose: m.dose,
|
||||
schedules: m.schedules.map((s) => ({
|
||||
windowStart: s.windowStart,
|
||||
windowEnd: s.windowEnd,
|
||||
label: s.label,
|
||||
})),
|
||||
})),
|
||||
mood: moodSummary,
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,138 @@
|
||||
import { prisma } from "@/lib/db";
|
||||
import { apiHandler, requireAuth } from "@/lib/api-handler";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
import { auditLog } from "@/lib/auth/audit";
|
||||
import { apiError, getClientIp } from "@/lib/api-response";
|
||||
import { checkRateLimit } from "@/lib/rate-limit";
|
||||
import {
|
||||
toCSV,
|
||||
formatMeasurementsForExport,
|
||||
formatMedicationsForExport,
|
||||
formatIntakeEventsForExport,
|
||||
formatMoodEntriesForExport,
|
||||
} from "@/lib/export";
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
|
||||
/**
|
||||
* Export user data.
|
||||
* Query params:
|
||||
* format: "csv" | "json" (default: json)
|
||||
* type: "measurements" | "medications" | "intake" | "all" (default: all)
|
||||
*
|
||||
* Re-authentication is required via session (user must be logged in).
|
||||
*/
|
||||
export const GET = apiHandler(async (request: NextRequest) => {
|
||||
const { user } = await requireAuth();
|
||||
|
||||
const rl = await checkRateLimit(`export:${user.id}`, 10, 60 * 60 * 1000);
|
||||
if (!rl.allowed) {
|
||||
return apiError("Maximal 10 Exports pro Stunde", 429);
|
||||
}
|
||||
|
||||
annotate({ action: { name: "export.download" } });
|
||||
|
||||
const { searchParams } = new URL(request.url);
|
||||
const format = searchParams.get("format") ?? "json";
|
||||
const type = searchParams.get("type") ?? "all";
|
||||
|
||||
if (!["csv", "json"].includes(format)) {
|
||||
return apiError("Format muss csv oder json sein", 422);
|
||||
}
|
||||
if (!["measurements", "medications", "intake", "mood", "all"].includes(type)) {
|
||||
return apiError("Typ muss measurements, medications, intake, mood oder all sein", 422);
|
||||
}
|
||||
|
||||
const userId = user.id;
|
||||
|
||||
const data: Record<string, unknown> = {};
|
||||
|
||||
if (type === "measurements" || type === "all") {
|
||||
const measurements = await prisma.measurement.findMany({
|
||||
where: { userId },
|
||||
orderBy: { measuredAt: "desc" },
|
||||
});
|
||||
data.measurements =
|
||||
format === "csv"
|
||||
? toCSV(formatMeasurementsForExport(measurements))
|
||||
: formatMeasurementsForExport(measurements);
|
||||
}
|
||||
|
||||
if (type === "medications" || type === "all") {
|
||||
const medications = await prisma.medication.findMany({
|
||||
where: { userId },
|
||||
include: { schedules: true },
|
||||
orderBy: { createdAt: "desc" },
|
||||
});
|
||||
data.medications =
|
||||
format === "csv"
|
||||
? toCSV(formatMedicationsForExport(medications))
|
||||
: formatMedicationsForExport(medications);
|
||||
}
|
||||
|
||||
if (type === "intake" || type === "all") {
|
||||
const events = await prisma.medicationIntakeEvent.findMany({
|
||||
where: { userId },
|
||||
include: { medication: { select: { name: true } } },
|
||||
orderBy: { scheduledFor: "desc" },
|
||||
});
|
||||
data.intakeEvents =
|
||||
format === "csv"
|
||||
? toCSV(formatIntakeEventsForExport(events))
|
||||
: formatIntakeEventsForExport(events);
|
||||
}
|
||||
|
||||
if (type === "mood" || type === "all") {
|
||||
const moodEntries = await prisma.moodEntry.findMany({
|
||||
where: { userId },
|
||||
orderBy: { moodLoggedAt: "desc" },
|
||||
});
|
||||
data.moodEntries =
|
||||
format === "csv"
|
||||
? toCSV(formatMoodEntriesForExport(moodEntries))
|
||||
: formatMoodEntriesForExport(moodEntries);
|
||||
}
|
||||
|
||||
await auditLog("export.download", {
|
||||
userId,
|
||||
ipAddress: getClientIp(request),
|
||||
details: { format, type },
|
||||
});
|
||||
|
||||
annotate({ meta: { export_format: format, export_type: type } });
|
||||
|
||||
if (format === "csv") {
|
||||
// For CSV with all types, combine into separate sections
|
||||
const csvParts: string[] = [];
|
||||
if (data.measurements) {
|
||||
csvParts.push("# Measurements\n" + data.measurements);
|
||||
}
|
||||
if (data.medications) {
|
||||
csvParts.push("# Medications\n" + data.medications);
|
||||
}
|
||||
if (data.intakeEvents) {
|
||||
csvParts.push("# Intake Events\n" + data.intakeEvents);
|
||||
}
|
||||
if (data.moodEntries) {
|
||||
csvParts.push("# Mood Entries\n" + data.moodEntries);
|
||||
}
|
||||
const csvContent = csvParts.join("\n\n");
|
||||
|
||||
return new NextResponse(csvContent, {
|
||||
status: 200,
|
||||
headers: {
|
||||
"Content-Type": "text/csv; charset=utf-8",
|
||||
"Content-Disposition": `attachment; filename="healthlog-export-${new Date().toISOString().slice(0, 10)}.csv"`,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return NextResponse.json(
|
||||
{ data },
|
||||
{
|
||||
status: 200,
|
||||
headers: {
|
||||
"Content-Disposition": `attachment; filename="healthlog-export-${new Date().toISOString().slice(0, 10)}.json"`,
|
||||
},
|
||||
},
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,746 @@
|
||||
import { prisma } from "@/lib/db";
|
||||
import { apiHandler, requireAuth } from "@/lib/api-handler";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
import { apiSuccess } from "@/lib/api-response";
|
||||
import {
|
||||
ACHIEVEMENT_DEFINITIONS,
|
||||
GAMIFICATION_ROLLOUT_AT,
|
||||
calculateLongestStreak,
|
||||
evaluateAchievementsWithCompletionDates,
|
||||
toBerlinDayKey,
|
||||
} from "@/lib/gamification/achievements";
|
||||
import {
|
||||
classifyBMI,
|
||||
classifyBP,
|
||||
classifyPulse,
|
||||
} from "@/lib/analytics/classifications";
|
||||
import { classifyIntakeTiming } from "@/lib/analytics/compliance";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
const DAY_MS = 24 * 60 * 60 * 1000;
|
||||
const ROLLING_WINDOW_DAYS = 30;
|
||||
|
||||
type IntakeEventRecord = {
|
||||
medicationId: string;
|
||||
scheduledFor: Date;
|
||||
takenAt: Date | null;
|
||||
skipped: boolean;
|
||||
};
|
||||
|
||||
type MedicationScheduleRecord = {
|
||||
windowStart: string;
|
||||
windowEnd: string;
|
||||
daysOfWeek: string | null;
|
||||
};
|
||||
|
||||
type MeasurementRecord = {
|
||||
type: "WEIGHT" | "BLOOD_PRESSURE_SYS" | "BLOOD_PRESSURE_DIA" | "PULSE";
|
||||
value: number;
|
||||
measuredAt: Date;
|
||||
};
|
||||
|
||||
function maxDate(a: Date, b: Date): Date {
|
||||
return a > b ? a : b;
|
||||
}
|
||||
|
||||
function dayKeyToSerial(dayKey: string): number {
|
||||
const [year, month, day] = dayKey.split("-").map(Number);
|
||||
return Date.UTC(year, month - 1, day) / DAY_MS;
|
||||
}
|
||||
|
||||
function serialToDayKey(serial: number): string {
|
||||
const date = new Date(serial * DAY_MS);
|
||||
const year = date.getUTCFullYear();
|
||||
const month = String(date.getUTCMonth() + 1).padStart(2, "0");
|
||||
const day = String(date.getUTCDate()).padStart(2, "0");
|
||||
return `${year}-${month}-${day}`;
|
||||
}
|
||||
|
||||
function dayKeyToDate(dayKey: string): Date {
|
||||
const [year, month, day] = dayKey.split("-").map(Number);
|
||||
return new Date(Date.UTC(year, month - 1, day, 12, 0, 0));
|
||||
}
|
||||
|
||||
function mean(values: number[]): number {
|
||||
if (values.length === 0) return 0;
|
||||
return values.reduce((total, value) => total + value, 0) / values.length;
|
||||
}
|
||||
|
||||
function findCountCompletionDate(dates: Date[], target: number): Date | null {
|
||||
if (dates.length < target) return null;
|
||||
const sorted = [...dates].sort((a, b) => a.getTime() - b.getTime());
|
||||
return sorted[target - 1] ?? null;
|
||||
}
|
||||
|
||||
function findStreakCompletionDate(
|
||||
dayKeys: string[],
|
||||
target: number,
|
||||
firstDateByDay: Map<string, Date>,
|
||||
): Date | null {
|
||||
if (dayKeys.length === 0) return null;
|
||||
|
||||
let streak = 1;
|
||||
if (target === 1) {
|
||||
return firstDateByDay.get(dayKeys[0]) ?? null;
|
||||
}
|
||||
|
||||
for (let i = 1; i < dayKeys.length; i++) {
|
||||
const previous = dayKeyToSerial(dayKeys[i - 1]);
|
||||
const current = dayKeyToSerial(dayKeys[i]);
|
||||
streak = current - previous === 1 ? streak + 1 : 1;
|
||||
|
||||
if (streak >= target) {
|
||||
return firstDateByDay.get(dayKeys[i]) ?? null;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function toDaySeries(dayKeys: string[]): {
|
||||
dayKeys: string[];
|
||||
firstDateByDay: Map<string, Date>;
|
||||
} {
|
||||
const sortedKeys = [...new Set(dayKeys)].sort();
|
||||
const firstDateByDay = new Map<string, Date>(
|
||||
sortedKeys.map((key) => [key, dayKeyToDate(key)]),
|
||||
);
|
||||
|
||||
return {
|
||||
dayKeys: sortedKeys,
|
||||
firstDateByDay,
|
||||
};
|
||||
}
|
||||
|
||||
function getEventDaySeries(dates: Date[]): {
|
||||
dayKeys: string[];
|
||||
firstDateByDay: Map<string, Date>;
|
||||
} {
|
||||
const firstDateByDay = new Map<string, Date>();
|
||||
|
||||
for (const date of dates) {
|
||||
const dayKey = toBerlinDayKey(date);
|
||||
const existing = firstDateByDay.get(dayKey);
|
||||
|
||||
if (!existing || date < existing) {
|
||||
firstDateByDay.set(dayKey, date);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
dayKeys: Array.from(firstDateByDay.keys()).sort(),
|
||||
firstDateByDay,
|
||||
};
|
||||
}
|
||||
|
||||
function getHealthGreenDaySeries(
|
||||
measurements: MeasurementRecord[],
|
||||
heightCm: number | null,
|
||||
) {
|
||||
const dayStats = new Map<
|
||||
string,
|
||||
{
|
||||
weight: number[];
|
||||
bpSys: number[];
|
||||
bpDia: number[];
|
||||
pulse: number[];
|
||||
}
|
||||
>();
|
||||
|
||||
for (const measurement of measurements) {
|
||||
const dayKey = toBerlinDayKey(measurement.measuredAt);
|
||||
const bucket = dayStats.get(dayKey) ?? {
|
||||
weight: [],
|
||||
bpSys: [],
|
||||
bpDia: [],
|
||||
pulse: [],
|
||||
};
|
||||
|
||||
if (measurement.type === "WEIGHT") bucket.weight.push(measurement.value);
|
||||
if (measurement.type === "BLOOD_PRESSURE_SYS")
|
||||
bucket.bpSys.push(measurement.value);
|
||||
if (measurement.type === "BLOOD_PRESSURE_DIA")
|
||||
bucket.bpDia.push(measurement.value);
|
||||
if (measurement.type === "PULSE") bucket.pulse.push(measurement.value);
|
||||
|
||||
dayStats.set(dayKey, bucket);
|
||||
}
|
||||
|
||||
const bmiGreenDays: string[] = [];
|
||||
const bpGreenDays: string[] = [];
|
||||
const pulseGreenDays: string[] = [];
|
||||
|
||||
for (const [dayKey, bucket] of dayStats.entries()) {
|
||||
if (heightCm && bucket.weight.length > 0) {
|
||||
const bmi = mean(bucket.weight) / (heightCm / 100) ** 2;
|
||||
if (classifyBMI(bmi).severity === "normal") {
|
||||
bmiGreenDays.push(dayKey);
|
||||
}
|
||||
}
|
||||
|
||||
if (bucket.bpSys.length > 0 && bucket.bpDia.length > 0) {
|
||||
const bpClass = classifyBP(mean(bucket.bpSys), mean(bucket.bpDia));
|
||||
if (bpClass.severity === "normal") {
|
||||
bpGreenDays.push(dayKey);
|
||||
}
|
||||
}
|
||||
|
||||
if (bucket.pulse.length > 0) {
|
||||
const pulseClass = classifyPulse(mean(bucket.pulse));
|
||||
if (pulseClass.severity === "normal") {
|
||||
pulseGreenDays.push(dayKey);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
bmi: toDaySeries(bmiGreenDays),
|
||||
bp: toDaySeries(bpGreenDays),
|
||||
pulse: toDaySeries(pulseGreenDays),
|
||||
};
|
||||
}
|
||||
|
||||
function getOnTimePerfectDaySeries(
|
||||
intakeEvents: IntakeEventRecord[],
|
||||
schedulesByMedicationId: Map<string, MedicationScheduleRecord[]>,
|
||||
) {
|
||||
const eventsByDay = new Map<string, IntakeEventRecord[]>();
|
||||
|
||||
for (const event of intakeEvents) {
|
||||
const dayKey = toBerlinDayKey(event.scheduledFor);
|
||||
const list = eventsByDay.get(dayKey) ?? [];
|
||||
list.push(event);
|
||||
eventsByDay.set(dayKey, list);
|
||||
}
|
||||
|
||||
const perfectDays: string[] = [];
|
||||
|
||||
for (const [dayKey, events] of eventsByDay.entries()) {
|
||||
if (events.length === 0) continue;
|
||||
|
||||
const scheduledDate = dayKeyToDate(dayKey);
|
||||
let isPerfectDay = true;
|
||||
|
||||
for (const event of events) {
|
||||
if (event.skipped || event.takenAt === null) {
|
||||
isPerfectDay = false;
|
||||
break;
|
||||
}
|
||||
|
||||
const schedules = schedulesByMedicationId.get(event.medicationId) ?? [];
|
||||
if (schedules.length === 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const eventMinutes =
|
||||
event.scheduledFor.getUTCHours() * 60 +
|
||||
event.scheduledFor.getUTCMinutes();
|
||||
|
||||
let bestSchedule = schedules[0];
|
||||
let bestDistance = Infinity;
|
||||
|
||||
for (const schedule of schedules) {
|
||||
const [h, m] = schedule.windowStart.split(":").map(Number);
|
||||
const scheduleMinutes = h * 60 + m;
|
||||
const distance = Math.abs(eventMinutes - scheduleMinutes);
|
||||
if (distance < bestDistance) {
|
||||
bestDistance = distance;
|
||||
bestSchedule = schedule;
|
||||
}
|
||||
}
|
||||
|
||||
const timing = classifyIntakeTiming(
|
||||
event.takenAt,
|
||||
bestSchedule.windowStart,
|
||||
bestSchedule.windowEnd,
|
||||
scheduledDate,
|
||||
);
|
||||
|
||||
if (timing !== "on_time") {
|
||||
isPerfectDay = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (isPerfectDay) {
|
||||
perfectDays.push(dayKey);
|
||||
}
|
||||
}
|
||||
|
||||
return toDaySeries(perfectDays);
|
||||
}
|
||||
|
||||
function parseDaysOfWeek(daysOfWeek: string | null): Set<number> | null {
|
||||
if (!daysOfWeek) return null;
|
||||
|
||||
const values = daysOfWeek
|
||||
.split(",")
|
||||
.map((value) => Number(value.trim()))
|
||||
.filter((value) => Number.isInteger(value) && value >= 0 && value <= 6);
|
||||
|
||||
return values.length > 0 ? new Set(values) : null;
|
||||
}
|
||||
|
||||
function getExpectedIntakesForDay(
|
||||
schedules: MedicationScheduleRecord[],
|
||||
dayKey: string,
|
||||
): number {
|
||||
if (schedules.length === 0) return 0;
|
||||
if (!/^\d{4}-\d{2}-\d{2}$/.test(dayKey)) return 0;
|
||||
|
||||
const day = dayKeyToDate(dayKey).getUTCDay();
|
||||
let expected = 0;
|
||||
|
||||
for (const schedule of schedules) {
|
||||
const allowedDays = parseDaysOfWeek(schedule.daysOfWeek);
|
||||
if (!allowedDays || allowedDays.has(day)) {
|
||||
expected += 1;
|
||||
}
|
||||
}
|
||||
|
||||
return expected;
|
||||
}
|
||||
|
||||
function getIntakeIssueMetrics(
|
||||
intakeEvents: IntakeEventRecord[],
|
||||
schedulesByMedicationId: Map<string, MedicationScheduleRecord[]>,
|
||||
) {
|
||||
const skippedIntakeDates = intakeEvents
|
||||
.filter((event) => event.skipped)
|
||||
.map((event) => event.scheduledFor)
|
||||
.sort((a, b) => a.getTime() - b.getTime());
|
||||
|
||||
const eventsByMedicationDay = new Map<
|
||||
string,
|
||||
Map<string, IntakeEventRecord[]>
|
||||
>();
|
||||
|
||||
for (const event of intakeEvents) {
|
||||
if (!event.medicationId || Number.isNaN(event.scheduledFor.getTime())) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const dayKey = toBerlinDayKey(event.scheduledFor);
|
||||
const byDay = eventsByMedicationDay.get(event.medicationId) ?? new Map();
|
||||
const list = byDay.get(dayKey) ?? [];
|
||||
list.push(event);
|
||||
byDay.set(dayKey, list);
|
||||
eventsByMedicationDay.set(event.medicationId, byDay);
|
||||
}
|
||||
|
||||
let overIntakeCount = 0;
|
||||
const overIntakeDates: Date[] = [];
|
||||
|
||||
for (const [medicationId, dayMap] of eventsByMedicationDay.entries()) {
|
||||
const schedules = schedulesByMedicationId.get(medicationId) ?? [];
|
||||
|
||||
for (const [dayKey, events] of dayMap.entries()) {
|
||||
const expectedCount = getExpectedIntakesForDay(schedules, dayKey);
|
||||
|
||||
if (expectedCount <= 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const takenEvents = events
|
||||
.filter((event) => !event.skipped && event.takenAt !== null)
|
||||
.sort((a, b) => {
|
||||
const aTime = (a.takenAt ?? a.scheduledFor).getTime();
|
||||
const bTime = (b.takenAt ?? b.scheduledFor).getTime();
|
||||
return aTime - bTime;
|
||||
});
|
||||
|
||||
const excessCount = Math.max(0, takenEvents.length - expectedCount);
|
||||
if (excessCount === 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
overIntakeCount += excessCount;
|
||||
|
||||
for (
|
||||
let index = takenEvents.length - excessCount;
|
||||
index < takenEvents.length;
|
||||
index++
|
||||
) {
|
||||
const event = takenEvents[index];
|
||||
if (!event) continue;
|
||||
overIntakeDates.push(event.takenAt ?? event.scheduledFor);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
overIntakeDates.sort((a, b) => a.getTime() - b.getTime());
|
||||
|
||||
return {
|
||||
skippedIntakeCount: skippedIntakeDates.length,
|
||||
skippedIntakeDates,
|
||||
overIntakeCount,
|
||||
overIntakeDates,
|
||||
};
|
||||
}
|
||||
|
||||
function getCompliance80DaySeries(
|
||||
intakeEvents: IntakeEventRecord[],
|
||||
startDate: Date,
|
||||
endDate: Date,
|
||||
) {
|
||||
const perDayCounts = new Map<number, { logged: number; taken: number }>();
|
||||
|
||||
for (const event of intakeEvents) {
|
||||
const serial = dayKeyToSerial(toBerlinDayKey(event.scheduledFor));
|
||||
const current = perDayCounts.get(serial) ?? { logged: 0, taken: 0 };
|
||||
|
||||
const logged = event.skipped || event.takenAt !== null;
|
||||
const taken = !event.skipped && event.takenAt !== null;
|
||||
|
||||
if (logged) current.logged += 1;
|
||||
if (taken) current.taken += 1;
|
||||
|
||||
perDayCounts.set(serial, current);
|
||||
}
|
||||
|
||||
const startSerial = dayKeyToSerial(toBerlinDayKey(startDate));
|
||||
const endSerial = dayKeyToSerial(toBerlinDayKey(endDate));
|
||||
|
||||
let rollingLogged = 0;
|
||||
let rollingTaken = 0;
|
||||
const greenDays: string[] = [];
|
||||
|
||||
for (let serial = startSerial; serial <= endSerial; serial++) {
|
||||
const todayCounts = perDayCounts.get(serial);
|
||||
if (todayCounts) {
|
||||
rollingLogged += todayCounts.logged;
|
||||
rollingTaken += todayCounts.taken;
|
||||
}
|
||||
|
||||
const outOfWindowCounts = perDayCounts.get(serial - ROLLING_WINDOW_DAYS);
|
||||
if (outOfWindowCounts) {
|
||||
rollingLogged -= outOfWindowCounts.logged;
|
||||
rollingTaken -= outOfWindowCounts.taken;
|
||||
}
|
||||
|
||||
const hasFullWindow = serial >= startSerial + (ROLLING_WINDOW_DAYS - 1);
|
||||
if (!hasFullWindow || rollingLogged <= 0) continue;
|
||||
|
||||
const compliance = Math.round((rollingTaken / rollingLogged) * 100);
|
||||
if (compliance >= 80) {
|
||||
greenDays.push(serialToDayKey(serial));
|
||||
}
|
||||
}
|
||||
|
||||
return toDaySeries(greenDays);
|
||||
}
|
||||
|
||||
export const GET = apiHandler(async () => {
|
||||
const { user } = await requireAuth();
|
||||
annotate({ action: { name: "gamification.achievements" } });
|
||||
|
||||
const now = new Date();
|
||||
const userId = user.id;
|
||||
const startDate = maxDate(
|
||||
user.createdAt,
|
||||
GAMIFICATION_ROLLOUT_AT,
|
||||
);
|
||||
|
||||
const [measurements, intakeEvents, medications, passkeys, auditEvents] =
|
||||
await Promise.all([
|
||||
prisma.measurement.findMany({
|
||||
where: {
|
||||
userId,
|
||||
measuredAt: { gte: startDate, lte: now },
|
||||
source: { not: "IMPORT" },
|
||||
type: {
|
||||
in: [
|
||||
"WEIGHT",
|
||||
"BLOOD_PRESSURE_SYS",
|
||||
"BLOOD_PRESSURE_DIA",
|
||||
"PULSE",
|
||||
],
|
||||
},
|
||||
},
|
||||
select: {
|
||||
type: true,
|
||||
value: true,
|
||||
measuredAt: true,
|
||||
},
|
||||
}),
|
||||
prisma.medicationIntakeEvent.findMany({
|
||||
where: {
|
||||
userId,
|
||||
source: { not: "IMPORT" },
|
||||
scheduledFor: { gte: startDate, lte: now },
|
||||
},
|
||||
select: {
|
||||
medicationId: true,
|
||||
scheduledFor: true,
|
||||
takenAt: true,
|
||||
skipped: true,
|
||||
},
|
||||
}),
|
||||
prisma.medication.findMany({
|
||||
where: { userId },
|
||||
select: {
|
||||
id: true,
|
||||
schedules: {
|
||||
select: {
|
||||
windowStart: true,
|
||||
windowEnd: true,
|
||||
daysOfWeek: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
prisma.passkey.findMany({
|
||||
where: {
|
||||
userId,
|
||||
createdAt: { gte: startDate, lte: now },
|
||||
},
|
||||
select: {
|
||||
createdAt: true,
|
||||
},
|
||||
}),
|
||||
prisma.auditLog.findMany({
|
||||
where: {
|
||||
userId,
|
||||
createdAt: { gte: startDate, lte: now },
|
||||
action: {
|
||||
in: [
|
||||
"auth.login.passkey",
|
||||
"auth.login.password",
|
||||
"bugreport.submit",
|
||||
],
|
||||
},
|
||||
},
|
||||
select: {
|
||||
action: true,
|
||||
createdAt: true,
|
||||
},
|
||||
}),
|
||||
]);
|
||||
|
||||
const schedulesByMedicationId = new Map(
|
||||
medications.map((med) => [med.id, med.schedules]),
|
||||
);
|
||||
const intakeIssueMetrics = getIntakeIssueMetrics(
|
||||
intakeEvents,
|
||||
schedulesByMedicationId,
|
||||
);
|
||||
|
||||
const takenIntakeDates = intakeEvents
|
||||
.filter((event) => !event.skipped && event.takenAt !== null)
|
||||
.map((event) => event.takenAt as Date);
|
||||
const passkeyCreatedDates = passkeys.map((passkey) => passkey.createdAt);
|
||||
const passkeyLoginDates = auditEvents
|
||||
.filter((event) => event.action === "auth.login.passkey")
|
||||
.map((event) => event.createdAt);
|
||||
const passwordLoginDates = auditEvents
|
||||
.filter((event) => event.action === "auth.login.password")
|
||||
.map((event) => event.createdAt);
|
||||
const bugReportDates = auditEvents
|
||||
.filter((event) => event.action === "bugreport.submit")
|
||||
.map((event) => event.createdAt);
|
||||
const loginDaySeries = getEventDaySeries([
|
||||
...passkeyLoginDates,
|
||||
...passwordLoginDates,
|
||||
]);
|
||||
|
||||
const healthSeries = getHealthGreenDaySeries(
|
||||
measurements as MeasurementRecord[],
|
||||
user.heightCm,
|
||||
);
|
||||
const onTimeSeries = getOnTimePerfectDaySeries(
|
||||
intakeEvents,
|
||||
schedulesByMedicationId,
|
||||
);
|
||||
const complianceSeries = getCompliance80DaySeries(
|
||||
intakeEvents,
|
||||
startDate,
|
||||
now,
|
||||
);
|
||||
|
||||
const metrics = {
|
||||
totalTakenIntakes: takenIntakeDates.length,
|
||||
overIntakeCount: intakeIssueMetrics.overIntakeCount,
|
||||
skippedIntakeCount: intakeIssueMetrics.skippedIntakeCount,
|
||||
bmiGreenStreak: calculateLongestStreak(healthSeries.bmi.dayKeys),
|
||||
bpGreenStreak: calculateLongestStreak(healthSeries.bp.dayKeys),
|
||||
pulseGreenStreak: calculateLongestStreak(healthSeries.pulse.dayKeys),
|
||||
onTimePerfectDayStreak: calculateLongestStreak(onTimeSeries.dayKeys),
|
||||
compliance80DayStreak: calculateLongestStreak(complianceSeries.dayKeys),
|
||||
passkeyCreatedCount: passkeyCreatedDates.length,
|
||||
passkeyLoginCount: passkeyLoginDates.length,
|
||||
passwordLoginCount: passwordLoginDates.length,
|
||||
loginDayStreak: calculateLongestStreak(loginDaySeries.dayKeys),
|
||||
bugReportCount: bugReportDates.length,
|
||||
};
|
||||
|
||||
const completionDates: Partial<Record<string, Date>> = {};
|
||||
|
||||
for (const definition of ACHIEVEMENT_DEFINITIONS) {
|
||||
if (definition.metric === "totalTakenIntakes") {
|
||||
const completedAt = findCountCompletionDate(
|
||||
takenIntakeDates,
|
||||
definition.target,
|
||||
);
|
||||
if (completedAt) completionDates[definition.id] = completedAt;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (definition.metric === "passkeyCreatedCount") {
|
||||
const completedAt = findCountCompletionDate(
|
||||
passkeyCreatedDates,
|
||||
definition.target,
|
||||
);
|
||||
if (completedAt) completionDates[definition.id] = completedAt;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (definition.metric === "passkeyLoginCount") {
|
||||
const completedAt = findCountCompletionDate(
|
||||
passkeyLoginDates,
|
||||
definition.target,
|
||||
);
|
||||
if (completedAt) completionDates[definition.id] = completedAt;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (definition.metric === "passwordLoginCount") {
|
||||
const completedAt = findCountCompletionDate(
|
||||
passwordLoginDates,
|
||||
definition.target,
|
||||
);
|
||||
if (completedAt) completionDates[definition.id] = completedAt;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (definition.metric === "bugReportCount") {
|
||||
const completedAt = findCountCompletionDate(
|
||||
bugReportDates,
|
||||
definition.target,
|
||||
);
|
||||
if (completedAt) completionDates[definition.id] = completedAt;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (definition.metric === "overIntakeCount") {
|
||||
const completedAt = findCountCompletionDate(
|
||||
intakeIssueMetrics.overIntakeDates,
|
||||
definition.target,
|
||||
);
|
||||
if (completedAt) completionDates[definition.id] = completedAt;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (definition.metric === "skippedIntakeCount") {
|
||||
const completedAt = findCountCompletionDate(
|
||||
intakeIssueMetrics.skippedIntakeDates,
|
||||
definition.target,
|
||||
);
|
||||
if (completedAt) completionDates[definition.id] = completedAt;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (definition.metric === "loginDayStreak") {
|
||||
const completedAt = findStreakCompletionDate(
|
||||
loginDaySeries.dayKeys,
|
||||
definition.target,
|
||||
loginDaySeries.firstDateByDay,
|
||||
);
|
||||
if (completedAt) completionDates[definition.id] = completedAt;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (definition.metric === "bmiGreenStreak") {
|
||||
const completedAt = findStreakCompletionDate(
|
||||
healthSeries.bmi.dayKeys,
|
||||
definition.target,
|
||||
healthSeries.bmi.firstDateByDay,
|
||||
);
|
||||
if (completedAt) completionDates[definition.id] = completedAt;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (definition.metric === "bpGreenStreak") {
|
||||
const completedAt = findStreakCompletionDate(
|
||||
healthSeries.bp.dayKeys,
|
||||
definition.target,
|
||||
healthSeries.bp.firstDateByDay,
|
||||
);
|
||||
if (completedAt) completionDates[definition.id] = completedAt;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (definition.metric === "pulseGreenStreak") {
|
||||
const completedAt = findStreakCompletionDate(
|
||||
healthSeries.pulse.dayKeys,
|
||||
definition.target,
|
||||
healthSeries.pulse.firstDateByDay,
|
||||
);
|
||||
if (completedAt) completionDates[definition.id] = completedAt;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (definition.metric === "onTimePerfectDayStreak") {
|
||||
const completedAt = findStreakCompletionDate(
|
||||
onTimeSeries.dayKeys,
|
||||
definition.target,
|
||||
onTimeSeries.firstDateByDay,
|
||||
);
|
||||
if (completedAt) completionDates[definition.id] = completedAt;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (definition.metric === "compliance80DayStreak") {
|
||||
const completedAt = findStreakCompletionDate(
|
||||
complianceSeries.dayKeys,
|
||||
definition.target,
|
||||
complianceSeries.firstDateByDay,
|
||||
);
|
||||
if (completedAt) completionDates[definition.id] = completedAt;
|
||||
}
|
||||
}
|
||||
|
||||
// Load persisted achievements
|
||||
const persisted = await prisma.userAchievement.findMany({
|
||||
where: { userId },
|
||||
select: { achievementId: true, unlockedAt: true },
|
||||
});
|
||||
const persistedMap = new Map(
|
||||
persisted.map((p) => [p.achievementId, p.unlockedAt]),
|
||||
);
|
||||
|
||||
// Merge: persisted dates take priority, then calculated dates
|
||||
for (const [id, date] of Object.entries(completionDates)) {
|
||||
if (!persistedMap.has(id) && date) {
|
||||
persistedMap.set(id, date);
|
||||
}
|
||||
}
|
||||
|
||||
// Use persisted dates as the source of truth
|
||||
const mergedDates: Partial<Record<string, Date>> = {};
|
||||
for (const [id, date] of persistedMap) {
|
||||
mergedDates[id] = date;
|
||||
}
|
||||
|
||||
const result = evaluateAchievementsWithCompletionDates(
|
||||
metrics,
|
||||
mergedDates,
|
||||
);
|
||||
|
||||
// Persist newly unlocked achievements
|
||||
const newUnlocks = result.achievements.filter(
|
||||
(a) => a.unlocked && a.completedAt && !persisted.some((p) => p.achievementId === a.id),
|
||||
);
|
||||
if (newUnlocks.length > 0) {
|
||||
await prisma.userAchievement.createMany({
|
||||
data: newUnlocks.map((a) => ({
|
||||
userId,
|
||||
achievementId: a.id,
|
||||
unlockedAt: new Date(a.completedAt!),
|
||||
})),
|
||||
skipDuplicates: true,
|
||||
});
|
||||
}
|
||||
|
||||
return apiSuccess(result);
|
||||
});
|
||||
@@ -0,0 +1,50 @@
|
||||
import { prisma } from "@/lib/db";
|
||||
import { getWorkerStatus } from "@/lib/jobs/worker-status";
|
||||
import { getSession } from "@/lib/auth/session";
|
||||
import { NextResponse } from "next/server";
|
||||
import { apiHandler } from "@/lib/api-handler";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export const GET = apiHandler(async () => {
|
||||
annotate({ action: { name: "health.check" } });
|
||||
|
||||
let dbOk = true;
|
||||
|
||||
try {
|
||||
await prisma.$queryRaw`SELECT 1`;
|
||||
} catch {
|
||||
dbOk = false;
|
||||
}
|
||||
|
||||
const worker = getWorkerStatus();
|
||||
const status = dbOk && worker.running ? "ok" : "degraded";
|
||||
const statusCode = status === "ok" ? 200 : 503;
|
||||
|
||||
const cacheHeaders = {
|
||||
"Cache-Control": "no-store, no-cache, must-revalidate",
|
||||
};
|
||||
|
||||
// Only expose detailed info to authenticated admins
|
||||
const session = await getSession().catch(() => null);
|
||||
if (session?.user.role === "ADMIN") {
|
||||
return NextResponse.json(
|
||||
{
|
||||
status,
|
||||
timestamp: new Date().toISOString(),
|
||||
database: dbOk ? "connected" : "disconnected",
|
||||
worker: worker.running ? "running" : "stopped",
|
||||
...(worker.lastHeartbeat
|
||||
? { workerLastHeartbeat: worker.lastHeartbeat }
|
||||
: {}),
|
||||
},
|
||||
{ status: statusCode, headers: cacheHeaders },
|
||||
);
|
||||
}
|
||||
|
||||
return NextResponse.json(
|
||||
{ status },
|
||||
{ status: statusCode, headers: cacheHeaders },
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,122 @@
|
||||
import { prisma } from "@/lib/db";
|
||||
import { apiHandler, requireAuth } from "@/lib/api-handler";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
import { auditLog } from "@/lib/auth/audit";
|
||||
import { apiSuccess, getClientIp, safeJson } from "@/lib/api-response";
|
||||
import { NextRequest } from "next/server";
|
||||
import { z } from "zod/v4";
|
||||
|
||||
import { validateMeasurementRange } from "@/lib/validations/measurement";
|
||||
|
||||
const measurementSchema = z
|
||||
.object({
|
||||
type: z.enum([
|
||||
"WEIGHT",
|
||||
"BLOOD_PRESSURE_SYS",
|
||||
"BLOOD_PRESSURE_DIA",
|
||||
"PULSE",
|
||||
"BODY_FAT",
|
||||
"SLEEP_DURATION",
|
||||
"ACTIVITY_STEPS",
|
||||
]),
|
||||
value: z.number(),
|
||||
unit: z.string(),
|
||||
measuredAt: z.string().datetime(),
|
||||
source: z.string().optional(),
|
||||
notes: z.string().optional(),
|
||||
})
|
||||
.refine(
|
||||
(data) => validateMeasurementRange(data.type, data.value) === null,
|
||||
"Wert ausserhalb des plausiblen Bereichs",
|
||||
);
|
||||
|
||||
const moodEntrySchema = z.object({
|
||||
date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/),
|
||||
mood: z.enum(["SUPER_GUT", "GUT", "OKAY", "SCHLECHT", "LAUSIG"]),
|
||||
score: z.number().int().min(1).max(5),
|
||||
tags: z.string().optional(),
|
||||
loggedAt: z.string().datetime().optional(),
|
||||
});
|
||||
|
||||
const importSchema = z.object({
|
||||
measurements: z.array(measurementSchema).max(10000).optional(),
|
||||
moodEntries: z.array(moodEntrySchema).max(10000).optional(),
|
||||
});
|
||||
|
||||
/**
|
||||
* Import user data (JSON format matching export structure).
|
||||
* Deduplicates via unique constraints — existing records are skipped.
|
||||
*/
|
||||
export const POST = apiHandler(async (request: NextRequest) => {
|
||||
const { user } = await requireAuth();
|
||||
annotate({ action: { name: "import.upload" } });
|
||||
|
||||
const { data: body, error: jsonError } = await safeJson(request);
|
||||
|
||||
if (jsonError) return jsonError;
|
||||
const parsed = importSchema.safeParse(body);
|
||||
if (!parsed.success) {
|
||||
return apiSuccess({ error: parsed.error.issues[0].message }, 422);
|
||||
}
|
||||
|
||||
const userId = user.id;
|
||||
const data = parsed.data;
|
||||
const stats = { measurements: 0, moodEntries: 0, skipped: 0 };
|
||||
|
||||
// Import measurements
|
||||
if (data.measurements?.length) {
|
||||
for (const m of data.measurements) {
|
||||
try {
|
||||
await prisma.measurement.create({
|
||||
data: {
|
||||
userId,
|
||||
type: m.type,
|
||||
value: m.value,
|
||||
unit: m.unit,
|
||||
source: "IMPORT",
|
||||
measuredAt: new Date(m.measuredAt),
|
||||
notes: m.notes || null,
|
||||
},
|
||||
});
|
||||
stats.measurements++;
|
||||
} catch {
|
||||
// Unique constraint violation — skip duplicate
|
||||
stats.skipped++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Import mood entries
|
||||
if (data.moodEntries?.length) {
|
||||
for (const e of data.moodEntries) {
|
||||
try {
|
||||
const loggedAt = e.loggedAt ? new Date(e.loggedAt) : new Date();
|
||||
await prisma.moodEntry.create({
|
||||
data: {
|
||||
userId,
|
||||
date: e.date,
|
||||
mood: e.mood,
|
||||
score: e.score,
|
||||
tags: e.tags || null,
|
||||
source: "IMPORT",
|
||||
moodLoggedAt: loggedAt,
|
||||
},
|
||||
});
|
||||
stats.moodEntries++;
|
||||
} catch {
|
||||
// Unique constraint violation — skip duplicate
|
||||
stats.skipped++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
await auditLog("import.upload", {
|
||||
userId,
|
||||
ipAddress: getClientIp(request),
|
||||
details: stats,
|
||||
});
|
||||
|
||||
annotate({ meta: { import_stats: stats } });
|
||||
|
||||
return apiSuccess(stats);
|
||||
});
|
||||
@@ -0,0 +1,145 @@
|
||||
import { prisma } from "@/lib/db";
|
||||
import { apiHandler } from "@/lib/api-handler";
|
||||
import { annotate, getEvent } from "@/lib/logging/context";
|
||||
import { auditLog } from "@/lib/auth/audit";
|
||||
import { apiSuccess, apiError, getClientIp, safeJson } from "@/lib/api-response";
|
||||
import { hashToken } from "@/lib/auth/hmac";
|
||||
import { checkRateLimit, rateLimitHeaders } from "@/lib/rate-limit";
|
||||
import { externalIntakeSchema } from "@/lib/validations/medication";
|
||||
import { isApiGloballyEnabled } from "@/lib/app-settings";
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
|
||||
/**
|
||||
* External medication ingest endpoint.
|
||||
* Auth: Bearer token (hashed and looked up in api_tokens table).
|
||||
* Idempotent via idempotencyKey.
|
||||
* Rate limit: 60 requests per minute per IP.
|
||||
*/
|
||||
export const POST = apiHandler(async (request: NextRequest) => {
|
||||
annotate({ action: { name: "ingest.medication" } });
|
||||
|
||||
if (!(await isApiGloballyEnabled())) {
|
||||
return apiError("API ist global deaktiviert", 403);
|
||||
}
|
||||
|
||||
const ip = getClientIp(request);
|
||||
|
||||
// Rate limiting: 60 requests per minute per IP
|
||||
const rl = await checkRateLimit(`ingest:${ip}`, 60, 60 * 1000);
|
||||
if (!rl.allowed) {
|
||||
return NextResponse.json(
|
||||
{ data: null, error: "Rate limit exceeded" },
|
||||
{ status: 429, headers: rateLimitHeaders(rl) },
|
||||
);
|
||||
}
|
||||
|
||||
// Extract bearer token
|
||||
const authHeader = request.headers.get("authorization");
|
||||
if (!authHeader?.startsWith("Bearer ")) {
|
||||
return apiError("Authorization header required", 401);
|
||||
}
|
||||
|
||||
const token = authHeader.slice(7);
|
||||
const tokenHashValue = hashToken(token);
|
||||
|
||||
const apiToken = await prisma.apiToken.findUnique({
|
||||
where: { tokenHash: tokenHashValue },
|
||||
select: {
|
||||
id: true,
|
||||
userId: true,
|
||||
permissions: true,
|
||||
revoked: true,
|
||||
expiresAt: true,
|
||||
lastUsedAt: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (!apiToken || apiToken.revoked) {
|
||||
return apiError("Invalid or revoked token", 401);
|
||||
}
|
||||
|
||||
if (apiToken.expiresAt && apiToken.expiresAt < new Date()) {
|
||||
return apiError("Token expired", 401);
|
||||
}
|
||||
|
||||
if (!apiToken.permissions.includes("medication:ingest")) {
|
||||
return apiError("Insufficient permissions", 403);
|
||||
}
|
||||
|
||||
// Annotate auth after verification
|
||||
getEvent()?.setAuth({
|
||||
user_id: apiToken.userId,
|
||||
auth_method: "api_key",
|
||||
});
|
||||
|
||||
// Update lastUsedAt
|
||||
await prisma.apiToken.update({
|
||||
where: { id: apiToken.id },
|
||||
data: { lastUsedAt: new Date() },
|
||||
});
|
||||
|
||||
const { data: body, error: jsonError } = await safeJson(request);
|
||||
|
||||
if (jsonError) return jsonError;
|
||||
const parsed = externalIntakeSchema.safeParse(body);
|
||||
if (!parsed.success) {
|
||||
return apiError(parsed.error.issues[0].message, 422);
|
||||
}
|
||||
|
||||
const { medicationName, takenAt, idempotencyKey } = parsed.data;
|
||||
|
||||
// Idempotency check (scoped to token owner to prevent cross-user lookups)
|
||||
const existing = await prisma.medicationIntakeEvent.findFirst({
|
||||
where: {
|
||||
idempotencyKey,
|
||||
userId: apiToken.userId,
|
||||
},
|
||||
});
|
||||
if (existing) {
|
||||
return apiSuccess(existing);
|
||||
}
|
||||
|
||||
// Find medication by name for this user
|
||||
const medication = await prisma.medication.findFirst({
|
||||
where: {
|
||||
userId: apiToken.userId,
|
||||
name: { equals: medicationName, mode: "insensitive" },
|
||||
active: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (!medication) {
|
||||
return apiError("Medikament nicht gefunden", 404);
|
||||
}
|
||||
|
||||
const medicationScope = `medication:${medication.id}:ingest`;
|
||||
if (!apiToken.permissions.includes(medicationScope)) {
|
||||
return apiError("API-Endpoint fuer dieses Medikament ist deaktiviert", 403);
|
||||
}
|
||||
|
||||
const event = await prisma.medicationIntakeEvent.create({
|
||||
data: {
|
||||
userId: apiToken.userId,
|
||||
medicationId: medication.id,
|
||||
scheduledFor: takenAt ?? new Date(),
|
||||
takenAt: takenAt ?? new Date(),
|
||||
skipped: false,
|
||||
source: "API",
|
||||
idempotencyKey,
|
||||
},
|
||||
});
|
||||
|
||||
await auditLog("medication.ingest.external", {
|
||||
userId: apiToken.userId,
|
||||
ipAddress: ip,
|
||||
details: {
|
||||
medicationId: medication.id,
|
||||
eventId: event.id,
|
||||
tokenId: apiToken.id,
|
||||
},
|
||||
});
|
||||
|
||||
annotate({ meta: { medication_id: medication.id, event_id: event.id } });
|
||||
|
||||
return apiSuccess(event, 201);
|
||||
});
|
||||
@@ -0,0 +1,31 @@
|
||||
import { NextRequest } from "next/server";
|
||||
import { apiSuccess } from "@/lib/api-response";
|
||||
import {
|
||||
generateBloodPressureStatusForUser,
|
||||
resolveBloodPressureStatusLocale,
|
||||
} from "@/lib/insights/blood-pressure-status";
|
||||
import { apiHandler, requireAuth } from "@/lib/api-handler";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export const GET = apiHandler(async (request: NextRequest) => {
|
||||
const { user } = await requireAuth();
|
||||
|
||||
const localeParam = request.nextUrl.searchParams.get("locale");
|
||||
const locale = resolveBloodPressureStatusLocale(
|
||||
localeParam ?? user.locale ?? "de",
|
||||
);
|
||||
|
||||
const result = await generateBloodPressureStatusForUser(
|
||||
user.id,
|
||||
{
|
||||
locale,
|
||||
force: false,
|
||||
},
|
||||
);
|
||||
|
||||
annotate({ action: { name: "insights.blood-pressure-status" } });
|
||||
|
||||
return apiSuccess(result);
|
||||
});
|
||||
@@ -0,0 +1,28 @@
|
||||
import { NextRequest } from "next/server";
|
||||
import { apiSuccess } from "@/lib/api-response";
|
||||
import {
|
||||
generateBmiStatusForUser,
|
||||
resolveBmiStatusLocale,
|
||||
} from "@/lib/insights/bmi-status";
|
||||
import { apiHandler, requireAuth } from "@/lib/api-handler";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export const GET = apiHandler(async (request: NextRequest) => {
|
||||
const { user } = await requireAuth();
|
||||
|
||||
const localeParam = request.nextUrl.searchParams.get("locale");
|
||||
const locale = resolveBmiStatusLocale(
|
||||
localeParam ?? user.locale ?? "de",
|
||||
);
|
||||
|
||||
const result = await generateBmiStatusForUser(user.id, {
|
||||
locale,
|
||||
force: false,
|
||||
});
|
||||
|
||||
annotate({ action: { name: "insights.bmi-status" } });
|
||||
|
||||
return apiSuccess(result);
|
||||
});
|
||||
@@ -0,0 +1,378 @@
|
||||
import { prisma } from "@/lib/db";
|
||||
import { apiSuccess } from "@/lib/api-response";
|
||||
import { summarize, type DataPoint } from "@/lib/analytics/trends";
|
||||
import { getBpTargets } from "@/lib/analytics/bp-targets";
|
||||
import {
|
||||
classifyBMI,
|
||||
classifyBP,
|
||||
generateAlerts,
|
||||
} from "@/lib/analytics/classifications";
|
||||
import {
|
||||
pairByTimestamp,
|
||||
pearsonCorrelation,
|
||||
type PairedPoint,
|
||||
} from "@/lib/analytics/correlations";
|
||||
import { calculateCompliance } from "@/lib/analytics/compliance";
|
||||
import { getMedicationCategories } from "@/lib/medication-category";
|
||||
import type { MeasurementType } from "@/generated/prisma/client";
|
||||
import { apiHandler, requireAuth } from "@/lib/api-handler";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export const GET = apiHandler(async () => {
|
||||
const { user } = await requireAuth();
|
||||
|
||||
const userId = user.id;
|
||||
const ninetyDaysAgo = new Date(Date.now() - 90 * 24 * 60 * 60 * 1000);
|
||||
|
||||
// Fetch user profile
|
||||
const dbUser = await prisma.user.findUnique({
|
||||
where: { id: userId },
|
||||
select: {
|
||||
heightCm: true,
|
||||
dateOfBirth: true,
|
||||
openaiKeyEncrypted: true,
|
||||
},
|
||||
});
|
||||
|
||||
// Fetch all measurements (90 days)
|
||||
const types: MeasurementType[] = [
|
||||
"WEIGHT",
|
||||
"BLOOD_PRESSURE_SYS",
|
||||
"BLOOD_PRESSURE_DIA",
|
||||
"PULSE",
|
||||
"BODY_FAT",
|
||||
];
|
||||
|
||||
const allMeasurements = await prisma.measurement.findMany({
|
||||
where: { userId, type: { in: types }, measuredAt: { gte: ninetyDaysAgo } },
|
||||
orderBy: { measuredAt: "asc" },
|
||||
select: { type: true, value: true, measuredAt: true },
|
||||
});
|
||||
|
||||
// Fetch mood entries (90 days)
|
||||
const moodEntries = await prisma.moodEntry.findMany({
|
||||
where: { userId, moodLoggedAt: { gte: ninetyDaysAgo } },
|
||||
orderBy: { moodLoggedAt: "asc" },
|
||||
select: { date: true, score: true, moodLoggedAt: true },
|
||||
});
|
||||
|
||||
// Aggregate mood to daily averages
|
||||
const moodByDay = new Map<string, { sum: number; count: number }>();
|
||||
for (const entry of moodEntries) {
|
||||
const current = moodByDay.get(entry.date) ?? { sum: 0, count: 0 };
|
||||
current.sum += entry.score;
|
||||
current.count += 1;
|
||||
moodByDay.set(entry.date, current);
|
||||
}
|
||||
const dailyMoodEntries = Array.from(moodByDay.entries())
|
||||
.sort(([a], [b]) => a.localeCompare(b))
|
||||
.map(([day, stats]) => ({
|
||||
day,
|
||||
value: Math.round((stats.sum / stats.count) * 100) / 100,
|
||||
}));
|
||||
|
||||
// Build DataPoint array for mood summary
|
||||
const moodDataPoints: DataPoint[] = moodEntries.map((e) => ({
|
||||
date: e.moodLoggedAt,
|
||||
value: e.score,
|
||||
}));
|
||||
const moodSummary = moodDataPoints.length > 0 ? summarize(moodDataPoints) : null;
|
||||
|
||||
const byType = (t: MeasurementType): DataPoint[] =>
|
||||
allMeasurements
|
||||
.filter((m) => m.type === t)
|
||||
.map((m) => ({ date: m.measuredAt, value: m.value }));
|
||||
|
||||
// Summaries
|
||||
const summaries: Record<string, ReturnType<typeof summarize>> = {};
|
||||
for (const t of types) {
|
||||
const data = byType(t);
|
||||
if (data.length > 0) {
|
||||
summaries[t] = summarize(data);
|
||||
}
|
||||
}
|
||||
|
||||
// BMI
|
||||
let bmi: number | null = null;
|
||||
let bmiClassification = null;
|
||||
if (dbUser?.heightCm && summaries.WEIGHT?.latest) {
|
||||
const heightM = dbUser.heightCm / 100;
|
||||
bmi = Math.round((summaries.WEIGHT.latest / (heightM * heightM)) * 10) / 10;
|
||||
bmiClassification = classifyBMI(bmi);
|
||||
}
|
||||
|
||||
// BP classification (30-day average)
|
||||
let bpClassification = null;
|
||||
const bpTargets = getBpTargets(dbUser?.dateOfBirth ?? null);
|
||||
if (
|
||||
summaries.BLOOD_PRESSURE_SYS?.avg30 &&
|
||||
summaries.BLOOD_PRESSURE_DIA?.avg30
|
||||
) {
|
||||
bpClassification = classifyBP(
|
||||
summaries.BLOOD_PRESSURE_SYS.avg30,
|
||||
summaries.BLOOD_PRESSURE_DIA.avg30,
|
||||
);
|
||||
}
|
||||
|
||||
// BP target adherence
|
||||
let bpPctInTarget: number | null = null;
|
||||
if (bpTargets) {
|
||||
const sysData = byType("BLOOD_PRESSURE_SYS");
|
||||
const diaData = byType("BLOOD_PRESSURE_DIA");
|
||||
const sysPairs = pairByTimestamp(sysData, diaData, 5 * 60 * 1000);
|
||||
|
||||
if (sysPairs.length > 0) {
|
||||
const inTarget = sysPairs.filter(
|
||||
(p) =>
|
||||
p.a >= bpTargets.sysLow &&
|
||||
p.a <= bpTargets.sysHigh &&
|
||||
p.b >= bpTargets.diaLow &&
|
||||
p.b <= bpTargets.diaHigh,
|
||||
).length;
|
||||
bpPctInTarget = Math.round((inTarget / sysPairs.length) * 100);
|
||||
}
|
||||
}
|
||||
|
||||
// Correlations: Weight vs Sys BP
|
||||
const weightData = byType("WEIGHT");
|
||||
const sysData = byType("BLOOD_PRESSURE_SYS");
|
||||
const weightBpPairs = pairByTimestamp(weightData, sysData);
|
||||
const weightBpCorrelation = pearsonCorrelation(weightBpPairs);
|
||||
const scatterData = weightBpPairs.map((p) => ({
|
||||
weight: p.a,
|
||||
sysBP: p.b,
|
||||
}));
|
||||
|
||||
// Correlations: Mood vs metrics (using daily averages matched by date)
|
||||
function buildMoodMetricPairs(
|
||||
dailyMood: Array<{ day: string; value: number }>,
|
||||
measurements: Array<{ measuredAt: Date; value: number }>,
|
||||
): PairedPoint[] {
|
||||
// Group measurements by day
|
||||
const metricByDay = new Map<string, { sum: number; count: number }>();
|
||||
for (const m of measurements) {
|
||||
const dayKey = m.measuredAt.toISOString().slice(0, 10);
|
||||
const current = metricByDay.get(dayKey) ?? { sum: 0, count: 0 };
|
||||
current.sum += m.value;
|
||||
current.count += 1;
|
||||
metricByDay.set(dayKey, current);
|
||||
}
|
||||
|
||||
const pairs: PairedPoint[] = [];
|
||||
for (const mood of dailyMood) {
|
||||
const metric = metricByDay.get(mood.day);
|
||||
if (metric) {
|
||||
pairs.push({
|
||||
a: mood.value,
|
||||
b: Math.round((metric.sum / metric.count) * 100) / 100,
|
||||
date: new Date(`${mood.day}T12:00:00.000Z`),
|
||||
});
|
||||
}
|
||||
}
|
||||
return pairs;
|
||||
}
|
||||
|
||||
// Mood vs Systolic BP
|
||||
const moodBpPairs = buildMoodMetricPairs(
|
||||
dailyMoodEntries,
|
||||
allMeasurements.filter((m) => m.type === "BLOOD_PRESSURE_SYS").map((m) => ({ measuredAt: m.measuredAt, value: m.value })),
|
||||
);
|
||||
const moodBpCorrelation = pearsonCorrelation(moodBpPairs);
|
||||
const moodBpScatterData = moodBpPairs.map((p) => ({ mood: p.a, sysBP: p.b }));
|
||||
|
||||
// Mood vs Weight
|
||||
const moodWeightPairs = buildMoodMetricPairs(
|
||||
dailyMoodEntries,
|
||||
allMeasurements.filter((m) => m.type === "WEIGHT").map((m) => ({ measuredAt: m.measuredAt, value: m.value })),
|
||||
);
|
||||
const moodWeightCorrelation = pearsonCorrelation(moodWeightPairs);
|
||||
const moodWeightScatterData = moodWeightPairs.map((p) => ({ mood: p.a, weight: p.b }));
|
||||
|
||||
// Mood vs Pulse
|
||||
const moodPulsePairs = buildMoodMetricPairs(
|
||||
dailyMoodEntries,
|
||||
allMeasurements.filter((m) => m.type === "PULSE").map((m) => ({ measuredAt: m.measuredAt, value: m.value })),
|
||||
);
|
||||
const moodPulseCorrelation = pearsonCorrelation(moodPulsePairs);
|
||||
const moodPulseScatterData = moodPulsePairs.map((p) => ({ mood: p.a, pulse: p.b }));
|
||||
|
||||
// Medication compliance
|
||||
const medications = await prisma.medication.findMany({
|
||||
where: { userId, active: true },
|
||||
include: { schedules: true },
|
||||
});
|
||||
const categoryMap = await getMedicationCategories(
|
||||
medications.map((m) => m.id),
|
||||
);
|
||||
|
||||
const medCompliance = [];
|
||||
const bpMedicationEvents: Array<{
|
||||
scheduledFor: Date;
|
||||
takenAt: Date | null;
|
||||
skipped: boolean;
|
||||
}> = [];
|
||||
const bpMedications = medications.filter(
|
||||
(med) => (categoryMap[med.id] ?? "OTHER") === "BLOOD_PRESSURE",
|
||||
);
|
||||
for (const med of medications) {
|
||||
const events = await prisma.medicationIntakeEvent.findMany({
|
||||
where: {
|
||||
medicationId: med.id,
|
||||
userId,
|
||||
scheduledFor: { gte: ninetyDaysAgo },
|
||||
},
|
||||
orderBy: { scheduledFor: "desc" },
|
||||
});
|
||||
const mapped = events.map((e) => ({
|
||||
takenAt: e.takenAt,
|
||||
skipped: e.skipped,
|
||||
scheduledFor: e.scheduledFor,
|
||||
}));
|
||||
const c7 = calculateCompliance(mapped, med.schedules, 7, med.createdAt);
|
||||
const c30 = calculateCompliance(mapped, med.schedules, 30, med.createdAt);
|
||||
|
||||
medCompliance.push({
|
||||
id: med.id,
|
||||
name: med.name,
|
||||
dose: med.dose,
|
||||
category: categoryMap[med.id] ?? "OTHER",
|
||||
compliance7: c7.rate,
|
||||
compliance30: c30.rate,
|
||||
streak: c7.streak,
|
||||
taken7: c7.taken,
|
||||
skipped7: c7.skipped,
|
||||
missed7: c7.missed,
|
||||
});
|
||||
|
||||
if ((categoryMap[med.id] ?? "OTHER") === "BLOOD_PRESSURE") {
|
||||
bpMedicationEvents.push(
|
||||
...events.map((e) => ({
|
||||
scheduledFor: e.scheduledFor,
|
||||
takenAt: e.takenAt,
|
||||
skipped: e.skipped,
|
||||
})),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Correlation: continuity of BP medications vs systolic BP
|
||||
let bpMedicationCorrelation: {
|
||||
r: number;
|
||||
strength: string;
|
||||
n: number;
|
||||
medicationCount: number;
|
||||
} | null = null;
|
||||
const bpMedicationScatterData: Array<{
|
||||
continuityPct: number;
|
||||
sysBP: number;
|
||||
}> = [];
|
||||
|
||||
const expectedBpIntakesPerDay = bpMedications.reduce(
|
||||
(sum, med) => sum + med.schedules.length,
|
||||
0,
|
||||
);
|
||||
|
||||
if (expectedBpIntakesPerDay > 0) {
|
||||
const sysByDay = new Map<string, number[]>();
|
||||
for (const m of allMeasurements) {
|
||||
if (m.type !== "BLOOD_PRESSURE_SYS") continue;
|
||||
const dayKey = m.measuredAt.toISOString().slice(0, 10);
|
||||
const list = sysByDay.get(dayKey) ?? [];
|
||||
list.push(m.value);
|
||||
sysByDay.set(dayKey, list);
|
||||
}
|
||||
|
||||
const takenByDay = new Map<string, number>();
|
||||
for (const event of bpMedicationEvents) {
|
||||
if (event.skipped || !event.takenAt) continue;
|
||||
const dayKey = event.scheduledFor.toISOString().slice(0, 10);
|
||||
takenByDay.set(dayKey, (takenByDay.get(dayKey) ?? 0) + 1);
|
||||
}
|
||||
|
||||
const pairs: Array<{ a: number; b: number; date: Date }> = [];
|
||||
for (const [dayKey, sysValues] of sysByDay.entries()) {
|
||||
const taken = takenByDay.get(dayKey) ?? 0;
|
||||
const continuity = Math.min(1, taken / expectedBpIntakesPerDay);
|
||||
const avgSys =
|
||||
sysValues.reduce((sum, value) => sum + value, 0) / sysValues.length;
|
||||
pairs.push({
|
||||
a: continuity,
|
||||
b: avgSys,
|
||||
date: new Date(`${dayKey}T00:00:00.000Z`),
|
||||
});
|
||||
bpMedicationScatterData.push({
|
||||
continuityPct: Math.round(continuity * 100),
|
||||
sysBP: Math.round(avgSys * 10) / 10,
|
||||
});
|
||||
}
|
||||
|
||||
const corr = pearsonCorrelation(pairs);
|
||||
if (corr) {
|
||||
bpMedicationCorrelation = {
|
||||
...corr,
|
||||
medicationCount: bpMedications.length,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// Generate alerts
|
||||
const alerts = generateAlerts({
|
||||
bmi,
|
||||
bpAvgSys: summaries.BLOOD_PRESSURE_SYS?.avg30 ?? null,
|
||||
bpAvgDia: summaries.BLOOD_PRESSURE_DIA?.avg30 ?? null,
|
||||
bpPctInTarget,
|
||||
weightSlope30: summaries.WEIGHT?.slope30?.slope ?? null,
|
||||
pulseAvg30: summaries.PULSE?.avg30 ?? null,
|
||||
pulseAnomalyCount: summaries.PULSE?.anomalyCount,
|
||||
medications: medCompliance.map((m) => ({
|
||||
name: m.name,
|
||||
compliance7: m.compliance7,
|
||||
compliance30: m.compliance30,
|
||||
})),
|
||||
});
|
||||
|
||||
// Data span
|
||||
const firstMeasurement =
|
||||
allMeasurements.length > 0 ? allMeasurements[0].measuredAt : null;
|
||||
const dataSpanDays = firstMeasurement
|
||||
? Math.ceil(
|
||||
(Date.now() - firstMeasurement.getTime()) / (24 * 60 * 60 * 1000),
|
||||
)
|
||||
: 0;
|
||||
|
||||
annotate({
|
||||
action: { name: "insights.comprehensive" },
|
||||
meta: {
|
||||
totalMeasurements: allMeasurements.length,
|
||||
moodEntries: moodEntries.length,
|
||||
medications: medications.length,
|
||||
},
|
||||
});
|
||||
|
||||
return apiSuccess({
|
||||
summaries,
|
||||
bmi,
|
||||
bmiClassification,
|
||||
bpClassification,
|
||||
bpPctInTarget,
|
||||
bpTargets,
|
||||
weightBpCorrelation,
|
||||
scatterData,
|
||||
bpMedicationCorrelation,
|
||||
bpMedicationScatterData,
|
||||
moodSummary,
|
||||
moodBpCorrelation,
|
||||
moodBpScatterData,
|
||||
moodWeightCorrelation,
|
||||
moodWeightScatterData,
|
||||
moodPulseCorrelation,
|
||||
moodPulseScatterData,
|
||||
medications: medCompliance,
|
||||
alerts,
|
||||
hasOpenAiKey: !!dbUser?.openaiKeyEncrypted,
|
||||
dataSpanDays,
|
||||
totalMeasurements: allMeasurements.length,
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,28 @@
|
||||
import { NextRequest } from "next/server";
|
||||
import { apiSuccess } from "@/lib/api-response";
|
||||
import {
|
||||
generateGeneralStatusForUser,
|
||||
resolveGeneralStatusLocale,
|
||||
} from "@/lib/insights/general-status";
|
||||
import { apiHandler, requireAuth } from "@/lib/api-handler";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export const GET = apiHandler(async (request: NextRequest) => {
|
||||
const { user } = await requireAuth();
|
||||
|
||||
const localeParam = request.nextUrl.searchParams.get("locale");
|
||||
const locale = resolveGeneralStatusLocale(
|
||||
localeParam ?? user.locale ?? "de",
|
||||
);
|
||||
|
||||
const result = await generateGeneralStatusForUser(user.id, {
|
||||
locale,
|
||||
force: false,
|
||||
});
|
||||
|
||||
annotate({ action: { name: "insights.general-status" } });
|
||||
|
||||
return apiSuccess(result);
|
||||
});
|
||||
@@ -0,0 +1,156 @@
|
||||
import { prisma } from "@/lib/db";
|
||||
import { auditLog } from "@/lib/auth/audit";
|
||||
import { apiSuccess, apiError, getClientIp } from "@/lib/api-response";
|
||||
import { decrypt } from "@/lib/crypto";
|
||||
import { extractFeatures } from "@/lib/insights/features";
|
||||
import {
|
||||
INSIGHTS_SYSTEM_PROMPT,
|
||||
buildUserPrompt,
|
||||
type InsightsOutput,
|
||||
} from "@/lib/insights/prompt";
|
||||
import { checkRateLimit } from "@/lib/rate-limit";
|
||||
import { NextRequest } from "next/server";
|
||||
import { apiHandler, requireAuth } from "@/lib/api-handler";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
|
||||
/**
|
||||
* Generate AI-powered health insights.
|
||||
* Rate limit: 2 per hour per user.
|
||||
* Caches result daily (or until new data arrives).
|
||||
*/
|
||||
export const POST = apiHandler(async (request: NextRequest) => {
|
||||
const { user } = await requireAuth();
|
||||
|
||||
const userId = user.id;
|
||||
|
||||
// Rate limit: 2 per hour per user
|
||||
const rl = await checkRateLimit(`insights:${userId}`, 2, 60 * 60 * 1000);
|
||||
if (!rl.allowed) {
|
||||
return apiError(
|
||||
"Maximal 2 Insights-Generierungen pro Stunde. Bitte spaeter erneut versuchen.",
|
||||
429,
|
||||
);
|
||||
}
|
||||
|
||||
const dbUser = await prisma.user.findUnique({
|
||||
where: { id: userId },
|
||||
select: {
|
||||
openaiKeyEncrypted: true,
|
||||
insightsPrivacyMode: true,
|
||||
insightsCachedAt: true,
|
||||
insightsCachedText: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (!dbUser?.openaiKeyEncrypted) {
|
||||
return apiError(
|
||||
"Kein OpenAI API-Key hinterlegt. Bitte in den Einstellungen konfigurieren.",
|
||||
422,
|
||||
);
|
||||
}
|
||||
|
||||
// Check if force refresh is requested
|
||||
const body = await request.json().catch(() => ({}));
|
||||
const forceRefresh = body.force === true;
|
||||
|
||||
// Return cached result if available and less than 24h old
|
||||
if (
|
||||
!forceRefresh &&
|
||||
dbUser.insightsCachedAt &&
|
||||
dbUser.insightsCachedText &&
|
||||
Date.now() - dbUser.insightsCachedAt.getTime() < 24 * 60 * 60 * 1000
|
||||
) {
|
||||
try {
|
||||
const cached = JSON.parse(dbUser.insightsCachedText) as InsightsOutput;
|
||||
annotate({ action: { name: "insights.generate" }, meta: { cached: true } });
|
||||
return apiSuccess({
|
||||
insights: cached,
|
||||
cached: true,
|
||||
cachedAt: dbUser.insightsCachedAt,
|
||||
});
|
||||
} catch {
|
||||
// Invalid cache, regenerate
|
||||
}
|
||||
}
|
||||
|
||||
const apiKey = decrypt(dbUser.openaiKeyEncrypted);
|
||||
const includeRaw = dbUser.insightsPrivacyMode === "raw";
|
||||
const features = await extractFeatures(userId, includeRaw);
|
||||
const featuresJson = JSON.stringify(features, null, 2);
|
||||
const userPrompt = buildUserPrompt(featuresJson, dbUser.insightsPrivacyMode);
|
||||
|
||||
// Call OpenAI
|
||||
const openaiRes = await fetch(
|
||||
"https://api.openai.com/v1/chat/completions",
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `Bearer ${apiKey}`,
|
||||
},
|
||||
body: JSON.stringify({
|
||||
model: "gpt-4o-mini",
|
||||
messages: [
|
||||
{ role: "system", content: INSIGHTS_SYSTEM_PROMPT },
|
||||
{ role: "user", content: userPrompt },
|
||||
],
|
||||
temperature: 0.3,
|
||||
max_tokens: 1000,
|
||||
response_format: { type: "json_object" },
|
||||
}),
|
||||
},
|
||||
);
|
||||
|
||||
if (!openaiRes.ok) {
|
||||
const errBody = await openaiRes.text();
|
||||
annotate({ meta: { openai_status: openaiRes.status, openai_error: errBody } });
|
||||
if (openaiRes.status === 401) {
|
||||
return apiError("Ungueltiger OpenAI API-Key", 422);
|
||||
}
|
||||
return apiError("OpenAI-Anfrage fehlgeschlagen", 502);
|
||||
}
|
||||
|
||||
const openaiJson = await openaiRes.json();
|
||||
const content = openaiJson.choices?.[0]?.message?.content;
|
||||
|
||||
if (!content) {
|
||||
return apiError("Keine Antwort von OpenAI erhalten", 502);
|
||||
}
|
||||
|
||||
let insights: InsightsOutput;
|
||||
try {
|
||||
insights = JSON.parse(content);
|
||||
} catch {
|
||||
return apiError("OpenAI-Antwort konnte nicht verarbeitet werden", 502);
|
||||
}
|
||||
|
||||
// Cache the result
|
||||
await prisma.user.update({
|
||||
where: { id: userId },
|
||||
data: {
|
||||
insightsCachedAt: new Date(),
|
||||
insightsCachedText: JSON.stringify(insights),
|
||||
},
|
||||
});
|
||||
|
||||
// Audit log (no sensitive content)
|
||||
await auditLog("insights.generate", {
|
||||
userId,
|
||||
ipAddress: getClientIp(request),
|
||||
details: {
|
||||
privacyMode: dbUser.insightsPrivacyMode,
|
||||
tokensUsed: openaiJson.usage?.total_tokens ?? null,
|
||||
},
|
||||
});
|
||||
|
||||
annotate({
|
||||
action: { name: "insights.generate" },
|
||||
meta: {
|
||||
cached: false,
|
||||
privacyMode: dbUser.insightsPrivacyMode,
|
||||
tokensUsed: openaiJson.usage?.total_tokens ?? null,
|
||||
},
|
||||
});
|
||||
|
||||
return apiSuccess({ insights, cached: false });
|
||||
});
|
||||
@@ -0,0 +1,31 @@
|
||||
import { NextRequest } from "next/server";
|
||||
import { apiSuccess } from "@/lib/api-response";
|
||||
import {
|
||||
generateMedicationComplianceStatusForUser,
|
||||
resolveMedicationComplianceStatusLocale,
|
||||
} from "@/lib/insights/medication-compliance-status";
|
||||
import { apiHandler, requireAuth } from "@/lib/api-handler";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export const GET = apiHandler(async (request: NextRequest) => {
|
||||
const { user } = await requireAuth();
|
||||
|
||||
const localeParam = request.nextUrl.searchParams.get("locale");
|
||||
const locale = resolveMedicationComplianceStatusLocale(
|
||||
localeParam ?? user.locale ?? "de",
|
||||
);
|
||||
|
||||
const result = await generateMedicationComplianceStatusForUser(
|
||||
user.id,
|
||||
{
|
||||
locale,
|
||||
force: false,
|
||||
},
|
||||
);
|
||||
|
||||
annotate({ action: { name: "insights.medication-compliance-status" } });
|
||||
|
||||
return apiSuccess(result);
|
||||
});
|
||||
@@ -0,0 +1,28 @@
|
||||
import { NextRequest } from "next/server";
|
||||
import { apiSuccess } from "@/lib/api-response";
|
||||
import {
|
||||
generateMoodStatusForUser,
|
||||
resolveMoodStatusLocale,
|
||||
} from "@/lib/insights/mood-status";
|
||||
import { apiHandler, requireAuth } from "@/lib/api-handler";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export const GET = apiHandler(async (request: NextRequest) => {
|
||||
const { user } = await requireAuth();
|
||||
|
||||
const localeParam = request.nextUrl.searchParams.get("locale");
|
||||
const locale = resolveMoodStatusLocale(
|
||||
localeParam ?? user.locale ?? "de",
|
||||
);
|
||||
|
||||
const result = await generateMoodStatusForUser(user.id, {
|
||||
locale,
|
||||
force: false,
|
||||
});
|
||||
|
||||
annotate({ action: { name: "insights.mood-status" } });
|
||||
|
||||
return apiSuccess(result);
|
||||
});
|
||||
@@ -0,0 +1,28 @@
|
||||
import { NextRequest } from "next/server";
|
||||
import { apiSuccess } from "@/lib/api-response";
|
||||
import {
|
||||
generatePulseStatusForUser,
|
||||
resolvePulseStatusLocale,
|
||||
} from "@/lib/insights/pulse-status";
|
||||
import { apiHandler, requireAuth } from "@/lib/api-handler";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export const GET = apiHandler(async (request: NextRequest) => {
|
||||
const { user } = await requireAuth();
|
||||
|
||||
const localeParam = request.nextUrl.searchParams.get("locale");
|
||||
const locale = resolvePulseStatusLocale(
|
||||
localeParam ?? user.locale ?? "de",
|
||||
);
|
||||
|
||||
const result = await generatePulseStatusForUser(user.id, {
|
||||
locale,
|
||||
force: false,
|
||||
});
|
||||
|
||||
annotate({ action: { name: "insights.pulse-status" } });
|
||||
|
||||
return apiSuccess(result);
|
||||
});
|
||||
@@ -0,0 +1,86 @@
|
||||
import { prisma } from "@/lib/db";
|
||||
import { apiSuccess, apiError, safeJson } from "@/lib/api-response";
|
||||
import { encrypt } from "@/lib/crypto";
|
||||
import { NextRequest } from "next/server";
|
||||
import { apiHandler, requireAuth } from "@/lib/api-handler";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
|
||||
/**
|
||||
* Get insights configuration status.
|
||||
*/
|
||||
export const GET = apiHandler(async () => {
|
||||
const { user } = await requireAuth();
|
||||
|
||||
const dbUser = await prisma.user.findUnique({
|
||||
where: { id: user.id },
|
||||
select: {
|
||||
openaiKeyEncrypted: true,
|
||||
insightsPrivacyMode: true,
|
||||
insightsCachedAt: true,
|
||||
},
|
||||
});
|
||||
|
||||
annotate({ action: { name: "insights.settings.get" } });
|
||||
|
||||
return apiSuccess({
|
||||
hasKey: !!dbUser?.openaiKeyEncrypted,
|
||||
privacyMode: dbUser?.insightsPrivacyMode ?? "aggregated",
|
||||
lastInsightAt: dbUser?.insightsCachedAt ?? null,
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* Update insights settings (API key and/or privacy mode).
|
||||
*/
|
||||
export const PUT = apiHandler(async (request: NextRequest) => {
|
||||
const { user } = await requireAuth();
|
||||
|
||||
const { data: body, error: jsonError } = await safeJson<Record<string, unknown>>(request);
|
||||
|
||||
if (jsonError) return jsonError;
|
||||
const data: Record<string, unknown> = {};
|
||||
|
||||
// Update API key if provided
|
||||
if (typeof body.apiKey === "string") {
|
||||
const key = (body.apiKey as string).trim();
|
||||
if (key === "") {
|
||||
// Remove key
|
||||
data.openaiKeyEncrypted = null;
|
||||
data.insightsCachedAt = null;
|
||||
data.insightsCachedText = null;
|
||||
} else {
|
||||
if (!key.startsWith("sk-")) {
|
||||
return apiError(
|
||||
"Ungueltiges API-Key-Format (muss mit sk- beginnen)",
|
||||
422,
|
||||
);
|
||||
}
|
||||
data.openaiKeyEncrypted = encrypt(key);
|
||||
}
|
||||
}
|
||||
|
||||
// Update privacy mode if provided
|
||||
if (typeof body.privacyMode === "string") {
|
||||
const mode = body.privacyMode as string;
|
||||
if (!["aggregated", "raw"].includes(mode)) {
|
||||
return apiError("Ungueltiger Privacy-Modus", 422);
|
||||
}
|
||||
data.insightsPrivacyMode = mode;
|
||||
// Clear cache when privacy mode changes
|
||||
data.insightsCachedAt = null;
|
||||
data.insightsCachedText = null;
|
||||
}
|
||||
|
||||
if (Object.keys(data).length === 0) {
|
||||
return apiError("Keine Aenderungen", 422);
|
||||
}
|
||||
|
||||
await prisma.user.update({
|
||||
where: { id: user.id },
|
||||
data,
|
||||
});
|
||||
|
||||
annotate({ action: { name: "insights.settings.update" } });
|
||||
|
||||
return apiSuccess({ updated: true });
|
||||
});
|
||||
@@ -0,0 +1,589 @@
|
||||
import { prisma } from "@/lib/db";
|
||||
import { apiSuccess } from "@/lib/api-response";
|
||||
import {
|
||||
classifyBMI,
|
||||
classifyBP,
|
||||
classifySleepDuration,
|
||||
classifyBodyFat,
|
||||
classifySteps,
|
||||
getWeightRange,
|
||||
getSleepDurationRange,
|
||||
getStepsRange,
|
||||
getBpTargetsByAge,
|
||||
} from "@/lib/analytics/classifications";
|
||||
import { calculateCompliance } from "@/lib/analytics/compliance";
|
||||
import { pairByTimestamp } from "@/lib/analytics/correlations";
|
||||
import {
|
||||
classifyPulseByTarget,
|
||||
getPersonalizedPulseTarget,
|
||||
} from "@/lib/analytics/pulse-targets";
|
||||
import type { MeasurementType } from "@/generated/prisma/client";
|
||||
import { apiHandler, requireAuth } from "@/lib/api-handler";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
function getAge(dateOfBirth: Date): number {
|
||||
const today = new Date();
|
||||
let age = today.getFullYear() - dateOfBirth.getFullYear();
|
||||
const monthDiff = today.getMonth() - dateOfBirth.getMonth();
|
||||
if (
|
||||
monthDiff < 0 ||
|
||||
(monthDiff === 0 && today.getDate() < dateOfBirth.getDate())
|
||||
) {
|
||||
age--;
|
||||
}
|
||||
return age;
|
||||
}
|
||||
|
||||
interface TargetItem {
|
||||
type: string;
|
||||
label: string;
|
||||
current: number | null;
|
||||
average30: number | null;
|
||||
trend: "up" | "down" | "stable" | null;
|
||||
unit: string;
|
||||
range: { min: number; max: number } | null;
|
||||
classification: { category: string; color: string } | null;
|
||||
source: string;
|
||||
details?: {
|
||||
medications?: Array<{
|
||||
name: string;
|
||||
compliance7: number;
|
||||
compliance30: number;
|
||||
}>;
|
||||
};
|
||||
}
|
||||
|
||||
export const GET = apiHandler(async () => {
|
||||
const { user } = await requireAuth();
|
||||
|
||||
const userId = user.id;
|
||||
|
||||
// Fetch user profile
|
||||
const dbUser = await prisma.user.findUnique({
|
||||
where: { id: userId },
|
||||
select: {
|
||||
heightCm: true,
|
||||
dateOfBirth: true,
|
||||
gender: true,
|
||||
},
|
||||
});
|
||||
|
||||
const age = dbUser?.dateOfBirth ? getAge(new Date(dbUser.dateOfBirth)) : null;
|
||||
const gender = (dbUser?.gender as "MALE" | "FEMALE" | null) ?? null;
|
||||
const heightCm = dbUser?.heightCm ?? null;
|
||||
|
||||
// Fetch latest measurements for each type
|
||||
const types: MeasurementType[] = [
|
||||
"WEIGHT",
|
||||
"BLOOD_PRESSURE_SYS",
|
||||
"BLOOD_PRESSURE_DIA",
|
||||
"PULSE",
|
||||
"SLEEP_DURATION",
|
||||
"BODY_FAT",
|
||||
"ACTIVITY_STEPS",
|
||||
];
|
||||
|
||||
const thirtyDaysAgo = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000);
|
||||
|
||||
// Fetch all measurements in the last 30 days + the latest for each type
|
||||
const recentMeasurements = await prisma.measurement.findMany({
|
||||
where: {
|
||||
userId,
|
||||
type: { in: types },
|
||||
measuredAt: { gte: thirtyDaysAgo },
|
||||
},
|
||||
orderBy: { measuredAt: "desc" },
|
||||
select: { type: true, value: true, measuredAt: true },
|
||||
});
|
||||
|
||||
// Also get the absolute latest measurement per type (even if older than 30 days)
|
||||
const latestByType: Record<string, number | null> = {};
|
||||
const avg30ByType: Record<string, number | null> = {};
|
||||
|
||||
for (const t of types) {
|
||||
// Latest value
|
||||
const latest = await prisma.measurement.findFirst({
|
||||
where: { userId, type: t },
|
||||
orderBy: { measuredAt: "desc" },
|
||||
select: { value: true },
|
||||
});
|
||||
latestByType[t] = latest?.value ?? null;
|
||||
|
||||
// 30-day average
|
||||
const recentOfType = recentMeasurements.filter((m) => m.type === t);
|
||||
if (recentOfType.length > 0) {
|
||||
const sum = recentOfType.reduce((acc, m) => acc + m.value, 0);
|
||||
avg30ByType[t] = Math.round((sum / recentOfType.length) * 10) / 10;
|
||||
} else {
|
||||
avg30ByType[t] = null;
|
||||
}
|
||||
}
|
||||
|
||||
// Compute trend (compare first half of 30-day data to second half)
|
||||
function computeTrend(
|
||||
type: MeasurementType,
|
||||
): "up" | "down" | "stable" | null {
|
||||
const data = recentMeasurements
|
||||
.filter((m) => m.type === type)
|
||||
.sort((a, b) => a.measuredAt.getTime() - b.measuredAt.getTime());
|
||||
if (data.length < 4) return null;
|
||||
|
||||
const mid = Math.floor(data.length / 2);
|
||||
const firstHalf = data.slice(0, mid);
|
||||
const secondHalf = data.slice(mid);
|
||||
|
||||
const avgFirst =
|
||||
firstHalf.reduce((s, m) => s + m.value, 0) / firstHalf.length;
|
||||
const avgSecond =
|
||||
secondHalf.reduce((s, m) => s + m.value, 0) / secondHalf.length;
|
||||
|
||||
const diff = avgSecond - avgFirst;
|
||||
const threshold = avgFirst * 0.02; // 2% change threshold
|
||||
|
||||
if (diff > threshold) return "up";
|
||||
if (diff < -threshold) return "down";
|
||||
return "stable";
|
||||
}
|
||||
|
||||
// Build target items
|
||||
const targets: TargetItem[] = [];
|
||||
|
||||
// 1. Weight
|
||||
const weightRange = heightCm ? getWeightRange(heightCm) : null;
|
||||
let weightClassification: { category: string; color: string } | null = null;
|
||||
if (latestByType.WEIGHT != null && heightCm) {
|
||||
const heightM = heightCm / 100;
|
||||
const bmi = latestByType.WEIGHT / (heightM * heightM);
|
||||
const cls = classifyBMI(bmi);
|
||||
weightClassification = { category: cls.category, color: cls.color };
|
||||
}
|
||||
targets.push({
|
||||
type: "WEIGHT",
|
||||
label: "Gewicht",
|
||||
current: latestByType.WEIGHT ?? null,
|
||||
average30: avg30ByType.WEIGHT ?? null,
|
||||
trend: computeTrend("WEIGHT"),
|
||||
unit: "kg",
|
||||
range: weightRange,
|
||||
classification: weightClassification,
|
||||
source: "WHO BMI",
|
||||
});
|
||||
|
||||
// 2. Blood Pressure (sys/dia combined)
|
||||
const bpRange = age != null ? getBpTargetsByAge(age, gender) : null;
|
||||
let bpClassification: { category: string; color: string } | null = null;
|
||||
if (
|
||||
latestByType.BLOOD_PRESSURE_SYS != null &&
|
||||
latestByType.BLOOD_PRESSURE_DIA != null
|
||||
) {
|
||||
const cls = classifyBP(
|
||||
latestByType.BLOOD_PRESSURE_SYS,
|
||||
latestByType.BLOOD_PRESSURE_DIA,
|
||||
);
|
||||
bpClassification = { category: cls.category, color: cls.color };
|
||||
}
|
||||
targets.push({
|
||||
type: "BLOOD_PRESSURE",
|
||||
label: "Blutdruck",
|
||||
current: latestByType.BLOOD_PRESSURE_SYS ?? null,
|
||||
average30: avg30ByType.BLOOD_PRESSURE_SYS ?? null,
|
||||
trend: computeTrend("BLOOD_PRESSURE_SYS"),
|
||||
unit: "mmHg",
|
||||
range: bpRange ? { min: bpRange.sysLow, max: bpRange.sysHigh } : null,
|
||||
classification: bpClassification,
|
||||
source: "ESC/ESH 2018",
|
||||
// Extra fields for diastolic
|
||||
} as TargetItem);
|
||||
|
||||
// 2b. Blood pressure target-hit rate over 30 days
|
||||
if (bpRange) {
|
||||
const sysPoints = recentMeasurements
|
||||
.filter((measurement) => measurement.type === "BLOOD_PRESSURE_SYS")
|
||||
.map((measurement) => ({
|
||||
date: measurement.measuredAt,
|
||||
value: measurement.value,
|
||||
}));
|
||||
const diaPoints = recentMeasurements
|
||||
.filter((measurement) => measurement.type === "BLOOD_PRESSURE_DIA")
|
||||
.map((measurement) => ({
|
||||
date: measurement.measuredAt,
|
||||
value: measurement.value,
|
||||
}));
|
||||
|
||||
const bpPairs = pairByTimestamp(sysPoints, diaPoints, 5 * 60 * 1000);
|
||||
const bpInTargetCount = bpPairs.filter(
|
||||
(pair) =>
|
||||
pair.a >= bpRange.sysLow &&
|
||||
pair.a <= bpRange.sysHigh &&
|
||||
pair.b >= bpRange.diaLow &&
|
||||
pair.b <= bpRange.diaHigh,
|
||||
).length;
|
||||
const bpInTargetRate =
|
||||
bpPairs.length > 0
|
||||
? Math.round((bpInTargetCount / bpPairs.length) * 100 * 10) / 10
|
||||
: null;
|
||||
|
||||
targets.push({
|
||||
type: "BLOOD_PRESSURE_IN_TARGET",
|
||||
label: "Blutdruck im Zielbereich",
|
||||
current: bpInTargetRate,
|
||||
average30: bpInTargetRate,
|
||||
trend: null,
|
||||
unit: "%",
|
||||
range: { min: 70, max: 100 },
|
||||
classification:
|
||||
bpInTargetRate != null
|
||||
? bpInTargetRate >= 70
|
||||
? { category: "Gut", color: "#50fa7b" }
|
||||
: bpInTargetRate >= 40
|
||||
? { category: "Moderat", color: "#f1fa8c" }
|
||||
: { category: "Niedrig", color: "#ff5555" }
|
||||
: null,
|
||||
source: "ESC/ESH 2018",
|
||||
});
|
||||
}
|
||||
|
||||
// 3. Pulse
|
||||
const pulseTarget = getPersonalizedPulseTarget(age, gender);
|
||||
let pulseClassification: { category: string; color: string } | null = null;
|
||||
if (latestByType.PULSE != null) {
|
||||
const cls = classifyPulseByTarget(latestByType.PULSE, pulseTarget);
|
||||
pulseClassification = { category: cls.category, color: cls.color };
|
||||
}
|
||||
targets.push({
|
||||
type: "PULSE",
|
||||
label: "Ruhepuls",
|
||||
current: latestByType.PULSE ?? null,
|
||||
average30: avg30ByType.PULSE ?? null,
|
||||
trend: computeTrend("PULSE"),
|
||||
unit: "bpm",
|
||||
range: { min: pulseTarget.greenMin, max: pulseTarget.greenMax },
|
||||
classification: pulseClassification,
|
||||
source: pulseTarget.source,
|
||||
});
|
||||
|
||||
// 4. Sleep Duration
|
||||
const sleepRange = getSleepDurationRange();
|
||||
let sleepClassification: { category: string; color: string } | null = null;
|
||||
if (latestByType.SLEEP_DURATION != null) {
|
||||
const cls = classifySleepDuration(latestByType.SLEEP_DURATION);
|
||||
sleepClassification = { category: cls.category, color: cls.color };
|
||||
}
|
||||
targets.push({
|
||||
type: "SLEEP_DURATION",
|
||||
label: "Schlafdauer",
|
||||
current: latestByType.SLEEP_DURATION ?? null,
|
||||
average30: avg30ByType.SLEEP_DURATION ?? null,
|
||||
trend: computeTrend("SLEEP_DURATION"),
|
||||
unit: "h",
|
||||
range: sleepRange,
|
||||
classification: sleepClassification,
|
||||
source: "AASM/SRS",
|
||||
});
|
||||
|
||||
// 5. BMI (derived from weight + height)
|
||||
if (heightCm) {
|
||||
const heightM = heightCm / 100;
|
||||
const heightSq = heightM * heightM;
|
||||
const latestWeight = latestByType.WEIGHT ?? null;
|
||||
const currentBmi =
|
||||
latestWeight != null
|
||||
? Math.round((latestWeight / heightSq) * 10) / 10
|
||||
: null;
|
||||
|
||||
// Compute 30-day average BMI from average weight
|
||||
const avgWeight = avg30ByType.WEIGHT ?? null;
|
||||
const avgBmi =
|
||||
avgWeight != null ? Math.round((avgWeight / heightSq) * 10) / 10 : null;
|
||||
|
||||
let bmiClassification: { category: string; color: string } | null = null;
|
||||
if (currentBmi != null) {
|
||||
const cls = classifyBMI(currentBmi);
|
||||
bmiClassification = { category: cls.category, color: cls.color };
|
||||
}
|
||||
|
||||
targets.push({
|
||||
type: "BMI",
|
||||
label: "BMI",
|
||||
current: currentBmi,
|
||||
average30: avgBmi,
|
||||
trend: computeTrend("WEIGHT"), // BMI trend follows weight trend
|
||||
unit: "kg/m\u00B2",
|
||||
range: { min: 18.5, max: 24.9 },
|
||||
classification: bmiClassification,
|
||||
source: "WHO",
|
||||
});
|
||||
}
|
||||
|
||||
// 6. Body Fat
|
||||
let bodyFatClassification: { category: string; color: string } | null = null;
|
||||
if (latestByType.BODY_FAT != null && age != null) {
|
||||
const cls = classifyBodyFat(latestByType.BODY_FAT, gender, age);
|
||||
bodyFatClassification = { category: cls.category, color: cls.color };
|
||||
}
|
||||
// Body fat ranges depend on gender/age; provide simplified ranges
|
||||
let bodyFatRange: { min: number; max: number } | null = null;
|
||||
if (gender === "MALE") {
|
||||
bodyFatRange = { min: 14, max: 24 };
|
||||
} else if (gender === "FEMALE") {
|
||||
bodyFatRange = { min: 21, max: 31 };
|
||||
} else if (age != null) {
|
||||
// Average of male/female fitness+average ranges
|
||||
bodyFatRange = { min: 17.5, max: 27.5 };
|
||||
}
|
||||
targets.push({
|
||||
type: "BODY_FAT",
|
||||
label: "Koerperfett",
|
||||
current: latestByType.BODY_FAT ?? null,
|
||||
average30: avg30ByType.BODY_FAT ?? null,
|
||||
trend: computeTrend("BODY_FAT"),
|
||||
unit: "%",
|
||||
range: bodyFatRange,
|
||||
classification: bodyFatClassification,
|
||||
source: "ACE",
|
||||
});
|
||||
|
||||
// 7. Activity Steps
|
||||
const stepsRange = getStepsRange();
|
||||
let stepsClassification: { category: string; color: string } | null = null;
|
||||
if (avg30ByType.ACTIVITY_STEPS != null) {
|
||||
const cls = classifySteps(avg30ByType.ACTIVITY_STEPS);
|
||||
stepsClassification = { category: cls.category, color: cls.color };
|
||||
}
|
||||
targets.push({
|
||||
type: "ACTIVITY_STEPS",
|
||||
label: "Schritte/Tag",
|
||||
current: latestByType.ACTIVITY_STEPS ?? null,
|
||||
average30: avg30ByType.ACTIVITY_STEPS ?? null,
|
||||
trend: computeTrend("ACTIVITY_STEPS"),
|
||||
unit: "Schritte",
|
||||
range: stepsRange,
|
||||
classification: stepsClassification,
|
||||
source: "WHO",
|
||||
});
|
||||
|
||||
// 8. Medication Compliance (average across active medications)
|
||||
const activeMedications = await prisma.medication.findMany({
|
||||
where: { userId, active: true },
|
||||
include: { schedules: true },
|
||||
orderBy: { name: "asc" },
|
||||
});
|
||||
|
||||
if (activeMedications.length > 0) {
|
||||
const thirtyDaysAgoIntake = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000);
|
||||
const intakeEvents = await prisma.medicationIntakeEvent.findMany({
|
||||
where: {
|
||||
userId,
|
||||
medicationId: {
|
||||
in: activeMedications.map((medication) => medication.id),
|
||||
},
|
||||
scheduledFor: { gte: thirtyDaysAgoIntake },
|
||||
},
|
||||
orderBy: { scheduledFor: "desc" },
|
||||
select: {
|
||||
medicationId: true,
|
||||
takenAt: true,
|
||||
skipped: true,
|
||||
scheduledFor: true,
|
||||
},
|
||||
});
|
||||
|
||||
const medicationStats = activeMedications.map((medication) => {
|
||||
const medicationEvents = intakeEvents.filter(
|
||||
(event) => event.medicationId === medication.id,
|
||||
);
|
||||
const compliance7 = calculateCompliance(
|
||||
medicationEvents,
|
||||
medication.schedules,
|
||||
7,
|
||||
medication.createdAt,
|
||||
);
|
||||
const compliance30 = calculateCompliance(
|
||||
medicationEvents,
|
||||
medication.schedules,
|
||||
30,
|
||||
medication.createdAt,
|
||||
);
|
||||
|
||||
return {
|
||||
name: medication.name,
|
||||
compliance7: compliance7.rate,
|
||||
compliance30: compliance30.rate,
|
||||
totalExpected7: compliance7.totalExpected,
|
||||
taken7: compliance7.taken,
|
||||
totalExpected30: compliance30.totalExpected,
|
||||
taken30: compliance30.taken,
|
||||
};
|
||||
});
|
||||
|
||||
const totalExpected7 = medicationStats.reduce(
|
||||
(sum, medication) => sum + medication.totalExpected7,
|
||||
0,
|
||||
);
|
||||
const totalTaken7 = medicationStats.reduce(
|
||||
(sum, medication) => sum + medication.taken7,
|
||||
0,
|
||||
);
|
||||
const totalExpected30 = medicationStats.reduce(
|
||||
(sum, medication) => sum + medication.totalExpected30,
|
||||
0,
|
||||
);
|
||||
const totalTaken30 = medicationStats.reduce(
|
||||
(sum, medication) => sum + medication.taken30,
|
||||
0,
|
||||
);
|
||||
|
||||
const complianceRate7 =
|
||||
totalExpected7 > 0
|
||||
? Math.round(
|
||||
(Math.min(1, totalTaken7 / totalExpected7) * 100 + Number.EPSILON) *
|
||||
10,
|
||||
) / 10
|
||||
: null;
|
||||
const complianceRate30 =
|
||||
totalExpected30 > 0
|
||||
? Math.round(
|
||||
(Math.min(1, totalTaken30 / totalExpected30) * 100 +
|
||||
Number.EPSILON) *
|
||||
10,
|
||||
) / 10
|
||||
: complianceRate7;
|
||||
|
||||
targets.push({
|
||||
type: "MEDICATION_COMPLIANCE",
|
||||
label: "Einnahmetreue",
|
||||
current: complianceRate7,
|
||||
average30: complianceRate30,
|
||||
trend: null,
|
||||
unit: "%",
|
||||
range: { min: 90, max: 100 },
|
||||
classification:
|
||||
complianceRate7 != null
|
||||
? complianceRate7 >= 90
|
||||
? { category: "Sehr gut", color: "#50fa7b" }
|
||||
: complianceRate7 >= 70
|
||||
? { category: "Gut", color: "#f1fa8c" }
|
||||
: { category: "Niedrig", color: "#ff5555" }
|
||||
: null,
|
||||
source: "7-Tage",
|
||||
details: {
|
||||
medications: medicationStats.map((medication) => ({
|
||||
name: medication.name,
|
||||
compliance7: medication.compliance7,
|
||||
compliance30: medication.compliance30,
|
||||
})),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// 9. Mood targets (if mood data exists)
|
||||
const moodEntries = await prisma.moodEntry.findMany({
|
||||
where: { userId },
|
||||
orderBy: { moodLoggedAt: "desc" },
|
||||
select: { score: true, moodLoggedAt: true },
|
||||
});
|
||||
|
||||
if (moodEntries.length >= 3) {
|
||||
const thirtyDaysAgoMood = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000);
|
||||
const recentMood = moodEntries.filter(
|
||||
(entry) => entry.moodLoggedAt >= thirtyDaysAgoMood,
|
||||
);
|
||||
const latestMoodScore = moodEntries[0]?.score ?? null;
|
||||
|
||||
const moodAvg30 =
|
||||
recentMood.length > 0
|
||||
? Math.round(
|
||||
(recentMood.reduce((sum, e) => sum + e.score, 0) /
|
||||
recentMood.length) *
|
||||
10,
|
||||
) / 10
|
||||
: null;
|
||||
|
||||
// Mood trend: compare first half to second half of last 30 days
|
||||
let moodTrend: "up" | "down" | "stable" | null = null;
|
||||
if (recentMood.length >= 4) {
|
||||
const sorted = [...recentMood].sort(
|
||||
(a, b) => a.moodLoggedAt.getTime() - b.moodLoggedAt.getTime(),
|
||||
);
|
||||
const mid = Math.floor(sorted.length / 2);
|
||||
const firstHalf = sorted.slice(0, mid);
|
||||
const secondHalf = sorted.slice(mid);
|
||||
const avgFirst =
|
||||
firstHalf.reduce((s, e) => s + e.score, 0) / firstHalf.length;
|
||||
const avgSecond =
|
||||
secondHalf.reduce((s, e) => s + e.score, 0) / secondHalf.length;
|
||||
const diff = avgSecond - avgFirst;
|
||||
if (diff > 0.2) moodTrend = "up";
|
||||
else if (diff < -0.2) moodTrend = "down";
|
||||
else moodTrend = "stable";
|
||||
}
|
||||
|
||||
const moodClassification =
|
||||
latestMoodScore != null
|
||||
? latestMoodScore >= 3.5
|
||||
? { category: "Gut", color: "#50fa7b" }
|
||||
: latestMoodScore >= 2
|
||||
? { category: "Moderat", color: "#f1fa8c" }
|
||||
: { category: "Niedrig", color: "#ff5555" }
|
||||
: null;
|
||||
|
||||
targets.push({
|
||||
type: "MOOD_SCORE",
|
||||
label: "Stimmung",
|
||||
current: latestMoodScore,
|
||||
average30: moodAvg30,
|
||||
trend: moodTrend,
|
||||
unit: "/ 5",
|
||||
range: { min: 3.5, max: 5 },
|
||||
classification: moodClassification,
|
||||
source: "moodLog",
|
||||
});
|
||||
|
||||
// Mood stability: standard deviation of recent scores (lower = more stable)
|
||||
if (recentMood.length >= 5) {
|
||||
const mean = moodAvg30 ?? latestMoodScore ?? 3;
|
||||
const variance =
|
||||
recentMood.reduce((sum, e) => sum + (e.score - mean) ** 2, 0) /
|
||||
recentMood.length;
|
||||
const stdDev = Math.round(Math.sqrt(variance) * 100) / 100;
|
||||
|
||||
const stabilityClassification =
|
||||
stdDev <= 0.5
|
||||
? { category: "Sehr stabil", color: "#50fa7b" }
|
||||
: stdDev <= 1.0
|
||||
? { category: "Stabil", color: "#f1fa8c" }
|
||||
: { category: "Schwankend", color: "#ff5555" };
|
||||
|
||||
targets.push({
|
||||
type: "MOOD_STABILITY",
|
||||
label: "Stimmungsstabilitaet",
|
||||
current: stdDev,
|
||||
average30: stdDev,
|
||||
trend: null,
|
||||
unit: "\u03C3",
|
||||
range: { min: 0, max: 0.5 },
|
||||
classification: stabilityClassification,
|
||||
source: "moodLog",
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
annotate({ action: { name: "insights.targets" }, meta: { targetCount: targets.length } });
|
||||
|
||||
return apiSuccess({
|
||||
targets,
|
||||
// Extra diastolic data for BP display
|
||||
bpDiastolic: {
|
||||
current: latestByType.BLOOD_PRESSURE_DIA ?? null,
|
||||
average30: avg30ByType.BLOOD_PRESSURE_DIA ?? null,
|
||||
range: bpRange ? { min: bpRange.diaLow, max: bpRange.diaHigh } : null,
|
||||
},
|
||||
profile: {
|
||||
heightCm,
|
||||
age,
|
||||
gender,
|
||||
},
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,28 @@
|
||||
import { NextRequest } from "next/server";
|
||||
import { apiSuccess } from "@/lib/api-response";
|
||||
import {
|
||||
generateWeightStatusForUser,
|
||||
resolveWeightStatusLocale,
|
||||
} from "@/lib/insights/weight-status";
|
||||
import { apiHandler, requireAuth } from "@/lib/api-handler";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export const GET = apiHandler(async (request: NextRequest) => {
|
||||
const { user } = await requireAuth();
|
||||
|
||||
const localeParam = request.nextUrl.searchParams.get("locale");
|
||||
const locale = resolveWeightStatusLocale(
|
||||
localeParam ?? user.locale ?? "de",
|
||||
);
|
||||
|
||||
const result = await generateWeightStatusForUser(user.id, {
|
||||
locale,
|
||||
force: false,
|
||||
});
|
||||
|
||||
annotate({ action: { name: "insights.weight-status" } });
|
||||
|
||||
return apiSuccess(result);
|
||||
});
|
||||
@@ -0,0 +1,33 @@
|
||||
import { prisma } from "@/lib/db";
|
||||
import { apiHandler, requireAuth } from "@/lib/api-handler";
|
||||
import { apiSuccess } from "@/lib/api-response";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export const GET = apiHandler(async () => {
|
||||
const { user } = await requireAuth();
|
||||
annotate({ action: { name: "moodlog.status" } });
|
||||
|
||||
const dbUser = await prisma.user.findUnique({
|
||||
where: { id: user.id },
|
||||
select: {
|
||||
moodLogUrlEncrypted: true,
|
||||
moodLogEnabled: true,
|
||||
moodLogLastSyncedAt: true,
|
||||
moodLogWebhookSecret: true,
|
||||
},
|
||||
});
|
||||
|
||||
const entryCount = await prisma.moodEntry.count({
|
||||
where: { userId: user.id },
|
||||
});
|
||||
|
||||
return apiSuccess({
|
||||
configured: Boolean(dbUser?.moodLogUrlEncrypted),
|
||||
enabled: dbUser?.moodLogEnabled ?? false,
|
||||
lastSyncedAt: dbUser?.moodLogLastSyncedAt ?? null,
|
||||
entryCount,
|
||||
webhookSecret: dbUser?.moodLogWebhookSecret ?? null,
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,35 @@
|
||||
import { NextRequest } from "next/server";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { apiHandler, requireAuth } from "@/lib/api-handler";
|
||||
import { apiSuccess, apiError } from "@/lib/api-response";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
import { syncMoodLogEntries } from "@/lib/moodlog/sync";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export const POST = apiHandler(async (request: NextRequest) => {
|
||||
const { user } = await requireAuth();
|
||||
annotate({ action: { name: "moodlog.sync" } });
|
||||
|
||||
// Check global toggle
|
||||
const appSettings = await prisma.appSettings.findUnique({
|
||||
where: { id: "singleton" },
|
||||
select: { moodLogGlobal: true },
|
||||
});
|
||||
if (appSettings && !appSettings.moodLogGlobal) {
|
||||
return apiError("moodLog-Integration ist deaktiviert", 403);
|
||||
}
|
||||
|
||||
let fullSync = false;
|
||||
try {
|
||||
const body = await request.json();
|
||||
fullSync = body?.fullSync === true;
|
||||
} catch {
|
||||
// No body or invalid JSON — use defaults
|
||||
}
|
||||
|
||||
const imported = await syncMoodLogEntries(user.id, {
|
||||
fullSync,
|
||||
});
|
||||
return apiSuccess({ imported });
|
||||
});
|
||||
@@ -0,0 +1,128 @@
|
||||
import { NextRequest } from "next/server";
|
||||
import { timingSafeEqual } from "node:crypto";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { apiError } from "@/lib/api-response";
|
||||
import { checkRateLimit } from "@/lib/rate-limit";
|
||||
import { getClientIp } from "@/lib/api-response";
|
||||
import { moodLogWebhookPayloadSchema } from "@/lib/validations/moodlog";
|
||||
import { apiHandler } from "@/lib/api-handler";
|
||||
import { annotate, getEvent } from "@/lib/logging/context";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export const POST = apiHandler(async (request: NextRequest) => {
|
||||
annotate({ action: { name: "moodlog.webhook" } });
|
||||
|
||||
// 1. Rate limit (30/min per IP)
|
||||
const ip = getClientIp(request) ?? "unknown";
|
||||
const rl = await checkRateLimit(`moodlog-webhook:${ip}`, 30, 60_000);
|
||||
if (!rl.allowed) {
|
||||
return apiError("Rate limit exceeded", 429);
|
||||
}
|
||||
|
||||
// 2. Check global toggle
|
||||
const appSettings = await prisma.appSettings.findUnique({
|
||||
where: { id: "singleton" },
|
||||
select: { moodLogGlobal: true },
|
||||
});
|
||||
if (appSettings && !appSettings.moodLogGlobal) {
|
||||
return apiError("moodLog integration is disabled", 403);
|
||||
}
|
||||
|
||||
// 3. Get webhook secret from header
|
||||
const webhookSecret = request.headers.get("x-webhook-secret");
|
||||
if (!webhookSecret) {
|
||||
return apiError("Missing X-Webhook-Secret header", 401);
|
||||
}
|
||||
|
||||
// 4. Find all enabled users with webhook secrets and compare timing-safe
|
||||
const candidates = await prisma.user.findMany({
|
||||
where: {
|
||||
moodLogEnabled: true,
|
||||
moodLogWebhookSecret: { not: null },
|
||||
},
|
||||
select: { id: true, moodLogWebhookSecret: true },
|
||||
});
|
||||
|
||||
const receivedBuf = Buffer.from(webhookSecret, "utf8");
|
||||
const user = candidates.find((c) => {
|
||||
if (!c.moodLogWebhookSecret) return false;
|
||||
const expectedBuf = Buffer.from(c.moodLogWebhookSecret, "utf8");
|
||||
if (expectedBuf.length !== receivedBuf.length) return false;
|
||||
return timingSafeEqual(expectedBuf, receivedBuf);
|
||||
});
|
||||
|
||||
if (!user) {
|
||||
return apiError("Invalid webhook secret", 401);
|
||||
}
|
||||
|
||||
getEvent()?.setAuth({ user_id: user.id, auth_method: "webhook_secret" });
|
||||
|
||||
// 5. Parse body
|
||||
let body: Record<string, unknown>;
|
||||
try {
|
||||
body = await request.json();
|
||||
} catch {
|
||||
return apiError("Invalid JSON", 400);
|
||||
}
|
||||
|
||||
// Handle test pings from moodLog's "Test senden" button
|
||||
if (body.event === "webhook.test") {
|
||||
annotate({ meta: { webhook_event: "webhook.test" } });
|
||||
return new Response(null, { status: 200 });
|
||||
}
|
||||
|
||||
const parsed = moodLogWebhookPayloadSchema.safeParse(body);
|
||||
if (!parsed.success) {
|
||||
return apiError("Invalid payload", 400);
|
||||
}
|
||||
|
||||
const { event, entry } = parsed.data;
|
||||
annotate({ meta: { webhook_event: event } });
|
||||
|
||||
// 5. Process event (non-blocking — fire and forget with error logging)
|
||||
const moodLoggedAt = new Date(entry.time);
|
||||
|
||||
try {
|
||||
if (event === "mood.deleted") {
|
||||
await prisma.moodEntry.deleteMany({
|
||||
where: {
|
||||
userId: user.id,
|
||||
date: entry.date,
|
||||
moodLoggedAt,
|
||||
},
|
||||
});
|
||||
} else {
|
||||
// mood.created or mood.updated
|
||||
await prisma.moodEntry.upsert({
|
||||
where: {
|
||||
userId_date_moodLoggedAt: {
|
||||
userId: user.id,
|
||||
date: entry.date,
|
||||
moodLoggedAt,
|
||||
},
|
||||
},
|
||||
update: {
|
||||
mood: entry.mood,
|
||||
score: entry.score,
|
||||
tags: entry.tags ? JSON.stringify(entry.tags) : null,
|
||||
source: "MOODLOG",
|
||||
},
|
||||
create: {
|
||||
userId: user.id,
|
||||
date: entry.date,
|
||||
mood: entry.mood,
|
||||
score: entry.score,
|
||||
tags: entry.tags ? JSON.stringify(entry.tags) : null,
|
||||
source: "MOODLOG",
|
||||
moodLoggedAt,
|
||||
},
|
||||
});
|
||||
}
|
||||
} catch (err) {
|
||||
getEvent()?.addWarning("DB operation failed: " + err);
|
||||
}
|
||||
|
||||
// 6. Return 200 immediately
|
||||
return new Response(null, { status: 200 });
|
||||
});
|
||||
@@ -0,0 +1,113 @@
|
||||
import { prisma } from "@/lib/db";
|
||||
import { apiHandler, requireAuth } from "@/lib/api-handler";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
import { auditLog } from "@/lib/auth/audit";
|
||||
import { apiSuccess, apiError, getClientIp, safeJson } from "@/lib/api-response";
|
||||
import { updateMeasurementSchema } from "@/lib/validations/measurement";
|
||||
import { NextRequest } from "next/server";
|
||||
|
||||
type RouteParams = { params: Promise<{ id: string }> };
|
||||
|
||||
export const GET = apiHandler(async (_request: NextRequest, { params }: RouteParams) => {
|
||||
const { user } = await requireAuth();
|
||||
|
||||
const { id } = await params;
|
||||
|
||||
const measurement = await prisma.measurement.findUnique({
|
||||
where: { id },
|
||||
});
|
||||
|
||||
if (!measurement || measurement.userId !== user.id) {
|
||||
return apiError("Messwert nicht gefunden", 404);
|
||||
}
|
||||
|
||||
annotate({
|
||||
action: {
|
||||
name: "measurement.get",
|
||||
entity_type: "measurement",
|
||||
entity_id: id,
|
||||
},
|
||||
});
|
||||
|
||||
return apiSuccess(measurement);
|
||||
});
|
||||
|
||||
export const PUT = apiHandler(async (request: NextRequest, { params }: RouteParams) => {
|
||||
const { user } = await requireAuth();
|
||||
|
||||
const { id } = await params;
|
||||
|
||||
const existing = await prisma.measurement.findUnique({
|
||||
where: { id },
|
||||
});
|
||||
|
||||
if (!existing || existing.userId !== user.id) {
|
||||
return apiError("Messwert nicht gefunden", 404);
|
||||
}
|
||||
|
||||
const { data: body, error: jsonError } = await safeJson(request);
|
||||
|
||||
if (jsonError) return jsonError;
|
||||
const parsed = updateMeasurementSchema.safeParse(body);
|
||||
if (!parsed.success) {
|
||||
return apiError(parsed.error.issues[0].message, 422);
|
||||
}
|
||||
|
||||
const data = parsed.data;
|
||||
const measurement = await prisma.measurement.update({
|
||||
where: { id },
|
||||
data: {
|
||||
...(data.value !== undefined && { value: data.value }),
|
||||
...(data.measuredAt !== undefined && { measuredAt: data.measuredAt }),
|
||||
...(data.notes !== undefined && { notes: data.notes }),
|
||||
},
|
||||
});
|
||||
|
||||
await auditLog("measurement.update", {
|
||||
userId: user.id,
|
||||
ipAddress: getClientIp(request),
|
||||
details: { measurementId: id },
|
||||
});
|
||||
|
||||
annotate({
|
||||
action: {
|
||||
name: "measurement.update",
|
||||
entity_type: "measurement",
|
||||
entity_id: id,
|
||||
},
|
||||
});
|
||||
|
||||
return apiSuccess(measurement);
|
||||
});
|
||||
|
||||
export const DELETE = apiHandler(async (request: NextRequest, { params }: RouteParams) => {
|
||||
const { user } = await requireAuth();
|
||||
|
||||
const { id } = await params;
|
||||
|
||||
const existing = await prisma.measurement.findUnique({
|
||||
where: { id },
|
||||
});
|
||||
|
||||
if (!existing || existing.userId !== user.id) {
|
||||
return apiError("Messwert nicht gefunden", 404);
|
||||
}
|
||||
|
||||
await prisma.measurement.delete({ where: { id } });
|
||||
|
||||
await auditLog("measurement.delete", {
|
||||
userId: user.id,
|
||||
ipAddress: getClientIp(request),
|
||||
details: { measurementId: id, type: existing.type },
|
||||
});
|
||||
|
||||
annotate({
|
||||
action: {
|
||||
name: "measurement.delete",
|
||||
entity_type: "measurement",
|
||||
entity_id: id,
|
||||
},
|
||||
});
|
||||
|
||||
return apiSuccess({ deleted: true });
|
||||
});
|
||||
@@ -0,0 +1,157 @@
|
||||
import { prisma } from "@/lib/db";
|
||||
import { apiHandler, requireAuth } from "@/lib/api-handler";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
import { auditLog } from "@/lib/auth/audit";
|
||||
import { apiSuccess, apiError, getClientIp, safeJson } from "@/lib/api-response";
|
||||
import {
|
||||
createMeasurementSchema,
|
||||
createBatchMeasurementSchema,
|
||||
listMeasurementsSchema,
|
||||
getUnitForType,
|
||||
} from "@/lib/validations/measurement";
|
||||
import { NextRequest } from "next/server";
|
||||
import type {
|
||||
MeasurementType,
|
||||
MeasurementSource,
|
||||
} from "@/generated/prisma/client";
|
||||
import { Prisma } from "@/generated/prisma/client";
|
||||
|
||||
export const GET = apiHandler(async (request: NextRequest) => {
|
||||
const { user } = await requireAuth();
|
||||
|
||||
const params = Object.fromEntries(request.nextUrl.searchParams);
|
||||
const parsed = listMeasurementsSchema.safeParse(params);
|
||||
if (!parsed.success) {
|
||||
return apiError(parsed.error.issues[0].message, 422);
|
||||
}
|
||||
|
||||
const { type, from, to, limit, offset, sortBy, sortDir } = parsed.data;
|
||||
|
||||
const where = {
|
||||
userId: user.id,
|
||||
...(type && { type: type as MeasurementType }),
|
||||
...(from || to
|
||||
? {
|
||||
measuredAt: {
|
||||
...(from && { gte: from }),
|
||||
...(to && { lte: to }),
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
};
|
||||
|
||||
const [measurements, total] = await Promise.all([
|
||||
prisma.measurement.findMany({
|
||||
where,
|
||||
orderBy: { [sortBy]: sortDir },
|
||||
take: limit,
|
||||
skip: offset,
|
||||
}),
|
||||
prisma.measurement.count({ where }),
|
||||
]);
|
||||
|
||||
annotate({ action: { name: "measurement.list" }, meta: { total, type } });
|
||||
|
||||
return apiSuccess({
|
||||
measurements,
|
||||
meta: { total, limit, offset },
|
||||
});
|
||||
});
|
||||
|
||||
export const POST = apiHandler(async (request: NextRequest) => {
|
||||
const { user } = await requireAuth();
|
||||
|
||||
const { data: body, error: jsonError } = await safeJson(request);
|
||||
|
||||
if (jsonError) return jsonError;
|
||||
|
||||
// Batch mode (array of measurements, e.g. combined BP + Pulse)
|
||||
if (Array.isArray(body)) {
|
||||
const parsed = createBatchMeasurementSchema.safeParse({
|
||||
measurements: body,
|
||||
});
|
||||
if (!parsed.success) {
|
||||
return apiError(parsed.error.issues[0].message, 422);
|
||||
}
|
||||
|
||||
const results = await prisma.$transaction(
|
||||
parsed.data.measurements.map((m) =>
|
||||
prisma.measurement.create({
|
||||
data: {
|
||||
userId: user.id,
|
||||
type: m.type as MeasurementType,
|
||||
value: m.value,
|
||||
unit: getUnitForType(m.type),
|
||||
source: (m.source ?? "MANUAL") as MeasurementSource,
|
||||
measuredAt: m.measuredAt,
|
||||
notes: m.notes ?? null,
|
||||
},
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
await auditLog("measurement.create.batch", {
|
||||
userId: user.id,
|
||||
ipAddress: getClientIp(request),
|
||||
details: {
|
||||
count: results.length,
|
||||
types: parsed.data.measurements.map((m) => m.type),
|
||||
},
|
||||
});
|
||||
|
||||
annotate({
|
||||
action: { name: "measurement.create.batch" },
|
||||
meta: {
|
||||
count: results.length,
|
||||
types: parsed.data.measurements.map((m) => m.type),
|
||||
},
|
||||
});
|
||||
|
||||
return apiSuccess(results, 201);
|
||||
}
|
||||
|
||||
// Single mode (existing behavior)
|
||||
const parsed = createMeasurementSchema.safeParse(body);
|
||||
if (!parsed.success) {
|
||||
return apiError(parsed.error.issues[0].message, 422);
|
||||
}
|
||||
|
||||
const { type, value, measuredAt, notes, source } = parsed.data;
|
||||
|
||||
// Handle unique constraint violation
|
||||
let measurement;
|
||||
try {
|
||||
measurement = await prisma.measurement.create({
|
||||
data: {
|
||||
userId: user.id,
|
||||
type: type as MeasurementType,
|
||||
value,
|
||||
unit: getUnitForType(type),
|
||||
source: (source ?? "MANUAL") as MeasurementSource,
|
||||
measuredAt,
|
||||
notes: notes ?? null,
|
||||
},
|
||||
});
|
||||
} catch (err) {
|
||||
if (err instanceof Prisma.PrismaClientKnownRequestError && err.code === "P2002") {
|
||||
return apiError("Ein Messwert mit diesen Daten existiert bereits", 409);
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
|
||||
await auditLog("measurement.create", {
|
||||
userId: user.id,
|
||||
ipAddress: getClientIp(request),
|
||||
details: { type, measurementId: measurement.id },
|
||||
});
|
||||
|
||||
annotate({
|
||||
action: {
|
||||
name: "measurement.create",
|
||||
entity_type: "measurement",
|
||||
entity_id: measurement.id,
|
||||
},
|
||||
});
|
||||
|
||||
return apiSuccess(measurement, 201);
|
||||
});
|
||||
@@ -0,0 +1,177 @@
|
||||
import { randomBytes } from "node:crypto";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { apiHandler, requireAuth } from "@/lib/api-handler";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
import { auditLog } from "@/lib/auth/audit";
|
||||
import { hashToken } from "@/lib/auth/hmac";
|
||||
import { apiSuccess, apiError, getClientIp } from "@/lib/api-response";
|
||||
import { isApiGloballyEnabled } from "@/lib/app-settings";
|
||||
import { NextRequest } from "next/server";
|
||||
|
||||
type RouteParams = { params: Promise<{ id: string }> };
|
||||
|
||||
function medicationScope(medicationId: string): string {
|
||||
return `medication:${medicationId}:ingest`;
|
||||
}
|
||||
|
||||
export const GET = apiHandler(async (_request: NextRequest, { params }: RouteParams) => {
|
||||
const { user } = await requireAuth();
|
||||
if (!(await isApiGloballyEnabled())) {
|
||||
return apiError("API ist global deaktiviert", 403);
|
||||
}
|
||||
|
||||
const { id } = await params;
|
||||
const medication = await prisma.medication.findUnique({ where: { id } });
|
||||
if (!medication || medication.userId !== user.id) {
|
||||
return apiError("Medikament nicht gefunden", 404);
|
||||
}
|
||||
|
||||
const scope = medicationScope(id);
|
||||
const now = new Date();
|
||||
|
||||
const activeTokenCount = await prisma.apiToken.count({
|
||||
where: {
|
||||
userId: user.id,
|
||||
revoked: false,
|
||||
permissions: { has: scope },
|
||||
OR: [{ expiresAt: null }, { expiresAt: { gt: now } }],
|
||||
},
|
||||
});
|
||||
|
||||
annotate({
|
||||
action: {
|
||||
name: "medication.api_endpoint.get",
|
||||
entity_type: "medication",
|
||||
entity_id: id,
|
||||
},
|
||||
meta: { active_token_count: activeTokenCount },
|
||||
});
|
||||
|
||||
return apiSuccess({
|
||||
enabled: activeTokenCount > 0,
|
||||
activeTokenCount,
|
||||
});
|
||||
});
|
||||
|
||||
export const PUT = apiHandler(async (request: NextRequest, { params }: RouteParams) => {
|
||||
const { user } = await requireAuth();
|
||||
if (!(await isApiGloballyEnabled())) {
|
||||
return apiError("API ist global deaktiviert", 403);
|
||||
}
|
||||
|
||||
const { id } = await params;
|
||||
const medication = await prisma.medication.findUnique({ where: { id } });
|
||||
if (!medication || medication.userId !== user.id) {
|
||||
return apiError("Medikament nicht gefunden", 404);
|
||||
}
|
||||
|
||||
let enabled = false;
|
||||
try {
|
||||
const body = await request.json();
|
||||
enabled = body?.enabled === true;
|
||||
} catch {
|
||||
return apiError("Ungültige Anfrage", 422);
|
||||
}
|
||||
|
||||
const scope = medicationScope(id);
|
||||
|
||||
if (enabled) {
|
||||
const existing = await prisma.apiToken.count({
|
||||
where: {
|
||||
userId: user.id,
|
||||
revoked: false,
|
||||
permissions: { has: scope },
|
||||
OR: [{ expiresAt: null }, { expiresAt: { gt: new Date() } }],
|
||||
},
|
||||
});
|
||||
|
||||
if (existing > 0) {
|
||||
annotate({
|
||||
action: {
|
||||
name: "medication.api_endpoint.enable",
|
||||
entity_type: "medication",
|
||||
entity_id: id,
|
||||
},
|
||||
meta: { already_enabled: true, active_token_count: existing },
|
||||
});
|
||||
|
||||
return apiSuccess({
|
||||
enabled: true,
|
||||
activeTokenCount: existing,
|
||||
token: null,
|
||||
created: false,
|
||||
});
|
||||
}
|
||||
|
||||
const rawToken = `hlk_${randomBytes(32).toString("hex")}`;
|
||||
const tokenHashValue = hashToken(rawToken);
|
||||
|
||||
await prisma.apiToken.create({
|
||||
data: {
|
||||
userId: user.id,
|
||||
name: `API Endpoint: ${medication.name}`,
|
||||
tokenHash: tokenHashValue,
|
||||
permissions: ["medication:ingest", scope],
|
||||
expiresAt: null,
|
||||
},
|
||||
});
|
||||
|
||||
await auditLog("medication.api_endpoint.enable", {
|
||||
userId: user.id,
|
||||
ipAddress: getClientIp(request),
|
||||
details: { medicationId: id, medicationName: medication.name },
|
||||
});
|
||||
|
||||
annotate({
|
||||
action: {
|
||||
name: "medication.api_endpoint.enable",
|
||||
entity_type: "medication",
|
||||
entity_id: id,
|
||||
},
|
||||
meta: { created: true },
|
||||
});
|
||||
|
||||
return apiSuccess(
|
||||
{
|
||||
enabled: true,
|
||||
activeTokenCount: 1,
|
||||
token: rawToken,
|
||||
created: true,
|
||||
},
|
||||
201,
|
||||
);
|
||||
}
|
||||
|
||||
const revoked = await prisma.apiToken.updateMany({
|
||||
where: {
|
||||
userId: user.id,
|
||||
revoked: false,
|
||||
permissions: { has: scope },
|
||||
},
|
||||
data: { revoked: true },
|
||||
});
|
||||
|
||||
await auditLog("medication.api_endpoint.disable", {
|
||||
userId: user.id,
|
||||
ipAddress: getClientIp(request),
|
||||
details: {
|
||||
medicationId: id,
|
||||
medicationName: medication.name,
|
||||
revokedTokens: revoked.count,
|
||||
},
|
||||
});
|
||||
|
||||
annotate({
|
||||
action: {
|
||||
name: "medication.api_endpoint.disable",
|
||||
entity_type: "medication",
|
||||
entity_id: id,
|
||||
},
|
||||
meta: { revoked_token_count: revoked.count },
|
||||
});
|
||||
|
||||
return apiSuccess({
|
||||
enabled: false,
|
||||
revokedTokenCount: revoked.count,
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,133 @@
|
||||
import { prisma } from "@/lib/db";
|
||||
import { apiHandler, requireAuth } from "@/lib/api-handler";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
import { apiSuccess, apiError } from "@/lib/api-response";
|
||||
import {
|
||||
calculateCompliance,
|
||||
classifyIntakeTiming,
|
||||
} from "@/lib/analytics/compliance";
|
||||
import type { DailyComplianceEntry } from "@/lib/analytics/compliance";
|
||||
|
||||
type RouteParams = { params: Promise<{ id: string }> };
|
||||
|
||||
export const GET = apiHandler(async (_request: Request, { params }: RouteParams) => {
|
||||
const { user } = await requireAuth();
|
||||
|
||||
const { id } = await params;
|
||||
const medication = await prisma.medication.findUnique({
|
||||
where: { id },
|
||||
include: { schedules: true },
|
||||
});
|
||||
|
||||
if (!medication || medication.userId !== user.id) {
|
||||
return apiError("Medikament nicht gefunden", 404);
|
||||
}
|
||||
|
||||
const events = await prisma.medicationIntakeEvent.findMany({
|
||||
where: { medicationId: id, userId: user.id },
|
||||
orderBy: { scheduledFor: "desc" },
|
||||
});
|
||||
|
||||
const mapped = events.map((e) => ({
|
||||
takenAt: e.takenAt,
|
||||
skipped: e.skipped,
|
||||
scheduledFor: e.scheduledFor,
|
||||
}));
|
||||
|
||||
const createdAt = medication.createdAt;
|
||||
const compliance7 = calculateCompliance(
|
||||
mapped,
|
||||
medication.schedules,
|
||||
7,
|
||||
createdAt,
|
||||
);
|
||||
const compliance30 = calculateCompliance(
|
||||
mapped,
|
||||
medication.schedules,
|
||||
30,
|
||||
createdAt,
|
||||
);
|
||||
|
||||
// Build daily compliance map for heatmap/line chart (90 days)
|
||||
const now = new Date();
|
||||
const schedulesPerDay = medication.schedules.length;
|
||||
const dailyCompliance: Record<string, DailyComplianceEntry> = {};
|
||||
|
||||
for (let d = 0; d < 90; d++) {
|
||||
const dayStart = new Date(now.getTime() - (d + 1) * 24 * 60 * 60 * 1000);
|
||||
const dayEnd = new Date(now.getTime() - d * 24 * 60 * 60 * 1000);
|
||||
|
||||
// Skip days before medication was created
|
||||
if (dayEnd <= createdAt) continue;
|
||||
|
||||
const dateKey = dayStart.toISOString().slice(0, 10);
|
||||
|
||||
const dayEvents = mapped.filter(
|
||||
(e) => e.scheduledFor >= dayStart && e.scheduledFor < dayEnd,
|
||||
);
|
||||
|
||||
const takenEvents = dayEvents.filter(
|
||||
(e) => e.takenAt !== null && !e.skipped,
|
||||
);
|
||||
|
||||
// Classify timing for each taken event against the best-matching schedule
|
||||
let onTime = 0;
|
||||
let late = 0;
|
||||
let veryLate = 0;
|
||||
|
||||
for (const evt of takenEvents) {
|
||||
if (medication.schedules.length === 0) {
|
||||
// No schedule info: treat all taken as on_time
|
||||
onTime++;
|
||||
continue;
|
||||
}
|
||||
|
||||
// Match event to the closest schedule window by scheduledFor time
|
||||
const evtHour = evt.scheduledFor.getUTCHours();
|
||||
const evtMin = evt.scheduledFor.getUTCMinutes();
|
||||
|
||||
let bestSchedule = medication.schedules[0];
|
||||
let bestDist = Infinity;
|
||||
|
||||
for (const sched of medication.schedules) {
|
||||
const [sh, sm] = sched.windowStart.split(":").map(Number);
|
||||
const dist = Math.abs(evtHour * 60 + evtMin - (sh * 60 + sm));
|
||||
if (dist < bestDist) {
|
||||
bestDist = dist;
|
||||
bestSchedule = sched;
|
||||
}
|
||||
}
|
||||
|
||||
const timing = classifyIntakeTiming(
|
||||
evt.takenAt,
|
||||
bestSchedule.windowStart,
|
||||
bestSchedule.windowEnd,
|
||||
dayStart, // the scheduled date
|
||||
);
|
||||
|
||||
if (timing === "on_time") onTime++;
|
||||
else if (timing === "late") late++;
|
||||
else veryLate++;
|
||||
}
|
||||
|
||||
dailyCompliance[dateKey] = {
|
||||
expected: schedulesPerDay,
|
||||
taken: takenEvents.length,
|
||||
skipped: dayEvents.filter((e) => e.skipped).length,
|
||||
onTime,
|
||||
late,
|
||||
veryLate,
|
||||
};
|
||||
}
|
||||
|
||||
annotate({
|
||||
action: {
|
||||
name: "medication.compliance",
|
||||
entity_type: "medication",
|
||||
entity_id: id,
|
||||
},
|
||||
meta: { compliance7: compliance7.rate, compliance30: compliance30.rate },
|
||||
});
|
||||
|
||||
return apiSuccess({ compliance7, compliance30, dailyCompliance });
|
||||
});
|
||||
@@ -0,0 +1,102 @@
|
||||
import { prisma } from "@/lib/db";
|
||||
import { apiHandler, requireAuth } from "@/lib/api-handler";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
import { auditLog } from "@/lib/auth/audit";
|
||||
import { apiSuccess, apiError, getClientIp, safeJson } from "@/lib/api-response";
|
||||
import { updateIntakeEventSchema } from "@/lib/validations/medication";
|
||||
import { NextRequest } from "next/server";
|
||||
|
||||
type RouteParams = { params: Promise<{ id: string; eventId: string }> };
|
||||
|
||||
export const PUT = apiHandler(async (request: NextRequest, { params }: RouteParams) => {
|
||||
const { user } = await requireAuth();
|
||||
|
||||
const { id, eventId } = await params;
|
||||
|
||||
const event = await prisma.medicationIntakeEvent.findUnique({
|
||||
where: { id: eventId },
|
||||
});
|
||||
|
||||
if (
|
||||
!event ||
|
||||
event.userId !== user.id ||
|
||||
event.medicationId !== id
|
||||
) {
|
||||
return apiError("Einnahme nicht gefunden", 404);
|
||||
}
|
||||
|
||||
const { data: body, error: jsonError } = await safeJson(request);
|
||||
|
||||
if (jsonError) return jsonError;
|
||||
const parsed = updateIntakeEventSchema.safeParse(body);
|
||||
if (!parsed.success) {
|
||||
return apiError(parsed.error.issues[0].message, 422);
|
||||
}
|
||||
|
||||
const data = parsed.data;
|
||||
const updated = await prisma.medicationIntakeEvent.update({
|
||||
where: { id: eventId },
|
||||
data: {
|
||||
...(data.takenAt !== undefined && { takenAt: data.takenAt }),
|
||||
...(data.skipped !== undefined && { skipped: data.skipped }),
|
||||
...(data.scheduledFor !== undefined && {
|
||||
scheduledFor: data.scheduledFor,
|
||||
}),
|
||||
},
|
||||
});
|
||||
|
||||
await auditLog("medication.intake.update", {
|
||||
userId: user.id,
|
||||
ipAddress: getClientIp(request),
|
||||
details: { eventId, medicationId: id },
|
||||
});
|
||||
|
||||
annotate({
|
||||
action: {
|
||||
name: "medication.intake.update",
|
||||
entity_type: "intake_event",
|
||||
entity_id: eventId,
|
||||
},
|
||||
meta: { medication_id: id },
|
||||
});
|
||||
|
||||
return apiSuccess(updated);
|
||||
});
|
||||
|
||||
export const DELETE = apiHandler(async (request: NextRequest, { params }: RouteParams) => {
|
||||
const { user } = await requireAuth();
|
||||
|
||||
const { id, eventId } = await params;
|
||||
|
||||
const event = await prisma.medicationIntakeEvent.findUnique({
|
||||
where: { id: eventId },
|
||||
});
|
||||
|
||||
if (
|
||||
!event ||
|
||||
event.userId !== user.id ||
|
||||
event.medicationId !== id
|
||||
) {
|
||||
return apiError("Einnahme nicht gefunden", 404);
|
||||
}
|
||||
|
||||
await prisma.medicationIntakeEvent.delete({ where: { id: eventId } });
|
||||
|
||||
const ip = getClientIp(request) ?? "unknown";
|
||||
await auditLog("medication.intake.delete", {
|
||||
userId: user.id,
|
||||
ipAddress: ip,
|
||||
details: { eventId, medicationId: id },
|
||||
});
|
||||
|
||||
annotate({
|
||||
action: {
|
||||
name: "medication.intake.delete",
|
||||
entity_type: "intake_event",
|
||||
entity_id: eventId,
|
||||
},
|
||||
meta: { medication_id: id },
|
||||
});
|
||||
|
||||
return apiSuccess({ deleted: true });
|
||||
});
|
||||
@@ -0,0 +1,112 @@
|
||||
import { prisma } from "@/lib/db";
|
||||
import { apiHandler, requireAuth } from "@/lib/api-handler";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
import { auditLog } from "@/lib/auth/audit";
|
||||
import { apiSuccess, apiError, getClientIp, safeJson } from "@/lib/api-response";
|
||||
import { NextRequest } from "next/server";
|
||||
import { z } from "zod/v4";
|
||||
|
||||
const importEntrySchema = z.object({
|
||||
datum: z.string().regex(/^\d{4}-\d{2}-\d{2}$/),
|
||||
uhrzeit: z.string().regex(/^\d{2}:\d{2}:\d{2}$/),
|
||||
zaehler: z.union([z.number().int(), z.string()]).optional(),
|
||||
});
|
||||
|
||||
const importSchema = z.array(importEntrySchema).min(1).max(1000);
|
||||
|
||||
type RouteParams = { params: Promise<{ id: string }> };
|
||||
|
||||
export const POST = apiHandler(async (request: NextRequest, { params }: RouteParams) => {
|
||||
const { user } = await requireAuth();
|
||||
|
||||
const { id } = await params;
|
||||
const medication = await prisma.medication.findUnique({ where: { id } });
|
||||
if (!medication || medication.userId !== user.id) {
|
||||
return apiError("Medikament nicht gefunden", 404);
|
||||
}
|
||||
|
||||
const { data: body, error: jsonError } = await safeJson(request);
|
||||
|
||||
if (jsonError) return jsonError;
|
||||
|
||||
// Support both direct arrays and object-with-array payloads
|
||||
const payload = Array.isArray(body)
|
||||
? body
|
||||
: typeof body === "object" && body !== null
|
||||
? Object.values(body).find((value) => Array.isArray(value))
|
||||
: null;
|
||||
|
||||
const parsed = importSchema.safeParse(payload);
|
||||
if (!parsed.success) {
|
||||
return apiError(
|
||||
`Ungültiges Format: ${parsed.error.issues[0].message}`,
|
||||
422,
|
||||
);
|
||||
}
|
||||
|
||||
const entries = parsed.data;
|
||||
let imported = 0;
|
||||
let skippedDuplicates = 0;
|
||||
let skippedInvalid = 0;
|
||||
|
||||
for (const entry of entries) {
|
||||
// Parse as local datetime first; if invalid, fall back to CET offset.
|
||||
let takenAt = new Date(`${entry.datum}T${entry.uhrzeit}`);
|
||||
if (isNaN(takenAt.getTime())) {
|
||||
takenAt = new Date(`${entry.datum}T${entry.uhrzeit}+01:00`);
|
||||
}
|
||||
if (isNaN(takenAt.getTime())) {
|
||||
skippedInvalid++;
|
||||
continue;
|
||||
}
|
||||
|
||||
// Prefer explicit counter; otherwise use timestamp-based dedup key.
|
||||
const idempotencyKey = entry.zaehler
|
||||
? `import-${id}-${String(entry.zaehler)}`
|
||||
: `import-${id}-${takenAt.getTime()}`;
|
||||
|
||||
const existing = await prisma.medicationIntakeEvent.findUnique({
|
||||
where: { idempotencyKey },
|
||||
});
|
||||
if (existing) {
|
||||
skippedDuplicates++;
|
||||
continue;
|
||||
}
|
||||
|
||||
await prisma.medicationIntakeEvent.create({
|
||||
data: {
|
||||
userId: user.id,
|
||||
medicationId: id,
|
||||
scheduledFor: takenAt,
|
||||
takenAt,
|
||||
skipped: false,
|
||||
source: "IMPORT",
|
||||
idempotencyKey,
|
||||
},
|
||||
});
|
||||
imported++;
|
||||
}
|
||||
|
||||
await auditLog("medication.intake.import", {
|
||||
userId: user.id,
|
||||
ipAddress: getClientIp(request),
|
||||
details: {
|
||||
medicationId: id,
|
||||
imported,
|
||||
skippedDuplicates,
|
||||
skippedInvalid,
|
||||
total: entries.length,
|
||||
},
|
||||
});
|
||||
|
||||
annotate({
|
||||
action: {
|
||||
name: "medication.intake.import",
|
||||
entity_type: "medication",
|
||||
entity_id: id,
|
||||
},
|
||||
meta: { imported, skippedDuplicates, skippedInvalid, total: entries.length },
|
||||
});
|
||||
|
||||
return apiSuccess({ imported, skippedDuplicates, skippedInvalid }, 201);
|
||||
});
|
||||
@@ -0,0 +1,39 @@
|
||||
import { prisma } from "@/lib/db";
|
||||
import { apiHandler, requireAuth } from "@/lib/api-handler";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
import { auditLog } from "@/lib/auth/audit";
|
||||
import { apiSuccess, apiError, getClientIp } from "@/lib/api-response";
|
||||
import { NextRequest } from "next/server";
|
||||
|
||||
type RouteParams = { params: Promise<{ id: string }> };
|
||||
|
||||
export const DELETE = apiHandler(async (request: NextRequest, { params }: RouteParams) => {
|
||||
const { user } = await requireAuth();
|
||||
|
||||
const { id } = await params;
|
||||
const medication = await prisma.medication.findUnique({ where: { id } });
|
||||
if (!medication || medication.userId !== user.id) {
|
||||
return apiError("Medikament nicht gefunden", 404);
|
||||
}
|
||||
|
||||
const { count } = await prisma.medicationIntakeEvent.deleteMany({
|
||||
where: { medicationId: id, userId: user.id },
|
||||
});
|
||||
|
||||
await auditLog("medication.intake.purge", {
|
||||
userId: user.id,
|
||||
ipAddress: getClientIp(request),
|
||||
details: { medicationId: id, name: medication.name, deletedCount: count },
|
||||
});
|
||||
|
||||
annotate({
|
||||
action: {
|
||||
name: "medication.intake.purge",
|
||||
entity_type: "medication",
|
||||
entity_id: id,
|
||||
},
|
||||
meta: { purged_count: count },
|
||||
});
|
||||
|
||||
return apiSuccess({ purged: true, count });
|
||||
});
|
||||
@@ -0,0 +1,139 @@
|
||||
import { prisma } from "@/lib/db";
|
||||
import { apiHandler, requireAuth } from "@/lib/api-handler";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
import { auditLog } from "@/lib/auth/audit";
|
||||
import { apiSuccess, apiError, getClientIp, safeJson } from "@/lib/api-response";
|
||||
import {
|
||||
intakeSchema,
|
||||
listIntakeEventsSchema,
|
||||
} from "@/lib/validations/medication";
|
||||
import { NextRequest } from "next/server";
|
||||
|
||||
type RouteParams = { params: Promise<{ id: string }> };
|
||||
|
||||
export const POST = apiHandler(async (request: NextRequest, { params }: RouteParams) => {
|
||||
const { user } = await requireAuth();
|
||||
|
||||
const { id } = await params;
|
||||
const medication = await prisma.medication.findUnique({ where: { id } });
|
||||
if (!medication || medication.userId !== user.id) {
|
||||
return apiError("Medikament nicht gefunden", 404);
|
||||
}
|
||||
|
||||
const { data: body, error: jsonError } = await safeJson(request);
|
||||
|
||||
if (jsonError) return jsonError;
|
||||
const parsed = intakeSchema.safeParse({
|
||||
...(body as Record<string, unknown>),
|
||||
medicationId: id,
|
||||
});
|
||||
if (!parsed.success) {
|
||||
return apiError(parsed.error.issues[0].message, 422);
|
||||
}
|
||||
|
||||
const { scheduledFor, takenAt, skipped, idempotencyKey } = parsed.data;
|
||||
|
||||
// Idempotency check (explicit key or server-side dedup window)
|
||||
if (idempotencyKey) {
|
||||
const existing = await prisma.medicationIntakeEvent.findFirst({
|
||||
where: {
|
||||
idempotencyKey,
|
||||
userId: user.id,
|
||||
medicationId: id,
|
||||
},
|
||||
});
|
||||
if (existing) {
|
||||
return apiSuccess(existing);
|
||||
}
|
||||
} else {
|
||||
// Server-side dedup: prevent double-logging within 60 seconds
|
||||
const recentDuplicate = await prisma.medicationIntakeEvent.findFirst({
|
||||
where: {
|
||||
userId: user.id,
|
||||
medicationId: id,
|
||||
skipped,
|
||||
createdAt: { gte: new Date(Date.now() - 60_000) },
|
||||
},
|
||||
orderBy: { createdAt: "desc" },
|
||||
});
|
||||
if (recentDuplicate) {
|
||||
return apiSuccess(recentDuplicate);
|
||||
}
|
||||
}
|
||||
|
||||
const [event] = await prisma.$transaction([
|
||||
prisma.medicationIntakeEvent.create({
|
||||
data: {
|
||||
userId: user.id,
|
||||
medicationId: id,
|
||||
scheduledFor: scheduledFor ?? takenAt ?? new Date(),
|
||||
takenAt: skipped ? null : (takenAt ?? new Date()),
|
||||
skipped,
|
||||
source: "WEB",
|
||||
idempotencyKey: idempotencyKey ?? null,
|
||||
},
|
||||
}),
|
||||
// Reset snooze when medication is taken
|
||||
...(!skipped
|
||||
? [
|
||||
prisma.medication.update({
|
||||
where: { id },
|
||||
data: { snoozedUntil: null },
|
||||
}),
|
||||
]
|
||||
: []),
|
||||
]);
|
||||
|
||||
await auditLog("medication.intake", {
|
||||
userId: user.id,
|
||||
ipAddress: getClientIp(request),
|
||||
details: { medicationId: id, eventId: event.id, skipped },
|
||||
});
|
||||
|
||||
annotate({
|
||||
action: {
|
||||
name: "medication.intake",
|
||||
entity_type: "intake_event",
|
||||
entity_id: event.id,
|
||||
},
|
||||
meta: { medication_id: id, skipped },
|
||||
});
|
||||
|
||||
return apiSuccess(event, 201);
|
||||
});
|
||||
|
||||
export const GET = apiHandler(async (request: NextRequest, { params }: RouteParams) => {
|
||||
const { user } = await requireAuth();
|
||||
|
||||
const { id } = await params;
|
||||
const medication = await prisma.medication.findUnique({ where: { id } });
|
||||
if (!medication || medication.userId !== user.id) {
|
||||
return apiError("Medikament nicht gefunden", 404);
|
||||
}
|
||||
|
||||
const searchParams = Object.fromEntries(request.nextUrl.searchParams);
|
||||
const parsed = listIntakeEventsSchema.safeParse(searchParams);
|
||||
if (!parsed.success) {
|
||||
return apiError(parsed.error.issues[0].message, 422);
|
||||
}
|
||||
|
||||
const { limit, offset, sortBy, sortDir } = parsed.data;
|
||||
const where = { medicationId: id, userId: user.id };
|
||||
|
||||
const [events, total] = await Promise.all([
|
||||
prisma.medicationIntakeEvent.findMany({
|
||||
where,
|
||||
orderBy: { [sortBy]: sortDir },
|
||||
take: limit,
|
||||
skip: offset,
|
||||
}),
|
||||
prisma.medicationIntakeEvent.count({ where }),
|
||||
]);
|
||||
|
||||
annotate({
|
||||
action: { name: "medication.intake.list" },
|
||||
meta: { medication_id: id, total },
|
||||
});
|
||||
|
||||
return apiSuccess({ events, meta: { total, limit, offset } });
|
||||
});
|
||||
@@ -0,0 +1,114 @@
|
||||
import { prisma } from "@/lib/db";
|
||||
import { apiHandler, requireAuth } from "@/lib/api-handler";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
import { apiSuccess, apiError, safeJson } from "@/lib/api-response";
|
||||
import { phaseConfigSchema } from "@/lib/validations/phase-config";
|
||||
import { NextRequest } from "next/server";
|
||||
|
||||
type RouteParams = { params: Promise<{ id: string }> };
|
||||
|
||||
export const GET = apiHandler(async (_request: NextRequest, { params }: RouteParams) => {
|
||||
const { user } = await requireAuth();
|
||||
|
||||
const { id } = await params;
|
||||
const medication = await prisma.medication.findUnique({
|
||||
where: { id },
|
||||
select: { userId: true },
|
||||
});
|
||||
if (!medication || medication.userId !== user.id) {
|
||||
return apiError("Medikament nicht gefunden", 404);
|
||||
}
|
||||
|
||||
const config = await prisma.reminderPhaseConfig.findUnique({
|
||||
where: { medicationId: id },
|
||||
});
|
||||
|
||||
annotate({
|
||||
action: {
|
||||
name: "medication.phase_config.get",
|
||||
entity_type: "medication",
|
||||
entity_id: id,
|
||||
},
|
||||
});
|
||||
|
||||
// Return config or defaults
|
||||
return apiSuccess(
|
||||
config ?? {
|
||||
greenValue: 60,
|
||||
greenMode: "MINUTES",
|
||||
yellowValue: 30,
|
||||
yellowMode: "MINUTES",
|
||||
orangeValue: 0,
|
||||
orangeMode: "MINUTES",
|
||||
redValue: 240,
|
||||
redMode: "MINUTES",
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
export const PUT = apiHandler(async (request: NextRequest, { params }: RouteParams) => {
|
||||
const { user } = await requireAuth();
|
||||
|
||||
const { id } = await params;
|
||||
const medication = await prisma.medication.findUnique({
|
||||
where: { id },
|
||||
select: { userId: true },
|
||||
});
|
||||
if (!medication || medication.userId !== user.id) {
|
||||
return apiError("Medikament nicht gefunden", 404);
|
||||
}
|
||||
|
||||
const { data: body, error: jsonError } = await safeJson(request);
|
||||
|
||||
if (jsonError) return jsonError;
|
||||
const parsed = phaseConfigSchema.safeParse(body);
|
||||
if (!parsed.success) {
|
||||
return apiError("Ungültige Eingabe", 400);
|
||||
}
|
||||
|
||||
const config = await prisma.reminderPhaseConfig.upsert({
|
||||
where: { medicationId: id },
|
||||
create: {
|
||||
medicationId: id,
|
||||
...parsed.data,
|
||||
},
|
||||
update: parsed.data,
|
||||
});
|
||||
|
||||
annotate({
|
||||
action: {
|
||||
name: "medication.phase_config.update",
|
||||
entity_type: "medication",
|
||||
entity_id: id,
|
||||
},
|
||||
});
|
||||
|
||||
return apiSuccess(config);
|
||||
});
|
||||
|
||||
export const DELETE = apiHandler(async (_request: NextRequest, { params }: RouteParams) => {
|
||||
const { user } = await requireAuth();
|
||||
|
||||
const { id } = await params;
|
||||
const medication = await prisma.medication.findUnique({
|
||||
where: { id },
|
||||
select: { userId: true },
|
||||
});
|
||||
if (!medication || medication.userId !== user.id) {
|
||||
return apiError("Medikament nicht gefunden", 404);
|
||||
}
|
||||
|
||||
await prisma.reminderPhaseConfig.deleteMany({
|
||||
where: { medicationId: id },
|
||||
});
|
||||
|
||||
annotate({
|
||||
action: {
|
||||
name: "medication.phase_config.reset",
|
||||
entity_type: "medication",
|
||||
entity_id: id,
|
||||
},
|
||||
});
|
||||
|
||||
return apiSuccess({ reset: true });
|
||||
});
|
||||
@@ -0,0 +1,206 @@
|
||||
import { prisma } from "@/lib/db";
|
||||
import { apiHandler, requireAuth } from "@/lib/api-handler";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
import { auditLog } from "@/lib/auth/audit";
|
||||
import { apiSuccess, apiError, getClientIp, safeJson } from "@/lib/api-response";
|
||||
import { updateMedicationSchema } from "@/lib/validations/medication";
|
||||
import {
|
||||
deleteMedicationCategory,
|
||||
getMedicationCategories,
|
||||
setMedicationCategory,
|
||||
} from "@/lib/medication-category";
|
||||
import { serializeScheduleRecurrence } from "@/lib/medication-schedule";
|
||||
import { NextRequest } from "next/server";
|
||||
|
||||
type RouteParams = { params: Promise<{ id: string }> };
|
||||
|
||||
export const GET = apiHandler(async (_request: NextRequest, { params }: RouteParams) => {
|
||||
const { user } = await requireAuth();
|
||||
|
||||
const { id } = await params;
|
||||
const medication = await prisma.medication.findUnique({
|
||||
where: { id },
|
||||
include: { schedules: true },
|
||||
});
|
||||
|
||||
if (!medication || medication.userId !== user.id) {
|
||||
return apiError("Medikament nicht gefunden", 404);
|
||||
}
|
||||
|
||||
let category = "OTHER";
|
||||
try {
|
||||
const categories = await getMedicationCategories([id]);
|
||||
category = categories[id] ?? "OTHER";
|
||||
} catch {
|
||||
// Category enrichment is optional
|
||||
}
|
||||
|
||||
annotate({
|
||||
action: {
|
||||
name: "medication.get",
|
||||
entity_type: "medication",
|
||||
entity_id: id,
|
||||
},
|
||||
});
|
||||
|
||||
return apiSuccess({ ...medication, category });
|
||||
});
|
||||
|
||||
export const PUT = apiHandler(async (request: NextRequest, { params }: RouteParams) => {
|
||||
const { user } = await requireAuth();
|
||||
|
||||
const { id } = await params;
|
||||
const existing = await prisma.medication.findUnique({ where: { id } });
|
||||
if (!existing || existing.userId !== user.id) {
|
||||
return apiError("Medikament nicht gefunden", 404);
|
||||
}
|
||||
|
||||
const { data: body, error: jsonError } = await safeJson(request);
|
||||
|
||||
if (jsonError) return jsonError;
|
||||
const parsed = updateMedicationSchema.safeParse(body);
|
||||
if (!parsed.success) {
|
||||
return apiError(parsed.error.issues[0].message, 422);
|
||||
}
|
||||
|
||||
const { name, dose, category, active, notificationsEnabled, schedules } =
|
||||
parsed.data;
|
||||
|
||||
const pausedAtPatch =
|
||||
active === undefined
|
||||
? {}
|
||||
: active
|
||||
? { pausedAt: null as Date | null }
|
||||
: existing.active
|
||||
? { pausedAt: new Date() }
|
||||
: {};
|
||||
|
||||
// If schedules provided, replace all
|
||||
if (schedules) {
|
||||
await prisma.medicationSchedule.deleteMany({
|
||||
where: { medicationId: id },
|
||||
});
|
||||
}
|
||||
|
||||
const baseUpdateData = {
|
||||
...(name !== undefined && { name }),
|
||||
...(dose !== undefined && { dose }),
|
||||
...(active !== undefined && { active }),
|
||||
...(notificationsEnabled !== undefined && { notificationsEnabled }),
|
||||
...(schedules && {
|
||||
schedules: {
|
||||
create: schedules.map((s) => ({
|
||||
windowStart: s.windowStart,
|
||||
windowEnd: s.windowEnd,
|
||||
label: s.label ?? null,
|
||||
dose: s.dose ?? null,
|
||||
daysOfWeek: serializeScheduleRecurrence({
|
||||
daysOfWeek: s.daysOfWeek ?? [],
|
||||
intervalWeeks: s.intervalWeeks ?? 1,
|
||||
}),
|
||||
})),
|
||||
},
|
||||
}),
|
||||
};
|
||||
|
||||
const withoutNotifications = { ...baseUpdateData } as Record<
|
||||
string,
|
||||
unknown
|
||||
>;
|
||||
delete withoutNotifications.notificationsEnabled;
|
||||
const hasPausedAtPatch = Object.keys(pausedAtPatch).length > 0;
|
||||
const hasNotificationsPatch = notificationsEnabled !== undefined;
|
||||
|
||||
const updateCandidates: Array<Record<string, unknown>> = [
|
||||
{ ...baseUpdateData, ...pausedAtPatch },
|
||||
];
|
||||
if (hasPausedAtPatch) {
|
||||
updateCandidates.push(baseUpdateData);
|
||||
}
|
||||
if (hasNotificationsPatch) {
|
||||
updateCandidates.push({ ...withoutNotifications, ...pausedAtPatch });
|
||||
if (hasPausedAtPatch) {
|
||||
updateCandidates.push(withoutNotifications);
|
||||
}
|
||||
}
|
||||
|
||||
let medication;
|
||||
let lastUpdateErr: unknown;
|
||||
for (const candidate of updateCandidates) {
|
||||
try {
|
||||
medication = await prisma.medication.update({
|
||||
where: { id },
|
||||
data: candidate,
|
||||
include: { schedules: true },
|
||||
});
|
||||
break;
|
||||
} catch (updateErr) {
|
||||
lastUpdateErr = updateErr;
|
||||
}
|
||||
}
|
||||
if (!medication) throw lastUpdateErr;
|
||||
|
||||
const normalizedCategory =
|
||||
category !== undefined
|
||||
? await setMedicationCategory(id, category)
|
||||
: ((await getMedicationCategories([id]))[id] ?? "OTHER");
|
||||
|
||||
await auditLog("medication.update", {
|
||||
userId: user.id,
|
||||
ipAddress: getClientIp(request),
|
||||
details: { medicationId: id },
|
||||
});
|
||||
|
||||
annotate({
|
||||
action: {
|
||||
name: "medication.update",
|
||||
entity_type: "medication",
|
||||
entity_id: id,
|
||||
},
|
||||
});
|
||||
|
||||
return apiSuccess({
|
||||
...medication,
|
||||
category: normalizedCategory,
|
||||
});
|
||||
});
|
||||
|
||||
export const DELETE = apiHandler(async (request: NextRequest, { params }: RouteParams) => {
|
||||
const { user } = await requireAuth();
|
||||
|
||||
const { id } = await params;
|
||||
const existing = await prisma.medication.findUnique({ where: { id } });
|
||||
if (!existing || existing.userId !== user.id) {
|
||||
return apiError("Medikament nicht gefunden", 404);
|
||||
}
|
||||
|
||||
// Revoke API tokens scoped to this medication
|
||||
const medicationScope = `medication:${id}:ingest`;
|
||||
await prisma.apiToken.updateMany({
|
||||
where: {
|
||||
userId: user.id,
|
||||
revoked: false,
|
||||
permissions: { has: medicationScope },
|
||||
},
|
||||
data: { revoked: true },
|
||||
});
|
||||
|
||||
await deleteMedicationCategory(id);
|
||||
await prisma.medication.delete({ where: { id } });
|
||||
|
||||
await auditLog("medication.delete", {
|
||||
userId: user.id,
|
||||
ipAddress: getClientIp(request),
|
||||
details: { medicationId: id, name: existing.name },
|
||||
});
|
||||
|
||||
annotate({
|
||||
action: {
|
||||
name: "medication.delete",
|
||||
entity_type: "medication",
|
||||
entity_id: id,
|
||||
},
|
||||
});
|
||||
|
||||
return apiSuccess({ deleted: true });
|
||||
});
|
||||
@@ -0,0 +1,102 @@
|
||||
import { NextRequest } from "next/server";
|
||||
import { z } from "zod/v4";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { apiHandler, requireAuth } from "@/lib/api-handler";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
import { apiError, apiSuccess } from "@/lib/api-response";
|
||||
|
||||
const querySchema = z.object({
|
||||
from: z.iso
|
||||
.datetime({ offset: true })
|
||||
.transform((value) => new Date(value))
|
||||
.optional(),
|
||||
to: z.iso
|
||||
.datetime({ offset: true })
|
||||
.transform((value) => new Date(value))
|
||||
.optional(),
|
||||
});
|
||||
|
||||
function toBerlinDayKey(date: Date): string {
|
||||
return new Intl.DateTimeFormat("sv-SE", {
|
||||
timeZone: "Europe/Berlin",
|
||||
year: "numeric",
|
||||
month: "2-digit",
|
||||
day: "2-digit",
|
||||
}).format(date);
|
||||
}
|
||||
|
||||
interface DailySummary {
|
||||
date: string;
|
||||
total: number;
|
||||
medications: Record<string, number>;
|
||||
}
|
||||
|
||||
export const GET = apiHandler(async (request: NextRequest) => {
|
||||
const { user } = await requireAuth();
|
||||
|
||||
const parsed = querySchema.safeParse(
|
||||
Object.fromEntries(request.nextUrl.searchParams),
|
||||
);
|
||||
if (!parsed.success) {
|
||||
return apiError(parsed.error.issues[0].message, 422);
|
||||
}
|
||||
|
||||
const { from, to } = parsed.data;
|
||||
|
||||
const events = await prisma.medicationIntakeEvent.findMany({
|
||||
where: {
|
||||
userId: user.id,
|
||||
skipped: false,
|
||||
takenAt: {
|
||||
not: null,
|
||||
...(from && { gte: from }),
|
||||
...(to && { lte: to }),
|
||||
},
|
||||
},
|
||||
select: {
|
||||
takenAt: true,
|
||||
medication: {
|
||||
select: {
|
||||
name: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
orderBy: { takenAt: "asc" },
|
||||
});
|
||||
|
||||
const medicationNames = new Set<string>();
|
||||
const byDay = new Map<string, DailySummary>();
|
||||
|
||||
for (const event of events) {
|
||||
if (!event.takenAt) continue;
|
||||
|
||||
const medicationName = event.medication.name;
|
||||
const dayKey = toBerlinDayKey(event.takenAt);
|
||||
medicationNames.add(medicationName);
|
||||
|
||||
const existing = byDay.get(dayKey) ?? {
|
||||
date: dayKey,
|
||||
total: 0,
|
||||
medications: {},
|
||||
};
|
||||
|
||||
existing.total += 1;
|
||||
existing.medications[medicationName] =
|
||||
(existing.medications[medicationName] ?? 0) + 1;
|
||||
byDay.set(dayKey, existing);
|
||||
}
|
||||
|
||||
const points = [...byDay.values()].sort((a, b) =>
|
||||
a.date.localeCompare(b.date),
|
||||
);
|
||||
|
||||
annotate({
|
||||
action: { name: "medication.intake_summary" },
|
||||
meta: { point_count: points.length, medication_count: medicationNames.size },
|
||||
});
|
||||
|
||||
return apiSuccess({
|
||||
points,
|
||||
medications: [...medicationNames].sort((a, b) => a.localeCompare(b, "de")),
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,148 @@
|
||||
import { prisma } from "@/lib/db";
|
||||
import { apiHandler, requireAuth } from "@/lib/api-handler";
|
||||
import { annotate, getEvent } from "@/lib/logging/context";
|
||||
import { auditLog } from "@/lib/auth/audit";
|
||||
import { apiSuccess, apiError, getClientIp, safeJson } from "@/lib/api-response";
|
||||
import { createMedicationSchema } from "@/lib/validations/medication";
|
||||
import {
|
||||
getMedicationCategories,
|
||||
setMedicationCategory,
|
||||
} from "@/lib/medication-category";
|
||||
import { serializeScheduleRecurrence } from "@/lib/medication-schedule";
|
||||
import { getUserTodayBounds } from "@/lib/timezone";
|
||||
import { NextRequest } from "next/server";
|
||||
|
||||
export const GET = apiHandler(async () => {
|
||||
const { user } = await requireAuth();
|
||||
|
||||
// Compute today's UTC range for event counting
|
||||
const userTz = user.timezone || "Europe/Berlin";
|
||||
const { start: todayStartUtc, end: todayEndUtc } = getUserTodayBounds(
|
||||
new Date(),
|
||||
userTz,
|
||||
);
|
||||
|
||||
// Run all three queries in parallel
|
||||
const [medications, latestIntakes, todayEvents] = await Promise.all([
|
||||
prisma.medication.findMany({
|
||||
where: { userId: user.id },
|
||||
include: { schedules: true },
|
||||
orderBy: { createdAt: "desc" },
|
||||
}),
|
||||
prisma.medicationIntakeEvent.groupBy({
|
||||
by: ["medicationId"],
|
||||
where: {
|
||||
userId: user.id,
|
||||
skipped: false,
|
||||
takenAt: { not: null },
|
||||
},
|
||||
_max: { takenAt: true },
|
||||
}),
|
||||
prisma.medicationIntakeEvent.groupBy({
|
||||
by: ["medicationId"],
|
||||
where: {
|
||||
userId: user.id,
|
||||
scheduledFor: { gte: todayStartUtc, lte: todayEndUtc },
|
||||
},
|
||||
_count: { id: true },
|
||||
}),
|
||||
]);
|
||||
|
||||
const lastTakenAtByMedicationId = Object.fromEntries(
|
||||
latestIntakes.map((entry) => [
|
||||
entry.medicationId,
|
||||
entry._max.takenAt ? entry._max.takenAt.toISOString() : null,
|
||||
]),
|
||||
);
|
||||
const todayEventCountByMedId = Object.fromEntries(
|
||||
todayEvents.map(
|
||||
(entry: { medicationId: string; _count: { id: number } }) => [
|
||||
entry.medicationId,
|
||||
entry._count.id,
|
||||
],
|
||||
),
|
||||
);
|
||||
|
||||
let categoryMap: Record<string, string> = {};
|
||||
try {
|
||||
categoryMap = await getMedicationCategories(medications.map((m) => m.id));
|
||||
} catch (error) {
|
||||
getEvent()?.addWarning("Medication categories could not be loaded");
|
||||
}
|
||||
|
||||
annotate({
|
||||
action: { name: "medication.list" },
|
||||
meta: { count: medications.length },
|
||||
});
|
||||
|
||||
return apiSuccess(
|
||||
medications.map((m) => ({
|
||||
...m,
|
||||
category: categoryMap[m.id] ?? "OTHER",
|
||||
lastTakenAt: lastTakenAtByMedicationId[m.id] ?? null,
|
||||
todayEventCount: todayEventCountByMedId[m.id] ?? 0,
|
||||
})),
|
||||
);
|
||||
});
|
||||
|
||||
export const POST = apiHandler(async (request: NextRequest) => {
|
||||
const { user } = await requireAuth();
|
||||
|
||||
const { data: body, error: jsonError } = await safeJson(request);
|
||||
|
||||
if (jsonError) return jsonError;
|
||||
const parsed = createMedicationSchema.safeParse(body);
|
||||
if (!parsed.success) {
|
||||
return apiError(parsed.error.issues[0].message, 422);
|
||||
}
|
||||
|
||||
const { name, dose, category, schedules } = parsed.data;
|
||||
|
||||
const medication = await prisma.medication.create({
|
||||
data: {
|
||||
userId: user.id,
|
||||
name,
|
||||
dose,
|
||||
schedules: {
|
||||
create: schedules.map((s) => ({
|
||||
windowStart: s.windowStart,
|
||||
windowEnd: s.windowEnd,
|
||||
label: s.label ?? null,
|
||||
dose: s.dose ?? null,
|
||||
daysOfWeek: serializeScheduleRecurrence({
|
||||
daysOfWeek: s.daysOfWeek ?? [],
|
||||
intervalWeeks: s.intervalWeeks ?? 1,
|
||||
}),
|
||||
})),
|
||||
},
|
||||
},
|
||||
include: { schedules: true },
|
||||
});
|
||||
|
||||
const normalizedCategory = await setMedicationCategory(
|
||||
medication.id,
|
||||
category,
|
||||
);
|
||||
|
||||
await auditLog("medication.create", {
|
||||
userId: user.id,
|
||||
ipAddress: getClientIp(request),
|
||||
details: { medicationId: medication.id, name },
|
||||
});
|
||||
|
||||
annotate({
|
||||
action: {
|
||||
name: "medication.create",
|
||||
entity_type: "medication",
|
||||
entity_id: medication.id,
|
||||
},
|
||||
});
|
||||
|
||||
return apiSuccess(
|
||||
{
|
||||
...medication,
|
||||
category: normalizedCategory,
|
||||
},
|
||||
201,
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,53 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { checkRateLimit } from "@/lib/rate-limit";
|
||||
import { getClientIp } from "@/lib/api-response";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
import { apiHandler } from "@/lib/api-handler";
|
||||
|
||||
/**
|
||||
* CSP violation report endpoint.
|
||||
* Receives browser-reported Content-Security-Policy violations
|
||||
* and logs them as structured wide events for monitoring via Loki.
|
||||
*/
|
||||
export const POST = apiHandler(async (request: NextRequest) => {
|
||||
const ip = getClientIp(request);
|
||||
|
||||
// Rate limit to prevent abuse (50 reports per minute per IP)
|
||||
const rl = await checkRateLimit(`csp-report:${ip}`, 50, 60_000);
|
||||
if (!rl.allowed) {
|
||||
return new NextResponse(null, { status: 429 });
|
||||
}
|
||||
|
||||
let payload: Record<string, unknown> = {};
|
||||
try {
|
||||
const raw = await request.text();
|
||||
if (raw.length > 10_000) {
|
||||
return new NextResponse(null, { status: 413 });
|
||||
}
|
||||
payload = JSON.parse(raw) as Record<string, unknown>;
|
||||
} catch {
|
||||
return new NextResponse(null, { status: 400 });
|
||||
}
|
||||
|
||||
// Browsers send either { "csp-report": { ... } } or { ... } depending on report-uri vs report-to
|
||||
const report =
|
||||
(payload["csp-report"] as Record<string, unknown> | undefined) ?? payload;
|
||||
|
||||
annotate({
|
||||
action: { name: "csp.violation" },
|
||||
meta: {
|
||||
blocked_uri: String(report["blocked-uri"] ?? report["blockedURL"] ?? ""),
|
||||
violated_directive: String(
|
||||
report["violated-directive"] ?? report["effectiveDirective"] ?? "",
|
||||
),
|
||||
document_uri: String(
|
||||
report["document-uri"] ?? report["documentURL"] ?? "",
|
||||
),
|
||||
source_file: String(report["source-file"] ?? report["sourceFile"] ?? ""),
|
||||
line_number: report["line-number"] ?? report["lineNumber"] ?? null,
|
||||
disposition: String(report["disposition"] ?? ""),
|
||||
},
|
||||
});
|
||||
|
||||
return new NextResponse(null, { status: 204 });
|
||||
});
|
||||
@@ -0,0 +1,61 @@
|
||||
import { NextRequest } from "next/server";
|
||||
import { z } from "zod/v4";
|
||||
import { apiError, apiSuccess, getClientIp } from "@/lib/api-response";
|
||||
import { checkRateLimit } from "@/lib/rate-limit";
|
||||
import { getGlitchtipSettings } from "@/lib/monitoring-settings";
|
||||
import { sendGlitchtipEvent } from "@/lib/monitoring/glitchtip";
|
||||
import { apiHandler } from "@/lib/api-handler";
|
||||
import { annotate, getEvent } from "@/lib/logging/context";
|
||||
|
||||
const clientErrorSchema = z.object({
|
||||
message: z.string().min(1).max(2000),
|
||||
stack: z.string().max(20000).optional(),
|
||||
level: z.enum(["error", "warning", "info"]).optional(),
|
||||
type: z.string().max(120).optional(),
|
||||
url: z.string().max(2000).optional(),
|
||||
userAgent: z.string().max(1000).optional(),
|
||||
});
|
||||
|
||||
export const POST = apiHandler(async (request: NextRequest) => {
|
||||
annotate({ action: { name: "monitoring.glitchtip.report" } });
|
||||
|
||||
const ip = getClientIp(request);
|
||||
const rl = await checkRateLimit(`glitchtip:${ip}`, 20, 60 * 1000);
|
||||
if (!rl.allowed) return apiError("Rate limit exceeded", 429);
|
||||
|
||||
const settings = await getGlitchtipSettings();
|
||||
if (!settings.glitchtipEnabled || !settings.glitchtipDsn) {
|
||||
return apiSuccess({ skipped: true });
|
||||
}
|
||||
|
||||
let body: unknown;
|
||||
try {
|
||||
body = await request.json();
|
||||
} catch {
|
||||
return apiError("Ungültige JSON-Daten", 422);
|
||||
}
|
||||
|
||||
const parsed = clientErrorSchema.safeParse(body);
|
||||
if (!parsed.success) return apiError("Ungültige Fehlerdaten", 422);
|
||||
|
||||
const delivery = await sendGlitchtipEvent({
|
||||
dsn: settings.glitchtipDsn,
|
||||
input: {
|
||||
environment: settings.glitchtipEnvironment || "production",
|
||||
message: parsed.data.message,
|
||||
stack: parsed.data.stack,
|
||||
level: parsed.data.level ?? "error",
|
||||
type: parsed.data.type,
|
||||
url: parsed.data.url,
|
||||
userAgent: parsed.data.userAgent,
|
||||
sourceTag: "healthlog-client",
|
||||
},
|
||||
});
|
||||
|
||||
if (!delivery.ok) {
|
||||
getEvent()?.addWarning("Glitchtip event rejected: " + delivery.method + " " + delivery.status + " " + delivery.details);
|
||||
return apiError("Glitchtip konnte Fehler nicht annehmen", 502);
|
||||
}
|
||||
|
||||
return apiSuccess({ sent: true });
|
||||
});
|
||||
@@ -0,0 +1,17 @@
|
||||
import { apiHandler } from "@/lib/api-handler";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
import { apiSuccess } from "@/lib/api-response";
|
||||
import { getPublicMonitoringSettings } from "@/lib/monitoring-settings";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export const GET = apiHandler(async () => {
|
||||
annotate({ action: { name: "monitoring.settings.get" } });
|
||||
|
||||
const settings = await getPublicMonitoringSettings();
|
||||
return apiSuccess({
|
||||
umamiEnabled: settings.umamiEnabled,
|
||||
umamiWebsiteId: settings.umamiWebsiteId,
|
||||
glitchtipEnabled: settings.glitchtipEnabled,
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,49 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { apiHandler } from "@/lib/api-handler";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
import { getPublicMonitoringSettings } from "@/lib/monitoring-settings";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
const NOOP_SCRIPT = "/* umami disabled */";
|
||||
|
||||
export const GET = apiHandler(async () => {
|
||||
annotate({ action: { name: "monitoring.umami-script" } });
|
||||
|
||||
const settings = await getPublicMonitoringSettings();
|
||||
if (
|
||||
!settings.umamiEnabled ||
|
||||
!settings.umamiScriptUrl ||
|
||||
!settings.umamiWebsiteId
|
||||
) {
|
||||
return new NextResponse(NOOP_SCRIPT, {
|
||||
status: 200,
|
||||
headers: {
|
||||
"Content-Type": "application/javascript; charset=utf-8",
|
||||
"Cache-Control": "public, max-age=60",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const response = await fetch(settings.umamiScriptUrl, {
|
||||
next: { revalidate: 3600 },
|
||||
});
|
||||
if (!response.ok) {
|
||||
return new NextResponse(NOOP_SCRIPT, {
|
||||
status: 200,
|
||||
headers: {
|
||||
"Content-Type": "application/javascript; charset=utf-8",
|
||||
"Cache-Control": "public, max-age=60",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const script = await response.text();
|
||||
return new NextResponse(script, {
|
||||
status: 200,
|
||||
headers: {
|
||||
"Content-Type": "application/javascript; charset=utf-8",
|
||||
"Cache-Control": "public, max-age=1800",
|
||||
},
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,117 @@
|
||||
import { prisma } from "@/lib/db";
|
||||
import { auditLog } from "@/lib/auth/audit";
|
||||
import { apiSuccess, apiError, getClientIp, safeJson } from "@/lib/api-response";
|
||||
import {
|
||||
updateMoodEntrySchema,
|
||||
getScoreForMood,
|
||||
} from "@/lib/validations/moodlog";
|
||||
import { NextRequest } from "next/server";
|
||||
import { apiHandler, requireAuth } from "@/lib/api-handler";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
|
||||
type RouteParams = { params: Promise<{ id: string }> };
|
||||
|
||||
function toBerlinDate(date: Date): string {
|
||||
return new Intl.DateTimeFormat("sv-SE", {
|
||||
timeZone: "Europe/Berlin",
|
||||
}).format(date);
|
||||
}
|
||||
|
||||
function parseTags(tags: string | null): string[] {
|
||||
if (!tags) return [];
|
||||
try {
|
||||
return JSON.parse(tags) as string[];
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
export const GET = apiHandler(async (_request: NextRequest, { params }: RouteParams) => {
|
||||
const { user } = await requireAuth();
|
||||
|
||||
const { id } = await params;
|
||||
|
||||
const entry = await prisma.moodEntry.findUnique({ where: { id } });
|
||||
|
||||
if (!entry || entry.userId !== user.id) {
|
||||
return apiError("Stimmungseintrag nicht gefunden", 404);
|
||||
}
|
||||
|
||||
annotate({ action: { name: "mood-entries.get" }, meta: { moodEntryId: id } });
|
||||
|
||||
return apiSuccess({ ...entry, tags: parseTags(entry.tags) });
|
||||
});
|
||||
|
||||
export const PUT = apiHandler(async (request: NextRequest, { params }: RouteParams) => {
|
||||
const { user } = await requireAuth();
|
||||
|
||||
const { id } = await params;
|
||||
|
||||
const existing = await prisma.moodEntry.findUnique({ where: { id } });
|
||||
|
||||
if (!existing || existing.userId !== user.id) {
|
||||
return apiError("Stimmungseintrag nicht gefunden", 404);
|
||||
}
|
||||
|
||||
const { data: body, error: jsonError } = await safeJson(request);
|
||||
|
||||
if (jsonError) return jsonError;
|
||||
const parsed = updateMoodEntrySchema.safeParse(body);
|
||||
if (!parsed.success) {
|
||||
return apiError(parsed.error.issues[0].message, 422);
|
||||
}
|
||||
|
||||
const data = parsed.data;
|
||||
|
||||
const updateData: Record<string, unknown> = {};
|
||||
if (data.mood !== undefined) {
|
||||
updateData.mood = data.mood;
|
||||
updateData.score = getScoreForMood(data.mood);
|
||||
}
|
||||
if (data.moodLoggedAt !== undefined) {
|
||||
updateData.moodLoggedAt = data.moodLoggedAt;
|
||||
updateData.date = toBerlinDate(data.moodLoggedAt);
|
||||
}
|
||||
if (data.tags !== undefined) {
|
||||
updateData.tags = data.tags ? JSON.stringify(data.tags) : null;
|
||||
}
|
||||
|
||||
const entry = await prisma.moodEntry.update({
|
||||
where: { id },
|
||||
data: updateData,
|
||||
});
|
||||
|
||||
await auditLog("moodEntry.update", {
|
||||
userId: user.id,
|
||||
ipAddress: getClientIp(request),
|
||||
details: { moodEntryId: id },
|
||||
});
|
||||
|
||||
annotate({ action: { name: "mood-entries.update" }, meta: { moodEntryId: id } });
|
||||
|
||||
return apiSuccess({ ...entry, tags: parseTags(entry.tags) });
|
||||
});
|
||||
|
||||
export const DELETE = apiHandler(async (request: NextRequest, { params }: RouteParams) => {
|
||||
const { user } = await requireAuth();
|
||||
|
||||
const { id } = await params;
|
||||
|
||||
const existing = await prisma.moodEntry.findUnique({ where: { id } });
|
||||
|
||||
if (!existing || existing.userId !== user.id) {
|
||||
return apiError("Stimmungseintrag nicht gefunden", 404);
|
||||
}
|
||||
|
||||
await prisma.moodEntry.delete({ where: { id } });
|
||||
|
||||
await auditLog("moodEntry.delete", {
|
||||
userId: user.id,
|
||||
ipAddress: getClientIp(request),
|
||||
details: { moodEntryId: id, mood: existing.mood },
|
||||
});
|
||||
|
||||
annotate({ action: { name: "mood-entries.delete" }, meta: { moodEntryId: id } });
|
||||
|
||||
return apiSuccess({ deleted: true });
|
||||
});
|
||||
@@ -0,0 +1,122 @@
|
||||
import { prisma } from "@/lib/db";
|
||||
import { auditLog } from "@/lib/auth/audit";
|
||||
import { apiSuccess, apiError, getClientIp, safeJson } from "@/lib/api-response";
|
||||
import {
|
||||
createMoodEntrySchema,
|
||||
listMoodEntriesSchema,
|
||||
getScoreForMood,
|
||||
} from "@/lib/validations/moodlog";
|
||||
import { NextRequest } from "next/server";
|
||||
import { Prisma } from "@/generated/prisma/client";
|
||||
import { apiHandler, requireAuth } from "@/lib/api-handler";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
|
||||
function toBerlinDate(date: Date): string {
|
||||
return new Intl.DateTimeFormat("sv-SE", {
|
||||
timeZone: "Europe/Berlin",
|
||||
}).format(date);
|
||||
}
|
||||
|
||||
function parseTags(tags: string | null): string[] {
|
||||
if (!tags) return [];
|
||||
try {
|
||||
return JSON.parse(tags) as string[];
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
export const GET = apiHandler(async (request: NextRequest) => {
|
||||
const { user } = await requireAuth();
|
||||
|
||||
const params = Object.fromEntries(request.nextUrl.searchParams);
|
||||
const parsed = listMoodEntriesSchema.safeParse(params);
|
||||
if (!parsed.success) {
|
||||
return apiError(parsed.error.issues[0].message, 422);
|
||||
}
|
||||
|
||||
const { mood, from, to, limit, offset, sortBy, sortDir } = parsed.data;
|
||||
|
||||
const where = {
|
||||
userId: user.id,
|
||||
...(mood && { mood }),
|
||||
...(from || to
|
||||
? {
|
||||
date: {
|
||||
...(from && { gte: from }),
|
||||
...(to && { lte: to }),
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
};
|
||||
|
||||
const [entries, total] = await Promise.all([
|
||||
prisma.moodEntry.findMany({
|
||||
where,
|
||||
orderBy: { [sortBy]: sortDir },
|
||||
take: limit,
|
||||
skip: offset,
|
||||
}),
|
||||
prisma.moodEntry.count({ where }),
|
||||
]);
|
||||
|
||||
annotate({ action: { name: "mood-entries.list" }, meta: { total, limit, offset } });
|
||||
|
||||
const entriesWithParsedTags = entries.map((e) => ({
|
||||
...e,
|
||||
tags: parseTags(e.tags),
|
||||
}));
|
||||
|
||||
return apiSuccess({
|
||||
entries: entriesWithParsedTags,
|
||||
meta: { total, limit, offset },
|
||||
});
|
||||
});
|
||||
|
||||
export const POST = apiHandler(async (request: NextRequest) => {
|
||||
const { user } = await requireAuth();
|
||||
|
||||
const { data: body, error: jsonError } = await safeJson(request);
|
||||
|
||||
if (jsonError) return jsonError;
|
||||
const parsed = createMoodEntrySchema.safeParse(body);
|
||||
if (!parsed.success) {
|
||||
return apiError(parsed.error.issues[0].message, 422);
|
||||
}
|
||||
|
||||
const { mood, tags, moodLoggedAt, source } = parsed.data;
|
||||
const date = toBerlinDate(moodLoggedAt);
|
||||
const score = getScoreForMood(mood);
|
||||
|
||||
try {
|
||||
const entry = await prisma.moodEntry.create({
|
||||
data: {
|
||||
userId: user.id,
|
||||
date,
|
||||
mood,
|
||||
score,
|
||||
tags: tags ? JSON.stringify(tags) : null,
|
||||
source: source ?? "MANUAL",
|
||||
moodLoggedAt,
|
||||
},
|
||||
});
|
||||
|
||||
await auditLog("moodEntry.create", {
|
||||
userId: user.id,
|
||||
ipAddress: getClientIp(request),
|
||||
details: { moodEntryId: entry.id, mood },
|
||||
});
|
||||
|
||||
annotate({ action: { name: "mood-entries.create" }, meta: { moodEntryId: entry.id, mood } });
|
||||
|
||||
return apiSuccess({ ...entry, tags: parseTags(entry.tags) }, 201);
|
||||
} catch (err) {
|
||||
if (err instanceof Prisma.PrismaClientKnownRequestError && err.code === "P2002") {
|
||||
return apiError(
|
||||
"Ein Stimmungseintrag mit diesen Daten existiert bereits",
|
||||
409,
|
||||
);
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,53 @@
|
||||
import { prisma } from "@/lib/db";
|
||||
import { apiSuccess } from "@/lib/api-response";
|
||||
import { summarize, type DataPoint } from "@/lib/analytics/trends";
|
||||
import { apiHandler, requireAuth } from "@/lib/api-handler";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
/** Aggregate multiple mood entries per day into daily averages. */
|
||||
function aggregateDailyAverages(
|
||||
records: Array<{ date: string; score: number }>,
|
||||
) {
|
||||
const byDay = new Map<string, { sum: number; count: number }>();
|
||||
for (const record of records) {
|
||||
const current = byDay.get(record.date) ?? { sum: 0, count: 0 };
|
||||
current.sum += record.score;
|
||||
current.count += 1;
|
||||
byDay.set(record.date, current);
|
||||
}
|
||||
return Array.from(byDay.entries())
|
||||
.sort(([a], [b]) => a.localeCompare(b))
|
||||
.map(([day, stats]) => ({
|
||||
date: day,
|
||||
score: Math.round((stats.sum / stats.count) * 100) / 100,
|
||||
samples: stats.count,
|
||||
}));
|
||||
}
|
||||
|
||||
export const GET = apiHandler(async () => {
|
||||
const { user } = await requireAuth();
|
||||
|
||||
const moodEntries = await prisma.moodEntry.findMany({
|
||||
where: { userId: user.id },
|
||||
orderBy: { moodLoggedAt: "asc" },
|
||||
select: { date: true, score: true, moodLoggedAt: true },
|
||||
});
|
||||
|
||||
const entries = aggregateDailyAverages(
|
||||
moodEntries.map((e) => ({ date: e.date, score: e.score })),
|
||||
);
|
||||
|
||||
// Build DataPoint array for summarize() using moodLoggedAt as the date
|
||||
const dataPoints: DataPoint[] = moodEntries.map((e) => ({
|
||||
date: e.moodLoggedAt,
|
||||
value: e.score,
|
||||
}));
|
||||
|
||||
const summary = summarize(dataPoints);
|
||||
|
||||
annotate({ action: { name: "mood.analytics" }, meta: { entryCount: moodEntries.length } });
|
||||
|
||||
return apiSuccess({ entries, summary });
|
||||
});
|
||||
@@ -0,0 +1,127 @@
|
||||
import { NextRequest } from "next/server";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { apiHandler, requireAuth } from "@/lib/api-handler";
|
||||
import { annotate, getEvent } from "@/lib/logging/context";
|
||||
import { apiSuccess, apiError } from "@/lib/api-response";
|
||||
import { notificationPreferenceSchema } from "@/lib/validations/notifications";
|
||||
import { EVENT_TYPES, CHANNEL_TYPE_LABELS } from "@/lib/notifications/types";
|
||||
import type { ChannelType } from "@/lib/notifications/types";
|
||||
import { decrypt, encrypt } from "@/lib/crypto";
|
||||
|
||||
export const GET = apiHandler(async () => {
|
||||
const { user } = await requireAuth();
|
||||
annotate({ action: { name: "notifications.preferences.get" } });
|
||||
|
||||
const appSettings = await prisma.appSettings.findUnique({
|
||||
where: { id: "singleton" },
|
||||
});
|
||||
|
||||
const globalToggles: Record<string, boolean> = {
|
||||
TELEGRAM: appSettings?.telegramGlobal ?? true,
|
||||
NTFY: appSettings?.ntfyGlobal ?? true,
|
||||
WEB_PUSH: appSettings?.webPushGlobal ?? true,
|
||||
};
|
||||
|
||||
const channels = await prisma.notificationChannel.findMany({
|
||||
where: { userId: user.id },
|
||||
include: { preferences: true },
|
||||
});
|
||||
|
||||
// Auto-migrate legacy Telegram config from User model if no channel record exists
|
||||
const hasTelegramChannel = channels.some((ch) => ch.type === "TELEGRAM");
|
||||
if (!hasTelegramChannel) {
|
||||
try {
|
||||
const legacyUser = await prisma.user.findUnique({
|
||||
where: { id: user.id },
|
||||
select: {
|
||||
telegramBotToken: true,
|
||||
telegramChatId: true,
|
||||
telegramEnabled: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (legacyUser?.telegramBotToken && legacyUser.telegramChatId) {
|
||||
const botToken = decrypt(legacyUser.telegramBotToken);
|
||||
const channelConfig = encrypt(
|
||||
JSON.stringify({ botToken, chatId: legacyUser.telegramChatId }),
|
||||
);
|
||||
|
||||
const created = await prisma.notificationChannel.upsert({
|
||||
where: {
|
||||
userId_type: { userId: user.id, type: "TELEGRAM" },
|
||||
},
|
||||
create: {
|
||||
userId: user.id,
|
||||
type: "TELEGRAM",
|
||||
enabled: legacyUser.telegramEnabled ?? true,
|
||||
config: channelConfig,
|
||||
},
|
||||
update: {},
|
||||
include: { preferences: true },
|
||||
});
|
||||
|
||||
channels.push(created);
|
||||
}
|
||||
} catch (err) {
|
||||
getEvent()?.addWarning("Legacy Telegram migration failed");
|
||||
}
|
||||
}
|
||||
|
||||
const channelData = channels.map((ch) => ({
|
||||
id: ch.id,
|
||||
type: ch.type,
|
||||
label: CHANNEL_TYPE_LABELS[ch.type as ChannelType] ?? ch.type,
|
||||
enabled: ch.enabled,
|
||||
globallyEnabled: globalToggles[ch.type] ?? true,
|
||||
}));
|
||||
|
||||
const preferences = channels.flatMap((ch) =>
|
||||
ch.preferences.map((p) => ({
|
||||
channelId: p.channelId,
|
||||
eventType: p.eventType,
|
||||
enabled: p.enabled,
|
||||
})),
|
||||
);
|
||||
|
||||
return apiSuccess({
|
||||
channels: channelData,
|
||||
preferences,
|
||||
eventTypes: EVENT_TYPES as unknown as string[],
|
||||
});
|
||||
});
|
||||
|
||||
export const PUT = apiHandler(async (request: NextRequest) => {
|
||||
const { user } = await requireAuth();
|
||||
annotate({ action: { name: "notifications.preferences.update" } });
|
||||
|
||||
let body: unknown;
|
||||
try {
|
||||
body = await request.json();
|
||||
} catch {
|
||||
return apiError("Ungültige JSON-Daten", 422);
|
||||
}
|
||||
|
||||
const parsed = notificationPreferenceSchema.safeParse(body);
|
||||
if (!parsed.success) return apiError("Ungültige Daten", 422);
|
||||
|
||||
const { channelId, eventType, enabled } = parsed.data;
|
||||
|
||||
const channel = await prisma.notificationChannel.findFirst({
|
||||
where: { id: channelId, userId: user.id },
|
||||
});
|
||||
if (!channel) return apiError("Kanal nicht gefunden", 404);
|
||||
|
||||
const preference = await prisma.notificationPreference.upsert({
|
||||
where: {
|
||||
channelId_eventType: { channelId, eventType },
|
||||
},
|
||||
create: { channelId, eventType, enabled },
|
||||
update: { enabled },
|
||||
});
|
||||
|
||||
return apiSuccess({
|
||||
channelId: preference.channelId,
|
||||
eventType: preference.eventType,
|
||||
enabled: preference.enabled,
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,19 @@
|
||||
import { apiHandler } from "@/lib/api-handler";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
import { apiSuccess, apiError } from "@/lib/api-response";
|
||||
import { getVapidConfig } from "@/lib/notifications/vapid-config";
|
||||
|
||||
/**
|
||||
* GET /api/notifications/vapid
|
||||
* Returns the VAPID public key for Web Push subscription.
|
||||
*/
|
||||
export const GET = apiHandler(async () => {
|
||||
annotate({ action: { name: "notifications.vapid" } });
|
||||
|
||||
const config = await getVapidConfig();
|
||||
if (!config?.publicKey) {
|
||||
return apiError("Web Push is not configured", 503);
|
||||
}
|
||||
|
||||
return apiSuccess({ publicKey: config.publicKey });
|
||||
});
|
||||
@@ -0,0 +1,109 @@
|
||||
import { NextRequest } from "next/server";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { apiHandler, requireAuth } from "@/lib/api-handler";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
import { apiSuccess, apiError } from "@/lib/api-response";
|
||||
import { encrypt } from "@/lib/crypto";
|
||||
import { z } from "zod/v4";
|
||||
|
||||
const subscribeSchema = z.object({
|
||||
endpoint: z.string().url(),
|
||||
keys: z.object({
|
||||
p256dh: z.string().min(1),
|
||||
auth: z.string().min(1),
|
||||
}),
|
||||
});
|
||||
|
||||
const unsubscribeSchema = z.object({
|
||||
endpoint: z.string().url(),
|
||||
});
|
||||
|
||||
/**
|
||||
* POST /api/notifications/web-push
|
||||
* Save a Web Push subscription for the current user.
|
||||
*/
|
||||
export const POST = apiHandler(async (request: NextRequest) => {
|
||||
const { user } = await requireAuth();
|
||||
annotate({ action: { name: "notifications.web-push.subscribe" } });
|
||||
|
||||
let body: unknown;
|
||||
try {
|
||||
body = await request.json();
|
||||
} catch {
|
||||
return apiError("Ungültige JSON-Daten", 422);
|
||||
}
|
||||
|
||||
const parsed = subscribeSchema.safeParse(body);
|
||||
if (!parsed.success) return apiError("Ungültige Daten", 422);
|
||||
|
||||
const { endpoint, keys } = parsed.data;
|
||||
const userAgent = request.headers.get("user-agent") ?? undefined;
|
||||
|
||||
// Upsert subscription (encrypt sensitive keys)
|
||||
await prisma.pushSubscription.upsert({
|
||||
where: {
|
||||
userId_endpoint: {
|
||||
userId: user.id,
|
||||
endpoint,
|
||||
},
|
||||
},
|
||||
create: {
|
||||
userId: user.id,
|
||||
endpoint,
|
||||
p256dh: encrypt(keys.p256dh),
|
||||
auth: encrypt(keys.auth),
|
||||
userAgent,
|
||||
},
|
||||
update: {
|
||||
p256dh: encrypt(keys.p256dh),
|
||||
auth: encrypt(keys.auth),
|
||||
userAgent,
|
||||
},
|
||||
});
|
||||
|
||||
// Ensure a WEB_PUSH notification channel exists for this user
|
||||
const existingChannel = await prisma.notificationChannel.findFirst({
|
||||
where: { userId: user.id, type: "WEB_PUSH" },
|
||||
});
|
||||
|
||||
if (!existingChannel) {
|
||||
await prisma.notificationChannel.create({
|
||||
data: {
|
||||
userId: user.id,
|
||||
type: "WEB_PUSH",
|
||||
enabled: true,
|
||||
config: encrypt(JSON.stringify({})),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return apiSuccess({ subscribed: true });
|
||||
});
|
||||
|
||||
/**
|
||||
* DELETE /api/notifications/web-push
|
||||
* Remove a Web Push subscription.
|
||||
*/
|
||||
export const DELETE = apiHandler(async (request: NextRequest) => {
|
||||
const { user } = await requireAuth();
|
||||
annotate({ action: { name: "notifications.web-push.unsubscribe" } });
|
||||
|
||||
let body: unknown;
|
||||
try {
|
||||
body = await request.json();
|
||||
} catch {
|
||||
return apiError("Ungültige JSON-Daten", 422);
|
||||
}
|
||||
|
||||
const parsed = unsubscribeSchema.safeParse(body);
|
||||
if (!parsed.success) return apiError("Ungültige Daten", 422);
|
||||
|
||||
await prisma.pushSubscription.deleteMany({
|
||||
where: {
|
||||
userId: user.id,
|
||||
endpoint: parsed.data.endpoint,
|
||||
},
|
||||
});
|
||||
|
||||
return apiSuccess({ unsubscribed: true });
|
||||
});
|
||||
@@ -0,0 +1,55 @@
|
||||
import { prisma } from "@/lib/db";
|
||||
import { apiHandler, requireAuth } from "@/lib/api-handler";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
import { apiSuccess, apiError, safeJson } from "@/lib/api-response";
|
||||
import { NextRequest } from "next/server";
|
||||
import { z } from "zod/v4";
|
||||
|
||||
const onboardingSchema = z.object({
|
||||
heightCm: z.number().min(50).max(300).optional(),
|
||||
dateOfBirth: z.string().optional(),
|
||||
gender: z.enum(["MALE", "FEMALE"]).optional(),
|
||||
});
|
||||
|
||||
/**
|
||||
* Complete the onboarding flow. Saves optional profile data and marks
|
||||
* onboarding as completed.
|
||||
*/
|
||||
export const POST = apiHandler(async (request: NextRequest) => {
|
||||
const { user } = await requireAuth();
|
||||
annotate({ action: { name: "onboarding.complete" } });
|
||||
|
||||
const { data: body, error: jsonError } = await safeJson(request);
|
||||
|
||||
if (jsonError) return jsonError;
|
||||
const result = z.safeParse(onboardingSchema, body);
|
||||
if (!result.success) {
|
||||
return apiError("Ungültige Eingabe", 422);
|
||||
}
|
||||
|
||||
const data: Record<string, unknown> = {
|
||||
onboardingCompletedAt: new Date(),
|
||||
};
|
||||
|
||||
if (result.data.heightCm) {
|
||||
data.heightCm = result.data.heightCm;
|
||||
}
|
||||
|
||||
if (result.data.dateOfBirth) {
|
||||
const dob = new Date(result.data.dateOfBirth);
|
||||
if (!isNaN(dob.getTime())) {
|
||||
data.dateOfBirth = dob;
|
||||
}
|
||||
}
|
||||
|
||||
if (result.data.gender) {
|
||||
data.gender = result.data.gender;
|
||||
}
|
||||
|
||||
await prisma.user.update({
|
||||
where: { id: user.id },
|
||||
data,
|
||||
});
|
||||
|
||||
return apiSuccess({ completed: true });
|
||||
});
|
||||
@@ -0,0 +1,112 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { apiHandler } from "@/lib/api-handler";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
import { getPublicMonitoringSettings } from "@/lib/monitoring-settings";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
// Allowed URL patterns for the Umami proxy to prevent SSRF.
|
||||
// Only permits HTTPS URLs (or localhost in dev) to known analytics paths.
|
||||
function isAllowedUmamiUrl(url: string): boolean {
|
||||
try {
|
||||
const parsed = new URL(url);
|
||||
const isDev = process.env.NODE_ENV === "development";
|
||||
if (!isDev && parsed.protocol !== "https:") return false;
|
||||
// Block requests to private/internal networks
|
||||
const hostname = parsed.hostname;
|
||||
if (
|
||||
hostname === "169.254.169.254" || // cloud metadata
|
||||
hostname === "localhost" ||
|
||||
hostname.startsWith("10.") ||
|
||||
hostname.startsWith("192.168.") ||
|
||||
hostname === "127.0.0.1" ||
|
||||
hostname === "[::1]" ||
|
||||
hostname === "0.0.0.0" ||
|
||||
hostname.endsWith(".internal") ||
|
||||
hostname.endsWith(".local") ||
|
||||
// 172.16.0.0/12 (172.16.x.x - 172.31.x.x)
|
||||
(hostname.startsWith("172.") &&
|
||||
(() => {
|
||||
const second = parseInt(hostname.split(".")[1] ?? "0", 10);
|
||||
return second >= 16 && second <= 31;
|
||||
})())
|
||||
) {
|
||||
if (!isDev) return false;
|
||||
}
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function resolveUmamiSendUrls(scriptUrl: string | null): string[] {
|
||||
if (!scriptUrl) return [];
|
||||
try {
|
||||
const parsed = new URL(scriptUrl);
|
||||
const origin = parsed.origin;
|
||||
const pathSegments = parsed.pathname.split("/").filter(Boolean);
|
||||
const segments = [...pathSegments];
|
||||
|
||||
// Remove script file segment (e.g. script.js, umami.js) if present.
|
||||
if (segments.length > 0 && segments[segments.length - 1]?.includes(".")) {
|
||||
segments.pop();
|
||||
}
|
||||
|
||||
const prefix = segments.length > 0 ? `/${segments.join("/")}` : "";
|
||||
const candidates = [
|
||||
`${origin}${prefix}/api/send`,
|
||||
`${origin}/api/send`,
|
||||
`${origin}/umami/api/send`,
|
||||
];
|
||||
|
||||
return Array.from(new Set(candidates.filter(isAllowedUmamiUrl)));
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
export const POST = apiHandler(async (request: NextRequest) => {
|
||||
annotate({ action: { name: "umami.proxy" } });
|
||||
|
||||
const settings = await getPublicMonitoringSettings();
|
||||
if (!settings.umamiEnabled) {
|
||||
return NextResponse.json({}, { status: 204 });
|
||||
}
|
||||
|
||||
const targetUrls = resolveUmamiSendUrls(settings.umamiScriptUrl);
|
||||
if (targetUrls.length === 0 || !settings.umamiWebsiteId) {
|
||||
return NextResponse.json({}, { status: 204 });
|
||||
}
|
||||
|
||||
const body = await request.arrayBuffer();
|
||||
// Limit proxy body size to 64 KB to prevent abuse
|
||||
if (body.byteLength > 65536) {
|
||||
return NextResponse.json({}, { status: 413 });
|
||||
}
|
||||
|
||||
let lastResponseStatus = 404;
|
||||
|
||||
for (const targetUrl of targetUrls) {
|
||||
const upstream = await fetch(targetUrl, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"content-type":
|
||||
request.headers.get("content-type") || "application/json",
|
||||
"user-agent": request.headers.get("user-agent") || "healthlog-proxy",
|
||||
},
|
||||
body,
|
||||
cache: "no-store",
|
||||
});
|
||||
|
||||
lastResponseStatus = upstream.status;
|
||||
|
||||
// Try next candidate only for path misses.
|
||||
if (upstream.status === 404) {
|
||||
continue;
|
||||
}
|
||||
|
||||
return new NextResponse(null, { status: upstream.status });
|
||||
}
|
||||
|
||||
return new NextResponse(null, { status: lastResponseStatus });
|
||||
});
|
||||
@@ -0,0 +1,66 @@
|
||||
import { prisma } from "@/lib/db";
|
||||
import { auditLog } from "@/lib/auth/audit";
|
||||
import { apiSuccess, apiError, getClientIp } from "@/lib/api-response";
|
||||
import { destroyAllSessions } from "@/lib/auth/session";
|
||||
import { NextRequest } from "next/server";
|
||||
import { apiHandler, requireAuth } from "@/lib/api-handler";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
/**
|
||||
* Permanently delete the user account and ALL associated data.
|
||||
* Cascading deletes in the schema handle all related records.
|
||||
*/
|
||||
export const DELETE = apiHandler(async (request: NextRequest) => {
|
||||
const { user } = await requireAuth();
|
||||
|
||||
let confirm = "";
|
||||
try {
|
||||
const body = await request.json();
|
||||
confirm = typeof body?.confirm === "string" ? body.confirm : "";
|
||||
} catch {
|
||||
return apiError("Ungueltige Anfrage", 422);
|
||||
}
|
||||
|
||||
if (confirm !== "DELETE_ACCOUNT") {
|
||||
return apiError(
|
||||
"Bestaetigung fehlt. Sende { confirm: 'DELETE_ACCOUNT' }",
|
||||
422,
|
||||
);
|
||||
}
|
||||
|
||||
// Prevent last admin from deleting themselves
|
||||
if (user.role === "ADMIN") {
|
||||
const adminCount = await prisma.user.count({ where: { role: "ADMIN" } });
|
||||
if (adminCount <= 1) {
|
||||
return apiError(
|
||||
"Der letzte Admin-Account kann nicht geloescht werden",
|
||||
400,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const userId = user.id;
|
||||
const username = user.username;
|
||||
|
||||
// Log before deletion (userId will be SetNull in audit_logs after cascade)
|
||||
await auditLog("user.account.delete", {
|
||||
userId,
|
||||
ipAddress: getClientIp(request),
|
||||
details: { username },
|
||||
});
|
||||
|
||||
// Destroy all sessions first
|
||||
await destroyAllSessions(userId);
|
||||
|
||||
// Delete user — all related data is removed via onDelete: Cascade
|
||||
await prisma.user.delete({ where: { id: userId } });
|
||||
|
||||
annotate({
|
||||
action: { name: "settings.account.delete" },
|
||||
meta: { username },
|
||||
});
|
||||
|
||||
return apiSuccess({ deleted: true });
|
||||
});
|
||||
@@ -0,0 +1,117 @@
|
||||
import { prisma } from "@/lib/db";
|
||||
import { auditLog } from "@/lib/auth/audit";
|
||||
import { apiSuccess, apiError, getClientIp } from "@/lib/api-response";
|
||||
import { NextRequest } from "next/server";
|
||||
import { apiHandler, requireAuth } from "@/lib/api-handler";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
/**
|
||||
* Delete all user-owned health/integration data while keeping the account.
|
||||
*/
|
||||
export const DELETE = apiHandler(async (request: NextRequest) => {
|
||||
const { user } = await requireAuth();
|
||||
|
||||
let confirm = "";
|
||||
try {
|
||||
const body = await request.json();
|
||||
confirm = typeof body?.confirm === "string" ? body.confirm : "";
|
||||
} catch {
|
||||
return apiError("Ungueltige Anfrage", 422);
|
||||
}
|
||||
|
||||
if (confirm !== "DELETE") {
|
||||
return apiError("Bestaetigung fehlt", 422);
|
||||
}
|
||||
|
||||
const userId = user.id;
|
||||
|
||||
const result = await prisma.$transaction(async (tx) => {
|
||||
const measurements = await tx.measurement.deleteMany({
|
||||
where: { userId },
|
||||
});
|
||||
const intakeEvents = await tx.medicationIntakeEvent.deleteMany({
|
||||
where: { userId },
|
||||
});
|
||||
const medications = await tx.medication.deleteMany({
|
||||
where: { userId },
|
||||
});
|
||||
const moodEntries = await tx.moodEntry.deleteMany({
|
||||
where: { userId },
|
||||
});
|
||||
const apiTokens = await tx.apiToken.deleteMany({
|
||||
where: { userId },
|
||||
});
|
||||
const withingsConnections = await tx.withingsConnection.deleteMany({
|
||||
where: { userId },
|
||||
});
|
||||
const notificationChannels = await tx.notificationChannel.deleteMany({
|
||||
where: { userId },
|
||||
});
|
||||
const pushSubscriptions = await tx.pushSubscription.deleteMany({
|
||||
where: { userId },
|
||||
});
|
||||
const dataBackups = await tx.dataBackup.deleteMany({
|
||||
where: { userId },
|
||||
});
|
||||
const achievements = await tx.userAchievement.deleteMany({
|
||||
where: { userId },
|
||||
});
|
||||
const telegramDeletions = await tx.telegramScheduledDeletion.deleteMany({
|
||||
where: { userId },
|
||||
});
|
||||
const auditLogs = await tx.auditLog.deleteMany({
|
||||
where: { userId },
|
||||
});
|
||||
|
||||
await tx.user.update({
|
||||
where: { id: userId },
|
||||
data: {
|
||||
heightCm: null,
|
||||
dateOfBirth: null,
|
||||
gender: null,
|
||||
openaiKeyEncrypted: null,
|
||||
insightsPrivacyMode: "aggregated",
|
||||
insightsCachedAt: null,
|
||||
insightsCachedText: null,
|
||||
telegramBotToken: null,
|
||||
telegramChatId: null,
|
||||
telegramEnabled: false,
|
||||
withingsClientIdEncrypted: null,
|
||||
withingsClientSecretEncrypted: null,
|
||||
moodLogUrlEncrypted: null,
|
||||
moodLogApiKeyEncrypted: null,
|
||||
moodLogEnabled: false,
|
||||
moodLogLastSyncedAt: null,
|
||||
moodLogWebhookSecret: null,
|
||||
onboardingCompletedAt: null,
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
measurements: measurements.count,
|
||||
intakeEvents: intakeEvents.count,
|
||||
medications: medications.count,
|
||||
moodEntries: moodEntries.count,
|
||||
apiTokens: apiTokens.count,
|
||||
withingsConnections: withingsConnections.count,
|
||||
notificationChannels: notificationChannels.count,
|
||||
pushSubscriptions: pushSubscriptions.count,
|
||||
dataBackups: dataBackups.count,
|
||||
achievements: achievements.count,
|
||||
telegramDeletions: telegramDeletions.count,
|
||||
auditLogs: auditLogs.count,
|
||||
};
|
||||
});
|
||||
|
||||
await auditLog("user.data.clear", {
|
||||
userId,
|
||||
ipAddress: getClientIp(request),
|
||||
details: result,
|
||||
});
|
||||
|
||||
annotate({ action: { name: "settings.data.clear" }, meta: result });
|
||||
|
||||
return apiSuccess({ cleared: true, ...result });
|
||||
});
|
||||
@@ -0,0 +1,16 @@
|
||||
import { apiSuccess } from "@/lib/api-response";
|
||||
import { getGlobalServiceAvailability } from "@/lib/app-settings";
|
||||
import { apiHandler, requireAuth } from "@/lib/api-handler";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export const GET = apiHandler(async () => {
|
||||
await requireAuth();
|
||||
|
||||
const availability = await getGlobalServiceAvailability();
|
||||
|
||||
annotate({ action: { name: "settings.global-services.get" } });
|
||||
|
||||
return apiSuccess(availability);
|
||||
});
|
||||
@@ -0,0 +1,80 @@
|
||||
import { NextRequest } from "next/server";
|
||||
import { randomBytes } from "node:crypto";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { apiSuccess, apiError } from "@/lib/api-response";
|
||||
import { encrypt } from "@/lib/crypto";
|
||||
import { moodLogCredentialsSchema } from "@/lib/validations/moodlog";
|
||||
import { apiHandler, requireAuth } from "@/lib/api-handler";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export const PUT = apiHandler(async (request: NextRequest) => {
|
||||
const { user } = await requireAuth();
|
||||
|
||||
let body: unknown;
|
||||
try {
|
||||
body = await request.json();
|
||||
} catch {
|
||||
return apiError("Invalid JSON", 400);
|
||||
}
|
||||
|
||||
const parsed = moodLogCredentialsSchema.safeParse(body);
|
||||
if (!parsed.success) {
|
||||
return apiError("Ungueltige Eingabe", 422);
|
||||
}
|
||||
|
||||
const { url, apiKey } = parsed.data;
|
||||
|
||||
// Generate webhook secret if not yet set
|
||||
const existing = await prisma.user.findUnique({
|
||||
where: { id: user.id },
|
||||
select: { moodLogWebhookSecret: true },
|
||||
});
|
||||
|
||||
const webhookSecret =
|
||||
existing?.moodLogWebhookSecret ?? `mb_${randomBytes(32).toString("hex")}`;
|
||||
|
||||
await prisma.user.update({
|
||||
where: { id: user.id },
|
||||
data: {
|
||||
moodLogUrlEncrypted: encrypt(url),
|
||||
moodLogApiKeyEncrypted: encrypt(apiKey),
|
||||
moodLogEnabled: true,
|
||||
moodLogWebhookSecret: webhookSecret,
|
||||
},
|
||||
});
|
||||
|
||||
annotate({ action: { name: "settings.moodlog.update" } });
|
||||
|
||||
return apiSuccess({
|
||||
configured: true,
|
||||
enabled: true,
|
||||
webhookSecret,
|
||||
});
|
||||
});
|
||||
|
||||
export const DELETE = apiHandler(async () => {
|
||||
const { user } = await requireAuth();
|
||||
|
||||
// Delete all mood entries for this user
|
||||
await prisma.moodEntry.deleteMany({
|
||||
where: { userId: user.id },
|
||||
});
|
||||
|
||||
// Clear credentials
|
||||
await prisma.user.update({
|
||||
where: { id: user.id },
|
||||
data: {
|
||||
moodLogUrlEncrypted: null,
|
||||
moodLogApiKeyEncrypted: null,
|
||||
moodLogEnabled: false,
|
||||
moodLogLastSyncedAt: null,
|
||||
moodLogWebhookSecret: null,
|
||||
},
|
||||
});
|
||||
|
||||
annotate({ action: { name: "settings.moodlog.disconnect" } });
|
||||
|
||||
return apiSuccess({ disconnected: true });
|
||||
});
|
||||
@@ -0,0 +1,92 @@
|
||||
import { prisma } from "@/lib/db";
|
||||
import { apiSuccess, apiError, safeJson } from "@/lib/api-response";
|
||||
import { ntfySettingsSchema } from "@/lib/validations/notifications";
|
||||
import { encrypt, decrypt } from "@/lib/crypto";
|
||||
import { NextRequest } from "next/server";
|
||||
import { apiHandler, requireAuth } from "@/lib/api-handler";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
|
||||
/**
|
||||
* GET: Return current ntfy config (without auth token).
|
||||
* PUT: Update ntfy config.
|
||||
*/
|
||||
export const GET = apiHandler(async () => {
|
||||
const { user } = await requireAuth();
|
||||
|
||||
const channel = await prisma.notificationChannel.findUnique({
|
||||
where: {
|
||||
userId_type: { userId: user.id, type: "NTFY" },
|
||||
},
|
||||
});
|
||||
|
||||
if (!channel) {
|
||||
return apiSuccess({
|
||||
enabled: false,
|
||||
serverUrl: "https://ntfy.sh",
|
||||
topic: "",
|
||||
hasAuthToken: false,
|
||||
});
|
||||
}
|
||||
|
||||
const config = JSON.parse(decrypt(channel.config)) as {
|
||||
serverUrl: string;
|
||||
topic: string;
|
||||
authToken?: string;
|
||||
};
|
||||
|
||||
annotate({ action: { name: "settings.ntfy.get" } });
|
||||
|
||||
return apiSuccess({
|
||||
enabled: channel.enabled,
|
||||
serverUrl: config.serverUrl,
|
||||
topic: config.topic,
|
||||
hasAuthToken: !!config.authToken,
|
||||
});
|
||||
});
|
||||
|
||||
export const PUT = apiHandler(async (request: NextRequest) => {
|
||||
const { user } = await requireAuth();
|
||||
|
||||
const { data: body, error: jsonError } = await safeJson(request);
|
||||
|
||||
if (jsonError) return jsonError;
|
||||
const parsed = ntfySettingsSchema.safeParse(body);
|
||||
if (!parsed.success) return apiError("Ungueltige Daten", 422);
|
||||
|
||||
const { serverUrl, topic, authToken, enabled } = parsed.data;
|
||||
|
||||
if (enabled && (!serverUrl || !topic)) {
|
||||
return apiError(
|
||||
"Server-URL und Topic sind erforderlich, wenn ntfy aktiviert ist",
|
||||
422,
|
||||
);
|
||||
}
|
||||
|
||||
const config = JSON.stringify({
|
||||
serverUrl: serverUrl || "https://ntfy.sh",
|
||||
topic: topic || "",
|
||||
...(authToken ? { authToken } : {}),
|
||||
});
|
||||
|
||||
const encryptedConfig = encrypt(config);
|
||||
|
||||
await prisma.notificationChannel.upsert({
|
||||
where: {
|
||||
userId_type: { userId: user.id, type: "NTFY" },
|
||||
},
|
||||
create: {
|
||||
userId: user.id,
|
||||
type: "NTFY",
|
||||
enabled,
|
||||
config: encryptedConfig,
|
||||
},
|
||||
update: {
|
||||
enabled,
|
||||
config: encryptedConfig,
|
||||
},
|
||||
});
|
||||
|
||||
annotate({ action: { name: "settings.ntfy.update" }, meta: { enabled } });
|
||||
|
||||
return apiSuccess({ saved: true });
|
||||
});
|
||||
@@ -0,0 +1,52 @@
|
||||
import { prisma } from "@/lib/db";
|
||||
import { apiSuccess, apiError } from "@/lib/api-response";
|
||||
import { decrypt } from "@/lib/crypto";
|
||||
import { sendViaNtfy } from "@/lib/notifications/senders/ntfy";
|
||||
import type { NtfyChannelConfig } from "@/lib/notifications/types";
|
||||
import { checkRateLimit } from "@/lib/rate-limit";
|
||||
import { apiHandler, requireAuth } from "@/lib/api-handler";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
|
||||
/**
|
||||
* POST: Send a test notification via ntfy.
|
||||
*/
|
||||
export const POST = apiHandler(async () => {
|
||||
const { user } = await requireAuth();
|
||||
|
||||
const rl = await checkRateLimit(`ntfy-test:${user.id}`, 5, 5 * 60 * 1000);
|
||||
if (!rl.allowed) {
|
||||
return apiError("Maximal 5 Tests in 5 Minuten", 429);
|
||||
}
|
||||
|
||||
const channel = await prisma.notificationChannel.findUnique({
|
||||
where: {
|
||||
userId_type: { userId: user.id, type: "NTFY" },
|
||||
},
|
||||
});
|
||||
|
||||
if (!channel) {
|
||||
return apiError("ntfy ist nicht konfiguriert", 400);
|
||||
}
|
||||
|
||||
const config = JSON.parse(decrypt(channel.config)) as NtfyChannelConfig;
|
||||
|
||||
if (!config.serverUrl || !config.topic) {
|
||||
return apiError("Server-URL und Topic sind erforderlich", 400);
|
||||
}
|
||||
|
||||
const success = await sendViaNtfy(config, {
|
||||
eventType: "SYSTEM_ALERT",
|
||||
userId: user.id,
|
||||
title: "HealthLog Test",
|
||||
message:
|
||||
"HealthLog: Verbindung erfolgreich! ntfy-Benachrichtigungen sind aktiv.",
|
||||
});
|
||||
|
||||
if (!success) {
|
||||
return apiError("Testnachricht konnte nicht gesendet werden", 500);
|
||||
}
|
||||
|
||||
annotate({ action: { name: "settings.ntfy.test" }, meta: { success: true } });
|
||||
|
||||
return apiSuccess({ sent: true });
|
||||
});
|
||||
@@ -0,0 +1,16 @@
|
||||
import { apiSuccess } from "@/lib/api-response";
|
||||
import { getReminderThresholds } from "@/lib/app-settings";
|
||||
import { apiHandler, requireAuth } from "@/lib/api-handler";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export const GET = apiHandler(async () => {
|
||||
await requireAuth();
|
||||
|
||||
const thresholds = await getReminderThresholds();
|
||||
|
||||
annotate({ action: { name: "settings.reminder-thresholds.get" } });
|
||||
|
||||
return apiSuccess(thresholds);
|
||||
});
|
||||
@@ -0,0 +1,198 @@
|
||||
import { prisma } from "@/lib/db";
|
||||
import { apiSuccess, apiError, safeJson } from "@/lib/api-response";
|
||||
import { decrypt, encrypt } from "@/lib/crypto";
|
||||
import { deleteTelegramWebhook, setTelegramWebhook } from "@/lib/telegram";
|
||||
import { telegramSettingsSchema } from "@/lib/validations/telegram";
|
||||
import { NextRequest } from "next/server";
|
||||
import { z } from "zod/v4";
|
||||
import { apiHandler, requireAuth } from "@/lib/api-handler";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
|
||||
/**
|
||||
* Get Telegram notification settings for the current user.
|
||||
* Never returns the bot token in plaintext.
|
||||
*/
|
||||
export const GET = apiHandler(async () => {
|
||||
const { user } = await requireAuth();
|
||||
|
||||
const dbUser = await prisma.user.findUnique({
|
||||
where: { id: user.id },
|
||||
select: {
|
||||
telegramBotToken: true,
|
||||
telegramChatId: true,
|
||||
telegramEnabled: true,
|
||||
},
|
||||
});
|
||||
|
||||
annotate({ action: { name: "settings.telegram.get" } });
|
||||
|
||||
return apiSuccess({
|
||||
enabled: dbUser?.telegramEnabled ?? false,
|
||||
hasBotToken: !!dbUser?.telegramBotToken,
|
||||
chatId: dbUser?.telegramChatId ?? null,
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* Update Telegram notification settings.
|
||||
*/
|
||||
export const PUT = apiHandler(async (request: NextRequest) => {
|
||||
const { user } = await requireAuth();
|
||||
|
||||
const current = await prisma.user.findUnique({
|
||||
where: { id: user.id },
|
||||
select: {
|
||||
telegramBotToken: true,
|
||||
telegramChatId: true,
|
||||
telegramEnabled: true,
|
||||
},
|
||||
});
|
||||
if (!current) return apiError("Benutzer nicht gefunden", 404);
|
||||
|
||||
const { data: body, error: jsonError } = await safeJson(request);
|
||||
|
||||
if (jsonError) return jsonError;
|
||||
const result = z.safeParse(telegramSettingsSchema, body);
|
||||
if (!result.success) {
|
||||
return apiError("Ungueltige Eingabe", 422);
|
||||
}
|
||||
|
||||
const { botToken, chatId, enabled } = result.data;
|
||||
const trimmedToken = botToken?.trim();
|
||||
const trimmedChatId = chatId?.trim();
|
||||
|
||||
const hasTokenAfter =
|
||||
botToken !== undefined ? !!trimmedToken : !!current.telegramBotToken;
|
||||
const hasChatIdAfter =
|
||||
chatId !== undefined ? !!trimmedChatId : !!current.telegramChatId;
|
||||
|
||||
if (enabled && (!hasTokenAfter || !hasChatIdAfter)) {
|
||||
return apiError(
|
||||
"Fuer aktiviertes Telegram werden Bot-Token und Chat-ID benoetigt",
|
||||
422,
|
||||
);
|
||||
}
|
||||
|
||||
const currentTokenPlain = current.telegramBotToken
|
||||
? decrypt(current.telegramBotToken)
|
||||
: null;
|
||||
const tokenForWebhook = trimmedToken || currentTokenPlain;
|
||||
|
||||
if (enabled && tokenForWebhook) {
|
||||
const appUrl = process.env.APP_URL ?? process.env.NEXT_PUBLIC_APP_URL;
|
||||
if (!appUrl) {
|
||||
return apiError(
|
||||
"Server-Konfiguration fehlerhaft: APP_URL (oder NEXT_PUBLIC_APP_URL) fehlt.",
|
||||
500,
|
||||
);
|
||||
}
|
||||
|
||||
let appBaseUrl: URL;
|
||||
try {
|
||||
appBaseUrl = new URL(appUrl);
|
||||
} catch {
|
||||
return apiError(
|
||||
"Server-Konfiguration fehlerhaft: APP_URL ist ungueltig.",
|
||||
500,
|
||||
);
|
||||
}
|
||||
|
||||
if (appBaseUrl.protocol !== "https:") {
|
||||
return apiError(
|
||||
"Telegram-Webhook benoetigt eine oeffentliche HTTPS-URL (kein http/localhost).",
|
||||
422,
|
||||
);
|
||||
}
|
||||
|
||||
const localHosts = new Set(["localhost", "127.0.0.1", "::1"]);
|
||||
if (localHosts.has(appBaseUrl.hostname.toLowerCase())) {
|
||||
return apiError(
|
||||
"Telegram-Webhook benoetigt eine oeffentlich erreichbare Domain (localhost ist nicht erlaubt).",
|
||||
422,
|
||||
);
|
||||
}
|
||||
|
||||
if (
|
||||
appBaseUrl.port &&
|
||||
!["80", "88", "443", "8443"].includes(appBaseUrl.port)
|
||||
) {
|
||||
return apiError(
|
||||
"Telegram-Webhook erlaubt nur die Ports 80, 88, 443 oder 8443.",
|
||||
422,
|
||||
);
|
||||
}
|
||||
|
||||
const webhookUrl = new URL("/api/telegram/webhook", appBaseUrl).toString();
|
||||
const webhookSecret = process.env.TELEGRAM_WEBHOOK_SECRET;
|
||||
const ok = await setTelegramWebhook(
|
||||
tokenForWebhook,
|
||||
webhookUrl,
|
||||
webhookSecret,
|
||||
);
|
||||
if (!ok) {
|
||||
return apiError(
|
||||
"Telegram-Webhook konnte nicht gesetzt werden. Pruefe Bot-Token und Erreichbarkeit.",
|
||||
422,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const data: Record<string, unknown> = { telegramEnabled: enabled };
|
||||
|
||||
if (botToken !== undefined) {
|
||||
data.telegramBotToken = trimmedToken ? encrypt(trimmedToken) : null;
|
||||
}
|
||||
|
||||
if (chatId !== undefined) {
|
||||
data.telegramChatId = trimmedChatId || null;
|
||||
}
|
||||
|
||||
await prisma.user.update({
|
||||
where: { id: user.id },
|
||||
data,
|
||||
});
|
||||
|
||||
// Sync to NotificationChannel so the dispatcher can find Telegram
|
||||
const finalToken = trimmedToken ? trimmedToken : currentTokenPlain;
|
||||
const finalChatId = trimmedChatId ?? current.telegramChatId;
|
||||
|
||||
if (finalToken && finalChatId) {
|
||||
const channelConfig = encrypt(
|
||||
JSON.stringify({ botToken: finalToken, chatId: finalChatId }),
|
||||
);
|
||||
await prisma.notificationChannel.upsert({
|
||||
where: {
|
||||
userId_type: {
|
||||
userId: user.id,
|
||||
type: "TELEGRAM",
|
||||
},
|
||||
},
|
||||
create: {
|
||||
userId: user.id,
|
||||
type: "TELEGRAM",
|
||||
enabled,
|
||||
config: channelConfig,
|
||||
},
|
||||
update: {
|
||||
enabled,
|
||||
config: channelConfig,
|
||||
},
|
||||
});
|
||||
} else if (!enabled) {
|
||||
// Remove the channel record if disabled and no credentials
|
||||
await prisma.notificationChannel.deleteMany({
|
||||
where: {
|
||||
userId: user.id,
|
||||
type: "TELEGRAM",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
if (!enabled && tokenForWebhook) {
|
||||
await deleteTelegramWebhook(tokenForWebhook).catch(() => {});
|
||||
}
|
||||
|
||||
annotate({ action: { name: "settings.telegram.update" }, meta: { enabled } });
|
||||
|
||||
return apiSuccess({ updated: true });
|
||||
});
|
||||
@@ -0,0 +1,49 @@
|
||||
import { prisma } from "@/lib/db";
|
||||
import { apiSuccess, apiError } from "@/lib/api-response";
|
||||
import { decrypt } from "@/lib/crypto";
|
||||
import { sendTelegramMessage } from "@/lib/telegram";
|
||||
import { checkRateLimit } from "@/lib/rate-limit";
|
||||
import { apiHandler, requireAuth } from "@/lib/api-handler";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
|
||||
/**
|
||||
* Send a test Telegram message to verify the bot token and chat ID.
|
||||
*/
|
||||
export const POST = apiHandler(async () => {
|
||||
const { user } = await requireAuth();
|
||||
|
||||
const rl = await checkRateLimit(`telegram-test:${user.id}`, 5, 5 * 60 * 1000);
|
||||
if (!rl.allowed) {
|
||||
return apiError("Maximal 5 Tests in 5 Minuten", 429);
|
||||
}
|
||||
|
||||
const dbUser = await prisma.user.findUnique({
|
||||
where: { id: user.id },
|
||||
select: { telegramBotToken: true, telegramChatId: true },
|
||||
});
|
||||
|
||||
if (!dbUser?.telegramBotToken || !dbUser?.telegramChatId) {
|
||||
return apiError(
|
||||
"Bot-Token und Chat-ID muessen zuerst gespeichert werden",
|
||||
422,
|
||||
);
|
||||
}
|
||||
|
||||
const botToken = decrypt(dbUser.telegramBotToken);
|
||||
const ok = await sendTelegramMessage(
|
||||
botToken,
|
||||
dbUser.telegramChatId,
|
||||
"HealthLog: Verbindung erfolgreich! Telegram-Benachrichtigungen sind aktiv.",
|
||||
);
|
||||
|
||||
if (!ok) {
|
||||
return apiError(
|
||||
"Nachricht konnte nicht gesendet werden. Pruefe Bot-Token und Chat-ID.",
|
||||
422,
|
||||
);
|
||||
}
|
||||
|
||||
annotate({ action: { name: "settings.telegram.test" }, meta: { success: true } });
|
||||
|
||||
return apiSuccess({ sent: true });
|
||||
});
|
||||
@@ -0,0 +1,633 @@
|
||||
import { timingSafeEqual } from "node:crypto";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { decrypt } from "@/lib/crypto";
|
||||
import {
|
||||
answerTelegramCallbackQuery,
|
||||
deleteMessage,
|
||||
sendTelegramMessage,
|
||||
} from "@/lib/telegram";
|
||||
import { checkRateLimit, rateLimitHeaders } from "@/lib/rate-limit";
|
||||
import { getClientIp } from "@/lib/api-response";
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { apiHandler } from "@/lib/api-handler";
|
||||
import { annotate, getEvent } from "@/lib/logging/context";
|
||||
|
||||
interface TelegramUpdate {
|
||||
update_id: number;
|
||||
message?: {
|
||||
message_id?: number;
|
||||
text?: string;
|
||||
chat?: { id: number | string };
|
||||
};
|
||||
callback_query?: {
|
||||
id: string;
|
||||
data?: string;
|
||||
from?: { id?: number | string };
|
||||
message?: {
|
||||
message_id?: number;
|
||||
chat?: { id: number | string };
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
function hasValidSecret(request: NextRequest): boolean {
|
||||
const expected = process.env.TELEGRAM_WEBHOOK_SECRET;
|
||||
if (!expected) {
|
||||
getEvent()?.addWarning("TELEGRAM_WEBHOOK_SECRET not configured");
|
||||
return false;
|
||||
}
|
||||
const received = request.headers.get("x-telegram-bot-api-secret-token");
|
||||
if (!received) return false;
|
||||
const a = Buffer.from(expected, "utf8");
|
||||
const b = Buffer.from(received, "utf8");
|
||||
if (a.length !== b.length) return false;
|
||||
return timingSafeEqual(a, b);
|
||||
}
|
||||
|
||||
function toChatId(value: number | string | undefined | null): string | null {
|
||||
if (value === undefined || value === null) return null;
|
||||
return String(value);
|
||||
}
|
||||
|
||||
function escapeHtml(input: string): string {
|
||||
return input
|
||||
.replaceAll("&", "&")
|
||||
.replaceAll("<", "<")
|
||||
.replaceAll(">", ">");
|
||||
}
|
||||
|
||||
async function cleanupReminderTracking(medicationId: string): Promise<void> {
|
||||
try {
|
||||
await prisma.telegramReminderMessage.deleteMany({
|
||||
where: { medicationId },
|
||||
});
|
||||
} catch {
|
||||
// Best-effort cleanup
|
||||
}
|
||||
}
|
||||
|
||||
const AUTO_DELETE_DELAY_MS = 60 * 60 * 1000; // 1 hour
|
||||
|
||||
async function scheduleAutoDelete(
|
||||
userId: string,
|
||||
chatId: string,
|
||||
messageIds: number[],
|
||||
): Promise<void> {
|
||||
const deleteAfter = new Date(Date.now() + AUTO_DELETE_DELAY_MS);
|
||||
try {
|
||||
await prisma.telegramScheduledDeletion.createMany({
|
||||
data: messageIds.map((messageId) => ({
|
||||
userId,
|
||||
chatId,
|
||||
messageId,
|
||||
deleteAfter,
|
||||
})),
|
||||
});
|
||||
} catch {
|
||||
// Best-effort
|
||||
}
|
||||
}
|
||||
|
||||
async function findTelegramUser(chatId: string) {
|
||||
return prisma.user.findFirst({
|
||||
where: {
|
||||
telegramEnabled: true,
|
||||
telegramChatId: chatId,
|
||||
telegramBotToken: { not: null },
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
telegramBotToken: true,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async function markMedicationTaken(
|
||||
userId: string,
|
||||
medicationId: string,
|
||||
idempotencyKey: string,
|
||||
): Promise<{ ok: boolean; message: string; medicationName?: string }> {
|
||||
const medication = await prisma.medication.findFirst({
|
||||
where: { id: medicationId, userId, active: true },
|
||||
select: { id: true, name: true },
|
||||
});
|
||||
if (!medication) {
|
||||
return { ok: false, message: "Medikament nicht gefunden oder inaktiv." };
|
||||
}
|
||||
|
||||
const existing = await prisma.medicationIntakeEvent.findFirst({
|
||||
where: { userId, medicationId: medication.id, idempotencyKey },
|
||||
select: { id: true },
|
||||
});
|
||||
|
||||
if (!existing) {
|
||||
await prisma.$transaction([
|
||||
prisma.medicationIntakeEvent.create({
|
||||
data: {
|
||||
userId,
|
||||
medicationId: medication.id,
|
||||
scheduledFor: new Date(),
|
||||
takenAt: new Date(),
|
||||
skipped: false,
|
||||
source: "REMINDER",
|
||||
idempotencyKey,
|
||||
},
|
||||
}),
|
||||
prisma.medication.update({
|
||||
where: { id: medication.id },
|
||||
data: { snoozedUntil: null },
|
||||
}),
|
||||
]);
|
||||
}
|
||||
|
||||
return {
|
||||
ok: true,
|
||||
message: existing
|
||||
? `${medication.name} war bereits erfasst.`
|
||||
: `${medication.name} als eingenommen erfasst.`,
|
||||
medicationName: medication.name,
|
||||
};
|
||||
}
|
||||
|
||||
async function handleCallback(update: TelegramUpdate) {
|
||||
const callback = update.callback_query;
|
||||
if (!callback) return;
|
||||
|
||||
const chatId =
|
||||
toChatId(callback.message?.chat?.id) ?? toChatId(callback.from?.id);
|
||||
if (!chatId) return;
|
||||
|
||||
const user = await findTelegramUser(chatId);
|
||||
if (!user?.telegramBotToken) return;
|
||||
const botToken = decrypt(user.telegramBotToken);
|
||||
|
||||
const data = callback.data ?? "";
|
||||
const messageId = callback.message?.message_id;
|
||||
|
||||
if (data.startsWith("taken:")) {
|
||||
const medicationId = data.slice("taken:".length).trim();
|
||||
if (!medicationId) {
|
||||
await answerTelegramCallbackQuery(
|
||||
botToken,
|
||||
callback.id,
|
||||
"Ungültige Aktion.",
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const msgId = messageId ?? "na";
|
||||
const idempotencyKey =
|
||||
`telegram:cb:${chatId}:${msgId}:${medicationId}`.slice(0, 128);
|
||||
|
||||
const result = await markMedicationTaken(
|
||||
user.id,
|
||||
medicationId,
|
||||
idempotencyKey,
|
||||
);
|
||||
await answerTelegramCallbackQuery(botToken, callback.id, result.message);
|
||||
if (messageId) {
|
||||
await deleteMessage(botToken, chatId, messageId);
|
||||
}
|
||||
await cleanupReminderTracking(medicationId);
|
||||
} else if (data.startsWith("snooze:")) {
|
||||
// Format: "snooze:{medicationId}:{minutes}"
|
||||
const parts = data.split(":");
|
||||
const medicationId = parts[1];
|
||||
const minutes = parseInt(parts[2], 10);
|
||||
if (!medicationId || !Number.isFinite(minutes)) {
|
||||
await answerTelegramCallbackQuery(
|
||||
botToken,
|
||||
callback.id,
|
||||
"Ungültige Aktion.",
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const medication = await prisma.medication.findFirst({
|
||||
where: { id: medicationId, userId: user.id, active: true },
|
||||
select: { id: true, name: true },
|
||||
});
|
||||
if (!medication) {
|
||||
await answerTelegramCallbackQuery(
|
||||
botToken,
|
||||
callback.id,
|
||||
"Medikament nicht gefunden.",
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
await prisma.medication.update({
|
||||
where: { id: medication.id },
|
||||
data: { snoozedUntil: new Date(Date.now() + minutes * 60000) },
|
||||
});
|
||||
|
||||
const label = minutes <= 60 ? "1 Stunde" : "3 Stunden";
|
||||
await answerTelegramCallbackQuery(
|
||||
botToken,
|
||||
callback.id,
|
||||
`${medication.name} für ${label} zurückgestellt.`,
|
||||
);
|
||||
if (messageId) {
|
||||
await deleteMessage(botToken, chatId, messageId);
|
||||
}
|
||||
await cleanupReminderTracking(medicationId);
|
||||
} else if (data.startsWith("skip:")) {
|
||||
const medicationId = data.slice("skip:".length).trim();
|
||||
if (!medicationId) {
|
||||
await answerTelegramCallbackQuery(
|
||||
botToken,
|
||||
callback.id,
|
||||
"Ungültige Aktion.",
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const medication = await prisma.medication.findFirst({
|
||||
where: { id: medicationId, userId: user.id, active: true },
|
||||
select: { id: true, name: true },
|
||||
});
|
||||
if (!medication) {
|
||||
await answerTelegramCallbackQuery(
|
||||
botToken,
|
||||
callback.id,
|
||||
"Medikament nicht gefunden.",
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const msgId = messageId ?? "na";
|
||||
const idempotencyKey =
|
||||
`telegram:skip:${chatId}:${msgId}:${medicationId}`.slice(0, 128);
|
||||
|
||||
const existing = await prisma.medicationIntakeEvent.findFirst({
|
||||
where: { userId: user.id, medicationId: medication.id, idempotencyKey },
|
||||
select: { id: true },
|
||||
});
|
||||
|
||||
if (!existing) {
|
||||
const endOfDay = new Date();
|
||||
endOfDay.setHours(23, 59, 59, 999);
|
||||
|
||||
await prisma.$transaction([
|
||||
prisma.medicationIntakeEvent.create({
|
||||
data: {
|
||||
userId: user.id,
|
||||
medicationId: medication.id,
|
||||
scheduledFor: new Date(),
|
||||
takenAt: null,
|
||||
skipped: true,
|
||||
source: "REMINDER",
|
||||
idempotencyKey,
|
||||
},
|
||||
}),
|
||||
prisma.medication.update({
|
||||
where: { id: medication.id },
|
||||
data: { snoozedUntil: endOfDay },
|
||||
}),
|
||||
]);
|
||||
}
|
||||
|
||||
await answerTelegramCallbackQuery(
|
||||
botToken,
|
||||
callback.id,
|
||||
`${medication.name} übersprungen.`,
|
||||
);
|
||||
if (messageId) {
|
||||
await deleteMessage(botToken, chatId, messageId);
|
||||
}
|
||||
await cleanupReminderTracking(medicationId);
|
||||
} else if (data.startsWith("ack:")) {
|
||||
const medicationId = data.slice("ack:".length).trim();
|
||||
if (!medicationId) {
|
||||
await answerTelegramCallbackQuery(botToken, callback.id, "Ungültige Aktion.");
|
||||
return;
|
||||
}
|
||||
|
||||
const medication = await prisma.medication.findFirst({
|
||||
where: { id: medicationId, userId: user.id },
|
||||
select: { id: true, name: true },
|
||||
});
|
||||
|
||||
await answerTelegramCallbackQuery(
|
||||
botToken,
|
||||
callback.id,
|
||||
medication ? `${medication.name} bestätigt.` : "Bestätigt.",
|
||||
);
|
||||
if (messageId) {
|
||||
await deleteMessage(botToken, chatId, messageId);
|
||||
}
|
||||
await cleanupReminderTracking(medicationId);
|
||||
} else if (data.startsWith("add:")) {
|
||||
// Format: "add:{medicationId}" or "add:{medicationId}:umid:{userMsgId}"
|
||||
const withoutPrefix = data.slice("add:".length);
|
||||
const umidIdx = withoutPrefix.indexOf(":umid:");
|
||||
const medicationId = umidIdx >= 0 ? withoutPrefix.slice(0, umidIdx) : withoutPrefix.trim();
|
||||
if (!medicationId) {
|
||||
await answerTelegramCallbackQuery(botToken, callback.id, "Ungültige Aktion.");
|
||||
return;
|
||||
}
|
||||
|
||||
const msgId = messageId ?? "na";
|
||||
const idempotencyKey =
|
||||
`telegram:add:${chatId}:${msgId}:${medicationId}`.slice(0, 128);
|
||||
|
||||
const result = await markMedicationTaken(user.id, medicationId, idempotencyKey);
|
||||
await answerTelegramCallbackQuery(botToken, callback.id, result.message);
|
||||
if (messageId) {
|
||||
await deleteMessage(botToken, chatId, messageId);
|
||||
}
|
||||
// Also delete the user's /add command message if encoded
|
||||
const userMsgMatch = data.match(/:umid:(\d+)$/);
|
||||
if (userMsgMatch) {
|
||||
const userMsgId = parseInt(userMsgMatch[1], 10);
|
||||
if (Number.isFinite(userMsgId)) {
|
||||
await deleteMessage(botToken, chatId, userMsgId).catch(() => {});
|
||||
}
|
||||
}
|
||||
} else if (data.startsWith("cancel_add")) {
|
||||
// Delete the bot's selection message
|
||||
if (messageId) {
|
||||
await deleteMessage(botToken, chatId, messageId);
|
||||
}
|
||||
// Delete the user's original /add command message if encoded
|
||||
const userMsgMatch = data.match(/:umid:(\d+)$/);
|
||||
if (userMsgMatch) {
|
||||
const userMsgId = parseInt(userMsgMatch[1], 10);
|
||||
if (Number.isFinite(userMsgId)) {
|
||||
await deleteMessage(botToken, chatId, userMsgId).catch(() => {});
|
||||
}
|
||||
}
|
||||
await answerTelegramCallbackQuery(botToken, callback.id, "Abgebrochen.");
|
||||
} else {
|
||||
await answerTelegramCallbackQuery(
|
||||
botToken,
|
||||
callback.id,
|
||||
"Unbekannte Aktion.",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleTextMessage(update: TelegramUpdate) {
|
||||
const message = update.message;
|
||||
const text = message?.text?.trim();
|
||||
const chatId = toChatId(message?.chat?.id);
|
||||
if (!text || !chatId) return;
|
||||
|
||||
const user = await findTelegramUser(chatId);
|
||||
if (!user?.telegramBotToken) return;
|
||||
const botToken = decrypt(user.telegramBotToken);
|
||||
|
||||
if (/^\/help\b/i.test(text) || /^\/start\b/i.test(text) || /^hilfe$/i.test(text)) {
|
||||
const userMsgId = message?.message_id;
|
||||
const resp = await sendTelegramMessage(
|
||||
botToken,
|
||||
chatId,
|
||||
`<b>Verfügbare Befehle:</b>\n\n` +
|
||||
`/help — Diese Hilfe anzeigen\n` +
|
||||
`/add — Einnahme erfassen\n` +
|
||||
`/start — Bot starten\n\n` +
|
||||
`<b>Textbefehle:</b>\n` +
|
||||
`genommen <Name> — Einnahme bestätigen\n\n` +
|
||||
`<b>Über die Buttons in Erinnerungen:</b>\n` +
|
||||
`• Genommen — Einnahme bestätigen\n` +
|
||||
`• 🕐 1h / 🕐 3h — Erinnerung verschieben\n` +
|
||||
`• ⏭ Überspringen — Einnahme überspringen\n` +
|
||||
`• ✓ Bestätigen — Verpasste Einnahme bestätigen`,
|
||||
);
|
||||
const toDelete = [userMsgId, resp.messageId].filter(
|
||||
(id): id is number => id != null,
|
||||
);
|
||||
if (toDelete.length > 0) {
|
||||
await scheduleAutoDelete(user.id, chatId, toDelete);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (/^\/add\b/i.test(text)) {
|
||||
const userMsgId = message?.message_id;
|
||||
const meds = await prisma.medication.findMany({
|
||||
where: { userId: user.id, active: true },
|
||||
select: { id: true, name: true, dose: true },
|
||||
orderBy: { name: "asc" },
|
||||
});
|
||||
|
||||
if (meds.length === 0) {
|
||||
const resp = await sendTelegramMessage(
|
||||
botToken,
|
||||
chatId,
|
||||
"Keine aktiven Medikamente gefunden.",
|
||||
);
|
||||
const toDelete = [userMsgId, resp.messageId].filter(
|
||||
(id): id is number => id != null,
|
||||
);
|
||||
if (toDelete.length > 0) {
|
||||
await scheduleAutoDelete(user.id, chatId, toDelete);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (meds.length === 1) {
|
||||
const idempotencyKey =
|
||||
`telegram:add:${update.update_id}:${meds[0].id}`.slice(0, 128);
|
||||
const result = await markMedicationTaken(
|
||||
user.id,
|
||||
meds[0].id,
|
||||
idempotencyKey,
|
||||
);
|
||||
const resp = await sendTelegramMessage(
|
||||
botToken,
|
||||
chatId,
|
||||
result.ok
|
||||
? `${escapeHtml(result.message)}`
|
||||
: `${escapeHtml(result.message)}`,
|
||||
);
|
||||
const toDelete = [userMsgId, resp.messageId].filter(
|
||||
(id): id is number => id != null,
|
||||
);
|
||||
if (toDelete.length > 0) {
|
||||
await scheduleAutoDelete(user.id, chatId, toDelete);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Encode user's message ID in callback data so cancel/add can delete it
|
||||
const umidSuffix = userMsgId ? `:umid:${userMsgId}` : "";
|
||||
const keyboard = {
|
||||
inline_keyboard: [
|
||||
...meds.map((med) => [
|
||||
{
|
||||
text: `${med.name} (${med.dose})`,
|
||||
callback_data: `add:${med.id}${umidSuffix}`,
|
||||
},
|
||||
]),
|
||||
[
|
||||
{
|
||||
text: "Abbrechen",
|
||||
callback_data: `cancel_add${umidSuffix}`,
|
||||
},
|
||||
],
|
||||
],
|
||||
};
|
||||
const resp = await sendTelegramMessage(
|
||||
botToken,
|
||||
chatId,
|
||||
"<b>Welches Medikament eingenommen?</b>",
|
||||
{ parseMode: "HTML", replyMarkup: keyboard },
|
||||
);
|
||||
// Fallback auto-delete if user never interacts with the selection
|
||||
const toDelete = [userMsgId, resp.messageId].filter(
|
||||
(id): id is number => id != null,
|
||||
);
|
||||
if (toDelete.length > 0) {
|
||||
await scheduleAutoDelete(user.id, chatId, toDelete);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Greeting responses
|
||||
const greetings = ["hi", "hallo", "hey", "moin"];
|
||||
const lowerText = text.toLowerCase();
|
||||
const matchedGreeting = greetings.find((g) => lowerText === g);
|
||||
if (matchedGreeting) {
|
||||
const userMsgId = message?.message_id;
|
||||
const reply = text.charAt(0).toUpperCase() + text.slice(1).toLowerCase();
|
||||
const resp = await sendTelegramMessage(botToken, chatId, `${reply}! 👋`);
|
||||
const toDelete = [userMsgId, resp.messageId].filter(
|
||||
(id): id is number => id != null,
|
||||
);
|
||||
if (toDelete.length > 0) {
|
||||
await scheduleAutoDelete(user.id, chatId, toDelete);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (!/^genommen\b/i.test(text)) return;
|
||||
|
||||
const userMsgId = message?.message_id;
|
||||
const nameInput = text.replace(/^genommen\b/i, "").trim();
|
||||
|
||||
let medicationId: string | null = null;
|
||||
if (nameInput) {
|
||||
const med = await prisma.medication.findFirst({
|
||||
where: {
|
||||
userId: user.id,
|
||||
active: true,
|
||||
name: { equals: nameInput, mode: "insensitive" },
|
||||
},
|
||||
select: { id: true },
|
||||
});
|
||||
medicationId = med?.id ?? null;
|
||||
} else {
|
||||
const meds = await prisma.medication.findMany({
|
||||
where: { userId: user.id, active: true },
|
||||
select: { id: true, name: true },
|
||||
orderBy: { name: "asc" },
|
||||
take: 2,
|
||||
});
|
||||
if (meds.length === 1) {
|
||||
medicationId = meds[0].id;
|
||||
} else {
|
||||
const resp = await sendTelegramMessage(
|
||||
botToken,
|
||||
chatId,
|
||||
"Bitte Medikament angeben, z.B. <b>genommen Ramipril</b>.",
|
||||
);
|
||||
const toDelete = [userMsgId, resp.messageId].filter(
|
||||
(id): id is number => id != null,
|
||||
);
|
||||
if (toDelete.length > 0) {
|
||||
await scheduleAutoDelete(user.id, chatId, toDelete);
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (!medicationId) {
|
||||
const resp = await sendTelegramMessage(
|
||||
botToken,
|
||||
chatId,
|
||||
"Medikament nicht gefunden. Bitte Namen exakt wie in HealthLog senden.",
|
||||
);
|
||||
const toDelete = [userMsgId, resp.messageId].filter(
|
||||
(id): id is number => id != null,
|
||||
);
|
||||
if (toDelete.length > 0) {
|
||||
await scheduleAutoDelete(user.id, chatId, toDelete);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const idempotencyKey =
|
||||
`telegram:text:${update.update_id}:${medicationId}`.slice(0, 128);
|
||||
const result = await markMedicationTaken(
|
||||
user.id,
|
||||
medicationId,
|
||||
idempotencyKey,
|
||||
);
|
||||
const resp = await sendTelegramMessage(
|
||||
botToken,
|
||||
chatId,
|
||||
result.ok
|
||||
? `✅ ${escapeHtml(result.message)}`
|
||||
: `⚠️ ${escapeHtml(result.message)}`,
|
||||
);
|
||||
const toDelete = [userMsgId, resp.messageId].filter(
|
||||
(id): id is number => id != null,
|
||||
);
|
||||
if (toDelete.length > 0) {
|
||||
await scheduleAutoDelete(user.id, chatId, toDelete);
|
||||
}
|
||||
}
|
||||
|
||||
export const POST = apiHandler(async (request: NextRequest) => {
|
||||
annotate({ action: { name: "telegram.webhook" } });
|
||||
|
||||
const ip = getClientIp(request);
|
||||
const rl = await checkRateLimit(`telegram-webhook:${ip}`, 120, 60 * 1000);
|
||||
if (!rl.allowed) {
|
||||
return NextResponse.json(
|
||||
{ status: "rate_limited" },
|
||||
{ status: 429, headers: rateLimitHeaders(rl) },
|
||||
);
|
||||
}
|
||||
|
||||
if (!hasValidSecret(request)) {
|
||||
return NextResponse.json({ status: "unauthorized" }, { status: 401 });
|
||||
}
|
||||
|
||||
getEvent()?.setAuth({ auth_method: "telegram_webhook" });
|
||||
|
||||
let update: TelegramUpdate;
|
||||
try {
|
||||
update = (await request.json()) as TelegramUpdate;
|
||||
} catch {
|
||||
return NextResponse.json({ status: "invalid json" }, { status: 200 });
|
||||
}
|
||||
if (!update || typeof update.update_id !== "number") {
|
||||
return NextResponse.json({ status: "ignored" }, { status: 200 });
|
||||
}
|
||||
|
||||
annotate({ meta: { update_id: update.update_id } });
|
||||
|
||||
if (update.callback_query) {
|
||||
await handleCallback(update);
|
||||
return NextResponse.json({ status: "ok" }, { status: 200 });
|
||||
}
|
||||
|
||||
if (update.message?.text) {
|
||||
await handleTextMessage(update);
|
||||
return NextResponse.json({ status: "ok" }, { status: 200 });
|
||||
}
|
||||
|
||||
return NextResponse.json({ status: "ignored" }, { status: 200 });
|
||||
});
|
||||
|
||||
export const GET = apiHandler(async (request: NextRequest) => {
|
||||
annotate({ action: { name: "telegram.webhook.verify" } });
|
||||
|
||||
if (!hasValidSecret(request)) {
|
||||
return NextResponse.json({ status: "unauthorized" }, { status: 401 });
|
||||
}
|
||||
getEvent()?.setAuth({ auth_method: "telegram_webhook" });
|
||||
return NextResponse.json({ status: "ok" }, { status: 200 });
|
||||
});
|
||||
@@ -0,0 +1,33 @@
|
||||
import { prisma } from "@/lib/db";
|
||||
import { apiHandler, requireAuth } from "@/lib/api-handler";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
import { apiSuccess, apiError } from "@/lib/api-response";
|
||||
import { isApiGloballyEnabled } from "@/lib/app-settings";
|
||||
|
||||
type RouteParams = { params: Promise<{ id: string }> };
|
||||
|
||||
/**
|
||||
* Revoke an API token.
|
||||
*/
|
||||
export const DELETE = apiHandler(async (_request: Request, { params }: RouteParams) => {
|
||||
const { user } = await requireAuth();
|
||||
annotate({ action: { name: "tokens.revoke" } });
|
||||
|
||||
if (!(await isApiGloballyEnabled())) {
|
||||
return apiError("API ist global deaktiviert", 403);
|
||||
}
|
||||
|
||||
const { id } = await params;
|
||||
const token = await prisma.apiToken.findUnique({ where: { id } });
|
||||
|
||||
if (!token || token.userId !== user.id) {
|
||||
return apiError("Token nicht gefunden", 404);
|
||||
}
|
||||
|
||||
await prisma.apiToken.update({
|
||||
where: { id },
|
||||
data: { revoked: true },
|
||||
});
|
||||
|
||||
return apiSuccess({ revoked: true });
|
||||
});
|
||||
@@ -0,0 +1,77 @@
|
||||
import { prisma } from "@/lib/db";
|
||||
import { apiHandler, requireAuth } from "@/lib/api-handler";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
import { apiSuccess, apiError, safeJson } from "@/lib/api-response";
|
||||
import { hashToken } from "@/lib/auth/hmac";
|
||||
import { isApiGloballyEnabled } from "@/lib/app-settings";
|
||||
import { randomBytes } from "node:crypto";
|
||||
import { NextRequest } from "next/server";
|
||||
import { z } from "zod/v4";
|
||||
|
||||
const createTokenSchema = z.object({
|
||||
name: z.string().min(1, "Name erforderlich").max(100),
|
||||
expiresInDays: z.number().int().min(1).max(365).optional(),
|
||||
});
|
||||
|
||||
export const GET = apiHandler(async () => {
|
||||
const { user } = await requireAuth();
|
||||
annotate({ action: { name: "tokens.list" } });
|
||||
|
||||
if (!(await isApiGloballyEnabled())) {
|
||||
return apiError("API ist global deaktiviert", 403);
|
||||
}
|
||||
|
||||
const tokens = await prisma.apiToken.findMany({
|
||||
where: { userId: user.id },
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
permissions: true,
|
||||
lastUsedAt: true,
|
||||
expiresAt: true,
|
||||
createdAt: true,
|
||||
revoked: true,
|
||||
},
|
||||
orderBy: { createdAt: "desc" },
|
||||
});
|
||||
|
||||
return apiSuccess(tokens);
|
||||
});
|
||||
|
||||
export const POST = apiHandler(async (request: NextRequest) => {
|
||||
const { user } = await requireAuth();
|
||||
annotate({ action: { name: "tokens.create" } });
|
||||
|
||||
if (!(await isApiGloballyEnabled())) {
|
||||
return apiError("API ist global deaktiviert", 403);
|
||||
}
|
||||
|
||||
const { data: body, error: jsonError } = await safeJson(request);
|
||||
|
||||
if (jsonError) return jsonError;
|
||||
const parsed = createTokenSchema.safeParse(body);
|
||||
if (!parsed.success) {
|
||||
return apiError(parsed.error.issues[0].message, 422);
|
||||
}
|
||||
|
||||
const { name, expiresInDays } = parsed.data;
|
||||
|
||||
// Generate a random token
|
||||
const rawToken = `hlk_${randomBytes(32).toString("hex")}`;
|
||||
const tokenHashValue = hashToken(rawToken);
|
||||
|
||||
await prisma.apiToken.create({
|
||||
data: {
|
||||
userId: user.id,
|
||||
name,
|
||||
tokenHash: tokenHashValue,
|
||||
permissions: ["medication:ingest"],
|
||||
expiresAt: expiresInDays
|
||||
? new Date(Date.now() + expiresInDays * 86400000)
|
||||
: null,
|
||||
},
|
||||
});
|
||||
|
||||
// Return the raw token ONCE — it can never be retrieved again
|
||||
return apiSuccess({ token: rawToken, name }, 201);
|
||||
});
|
||||
@@ -0,0 +1,114 @@
|
||||
import { prisma } from "@/lib/db";
|
||||
import { apiHandler, requireAuth } from "@/lib/api-handler";
|
||||
import { annotate, getEvent } from "@/lib/logging/context";
|
||||
import { auditLog } from "@/lib/auth/audit";
|
||||
import { encrypt } from "@/lib/crypto";
|
||||
import { exchangeCode } from "@/lib/withings/client";
|
||||
import { getUserWithingsCredentials } from "@/lib/withings/credentials";
|
||||
import { setupWebhook } from "@/lib/withings/sync";
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { timingSafeEqual } from "node:crypto";
|
||||
|
||||
/**
|
||||
* OAuth callback from Withings. Exchanges code for tokens and stores them.
|
||||
*/
|
||||
export const GET = apiHandler(async (request: NextRequest) => {
|
||||
const { user } = await requireAuth();
|
||||
annotate({ action: { name: "withings.callback" } });
|
||||
|
||||
const { searchParams } = new URL(request.url);
|
||||
const code = searchParams.get("code");
|
||||
const state = searchParams.get("state");
|
||||
const storedState = request.cookies.get("withings_state")?.value;
|
||||
|
||||
// CSRF check (timing-safe comparison to prevent timing attacks)
|
||||
if (
|
||||
!state ||
|
||||
!storedState ||
|
||||
state.length !== storedState.length ||
|
||||
!timingSafeEqual(Buffer.from(state), Buffer.from(storedState))
|
||||
) {
|
||||
return NextResponse.redirect(
|
||||
new URL(
|
||||
"/settings?withings=error&reason=state",
|
||||
process.env.NEXT_PUBLIC_APP_URL!,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
// Verify state contains current user's ID
|
||||
const [stateUserId] = state.split(":");
|
||||
if (stateUserId !== user.id) {
|
||||
return NextResponse.redirect(
|
||||
new URL(
|
||||
"/settings?withings=error&reason=user",
|
||||
process.env.NEXT_PUBLIC_APP_URL!,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
if (!code) {
|
||||
return NextResponse.redirect(
|
||||
new URL(
|
||||
"/settings?withings=error&reason=nocode",
|
||||
process.env.NEXT_PUBLIC_APP_URL!,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
const creds = await getUserWithingsCredentials(user.id);
|
||||
if (!creds) {
|
||||
return NextResponse.redirect(
|
||||
new URL(
|
||||
"/settings?withings=error&reason=nocreds",
|
||||
process.env.NEXT_PUBLIC_APP_URL!,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
const tokens = await exchangeCode(code, creds);
|
||||
|
||||
const expiresAt = new Date(Date.now() + tokens.expires_in * 1000);
|
||||
|
||||
// Upsert connection (user may be reconnecting)
|
||||
await prisma.withingsConnection.upsert({
|
||||
where: { userId: user.id },
|
||||
update: {
|
||||
withingsUserId: tokens.userid,
|
||||
accessToken: encrypt(tokens.access_token),
|
||||
refreshToken: encrypt(tokens.refresh_token),
|
||||
tokenExpiresAt: expiresAt,
|
||||
},
|
||||
create: {
|
||||
userId: user.id,
|
||||
withingsUserId: tokens.userid,
|
||||
accessToken: encrypt(tokens.access_token),
|
||||
refreshToken: encrypt(tokens.refresh_token),
|
||||
tokenExpiresAt: expiresAt,
|
||||
},
|
||||
});
|
||||
|
||||
// Subscribe to webhooks in background
|
||||
setupWebhook(user.id).catch((err) => getEvent()?.addWarning("Webhook setup failed: " + err));
|
||||
|
||||
await auditLog("withings.connect", {
|
||||
userId: user.id,
|
||||
details: { withingsUserId: tokens.userid },
|
||||
});
|
||||
|
||||
const response = NextResponse.redirect(
|
||||
new URL("/settings?withings=connected", process.env.NEXT_PUBLIC_APP_URL!),
|
||||
);
|
||||
response.cookies.delete("withings_state");
|
||||
return response;
|
||||
} catch (err) {
|
||||
getEvent()?.setError(err);
|
||||
return NextResponse.redirect(
|
||||
new URL(
|
||||
"/settings?withings=error&reason=token",
|
||||
process.env.NEXT_PUBLIC_APP_URL!,
|
||||
),
|
||||
);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,40 @@
|
||||
import { apiHandler, requireAuth } from "@/lib/api-handler";
|
||||
import { apiError } from "@/lib/api-response";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
import { getAuthorizationUrl } from "@/lib/withings/client";
|
||||
import { getUserWithingsCredentials } from "@/lib/withings/credentials";
|
||||
import { randomBytes } from "node:crypto";
|
||||
import { NextResponse } from "next/server";
|
||||
|
||||
/**
|
||||
* Redirects the user to Withings OAuth authorization page.
|
||||
* State param = userId:random for CSRF protection.
|
||||
*/
|
||||
export const GET = apiHandler(async () => {
|
||||
const { user } = await requireAuth();
|
||||
annotate({ action: { name: "withings.connect" } });
|
||||
|
||||
const creds = await getUserWithingsCredentials(user.id);
|
||||
if (!creds) {
|
||||
return apiError(
|
||||
"Bitte zuerst Withings Client-ID und Client-Secret in den Einstellungen hinterlegen.",
|
||||
400,
|
||||
);
|
||||
}
|
||||
|
||||
const stateNonce = randomBytes(16).toString("hex");
|
||||
const state = `${user.id}:${stateNonce}`;
|
||||
|
||||
const url = getAuthorizationUrl(state, creds);
|
||||
|
||||
const response = NextResponse.redirect(url);
|
||||
response.cookies.set("withings_state", state, {
|
||||
httpOnly: true,
|
||||
secure: process.env.NODE_ENV === "production",
|
||||
sameSite: "lax",
|
||||
maxAge: 600,
|
||||
path: "/",
|
||||
});
|
||||
|
||||
return response;
|
||||
});
|
||||
@@ -0,0 +1,80 @@
|
||||
import { prisma } from "@/lib/db";
|
||||
import { apiHandler, requireAuth } from "@/lib/api-handler";
|
||||
import { apiSuccess, apiError, safeJson } from "@/lib/api-response";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
import { encrypt } from "@/lib/crypto";
|
||||
import { withingsCredentialsSchema } from "@/lib/validations/withings";
|
||||
import { NextRequest } from "next/server";
|
||||
import { z } from "zod/v4";
|
||||
|
||||
/**
|
||||
* Check if user has Withings credentials stored.
|
||||
*/
|
||||
export const GET = apiHandler(async () => {
|
||||
const { user } = await requireAuth();
|
||||
annotate({ action: { name: "withings.credentials.get" } });
|
||||
|
||||
const dbUser = await prisma.user.findUnique({
|
||||
where: { id: user.id },
|
||||
select: {
|
||||
withingsClientIdEncrypted: true,
|
||||
withingsClientSecretEncrypted: true,
|
||||
},
|
||||
});
|
||||
|
||||
return apiSuccess({
|
||||
hasCredentials:
|
||||
!!dbUser?.withingsClientIdEncrypted &&
|
||||
!!dbUser?.withingsClientSecretEncrypted,
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* Save Withings API credentials (encrypted).
|
||||
*/
|
||||
export const PUT = apiHandler(async (request: NextRequest) => {
|
||||
const { user } = await requireAuth();
|
||||
annotate({ action: { name: "withings.credentials.update" } });
|
||||
|
||||
const { data: body, error: jsonError } = await safeJson(request);
|
||||
|
||||
if (jsonError) return jsonError;
|
||||
const result = z.safeParse(withingsCredentialsSchema, body);
|
||||
if (!result.success) {
|
||||
return apiError("Client-ID und Client-Secret sind erforderlich", 422);
|
||||
}
|
||||
|
||||
await prisma.user.update({
|
||||
where: { id: user.id },
|
||||
data: {
|
||||
withingsClientIdEncrypted: encrypt(result.data.clientId),
|
||||
withingsClientSecretEncrypted: encrypt(result.data.clientSecret),
|
||||
},
|
||||
});
|
||||
|
||||
return apiSuccess({ updated: true });
|
||||
});
|
||||
|
||||
/**
|
||||
* Delete Withings credentials and disconnect.
|
||||
*/
|
||||
export const DELETE = apiHandler(async () => {
|
||||
const { user } = await requireAuth();
|
||||
annotate({ action: { name: "withings.credentials.delete" } });
|
||||
|
||||
// Remove connection first
|
||||
await prisma.withingsConnection
|
||||
.delete({ where: { userId: user.id } })
|
||||
.catch(() => {});
|
||||
|
||||
// Remove credentials
|
||||
await prisma.user.update({
|
||||
where: { id: user.id },
|
||||
data: {
|
||||
withingsClientIdEncrypted: null,
|
||||
withingsClientSecretEncrypted: null,
|
||||
},
|
||||
});
|
||||
|
||||
return apiSuccess({ deleted: true });
|
||||
});
|
||||
@@ -0,0 +1,43 @@
|
||||
import { prisma } from "@/lib/db";
|
||||
import { apiHandler, requireAuth } from "@/lib/api-handler";
|
||||
import { auditLog } from "@/lib/auth/audit";
|
||||
import { apiSuccess, apiError } from "@/lib/api-response";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
import { decrypt } from "@/lib/crypto";
|
||||
import { unsubscribeWebhook } from "@/lib/withings/client";
|
||||
import { getWithingsWebhookCallbackUrl } from "@/lib/withings/sync";
|
||||
|
||||
/**
|
||||
* Disconnect Withings integration for the current user.
|
||||
*/
|
||||
export const POST = apiHandler(async () => {
|
||||
const { user } = await requireAuth();
|
||||
annotate({ action: { name: "withings.disconnect" } });
|
||||
|
||||
const connection = await prisma.withingsConnection.findUnique({
|
||||
where: { userId: user.id },
|
||||
});
|
||||
|
||||
if (!connection) {
|
||||
return apiError("Keine Withings-Verbindung vorhanden", 404);
|
||||
}
|
||||
|
||||
// Try to unsubscribe webhook (best-effort)
|
||||
try {
|
||||
const accessToken = decrypt(connection.accessToken);
|
||||
const callbackUrl = getWithingsWebhookCallbackUrl();
|
||||
await unsubscribeWebhook(accessToken, callbackUrl);
|
||||
} catch {
|
||||
// Ignore — token might be expired
|
||||
}
|
||||
|
||||
await prisma.withingsConnection.delete({
|
||||
where: { userId: user.id },
|
||||
});
|
||||
|
||||
await auditLog("withings.disconnect", {
|
||||
userId: user.id,
|
||||
});
|
||||
|
||||
return apiSuccess({ disconnected: true });
|
||||
});
|
||||
@@ -0,0 +1,89 @@
|
||||
import { prisma } from "@/lib/db";
|
||||
import { apiHandler, requireAuth } from "@/lib/api-handler";
|
||||
import { annotate, getEvent } from "@/lib/logging/context";
|
||||
import { apiSuccess } from "@/lib/api-response";
|
||||
import { decrypt, encrypt } from "@/lib/crypto";
|
||||
import { getUserWithingsCredentials } from "@/lib/withings/credentials";
|
||||
import { refreshAccessToken } from "@/lib/withings/client";
|
||||
|
||||
/**
|
||||
* Get Withings connection status for the current user.
|
||||
* "configured" now checks per-user credentials instead of env vars.
|
||||
*/
|
||||
export const GET = apiHandler(async () => {
|
||||
const { user } = await requireAuth();
|
||||
annotate({ action: { name: "withings.status" } });
|
||||
|
||||
const dbUser = await prisma.user.findUnique({
|
||||
where: { id: user.id },
|
||||
select: {
|
||||
withingsClientIdEncrypted: true,
|
||||
withingsClientSecretEncrypted: true,
|
||||
},
|
||||
});
|
||||
|
||||
const configured =
|
||||
!!dbUser?.withingsClientIdEncrypted && !!dbUser?.withingsClientSecretEncrypted;
|
||||
|
||||
const connection = await prisma.withingsConnection.findUnique({
|
||||
where: { userId: user.id },
|
||||
select: {
|
||||
withingsUserId: true,
|
||||
accessToken: true,
|
||||
refreshToken: true,
|
||||
lastSyncedAt: true,
|
||||
tokenExpiresAt: true,
|
||||
createdAt: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (!connection) {
|
||||
return apiSuccess({ connected: false, configured });
|
||||
}
|
||||
|
||||
let tokenExpiresAt = connection.tokenExpiresAt;
|
||||
const now = Date.now();
|
||||
let tokenExpired = tokenExpiresAt.getTime() <= now;
|
||||
let tokenRefreshFailed = false;
|
||||
|
||||
// Keep status reliable: if token is expired (or about to expire), refresh it
|
||||
// before reporting "abgelaufen" in the UI.
|
||||
const shouldRefresh = tokenExpiresAt.getTime() - 60_000 <= now;
|
||||
if (shouldRefresh) {
|
||||
try {
|
||||
const creds = await getUserWithingsCredentials(user.id);
|
||||
if (creds) {
|
||||
const refreshToken = decrypt(connection.refreshToken);
|
||||
const refreshed = await refreshAccessToken(refreshToken, creds);
|
||||
tokenExpiresAt = new Date(Date.now() + refreshed.expires_in * 1000);
|
||||
tokenExpired = tokenExpiresAt.getTime() <= Date.now();
|
||||
|
||||
await prisma.withingsConnection.update({
|
||||
where: { userId: user.id },
|
||||
data: {
|
||||
accessToken: encrypt(refreshed.access_token),
|
||||
refreshToken: encrypt(refreshed.refresh_token),
|
||||
tokenExpiresAt,
|
||||
},
|
||||
});
|
||||
} else if (tokenExpired) {
|
||||
tokenRefreshFailed = true;
|
||||
}
|
||||
} catch (error) {
|
||||
if (tokenExpired) {
|
||||
tokenRefreshFailed = true;
|
||||
}
|
||||
getEvent()?.addWarning("Token refresh failed");
|
||||
}
|
||||
}
|
||||
|
||||
return apiSuccess({
|
||||
connected: true,
|
||||
configured,
|
||||
lastSyncedAt: connection.lastSyncedAt,
|
||||
connectedAt: connection.createdAt,
|
||||
tokenExpired,
|
||||
tokenRefreshFailed,
|
||||
tokenExpiresAt,
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,26 @@
|
||||
import { apiHandler, requireAuth } from "@/lib/api-handler";
|
||||
import { apiSuccess } from "@/lib/api-response";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
import { syncUserMeasurements } from "@/lib/withings/sync";
|
||||
import { NextRequest } from "next/server";
|
||||
|
||||
/**
|
||||
* Manually trigger a Withings sync for the current user.
|
||||
*/
|
||||
export const POST = apiHandler(async (request: NextRequest) => {
|
||||
const { user } = await requireAuth();
|
||||
annotate({ action: { name: "withings.sync" } });
|
||||
|
||||
let fullSync = false;
|
||||
try {
|
||||
const body = await request.json();
|
||||
fullSync = body?.fullSync === true;
|
||||
} catch {
|
||||
// no body provided -> default incremental sync
|
||||
}
|
||||
|
||||
const imported = await syncUserMeasurements(user.id, {
|
||||
fullSync,
|
||||
});
|
||||
return apiSuccess({ imported, fullSync });
|
||||
});
|
||||
@@ -0,0 +1,105 @@
|
||||
import { timingSafeEqual } from "node:crypto";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { syncUserMeasurements } from "@/lib/withings/sync";
|
||||
import { checkRateLimit, rateLimitHeaders } from "@/lib/rate-limit";
|
||||
import { getClientIp, safeJson } from "@/lib/api-response";
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { apiHandler } from "@/lib/api-handler";
|
||||
import { annotate, getEvent } from "@/lib/logging/context";
|
||||
|
||||
function hasValidWebhookSecret(request: NextRequest): boolean {
|
||||
const expected = process.env.WITHINGS_WEBHOOK_SECRET;
|
||||
if (!expected) {
|
||||
getEvent()?.addWarning("WITHINGS_WEBHOOK_SECRET not configured");
|
||||
return false;
|
||||
}
|
||||
const received = request.nextUrl.searchParams.get("secret");
|
||||
if (!received) return false;
|
||||
const a = Buffer.from(expected, "utf8");
|
||||
const b = Buffer.from(received, "utf8");
|
||||
if (a.length !== b.length) return false;
|
||||
return timingSafeEqual(a, b);
|
||||
}
|
||||
|
||||
/**
|
||||
* Withings webhook notification endpoint.
|
||||
* Withings sends a POST when new measurements are available.
|
||||
* The webhook sends: userid, startdate, enddate, appli
|
||||
*/
|
||||
export const POST = apiHandler(async (request: NextRequest) => {
|
||||
annotate({ action: { name: "withings.webhook" } });
|
||||
|
||||
const ip = getClientIp(request);
|
||||
const rl = await checkRateLimit(`withings-webhook:${ip}`, 30, 60 * 1000);
|
||||
if (!rl.allowed) {
|
||||
return NextResponse.json(
|
||||
{ status: "rate_limited" },
|
||||
{ status: 429, headers: rateLimitHeaders(rl) },
|
||||
);
|
||||
}
|
||||
|
||||
if (!hasValidWebhookSecret(request)) {
|
||||
return NextResponse.json({ status: "unauthorized" }, { status: 401 });
|
||||
}
|
||||
|
||||
getEvent()?.setAuth({ auth_method: "webhook_secret" });
|
||||
|
||||
// Withings sends form-encoded or JSON depending on version
|
||||
const contentType = request.headers.get("content-type") ?? "";
|
||||
let withingsUserId: string | null = null;
|
||||
|
||||
if (contentType.includes("application/x-www-form-urlencoded")) {
|
||||
const formData = await request.formData();
|
||||
withingsUserId = formData.get("userid") as string;
|
||||
} else {
|
||||
const { data: body, error: jsonError } = await safeJson<{ userid?: string | number }>(request);
|
||||
if (jsonError) return jsonError;
|
||||
withingsUserId = body.userid?.toString() ?? null;
|
||||
}
|
||||
|
||||
if (!withingsUserId) {
|
||||
return NextResponse.json({ status: "ignored" }, { status: 200 });
|
||||
}
|
||||
|
||||
annotate({ meta: { withings_user_id: withingsUserId } });
|
||||
|
||||
// Find user by Withings user ID
|
||||
const connection = await prisma.withingsConnection.findFirst({
|
||||
where: { withingsUserId },
|
||||
});
|
||||
|
||||
if (!connection) {
|
||||
getEvent()?.addWarning("Webhook for unknown withings user: " + withingsUserId);
|
||||
return NextResponse.json({ status: "unknown_user" }, { status: 200 });
|
||||
}
|
||||
|
||||
// Sync measurements (non-blocking response for Withings)
|
||||
syncUserMeasurements(connection.userId).catch((err) => {
|
||||
getEvent()?.addWarning("Sync failed for user " + connection.userId + ": " + err);
|
||||
});
|
||||
|
||||
return NextResponse.json({ status: "ok" }, { status: 200 });
|
||||
});
|
||||
|
||||
/**
|
||||
* Withings sends a HEAD request to verify the webhook URL.
|
||||
*/
|
||||
export const HEAD = apiHandler(async (request: NextRequest) => {
|
||||
annotate({ action: { name: "withings.webhook.verify" } });
|
||||
|
||||
if (!hasValidWebhookSecret(request)) {
|
||||
return new NextResponse(null, { status: 401 });
|
||||
}
|
||||
getEvent()?.setAuth({ auth_method: "webhook_secret" });
|
||||
return new NextResponse(null, { status: 200 });
|
||||
});
|
||||
|
||||
export const GET = apiHandler(async (request: NextRequest) => {
|
||||
annotate({ action: { name: "withings.webhook.verify" } });
|
||||
|
||||
if (!hasValidWebhookSecret(request)) {
|
||||
return NextResponse.json({ status: "unauthorized" }, { status: 401 });
|
||||
}
|
||||
getEvent()?.setAuth({ auth_method: "webhook_secret" });
|
||||
return NextResponse.json({ status: "ok" }, { status: 200 });
|
||||
});
|
||||
@@ -0,0 +1,230 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { useRouter, useSearchParams } from "next/navigation";
|
||||
import { useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { KeyRound, Lock, Loader2 } from "lucide-react";
|
||||
import { Logo } from "@/components/ui/logo";
|
||||
import Link from "next/link";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { Separator } from "@/components/ui/separator";
|
||||
import { useTranslations } from "@/lib/i18n/context";
|
||||
|
||||
export default function LoginPage() {
|
||||
const router = useRouter();
|
||||
const searchParams = useSearchParams();
|
||||
const queryClient = useQueryClient();
|
||||
const { t } = useTranslations();
|
||||
const [mode, setMode] = useState<"passkey" | "password">("passkey");
|
||||
const [email, setEmail] = useState("");
|
||||
const [password, setPassword] = useState("");
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const { data: registrationEnabled } = useQuery({
|
||||
queryKey: ["auth", "registration-status"],
|
||||
queryFn: async () => {
|
||||
const res = await fetch("/api/auth/registration-status", {
|
||||
cache: "no-store",
|
||||
});
|
||||
if (!res.ok) return true;
|
||||
const json = await res.json();
|
||||
return Boolean(json.data?.registrationEnabled ?? true);
|
||||
},
|
||||
staleTime: 60 * 1000,
|
||||
});
|
||||
|
||||
function getRedirectTarget(): string {
|
||||
const next = searchParams.get("next");
|
||||
if (!next) return "/";
|
||||
// Prevent open redirects: only allow local absolute paths.
|
||||
if (next.startsWith("/") && !next.startsWith("//")) {
|
||||
return next;
|
||||
}
|
||||
return "/";
|
||||
}
|
||||
|
||||
async function handlePasskeyLogin() {
|
||||
setError(null);
|
||||
setLoading(true);
|
||||
|
||||
try {
|
||||
const optRes = await fetch("/api/auth/passkey/login-options", {
|
||||
method: "POST",
|
||||
});
|
||||
const optJson = await optRes.json();
|
||||
if (!optRes.ok) {
|
||||
setError(optJson.error);
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
|
||||
const { options, challengeId } = optJson.data;
|
||||
const { startAuthentication } = await import(
|
||||
"@simplewebauthn/browser"
|
||||
);
|
||||
const credential = await startAuthentication({ optionsJSON: options });
|
||||
|
||||
const verifyRes = await fetch("/api/auth/passkey/login-verify", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ challengeId, credential }),
|
||||
});
|
||||
|
||||
const verifyJson = await verifyRes.json();
|
||||
if (!verifyRes.ok) {
|
||||
setError(verifyJson.error || t("auth.loginFailed"));
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
|
||||
await queryClient.invalidateQueries({ queryKey: ["auth"] });
|
||||
router.push(getRedirectTarget());
|
||||
} catch {
|
||||
setError(t("auth.passkeyFailed"));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function handlePasswordLogin(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
setError(null);
|
||||
setLoading(true);
|
||||
|
||||
try {
|
||||
const res = await fetch("/api/auth/login", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ email, password }),
|
||||
});
|
||||
|
||||
const json = await res.json();
|
||||
if (!res.ok) {
|
||||
setError(json.error);
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
|
||||
await queryClient.invalidateQueries({ queryKey: ["auth"] });
|
||||
router.push(getRedirectTarget());
|
||||
} catch {
|
||||
setError(t("auth.loginFailed"));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="w-full max-w-sm">
|
||||
<div className="border-border bg-card rounded-xl border p-8 shadow-lg shadow-black/20">
|
||||
<div className="flex flex-col items-center gap-3 text-center">
|
||||
<div className="bg-primary/10 flex h-12 w-12 items-center justify-center rounded-lg">
|
||||
<Logo className="text-primary" size={28} />
|
||||
</div>
|
||||
<div>
|
||||
<h1 className="text-xl font-bold tracking-tight">HealthLog</h1>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="mt-8 space-y-4">
|
||||
<Button
|
||||
onClick={handlePasskeyLogin}
|
||||
className="w-full"
|
||||
disabled={loading}
|
||||
>
|
||||
{loading && mode === "passkey" ? (
|
||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||
) : (
|
||||
<KeyRound className="mr-2 h-4 w-4" />
|
||||
)}
|
||||
{t("auth.loginWithPasskey")}
|
||||
</Button>
|
||||
|
||||
<div className="flex items-center gap-3">
|
||||
<Separator className="flex-1" />
|
||||
<span className="text-muted-foreground text-xs">
|
||||
{t("common.or")}
|
||||
</span>
|
||||
<Separator className="flex-1" />
|
||||
</div>
|
||||
|
||||
{mode === "passkey" ? (
|
||||
<Button
|
||||
variant="outline"
|
||||
className="w-full"
|
||||
onClick={() => setMode("password")}
|
||||
>
|
||||
<Lock className="mr-2 h-4 w-4" />
|
||||
{t("auth.loginWithPassword")}
|
||||
</Button>
|
||||
) : (
|
||||
<form onSubmit={handlePasswordLogin} className="space-y-3">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="email">{t("auth.emailOrUsername")}</Label>
|
||||
<Input
|
||||
id="email"
|
||||
type="text"
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
required
|
||||
autoComplete="username"
|
||||
placeholder={t("auth.emailOrUsernamePlaceholder")}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="password">{t("auth.password")}</Label>
|
||||
<Input
|
||||
id="password"
|
||||
type="password"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
required
|
||||
autoComplete="current-password"
|
||||
placeholder="********"
|
||||
/>
|
||||
</div>
|
||||
<Button type="submit" className="w-full" disabled={loading}>
|
||||
{loading && mode === "password" ? (
|
||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||
) : (
|
||||
<Lock className="mr-2 h-4 w-4" />
|
||||
)}
|
||||
{t("auth.login")}
|
||||
</Button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setMode("passkey")}
|
||||
className="text-muted-foreground hover:text-foreground w-full text-center text-xs"
|
||||
>
|
||||
{t("auth.backToPasskey")}
|
||||
</button>
|
||||
</form>
|
||||
)}
|
||||
|
||||
{error && (
|
||||
<div
|
||||
role="alert"
|
||||
className="bg-destructive/10 text-destructive rounded-lg p-3 text-sm"
|
||||
>
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{registrationEnabled === true && (
|
||||
<p className="text-muted-foreground text-center text-xs">
|
||||
{t("auth.noAccount")}{" "}
|
||||
<Link
|
||||
href="/auth/register"
|
||||
className="text-primary hover:underline"
|
||||
>
|
||||
{t("auth.register")}
|
||||
</Link>
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useQueryClient } from "@tanstack/react-query";
|
||||
import { Loader2, UserPlus } from "lucide-react";
|
||||
import { Logo } from "@/components/ui/logo";
|
||||
import Link from "next/link";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { PasswordStrength } from "@/components/ui/password-strength";
|
||||
import { useTranslations } from "@/lib/i18n/context";
|
||||
|
||||
export default function RegisterPage() {
|
||||
const router = useRouter();
|
||||
const queryClient = useQueryClient();
|
||||
const [email, setEmail] = useState("");
|
||||
const [username, setUsername] = useState("");
|
||||
const [password, setPassword] = useState("");
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const { t } = useTranslations();
|
||||
|
||||
async function handleRegister(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
setError(null);
|
||||
setLoading(true);
|
||||
|
||||
try {
|
||||
const res = await fetch("/api/auth/register", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ email, username, password }),
|
||||
});
|
||||
|
||||
const json = await res.json();
|
||||
if (!res.ok) {
|
||||
setError(json.error);
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
|
||||
await queryClient.invalidateQueries({ queryKey: ["auth"] });
|
||||
router.push("/");
|
||||
} catch {
|
||||
setError(t("auth.registerFailed"));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="w-full max-w-sm">
|
||||
<div className="border-border bg-card rounded-xl border p-8 shadow-lg shadow-black/20">
|
||||
<div className="flex flex-col items-center gap-3 text-center">
|
||||
<div className="bg-primary/10 flex h-12 w-12 items-center justify-center rounded-lg">
|
||||
<Logo className="text-primary" size={28} />
|
||||
</div>
|
||||
<div>
|
||||
<h1 className="text-xl font-bold tracking-tight">
|
||||
{t("auth.createAccount")}
|
||||
</h1>
|
||||
<p className="text-muted-foreground mt-1 text-sm">
|
||||
{t("auth.newAccount")}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<form onSubmit={handleRegister} className="mt-8 space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="email">{t("auth.email")}</Label>
|
||||
<Input
|
||||
id="email"
|
||||
type="email"
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
placeholder={t("auth.emailPlaceholder")}
|
||||
required
|
||||
autoComplete="email"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="username">{t("auth.username")}</Label>
|
||||
<Input
|
||||
id="username"
|
||||
type="text"
|
||||
value={username}
|
||||
onChange={(e) => setUsername(e.target.value)}
|
||||
placeholder="user"
|
||||
required
|
||||
autoComplete="username"
|
||||
minLength={3}
|
||||
maxLength={30}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="password">{t("auth.password")}</Label>
|
||||
<Input
|
||||
id="password"
|
||||
type="password"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
placeholder={t("auth.passwordMinLength")}
|
||||
required
|
||||
autoComplete="new-password"
|
||||
/>
|
||||
<PasswordStrength password={password} />
|
||||
<p className="text-muted-foreground text-xs">
|
||||
{t("auth.passkeySetupLater")}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<div role="alert" className="bg-destructive/10 text-destructive rounded-lg p-3 text-sm">
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<Button type="submit" className="w-full" disabled={loading}>
|
||||
{loading ? (
|
||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||
) : (
|
||||
<UserPlus className="mr-2 h-4 w-4" />
|
||||
)}
|
||||
{t("auth.register")}
|
||||
</Button>
|
||||
|
||||
<p className="text-muted-foreground text-center text-xs">
|
||||
{t("auth.hasAccount")}{" "}
|
||||
<Link href="/auth/login" className="text-primary hover:underline">
|
||||
{t("auth.login")}
|
||||
</Link>
|
||||
</p>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,202 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useRef } from "react";
|
||||
import { useAuth } from "@/hooks/use-auth";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { Loader2, Upload, X, CheckCircle2, ImageIcon, Bug } from "lucide-react";
|
||||
import { useTranslations } from "@/lib/i18n/context";
|
||||
|
||||
export default function BugReportPage() {
|
||||
const { isAuthenticated } = useAuth();
|
||||
const [description, setDescription] = useState("");
|
||||
const [screenshot, setScreenshot] = useState<string | null>(null);
|
||||
const [screenshotName, setScreenshotName] = useState<string | null>(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [result, setResult] = useState<{
|
||||
type: "success" | "error";
|
||||
message: string;
|
||||
} | null>(null);
|
||||
const fileRef = useRef<HTMLInputElement>(null);
|
||||
const { t } = useTranslations();
|
||||
|
||||
async function handleScreenshot(e: React.ChangeEvent<HTMLInputElement>) {
|
||||
const file = e.target.files?.[0];
|
||||
if (!file) return;
|
||||
|
||||
if (!file.type.startsWith("image/")) {
|
||||
setResult({ type: "error", message: t("bugreport.imageOnly") });
|
||||
return;
|
||||
}
|
||||
|
||||
if (file.size > 5 * 1024 * 1024) {
|
||||
setResult({
|
||||
type: "error",
|
||||
message: t("bugreport.tooLarge"),
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const reader = new FileReader();
|
||||
reader.onload = () => {
|
||||
setScreenshot(reader.result as string);
|
||||
setScreenshotName(file.name);
|
||||
};
|
||||
reader.readAsDataURL(file);
|
||||
}
|
||||
|
||||
function removeScreenshot() {
|
||||
setScreenshot(null);
|
||||
setScreenshotName(null);
|
||||
if (fileRef.current) fileRef.current.value = "";
|
||||
}
|
||||
|
||||
async function handleSubmit(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
setResult(null);
|
||||
setLoading(true);
|
||||
|
||||
try {
|
||||
const res = await fetch("/api/bugreport", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
description,
|
||||
...(screenshot ? { screenshot } : {}),
|
||||
}),
|
||||
});
|
||||
|
||||
const json = await res.json();
|
||||
if (res.ok) {
|
||||
setResult({
|
||||
type: "success",
|
||||
message: t("bugreport.success"),
|
||||
});
|
||||
setDescription("");
|
||||
removeScreenshot();
|
||||
} else {
|
||||
setResult({
|
||||
type: "error",
|
||||
message: json.error || t("bugreport.errorCreating"),
|
||||
});
|
||||
}
|
||||
} catch {
|
||||
setResult({ type: "error", message: t("common.networkError") });
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
if (!isAuthenticated) {
|
||||
return (
|
||||
<div className="mx-auto w-full max-w-6xl space-y-6">
|
||||
<h1 className="text-2xl font-bold tracking-tight">
|
||||
{t("bugreport.title")}
|
||||
</h1>
|
||||
<p className="text-muted-foreground text-sm">
|
||||
{t("bugreport.loginRequired")}
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="mx-auto w-full max-w-6xl space-y-6">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold tracking-tight">
|
||||
{t("bugreport.title")}
|
||||
</h1>
|
||||
<p className="text-muted-foreground text-sm">
|
||||
{t("bugreport.subtitle")}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="bg-card border-border w-full rounded-xl border p-6">
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="bug-desc">{t("bugreport.description")}</Label>
|
||||
<textarea
|
||||
id="bug-desc"
|
||||
value={description}
|
||||
onChange={(e) => setDescription(e.target.value)}
|
||||
placeholder=""
|
||||
required
|
||||
minLength={10}
|
||||
maxLength={5000}
|
||||
rows={9}
|
||||
className="border-input bg-background text-foreground placeholder:text-muted-foreground focus-visible:ring-ring w-full rounded-md border px-3 py-2 text-sm focus-visible:ring-2 focus-visible:outline-none"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label>{t("bugreport.screenshot")}</Label>
|
||||
<input
|
||||
ref={fileRef}
|
||||
type="file"
|
||||
accept="image/*"
|
||||
onChange={handleScreenshot}
|
||||
className="hidden"
|
||||
/>
|
||||
{screenshot ? (
|
||||
<div className="bg-muted/50 relative rounded-lg p-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<ImageIcon className="text-muted-foreground h-4 w-4" />
|
||||
<span className="flex-1 truncate text-sm">
|
||||
{screenshotName}
|
||||
</span>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-7 w-7"
|
||||
onClick={removeScreenshot}
|
||||
>
|
||||
<X className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
{/* eslint-disable-next-line @next/next/no-img-element */}
|
||||
<img
|
||||
src={screenshot}
|
||||
alt={t("bugreport.screenshotPreview")}
|
||||
className="mt-2 max-h-48 rounded border object-contain"
|
||||
/>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
{result && (
|
||||
<div
|
||||
className={`rounded-lg p-3 text-sm ${
|
||||
result.type === "success"
|
||||
? "bg-dracula-green/10 text-dracula-green"
|
||||
: "bg-destructive/10 text-destructive"
|
||||
}`}
|
||||
>
|
||||
{result.type === "success" && (
|
||||
<CheckCircle2 className="mr-2 inline h-4 w-4" />
|
||||
)}
|
||||
{result.message}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex items-center justify-between pt-2">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => fileRef.current?.click()}
|
||||
>
|
||||
<Upload className="mr-2 h-4 w-4" />
|
||||
{t("bugreport.attachScreenshot")}
|
||||
</Button>
|
||||
<Button type="submit" disabled={loading}>
|
||||
{loading && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
|
||||
<Bug className="mr-2 h-4 w-4" />
|
||||
{t("bugreport.submit")}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 9.4 KiB |
@@ -0,0 +1,168 @@
|
||||
@import "tailwindcss";
|
||||
@import "tw-animate-css";
|
||||
@import "shadcn/tailwind.css";
|
||||
|
||||
@custom-variant dark (&:is(.dark *));
|
||||
|
||||
@theme inline {
|
||||
--color-background: var(--background);
|
||||
--color-foreground: var(--foreground);
|
||||
--font-sans: var(--font-sans);
|
||||
--font-mono: var(--font-mono);
|
||||
--color-sidebar-ring: var(--sidebar-ring);
|
||||
--color-sidebar-border: var(--sidebar-border);
|
||||
--color-sidebar-accent-foreground: var(--sidebar-accent-foreground);
|
||||
--color-sidebar-accent: var(--sidebar-accent);
|
||||
--color-sidebar-primary-foreground: var(--sidebar-primary-foreground);
|
||||
--color-sidebar-primary: var(--sidebar-primary);
|
||||
--color-sidebar-foreground: var(--sidebar-foreground);
|
||||
--color-sidebar: var(--sidebar);
|
||||
--color-chart-5: var(--chart-5);
|
||||
--color-chart-4: var(--chart-4);
|
||||
--color-chart-3: var(--chart-3);
|
||||
--color-chart-2: var(--chart-2);
|
||||
--color-chart-1: var(--chart-1);
|
||||
--color-ring: var(--ring);
|
||||
--color-input: var(--input);
|
||||
--color-border: var(--border);
|
||||
--color-destructive: var(--destructive);
|
||||
--color-accent-foreground: var(--accent-foreground);
|
||||
--color-accent: var(--accent);
|
||||
--color-muted-foreground: var(--muted-foreground);
|
||||
--color-muted: var(--muted);
|
||||
--color-secondary-foreground: var(--secondary-foreground);
|
||||
--color-secondary: var(--secondary);
|
||||
--color-primary-foreground: var(--primary-foreground);
|
||||
--color-primary: var(--primary);
|
||||
--color-popover-foreground: var(--popover-foreground);
|
||||
--color-popover: var(--popover);
|
||||
--color-card-foreground: var(--card-foreground);
|
||||
--color-card: var(--card);
|
||||
--radius-sm: calc(var(--radius) - 4px);
|
||||
--radius-md: calc(var(--radius) - 2px);
|
||||
--radius-lg: var(--radius);
|
||||
--radius-xl: calc(var(--radius) + 4px);
|
||||
--radius-2xl: calc(var(--radius) + 8px);
|
||||
--radius-3xl: calc(var(--radius) + 12px);
|
||||
--radius-4xl: calc(var(--radius) + 16px);
|
||||
|
||||
/* Dracula semantic colors for charts */
|
||||
--color-dracula-purple: var(--dracula-purple);
|
||||
--color-dracula-pink: var(--dracula-pink);
|
||||
--color-dracula-green: var(--dracula-green);
|
||||
--color-dracula-cyan: var(--dracula-cyan);
|
||||
--color-dracula-orange: var(--dracula-orange);
|
||||
--color-dracula-red: var(--dracula-red);
|
||||
--color-dracula-yellow: var(--dracula-yellow);
|
||||
--color-dracula-lavender: var(--dracula-lavender);
|
||||
}
|
||||
|
||||
/*
|
||||
* Dracula Theme
|
||||
* Based on https://draculatheme.com/contribute
|
||||
* Mapped to shadcn/ui CSS variable system
|
||||
*/
|
||||
|
||||
/* ── Dracula palette (shared) ────────────────────── */
|
||||
:root {
|
||||
--dracula-bg: #282a36;
|
||||
--dracula-current: #44475a;
|
||||
--dracula-fg: #f8f8f2;
|
||||
--dracula-comment: #9aa3b3;
|
||||
--dracula-cyan: #8be9fd;
|
||||
--dracula-green: #50fa7b;
|
||||
--dracula-orange: #ffb86c;
|
||||
--dracula-pink: #ff79c6;
|
||||
--dracula-purple: #bd93f9;
|
||||
--dracula-red: #ff5555;
|
||||
--dracula-yellow: #f1fa8c;
|
||||
--dracula-lavender: #d6acff;
|
||||
|
||||
--radius: 0.625rem;
|
||||
}
|
||||
|
||||
/* ── Dark mode (default) ─────────────────────────── */
|
||||
:root.dark {
|
||||
--background: #282a36;
|
||||
--foreground: #f8f8f2;
|
||||
--card: #1e1f29;
|
||||
--card-foreground: #f8f8f2;
|
||||
--popover: #1e1f29;
|
||||
--popover-foreground: #f8f8f2;
|
||||
--primary: #bd93f9;
|
||||
--primary-foreground: #282a36;
|
||||
--secondary: #44475a;
|
||||
--secondary-foreground: #f8f8f2;
|
||||
--muted: #44475a;
|
||||
--muted-foreground: #f8f8f2;
|
||||
--accent: #44475a;
|
||||
--accent-foreground: #f8f8f2;
|
||||
--destructive: #ff5555;
|
||||
--border: #44475a;
|
||||
--input: #44475a;
|
||||
--ring: #bd93f9;
|
||||
--chart-1: #bd93f9;
|
||||
--chart-2: #50fa7b;
|
||||
--chart-3: #ff79c6;
|
||||
--chart-4: #8be9fd;
|
||||
--chart-5: #ffb86c;
|
||||
--sidebar: #1e1f29;
|
||||
--sidebar-foreground: #f8f8f2;
|
||||
--sidebar-primary: #bd93f9;
|
||||
--sidebar-primary-foreground: #f8f8f2;
|
||||
--sidebar-accent: #44475a;
|
||||
--sidebar-accent-foreground: #f8f8f2;
|
||||
--sidebar-border: #44475a;
|
||||
--sidebar-ring: #bd93f9;
|
||||
|
||||
color-scheme: dark;
|
||||
}
|
||||
|
||||
/* ── Light mode (Alucard — official Dracula light) ── */
|
||||
:root.light {
|
||||
--background: #f5f5f5;
|
||||
--foreground: #1f1f1f;
|
||||
--card: #ffffff;
|
||||
--card-foreground: #1f1f1f;
|
||||
--popover: #ffffff;
|
||||
--popover-foreground: #1f1f1f;
|
||||
--primary: #644ac9;
|
||||
--primary-foreground: #ffffff;
|
||||
--secondary: #dcdeef;
|
||||
--secondary-foreground: #1f1f1f;
|
||||
--muted: #dcdeef;
|
||||
--muted-foreground: #1f1f1f;
|
||||
--accent: #dcdeef;
|
||||
--accent-foreground: #1f1f1f;
|
||||
--destructive: #cb3a2a;
|
||||
--border: #cfcfde;
|
||||
--input: #cfcfde;
|
||||
--ring: #644ac9;
|
||||
--chart-1: #644ac9;
|
||||
--chart-2: #14720a;
|
||||
--chart-3: #a3134d;
|
||||
--chart-4: #036a96;
|
||||
--chart-5: #a34d14;
|
||||
--sidebar: #ffffff;
|
||||
--sidebar-foreground: #1f1f1f;
|
||||
--sidebar-primary: #644ac9;
|
||||
--sidebar-primary-foreground: #ffffff;
|
||||
--sidebar-accent: #dcdeef;
|
||||
--sidebar-accent-foreground: #1f1f1f;
|
||||
--sidebar-border: #cfcfde;
|
||||
--sidebar-ring: #644ac9;
|
||||
|
||||
color-scheme: light;
|
||||
}
|
||||
|
||||
@layer base {
|
||||
* {
|
||||
@apply border-border outline-ring/50;
|
||||
}
|
||||
body {
|
||||
@apply bg-background text-foreground;
|
||||
}
|
||||
p {
|
||||
color: var(--foreground);
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,82 @@
|
||||
import type { Metadata, Viewport } from "next";
|
||||
import { Inter } from "next/font/google";
|
||||
import { headers } from "next/headers";
|
||||
import "./globals.css";
|
||||
import { Providers } from "@/components/providers";
|
||||
import { AuthShell } from "@/components/layout/auth-shell";
|
||||
import { MonitoringBootstrap } from "@/components/monitoring/bootstrap";
|
||||
|
||||
const inter = Inter({
|
||||
variable: "--font-sans",
|
||||
subsets: ["latin"],
|
||||
weight: ["400", "500", "600", "700"],
|
||||
});
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: "HealthLog",
|
||||
description:
|
||||
"Personal health tracking — weight, blood pressure, pulse, mood, medication compliance",
|
||||
manifest: "/manifest.json",
|
||||
icons: {
|
||||
icon: "/favicon.svg",
|
||||
apple: "/logo-192.png",
|
||||
},
|
||||
appleWebApp: {
|
||||
capable: true,
|
||||
statusBarStyle: "black-translucent",
|
||||
title: "HealthLog",
|
||||
},
|
||||
openGraph: {
|
||||
title: "HealthLog",
|
||||
description:
|
||||
"Personal health tracking — weight, blood pressure, pulse, mood, medication compliance",
|
||||
type: "website",
|
||||
locale: "de_DE",
|
||||
siteName: "HealthLog",
|
||||
},
|
||||
twitter: {
|
||||
card: "summary",
|
||||
title: "HealthLog",
|
||||
description:
|
||||
"Personal health tracking — weight, blood pressure, pulse, mood, medication compliance",
|
||||
},
|
||||
};
|
||||
|
||||
export const viewport: Viewport = {
|
||||
width: "device-width",
|
||||
initialScale: 1,
|
||||
viewportFit: "cover",
|
||||
themeColor: "#282a36",
|
||||
};
|
||||
|
||||
// Inline script to apply theme before first paint (prevents FOUC)
|
||||
const themeScript = `(function(){try{var t=localStorage.getItem("healthlog-theme");var c=(t==="light"||t==="dark")?t:(window.matchMedia("(prefers-color-scheme:dark)").matches?"dark":"light");document.documentElement.classList.add(c)}catch(e){document.documentElement.classList.add("dark")}})()`;
|
||||
|
||||
export default async function RootLayout({
|
||||
children,
|
||||
}: Readonly<{
|
||||
children: React.ReactNode;
|
||||
}>) {
|
||||
const nonce =
|
||||
process.env.NODE_ENV === "production"
|
||||
? ((await headers()).get("x-nonce") ?? undefined)
|
||||
: undefined;
|
||||
|
||||
return (
|
||||
<html lang="de" suppressHydrationWarning>
|
||||
<head>
|
||||
<script
|
||||
suppressHydrationWarning
|
||||
nonce={nonce}
|
||||
dangerouslySetInnerHTML={{ __html: themeScript }}
|
||||
/>
|
||||
</head>
|
||||
<body className={`${inter.variable} font-sans antialiased`}>
|
||||
<Providers>
|
||||
<MonitoringBootstrap />
|
||||
<AuthShell>{children}</AuthShell>
|
||||
</Providers>
|
||||
</body>
|
||||
</html>
|
||||
);
|
||||
}
|
||||
Loaded 100 of 301 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user