Commit 39411c79 authored by Aryan Noshirvnai's avatar Aryan Noshirvnai

Add admin account moderation UI and global search on Home

AdminPanel's Users tab gains a search box and a per-user Manage panel
(rename, deactivate/reactivate, suspend/unsuspend, reset password),
wired to the new backend endpoints.

Home gains a search box at the top that reuses the existing shared-
library search (same one Library's "Shared" scope already calls) -
while a query is active it replaces the feed sections with results,
reusing the existing HomeSongRow/claim-then-act flow unchanged.
Co-Authored-By: 's avatarClaude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019i3NAUkLkHNbsPg5vKfzF9
parent 18253e9a
......@@ -122,10 +122,15 @@ export interface AdminUser {
username: string | null
phone_number: string | null
role: 'user' | 'business_admin' | 'super_admin'
is_active: boolean
suspended_until: string | null
}
export function listUsers(role?: string) {
const suffix = role ? `?${new URLSearchParams({ role })}` : ''
export function listUsers(opts?: { role?: string; q?: string }) {
const params = new URLSearchParams()
if (opts?.role) params.set('role', opts.role)
if (opts?.q) params.set('q', opts.q)
const suffix = params.toString() ? `?${params}` : ''
return apiFetch<{ status: string; users: AdminUser[] }>(`/soundmarks/admin/users${suffix}`)
}
......@@ -136,6 +141,22 @@ export function updateUserRole(userId: number, role: string) {
)
}
/** Partial update - omit whichever fields aren't being changed. suspendHours: a positive
* number suspends until that many hours from now, 0 clears any existing suspension. */
export function editUser(userId: number, body: { username?: string; is_active?: boolean; suspend_hours?: number }) {
return apiFetch<{ status: string; user: AdminUser }>(`/soundmarks/admin/users/${userId}`, {
method: 'PATCH',
json: body,
})
}
export function resetUserPassword(userId: number, newPassword: string) {
return apiFetch<{ status: string }>(`/soundmarks/admin/users/${userId}/reset-password`, {
method: 'POST',
json: { new_password: newPassword },
})
}
/** For PlayerContext's `streamUrl` override - a direct, token-authenticated URL for a
* soundmark's anthem (streamable regardless of who uploaded the underlying song), mirroring
* api/stream.ts's fetchStreamUrl but against the soundmark-specific endpoint. See
......
......@@ -36,7 +36,7 @@ const LANDMARK: soundmarksApi.Soundmark = {
updated_at: '2026-01-01T00:00:00Z',
}
const BUSINESS_OWNER: soundmarksApi.AdminUser = { id: 5, username: 'joe', phone_number: '+15559999', role: 'business_admin' }
const BUSINESS_OWNER: soundmarksApi.AdminUser = { id: 5, username: 'joe', phone_number: '+15559999', role: 'business_admin', is_active: true, suspended_until: null }
const BUSINESS: soundmarksApi.Soundmark = {
...LANDMARK,
......@@ -60,7 +60,7 @@ const SUGGESTION: soundmarksApi.SoundmarkSuggestion = {
created_at: '2026-01-01T00:00:00Z',
}
const PLAIN_USER: soundmarksApi.AdminUser = { id: 7, username: 'alex', phone_number: '+15551234', role: 'user' }
const PLAIN_USER: soundmarksApi.AdminUser = { id: 7, username: 'alex', phone_number: '+15551234', role: 'user', is_active: true, suspended_until: null }
function mockEmptyQueue() {
return vi.spyOn(soundmarksApi, 'getReviewQueue').mockResolvedValue({ status: 'success', suggestions: [] })
......@@ -200,6 +200,125 @@ describe('AdminPanel', () => {
})
})
it('searches users by username', async () => {
vi.spyOn(soundmarksApi, 'getAllSoundmarks').mockResolvedValue({ status: 'success', soundmarks: [] })
const listUsers = vi.spyOn(soundmarksApi, 'listUsers').mockResolvedValue({ status: 'success', users: [PLAIN_USER] })
mockEmptyQueue()
renderPanel()
await userEvent.click(screen.getByRole('button', { name: 'users' }))
await screen.findByText('alex')
await userEvent.type(screen.getByRole('textbox', { name: 'Search users' }), 'ale')
await waitFor(() => {
expect(listUsers).toHaveBeenCalledWith({ q: 'ale' })
})
})
it('renames a user from the Manage panel', async () => {
vi.spyOn(soundmarksApi, 'getAllSoundmarks').mockResolvedValue({ status: 'success', soundmarks: [] })
vi.spyOn(soundmarksApi, 'listUsers').mockResolvedValue({ status: 'success', users: [PLAIN_USER] })
mockEmptyQueue()
const editUser = vi.spyOn(soundmarksApi, 'editUser').mockResolvedValue({
status: 'success',
user: { ...PLAIN_USER, username: 'alexrenamed' },
})
renderPanel()
await userEvent.click(screen.getByRole('button', { name: 'users' }))
await screen.findByText('alex')
await userEvent.click(screen.getByRole('button', { name: 'Manage' }))
const usernameField = screen.getByLabelText('Username')
await userEvent.clear(usernameField)
await userEvent.type(usernameField, 'alexrenamed')
await userEvent.click(screen.getByRole('button', { name: 'Rename' }))
await waitFor(() => {
expect(editUser).toHaveBeenCalledWith(PLAIN_USER.id, { username: 'alexrenamed' })
})
await screen.findByText('alexrenamed')
})
it('deactivates a user after confirming', async () => {
vi.spyOn(soundmarksApi, 'getAllSoundmarks').mockResolvedValue({ status: 'success', soundmarks: [] })
vi.spyOn(soundmarksApi, 'listUsers').mockResolvedValue({ status: 'success', users: [PLAIN_USER] })
mockEmptyQueue()
const editUser = vi.spyOn(soundmarksApi, 'editUser').mockResolvedValue({
status: 'success',
user: { ...PLAIN_USER, is_active: false },
})
vi.spyOn(window, 'confirm').mockReturnValue(true)
renderPanel()
await userEvent.click(screen.getByRole('button', { name: 'users' }))
await screen.findByText('alex')
await userEvent.click(screen.getByRole('button', { name: 'Manage' }))
await userEvent.click(screen.getByRole('button', { name: 'Deactivate account' }))
await waitFor(() => {
expect(editUser).toHaveBeenCalledWith(PLAIN_USER.id, { is_active: false })
})
await screen.findByText('deactivated')
})
it('does not deactivate when the confirmation is declined', async () => {
vi.spyOn(soundmarksApi, 'getAllSoundmarks').mockResolvedValue({ status: 'success', soundmarks: [] })
vi.spyOn(soundmarksApi, 'listUsers').mockResolvedValue({ status: 'success', users: [PLAIN_USER] })
mockEmptyQueue()
const editUser = vi.spyOn(soundmarksApi, 'editUser')
vi.spyOn(window, 'confirm').mockReturnValue(false)
renderPanel()
await userEvent.click(screen.getByRole('button', { name: 'users' }))
await screen.findByText('alex')
await userEvent.click(screen.getByRole('button', { name: 'Manage' }))
await userEvent.click(screen.getByRole('button', { name: 'Deactivate account' }))
expect(editUser).not.toHaveBeenCalled()
})
it('suspends a user for a given number of hours', async () => {
vi.spyOn(soundmarksApi, 'getAllSoundmarks').mockResolvedValue({ status: 'success', soundmarks: [] })
vi.spyOn(soundmarksApi, 'listUsers').mockResolvedValue({ status: 'success', users: [PLAIN_USER] })
mockEmptyQueue()
const futureIso = new Date(Date.now() + 2 * 60 * 60 * 1000).toISOString()
const editUser = vi.spyOn(soundmarksApi, 'editUser').mockResolvedValue({
status: 'success',
user: { ...PLAIN_USER, suspended_until: futureIso },
})
renderPanel()
await userEvent.click(screen.getByRole('button', { name: 'users' }))
await screen.findByText('alex')
await userEvent.click(screen.getByRole('button', { name: 'Manage' }))
await userEvent.click(screen.getByRole('button', { name: 'Suspend' }))
await waitFor(() => {
expect(editUser).toHaveBeenCalledWith(PLAIN_USER.id, { suspend_hours: 24 })
})
await screen.findByText('suspended')
})
it('resets a users password from the Manage panel', async () => {
vi.spyOn(soundmarksApi, 'getAllSoundmarks').mockResolvedValue({ status: 'success', soundmarks: [] })
vi.spyOn(soundmarksApi, 'listUsers').mockResolvedValue({ status: 'success', users: [PLAIN_USER] })
mockEmptyQueue()
const resetPassword = vi.spyOn(soundmarksApi, 'resetUserPassword').mockResolvedValue({ status: 'success' })
renderPanel()
await userEvent.click(screen.getByRole('button', { name: 'users' }))
await screen.findByText('alex')
await userEvent.click(screen.getByRole('button', { name: 'Manage' }))
await userEvent.type(screen.getByLabelText('New password'), 'brandnewpassword')
await userEvent.click(screen.getByRole('button', { name: 'Reset password' }))
await waitFor(() => {
expect(resetPassword).toHaveBeenCalledWith(PLAIN_USER.id, 'brandnewpassword')
})
})
it('sets an anthem on a major-tier soundmark by picking from the public library', async () => {
vi.spyOn(soundmarksApi, 'getAllSoundmarks').mockResolvedValue({ status: 'success', soundmarks: [LANDMARK] })
vi.spyOn(soundmarksApi, 'listUsers').mockResolvedValue({ status: 'success', users: [] })
......
This diff is collapsed.
......@@ -136,6 +136,63 @@ describe('Home', () => {
expect(screen.queryByText(/stranger/)).not.toBeInTheDocument()
})
it('searches the shared library and replaces the feed with results', async () => {
vi.spyOn(homeApi, 'getHomeFeed').mockResolvedValue({
status: 'success',
latest_songs: [OWN_SONG],
new_albums: [],
suggestions: [],
})
const search = vi.spyOn(libraryApi, 'searchSharedLibrary').mockResolvedValue({
status: 'success',
songs: [{ ...OTHER_SONG, lyrics: null, file_path: '/tmp/fake.mp3' }],
})
renderHome()
await screen.findByText('My Own Track')
await userEvent.type(screen.getByRole('textbox', { name: 'Search all of Stax' }), 'else')
await waitFor(() => {
expect(search).toHaveBeenCalledWith('else')
})
expect(await screen.findByText("Someone Else's Track")).toBeInTheDocument()
// The normal feed sections are replaced while a search is active, not just supplemented.
expect(screen.queryByText('My Own Track')).not.toBeInTheDocument()
expect(screen.queryByText('New Songs')).not.toBeInTheDocument()
})
it('shows an empty state when a search finds nothing', async () => {
vi.spyOn(homeApi, 'getHomeFeed').mockResolvedValue({ status: 'success', latest_songs: [OWN_SONG], new_albums: [], suggestions: [] })
vi.spyOn(libraryApi, 'searchSharedLibrary').mockResolvedValue({ status: 'success', songs: [] })
renderHome()
await screen.findByText('My Own Track')
await userEvent.type(screen.getByRole('textbox', { name: 'Search all of Stax' }), 'nothing here')
expect(await screen.findByText(/No songs found for "nothing here"/)).toBeInTheDocument()
})
it('restores the normal feed once the search query is cleared', async () => {
vi.spyOn(homeApi, 'getHomeFeed').mockResolvedValue({ status: 'success', latest_songs: [OWN_SONG], new_albums: [], suggestions: [] })
vi.spyOn(libraryApi, 'searchSharedLibrary').mockResolvedValue({
status: 'success',
songs: [{ ...OTHER_SONG, lyrics: null, file_path: '/tmp/fake.mp3' }],
})
renderHome()
await screen.findByText('My Own Track')
const input = screen.getByRole('textbox', { name: 'Search all of Stax' })
await userEvent.type(input, 'else')
await screen.findByText("Someone Else's Track")
await userEvent.clear(input)
expect(await screen.findByText('My Own Track')).toBeInTheDocument()
expect(screen.queryByText("Someone Else's Track")).not.toBeInTheDocument()
})
it('plays a song the caller already owns directly, without claiming it first', async () => {
vi.spyOn(homeApi, 'getHomeFeed').mockResolvedValue({ status: 'success', latest_songs: [OWN_SONG], new_albums: [], suggestions: [] })
const claimSharedSong = vi.spyOn(libraryApi, 'claimSharedSong')
......
import { useEffect, useState } from 'react'
import { Disc3, Globe, ListMusic, Sparkles, type LucideIcon } from 'lucide-react'
import { Disc3, Globe, ListMusic, Search, Sparkles, type LucideIcon } from 'lucide-react'
import { getHomeFeed, type HomeAlbum, type HomeSong } from '../api/home'
import { searchSharedLibrary } from '../api/library'
import { ApiError } from '../api/client'
import { Layout } from '../components/Layout'
import { Input } from '../components/ui/Input'
import { AddToPlaylistModal } from '../components/AddToPlaylistModal'
import { HomeAlbumCard } from '../components/HomeAlbumCard'
import { HomeSongRow } from '../components/HomeSongRow'
......@@ -35,6 +37,9 @@ export function Home() {
const [loading, setLoading] = useState(true)
const [error, setError] = useState<string | null>(null)
const [addingSong, setAddingSong] = useState<{ id: number; title: string } | null>(null)
const [query, setQuery] = useState('')
const [searchResults, setSearchResults] = useState<HomeSong[] | null>(null)
const [searching, setSearching] = useState(false)
useEffect(() => {
getHomeFeed()
......@@ -47,10 +52,63 @@ export function Home() {
.finally(() => setLoading(false))
}, [])
// Global search across every user's library (the same pool Home's own feed sections draw
// from), not the caller's own - searchSharedLibrary already excludes anything the caller has
// a copy of, so every result here always goes through HomeSongRow's claim-then-act path via
// useHomeSongPlayback. 400ms debounce, same idiom Library.tsx's own search uses.
const isSearching = query.trim().length > 0
useEffect(() => {
if (!query.trim()) {
setSearchResults(null)
return
}
setSearching(true)
const handle = setTimeout(() => {
searchSharedLibrary(query.trim())
.then((res) => setSearchResults(res.songs))
.catch(() => setSearchResults([]))
.finally(() => setSearching(false))
}, 400)
return () => clearTimeout(handle)
}, [query])
const isEmpty = !loading && !error && latestSongs.length === 0 && newAlbums.length === 0 && suggestions.length === 0
return (
<Layout title="Home">
<div className="relative mb-6">
<Search size={16} strokeWidth={2} className="pointer-events-none absolute left-3 top-1/2 -translate-y-1/2 text-on-surface-variant" />
<Input
placeholder="Search all of Stax"
value={query}
onChange={(e) => setQuery(e.target.value)}
className="pl-9"
aria-label="Search all of Stax"
/>
</div>
{isSearching ? (
<div className="animate-content-enter">
{searching && (
<div className="space-y-1">
<SkeletonRow />
<SkeletonRow />
<SkeletonRow />
</div>
)}
{!searching && searchResults && searchResults.length === 0 && (
<EmptyState icon={Search} message={`No songs found for "${query.trim()}".`} />
)}
{!searching && searchResults && searchResults.length > 0 && (
<ul className="space-y-1">
{searchResults.map((song) => (
<HomeSongRow key={song.id} song={song} onAddToPlaylist={setAddingSong} />
))}
</ul>
)}
</div>
) : (
<>
{loading && (
<div className="space-y-1">
<SkeletonRow />
......@@ -105,6 +163,8 @@ export function Home() {
)}
</div>
)}
</>
)}
{addingSong && <AddToPlaylistModal song={addingSong} onClose={() => setAddingSong(null)} />}
</Layout>
......
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment