forked from administration/panel
feat: case system
parent
e9b623f60d
commit
eb0bd7a7c9
|
@ -0,0 +1,41 @@
|
|||
import { ReportCard } from "@/components/cards/ReportCard";
|
||||
import { CardLink } from "@/components/common/CardLink";
|
||||
import { NavigationToolbar } from "@/components/common/NavigationToolbar";
|
||||
import { CaseActions } from "@/components/pages/inspector/CaseActions";
|
||||
import { fetchCaseById, fetchReportsByCase } from "@/lib/db";
|
||||
import { PizzaIcon } from "lucide-react";
|
||||
import { notFound } from "next/navigation";
|
||||
|
||||
export default async function Reports({ params }: { params: { id: string } }) {
|
||||
const Case = await fetchCaseById(params.id);
|
||||
if (!Case) return notFound();
|
||||
|
||||
const reports = await fetchReportsByCase(params.id);
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-2">
|
||||
<NavigationToolbar>Viewing Case</NavigationToolbar>
|
||||
<CaseActions Case={Case} />
|
||||
|
||||
<div className="flex flex-col gap-2">
|
||||
<h1 className="text-2xl">Reports</h1>
|
||||
{reports.length ? (
|
||||
reports.map((report) => (
|
||||
<CardLink key={report._id} href={`/panel/reports/${report._id}`}>
|
||||
<ReportCard report={report} />
|
||||
</CardLink>
|
||||
))
|
||||
) : (
|
||||
<>
|
||||
<h2 className="mt-8 flex justify-center">
|
||||
<PizzaIcon className="text-gray-400" />
|
||||
</h2>
|
||||
<h3 className="text-xs text-center pb-2 text-gray-400">
|
||||
No reports added yet.
|
||||
</h3>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
|
@ -0,0 +1,37 @@
|
|||
import { CaseCard } from "@/components/cards/CaseCard";
|
||||
import { CardLink } from "@/components/common/CardLink";
|
||||
import { CreateCase } from "@/components/common/CreateCase";
|
||||
import { fetchOpenCases } from "@/lib/db";
|
||||
import { PizzaIcon } from "lucide-react";
|
||||
|
||||
export default async function Reports() {
|
||||
const cases = (await fetchOpenCases()).reverse();
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-8">
|
||||
<div className="flex flex-col gap-2">
|
||||
<div className="flex flex-row gap-2 items-center">
|
||||
<CreateCase />
|
||||
<h1 className="text-2xl">Open Cases</h1>
|
||||
</div>
|
||||
|
||||
{cases.length ? (
|
||||
cases.map((entry) => (
|
||||
<CardLink key={entry._id} href={`/panel/cases/${entry._id}`}>
|
||||
<CaseCard entry={entry} />
|
||||
</CardLink>
|
||||
))
|
||||
) : (
|
||||
<>
|
||||
<h2 className="mt-8 flex justify-center">
|
||||
<PizzaIcon className="text-gray-400" />
|
||||
</h2>
|
||||
<h3 className="text-xs text-center pb-2 text-gray-400">
|
||||
No cases currently open.
|
||||
</h3>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
|
@ -13,12 +13,15 @@ export default async function Reports() {
|
|||
const byCategory: Record<string, Report[]> = {
|
||||
Urgent: [],
|
||||
All: [],
|
||||
AssignedToCase: [],
|
||||
};
|
||||
const keyOrder = ["Urgent", "All"];
|
||||
|
||||
const countsByAuthor: Record<string, number> = {};
|
||||
for (const report of reports) {
|
||||
if (report.content.report_reason.includes("Illegal")) {
|
||||
if (report.case_id) {
|
||||
byCategory.AssignedToCase.push(report);
|
||||
} else if (report.content.report_reason.includes("Illegal")) {
|
||||
byCategory.Urgent.push(report);
|
||||
} else {
|
||||
countsByAuthor[report.author_id] =
|
||||
|
@ -50,21 +53,23 @@ export default async function Reports() {
|
|||
<div className="flex flex-col gap-8">
|
||||
{/*<Input placeholder="Search for reports..." disabled />*/}
|
||||
{reports.length ? (
|
||||
keyOrder.map((key) => {
|
||||
return (
|
||||
<div key={key} className="flex flex-col gap-2">
|
||||
<h1 className="text-2xl">{authorNames[key] ?? key}</h1>
|
||||
{byCategory[key].map((report) => (
|
||||
<CardLink
|
||||
key={report._id}
|
||||
href={`/panel/reports/${report._id}`}
|
||||
>
|
||||
<ReportCard report={report} />
|
||||
</CardLink>
|
||||
))}{" "}
|
||||
</div>
|
||||
);
|
||||
})
|
||||
keyOrder
|
||||
.filter((key) => byCategory[key].length)
|
||||
.map((key) => {
|
||||
return (
|
||||
<div key={key} className="flex flex-col gap-2">
|
||||
<h1 className="text-2xl">{authorNames[key] ?? key}</h1>
|
||||
{byCategory[key].map((report) => (
|
||||
<CardLink
|
||||
key={report._id}
|
||||
href={`/panel/reports/${report._id}`}
|
||||
>
|
||||
<ReportCard report={report} />
|
||||
</CardLink>
|
||||
))}{" "}
|
||||
</div>
|
||||
);
|
||||
})
|
||||
) : (
|
||||
<>
|
||||
<h2 className="mt-8 flex justify-center">
|
||||
|
@ -75,6 +80,20 @@ export default async function Reports() {
|
|||
</h3>
|
||||
</>
|
||||
)}
|
||||
{byCategory["AssignedToCase"].length && (
|
||||
<details>
|
||||
<summary>
|
||||
<h1 className="text-xl inline">Reports assigned to cases</h1>
|
||||
</summary>
|
||||
<div className="flex flex-col gap-2">
|
||||
{byCategory["AssignedToCase"].map((report) => (
|
||||
<CardLink key={report._id} href={`/panel/reports/${report._id}`}>
|
||||
<ReportCard report={report} />
|
||||
</CardLink>
|
||||
))}
|
||||
</div>
|
||||
</details>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
|
@ -0,0 +1,32 @@
|
|||
import { Report } from "revolt-api";
|
||||
import { Card, CardDescription, CardHeader, CardTitle } from "../ui/card";
|
||||
import { Badge } from "../ui/badge";
|
||||
import dayjs from "dayjs";
|
||||
import { decodeTime } from "ulid";
|
||||
|
||||
import relativeTime from "dayjs/plugin/relativeTime";
|
||||
import { CaseDocument } from "@/lib/db";
|
||||
dayjs.extend(relativeTime);
|
||||
|
||||
export function CaseCard({ entry: entry }: { entry: CaseDocument }) {
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle
|
||||
className={`overflow-ellipsis whitespace-nowrap overflow-x-clip ${
|
||||
entry.status !== "Open" ? "text-gray-500" : ""
|
||||
}`}
|
||||
>
|
||||
{entry.title || "No reason specified"}
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
{entry._id.toString().substring(20, 26)} ·{" "}
|
||||
{dayjs(decodeTime(entry._id)).fromNow()} · {entry.author}{" "}
|
||||
{entry.status !== "Open" && entry.closed_at && (
|
||||
<>· Closed {dayjs(entry.closed_at).fromNow()}</>
|
||||
)}
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
</Card>
|
||||
);
|
||||
}
|
|
@ -0,0 +1,54 @@
|
|||
"use client";
|
||||
|
||||
import { Plus } from "lucide-react";
|
||||
import { Button } from "../ui/button";
|
||||
import { Popover, PopoverContent, PopoverTrigger } from "../ui/popover";
|
||||
import { Label } from "../ui/label";
|
||||
import { Input } from "../ui/input";
|
||||
import { useState } from "react";
|
||||
import { createCase } from "@/lib/db";
|
||||
import { useRouter } from "next/navigation";
|
||||
|
||||
export function CreateCase() {
|
||||
const [title, setTitle] = useState("");
|
||||
const router = useRouter();
|
||||
|
||||
return (
|
||||
<Popover>
|
||||
<PopoverTrigger asChild>
|
||||
<Button variant="outline" size="icon">
|
||||
<Plus className="h-4 w-4" />
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent className="w-80">
|
||||
<div className="grid gap-4">
|
||||
<div className="space-y-2">
|
||||
<h4 className="font-medium leading-none">Create Case</h4>
|
||||
</div>
|
||||
<div className="grid gap-2">
|
||||
<div className="grid grid-cols-3 items-center gap-4">
|
||||
<Label htmlFor="description">Title</Label>
|
||||
<Input
|
||||
id="description"
|
||||
className="col-span-2 h-8"
|
||||
value={title}
|
||||
onChange={(e) => setTitle(e.currentTarget.value)}
|
||||
/>
|
||||
</div>
|
||||
<Button
|
||||
variant="secondary"
|
||||
onClick={() => {
|
||||
if (!title) return;
|
||||
createCase(title).then((id) =>
|
||||
router.push(`/panel/cases/${id}`)
|
||||
);
|
||||
}}
|
||||
>
|
||||
Create
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
);
|
||||
}
|
|
@ -11,6 +11,7 @@ import {
|
|||
Siren,
|
||||
Sparkles,
|
||||
TrendingUp,
|
||||
BookCopy,
|
||||
} from "lucide-react";
|
||||
|
||||
export function NavigationLinks() {
|
||||
|
@ -34,6 +35,12 @@ export function NavigationLinks() {
|
|||
>
|
||||
<Siren className="h-4 w-4" />
|
||||
</Link>
|
||||
<Link
|
||||
className={buttonVariants({ variant: "outline", size: "icon" })}
|
||||
href="/panel/cases"
|
||||
>
|
||||
<BookCopy className="h-4 w-4" />
|
||||
</Link>
|
||||
<Link
|
||||
className={buttonVariants({ variant: "outline", size: "icon" })}
|
||||
href="/panel/inspect"
|
||||
|
|
|
@ -16,7 +16,7 @@ export function NavigationToolbar({ children }: { children: string }) {
|
|||
<Button variant="outline" size="icon" onClick={() => router.back()}>
|
||||
<ArrowLeft className="h-4 w-4" />
|
||||
</Button>
|
||||
<Popover>
|
||||
{/* <Popover>
|
||||
<PopoverTrigger asChild>
|
||||
<Button variant="outline" size="icon">
|
||||
<Star
|
||||
|
@ -49,7 +49,7 @@ export function NavigationToolbar({ children }: { children: string }) {
|
|||
</div>
|
||||
</div>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
</Popover> */}
|
||||
<h2 className="text-2xl">{children}</h2>
|
||||
</div>
|
||||
);
|
||||
|
|
|
@ -0,0 +1,95 @@
|
|||
"use client";
|
||||
|
||||
import { Textarea } from "../../ui/textarea";
|
||||
import { Button } from "../../ui/button";
|
||||
import { useState } from "react";
|
||||
import { useToast } from "../../ui/use-toast";
|
||||
import { CaseDocument } from "@/lib/db";
|
||||
import { CaseCard } from "@/components/cards/CaseCard";
|
||||
import { closeCase, reopenCase, updateCaseNotes } from "@/lib/actions";
|
||||
|
||||
export function CaseActions({ Case }: { Case: CaseDocument }) {
|
||||
const { toast } = useToast();
|
||||
const [caseDraft, setDraft] = useState(Case);
|
||||
|
||||
return (
|
||||
<>
|
||||
<CaseCard entry={Case} />
|
||||
|
||||
<Textarea
|
||||
cols={8}
|
||||
placeholder="Enter notes here... (save on unfocus)"
|
||||
className="!min-h-0 !h-[76px]"
|
||||
defaultValue={Case.notes}
|
||||
onBlur={async (e) => {
|
||||
const notes = e.currentTarget.value;
|
||||
if (notes === caseDraft.notes ?? "") return;
|
||||
|
||||
try {
|
||||
await updateCaseNotes(Case._id, notes);
|
||||
setDraft((c) => ({ ...c, notes }));
|
||||
toast({
|
||||
title: "Updated report notes",
|
||||
});
|
||||
} catch (err) {
|
||||
toast({
|
||||
title: "Failed to update report notes",
|
||||
description: String(err),
|
||||
variant: "destructive",
|
||||
});
|
||||
}
|
||||
}}
|
||||
/>
|
||||
|
||||
<div className="flex gap-2">
|
||||
{caseDraft.status === "Open" ? (
|
||||
<>
|
||||
<Button
|
||||
className="flex-1 bg-green-400 hover:bg-green-300"
|
||||
onClick={async () => {
|
||||
try {
|
||||
const $set = await closeCase(Case._id);
|
||||
setDraft((c) => ({ ...c, ...$set }));
|
||||
toast({
|
||||
title: "Closed case",
|
||||
});
|
||||
} catch (err) {
|
||||
toast({
|
||||
title: "Failed to close case",
|
||||
description: String(err),
|
||||
variant: "destructive",
|
||||
});
|
||||
}
|
||||
}}
|
||||
>
|
||||
Close Case
|
||||
</Button>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Button
|
||||
className="flex-1"
|
||||
onClick={async () => {
|
||||
try {
|
||||
const $set = await reopenCase(Case._id);
|
||||
setDraft((c) => ({ ...c, ...$set }));
|
||||
toast({
|
||||
title: "Opened case again",
|
||||
});
|
||||
} catch (err) {
|
||||
toast({
|
||||
title: "Failed to re-open case",
|
||||
description: String(err),
|
||||
variant: "destructive",
|
||||
});
|
||||
}
|
||||
}}
|
||||
>
|
||||
Re-open Case
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
|
@ -14,6 +14,7 @@ import {
|
|||
import { useState } from "react";
|
||||
import { useToast } from "../../ui/use-toast";
|
||||
import {
|
||||
assignReportToCase,
|
||||
rejectReport,
|
||||
reopenReport,
|
||||
resolveReport,
|
||||
|
@ -32,6 +33,10 @@ import {
|
|||
AlertDialogTrigger,
|
||||
} from "../../ui/alert-dialog";
|
||||
import { ReportCard } from "../../cards/ReportCard";
|
||||
import { Popover } from "@radix-ui/react-popover";
|
||||
import { PopoverContent, PopoverTrigger } from "@/components/ui/popover";
|
||||
import { CaseDocument, ReportDocument, fetchOpenCases } from "@/lib/db";
|
||||
import { CaseCard } from "@/components/cards/CaseCard";
|
||||
|
||||
const template: Record<string, (ref: string) => string> = {
|
||||
resolved: (ref) =>
|
||||
|
@ -54,11 +59,12 @@ export function ReportActions({
|
|||
report,
|
||||
reference,
|
||||
}: {
|
||||
report: Report;
|
||||
report: ReportDocument;
|
||||
reference: string;
|
||||
}) {
|
||||
const { toast } = useToast();
|
||||
const [reportDraft, setDraft] = useState(report);
|
||||
const [availableCases, setAvailableCases] = useState<CaseDocument[]>([]);
|
||||
|
||||
function rejectHandler(reason: string) {
|
||||
return async () => {
|
||||
|
@ -83,6 +89,7 @@ export function ReportActions({
|
|||
<ReportCard report={reportDraft} />
|
||||
|
||||
<Textarea
|
||||
cols={8}
|
||||
placeholder="Enter notes here... (save on unfocus)"
|
||||
className="!min-h-0 !h-[76px]"
|
||||
defaultValue={report.notes}
|
||||
|
@ -106,6 +113,74 @@ export function ReportActions({
|
|||
}}
|
||||
/>
|
||||
|
||||
{reportDraft.case_id ? (
|
||||
<Button
|
||||
variant="destructive"
|
||||
onClick={async () => {
|
||||
try {
|
||||
const $set = await assignReportToCase(report._id);
|
||||
setDraft((report) => ({ ...report, ...$set }));
|
||||
toast({
|
||||
title: "Removed report from case",
|
||||
});
|
||||
} catch (err) {
|
||||
toast({
|
||||
title: "Failed to resolve report",
|
||||
description: String(err),
|
||||
variant: "destructive",
|
||||
});
|
||||
}
|
||||
}}
|
||||
>
|
||||
Remove from case
|
||||
</Button>
|
||||
) : (
|
||||
<Popover>
|
||||
<PopoverTrigger asChild>
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => {
|
||||
fetchOpenCases().then(setAvailableCases);
|
||||
}}
|
||||
>
|
||||
Add to case
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent className="w-80">
|
||||
<div className="grid gap-4">
|
||||
<div className="space-y-2">
|
||||
<h4 className="font-medium leading-none">Open Cases</h4>
|
||||
{availableCases.map((entry) => (
|
||||
<a
|
||||
key={entry._id}
|
||||
onClick={async () => {
|
||||
try {
|
||||
const $set = await assignReportToCase(
|
||||
report._id,
|
||||
entry._id
|
||||
);
|
||||
setDraft((report) => ({ ...report, ...$set }));
|
||||
toast({
|
||||
title: "Assigned report to case",
|
||||
});
|
||||
} catch (err) {
|
||||
toast({
|
||||
title: "Failed to resolve report",
|
||||
description: String(err),
|
||||
variant: "destructive",
|
||||
});
|
||||
}
|
||||
}}
|
||||
>
|
||||
<CaseCard entry={entry} />
|
||||
</a>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
)}
|
||||
|
||||
<div className="flex gap-2">
|
||||
{reportDraft.status === "Created" ? (
|
||||
<>
|
||||
|
|
|
@ -3,15 +3,8 @@ import { SafetyNotes, insertAuditLog } from "./db";
|
|||
|
||||
type Permission =
|
||||
| `authifier${
|
||||
| ""
|
||||
| `/classification${
|
||||
| ""
|
||||
| "/fetch"
|
||||
| "/create"
|
||||
| "/update"
|
||||
| "/delete"
|
||||
}`
|
||||
}`
|
||||
| `/classification${"" | "/fetch" | "/create" | "/update" | "/delete"}`}`
|
||||
| "publish_message"
|
||||
| "chat_message"
|
||||
| `accounts${
|
||||
|
@ -31,19 +24,30 @@ type Permission =
|
|||
| `/create${"" | "/dm" | "/invites"}`
|
||||
| `/update${"" | "/invites"}`}`
|
||||
| `messages${"" | `/fetch${"" | "/by-id" | "/by-user"}`}`
|
||||
| `cases${
|
||||
| ""
|
||||
| "/create"
|
||||
| `/fetch${"" | "/by-id" | "/open"}`
|
||||
| `/update${"" | "/close" | "/reopen" | "/notes"}`}`
|
||||
| `reports${
|
||||
| ""
|
||||
| `/fetch${
|
||||
| ""
|
||||
| "/by-id"
|
||||
| "/open"
|
||||
| `/related${"" | "/by-content" | "/by-user" | "/against-user"}`
|
||||
| `/related${
|
||||
| ""
|
||||
| "/by-content"
|
||||
| "/by-user"
|
||||
| "/by-case"
|
||||
| "/against-user"}`
|
||||
| `/snapshots${"" | "/by-report" | "/by-user"}`}`
|
||||
| `/update${
|
||||
| ""
|
||||
| "/notes"
|
||||
| "/resolve"
|
||||
| "/reject"
|
||||
| "/case"
|
||||
| "/reopen"
|
||||
| `/bulk-close${"" | "/by-user"}`}`}`
|
||||
| `sessions${"" | `/fetch${"" | "/by-account-id"}`}`
|
||||
|
@ -103,6 +107,8 @@ const PermissionSets = {
|
|||
// View open reports
|
||||
"view-open-reports": [
|
||||
"users/fetch/by-id",
|
||||
"cases/fetch/open",
|
||||
"cases/fetch/by-id",
|
||||
"reports/fetch/open",
|
||||
"reports/fetch/by-id",
|
||||
"reports/fetch/related",
|
||||
|
@ -114,7 +120,12 @@ const PermissionSets = {
|
|||
"reports/update/notes",
|
||||
"reports/update/resolve",
|
||||
"reports/update/reject",
|
||||
"reports/update/case",
|
||||
"reports/update/reopen",
|
||||
"cases/create",
|
||||
"cases/update/notes",
|
||||
"cases/update/close",
|
||||
"cases/update/reopen",
|
||||
] as Permission[],
|
||||
|
||||
// Revolt Discover
|
||||
|
@ -212,9 +223,7 @@ const PermissionSets = {
|
|||
"safety_notes/update",
|
||||
] as Permission[],
|
||||
|
||||
"authifier": [
|
||||
"authifier/classification",
|
||||
] as Permission[],
|
||||
authifier: ["authifier/classification"] as Permission[],
|
||||
};
|
||||
|
||||
const Roles = {
|
||||
|
@ -287,5 +296,5 @@ export async function checkPermission(
|
|||
if (!(await hasPermissionFromSession(permission)))
|
||||
throw `Missing permission ${permission}`;
|
||||
|
||||
await insertAuditLog(permission, context, args);
|
||||
return await insertAuditLog(permission, context, args);
|
||||
}
|
||||
|
|
225
lib/actions.ts
225
lib/actions.ts
|
@ -4,8 +4,10 @@ import { readFile, readdir, writeFile } from "fs/promises";
|
|||
import { PLATFORM_MOD_ID, RESTRICT_ACCESS_LIST } from "./constants";
|
||||
import mongo, {
|
||||
Account,
|
||||
CaseDocument,
|
||||
ChannelInvite,
|
||||
EmailClassification,
|
||||
ReportDocument,
|
||||
createDM,
|
||||
fetchAccountById,
|
||||
findDM,
|
||||
|
@ -98,6 +100,48 @@ export async function updateReportNotes(reportId: string, notes: string) {
|
|||
);
|
||||
}
|
||||
|
||||
export async function updateCaseNotes(caseId: string, notes: string) {
|
||||
await checkPermission("cases/update/notes", caseId, { notes });
|
||||
|
||||
return await mongo()
|
||||
.db("revolt")
|
||||
.collection<CaseDocument>("safety_cases")
|
||||
.updateOne(
|
||||
{ _id: caseId },
|
||||
{
|
||||
$set: {
|
||||
notes,
|
||||
},
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
export async function assignReportToCase(reportId: string, caseId?: string) {
|
||||
await checkPermission("reports/update/case", reportId);
|
||||
|
||||
const $set = {
|
||||
case_id: caseId ?? null,
|
||||
} as ReportDocument;
|
||||
|
||||
await mongo()
|
||||
.db("revolt")
|
||||
.collection<ReportDocument>("safety_reports")
|
||||
.updateOne(
|
||||
{ _id: reportId },
|
||||
caseId
|
||||
? {
|
||||
$set,
|
||||
}
|
||||
: {
|
||||
$unset: {
|
||||
case_id: 1,
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
return $set;
|
||||
}
|
||||
|
||||
export async function resolveReport(reportId: string) {
|
||||
await checkPermission("reports/update/resolve", reportId);
|
||||
|
||||
|
@ -116,6 +160,24 @@ export async function resolveReport(reportId: string) {
|
|||
return $set;
|
||||
}
|
||||
|
||||
export async function closeCase(caseId: string) {
|
||||
await checkPermission("cases/update/close", caseId);
|
||||
|
||||
const $set = {
|
||||
status: "Closed",
|
||||
closed_at: new Date().toISOString(),
|
||||
} as CaseDocument;
|
||||
|
||||
await mongo().db("revolt").collection<CaseDocument>("safety_cases").updateOne(
|
||||
{ _id: caseId },
|
||||
{
|
||||
$set,
|
||||
}
|
||||
);
|
||||
|
||||
return $set;
|
||||
}
|
||||
|
||||
export async function rejectReport(reportId: string, reason: string) {
|
||||
await checkPermission("reports/update/reject", reportId, { reason });
|
||||
|
||||
|
@ -158,6 +220,23 @@ export async function reopenReport(reportId: string) {
|
|||
return $set;
|
||||
}
|
||||
|
||||
export async function reopenCase(caseId: string) {
|
||||
await checkPermission("cases/update/reopen", caseId);
|
||||
|
||||
const $set = {
|
||||
status: "Open",
|
||||
} as CaseDocument;
|
||||
|
||||
await mongo().db("revolt").collection<CaseDocument>("safety_cases").updateOne(
|
||||
{ _id: caseId },
|
||||
{
|
||||
$set,
|
||||
}
|
||||
);
|
||||
|
||||
return $set;
|
||||
}
|
||||
|
||||
export async function closeReportsByUser(userId: string) {
|
||||
await checkPermission("reports/update/bulk-close/by-user", userId);
|
||||
|
||||
|
@ -208,8 +287,8 @@ export async function deleteMFARecoveryCodes(userId: string) {
|
|||
$unset: {
|
||||
"mfa.recovery_codes": 1,
|
||||
},
|
||||
},
|
||||
)
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
export async function disableMFA(userId: string) {
|
||||
|
@ -225,8 +304,8 @@ export async function disableMFA(userId: string) {
|
|||
$unset: {
|
||||
"mfa.totp_token": 1,
|
||||
},
|
||||
},
|
||||
)
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
export async function changeAccountEmail(userId: string, email: string) {
|
||||
|
@ -287,9 +366,7 @@ export async function verifyAccountEmail(userId: string) {
|
|||
export async function lookupEmail(email: string): Promise<string | false> {
|
||||
await checkPermission("accounts/fetch/by-email", email);
|
||||
|
||||
const accounts = mongo()
|
||||
.db("revolt")
|
||||
.collection<Account>("accounts");
|
||||
const accounts = mongo().db("revolt").collection<Account>("accounts");
|
||||
|
||||
let result = await accounts.findOne({ email: email });
|
||||
if (result) return result._id;
|
||||
|
@ -598,10 +675,7 @@ export async function updateServerOwner(serverId: string, userId: string) {
|
|||
await mongo()
|
||||
.db("revolt")
|
||||
.collection<Server>("servers")
|
||||
.updateOne(
|
||||
{ _id: serverId },
|
||||
{ $set: { owner: userId } },
|
||||
);
|
||||
.updateOne({ _id: serverId }, { $set: { owner: userId } });
|
||||
|
||||
await publishMessage(serverId, {
|
||||
type: "ServerUpdate",
|
||||
|
@ -613,8 +687,16 @@ export async function updateServerOwner(serverId: string, userId: string) {
|
|||
});
|
||||
}
|
||||
|
||||
export async function addServerMember(serverId: string, userId: string, withEvent: boolean) {
|
||||
await checkPermission("servers/update/add-member", { serverId, userId, withEvent });
|
||||
export async function addServerMember(
|
||||
serverId: string,
|
||||
userId: string,
|
||||
withEvent: boolean
|
||||
) {
|
||||
await checkPermission("servers/update/add-member", {
|
||||
serverId,
|
||||
userId,
|
||||
withEvent,
|
||||
});
|
||||
|
||||
const server = await mongo()
|
||||
.db("revolt")
|
||||
|
@ -643,7 +725,7 @@ export async function addServerMember(serverId: string, userId: string, withEven
|
|||
joined_at: Long.fromNumber(Date.now()) as unknown as string,
|
||||
});
|
||||
|
||||
await publishMessage(userId + '!', {
|
||||
await publishMessage(userId + "!", {
|
||||
type: "ServerCreate",
|
||||
id: serverId,
|
||||
channels: channels,
|
||||
|
@ -686,11 +768,11 @@ export async function quarantineServer(serverId: string, message: string) {
|
|||
server,
|
||||
members,
|
||||
invites,
|
||||
}
|
||||
};
|
||||
|
||||
await writeFile(
|
||||
`./exports/${new Date().toISOString()} - ${serverId}.json`,
|
||||
JSON.stringify(backup),
|
||||
JSON.stringify(backup)
|
||||
);
|
||||
|
||||
await mongo()
|
||||
|
@ -703,7 +785,7 @@ export async function quarantineServer(serverId: string, message: string) {
|
|||
owner: "0".repeat(26),
|
||||
analytics: false,
|
||||
discoverable: false,
|
||||
}
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
|
@ -728,10 +810,11 @@ export async function quarantineServer(serverId: string, message: string) {
|
|||
await Promise.allSettled(
|
||||
m.map(async (member) => {
|
||||
const messageId = ulid();
|
||||
|
||||
|
||||
let dm = await findDM(PLATFORM_MOD_ID, member._id.user);
|
||||
if (!dm) dm = await createDM(PLATFORM_MOD_ID, member._id.user, messageId);
|
||||
|
||||
if (!dm)
|
||||
dm = await createDM(PLATFORM_MOD_ID, member._id.user, messageId);
|
||||
|
||||
await sendChatMessage({
|
||||
_id: messageId,
|
||||
author: PLATFORM_MOD_ID,
|
||||
|
@ -837,11 +920,15 @@ export async function resetBotToken(botId: string) {
|
|||
$set: {
|
||||
token: nanoid(64),
|
||||
},
|
||||
},
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
export async function transferBot(botId: string, ownerId: string, resetToken: boolean) {
|
||||
export async function transferBot(
|
||||
botId: string,
|
||||
ownerId: string,
|
||||
resetToken: boolean
|
||||
) {
|
||||
await checkPermission("bots/update/owner", { botId, ownerId, resetToken });
|
||||
|
||||
if (resetToken) {
|
||||
|
@ -858,15 +945,13 @@ export async function transferBot(botId: string, ownerId: string, resetToken: bo
|
|||
{
|
||||
$set: {
|
||||
owner: ownerId,
|
||||
...(
|
||||
resetToken
|
||||
? {
|
||||
...(resetToken
|
||||
? {
|
||||
token: nanoid(64),
|
||||
}
|
||||
: {}
|
||||
),
|
||||
: {}),
|
||||
},
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
await mongo()
|
||||
|
@ -880,22 +965,19 @@ export async function transferBot(botId: string, ownerId: string, resetToken: bo
|
|||
$set: {
|
||||
"bot.owner": ownerId,
|
||||
},
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
// This doesn't appear to work, maybe Revite can't handle it. I'll leave it in regardless.
|
||||
await publishMessage(
|
||||
botId,
|
||||
{
|
||||
type: "UserUpdate",
|
||||
id: botId,
|
||||
data: {
|
||||
bot: {
|
||||
owner: ownerId,
|
||||
},
|
||||
await publishMessage(botId, {
|
||||
type: "UserUpdate",
|
||||
id: botId,
|
||||
data: {
|
||||
bot: {
|
||||
owner: ownerId,
|
||||
},
|
||||
},
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
export async function restoreAccount(accountId: string) {
|
||||
|
@ -965,15 +1047,19 @@ export async function fetchBackups() {
|
|||
await checkPermission("backup/fetch", null);
|
||||
|
||||
return await Promise.all(
|
||||
(await readdir("./exports", { withFileTypes: true }))
|
||||
(
|
||||
await readdir("./exports", { withFileTypes: true })
|
||||
)
|
||||
.filter((file) => file.isFile() && file.name.endsWith(".json"))
|
||||
.map(async (file) => {
|
||||
let type: string | null = null;
|
||||
try {
|
||||
type = JSON.parse((await readFile(`./exports/${file.name}`)).toString("utf-8"))._event;
|
||||
} catch(e) {}
|
||||
type = JSON.parse(
|
||||
(await readFile(`./exports/${file.name}`)).toString("utf-8")
|
||||
)._event;
|
||||
} catch (e) {}
|
||||
|
||||
return { name: file.name, type: type }
|
||||
return { name: file.name, type: type };
|
||||
})
|
||||
);
|
||||
}
|
||||
|
@ -984,7 +1070,9 @@ export async function fetchBackup(name: string) {
|
|||
return JSON.parse((await readFile(`./exports/${name}`)).toString("utf-8"));
|
||||
}
|
||||
|
||||
export async function fetchEmailClassifications(): Promise<EmailClassification[]> {
|
||||
export async function fetchEmailClassifications(): Promise<
|
||||
EmailClassification[]
|
||||
> {
|
||||
await checkPermission("authifier/classification/fetch", null);
|
||||
|
||||
return await mongo()
|
||||
|
@ -994,27 +1082,34 @@ export async function fetchEmailClassifications(): Promise<EmailClassification[]
|
|||
.toArray();
|
||||
}
|
||||
|
||||
export async function createEmailClassification(domain: string, classification: string) {
|
||||
await checkPermission("authifier/classification/create", { domain, classification });
|
||||
export async function createEmailClassification(
|
||||
domain: string,
|
||||
classification: string
|
||||
) {
|
||||
await checkPermission("authifier/classification/create", {
|
||||
domain,
|
||||
classification,
|
||||
});
|
||||
|
||||
await mongo()
|
||||
.db("authifier")
|
||||
.collection<EmailClassification>("email_classification")
|
||||
.insertOne(
|
||||
{ _id: domain, classification },
|
||||
);
|
||||
.insertOne({ _id: domain, classification });
|
||||
}
|
||||
|
||||
export async function updateEmailClassification(domain: string, classification: string) {
|
||||
await checkPermission("authifier/classification/update", { domain, classification });
|
||||
export async function updateEmailClassification(
|
||||
domain: string,
|
||||
classification: string
|
||||
) {
|
||||
await checkPermission("authifier/classification/update", {
|
||||
domain,
|
||||
classification,
|
||||
});
|
||||
|
||||
await mongo()
|
||||
.db("authifier")
|
||||
.collection<EmailClassification>("email_classification")
|
||||
.updateOne(
|
||||
{ _id: domain },
|
||||
{ $set: { classification } },
|
||||
);
|
||||
.updateOne({ _id: domain }, { $set: { classification } });
|
||||
}
|
||||
|
||||
export async function deleteEmailClassification(domain: string) {
|
||||
|
@ -1023,21 +1118,19 @@ export async function deleteEmailClassification(domain: string) {
|
|||
await mongo()
|
||||
.db("authifier")
|
||||
.collection<EmailClassification>("email_classification")
|
||||
.deleteOne(
|
||||
{ _id: domain },
|
||||
);
|
||||
.deleteOne({ _id: domain });
|
||||
}
|
||||
|
||||
export async function searchUserByTag(username: string, discriminator: string): Promise<string | false> {
|
||||
export async function searchUserByTag(
|
||||
username: string,
|
||||
discriminator: string
|
||||
): Promise<string | false> {
|
||||
await checkPermission("users/fetch/by-tag", { username, discriminator });
|
||||
|
||||
const result = await mongo()
|
||||
.db("revolt")
|
||||
.collection<User>("users")
|
||||
.findOne({
|
||||
username,
|
||||
discriminator,
|
||||
});
|
||||
const result = await mongo().db("revolt").collection<User>("users").findOne({
|
||||
username,
|
||||
discriminator,
|
||||
});
|
||||
|
||||
return result?._id || false;
|
||||
}
|
||||
|
|
151
lib/db.ts
151
lib/db.ts
|
@ -21,6 +21,19 @@ import { getServerSession } from "next-auth";
|
|||
|
||||
let client: MongoClient;
|
||||
|
||||
export type CaseDocument = {
|
||||
_id: string;
|
||||
title: string;
|
||||
notes?: string;
|
||||
author: string;
|
||||
status: "Open" | "Closed";
|
||||
closed_at?: string;
|
||||
};
|
||||
|
||||
export type ReportDocument = Report & {
|
||||
case_id?: string;
|
||||
};
|
||||
|
||||
function mongo() {
|
||||
if (!client) {
|
||||
client = new MongoClient(process.env.MONGODB!);
|
||||
|
@ -55,6 +68,8 @@ export async function insertAuditLog(
|
|||
context,
|
||||
args,
|
||||
});
|
||||
|
||||
return session!.user!.email!;
|
||||
}
|
||||
|
||||
export async function fetchBotById(id: string) {
|
||||
|
@ -116,34 +131,33 @@ export type Account = {
|
|||
export async function fetchAccountById(id: string) {
|
||||
await checkPermission("accounts/fetch/by-id", id);
|
||||
|
||||
return await mongo()
|
||||
return (await mongo()
|
||||
.db("revolt")
|
||||
.collection<Account>("accounts")
|
||||
.aggregate(
|
||||
[
|
||||
{
|
||||
$match: { _id: id },
|
||||
.aggregate([
|
||||
{
|
||||
$match: { _id: id },
|
||||
},
|
||||
{
|
||||
$project: {
|
||||
password: 0,
|
||||
"mfa.totp_token.secret": 0,
|
||||
},
|
||||
{
|
||||
$project: {
|
||||
password: 0,
|
||||
"mfa.totp_token.secret": 0,
|
||||
}
|
||||
},
|
||||
{
|
||||
$set: {
|
||||
// Replace recovery code array with amount of codes
|
||||
"mfa.recovery_codes": {
|
||||
$cond: {
|
||||
if: { $isArray: "$mfa.recovery_codes" },
|
||||
then: { $size: "$mfa.recovery_codes" },
|
||||
else: undefined,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
$set: {
|
||||
// Replace recovery code array with amount of codes
|
||||
"mfa.recovery_codes": {
|
||||
$cond: {
|
||||
if: { $isArray: "$mfa.recovery_codes" },
|
||||
then: { $size: "$mfa.recovery_codes", },
|
||||
else: undefined,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
).next() as WithId<Account>;
|
||||
},
|
||||
])
|
||||
.next()) as WithId<Account>;
|
||||
}
|
||||
|
||||
export async function fetchSessionsByAccount(accountId: string) {
|
||||
|
@ -288,7 +302,7 @@ export async function fetchServers(query: Filter<Server>) {
|
|||
}
|
||||
|
||||
// `vanity` should eventually be added to the backend as well
|
||||
export type ChannelInvite = Invite & { vanity?: boolean }
|
||||
export type ChannelInvite = Invite & { vanity?: boolean };
|
||||
|
||||
export async function fetchInvites(query: Filter<ChannelInvite>) {
|
||||
await checkPermission("channels/fetch/invites", query);
|
||||
|
@ -306,12 +320,12 @@ export async function fetchInvites(query: Filter<ChannelInvite>) {
|
|||
.toArray();
|
||||
|
||||
const users = await mongo()
|
||||
.db("revolt")
|
||||
.collection<User>("users")
|
||||
.find({ _id: { $in: invites.map((invite) => invite.creator) } })
|
||||
.toArray();
|
||||
.db("revolt")
|
||||
.collection<User>("users")
|
||||
.find({ _id: { $in: invites.map((invite) => invite.creator) } })
|
||||
.toArray();
|
||||
|
||||
return { invites, channels, users }
|
||||
return { invites, channels, users };
|
||||
}
|
||||
|
||||
export async function fetchMessageById(id: string) {
|
||||
|
@ -358,7 +372,7 @@ export async function fetchOpenReports() {
|
|||
|
||||
return await mongo()
|
||||
.db("revolt")
|
||||
.collection<Report>("safety_reports")
|
||||
.collection<ReportDocument>("safety_reports")
|
||||
.find(
|
||||
{ status: "Created" },
|
||||
{
|
||||
|
@ -370,6 +384,23 @@ export async function fetchOpenReports() {
|
|||
.toArray();
|
||||
}
|
||||
|
||||
export async function fetchOpenCases() {
|
||||
await checkPermission("cases/fetch/open", "all");
|
||||
|
||||
return await mongo()
|
||||
.db("revolt")
|
||||
.collection<CaseDocument>("safety_cases")
|
||||
.find(
|
||||
{ status: "Open" },
|
||||
{
|
||||
sort: {
|
||||
_id: -1,
|
||||
},
|
||||
}
|
||||
)
|
||||
.toArray();
|
||||
}
|
||||
|
||||
export async function fetchRelatedReportsByContent(contentId: string) {
|
||||
await checkPermission("reports/fetch/related/by-content", contentId);
|
||||
|
||||
|
@ -404,6 +435,23 @@ export async function fetchReportsByUser(userId: string) {
|
|||
.toArray();
|
||||
}
|
||||
|
||||
export async function fetchReportsByCase(caseId: string) {
|
||||
await checkPermission("reports/fetch/related/by-case", caseId);
|
||||
|
||||
return await mongo()
|
||||
.db("revolt")
|
||||
.collection<ReportDocument>("safety_reports")
|
||||
.find(
|
||||
{ case_id: caseId },
|
||||
{
|
||||
sort: {
|
||||
_id: -1,
|
||||
},
|
||||
}
|
||||
)
|
||||
.toArray();
|
||||
}
|
||||
|
||||
export async function fetchReportsAgainstUser(userId: string) {
|
||||
await checkPermission("reports/fetch/related/against-user", userId);
|
||||
|
||||
|
@ -463,6 +511,27 @@ export async function fetchReportById(id: string) {
|
|||
.findOne({ _id: id });
|
||||
}
|
||||
|
||||
export async function createCase(title: string) {
|
||||
const id = ulid();
|
||||
const author = await checkPermission("cases/create", { title });
|
||||
|
||||
await mongo()
|
||||
.db("revolt")
|
||||
.collection<CaseDocument>("safety_cases")
|
||||
.insertOne({ _id: id, author, status: "Open", title });
|
||||
|
||||
return id;
|
||||
}
|
||||
|
||||
export async function fetchCaseById(id: string) {
|
||||
await checkPermission("cases/fetch/by-id", id);
|
||||
|
||||
return await mongo()
|
||||
.db("revolt")
|
||||
.collection<CaseDocument>("safety_cases")
|
||||
.findOne({ _id: id });
|
||||
}
|
||||
|
||||
export async function fetchMembershipsByUser(userId: string) {
|
||||
await checkPermission("users/fetch/memberships", userId);
|
||||
|
||||
|
@ -562,13 +631,19 @@ export async function fetchAuthifierEmailClassification(provider: string) {
|
|||
}
|
||||
|
||||
export type SafetyNotes = {
|
||||
_id: { id: string, type: "message" | "channel" | "server" | "user" | "account" | "global" };
|
||||
_id: {
|
||||
id: string;
|
||||
type: "message" | "channel" | "server" | "user" | "account" | "global";
|
||||
};
|
||||
text: string;
|
||||
edited_by: string;
|
||||
edited_at: Date;
|
||||
}
|
||||
};
|
||||
|
||||
export async function fetchSafetyNote(objectId: string, type: SafetyNotes["_id"]["type"]) {
|
||||
export async function fetchSafetyNote(
|
||||
objectId: string,
|
||||
type: SafetyNotes["_id"]["type"]
|
||||
) {
|
||||
await checkPermission(`safety_notes/fetch/${type}`, objectId);
|
||||
|
||||
return mongo()
|
||||
|
@ -577,7 +652,11 @@ export async function fetchSafetyNote(objectId: string, type: SafetyNotes["_id"]
|
|||
.findOne({ _id: { id: objectId, type: type } });
|
||||
}
|
||||
|
||||
export async function updateSafetyNote(objectId: string, type: SafetyNotes["_id"]["type"], note: string) {
|
||||
export async function updateSafetyNote(
|
||||
objectId: string,
|
||||
type: SafetyNotes["_id"]["type"],
|
||||
note: string
|
||||
) {
|
||||
await checkPermission(`safety_notes/update/${type}`, objectId);
|
||||
|
||||
const session = await getServerSession();
|
||||
|
@ -594,6 +673,6 @@ export async function updateSafetyNote(objectId: string, type: SafetyNotes["_id"
|
|||
edited_by: session?.user?.email ?? "",
|
||||
},
|
||||
},
|
||||
{ upsert: true },
|
||||
{ upsert: true }
|
||||
);
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue