feat: user invites in account panel

This commit is contained in:
2026-08-31 21:08:47 +02:00
parent 73ef2b625d
commit 68991a3722
8 changed files with 711 additions and 4 deletions
+101
View File
@@ -0,0 +1,101 @@
import { describe, it, expect, beforeEach, vi, afterEach } from 'vitest'
import { setActivePinia, createPinia } from 'pinia'
import { getInvitesApi, createInviteApi, deleteInviteApi } from '../invites'
import { useAuthStore } from '@/stores/auth'
import { API_BASE_URL } from '@/api/http'
describe('invites API', () => {
const originalFetch = global.fetch
beforeEach(() => {
setActivePinia(createPinia())
localStorage.clear()
vi.restoreAllMocks()
const authStore = useAuthStore()
authStore.setTokens({ access_token: 'token-123', refresh_token: 'refresh-123' })
})
afterEach(() => {
global.fetch = originalFetch
localStorage.clear()
})
it('getInvitesApi sends GET to /user/invites and returns the invites', async () => {
const mockInvites = [{ id: 'invite-1', code: 'ABC123' }]
const fetchMock = vi.fn<typeof fetch>().mockResolvedValueOnce({
ok: true,
status: 200,
json: async () => mockInvites,
} as unknown as Response)
global.fetch = fetchMock
const result = await getInvitesApi()
expect(fetchMock).toHaveBeenCalledWith(
`${API_BASE_URL}/user/invites`,
expect.objectContaining({ method: 'GET' }),
)
expect(result).toEqual(mockInvites)
})
it('getInvitesApi throws on failure', async () => {
global.fetch = vi.fn<typeof fetch>().mockResolvedValueOnce({
ok: false,
json: async () => ({ message: 'Failed' }),
} as unknown as Response)
await expect(getInvitesApi()).rejects.toThrow('Failed')
})
it('createInviteApi sends POST to /user/invites and returns the created invite', async () => {
const mockInvite = { id: 'invite-1', code: 'ABC123' }
const fetchMock = vi.fn<typeof fetch>().mockResolvedValueOnce({
ok: true,
status: 201,
json: async () => mockInvite,
} as unknown as Response)
global.fetch = fetchMock
const result = await createInviteApi()
expect(fetchMock).toHaveBeenCalledWith(
`${API_BASE_URL}/user/invites`,
expect.objectContaining({ method: 'POST' }),
)
expect(result).toEqual(mockInvite)
})
it('createInviteApi throws on failure', async () => {
global.fetch = vi.fn<typeof fetch>().mockResolvedValueOnce({
ok: false,
json: async () => ({ message: 'Failed to create invite' }),
} as unknown as Response)
await expect(createInviteApi()).rejects.toThrow('Failed to create invite')
})
it('deleteInviteApi sends DELETE to /user/invites/:id', async () => {
const fetchMock = vi.fn<typeof fetch>().mockResolvedValueOnce({
ok: true,
status: 204,
} as unknown as Response)
global.fetch = fetchMock
await deleteInviteApi('invite-1')
expect(fetchMock).toHaveBeenCalledWith(
`${API_BASE_URL}/user/invites/invite-1`,
expect.objectContaining({ method: 'DELETE' }),
)
})
it('deleteInviteApi throws on failure', async () => {
global.fetch = vi.fn<typeof fetch>().mockResolvedValueOnce({
ok: false,
json: async () => ({ message: 'Failed to delete invite' }),
} as unknown as Response)
await expect(deleteInviteApi('invite-1')).rejects.toThrow('Failed to delete invite')
})
})
+26
View File
@@ -0,0 +1,26 @@
import { apiClient } from '@/api/client'
import { extractErrorMessage } from '@/api/http'
import type { Invite } from '@/types/invite'
export async function getInvitesApi(): Promise<Invite[]> {
const response = await apiClient.get('/user/invites')
if (!response.ok) {
throw new Error(await extractErrorMessage(response, 'Failed to load invites'))
}
return response.json()
}
export async function createInviteApi(): Promise<Invite> {
const response = await apiClient.post('/user/invites')
if (!response.ok) {
throw new Error(await extractErrorMessage(response, 'Failed to create invite'))
}
return response.json()
}
export async function deleteInviteApi(id: string): Promise<void> {
const response = await apiClient.delete(`/user/invites/${id}`)
if (!response.ok) {
throw new Error(await extractErrorMessage(response, 'Failed to delete invite'))
}
}
+1 -1
View File
@@ -16,7 +16,7 @@ const listsStore = useListsStore()
listsStore.pendingCount
}}</span>
</RouterLink>
<RouterLink to="/about" class="nav-item" active-class="is-active">
<RouterLink to="/account" class="nav-item" active-class="is-active">
<span class="nav-icon"></span>
<span class="nav-label">Account</span>
</RouterLink>
+441
View File
@@ -0,0 +1,441 @@
<script setup lang="ts">
import { computed, onBeforeUnmount, ref } from 'vue'
import { getInvitesApi, createInviteApi, deleteInviteApi } from '@/api/invites'
import type { Invite } from '@/types/invite'
type InviteStatus = 'active' | 'used' | 'expired'
const expanded = ref(false)
const invites = ref<Invite[]>([])
const isLoading = ref(false)
const isCreating = ref(false)
const error = ref('')
const pendingDeleteId = ref<string | null>(null)
const deletingId = ref<string | null>(null)
const copiedId = ref<string | null>(null)
let hasLoaded = false
let copiedTimeout: ReturnType<typeof setTimeout> | undefined
const activeCount = computed(
() => invites.value.filter((invite) => inviteStatus(invite) === 'active').length,
)
onBeforeUnmount(() => {
clearTimeout(copiedTimeout)
})
function isOffline(): boolean {
return typeof navigator !== 'undefined' && !navigator.onLine
}
async function toggleExpanded() {
expanded.value = !expanded.value
if (expanded.value && !hasLoaded) {
await loadInvites()
}
}
async function loadInvites() {
error.value = ''
if (isOffline()) {
error.value = 'You must be online to manage invites.'
return
}
isLoading.value = true
try {
invites.value = await getInvitesApi()
hasLoaded = true
} catch (err) {
error.value = err instanceof Error ? err.message : 'Failed to load invites'
} finally {
isLoading.value = false
}
}
async function handleCreate() {
error.value = ''
if (isOffline()) {
error.value = 'You must be online to create an invite.'
return
}
isCreating.value = true
try {
const invite = await createInviteApi()
invites.value = [invite, ...invites.value]
hasLoaded = true
} catch (err) {
error.value = err instanceof Error ? err.message : 'Failed to create invite'
} finally {
isCreating.value = false
}
}
function requestDelete(id: string) {
error.value = ''
pendingDeleteId.value = id
}
function cancelDelete() {
pendingDeleteId.value = null
}
async function confirmDelete(id: string) {
error.value = ''
if (isOffline()) {
error.value = 'You must be online to delete an invite.'
pendingDeleteId.value = null
return
}
deletingId.value = id
try {
await deleteInviteApi(id)
invites.value = invites.value.filter((invite) => invite.id !== id)
} catch (err) {
error.value = err instanceof Error ? err.message : 'Failed to delete invite'
} finally {
deletingId.value = null
pendingDeleteId.value = null
}
}
async function copyCode(invite: Invite) {
try {
await navigator.clipboard.writeText(invite.code)
copiedId.value = invite.id
clearTimeout(copiedTimeout)
copiedTimeout = setTimeout(() => {
copiedId.value = null
}, 1500)
} catch {
// Clipboard access denied or unavailable; nothing sensible to do.
}
}
function inviteStatus(invite: Invite): InviteStatus {
if (invite.consumed_at) return 'used'
if (invite.expires_at && new Date(invite.expires_at).getTime() < Date.now()) return 'expired'
return 'active'
}
function statusLabel(invite: Invite): string {
const status = inviteStatus(invite)
return status === 'used' ? 'Used' : status === 'expired' ? 'Expired' : 'Active'
}
// Standard "time ago"/"time until" formatter: walk unit divisions until the
// duration fits in one, so both past and future dates read naturally.
function formatRelative(dateStr: string): string {
const divisions: [number, Intl.RelativeTimeFormatUnit][] = [
[60, 'seconds'],
[60, 'minutes'],
[24, 'hours'],
[7, 'days'],
[4.34524, 'weeks'],
[12, 'months'],
[Number.POSITIVE_INFINITY, 'years'],
]
const rtf = new Intl.RelativeTimeFormat('en', { numeric: 'auto' })
let duration = (new Date(dateStr).getTime() - Date.now()) / 1000
for (const [amount, unit] of divisions) {
if (Math.abs(duration) < amount) {
return rtf.format(Math.round(duration), unit)
}
duration /= amount
}
return rtf.format(Math.round(duration), 'years')
}
function inviteDetail(invite: Invite): string {
const status = inviteStatus(invite)
if (status === 'used') {
return invite.consumed_at ? `Used ${formatRelative(invite.consumed_at)}` : 'Used'
}
if (!invite.expires_at) {
return 'No expiry'
}
return `${status === 'expired' ? 'Expired' : 'Expires'} ${formatRelative(invite.expires_at)}`
}
</script>
<template>
<section class="card info-card invites-card">
<button
type="button"
class="invites-toggle"
:aria-expanded="expanded"
aria-controls="invites-panel"
@click="toggleExpanded"
>
<span class="invites-toggle-label">
<h4>Invites</h4>
<span v-if="activeCount > 0" class="invites-count-badge">{{ activeCount }} active</span>
</span>
<span class="chevron" :class="{ 'is-open': expanded }" aria-hidden="true"></span>
</button>
<div v-if="expanded" id="invites-panel" class="invites-body">
<p class="invites-hint">
Invite codes let someone new create an account. Creating, listing, and deleting invites
requires an internet connection.
</p>
<p v-if="isLoading" class="invites-loading">Loading invites</p>
<ul v-else-if="invites.length > 0" class="invite-list">
<li
v-for="invite in invites"
:key="invite.id"
class="invite-ticket"
:class="`is-${inviteStatus(invite)}`"
>
<div class="invite-ticket-main">
<code class="invite-code">{{ invite.code }}</code>
<span class="invite-status-pill" :class="`pill-${inviteStatus(invite)}`">{{
statusLabel(invite)
}}</span>
</div>
<div class="invite-ticket-meta">
<span class="invite-detail">{{ inviteDetail(invite) }}</span>
<div v-if="pendingDeleteId !== invite.id" class="invite-actions">
<button type="button" class="ticket-btn" @click="copyCode(invite)">
{{ copiedId === invite.id ? 'Copied!' : 'Copy' }}
</button>
<button
type="button"
class="ticket-btn ticket-btn-danger"
:disabled="inviteStatus(invite) === 'used'"
:title="inviteStatus(invite) === 'used' ? 'Used invites cannot be deleted' : ''"
@click="requestDelete(invite.id)"
>
Delete
</button>
</div>
<div v-else class="invite-actions">
<span class="confirm-label">Delete this invite?</span>
<button type="button" class="ticket-btn" @click="cancelDelete">No</button>
<button
type="button"
class="ticket-btn ticket-btn-danger"
:disabled="deletingId === invite.id"
@click="confirmDelete(invite.id)"
>
{{ deletingId === invite.id ? 'Deleting…' : 'Yes' }}
</button>
</div>
</div>
</li>
</ul>
<p v-else class="invites-empty">No invites yet. Generate one to invite someone.</p>
<p v-if="error" class="banner banner-error">{{ error }}</p>
<button
type="button"
class="btn btn-primary generate-btn"
:disabled="isCreating"
@click="handleCreate"
>
{{ isCreating ? 'Generating…' : '+ Generate invite' }}
</button>
</div>
</section>
</template>
<style scoped>
.invites-toggle {
display: flex;
align-items: center;
justify-content: space-between;
width: 100%;
background: none;
border: none;
padding: 0;
color: inherit;
cursor: pointer;
text-align: left;
}
.invites-toggle-label {
display: flex;
align-items: center;
gap: 0.5rem;
}
.invites-toggle-label h4 {
font-size: 0.85rem;
margin: 0;
}
.invites-count-badge {
font-size: 0.65rem;
font-weight: 600;
padding: 0.15rem 0.5rem;
border-radius: 999px;
background-color: var(--c-accent-bg);
color: var(--c-accent-strong);
}
.chevron {
color: var(--c-text-soft);
transition: transform 0.15s ease-in-out;
}
.chevron.is-open {
transform: rotate(180deg);
}
.invites-body {
display: flex;
flex-direction: column;
gap: 0.75rem;
margin-top: 0.85rem;
}
.invites-hint {
font-size: 0.8rem;
color: var(--c-text-soft);
margin: 0;
}
.invites-loading,
.invites-empty {
font-size: 0.85rem;
color: var(--c-text-soft);
margin: 0;
}
.invite-list {
list-style: none;
display: flex;
flex-direction: column;
gap: 0.6rem;
}
.invite-ticket {
border: 1px solid var(--c-border);
border-left: 3px solid var(--c-text-soft);
border-radius: var(--radius-md);
background-color: var(--c-bg-mute);
padding: 0.65rem 0.85rem;
}
.invite-ticket.is-active {
border-left-color: var(--c-success);
}
.invite-ticket.is-expired {
border-left-color: var(--c-danger);
}
.invite-ticket.is-used {
border-left-color: var(--c-text-soft);
opacity: 0.75;
}
.invite-ticket-main {
display: flex;
align-items: center;
justify-content: space-between;
gap: 0.5rem;
}
.invite-code {
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 0.95rem;
letter-spacing: 0.06em;
color: var(--c-heading);
}
.invite-status-pill {
flex-shrink: 0;
font-size: 0.65rem;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.04em;
padding: 0.15rem 0.5rem;
border-radius: 999px;
}
.pill-active {
background-color: rgba(52, 211, 153, 0.14);
color: var(--c-success);
}
.pill-expired {
background-color: var(--c-danger-bg);
color: var(--c-danger);
}
.pill-used {
background-color: var(--c-bg-elevated);
color: var(--c-text-soft);
}
.invite-ticket-meta {
display: flex;
align-items: center;
justify-content: space-between;
gap: 0.5rem;
border-top: 1px dashed var(--c-border);
margin-top: 0.55rem;
padding-top: 0.5rem;
}
.invite-detail {
font-size: 0.75rem;
color: var(--c-text-soft);
}
.invite-actions {
display: flex;
align-items: center;
gap: 0.4rem;
}
.confirm-label {
font-size: 0.75rem;
color: var(--c-text-soft);
}
.ticket-btn {
background: none;
border: 1px solid var(--c-border);
color: var(--c-text);
font-size: 0.72rem;
padding: 0.25rem 0.55rem;
border-radius: var(--radius-sm);
cursor: pointer;
}
.ticket-btn:hover:not(:disabled) {
border-color: var(--c-border-hover);
color: var(--c-heading);
}
.ticket-btn:disabled {
opacity: 0.45;
cursor: not-allowed;
}
.ticket-btn-danger {
color: var(--c-danger);
border-color: rgba(248, 113, 113, 0.35);
}
.ticket-btn-danger:hover:not(:disabled) {
background-color: var(--c-danger-bg);
}
.generate-btn {
width: auto;
align-self: flex-start;
padding: 0.55rem 1.1rem;
}
</style>
@@ -0,0 +1,130 @@
import { describe, it, expect, beforeEach, vi } from 'vitest'
import { mount } from '@vue/test-utils'
import InvitesPanel from '../InvitesPanel.vue'
import * as invitesApi from '@/api/invites'
import type { Invite } from '@/types/invite'
describe('InvitesPanel', () => {
beforeEach(() => {
vi.restoreAllMocks()
Object.defineProperty(navigator, 'onLine', { value: true, configurable: true })
})
it('renders collapsed by default without loading invites', () => {
const getSpy = vi.spyOn(invitesApi, 'getInvitesApi')
const wrapper = mount(InvitesPanel)
expect(wrapper.text()).toContain('Invites')
expect(wrapper.find('#invites-panel').exists()).toBe(false)
expect(getSpy).not.toHaveBeenCalled()
})
it('loads and displays invites on expand', async () => {
const mockInvites: Invite[] = [
{ id: 'invite-1', code: 'ABC123', expires_at: '2099-01-01T00:00:00.000Z' },
{
id: 'invite-2',
code: 'USEDCODE',
expires_at: '2099-01-01T00:00:00.000Z',
consumed_at: '2026-01-01T00:00:00.000Z',
},
]
vi.spyOn(invitesApi, 'getInvitesApi').mockResolvedValueOnce(mockInvites)
const wrapper = mount(InvitesPanel)
await wrapper.find('.invites-toggle').trigger('click')
await flushPromises()
expect(wrapper.text()).toContain('ABC123')
expect(wrapper.text()).toContain('USEDCODE')
expect(wrapper.text()).toContain('Active')
expect(wrapper.text()).toContain('Used')
})
it('shows an offline message instead of fetching when expanded offline', async () => {
Object.defineProperty(navigator, 'onLine', { value: false, configurable: true })
const getSpy = vi.spyOn(invitesApi, 'getInvitesApi')
const wrapper = mount(InvitesPanel)
await wrapper.find('.invites-toggle').trigger('click')
expect(getSpy).not.toHaveBeenCalled()
expect(wrapper.find('.banner-error').text()).toContain('must be online')
})
it('shows empty state when there are no invites', async () => {
vi.spyOn(invitesApi, 'getInvitesApi').mockResolvedValueOnce([])
const wrapper = mount(InvitesPanel)
await wrapper.find('.invites-toggle').trigger('click')
await flushPromises()
expect(wrapper.text()).toContain('No invites yet')
})
it('generates a new invite and prepends it to the list', async () => {
vi.spyOn(invitesApi, 'getInvitesApi').mockResolvedValueOnce([])
const newInvite: Invite = { id: 'invite-new', code: 'NEWCODE1' }
vi.spyOn(invitesApi, 'createInviteApi').mockResolvedValueOnce(newInvite)
const wrapper = mount(InvitesPanel)
await wrapper.find('.invites-toggle').trigger('click')
await flushPromises()
await wrapper.find('.generate-btn').trigger('click')
await flushPromises()
expect(wrapper.text()).toContain('NEWCODE1')
})
it('deletes an invite after confirming', async () => {
const mockInvite: Invite = { id: 'invite-1', code: 'ABC123' }
vi.spyOn(invitesApi, 'getInvitesApi').mockResolvedValueOnce([mockInvite])
const deleteSpy = vi.spyOn(invitesApi, 'deleteInviteApi').mockResolvedValueOnce()
const wrapper = mount(InvitesPanel)
await wrapper.find('.invites-toggle').trigger('click')
await flushPromises()
await wrapper.find('.ticket-btn-danger').trigger('click')
expect(wrapper.text()).toContain('Delete this invite?')
const confirmButtons = wrapper.findAll('.ticket-btn-danger')
await confirmButtons[confirmButtons.length - 1]?.trigger('click')
await flushPromises()
expect(deleteSpy).toHaveBeenCalledWith('invite-1')
expect(wrapper.text()).toContain('No invites yet')
})
it('disables delete for already-used invites', async () => {
const usedInvite: Invite = {
id: 'invite-1',
code: 'USEDCODE',
consumed_at: '2026-01-01T00:00:00.000Z',
}
vi.spyOn(invitesApi, 'getInvitesApi').mockResolvedValueOnce([usedInvite])
const wrapper = mount(InvitesPanel)
await wrapper.find('.invites-toggle').trigger('click')
await flushPromises()
const deleteBtn = wrapper.find('.ticket-btn-danger')
expect((deleteBtn.element as HTMLButtonElement).disabled).toBe(true)
})
it('shows an error banner when loading invites fails', async () => {
vi.spyOn(invitesApi, 'getInvitesApi').mockRejectedValueOnce(new Error('Network error'))
const wrapper = mount(InvitesPanel)
await wrapper.find('.invites-toggle').trigger('click')
await flushPromises()
expect(wrapper.find('.banner-error').text()).toContain('Network error')
})
})
function flushPromises() {
return new Promise((resolve) => setTimeout(resolve))
}
+3 -3
View File
@@ -24,9 +24,9 @@ const router = createRouter({
component: () => import('../views/LoginView.vue'),
},
{
path: '/about',
name: 'about',
component: () => import('../views/AboutView.vue'),
path: '/account',
name: 'account',
component: () => import('../views/AccountView.vue'),
},
],
})
+6
View File
@@ -0,0 +1,6 @@
export interface Invite {
id: string
code: string
expires_at?: string
consumed_at?: string
}
@@ -3,6 +3,7 @@ import { onMounted, ref } from 'vue'
import { useListsStore } from '@/stores/lists'
import { useAuthStore } from '@/stores/auth'
import ChangePasswordModal from '@/components/ChangePasswordModal.vue'
import InvitesPanel from '@/components/InvitesPanel.vue'
const listsStore = useListsStore()
const authStore = useAuthStore()
@@ -34,6 +35,8 @@ onMounted(() => {
</button>
</section>
<InvitesPanel />
<h1>Pending changes</h1>
<section class="card info-card">