feat(release): publish minimal self-contained Magent source

This commit is contained in:
Magent release tooling
2026-09-19 16:58:12 +12:00
commit 5fa5d45535
272 changed files with 79305 additions and 0 deletions
@@ -0,0 +1,223 @@
"use client";
import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { authFetch, getApiBase } from "../lib/auth";
import "../email-recaps/recaps.css";
type Preference = {
automatic_monthly: boolean;
state: "off" | "pending" | "expired" | "enabled";
email: string | null;
can_subscribe: boolean;
detail: string;
schedule_enabled: boolean;
next_send_at: number | null;
day: number;
hour: number;
resend_after: number | null;
};
const scheduled = (value: number) =>
`${new Date(value * 1000).toLocaleString(undefined, { dateStyle: "long", timeStyle: "short", timeZone: "UTC" })} UTC`;
export default function MonthlyRecapPreference() {
const router = useRouter();
const [data, setData] = useState<Preference | null>(null);
const [automatic, setAutomatic] = useState(false);
const [busy, setBusy] = useState(false);
const [error, setError] = useState("");
const [notice, setNotice] = useState("");
const [revision, setRevision] = useState(0);
const [now, setNow] = useState(Date.now());
useEffect(() => {
void revision;
const abort = new AbortController();
setError("");
void authFetch(`${getApiBase()}/profile/email-recaps`, { signal: abort.signal })
.then(async (response) => {
if (response.status === 401) {
router.replace("/login?next=%2Fprofile");
return;
}
if (!response.ok) throw new Error("Could not load your email preference. Please try again.");
const result = (await response.json()) as Preference;
if (!abort.signal.aborted) {
setData(result);
setAutomatic(result.automatic_monthly);
}
})
.catch((err: Error) => {
if (!abort.signal.aborted) setError(err.message);
});
return () => abort.abort();
}, [revision, router]);
useEffect(() => {
if (!data?.resend_after || data.state === "enabled" || data.resend_after * 1000 <= Date.now()) return;
const timer = window.setInterval(() => setNow(Date.now()), 1000);
return () => window.clearInterval(timer);
}, [data?.resend_after, data?.state]);
const save = async (enabled: boolean, monthly = automatic) => {
if (busy) return;
setBusy(true);
setError("");
setNotice("");
try {
const response = await authFetch(`${getApiBase()}/profile/email-recaps`, {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ enabled, automatic_monthly: monthly }),
});
if (response.status === 401) {
router.replace("/login?next=%2Fprofile");
return;
}
const result = await response.json().catch(() => ({}));
if (!response.ok)
throw new Error(typeof result.detail === "string" ? result.detail : "Could not update your email preference.");
setData(result);
setAutomatic(result.automatic_monthly);
setNow(Date.now());
setNotice(
result.message || (enabled ? "Personal report emails are enabled." : "Personal report emails are off."),
);
} catch (err) {
setError(err instanceof Error ? err.message : "Could not update your email preference.");
// A confirmation may be pending even if SMTP could not confirm delivery.
const response = await authFetch(`${getApiBase()}/profile/email-recaps`).catch(() => null);
if (response?.ok) {
const fresh = await response.json();
setData(fresh);
setAutomatic(fresh.automatic_monthly);
setNow(Date.now());
}
} finally {
setBusy(false);
}
};
const cooldown = data?.resend_after ? Math.max(0, Math.ceil(data.resend_after - now / 1000)) : 0;
return (
<section className="recap-preference" id="monthly-recaps" aria-labelledby="recap-preference-title">
<div className="recap-section-heading">
<div>
<span className="recap-eyebrow">A little look back</span>
<h2 id="recap-preference-title">Your reports, your choice.</h2>
</div>
{data && (
<span className={`recap-pill ${data.state === "enabled" ? "is-enabled" : ""}`}>
{
{ off: "Off", pending: "Check your inbox", expired: "Confirmation expired", enabled: "Email confirmed" }[
data.state
]
}
</span>
)}
</div>
<p>
Email yourself your viewing report whenever you want. Choose a previous month or the current month so far, and
decide whether you also want automatic monthly emails.{" "}
<a href="/insights/reports">Explore your latest report </a>
</p>
{!data && !error && <p role="status">Loading your email preference</p>}
{data && (
<>
{data.state === "enabled" ? (
<p className="recap-delivery-address">
Recaps will go to <strong>{data.email}</strong>.{" "}
{!data.automatic_monthly
? "On demand only: choose a month in Reports and email it whenever you want."
: data.schedule_enabled && data.next_send_at
? `Next scheduled send: ${scheduled(data.next_send_at)}.`
: "The administrator has paused scheduled delivery."}
</p>
) : (
<p>
{data.state === "pending"
? `Check ${data.email} for a confirmation link. It expires after 24 hours. No viewing history is emailed until you confirm.`
: data.state === "expired"
? "Request a new confirmation link to turn on your recaps."
: "Confirm your profile email to turn this on. You can unsubscribe from any recap or here in Profile."}
</p>
)}
{!data.can_subscribe && data.state !== "enabled" && <p className="recap-muted">{data.detail}</p>}
{data.state !== "enabled" && data.can_subscribe && automatic && !data.schedule_enabled && (
<p className="recap-muted">
You can subscribe now. Monthly sends will begin when your administrator starts the schedule.
</p>
)}
<label className="recap-delivery-choice">
Delivery preference
<select
value={automatic ? "monthly" : "manual"}
disabled={busy || data.state === "pending"}
onChange={(event) => {
const monthly = event.target.value === "monthly";
setAutomatic(monthly);
if (data.state === "enabled") void save(true, monthly);
}}
>
<option value="manual">On demand only</option>
<option value="monthly">On demand + automatic monthly emails</option>
</select>
</label>
<div className="recap-actions">
{data.state !== "enabled" && (
<button
type="button"
className="account-primary"
disabled={busy || !data.can_subscribe || cooldown > 0}
onClick={() => void save(true)}
>
{busy
? "Sending confirmation…"
: data.state === "off"
? "Confirm my email for reports"
: "Send a new confirmation"}
</button>
)}
{data.state !== "off" && (
<button type="button" className="account-secondary" disabled={busy} onClick={() => void save(false)}>
{busy ? "Updating…" : data.state === "enabled" ? "Turn off report emails" : "Cancel subscription"}
</button>
)}
<button
type="button"
className="account-secondary"
disabled={busy}
onClick={() => {
setNotice("");
setRevision((value) => value + 1);
}}
>
Refresh preference
</button>
</div>
{cooldown > 0 && data.state !== "enabled" && (
<p className="recap-muted">
Another confirmation can be requested in {Math.ceil(cooldown / 60)}{" "}
{Math.ceil(cooldown / 60) === 1 ? "minute" : "minutes"}.
</p>
)}
</>
)}
{error && (
<p className="account-notice is-error" role="alert">
{error}
{!data && (
<button type="button" className="account-secondary" onClick={() => setRevision((value) => value + 1)}>
Try again
</button>
)}
</p>
)}
{notice && (
<p className="account-notice is-status" role="status">
{notice}
</p>
)}
</section>
);
}
@@ -0,0 +1,197 @@
"use client";
import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { authFetch, getApiBase } from "../lib/auth";
import "../email-recaps/recaps.css";
type Preference = {
state: "off" | "pending" | "expired" | "enabled";
email: string | null;
can_subscribe: boolean;
detail: string;
schedule_enabled: boolean;
next_send_at: number | null;
weekday: number;
hour: number;
resend_after: number | null;
};
const scheduled = (value: number) =>
`${new Date(value * 1000).toLocaleString(undefined, { dateStyle: "long", timeStyle: "short", timeZone: "UTC" })} UTC`;
export default function NewsletterPreference() {
const router = useRouter();
const [data, setData] = useState<Preference | null>(null);
const [busy, setBusy] = useState(false);
const [error, setError] = useState("");
const [notice, setNotice] = useState("");
const [revision, setRevision] = useState(0);
const [now, setNow] = useState(Date.now());
useEffect(() => {
void revision;
const abort = new AbortController();
setError("");
void authFetch(`${getApiBase()}/profile/newsletters`, { signal: abort.signal })
.then(async (response) => {
if (response.status === 401) {
router.replace("/login?next=%2Fprofile");
return;
}
if (!response.ok) throw new Error("Could not load your email preference. Please try again.");
const result = (await response.json()) as Preference;
if (!abort.signal.aborted) setData(result);
})
.catch((err: Error) => {
if (!abort.signal.aborted) setError(err.message);
});
return () => abort.abort();
}, [revision, router]);
useEffect(() => {
if (!data?.resend_after || data.state === "enabled" || data.resend_after * 1000 <= Date.now()) return;
const timer = window.setInterval(() => setNow(Date.now()), 1000);
return () => window.clearInterval(timer);
}, [data?.resend_after, data?.state]);
const save = async (enabled: boolean) => {
if (busy) return;
setBusy(true);
setError("");
setNotice("");
try {
const response = await authFetch(`${getApiBase()}/profile/newsletters`, {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ enabled }),
});
if (response.status === 401) {
router.replace("/login?next=%2Fprofile");
return;
}
const result = await response.json().catch(() => ({}));
if (!response.ok)
throw new Error(typeof result.detail === "string" ? result.detail : "Could not update your email preference.");
setData(result);
setNow(Date.now());
setNotice(result.message || (enabled ? "Newsletters are on." : "Newsletters are off."));
} catch (err) {
setError(err instanceof Error ? err.message : "Could not update your email preference.");
// A confirmation may be pending even if SMTP could not confirm delivery.
const response = await authFetch(`${getApiBase()}/profile/newsletters`).catch(() => null);
if (response?.ok) {
setData(await response.json());
setNow(Date.now());
}
} finally {
setBusy(false);
}
};
const cooldown = data?.resend_after ? Math.max(0, Math.ceil(data.resend_after - now / 1000)) : 0;
return (
<section className="recap-preference" id="newsletters" aria-labelledby="newsletter-preference-title">
<div className="recap-section-heading">
<div>
<span className="recap-eyebrow">Your next watch</span>
<h2 id="newsletter-preference-title">New in your library.</h2>
</div>
{data && (
<span className={`recap-pill ${data.state === "enabled" ? "is-enabled" : ""}`}>
{
{ off: "Off", pending: "Check your inbox", expired: "Confirmation expired", enabled: "Subscribed" }[
data.state
]
}
</span>
)}
</div>
<p>
Your minutes, movies, episodes, longest run and requests, in one personal monthly email.{" "}
<a href="/insights/reports">Explore your latest report </a>
</p>
{!data && !error && <p role="status">Loading your email preference</p>}
{data && (
<>
{data.state === "enabled" ? (
<p className="recap-delivery-address">
Newsletters will go to <strong>{data.email}</strong>.{" "}
{data.schedule_enabled && data.next_send_at
? `Next scheduled send: ${scheduled(data.next_send_at)}.`
: "Weekly sending is paused. You may still receive editions scheduled by your administrator."}
</p>
) : (
<p>
{data.state === "pending"
? `Check ${data.email} for a confirmation link. It expires after 24 hours. Your newsletter subscription starts after you confirm.`
: data.state === "expired"
? "Request a new confirmation link to turn on newsletters."
: "Subscribe with your profile email. If you already confirmed it for monthly recaps, you can turn this on straight away. Otherwise, we?ll send a confirmation link."}
</p>
)}
{!data.can_subscribe && data.state !== "enabled" && <p className="recap-muted">{data.detail}</p>}
{data.state !== "enabled" && data.can_subscribe && !data.schedule_enabled && (
<p className="recap-muted">You can subscribe now, ready for the next edition your administrator sends.</p>
)}
<div className="recap-actions">
{data.state !== "enabled" && (
<button
type="button"
className="account-primary"
disabled={busy || !data.can_subscribe || cooldown > 0}
onClick={() => void save(true)}
>
{busy
? "Sending confirmation…"
: data.state === "off"
? "Email me new arrivals"
: "Resend newsletter confirmation"}
</button>
)}
{data.state !== "off" && (
<button type="button" className="account-secondary" disabled={busy} onClick={() => void save(false)}>
{busy
? "Updating…"
: data.state === "enabled"
? "Turn off newsletters"
: "Cancel newsletter subscription"}
</button>
)}
<button
type="button"
className="account-secondary"
disabled={busy}
onClick={() => {
setNotice("");
setRevision((value) => value + 1);
}}
>
Refresh newsletter preference
</button>
</div>
{cooldown > 0 && data.state !== "enabled" && (
<p className="recap-muted">
Another confirmation can be requested in {Math.ceil(cooldown / 60)}{" "}
{Math.ceil(cooldown / 60) === 1 ? "minute" : "minutes"}.
</p>
)}
</>
)}
{error && (
<p className="account-notice is-error" role="alert">
{error}
{!data && (
<button type="button" className="account-secondary" onClick={() => setRevision((value) => value + 1)}>
Try again
</button>
)}
</p>
)}
{notice && (
<p className="account-notice is-status" role="status">
{notice}
</p>
)}
</section>
);
}
+629
View File
@@ -0,0 +1,629 @@
"use client";
import { useRouter } from "next/navigation";
import { useCallback, useEffect, useMemo, useState } from "react";
import { authFetch, clearToken, getApiBase, getToken } from "../../lib/auth";
import { useEffectiveRole } from "../../lib/viewMode";
import InviteDeliveryChoice from "../../ui/InviteDeliveryChoice";
import PageHeading from "../../ui/PageHeading";
type ProfileInfo = { username: string; role: string; invite_management_enabled?: boolean };
type OwnedInvite = {
id: number;
code: string;
label?: string | null;
description?: string | null;
code_available?: boolean;
recipient_email?: string | null;
max_uses?: number | null;
use_count: number;
remaining_uses?: number | null;
enabled: boolean;
expires_at?: string | null;
is_usable?: boolean;
created_at?: string | null;
};
type OwnedInvitesResponse = {
invites?: OwnedInvite[];
invite_access?: { enabled?: boolean; managed_by_master?: boolean };
master_invite?: {
id: number;
code: string;
label?: string | null;
max_uses?: number | null;
expires_at?: string | null;
} | null;
};
type InviteForm = {
code: string;
label: string;
description: string;
recipient_email: string;
enabled: boolean;
message: string;
};
type DeliveryMethod = "" | "manual" | "email";
const defaultInviteForm = (): InviteForm => ({
code: "",
label: "",
description: "",
recipient_email: "",
enabled: true,
message: "",
});
const formatDate = (value?: string | null) => {
if (!value) return "Never";
const date = new Date(value);
return Number.isNaN(date.valueOf()) ? value : date.toLocaleString();
};
const isValidEmail = (value: string) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value.trim());
export default function ProfileInvitesPage() {
const router = useRouter();
const [profile, setProfile] = useState<ProfileInfo | null>(null);
const [invites, setInvites] = useState<OwnedInvite[]>([]);
const [inviteAccessEnabled, setInviteAccessEnabled] = useState(false);
const [inviteManagedByMaster, setInviteManagedByMaster] = useState(false);
const [masterInvite, setMasterInvite] = useState<OwnedInvitesResponse["master_invite"]>(null);
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
const [error, setError] = useState<string | null>(null);
const [status, setStatus] = useState<string | null>(null);
const [editingId, setEditingId] = useState<number | null>(null);
const [flowStep, setFlowStep] = useState(1);
const [useCustomCode, setUseCustomCode] = useState(false);
const [deliveryMethod, setDeliveryMethod] = useState<DeliveryMethod>("");
const [inviteForm, setInviteForm] = useState<InviteForm>(defaultInviteForm());
const [createdInvite, setCreatedInvite] = useState<OwnedInvite | null>(null);
const effectiveRole = useEffectiveRole(profile?.role);
const canManageInvites =
effectiveRole === "admin" ||
(profile?.role === "admin" ? Boolean(profile.invite_management_enabled) : inviteAccessEnabled);
const signupBaseUrl = useMemo(() => {
if (typeof window === "undefined") return "/signup";
return `${window.location.origin}/signup`;
}, []);
const loadInvites = useCallback(async () => {
const response = await authFetch(`${getApiBase()}/auth/profile/invites`);
if (!response.ok) {
if (response.status === 401) {
clearToken();
router.push("/login");
return;
}
throw new Error("Could not load your invite workspace.");
}
const data = (await response.json()) as OwnedInvitesResponse;
setInvites(Array.isArray(data.invites) ? data.invites : []);
setInviteAccessEnabled(Boolean(data.invite_access?.enabled));
setInviteManagedByMaster(Boolean(data.invite_access?.managed_by_master));
setMasterInvite(data.master_invite ?? null);
}, [router]);
useEffect(() => {
if (!getToken()) {
router.push("/login");
return;
}
const load = async () => {
try {
const profileResponse = await authFetch(`${getApiBase()}/auth/profile`);
if (!profileResponse.ok) {
if (profileResponse.status === 401) {
clearToken();
router.push("/login");
return;
}
throw new Error("Could not load your profile.");
}
const profileData = await profileResponse.json();
setProfile(profileData?.user ?? null);
await loadInvites();
} catch (err) {
console.error(err);
setError(err instanceof Error ? err.message : "Could not load your invite workspace.");
} finally {
setLoading(false);
}
};
void load();
}, [loadInvites, router]);
const resetFlow = () => {
setEditingId(null);
setFlowStep(1);
setUseCustomCode(false);
setDeliveryMethod("");
setInviteForm(defaultInviteForm());
};
const editInvite = (invite: OwnedInvite) => {
setEditingId(invite.id);
setCreatedInvite(null);
setFlowStep(4);
setUseCustomCode(true);
setDeliveryMethod(invite.recipient_email ? "email" : "manual");
setInviteForm({
code: invite.code,
label: invite.label ?? "",
description: invite.description ?? "",
recipient_email: invite.recipient_email ?? "",
enabled: invite.enabled !== false,
message: "",
});
setError(null);
setStatus(null);
window.scrollTo({ top: 0, behavior: "smooth" });
};
const saveInvite = async (event: React.FormEvent) => {
event.preventDefault();
if (!canManageInvites) return;
const inviteName = inviteForm.label.trim();
const recipientEmail = inviteForm.recipient_email.trim();
if (!inviteName) {
setError("Give this invite a name so you can recognise it later.");
return;
}
if (!deliveryMethod) {
setError("Choose how you want to deliver the invite.");
return;
}
if (deliveryMethod === "email" && !isValidEmail(recipientEmail)) {
setError("Enter a valid recipient email address.");
return;
}
setSaving(true);
setError(null);
setStatus(null);
try {
const response = await authFetch(
editingId == null
? `${getApiBase()}/auth/profile/invites`
: `${getApiBase()}/auth/profile/invites/${editingId}`,
{
method: editingId == null ? "POST" : "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
code: useCustomCode ? inviteForm.code || null : null,
label: inviteName,
description: inviteForm.description || null,
recipient_email: deliveryMethod === "email" ? recipientEmail : null,
enabled: inviteForm.enabled,
send_email: editingId == null && deliveryMethod === "email",
message: inviteForm.message || null,
}),
},
);
if (!response.ok) {
if (response.status === 401) {
clearToken();
router.push("/login");
return;
}
throw new Error((await response.text()) || "Could not save the invite.");
}
const data = await response.json();
const savedInvite = data?.invite as OwnedInvite | undefined;
setStatus(
data?.email?.status === "ok"
? `Invite created and emailed to ${data.email.recipient_email}.`
: data?.email?.status === "error"
? `Invite created, but the email could not be sent: ${data.email.detail}`
: editingId == null
? "Invite link created and ready to share."
: "Invite updated.",
);
resetFlow();
if (editingId == null && savedInvite) setCreatedInvite(savedInvite);
await loadInvites();
} catch (err) {
console.error(err);
setError(err instanceof Error ? err.message : "Could not save the invite.");
} finally {
setSaving(false);
}
};
const deleteInvite = async (invite: OwnedInvite) => {
if (!canManageInvites) return;
if (!window.confirm(`Delete invite “${invite.label || invite.code}”?`)) return;
setError(null);
try {
const response = await authFetch(`${getApiBase()}/auth/profile/invites/${invite.id}`, { method: "DELETE" });
if (!response.ok) throw new Error((await response.text()) || "Could not delete the invite.");
if (editingId === invite.id) resetFlow();
setStatus(`Deleted ${invite.label || invite.code}.`);
await loadInvites();
} catch (err) {
console.error(err);
setError(err instanceof Error ? err.message : "Could not delete the invite.");
}
};
const copyInviteLink = async (invite: OwnedInvite) => {
if (!canManageInvites) return;
try {
let usableInvite = invite;
if (!invite.code_available) {
const response = await authFetch(`${getApiBase()}/auth/profile/invites/${invite.id}/rotate`, {
method: "POST",
});
if (!response.ok) throw new Error((await response.text()) || "Could not generate a replacement link.");
const data = await response.json();
usableInvite = data.invite as OwnedInvite;
setInvites((current) => current.map((item) => (item.id === invite.id ? usableInvite : item)));
}
const url = `${signupBaseUrl}?code=${encodeURIComponent(usableInvite.code)}`;
await navigator.clipboard.writeText(url);
setStatus(
`Copied the link for ${invite.label || usableInvite.code}. Keep it safe; Magent will not display it again after this page reloads.`,
);
} catch {
setError("Could not generate or copy the invite link.");
}
};
const codeCharacters = inviteForm.code.replace(/[^a-z0-9]/gi, "");
const identityReady = Boolean(inviteForm.label.trim() && (!useCustomCode || codeCharacters.length >= 6));
const createdInviteUrl = createdInvite ? `${signupBaseUrl}?code=${encodeURIComponent(createdInvite.code)}` : "";
if (loading) return <main className="card">Loading invite workspace</main>;
return (
<main className="card invites-page">
<PageHeading title="Invites" description="Invite someone to your media library and manage the links you share." />
{error && <div className="error-banner">{error}</div>}
{status && <div className="status-banner">{status}</div>}
{!canManageInvites ? (
<section className="profile-section profile-tab-panel">
<h2>Invites are not enabled for your account</h2>
<p className="lede">Ask an administrator if you need permission to invite someone.</p>
</section>
) : (
<section className="profile-section profile-invites-section profile-tab-panel">
<div className="invite-flow-heading">
<div>
<span className="eyebrow">Invite flow</span>
<h2>{editingId == null ? "Create an invite" : `Edit ${inviteForm.label || "invite"}`}</h2>
<p className="lede">Set up the invite one decision at a time.</p>
</div>
{editingId != null && (
<button type="button" className="ghost-button" onClick={resetFlow}>
Cancel edit
</button>
)}
</div>
{createdInvite && editingId == null ? (
<div className="invite-created-card" role="status">
<span className="eyebrow">Invite ready</span>
<h3>{createdInvite.label || "Your invite"}</h3>
<p>
{createdInvite.recipient_email
? `The invite was emailed to ${createdInvite.recipient_email}.`
: "Copy this link and send it to the person you are inviting."}
</p>
<div className="invite-created-link">
<input value={createdInviteUrl} readOnly aria-label="Created invite link" />
<button type="button" onClick={() => void copyInviteLink(createdInvite)}>
Copy link
</button>
</div>
<button
type="button"
className="ghost-button"
onClick={() => {
setCreatedInvite(null);
resetFlow();
}}
>
Create another invite
</button>
</div>
) : (
<form onSubmit={saveInvite} className="invite-flow-form">
<ol className="invite-flow-route" aria-label="Invite creation progress">
{["Identity", "Description", "Access", "Delivery"].map((label, index) => {
const step = index + 1;
return (
<li key={label} className={step === flowStep ? "is-active" : step < flowStep ? "is-complete" : ""}>
<span>{String(step).padStart(2, "0")}</span>
<strong>{label}</strong>
</li>
);
})}
</ol>
<section className={`invite-flow-step ${flowStep > 1 ? "is-complete" : "is-active"}`}>
<header>
<span className="invite-flow-number">01</span>
<div>
<span className="eyebrow">Identity</span>
<h3>Who is this invite for?</h3>
<p>Give it a name that will make sense when you return later.</p>
</div>
</header>
<div className="invite-flow-fields">
<label>
<span>Invite name</span>
<input
value={inviteForm.label}
onChange={(event) => setInviteForm((current) => ({ ...current, label: event.target.value }))}
placeholder="Family, that guy from work, the neighbour"
/>
</label>
<label className="invite-flow-choice-line">
<input
type="checkbox"
checked={useCustomCode}
disabled={editingId != null}
onChange={(event) => {
setUseCustomCode(event.target.checked);
if (!event.target.checked) setInviteForm((current) => ({ ...current, code: "" }));
}}
/>
<span>
<strong>Choose a custom invite code</strong>
<small>
The code appears at the end of the sign-up link. Leave this off and Magent will create a secure
code for you.
</small>
</span>
</label>
{useCustomCode && (
<label>
<span>Custom code</span>
<input
value={inviteForm.code}
disabled={editingId != null}
onChange={(event) => setInviteForm((current) => ({ ...current, code: event.target.value }))}
placeholder="At least 6 letters or numbers"
/>
<small>
This becomes <code>/signup?code={inviteForm.code || "YOUR-CODE"}</code>.
</small>
</label>
)}
{flowStep === 1 && (
<div className="invite-flow-actions">
<button type="button" disabled={!identityReady} onClick={() => setFlowStep(2)}>
Continue to description
</button>
</div>
)}
</div>
</section>
{flowStep >= 2 && (
<section className={`invite-flow-step ${flowStep > 2 ? "is-complete" : "is-active"}`}>
<header>
<span className="invite-flow-number">02</span>
<div>
<span className="eyebrow">Description</span>
<h3>Add a welcome note</h3>
<p>This optional message is shown on the sign-up page.</p>
</div>
</header>
<div className="invite-flow-fields">
<label>
<span>Welcome note (optional)</span>
<textarea
rows={3}
value={inviteForm.description}
onChange={(event) =>
setInviteForm((current) => ({ ...current, description: event.target.value }))
}
placeholder="Welcome! Use this link to create your account."
/>
</label>
{flowStep === 2 && (
<div className="invite-flow-actions">
<button type="button" className="ghost-button" onClick={() => setFlowStep(1)}>
Back
</button>
<button
type="button"
className="ghost-button"
onClick={() => {
setInviteForm((current) => ({ ...current, description: "" }));
setFlowStep(3);
}}
>
Skip
</button>
<button type="button" onClick={() => setFlowStep(3)}>
Continue
</button>
</div>
)}
</div>
</section>
)}
{flowStep >= 3 && (
<section className={`invite-flow-step ${flowStep > 3 ? "is-complete" : "is-active"}`}>
<header>
<span className="invite-flow-number">03</span>
<div>
<span className="eyebrow">Access</span>
<h3>Account access is applied automatically</h3>
<p>Magent uses the safe invite policy configured by an administrator.</p>
</div>
</header>
<div className="invite-flow-fields">
<div className="invite-policy-note">
<strong>Standard user access</strong>
<span>
{inviteManagedByMaster && masterInvite
? `Using the “${masterInvite.label || masterInvite.code}” invite policy. Usage and expiry limits are automatic.`
: "This invite creates a standard user account using your configured defaults."}
</span>
</div>
{flowStep === 3 && (
<div className="invite-flow-actions">
<button type="button" className="ghost-button" onClick={() => setFlowStep(2)}>
Back
</button>
<button type="button" onClick={() => setFlowStep(4)}>
Continue to delivery
</button>
</div>
)}
</div>
</section>
)}
{flowStep >= 4 && (
<section className="invite-flow-step is-active">
<header>
<span className="invite-flow-number">04</span>
<div>
<span className="eyebrow">Delivery</span>
<h3>How will they receive it?</h3>
<p>Copy the link yourself, or let Magent email it directly.</p>
</div>
</header>
<div className="invite-flow-fields">
<InviteDeliveryChoice
value={deliveryMethod}
onChange={(method) => {
setDeliveryMethod(method);
if (method === "manual")
setInviteForm((current) => ({ ...current, recipient_email: "", message: "" }));
}}
/>
{deliveryMethod === "manual" && (
<div className="invite-delivery-summary">
<strong>Your link will appear as soon as the invite is created.</strong>
<span>No email address is required and Magent will not send a message.</span>
</div>
)}
{deliveryMethod === "email" && (
<div className="invite-flow-field-grid invite-delivery-fields">
<label>
<span>Recipient email</span>
<input
type="email"
value={inviteForm.recipient_email}
onChange={(event) =>
setInviteForm((current) => ({ ...current, recipient_email: event.target.value }))
}
placeholder="person@example.com"
/>
</label>
<label>
<span>Email note (optional)</span>
<textarea
rows={3}
value={inviteForm.message}
onChange={(event) =>
setInviteForm((current) => ({ ...current, message: event.target.value }))
}
placeholder="A short personal message"
/>
</label>
</div>
)}
{editingId != null && (
<label className="invite-status-control">
<input
type="checkbox"
checked={inviteForm.enabled}
onChange={(event) =>
setInviteForm((current) => ({ ...current, enabled: event.target.checked }))
}
/>
<span>
<strong>{inviteForm.enabled ? "Invite enabled" : "Invite disabled"}</strong>
<small>Disable this existing invite to stop its link from accepting sign-ups.</small>
</span>
</label>
)}
<div className="invite-flow-actions">
<button type="button" className="ghost-button" onClick={() => setFlowStep(3)}>
Back
</button>
<button
type="submit"
disabled={
saving ||
!deliveryMethod ||
(deliveryMethod === "email" && !isValidEmail(inviteForm.recipient_email))
}
>
{saving
? "Saving…"
: editingId != null
? "Save invite"
: deliveryMethod === "email"
? "Create and email invite"
: "Create invite link"}
</button>
</div>
</div>
</section>
)}
</form>
)}
<div className="profile-invites-list">
<div className="invite-flow-heading">
<div>
<span className="eyebrow">Your invites</span>
<h2>Created invites</h2>
<p className="lede">Copy, edit, disable, or remove invitations you have made.</p>
</div>
</div>
{invites.length === 0 ? (
<div className="status-banner">You have not created any invites yet.</div>
) : (
<div className="admin-list">
{invites.map((invite) => (
<div key={invite.id} className="admin-list-item">
<div className="admin-list-item-main">
<div className="admin-list-item-title-row">
<strong>{invite.label || "Unnamed invite"}</strong>
<code className="invite-code">{invite.code}</code>
<span className={`small-pill ${invite.is_usable ? "" : "is-muted"}`}>
{invite.is_usable ? "Ready" : "Unavailable"}
</span>
</div>
{invite.description && (
<p className="admin-list-item-text admin-list-item-text--muted">{invite.description}</p>
)}
<div className="admin-meta-row">
<span>Delivery: {invite.recipient_email || "Manual link"}</span>
<span>
Uses: {invite.use_count}
{typeof invite.max_uses === "number" ? ` / ${invite.max_uses}` : ""}
</span>
<span>Expires: {formatDate(invite.expires_at)}</span>
<span>Created: {formatDate(invite.created_at)}</span>
</div>
</div>
<div className="admin-inline-actions">
<button type="button" className="ghost-button" onClick={() => void copyInviteLink(invite)}>
{invite.code_available ? "Copy link" : "Generate replacement link"}
</button>
<button type="button" className="ghost-button" onClick={() => editInvite(invite)}>
Edit
</button>
<button type="button" onClick={() => void deleteInvite(invite)}>
Delete
</button>
</div>
</div>
))}
</div>
)}
</div>
</section>
)}
</main>
);
}
+485
View File
@@ -0,0 +1,485 @@
"use client";
import { useRouter } from "next/navigation";
import { type FormEvent, type KeyboardEvent, useCallback, useEffect, useState } from "react";
import { authFetch, clearToken, getApiBase, getToken } from "../lib/auth";
import { canAccess, type FeatureAccess } from "../lib/features";
import { useEffectiveRole } from "../lib/viewMode";
import PageHeading from "../ui/PageHeading";
import MonthlyRecapPreference from "./MonthlyRecapPreference";
import NewsletterPreference from "./NewsletterPreference";
type ProfileInfo = {
features?: FeatureAccess;
username: string;
email?: string | null;
role: string;
auth_provider: string;
password_change_supported?: boolean;
password_provider?: "local" | "jellyfin" | null;
};
type ActivityEntry = {
ip: string;
user_agent: string;
first_seen_at: string;
last_seen_at: string;
};
type ProfileResponse = {
user: ProfileInfo;
stats?: { total: number; ready: number; in_progress: number };
activity?: { recent: ActivityEntry[] };
};
type Notice = { tone: "status" | "error"; message: string } | null;
type ProfileTab = "overview" | "security" | "activity";
const TABS: { key: ProfileTab; label: string }[] = [
{ key: "overview", label: "Account" },
{ key: "security", label: "Security" },
{ key: "activity", label: "Activity" },
];
const normalizeTab = (value: string | null): ProfileTab =>
value === "security" || value === "activity" ? value : "overview";
const formatDate = (value?: string) => {
if (!value) return "Not recorded";
const date = new Date(value);
return Number.isNaN(date.valueOf())
? "Not recorded"
: date.toLocaleString(undefined, { dateStyle: "medium", timeStyle: "short" });
};
const deviceName = (agent: string) => {
const value = (agent || "").toLowerCase();
const browser = value.includes("edg/")
? "Edge"
: value.includes("firefox/") || value.includes("fxios/")
? "Firefox"
: value.includes("chrome/") || value.includes("crios/")
? "Chrome"
: value.includes("safari/")
? "Safari"
: "Browser";
const device = /iphone|ipad/.test(value)
? "iOS"
: value.includes("android")
? "Android"
: value.includes("windows")
? "Windows"
: value.includes("macintosh")
? "Mac"
: value.includes("linux")
? "Linux"
: "";
return device ? `${browser} on ${device}` : browser;
};
const responseMessage = async (response: Response, fallback: string) => {
const data = await response.json().catch(() => null);
return typeof data?.detail === "string" && data.detail.trim() ? data.detail : fallback;
};
export default function ProfilePage() {
const router = useRouter();
const [data, setData] = useState<ProfileResponse | null>(null);
const [loading, setLoading] = useState(true);
const [loadError, setLoadError] = useState("");
const [activeTab, setActiveTab] = useState<ProfileTab>("overview");
const [email, setEmail] = useState("");
const [emailSaving, setEmailSaving] = useState(false);
const [emailNotice, setEmailNotice] = useState<Notice>(null);
const [currentPassword, setCurrentPassword] = useState("");
const [newPassword, setNewPassword] = useState("");
const [confirmPassword, setConfirmPassword] = useState("");
const [passwordSaving, setPasswordSaving] = useState(false);
const [passwordNotice, setPasswordNotice] = useState<Notice>(null);
const [showAllActivity, setShowAllActivity] = useState(false);
const loadProfile = useCallback(async () => {
if (!getToken()) {
router.replace("/login?next=%2Fprofile");
return;
}
setLoading(true);
setLoadError("");
try {
const response = await authFetch(`${getApiBase()}/auth/profile`);
if (response.status === 401) {
clearToken();
router.replace("/login?next=%2Fprofile");
return;
}
if (!response.ok) throw new Error("Could not load your profile. Please try again.");
const profile = (await response.json()) as ProfileResponse;
setData(profile);
setEmail(profile.user.email ?? "");
} catch {
setLoadError("Could not load your profile. Please try again.");
} finally {
setLoading(false);
}
}, [router]);
useEffect(() => {
void loadProfile();
}, [loadProfile]);
useEffect(() => {
const syncTab = () => setActiveTab(normalizeTab(new URLSearchParams(window.location.search).get("tab")));
syncTab();
window.addEventListener("popstate", syncTab);
return () => window.removeEventListener("popstate", syncTab);
}, []);
const selectTab = (tab: ProfileTab) => {
setActiveTab(tab);
router.replace(tab === "overview" ? "/profile" : `/profile?tab=${tab}`, { scroll: false });
};
const tabKeyDown = (event: KeyboardEvent<HTMLButtonElement>, index: number) => {
let next = index;
if (event.key === "ArrowRight") next = (index + 1) % TABS.length;
else if (event.key === "ArrowLeft") next = (index + TABS.length - 1) % TABS.length;
else if (event.key === "Home") next = 0;
else if (event.key === "End") next = TABS.length - 1;
else return;
event.preventDefault();
selectTab(TABS[next].key);
document.getElementById(`profile-tab-${TABS[next].key}`)?.focus();
};
const saveEmail = async (event: FormEvent<HTMLFormElement>) => {
event.preventDefault();
if (emailSaving) return;
setEmailSaving(true);
setEmailNotice(null);
try {
const response = await authFetch(`${getApiBase()}/auth/profile/email`, {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ email: email.trim() || null }),
});
if (response.status === 401) {
clearToken();
router.replace("/login?next=%2Fprofile");
return;
}
if (!response.ok)
throw new Error(await responseMessage(response, "Could not save your email. Please try again."));
const result = await response.json();
const saved = typeof result.email === "string" ? result.email : "";
setData((current) => (current ? { ...current, user: { ...current.user, email: saved || null } } : current));
setEmail(saved);
setEmailNotice({ tone: "status", message: saved ? "Email saved." : "Email removed." });
} catch (error) {
setEmailNotice({ tone: "error", message: error instanceof Error ? error.message : "Could not save your email." });
} finally {
setEmailSaving(false);
}
};
const savePassword = async (event: FormEvent<HTMLFormElement>) => {
event.preventDefault();
if (passwordSaving) return;
setPasswordNotice(null);
if (newPassword.trim().length < 8) {
setPasswordNotice({ tone: "error", message: "Use at least 8 characters for your new password." });
return;
}
if (newPassword !== confirmPassword) {
setPasswordNotice({ tone: "error", message: "The new passwords do not match." });
return;
}
setPasswordSaving(true);
try {
const response = await authFetch(`${getApiBase()}/auth/password`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ current_password: currentPassword, new_password: newPassword }),
});
if (!response.ok)
throw new Error(await responseMessage(response, "Could not change your password. Please try again."));
const result = await response.json();
setCurrentPassword("");
setNewPassword("");
setConfirmPassword("");
setPasswordNotice({
tone: "status",
message:
result.provider === "jellyfin"
? "Password updated for Jellyfin and Magent. Seerr uses the same password."
: "Password updated.",
});
} catch (error) {
setPasswordNotice({
tone: "error",
message: error instanceof Error ? error.message : "Could not change your password.",
});
} finally {
setPasswordSaving(false);
}
};
const user = data?.user;
const effectiveRole = useEffectiveRole(user?.role);
const passwordProvider = user?.password_provider ?? (user?.auth_provider === "jellyfin" ? "jellyfin" : "local");
const canChangePassword =
user?.password_change_supported ?? ["local", "jellyfin"].includes(user?.auth_provider ?? "");
const emailChanged = email.trim() !== (user?.email ?? "");
const recent = data?.activity?.recent ?? [];
const notice = (value: Notice) =>
value && (
<p className={`account-notice is-${value.tone}`} role={value.tone === "error" ? "alert" : "status"}>
{value.message}
</p>
);
return (
<main className="account-page">
<PageHeading
title="My profile"
description="Your contact details, security, and activity."
actions={
user && (
<div className="account-identity">
<span className="account-avatar" aria-hidden="true">
{user.username.slice(0, 1).toUpperCase()}
</span>
<div>
<strong>{user.username}</strong>
<span>{effectiveRole === "admin" ? "Administrator" : "Member"}</span>
</div>
</div>
)
}
/>
{loading ? (
<p className="account-empty" role="status">
Loading your profile
</p>
) : loadError ? (
<div className="account-empty">
<p role="alert">{loadError}</p>
<button type="button" className="account-secondary" onClick={() => void loadProfile()}>
Try again
</button>
</div>
) : (
user && (
<>
<div className="account-tabs" role="tablist" aria-label="Profile sections">
{TABS.map((tab, index) => (
<button
key={tab.key}
id={`profile-tab-${tab.key}`}
type="button"
role="tab"
aria-selected={activeTab === tab.key}
aria-controls={`profile-panel-${tab.key}`}
tabIndex={activeTab === tab.key ? 0 : -1}
onKeyDown={(event) => tabKeyDown(event, index)}
onClick={() => selectTab(tab.key)}
>
{tab.label}
</button>
))}
</div>
<section
className="account-panel"
id="profile-panel-overview"
role="tabpanel"
aria-labelledby="profile-tab-overview"
hidden={activeTab !== "overview"}
>
<div className="account-section-intro">
<h2>Contact email</h2>
<p>For password recovery and updates on your reported issues.</p>
</div>
<form className="account-form" onSubmit={saveEmail}>
<label htmlFor="profile-email">Email address</label>
<input
id="profile-email"
name="email"
type="email"
autoComplete="email"
placeholder="you@example.com"
value={email}
disabled={emailSaving}
onChange={(event) => {
setEmail(event.target.value);
setEmailNotice(null);
}}
/>
{!user.email && (
<p className="account-hint">Add an email so we can let you know when a fix is ready.</p>
)}
{user.email && !email.trim() && (
<p className="account-hint">Saving without an email stops account and issue emails.</p>
)}
{notice(emailNotice)}
<div className="account-form-actions">
<button type="submit" className="account-primary" disabled={emailSaving || !emailChanged}>
{emailSaving ? "Saving…" : "Save email"}
</button>
{emailChanged && (
<button
type="button"
className="account-secondary"
disabled={emailSaving}
onClick={() => {
setEmail(user.email ?? "");
setEmailNotice(null);
}}
>
Discard
</button>
)}
</div>
</form>
<div className="account-connected">
<span className="account-connection-dot" aria-hidden="true" />
<span>
{user.auth_provider === "jellyfin"
? "Connected with your Jellyfin account"
: user.auth_provider === "local"
? "Signed in with a Magent account"
: "Signed in with your media account"}
</span>
</div>
{canAccess({ ...user, role: effectiveRole ?? undefined }, "stats") && (
<MonthlyRecapPreference key={user.email || "no-email"} />
)}
<NewsletterPreference key={`newsletter-${user.email || "no-email"}`} />
</section>
<section
className="account-panel"
id="profile-panel-security"
role="tabpanel"
aria-labelledby="profile-tab-security"
hidden={activeTab !== "security"}
>
<div className="account-section-intro">
<h2>Change password</h2>
<p>
{passwordProvider === "jellyfin"
? "One password for Jellyfin, Seerr and Magent."
: "Keep your Magent account secure."}
</p>
</div>
{canChangePassword ? (
<form className="account-form" onSubmit={savePassword}>
<fieldset disabled={passwordSaving}>
<label htmlFor="profile-current-password">Current password</label>
<input
id="profile-current-password"
type="password"
autoComplete="current-password"
value={currentPassword}
onChange={(event) => setCurrentPassword(event.target.value)}
required
/>
<label htmlFor="profile-new-password">New password</label>
<input
id="profile-new-password"
type="password"
autoComplete="new-password"
aria-describedby="password-length"
value={newPassword}
onChange={(event) => setNewPassword(event.target.value)}
minLength={8}
required
/>
<p id="password-length" className="account-hint">
At least 8 characters.
</p>
<label htmlFor="profile-confirm-password">Confirm new password</label>
<input
id="profile-confirm-password"
type="password"
autoComplete="new-password"
value={confirmPassword}
onChange={(event) => setConfirmPassword(event.target.value)}
minLength={8}
required
/>
</fieldset>
{notice(passwordNotice)}
<div className="account-form-actions">
<button type="submit" className="account-primary" disabled={passwordSaving}>
{passwordSaving ? "Updating…" : "Update password"}
</button>
</div>
</form>
) : (
<p className="account-empty">
Password changes are managed by your sign-in provider. Contact an administrator for help.
</p>
)}
</section>
<section
className="account-panel"
id="profile-panel-activity"
role="tabpanel"
aria-labelledby="profile-tab-activity"
hidden={activeTab !== "activity"}
>
<div className="account-section-intro">
<h2>Your activity</h2>
<p>Your requests and recent account access.</p>
</div>
{data?.stats && (
<div className="account-request-summary">
<div>
<strong>{data.stats.total}</strong>
<span>Requests</span>
</div>
<div>
<strong>{data.stats.ready}</strong>
<span>Ready to watch</span>
</div>
<a href="/">
View my requests <span aria-hidden="true"></span>
</a>
</div>
)}
<h3 className="account-list-heading">Recent account access</h3>
{recent.length ? (
<ul className="account-access-list">
{(showAllActivity ? recent : recent.slice(0, 5)).map((entry, index) => (
<li key={`${entry.ip}-${entry.last_seen_at}-${index}`}>
<div className="account-access-summary">
<strong>{deviceName(entry.user_agent)}</strong>
<time dateTime={entry.last_seen_at}>{formatDate(entry.last_seen_at)}</time>
</div>
<details>
<summary>Connection details</summary>
<dl>
<div>
<dt>IP address</dt>
<dd>{entry.ip || "Not recorded"}</dd>
</div>
<div>
<dt>First seen</dt>
<dd>{formatDate(entry.first_seen_at)}</dd>
</div>
</dl>
</details>
</li>
))}
</ul>
) : (
<p className="account-empty">No recent activity yet.</p>
)}
{recent.length > 5 && (
<button
className="account-secondary"
type="button"
onClick={() => setShowAllActivity(!showAllActivity)}
>
{showAllActivity ? "Show less" : "Show all activity"}
</button>
)}
</section>
</>
)
)}
</main>
);
}