Move invite flow to client navigation

This commit is contained in:
2026-09-01 22:20:48 +12:00
parent 06d944c9d9
commit c6d449dc17
5 changed files with 214 additions and 513 deletions
+12 -2
View File
@@ -102,6 +102,12 @@ def _require_recipient_email(value: object) -> str:
) )
def _optional_recipient_email(value: object) -> str | None:
if value is None or not str(value).strip():
return None
return _require_recipient_email(value)
def _auth_client_ip(request: Request) -> str: def _auth_client_ip(request: Request) -> str:
direct_host = request.client.host if request.client else None direct_host = request.client.host if request.client else None
if request_trusts_forwarded_headers(direct_host): if request_trusts_forwarded_headers(direct_host):
@@ -1210,8 +1216,10 @@ async def create_profile_invite(payload: dict, current_user: dict = Depends(get_
label = str(label).strip() or None label = str(label).strip() or None
if description is not None: if description is not None:
description = str(description).strip() or None description = str(description).strip() or None
recipient_email = _require_recipient_email(recipient_email)
send_email = bool(payload.get("send_email")) send_email = bool(payload.get("send_email"))
recipient_email = _optional_recipient_email(recipient_email)
if send_email and not recipient_email:
recipient_email = _require_recipient_email(recipient_email)
delivery_message = str(payload.get("message") or "").strip() or None delivery_message = str(payload.get("message") or "").strip() or None
master_invite = _get_self_service_master_invite() master_invite = _get_self_service_master_invite()
@@ -1300,8 +1308,10 @@ async def update_profile_invite(
label = str(label).strip() or None label = str(label).strip() or None
if description is not None: if description is not None:
description = str(description).strip() or None description = str(description).strip() or None
recipient_email = _require_recipient_email(recipient_email)
send_email = bool(payload.get("send_email")) send_email = bool(payload.get("send_email"))
recipient_email = _optional_recipient_email(recipient_email)
if send_email and not recipient_email:
recipient_email = _require_recipient_email(recipient_email)
delivery_message = str(payload.get("message") or "").strip() or None delivery_message = str(payload.get("message") or "").strip() or None
master_invite = _get_self_service_master_invite() master_invite = _get_self_service_master_invite()
+22 -6
View File
@@ -1424,7 +1424,23 @@ class AuthFlowTests(TempDatabaseMixin, unittest.IsolatedAsyncioTestCase):
send_email.assert_awaited_once() send_email.assert_awaited_once()
self.assertEqual(send_email.await_args.kwargs["recipient_email"], "local@example.com") self.assertEqual(send_email.await_args.kwargs["recipient_email"], "local@example.com")
async def test_profile_invite_requires_recipient_email(self) -> None: async def test_profile_manual_invite_does_not_require_recipient_email(self) -> None:
current_user = {
"username": "invite-owner",
"role": "user",
"invite_management_enabled": True,
"profile_id": None,
}
result = await auth_router.create_profile_invite(
{"label": "Family", "recipient_email": None, "send_email": False},
current_user,
)
self.assertEqual(result["status"], "ok")
self.assertIsNone(result["invite"]["recipient_email"])
self.assertIsNone(result["email"])
async def test_profile_email_delivery_requires_recipient_email(self) -> None:
current_user = { current_user = {
"username": "invite-owner", "username": "invite-owner",
"role": "user", "role": "user",
@@ -1432,13 +1448,13 @@ class AuthFlowTests(TempDatabaseMixin, unittest.IsolatedAsyncioTestCase):
"profile_id": None, "profile_id": None,
} }
with self.assertRaises(HTTPException) as context: with self.assertRaises(HTTPException) as context:
await auth_router.create_profile_invite({"label": "Missing email"}, current_user) await auth_router.create_profile_invite(
{"label": "Missing email", "send_email": True},
current_user,
)
self.assertEqual(context.exception.status_code, 400) self.assertEqual(context.exception.status_code, 400)
self.assertEqual( self.assertEqual(context.exception.detail, "recipient_email is required and must be a valid email address.")
context.exception.detail,
"recipient_email is required and must be a valid email address.",
)
class MediaReplacementTests(unittest.IsolatedAsyncioTestCase): class MediaReplacementTests(unittest.IsolatedAsyncioTestCase):
+11 -39
View File
@@ -209,7 +209,6 @@ export default function AdminInviteManagementPage() {
const [inviteFlowStep, setInviteFlowStep] = useState(1) const [inviteFlowStep, setInviteFlowStep] = useState(1)
const [useCustomInviteCode, setUseCustomInviteCode] = useState(false) const [useCustomInviteCode, setUseCustomInviteCode] = useState(false)
const [inviteDeliveryMethod, setInviteDeliveryMethod] = useState<InviteDeliveryMethod>('') const [inviteDeliveryMethod, setInviteDeliveryMethod] = useState<InviteDeliveryMethod>('')
const [createdInvite, setCreatedInvite] = useState<Invite | null>(null)
const [inviteSummary, setInviteSummary] = useState<InviteSummary | null>(null) const [inviteSummary, setInviteSummary] = useState<InviteSummary | null>(null)
const [inviteView, setInviteView] = useState<InviteView>('all') const [inviteView, setInviteView] = useState<InviteView>('all')
@@ -392,7 +391,6 @@ export default function AdminInviteManagementPage() {
setInviteFlowStep(4) setInviteFlowStep(4)
setUseCustomInviteCode(true) setUseCustomInviteCode(true)
setInviteDeliveryMethod(invite.recipient_email ? 'email' : 'manual') setInviteDeliveryMethod(invite.recipient_email ? 'email' : 'manual')
setCreatedInvite(null)
setStatus(null) setStatus(null)
setError(null) setError(null)
} }
@@ -449,8 +447,6 @@ export default function AdminInviteManagementPage() {
throw new Error(text || 'Save failed') throw new Error(text || 'Save failed')
} }
const data = await response.json() const data = await response.json()
const savedInvite = (data?.invite ?? null) as Invite | null
setCreatedInvite(savedInvite)
resetInviteEditor() resetInviteEditor()
if (data?.email?.status === 'ok') { if (data?.email?.status === 'ok') {
setStatus( setStatus(
@@ -912,9 +908,6 @@ export default function AdminInviteManagementPage() {
const inviteIdentityReady = Boolean( const inviteIdentityReady = Boolean(
inviteForm.label.trim() && (!useCustomInviteCode || inviteCodeCharacters.length >= 6) inviteForm.label.trim() && (!useCustomInviteCode || inviteCodeCharacters.length >= 6)
) )
const createdInviteUrl = createdInvite
? `${signupBaseUrl}?code=${encodeURIComponent(createdInvite.code)}`
: ''
const inviteAttentionCount = inviteSummary?.attention ?? invites.filter((invite) => !isInviteOperationallyReady(invite)).length const inviteAttentionCount = inviteSummary?.attention ?? invites.filter((invite) => !isInviteOperationallyReady(invite)).length
const filteredInvites = useMemo(() => { const filteredInvites = useMemo(() => {
if (inviteView === 'ready') return invites.filter(isInviteOperationallyReady) if (inviteView === 'ready') return invites.filter(isInviteOperationallyReady)
@@ -1281,13 +1274,9 @@ export default function AdminInviteManagementPage() {
<button <button
type="button" type="button"
className="ghost-button" className="ghost-button"
onClick={() => { onClick={() => router.push('/profile/invites')}
setCreatedInvite(null)
resetInviteEditor()
setActiveTab('invites')
}}
> >
New invite Create invite
</button> </button>
<button <button
type="button" type="button"
@@ -1694,37 +1683,20 @@ export default function AdminInviteManagementPage() {
<div className="admin-panel invite-admin-form-panel"> <div className="admin-panel invite-admin-form-panel">
<div className="invite-flow-heading"> <div className="invite-flow-heading">
<div> <div>
<span className="eyebrow">Invite flow</span> <span className="eyebrow">Invite operations</span>
<h2>{inviteEditingId == null ? 'Create an invite' : `Edit ${inviteForm.label || 'invite'}`}</h2> <h2>{inviteEditingId == null ? 'Client invite workspace' : `Edit ${inviteForm.label || 'invite'}`}</h2>
<p className="lede">Set up the invite one decision at a time.</p> <p className="lede">Creation is client-facing. Admins can still maintain existing invites here.</p>
</div> </div>
{inviteEditingId != null && ( {inviteEditingId != null && (
<button type="button" className="ghost-button" onClick={resetInviteEditor}>Cancel edit</button> <button type="button" className="ghost-button" onClick={resetInviteEditor}>Cancel edit</button>
)} )}
</div> </div>
{createdInvite && inviteEditingId == null ? ( {inviteEditingId == null ? (
<div className="invite-created-card" role="status"> <div className="invite-created-card">
<span className="eyebrow">Invite ready</span> <span className="eyebrow">Option 04 · Invites</span>
<h3>{createdInvite.label || 'Your invite'}</h3> <h3>Create invites from the client workspace</h3>
<p> <p>The guided invite flow now lives in the main navigation where users can create and manage their own invitations.</p>
{createdInvite.recipient_email <button type="button" onClick={() => router.push('/profile/invites')}>Open client invite workspace</button>
? `The invitation was emailed to ${createdInvite.recipient_email}. You can also copy the link below.`
: '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)
resetInviteEditor()
}}
>
Create another invite
</button>
</div> </div>
) : ( ) : (
<form onSubmit={saveInvite} className="invite-flow-form"> <form onSubmit={saveInvite} className="invite-flow-form">
+160 -452
View File
@@ -4,134 +4,72 @@ import { useRouter } from 'next/navigation'
import { useEffect, useMemo, useState } from 'react' import { useEffect, useMemo, useState } from 'react'
import { authFetch, clearToken, getApiBase, getToken } from '../../lib/auth' import { authFetch, clearToken, getApiBase, getToken } from '../../lib/auth'
type ProfileInfo = { type ProfileInfo = { username: string; role: string; invite_management_enabled?: boolean }
username: string
role: string
auth_provider: string
invite_management_enabled?: boolean
}
type ProfileResponse = {
user: ProfileInfo
}
type OwnedInvite = { type OwnedInvite = {
id: number id: number; code: string; label?: string | null; description?: string | null
code: string recipient_email?: string | null; max_uses?: number | null; use_count: number
label?: string | null remaining_uses?: number | null; enabled: boolean; expires_at?: string | null
description?: string | null is_usable?: boolean; created_at?: string | null
recipient_email?: string | null
max_uses?: number | null
use_count: number
remaining_uses?: number | null
enabled: boolean
expires_at?: string | null
is_expired?: boolean
is_usable?: boolean
created_at?: string | null
updated_at?: string | null
} }
type OwnedInvitesResponse = { type OwnedInvitesResponse = {
invites?: OwnedInvite[] invites?: OwnedInvite[]
count?: number invite_access?: { enabled?: boolean; managed_by_master?: boolean }
invite_access?: { master_invite?: { id: number; code: string; label?: string | null; max_uses?: number | null; expires_at?: string | null } | null
enabled?: boolean
managed_by_master?: boolean
} }
master_invite?: { type InviteForm = {
id: number code: string; label: string; description: string; recipient_email: string
code: string enabled: boolean; message: string
label?: string | null
description?: string | null
max_uses?: number | null
enabled?: boolean
expires_at?: string | null
is_usable?: boolean
} | null
} }
type DeliveryMethod = '' | 'manual' | 'email'
type OwnedInviteForm = { const defaultInviteForm = (): InviteForm => ({
code: string code: '', label: '', description: '', recipient_email: '', enabled: true, message: '',
label: string
description: string
recipient_email: string
max_uses: string
expires_at: string
enabled: boolean
send_email: boolean
message: string
}
const defaultOwnedInviteForm = (): OwnedInviteForm => ({
code: '',
label: '',
description: '',
recipient_email: '',
max_uses: '',
expires_at: '',
enabled: true,
send_email: false,
message: '',
}) })
const formatDate = (value?: string | null) => { const formatDate = (value?: string | null) => {
if (!value) return 'Never' if (!value) return 'Never'
const date = new Date(value) const date = new Date(value)
if (Number.isNaN(date.valueOf())) return value return Number.isNaN(date.valueOf()) ? value : date.toLocaleString()
return date.toLocaleString()
} }
const isValidEmail = (value: string) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value.trim()) const isValidEmail = (value: string) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value.trim())
export default function ProfileInvitesPage() { export default function ProfileInvitesPage() {
const router = useRouter() const router = useRouter()
const [profile, setProfile] = useState<ProfileInfo | null>(null) const [profile, setProfile] = useState<ProfileInfo | null>(null)
const [inviteStatus, setInviteStatus] = useState<string | null>(null)
const [inviteError, setInviteError] = useState<string | null>(null)
const [invites, setInvites] = useState<OwnedInvite[]>([]) const [invites, setInvites] = useState<OwnedInvite[]>([])
const [inviteSaving, setInviteSaving] = useState(false)
const [inviteEditingId, setInviteEditingId] = useState<number | null>(null)
const [inviteForm, setInviteForm] = useState<OwnedInviteForm>(defaultOwnedInviteForm())
const [inviteAccessEnabled, setInviteAccessEnabled] = useState(false) const [inviteAccessEnabled, setInviteAccessEnabled] = useState(false)
const [inviteManagedByMaster, setInviteManagedByMaster] = useState(false) const [inviteManagedByMaster, setInviteManagedByMaster] = useState(false)
const [masterInviteTemplate, setMasterInviteTemplate] = useState<OwnedInvitesResponse['master_invite']>(null) const [masterInvite, setMasterInvite] = useState<OwnedInvitesResponse['master_invite']>(null)
const [loading, setLoading] = useState(true) 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(() => { const signupBaseUrl = useMemo(() => {
if (typeof window === 'undefined') return '/signup' if (typeof window === 'undefined') return '/signup'
return `${window.location.origin}/signup` return `${window.location.origin}/signup`
}, []) }, [])
const loadPage = async () => { const loadInvites = async () => {
const baseUrl = getApiBase() const response = await authFetch(`${getApiBase()}/auth/profile/invites`)
const [profileResponse, invitesResponse] = await Promise.all([ if (!response.ok) {
authFetch(`${baseUrl}/auth/profile`), if (response.status === 401) {
authFetch(`${baseUrl}/auth/profile/invites`),
])
if (!profileResponse.ok || !invitesResponse.ok) {
if (profileResponse.status === 401 || invitesResponse.status === 401) {
clearToken() clearToken()
router.push('/login') router.push('/login')
return return
} }
throw new Error('Could not load invite tools.') throw new Error('Could not load your invite workspace.')
} }
const [profileData, inviteData] = (await Promise.all([ const data = (await response.json()) as OwnedInvitesResponse
profileResponse.json(), setInvites(Array.isArray(data.invites) ? data.invites : [])
invitesResponse.json(), setInviteAccessEnabled(Boolean(data.invite_access?.enabled))
])) as [ProfileResponse, OwnedInvitesResponse] setInviteManagedByMaster(Boolean(data.invite_access?.managed_by_master))
const user = profileData?.user ?? {} setMasterInvite(data.master_invite ?? null)
setProfile({
username: user?.username ?? 'Unknown',
role: user?.role ?? 'user',
auth_provider: user?.auth_provider ?? 'local',
invite_management_enabled: Boolean(user?.invite_management_enabled ?? false),
})
setInvites(Array.isArray(inviteData?.invites) ? inviteData.invites : [])
setInviteAccessEnabled(Boolean(inviteData?.invite_access?.enabled ?? false))
setInviteManagedByMaster(Boolean(inviteData?.invite_access?.managed_by_master ?? false))
setMasterInviteTemplate(inviteData?.master_invite ?? null)
} }
useEffect(() => { useEffect(() => {
@@ -141,10 +79,21 @@ export default function ProfileInvitesPage() {
} }
const load = async () => { const load = async () => {
try { try {
await loadPage() 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) { } catch (err) {
console.error(err) console.error(err)
setInviteError(err instanceof Error ? err.message : 'Could not load invite tools.') setError(err instanceof Error ? err.message : 'Could not load your invite workspace.')
} finally { } finally {
setLoading(false) setLoading(false)
} }
@@ -152,80 +101,65 @@ export default function ProfileInvitesPage() {
void load() void load()
}, [router]) }, [router])
const resetInviteEditor = () => { const resetFlow = () => {
setInviteEditingId(null) setEditingId(null)
setInviteForm(defaultOwnedInviteForm()) setFlowStep(1)
setUseCustomCode(false)
setDeliveryMethod('')
setInviteForm(defaultInviteForm())
} }
const editInvite = (invite: OwnedInvite) => { const editInvite = (invite: OwnedInvite) => {
setInviteEditingId(invite.id) setEditingId(invite.id)
setInviteError(null) setCreatedInvite(null)
setInviteStatus(null) setFlowStep(4)
setUseCustomCode(true)
setDeliveryMethod(invite.recipient_email ? 'email' : 'manual')
setInviteForm({ setInviteForm({
code: invite.code ?? '', code: invite.code,
label: invite.label ?? '', label: invite.label ?? '',
description: invite.description ?? '', description: invite.description ?? '',
recipient_email: invite.recipient_email ?? '', recipient_email: invite.recipient_email ?? '',
max_uses: typeof invite.max_uses === 'number' ? String(invite.max_uses) : '',
expires_at: invite.expires_at ?? '',
enabled: invite.enabled !== false, enabled: invite.enabled !== false,
send_email: false,
message: '', message: '',
}) })
} setError(null)
setStatus(null)
const reloadInvites = async () => { window.scrollTo({ top: 0, behavior: 'smooth' })
const baseUrl = getApiBase()
const response = await authFetch(`${baseUrl}/auth/profile/invites`)
if (!response.ok) {
if (response.status === 401) {
clearToken()
router.push('/login')
return
}
throw new Error(`Invite refresh failed: ${response.status}`)
}
const data = (await response.json()) as OwnedInvitesResponse
setInvites(Array.isArray(data?.invites) ? data.invites : [])
setInviteAccessEnabled(Boolean(data?.invite_access?.enabled ?? false))
setInviteManagedByMaster(Boolean(data?.invite_access?.managed_by_master ?? false))
setMasterInviteTemplate(data?.master_invite ?? null)
} }
const saveInvite = async (event: React.FormEvent) => { const saveInvite = async (event: React.FormEvent) => {
event.preventDefault() event.preventDefault()
const inviteName = inviteForm.label.trim()
const recipientEmail = inviteForm.recipient_email.trim() const recipientEmail = inviteForm.recipient_email.trim()
if (!recipientEmail) { if (!inviteName) {
setInviteError('Recipient email is required.') setError('Give this invite a name so you can recognise it later.')
setInviteStatus(null)
return return
} }
if (!isValidEmail(recipientEmail)) { if (!deliveryMethod) {
setInviteError('Recipient email must be valid.') setError('Choose how you want to deliver the invite.')
setInviteStatus(null)
return return
} }
setInviteSaving(true) if (deliveryMethod === 'email' && !isValidEmail(recipientEmail)) {
setInviteError(null) setError('Enter a valid recipient email address.')
setInviteStatus(null) return
}
setSaving(true)
setError(null)
setStatus(null)
try { try {
const baseUrl = getApiBase()
const response = await authFetch( const response = await authFetch(
inviteEditingId == null editingId == null ? `${getApiBase()}/auth/profile/invites` : `${getApiBase()}/auth/profile/invites/${editingId}`,
? `${baseUrl}/auth/profile/invites`
: `${baseUrl}/auth/profile/invites/${inviteEditingId}`,
{ {
method: inviteEditingId == null ? 'POST' : 'PUT', method: editingId == null ? 'POST' : 'PUT',
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ body: JSON.stringify({
code: inviteForm.code || null, code: useCustomCode ? inviteForm.code || null : null,
label: inviteForm.label || null, label: inviteName,
description: inviteForm.description || null, description: inviteForm.description || null,
recipient_email: recipientEmail, recipient_email: deliveryMethod === 'email' ? recipientEmail : null,
max_uses: inviteForm.max_uses || null,
expires_at: inviteForm.expires_at || null,
enabled: inviteForm.enabled, enabled: inviteForm.enabled,
send_email: inviteForm.send_email, send_email: editingId == null && deliveryMethod === 'email',
message: inviteForm.message || null, message: inviteForm.message || null,
}), }),
} }
@@ -236,362 +170,136 @@ export default function ProfileInvitesPage() {
router.push('/login') router.push('/login')
return return
} }
const text = await response.text() throw new Error((await response.text()) || 'Could not save the invite.')
throw new Error(text || 'Invite save failed')
} }
const data = await response.json().catch(() => ({})) const data = await response.json()
if (data?.email?.status === 'ok') { const savedInvite = data?.invite as OwnedInvite | undefined
setInviteStatus( setStatus(
`${inviteEditingId == null ? 'Invite created' : 'Invite updated'} and email sent to ${data.email.recipient_email}.` 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.'
) )
} else if (data?.email?.status === 'error') { resetFlow()
setInviteStatus( if (editingId == null && savedInvite) setCreatedInvite(savedInvite)
`${inviteEditingId == null ? 'Invite created' : 'Invite updated'}, but email failed: ${data.email.detail}` await loadInvites()
)
} else {
setInviteStatus(inviteEditingId == null ? 'Invite created.' : 'Invite updated.')
}
resetInviteEditor()
await reloadInvites()
} catch (err) { } catch (err) {
console.error(err) console.error(err)
setInviteError(err instanceof Error ? err.message : 'Could not save invite.') setError(err instanceof Error ? err.message : 'Could not save the invite.')
} finally { } finally {
setInviteSaving(false) setSaving(false)
} }
} }
const deleteInvite = async (invite: OwnedInvite) => { const deleteInvite = async (invite: OwnedInvite) => {
if (!window.confirm(`Delete invite "${invite.code}"?`)) return if (!window.confirm(`Delete invite ${invite.label || invite.code}?`)) return
setInviteError(null) setError(null)
setInviteStatus(null)
try { try {
const baseUrl = getApiBase() const response = await authFetch(`${getApiBase()}/auth/profile/invites/${invite.id}`, { method: 'DELETE' })
const response = await authFetch(`${baseUrl}/auth/profile/invites/${invite.id}`, { if (!response.ok) throw new Error((await response.text()) || 'Could not delete the invite.')
method: 'DELETE', if (editingId === invite.id) resetFlow()
}) setStatus(`Deleted ${invite.label || invite.code}.`)
if (!response.ok) { await loadInvites()
if (response.status === 401) {
clearToken()
router.push('/login')
return
}
const text = await response.text()
throw new Error(text || 'Invite delete failed')
}
if (inviteEditingId === invite.id) {
resetInviteEditor()
}
setInviteStatus(`Deleted invite ${invite.code}.`)
await reloadInvites()
} catch (err) { } catch (err) {
console.error(err) console.error(err)
setInviteError(err instanceof Error ? err.message : 'Could not delete invite.') setError(err instanceof Error ? err.message : 'Could not delete the invite.')
} }
} }
const copyInviteLink = async (invite: OwnedInvite) => { const copyInviteLink = async (invite: OwnedInvite) => {
const url = `${signupBaseUrl}?code=${encodeURIComponent(invite.code)}` const url = `${signupBaseUrl}?code=${encodeURIComponent(invite.code)}`
try { try {
if (navigator.clipboard?.writeText) {
await navigator.clipboard.writeText(url) await navigator.clipboard.writeText(url)
setInviteStatus(`Copied invite link for ${invite.code}.`) setStatus(`Copied the link for ${invite.label || invite.code}.`)
} else { } catch {
window.prompt('Copy invite link', url)
}
} catch (err) {
console.error(err)
window.prompt('Copy invite link', url) 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 canManageInvites = profile?.role === 'admin' || inviteAccessEnabled
const createdInviteUrl = createdInvite ? `${signupBaseUrl}?code=${encodeURIComponent(createdInvite.code)}` : ''
if (loading) { if (loading) return <main className="card">Loading invite workspace</main>
return <main className="card">Loading invite tools...</main>
}
return ( return (
<main className="card"> <main className="card">
<div className="user-directory-panel-header profile-page-header"> <div className="user-directory-panel-header profile-page-header">
<div> <div>
<h1>Invites</h1> <span className="section-kicker">04 · Invites</span>
<p className="lede">Create invite links, email them directly, and track who you have invited.</p> <h1>Invite someone to Grizzlyflix</h1>
<p className="lede">Create a secure invitation one simple decision at a time.</p>
</div> </div>
</div> </div>
{error && <div className="error-banner">{error}</div>}
{inviteError && <div className="error-banner">{inviteError}</div>} {status && <div className="status-banner">{status}</div>}
{inviteStatus && <div className="status-banner">{inviteStatus}</div>}
{!canManageInvites ? ( {!canManageInvites ? (
<section className="profile-section profile-tab-panel"> <section className="profile-section profile-tab-panel">
<h2>Invite access is disabled</h2> <h2>Invites are not enabled for your account</h2>
<p className="lede"> <p className="lede">Ask an administrator if you need permission to invite someone.</p>
Your account is not currently allowed to create self-service invites. Ask an administrator to enable invite access for your profile.
</p>
<div className="admin-inline-actions">
<button type="button" onClick={() => router.push('/profile')}>
Return to profile
</button>
</div>
</section> </section>
) : ( ) : (
<section className="profile-section profile-invites-section profile-tab-panel"> <section className="profile-section profile-invites-section profile-tab-panel">
<div className="user-directory-panel-header"> <div className="invite-flow-heading">
<div> <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>
<h2>Invite workspace</h2> {editingId != null && <button type="button" className="ghost-button" onClick={resetFlow}>Cancel edit</button>}
<p className="lede">
{inviteManagedByMaster
? 'Create and manage invite links you have issued. New invites use the admin master invite rule.'
: 'Create and manage invite links you have issued. New invites use your account defaults.'}
</p>
</div>
</div> </div>
<div className="profile-invites-layout"> {createdInvite && editingId == null ? (
<div className="profile-invite-form-card"> <div className="invite-created-card" role="status">
<h3>{inviteEditingId == null ? 'Create invite' : 'Edit invite'}</h3> <span className="eyebrow">Invite ready</span><h3>{createdInvite.label || 'Your invite'}</h3>
<p className="meta profile-invite-form-lede"> <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>
Save a recipient email, send the invite immediately, and keep the generated link ready to copy. <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>
</p> <button type="button" className="ghost-button" onClick={() => { setCreatedInvite(null); resetFlow() }}>Create another invite</button>
{inviteManagedByMaster && masterInviteTemplate ? (
<div className="status-banner profile-invite-master-banner">
Using master invite rule <code>{masterInviteTemplate.code}</code>
{masterInviteTemplate.label ? ` (${masterInviteTemplate.label})` : ''}. Limits and status are managed by admin.
</div>
) : null}
<form onSubmit={saveInvite} className="admin-form compact-form invite-form-layout profile-form-layout">
<div className="invite-form-row">
<div className="invite-form-row-label">
<span>Identity</span>
<small>Optional code and label for easier tracking.</small>
</div>
<div className="invite-form-row-control invite-form-row-grid">
<label>
<span>Code (optional)</span>
<input
value={inviteForm.code}
onChange={(event) =>
setInviteForm((current) => ({ ...current, code: event.target.value }))
}
placeholder="Leave blank to auto-generate"
/>
</label>
<label>
<span>Label</span>
<input
value={inviteForm.label}
onChange={(event) =>
setInviteForm((current) => ({ ...current, label: event.target.value }))
}
placeholder="Family invite"
/>
</label>
</div>
</div> </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>
<div className="invite-form-row"> <section className={`invite-flow-step ${flowStep > 1 ? 'is-complete' : 'is-active'}`}>
<div className="invite-form-row-label"> <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>
<span>Description</span> <div className="invite-flow-fields">
<small>Optional note shown on the signup page.</small> <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>
</div> <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>
<div className="invite-form-row-control"> {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>}
<textarea {flowStep === 1 && <div className="invite-flow-actions"><button type="button" disabled={!identityReady} onClick={() => setFlowStep(2)}>Continue to description</button></div>}
rows={3}
value={inviteForm.description}
onChange={(event) =>
setInviteForm((current) => ({
...current,
description: event.target.value,
}))
}
placeholder="Optional note shown on the signup page"
/>
</div>
</div> </div>
</section>
<div className="invite-form-row"> {flowStep >= 2 && <section className={`invite-flow-step ${flowStep > 2 ? 'is-complete' : 'is-active'}`}>
<div className="invite-form-row-label"> <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>
<span>Delivery</span> <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>
<small>Recipient email is required. You can also send the invite immediately after saving.</small> </section>}
</div>
<div className="invite-form-row-control invite-form-row-control--stacked">
<label>
<span>Recipient email (required)</span>
<input
type="email"
required
value={inviteForm.recipient_email}
onChange={(event) =>
setInviteForm((current) => ({
...current,
recipient_email: event.target.value,
}))
}
placeholder="Required recipient email"
/>
</label>
<label>
<span>Delivery note</span>
<textarea
rows={3}
value={inviteForm.message}
onChange={(event) =>
setInviteForm((current) => ({
...current,
message: event.target.value,
}))
}
placeholder="Optional note to include in the email"
/>
</label>
<label className="inline-checkbox">
<input
type="checkbox"
checked={inviteForm.send_email}
onChange={(event) =>
setInviteForm((current) => ({
...current,
send_email: event.target.checked,
}))
}
/>
Send "You have been invited" email after saving
</label>
</div>
</div>
<div className="invite-form-row"> {flowStep >= 3 && <section className={`invite-flow-step ${flowStep > 3 ? 'is-complete' : 'is-active'}`}>
<div className="invite-form-row-label"> <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>
<span>Limits</span> <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>
<small>Usage cap and optional expiry date/time.</small> </section>}
</div>
<div className="invite-form-row-control invite-form-row-grid">
<label>
<span>Max uses</span>
<input
value={inviteForm.max_uses}
onChange={(event) =>
setInviteForm((current) => ({ ...current, max_uses: event.target.value }))
}
inputMode="numeric"
placeholder="Blank = unlimited"
disabled={inviteManagedByMaster}
/>
</label>
<label>
<span>Invite expiry (ISO datetime)</span>
<input
value={inviteForm.expires_at}
onChange={(event) =>
setInviteForm((current) => ({ ...current, expires_at: event.target.value }))
}
placeholder="2026-03-01T12:00:00+00:00"
disabled={inviteManagedByMaster}
/>
</label>
</div>
</div>
<div className="invite-form-row"> {flowStep >= 4 && <section className="invite-flow-step is-active">
<div className="invite-form-row-label"> <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>
<span>Status</span> <div className="invite-flow-fields">
<small>Enable or disable this invite before sharing.</small> <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>
</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>}
<div className="invite-form-row-control invite-form-row-control--stacked"> {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>}
<label className="inline-checkbox"> {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>}
<input <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>
type="checkbox"
checked={inviteForm.enabled}
onChange={(event) =>
setInviteForm((current) => ({
...current,
enabled: event.target.checked,
}))
}
disabled={inviteManagedByMaster}
/>
Invite is enabled
</label>
<div className="admin-inline-actions">
<button type="submit" disabled={inviteSaving}>
{inviteSaving
? 'Saving…'
: inviteEditingId == null
? 'Create invite'
: 'Save invite'}
</button>
{inviteEditingId != null && (
<button type="button" className="ghost-button" onClick={resetInviteEditor}>
Cancel edit
</button>
)}
</div>
</div>
</div> </div>
</section>}
</form> </form>
<div className="meta profile-invite-hint"> )}
Invite URL format: <code>{signupBaseUrl}?code=INVITECODE</code>
</div>
</div>
<div className="profile-invites-list"> <div className="profile-invites-list">
{invites.length === 0 ? ( <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>
<div className="status-banner">You have not created any invites yet.</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 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">
<code className="invite-code">{invite.code}</code>
<span className={`small-pill ${invite.is_usable ? '' : 'is-muted'}`}>
{invite.is_usable ? 'Usable' : 'Unavailable'}
</span>
<span className="small-pill is-muted">
{invite.remaining_uses == null ? 'Unlimited' : `${invite.remaining_uses} left`}
</span>
</div>
{invite.label && <p className="admin-list-item-text">{invite.label}</p>}
{invite.description && (
<p className="admin-list-item-text admin-list-item-text--muted">
{invite.description}
</p>
)}
<div className="admin-meta-row">
<span>Recipient: {invite.recipient_email || 'Not set'}</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={() => copyInviteLink(invite)}
>
Copy link
</button>
<button
type="button"
className="ghost-button"
onClick={() => editInvite(invite)}
>
Edit
</button>
<button type="button" onClick={() => deleteInvite(invite)}>
Delete
</button>
</div>
</div>
))}
</div>
)}
</div>
</div> </div>
</section> </section>
)} )}
-5
View File
@@ -67,11 +67,6 @@ export default function HeaderActions() {
}, },
] ]
: [ : [
{
href: '/profile',
label: 'Profile',
match: (path: string) => path.startsWith('/profile') && !path.startsWith('/profile/invites'),
},
{ {
href: '/profile/invites', href: '/profile/invites',
label: 'Invites', label: 'Invites',