feat: 7-Tage-Ansicht der eigenen Storys für den Ersteller (Web + App)

- stories.listActive: der Owner bekommt seine Storys der letzten 7 Tage mit
  isExpired, alle anderen weiterhin nur die aktiven 24 Stunden
- stories.hasActiveStory: optional includeOwnRecent → grauer Ring
  (expiredOnly) nur in der Story-Leiste, nicht an Profilbildern im Feed
- Viewer: Hinweis "Abgelaufen – nur für dich sichtbar", Kommentare bei
  abgelaufenen Storys nur lesbar, Pfote nur als Zähler; Löschen und
  Zuschauerliste bleiben

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
adminandClaude Opus 5.5 committed 2026-10-02 19:30:22 +02:00
1 parent a01c58e5f0
commit 2c0680cef9
15 files changed
+215 -37

No files matched your search

+5 -2
View File
@@ -260,7 +260,8 @@
"postError": "Kommentar konnte nicht gepostet werden. Bitte versuche es erneut.",
"deleteError": "Kommentar konnte nicht gelöscht werden. Bitte versuche es erneut.",
"countSingular": "1 Kommentar",
"countPlural": "{count} Kommentare"
"countPlural": "{count} Kommentare",
"readOnlyExpired": "Die Story ist abgelaufen. Kommentare kannst du noch lesen, aber nicht mehr schreiben."
},
"RelativeTime": {
"justNow": "gerade eben",
@@ -588,7 +589,9 @@
"deleteStoryCancel": "Abbrechen",
"deleteStoryConfirm": "Löschen",
"storyDeleted": "Story gelöscht",
"storyDeleteError": "Die Story konnte nicht gelöscht werden. Bitte versuch es noch einmal."
"storyDeleteError": "Die Story konnte nicht gelöscht werden. Bitte versuch es noch einmal.",
"expiredOwnerOnly": "Abgelaufen – nur für dich sichtbar",
"pawCount": "{count, plural, one {# Pfote} other {# Pfoten}}"
},
"StoryTray": {
"storiesAriaLabel": "Storys",
+5 -2
View File
@@ -260,7 +260,8 @@
"postError": "Couldn't post comment. Please try again.",
"deleteError": "Couldn't delete comment. Please try again.",
"countSingular": "1 comment",
"countPlural": "{count} comments"
"countPlural": "{count} comments",
"readOnlyExpired": "This story has expired. You can still read comments but not add new ones."
},
"RelativeTime": {
"justNow": "now",
@@ -588,7 +589,9 @@
"deleteStoryCancel": "Cancel",
"deleteStoryConfirm": "Delete",
"storyDeleted": "Story deleted",
"storyDeleteError": "The story could not be deleted. Please try again."
"storyDeleteError": "The story could not be deleted. Please try again.",
"expiredOwnerOnly": "Expired – only visible to you",
"pawCount": "{count, plural, one {# paw} other {# paws}}"
},
"StoryTray": {
"storiesAriaLabel": "Stories",
+38 -8
View File
@@ -5,7 +5,7 @@ import { useLocalSearchParams, useRouter } from "expo-router";
import { useTranslation } from "react-i18next";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { Image } from "expo-image";
import { Eye, MessageCircle, Trash2, X } from "lucide-react-native";
import { Clock, Eye, MessageCircle, PawPrint, Trash2, X } from "lucide-react-native";
import { useTRPC } from "../../src/api/trpc";
import { useActivePet } from "../../src/context/ActivePetContext";
import { PetAvatar } from "../../src/components/PetAvatar";
@@ -185,6 +185,15 @@ export default function StoryViewerScreen() {
<Text style={styles.petName}>{petName}</Text>
</View>
{currentStory.isExpired && (
<View style={[styles.expiredRow, { top: insets.top + 56 }]} pointerEvents="none">
<View style={styles.expiredBadge}>
<Clock size={14} color={colors.pureWhite} />
<Text style={styles.expiredText}>{t("storyViewer.expiredOwnerOnly")}</Text>
</View>
</View>
)}
{isOwnStory && (
<View style={[styles.ownerActions, { top: insets.top + 8 }]}>
<Pressable
@@ -211,13 +220,22 @@ export default function StoryViewerScreen() {
{activePetId && (
<View style={[styles.actions, { bottom: insets.bottom + 24 }]}>
<StoryPawButton
key={currentStory.id}
storyId={currentStory.id}
petId={activePetId}
initialCount={currentStory.reactionCount}
initialReacted={currentStory.reactedByViewer}
/>
{currentStory.isExpired ? (
<View style={styles.actionWrap} accessibilityLabel={t("storyViewer.pawCount", { count: currentStory.reactionCount })}>
<View style={styles.actionCircle}>
<PawPrint size={20} color={colors.pureWhite} />
</View>
{currentStory.reactionCount > 0 && <Text style={styles.actionCount}>{currentStory.reactionCount}</Text>}
</View>
) : (
<StoryPawButton
key={currentStory.id}
storyId={currentStory.id}
petId={activePetId}
initialCount={currentStory.reactionCount}
initialReacted={currentStory.reactedByViewer}
/>
)}
<Pressable
onPress={() => setOpenSheet("comments")}
accessibilityRole="button"
@@ -245,6 +263,7 @@ export default function StoryViewerScreen() {
onClose={() => setOpenSheet(null)}
onChanged={refreshStories}
onPressPet={openPet}
readOnly={currentStory.isExpired}
/>
)}
{isOwnStory && (
@@ -281,6 +300,17 @@ const styles = StyleSheet.create({
actionWrap: { alignItems: "center", gap: 2 },
actionCircle: { width: 44, height: 44, borderRadius: 22, backgroundColor: "rgba(0,0,0,0.4)", alignItems: "center", justifyContent: "center" },
actionCount: { color: colors.pureWhite, fontSize: 12, fontWeight: "600", textShadowColor: "rgba(0,0,0,0.6)", textShadowRadius: 3 },
expiredRow: { position: "absolute", left: 0, right: 0, alignItems: "center", zIndex: 2 },
expiredBadge: {
flexDirection: "row",
alignItems: "center",
gap: 6,
paddingHorizontal: 12,
paddingVertical: 6,
borderRadius: 999,
backgroundColor: "rgba(0,0,0,0.6)",
},
expiredText: { color: colors.pureWhite, fontSize: 12, fontWeight: "600" },
ownerActions: { position: "absolute", left: 16, flexDirection: "row", alignItems: "center", gap: 8, zIndex: 2 },
deleteButton: { width: 36, height: 36, borderRadius: 18, backgroundColor: "rgba(0,0,0,0.4)", alignItems: "center", justifyContent: "center" },
viewerCount: {
+2 -1
View File
@@ -158,7 +158,8 @@ Neu 7:
- [x] Nutzerfeedback - Story löschbar ? wie kann man die story löschen, falls man mal was falsches in die story geladen hat ?
→ Gab es bisher nirgends. Neu: Server `stories.delete` (nur Owner; löscht Aufrufe — `StoryView` hat bewusst kein Cascade —, dann die Story, Pfoten/Kommentare per Cascade; danach Bild in Supabase Storage bzw. Mux-Asset best-effort). Web: Papierkorb neben der Zuschauerzahl in der eigenen Story + Rückfrage (`AlertDialog`), Bild-Timer pausiert während der Rückfrage, gelöscht wird die beim Antippen gemerkte Story-ID. App: gleicher Papierkorb + native Rückfrage, Timer pausiert. Nach dem Löschen springt der Viewer zur nächsten Story bzw. schließt, wenn keine mehr da ist. 5 neue Tests in `src/__tests__/stories.test.ts`. Nicht auf einem Gerät getestet. Commit `81d9c6d`, live (Web + OTA Runtime 1.0.6: Android `49757586-c443-4952-a679-c66a4225ef82`, iOS `48d22b11-abc9-4c75-be52-a122b0130c5e`).
- [ ] Storys nur für Ersteller länger einsehbar wegen den Kommentaren (7Tage)
- [x] Storys nur für Ersteller länger einsehbar wegen den Kommentaren (7Tage)
→ **Umgesetzt (02.10.):** Der Ersteller sieht seine Storys 7 Tage lang (danach löscht der Aufräum-Job sie), alle anderen weiterhin nur 24 Stunden. Server: `stories.listActive` liefert dem Owner die Storys der letzten 7 Tage mit `isExpired`; `stories.hasActiveStory` meldet mit `includeOwnRecent` (nur die Story-Leiste setzt das) einen grauen Ring `expiredOnly`, damit Profilbilder im Feed nicht ebenfalls grau umrandet werden. Web + App: grauer Ring „Deine Story“, Hinweis „Abgelaufen – nur für dich sichtbar“ im Viewer, Kommentare bei abgelaufenen Storys nur lesbar, Pfote nur als Zähler; Zuschauerliste und Löschen bleiben. Keine Schemaänderung. 4 neue Tests. Nicht auf einem Gerät getestet.
→ Noch offen. Befund: abgelaufene Storys werden nie gelöscht (Einträge, Bilder, Mux-Videos bleiben liegen) — Vorschlag: grauer Ring "Deine Story" 7 Tage für den Ersteller, danach Aufräum-Cron (braucht einen Auslöser auf dem NAS, die bestehenden Cron-Routen haben keinen) + Satz unter "Speicherdauer" in der Datenschutzerklärung. **Teil erledigt (02.10.):** Aufräum-Job gebaut — `/api/cron/cleanup-stories` löscht Storys älter als 7 Tage komplett (Aufrufe, Pfoten, Kommentare, Bild, Mux-Video; gemeinsame Funktion `src/lib/story-cleanup.ts`, auch von „Story löschen“ genutzt), täglich 04:30 über die bestehende NAS-Crontab (`docker/run-cron.sh`, Log in `docker/cron.log`); Datenschutzerklärung Abschnitt 6 ergänzt. Offen bleibt nur die 7-Tage-Ansicht für den Ersteller.
+8 -2
View File
@@ -10,6 +10,8 @@ type Props = {
/** Avatar size in px — used to scale the paw outline (default: 32) */
size?: number;
onPress?: () => void;
/** Nur Story-Leiste: eigene abgelaufene Storys (≤ 7 Tage) als grauer Ring. */
includeOwnRecent?: boolean;
};
const RING_PAD = 8;
@@ -35,12 +37,16 @@ export function getPawRingBox(size: number) {
* instead of inline SVG markup. Orange = unseen stories, gray = all seen,
* no ring = no active story (STORY-02).
*/
export function PawRing({ petId, children, size = 32, onPress }: Props) {
export function PawRing({ petId, children, size = 32, onPress, includeOwnRecent }: Props) {
const trpc = useTRPC();
const { activePetId } = useActivePet();
const { data = { hasStory: false, allSeen: false } } = useQuery(
trpc.stories.hasActiveStory.queryOptions({ petId, viewerPetId: activePetId ?? undefined })
trpc.stories.hasActiveStory.queryOptions({
petId,
viewerPetId: activePetId ?? undefined,
...(includeOwnRecent ? { includeOwnRecent: true } : {}),
})
);
const { hasStory, allSeen } = data;
const ringColor = allSeen ? SEEN_COLOR : UNSEEN_COLOR;
+2 -2
View File
@@ -32,7 +32,7 @@ export function StoryTray() {
const styles = useMemo(() => makeStyles(colors), [colors]);
const { data: ownStory } = useQuery({
...trpc.stories.hasActiveStory.queryOptions({ petId: activePetId ?? "" }),
...trpc.stories.hasActiveStory.queryOptions({ petId: activePetId ?? "", includeOwnRecent: true }),
enabled: !!activePetId,
});
const activePet = pets.find((pet) => pet.id === activePetId) ?? null;
@@ -63,7 +63,7 @@ export function StoryTray() {
{ownStory?.hasStory && activePet && (
<Pressable style={styles.item} onPress={() => openViewer(activePet)}>
<PawRing petId={activePet.id} size={AVATAR_SIZE}>
<PawRing petId={activePet.id} size={AVATAR_SIZE} includeOwnRecent>
<PetAvatar name={activePet.name} avatarKey={activePet.avatarKey} size="lg" />
</PawRing>
<Text style={styles.label} numberOfLines={1}>
@@ -29,6 +29,8 @@ type Props = {
/** Wird nach Hinzufügen/Löschen aufgerufen, damit der Viewer den Zähler neu lädt. */
onChanged: () => void;
onPressPet: (petId: string) => void;
/** Abgelaufene Story in der 7-Tage-Ansicht des Erstellers: nur lesen. */
readOnly?: boolean;
};
/**
@@ -37,7 +39,7 @@ type Props = {
* verdeckt die Tastatur sonst die laufende Story und sie springt weiter,
* während man noch tippt).
*/
export function StoryCommentsSheet({ storyId, activePetId, visible, onClose, onChanged, onPressPet }: Props) {
export function StoryCommentsSheet({ storyId, activePetId, visible, onClose, onChanged, onPressPet, readOnly = false }: Props) {
const { t } = useTranslation();
const { colors } = useTheme();
const insets = useSafeAreaInsets();
@@ -116,6 +118,9 @@ export function StoryCommentsSheet({ storyId, activePetId, visible, onClose, onC
/>
)}
{readOnly ? (
<Text style={styles.readOnly}>{t("storyViewer.readOnlyExpired")}</Text>
) : (
<View style={styles.inputRow}>
<TextField
placeholder={t("comments.placeholder")}
@@ -135,6 +140,7 @@ export function StoryCommentsSheet({ storyId, activePetId, visible, onClose, onC
{add.isPending ? <ActivityIndicator color="#ffffff" /> : <Send size={18} color="#ffffff" />}
</Pressable>
</View>
)}
{add.isError && <Text style={styles.error}>{t("storyViewer.commentError")}</Text>}
</View>
</KeyboardAvoidingView>
@@ -169,6 +175,7 @@ function makeStyles(colors: ColorTokens, insetBottom: number) {
input: { flex: 1 },
send: { width: 48, height: 48, borderRadius: radii.lg, backgroundColor: colors.marigoldOrange, alignItems: "center", justifyContent: "center" },
sendDisabled: { opacity: 0.5 },
readOnly: { ...typography.body, fontSize: 13, color: colors.quietGray, paddingHorizontal: 16, paddingTop: 10 },
error: { ...typography.body, fontSize: 12, color: colors.alertRed, paddingHorizontal: 12, paddingTop: 6 },
});
}
+5 -1
View File
@@ -416,6 +416,10 @@
"deleteTitle": "Story löschen?",
"deleteDescription": "Die Story wird mit allen Aufrufen, Pfoten und Kommentaren endgültig gelöscht.",
"deleteConfirm": "Löschen",
"deleteError": "Die Story konnte nicht gelöscht werden. Bitte versuch es noch einmal."
"deleteError": "Die Story konnte nicht gelöscht werden. Bitte versuch es noch einmal.",
"expiredOwnerOnly": "Abgelaufen – nur für dich sichtbar",
"readOnlyExpired": "Die Story ist abgelaufen. Kommentare kannst du noch lesen, aber nicht mehr schreiben.",
"pawCount_one": "{{count}} Pfote",
"pawCount_other": "{{count}} Pfoten"
}
}
+5 -1
View File
@@ -416,6 +416,10 @@
"deleteTitle": "Delete story?",
"deleteDescription": "The story and all its views, paws and comments will be deleted permanently.",
"deleteConfirm": "Delete",
"deleteError": "The story could not be deleted. Please try again."
"deleteError": "The story could not be deleted. Please try again.",
"expiredOwnerOnly": "Expired – only visible to you",
"readOnlyExpired": "This story has expired. You can still read comments but not add new ones.",
"pawCount_one": "{{count}} paw",
"pawCount_other": "{{count}} paws"
}
}
+55
View File
@@ -240,6 +240,61 @@ describe("stories.listActive", () => {
});
});
describe("stories — 7-Tage-Ansicht für den Ersteller", () => {
beforeEach(() => vi.clearAllMocks());
it("listActive shows the owner their stories of the last 7 days, marked as expired", async () => {
const { caller, mockPrisma } = createCaller();
mockPrisma.pet.findUnique.mockResolvedValue({ ownerId: "owner-1" });
mockPrisma.story.findMany.mockResolvedValue([
{ id: "old", expiresAt: new Date(Date.now() - 60_000), reactionCount: 1 },
{ id: "new", expiresAt: new Date(Date.now() + 60_000), reactionCount: 0 },
]);
const result = await caller.listActive({ petId: "pet-1" });
expect(result.map((s) => s.isExpired)).toEqual([true, false]);
const where = mockPrisma.story.findMany.mock.calls[0][0].where;
expect(where.createdAt.gte).toBeInstanceOf(Date);
expect(where.expiresAt).toBeUndefined();
});
it("listActive still shows other viewers only the active 24 hours", async () => {
const { caller, mockPrisma } = createCaller();
mockPrisma.pet.findUnique.mockResolvedValue({ ownerId: "owner-2" });
mockPrisma.story.findMany.mockResolvedValue([]);
await caller.listActive({ petId: "pet-2" });
const where = mockPrisma.story.findMany.mock.calls[0][0].where;
expect(where.expiresAt.gt).toBeInstanceOf(Date);
expect(where.createdAt).toBeUndefined();
});
it("hasActiveStory reports a gray ring for the owner's expired stories only with includeOwnRecent", async () => {
const { caller, mockPrisma } = createCaller();
mockPrisma.story.findMany.mockResolvedValue([]); // nichts aktiv
mockPrisma.pet.findUnique.mockResolvedValue({ ownerId: "owner-1" });
mockPrisma.story.count.mockResolvedValue(2);
expect(await caller.hasActiveStory({ petId: "pet-1", includeOwnRecent: true })).toEqual({
hasStory: true,
allSeen: true,
expiredOnly: true,
});
expect(await caller.hasActiveStory({ petId: "pet-1" })).toEqual({ hasStory: false, allSeen: false, expiredOnly: false });
});
it("hasActiveStory never shows someone else's expired stories", async () => {
const { caller, mockPrisma } = createCaller();
mockPrisma.story.findMany.mockResolvedValue([]);
mockPrisma.pet.findUnique.mockResolvedValue({ ownerId: "owner-2" });
mockPrisma.story.count.mockResolvedValue(3);
expect(await caller.hasActiveStory({ petId: "pet-2", includeOwnRecent: true })).toMatchObject({ hasStory: false });
});
});
describe("stories.hasActiveStory", () => {
beforeEach(() => vi.clearAllMocks());
+4 -1
View File
@@ -12,6 +12,8 @@ interface PawRingProps {
size?: number;
/** Optional tap handler — rendered as <button> when hasActiveStory */
onPress?: () => void;
/** Nur Story-Leiste: eigene abgelaufene Storys (≤ 7 Tage) als grauer Ring. */
includeOwnRecent?: boolean;
}
const RING_PAD = 8;
@@ -22,7 +24,7 @@ const RING_PAD = 8;
* Orange = unseen stories; gray = all stories already seen; no ring = no stories (STORY-02).
* viewerPetId is read from ActivePetContext so callers don't need to pass it explicitly.
*/
export function PawRing({ petId, children, size = 32, onPress }: PawRingProps) {
export function PawRing({ petId, children, size = 32, onPress, includeOwnRecent }: PawRingProps) {
const trpc = useTRPC();
const { activePetId } = useActivePet();
@@ -30,6 +32,7 @@ export function PawRing({ petId, children, size = 32, onPress }: PawRingProps) {
trpc.stories.hasActiveStory.queryOptions({
petId,
viewerPetId: activePetId ?? undefined,
...(includeOwnRecent ? { includeOwnRecent: true } : {}),
})
);
@@ -12,6 +12,8 @@ interface StoryCommentsOverlayProps {
activePetId: string;
open: boolean;
onClose: () => void;
/** Abgelaufene Story in der 7-Tage-Ansicht des Erstellers: nur lesen, nicht schreiben. */
readOnly?: boolean;
}
/**
@@ -25,6 +27,7 @@ export function StoryCommentsOverlay({
activePetId,
open,
onClose,
readOnly = false,
}: StoryCommentsOverlayProps) {
const t = useTranslations("Comments");
const trpc = useTRPC();
@@ -115,6 +118,9 @@ export function StoryCommentsOverlay({
<div ref={listEndRef} />
</div>
{readOnly ? (
<p className="border-t border-white/10 px-3 py-2 text-xs text-white/60 shrink-0">{t("readOnlyExpired")}</p>
) : (
<div className="flex items-center gap-2 border-t border-white/10 px-3 py-2 shrink-0">
<input
value={body}
@@ -143,6 +149,7 @@ export function StoryCommentsOverlay({
)}
</button>
</div>
)}
</div>
);
}
+2 -1
View File
@@ -51,7 +51,7 @@ export function StoryTray() {
// Eigene Story: gleiche Query-Form wie StoryForm's Invalidierung ({ petId }),
// damit der Ring direkt nach dem Posten erscheint.
const { data: ownStory } = useQuery({
...trpc.stories.hasActiveStory.queryOptions({ petId: activePetId ?? "" }),
...trpc.stories.hasActiveStory.queryOptions({ petId: activePetId ?? "", includeOwnRecent: true }),
enabled: !!activePetId,
});
const { data: myPets = [] } = useQuery({ ...trpc.pets.list.queryOptions(), enabled: !!activePetId });
@@ -100,6 +100,7 @@ export function StoryTray() {
<div className="flex flex-col items-center gap-1 shrink-0" role="listitem">
<PawRing
petId={activePet.id}
includeOwnRecent
size={TRAY_AVATAR_SIZE}
onPress={() =>
setViewingPet({ id: activePet.id, name: activePet.name, avatarKey: activePet.avatarKey ?? null })
+27 -8
View File
@@ -3,7 +3,7 @@
import { useState, useEffect, useCallback, useRef } from "react";
import { createPortal } from "react-dom";
import dynamic from "next/dynamic";
import { X, Eye, Volume2, VolumeX, Loader2, MessageCircle, Trash2 } from "lucide-react";
import { X, Eye, Volume2, VolumeX, Loader2, MessageCircle, Trash2, PawPrint, Clock } from "lucide-react";
import { toast } from "sonner";
import {
AlertDialog,
@@ -249,6 +249,7 @@ export function StoryViewer({
setDeleteTargetId(null);
toast.success(t("storyDeleted"));
void queryClient.invalidateQueries(trpc.stories.listActive.queryOptions({ petId }));
void queryClient.invalidateQueries(trpc.stories.hasActiveStory.queryOptions({ petId }));
void queryClient.invalidateQueries(trpc.follows.pathFilter());
if (remaining <= 0) handleClose();
else setCurrentIndex((i) => Math.min(i, remaining - 1));
@@ -431,6 +432,14 @@ export function StoryViewer({
<X className="h-5 w-5" aria-hidden="true" />
</button>
{/* 7-Tage-Ansicht: abgelaufene eigene Story kennzeichnen */}
{currentStory.isExpired && (
<div className="absolute top-20 left-1/2 -translate-x-1/2 flex items-center gap-1.5 rounded-full bg-black/60 px-3 py-1.5 text-xs text-white">
<Clock className="h-3.5 w-3.5" aria-hidden="true" />
{t("expiredOwnerOnly")}
</div>
)}
{/* Viewer count + delete — top left (owner only) */}
{isOwnPet && (
<div className="absolute top-8 left-4 flex items-center gap-2">
@@ -460,13 +469,22 @@ export function StoryViewer({
{/* Gitea #29 — paw + comment buttons, bottom right */}
{activePetId && (
<div className="absolute bottom-6 right-4 z-10 flex flex-col items-center gap-4">
<StoryPawButton
key={currentStory.id}
storyId={currentStory.id}
petId={activePetId}
initialCount={currentStory.reactionCount}
initialReacted={currentStory.reactedByViewer}
/>
{currentStory.isExpired ? (
<span className="flex flex-col items-center gap-0.5 text-white" aria-label={t("pawCount", { count: currentStory.reactionCount })}>
<span className="flex h-9 w-9 items-center justify-center rounded-full bg-black/40">
<PawPrint className="h-4 w-4" aria-hidden="true" />
</span>
{currentStory.reactionCount > 0 && <span className="text-xs drop-shadow">{currentStory.reactionCount}</span>}
</span>
) : (
<StoryPawButton
key={currentStory.id}
storyId={currentStory.id}
petId={activePetId}
initialCount={currentStory.reactionCount}
initialReacted={currentStory.reactedByViewer}
/>
)}
<button
type="button"
onClick={() => setCommentsOpen((o) => !o)}
@@ -491,6 +509,7 @@ export function StoryViewer({
activePetId={activePetId}
open={commentsOpen}
onClose={() => setCommentsOpen(false)}
readOnly={currentStory.isExpired}
/>
)}
</div>,
+42 -7
View File
@@ -8,7 +8,15 @@ import {
ALLOWED_CONTENT_TYPES,
MAX_FILE_SIZE,
} from "@/lib/supabase-storage";
import { deleteStoryWithMedia } from "@/lib/story-cleanup";
import { STORY_RETENTION_DAYS, deleteStoryWithMedia } from "@/lib/story-cleanup";
const DAY_MS = 24 * 60 * 60 * 1000;
/** Besitzt der aufrufende Owner dieses Tier? Für die 7-Tage-Ansicht des Erstellers. */
async function isOwnPet(prisma: PrismaClient, petId: string, userId: string): Promise<boolean> {
const pet = await prisma.pet.findUnique({ where: { id: petId }, select: { ownerId: true } });
return pet?.ownerId === userId;
}
import { randomUUID } from "crypto";
import { petIdentitySelect } from "@/repositories/pet-repository";
import { assertPetOwnership } from "@/lib/assert-pet-ownership";
@@ -220,12 +228,20 @@ export const storiesRouter = router({
* With the optional viewerPetId, each story also carries reactedByViewer so
* the paw button can start filled — optional so older app builds that only
* send { petId } keep working unchanged (reactedByViewer is then false).
*
* 7-Tage-Ansicht: Der Owner des Tiers bekommt zusätzlich seine abgelaufenen
* Storys der letzten STORY_RETENTION_DAYS (isExpired: true) — alle anderen
* sehen weiterhin nur die aktiven 24 Stunden.
*/
listActive: protectedProcedure
.input(z.object({ petId: z.string().min(1), viewerPetId: z.string().min(1).optional() }))
.query(async ({ ctx, input }) => {
const now = new Date();
const ownerView = await isOwnPet(ctx.prisma, input.petId, ctx.userId);
const stories = await ctx.prisma.story.findMany({
where: { petId: input.petId, expiresAt: { gt: new Date() } },
where: ownerView
? { petId: input.petId, createdAt: { gte: new Date(now.getTime() - STORY_RETENTION_DAYS * DAY_MS) } }
: { petId: input.petId, expiresAt: { gt: now } },
include: {
musicTrack: true,
...(input.viewerPetId
@@ -238,6 +254,7 @@ export const storiesRouter = router({
return stories.map(({ reactions, ...story }: (typeof stories)[number] & { reactions?: { petId: string }[] }) => ({
...story,
reactedByViewer: (reactions?.length ?? 0) > 0,
isExpired: story.expiresAt <= now,
}));
}),
@@ -249,16 +266,34 @@ export const storiesRouter = router({
* viewerPetId is optional — without it allSeen is always false.
*/
hasActiveStory: protectedProcedure
.input(z.object({ petId: z.string().min(1), viewerPetId: z.string().optional() }))
.input(
z.object({
petId: z.string().min(1),
viewerPetId: z.string().optional(),
// Nur die Story-Leiste setzt das: eigene, schon abgelaufene Storys der
// letzten 7 Tage ergeben einen grauen Ring (expiredOnly). Überall sonst
// (Profilbilder im Feed usw.) bleibt es beim 24-Stunden-Verhalten.
includeOwnRecent: z.boolean().optional(),
})
)
.query(async ({ ctx, input }) => {
const now = new Date();
const activeStories = await ctx.prisma.story.findMany({
where: { petId: input.petId, expiresAt: { gt: new Date() } },
where: { petId: input.petId, expiresAt: { gt: now } },
select: { id: true },
});
if (activeStories.length === 0) return { hasStory: false, allSeen: false };
if (activeStories.length === 0) {
if (input.includeOwnRecent && (await isOwnPet(ctx.prisma, input.petId, ctx.userId))) {
const recent = await ctx.prisma.story.count({
where: { petId: input.petId, createdAt: { gte: new Date(now.getTime() - STORY_RETENTION_DAYS * DAY_MS) } },
});
if (recent > 0) return { hasStory: true, allSeen: true, expiredOnly: true };
}
return { hasStory: false, allSeen: false, expiredOnly: false };
}
if (!input.viewerPetId) return { hasStory: true, allSeen: false };
if (!input.viewerPetId) return { hasStory: true, allSeen: false, expiredOnly: false };
const viewedCount = await ctx.prisma.storyView.count({
where: {
@@ -267,7 +302,7 @@ export const storiesRouter = router({
},
});
return { hasStory: true, allSeen: viewedCount >= activeStories.length };
return { hasStory: true, allSeen: viewedCount >= activeStories.length, expiredOnly: false };
}),
/**