refactor(admin): admin.ts nach Bereichen aufteilen, getActiveAds in den ads-Router
- Die 63 Admin-Prozeduren liegen jetzt nach Bereich in src/trpc/routers/admin-procedures/ (system, dashboard, posts, blacklist, users, verification, team, reports, ads, music) plus guards.ts und post-actions.ts. admin.ts setzt trpc.admin.* daraus zusammen (34 statt ~1800 Zeilen); API, Importe und Test-Mocks von assertAdmin bleiben gleich. - getActiveAds war eine Nutzer-Prozedur für den Feed: jetzt trpc.ads.getActiveAds (FeedList, Tests nach ads.test.ts). Inhalt der Prozeduren unverändert. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
fc740987cd
commit
de6b36e3d3
19 files changed
+2002
-1863
No files matched your search
@@ -50,7 +50,7 @@ The client-side "which pet is currently active" state lives in `src/context/Acti
|
||||
|
||||
### Denormalized engagement counters
|
||||
|
||||
`Post.reactionCount/commentCount/repostCount` and `Advertisement.adReactionCount/adCommentCount/adRepostCount` are maintained transactionally at every create/delete site (reactions, comments, reposts, ads routers, and `admin.ts` moderation deletes) instead of computed via live `_count`/`count()` on read. Feed/explore/posts/admin reads use these columns directly. If you add a new mutation that creates or deletes a reaction/comment/repost, you must increment/decrement the matching counter in the same transaction — there is no background reconciliation job.
|
||||
`Post.reactionCount/commentCount/repostCount` and `Advertisement.adReactionCount/adCommentCount/adRepostCount` are maintained transactionally at every create/delete site (reactions, comments, reposts, ads routers, and the admin moderation deletes in `admin-procedures/`) instead of computed via live `_count`/`count()` on read. Feed/explore/posts/admin reads use these columns directly. If you add a new mutation that creates or deletes a reaction/comment/repost, you must increment/decrement the matching counter in the same transaction — there is no background reconciliation job.
|
||||
|
||||
### Routing structure
|
||||
|
||||
@@ -84,9 +84,9 @@ All uploads are presigned/direct-to-storage — media bytes never pass through t
|
||||
|
||||
### Admin / moderation panel
|
||||
|
||||
Gated by path secret (see `proxy.ts` above) *and* by role at the tRPC layer: `src/trpc/routers/admin.ts`'s `assertAdmin()` allows either `ADMIN_OWNER_ID` (env-configured super-admin bootstrap) or an `AdminRole` row (`SUPER_ADMIN` / `MODERATOR`). Actions are written to `ModerationLog`. Pages live under `src/app/p/[secret]/{users,pets,moderators,posts,reports,ads,referrals,curator,…}`. The dashboard has a collapsible "Tierarten" card (`SpeciesDistributionCard`, `petAdmin.speciesDistribution`: pets per species incl. empty species and per breed, curator pet excluded). The "Tiere" page (`pets`, router `pet-admin.ts`) manages single pets: verified/founding toggles, clearing profile content, deleting a pet (reason is sent to the owner as a team DM on another of their pets, or by e-mail if it was their only pet) and the owner's referral ranks.
|
||||
Gated by path secret (see `proxy.ts` above) *and* by role at the tRPC layer: `assertAdmin()` (`src/trpc/routers/admin-procedures/guards.ts`, re-exported from `admin.ts`) allows either `ADMIN_OWNER_ID` (env-configured super-admin bootstrap) or an `AdminRole` row (`SUPER_ADMIN` / `MODERATOR`). Actions are written to `ModerationLog` via `modLog()` (`src/lib/admin/mod-log.ts`). `trpc.admin.*` is assembled in `src/trpc/routers/admin.ts` from per-area procedure objects in `src/trpc/routers/admin-procedures/` (posts, users, reports, ads, …) — add new admin procedures there, not in `admin.ts`. Every admin page reloads its visible data after any successful mutation (`AdminAutoRefresh` in the admin layout), so admin pages need no manual `invalidateQueries`. Pages live under `src/app/p/[secret]/{users,pets,moderators,posts,reports,ads,referrals,curator,…}`. The dashboard has a collapsible "Tierarten" card (`SpeciesDistributionCard`, `petAdmin.speciesDistribution`: pets per species incl. empty species and per breed, curator pet excluded). The "Tiere" page (`pets`, router `pet-admin.ts`) manages single pets: verified/founding toggles, clearing profile content, deleting a pet (reason is sent to the owner as a team DM on another of their pets, or by e-mail if it was their only pet) and the owner's referral ranks.
|
||||
|
||||
**Report statistics (`ReportDecision`, `src/lib/report-decisions.ts`):** every moderator decision on a report is stored as an append-only row (UPHELD/DISMISSED) before the `Report` itself is deleted — shown on the users page, the pet detail sheet and the "Auswertung" tab of `/p/[secret]/reports`. A new path that resolves reports by moderator decision must run `reportDecisionOps()` in the same transaction (current: `dismissReport`, `upholdReport`, `deletePostAsModerator` in `admin.ts`, `petAdmin.delete`). Rows have no FKs: `deletePetCompletely` nulls the pet's ids, `deleteOwnerAccount` anonymizes the owner's ids — never delete the rows, other owners' counts depend on them.
|
||||
**Report statistics (`ReportDecision`, `src/lib/report-decisions.ts`):** every moderator decision on a report is stored as an append-only row (UPHELD/DISMISSED) before the `Report` itself is deleted — shown on the users page, the pet detail sheet and the "Auswertung" tab of `/p/[secret]/reports`. A new path that resolves reports by moderator decision must run `reportDecisionOps()` in the same transaction (current: `dismissReport`, `upholdReport`, `deletePostAsModerator` in `admin-procedures/`, `petAdmin.delete`). Rows have no FKs: `deletePetCompletely` nulls the pet's ids, `deleteOwnerAccount` anonymizes the owner's ids — never delete the rows, other owners' counts depend on them.
|
||||
|
||||
**Never delete a pet with a bare `prisma.pet.delete`** — use `deletePetCompletely()` (`src/lib/delete-pet.ts`). `StoryView` (D-08), `Report.reporter` and `Repost.originalPost` have no cascade and would block the delete, and the denormalized counters on *other* pets' posts/stories must drop by this pet's paws/comments/paw-backs. `pets.delete`, `deleteOwnerAccount` and the admin delete all go through it.
|
||||
|
||||
|
||||
@@ -598,57 +598,6 @@ describe("admin.exportUserData", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("admin.getActiveAds", () => {
|
||||
const adUnfiltered = { id: "ad-all", species: [], breeds: [] };
|
||||
const adDogsOnly = { id: "ad-dogs", species: ["species-dog"], breeds: [] };
|
||||
const adSiameseCatsOnly = { id: "ad-siamese", species: ["species-cat"], breeds: ["breed-siamese"] };
|
||||
|
||||
it("returns [] when the pet does not exist", async () => {
|
||||
const { caller, mockPrisma } = await createAdminCaller();
|
||||
mockPrisma.pet.findUnique.mockResolvedValue(null);
|
||||
|
||||
const result = await caller.admin.getActiveAds({ petId: "missing-pet" });
|
||||
|
||||
expect(result).toEqual([]);
|
||||
});
|
||||
|
||||
it("returns untargeted ads and matching-species ads, excludes non-matching species", async () => {
|
||||
const { caller, mockPrisma } = await createAdminCaller();
|
||||
mockPrisma.pet.findUnique.mockResolvedValue({ speciesId: "species-dog", breedId: null });
|
||||
mockPrisma.advertisement.findMany.mockResolvedValue([adUnfiltered, adDogsOnly, adSiameseCatsOnly]);
|
||||
|
||||
const result = await caller.admin.getActiveAds({ petId: "pet-dog-1" });
|
||||
|
||||
expect(result.map((a) => a.id)).toEqual(["ad-all", "ad-dogs"]);
|
||||
});
|
||||
|
||||
it("only shows a breed-narrowed ad to a pet with the matching breed", async () => {
|
||||
const { caller, mockPrisma } = await createAdminCaller();
|
||||
mockPrisma.advertisement.findMany.mockResolvedValue([adUnfiltered, adSiameseCatsOnly]);
|
||||
|
||||
mockPrisma.pet.findUnique.mockResolvedValue({ speciesId: "species-cat", breedId: "breed-siamese" });
|
||||
const matching = await caller.admin.getActiveAds({ petId: "pet-siamese" });
|
||||
expect(matching.map((a) => a.id)).toEqual(["ad-all", "ad-siamese"]);
|
||||
|
||||
mockPrisma.pet.findUnique.mockResolvedValue({ speciesId: "species-cat", breedId: "breed-persian" });
|
||||
const nonMatching = await caller.admin.getActiveAds({ petId: "pet-persian" });
|
||||
expect(nonMatching.map((a) => a.id)).toEqual(["ad-all"]);
|
||||
|
||||
mockPrisma.pet.findUnique.mockResolvedValue({ speciesId: "species-cat", breedId: null });
|
||||
const noBreedSet = await caller.admin.getActiveAds({ petId: "pet-mixed-cat" });
|
||||
expect(noBreedSet.map((a) => a.id)).toEqual(["ad-all"]);
|
||||
});
|
||||
|
||||
it("does not require admin role — any authenticated owner can fetch ads for their pet", async () => {
|
||||
const { caller, mockPrisma } = await createAdminCaller({ userId: "regular-owner" });
|
||||
mockPrisma.pet.findUnique.mockResolvedValue({ speciesId: "species-dog", breedId: null });
|
||||
mockPrisma.advertisement.findMany.mockResolvedValue([adUnfiltered]);
|
||||
|
||||
await expect(caller.admin.getActiveAds({ petId: "pet-dog-1" })).resolves.toEqual([adUnfiltered]);
|
||||
});
|
||||
});
|
||||
|
||||
// Gitea #18 — legal AI-content disclosure moderator correction.
|
||||
describe("admin.setAiDisclosure", () => {
|
||||
it("wraps the post update + moderation log write in a transaction, requiring a reason", async () => {
|
||||
vi.stubEnv("ADMIN_OWNER_ID", "admin-1");
|
||||
|
||||
@@ -211,3 +211,55 @@ describe("ads.toggleRepost", () => {
|
||||
expect(result).toEqual({ reposted: false, count: 1 });
|
||||
});
|
||||
});
|
||||
|
||||
describe("ads.getActiveAds", () => {
|
||||
const adUnfiltered = { id: "ad-all", species: [], breeds: [] };
|
||||
const adDogsOnly = { id: "ad-dogs", species: ["species-dog"], breeds: [] };
|
||||
const adSiameseCatsOnly = { id: "ad-siamese", species: ["species-cat"], breeds: ["breed-siamese"] };
|
||||
|
||||
it("returns [] when the pet does not exist", async () => {
|
||||
const { caller, mockPrisma } = await createAdsCaller();
|
||||
mockPrisma.pet.findUnique.mockResolvedValue(null);
|
||||
|
||||
const result = await caller.ads.getActiveAds({ petId: "missing-pet" });
|
||||
|
||||
expect(result).toEqual([]);
|
||||
});
|
||||
|
||||
it("returns untargeted ads and matching-species ads, excludes non-matching species", async () => {
|
||||
const { caller, mockPrisma } = await createAdsCaller();
|
||||
mockPrisma.pet.findUnique.mockResolvedValue({ speciesId: "species-dog", breedId: null });
|
||||
mockPrisma.advertisement.findMany.mockResolvedValue([adUnfiltered, adDogsOnly, adSiameseCatsOnly]);
|
||||
|
||||
const result = await caller.ads.getActiveAds({ petId: "pet-dog-1" });
|
||||
|
||||
expect(result.map((a) => a.id)).toEqual(["ad-all", "ad-dogs"]);
|
||||
});
|
||||
|
||||
it("only shows a breed-narrowed ad to a pet with the matching breed", async () => {
|
||||
const { caller, mockPrisma } = await createAdsCaller();
|
||||
mockPrisma.advertisement.findMany.mockResolvedValue([adUnfiltered, adSiameseCatsOnly]);
|
||||
|
||||
mockPrisma.pet.findUnique.mockResolvedValue({ speciesId: "species-cat", breedId: "breed-siamese" });
|
||||
const matching = await caller.ads.getActiveAds({ petId: "pet-siamese" });
|
||||
expect(matching.map((a) => a.id)).toEqual(["ad-all", "ad-siamese"]);
|
||||
|
||||
mockPrisma.pet.findUnique.mockResolvedValue({ speciesId: "species-cat", breedId: "breed-persian" });
|
||||
const nonMatching = await caller.ads.getActiveAds({ petId: "pet-persian" });
|
||||
expect(nonMatching.map((a) => a.id)).toEqual(["ad-all"]);
|
||||
|
||||
mockPrisma.pet.findUnique.mockResolvedValue({ speciesId: "species-cat", breedId: null });
|
||||
const noBreedSet = await caller.ads.getActiveAds({ petId: "pet-mixed-cat" });
|
||||
expect(noBreedSet.map((a) => a.id)).toEqual(["ad-all"]);
|
||||
});
|
||||
|
||||
it("does not require admin role — any authenticated owner can fetch ads for their pet", async () => {
|
||||
const { caller, mockPrisma } = await createAdsCaller({ userId: "regular-owner" });
|
||||
mockPrisma.pet.findUnique.mockResolvedValue({ speciesId: "species-dog", breedId: null });
|
||||
mockPrisma.advertisement.findMany.mockResolvedValue([adUnfiltered]);
|
||||
|
||||
await expect(caller.ads.getActiveAds({ petId: "pet-dog-1" })).resolves.toEqual([adUnfiltered]);
|
||||
});
|
||||
});
|
||||
|
||||
// Gitea #18 — legal AI-content disclosure moderator correction.
|
||||
@@ -134,7 +134,7 @@ export default function AdminAdsPage() {
|
||||
...f,
|
||||
species: checked ? [...f.species, speciesId] : f.species.filter((id) => id !== speciesId),
|
||||
// Unchecking a species drops any breed selections that belonged to it —
|
||||
// breeds only narrow WITHIN a checked species (see admin.ts getActiveAds).
|
||||
// breeds only narrow WITHIN a checked species (see ads.ts getActiveAds).
|
||||
breeds: checked
|
||||
? f.breeds
|
||||
: f.breeds.filter((id) => !(breedsBySpecies[speciesId] ?? []).some((b) => b.id === id)),
|
||||
|
||||
@@ -71,7 +71,7 @@ export function FeedList() {
|
||||
}, [inView, hasNextPage, isFetchingNextPage, fetchNextPage]);
|
||||
|
||||
const { data: activeAds } = useQuery(
|
||||
trpc.admin.getActiveAds.queryOptions(
|
||||
trpc.ads.getActiveAds.queryOptions(
|
||||
{ petId: activePetId ?? "" },
|
||||
{ enabled: !!activePetId }
|
||||
)
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
import "server-only";
|
||||
import { z } from "zod";
|
||||
import { randomUUID } from "crypto";
|
||||
import { AdminRoleType } from "@prisma/client";
|
||||
import { protectedProcedure } from "@/trpc/init";
|
||||
import { modLog } from "@/lib/admin/mod-log";
|
||||
import { createSignedUploadUrl, ALLOWED_CONTENT_TYPES, MAX_FILE_SIZE } from "@/lib/supabase-storage";
|
||||
import { assertAdmin } from "@/trpc/routers/admin-procedures/guards";
|
||||
|
||||
/** Werbeanzeigen verwalten. Teil von `trpc.admin.*` (admin.ts). */
|
||||
|
||||
export const adminAdsProcedures = {
|
||||
// ─── Ad media upload ─────────────────────────────────────────────────────────
|
||||
getAdImagePresignedUrl: protectedProcedure
|
||||
.input(
|
||||
z.object({
|
||||
contentType: z.enum(ALLOWED_CONTENT_TYPES),
|
||||
fileSize: z.number().max(MAX_FILE_SIZE, "Image must be under 10 MB"),
|
||||
})
|
||||
)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
await assertAdmin(ctx.prisma, ctx.userId, AdminRoleType.SUPER_ADMIN);
|
||||
const ext = input.contentType.split("/")[1]!.replace("jpeg", "jpg");
|
||||
const key = `ads/${ctx.userId}/${randomUUID()}.${ext}`;
|
||||
const { signedUrl } = await createSignedUploadUrl(key);
|
||||
return { presignedUrl: signedUrl, key };
|
||||
}),
|
||||
|
||||
// ─── Advertisements ──────────────────────────────────────────────────────────
|
||||
listAds: protectedProcedure.query(async ({ ctx }) => {
|
||||
await assertAdmin(ctx.prisma, ctx.userId, AdminRoleType.MODERATOR);
|
||||
return ctx.prisma.advertisement.findMany({ orderBy: { createdAt: "desc" } });
|
||||
}),
|
||||
|
||||
createAd: protectedProcedure
|
||||
.input(
|
||||
z.object({
|
||||
title: z.string().min(1).max(100),
|
||||
caption: z.string().max(500).optional(),
|
||||
imageKey: z.string().optional(),
|
||||
targetUrl: z.string().url().or(z.literal("")).optional(),
|
||||
isActive: z.boolean().default(true),
|
||||
species: z.array(z.string()).default([]),
|
||||
breeds: z.array(z.string()).default([]),
|
||||
startDate: z.string().datetime().optional(),
|
||||
endDate: z.string().datetime().optional(),
|
||||
})
|
||||
)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const callerRole = await assertAdmin(ctx.prisma, ctx.userId, AdminRoleType.SUPER_ADMIN);
|
||||
// Interactive transaction (not the array form used elsewhere in this file)
|
||||
// because the log entry needs the DB-generated ad id, which only exists
|
||||
// after the create resolves.
|
||||
return ctx.prisma.$transaction(async (tx) => {
|
||||
const ad = await tx.advertisement.create({
|
||||
data: {
|
||||
title: input.title,
|
||||
caption: input.caption ?? null,
|
||||
imageKey: input.imageKey ?? null,
|
||||
targetUrl: input.targetUrl || null,
|
||||
isActive: input.isActive,
|
||||
species: input.species,
|
||||
breeds: input.breeds,
|
||||
startDate: input.startDate ? new Date(input.startDate) : null,
|
||||
endDate: input.endDate ? new Date(input.endDate) : null,
|
||||
createdBy: ctx.userId,
|
||||
},
|
||||
});
|
||||
await modLog(tx, ctx, callerRole, {
|
||||
action: "CREATE_AD",
|
||||
targetType: "AD",
|
||||
targetId: ad.id,
|
||||
reason: input.title,
|
||||
});
|
||||
return ad;
|
||||
});
|
||||
}),
|
||||
|
||||
updateAd: protectedProcedure
|
||||
.input(
|
||||
z.object({
|
||||
id: z.string().min(1),
|
||||
title: z.string().min(1).max(100).optional(),
|
||||
caption: z.string().max(500).nullable().optional(),
|
||||
imageKey: z.string().nullable().optional(),
|
||||
targetUrl: z.string().url().or(z.literal("")).nullable().optional(),
|
||||
isActive: z.boolean().optional(),
|
||||
species: z.array(z.string()).optional(),
|
||||
breeds: z.array(z.string()).optional(),
|
||||
startDate: z.string().datetime().nullable().optional(),
|
||||
endDate: z.string().datetime().nullable().optional(),
|
||||
})
|
||||
)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const callerRole = await assertAdmin(ctx.prisma, ctx.userId, AdminRoleType.SUPER_ADMIN);
|
||||
const { id, targetUrl, startDate, endDate, ...rest } = input;
|
||||
const [ad] = await ctx.prisma.$transaction([
|
||||
ctx.prisma.advertisement.update({
|
||||
where: { id },
|
||||
data: {
|
||||
...rest,
|
||||
targetUrl: targetUrl === "" ? null : targetUrl,
|
||||
startDate: startDate ? new Date(startDate) : startDate === null ? null : undefined,
|
||||
endDate: endDate ? new Date(endDate) : endDate === null ? null : undefined,
|
||||
},
|
||||
}),
|
||||
modLog(ctx.prisma, ctx, callerRole, { action: "UPDATE_AD", targetType: "AD", targetId: id }),
|
||||
]);
|
||||
return ad;
|
||||
}),
|
||||
|
||||
deleteAd: protectedProcedure
|
||||
.input(z.object({ id: z.string().min(1) }))
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const callerRole = await assertAdmin(ctx.prisma, ctx.userId, AdminRoleType.SUPER_ADMIN);
|
||||
await ctx.prisma.$transaction([
|
||||
ctx.prisma.advertisement.delete({ where: { id: input.id } }),
|
||||
modLog(ctx.prisma, ctx, callerRole, { action: "DELETE_AD", targetType: "AD", targetId: input.id }),
|
||||
]);
|
||||
return { success: true };
|
||||
}),
|
||||
};
|
||||
@@ -0,0 +1,106 @@
|
||||
import "server-only";
|
||||
import { z } from "zod";
|
||||
import { AdminRoleType, BlacklistEntryType } from "@prisma/client";
|
||||
import { protectedProcedure } from "@/trpc/init";
|
||||
import { modLog } from "@/lib/admin/mod-log";
|
||||
import { matchesWordBlacklist, matchesLinkBlacklist } from "@/lib/blacklist";
|
||||
import { assertAdmin, rethrowNotFound } from "@/trpc/routers/admin-procedures/guards";
|
||||
|
||||
/** Wort-/Link-/Hashtag-Blacklist (Gitea #10 Phase 3). Teil von `trpc.admin.*` (admin.ts). */
|
||||
|
||||
export const adminBlacklistProcedures = {
|
||||
// ─── Blacklist (Gitea #10 Phase 3) ────────────────────────────────────────────
|
||||
listBlacklist: protectedProcedure
|
||||
.input(z.object({ type: z.nativeEnum(BlacklistEntryType).optional() }))
|
||||
.query(async ({ ctx, input }) => {
|
||||
await assertAdmin(ctx.prisma, ctx.userId, AdminRoleType.MODERATOR);
|
||||
return ctx.prisma.blacklistEntry.findMany({
|
||||
where: input.type ? { type: input.type } : undefined,
|
||||
orderBy: { createdAt: "desc" },
|
||||
});
|
||||
}),
|
||||
|
||||
createBlacklistEntry: protectedProcedure
|
||||
.input(
|
||||
z.object({
|
||||
type: z.nativeEnum(BlacklistEntryType),
|
||||
value: z.string().min(1).max(200),
|
||||
})
|
||||
)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const callerRole = await assertAdmin(ctx.prisma, ctx.userId, AdminRoleType.MODERATOR);
|
||||
const value = input.value.trim().toLowerCase().replace(/^#/, "");
|
||||
|
||||
const entry = await ctx.prisma.blacklistEntry.upsert({
|
||||
where: { type_value: { type: input.type, value } },
|
||||
create: { type: input.type, value, createdBy: ctx.userId },
|
||||
update: {},
|
||||
});
|
||||
|
||||
// Retroactive scan — hide existing non-hidden posts matching this
|
||||
// single new entry. Capped so a runaway match set can't hang the
|
||||
// request; PawFeed's current scale makes a synchronous scan fine.
|
||||
const RETROACTIVE_SCAN_LIMIT = 5000;
|
||||
let matchingPostIds: string[] = [];
|
||||
|
||||
if (input.type === "HASHTAG") {
|
||||
const rows = await ctx.prisma.postHashtag.findMany({
|
||||
where: { hashtag: { tag: value }, post: { hiddenAt: null } },
|
||||
select: { postId: true },
|
||||
take: RETROACTIVE_SCAN_LIMIT,
|
||||
});
|
||||
matchingPostIds = rows.map((r) => r.postId);
|
||||
} else {
|
||||
const candidates = await ctx.prisma.post.findMany({
|
||||
where: { hiddenAt: null, caption: { not: null } },
|
||||
select: { id: true, caption: true },
|
||||
take: RETROACTIVE_SCAN_LIMIT,
|
||||
});
|
||||
const matchFn = input.type === "WORD" ? matchesWordBlacklist : matchesLinkBlacklist;
|
||||
matchingPostIds = candidates
|
||||
.filter((p) => matchFn(p.caption!, [value]) !== null)
|
||||
.map((p) => p.id);
|
||||
}
|
||||
|
||||
if (matchingPostIds.length > 0) {
|
||||
const reason = `Auto-hidden: retroactive blacklist scan (${input.type.toLowerCase()} "${value}")`;
|
||||
await ctx.prisma.$transaction([
|
||||
ctx.prisma.post.updateMany({
|
||||
where: { id: { in: matchingPostIds } },
|
||||
data: { hiddenAt: new Date() },
|
||||
}),
|
||||
ctx.prisma.moderationLog.createMany({
|
||||
data: matchingPostIds.map((postId) => ({
|
||||
action: "HIDE_POST",
|
||||
targetType: "POST",
|
||||
targetId: postId,
|
||||
reason,
|
||||
moderatorId: ctx.userId,
|
||||
moderatorRole: callerRole,
|
||||
ipAddress: ctx.ip,
|
||||
})),
|
||||
}),
|
||||
]);
|
||||
}
|
||||
|
||||
return { entry, hiddenCount: matchingPostIds.length };
|
||||
}),
|
||||
|
||||
deleteBlacklistEntry: protectedProcedure
|
||||
.input(z.object({ id: z.string().min(1) }))
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const callerRole = await assertAdmin(ctx.prisma, ctx.userId, AdminRoleType.MODERATOR);
|
||||
await ctx.prisma
|
||||
.$transaction(async (tx) => {
|
||||
const entry = await tx.blacklistEntry.delete({ where: { id: input.id } });
|
||||
await modLog(tx, ctx, callerRole, {
|
||||
action: "DELETE_BLACKLIST_ENTRY",
|
||||
targetType: "SYSTEM",
|
||||
targetId: input.id,
|
||||
reason: `${entry.type.toLowerCase()}: ${entry.value}`,
|
||||
});
|
||||
})
|
||||
.catch(rethrowNotFound);
|
||||
return { success: true };
|
||||
}),
|
||||
};
|
||||
@@ -0,0 +1,181 @@
|
||||
import "server-only";
|
||||
import { z } from "zod";
|
||||
import { protectedProcedure } from "@/trpc/init";
|
||||
import { getDailyVisitCount, getUniqueVisitorCount, lastNDays, daysInRange } from "@/lib/visit-tracking";
|
||||
import { assertAdmin } from "@/trpc/routers/admin-procedures/guards";
|
||||
|
||||
/** Dashboard-Zahlen und Zeitreihen. Teil von `trpc.admin.*` (admin.ts). */
|
||||
|
||||
type Granularity = "day" | "week" | "month";
|
||||
const BUCKET_COUNT: Record<Granularity, number> = { day: 30, week: 12, month: 12 };
|
||||
|
||||
/** Truncates a date down to the start of its bucket, in UTC (day/ISO-week-Monday/month-1st). */
|
||||
function truncateUTC(date: Date, granularity: Granularity): Date {
|
||||
const d = new Date(Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate()));
|
||||
if (granularity === "month") return new Date(Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), 1));
|
||||
if (granularity === "week") {
|
||||
const isoDow = d.getUTCDay() || 7; // Mon=1..Sun=7
|
||||
d.setUTCDate(d.getUTCDate() - isoDow + 1);
|
||||
}
|
||||
return d;
|
||||
}
|
||||
|
||||
function stepBackOneBucket(date: Date, granularity: Granularity): Date {
|
||||
const d = new Date(date);
|
||||
if (granularity === "month") d.setUTCMonth(d.getUTCMonth() - 1);
|
||||
else if (granularity === "week") d.setUTCDate(d.getUTCDate() - 7);
|
||||
else d.setUTCDate(d.getUTCDate() - 1);
|
||||
return d;
|
||||
}
|
||||
|
||||
/** Ordered bucket start-dates (oldest first) ending at the current bucket. */
|
||||
function buildBuckets(granularity: Granularity): Date[] {
|
||||
const buckets: Date[] = [];
|
||||
let cursor = truncateUTC(new Date(), granularity);
|
||||
for (let i = 0; i < BUCKET_COUNT[granularity]; i++) {
|
||||
buckets.unshift(cursor);
|
||||
cursor = stepBackOneBucket(cursor, granularity);
|
||||
}
|
||||
return buckets;
|
||||
}
|
||||
|
||||
/** Counts how many timestamps fall in each bucket (zero-filled — no gaps). */
|
||||
function countByBucket(timestamps: Date[], buckets: Date[], granularity: Granularity): number[] {
|
||||
const counts = new Map<number, number>();
|
||||
for (const ts of timestamps) {
|
||||
const key = truncateUTC(ts, granularity).getTime();
|
||||
counts.set(key, (counts.get(key) ?? 0) + 1);
|
||||
}
|
||||
return buckets.map((b) => counts.get(b.getTime()) ?? 0);
|
||||
}
|
||||
|
||||
export const adminDashboardProcedures = {
|
||||
// ─── Dashboard ───────────────────────────────────────────────────────────────
|
||||
getStats: protectedProcedure.query(async ({ ctx }) => {
|
||||
await assertAdmin(ctx.prisma, ctx.userId);
|
||||
const [
|
||||
owners,
|
||||
pets,
|
||||
posts,
|
||||
bans,
|
||||
ads,
|
||||
reports,
|
||||
shadowbans,
|
||||
blacklistEntries,
|
||||
verificationPending,
|
||||
verificationClosed,
|
||||
dau,
|
||||
mau,
|
||||
] = await Promise.all([
|
||||
ctx.prisma.owner.count(),
|
||||
ctx.prisma.pet.count(),
|
||||
ctx.prisma.post.count(),
|
||||
ctx.prisma.userBan.count(),
|
||||
ctx.prisma.advertisement.count({ where: { isActive: true } }),
|
||||
ctx.prisma.report.count(),
|
||||
ctx.prisma.shadowban.count(),
|
||||
ctx.prisma.blacklistEntry.count(),
|
||||
ctx.prisma.verificationRequest.count({ where: { status: "PENDING" } }),
|
||||
ctx.prisma.verificationRequest.count({ where: { status: { in: ["APPROVED", "REJECTED"] } } }),
|
||||
getDailyVisitCount(new Date()),
|
||||
getUniqueVisitorCount(lastNDays(30)),
|
||||
]);
|
||||
return {
|
||||
owners,
|
||||
pets,
|
||||
posts,
|
||||
bans,
|
||||
activeAds: ads,
|
||||
reports,
|
||||
shadowbans,
|
||||
blacklistEntries,
|
||||
verificationPending,
|
||||
verificationClosed,
|
||||
dau,
|
||||
mau,
|
||||
};
|
||||
}),
|
||||
|
||||
/** New posts per bucket over the trailing window (30 days / 12 weeks / 12 months). */
|
||||
getPostsOverTime: protectedProcedure
|
||||
.input(z.object({ granularity: z.enum(["day", "week", "month"]) }))
|
||||
.query(async ({ ctx, input }) => {
|
||||
await assertAdmin(ctx.prisma, ctx.userId);
|
||||
const buckets = buildBuckets(input.granularity);
|
||||
const posts = await ctx.prisma.post.findMany({
|
||||
where: { createdAt: { gte: buckets[0] } },
|
||||
select: { createdAt: true },
|
||||
});
|
||||
const counts = countByBucket(posts.map((p) => p.createdAt), buckets, input.granularity);
|
||||
return buckets.map((date, i) => ({ date: date.toISOString(), value: counts[i]! }));
|
||||
}),
|
||||
|
||||
/** Cumulative total owners per bucket — the growth curve, not just new signups. */
|
||||
getOwnerGrowth: protectedProcedure
|
||||
.input(z.object({ granularity: z.enum(["day", "week", "month"]) }))
|
||||
.query(async ({ ctx, input }) => {
|
||||
await assertAdmin(ctx.prisma, ctx.userId);
|
||||
const buckets = buildBuckets(input.granularity);
|
||||
const [baselineCount, owners] = await Promise.all([
|
||||
ctx.prisma.owner.count({ where: { createdAt: { lt: buckets[0] } } }),
|
||||
ctx.prisma.owner.findMany({
|
||||
where: { createdAt: { gte: buckets[0] } },
|
||||
select: { createdAt: true },
|
||||
}),
|
||||
]);
|
||||
const newPerBucket = countByBucket(owners.map((o) => o.createdAt), buckets, input.granularity);
|
||||
let running = baselineCount;
|
||||
const cumulative = newPerBucket.map((n) => (running += n));
|
||||
return buckets.map((date, i) => ({ date: date.toISOString(), value: cumulative[i]! }));
|
||||
}),
|
||||
|
||||
/** New comments per bucket over the trailing window. */
|
||||
getCommentsOverTime: protectedProcedure
|
||||
.input(z.object({ granularity: z.enum(["day", "week", "month"]) }))
|
||||
.query(async ({ ctx, input }) => {
|
||||
await assertAdmin(ctx.prisma, ctx.userId);
|
||||
const buckets = buildBuckets(input.granularity);
|
||||
const comments = await ctx.prisma.comment.findMany({
|
||||
where: { createdAt: { gte: buckets[0] } },
|
||||
select: { createdAt: true },
|
||||
});
|
||||
const counts = countByBucket(comments.map((c) => c.createdAt), buckets, input.granularity);
|
||||
return buckets.map((date, i) => ({ date: date.toISOString(), value: counts[i]! }));
|
||||
}),
|
||||
|
||||
/** New reactions ("likes") per bucket over the trailing window. */
|
||||
getReactionsOverTime: protectedProcedure
|
||||
.input(z.object({ granularity: z.enum(["day", "week", "month"]) }))
|
||||
.query(async ({ ctx, input }) => {
|
||||
await assertAdmin(ctx.prisma, ctx.userId);
|
||||
const buckets = buildBuckets(input.granularity);
|
||||
const reactions = await ctx.prisma.reaction.findMany({
|
||||
where: { createdAt: { gte: buckets[0] } },
|
||||
select: { createdAt: true },
|
||||
});
|
||||
const counts = countByBucket(reactions.map((r) => r.createdAt), buckets, input.granularity);
|
||||
return buckets.map((date, i) => ({ date: date.toISOString(), value: counts[i]! }));
|
||||
}),
|
||||
|
||||
/**
|
||||
* Unique daily visitors per bucket (Redis-backed, see visit-tracking.ts) —
|
||||
* the DAU trend line. Week/month buckets union each day's set in range
|
||||
* rather than summing daily counts, so a repeat visitor within the bucket
|
||||
* is still counted once.
|
||||
*/
|
||||
getVisitsOverTime: protectedProcedure
|
||||
.input(z.object({ granularity: z.enum(["day", "week", "month"]) }))
|
||||
.query(async ({ ctx, input }) => {
|
||||
await assertAdmin(ctx.prisma, ctx.userId);
|
||||
const buckets = buildBuckets(input.granularity);
|
||||
const tomorrow = truncateUTC(new Date(), "day");
|
||||
tomorrow.setUTCDate(tomorrow.getUTCDate() + 1);
|
||||
const values = await Promise.all(
|
||||
buckets.map((bucketStart, i) => {
|
||||
const bucketEnd = i + 1 < buckets.length ? buckets[i + 1]! : tomorrow;
|
||||
return getUniqueVisitorCount(daysInRange(bucketStart, bucketEnd));
|
||||
})
|
||||
);
|
||||
return buckets.map((date, i) => ({ date: date.toISOString(), value: values[i]! }));
|
||||
}),
|
||||
};
|
||||
@@ -0,0 +1,65 @@
|
||||
import "server-only";
|
||||
import { TRPCError } from "@trpc/server";
|
||||
import { AdminRoleType, Prisma, type PrismaClient } from "@prisma/client";
|
||||
|
||||
/** Rollenprüfung und gemeinsame Fehlerbehandlung für alle Admin-Prozeduren. */
|
||||
|
||||
/** A caller's resolved admin identity for logging — "BOOTSTRAP" has no AdminRole row of its own. */
|
||||
export type ResolvedAdminRole = AdminRoleType | "BOOTSTRAP";
|
||||
|
||||
/** The env-bootstrapped super-owner, the AdminRole row's role, or null for non-admins. */
|
||||
export async function resolveAdminRole(prisma: PrismaClient, userId: string): Promise<ResolvedAdminRole | null> {
|
||||
if (process.env.ADMIN_OWNER_ID === userId) return "BOOTSTRAP";
|
||||
const role = await prisma.adminRole.findUnique({ where: { ownerId: userId } });
|
||||
return role?.role ?? null;
|
||||
}
|
||||
|
||||
const ROLE_RANK: Record<AdminRoleType, number> = {
|
||||
[AdminRoleType.SUPPORT]: 0,
|
||||
[AdminRoleType.MODERATOR]: 1,
|
||||
[AdminRoleType.SUPER_ADMIN]: 2,
|
||||
};
|
||||
|
||||
/**
|
||||
* Resolves the caller's admin role, throwing FORBIDDEN unless it meets
|
||||
* `minRole` on the SUPPORT < MODERATOR < SUPER_ADMIN scale (permission
|
||||
* matrix, Gitea #10). Returns the resolved role so mutation call sites can
|
||||
* stamp it onto the ModerationLog entry they write in the same request.
|
||||
*/
|
||||
export async function assertAdmin(
|
||||
prisma: PrismaClient,
|
||||
userId: string,
|
||||
minRole: AdminRoleType = AdminRoleType.SUPPORT
|
||||
): Promise<ResolvedAdminRole> {
|
||||
const role = await resolveAdminRole(prisma, userId);
|
||||
if (role === null || (role !== "BOOTSTRAP" && ROLE_RANK[role] < ROLE_RANK[minRole])) {
|
||||
throw new TRPCError({ code: "FORBIDDEN" });
|
||||
}
|
||||
return role;
|
||||
}
|
||||
|
||||
/**
|
||||
* Moderationsaktionen gegen ein Konto (sperren, verwarnen, löschen …) nur
|
||||
* gegen niedrigere Ränge. Das Bootstrap-Konto (ADMIN_OWNER_ID, besitzt das
|
||||
* Team-Tier) ist für alle tabu, es selbst darf gegen jede Rolle vorgehen.
|
||||
*/
|
||||
export async function assertCanModerate(
|
||||
prisma: PrismaClient,
|
||||
callerRole: ResolvedAdminRole,
|
||||
targetOwnerId: string
|
||||
): Promise<void> {
|
||||
if (process.env.ADMIN_OWNER_ID === targetOwnerId) throw new TRPCError({ code: "FORBIDDEN" });
|
||||
if (callerRole === "BOOTSTRAP") return;
|
||||
const target = await prisma.adminRole.findUnique({ where: { ownerId: targetOwnerId } });
|
||||
if (target && ROLE_RANK[target.role] >= ROLE_RANK[callerRole]) {
|
||||
throw new TRPCError({ code: "FORBIDDEN", message: "Cannot act on an admin with an equal or higher role." });
|
||||
}
|
||||
}
|
||||
|
||||
/** Prisma P2025 (zu löschender Eintrag fehlt) → NOT_FOUND statt Serverfehler. */
|
||||
export function rethrowNotFound(err: unknown): never {
|
||||
if (err instanceof Prisma.PrismaClientKnownRequestError && err.code === "P2025") {
|
||||
throw new TRPCError({ code: "NOT_FOUND" });
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
import "server-only";
|
||||
import { z } from "zod";
|
||||
import { randomUUID } from "crypto";
|
||||
import { AdminRoleType } from "@prisma/client";
|
||||
import { protectedProcedure } from "@/trpc/init";
|
||||
import { modLog } from "@/lib/admin/mod-log";
|
||||
import { createSignedUploadUrl, MUSIC_STORAGE_BUCKET, MUSIC_ALLOWED_CONTENT_TYPES, MAX_MUSIC_FILE_SIZE } from "@/lib/supabase-storage";
|
||||
import { assertAdmin } from "@/trpc/routers/admin-procedures/guards";
|
||||
|
||||
/** Musikkatalog für Storys. Teil von `trpc.admin.*` (admin.ts). */
|
||||
|
||||
export const adminMusicProcedures = {
|
||||
// ─── Music track catalog (Story music overlay) ────────────────────────────────
|
||||
// Admin-curated only — no user upload path, so copyright liability for each
|
||||
// track stays with the admin who uploaded it (licenseNote is required).
|
||||
getMusicTrackUploadUrl: protectedProcedure
|
||||
.input(
|
||||
z.object({
|
||||
contentType: z.enum(MUSIC_ALLOWED_CONTENT_TYPES),
|
||||
fileSize: z.number().max(MAX_MUSIC_FILE_SIZE, "Audio file must be under 5 MB"),
|
||||
})
|
||||
)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
await assertAdmin(ctx.prisma, ctx.userId, AdminRoleType.SUPER_ADMIN);
|
||||
const ext = input.contentType.split("/")[1]!.replace("mpeg", "mp3");
|
||||
const key = `tracks/${randomUUID()}.${ext}`;
|
||||
const { signedUrl } = await createSignedUploadUrl(key, MUSIC_STORAGE_BUCKET);
|
||||
return { presignedUrl: signedUrl, key };
|
||||
}),
|
||||
|
||||
listMusicTracks: protectedProcedure
|
||||
.input(z.object({ activeOnly: z.boolean().default(false) }).optional())
|
||||
.query(async ({ ctx, input }) => {
|
||||
await assertAdmin(ctx.prisma, ctx.userId, AdminRoleType.MODERATOR);
|
||||
return ctx.prisma.musicTrack.findMany({
|
||||
where: input?.activeOnly ? { active: true } : undefined,
|
||||
orderBy: { createdAt: "desc" },
|
||||
});
|
||||
}),
|
||||
|
||||
createMusicTrack: protectedProcedure
|
||||
.input(
|
||||
z.object({
|
||||
title: z.string().min(1).max(100),
|
||||
artist: z.string().min(1).max(100),
|
||||
licenseNote: z.string().min(1).max(500),
|
||||
storageKey: z.string().min(1),
|
||||
durationSecs: z.number().positive(),
|
||||
})
|
||||
)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const callerRole = await assertAdmin(ctx.prisma, ctx.userId, AdminRoleType.SUPER_ADMIN);
|
||||
return ctx.prisma.$transaction(async (tx) => {
|
||||
const track = await tx.musicTrack.create({
|
||||
data: { ...input, createdBy: ctx.userId },
|
||||
});
|
||||
await modLog(tx, ctx, callerRole, {
|
||||
action: "CREATE_MUSIC_TRACK",
|
||||
targetType: "MUSIC_TRACK",
|
||||
targetId: track.id,
|
||||
reason: input.title,
|
||||
});
|
||||
return track;
|
||||
});
|
||||
}),
|
||||
|
||||
updateMusicTrack: protectedProcedure
|
||||
.input(
|
||||
z.object({
|
||||
id: z.string().min(1),
|
||||
title: z.string().min(1).max(100).optional(),
|
||||
artist: z.string().min(1).max(100).optional(),
|
||||
licenseNote: z.string().min(1).max(500).optional(),
|
||||
active: z.boolean().optional(),
|
||||
})
|
||||
)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const callerRole = await assertAdmin(ctx.prisma, ctx.userId, AdminRoleType.SUPER_ADMIN);
|
||||
const { id, ...rest } = input;
|
||||
const [track] = await ctx.prisma.$transaction([
|
||||
ctx.prisma.musicTrack.update({ where: { id }, data: rest }),
|
||||
modLog(ctx.prisma, ctx, callerRole, { action: "UPDATE_MUSIC_TRACK", targetType: "MUSIC_TRACK", targetId: id }),
|
||||
]);
|
||||
return track;
|
||||
}),
|
||||
|
||||
// Hard delete — only safe once no Story references the track any more
|
||||
// (Story.musicTrackId is onDelete: SetNull, so this wouldn't corrupt old
|
||||
// stories either way, but updateMusicTrack's active:false is the preferred
|
||||
// way to retire a track without breaking its own audit trail).
|
||||
deleteMusicTrack: protectedProcedure
|
||||
.input(z.object({ id: z.string().min(1) }))
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const callerRole = await assertAdmin(ctx.prisma, ctx.userId, AdminRoleType.SUPER_ADMIN);
|
||||
await ctx.prisma.$transaction([
|
||||
ctx.prisma.musicTrack.delete({ where: { id: input.id } }),
|
||||
modLog(ctx.prisma, ctx, callerRole, {
|
||||
action: "DELETE_MUSIC_TRACK",
|
||||
targetType: "MUSIC_TRACK",
|
||||
targetId: input.id,
|
||||
}),
|
||||
]);
|
||||
return { success: true };
|
||||
}),
|
||||
};
|
||||
@@ -0,0 +1,89 @@
|
||||
import "server-only";
|
||||
import { TRPCError } from "@trpc/server";
|
||||
import { Prisma, type PrismaClient } from "@prisma/client";
|
||||
import { modLog, type ModLogActor } from "@/lib/admin/mod-log";
|
||||
import { postDeleteOps } from "@/lib/delete-post";
|
||||
import { sendTeamMessage } from "@/lib/team-pet";
|
||||
import { describeReportTarget, reportUpheldMessage } from "@/lib/report-feedback";
|
||||
import { reportDecisionOps } from "@/lib/report-decisions";
|
||||
import { type ResolvedAdminRole } from "@/trpc/routers/admin-procedures/guards";
|
||||
|
||||
/** Beitrags-Aktionen, die Beitrags- und Meldungs-Moderation teilen. */
|
||||
|
||||
/** Ein Feld eines Beitrags setzen (ausblenden, anpinnen …) und die Aktion im selben Schritt protokollieren. */
|
||||
export async function updatePostLogged(
|
||||
ctx: { prisma: PrismaClient } & ModLogActor,
|
||||
callerRole: ResolvedAdminRole,
|
||||
postId: string,
|
||||
data: Prisma.PostUpdateInput,
|
||||
action: string,
|
||||
reason?: string
|
||||
): Promise<{ success: true }> {
|
||||
const post = await ctx.prisma.post.findUnique({ where: { id: postId } });
|
||||
if (!post) throw new TRPCError({ code: "NOT_FOUND" });
|
||||
|
||||
await ctx.prisma.$transaction([
|
||||
ctx.prisma.post.update({ where: { id: postId }, data }),
|
||||
modLog(ctx.prisma, ctx, callerRole, { action, targetType: "POST", targetId: postId, reason }),
|
||||
]);
|
||||
return { success: true };
|
||||
}
|
||||
|
||||
/** Name des gemeldeten Tiers bzw. des Tiers, dem der gemeldete Beitrag gehört — für die Team-Nachricht an den Melder. */
|
||||
export async function reportTargetPetName(
|
||||
prisma: PrismaClient,
|
||||
report: { targetPostId: string | null; targetPetId: string | null }
|
||||
): Promise<string | null> {
|
||||
if (report.targetPostId) {
|
||||
const post = await prisma.post.findUnique({
|
||||
where: { id: report.targetPostId },
|
||||
select: { pet: { select: { name: true } } },
|
||||
});
|
||||
return post?.pet?.name ?? null;
|
||||
}
|
||||
if (!report.targetPetId) return null;
|
||||
return (await prisma.pet.findUnique({ where: { id: report.targetPetId }, select: { name: true } }))?.name ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Beitrag als Moderator löschen: Meldungen, Paw-Backs und repostCount räumt
|
||||
* postDeleteOps ab (delete-post.ts), Log im selben Schritt. Mit
|
||||
* `notifyReporters` bekommt jeder Melder danach eine Dankes-Nachricht.
|
||||
*/
|
||||
export async function deletePostAsModerator(
|
||||
ctx: { prisma: PrismaClient } & ModLogActor,
|
||||
callerRole: ResolvedAdminRole,
|
||||
postId: string,
|
||||
reason: string | undefined,
|
||||
notifyReporters: boolean
|
||||
): Promise<{ success: true }> {
|
||||
const post = await ctx.prisma.post.findUnique({
|
||||
where: { id: postId },
|
||||
select: { repost: { select: { originalPostId: true } }, pet: { select: { name: true } } },
|
||||
});
|
||||
if (!post) throw new TRPCError({ code: "NOT_FOUND" });
|
||||
|
||||
// Offene Meldungen vor dem Löschen einsammeln — sie fallen mit dem Beitrag weg,
|
||||
// zählen in der Melde-Statistik aber als bestätigt (report-decisions.ts).
|
||||
const reports = await ctx.prisma.report.findMany({
|
||||
where: { targetPostId: postId },
|
||||
select: { reporterPetId: true, targetPostId: true, targetPetId: true, reason: true, createdAt: true },
|
||||
});
|
||||
const reporterPetIds = notifyReporters ? [...new Set(reports.map((r) => r.reporterPetId))] : [];
|
||||
|
||||
await ctx.prisma.$transaction([
|
||||
...(await reportDecisionOps(ctx.prisma, reports, "UPHELD", ctx.userId)),
|
||||
...(await postDeleteOps(ctx.prisma, postId, post.repost?.originalPostId)),
|
||||
modLog(ctx.prisma, ctx, callerRole, { action: "DELETE_POST", targetType: "POST", targetId: postId, reason }),
|
||||
]);
|
||||
|
||||
const message = reportUpheldMessage(describeReportTarget("post", post.pet?.name ?? null));
|
||||
// Sequential (ensureTeamPet must not race with itself) and
|
||||
// best-effort: one failing recipient must not stop the others.
|
||||
for (const petId of reporterPetIds) {
|
||||
await sendTeamMessage(ctx.prisma, petId, message).catch((err) =>
|
||||
console.error("[admin] report upheld notification failed", petId, err)
|
||||
);
|
||||
}
|
||||
return { success: true };
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
import "server-only";
|
||||
import { z } from "zod";
|
||||
import { AdminRoleType } from "@prisma/client";
|
||||
import { protectedProcedure } from "@/trpc/init";
|
||||
import { modLog } from "@/lib/admin/mod-log";
|
||||
import { petIdentitySelect } from "@/repositories/pet-repository";
|
||||
import { assertAdmin } from "@/trpc/routers/admin-procedures/guards";
|
||||
import { updatePostLogged, deletePostAsModerator } from "@/trpc/routers/admin-procedures/post-actions";
|
||||
|
||||
/** Beitrags- und Kommentar-Moderation. Teil von `trpc.admin.*` (admin.ts). */
|
||||
|
||||
export const adminPostsProcedures = {
|
||||
// ─── Post moderation ─────────────────────────────────────────────────────────
|
||||
listPosts: protectedProcedure
|
||||
.input(
|
||||
z.object({
|
||||
cursor: z.string().nullish(),
|
||||
limit: z.number().min(1).max(50).default(20),
|
||||
search: z.string().optional(),
|
||||
})
|
||||
)
|
||||
.query(async ({ ctx, input }) => {
|
||||
await assertAdmin(ctx.prisma, ctx.userId);
|
||||
const posts = await ctx.prisma.post.findMany({
|
||||
where: input.search
|
||||
? {
|
||||
OR: [
|
||||
{ caption: { contains: input.search, mode: "insensitive" } },
|
||||
{ pet: { name: { contains: input.search, mode: "insensitive" } } },
|
||||
],
|
||||
}
|
||||
: undefined,
|
||||
include: {
|
||||
pet: { select: { ...petIdentitySelect, ownerId: true } },
|
||||
images: { orderBy: { position: "asc" }, take: 1 },
|
||||
videoPost: { select: { muxPlaybackId: true } },
|
||||
milestone: true,
|
||||
repost: {
|
||||
include: {
|
||||
originalPost: {
|
||||
include: {
|
||||
pet: { select: { id: true, name: true, nickname: true } },
|
||||
images: { orderBy: { position: "asc" }, take: 1 },
|
||||
milestone: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
orderBy: { createdAt: "desc" },
|
||||
take: input.limit + 1,
|
||||
...(input.cursor ? { skip: 1, cursor: { id: input.cursor } } : {}),
|
||||
});
|
||||
const hasNext = posts.length > input.limit;
|
||||
const items = hasNext ? posts.slice(0, input.limit) : posts;
|
||||
|
||||
// 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
|
||||
.input(z.object({ postId: z.string().min(1), reason: z.string().max(500).optional() }))
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const callerRole = await assertAdmin(ctx.prisma, ctx.userId, AdminRoleType.MODERATOR);
|
||||
return deletePostAsModerator(ctx, callerRole, input.postId, input.reason, false);
|
||||
}),
|
||||
|
||||
hidePost: protectedProcedure
|
||||
.input(z.object({ postId: z.string().min(1), reason: z.string().min(1).max(500) }))
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const callerRole = await assertAdmin(ctx.prisma, ctx.userId, AdminRoleType.MODERATOR);
|
||||
return updatePostLogged(ctx, callerRole, input.postId, { hiddenAt: new Date() }, "HIDE_POST", input.reason);
|
||||
}),
|
||||
|
||||
unhidePost: protectedProcedure
|
||||
.input(z.object({ postId: z.string().min(1) }))
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const callerRole = await assertAdmin(ctx.prisma, ctx.userId, AdminRoleType.MODERATOR);
|
||||
return updatePostLogged(ctx, callerRole, input.postId, { hiddenAt: null }, "UNHIDE_POST");
|
||||
}),
|
||||
|
||||
// Gitea #18 — legal AI-content disclosure correction. Owners cannot change
|
||||
// their own aiDisclosure choice after posting; this is the only other
|
||||
// write path, always requiring a reason for the audit trail.
|
||||
setAiDisclosure: protectedProcedure
|
||||
.input(
|
||||
z.object({
|
||||
postId: z.string().min(1),
|
||||
aiDisclosure: z.enum(["NONE", "AI_MODIFIED", "AI_GENERATED"]),
|
||||
reason: z.string().min(1).max(500),
|
||||
})
|
||||
)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const callerRole = await assertAdmin(ctx.prisma, ctx.userId, AdminRoleType.MODERATOR);
|
||||
return updatePostLogged(
|
||||
ctx,
|
||||
callerRole,
|
||||
input.postId,
|
||||
{ aiDisclosure: input.aiDisclosure },
|
||||
"SET_AI_DISCLOSURE",
|
||||
input.reason
|
||||
);
|
||||
}),
|
||||
|
||||
pinPost: protectedProcedure
|
||||
.input(z.object({ postId: z.string().min(1) }))
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const callerRole = await assertAdmin(ctx.prisma, ctx.userId, AdminRoleType.MODERATOR);
|
||||
return updatePostLogged(ctx, callerRole, input.postId, { pinnedAt: new Date() }, "PIN_POST");
|
||||
}),
|
||||
|
||||
unpinPost: protectedProcedure
|
||||
.input(z.object({ postId: z.string().min(1) }))
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const callerRole = await assertAdmin(ctx.prisma, ctx.userId, AdminRoleType.MODERATOR);
|
||||
return updatePostLogged(ctx, callerRole, input.postId, { pinnedAt: null }, "UNPIN_POST");
|
||||
}),
|
||||
|
||||
listComments: protectedProcedure
|
||||
.input(z.object({ postId: z.string().min(1) }))
|
||||
.query(async ({ ctx, input }) => {
|
||||
await assertAdmin(ctx.prisma, ctx.userId);
|
||||
return ctx.prisma.comment.findMany({
|
||||
where: { postId: input.postId },
|
||||
include: { pet: { select: petIdentitySelect } },
|
||||
orderBy: { createdAt: "asc" },
|
||||
});
|
||||
}),
|
||||
|
||||
deleteComment: protectedProcedure
|
||||
.input(z.object({ commentId: z.string().min(1), reason: z.string().max(500).optional() }))
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const callerRole = await assertAdmin(ctx.prisma, ctx.userId, AdminRoleType.MODERATOR);
|
||||
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 modLog(tx, ctx, callerRole, {
|
||||
action: "DELETE_COMMENT",
|
||||
targetType: "COMMENT",
|
||||
targetId: input.commentId,
|
||||
reason: input.reason,
|
||||
});
|
||||
});
|
||||
return { success: true };
|
||||
}),
|
||||
};
|
||||
@@ -0,0 +1,208 @@
|
||||
import "server-only";
|
||||
import { z } from "zod";
|
||||
import { TRPCError } from "@trpc/server";
|
||||
import { AdminRoleType, type ReportReason } from "@prisma/client";
|
||||
import { protectedProcedure } from "@/trpc/init";
|
||||
import { modLog } from "@/lib/admin/mod-log";
|
||||
import { petIdentitySelect } from "@/repositories/pet-repository";
|
||||
import { sendTeamMessage } from "@/lib/team-pet";
|
||||
import { describeReportTarget, profileReportUpheldMessage, reportDismissedMessage } from "@/lib/report-feedback";
|
||||
import { isFrequentFalseReporter, reportDecisionOps, reportStatsByPet } from "@/lib/report-decisions";
|
||||
import { assertAdmin } from "@/trpc/routers/admin-procedures/guards";
|
||||
import { reportTargetPetName, deletePostAsModerator } from "@/trpc/routers/admin-procedures/post-actions";
|
||||
|
||||
/** Meldungen: Warteschlange und Entscheidungen (Melde-Statistik: report-decisions.ts). Teil von `trpc.admin.*` (admin.ts). */
|
||||
|
||||
type ReportSeverity = "HIGH" | "MEDIUM" | "LOW";
|
||||
|
||||
/** Derived from ReportReason — reporters don't self-rate severity. */
|
||||
const REPORT_SEVERITY: Record<ReportReason, ReportSeverity> = {
|
||||
HARASSMENT: "HIGH",
|
||||
INAPPROPRIATE: "HIGH",
|
||||
MISINFORMATION: "MEDIUM",
|
||||
SPAM: "LOW",
|
||||
OTHER: "LOW",
|
||||
};
|
||||
const SEVERITY_RANK: Record<ReportSeverity, number> = { HIGH: 2, MEDIUM: 1, LOW: 0 };
|
||||
|
||||
export const adminReportsProcedures = {
|
||||
// ─── Reports ─────────────────────────────────────────────────────────────────
|
||||
listReports: protectedProcedure.query(async ({ ctx }) => {
|
||||
await assertAdmin(ctx.prisma, ctx.userId);
|
||||
|
||||
const reports = await ctx.prisma.report.findMany({
|
||||
include: {
|
||||
reporter: { select: petIdentitySelect },
|
||||
},
|
||||
orderBy: { createdAt: "desc" },
|
||||
take: 100,
|
||||
});
|
||||
|
||||
// targetPostId is a raw string — no Prisma relation, so fetch posts separately
|
||||
const postIds = [...new Set(
|
||||
reports.map((r) => r.targetPostId).filter((id): id is string => !!id)
|
||||
)];
|
||||
|
||||
const posts = postIds.length > 0
|
||||
? await ctx.prisma.post.findMany({
|
||||
where: { id: { in: postIds } },
|
||||
select: {
|
||||
id: true,
|
||||
caption: true,
|
||||
type: true,
|
||||
createdAt: true,
|
||||
reactionCount: true,
|
||||
commentCount: true,
|
||||
pet: { select: petIdentitySelect },
|
||||
images: {
|
||||
orderBy: { position: "asc" },
|
||||
take: 4,
|
||||
select: { storageKey: true, position: true, blurhash: true },
|
||||
},
|
||||
},
|
||||
})
|
||||
: [];
|
||||
|
||||
const postMap = new Map(posts.map((p) => [p.id, p]));
|
||||
|
||||
// Profil-Meldungen: Tier zum Anzeigen (Name statt roher ID auf der Admin-Seite)
|
||||
const targetPetIds = [...new Set(reports.map((r) => r.targetPetId).filter((id): id is string => !!id))];
|
||||
const targetPets = targetPetIds.length > 0
|
||||
? ((await ctx.prisma.pet.findMany({ where: { id: { in: targetPetIds } }, select: petIdentitySelect })) ?? [])
|
||||
: [];
|
||||
const targetPetMap = new Map(targetPets.map((p) => [p.id, p]));
|
||||
// Melder mit „häufigen Fehlmeldungen“ markieren (Melde-Statistik, report-decisions.ts).
|
||||
const reporterStats = await reportStatsByPet(ctx.prisma, [...new Set(reports.map((r) => r.reporterPetId))]);
|
||||
|
||||
// Severity-first, newest-within-severity — reports don't carry an
|
||||
// explicit severity column, it's derived from `reason` (Gitea #10).
|
||||
return reports
|
||||
.map((r) => ({
|
||||
...r,
|
||||
severity: REPORT_SEVERITY[r.reason],
|
||||
post: r.targetPostId ? (postMap.get(r.targetPostId) ?? null) : null,
|
||||
targetPet: r.targetPetId ? (targetPetMap.get(r.targetPetId) ?? null) : null,
|
||||
reporterFrequentFalseReporter: isFrequentFalseReporter(reporterStats.get(r.reporterPetId)!.filed),
|
||||
}))
|
||||
.sort(
|
||||
(a, b) =>
|
||||
SEVERITY_RANK[b.severity] - SEVERITY_RANK[a.severity] ||
|
||||
b.createdAt.getTime() - a.createdAt.getTime()
|
||||
);
|
||||
}),
|
||||
|
||||
// Full images + reactor list for the report detail dialog. Comments reuse
|
||||
// the existing listComments/deleteComment pair (see admin posts page) —
|
||||
// no need to duplicate that fetch here.
|
||||
getReportedPostDetail: protectedProcedure
|
||||
.input(z.object({ postId: z.string().min(1) }))
|
||||
.query(async ({ ctx, input }) => {
|
||||
await assertAdmin(ctx.prisma, ctx.userId);
|
||||
|
||||
const post = await ctx.prisma.post.findUnique({
|
||||
where: { id: input.postId },
|
||||
select: {
|
||||
id: true,
|
||||
caption: true,
|
||||
type: true,
|
||||
createdAt: true,
|
||||
hiddenAt: true,
|
||||
pet: { select: petIdentitySelect },
|
||||
images: {
|
||||
orderBy: { position: "asc" },
|
||||
select: { storageKey: true, position: true, blurhash: true },
|
||||
},
|
||||
reactions: {
|
||||
orderBy: { createdAt: "desc" },
|
||||
take: 200,
|
||||
select: {
|
||||
pet: { select: petIdentitySelect },
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
if (!post) throw new TRPCError({ code: "NOT_FOUND" });
|
||||
return post;
|
||||
}),
|
||||
|
||||
dismissReport: protectedProcedure
|
||||
.input(
|
||||
z.object({
|
||||
reportId: z.string().min(1),
|
||||
// found.md: der Melder bekommt eine Team-Nachricht mit Begründung.
|
||||
notifyReporter: z.boolean().default(true),
|
||||
message: z.string().max(500).optional(),
|
||||
})
|
||||
)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const callerRole = await assertAdmin(ctx.prisma, ctx.userId, AdminRoleType.MODERATOR);
|
||||
const report = await ctx.prisma.report.findUnique({ where: { id: input.reportId } });
|
||||
if (!report) throw new TRPCError({ code: "NOT_FOUND" });
|
||||
await ctx.prisma.$transaction([
|
||||
...(await reportDecisionOps(ctx.prisma, [report], "DISMISSED", ctx.userId)),
|
||||
ctx.prisma.report.delete({ where: { id: input.reportId } }),
|
||||
modLog(ctx.prisma, ctx, callerRole, {
|
||||
action: "DISMISS_REPORT",
|
||||
targetType: "REPORT",
|
||||
targetId: input.reportId,
|
||||
reason: input.message?.trim() || null,
|
||||
}),
|
||||
]);
|
||||
|
||||
// Best-effort — the dismissal is already persisted; a failed message
|
||||
// must not fail the request.
|
||||
if (input.notifyReporter) {
|
||||
try {
|
||||
const targetPetName = await reportTargetPetName(ctx.prisma, report);
|
||||
const target = describeReportTarget(report.targetPostId ? "post" : "pet", targetPetName);
|
||||
await sendTeamMessage(ctx.prisma, report.reporterPetId, reportDismissedMessage(target, input.message ?? ""));
|
||||
} catch (err) {
|
||||
console.error("[admin] report dismissal notification failed", err);
|
||||
}
|
||||
}
|
||||
return { success: true };
|
||||
}),
|
||||
|
||||
// Profil-Meldung bestätigen: Der Moderator hat (separat) gehandelt — z. B.
|
||||
// verwarnt, gesperrt oder Inhalte entfernt. Beitrags-Meldungen werden über
|
||||
// „Beitrag löschen“ bestätigt. Zählt in der Melde-Statistik als bestätigt.
|
||||
upholdReport: protectedProcedure
|
||||
.input(z.object({ reportId: z.string().min(1), notifyReporter: z.boolean().default(true) }))
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const callerRole = await assertAdmin(ctx.prisma, ctx.userId, AdminRoleType.MODERATOR);
|
||||
const report = await ctx.prisma.report.findUnique({ where: { id: input.reportId } });
|
||||
if (!report) throw new TRPCError({ code: "NOT_FOUND" });
|
||||
if (report.targetPostId) {
|
||||
throw new TRPCError({ code: "BAD_REQUEST", message: "Beitrags-Meldungen über „Beitrag löschen“ bestätigen." });
|
||||
}
|
||||
await ctx.prisma.$transaction([
|
||||
...(await reportDecisionOps(ctx.prisma, [report], "UPHELD", ctx.userId)),
|
||||
ctx.prisma.report.delete({ where: { id: input.reportId } }),
|
||||
modLog(ctx.prisma, ctx, callerRole, { action: "UPHOLD_REPORT", targetType: "REPORT", targetId: input.reportId }),
|
||||
]);
|
||||
|
||||
if (input.notifyReporter) {
|
||||
try {
|
||||
const target = describeReportTarget("pet", await reportTargetPetName(ctx.prisma, report));
|
||||
await sendTeamMessage(ctx.prisma, report.reporterPetId, profileReportUpheldMessage(target));
|
||||
} catch (err) {
|
||||
console.error("[admin] report upheld notification failed", err);
|
||||
}
|
||||
}
|
||||
return { success: true };
|
||||
}),
|
||||
|
||||
deleteReportedPost: protectedProcedure
|
||||
.input(
|
||||
z.object({
|
||||
postId: z.string().min(1),
|
||||
reason: z.string().max(500).optional(),
|
||||
// found.md: alle Melder dieses Beitrags bekommen eine Dankes-Nachricht.
|
||||
notifyReporters: z.boolean().default(true),
|
||||
})
|
||||
)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const callerRole = await assertAdmin(ctx.prisma, ctx.userId, AdminRoleType.MODERATOR);
|
||||
return deletePostAsModerator(ctx, callerRole, input.postId, input.reason, input.notifyReporters);
|
||||
}),
|
||||
};
|
||||
@@ -0,0 +1,208 @@
|
||||
import "server-only";
|
||||
import { z } from "zod";
|
||||
import { TRPCError } from "@trpc/server";
|
||||
import { AdminRoleType } from "@prisma/client";
|
||||
import { clerkClient } from "@clerk/nextjs/server";
|
||||
import { protectedProcedure } from "@/trpc/init";
|
||||
import { modLog } from "@/lib/admin/mod-log";
|
||||
import { isMaintenanceModeEnabled, setMaintenanceMode } from "@/lib/maintenance";
|
||||
import { isStoryEditorEnabled, setStoryEditorEnabled } from "@/lib/feature-flags";
|
||||
import { resolveAdminRole, assertAdmin, rethrowNotFound } from "@/trpc/routers/admin-procedures/guards";
|
||||
|
||||
/** Rollen & Team, Wartungsmodus, Story-Editor-Notschalter, System-Mitteilungen. Teil von `trpc.admin.*` (admin.ts). */
|
||||
|
||||
export const adminSystemProcedures = {
|
||||
/** The caller's own admin identity — no minRole gate, anyone can ask "what am I". */
|
||||
getMyRole: protectedProcedure.query(({ ctx }) => resolveAdminRole(ctx.prisma, ctx.userId)),
|
||||
|
||||
// ─── Moderator management (grant/revoke stay super-admin only) ───────────────
|
||||
listModerators: protectedProcedure.query(async ({ ctx }) => {
|
||||
await assertAdmin(ctx.prisma, ctx.userId, AdminRoleType.MODERATOR);
|
||||
const roles = await ctx.prisma.adminRole.findMany({
|
||||
include: {
|
||||
owner: {
|
||||
include: { pets: { select: { name: true, nickname: true, avatarKey: true }, take: 1 } },
|
||||
},
|
||||
},
|
||||
orderBy: { grantedAt: "desc" },
|
||||
});
|
||||
// Namen + E-Mail für die Seite „Team & Rollen“ (statt nackter Clerk-IDs). Clerk-Ausfall → ohne Namen.
|
||||
const ids = [...new Set(roles.flatMap((r) => [r.ownerId, r.grantedBy]).filter((id): id is string => !!id))];
|
||||
let people = new Map<string, { name: string | null; email: string | null }>();
|
||||
if (ids.length > 0) {
|
||||
try {
|
||||
const { data } = await (await clerkClient()).users.getUserList({ userId: ids, limit: ids.length });
|
||||
people = new Map(
|
||||
data.map((u) => [
|
||||
u.id,
|
||||
{
|
||||
name: [u.firstName, u.lastName].filter(Boolean).join(" ") || null,
|
||||
email: u.emailAddresses.find((e) => e.id === u.primaryEmailAddressId)?.emailAddress ?? null,
|
||||
},
|
||||
])
|
||||
);
|
||||
} catch {
|
||||
// Liste bleibt nutzbar, nur ohne Namen.
|
||||
}
|
||||
}
|
||||
return roles.map((r) => ({
|
||||
...r,
|
||||
person: people.get(r.ownerId) ?? { name: null, email: null },
|
||||
grantedByName: r.grantedBy ? (people.get(r.grantedBy)?.name ?? null) : null,
|
||||
}));
|
||||
}),
|
||||
|
||||
grantRole: protectedProcedure
|
||||
.input(z.object({ ownerId: z.string().min(1), role: z.nativeEnum(AdminRoleType) }))
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const callerRole = await assertAdmin(ctx.prisma, ctx.userId, AdminRoleType.SUPER_ADMIN);
|
||||
const [role] = await ctx.prisma.$transaction([
|
||||
ctx.prisma.adminRole.upsert({
|
||||
where: { ownerId: input.ownerId },
|
||||
create: { ownerId: input.ownerId, role: input.role, grantedBy: ctx.userId },
|
||||
update: { role: input.role, grantedBy: ctx.userId, grantedAt: new Date() },
|
||||
}),
|
||||
modLog(ctx.prisma, ctx, callerRole, {
|
||||
action: "GRANT_ROLE",
|
||||
targetType: "USER",
|
||||
targetId: input.ownerId,
|
||||
reason: input.role,
|
||||
}),
|
||||
]);
|
||||
return role;
|
||||
}),
|
||||
|
||||
revokeRole: protectedProcedure
|
||||
.input(z.object({ ownerId: z.string().min(1) }))
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const callerRole = await assertAdmin(ctx.prisma, ctx.userId, AdminRoleType.SUPER_ADMIN);
|
||||
await ctx.prisma
|
||||
.$transaction([
|
||||
ctx.prisma.adminRole.delete({ where: { ownerId: input.ownerId } }),
|
||||
modLog(ctx.prisma, ctx, callerRole, { action: "REVOKE_ROLE", targetType: "USER", targetId: input.ownerId }),
|
||||
])
|
||||
.catch(rethrowNotFound);
|
||||
return { success: true };
|
||||
}),
|
||||
|
||||
/** Action count per moderator over the trailing window — throughput for the Moderators page. */
|
||||
getModeratorThroughput: protectedProcedure
|
||||
.input(z.object({ days: z.number().min(1).max(365).default(30) }))
|
||||
.query(async ({ ctx, input }) => {
|
||||
await assertAdmin(ctx.prisma, ctx.userId, AdminRoleType.MODERATOR);
|
||||
const since = new Date(Date.now() - input.days * 24 * 60 * 60 * 1000);
|
||||
const grouped = await ctx.prisma.moderationLog.groupBy({
|
||||
by: ["moderatorId"],
|
||||
where: { createdAt: { gte: since } },
|
||||
_count: true,
|
||||
});
|
||||
return grouped
|
||||
.map((g) => ({ moderatorId: g.moderatorId, actionCount: g._count }))
|
||||
.sort((a, b) => b.actionCount - a.actionCount);
|
||||
}),
|
||||
|
||||
getMaintenanceMode: protectedProcedure.query(async ({ ctx }) => {
|
||||
await assertAdmin(ctx.prisma, ctx.userId, AdminRoleType.MODERATOR);
|
||||
return { enabled: await isMaintenanceModeEnabled() };
|
||||
}),
|
||||
|
||||
setMaintenanceMode: protectedProcedure
|
||||
.input(z.object({ enabled: z.boolean() }))
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const callerRole = await assertAdmin(ctx.prisma, ctx.userId, AdminRoleType.SUPER_ADMIN);
|
||||
await setMaintenanceMode(input.enabled);
|
||||
await modLog(ctx.prisma, ctx, callerRole, {
|
||||
action: input.enabled ? "ENABLE_MAINTENANCE_MODE" : "DISABLE_MAINTENANCE_MODE",
|
||||
targetType: "SYSTEM",
|
||||
targetId: "maintenance",
|
||||
});
|
||||
return { success: true };
|
||||
}),
|
||||
|
||||
/** Notschalter Story-Editor — Moderatoren dürfen ihn im Notfall abschalten. */
|
||||
getStoryEditorEnabled: protectedProcedure.query(async ({ ctx }) => {
|
||||
await assertAdmin(ctx.prisma, ctx.userId, AdminRoleType.MODERATOR);
|
||||
return { enabled: await isStoryEditorEnabled() };
|
||||
}),
|
||||
|
||||
setStoryEditorEnabled: protectedProcedure
|
||||
.input(z.object({ enabled: z.boolean() }))
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const callerRole = await assertAdmin(ctx.prisma, ctx.userId, AdminRoleType.MODERATOR);
|
||||
await setStoryEditorEnabled(input.enabled);
|
||||
await modLog(ctx.prisma, ctx, callerRole, {
|
||||
action: input.enabled ? "ENABLE_STORY_EDITOR" : "DISABLE_STORY_EDITOR",
|
||||
targetType: "SYSTEM",
|
||||
targetId: "story-editor",
|
||||
});
|
||||
return { success: true };
|
||||
}),
|
||||
|
||||
// ─── Broadcast / System-Mitteilungen (Gitea #10, Phase 1) ────────────────
|
||||
createBroadcast: protectedProcedure
|
||||
.input(
|
||||
z.object({
|
||||
title: z.string().min(1).max(200),
|
||||
body: z.string().min(1).max(2000),
|
||||
})
|
||||
)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const callerRole = await assertAdmin(ctx.prisma, ctx.userId, AdminRoleType.SUPER_ADMIN);
|
||||
const broadcast = await ctx.prisma.broadcast.create({
|
||||
data: { title: input.title.trim(), body: input.body.trim(), createdBy: ctx.userId },
|
||||
});
|
||||
await modLog(ctx.prisma, ctx, callerRole, {
|
||||
action: "SEND_BROADCAST",
|
||||
targetType: "SYSTEM",
|
||||
targetId: broadcast.id,
|
||||
});
|
||||
return broadcast;
|
||||
}),
|
||||
|
||||
// Destructive — a broadcast may already be showing in owners' banners, so
|
||||
// deletion always requires a reason for the audit trail, same bar as
|
||||
// hidePost/banOwner. SUPER_ADMIN-gated to match createBroadcast.
|
||||
deleteBroadcast: protectedProcedure
|
||||
.input(z.object({ broadcastId: z.string().min(1), reason: z.string().min(1).max(500) }))
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const callerRole = await assertAdmin(ctx.prisma, ctx.userId, AdminRoleType.SUPER_ADMIN);
|
||||
const broadcast = await ctx.prisma.broadcast.findUnique({ where: { id: input.broadcastId } });
|
||||
if (!broadcast) throw new TRPCError({ code: "NOT_FOUND" });
|
||||
|
||||
await ctx.prisma.$transaction([
|
||||
// BroadcastReceipt rows cascade (schema.prisma: onDelete: Cascade).
|
||||
ctx.prisma.broadcast.delete({ where: { id: input.broadcastId } }),
|
||||
modLog(ctx.prisma, ctx, callerRole, {
|
||||
action: "DELETE_BROADCAST",
|
||||
targetType: "SYSTEM",
|
||||
targetId: input.broadcastId,
|
||||
reason: input.reason,
|
||||
}),
|
||||
]);
|
||||
return { success: true };
|
||||
}),
|
||||
|
||||
listBroadcasts: protectedProcedure.query(async ({ ctx }) => {
|
||||
await assertAdmin(ctx.prisma, ctx.userId, AdminRoleType.MODERATOR);
|
||||
const [broadcasts, totalOwners] = await Promise.all([
|
||||
ctx.prisma.broadcast.findMany({
|
||||
orderBy: { createdAt: "desc" },
|
||||
take: 50,
|
||||
include: { _count: { select: { receipts: true } } },
|
||||
}),
|
||||
ctx.prisma.owner.count(),
|
||||
]);
|
||||
const readCounts = await ctx.prisma.broadcastReceipt.groupBy({
|
||||
by: ["broadcastId"],
|
||||
where: { broadcastId: { in: broadcasts.map((b) => b.id) }, readAt: { not: null } },
|
||||
_count: true,
|
||||
});
|
||||
const readCountByBroadcast = new Map(readCounts.map((r) => [r.broadcastId, r._count]));
|
||||
return broadcasts.map((b) => ({
|
||||
...b,
|
||||
deliveredCount: b._count.receipts,
|
||||
readCount: readCountByBroadcast.get(b.id) ?? 0,
|
||||
totalOwners,
|
||||
}));
|
||||
}),
|
||||
};
|
||||
@@ -0,0 +1,126 @@
|
||||
import "server-only";
|
||||
import { z } from "zod";
|
||||
import { TRPCError } from "@trpc/server";
|
||||
import { protectedProcedure } from "@/trpc/init";
|
||||
import { petIdentitySelect } from "@/repositories/pet-repository";
|
||||
import { ensureTeamPet, sendTeamMessage } from "@/lib/team-pet";
|
||||
import { assertAdmin } from "@/trpc/routers/admin-procedures/guards";
|
||||
|
||||
/** Team-Postfach (Kurator-Tier „PawFeed Team“). Teil von `trpc.admin.*` (admin.ts). */
|
||||
|
||||
export const adminTeamProcedures = {
|
||||
// ─── Team messaging (Gitea #6, shared inbox follow-up Gitea #10) ──────────────
|
||||
// Reuses the existing pet-to-pet Conversation/Message model instead of a
|
||||
// parallel admin-inbox system: a single "PawFeed Team" system Pet, owned by
|
||||
// the env-bootstrapped ADMIN_OWNER_ID, DMs the target pet through the normal
|
||||
// conversation flow.
|
||||
//
|
||||
// startTeamConversation still exists for lazily creating the conversation
|
||||
// row. Reading/sending, however, no longer routes through the ordinary
|
||||
// /messages/[conversationId] UI + assertPetOwnership — that only ever
|
||||
// worked for the literal ADMIN_OWNER_ID account, since assertPetOwnership
|
||||
// requires ctx.userId === pet.ownerId and the Team pet has one fixed owner.
|
||||
// listTeamConversations/getTeamConversationThread/sendTeamReply below gate
|
||||
// on assertAdmin instead, so every SUPPORT+ admin sees and can reply to the
|
||||
// same shared Team inbox — see /p/[secret]/messages.
|
||||
startTeamConversation: protectedProcedure
|
||||
.input(z.object({ targetPetId: z.string().min(1) }))
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
await assertAdmin(ctx.prisma, ctx.userId);
|
||||
|
||||
const targetPet = await ctx.prisma.pet.findUnique({
|
||||
where: { id: input.targetPetId },
|
||||
select: { id: true },
|
||||
});
|
||||
if (!targetPet) throw new TRPCError({ code: "NOT_FOUND" });
|
||||
|
||||
const teamPet = await ensureTeamPet(ctx.prisma);
|
||||
|
||||
if (teamPet.id === input.targetPetId) {
|
||||
throw new TRPCError({ code: "BAD_REQUEST", message: "Cannot message the Team pet itself." });
|
||||
}
|
||||
|
||||
const [petAId, petBId] = [teamPet.id, input.targetPetId].sort();
|
||||
const conversation = await ctx.prisma.conversation.upsert({
|
||||
where: { petAId_petBId: { petAId, petBId } },
|
||||
update: {},
|
||||
create: { petAId, petBId },
|
||||
});
|
||||
|
||||
return { conversationId: conversation.id, teamPetId: teamPet.id };
|
||||
}),
|
||||
|
||||
/** All conversations involving the Team pet — the shared admin inbox list. */
|
||||
listTeamConversations: protectedProcedure.query(async ({ ctx }) => {
|
||||
await assertAdmin(ctx.prisma, ctx.userId);
|
||||
const teamPet = await ensureTeamPet(ctx.prisma);
|
||||
|
||||
const convs = await ctx.prisma.conversation.findMany({
|
||||
where: { OR: [{ petAId: teamPet.id }, { petBId: teamPet.id }] },
|
||||
include: {
|
||||
petA: { select: petIdentitySelect },
|
||||
petB: { select: petIdentitySelect },
|
||||
messages: { orderBy: { createdAt: "desc" }, take: 1 },
|
||||
_count: {
|
||||
select: { messages: { where: { senderPetId: { not: teamPet.id }, readAt: null } } },
|
||||
},
|
||||
},
|
||||
orderBy: { updatedAt: "desc" },
|
||||
});
|
||||
|
||||
return convs.map((c) => ({
|
||||
id: c.id,
|
||||
otherPet: c.petAId === teamPet.id ? c.petB : c.petA,
|
||||
lastMessage: c.messages[0] ?? null,
|
||||
unreadCount: c._count.messages,
|
||||
updatedAt: c.updatedAt,
|
||||
}));
|
||||
}),
|
||||
|
||||
/** Full message thread for one Team conversation. Marks incoming messages as read (shared inbox). */
|
||||
getTeamConversationThread: protectedProcedure
|
||||
.input(z.object({ conversationId: z.string().min(1) }))
|
||||
.query(async ({ ctx, input }) => {
|
||||
await assertAdmin(ctx.prisma, ctx.userId);
|
||||
const teamPet = await ensureTeamPet(ctx.prisma);
|
||||
|
||||
const conv = await ctx.prisma.conversation.findUnique({ where: { id: input.conversationId } });
|
||||
if (!conv || (conv.petAId !== teamPet.id && conv.petBId !== teamPet.id)) {
|
||||
throw new TRPCError({ code: "NOT_FOUND" });
|
||||
}
|
||||
|
||||
const messages = await ctx.prisma.message.findMany({
|
||||
where: { conversationId: input.conversationId },
|
||||
orderBy: { createdAt: "asc" },
|
||||
take: 200,
|
||||
include: { senderPet: { select: petIdentitySelect } },
|
||||
});
|
||||
|
||||
// Fire-and-forget — any admin opening the thread marks it read for the whole team.
|
||||
ctx.prisma.message
|
||||
.updateMany({
|
||||
where: { conversationId: input.conversationId, senderPetId: { not: teamPet.id }, readAt: null },
|
||||
data: { readAt: new Date() },
|
||||
})
|
||||
.catch((err) => console.error("[admin] team-thread mark-read failed", err));
|
||||
|
||||
return { teamPetId: teamPet.id, messages };
|
||||
}),
|
||||
|
||||
/** Reply as the Team pet. Reuses sendTeamMessage (same helper used for automated notices). */
|
||||
sendTeamReply: protectedProcedure
|
||||
.input(z.object({ conversationId: z.string().min(1), body: z.string().min(1).max(1000) }))
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
await assertAdmin(ctx.prisma, ctx.userId);
|
||||
const teamPet = await ensureTeamPet(ctx.prisma);
|
||||
|
||||
const conv = await ctx.prisma.conversation.findUnique({ where: { id: input.conversationId } });
|
||||
if (!conv || (conv.petAId !== teamPet.id && conv.petBId !== teamPet.id)) {
|
||||
throw new TRPCError({ code: "NOT_FOUND" });
|
||||
}
|
||||
const recipientPetId = conv.petAId === teamPet.id ? conv.petBId : conv.petAId;
|
||||
|
||||
await sendTeamMessage(ctx.prisma, recipientPetId, input.body);
|
||||
return { success: true };
|
||||
}),
|
||||
};
|
||||
@@ -0,0 +1,339 @@
|
||||
import "server-only";
|
||||
import { z } from "zod";
|
||||
import { randomUUID } from "crypto";
|
||||
import { TRPCError } from "@trpc/server";
|
||||
import { AdminRoleType } from "@prisma/client";
|
||||
import { clerkClient } from "@clerk/nextjs/server";
|
||||
import { protectedProcedure } from "@/trpc/init";
|
||||
import { modLog } from "@/lib/admin/mod-log";
|
||||
import { petIdentitySelect } from "@/repositories/pet-repository";
|
||||
import { buildDataExport } from "@/lib/gdpr-export";
|
||||
import { uploadExport } from "@/lib/data-export-storage";
|
||||
import { sendMail } from "@/lib/mail";
|
||||
import { buildGreeting, renderBrandedMailHtml } from "@/lib/mail-template";
|
||||
import { deleteOwnerAccount } from "@/lib/delete-account";
|
||||
import { reportStatsByOwner, withFalseReporterFlag } from "@/lib/report-decisions";
|
||||
import { resolveAdminRole, assertAdmin, assertCanModerate, rethrowNotFound } from "@/trpc/routers/admin-procedures/guards";
|
||||
|
||||
/** Nutzer: Liste, Sperren, Shadowban, Verwarnungen, Konto löschen, Datenauskunft. Teil von `trpc.admin.*` (admin.ts). */
|
||||
|
||||
const DATA_EXPORT_TOKEN_TTL_MS = 7 * 24 * 60 * 60 * 1000; // 7 days
|
||||
|
||||
export const adminUsersProcedures = {
|
||||
// ─── Ban status check (no admin role required) ───────────────────────────────
|
||||
getActiveBan: protectedProcedure
|
||||
.input(z.object({ ownerId: z.string().min(1) }))
|
||||
.query(async ({ ctx, input }) => {
|
||||
// Only the owner themselves or an admin should query ban status
|
||||
if (input.ownerId !== ctx.userId && (await resolveAdminRole(ctx.prisma, ctx.userId)) === null) {
|
||||
throw new TRPCError({ code: "FORBIDDEN" });
|
||||
}
|
||||
const ban = await ctx.prisma.userBan.findUnique({ where: { ownerId: input.ownerId } });
|
||||
if (!ban) return null;
|
||||
// Check if a temporary ban has expired
|
||||
if (ban.expiresAt && ban.expiresAt < new Date()) {
|
||||
await ctx.prisma.userBan
|
||||
.delete({ where: { id: ban.id } })
|
||||
.catch((err) => console.error("[admin] expired ban cleanup failed", err));
|
||||
return null;
|
||||
}
|
||||
return ban;
|
||||
}),
|
||||
|
||||
// ─── Users / bans ────────────────────────────────────────────────────────────
|
||||
listUsers: protectedProcedure
|
||||
.input(
|
||||
z.object({
|
||||
cursor: z.string().nullish(),
|
||||
limit: z.number().min(1).max(50).default(20),
|
||||
search: z.string().optional(),
|
||||
banStatus: z.enum(["all", "banned", "active"]).default("all"),
|
||||
role: z.union([z.literal("all"), z.literal("none"), z.nativeEnum(AdminRoleType)]).default("all"),
|
||||
})
|
||||
)
|
||||
.query(async ({ ctx, input }) => {
|
||||
await assertAdmin(ctx.prisma, ctx.userId);
|
||||
const clerk = await clerkClient();
|
||||
|
||||
// Owner has no local name/email (Clerk owns that) — resolve matching
|
||||
// owner IDs by unioning Clerk's own query search (name/email/username)
|
||||
// with a local Pet.name match, since admins commonly search by pet
|
||||
// name too. Clerk search is capped at 100 matches for now.
|
||||
let searchedIds: string[] | null = null;
|
||||
if (input.search) {
|
||||
const [clerkMatches, petMatches] = await Promise.all([
|
||||
clerk.users.getUserList({ query: input.search, limit: 100 }),
|
||||
ctx.prisma.pet.findMany({
|
||||
where: { name: { contains: input.search, mode: "insensitive" } },
|
||||
select: { ownerId: true },
|
||||
}),
|
||||
]);
|
||||
searchedIds = [
|
||||
...new Set([...clerkMatches.data.map((u) => u.id), ...petMatches.map((p) => p.ownerId)]),
|
||||
];
|
||||
if (searchedIds.length === 0) {
|
||||
return { users: [], nextCursor: null };
|
||||
}
|
||||
}
|
||||
|
||||
const owners = await ctx.prisma.owner.findMany({
|
||||
where: {
|
||||
...(searchedIds ? { id: { in: searchedIds } } : {}),
|
||||
...(input.banStatus === "banned" ? { ban: { isNot: null } } : {}),
|
||||
...(input.banStatus === "active" ? { ban: null } : {}),
|
||||
...(input.role === "none" ? { adminRole: null } : {}),
|
||||
...(input.role !== "all" && input.role !== "none" ? { adminRole: { role: input.role } } : {}),
|
||||
},
|
||||
include: {
|
||||
pets: { select: { ...petIdentitySelect, isVerified: true }, take: 3 },
|
||||
ban: true,
|
||||
shadowban: true,
|
||||
adminRole: true,
|
||||
_count: { select: { pets: true, warnings: true } },
|
||||
},
|
||||
orderBy: { createdAt: "desc" },
|
||||
take: input.limit + 1,
|
||||
...(input.cursor ? { skip: 1, cursor: { id: input.cursor } } : {}),
|
||||
});
|
||||
const hasNext = owners.length > input.limit;
|
||||
const items = hasNext ? owners.slice(0, input.limit) : owners;
|
||||
|
||||
// Batch-fetch Clerk profile data (email/name) — Owner only stores the
|
||||
// Clerk userId locally, everything else lives in Clerk (Gitea #6).
|
||||
const clerkUsers = items.length > 0
|
||||
? (await clerk.users.getUserList({ userId: items.map((o) => o.id), limit: items.length })).data
|
||||
: [];
|
||||
const clerkById = new Map(clerkUsers.map((u) => [u.id, u]));
|
||||
const reportStats = await reportStatsByOwner(ctx.prisma, items.map((o) => o.id));
|
||||
|
||||
const usersWithClerkData = items.map((owner) => {
|
||||
const clerkUser = clerkById.get(owner.id);
|
||||
const primaryEmail = clerkUser?.emailAddresses.find(
|
||||
(e) => e.id === clerkUser.primaryEmailAddressId
|
||||
)?.emailAddress;
|
||||
return {
|
||||
...owner,
|
||||
reportStats: withFalseReporterFlag(reportStats.get(owner.id)!),
|
||||
clerk: clerkUser
|
||||
? {
|
||||
email: primaryEmail ?? null,
|
||||
name: [clerkUser.firstName, clerkUser.lastName].filter(Boolean).join(" ") || null,
|
||||
createdAt: new Date(clerkUser.createdAt),
|
||||
}
|
||||
: null,
|
||||
};
|
||||
});
|
||||
|
||||
return { users: usersWithClerkData, nextCursor: hasNext ? items[items.length - 1]!.id : null };
|
||||
}),
|
||||
|
||||
banUser: protectedProcedure
|
||||
.input(
|
||||
z.object({
|
||||
ownerId: z.string().min(1),
|
||||
reason: z.string().max(500).optional(),
|
||||
expiresAt: z.string().datetime().optional(),
|
||||
})
|
||||
)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const callerRole = await assertAdmin(ctx.prisma, ctx.userId, AdminRoleType.MODERATOR);
|
||||
if (input.ownerId === ctx.userId)
|
||||
throw new TRPCError({ code: "BAD_REQUEST", message: "Cannot ban yourself." });
|
||||
await assertCanModerate(ctx.prisma, callerRole, input.ownerId);
|
||||
await ctx.prisma.$transaction([
|
||||
ctx.prisma.userBan.upsert({
|
||||
where: { ownerId: input.ownerId },
|
||||
create: {
|
||||
ownerId: input.ownerId,
|
||||
reason: input.reason ?? null,
|
||||
bannedBy: ctx.userId,
|
||||
expiresAt: input.expiresAt ? new Date(input.expiresAt) : null,
|
||||
},
|
||||
update: {
|
||||
reason: input.reason ?? null,
|
||||
bannedBy: ctx.userId,
|
||||
bannedAt: new Date(),
|
||||
expiresAt: input.expiresAt ? new Date(input.expiresAt) : null,
|
||||
},
|
||||
}),
|
||||
modLog(ctx.prisma, ctx, callerRole, {
|
||||
action: "BAN_USER",
|
||||
targetType: "USER",
|
||||
targetId: input.ownerId,
|
||||
reason: input.reason,
|
||||
}),
|
||||
]);
|
||||
return { success: true };
|
||||
}),
|
||||
|
||||
unbanUser: protectedProcedure
|
||||
.input(z.object({ ownerId: z.string().min(1) }))
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const callerRole = await assertAdmin(ctx.prisma, ctx.userId, AdminRoleType.MODERATOR);
|
||||
await ctx.prisma
|
||||
.$transaction([
|
||||
ctx.prisma.userBan.delete({ where: { ownerId: input.ownerId } }),
|
||||
modLog(ctx.prisma, ctx, callerRole, { action: "UNBAN_USER", targetType: "USER", targetId: input.ownerId }),
|
||||
])
|
||||
.catch(rethrowNotFound);
|
||||
return { success: true };
|
||||
}),
|
||||
|
||||
shadowbanOwner: protectedProcedure
|
||||
.input(z.object({ ownerId: z.string().min(1), reason: z.string().min(1).max(500) }))
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const callerRole = await assertAdmin(ctx.prisma, ctx.userId, AdminRoleType.MODERATOR);
|
||||
if (input.ownerId === ctx.userId)
|
||||
throw new TRPCError({ code: "BAD_REQUEST", message: "Cannot shadowban yourself." });
|
||||
await assertCanModerate(ctx.prisma, callerRole, input.ownerId);
|
||||
await ctx.prisma.$transaction([
|
||||
ctx.prisma.shadowban.upsert({
|
||||
where: { ownerId: input.ownerId },
|
||||
create: { ownerId: input.ownerId, reason: input.reason, shadowbannedBy: ctx.userId },
|
||||
update: { reason: input.reason, shadowbannedBy: ctx.userId, shadowbannedAt: new Date() },
|
||||
}),
|
||||
modLog(ctx.prisma, ctx, callerRole, {
|
||||
action: "SHADOWBAN_USER",
|
||||
targetType: "USER",
|
||||
targetId: input.ownerId,
|
||||
reason: input.reason,
|
||||
}),
|
||||
]);
|
||||
return { success: true };
|
||||
}),
|
||||
|
||||
removeShadowban: protectedProcedure
|
||||
.input(z.object({ ownerId: z.string().min(1) }))
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const callerRole = await assertAdmin(ctx.prisma, ctx.userId, AdminRoleType.MODERATOR);
|
||||
await ctx.prisma
|
||||
.$transaction([
|
||||
ctx.prisma.shadowban.delete({ where: { ownerId: input.ownerId } }),
|
||||
modLog(ctx.prisma, ctx, callerRole, {
|
||||
action: "UNSHADOWBAN_USER",
|
||||
targetType: "USER",
|
||||
targetId: input.ownerId,
|
||||
}),
|
||||
])
|
||||
.catch(rethrowNotFound);
|
||||
return { success: true };
|
||||
}),
|
||||
|
||||
// ─── Warnings (append-only, no delete/edit — Gitea #10 permission matrix) ────
|
||||
listWarnings: protectedProcedure
|
||||
.input(z.object({ ownerId: z.string().min(1) }))
|
||||
.query(async ({ ctx, input }) => {
|
||||
await assertAdmin(ctx.prisma, ctx.userId, AdminRoleType.MODERATOR);
|
||||
return ctx.prisma.warning.findMany({
|
||||
where: { ownerId: input.ownerId },
|
||||
orderBy: { createdAt: "desc" },
|
||||
});
|
||||
}),
|
||||
|
||||
issueWarning: protectedProcedure
|
||||
.input(z.object({ ownerId: z.string().min(1), reason: z.string().min(1).max(500) }))
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const callerRole = await assertAdmin(ctx.prisma, ctx.userId, AdminRoleType.MODERATOR);
|
||||
await assertCanModerate(ctx.prisma, callerRole, input.ownerId);
|
||||
const [warning] = await ctx.prisma.$transaction([
|
||||
ctx.prisma.warning.create({
|
||||
data: { ownerId: input.ownerId, reason: input.reason, issuedBy: ctx.userId },
|
||||
}),
|
||||
modLog(ctx.prisma, ctx, callerRole, {
|
||||
action: "WARN_USER",
|
||||
targetType: "USER",
|
||||
targetId: input.ownerId,
|
||||
reason: input.reason,
|
||||
}),
|
||||
]);
|
||||
return warning;
|
||||
}),
|
||||
|
||||
// ─── Admin-triggered GDPR Art. 17 erasure ("right to be forgotten") ──────────
|
||||
// Reuses the same deleteOwnerAccount() the self-service /api/account/delete
|
||||
// route calls, so both paths stay in sync. `confirmation` must equal the
|
||||
// target ownerId verbatim — mirrors the pet-name-confirmation friction step
|
||||
// on the self-service flow, adapted since an admin acting on someone else's
|
||||
// account can't "prove" they know a pet name the way the owner can.
|
||||
deleteUserAccount: protectedProcedure
|
||||
.input(z.object({ ownerId: z.string().min(1), confirmation: z.string().min(1) }))
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const callerRole = await assertAdmin(ctx.prisma, ctx.userId, AdminRoleType.SUPER_ADMIN);
|
||||
if (input.ownerId === ctx.userId) {
|
||||
throw new TRPCError({ code: "BAD_REQUEST", message: "Cannot delete your own account here." });
|
||||
}
|
||||
if (input.confirmation !== input.ownerId) {
|
||||
throw new TRPCError({ code: "BAD_REQUEST", message: "Confirmation does not match." });
|
||||
}
|
||||
await assertCanModerate(ctx.prisma, callerRole, input.ownerId);
|
||||
|
||||
await deleteOwnerAccount(ctx.prisma, input.ownerId);
|
||||
|
||||
// Written after deletion succeeds — targetId/moderatorId have no FK to
|
||||
// Owner, so the now-deleted account doesn't block this insert.
|
||||
await modLog(ctx.prisma, ctx, callerRole, {
|
||||
action: "DELETE_ACCOUNT",
|
||||
targetType: "USER",
|
||||
targetId: input.ownerId,
|
||||
});
|
||||
|
||||
return { success: true };
|
||||
}),
|
||||
|
||||
// ─── GDPR Art. 15 data export (Gitea #6, Plan B + pawfeed.org token follow-up) ─
|
||||
// Aggregates everything held about an Owner (gdpr-export.ts), uploads it as
|
||||
// JSON to a private Supabase Storage bucket, and emails a 7-day download
|
||||
// link. The link points at /api/gdpr-export/[token] on pawfeed.org, backed
|
||||
// by a bespoke DataExportToken row — deliberately NOT Supabase's native
|
||||
// signed URL, so the storage backend never appears in the URL the user
|
||||
// sees (see Gitea #6 follow-up comment). Synchronous: acceptable for now,
|
||||
// but a heavy account (many posts/messages) could make this request slow —
|
||||
// flagged in the Gitea #6 research note as a scaling risk for later.
|
||||
exportUserData: protectedProcedure
|
||||
.input(z.object({ ownerId: z.string().min(1) }))
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const callerRole = await assertAdmin(ctx.prisma, ctx.userId);
|
||||
|
||||
const exportData = await buildDataExport(ctx.prisma, input.ownerId);
|
||||
if (!exportData) throw new TRPCError({ code: "NOT_FOUND" });
|
||||
|
||||
const email = exportData.account.clerkProfile?.email;
|
||||
if (!email) {
|
||||
throw new TRPCError({
|
||||
code: "PRECONDITION_FAILED",
|
||||
message: "No email on file for this owner (Clerk profile missing or has no email).",
|
||||
});
|
||||
}
|
||||
|
||||
const key = `${input.ownerId}/${Date.now()}.json`;
|
||||
await uploadExport(key, JSON.stringify(exportData, null, 2));
|
||||
|
||||
const exportToken = await ctx.prisma.dataExportToken.create({
|
||||
data: {
|
||||
ownerId: input.ownerId,
|
||||
token: randomUUID().replace(/-/g, ""),
|
||||
storageKey: key,
|
||||
expiresAt: new Date(Date.now() + DATA_EXPORT_TOKEN_TTL_MS),
|
||||
},
|
||||
});
|
||||
const downloadUrl = `${process.env.NEXT_PUBLIC_APP_URL}/api/gdpr-export/${exportToken.token}`;
|
||||
const firstName = exportData.account.clerkProfile?.firstName ?? null;
|
||||
|
||||
await sendMail({
|
||||
to: email,
|
||||
subject: "Deine Daten bei PawFeed — Auskunft gemäß Art. 15 DSGVO",
|
||||
text: `${buildGreeting(firstName)}\n\nanbei der Link zu deiner Datenauskunft gemäß Art. 15 DSGVO. Der Link ist 7 Tage gültig:\n\n${downloadUrl}\n\nBei Fragen antworte einfach auf diese E-Mail.\n\nDein PawFeed-Team`,
|
||||
html: renderBrandedMailHtml({
|
||||
previewText: "Dein Datenauskunft-Link gemäß Art. 15 DSGVO ist bereit.",
|
||||
greetingName: firstName,
|
||||
bodyHtml: `<p style="margin: 0 0 16px;">anbei der Link zu deiner Datenauskunft gemäß Art. 15 DSGVO. Der Link ist <strong>7 Tage</strong> gültig.</p><p style="margin: 0;">Bei Fragen antworte einfach auf diese E-Mail.</p>`,
|
||||
ctaLabel: "Daten herunterladen",
|
||||
ctaUrl: downloadUrl,
|
||||
}),
|
||||
});
|
||||
|
||||
await modLog(ctx.prisma, ctx, callerRole, { action: "DATA_EXPORT", targetType: "USER", targetId: input.ownerId });
|
||||
|
||||
return { success: true, sentTo: email };
|
||||
}),
|
||||
};
|
||||
@@ -0,0 +1,168 @@
|
||||
import "server-only";
|
||||
import { z } from "zod";
|
||||
import { TRPCError } from "@trpc/server";
|
||||
import { AdminRoleType } from "@prisma/client";
|
||||
import { protectedProcedure } from "@/trpc/init";
|
||||
import { modLog } from "@/lib/admin/mod-log";
|
||||
import { petIdentitySelect } from "@/repositories/pet-repository";
|
||||
import { sendTeamMessage } from "@/lib/team-pet";
|
||||
import { germanNameSelect, withGermanName } from "@/lib/admin/taxonomy-name";
|
||||
import { assertAdmin } from "@/trpc/routers/admin-procedures/guards";
|
||||
|
||||
/** Verifizierungs-Haken und Verifizierungsanträge. Teil von `trpc.admin.*` (admin.ts). */
|
||||
|
||||
export const adminVerificationProcedures = {
|
||||
// ─── Verification checkmark (lives on Pet, not Owner — pets are the social
|
||||
// identity here, see CLAUDE.md) ────────────────────────────────────────────
|
||||
setPetVerified: protectedProcedure
|
||||
.input(z.object({ petId: z.string().min(1), isVerified: z.boolean() }))
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const callerRole = await assertAdmin(ctx.prisma, ctx.userId, AdminRoleType.MODERATOR);
|
||||
const [pet] = await ctx.prisma.$transaction([
|
||||
ctx.prisma.pet.update({
|
||||
where: { id: input.petId },
|
||||
data: { isVerified: input.isVerified },
|
||||
}),
|
||||
modLog(ctx.prisma, ctx, callerRole, {
|
||||
action: input.isVerified ? "VERIFY_PET" : "UNVERIFY_PET",
|
||||
targetType: "PET",
|
||||
targetId: input.petId,
|
||||
}),
|
||||
]);
|
||||
return pet;
|
||||
}),
|
||||
|
||||
// ─── Self-service verification requests (Gitea #10) ──────────────────────────
|
||||
listVerificationRequests: protectedProcedure
|
||||
.input(
|
||||
z.object({
|
||||
status: z.enum(["PENDING", "APPROVED", "REJECTED"]).default("PENDING"),
|
||||
cursor: z.string().nullish(),
|
||||
limit: z.number().min(1).max(50).default(20),
|
||||
})
|
||||
)
|
||||
.query(async ({ ctx, input }) => {
|
||||
await assertAdmin(ctx.prisma, ctx.userId, AdminRoleType.MODERATOR);
|
||||
// Full profile context pulled in here — pulled in so a moderator can
|
||||
// check the review checklist off the one card, no separate lookup on
|
||||
// the Users page needed (Gitea #10 follow-up).
|
||||
const requests = await ctx.prisma.verificationRequest.findMany({
|
||||
where: { status: input.status },
|
||||
include: {
|
||||
pet: {
|
||||
select: {
|
||||
...petIdentitySelect,
|
||||
isVerified: true,
|
||||
ownerId: true,
|
||||
bio: true,
|
||||
createdAt: true,
|
||||
species: { select: germanNameSelect },
|
||||
breed: { select: germanNameSelect },
|
||||
_count: { select: { posts: true, followers: true } },
|
||||
owner: {
|
||||
select: {
|
||||
ban: { select: { reason: true, expiresAt: true } },
|
||||
_count: { select: { warnings: true } },
|
||||
referralPerks: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
orderBy: { createdAt: "desc" },
|
||||
take: input.limit + 1,
|
||||
...(input.cursor ? { skip: 1, cursor: { id: input.cursor } } : {}),
|
||||
});
|
||||
const hasNext = requests.length > input.limit;
|
||||
const items = hasNext ? requests.slice(0, input.limit) : requests;
|
||||
// Empfehlungsprogramm-Vorteil VERIFICATION_PRIORITY: innerhalb der geladenen Seite nach oben sortieren.
|
||||
// Der Cursor bleibt die letzte ID der ursprünglichen Reihenfolge, damit die Paginierung stimmt.
|
||||
const hasPriority = (r: (typeof items)[number]) => r.pet.owner.referralPerks.includes("VERIFICATION_PRIORITY");
|
||||
const sorted = [...items.filter(hasPriority), ...items.filter((r) => !hasPriority(r))].map((r) => ({
|
||||
...r,
|
||||
pet: { ...r.pet, species: withGermanName(r.pet.species), breed: r.pet.breed ? withGermanName(r.pet.breed) : null },
|
||||
}));
|
||||
return { requests: sorted, nextCursor: hasNext ? items[items.length - 1]!.id : null };
|
||||
}),
|
||||
|
||||
// The checklist IS the decision — there's no separate approve/reject
|
||||
// action. All four true → APPROVED + Pet.isVerified flips on. Any false →
|
||||
// REJECTED with an itemized note built from the unmet items, so a
|
||||
// moderator can't approve on vibes and can't reject without saying why.
|
||||
reviewVerificationRequest: protectedProcedure
|
||||
.input(
|
||||
z.object({
|
||||
requestId: z.string().min(1),
|
||||
meetsAuthenticity: z.boolean(),
|
||||
meetsCompleteProfile: z.boolean(),
|
||||
meetsGoodStanding: z.boolean(),
|
||||
meetsEstablishedPresence: z.boolean(),
|
||||
note: z.string().max(500).optional(),
|
||||
})
|
||||
)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const callerRole = await assertAdmin(ctx.prisma, ctx.userId, AdminRoleType.MODERATOR);
|
||||
|
||||
const request = await ctx.prisma.verificationRequest.findUnique({
|
||||
where: { id: input.requestId },
|
||||
select: { petId: true, status: true },
|
||||
});
|
||||
if (!request) throw new TRPCError({ code: "NOT_FOUND" });
|
||||
if (request.status !== "PENDING") {
|
||||
throw new TRPCError({ code: "BAD_REQUEST", message: "This request was already reviewed." });
|
||||
}
|
||||
|
||||
const allMet =
|
||||
input.meetsAuthenticity &&
|
||||
input.meetsCompleteProfile &&
|
||||
input.meetsGoodStanding &&
|
||||
input.meetsEstablishedPresence;
|
||||
|
||||
const missing: string[] = [];
|
||||
if (!input.meetsAuthenticity) missing.push("Echtheits-/Verwechslungsrisiko nicht erkennbar");
|
||||
if (!input.meetsCompleteProfile) missing.push("Profil unvollständig");
|
||||
if (!input.meetsGoodStanding) missing.push("Kein sauberer Stand (Ban/offene Verwarnung)");
|
||||
if (!input.meetsEstablishedPresence) missing.push("Keine etablierte Präsenz");
|
||||
|
||||
const reviewNote = allMet
|
||||
? (input.note ?? null)
|
||||
: [`Fehlende Kriterien: ${missing.join(", ")}`, input.note].filter(Boolean).join(" — ");
|
||||
|
||||
await ctx.prisma.$transaction([
|
||||
ctx.prisma.verificationRequest.update({
|
||||
where: { id: input.requestId },
|
||||
data: {
|
||||
status: allMet ? "APPROVED" : "REJECTED",
|
||||
meetsAuthenticity: input.meetsAuthenticity,
|
||||
meetsCompleteProfile: input.meetsCompleteProfile,
|
||||
meetsGoodStanding: input.meetsGoodStanding,
|
||||
meetsEstablishedPresence: input.meetsEstablishedPresence,
|
||||
reviewNote,
|
||||
reviewedBy: ctx.userId,
|
||||
reviewedAt: new Date(),
|
||||
},
|
||||
}),
|
||||
...(allMet
|
||||
? [ctx.prisma.pet.update({ where: { id: request.petId }, data: { isVerified: true } })]
|
||||
: []),
|
||||
modLog(ctx.prisma, ctx, callerRole, {
|
||||
action: allMet ? "APPROVE_VERIFICATION_REQUEST" : "REJECT_VERIFICATION_REQUEST",
|
||||
targetType: "PET",
|
||||
targetId: request.petId,
|
||||
reason: reviewNote,
|
||||
}),
|
||||
]);
|
||||
|
||||
// Best-effort — the review itself already succeeded and is persisted;
|
||||
// a failed notification must not roll that back or fail the request.
|
||||
await sendTeamMessage(
|
||||
ctx.prisma,
|
||||
request.petId,
|
||||
allMet
|
||||
? "Gute Nachrichten — dein Verifizierungsantrag wurde genehmigt! Der Verifizierungs-Haken ist jetzt auf deinem Profil sichtbar."
|
||||
: `Dein Verifizierungsantrag wurde leider abgelehnt.\n\n${reviewNote}\n\nDu kannst jederzeit erneut einen Antrag stellen, sobald die fehlenden Punkte erfüllt sind.`
|
||||
).catch((err) => console.error("[admin] verification decision notification failed", err));
|
||||
|
||||
return { success: true, approved: allMet };
|
||||
}),
|
||||
};
|
||||
+27
-1807
File diff suppressed because it is too large.
Load diff
@@ -5,6 +5,39 @@ import { assertPetOwnership } from "@/lib/assert-pet-ownership";
|
||||
import { petIdentitySelect } from "@/repositories/pet-repository";
|
||||
|
||||
export const adsRouter = router({
|
||||
// Species/breed targeting (Gitea #9): species is the primary filter — empty
|
||||
// means "all species", a non-empty match required otherwise. breeds, if set,
|
||||
// narrows WITHIN an already-matched species (e.g. "Cats" + "Siamese" shows
|
||||
// only to Siamese cats, while "Cats" alone with no breeds shows to any cat).
|
||||
// A pet with no breed set never matches a breed-narrowed ad.
|
||||
// Für den Feed: welche Werbung dieses Tier sieht (früher admin.getActiveAds, keine Admin-Prozedur).
|
||||
getActiveAds: protectedProcedure
|
||||
.input(z.object({ petId: z.string().min(1) }))
|
||||
.query(async ({ ctx, input }) => {
|
||||
const pet = await ctx.prisma.pet.findUnique({
|
||||
where: { id: input.petId },
|
||||
select: { speciesId: true, breedId: true },
|
||||
});
|
||||
if (!pet) return [];
|
||||
|
||||
const now = new Date();
|
||||
const ads = await ctx.prisma.advertisement.findMany({
|
||||
where: {
|
||||
isActive: true,
|
||||
OR: [{ startDate: null }, { startDate: { lte: now } }],
|
||||
AND: [{ OR: [{ endDate: null }, { endDate: { gte: now } }] }],
|
||||
},
|
||||
orderBy: { createdAt: "desc" },
|
||||
});
|
||||
|
||||
return ads.filter((ad) => {
|
||||
if (ad.species.length === 0) return true;
|
||||
if (!ad.species.includes(pet.speciesId)) return false;
|
||||
if (ad.breeds.length === 0) return true;
|
||||
return !!pet.breedId && ad.breeds.includes(pet.breedId);
|
||||
});
|
||||
}),
|
||||
|
||||
// Returns view/reaction/comment/repost counts + whether the given pet has interacted
|
||||
getFeedData: protectedProcedure
|
||||
.input(z.object({ adId: z.string().min(1), petId: z.string().min(1) }))
|
||||
|
||||
Reference in new issue
Block a user