feat: engagement-counter denormalization, pagination fixes, dead-code cleanup

Bundles the 2026-07-12 code-audit session (Clusters A/B/C/D partial/E/F):
denormalized Post/Advertisement reaction/comment/repost counters synced
transactionally instead of live _count queries; real cursor-based pagination
for followers/following/blocks lists; assertPetOwnership + formatRelativeTime
centralized; dead r2.ts + AWS SDK deps removed; missing DB indexes added;
account-deletion flow, mention notifications, pull-to-refresh feed, and
mobile UI/i18n fixes from the surrounding sessions.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
adminandClaude Sonnet 5 committed 2026-07-16 19:22:23 +02:00
1 parent e91705063f
commit f14be58c06
182 files changed
+10562 -724

No files matched your search

+97
View File
@@ -0,0 +1,97 @@
/**
* Admin Router Unit Tests — deleteComment (Cluster A counter fix)
*
* admin.ts had zero test coverage before this change. Scope is limited to
* deleteComment, which previously deleted a Comment without ever decrementing
* the parent Post's commentCount — a real gap fixed alongside the Post
* denormalized-counter rollout (see comments.ts / reactions.ts for the same
* pattern on the user-facing mutation paths).
*
* Tests:
* - deleteComment decrements Post.commentCount and writes a moderation log
* - deleteComment throws FORBIDDEN for a non-admin caller
*/
import { describe, it, expect, vi, afterEach } from "vitest";
import { TRPCError } from "@trpc/server";
vi.mock("server-only", () => ({}));
vi.mock("@clerk/nextjs/server", () => ({
auth: vi.fn().mockResolvedValue({ userId: "admin-1" }),
}));
vi.mock("@/lib/supabase-storage", () => ({
createSignedUploadUrl: vi.fn(),
ALLOWED_CONTENT_TYPES: ["image/jpeg", "image/png", "image/webp"],
MAX_FILE_SIZE: 10 * 1024 * 1024,
}));
vi.mock("@/lib/prisma", () => ({ prisma: {} }));
import { createMockPrisma } from "@/__tests__/helpers/prisma-mock";
async function createAdminCaller(overrides?: {
userId?: string | null;
prisma?: ReturnType<typeof createMockPrisma>;
}) {
const { adminRouter } = await import("@/trpc/routers/admin");
const { initTRPC } = await import("@trpc/server");
const mockPrisma = overrides?.prisma ?? createMockPrisma();
const userId = overrides?.userId !== undefined ? overrides.userId : "admin-1";
// deleteComment uses the interactive-transaction callback form; other sites
// in this codebase use the array form — support both shapes here.
mockPrisma.$transaction.mockImplementation((arg: unknown) =>
typeof arg === "function"
? (arg as (tx: typeof mockPrisma) => unknown)(mockPrisma)
: Promise.all(arg as unknown[])
);
const t = initTRPC
.context<{ userId: string | null; prisma: typeof mockPrisma }>()
.create();
const testRouter = t.router({ admin: adminRouter });
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const caller = testRouter.createCaller({ userId, prisma: mockPrisma as any });
return { caller, mockPrisma };
}
afterEach(() => {
vi.unstubAllEnvs();
});
describe("admin.deleteComment", () => {
it("decrements Post.commentCount and writes a moderation log", async () => {
vi.stubEnv("ADMIN_OWNER_ID", "admin-1");
const { caller, mockPrisma } = await createAdminCaller();
mockPrisma.comment.delete.mockResolvedValue({ id: "cmt-1", postId: "post-1" });
mockPrisma.post.update.mockResolvedValue({ id: "post-1", commentCount: 4 });
mockPrisma.moderationLog.create.mockResolvedValue({ id: "log-1" });
const result = await caller.admin.deleteComment({ commentId: "cmt-1", reason: "spam" });
expect(mockPrisma.comment.delete).toHaveBeenCalledWith({ where: { id: "cmt-1" } });
expect(mockPrisma.post.update).toHaveBeenCalledWith({
where: { id: "post-1" },
data: { commentCount: { decrement: 1 } },
});
expect(mockPrisma.moderationLog.create).toHaveBeenCalledWith(
expect.objectContaining({
data: expect.objectContaining({ action: "DELETE_COMMENT", targetId: "cmt-1" }),
})
);
expect(result).toEqual({ success: true });
});
it("throws FORBIDDEN for a non-admin caller", async () => {
vi.stubEnv("ADMIN_OWNER_ID", "someone-else");
const { caller, mockPrisma } = await createAdminCaller();
mockPrisma.adminRole.findUnique.mockResolvedValue(null);
await expect(
caller.admin.deleteComment({ commentId: "cmt-1" })
).rejects.toThrow(TRPCError);
expect(mockPrisma.comment.delete).not.toHaveBeenCalled();
});
});
+176
View File
@@ -0,0 +1,176 @@
/**
* Ads Router Unit Tests — Cluster A counter rollout
*
* ads.ts had zero test coverage before this change. It previously ran 3
* separate count() queries per ad view (getFeedData) and re-counted via
* count() after every single reaction/repost toggle. This now reads/writes
* denormalized Advertisement.adReactionCount/adCommentCount/adRepostCount
* columns instead.
*
* Tests:
* - getFeedData reads counts from the Advertisement row, not count()
* - toggleReaction increments on create, decrements on remove
* - addComment increments adCommentCount
* - toggleRepost increments on create, decrements on remove
*/
import { describe, it, expect, vi } from "vitest";
vi.mock("server-only", () => ({}));
vi.mock("@clerk/nextjs/server", () => ({
auth: vi.fn().mockResolvedValue({ userId: "owner-1" }),
}));
vi.mock("@/lib/prisma", () => ({ prisma: {} }));
import { createMockPrisma } from "@/__tests__/helpers/prisma-mock";
async function createAdsCaller(overrides?: {
userId?: string | null;
prisma?: ReturnType<typeof createMockPrisma>;
}) {
const { adsRouter } = await import("@/trpc/routers/ads");
const { initTRPC } = await import("@trpc/server");
const mockPrisma = overrides?.prisma ?? createMockPrisma();
const userId = overrides?.userId !== undefined ? overrides.userId : "owner-1";
mockPrisma.$transaction.mockImplementation((ops: unknown[]) => Promise.all(ops));
const t = initTRPC
.context<{ userId: string | null; prisma: typeof mockPrisma }>()
.create();
const testRouter = t.router({ ads: adsRouter });
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const caller = testRouter.createCaller({ userId, prisma: mockPrisma as any });
return { caller, mockPrisma };
}
describe("ads.getFeedData", () => {
it("reads counts from the Advertisement row instead of count()", async () => {
const { caller, mockPrisma } = await createAdsCaller();
mockPrisma.advertisement.findUnique.mockResolvedValue({
adReactionCount: 12,
adCommentCount: 3,
adRepostCount: 1,
});
mockPrisma.adReaction.findUnique.mockResolvedValue({ id: "adrxn-1" });
mockPrisma.adRepost.findUnique.mockResolvedValue(null);
const result = await caller.ads.getFeedData({ adId: "ad-1", petId: "pet-1" });
expect(mockPrisma.advertisement.findUnique).toHaveBeenCalledWith(
expect.objectContaining({ where: { id: "ad-1" } })
);
expect(result).toEqual({
reactionCount: 12,
hasReacted: true,
commentCount: 3,
repostCount: 1,
hasReposted: false,
});
});
});
describe("ads.toggleReaction", () => {
it("creates a reaction and increments adReactionCount", async () => {
const { caller, mockPrisma } = await createAdsCaller();
mockPrisma.adReaction.findUnique.mockResolvedValue(null);
mockPrisma.adReaction.create.mockResolvedValue({ id: "adrxn-1" });
mockPrisma.advertisement.update.mockResolvedValue({ adReactionCount: 5 });
const result = await caller.ads.toggleReaction({ adId: "ad-1", petId: "pet-1" });
expect(mockPrisma.adReaction.create).toHaveBeenCalledWith(
expect.objectContaining({ data: { adId: "ad-1", petId: "pet-1" } })
);
expect(mockPrisma.advertisement.update).toHaveBeenCalledWith(
expect.objectContaining({
where: { id: "ad-1" },
data: { adReactionCount: { increment: 1 } },
})
);
expect(result).toEqual({ reacted: true, count: 5 });
});
it("removes an existing reaction and decrements adReactionCount", async () => {
const { caller, mockPrisma } = await createAdsCaller();
mockPrisma.adReaction.findUnique.mockResolvedValue({ id: "adrxn-1" });
mockPrisma.adReaction.delete.mockResolvedValue({ id: "adrxn-1" });
mockPrisma.advertisement.update.mockResolvedValue({ adReactionCount: 4 });
const result = await caller.ads.toggleReaction({ adId: "ad-1", petId: "pet-1" });
expect(mockPrisma.adReaction.delete).toHaveBeenCalledWith({ where: { id: "adrxn-1" } });
expect(mockPrisma.advertisement.update).toHaveBeenCalledWith(
expect.objectContaining({
where: { id: "ad-1" },
data: { adReactionCount: { decrement: 1 } },
})
);
expect(result).toEqual({ reacted: false, count: 4 });
});
});
describe("ads.addComment", () => {
it("creates a comment and increments adCommentCount", async () => {
const { caller, mockPrisma } = await createAdsCaller();
mockPrisma.adComment.create.mockResolvedValue({
id: "adcmt-1",
adId: "ad-1",
petId: "pet-1",
body: "Nice!",
pet: { id: "pet-1", name: "Buddy", avatarKey: null },
});
mockPrisma.advertisement.update.mockResolvedValue({ adCommentCount: 4 });
const result = await caller.ads.addComment({ adId: "ad-1", petId: "pet-1", body: "Nice!" });
expect(mockPrisma.advertisement.update).toHaveBeenCalledWith(
expect.objectContaining({
where: { id: "ad-1" },
data: { adCommentCount: { increment: 1 } },
})
);
expect(result).toMatchObject({ body: "Nice!" });
});
});
describe("ads.toggleRepost", () => {
it("creates a repost and increments adRepostCount", async () => {
const { caller, mockPrisma } = await createAdsCaller();
mockPrisma.adRepost.findUnique.mockResolvedValue(null);
mockPrisma.adRepost.create.mockResolvedValue({ id: "adrep-1" });
mockPrisma.advertisement.update.mockResolvedValue({ adRepostCount: 2 });
const result = await caller.ads.toggleRepost({ adId: "ad-1", petId: "pet-1" });
expect(mockPrisma.adRepost.create).toHaveBeenCalledWith(
expect.objectContaining({ data: { adId: "ad-1", petId: "pet-1" } })
);
expect(mockPrisma.advertisement.update).toHaveBeenCalledWith(
expect.objectContaining({
where: { id: "ad-1" },
data: { adRepostCount: { increment: 1 } },
})
);
expect(result).toEqual({ reposted: true, count: 2 });
});
it("removes an existing repost and decrements adRepostCount", async () => {
const { caller, mockPrisma } = await createAdsCaller();
mockPrisma.adRepost.findUnique.mockResolvedValue({ id: "adrep-1" });
mockPrisma.adRepost.delete.mockResolvedValue({ id: "adrep-1" });
mockPrisma.advertisement.update.mockResolvedValue({ adRepostCount: 1 });
const result = await caller.ads.toggleRepost({ adId: "ad-1", petId: "pet-1" });
expect(mockPrisma.adRepost.delete).toHaveBeenCalledWith({ where: { id: "adrep-1" } });
expect(result).toEqual({ reposted: false, count: 1 });
});
});
+4 -3
View File
@@ -143,11 +143,12 @@ describe("blocks.list", () => {
expect(mockPrisma.block.findMany).toHaveBeenCalledWith(
expect.objectContaining({
where: { blockerPetId: "pet-1" },
select: { blockedPetId: true },
select: { blockedPetId: true, createdAt: true },
})
);
expect(result).toHaveLength(2);
expect(result[0].blockedPetId).toBe("pet-2");
expect(result.items).toHaveLength(2);
expect(result.items[0].blockedPetId).toBe("pet-2");
expect(result.nextCursor).toBeNull();
});
it("SAFE-01 — list ownership assertion: cannot list blocks for a pet you don't own", async () => {
+17
View File
@@ -39,6 +39,9 @@ async function createCommentsCaller(overrides?: {
const mockPrisma = overrides?.prisma ?? createMockPrisma();
const userId = overrides?.userId !== undefined ? overrides.userId : "owner-1";
// $transaction receives an array of already-invoked mock calls (promises or
// plain values) — Promise.all mirrors that shape closely enough for tests.
mockPrisma.$transaction.mockImplementation((ops: unknown[]) => Promise.all(ops));
const t = initTRPC
.context<{ userId: string | null; prisma: typeof mockPrisma }>()
@@ -67,6 +70,7 @@ describe("comments.create", () => {
updatedAt: new Date(),
pet: { id: "pet-1", name: "Buddy", avatarKey: null },
});
mockPrisma.post.update.mockResolvedValue({ petId: "pet-1" });
const result = await caller.comments.create({
postId: "post-1",
@@ -75,6 +79,12 @@ describe("comments.create", () => {
});
expect(mockPrisma.comment.create).toHaveBeenCalled();
expect(mockPrisma.post.update).toHaveBeenCalledWith(
expect.objectContaining({
where: { id: "post-1" },
data: { commentCount: { increment: 1 } },
})
);
expect(result).toMatchObject({ body: "Cute pup!", petId: "pet-1" });
});
});
@@ -95,6 +105,7 @@ describe("comments.delete", () => {
updatedAt: new Date(),
});
mockPrisma.comment.delete.mockResolvedValue({ id: "cmt-1" });
mockPrisma.post.update.mockResolvedValue({ id: "post-1" });
await expect(
caller.comments.delete({ commentId: "cmt-1", petId: "pet-1" })
@@ -103,6 +114,12 @@ describe("comments.delete", () => {
expect(mockPrisma.comment.delete).toHaveBeenCalledWith(
expect.objectContaining({ where: { id: "cmt-1" } })
);
expect(mockPrisma.post.update).toHaveBeenCalledWith(
expect.objectContaining({
where: { id: "post-1" },
data: { commentCount: { decrement: 1 } },
})
);
});
it("ENGM-03 — delete other's comment throws FORBIDDEN", async () => {
+6 -4
View File
@@ -262,8 +262,9 @@ describe("follows.listFollowers", () => {
where: { followeePetId: "pet-1" },
})
);
expect(result).toHaveLength(1);
expect(result[0].follower.name).toBe("Max");
expect(result.items).toHaveLength(1);
expect(result.items[0].follower.name).toBe("Max");
expect(result.nextCursor).toBeNull();
});
});
@@ -290,7 +291,8 @@ describe("follows.listFollowing", () => {
where: { followerPetId: "pet-1" },
})
);
expect(result).toHaveLength(1);
expect(result[0].followee.name).toBe("Luna");
expect(result.items).toHaveLength(1);
expect(result.items[0].followee.name).toBe("Luna");
expect(result.nextCursor).toBeNull();
});
});
+83
View File
@@ -146,6 +146,47 @@ interface MockPostHashtagClient {
findMany: MockFn;
}
// ─── Ad-engagement mock interfaces ────────────────────────────────────────────
interface MockAdvertisementClient {
findUnique: MockFn;
findMany: MockFn;
update: MockFn;
}
interface MockAdReactionClient {
findUnique: MockFn;
create: MockFn;
delete: MockFn;
}
interface MockAdCommentClient {
create: MockFn;
findMany: MockFn;
}
interface MockAdRepostClient {
findUnique: MockFn;
create: MockFn;
delete: MockFn;
}
interface MockModerationLogClient {
create: MockFn;
findMany: MockFn;
}
interface MockAdminRoleClient {
findUnique: MockFn;
findMany: MockFn;
upsert: MockFn;
delete: MockFn;
}
interface MockNotificationClient {
create: MockFn;
}
interface MockPrismaClient {
pet: MockPetClient;
owner: MockOwnerClient;
@@ -166,6 +207,13 @@ interface MockPrismaClient {
repost: MockRepostClient;
hashtag: MockHashtagClient;
postHashtag: MockPostHashtagClient;
advertisement: MockAdvertisementClient;
adReaction: MockAdReactionClient;
adComment: MockAdCommentClient;
adRepost: MockAdRepostClient;
moderationLog: MockModerationLogClient;
adminRole: MockAdminRoleClient;
notification: MockNotificationClient;
$transaction: MockFn;
$disconnect: MockFn;
}
@@ -285,6 +333,41 @@ export function createMockPrisma(): MockPrismaClient {
upsert: vi.fn(),
findMany: vi.fn(),
},
advertisement: {
findUnique: vi.fn(),
findMany: vi.fn(),
update: vi.fn(),
},
adReaction: {
findUnique: vi.fn(),
create: vi.fn(),
delete: vi.fn(),
},
adComment: {
create: vi.fn(),
findMany: vi.fn(),
},
adRepost: {
findUnique: vi.fn(),
create: vi.fn(),
delete: vi.fn(),
},
moderationLog: {
create: vi.fn(),
findMany: vi.fn(),
},
adminRole: {
findUnique: vi.fn(),
findMany: vi.fn(),
upsert: vi.fn(),
delete: vi.fn(),
},
// Fire-and-forget in production code (`.catch(() => {})`) — default to a
// resolved promise so tests that don't care about notifications don't
// need to configure this every time.
notification: {
create: vi.fn().mockResolvedValue({}),
},
$transaction: vi.fn(),
$disconnect: vi.fn(),
};
+17 -15
View File
@@ -13,7 +13,7 @@
* Security (T-4-01, T-4-02, T-4-03, T-4-05, T-4-06):
* - Ownership assertions tested (T-4-01)
* - ContentType restriction tested (T-4-02)
* - No real R2 calls — getPresignedUploadUrl is mocked (T-4-03)
* - No real Supabase Storage calls — createSignedUploadUrl is mocked (T-4-03)
* - key.startsWith('avatars/') validation tested (T-4-05)
* - fileSize <= 10MB validation tested (T-4-06)
*
@@ -28,11 +28,14 @@ import { createMockPrisma } from "@/__tests__/helpers/prisma-mock";
// Mock server-only — the import guard throws in non-server environments
vi.mock("server-only", () => ({}));
// Mock getPresignedUploadUrl so no real R2 calls are made (T-4-03)
vi.mock("@/lib/r2", () => ({
getPresignedUploadUrl: vi
// Mock createSignedUploadUrl so no real Supabase Storage calls are made (T-4-03)
vi.mock("@/lib/supabase-storage", () => ({
createSignedUploadUrl: vi
.fn()
.mockResolvedValue("https://fake-r2.example.com/presigned-url"),
.mockResolvedValue({ signedUrl: "https://fake-supabase.example.com/presigned-url", path: "fake-path" }),
getPublicUrl: vi.fn((key: string) => `https://fake-supabase.example.com/public/${key}`),
ALLOWED_CONTENT_TYPES: ["image/jpeg", "image/png", "image/webp"],
MAX_FILE_SIZE: 10 * 1024 * 1024,
}));
// Mock Clerk server auth
@@ -45,7 +48,7 @@ vi.mock("@/lib/prisma", () => ({
prisma: {},
}));
import { getPresignedUploadUrl } from "@/lib/r2";
import { createSignedUploadUrl } from "@/lib/supabase-storage";
const OWNER_ID = "owner-1";
const ATTACKER_ID = "attacker-999";
@@ -102,16 +105,15 @@ describe("media.getPresignedUrl", () => {
fileSize: 1024,
});
// Assert getPresignedUploadUrl was called with correct arguments
expect(getPresignedUploadUrl).toHaveBeenCalledOnce();
const [calledKey, calledContentType] = (
getPresignedUploadUrl as ReturnType<typeof vi.fn>
// Assert createSignedUploadUrl was called with the correct scoped key
expect(createSignedUploadUrl).toHaveBeenCalledOnce();
const [calledKey] = (
createSignedUploadUrl as ReturnType<typeof vi.fn>
).mock.calls[0];
expect(calledKey).toMatch(new RegExp(`^avatars/${OWNER_ID}/${PET_ID}/`));
expect(calledContentType).toBe("image/jpeg");
// Assert returned URL matches mock
expect(result.presignedUrl).toBe("https://fake-r2.example.com/presigned-url");
expect(result.presignedUrl).toBe("https://fake-supabase.example.com/presigned-url");
// Assert key is scoped under avatars/
expect(result.key).toMatch(/^avatars\//);
@@ -134,7 +136,7 @@ describe("media.getPresignedUrl", () => {
});
// No presigned URL should be generated for non-owner
expect(getPresignedUploadUrl).not.toHaveBeenCalled();
expect(createSignedUploadUrl).not.toHaveBeenCalled();
});
it("Test 3 — rejects unsupported contentType image/gif (Zod BAD_REQUEST, T-4-02)", async () => {
@@ -149,7 +151,7 @@ describe("media.getPresignedUrl", () => {
).rejects.toThrow(TRPCError);
// No DB lookup or presigned URL should be generated for invalid type
expect(getPresignedUploadUrl).not.toHaveBeenCalled();
expect(createSignedUploadUrl).not.toHaveBeenCalled();
});
it("Test 4 — rejects oversized file (11MB > 10MB limit, T-4-06)", async () => {
@@ -163,7 +165,7 @@ describe("media.getPresignedUrl", () => {
})
).rejects.toThrow(TRPCError);
expect(getPresignedUploadUrl).not.toHaveBeenCalled();
expect(createSignedUploadUrl).not.toHaveBeenCalled();
});
});
+2
View File
@@ -17,6 +17,8 @@ import { TRPCError } from "@trpc/server";
import { petsRouter } from "@/trpc/routers/pets";
import { createMockPrisma } from "@/__tests__/helpers/prisma-mock";
vi.mock("server-only", () => ({}));
// Mock Clerk server auth — pets router imports from @clerk/nextjs/server via trpc/init
vi.mock("@clerk/nextjs/server", () => ({
auth: vi.fn().mockResolvedValue({ userId: "test-owner-1" }),
+17
View File
@@ -40,6 +40,9 @@ async function createReactionsCaller(overrides?: {
const mockPrisma = overrides?.prisma ?? createMockPrisma();
const userId = overrides?.userId !== undefined ? overrides.userId : "owner-1";
// $transaction receives an array of already-invoked mock calls (promises or
// plain values) — Promise.all mirrors that shape closely enough for tests.
mockPrisma.$transaction.mockImplementation((ops: unknown[]) => Promise.all(ops));
const t = initTRPC
.context<{ userId: string | null; prisma: typeof mockPrisma }>()
@@ -65,12 +68,19 @@ describe("reactions.toggle", () => {
petId: "pet-1",
createdAt: new Date(),
});
mockPrisma.post.update.mockResolvedValue({ petId: "pet-1" });
const result = await caller.reactions.toggle({ postId: "post-1", petId: "pet-1" });
expect(mockPrisma.reaction.create).toHaveBeenCalledWith(
expect.objectContaining({ data: { postId: "post-1", petId: "pet-1" } })
);
expect(mockPrisma.post.update).toHaveBeenCalledWith(
expect.objectContaining({
where: { id: "post-1" },
data: { reactionCount: { increment: 1 } },
})
);
expect(result).toMatchObject({ reacted: true });
});
@@ -85,10 +95,17 @@ describe("reactions.toggle", () => {
createdAt: new Date(),
});
mockPrisma.reaction.delete.mockResolvedValue({ id: "rxn-1" });
mockPrisma.post.update.mockResolvedValue({ id: "post-1" });
const result = await caller.reactions.toggle({ postId: "post-1", petId: "pet-1" });
expect(mockPrisma.reaction.delete).toHaveBeenCalled();
expect(mockPrisma.post.update).toHaveBeenCalledWith(
expect.objectContaining({
where: { id: "post-1" },
data: { reactionCount: { decrement: 1 } },
})
);
expect(result).toMatchObject({ reacted: false });
});
+41
View File
@@ -41,6 +41,9 @@ async function createRepostsCaller(overrides?: {
const mockPrisma = overrides?.prisma ?? createMockPrisma();
const userId = overrides?.userId !== undefined ? overrides.userId : "owner-1";
// $transaction receives an array of already-invoked mock calls (promises or
// plain values) — Promise.all mirrors that shape closely enough for tests.
mockPrisma.$transaction.mockImplementation((ops: unknown[]) => Promise.all(ops));
const t = initTRPC
.context<{ userId: string | null; prisma: typeof mockPrisma }>()
@@ -69,6 +72,8 @@ describe("reposts.create", () => {
createdAt,
});
mockPrisma.post.update.mockResolvedValue({ id: "orig-1", repostCount: 1 });
const result = await caller.reposts.create({
originalPostId: "orig-1",
reposterPetId: "pet-1",
@@ -79,6 +84,12 @@ describe("reposts.create", () => {
data: expect.objectContaining({ type: "REPOST", petId: "pet-1" }),
})
);
expect(mockPrisma.post.update).toHaveBeenCalledWith(
expect.objectContaining({
where: { id: "orig-1" },
data: { repostCount: { increment: 1 } },
})
);
expect(mockFanOutPost).toHaveBeenCalled();
expect(result).toMatchObject({ postId: "repost-1" });
});
@@ -115,3 +126,33 @@ describe("reposts.create", () => {
expect(result).toMatchObject({ postId: "existing-repost-1" });
});
});
// ─── reposts.delete ──────────────────────────────────────────────────────────
describe("reposts.delete", () => {
it("ENGM-04 — delete removes the repost Post and decrements the original post's repostCount", async () => {
const { caller, mockPrisma } = await createRepostsCaller();
mockPrisma.pet.findUnique.mockResolvedValue({ id: "pet-1", ownerId: "owner-1", name: "Buddy" });
mockPrisma.repost.findUnique.mockResolvedValue({
postId: "repost-1",
originalPostId: "orig-1",
reposterPetId: "pet-1",
createdAt: new Date(),
});
mockPrisma.post.delete.mockResolvedValue({ id: "repost-1" });
mockPrisma.post.update.mockResolvedValue({ id: "orig-1", repostCount: 0 });
await expect(
caller.reposts.delete({ originalPostId: "orig-1", reposterPetId: "pet-1" })
).resolves.not.toThrow();
expect(mockPrisma.post.delete).toHaveBeenCalledWith({ where: { id: "repost-1" } });
expect(mockPrisma.post.update).toHaveBeenCalledWith(
expect.objectContaining({
where: { id: "orig-1" },
data: { repostCount: { decrement: 1 } },
})
);
});
});
+3 -2
View File
@@ -204,7 +204,8 @@ type TrendingPost = {
pet: { id: string; name: string; avatarKey: string | null };
images: { storageKey: string; position: number }[];
milestone: { milestoneType: string; notes: string | null } | null;
_count: { reactions: number; comments: number };
reactionCount: number;
commentCount: number;
};
type TrendingHashtag = {
@@ -310,7 +311,7 @@ function TrendingContent({
<div className="absolute bottom-1 left-1 flex items-center gap-0.5 bg-black/50 rounded px-1 py-0.5">
<span className="text-white text-[10px]">🐾</span>
<span className="text-white text-[10px] font-medium">
{post._count.reactions}
{post.reactionCount}
</span>
</div>
{isCarousel && (
+12 -5
View File
@@ -1,6 +1,8 @@
import type { Metadata } from "next";
import { FeedList } from "@/components/feed/FeedList";
import { StoryTray } from "@/components/stories/StoryTray";
import { FeedHeader } from "@/components/feed/FeedHeader";
import { FeedPullToRefresh } from "@/components/feed/FeedPullToRefresh";
export const metadata: Metadata = {
title: "Home — PawFeed",
@@ -8,11 +10,16 @@ export const metadata: Metadata = {
export default function FeedPage() {
return (
<div className="max-w-[640px] mx-auto py-8">
<StoryTray />
<div className="px-6">
<FeedList />
<>
<FeedHeader />
<div className="max-w-[640px] mx-auto pt-12 pb-8 lg:pt-8">
<StoryTray />
<FeedPullToRefresh>
<div className="px-6">
<FeedList />
</div>
</FeedPullToRefresh>
</div>
</div>
</>
);
}
+41 -13
View File
@@ -3,7 +3,7 @@
import { useQuery } from "@tanstack/react-query";
import { useTRPC } from "@/trpc/client";
import { useState } from "react";
import { Check, Copy, Loader2, UserCheck, Clock } from "lucide-react";
import { Check, Copy, Loader2, UserCheck, Clock, Share2 } from "lucide-react";
import { toast } from "sonner";
export default function InvitePage() {
@@ -14,15 +14,32 @@ export default function InvitePage() {
const available = codes.filter((c) => !c.usedById && !c.revoked);
const used = codes.filter((c) => c.usedById || c.revoked);
const canShare = typeof navigator !== "undefined" && typeof navigator.share === "function";
function inviteUrl(code: string) {
return `${window.location.origin}/join?code=${code}`;
}
function copyLink(code: string, id: string) {
const url = `${window.location.origin}/join?code=${code}`;
void navigator.clipboard.writeText(url).then(() => {
void navigator.clipboard.writeText(inviteUrl(code)).then(() => {
setCopiedId(id);
toast.success("Link kopiert!");
setTimeout(() => setCopiedId(null), 2000);
});
}
async function shareLink(code: string) {
try {
await navigator.share({
title: "Du bist zu PawFeed eingeladen!",
text: "Erstelle ein Profil für dein Tier auf PawFeed – der sozialen Plattform für Haustiere 🐾",
url: inviteUrl(code),
});
} catch {
// User cancelled share sheet — no action needed
}
}
if (isLoading) {
return (
<div className="flex justify-center py-24">
@@ -81,17 +98,28 @@ export default function InvitePage() {
: ""}
</span>
) : (
<button
onClick={() => copyLink(code.code, code.id)}
className="shrink-0 flex items-center gap-1.5 text-xs text-muted-foreground hover:text-foreground transition-colors"
>
{copiedId === code.id ? (
<Check className="h-3.5 w-3.5 text-green-500" />
) : (
<Copy className="h-3.5 w-3.5" />
<div className="shrink-0 flex items-center gap-3">
{canShare && (
<button
onClick={() => void shareLink(code.code)}
className="flex items-center gap-1.5 text-xs text-orange-500 hover:text-orange-600 transition-colors font-medium"
>
<Share2 className="h-3.5 w-3.5" />
Teilen
</button>
)}
{copiedId === code.id ? "Kopiert" : "Link kopieren"}
</button>
<button
onClick={() => copyLink(code.code, code.id)}
className="flex items-center gap-1.5 text-xs text-muted-foreground hover:text-foreground transition-colors"
>
{copiedId === code.id ? (
<Check className="h-3.5 w-3.5 text-green-500" />
) : (
<Copy className="h-3.5 w-3.5" />
)}
{copiedId === code.id ? "Kopiert" : "Kopieren"}
</button>
</div>
)}
</div>
);
+4 -15
View File
@@ -9,23 +9,12 @@ import { useActivePet } from "@/context/ActivePetContext";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { Badge } from "@/components/ui/badge";
import { getAvatarUrl } from "@/lib/avatar-url";
type TFunc = (key: string, opts?: Record<string, string | number>) => string;
function formatRelativeTime(date: Date | string, t: TFunc): string {
const diffMs = Date.now() - new Date(date).getTime();
const diffMins = Math.floor(diffMs / 60000);
const diffHours = Math.floor(diffMins / 60);
const diffDays = Math.floor(diffHours / 24);
if (diffMins < 1) return t("timeNow");
if (diffMins < 60) return t("relativeMinutes", { count: diffMins });
if (diffHours < 24) return t("relativeHours", { count: diffHours });
if (diffDays < 7) return t("relativeDays", { count: diffDays });
return new Date(date).toLocaleDateString();
}
import { formatRelativeCompact } from "@/lib/format-relative-time";
export default function MessagesPage() {
const t = useTranslations("Messages");
const trt = useTranslations("RelativeTime");
const formatRelativeTime = (date: Date | string) => formatRelativeCompact(date, trt);
const trpc = useTRPC();
const router = useRouter();
const { activePetId } = useActivePet();
@@ -87,7 +76,7 @@ export default function MessagesPage() {
{conv.otherPet.name}
</p>
<span className="text-xs text-muted-foreground shrink-0">
{formatRelativeTime(conv.updatedAt, t as TFunc)}
{formatRelativeTime(conv.updatedAt)}
</span>
</div>
<div className="flex items-center justify-between gap-2 mt-0.5">
+12 -15
View File
@@ -3,28 +3,17 @@
import { useEffect } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { Bell, UserPlus, Heart, MessageCircle, Cake, Home } from "lucide-react";
import { Bell, UserPlus, Heart, MessageCircle, Cake, Home, AtSign, Repeat2 } from "lucide-react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { useTRPC } from "@/trpc/client";
import { useActivePet } from "@/context/ActivePetContext";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { getAvatarUrl } from "@/lib/avatar-url";
import { getMediaUrl } from "@/lib/media-url";
import { useTranslations } from "next-intl";
import { formatRelativeCompact } from "@/lib/format-relative-time";
function formatRelativeTime(date: Date | string): string {
const diffMs = Date.now() - new Date(date).getTime();
const diffMins = Math.floor(diffMs / 60000);
const diffHours = Math.floor(diffMins / 60);
const diffDays = Math.floor(diffHours / 24);
if (diffMins < 1) return "just now";
if (diffMins < 60) return `${diffMins}m`;
if (diffHours < 24) return `${diffHours}h`;
if (diffDays < 7) return `${diffDays}d`;
return new Date(date).toLocaleDateString();
}
type NotificationType = "FOLLOW" | "REACTION" | "COMMENT" | "MESSAGE" | "BIRTHDAY" | "ADOPTION_DAY";
type NotificationType = "FOLLOW" | "REACTION" | "COMMENT" | "MESSAGE" | "BIRTHDAY" | "ADOPTION_DAY" | "MENTION" | "PAW_BACK";
function notificationIcon(type: NotificationType) {
switch (type) {
@@ -34,6 +23,8 @@ function notificationIcon(type: NotificationType) {
case "MESSAGE": return <MessageCircle className="h-4 w-4 text-blue-500" />;
case "BIRTHDAY": return <Cake className="h-4 w-4 text-pink-500" />;
case "ADOPTION_DAY": return <Home className="h-4 w-4 text-emerald-500" />;
case "MENTION": return <AtSign className="h-4 w-4 text-violet-500" />;
case "PAW_BACK": return <Repeat2 className="h-4 w-4 text-orange-500" />;
}
}
@@ -42,6 +33,8 @@ export default function NotificationsPage() {
const queryClient = useQueryClient();
const router = useRouter();
const { activePetId } = useActivePet();
const trt = useTranslations("RelativeTime");
const formatRelativeTime = (date: Date | string) => formatRelativeCompact(date, trt);
const { data, isLoading } = useQuery({
...trpc.notifications.list.queryOptions({ petId: activePetId ?? "", limit: 30 }),
@@ -73,6 +66,8 @@ export default function NotificationsPage() {
return notif.actorPet ? `/pets/${notif.actorPet.id}` : null;
case "REACTION":
case "COMMENT":
case "MENTION":
case "PAW_BACK":
return notif.post?.petId ? `/pets/${notif.post.petId}` : null;
case "MESSAGE":
return null;
@@ -181,6 +176,8 @@ export default function NotificationsPage() {
)}
{notif.type === "COMMENT" && !notif.comment && "commented on your post"}
{notif.type === "MESSAGE" && "sent you a message"}
{notif.type === "MENTION" && "mentioned you in a comment"}
{notif.type === "PAW_BACK" && "shared your post (Paw-Back)"}
{notif.type === "BIRTHDAY" && "🎂 Alles Gute zum Geburtstag! Erstelle einen Jubiläums-Post."}
{notif.type === "ADOPTION_DAY" && "🏠 Heute ist der Adoptionstag! Feiere den Jahrestag."}
</span>
@@ -31,7 +31,7 @@ export default async function FollowersPage({ params }: PageProps) {
if (!pet) notFound();
const followers = await trpc.follows.listFollowers({ petId });
const { items: followers } = await trpc.follows.listFollowers({ petId });
return (
<div className="max-w-[480px] mx-auto px-4 py-6">
@@ -31,7 +31,7 @@ export default async function FollowingPage({ params }: PageProps) {
if (!pet) notFound();
const following = await trpc.follows.listFollowing({ petId });
const { items: following } = await trpc.follows.listFollowing({ petId });
return (
<div className="max-w-[480px] mx-auto px-4 py-6">
+1 -1
View File
@@ -50,7 +50,7 @@ export default async function PetProfilePage({ params }: PageProps) {
"owner")
: null;
const [followers, following] = await Promise.all([
const [{ items: followers }, { items: following }] = await Promise.all([
trpc.follows.listFollowers({ petId }),
trpc.follows.listFollowing({ petId }),
]);
+3
View File
@@ -2,6 +2,7 @@ import Link from "next/link";
import { createTRPCCaller } from "@/trpc/server";
import { buttonVariants } from "@/components/ui/button";
import { PetGrid } from "./PetGrid";
import { DeleteAccountDialog } from "@/components/account/DeleteAccountDialog";
/**
* My Pets page — /pets
@@ -31,6 +32,8 @@ export default async function PetsPage() {
<Link href="/datenschutz" className="hover:text-foreground transition-colors">Datenschutz</Link>
<span aria-hidden="true">·</span>
<Link href="/nutzungsbedingungen" className="hover:text-foreground transition-colors">AGB</Link>
<span aria-hidden="true">·</span>
<DeleteAccountDialog petNames={pets.map((p) => p.name)} />
</div>
</div>
);
+68
View File
@@ -0,0 +1,68 @@
import { auth, clerkClient } from "@clerk/nextjs/server";
import { prisma } from "@/lib/prisma";
import { deleteFiles } from "@/lib/supabase-storage";
export async function POST(req: Request) {
const { userId } = await auth();
if (!userId) {
return Response.json({ error: "Unauthorized" }, { status: 401 });
}
const body = (await req.json()) as { petNameConfirmation?: string };
const confirmation = body.petNameConfirmation?.trim();
if (!confirmation) {
return Response.json({ error: "Pet name required" }, { status: 400 });
}
const pets = await prisma.pet.findMany({
where: { ownerId: userId },
select: {
id: true,
name: true,
avatarKey: true,
posts: {
where: { type: "PHOTO" },
select: { images: { select: { storageKey: true } } },
},
stories: { select: { storageKey: true } },
},
});
const validNames = pets.map((p) => p.name.toLowerCase());
if (!validNames.includes(confirmation.toLowerCase())) {
return Response.json({ error: "Pet name does not match" }, { status: 400 });
}
// Collect all Supabase storage keys across avatars, post images, and stories
const storageKeys: string[] = [];
for (const pet of pets) {
if (pet.avatarKey) storageKeys.push(pet.avatarKey);
for (const post of pet.posts) {
for (const image of post.images) {
storageKeys.push(image.storageKey);
}
}
for (const story of pet.stories) {
storageKeys.push(story.storageKey);
}
}
// Delete storage files — non-blocking on failure (logged inside deleteFiles)
await deleteFiles(storageKeys);
// Delete all pets — cascades posts, comments, reactions, follows, notifications, etc.
await prisma.pet.deleteMany({ where: { ownerId: userId } });
// Delete invite codes this owner issued
await prisma.inviteCode.deleteMany({ where: { issuedById: userId } });
// Delete Owner record — cascades AdminRole + UserBan
await prisma.owner.delete({ where: { id: userId } });
// Delete Clerk user account — this invalidates the current session
const clerk = await clerkClient();
await clerk.users.deleteUser(userId);
return Response.json({ success: true });
}
+31
View File
@@ -0,0 +1,31 @@
import { NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { redis } from "@/lib/redis";
import { trimFeed } from "@/lib/feed-helpers";
// Vercel cron sends `Authorization: Bearer <CRON_SECRET>`.
// Set CRON_SECRET in your Vercel environment variables.
function authorized(req: Request): boolean {
const secret = process.env.CRON_SECRET;
if (!secret) return false;
return req.headers.get("authorization") === `Bearer ${secret}`;
}
/**
* Trims every pet's Redis feed sorted set down to the documented 90-day
* retention window (feed-helpers.ts FEED_RETENTION_MS). Without this cron,
* feed:{petId} sorted sets grow unbounded forever.
*/
export async function GET(req: Request) {
if (!authorized(req)) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}
const pets = await prisma.pet.findMany({ select: { id: true } });
for (const pet of pets) {
await trimFeed(redis, pet.id);
}
return NextResponse.json({ ok: true, petsTrimmed: pets.length });
}
+42 -13
View File
@@ -38,6 +38,19 @@ export default function AdminInvitesPage() {
})
);
const backfill = useMutation(
trpc.admin.backfillInviteCodes.mutationOptions({
onSuccess: (result) => {
invalidate();
toast.success(
result.updated === 0
? "Alle User haben bereits Codes."
: `${result.updated} User haben jetzt ihre Codes erhalten.`
);
},
})
);
function copyLink(code: string, id: string) {
const url = `${window.location.origin}/join?code=${code}`;
void navigator.clipboard.writeText(url).then(() => {
@@ -60,19 +73,35 @@ export default function AdminInvitesPage() {
{available.length} verfügbar · {used.length} verwendet · {revoked.length} widerrufen
</p>
</div>
<Button
size="sm"
onClick={() => createRoot.mutate()}
disabled={createRoot.isPending}
className="bg-orange-500 hover:bg-orange-600 text-white"
>
{createRoot.isPending ? (
<Loader2 className="h-4 w-4 animate-spin mr-1.5" />
) : (
<Plus className="h-4 w-4 mr-1.5" />
)}
Root-Code erstellen
</Button>
<div className="flex gap-2">
<Button
size="sm"
variant="outline"
onClick={() => backfill.mutate()}
disabled={backfill.isPending}
className="border-zinc-700 text-zinc-300 hover:bg-zinc-800"
>
{backfill.isPending ? (
<Loader2 className="h-4 w-4 animate-spin mr-1.5" />
) : (
<Plus className="h-4 w-4 mr-1.5" />
)}
Codes nachträglich zuweisen
</Button>
<Button
size="sm"
onClick={() => createRoot.mutate()}
disabled={createRoot.isPending}
className="bg-orange-500 hover:bg-orange-600 text-white"
>
{createRoot.isPending ? (
<Loader2 className="h-4 w-4 animate-spin mr-1.5" />
) : (
<Plus className="h-4 w-4 mr-1.5" />
)}
Root-Code erstellen
</Button>
</div>
</div>
{isLoading ? (
+3 -3
View File
@@ -104,10 +104,10 @@ export default function AdminPostsPage() {
{post.caption ?? <em className="text-zinc-500">No caption</em>}
</p>
<p className="text-xs text-zinc-500">
{post.pet.name} · {post._count.reactions} 🐾 · {post._count.comments} 💬
{post._count.reports > 0 && (
{post.pet.name} · {post.reactionCount} 🐾 · {post.commentCount} 💬
{post.reportCount > 0 && (
<span className="ml-2 text-yellow-400">
⚑ {post._count.reports} report{post._count.reports !== 1 ? "s" : ""}
⚑ {post.reportCount} report{post.reportCount !== 1 ? "s" : ""}
</span>
)}
</p>
+2 -2
View File
@@ -202,11 +202,11 @@ export default function AdminReportsPage() {
<div className="flex gap-3 text-xs text-zinc-500 mt-1">
<span className="flex items-center gap-1">
<Heart className="h-3 w-3" />
{report.post._count.reactions}
{report.post.reactionCount}
</span>
<span className="flex items-center gap-1">
<MessageCircle className="h-3 w-3" />
{report.post._count.comments}
{report.post.commentCount}
</span>
</div>
</div>
@@ -0,0 +1,192 @@
"use client";
import { useState } from "react";
import { Trash2, TriangleAlert, Loader2, CheckCircle2 } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
type Step = "warning" | "confirm" | "loading" | "done";
type Props = {
petNames: string[];
};
export function DeleteAccountDialog({ petNames }: Props) {
const [open, setOpen] = useState(false);
const [step, setStep] = useState<Step>("warning");
const [input, setInput] = useState("");
const [error, setError] = useState<string | null>(null);
const isValidName = petNames.some(
(n) => n.toLowerCase() === input.trim().toLowerCase()
);
const handleOpen = () => {
setStep("warning");
setInput("");
setError(null);
setOpen(true);
};
const handleClose = () => {
if (step === "loading") return;
setOpen(false);
};
const handleDelete = async () => {
if (!isValidName) return;
setStep("loading");
setError(null);
try {
const res = await fetch("/api/account/delete", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ petNameConfirmation: input.trim() }),
});
if (!res.ok) {
const data = (await res.json()) as { error?: string };
throw new Error(data.error ?? "Unbekannter Fehler");
}
setStep("done");
setTimeout(() => {
window.location.replace("https://pawfeed.org");
}, 1500);
} catch (err) {
setError(err instanceof Error ? err.message : "Etwas ist schiefgelaufen");
setStep("confirm");
}
};
return (
<>
<button
type="button"
onClick={handleOpen}
className="text-xs text-destructive/50 hover:text-destructive transition-colors"
>
Konto löschen
</button>
<Dialog open={open} onOpenChange={handleClose}>
<DialogContent className="max-w-md">
{step === "warning" && (
<>
<DialogHeader>
<DialogTitle className="flex items-center gap-2 text-destructive">
<TriangleAlert className="h-5 w-5 shrink-0" />
Konto wirklich löschen?
</DialogTitle>
</DialogHeader>
<p className="text-sm text-muted-foreground mt-1">
Diese Aktion ist <strong>unwiderruflich</strong>. Folgendes wird dauerhaft gelöscht:
</p>
<ul className="mt-3 space-y-1.5 text-sm text-muted-foreground">
{[
"Alle Tierprofile",
"Alle Posts, Kommentare und Reaktionen",
"Alle Bilder und Videos",
"Alle Chats und Nachrichten",
"Alle Gesundheitsdaten",
"Dein PawFeed-Konto",
].map((item) => (
<li key={item} className="flex items-center gap-2">
<span className="text-destructive font-bold">✕</span>
{item}
</li>
))}
</ul>
<div className="flex gap-2 justify-end mt-4">
<Button variant="outline" onClick={handleClose}>
Abbrechen
</Button>
<Button variant="destructive" onClick={() => setStep("confirm")}>
Ich verstehe, weiter
</Button>
</div>
</>
)}
{step === "confirm" && (
<>
<DialogHeader>
<DialogTitle className="flex items-center gap-2 text-destructive">
<Trash2 className="h-5 w-5 shrink-0" />
Bestätigung erforderlich
</DialogTitle>
</DialogHeader>
<p className="text-sm text-muted-foreground mt-1">
Gib den Namen eines deiner Haustiere ein, um die Löschung zu bestätigen:
</p>
<div className="flex flex-wrap gap-1.5 mt-3">
{petNames.map((name) => (
<button
key={name}
type="button"
onClick={() => { setInput(name); setError(null); }}
className="text-xs bg-muted hover:bg-muted/70 rounded px-2 py-1 font-medium transition-colors"
>
{name}
</button>
))}
</div>
<Input
className="mt-3"
value={input}
onChange={(e) => { setInput(e.target.value); setError(null); }}
placeholder="Tiername eingeben…"
autoFocus
/>
{error && (
<p className="text-xs text-destructive mt-1">{error}</p>
)}
<div className="flex gap-2 justify-end mt-4">
<Button variant="outline" onClick={handleClose}>
Abbrechen
</Button>
<Button
variant="destructive"
disabled={!isValidName}
onClick={handleDelete}
>
Konto endgültig löschen
</Button>
</div>
</>
)}
{step === "loading" && (
<div className="flex flex-col items-center gap-4 py-10">
<Loader2 className="h-8 w-8 animate-spin text-orange-500" />
<p className="text-sm text-muted-foreground">Konto wird gelöscht…</p>
</div>
)}
{step === "done" && (
<div className="flex flex-col items-center gap-4 py-10">
<CheckCircle2 className="h-8 w-8 text-emerald-500" />
<p className="text-sm font-medium">Konto erfolgreich gelöscht.</p>
<p className="text-xs text-muted-foreground">Du wirst weitergeleitet…</p>
</div>
)}
</DialogContent>
</Dialog>
</>
);
}
+6 -12
View File
@@ -4,9 +4,11 @@ import { useState, useRef, useCallback, useEffect } from "react";
import { ExternalLink, PawPrint, MessageCircle, Repeat2, Loader2 } from "lucide-react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { toast } from "sonner";
import { useTranslations } from "next-intl";
import { useTRPC } from "@/trpc/client";
import { getMediaUrl } from "@/lib/media-url";
import { getAvatarUrl } from "@/lib/avatar-url";
import { formatRelativeCompact } from "@/lib/format-relative-time";
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
import { Textarea } from "@/components/ui/textarea";
import { Button } from "@/components/ui/button";
@@ -25,18 +27,6 @@ type AdCardAd = {
imageKey: string | null;
};
function formatRelative(date: Date | string): string {
const diffMs = Date.now() - new Date(date).getTime();
const diffMins = Math.floor(diffMs / 60000);
const diffHours = Math.floor(diffMins / 60);
const diffDays = Math.floor(diffHours / 24);
if (diffMins < 1) return "gerade eben";
if (diffMins < 60) return `${diffMins}m`;
if (diffHours < 24) return `${diffHours}h`;
if (diffDays < 7) return `${diffDays}d`;
return new Date(date).toLocaleDateString("de-DE");
}
interface AdCardProps {
ad: AdCardAd;
activePetId: string;
@@ -45,6 +35,8 @@ interface AdCardProps {
export function AdCard({ ad, activePetId }: AdCardProps) {
const trpc = useTRPC();
const queryClient = useQueryClient();
const trt = useTranslations("RelativeTime");
const formatRelative = (date: Date | string) => formatRelativeCompact(date, trt);
const imageUrl = getMediaUrl(ad.imageKey);
// ── Interaction data ────────────────────────────────────────────────────────
@@ -274,6 +266,8 @@ interface AdCommentSheetProps {
function AdCommentSheet({ adId, petId, open, onOpenChange }: AdCommentSheetProps) {
const trpc = useTRPC();
const queryClient = useQueryClient();
const trt = useTranslations("RelativeTime");
const formatRelative = (date: Date | string) => formatRelativeCompact(date, trt);
const [body, setBody] = useState("");
const textareaRef = useRef<HTMLTextAreaElement>(null);
+33
View File
@@ -0,0 +1,33 @@
"use client";
import { useState, useEffect } from "react";
import { PawPrint } from "lucide-react";
export function FeedHeader() {
const [visible, setVisible] = useState(true);
useEffect(() => {
const mainEl = document.querySelector("main");
if (!mainEl) return;
const handleScroll = () => {
setVisible(mainEl.scrollTop < 60);
};
mainEl.addEventListener("scroll", handleScroll, { passive: true });
return () => mainEl.removeEventListener("scroll", handleScroll);
}, []);
return (
<div
className={`lg:hidden fixed top-0 left-0 right-0 z-40 flex items-center justify-center py-3 bg-background/90 backdrop-blur-sm border-b transition-transform duration-200 ${
visible ? "translate-y-0" : "-translate-y-full"
}`}
>
<div className="flex items-center gap-1.5">
<PawPrint className="h-5 w-5 text-orange-500" aria-hidden="true" />
<span className="text-lg font-semibold">PawFeed</span>
</div>
</div>
);
}
+98
View File
@@ -0,0 +1,98 @@
"use client";
import { useState, useEffect, useRef, useCallback } from "react";
import { Loader2 } from "lucide-react";
import { useQueryClient } from "@tanstack/react-query";
const PULL_THRESHOLD = 70;
export function FeedPullToRefresh({ children }: { children: React.ReactNode }) {
const queryClient = useQueryClient();
const [pullY, setPullY] = useState(0);
const [refreshing, setRefreshing] = useState(false);
const startYRef = useRef(0);
const isPullingRef = useRef(false);
const pullYRef = useRef(0);
const refreshingRef = useRef(false);
const triggerRefresh = useCallback(async () => {
refreshingRef.current = true;
setRefreshing(true);
setPullY(0);
pullYRef.current = 0;
try {
await queryClient.invalidateQueries({ queryKey: [["feed", "getFeed"]] });
} finally {
// Keep spinner visible briefly so fast refreshes still feel intentional
await new Promise((res) => setTimeout(res, 600));
refreshingRef.current = false;
setRefreshing(false);
}
}, [queryClient]);
useEffect(() => {
const mainEl = document.querySelector("main");
if (!mainEl) return;
const onTouchStart = (e: TouchEvent) => {
if (mainEl.scrollTop === 0 && !refreshingRef.current) {
startYRef.current = e.touches[0]!.clientY;
isPullingRef.current = true;
}
};
const onTouchMove = (e: TouchEvent) => {
if (!isPullingRef.current) return;
const deltaY = e.touches[0]!.clientY - startYRef.current;
if (deltaY > 0 && mainEl.scrollTop === 0) {
const dampened = Math.min(deltaY * 0.45, PULL_THRESHOLD + 24);
pullYRef.current = dampened;
setPullY(dampened);
}
};
const onTouchEnd = () => {
if (!isPullingRef.current) return;
isPullingRef.current = false;
if (pullYRef.current >= PULL_THRESHOLD) {
void triggerRefresh();
} else {
pullYRef.current = 0;
setPullY(0);
}
};
mainEl.addEventListener("touchstart", onTouchStart, { passive: true });
mainEl.addEventListener("touchmove", onTouchMove, { passive: true });
mainEl.addEventListener("touchend", onTouchEnd, { passive: true });
return () => {
mainEl.removeEventListener("touchstart", onTouchStart);
mainEl.removeEventListener("touchmove", onTouchMove);
mainEl.removeEventListener("touchend", onTouchEnd);
};
}, [triggerRefresh]);
const showIndicator = pullY > 8 || refreshing;
const progress = Math.min(pullY / PULL_THRESHOLD, 1);
return (
<div className="relative">
{showIndicator && (
<div
className="absolute left-1/2 z-50 -translate-x-1/2 w-8 h-8 rounded-full bg-background border shadow-md flex items-center justify-center"
style={{
top: refreshing ? 8 : Math.max(pullY - 44, 4),
opacity: refreshing ? 1 : progress,
}}
>
<Loader2
className={`h-4 w-4 text-orange-500 ${refreshing ? "animate-spin" : ""}`}
style={!refreshing ? { transform: `rotate(${progress * 270}deg)` } : undefined}
/>
</div>
)}
{children}
</div>
);
}
+7 -17
View File
@@ -38,6 +38,7 @@ import Link from "next/link";
import { getAvatarUrl } from "@/lib/avatar-url";
import { getMediaUrl } from "@/lib/media-url";
import { parseCaption } from "@/lib/parse-caption";
import { formatRelativeVerbose } from "@/lib/format-relative-time";
import { PawRing } from "@/components/stories/PawRing";
import { MilestoneCard } from "@/components/feed/MilestoneCard";
import { VideoCard } from "@/components/video/VideoCard";
@@ -95,7 +96,8 @@ export type PostCardPost = {
pet: PostPet;
images: PostImage[];
milestone: PostMilestone | null;
_count?: { reactions: number; comments: number } | null;
reactionCount?: number;
commentCount?: number;
repost?: {
originalPostId: string;
reposterPetId: string;
@@ -123,19 +125,7 @@ export function PostCard({ post, onDeleted, variant = "feed" }: PostCardProps) {
const trpc = useTRPC();
const { activePetId } = useActivePet();
function formatRelativeTime(date: Date | string): string {
const now = Date.now();
const diffMs = now - new Date(date).getTime();
const diffSecs = Math.floor(diffMs / 1000);
const diffMins = Math.floor(diffSecs / 60);
const diffHours = Math.floor(diffMins / 60);
const diffDays = Math.floor(diffHours / 24);
if (diffSecs < 60) return t("justNow");
if (diffMins < 60) return t("minutesAgo", { count: diffMins });
if (diffHours < 24) return t("hoursAgo", { count: diffHours });
if (diffDays < 7) return t("daysAgo", { count: diffDays });
return new Date(date).toLocaleDateString();
}
const formatRelativeTime = (date: Date | string) => formatRelativeVerbose(date, t);
const { pet, images, createdAt } = post;
const [currentCaption, setCurrentCaption] = useState(post.caption);
@@ -469,7 +459,7 @@ export function PostCard({ post, onDeleted, variant = "feed" }: PostCardProps) {
<PawButton
postId={post.id}
petId={activePetId}
initialCount={post._count?.reactions ?? 0}
initialCount={post.reactionCount ?? 0}
initialReacted={false}
/>
<button
@@ -479,8 +469,8 @@ export function PostCard({ post, onDeleted, variant = "feed" }: PostCardProps) {
className="flex items-center gap-1.5 text-sm text-muted-foreground hover:text-foreground transition-colors"
>
<MessageCircle className="h-4 w-4" aria-hidden="true" />
{(post._count?.comments ?? 0) > 0 && (
<span>{post._count!.comments}</span>
{(post.commentCount ?? 0) > 0 && (
<span>{post.commentCount}</span>
)}
</button>
<PawBackButton postId={post.id} petId={activePetId} />
+13 -14
View File
@@ -39,9 +39,11 @@ import Link from "next/link";
import { getAvatarUrl } from "@/lib/avatar-url";
import { getMediaUrl } from "@/lib/media-url";
import { parseCaption } from "@/lib/parse-caption";
import { formatRelativeCompact } from "@/lib/format-relative-time";
import { PawButton } from "@/components/feed/PawButton";
import { PawBackButton } from "@/components/feed/PawBackButton";
import { PawRing } from "@/components/stories/PawRing";
import { VideoCard } from "@/components/video/VideoCard";
import type { PostCardPost } from "@/components/feed/PostCard";
import { useTranslations } from "next-intl";
@@ -55,6 +57,7 @@ interface PostDetailDialogProps {
export function PostDetailDialog({ post, open, onClose, onDeleted }: PostDetailDialogProps) {
const t = useTranslations("PostCard");
const tc = useTranslations("Comments");
const trt = useTranslations("RelativeTime");
const trpc = useTRPC();
const { activePetId } = useActivePet();
const queryClient = useQueryClient();
@@ -163,17 +166,7 @@ export function PostDetailDialog({ post, open, onClose, onDeleted }: PostDetailD
[handleSubmitComment]
);
function formatRelativeTime(date: Date | string): string {
const diffMs = Date.now() - new Date(date).getTime();
const diffMins = Math.floor(diffMs / 60000);
const diffHours = Math.floor(diffMins / 60);
const diffDays = Math.floor(diffHours / 24);
if (diffMins < 1) return tc("justNow");
if (diffMins < 60) return `${diffMins}m`;
if (diffHours < 24) return `${diffHours}h`;
if (diffDays < 7) return `${diffDays}d`;
return new Date(date).toLocaleDateString();
}
const formatRelativeTime = (date: Date | string) => formatRelativeCompact(date, trt);
if (!post) return null;
@@ -242,7 +235,13 @@ export function PostDetailDialog({ post, open, onClose, onDeleted }: PostDetailD
</>
);
const imageContent = images.length > 0 && (
const mediaContent = post.type === "VIDEO" && post.videoPost ? (
<VideoCard
postId={post.id}
initialStatus={post.videoPost.status}
initialPlaybackId={post.videoPost.muxPlaybackId}
/>
) : images.length > 0 && (
isCarousel ? (
<div className="relative w-full h-full">
<Carousel setApi={setCarouselApi} className="h-full">
@@ -304,7 +303,7 @@ export function PostDetailDialog({ post, open, onClose, onDeleted }: PostDetailD
{/* Image column — fixed 45dvh strip on mobile, flex-1 full-height on desktop */}
<div className="shrink-0 h-[45dvh] md:h-full md:flex-1 md:min-w-0 bg-black flex items-center justify-center">
{imageContent}
{mediaContent}
</div>
{/* Right panel: desktop header + scrollable body + sticky input */}
@@ -372,7 +371,7 @@ export function PostDetailDialog({ post, open, onClose, onDeleted }: PostDetailD
<PawButton
postId={post.id}
petId={activePetId}
initialCount={post._count?.reactions ?? 0}
initialCount={post.reactionCount ?? 0}
initialReacted={false}
/>
<PawBackButton postId={post.id} petId={activePetId} />
+1 -1
View File
@@ -110,7 +110,7 @@ export function MessageThread({ conversationId, otherPet }: MessageThreadProps)
}
return (
<div className="flex flex-col h-[100dvh] max-h-[100dvh]">
<div className="flex flex-col h-[100dvh] max-h-[100dvh] pb-32 lg:pb-0">
{/* Header */}
<div className="flex items-center gap-3 px-4 py-3 border-b bg-card shrink-0">
<button
+1 -1
View File
@@ -109,7 +109,7 @@ export function MentionTextarea({
const pets = data?.pets ?? [];
return (
<div className="relative">
<div className="relative flex-1 min-w-0">
<Textarea
ref={mergedRef}
value={value}
+23
View File
@@ -0,0 +1,23 @@
import "server-only";
import { TRPCError } from "@trpc/server";
import type { PrismaClient } from "@prisma/client";
/**
* Ownership assertion — verifies that a pet belongs to the requesting owner
* before any mutation or scoped query proceeds. Never trust a client-supplied
* petId without this check first.
*/
export async function assertPetOwnership(
prisma: PrismaClient,
petId: string,
userId: string
) {
const pet = await prisma.pet.findUnique({ where: { id: petId } });
if (!pet || pet.ownerId !== userId) {
throw new TRPCError({
code: "FORBIDDEN",
message: "You do not have permission to access this pet.",
});
}
return pet;
}
+36
View File
@@ -0,0 +1,36 @@
type TFunc = (key: string, values?: Record<string, string | number>) => string;
/**
* Compact style: "5m", "3h", "2d". Used anywhere space is tight
* (comment lists, notifications, ad cards, message previews).
* Pass a translator scoped to the "RelativeTime" namespace.
*/
export function formatRelativeCompact(date: Date | string, t: TFunc): string {
const diffMs = Date.now() - new Date(date).getTime();
const diffMins = Math.floor(diffMs / 60000);
const diffHours = Math.floor(diffMins / 60);
const diffDays = Math.floor(diffHours / 24);
if (diffMins < 1) return t("justNow");
if (diffMins < 60) return t("minutes", { count: diffMins });
if (diffHours < 24) return t("hours", { count: diffHours });
if (diffDays < 7) return t("days", { count: diffDays });
return new Date(date).toLocaleDateString();
}
/**
* Verbose style: "5 minutes ago", "3 hours ago". Used where there's
* room to be explicit (main feed post cards).
* Pass a translator with justNow/minutesAgo/hoursAgo/daysAgo keys.
*/
export function formatRelativeVerbose(date: Date | string, t: TFunc): string {
const diffMs = Date.now() - new Date(date).getTime();
const diffSecs = Math.floor(diffMs / 1000);
const diffMins = Math.floor(diffSecs / 60);
const diffHours = Math.floor(diffMins / 60);
const diffDays = Math.floor(diffHours / 24);
if (diffSecs < 60) return t("justNow");
if (diffMins < 60) return t("minutesAgo", { count: diffMins });
if (diffHours < 24) return t("hoursAgo", { count: diffHours });
if (diffDays < 7) return t("daysAgo", { count: diffDays });
return new Date(date).toLocaleDateString();
}
+54
View File
@@ -0,0 +1,54 @@
import "server-only";
import type { PrismaClient } from "@prisma/client";
// g-flag regex is stateful — reset lastIndex before and after each use
const MENTION_REGEX = /@(\w{1,50})/g;
const MAX_MENTIONS = 10;
export function extractMentionNames(text: string | null | undefined): string[] {
if (!text) return [];
MENTION_REGEX.lastIndex = 0;
const matches: string[] = [];
let match: RegExpExecArray | null;
while ((match = MENTION_REGEX.exec(text)) !== null) {
matches.push(match[1]!);
if (matches.length >= MAX_MENTIONS) break;
}
MENTION_REGEX.lastIndex = 0;
return [...new Set(matches)];
}
export async function createMentionNotifications(
prisma: PrismaClient,
text: string | null | undefined,
actorPetId: string,
postId: string,
commentId?: string
): Promise<void> {
const names = extractMentionNames(text);
if (names.length === 0) return;
const mentionedPets = await prisma.pet.findMany({
where: {
name: { in: names, mode: "insensitive" },
id: { not: actorPetId },
},
select: { id: true },
});
await Promise.all(
mentionedPets.map((pet) =>
prisma.notification
.create({
data: {
recipientPetId: pet.id,
type: "MENTION",
actorPetId,
postId,
...(commentId ? { commentId } : {}),
},
})
.catch(() => {})
)
);
}
+14 -17
View File
@@ -3,23 +3,20 @@ import { MilestoneType } from "@prisma/client";
/**
* Hard-coded follower milestone thresholds and their corresponding MilestoneType enum values.
*
* Per D-09 and A3: these values are a constant array, not a DB table.
* Per D-09 and A3: these values are a constant map, not a DB table.
* Used by the follows router to detect when a follower count threshold is crossed
* and emit an auto-triggered milestone (D-10).
*/
export const FOLLOWER_MILESTONE_THRESHOLDS: Array<{
count: number;
type: MilestoneType;
}> = [
{ count: 500, type: MilestoneType.FOLLOWERS_500 },
{ count: 1_000, type: MilestoneType.FOLLOWERS_1K },
{ count: 2_500, type: MilestoneType.FOLLOWERS_2_5K },
{ count: 5_000, type: MilestoneType.FOLLOWERS_5K },
{ count: 10_000, type: MilestoneType.FOLLOWERS_10K },
{ count: 25_000, type: MilestoneType.FOLLOWERS_25K },
{ count: 50_000, type: MilestoneType.FOLLOWERS_50K },
{ count: 100_000, type: MilestoneType.FOLLOWERS_100K },
{ count: 250_000, type: MilestoneType.FOLLOWERS_250K },
{ count: 500_000, type: MilestoneType.FOLLOWERS_500K },
{ count: 1_000_000, type: MilestoneType.FOLLOWERS_1M },
];
export const FOLLOWER_MILESTONE_THRESHOLDS: Partial<Record<number, MilestoneType>> = {
500: MilestoneType.FOLLOWERS_500,
1000: MilestoneType.FOLLOWERS_1K,
2500: MilestoneType.FOLLOWERS_2_5K,
5000: MilestoneType.FOLLOWERS_5K,
10000: MilestoneType.FOLLOWERS_10K,
25000: MilestoneType.FOLLOWERS_25K,
50000: MilestoneType.FOLLOWERS_50K,
100000: MilestoneType.FOLLOWERS_100K,
250000: MilestoneType.FOLLOWERS_250K,
500000: MilestoneType.FOLLOWERS_500K,
1000000: MilestoneType.FOLLOWERS_1M,
};
-43
View File
@@ -1,43 +0,0 @@
import "server-only";
import { S3Client, PutObjectCommand } from "@aws-sdk/client-s3";
import { getSignedUrl } from "@aws-sdk/s3-request-presigner";
/**
* Cloudflare R2 client configured for presigned PUT uploads.
* This module is server-only — R2 credentials never reach the client bundle.
*
* Media bytes NEVER go through the API server.
* Flow: tRPC procedure generates presigned URL → client PUTs directly to R2.
*/
export const r2 = new S3Client({
region: "auto", // required by SDK but not used by R2
endpoint: `https://${process.env.CF_ACCOUNT_ID}.r2.cloudflarestorage.com`,
credentials: {
accessKeyId: process.env.R2_ACCESS_KEY_ID!,
secretAccessKey: process.env.R2_SECRET_ACCESS_KEY!,
},
});
/**
* Generate a presigned PUT URL for direct client-side upload to R2.
* The contentType MUST match what the browser sends in the PUT request
* (mismatch causes R2 to return 403 SignatureDoesNotMatch).
*
* @param key - R2 object key (e.g. "avatars/owner_xxx_1234567890.jpg")
* @param contentType - MIME type of the file being uploaded
* @returns A presigned URL string valid for 5 minutes
*/
export async function getPresignedUploadUrl(
key: string,
contentType: "image/jpeg" | "image/png" | "image/webp"
): Promise<string> {
return getSignedUrl(
r2,
new PutObjectCommand({
Bucket: process.env.R2_BUCKET_NAME!,
Key: key,
ContentType: contentType, // must match what browser sends in PUT
}),
{ expiresIn: 300 } // 5 minutes
);
}
+12
View File
@@ -40,3 +40,15 @@ export function getPublicUrl(key: string): string {
const { data } = getClient().storage.from(STORAGE_BUCKET).getPublicUrl(key);
return data.publicUrl;
}
/**
* Deletes a batch of storage objects by key. Non-throwing — storage cleanup
* failure is logged but must never block account deletion.
*/
export async function deleteFiles(keys: string[]): Promise<void> {
if (keys.length === 0) return;
const { error } = await getClient().storage.from(STORAGE_BUCKET).remove(keys);
if (error) {
console.error("[storage] deleteFiles partial failure:", error.message);
}
}
+62 -15
View File
@@ -80,7 +80,6 @@ export const adminRouter = router({
include: {
pet: { select: { id: true, name: true, avatarKey: true, ownerId: true } },
images: { orderBy: { position: "asc" }, take: 1 },
_count: { select: { reactions: true, comments: true, reports: true } },
},
orderBy: { createdAt: "desc" },
take: input.limit + 1,
@@ -88,7 +87,28 @@ export const adminRouter = router({
});
const hasNext = posts.length > input.limit;
const items = hasNext ? posts.slice(0, input.limit) : posts;
return { posts: items, nextCursor: hasNext ? items[items.length - 1]!.id : null };
// Report has no Prisma relation to Post (targetPostId is a raw string,
// not a FK — see listReports below), so report counts are computed
// separately rather than via _count.
const reportCounts = items.length
? await ctx.prisma.report.groupBy({
by: ["targetPostId"],
where: { targetPostId: { in: items.map((p) => p.id) } },
_count: true,
})
: [];
const reportCountMap = new Map(
reportCounts.map((r) => [r.targetPostId, r._count])
);
return {
posts: items.map((post) => ({
...post,
reportCount: reportCountMap.get(post.id) ?? 0,
})),
nextCursor: hasNext ? items[items.length - 1]!.id : null,
};
}),
deletePost: protectedProcedure
@@ -123,15 +143,21 @@ export const adminRouter = router({
.input(z.object({ commentId: z.string().min(1), reason: z.string().max(500).optional() }))
.mutation(async ({ ctx, input }) => {
await assertAdmin(ctx.prisma, ctx.userId);
await ctx.prisma.comment.delete({ where: { id: input.commentId } });
await ctx.prisma.moderationLog.create({
data: {
action: "DELETE_COMMENT",
targetType: "COMMENT",
targetId: input.commentId,
reason: input.reason ?? null,
moderatorId: ctx.userId,
},
await ctx.prisma.$transaction(async (tx) => {
const deleted = await tx.comment.delete({ where: { id: input.commentId } });
await tx.post.update({
where: { id: deleted.postId },
data: { commentCount: { decrement: 1 } },
});
await tx.moderationLog.create({
data: {
action: "DELETE_COMMENT",
targetType: "COMMENT",
targetId: input.commentId,
reason: input.reason ?? null,
moderatorId: ctx.userId,
},
});
});
return { success: true };
}),
@@ -238,13 +264,14 @@ export const adminRouter = router({
caption: true,
type: true,
createdAt: true,
reactionCount: true,
commentCount: true,
pet: { select: { id: true, name: true, avatarKey: true } },
images: {
orderBy: { position: "asc" },
take: 4,
select: { storageKey: true, position: true },
},
_count: { select: { reactions: true, comments: true } },
},
})
: [];
@@ -389,9 +416,6 @@ export const adminRouter = router({
OR: [{ startDate: null }, { startDate: { lte: now } }],
AND: [{ OR: [{ endDate: null }, { endDate: { gte: now } }] }],
},
include: {
_count: { select: { reactions: true, comments: true, reposts: true } },
},
orderBy: { createdAt: "desc" },
});
}),
@@ -470,4 +494,27 @@ export const adminRouter = router({
});
return { success: true };
}),
backfillInviteCodes: protectedProcedure.mutation(async ({ ctx }) => {
await assertAdmin(ctx.prisma, ctx.userId);
const { generateInviteCode, INVITE_CODES_PER_USER } = await import("@/lib/invite-codes");
const ownersWithoutCodes = await ctx.prisma.owner.findMany({
where: { NOT: { issuedInvites: { some: {} } } },
select: { id: true },
});
if (ownersWithoutCodes.length === 0) return { updated: 0 };
await ctx.prisma.inviteCode.createMany({
data: ownersWithoutCodes.flatMap(({ id }) =>
Array.from({ length: INVITE_CODES_PER_USER }, () => ({
code: generateInviteCode(),
issuedById: id,
}))
),
});
return { updated: ownersWithoutCodes.length };
}),
});
+66 -35
View File
@@ -7,25 +7,25 @@ export const adsRouter = router({
getFeedData: protectedProcedure
.input(z.object({ adId: z.string().min(1), petId: z.string().min(1) }))
.query(async ({ ctx, input }) => {
const [reactionCount, hasReacted, commentCount, repostCount, hasReposted] =
await Promise.all([
ctx.prisma.adReaction.count({ where: { adId: input.adId } }),
ctx.prisma.adReaction.findUnique({
where: { adId_petId: { adId: input.adId, petId: input.petId } },
select: { id: true },
}),
ctx.prisma.adComment.count({ where: { adId: input.adId } }),
ctx.prisma.adRepost.count({ where: { adId: input.adId } }),
ctx.prisma.adRepost.findUnique({
where: { adId_petId: { adId: input.adId, petId: input.petId } },
select: { id: true },
}),
]);
const [ad, hasReacted, hasReposted] = await Promise.all([
ctx.prisma.advertisement.findUnique({
where: { id: input.adId },
select: { adReactionCount: true, adCommentCount: true, adRepostCount: true },
}),
ctx.prisma.adReaction.findUnique({
where: { adId_petId: { adId: input.adId, petId: input.petId } },
select: { id: true },
}),
ctx.prisma.adRepost.findUnique({
where: { adId_petId: { adId: input.adId, petId: input.petId } },
select: { id: true },
}),
]);
return {
reactionCount,
reactionCount: ad?.adReactionCount ?? 0,
hasReacted: !!hasReacted,
commentCount,
repostCount,
commentCount: ad?.adCommentCount ?? 0,
repostCount: ad?.adRepostCount ?? 0,
hasReposted: !!hasReposted,
};
}),
@@ -37,13 +37,25 @@ export const adsRouter = router({
where: { adId_petId: { adId: input.adId, petId: input.petId } },
});
if (existing) {
await ctx.prisma.adReaction.delete({ where: { id: existing.id } });
const count = await ctx.prisma.adReaction.count({ where: { adId: input.adId } });
return { reacted: false, count };
const [, ad] = await ctx.prisma.$transaction([
ctx.prisma.adReaction.delete({ where: { id: existing.id } }),
ctx.prisma.advertisement.update({
where: { id: input.adId },
data: { adReactionCount: { decrement: 1 } },
select: { adReactionCount: true },
}),
]);
return { reacted: false, count: ad.adReactionCount };
} else {
await ctx.prisma.adReaction.create({ data: { adId: input.adId, petId: input.petId } });
const count = await ctx.prisma.adReaction.count({ where: { adId: input.adId } });
return { reacted: true, count };
const [, ad] = await ctx.prisma.$transaction([
ctx.prisma.adReaction.create({ data: { adId: input.adId, petId: input.petId } }),
ctx.prisma.advertisement.update({
where: { id: input.adId },
data: { adReactionCount: { increment: 1 } },
select: { adReactionCount: true },
}),
]);
return { reacted: true, count: ad.adReactionCount };
}
}),
@@ -69,12 +81,19 @@ export const adsRouter = router({
})
)
.mutation(async ({ ctx, input }) => {
return ctx.prisma.adComment.create({
data: { adId: input.adId, petId: input.petId, body: input.body },
include: {
pet: { select: { id: true, name: true, avatarKey: true } },
},
});
const [comment] = await ctx.prisma.$transaction([
ctx.prisma.adComment.create({
data: { adId: input.adId, petId: input.petId, body: input.body },
include: {
pet: { select: { id: true, name: true, avatarKey: true } },
},
}),
ctx.prisma.advertisement.update({
where: { id: input.adId },
data: { adCommentCount: { increment: 1 } },
}),
]);
return comment;
}),
toggleRepost: protectedProcedure
@@ -84,13 +103,25 @@ export const adsRouter = router({
where: { adId_petId: { adId: input.adId, petId: input.petId } },
});
if (existing) {
await ctx.prisma.adRepost.delete({ where: { id: existing.id } });
const count = await ctx.prisma.adRepost.count({ where: { adId: input.adId } });
return { reposted: false, count };
const [, ad] = await ctx.prisma.$transaction([
ctx.prisma.adRepost.delete({ where: { id: existing.id } }),
ctx.prisma.advertisement.update({
where: { id: input.adId },
data: { adRepostCount: { decrement: 1 } },
select: { adRepostCount: true },
}),
]);
return { reposted: false, count: ad.adRepostCount };
} else {
await ctx.prisma.adRepost.create({ data: { adId: input.adId, petId: input.petId } });
const count = await ctx.prisma.adRepost.count({ where: { adId: input.adId } });
return { reposted: true, count };
const [, ad] = await ctx.prisma.$transaction([
ctx.prisma.adRepost.create({ data: { adId: input.adId, petId: input.petId } }),
ctx.prisma.advertisement.update({
where: { id: input.adId },
data: { adRepostCount: { increment: 1 } },
select: { adRepostCount: true },
}),
]);
return { reposted: true, count: ad.adRepostCount };
}
}),
});
+17 -26
View File
@@ -2,28 +2,7 @@ import "server-only";
import { z } from "zod";
import { TRPCError } from "@trpc/server";
import { router, protectedProcedure } from "@/trpc/init";
import type { PrismaClient } from "@prisma/client";
/**
* Ownership assertion helper — verifies that a pet belongs to the requesting
* owner before any mutation or scoped query proceeds.
*
* Security (T-02-10): never trust client-supplied petId — acting pet must belong to ctx.userId.
*/
async function assertPetOwnership(
prisma: PrismaClient,
petId: string,
userId: string
) {
const pet = await prisma.pet.findUnique({ where: { id: petId } });
if (!pet || pet.ownerId !== userId) {
throw new TRPCError({
code: "FORBIDDEN",
message: "You do not have permission to access this pet.",
});
}
return pet;
}
import { assertPetOwnership } from "@/lib/assert-pet-ownership";
/**
* Blocks tRPC router — safety baseline (SAFE-01).
@@ -93,10 +72,22 @@ export const blocksRouter = router({
// Assert ownership — only the owner can query their own block list
await assertPetOwnership(ctx.prisma, input.petId, ctx.userId);
return ctx.prisma.block.findMany({
where: { blockerPetId: input.petId },
select: { blockedPetId: true },
take: input.limit,
const rows = await ctx.prisma.block.findMany({
where: {
blockerPetId: input.petId,
...(input.cursor ? { createdAt: { lt: new Date(input.cursor) } } : {}),
},
select: { blockedPetId: true, createdAt: true },
orderBy: { createdAt: "desc" },
take: input.limit + 1,
});
const hasNextPage = rows.length > input.limit;
const items = hasNextPage ? rows.slice(0, input.limit) : rows;
const nextCursor = hasNextPage
? items[items.length - 1]!.createdAt.toISOString()
: null;
return { items, nextCursor };
}),
});
+22 -20
View File
@@ -2,22 +2,8 @@ import "server-only";
import { z } from "zod";
import { TRPCError } from "@trpc/server";
import { router, protectedProcedure } from "@/trpc/init";
import type { PrismaClient } from "@prisma/client";
async function assertPetOwnership(
prisma: PrismaClient,
petId: string,
userId: string
) {
const pet = await prisma.pet.findUnique({ where: { id: petId } });
if (!pet || pet.ownerId !== userId) {
throw new TRPCError({
code: "FORBIDDEN",
message: "You do not have permission to access this pet.",
});
}
return pet;
}
import { createMentionNotifications } from "@/lib/mention-helpers";
import { assertPetOwnership } from "@/lib/assert-pet-ownership";
export const commentsRouter = router({
create: protectedProcedure
@@ -31,7 +17,7 @@ export const commentsRouter = router({
.mutation(async ({ ctx, input }) => {
await assertPetOwnership(ctx.prisma, input.petId, ctx.userId);
const [comment, post] = await Promise.all([
const [comment, post] = await ctx.prisma.$transaction([
ctx.prisma.comment.create({
data: {
postId: input.postId,
@@ -42,14 +28,15 @@ export const commentsRouter = router({
pet: { select: { id: true, name: true, avatarKey: true } },
},
}),
ctx.prisma.post.findUnique({
ctx.prisma.post.update({
where: { id: input.postId },
data: { commentCount: { increment: 1 } },
select: { petId: true },
}),
]);
// NOTF-03: notify post owner (skip self-comments)
if (post && post.petId !== input.petId) {
if (post.petId !== input.petId) {
ctx.prisma.notification
.create({
data: {
@@ -63,6 +50,15 @@ export const commentsRouter = router({
.catch(() => {});
}
// Notify all @mentioned pets in the comment body
createMentionNotifications(
ctx.prisma,
input.body,
input.petId,
input.postId,
comment.id
).catch(() => {});
return comment;
}),
@@ -115,6 +111,12 @@ export const commentsRouter = router({
});
}
await ctx.prisma.comment.delete({ where: { id: input.commentId } });
await ctx.prisma.$transaction([
ctx.prisma.comment.delete({ where: { id: input.commentId } }),
ctx.prisma.post.update({
where: { id: comment.postId },
data: { commentCount: { decrement: 1 } },
}),
]);
}),
});
+2 -3
View File
@@ -20,10 +20,10 @@ export const exploreRouter = router({
where: {
...(input.speciesId ? { speciesId: input.speciesId } : {}),
...(input.breedId ? { breedId: input.breedId } : {}),
...(input.cursor ? { id: { gt: input.cursor } } : {}),
},
orderBy: { createdAt: "desc" },
take: input.limit + 1,
...(input.cursor ? { skip: 1, cursor: { id: input.cursor } } : {}),
include: {
species: true,
breed: true,
@@ -55,9 +55,8 @@ export const exploreRouter = router({
images: { orderBy: { position: "asc" } },
pet: { select: { id: true, name: true, avatarKey: true } },
milestone: true,
_count: { select: { reactions: true, comments: true } },
},
orderBy: { reactions: { _count: "desc" } },
orderBy: { reactionCount: "desc" },
take: 12,
}),
ctx.prisma.hashtag.findMany({
+5 -22
View File
@@ -1,31 +1,15 @@
import "server-only";
import { z } from "zod";
import { TRPCError } from "@trpc/server";
import { router, protectedProcedure } from "@/trpc/init";
import { redis } from "@/lib/redis";
import { getFeedPage } from "@/lib/feed-helpers";
import type { PrismaClient } from "@prisma/client";
async function assertPetOwnership(
prisma: PrismaClient,
petId: string,
userId: string
) {
const pet = await prisma.pet.findUnique({ where: { id: petId } });
if (!pet || pet.ownerId !== userId) {
throw new TRPCError({
code: "FORBIDDEN",
message: "You do not have permission to access this pet.",
});
}
return pet;
}
import { assertPetOwnership } from "@/lib/assert-pet-ownership";
// Engagement-based ranking score for the algorithmic feed.
// Recency decays logarithmically; reaction/comment/repost weights are tuned
// so a post with 1 comment outranks a post with 3 reactions (comments signal intent).
function algoScore(
post: { _count: { reactions: number; comments: number; originalReposts: number }; createdAt: Date | string },
post: { reactionCount: number; commentCount: number; repostCount: number; createdAt: Date | string },
now: Date
): number {
const ageHours =
@@ -33,9 +17,9 @@ function algoScore(
const recency =
ageHours < 2 ? 10 : ageHours < 6 ? 5 : ageHours < 24 ? 2 : 0;
return (
post._count.reactions * 3 +
post._count.comments * 5 +
post._count.originalReposts * 4 +
post.reactionCount * 3 +
post.commentCount * 5 +
post.repostCount * 4 +
recency
);
}
@@ -57,7 +41,6 @@ export const feedRouter = router({
pet: { select: { id: true, name: true, avatarKey: true } },
images: { orderBy: { position: "asc" } as const },
milestone: true,
_count: { select: { reactions: true, comments: true, originalReposts: true } },
videoPost: { select: { status: true, muxPlaybackId: true } },
repost: {
include: {
+31 -43
View File
@@ -1,46 +1,11 @@
import "server-only";
import { z } from "zod";
import { TRPCError } from "@trpc/server";
import { MilestoneType } from "@prisma/client";
import { router, protectedProcedure } from "@/trpc/init";
import type { PrismaClient } from "@prisma/client";
import { redis } from "@/lib/redis";
import { backfillOnFollow, fanOutPost } from "@/lib/feed-helpers";
const FOLLOWER_MILESTONES: Partial<Record<number, MilestoneType>> = {
500: MilestoneType.FOLLOWERS_500,
1000: MilestoneType.FOLLOWERS_1K,
2500: MilestoneType.FOLLOWERS_2_5K,
5000: MilestoneType.FOLLOWERS_5K,
10000: MilestoneType.FOLLOWERS_10K,
25000: MilestoneType.FOLLOWERS_25K,
50000: MilestoneType.FOLLOWERS_50K,
100000: MilestoneType.FOLLOWERS_100K,
250000: MilestoneType.FOLLOWERS_250K,
500000: MilestoneType.FOLLOWERS_500K,
1000000: MilestoneType.FOLLOWERS_1M,
};
/**
* Ownership assertion helper — verifies that a pet belongs to the requesting
* owner before any mutation or scoped query proceeds.
*
* Security (T-02-10): never trust client-supplied petId — acting pet must belong to ctx.userId.
*/
async function assertPetOwnership(
prisma: PrismaClient,
petId: string,
userId: string
) {
const pet = await prisma.pet.findUnique({ where: { id: petId } });
if (!pet || pet.ownerId !== userId) {
throw new TRPCError({
code: "FORBIDDEN",
message: "You do not have permission to access this pet.",
});
}
return pet;
}
import { assertPetOwnership } from "@/lib/assert-pet-ownership";
import { FOLLOWER_MILESTONE_THRESHOLDS as FOLLOWER_MILESTONES } from "@/lib/milestone-thresholds";
/**
* Follows tRPC router — pet-to-pet social graph (SOCL-01, SOCL-02, SOCL-03).
@@ -200,8 +165,11 @@ export const followsRouter = router({
})
)
.query(async ({ ctx, input }) => {
return ctx.prisma.follow.findMany({
where: { followeePetId: input.petId },
const rows = await ctx.prisma.follow.findMany({
where: {
followeePetId: input.petId,
...(input.cursor ? { createdAt: { lt: new Date(input.cursor) } } : {}),
},
include: {
follower: {
select: {
@@ -213,8 +181,16 @@ export const followsRouter = router({
},
},
orderBy: { createdAt: "desc" },
take: input.limit,
take: input.limit + 1,
});
const hasNextPage = rows.length > input.limit;
const items = hasNextPage ? rows.slice(0, input.limit) : rows;
const nextCursor = hasNextPage
? items[items.length - 1]!.createdAt.toISOString()
: null;
return { items, nextCursor };
}),
/**
@@ -237,6 +213,7 @@ export const followsRouter = router({
followee: { select: { id: true, name: true, avatarKey: true } },
},
orderBy: { createdAt: "desc" },
take: 100,
});
return rows.map((r) => r.followee);
@@ -256,8 +233,11 @@ export const followsRouter = router({
})
)
.query(async ({ ctx, input }) => {
return ctx.prisma.follow.findMany({
where: { followerPetId: input.petId },
const rows = await ctx.prisma.follow.findMany({
where: {
followerPetId: input.petId,
...(input.cursor ? { createdAt: { lt: new Date(input.cursor) } } : {}),
},
include: {
followee: {
select: {
@@ -269,7 +249,15 @@ export const followsRouter = router({
},
},
orderBy: { createdAt: "desc" },
take: input.limit,
take: input.limit + 1,
});
const hasNextPage = rows.length > input.limit;
const items = hasNextPage ? rows.slice(0, input.limit) : rows;
const nextCursor = hasNextPage
? items[items.length - 1]!.createdAt.toISOString()
: null;
return { items, nextCursor };
}),
});
+4 -9
View File
@@ -1,14 +1,6 @@
import { z } from "zod";
import { TRPCError } from "@trpc/server";
import { router, protectedProcedure } from "@/trpc/init";
import type { PrismaClient } from "@prisma/client";
async function assertOwner(prisma: PrismaClient, petId: string, userId: string) {
const pet = await prisma.pet.findUnique({ where: { id: petId }, select: { ownerId: true } });
if (!pet || pet.ownerId !== userId) {
throw new TRPCError({ code: "FORBIDDEN" });
}
}
import { assertPetOwnership as assertOwner } from "@/lib/assert-pet-ownership";
export const healthRouter = router({
// ── Weight Logs ─────────────────────────────────────────────────────────────
@@ -20,6 +12,7 @@ export const healthRouter = router({
return ctx.prisma.weightLog.findMany({
where: { petId: input.petId },
orderBy: { date: "desc" },
take: 500,
});
}),
@@ -59,6 +52,7 @@ export const healthRouter = router({
return ctx.prisma.vetVisit.findMany({
where: { petId: input.petId },
orderBy: { date: "desc" },
take: 500,
});
}),
@@ -100,6 +94,7 @@ export const healthRouter = router({
return ctx.prisma.vaccine.findMany({
where: { petId: input.petId },
orderBy: { dateGiven: "desc" },
take: 500,
});
}),
+7 -15
View File
@@ -1,27 +1,27 @@
import "server-only";
import { z } from "zod";
import { TRPCError } from "@trpc/server";
import { protectedProcedure, router } from "@/trpc/init";
import { createSignedUploadUrl, getPublicUrl, ALLOWED_CONTENT_TYPES, MAX_FILE_SIZE } from "@/lib/supabase-storage";
import { randomUUID } from "crypto";
import { assertPetOwnership } from "@/lib/assert-pet-ownership";
/**
* Media tRPC router — presigned R2 upload pipeline.
* Media tRPC router — presigned Supabase Storage upload pipeline.
*
* Security (T-4-01, T-4-02, T-4-03, T-4-05, T-4-06):
* - `server-only` import prevents any client-side bundling of this module
* - R2 credentials live only in src/lib/r2.ts (also server-only)
* - Storage credentials live only in src/lib/supabase-storage.ts (also server-only)
* - Ownership assertion before any presigned URL is issued (T-4-01)
* - contentType restricted to jpeg/png/webp via Zod enum (T-4-02)
* - fileSize validated server-side at 10 MB max (T-4-06)
* - confirmUpload key must start with 'avatars/' (T-4-05)
*
* Architecture: Media bytes NEVER pass through the Next.js API server.
* Flow: getPresignedUrl → client PUTs directly to R2 → confirmUpload writes avatarKey to DB
* Flow: getPresignedUrl → client PUTs directly to Supabase Storage → confirmUpload writes avatarKey to DB
*/
export const mediaRouter = router({
/**
* Generate a presigned PUT URL for direct upload to Cloudflare R2.
* Generate a presigned PUT URL for direct upload to Supabase Storage.
*
* Ownership check prevents non-owners from getting a presigned URL for another owner's pet.
* ContentType is constrained to image/jpeg | image/png | image/webp — the same value is
@@ -38,10 +38,7 @@ export const mediaRouter = router({
)
.mutation(async ({ ctx, input }) => {
// Ownership assertion (T-4-01)
const pet = await ctx.prisma.pet.findUnique({ where: { id: input.petId } });
if (!pet || pet.ownerId !== ctx.userId) {
throw new TRPCError({ code: "FORBIDDEN" });
}
await assertPetOwnership(ctx.prisma, input.petId, ctx.userId);
const ext = input.contentType.split("/")[1].replace("jpeg", "jpg");
const key = `avatars/${ctx.userId}/${input.petId}/${randomUUID()}.${ext}`;
@@ -66,12 +63,7 @@ export const mediaRouter = router({
)
.mutation(async ({ ctx, input }) => {
// Ownership assertion (T-4-01): must own pet before writing avatarKey to DB
const pet = await ctx.prisma.pet.findUnique({
where: { id: input.petId },
});
if (!pet || pet.ownerId !== ctx.userId) {
throw new TRPCError({ code: "FORBIDDEN" });
}
await assertPetOwnership(ctx.prisma, input.petId, ctx.userId);
const updated = await ctx.prisma.pet.update({
where: { id: input.petId },
+1 -6
View File
@@ -3,6 +3,7 @@ import { z } from "zod";
import { TRPCError } from "@trpc/server";
import { router, protectedProcedure } from "@/trpc/init";
import type { PrismaClient } from "@prisma/client";
import { assertPetOwnership } from "@/lib/assert-pet-ownership";
/**
* Messages tRPC router — Phase 6 Direct Messages.
@@ -18,12 +19,6 @@ import type { PrismaClient } from "@prisma/client";
* - Conversation IDs are sorted (petAId < petBId) to prevent duplicates
*/
async function assertPetOwnership(prisma: PrismaClient, petId: string, userId: string) {
const pet = await prisma.pet.findUnique({ where: { id: petId } });
if (!pet || pet.ownerId !== userId) throw new TRPCError({ code: "FORBIDDEN" });
return pet;
}
/** Verify that petId is a participant of the conversation and belongs to ctx.userId */
async function assertParticipant(
prisma: PrismaClient,
+1 -14
View File
@@ -1,11 +1,10 @@
import "server-only";
import { z } from "zod";
import { TRPCError } from "@trpc/server";
import { MilestoneType } from "@prisma/client";
import { router, protectedProcedure } from "@/trpc/init";
import { redis } from "@/lib/redis";
import { fanOutPost } from "@/lib/feed-helpers";
import type { PrismaClient } from "@prisma/client";
import { assertPetOwnership } from "@/lib/assert-pet-ownership";
/**
* Milestones tRPC router — structured milestone posts (MILE-01, MILE-02).
@@ -17,18 +16,6 @@ import type { PrismaClient } from "@prisma/client";
* - follower-threshold types excluded from MilestoneForm picker (T-02-53, D-10)
*/
async function assertPetOwnership(
prisma: PrismaClient,
petId: string,
userId: string
) {
const pet = await prisma.pet.findUnique({ where: { id: petId } });
if (!pet || pet.ownerId !== userId) {
throw new TRPCError({ code: "FORBIDDEN" });
}
return pet;
}
export const milestonesRouter = router({
/**
* Create a milestone post: Post(type=MILESTONE) + nested Milestone + optional PostImage.
+1 -23
View File
@@ -1,30 +1,8 @@
import { z } from "zod";
import { TRPCError } from "@trpc/server";
import { router, protectedProcedure } from "@/trpc/init";
import type { PrismaClient } from "@prisma/client";
import { generateInviteCode, INVITE_CODES_PER_USER } from "@/lib/invite-codes";
/**
* Ownership assertion helper — verifies that a pet belongs to the requesting
* owner before any mutation or scoped query proceeds.
*
* Security (T-3-01, T-1-02): never trust client-supplied pet ids without DB verification.
* Every pet mutation asserts pet.ownerId === ctx.userId (ASVS V4).
*/
async function assertPetOwnership(
prisma: PrismaClient,
petId: string,
userId: string
) {
const pet = await prisma.pet.findUnique({ where: { id: petId } });
if (!pet || pet.ownerId !== userId) {
throw new TRPCError({
code: "FORBIDDEN",
message: "You do not have permission to access this pet.",
});
}
return pet;
}
import { assertPetOwnership } from "@/lib/assert-pet-ownership";
export const petsRouter = router({
/**
+7 -13
View File
@@ -12,6 +12,8 @@ import { fanOutPost } from "@/lib/feed-helpers";
import { randomUUID } from "crypto";
import type { PrismaClient } from "@prisma/client";
import { extractHashtags, saveHashtags } from "@/lib/hashtag-helpers";
import { createMentionNotifications } from "@/lib/mention-helpers";
import { assertPetOwnership } from "@/lib/assert-pet-ownership";
/**
* Posts tRPC router — photo post creation, caption edit, deletion, feed hydration.
@@ -68,12 +70,7 @@ export const postsRouter = router({
)
.mutation(async ({ ctx, input }) => {
// Ownership assertion (T-02-30)
const pet = await ctx.prisma.pet.findUnique({
where: { id: input.petId },
});
if (!pet || pet.ownerId !== ctx.userId) {
throw new TRPCError({ code: "FORBIDDEN" });
}
await assertPetOwnership(ctx.prisma, input.petId, ctx.userId);
const ext = input.contentType.split("/")[1].replace("jpeg", "jpg");
// Key scoped to posts/{ownerId}/{petId}/ (T-02-31 path-traversal prevention)
@@ -105,12 +102,7 @@ export const postsRouter = router({
)
.mutation(async ({ ctx, input }) => {
// Ownership assertion (T-02-30): posting as another pet blocked
const pet = await ctx.prisma.pet.findUnique({
where: { id: input.petId },
});
if (!pet || pet.ownerId !== ctx.userId) {
throw new TRPCError({ code: "FORBIDDEN" });
}
await assertPetOwnership(ctx.prisma, input.petId, ctx.userId);
// Create Post + PostImage[] in one nested write
const post = await ctx.prisma.post.create({
@@ -140,6 +132,9 @@ export const postsRouter = router({
const tags = extractHashtags(input.caption ?? null);
await saveHashtags(ctx.prisma, post.id, tags).catch(() => {});
// Notify @mentioned pets in caption
createMentionNotifications(ctx.prisma, input.caption ?? null, input.petId, post.id).catch(() => {});
return post;
}),
@@ -215,7 +210,6 @@ export const postsRouter = router({
images: { orderBy: { position: "asc" } },
pet: { select: { id: true, name: true, avatarKey: true } },
milestone: true,
_count: { select: { reactions: true, comments: true } },
videoPost: { select: { status: true, muxPlaybackId: true } },
repost: {
include: {
+14 -24
View File
@@ -1,23 +1,7 @@
import "server-only";
import { z } from "zod";
import { TRPCError } from "@trpc/server";
import { router, protectedProcedure } from "@/trpc/init";
import type { PrismaClient } from "@prisma/client";
async function assertPetOwnership(
prisma: PrismaClient,
petId: string,
userId: string
) {
const pet = await prisma.pet.findUnique({ where: { id: petId } });
if (!pet || pet.ownerId !== userId) {
throw new TRPCError({
code: "FORBIDDEN",
message: "You do not have permission to access this pet.",
});
}
return pet;
}
import { assertPetOwnership } from "@/lib/assert-pet-ownership";
export const reactionsRouter = router({
toggle: protectedProcedure
@@ -30,24 +14,31 @@ export const reactionsRouter = router({
});
if (existing) {
await ctx.prisma.reaction.delete({
where: { postId_petId: { postId: input.postId, petId: input.petId } },
});
await ctx.prisma.$transaction([
ctx.prisma.reaction.delete({
where: { postId_petId: { postId: input.postId, petId: input.petId } },
}),
ctx.prisma.post.update({
where: { id: input.postId },
data: { reactionCount: { decrement: 1 } },
}),
]);
return { reacted: false };
}
const [reaction, post] = await Promise.all([
const [, post] = await ctx.prisma.$transaction([
ctx.prisma.reaction.create({
data: { postId: input.postId, petId: input.petId },
}),
ctx.prisma.post.findUnique({
ctx.prisma.post.update({
where: { id: input.postId },
data: { reactionCount: { increment: 1 } },
select: { petId: true },
}),
]);
// NOTF-02: notify post owner (skip self-reactions)
if (post && post.petId !== input.petId) {
if (post.petId !== input.petId) {
ctx.prisma.notification
.create({
data: {
@@ -60,7 +51,6 @@ export const reactionsRouter = router({
.catch(() => {});
}
void reaction;
return { reacted: true };
}),
+1 -22
View File
@@ -3,28 +3,7 @@ import { z } from "zod";
import { TRPCError } from "@trpc/server";
import { ReportReason } from "@prisma/client";
import { router, protectedProcedure } from "@/trpc/init";
import type { PrismaClient } from "@prisma/client";
/**
* Ownership assertion helper — verifies that a pet belongs to the requesting
* owner before any mutation or scoped query proceeds.
*
* Security (T-02-10): never trust client-supplied petId — acting pet must belong to ctx.userId.
*/
async function assertPetOwnership(
prisma: PrismaClient,
petId: string,
userId: string
) {
const pet = await prisma.pet.findUnique({ where: { id: petId } });
if (!pet || pet.ownerId !== userId) {
throw new TRPCError({
code: "FORBIDDEN",
message: "You do not have permission to access this pet.",
});
}
return pet;
}
import { assertPetOwnership } from "@/lib/assert-pet-ownership";
/**
* Reports tRPC router — content reporting for review (SAFE-02).
+38 -27
View File
@@ -5,22 +5,7 @@ import { router, protectedProcedure } from "@/trpc/init";
import { redis } from "@/lib/redis";
import { fanOutPost } from "@/lib/feed-helpers";
import { extractHashtags, saveHashtags } from "@/lib/hashtag-helpers";
import type { PrismaClient } from "@prisma/client";
async function assertPetOwnership(
prisma: PrismaClient,
petId: string,
userId: string
) {
const pet = await prisma.pet.findUnique({ where: { id: petId } });
if (!pet || pet.ownerId !== userId) {
throw new TRPCError({
code: "FORBIDDEN",
message: "You do not have permission to access this pet.",
});
}
return pet;
}
import { assertPetOwnership } from "@/lib/assert-pet-ownership";
export const repostsRouter = router({
create: protectedProcedure
@@ -59,18 +44,24 @@ export const repostsRouter = router({
return { postId: existing.postId };
}
const post = await ctx.prisma.post.create({
data: {
petId: input.reposterPetId,
type: "REPOST",
repost: {
create: {
originalPostId: input.originalPostId,
reposterPetId: input.reposterPetId,
const [post] = await ctx.prisma.$transaction([
ctx.prisma.post.create({
data: {
petId: input.reposterPetId,
type: "REPOST",
repost: {
create: {
originalPostId: input.originalPostId,
reposterPetId: input.reposterPetId,
},
},
},
},
});
}),
ctx.prisma.post.update({
where: { id: input.originalPostId },
data: { repostCount: { increment: 1 } },
}),
]);
await fanOutPost(redis, post.id, input.reposterPetId, post.createdAt, ctx.prisma).catch(() => {});
@@ -78,6 +69,20 @@ export const repostsRouter = router({
const tags = extractHashtags(originalPost.caption);
await saveHashtags(ctx.prisma, post.id, tags).catch(() => {});
// Notify original post author (skip self-repost)
if (originalPost.petId !== input.reposterPetId) {
ctx.prisma.notification
.create({
data: {
recipientPetId: originalPost.petId,
type: "PAW_BACK",
actorPetId: input.reposterPetId,
postId: input.originalPostId,
},
})
.catch(() => {});
}
return { postId: post.id };
}),
@@ -104,7 +109,13 @@ export const repostsRouter = router({
}
// Deleting the Post cascades to the Repost record via onDelete: Cascade
await ctx.prisma.post.delete({ where: { id: repost.postId } });
await ctx.prisma.$transaction([
ctx.prisma.post.delete({ where: { id: repost.postId } }),
ctx.prisma.post.update({
where: { id: repost.originalPostId },
data: { repostCount: { decrement: 1 } },
}),
]);
}),
isReposted: protectedProcedure
+3 -13
View File
@@ -8,7 +8,7 @@ import {
MAX_FILE_SIZE,
} from "@/lib/supabase-storage";
import { randomUUID } from "crypto";
import type { PrismaClient } from "@prisma/client";
import { assertPetOwnership } from "@/lib/assert-pet-ownership";
/**
* Stories tRPC router — 24-hour photo stories with lazy-delete expiry (D-07).
@@ -21,18 +21,6 @@ import type { PrismaClient } from "@prisma/client";
* - All queries filter expiresAt > now — expired stories never returned (T-02-44)
*/
async function assertPetOwnership(
prisma: PrismaClient,
petId: string,
userId: string
) {
const pet = await prisma.pet.findUnique({ where: { id: petId } });
if (!pet || pet.ownerId !== userId) {
throw new TRPCError({ code: "FORBIDDEN" });
}
return pet;
}
export const storiesRouter = router({
/**
* Generate a presigned PUT URL for direct upload to Supabase Storage.
@@ -90,6 +78,7 @@ export const storiesRouter = router({
return ctx.prisma.story.findMany({
where: { petId: input.petId, expiresAt: { gt: new Date() } },
orderBy: { createdAt: "asc" },
take: 50,
});
}),
@@ -182,6 +171,7 @@ export const storiesRouter = router({
viewerPet: { select: { id: true, name: true, avatarKey: true } },
},
orderBy: { viewedAt: "desc" },
take: 200,
});
}),
});
+1 -9
View File
@@ -3,18 +3,10 @@ import { z } from "zod";
import { TRPCError } from "@trpc/server";
import { router, protectedProcedure } from "@/trpc/init";
import { mux } from "@/lib/mux";
import type { PrismaClient } from "@prisma/client";
import { assertPetOwnership } from "@/lib/assert-pet-ownership";
const MAX_VIDEO_DURATION_SECS = 180; // 3 min hard cap — Mux rejects longer via passthrough check
async function assertPetOwnership(prisma: PrismaClient, petId: string, userId: string) {
const pet = await prisma.pet.findUnique({ where: { id: petId } });
if (!pet || pet.ownerId !== userId) {
throw new TRPCError({ code: "FORBIDDEN" });
}
return pet;
}
export const videosRouter = router({
/**
* Create a Mux direct upload URL + a PROCESSING Post/VideoPost row.