Commit 29363679 authored by Aryan Noshirvnai's avatar Aryan Noshirvnai

Add three-tier Soundmarks (major/business/community) and dark map re-theme

Major locations get one super-admin-set anthem; businesses get an
owner-managed playlist; community spots stay fully vote-driven with the
top 3 proposals shown. Suggestions on major/business tiers go through a
review queue (CRM) instead of applying immediately. Also switches both
maps from default OSM tiles to CartoDB's free dark basemap with custom
tier-colored pin markers for a cleaner, more minimal look.
Co-Authored-By: 's avatarClaude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019i3NAUkLkHNbsPg5vKfzF9
parent b2c5ae5b
Pipeline #1062 failed with stage
...@@ -8,18 +8,25 @@ export interface SoundmarkSong { ...@@ -8,18 +8,25 @@ export interface SoundmarkSong {
coverart: string | null coverart: string | null
} }
export type SoundmarkTier = 'major' | 'business' | 'community'
export interface Soundmark { export interface Soundmark {
id: number id: number
name: string name: string
description: string | null description: string | null
tier: SoundmarkTier
latitude: number latitude: number
longitude: number longitude: number
radius_meters: number radius_meters: number
business_owner_id: number | null business_owner_id: number | null
business_owner_username: string | null business_owner_username: string | null
/** The currently-winning song - either the top-voted proposal, or the admin-set fallback if /** The currently playing song, resolved per tier: major -> the super-admin-set song directly,
* there are no proposals yet. See proposal_count to tell those two cases apart. */ * business -> the first track in the owner's playlist, community -> the top-voted proposal
* (falling back to the legacy song_id if there are no proposals yet). */
song: SoundmarkSong | null song: SoundmarkSong | null
/** Business tier only - the full ordered playlist (song is always playlist[0] when present). */
playlist: SoundmarkSong[]
/** Community tier only - 0 for major/business. */
proposal_count: number proposal_count: number
created_at: string created_at: string
updated_at: string updated_at: string
...@@ -48,6 +55,7 @@ export function getAllSoundmarks() { ...@@ -48,6 +55,7 @@ export function getAllSoundmarks() {
export interface SoundmarkCreateInput { export interface SoundmarkCreateInput {
name: string name: string
description?: string | null description?: string | null
tier: SoundmarkTier
latitude: number latitude: number
longitude: number longitude: number
radius_meters?: number radius_meters?: number
...@@ -69,8 +77,8 @@ export function deleteSoundmark(id: number) { ...@@ -69,8 +77,8 @@ export function deleteSoundmark(id: number) {
return apiFetch<{ status: string }>(`/soundmarks/${id}`, { method: 'DELETE' }) return apiFetch<{ status: string }>(`/soundmarks/${id}`, { method: 'DELETE' })
} }
/** Sets or clears (songId = null) a soundmark's anthem - business admins can only do this for /** Sets or clears (songId = null) a major-tier soundmark's single anthem. Business tier uses
* soundmarks they own; super admins can do it for any. */ * the playlist endpoints below; community tier is fully automated via proposals/voting. */
export function setSoundmarkSong(id: number, songId: number | null) { export function setSoundmarkSong(id: number, songId: number | null) {
return apiFetch<{ status: string; soundmark: Soundmark }>(`/soundmarks/${id}/song`, { return apiFetch<{ status: string; soundmark: Soundmark }>(`/soundmarks/${id}/song`, {
method: 'PATCH', method: 'PATCH',
...@@ -78,6 +86,21 @@ export function setSoundmarkSong(id: number, songId: number | null) { ...@@ -78,6 +86,21 @@ export function setSoundmarkSong(id: number, songId: number | null) {
}) })
} }
/** Adds a track to a business-tier soundmark's playlist (owner or super admin only). Adding a
* song that's already in the playlist is a no-op. */
export function addPlaylistTrack(id: number, songId: number) {
return apiFetch<{ status: string; soundmark: Soundmark }>(`/soundmarks/${id}/playlist`, {
method: 'POST',
json: { song_id: songId },
})
}
export function removePlaylistTrack(id: number, songId: number) {
return apiFetch<{ status: string; soundmark: Soundmark }>(`/soundmarks/${id}/playlist/${songId}`, {
method: 'DELETE',
})
}
export interface PublicLibrarySong { export interface PublicLibrarySong {
id: number id: number
title: string title: string
...@@ -176,3 +199,46 @@ export function voteForProposal(soundmarkId: number, proposalId: number) { ...@@ -176,3 +199,46 @@ export function voteForProposal(soundmarkId: number, proposalId: number) {
export function removeVote(soundmarkId: number) { export function removeVote(soundmarkId: number) {
return apiFetch<{ status: string }>(`/soundmarks/${soundmarkId}/proposals/vote`, { method: 'DELETE' }) return apiFetch<{ status: string }>(`/soundmarks/${soundmarkId}/proposals/vote`, { method: 'DELETE' })
} }
export interface SoundmarkSuggestion {
id: number
soundmark_id: number
soundmark_name: string | null
soundmark_tier: SoundmarkTier | null
song: SoundmarkSong | null
suggested_by_username: string | null
status: 'pending' | 'approved' | 'rejected'
created_at: string
}
/** Suggests a song for a major or business tier soundmark - goes to that soundmark's review
* queue rather than taking effect immediately. Community tier uses proposeSong instead. */
export function suggestSong(soundmarkId: number, songId: number) {
return apiFetch<{ status: string; suggestion: SoundmarkSuggestion }>(`/soundmarks/${soundmarkId}/suggestions`, {
method: 'POST',
json: { song_id: songId },
})
}
/** The review queue (CRM). Super admins see every pending suggestion; business admins only see
* suggestions for soundmarks they themselves own. */
export function getReviewQueue(status: string = 'pending') {
const params = new URLSearchParams({ status })
return apiFetch<{ status: string; suggestions: SoundmarkSuggestion[] }>(`/soundmarks/suggestions?${params}`)
}
/** Approves a suggestion and applies it: sets the song directly for major tier, adds it to the
* playlist for business tier. */
export function approveSuggestion(suggestionId: number) {
return apiFetch<{ status: string; suggestion: SoundmarkSuggestion }>(
`/soundmarks/suggestions/${suggestionId}/approve`,
{ method: 'POST' },
)
}
export function rejectSuggestion(suggestionId: number) {
return apiFetch<{ status: string; suggestion: SoundmarkSuggestion }>(
`/soundmarks/suggestions/${suggestionId}/reject`,
{ method: 'POST' },
)
}
...@@ -4,6 +4,7 @@ import type { LeafletMouseEvent } from 'leaflet' ...@@ -4,6 +4,7 @@ import type { LeafletMouseEvent } from 'leaflet'
import { MapPin, Search } from 'lucide-react' import { MapPin, Search } from 'lucide-react'
import { Input } from './ui/Input' import { Input } from './ui/Input'
import { geocodeAddress, type GeocodeResult } from '../api/soundmarks' import { geocodeAddress, type GeocodeResult } from '../api/soundmarks'
import { DARK_TILE_ATTRIBUTION, DARK_TILE_URL, soundmarkIcon } from '../lib/mapTheme'
const DEFAULT_CENTER: [number, number] = [20, 0] // low zoom, whole-world view when nothing is set yet const DEFAULT_CENTER: [number, number] = [20, 0] // low zoom, whole-world view when nothing is set yet
const ZOOM_NO_PIN = 2 const ZOOM_NO_PIN = 2
...@@ -108,15 +109,13 @@ export function LocationPicker({ latitude, longitude, onChange }: LocationPicker ...@@ -108,15 +109,13 @@ export function LocationPicker({ latitude, longitude, onChange }: LocationPicker
<div className="relative z-0 mt-3 h-56 overflow-hidden rounded-lg border border-neutral-700"> <div className="relative z-0 mt-3 h-56 overflow-hidden rounded-lg border border-neutral-700">
<MapContainer center={initialCenter} zoom={initialZoom} className="h-full w-full" scrollWheelZoom> <MapContainer center={initialCenter} zoom={initialZoom} className="h-full w-full" scrollWheelZoom>
<TileLayer <TileLayer attribution={DARK_TILE_ATTRIBUTION} url={DARK_TILE_URL} />
attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
<FlyToOnJump jumpTo={jumpTo} /> <FlyToOnJump jumpTo={jumpTo} />
<ClickToPlacePin onClick={onChange} /> <ClickToPlacePin onClick={onChange} />
{hasPin && ( {hasPin && (
<Marker <Marker
position={[latitude, longitude]} position={[latitude, longitude]}
icon={soundmarkIcon('generic')}
draggable draggable
eventHandlers={{ eventHandlers={{
dragend: (e) => { dragend: (e) => {
......
...@@ -8,12 +8,14 @@ const NEARBY: NearbySoundmark = { ...@@ -8,12 +8,14 @@ const NEARBY: NearbySoundmark = {
id: 1, id: 1,
name: "Joe's Cafe", name: "Joe's Cafe",
description: null, description: null,
tier: 'major',
latitude: 37.7749, latitude: 37.7749,
longitude: -122.4194, longitude: -122.4194,
radius_meters: 150, radius_meters: 150,
business_owner_id: null, business_owner_id: null,
business_owner_username: null, business_owner_username: null,
song: { id: 1, title: 'Anthem', artist: 'Artist', album: null, coverart: null }, song: { id: 1, title: 'Anthem', artist: 'Artist', album: null, coverart: null },
playlist: [],
created_at: '2026-01-01T00:00:00Z', created_at: '2026-01-01T00:00:00Z',
proposal_count: 0, proposal_count: 0,
updated_at: '2026-01-01T00:00:00Z', updated_at: '2026-01-01T00:00:00Z',
......
...@@ -3,6 +3,7 @@ import { CircleMarker, MapContainer, Marker, Popup, TileLayer, useMap } from 're ...@@ -3,6 +3,7 @@ import { CircleMarker, MapContainer, Marker, Popup, TileLayer, useMap } from 're
import type { Map as LeafletMap } from 'leaflet' import type { Map as LeafletMap } from 'leaflet'
import { LocateFixed } from 'lucide-react' import { LocateFixed } from 'lucide-react'
import type { NearbySoundmark } from '../api/soundmarks' import type { NearbySoundmark } from '../api/soundmarks'
import { DARK_TILE_ATTRIBUTION, DARK_TILE_URL, soundmarkIcon } from '../lib/mapTheme'
const INITIAL_ZOOM = 16 const INITIAL_ZOOM = 16
...@@ -43,10 +44,7 @@ export function SoundmarkMap({ userLocation, soundmarks }: SoundmarkMapProps) { ...@@ -43,10 +44,7 @@ export function SoundmarkMap({ userLocation, soundmarks }: SoundmarkMapProps) {
className="h-full w-full" className="h-full w-full"
scrollWheelZoom={false} scrollWheelZoom={false}
> >
<TileLayer <TileLayer attribution={DARK_TILE_ATTRIBUTION} url={DARK_TILE_URL} />
attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
<CenterOnMount lat={userLocation.lat} lon={userLocation.lon} /> <CenterOnMount lat={userLocation.lat} lon={userLocation.lon} />
<CircleMarker <CircleMarker
center={[userLocation.lat, userLocation.lon]} center={[userLocation.lat, userLocation.lon]}
...@@ -56,7 +54,7 @@ export function SoundmarkMap({ userLocation, soundmarks }: SoundmarkMapProps) { ...@@ -56,7 +54,7 @@ export function SoundmarkMap({ userLocation, soundmarks }: SoundmarkMapProps) {
<Popup>You are here</Popup> <Popup>You are here</Popup>
</CircleMarker> </CircleMarker>
{soundmarks.map((sm) => ( {soundmarks.map((sm) => (
<Marker key={sm.id} position={[sm.latitude, sm.longitude]}> <Marker key={sm.id} position={[sm.latitude, sm.longitude]} icon={soundmarkIcon(sm.tier)}>
<Popup> <Popup>
<span className="font-medium">{sm.name}</span> <span className="font-medium">{sm.name}</span>
{sm.song && ( {sm.song && (
......
import L from 'leaflet'
/** CartoDB's free "dark matter" basemap - no API key required, and it actually matches the
* app's own dark theme instead of fighting it like the default OSM tiles (bright white streets,
* yellow/orange roads) did. */
export const DARK_TILE_URL = 'https://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}{r}.png'
export const DARK_TILE_ATTRIBUTION =
'&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors &copy; <a href="https://carto.com/attributions">CARTO</a>'
export type MarkerTier = 'major' | 'business' | 'community' | 'generic'
const TIER_COLOR: Record<MarkerTier, string> = {
major: '#fbbf24', // amber - curated landmark
business: '#818cf8', // indigo - business
community: '#34d399', // emerald - community, matches the app's own accent color
generic: '#f5f5f5', // neutral white - used where tier isn't known yet (e.g. LocationPicker)
}
function pinSvg(color: string) {
return `<svg width="26" height="34" viewBox="0 0 26 34" xmlns="http://www.w3.org/2000/svg">
<path d="M13 0C5.8 0 0 5.8 0 13c0 9.75 13 21 13 21s13-11.25 13-21C26 5.8 20.2 0 13 0z" fill="${color}"/>
<circle cx="13" cy="13" r="4.5" fill="#0a0a0a"/>
</svg>`
}
const iconCache = new Map<MarkerTier, L.DivIcon>()
/** A minimal, flat teardrop marker (no drop shadow, no default-Leaflet blue) colored by tier -
* built once per tier and reused, since react-leaflet re-renders Markers often. */
export function soundmarkIcon(tier: MarkerTier): L.DivIcon {
const cached = iconCache.get(tier)
if (cached) return cached
const icon = L.divIcon({
className: 'stax-map-pin',
html: pinSvg(TIER_COLOR[tier]),
iconSize: [26, 34],
iconAnchor: [13, 34],
popupAnchor: [0, -30],
})
iconCache.set(tier, icon)
return icon
}
...@@ -23,19 +23,49 @@ const LANDMARK: soundmarksApi.Soundmark = { ...@@ -23,19 +23,49 @@ const LANDMARK: soundmarksApi.Soundmark = {
id: 1, id: 1,
name: 'Old Clock Tower', name: 'Old Clock Tower',
description: 'A neighborhood fixture', description: 'A neighborhood fixture',
tier: 'major',
latitude: 10, latitude: 10,
longitude: 20, longitude: 20,
radius_meters: 100, radius_meters: 100,
business_owner_id: null, business_owner_id: null,
business_owner_username: null, business_owner_username: null,
song: null, song: null,
playlist: [],
created_at: '2026-01-01T00:00:00Z', created_at: '2026-01-01T00:00:00Z',
proposal_count: 0, proposal_count: 0,
updated_at: '2026-01-01T00:00:00Z', updated_at: '2026-01-01T00:00:00Z',
} }
const BUSINESS_OWNER: soundmarksApi.AdminUser = { id: 5, username: 'joe', phone_number: '+15559999', role: 'business_admin' }
const BUSINESS: soundmarksApi.Soundmark = {
...LANDMARK,
id: 2,
name: "Joe's Cafe",
tier: 'business',
business_owner_id: BUSINESS_OWNER.id,
business_owner_username: BUSINESS_OWNER.username,
playlist: [{ id: 42, title: 'Cafe Anthem', artist: 'Local Band', album: null, coverart: null }],
song: { id: 42, title: 'Cafe Anthem', artist: 'Local Band', album: null, coverart: null },
}
const SUGGESTION: soundmarksApi.SoundmarkSuggestion = {
id: 900,
soundmark_id: LANDMARK.id,
soundmark_name: LANDMARK.name,
soundmark_tier: 'major',
song: { id: 99, title: 'Suggested Track', artist: 'Someone', album: null, coverart: null },
suggested_by_username: 'alex',
status: 'pending',
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' }
function mockEmptyQueue() {
return vi.spyOn(soundmarksApi, 'getReviewQueue').mockResolvedValue({ status: 'success', suggestions: [] })
}
function renderPanel() { function renderPanel() {
return render( return render(
<MemoryRouter> <MemoryRouter>
...@@ -59,19 +89,24 @@ describe('AdminPanel', () => { ...@@ -59,19 +89,24 @@ describe('AdminPanel', () => {
vi.restoreAllMocks() vi.restoreAllMocks()
}) })
it('lists every soundmark regardless of owner, distinguishing landmarks from businesses', async () => { it('lists every soundmark regardless of owner, distinguishing tiers', async () => {
vi.spyOn(soundmarksApi, 'getAllSoundmarks').mockResolvedValue({ status: 'success', soundmarks: [LANDMARK] }) vi.spyOn(soundmarksApi, 'getAllSoundmarks').mockResolvedValue({ status: 'success', soundmarks: [LANDMARK, BUSINESS] })
vi.spyOn(soundmarksApi, 'listUsers').mockResolvedValue({ status: 'success', users: [PLAIN_USER] }) vi.spyOn(soundmarksApi, 'listUsers').mockResolvedValue({ status: 'success', users: [PLAIN_USER] })
mockEmptyQueue()
renderPanel() renderPanel()
expect(await screen.findByText('Old Clock Tower')).toBeInTheDocument() expect(await screen.findByText('Old Clock Tower')).toBeInTheDocument()
expect(screen.getByText(/Landmark/)).toBeInTheDocument() expect(screen.getByText('Major landmark')).toBeInTheDocument()
expect(screen.getByText("Joe's Cafe")).toBeInTheDocument()
expect(screen.getByText('Business')).toBeInTheDocument()
expect(screen.getByText(/Owned by joe/)).toBeInTheDocument()
}) })
it('creates a new soundmark via the form', async () => { it('creates a new soundmark via the form', async () => {
vi.spyOn(soundmarksApi, 'getAllSoundmarks').mockResolvedValue({ status: 'success', soundmarks: [] }) vi.spyOn(soundmarksApi, 'getAllSoundmarks').mockResolvedValue({ status: 'success', soundmarks: [] })
vi.spyOn(soundmarksApi, 'listUsers').mockResolvedValue({ status: 'success', users: [] }) vi.spyOn(soundmarksApi, 'listUsers').mockResolvedValue({ status: 'success', users: [] })
mockEmptyQueue()
const create = vi.spyOn(soundmarksApi, 'createSoundmark').mockResolvedValue({ const create = vi.spyOn(soundmarksApi, 'createSoundmark').mockResolvedValue({
status: 'success', status: 'success',
soundmark: { ...LANDMARK, id: 2, name: 'New Plaza' }, soundmark: { ...LANDMARK, id: 2, name: 'New Plaza' },
...@@ -87,15 +122,35 @@ describe('AdminPanel', () => { ...@@ -87,15 +122,35 @@ describe('AdminPanel', () => {
await waitFor(() => { await waitFor(() => {
expect(create).toHaveBeenCalledWith( expect(create).toHaveBeenCalledWith(
expect.objectContaining({ name: 'New Plaza', latitude: 12.5, longitude: 45.5, business_owner_id: null }), expect.objectContaining({ name: 'New Plaza', tier: 'major', latitude: 12.5, longitude: 45.5, business_owner_id: null }),
) )
}) })
expect(await screen.findByText('New Plaza')).toBeInTheDocument() expect(await screen.findByText('New Plaza')).toBeInTheDocument()
}) })
it('requires an owner before creating a business-tier soundmark', async () => {
vi.spyOn(soundmarksApi, 'getAllSoundmarks').mockResolvedValue({ status: 'success', soundmarks: [] })
vi.spyOn(soundmarksApi, 'listUsers').mockResolvedValue({ status: 'success', users: [PLAIN_USER] })
mockEmptyQueue()
const create = vi.spyOn(soundmarksApi, 'createSoundmark')
renderPanel()
await screen.findByText(/No soundmarks yet/)
await userEvent.click(screen.getByRole('button', { name: 'New soundmark' }))
await userEvent.type(screen.getByPlaceholderText('Name'), 'New Cafe')
await userEvent.selectOptions(screen.getByRole('combobox', { name: 'Tier' }), 'business')
await userEvent.click(screen.getByRole('button', { name: 'Set location (mock)' }))
await userEvent.click(screen.getByRole('button', { name: 'Create soundmark' }))
expect(await screen.findByText(/need an owner/)).toBeInTheDocument()
expect(create).not.toHaveBeenCalled()
})
it('deletes a soundmark after confirming', async () => { it('deletes a soundmark after confirming', async () => {
vi.spyOn(soundmarksApi, 'getAllSoundmarks').mockResolvedValue({ status: 'success', soundmarks: [LANDMARK] }) vi.spyOn(soundmarksApi, 'getAllSoundmarks').mockResolvedValue({ status: 'success', soundmarks: [LANDMARK] })
vi.spyOn(soundmarksApi, 'listUsers').mockResolvedValue({ status: 'success', users: [] }) vi.spyOn(soundmarksApi, 'listUsers').mockResolvedValue({ status: 'success', users: [] })
mockEmptyQueue()
const del = vi.spyOn(soundmarksApi, 'deleteSoundmark').mockResolvedValue({ status: 'success' }) const del = vi.spyOn(soundmarksApi, 'deleteSoundmark').mockResolvedValue({ status: 'success' })
vi.spyOn(window, 'confirm').mockReturnValue(true) vi.spyOn(window, 'confirm').mockReturnValue(true)
...@@ -111,6 +166,7 @@ describe('AdminPanel', () => { ...@@ -111,6 +166,7 @@ describe('AdminPanel', () => {
it('does not delete when the confirmation is declined', async () => { it('does not delete when the confirmation is declined', async () => {
vi.spyOn(soundmarksApi, 'getAllSoundmarks').mockResolvedValue({ status: 'success', soundmarks: [LANDMARK] }) vi.spyOn(soundmarksApi, 'getAllSoundmarks').mockResolvedValue({ status: 'success', soundmarks: [LANDMARK] })
vi.spyOn(soundmarksApi, 'listUsers').mockResolvedValue({ status: 'success', users: [] }) vi.spyOn(soundmarksApi, 'listUsers').mockResolvedValue({ status: 'success', users: [] })
mockEmptyQueue()
const del = vi.spyOn(soundmarksApi, 'deleteSoundmark').mockResolvedValue({ status: 'success' }) const del = vi.spyOn(soundmarksApi, 'deleteSoundmark').mockResolvedValue({ status: 'success' })
vi.spyOn(window, 'confirm').mockReturnValue(false) vi.spyOn(window, 'confirm').mockReturnValue(false)
...@@ -125,6 +181,7 @@ describe('AdminPanel', () => { ...@@ -125,6 +181,7 @@ describe('AdminPanel', () => {
it('promotes a user to business_admin from the Users tab', async () => { it('promotes a user to business_admin from the Users tab', async () => {
vi.spyOn(soundmarksApi, 'getAllSoundmarks').mockResolvedValue({ status: 'success', soundmarks: [] }) vi.spyOn(soundmarksApi, 'getAllSoundmarks').mockResolvedValue({ status: 'success', soundmarks: [] })
vi.spyOn(soundmarksApi, 'listUsers').mockResolvedValue({ status: 'success', users: [PLAIN_USER] }) vi.spyOn(soundmarksApi, 'listUsers').mockResolvedValue({ status: 'success', users: [PLAIN_USER] })
mockEmptyQueue()
const updateRole = vi.spyOn(soundmarksApi, 'updateUserRole').mockResolvedValue({ const updateRole = vi.spyOn(soundmarksApi, 'updateUserRole').mockResolvedValue({
status: 'success', status: 'success',
user: { id: PLAIN_USER.id, username: PLAIN_USER.username, role: 'business_admin' }, user: { id: PLAIN_USER.id, username: PLAIN_USER.username, role: 'business_admin' },
...@@ -143,9 +200,10 @@ describe('AdminPanel', () => { ...@@ -143,9 +200,10 @@ describe('AdminPanel', () => {
}) })
}) })
it('sets an anthem on a soundmark by picking from the public library', async () => { 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, 'getAllSoundmarks').mockResolvedValue({ status: 'success', soundmarks: [LANDMARK] })
vi.spyOn(soundmarksApi, 'listUsers').mockResolvedValue({ status: 'success', users: [] }) vi.spyOn(soundmarksApi, 'listUsers').mockResolvedValue({ status: 'success', users: [] })
mockEmptyQueue()
vi.spyOn(libraryApi, 'getLibrary').mockResolvedValue({ status: 'success', library: [] }) vi.spyOn(libraryApi, 'getLibrary').mockResolvedValue({ status: 'success', library: [] })
vi.spyOn(soundmarksApi, 'searchSongLibrary').mockResolvedValue({ vi.spyOn(soundmarksApi, 'searchSongLibrary').mockResolvedValue({
status: 'success', status: 'success',
...@@ -168,4 +226,55 @@ describe('AdminPanel', () => { ...@@ -168,4 +226,55 @@ describe('AdminPanel', () => {
expect(setSong).toHaveBeenCalledWith(LANDMARK.id, 99) expect(setSong).toHaveBeenCalledWith(LANDMARK.id, 99)
}) })
}) })
it('adds a track to a business-tier soundmark via the playlist manager', async () => {
vi.spyOn(soundmarksApi, 'getAllSoundmarks').mockResolvedValue({ status: 'success', soundmarks: [BUSINESS] })
vi.spyOn(soundmarksApi, 'listUsers').mockResolvedValue({ status: 'success', users: [] })
mockEmptyQueue()
vi.spyOn(libraryApi, 'getLibrary').mockResolvedValue({ status: 'success', library: [] })
vi.spyOn(soundmarksApi, 'searchSongLibrary').mockResolvedValue({
status: 'success',
results: [{ id: 100, title: 'Second Track', artist: 'Anyone', album: null, genre: null, coverart: null }],
})
const addTrack = vi.spyOn(soundmarksApi, 'addPlaylistTrack').mockResolvedValue({
status: 'success',
soundmark: {
...BUSINESS,
playlist: [...BUSINESS.playlist, { id: 100, title: 'Second Track', artist: 'Anyone', album: null, coverart: null }],
},
})
renderPanel()
await screen.findByText("Joe's Cafe")
await userEvent.click(screen.getByRole('button', { name: /Manage playlist/ }))
await userEvent.click(screen.getByRole('button', { name: 'Add track' }))
await userEvent.click(screen.getByRole('button', { name: 'Public Library' }))
await screen.findByText('Second Track')
await userEvent.click(screen.getByText('Second Track'))
await waitFor(() => {
expect(addTrack).toHaveBeenCalledWith(BUSINESS.id, 100)
})
})
it('shows the review queue and approves a suggestion', async () => {
vi.spyOn(soundmarksApi, 'getAllSoundmarks').mockResolvedValue({ status: 'success', soundmarks: [LANDMARK] })
vi.spyOn(soundmarksApi, 'listUsers').mockResolvedValue({ status: 'success', users: [] })
vi.spyOn(soundmarksApi, 'getReviewQueue').mockResolvedValue({ status: 'success', suggestions: [SUGGESTION] })
const approve = vi.spyOn(soundmarksApi, 'approveSuggestion').mockResolvedValue({
status: 'success',
suggestion: { ...SUGGESTION, status: 'approved' },
})
renderPanel()
await userEvent.click(screen.getByRole('button', { name: /review queue/ }))
await screen.findByText('Suggested Track')
expect(screen.getByText(/suggested by alex/)).toBeInTheDocument()
await userEvent.click(screen.getByRole('button', { name: 'Approve' }))
await waitFor(() => expect(approve).toHaveBeenCalledWith(SUGGESTION.id))
await waitFor(() => expect(screen.queryByText('Suggested Track')).not.toBeInTheDocument())
})
}) })
This diff is collapsed.
...@@ -13,12 +13,14 @@ const OWNED_MARK: soundmarksApi.Soundmark = { ...@@ -13,12 +13,14 @@ const OWNED_MARK: soundmarksApi.Soundmark = {
id: 1, id: 1,
name: "Joe's Cafe", name: "Joe's Cafe",
description: 'Downtown spot', description: 'Downtown spot',
tier: 'business',
latitude: 1, latitude: 1,
longitude: 2, longitude: 2,
radius_meters: 150, radius_meters: 150,
business_owner_id: 5, business_owner_id: 5,
business_owner_username: 'joe', business_owner_username: 'joe',
song: null, song: null,
playlist: [],
created_at: '2026-01-01T00:00:00Z', created_at: '2026-01-01T00:00:00Z',
proposal_count: 0, proposal_count: 0,
updated_at: '2026-01-01T00:00:00Z', updated_at: '2026-01-01T00:00:00Z',
...@@ -37,6 +39,21 @@ const MY_SONG = { ...@@ -37,6 +39,21 @@ const MY_SONG = {
added_at: '2026-01-01T00:00:00Z', added_at: '2026-01-01T00:00:00Z',
} }
const SUGGESTION: soundmarksApi.SoundmarkSuggestion = {
id: 500,
soundmark_id: OWNED_MARK.id,
soundmark_name: OWNED_MARK.name,
soundmark_tier: 'business',
song: { id: 20, title: 'Suggested Jam', artist: 'A Fan', album: null, coverart: null },
suggested_by_username: 'listener',
status: 'pending',
created_at: '2026-01-01T00:00:00Z',
}
function mockEmptyQueue() {
return vi.spyOn(soundmarksApi, 'getReviewQueue').mockResolvedValue({ status: 'success', suggestions: [] })
}
function renderPanel() { function renderPanel() {
return render( return render(
<MemoryRouter> <MemoryRouter>
...@@ -62,60 +79,111 @@ describe('BusinessPanel', () => { ...@@ -62,60 +79,111 @@ describe('BusinessPanel', () => {
it('shows an empty state when the caller owns no soundmarks', async () => { it('shows an empty state when the caller owns no soundmarks', async () => {
vi.spyOn(soundmarksApi, 'getMySoundmarks').mockResolvedValue({ status: 'success', soundmarks: [] }) vi.spyOn(soundmarksApi, 'getMySoundmarks').mockResolvedValue({ status: 'success', soundmarks: [] })
mockEmptyQueue()
renderPanel() renderPanel()
expect(await screen.findByText(/No soundmarks assigned/)).toBeInTheDocument() expect(await screen.findByText(/No soundmarks assigned/)).toBeInTheDocument()
}) })
it('lists owned soundmarks and shows "No anthem set" when none is assigned', async () => { it('lists owned soundmarks and shows "No anthem set" when none is assigned', async () => {
vi.spyOn(soundmarksApi, 'getMySoundmarks').mockResolvedValue({ status: 'success', soundmarks: [OWNED_MARK] }) vi.spyOn(soundmarksApi, 'getMySoundmarks').mockResolvedValue({ status: 'success', soundmarks: [OWNED_MARK] })
mockEmptyQueue()
renderPanel() renderPanel()
expect(await screen.findByText("Joe's Cafe")).toBeInTheDocument() expect(await screen.findByText("Joe's Cafe")).toBeInTheDocument()
expect(screen.getByText('No anthem set')).toBeInTheDocument() expect(screen.getByText('No anthem set')).toBeInTheDocument()
}) })
it('sets an anthem by picking a song from "My Library"', async () => { it('adds a track by picking a song from "My Library"', async () => {
vi.spyOn(soundmarksApi, 'getMySoundmarks').mockResolvedValue({ status: 'success', soundmarks: [OWNED_MARK] }) vi.spyOn(soundmarksApi, 'getMySoundmarks').mockResolvedValue({ status: 'success', soundmarks: [OWNED_MARK] })
mockEmptyQueue()
vi.spyOn(libraryApi, 'getLibrary').mockResolvedValue({ status: 'success', library: [MY_SONG] }) vi.spyOn(libraryApi, 'getLibrary').mockResolvedValue({ status: 'success', library: [MY_SONG] })
const setSong = vi.spyOn(soundmarksApi, 'setSoundmarkSong').mockResolvedValue({ const addTrack = vi.spyOn(soundmarksApi, 'addPlaylistTrack').mockResolvedValue({
status: 'success', status: 'success',
soundmark: { ...OWNED_MARK, song: { id: MY_SONG.id, title: MY_SONG.title, artist: MY_SONG.artist, album: null, coverart: null } }, soundmark: {
...OWNED_MARK,
song: { id: MY_SONG.id, title: MY_SONG.title, artist: MY_SONG.artist, album: null, coverart: null },
playlist: [{ id: MY_SONG.id, title: MY_SONG.title, artist: MY_SONG.artist, album: null, coverart: null }],
},
}) })
renderPanel() renderPanel()
await screen.findByText("Joe's Cafe") await screen.findByText("Joe's Cafe")
await userEvent.click(screen.getByRole('button', { name: 'Set anthem' })) await userEvent.click(screen.getByRole('button', { name: 'Add track' }))
await screen.findByText('My Own Track') await screen.findByText('My Own Track')
await userEvent.click(screen.getByText('My Own Track')) await userEvent.click(screen.getByText('My Own Track'))
await waitFor(() => { await waitFor(() => {
expect(setSong).toHaveBeenCalledWith(OWNED_MARK.id, MY_SONG.id) expect(addTrack).toHaveBeenCalledWith(OWNED_MARK.id, MY_SONG.id)
}) })
expect(await screen.findByText('My Own Track', { selector: 'p' })).toBeInTheDocument() expect(await screen.findByText('My Own Track', { selector: 'p' })).toBeInTheDocument()
}) })
it('clears an assigned anthem', async () => { it('removes the currently playing track', async () => {
const withSong = { ...OWNED_MARK, song: { id: 10, title: 'Current', artist: 'Someone', album: null, coverart: null } } const withSong = {
...OWNED_MARK,
song: { id: 10, title: 'Current', artist: 'Someone', album: null, coverart: null },
playlist: [{ id: 10, title: 'Current', artist: 'Someone', album: null, coverart: null }],
}
vi.spyOn(soundmarksApi, 'getMySoundmarks').mockResolvedValue({ status: 'success', soundmarks: [withSong] }) vi.spyOn(soundmarksApi, 'getMySoundmarks').mockResolvedValue({ status: 'success', soundmarks: [withSong] })
mockEmptyQueue()
vi.spyOn(libraryApi, 'getLibrary').mockResolvedValue({ status: 'success', library: [] }) vi.spyOn(libraryApi, 'getLibrary').mockResolvedValue({ status: 'success', library: [] })
const setSong = vi const removeTrack = vi
.spyOn(soundmarksApi, 'setSoundmarkSong') .spyOn(soundmarksApi, 'removePlaylistTrack')
.mockResolvedValue({ status: 'success', soundmark: { ...withSong, song: null } }) .mockResolvedValue({ status: 'success', soundmark: { ...withSong, song: null, playlist: [] } })
renderPanel() renderPanel()
await screen.findByText('Current') await screen.findByText('Current')
await userEvent.click(screen.getByRole('button', { name: 'Clear' })) await userEvent.click(screen.getByRole('button', { name: 'Remove current' }))
await waitFor(() => { await waitFor(() => {
expect(setSong).toHaveBeenCalledWith(withSong.id, null) expect(removeTrack).toHaveBeenCalledWith(withSong.id, 10)
}) })
expect(await screen.findByText('No anthem set')).toBeInTheDocument() expect(await screen.findByText('No anthem set')).toBeInTheDocument()
}) })
it('shows an error message if loading soundmarks fails', async () => { it('shows an error message if loading soundmarks fails', async () => {
vi.spyOn(soundmarksApi, 'getMySoundmarks').mockRejectedValue(new ApiError(500, 'Server exploded', null)) vi.spyOn(soundmarksApi, 'getMySoundmarks').mockRejectedValue(new ApiError(500, 'Server exploded', null))
mockEmptyQueue()
renderPanel() renderPanel()
expect(await screen.findByText('Server exploded')).toBeInTheDocument() expect(await screen.findByText('Server exploded')).toBeInTheDocument()
}) })
it('shows the review queue for this business and approves a suggestion', async () => {
vi.spyOn(soundmarksApi, 'getMySoundmarks').mockResolvedValue({ status: 'success', soundmarks: [OWNED_MARK] })
vi.spyOn(soundmarksApi, 'getReviewQueue').mockResolvedValue({ status: 'success', suggestions: [SUGGESTION] })
const approve = vi.spyOn(soundmarksApi, 'approveSuggestion').mockResolvedValue({
status: 'success',
suggestion: { ...SUGGESTION, status: 'approved' },
})
renderPanel()
await userEvent.click(screen.getByRole('button', { name: /review queue/ }))
await screen.findByText('Suggested Jam')
expect(screen.getByText(/suggested by listener/)).toBeInTheDocument()
await userEvent.click(screen.getByRole('button', { name: 'Approve' }))
await waitFor(() => expect(approve).toHaveBeenCalledWith(SUGGESTION.id))
await waitFor(() => expect(screen.queryByText('Suggested Jam')).not.toBeInTheDocument())
})
it('rejects a suggestion without changing the playlist', async () => {
vi.spyOn(soundmarksApi, 'getMySoundmarks').mockResolvedValue({ status: 'success', soundmarks: [OWNED_MARK] })
vi.spyOn(soundmarksApi, 'getReviewQueue').mockResolvedValue({ status: 'success', suggestions: [SUGGESTION] })
const reject = vi.spyOn(soundmarksApi, 'rejectSuggestion').mockResolvedValue({
status: 'success',
suggestion: { ...SUGGESTION, status: 'rejected' },
})
renderPanel()
await userEvent.click(screen.getByRole('button', { name: /review queue/ }))
await screen.findByText('Suggested Jam')
await userEvent.click(screen.getByRole('button', { name: 'Reject' }))
await waitFor(() => expect(reject).toHaveBeenCalledWith(SUGGESTION.id))
await waitFor(() => expect(screen.queryByText('Suggested Jam')).not.toBeInTheDocument())
})
}) })
This diff is collapsed.
...@@ -12,23 +12,37 @@ const FOUND_MARK: soundmarksApi.NearbySoundmark = { ...@@ -12,23 +12,37 @@ const FOUND_MARK: soundmarksApi.NearbySoundmark = {
id: 1, id: 1,
name: 'Joe\'s Cafe', name: 'Joe\'s Cafe',
description: 'The house anthem.', description: 'The house anthem.',
tier: 'business',
latitude: 37.7749, latitude: 37.7749,
longitude: -122.4194, longitude: -122.4194,
radius_meters: 150, radius_meters: 150,
business_owner_id: 5, business_owner_id: 5,
business_owner_username: 'joe', business_owner_username: 'joe',
song: { id: 42, title: 'Cafe Anthem', artist: 'Local Band', album: null, coverart: null }, song: { id: 42, title: 'Cafe Anthem', artist: 'Local Band', album: null, coverart: null },
playlist: [{ id: 42, title: 'Cafe Anthem', artist: 'Local Band', album: null, coverart: null }],
created_at: '2026-01-01T00:00:00Z', created_at: '2026-01-01T00:00:00Z',
proposal_count: 0, proposal_count: 0,
updated_at: '2026-01-01T00:00:00Z', updated_at: '2026-01-01T00:00:00Z',
distance_meters: 12, distance_meters: 12,
} }
const NO_ANTHEM_MARK: soundmarksApi.NearbySoundmark = { const COMMUNITY_MARK: soundmarksApi.NearbySoundmark = {
...FOUND_MARK, ...FOUND_MARK,
id: 3,
name: 'Community Corner',
tier: 'community',
business_owner_id: null,
business_owner_username: null,
playlist: [],
proposal_count: 1,
}
const NO_ANTHEM_MARK: soundmarksApi.NearbySoundmark = {
...COMMUNITY_MARK,
id: 2, id: 2,
name: 'New Landmark', name: 'New Landmark',
song: null, song: null,
proposal_count: 0,
} }
const EXISTING_PROPOSAL: soundmarksApi.SoundmarkProposal = { const EXISTING_PROPOSAL: soundmarksApi.SoundmarkProposal = {
...@@ -100,6 +114,7 @@ describe('Nearby', () => { ...@@ -100,6 +114,7 @@ describe('Nearby', () => {
await waitFor(() => expect(screen.getByText('Cafe Anthem')).toBeInTheDocument()) await waitFor(() => expect(screen.getByText('Cafe Anthem')).toBeInTheDocument())
expect(screen.getByText('Local Band')).toBeInTheDocument() expect(screen.getByText('Local Band')).toBeInTheDocument()
expect(screen.getByText(/Joe's Cafe/)).toBeInTheDocument() expect(screen.getByText(/Joe's Cafe/)).toBeInTheDocument()
expect(screen.getByText('Business')).toBeInTheDocument()
expect(soundmarksApi.getNearbySoundmarks).toHaveBeenCalledWith(37.7749, -122.4194) expect(soundmarksApi.getNearbySoundmarks).toHaveBeenCalledWith(37.7749, -122.4194)
}) })
...@@ -146,7 +161,7 @@ describe('Nearby', () => { ...@@ -146,7 +161,7 @@ describe('Nearby', () => {
expect(screen.getByRole('button', { name: 'Try again' })).toBeInTheDocument() expect(screen.getByRole('button', { name: 'Try again' })).toBeInTheDocument()
}) })
it('shows a "propose one" prompt (no play button) for a soundmark with no anthem yet', async () => { it('shows a "propose one" prompt (no play button) for a community soundmark with no anthem yet', async () => {
mockGeolocation({ succeed: true }) mockGeolocation({ succeed: true })
vi.spyOn(soundmarksApi, 'getNearbySoundmarks').mockResolvedValue({ vi.spyOn(soundmarksApi, 'getNearbySoundmarks').mockResolvedValue({
status: 'success', status: 'success',
...@@ -161,9 +176,22 @@ describe('Nearby', () => { ...@@ -161,9 +176,22 @@ describe('Nearby', () => {
expect(screen.getByRole('button', { name: 'Propose a song' })).toBeInTheDocument() expect(screen.getByRole('button', { name: 'Propose a song' })).toBeInTheDocument()
}) })
it('lists existing proposals with their vote counts', async () => { it('shows a "suggest a song" prompt (no votes) for a business soundmark', async () => {
mockGeolocation({ succeed: true }) mockGeolocation({ succeed: true })
vi.spyOn(soundmarksApi, 'getNearbySoundmarks').mockResolvedValue({ status: 'success', soundmarks: [FOUND_MARK] }) vi.spyOn(soundmarksApi, 'getNearbySoundmarks').mockResolvedValue({ status: 'success', soundmarks: [FOUND_MARK] })
renderNearby()
await userEvent.click(screen.getByRole('button', { name: 'Find soundmarks near me' }))
await screen.findByText(/Joe's Cafe/)
expect(screen.getByRole('button', { name: 'Suggest a song' })).toBeInTheDocument()
expect(screen.queryByRole('button', { name: 'Propose a song' })).not.toBeInTheDocument()
expect(screen.getByText(/review queue/)).toBeInTheDocument()
})
it('lists existing proposals with their vote counts for a community soundmark', async () => {
mockGeolocation({ succeed: true })
vi.spyOn(soundmarksApi, 'getNearbySoundmarks').mockResolvedValue({ status: 'success', soundmarks: [COMMUNITY_MARK] })
vi.spyOn(soundmarksApi, 'getProposals').mockResolvedValue({ status: 'success', proposals: [EXISTING_PROPOSAL] }) vi.spyOn(soundmarksApi, 'getProposals').mockResolvedValue({ status: 'success', proposals: [EXISTING_PROPOSAL] })
renderNearby() renderNearby()
...@@ -175,7 +203,7 @@ describe('Nearby', () => { ...@@ -175,7 +203,7 @@ describe('Nearby', () => {
it('votes for a proposal and reflects the updated count', async () => { it('votes for a proposal and reflects the updated count', async () => {
mockGeolocation({ succeed: true }) mockGeolocation({ succeed: true })
vi.spyOn(soundmarksApi, 'getNearbySoundmarks').mockResolvedValue({ status: 'success', soundmarks: [FOUND_MARK] }) vi.spyOn(soundmarksApi, 'getNearbySoundmarks').mockResolvedValue({ status: 'success', soundmarks: [COMMUNITY_MARK] })
const getProposals = vi.spyOn(soundmarksApi, 'getProposals') const getProposals = vi.spyOn(soundmarksApi, 'getProposals')
getProposals.mockResolvedValueOnce({ status: 'success', proposals: [EXISTING_PROPOSAL] }) getProposals.mockResolvedValueOnce({ status: 'success', proposals: [EXISTING_PROPOSAL] })
const vote = vi.spyOn(soundmarksApi, 'voteForProposal').mockResolvedValue({ const vote = vi.spyOn(soundmarksApi, 'voteForProposal').mockResolvedValue({
...@@ -193,14 +221,14 @@ describe('Nearby', () => { ...@@ -193,14 +221,14 @@ describe('Nearby', () => {
await userEvent.click(screen.getByRole('button', { name: 'Vote for Cafe Anthem' })) await userEvent.click(screen.getByRole('button', { name: 'Vote for Cafe Anthem' }))
await waitFor(() => expect(vote).toHaveBeenCalledWith(FOUND_MARK.id, EXISTING_PROPOSAL.id)) await waitFor(() => expect(vote).toHaveBeenCalledWith(COMMUNITY_MARK.id, EXISTING_PROPOSAL.id))
expect(await screen.findByText('4 votes')).toBeInTheDocument() expect(await screen.findByText('4 votes')).toBeInTheDocument()
}) })
it('removes a vote when toggling an already-voted proposal', async () => { it('removes a vote when toggling an already-voted proposal', async () => {
const votedProposal = { ...EXISTING_PROPOSAL, has_voted: true } const votedProposal = { ...EXISTING_PROPOSAL, has_voted: true }
mockGeolocation({ succeed: true }) mockGeolocation({ succeed: true })
vi.spyOn(soundmarksApi, 'getNearbySoundmarks').mockResolvedValue({ status: 'success', soundmarks: [FOUND_MARK] }) vi.spyOn(soundmarksApi, 'getNearbySoundmarks').mockResolvedValue({ status: 'success', soundmarks: [COMMUNITY_MARK] })
const getProposals = vi.spyOn(soundmarksApi, 'getProposals') const getProposals = vi.spyOn(soundmarksApi, 'getProposals')
getProposals.mockResolvedValueOnce({ status: 'success', proposals: [votedProposal] }) getProposals.mockResolvedValueOnce({ status: 'success', proposals: [votedProposal] })
const remove = vi.spyOn(soundmarksApi, 'removeVote').mockResolvedValue({ status: 'success' }) const remove = vi.spyOn(soundmarksApi, 'removeVote').mockResolvedValue({ status: 'success' })
...@@ -215,13 +243,33 @@ describe('Nearby', () => { ...@@ -215,13 +243,33 @@ describe('Nearby', () => {
await userEvent.click(screen.getByRole('button', { name: 'Remove your vote for Cafe Anthem' })) await userEvent.click(screen.getByRole('button', { name: 'Remove your vote for Cafe Anthem' }))
await waitFor(() => expect(remove).toHaveBeenCalledWith(FOUND_MARK.id)) await waitFor(() => expect(remove).toHaveBeenCalledWith(COMMUNITY_MARK.id))
expect(await screen.findByText('2 votes')).toBeInTheDocument() expect(await screen.findByText('2 votes')).toBeInTheDocument()
}) })
it('proposes a song via the song picker', async () => { it('only shows the top 3 proposals even when more exist', async () => {
mockGeolocation({ succeed: true }) mockGeolocation({ succeed: true })
vi.spyOn(soundmarksApi, 'getNearbySoundmarks').mockResolvedValue({ status: 'success', soundmarks: [FOUND_MARK] }) vi.spyOn(soundmarksApi, 'getNearbySoundmarks').mockResolvedValue({ status: 'success', soundmarks: [COMMUNITY_MARK] })
const many = [1, 2, 3, 4].map((n) => ({
...EXISTING_PROPOSAL,
id: n,
song: { id: n, title: `Pick ${n}`, artist: 'Artist', album: null, coverart: null },
vote_count: 5 - n,
}))
vi.spyOn(soundmarksApi, 'getProposals').mockResolvedValue({ status: 'success', proposals: many })
renderNearby()
await userEvent.click(screen.getByRole('button', { name: 'Find soundmarks near me' }))
await screen.findByText('Pick 1')
expect(screen.getByText('Pick 2')).toBeInTheDocument()
expect(screen.getByText('Pick 3')).toBeInTheDocument()
expect(screen.queryByText('Pick 4')).not.toBeInTheDocument()
})
it('proposes a song via the song picker on a community soundmark', async () => {
mockGeolocation({ succeed: true })
vi.spyOn(soundmarksApi, 'getNearbySoundmarks').mockResolvedValue({ status: 'success', soundmarks: [COMMUNITY_MARK] })
vi.spyOn(libraryApi, 'getLibrary').mockResolvedValue({ vi.spyOn(libraryApi, 'getLibrary').mockResolvedValue({
status: 'success', status: 'success',
library: [ library: [
...@@ -246,12 +294,57 @@ describe('Nearby', () => { ...@@ -246,12 +294,57 @@ describe('Nearby', () => {
renderNearby() renderNearby()
await userEvent.click(screen.getByRole('button', { name: 'Find soundmarks near me' })) await userEvent.click(screen.getByRole('button', { name: 'Find soundmarks near me' }))
await screen.findByText(/Joe's Cafe/) await screen.findByText(/Community Corner/)
await userEvent.click(screen.getByRole('button', { name: 'Propose a song' })) await userEvent.click(screen.getByRole('button', { name: 'Propose a song' }))
await userEvent.click(await screen.findByText('My Pick')) await userEvent.click(await screen.findByText('My Pick'))
await waitFor(() => expect(propose).toHaveBeenCalledWith(FOUND_MARK.id, 55)) await waitFor(() => expect(propose).toHaveBeenCalledWith(COMMUNITY_MARK.id, 55))
})
it('suggests a song via the song picker on a business soundmark, showing a pending confirmation', async () => {
mockGeolocation({ succeed: true })
vi.spyOn(soundmarksApi, 'getNearbySoundmarks').mockResolvedValue({ status: 'success', soundmarks: [FOUND_MARK] })
vi.spyOn(libraryApi, 'getLibrary').mockResolvedValue({
status: 'success',
library: [
{
id: 55,
user_id: 1,
title: 'My Pick',
artist: 'Me',
album: null,
genre: null,
coverart: null,
lyrics: null,
file_path: '/x.mp3',
added_at: '2026-01-01T00:00:00Z',
},
],
})
const suggest = vi.spyOn(soundmarksApi, 'suggestSong').mockResolvedValue({
status: 'success',
suggestion: {
id: 300,
soundmark_id: FOUND_MARK.id,
soundmark_name: FOUND_MARK.name,
soundmark_tier: 'business',
song: { id: 55, title: 'My Pick', artist: 'Me', album: null, coverart: null },
suggested_by_username: 'me',
status: 'pending',
created_at: '2026-01-01T00:00:00Z',
},
})
renderNearby()
await userEvent.click(screen.getByRole('button', { name: 'Find soundmarks near me' }))
await screen.findByText(/Joe's Cafe/)
await userEvent.click(screen.getByRole('button', { name: 'Suggest a song' }))
await userEvent.click(await screen.findByText('My Pick'))
await waitFor(() => expect(suggest).toHaveBeenCalledWith(FOUND_MARK.id, 55))
expect(await screen.findByText('Suggested')).toBeInTheDocument()
}) })
it('shows a clear, accurate message on an insecure origin instead of a misleading "permission denied"', async () => { it('shows a clear, accurate message on an insecure origin instead of a misleading "permission denied"', async () => {
......
import { useEffect, useRef, useState } from 'react' import { useEffect, useRef, useState } from 'react'
import { MapPin, Music2, Pause, Play, Plus, ThumbsUp } from 'lucide-react' import { Check, ListMusic, MapPin, Music2, Pause, Play, Plus, ThumbsUp } from 'lucide-react'
import { Layout } from '../components/Layout' import { Layout } from '../components/Layout'
import { Button } from '../components/ui/Button' import { Button } from '../components/ui/Button'
import { EmptyState } from '../components/ui/EmptyState' import { EmptyState } from '../components/ui/EmptyState'
...@@ -12,6 +12,7 @@ import { ...@@ -12,6 +12,7 @@ import {
getProposals, getProposals,
proposeSong, proposeSong,
removeVote, removeVote,
suggestSong,
voteForProposal, voteForProposal,
type NearbySoundmark, type NearbySoundmark,
type SoundmarkProposal, type SoundmarkProposal,
...@@ -20,6 +21,12 @@ import { usePlayer } from '../context/PlayerContext' ...@@ -20,6 +21,12 @@ import { usePlayer } from '../context/PlayerContext'
type Status = 'idle' | 'locating' | 'ready' | 'error' type Status = 'idle' | 'locating' | 'ready' | 'error'
const TIER_LABEL: Record<NearbySoundmark['tier'], string> = {
major: 'Landmark',
business: 'Business',
community: 'Community spot',
}
function toPlayable(sm: NearbySoundmark & { song: NonNullable<NearbySoundmark['song']> }) { function toPlayable(sm: NearbySoundmark & { song: NonNullable<NearbySoundmark['song']> }) {
return { return {
// Negative to guarantee this can never collide with a real LibrarySong id - see the // Negative to guarantee this can never collide with a real LibrarySong id - see the
...@@ -42,6 +49,7 @@ export function Nearby() { ...@@ -42,6 +49,7 @@ export function Nearby() {
const [proposals, setProposals] = useState<SoundmarkProposal[]>([]) const [proposals, setProposals] = useState<SoundmarkProposal[]>([])
const [showSongPicker, setShowSongPicker] = useState(false) const [showSongPicker, setShowSongPicker] = useState(false)
const [votingKey, setVotingKey] = useState<number | 'propose' | null>(null) const [votingKey, setVotingKey] = useState<number | 'propose' | null>(null)
const [suggestionSent, setSuggestionSent] = useState(false)
const watchIdRef = useRef<number | null>(null) const watchIdRef = useRef<number | null>(null)
const { currentSong, isPlaying, isLoading: streamLoading, toggle } = usePlayer() const { currentSong, isPlaying, isLoading: streamLoading, toggle } = usePlayer()
...@@ -102,19 +110,21 @@ export function Nearby() { ...@@ -102,19 +110,21 @@ export function Nearby() {
const closest = soundmarks[0] const closest = soundmarks[0]
const active = closest?.song ? toPlayable(closest as NearbySoundmark & { song: NonNullable<NearbySoundmark['song']> }) : null const active = closest?.song ? toPlayable(closest as NearbySoundmark & { song: NonNullable<NearbySoundmark['song']> }) : null
const isCurrent = !!active && currentSong?.id === active.id const isCurrent = !!active && currentSong?.id === active.id
const isCommunity = closest?.tier === 'community'
// Refetch proposals when the detected soundmark itself changes (not on every watchPosition // Refetch proposals when the detected soundmark itself changes (not on every watchPosition
// tick, which produces a fresh `soundmarks` array even when you haven't actually moved to a // tick, which produces a fresh `soundmarks` array even when you haven't actually moved to a
// different one). // different one).
useEffect(() => { useEffect(() => {
if (!closest) { setSuggestionSent(false)
if (!closest || closest.tier !== 'community') {
setProposals([]) setProposals([])
return return
} }
getProposals(closest.id) getProposals(closest.id)
.then((res) => setProposals(res.proposals)) .then((res) => setProposals(res.proposals))
.catch(() => setProposals([])) .catch(() => setProposals([]))
}, [closest?.id]) }, [closest?.id, closest?.tier])
function refreshAfterVoteChange(soundmarkId: number) { function refreshAfterVoteChange(soundmarkId: number) {
getProposals(soundmarkId) getProposals(soundmarkId)
...@@ -146,26 +156,32 @@ export function Nearby() { ...@@ -146,26 +156,32 @@ export function Nearby() {
} }
} }
async function handlePropose(song: { id: number }) { async function handleSongPicked(song: { id: number }) {
if (!closest) return if (!closest) return
setShowSongPicker(false) setShowSongPicker(false)
setVotingKey('propose') setVotingKey('propose')
try { try {
if (isCommunity) {
await proposeSong(closest.id, song.id) await proposeSong(closest.id, song.id)
refreshAfterVoteChange(closest.id) refreshAfterVoteChange(closest.id)
} else {
await suggestSong(closest.id, song.id)
setSuggestionSent(true)
}
} catch (err) { } catch (err) {
setError(err instanceof ApiError ? err.message : 'Failed to propose that song') setError(err instanceof ApiError ? err.message : 'Failed to submit that song')
} finally { } finally {
setVotingKey(null) setVotingKey(null)
} }
} }
const topProposals = proposals.slice(0, 3)
return ( return (
<Layout title="Soundmarks"> <Layout title="Soundmarks">
<p className="mb-6 text-sm leading-relaxed text-neutral-400"> <p className="mb-6 text-sm leading-relaxed text-neutral-400">
Find the anthem playing at this spot - some places have a song tied to them, either because it's Find the anthem playing at this spot. Landmarks and businesses have a curated pick you can suggest
significant here or a local business chose it. You can propose your own pick too - whichever song changes to; community spots are fully driven by votes - whichever song has the most wins.
has the most votes is what plays.
</p> </p>
{status === 'idle' && ( {status === 'idle' && (
...@@ -210,6 +226,9 @@ export function Nearby() { ...@@ -210,6 +226,9 @@ export function Nearby() {
<p className="mb-2 flex items-center gap-1.5 px-1 text-xs font-medium uppercase tracking-wide text-emerald-400"> <p className="mb-2 flex items-center gap-1.5 px-1 text-xs font-medium uppercase tracking-wide text-emerald-400">
<MapPin size={12} strokeWidth={2.5} /> <MapPin size={12} strokeWidth={2.5} />
{closest.name} {closest.name}
<span className="ml-auto rounded-full bg-neutral-800 px-2 py-0.5 text-[10px] font-medium normal-case tracking-normal text-neutral-400">
{TIER_LABEL[closest.tier]}
</span>
</p> </p>
{active ? ( {active ? (
...@@ -245,14 +264,37 @@ export function Nearby() { ...@@ -245,14 +264,37 @@ export function Nearby() {
<div className="flex h-16 w-16 shrink-0 items-center justify-center rounded-lg bg-neutral-800 text-neutral-600"> <div className="flex h-16 w-16 shrink-0 items-center justify-center rounded-lg bg-neutral-800 text-neutral-600">
<Music2 size={20} strokeWidth={1.75} /> <Music2 size={20} strokeWidth={1.75} />
</div> </div>
<p className="text-sm text-neutral-400">No anthem here yet - propose one below.</p> <p className="text-sm text-neutral-400">
{isCommunity ? 'No anthem here yet - propose one below.' : 'No anthem set here yet.'}
</p>
</div> </div>
)} )}
{closest.description && <p className="mt-3 px-1 text-sm text-neutral-400">{closest.description}</p>} {closest.description && <p className="mt-3 px-1 text-sm text-neutral-400">{closest.description}</p>}
{closest.tier === 'business' && closest.playlist.length > 1 && (
<div className="mt-4 border-t border-neutral-800 pt-3"> <div className="mt-4 border-t border-neutral-800 pt-3">
<p className="mb-2 flex items-center gap-1.5 px-1 text-xs font-medium uppercase tracking-wide text-neutral-500">
<ListMusic size={12} strokeWidth={2.5} />
Playlist
</p>
<ul className="divide-y divide-neutral-800/60">
{closest.playlist.map((track) => (
<li key={track.id} className="flex items-center gap-3 px-1 py-2">
<div className="min-w-0 flex-1">
<p className="truncate text-sm font-medium text-white">{track.title}</p>
<p className="truncate text-xs text-neutral-500">{track.artist}</p>
</div>
</li>
))}
</ul>
</div>
)}
<div className="mt-4 border-t border-neutral-800 pt-3">
{isCommunity ? (
<>
<div className="mb-2 flex items-center justify-between px-1"> <div className="mb-2 flex items-center justify-between px-1">
<p className="text-xs font-medium uppercase tracking-wide text-neutral-500">Proposals</p> <p className="text-xs font-medium uppercase tracking-wide text-neutral-500">Top proposals</p>
<button <button
onClick={() => setShowSongPicker(true)} onClick={() => setShowSongPicker(true)}
disabled={votingKey === 'propose'} disabled={votingKey === 'propose'}
...@@ -263,13 +305,13 @@ export function Nearby() { ...@@ -263,13 +305,13 @@ export function Nearby() {
</button> </button>
</div> </div>
{proposals.length === 0 ? ( {topProposals.length === 0 ? (
<p className="px-1 text-sm text-neutral-500"> <p className="px-1 text-sm text-neutral-500">
No proposals yet - be the first to suggest a song for this spot. No proposals yet - be the first to suggest a song for this spot.
</p> </p>
) : ( ) : (
<ul className="divide-y divide-neutral-800/60"> <ul className="divide-y divide-neutral-800/60">
{proposals.map((proposal) => ( {topProposals.map((proposal) => (
<li key={proposal.id} className="flex items-center gap-3 py-2"> <li key={proposal.id} className="flex items-center gap-3 py-2">
<button <button
onClick={() => handleVoteToggle(proposal)} onClick={() => handleVoteToggle(proposal)}
...@@ -299,11 +341,34 @@ export function Nearby() { ...@@ -299,11 +341,34 @@ export function Nearby() {
))} ))}
</ul> </ul>
)} )}
</>
) : (
<div className="flex items-center justify-between px-1">
<p className="text-xs text-neutral-500">
Suggestions here go to {closest.tier === 'major' ? "Stax's" : "the owner's"} review queue.
</p>
{suggestionSent ? (
<span className="flex items-center gap-1 text-xs font-medium text-emerald-400">
<Check size={13} strokeWidth={2.5} />
Suggested
</span>
) : (
<button
onClick={() => setShowSongPicker(true)}
disabled={votingKey === 'propose'}
className="flex shrink-0 items-center gap-1 text-xs font-medium text-emerald-400 transition-colors hover:text-emerald-300 disabled:opacity-50"
>
<Plus size={13} strokeWidth={2.5} />
Suggest a song
</button>
)}
</div>
)}
</div> </div>
</div> </div>
)} )}
{showSongPicker && <SongPicker onClose={() => setShowSongPicker(false)} onSelect={handlePropose} />} {showSongPicker && <SongPicker onClose={() => setShowSongPicker(false)} onSelect={handleSongPicked} />}
</Layout> </Layout>
) )
} }
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