Add related cases and duplicate review suggestions

This commit is contained in:
2026-10-17 19:52:50 -04:00
parent 428aefdf24
commit 90b94911c5
15 changed files with 1289 additions and 1 deletions
@@ -0,0 +1,193 @@
<script lang="ts">
import { untrack } from 'svelte';
import {
moderationCaseRelations,
moderationCaseRelationLabels,
type ModerationCaseDetail,
type ModerationCaseRelationship,
type ModerationCaseRelation
} from '$lib/moderation.js';
import Dialog from '../primitives/Dialog.svelte';
import Field from '../primitives/Field.svelte';
import Input from '../primitives/Input.svelte';
import Select from '../primitives/Select.svelte';
import Textarea from '../primitives/Textarea.svelte';
import Button from '../primitives/Button.svelte';
let {
open = $bindable(false),
caseId,
revision,
candidates = [],
relationship,
onsubmitted
}: {
open?: boolean;
caseId: string;
revision: number;
candidates?: NonNullable<ModerationCaseDetail['candidateCases']>;
relationship?: ModerationCaseRelationship;
onsubmitted: () => void;
} = $props();
const openedRevision = untrack(() => revision);
let selected = $state('');
let caseReference = $state('');
let relation = $state<ModerationCaseRelation>('same_incident');
let reason = $state('');
let busy = $state(false);
let uncertain = $state(false);
let error = $state('');
let pending: Record<string, unknown> | null = null;
function relatedId(): string {
if (selected) return selected;
const value = caseReference.trim();
if (value.startsWith('/') || /^https?:\/\//i.test(value)) {
const path = new URL(value, 'http://localhost').pathname;
const match = /^\/moderation\/cases\/([^/]+)\/?$/.exec(path);
if (!match) throw new Error('Enter a case ID or a moderation case URL.');
return decodeURIComponent(match[1]);
}
return value;
}
async function submit(event: SubmitEvent) {
event.preventDefault();
if (busy) return;
error = '';
if (!pending) {
try {
const target = relationship ? '' : relatedId();
if ((!relationship && !target) || !reason.trim())
throw new Error('Choose a related case and provide a reason for this change.');
pending = {
id: caseId,
revision: openedRevision,
reason: reason.trim(),
idempotencyKey: crypto.randomUUID(),
...(relationship
? { op: 'unlink-case', relationshipId: relationship.id }
: { op: 'link-case', relatedCaseId: target, relation })
};
} catch (cause) {
error = cause instanceof Error ? cause.message : 'Enter a valid case reference.';
return;
}
}
busy = true;
try {
const response = await fetch('/api/moderation', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(pending)
});
const result = await response.json().catch(() => null);
if (!response.ok || !result?.ok) {
uncertain = response.status >= 500 || response.ok;
if (!uncertain) pending = null;
throw new Error(result?.error || 'Could not save the case relationship.');
}
open = false;
onsubmitted();
} catch (cause) {
if (pending) uncertain = true;
error =
cause instanceof Error ? cause.message : 'Could not save the case relationship.';
} finally {
busy = false;
}
}
</script>
<Dialog
bind:open
title={relationship ? 'Remove case relationship' : 'Link related case'}
{busy}
description="Relationships connect case records while preserving each case and its history."
>
<form onsubmit={submit}>
<fieldset disabled={busy || uncertain}>
{#if relationship}<p>
Remove the relationship with <strong>{relationship.case.title}</strong>. The
relationship history remains recorded.
</p>
{:else}
<Field label="Related case"
><Select
bind:value={selected}
options={[
{ value: '', label: 'Enter a case ID or URL' },
...candidates.map((item) => ({
value: item.id,
label: `${item.title}${item.sharedMatch ? ' · Shared archived match' : ''}`
}))
]}
/></Field
>
{#if !selected}<Field label="Case ID or URL" required
><Input bind:value={caseReference} required maxlength={2048} /></Field
>{/if}
<Field label="Relationship"
><Select
bind:value={relation}
options={moderationCaseRelations.map((value) => ({
value,
label: moderationCaseRelationLabels[value]
}))}
/></Field
>
<p class="hint">
Appeal and duplicate relationships refer to the same player. “Same incident” can
connect cases involving different players.
</p>
{/if}
<Field label="Relationship reason" required
><Textarea bind:value={reason} required rows={3} maxlength={4000} /></Field
>
</fieldset>
{#if error}<p class="ui-error" role="alert">{error}</p>{/if}
{#if uncertain}<p class="hint">
The result is uncertain. Retry sends the same request safely.
</p>{/if}
<div class="actions">
<Button disabled={busy} onclick={() => (open = false)}>Cancel</Button><Button
type="submit"
variant="primary"
loading={busy}
>{uncertain
? 'Retry same request'
: relationship
? 'Remove relationship'
: 'Link cases'}</Button
>
</div>
</form>
</Dialog>
<style>
form,
fieldset {
display: grid;
gap: var(--space-4);
min-width: 0;
}
fieldset {
margin: 0;
padding: 0;
border: 0;
}
p {
margin: 0;
line-height: var(--leading-body);
overflow-wrap: anywhere;
}
.hint {
color: var(--text-secondary);
font-size: var(--text-sm);
}
.actions {
display: flex;
justify-content: flex-end;
flex-wrap: wrap;
gap: var(--space-3);
}
</style>
@@ -0,0 +1,153 @@
<script lang="ts">
import {
moderationCaseRelationLabels,
moderationCaseStatusLabels,
type ModerationCaseDetail,
type ModerationCaseRelationship
} from '$lib/moderation.js';
import { moderationCaseHref } from '$ui/moderation.js';
import Button from '../primitives/Button.svelte';
import Badge from '../primitives/Badge.svelte';
import RelativeTime from '../RelativeTime.svelte';
import CaseRelationshipDialog from './CaseRelationshipDialog.svelte';
let {
caseId,
revision,
relationships = [],
candidates = [],
permitted,
onsubmitted
}: {
caseId: string;
revision: number;
relationships?: ModerationCaseRelationship[];
candidates?: NonNullable<ModerationCaseDetail['candidateCases']>;
permitted: boolean;
onsubmitted: () => void;
} = $props();
let open = $state(false);
let removing = $state<ModerationCaseRelationship | undefined>();
$effect(() => {
void caseId;
open = false;
});
function label(relationship: ModerationCaseRelationship) {
if (relationship.direction === 'incoming') {
if (relationship.relation === 'appeal_of') return 'Appealed by';
if (relationship.relation === 'duplicate_of') return 'Has duplicate';
}
return moderationCaseRelationLabels[relationship.relation];
}
</script>
<section aria-label="Related cases">
<div class="heading">
<h2>Related cases</h2>
{#if permitted}<Button
size="sm"
onclick={() => {
removing = undefined;
open = true;
}}>Link case</Button
>{/if}
</div>
{#if relationships.length}<ul class="records">
{#each relationships as relationship (relationship.id)}<li>
<div class="heading">
<strong>{label(relationship)}</strong><Badge
>{moderationCaseStatusLabels[relationship.case.status]}</Badge
>
</div>
<a href={moderationCaseHref(relationship.case.id)}>{relationship.case.title}</a>
<p class="hint">
{relationship.actor} · <RelativeTime value={relationship.createdAt} />
</p>
{#if permitted}<Button
size="sm"
ariaLabel={`Remove relationship with ${relationship.case.title}`}
onclick={() => {
removing = relationship;
open = true;
}}>Remove link</Button
>{/if}
</li>{/each}
</ul>{:else}<p class="hint">No cases linked yet.</p>{/if}
{#if candidates.length}<details>
<summary>Other cases for this player ({candidates.length})</summary>
<ul class="records">
{#each candidates as candidate}<li>
<a href={moderationCaseHref(candidate.id)}>{candidate.title}</a>
<span class="hint">{moderationCaseStatusLabels[candidate.status]}</span>
{#if candidate.sharedMatch}<Badge variant="warning"
>Shared archived match</Badge
>
<p class="hint">
Review for a possible duplicate or related incident.
</p>{/if}
</li>{/each}
</ul>
</details>{/if}
</section>
{#if permitted && open}<CaseRelationshipDialog
bind:open
{caseId}
{revision}
{candidates}
relationship={removing}
{onsubmitted}
/>{/if}
<style>
section {
display: grid;
gap: var(--space-4);
padding: var(--space-5);
border: 1px solid var(--border-subtle);
border-radius: var(--radius-lg);
background: var(--surface);
min-width: 0;
}
.heading {
display: flex;
align-items: center;
justify-content: space-between;
flex-wrap: wrap;
gap: var(--space-3);
}
h2 {
margin: 0;
font-size: var(--text-lg);
}
p {
margin: 0;
line-height: var(--leading-body);
}
.hint {
color: var(--text-secondary);
font-size: var(--text-sm);
}
.records {
list-style: none;
padding: 0;
margin: 0;
display: grid;
gap: var(--space-3);
}
.records > li {
display: grid;
justify-items: start;
gap: var(--space-2);
padding-top: var(--space-3);
border-top: 1px solid var(--border-subtle);
overflow-wrap: anywhere;
}
summary {
cursor: pointer;
font-size: var(--text-sm);
}
details .records {
margin-top: var(--space-3);
}
</style>
@@ -0,0 +1,106 @@
<script lang="ts">
import type { ModerationGame, ModerationOverview } from '$lib/moderation.js';
import { moderationCaseStatusLabels } from '$lib/moderation.js';
import { moderationCaseHref, moderationHref } from '$ui/moderation.js';
let { game, guid }: { game: ModerationGame; guid: string } = $props();
let report = $state<ModerationOverview | null>(null);
let loading = $state(false);
let failed = $state(false);
let retry = $state(0);
$effect(() => {
const target = guid.trim();
const targetGame = game;
void retry;
const controller = new AbortController();
report = null;
failed = false;
loading = !!target;
const timer = setTimeout(async () => {
if (!target) return;
try {
const params = new URLSearchParams({
view: 'cases',
game: targetGame,
guid: target
});
const response = await fetch(`/api/moderation?${params}`, {
signal: controller.signal
});
if (!response.ok) throw new Error('Case lookup failed');
const result: ModerationOverview = await response.json();
if (!Array.isArray(result.cases) || !Number.isSafeInteger(result.total))
throw new Error('Invalid case lookup response');
if (!controller.signal.aborted) report = result;
} catch {
if (!controller.signal.aborted) failed = true;
} finally {
if (!controller.signal.aborted) loading = false;
}
}, 300);
return () => {
clearTimeout(timer);
controller.abort();
};
});
</script>
<aside aria-label="Existing cases for this player">
{#if loading}<p role="status">Checking existing cases for this player…</p>
{:else if failed}<p role="status">
Existing cases could not be loaded. You can still open a case. <button
type="button"
onclick={() => retry++}>Retry lookup</button
>
</p>
{:else if report?.cases.length}
<strong
>{report.total} existing {report.total === 1 ? 'case' : 'cases'} for this player</strong
>
<p>Review these before opening another case.</p>
<ul>
{#each report.cases as item}<li>
<a href={moderationCaseHref(item.id)} target="_blank" rel="noreferrer"
>{item.title}</a
>
· {moderationCaseStatusLabels[item.status]}
</li>{/each}
</ul>
<a href={`${moderationHref({ game, guid })}&view=cases`} target="_blank" rel="noreferrer"
>View all cases for this player</a
>
{:else if report}<p>No existing cases found for this player.</p>{/if}
</aside>
<style>
aside {
padding: var(--space-3);
border: 1px solid var(--border-subtle);
border-radius: var(--radius-md);
color: var(--text-secondary);
font-size: var(--text-sm);
}
p {
margin: 0;
line-height: var(--leading-body);
}
ul {
margin: var(--space-2) 0;
padding-left: var(--space-5);
max-height: 200px;
overflow: auto;
}
li {
padding: var(--space-1) 0;
overflow-wrap: anywhere;
}
button {
border: 0;
background: none;
padding: 0;
color: var(--accent-primary);
font: inherit;
cursor: pointer;
text-decoration: underline;
}
</style>
@@ -20,6 +20,7 @@
import Select from '../primitives/Select.svelte';
import Textarea from '../primitives/Textarea.svelte';
import Button from '../primitives/Button.svelte';
import ExistingCaseNotice from './ExistingCaseNotice.svelte';
let {
open = $bindable(false),
@@ -395,6 +396,10 @@
complete.
</p>{/if}
{#if mode === 'case' || mode === 'edit-case'}
{#if mode === 'case' && open && game && guid.trim()}<ExistingCaseNotice
{game}
{guid}
/>{/if}
<Field label="Case title" required
><Input bind:value={title} required maxlength={160} /></Field
>