Files
Magent/frontend/app/profile/invites/page.tsx
T

305 lines
19 KiB
TypeScript

'use client'
import PageHeading from '../../ui/PageHeading'
import { useRouter } from 'next/navigation'
import { useEffect, useMemo, useState } from 'react'
import { authFetch, clearToken, getApiBase, getToken } from '../../lib/auth'
type ProfileInfo = { username: string; role: string; invite_management_enabled?: boolean }
type OwnedInvite = {
id: number; code: string; label?: string | null; description?: string | null
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 signupBaseUrl = useMemo(() => {
if (typeof window === 'undefined') return '/signup'
return `${window.location.origin}/signup`
}, [])
const loadInvites = 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)
}
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()
}, [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()
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 (!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) => {
const url = `${signupBaseUrl}?code=${encodeURIComponent(invite.code)}`
try {
await navigator.clipboard.writeText(url)
setStatus(`Copied the link for ${invite.label || invite.code}.`)
} catch {
window.prompt('Copy invite link', url)
}
}
const codeCharacters = inviteForm.code.replace(/[^a-z0-9]/gi, '')
const identityReady = Boolean(inviteForm.label.trim() && (!useCustomCode || codeCharacters.length >= 6))
const canManageInvites = profile?.role === 'admin' || inviteAccessEnabled
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 Grizzlyflix 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 to Grizzlyflix. 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">
<div className="invite-delivery-grid"><button type="button" className={deliveryMethod === 'manual' ? 'is-selected' : ''} onClick={() => { setDeliveryMethod('manual'); setInviteForm((current) => ({ ...current, recipient_email: '', message: '' })) }}><span className="eyebrow">Manual</span><strong>Give me a link</strong><small>Magent creates the URL. You copy and share it yourself.</small></button><button type="button" className={deliveryMethod === 'email' ? 'is-selected' : ''} onClick={() => setDeliveryMethod('email')}><span className="eyebrow">Email</span><strong>Send it for me</strong><small>Magent emails the invitation and still gives you a copyable URL.</small></button></div>
{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"><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)}>Copy 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>
)
}