Commit 1df8a1ab authored by Aryan Noshirvnai's avatar Aryan Noshirvnai

Add three-tier Soundmarks: major landmarks, business playlists, community voting

Adds a tier column (major/business/community) with tier-specific
governance: major locations get a single super-admin-set anthem,
businesses get an owner-managed playlist, community spots stay fully
vote-driven. Adds a suggestion/review-queue system (SoundmarkSuggestion)
for major and business tiers, scoped so business admins only see
suggestions for soundmarks they own while super admins see everything.

Migration backfills tier from the existing business_owner_id (owned ->
business, unowned -> major) and seeds each business's playlist from its
old single song_id so existing anthems aren't silently dropped.
Co-Authored-By: 's avatarClaude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019i3NAUkLkHNbsPg5vKfzF9
parent 9531f3a9
Pipeline #1061 passed with stage
in 3 minutes and 41 seconds
"""add soundmark tiers, playlists, and suggestions
Revision ID: e612e2750fa2
Revises: 63839d131d50
Create Date: 2026-08-12 05:51:26.141644
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision: str = 'e612e2750fa2'
down_revision: Union[str, Sequence[str], None] = '63839d131d50'
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None:
"""Upgrade schema."""
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('soundmark_playlist_tracks',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('soundmark_id', sa.Integer(), nullable=True),
sa.Column('song_id', sa.Integer(), nullable=True),
sa.Column('position', sa.Integer(), nullable=True),
sa.Column('added_at', sa.DateTime(), nullable=True),
sa.ForeignKeyConstraint(['song_id'], ['library_songs.id'], ),
sa.ForeignKeyConstraint(['soundmark_id'], ['soundmarks.id'], ),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('soundmark_id', 'song_id', name='uq_soundmark_playlist_song')
)
op.create_index(op.f('ix_soundmark_playlist_tracks_id'), 'soundmark_playlist_tracks', ['id'], unique=False)
op.create_index(op.f('ix_soundmark_playlist_tracks_soundmark_id'), 'soundmark_playlist_tracks', ['soundmark_id'], unique=False)
op.create_table('soundmark_suggestions',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('soundmark_id', sa.Integer(), nullable=True),
sa.Column('song_id', sa.Integer(), nullable=True),
sa.Column('suggested_by_user_id', sa.Integer(), nullable=True),
sa.Column('status', sa.String(), nullable=True),
sa.Column('reviewed_by_user_id', sa.Integer(), nullable=True),
sa.Column('reviewed_at', sa.DateTime(), nullable=True),
sa.Column('created_at', sa.DateTime(), nullable=True),
sa.ForeignKeyConstraint(['reviewed_by_user_id'], ['users.id'], ),
sa.ForeignKeyConstraint(['song_id'], ['library_songs.id'], ),
sa.ForeignKeyConstraint(['soundmark_id'], ['soundmarks.id'], ),
sa.ForeignKeyConstraint(['suggested_by_user_id'], ['users.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_index(op.f('ix_soundmark_suggestions_id'), 'soundmark_suggestions', ['id'], unique=False)
op.create_index(op.f('ix_soundmark_suggestions_soundmark_id'), 'soundmark_suggestions', ['soundmark_id'], unique=False)
op.create_index(op.f('ix_soundmark_suggestions_status'), 'soundmark_suggestions', ['status'], unique=False)
# server_default backfills existing rows with the model's own default ('community') -
# without it, adding a NOT NULL column to a table that already has rows fails.
op.add_column('soundmarks', sa.Column('tier', sa.String(), nullable=False, server_default='community'))
# ### end Alembic commands ###
# Data migration: existing soundmarks predate tiers, but they were all created by an
# admin through the super admin panel - not submitted by the public - so the closest
# honest classification is by whether they have an owner, not a blanket "community".
op.execute("UPDATE soundmarks SET tier = 'business' WHERE business_owner_id IS NOT NULL")
op.execute("UPDATE soundmarks SET tier = 'major' WHERE business_owner_id IS NULL")
# Business tier no longer plays sm.song_id directly (it plays the first playlist track) -
# without this, every pre-existing business soundmark that had a song set the old way would
# silently go anthem-less until someone manually re-added the same song to its playlist.
op.execute(
"INSERT INTO soundmark_playlist_tracks (soundmark_id, song_id, position) "
"SELECT id, song_id, 0 FROM soundmarks WHERE business_owner_id IS NOT NULL AND song_id IS NOT NULL"
)
def downgrade() -> None:
"""Downgrade schema."""
# ### commands auto generated by Alembic - please adjust! ###
op.drop_column('soundmarks', 'tier')
op.drop_index(op.f('ix_soundmark_suggestions_status'), table_name='soundmark_suggestions')
op.drop_index(op.f('ix_soundmark_suggestions_soundmark_id'), table_name='soundmark_suggestions')
op.drop_index(op.f('ix_soundmark_suggestions_id'), table_name='soundmark_suggestions')
op.drop_table('soundmark_suggestions')
op.drop_index(op.f('ix_soundmark_playlist_tracks_soundmark_id'), table_name='soundmark_playlist_tracks')
op.drop_index(op.f('ix_soundmark_playlist_tracks_id'), table_name='soundmark_playlist_tracks')
op.drop_table('soundmark_playlist_tracks')
# ### end Alembic commands ###
import math
import os
from datetime import datetime, timezone
from typing import Optional
import httpx
......@@ -9,12 +10,22 @@ from pydantic import BaseModel
from sqlalchemy.orm import Session
from src.core.config import logger
from src.core.database import get_db, LibrarySong, Soundmark, SoundmarkProposal, SoundmarkProposalVote, User
from src.core.database import (
get_db,
LibrarySong,
Soundmark,
SoundmarkPlaylistTrack,
SoundmarkProposal,
SoundmarkProposalVote,
SoundmarkSuggestion,
User,
)
from src.core.security import get_current_business_admin, get_current_super_admin, get_current_user, is_super_admin
router = APIRouter(prefix="/soundmarks", tags=["Soundmarks"])
VALID_ROLES = {"user", "business_admin", "super_admin"}
VALID_TIERS = {"major", "business", "community"}
# Nominatim's usage policy requires a real, identifying User-Agent - browsers won't let JS set
# a custom one on a raw fetch(), which is the main reason this is proxied server-side rather
# than called directly from the webapp.
......@@ -29,12 +40,48 @@ def _haversine_meters(lat1: float, lon1: float, lat2: float, lon2: float) -> flo
return R * 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))
def _validate_tier_and_owner(tier: str, business_owner_id: Optional[int]) -> None:
if tier not in VALID_TIERS:
raise HTTPException(status_code=422, detail=f"tier must be one of {sorted(VALID_TIERS)}")
if tier == "business" and business_owner_id is None:
raise HTTPException(status_code=422, detail="business-tier soundmarks require a business_owner_id")
if tier != "business" and business_owner_id is not None:
raise HTTPException(status_code=422, detail="only business-tier soundmarks can have an owner")
def _get_playlist(sm: Soundmark, db: Session) -> list:
tracks = (
db.query(SoundmarkPlaylistTrack)
.filter(SoundmarkPlaylistTrack.soundmark_id == sm.id)
.order_by(SoundmarkPlaylistTrack.position, SoundmarkPlaylistTrack.added_at)
.all()
)
songs = []
for t in tracks:
song = db.query(LibrarySong).filter(LibrarySong.id == t.song_id).first()
if song:
songs.append(
{"id": song.id, "title": song.title, "artist": song.artist, "album": song.album, "coverart": song.coverart}
)
return songs
def _resolve_active_song_id(sm: Soundmark, db: Session) -> Optional[int]:
"""The song that actually plays: whichever proposal has the most votes, ties broken by
whichever was proposed first. Soundmark.song_id (set directly via PATCH .../song) is only
the fallback for a soundmark with no proposals yet - see set_soundmark_song, which turns
every direct song assignment into a proposal (with the setter's own vote) so it competes
fairly instead of being silently overridden by a single stray vote."""
"""What actually plays, resolved differently per tier:
- "major": the single super-admin-set song_id, directly.
- "business": the first track in the owner's playlist (by position, then recency).
- "community": whichever proposal has the most votes (ties broken by earliest proposed) -
song_id itself is only a legacy fallback here, for rows that predate proposals entirely."""
if sm.tier == "major":
return sm.song_id
if sm.tier == "business":
featured = (
db.query(SoundmarkPlaylistTrack)
.filter(SoundmarkPlaylistTrack.soundmark_id == sm.id)
.order_by(SoundmarkPlaylistTrack.position, SoundmarkPlaylistTrack.added_at)
.first()
)
return featured.song_id if featured else None
proposals = db.query(SoundmarkProposal).filter(SoundmarkProposal.soundmark_id == sm.id).all()
if not proposals:
return sm.song_id
......@@ -50,11 +97,16 @@ def _serialize(sm: Soundmark, db: Session) -> dict:
active_song_id = _resolve_active_song_id(sm, db)
song = db.query(LibrarySong).filter(LibrarySong.id == active_song_id).first() if active_song_id else None
owner = db.query(User).filter(User.id == sm.business_owner_id).first() if sm.business_owner_id else None
proposal_count = db.query(SoundmarkProposal).filter(SoundmarkProposal.soundmark_id == sm.id).count()
proposal_count = (
db.query(SoundmarkProposal).filter(SoundmarkProposal.soundmark_id == sm.id).count()
if sm.tier == "community"
else 0
)
return {
"id": sm.id,
"name": sm.name,
"description": sm.description,
"tier": sm.tier,
"latitude": sm.latitude,
"longitude": sm.longitude,
"radius_meters": sm.radius_meters,
......@@ -71,6 +123,7 @@ def _serialize(sm: Soundmark, db: Session) -> dict:
if song
else None
),
"playlist": _get_playlist(sm, db) if sm.tier == "business" else [],
"proposal_count": proposal_count,
"created_at": sm.created_at,
"updated_at": sm.updated_at,
......@@ -101,6 +154,26 @@ def _serialize_proposal(p: SoundmarkProposal, db: Session, current_user_id: int)
}
def _serialize_suggestion(s: SoundmarkSuggestion, db: Session) -> dict:
song = db.query(LibrarySong).filter(LibrarySong.id == s.song_id).first()
sm = db.query(Soundmark).filter(Soundmark.id == s.soundmark_id).first()
suggester = db.query(User).filter(User.id == s.suggested_by_user_id).first()
return {
"id": s.id,
"soundmark_id": s.soundmark_id,
"soundmark_name": sm.name if sm else None,
"soundmark_tier": sm.tier if sm else None,
"song": (
{"id": song.id, "title": song.title, "artist": song.artist, "album": song.album, "coverart": song.coverart}
if song
else None
),
"suggested_by_username": suggester.username if suggester else None,
"status": s.status,
"created_at": s.created_at,
}
def _cast_vote(soundmark_id: int, proposal_id: int, user_id: int, db: Session) -> None:
"""One vote per (soundmark, user) - moves the vote if the user already backed a different
proposal here, no-ops if they're just re-affirming the one they already picked."""
......@@ -140,12 +213,18 @@ def _maybe_promote_to_business_admin(owner: User, db: Session) -> None:
db.add(owner)
def _check_owns_soundmark(sm: Soundmark, current_user: User) -> None:
if sm.business_owner_id != current_user.id and not is_super_admin(current_user):
raise HTTPException(status_code=403, detail="You don't own this soundmark")
# ---- Schemas ----
class SoundmarkCreate(BaseModel):
name: str
description: Optional[str] = None
tier: str = "community"
latitude: float
longitude: float
radius_meters: float = 200.0
......@@ -156,6 +235,7 @@ class SoundmarkCreate(BaseModel):
class SoundmarkUpdate(BaseModel):
name: Optional[str] = None
description: Optional[str] = None
tier: Optional[str] = None
latitude: Optional[float] = None
longitude: Optional[float] = None
radius_meters: Optional[float] = None
......@@ -167,6 +247,14 @@ class SongAssign(BaseModel):
song_id: Optional[int] = None # null clears the anthem
class PlaylistAdd(BaseModel):
song_id: int
class SuggestSong(BaseModel):
song_id: int
class RoleUpdate(BaseModel):
role: str
......@@ -281,6 +369,88 @@ def update_user_role(
return {"status": "success", "user": {"id": user.id, "username": user.username, "role": user.role}}
# ---- Review queue (business_admin+, scoped to what they can moderate) ----
@router.get("/suggestions")
def get_review_queue(
status: str = "pending",
db: Session = Depends(get_db),
current_user: User = Depends(get_current_business_admin),
):
"""Suggestions waiting on a decision. Super admins see every major/business soundmark's
queue; business admins only see suggestions for soundmarks they themselves own (a
business-tier soundmark always has an owner, so this scoping falls out naturally - no
major-tier suggestion is ever owned by anyone)."""
query = db.query(SoundmarkSuggestion).filter(SoundmarkSuggestion.status == status)
if not is_super_admin(current_user):
owned_ids = [
sm.id for sm in db.query(Soundmark).filter(Soundmark.business_owner_id == current_user.id).all()
]
query = query.filter(SoundmarkSuggestion.soundmark_id.in_(owned_ids))
suggestions = query.order_by(SoundmarkSuggestion.created_at).all()
return {"status": "success", "suggestions": [_serialize_suggestion(s, db) for s in suggestions]}
@router.post("/suggestions/{suggestion_id}/approve")
def approve_suggestion(
suggestion_id: int, db: Session = Depends(get_db), current_user: User = Depends(get_current_business_admin)
):
suggestion = db.query(SoundmarkSuggestion).filter(SoundmarkSuggestion.id == suggestion_id).first()
if not suggestion:
raise HTTPException(status_code=404, detail="Suggestion not found")
if suggestion.status != "pending":
raise HTTPException(status_code=400, detail="This suggestion has already been reviewed")
sm = db.query(Soundmark).filter(Soundmark.id == suggestion.soundmark_id).first()
if not sm:
raise HTTPException(status_code=404, detail="Soundmark not found")
_check_owns_soundmark(sm, current_user)
if sm.tier == "major":
sm.song_id = suggestion.song_id
elif sm.tier == "business":
existing = (
db.query(SoundmarkPlaylistTrack)
.filter(SoundmarkPlaylistTrack.soundmark_id == sm.id, SoundmarkPlaylistTrack.song_id == suggestion.song_id)
.first()
)
if not existing:
position = db.query(SoundmarkPlaylistTrack).filter(SoundmarkPlaylistTrack.soundmark_id == sm.id).count()
db.add(SoundmarkPlaylistTrack(soundmark_id=sm.id, song_id=suggestion.song_id, position=position))
suggestion.status = "approved"
suggestion.reviewed_by_user_id = current_user.id
suggestion.reviewed_at = datetime.now(timezone.utc)
db.commit()
db.refresh(suggestion)
return {"status": "success", "suggestion": _serialize_suggestion(suggestion, db)}
@router.post("/suggestions/{suggestion_id}/reject")
def reject_suggestion(
suggestion_id: int, db: Session = Depends(get_db), current_user: User = Depends(get_current_business_admin)
):
suggestion = db.query(SoundmarkSuggestion).filter(SoundmarkSuggestion.id == suggestion_id).first()
if not suggestion:
raise HTTPException(status_code=404, detail="Suggestion not found")
if suggestion.status != "pending":
raise HTTPException(status_code=400, detail="This suggestion has already been reviewed")
sm = db.query(Soundmark).filter(Soundmark.id == suggestion.soundmark_id).first()
if not sm:
raise HTTPException(status_code=404, detail="Soundmark not found")
_check_owns_soundmark(sm, current_user)
suggestion.status = "rejected"
suggestion.reviewed_by_user_id = current_user.id
suggestion.reviewed_at = datetime.now(timezone.utc)
db.commit()
db.refresh(suggestion)
return {"status": "success", "suggestion": _serialize_suggestion(suggestion, db)}
# ---- Super admin CRUD ----
@router.get("")
def list_all_soundmarks(db: Session = Depends(get_db), current_user: User = Depends(get_current_super_admin)):
marks = db.query(Soundmark).order_by(Soundmark.name).all()
......@@ -291,12 +461,15 @@ def list_all_soundmarks(db: Session = Depends(get_db), current_user: User = Depe
def create_soundmark(
body: SoundmarkCreate, db: Session = Depends(get_db), current_user: User = Depends(get_current_super_admin)
):
_validate_tier_and_owner(body.tier, body.business_owner_id)
owner = None
if body.business_owner_id is not None:
owner = db.query(User).filter(User.id == body.business_owner_id).first()
if not owner:
raise HTTPException(status_code=404, detail="Owner user not found")
if body.song_id is not None:
if body.tier != "major":
raise HTTPException(status_code=422, detail="song_id can only be set directly for major-tier soundmarks")
song = db.query(LibrarySong).filter(LibrarySong.id == body.song_id).first()
if not song:
raise HTTPException(status_code=404, detail="Song not found")
......@@ -320,18 +493,75 @@ def set_soundmark_song(
sm = db.query(Soundmark).filter(Soundmark.id == soundmark_id).first()
if not sm:
raise HTTPException(status_code=404, detail="Soundmark not found")
if sm.business_owner_id != current_user.id and not is_super_admin(current_user):
raise HTTPException(status_code=403, detail="You don't own this soundmark")
if sm.tier != "major":
raise HTTPException(
status_code=400,
detail="Only major-tier soundmarks use direct song assignment - business tier uses the playlist "
"endpoints, community tier is fully automated via proposals.",
)
_check_owns_soundmark(sm, current_user)
if body.song_id is not None:
song = db.query(LibrarySong).filter(LibrarySong.id == body.song_id).first()
if not song:
raise HTTPException(status_code=404, detail="Song not found")
sm.song_id = body.song_id
if body.song_id is not None:
# Turn this into a proposal (with the setter's own vote) rather than a silent
# override, so it competes fairly with user proposals instead of being trivially
# out-voted by whoever proposes something else first.
_propose_and_vote(sm.id, body.song_id, current_user.id, db)
db.commit()
db.refresh(sm)
return {"status": "success", "soundmark": _serialize(sm, db)}
@router.post("/{soundmark_id}/playlist", status_code=201)
def add_playlist_track(
soundmark_id: int,
body: PlaylistAdd,
db: Session = Depends(get_db),
current_user: User = Depends(get_current_business_admin),
):
sm = db.query(Soundmark).filter(Soundmark.id == soundmark_id).first()
if not sm:
raise HTTPException(status_code=404, detail="Soundmark not found")
if sm.tier != "business":
raise HTTPException(status_code=400, detail="Only business-tier soundmarks have a playlist")
_check_owns_soundmark(sm, current_user)
song = db.query(LibrarySong).filter(LibrarySong.id == body.song_id).first()
if not song:
raise HTTPException(status_code=404, detail="Song not found")
existing = (
db.query(SoundmarkPlaylistTrack)
.filter(SoundmarkPlaylistTrack.soundmark_id == sm.id, SoundmarkPlaylistTrack.song_id == body.song_id)
.first()
)
if not existing:
position = db.query(SoundmarkPlaylistTrack).filter(SoundmarkPlaylistTrack.soundmark_id == sm.id).count()
db.add(SoundmarkPlaylistTrack(soundmark_id=sm.id, song_id=body.song_id, position=position))
db.commit()
db.refresh(sm)
return {"status": "success", "soundmark": _serialize(sm, db)}
@router.delete("/{soundmark_id}/playlist/{song_id}")
def remove_playlist_track(
soundmark_id: int,
song_id: int,
db: Session = Depends(get_db),
current_user: User = Depends(get_current_business_admin),
):
sm = db.query(Soundmark).filter(Soundmark.id == soundmark_id).first()
if not sm:
raise HTTPException(status_code=404, detail="Soundmark not found")
if sm.tier != "business":
raise HTTPException(status_code=400, detail="Only business-tier soundmarks have a playlist")
_check_owns_soundmark(sm, current_user)
track = (
db.query(SoundmarkPlaylistTrack)
.filter(SoundmarkPlaylistTrack.soundmark_id == sm.id, SoundmarkPlaylistTrack.song_id == song_id)
.first()
)
if not track:
raise HTTPException(status_code=404, detail="Song not in playlist")
db.delete(track)
db.commit()
db.refresh(sm)
return {"status": "success", "soundmark": _serialize(sm, db)}
......@@ -349,12 +579,18 @@ def update_soundmark(
raise HTTPException(status_code=404, detail="Soundmark not found")
data = body.dict(exclude_unset=True)
effective_tier = data.get("tier", sm.tier)
effective_owner = data.get("business_owner_id", sm.business_owner_id)
_validate_tier_and_owner(effective_tier, effective_owner)
owner = None
if "business_owner_id" in data and data["business_owner_id"] is not None:
owner = db.query(User).filter(User.id == data["business_owner_id"]).first()
if not owner:
raise HTTPException(status_code=404, detail="Owner user not found")
if "song_id" in data and data["song_id"] is not None:
if effective_tier != "major":
raise HTTPException(status_code=422, detail="song_id can only be set directly for major-tier soundmarks")
song = db.query(LibrarySong).filter(LibrarySong.id == data["song_id"]).first()
if not song:
raise HTTPException(status_code=404, detail="Song not found")
......@@ -384,8 +620,7 @@ def delete_soundmark(
def stream_soundmark_anthem(
soundmark_id: int, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)
):
"""Streams a soundmark's current anthem (the most-voted proposal, or the admin-set
fallback if there are no proposals) regardless of which user originally uploaded the
"""Streams a soundmark's current anthem regardless of which user originally uploaded the
underlying LibrarySong - unlike /library/stream/{id}, this is deliberately not scoped to
the caller owning the song, since the whole point is other people hearing it too."""
sm = db.query(Soundmark).filter(Soundmark.id == soundmark_id).first()
......@@ -400,11 +635,35 @@ def stream_soundmark_anthem(
return FileResponse(song.file_path, media_type="audio/mpeg")
# ---- Song proposals & voting (any authenticated user) ----
# ---- Suggestions (major/business tier - any authenticated user proposes, owner reviews) ----
class ProposeSong(BaseModel):
song_id: int
@router.post("/{soundmark_id}/suggestions", status_code=201)
def suggest_song(
soundmark_id: int,
body: SuggestSong,
db: Session = Depends(get_db),
current_user: User = Depends(get_current_user),
):
sm = db.query(Soundmark).filter(Soundmark.id == soundmark_id).first()
if not sm:
raise HTTPException(status_code=404, detail="Soundmark not found")
if sm.tier == "community":
raise HTTPException(
status_code=400,
detail="Community soundmarks use proposals/voting, not suggestions - see POST /soundmarks/{id}/proposals",
)
song = db.query(LibrarySong).filter(LibrarySong.id == body.song_id).first()
if not song:
raise HTTPException(status_code=404, detail="Song not found")
suggestion = SoundmarkSuggestion(soundmark_id=soundmark_id, song_id=body.song_id, suggested_by_user_id=current_user.id)
db.add(suggestion)
db.commit()
db.refresh(suggestion)
return {"status": "success", "suggestion": _serialize_suggestion(suggestion, db)}
# ---- Song proposals & voting (community tier only - any authenticated user) ----
@router.get("/{soundmark_id}/proposals")
......@@ -412,6 +671,8 @@ def get_proposals(soundmark_id: int, db: Session = Depends(get_db), current_user
sm = db.query(Soundmark).filter(Soundmark.id == soundmark_id).first()
if not sm:
raise HTTPException(status_code=404, detail="Soundmark not found")
if sm.tier != "community":
raise HTTPException(status_code=400, detail="Only community soundmarks use proposals/voting")
proposals = db.query(SoundmarkProposal).filter(SoundmarkProposal.soundmark_id == soundmark_id).all()
serialized = [_serialize_proposal(p, db, current_user.id) for p in proposals]
serialized.sort(key=lambda p: -p["vote_count"])
......@@ -421,13 +682,15 @@ def get_proposals(soundmark_id: int, db: Session = Depends(get_db), current_user
@router.post("/{soundmark_id}/proposals", status_code=201)
def propose_song(
soundmark_id: int,
body: ProposeSong,
body: SuggestSong,
db: Session = Depends(get_db),
current_user: User = Depends(get_current_user),
):
sm = db.query(Soundmark).filter(Soundmark.id == soundmark_id).first()
if not sm:
raise HTTPException(status_code=404, detail="Soundmark not found")
if sm.tier != "community":
raise HTTPException(status_code=400, detail="Only community soundmarks use proposals/voting")
song = db.query(LibrarySong).filter(LibrarySong.id == body.song_id).first()
if not song:
raise HTTPException(status_code=404, detail="Song not found")
......@@ -444,6 +707,11 @@ def vote_for_proposal(
db: Session = Depends(get_db),
current_user: User = Depends(get_current_user),
):
sm = db.query(Soundmark).filter(Soundmark.id == soundmark_id).first()
if not sm:
raise HTTPException(status_code=404, detail="Soundmark not found")
if sm.tier != "community":
raise HTTPException(status_code=400, detail="Only community soundmarks use proposals/voting")
proposal = (
db.query(SoundmarkProposal)
.filter(SoundmarkProposal.id == proposal_id, SoundmarkProposal.soundmark_id == soundmark_id)
......
......@@ -128,15 +128,24 @@ class GeoDrop(Base):
class Soundmark(Base):
"""A curated 'anthem' tied to a real-world place - distinct from GeoDrop (any user
dropping a song for others to stumble on). A Soundmark with business_owner_id NULL is a
super-admin-curated landmark (e.g. locally significant to the area); one with an owner is
that business's location, and its anthem can only be changed by that owner or a super
admin. song_id is nullable so a soundmark can exist (name/location set by a super admin)
before anyone has picked its anthem yet."""
dropping a song for others to stumble on). Three tiers, distinguished by `tier`:
- "major": a super-admin-curated landmark. One official song (song_id), set directly by a
super admin (auto-applied). Anyone else's pick goes through SoundmarkSuggestion instead.
- "business": owned by a business_owner_id. Has a *playlist* (SoundmarkPlaylistTrack), not
a single song - the owner adds/removes tracks directly (auto-applied); everyone else's
picks go through SoundmarkSuggestion.
- "community": no owner, fully automated. Anyone can propose a song (SoundmarkProposal) and
vote; the most-voted one just plays, no review step at all - see
soundmarks.py's _resolve_active_song_id.
song_id is only meaningful for "major" (and as a legacy fallback for pre-tier "community"
rows that predate SoundmarkProposal - see _resolve_active_song_id)."""
__tablename__ = "soundmarks"
id = Column(Integer, primary_key=True, index=True)
name = Column(String, index=True)
description = Column(String, nullable=True)
tier = Column(String, default="community", nullable=False) # "major" | "business" | "community"
latitude = Column(Float)
longitude = Column(Float)
# How close (in meters) someone needs to be for this soundmark to be considered "active" -
......@@ -147,11 +156,39 @@ class Soundmark(Base):
created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc))
updated_at = Column(DateTime, default=lambda: datetime.now(timezone.utc), onupdate=lambda: datetime.now(timezone.utc))
class SoundmarkPlaylistTrack(Base):
"""One song in a "business"-tier soundmark's playlist. Added directly by the business
owner or a super admin (auto-applied, no review) - see SoundmarkSuggestion for how a
non-owner's pick gets added instead (only after being approved)."""
__tablename__ = "soundmark_playlist_tracks"
__table_args__ = (UniqueConstraint("soundmark_id", "song_id", name="uq_soundmark_playlist_song"),)
id = Column(Integer, primary_key=True, index=True)
soundmark_id = Column(Integer, ForeignKey("soundmarks.id"), index=True)
song_id = Column(Integer, ForeignKey("library_songs.id"))
position = Column(Integer, default=0)
added_at = Column(DateTime, default=lambda: datetime.now(timezone.utc))
class SoundmarkSuggestion(Base):
"""A song someone other than the owner suggested for a "major" or "business" soundmark -
sits in a review queue until the owner (business admin for their own business, super admin
for major locations - super admin can review either) approves or rejects it. Approving
applies the effect (sets Soundmark.song_id for "major", adds a SoundmarkPlaylistTrack for
"business"). "community" soundmarks don't use this at all - they use
SoundmarkProposal/SoundmarkProposalVote instead, with no review step."""
__tablename__ = "soundmark_suggestions"
id = Column(Integer, primary_key=True, index=True)
soundmark_id = Column(Integer, ForeignKey("soundmarks.id"), index=True)
song_id = Column(Integer, ForeignKey("library_songs.id"))
suggested_by_user_id = Column(Integer, ForeignKey("users.id"))
status = Column(String, default="pending", index=True) # "pending" | "approved" | "rejected"
reviewed_by_user_id = Column(Integer, ForeignKey("users.id"), nullable=True)
reviewed_at = Column(DateTime, nullable=True)
created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc))
class SoundmarkProposal(Base):
"""A candidate anthem someone's suggested for a soundmark. The proposal with the most
votes is what actually plays there (see soundmarks.py's _resolve_active_song) - the
business/super-admin-set Soundmark.song_id is only the fallback used while a soundmark has
no proposals yet, not a permanent override."""
"""A candidate anthem someone's suggested for a "community"-tier soundmark - see
Soundmark's docstring. The proposal with the most votes is what actually plays there (see
soundmarks.py's _resolve_active_song_id); there's no review step for this tier."""
__tablename__ = "soundmark_proposals"
__table_args__ = (UniqueConstraint("soundmark_id", "song_id", name="uq_soundmark_proposal_song"),)
id = Column(Integer, primary_key=True, index=True)
......
......@@ -3,7 +3,7 @@ import tempfile
import httpx
from src.core.database import LibrarySong, Soundmark
from src.core.database import LibrarySong, Soundmark, SoundmarkSuggestion
def _make_library_song(db_session, user_id, **overrides):
......@@ -22,7 +22,7 @@ def _make_library_song(db_session, user_id, **overrides):
def _make_soundmark(db_session, **overrides):
defaults = dict(name="Test Soundmark", latitude=37.7749, longitude=-122.4194, radius_meters=200.0)
defaults = dict(name="Test Soundmark", tier="community", latitude=37.7749, longitude=-122.4194, radius_meters=200.0)
defaults.update(overrides)
sm = Soundmark(**defaults)
db_session.add(sm)
......@@ -48,13 +48,19 @@ def test_regular_user_cannot_access_business_endpoints(client, auth_as):
def test_regular_user_cannot_access_super_admin_endpoints(client, auth_as):
headers, _ = auth_as()
assert client.get("/soundmarks", headers=headers).status_code == 403
assert client.post("/soundmarks", json={"name": "x", "latitude": 0, "longitude": 0}, headers=headers).status_code == 403
assert (
client.post("/soundmarks", json={"name": "x", "tier": "major", "latitude": 0, "longitude": 0}, headers=headers).status_code
== 403
)
def test_business_admin_cannot_access_super_admin_only_endpoints(client, auth_as):
headers, _ = auth_as(role="business_admin")
assert client.get("/soundmarks", headers=headers).status_code == 403
assert client.post("/soundmarks", json={"name": "x", "latitude": 0, "longitude": 0}, headers=headers).status_code == 403
assert (
client.post("/soundmarks", json={"name": "x", "tier": "major", "latitude": 0, "longitude": 0}, headers=headers).status_code
== 403
)
assert client.delete("/soundmarks/1", headers=headers).status_code == 403
......@@ -65,31 +71,77 @@ def test_super_admin_can_access_business_endpoints_too(client, db_session, auth_
assert response.status_code == 200
# ---- Super admin CRUD ----
# ---- Super admin CRUD + tier validation ----
def test_super_admin_creates_soundmark(client, auth_as):
def test_super_admin_creates_a_major_location(client, auth_as):
headers, _ = auth_as(role="super_admin")
response = client.post(
"/soundmarks",
json={"name": "Landmark Plaza", "description": "Historic square", "latitude": 1.0, "longitude": 2.0, "radius_meters": 100},
json={
"name": "Landmark Plaza",
"description": "Historic square",
"tier": "major",
"latitude": 1.0,
"longitude": 2.0,
"radius_meters": 100,
},
headers=headers,
)
assert response.status_code == 201
body = response.json()["soundmark"]
assert body["name"] == "Landmark Plaza"
assert body["tier"] == "major"
assert body["business_owner_id"] is None
assert body["song"] is None
def test_creating_soundmark_with_owner_promotes_them_to_business_admin(client, db_session, auth_as):
def test_creating_a_business_without_an_owner_fails(client, auth_as):
headers, _ = auth_as(role="super_admin")
response = client.post(
"/soundmarks", json={"name": "x", "tier": "business", "latitude": 0, "longitude": 0}, headers=headers
)
assert response.status_code == 422
def test_creating_a_non_business_with_an_owner_fails(client, auth_as):
headers, _ = auth_as(role="super_admin")
_, owner = auth_as()
response = client.post(
"/soundmarks",
json={"name": "x", "tier": "major", "latitude": 0, "longitude": 0, "business_owner_id": owner.id},
headers=headers,
)
assert response.status_code == 422
def test_creating_soundmark_with_invalid_tier_fails(client, auth_as):
headers, _ = auth_as(role="super_admin")
response = client.post(
"/soundmarks", json={"name": "x", "tier": "galactic", "latitude": 0, "longitude": 0}, headers=headers
)
assert response.status_code == 422
def test_creating_soundmark_with_song_id_on_non_major_tier_fails(client, auth_as):
headers, _ = auth_as(role="super_admin")
_, owner = auth_as()
song_response = client.post(
"/soundmarks",
json={"name": "x", "tier": "community", "latitude": 0, "longitude": 0, "song_id": 1},
headers=headers,
)
assert song_response.status_code == 422
def test_creating_business_with_owner_promotes_them_to_business_admin(client, db_session, auth_as):
headers, _ = auth_as(role="super_admin")
owner_headers, owner = auth_as() # plain "user" role
assert owner.role == "user"
response = client.post(
"/soundmarks",
json={"name": "Joe's Cafe", "latitude": 1.0, "longitude": 2.0, "business_owner_id": owner.id},
json={"name": "Joe's Cafe", "tier": "business", "latitude": 1.0, "longitude": 2.0, "business_owner_id": owner.id},
headers=headers,
)
assert response.status_code == 201
......@@ -101,14 +153,16 @@ def test_creating_soundmark_with_owner_promotes_them_to_business_admin(client, d
def test_creating_soundmark_with_unknown_owner_fails(client, auth_as):
headers, _ = auth_as(role="super_admin")
response = client.post(
"/soundmarks", json={"name": "x", "latitude": 0, "longitude": 0, "business_owner_id": 999999}, headers=headers
"/soundmarks",
json={"name": "x", "tier": "business", "latitude": 0, "longitude": 0, "business_owner_id": 999999},
headers=headers,
)
assert response.status_code == 404
def test_super_admin_updates_and_deletes_soundmark(client, db_session, auth_as):
headers, _ = auth_as(role="super_admin")
sm = _make_soundmark(db_session)
sm = _make_soundmark(db_session, tier="major")
response = client.patch(f"/soundmarks/{sm.id}", json={"name": "Renamed", "radius_meters": 50}, headers=headers)
assert response.status_code == 200
......@@ -120,10 +174,19 @@ def test_super_admin_updates_and_deletes_soundmark(client, db_session, auth_as):
assert db_session.query(Soundmark).filter(Soundmark.id == sm.id).first() is None
def test_updating_tier_is_validated_against_the_resulting_owner_state(client, db_session, auth_as):
headers, _ = auth_as(role="super_admin")
sm = _make_soundmark(db_session, tier="major")
# Can't flip to business without also providing an owner in the same request.
response = client.patch(f"/soundmarks/{sm.id}", json={"tier": "business"}, headers=headers)
assert response.status_code == 422
def test_super_admin_lists_all_soundmarks_regardless_of_owner(client, db_session, auth_as):
headers, _ = auth_as(role="super_admin")
_make_soundmark(db_session, name="Mark A")
_make_soundmark(db_session, name="Mark B")
_make_soundmark(db_session, name="Mark A", tier="major")
_make_soundmark(db_session, name="Mark B", tier="major")
response = client.get("/soundmarks", headers=headers)
assert response.status_code == 200
......@@ -131,66 +194,115 @@ def test_super_admin_lists_all_soundmarks_regardless_of_owner(client, db_session
assert {"Mark A", "Mark B"}.issubset(names)
# ---- Business admin song assignment ----
# ---- Major tier: direct single-song assignment ----
def test_business_admin_can_set_song_on_own_soundmark(client, db_session, auth_as):
headers, owner = auth_as(role="business_admin")
sm = _make_soundmark(db_session, business_owner_id=owner.id)
song, _ = _make_library_song(db_session, owner.id)
def test_super_admin_sets_song_on_a_major_location(client, db_session, auth_as):
headers, _ = auth_as(role="super_admin")
sm = _make_soundmark(db_session, tier="major")
song, _ = _make_library_song(db_session, 1)
response = client.patch(f"/soundmarks/{sm.id}/song", json={"song_id": song.id}, headers=headers)
assert response.status_code == 200
assert response.json()["soundmark"]["song"]["id"] == song.id
def test_business_admin_cannot_set_song_on_someone_elses_soundmark(client, db_session, auth_as):
def test_business_admin_cannot_set_song_on_a_major_location(client, db_session, auth_as):
headers, _ = auth_as(role="business_admin")
other_headers, other_owner = auth_as(role="business_admin")
sm = _make_soundmark(db_session, business_owner_id=other_owner.id)
song, _ = _make_library_song(db_session, other_owner.id)
sm = _make_soundmark(db_session, tier="major")
song, _ = _make_library_song(db_session, 1)
response = client.patch(f"/soundmarks/{sm.id}/song", json={"song_id": song.id}, headers=headers)
assert response.status_code == 403
def test_business_admin_can_pick_a_song_from_another_users_library(client, db_session, auth_as):
"""The whole point of the 'public library' picker - not restricted to songs they uploaded."""
def test_setting_song_on_a_business_tier_soundmark_is_rejected(client, db_session, auth_as):
"""Business tier uses the playlist endpoints instead - this endpoint is major-only now."""
headers, owner = auth_as(role="business_admin")
_, stranger = auth_as()
sm = _make_soundmark(db_session, business_owner_id=owner.id)
song, _ = _make_library_song(db_session, stranger.id, title="Someone Else's Song")
sm = _make_soundmark(db_session, tier="business", business_owner_id=owner.id)
song, _ = _make_library_song(db_session, owner.id)
response = client.patch(f"/soundmarks/{sm.id}/song", json={"song_id": song.id}, headers=headers)
assert response.status_code == 200
assert response.json()["soundmark"]["song"]["title"] == "Someone Else's Song"
assert response.status_code == 400
def test_setting_song_on_a_community_soundmark_is_rejected(client, db_session, auth_as):
headers, _ = auth_as(role="super_admin")
sm = _make_soundmark(db_session, tier="community")
song, _ = _make_library_song(db_session, 1)
response = client.patch(f"/soundmarks/{sm.id}/song", json={"song_id": song.id}, headers=headers)
assert response.status_code == 400
# ---- Business tier: playlist management ----
def test_business_admin_can_clear_the_anthem(client, db_session, auth_as):
def test_business_admin_adds_and_removes_playlist_tracks(client, db_session, auth_as):
headers, owner = auth_as(role="business_admin")
sm = _make_soundmark(db_session, tier="business", business_owner_id=owner.id)
song, _ = _make_library_song(db_session, owner.id)
sm = _make_soundmark(db_session, business_owner_id=owner.id, song_id=song.id)
response = client.patch(f"/soundmarks/{sm.id}/song", json={"song_id": None}, headers=headers)
response = client.post(f"/soundmarks/{sm.id}/playlist", json={"song_id": song.id}, headers=headers)
assert response.status_code == 201
assert [s["id"] for s in response.json()["soundmark"]["playlist"]] == [song.id]
assert response.json()["soundmark"]["song"]["id"] == song.id # first track is "now playing"
response = client.delete(f"/soundmarks/{sm.id}/playlist/{song.id}", headers=headers)
assert response.status_code == 200
assert response.json()["soundmark"]["song"] is None
assert response.json()["soundmark"]["playlist"] == []
def test_playlist_keeps_insertion_order_and_first_track_is_featured(client, db_session, auth_as):
headers, owner = auth_as(role="business_admin")
sm = _make_soundmark(db_session, tier="business", business_owner_id=owner.id)
song_a, _ = _make_library_song(db_session, owner.id, title="A")
song_b, _ = _make_library_song(db_session, owner.id, title="B")
client.post(f"/soundmarks/{sm.id}/playlist", json={"song_id": song_a.id}, headers=headers)
client.post(f"/soundmarks/{sm.id}/playlist", json={"song_id": song_b.id}, headers=headers)
response = client.get("/soundmarks/mine", headers=headers)
sm_body = next(s for s in response.json()["soundmarks"] if s["id"] == sm.id)
assert [t["title"] for t in sm_body["playlist"]] == ["A", "B"]
assert sm_body["song"]["title"] == "A"
def test_business_admin_cannot_manage_someone_elses_playlist(client, db_session, auth_as):
headers, _ = auth_as(role="business_admin")
_, other_owner = auth_as(role="business_admin")
sm = _make_soundmark(db_session, tier="business", business_owner_id=other_owner.id)
song, _ = _make_library_song(db_session, other_owner.id)
response = client.post(f"/soundmarks/{sm.id}/playlist", json={"song_id": song.id}, headers=headers)
assert response.status_code == 403
def test_super_admin_can_set_song_on_any_soundmark(client, db_session, auth_as):
def test_playlist_endpoints_reject_non_business_tier(client, db_session, auth_as):
headers, _ = auth_as(role="super_admin")
_, owner = auth_as(role="business_admin")
sm = _make_soundmark(db_session, business_owner_id=owner.id)
sm = _make_soundmark(db_session, tier="major")
song, _ = _make_library_song(db_session, 1)
response = client.post(f"/soundmarks/{sm.id}/playlist", json={"song_id": song.id}, headers=headers)
assert response.status_code == 400
def test_adding_the_same_song_to_a_playlist_twice_is_idempotent(client, db_session, auth_as):
headers, owner = auth_as(role="business_admin")
sm = _make_soundmark(db_session, tier="business", business_owner_id=owner.id)
song, _ = _make_library_song(db_session, owner.id)
response = client.patch(f"/soundmarks/{sm.id}/song", json={"song_id": song.id}, headers=headers)
assert response.status_code == 200
client.post(f"/soundmarks/{sm.id}/playlist", json={"song_id": song.id}, headers=headers)
response = client.post(f"/soundmarks/{sm.id}/playlist", json={"song_id": song.id}, headers=headers)
assert response.status_code == 201
assert len(response.json()["soundmark"]["playlist"]) == 1
def test_get_my_soundmarks_only_returns_own(client, db_session, auth_as):
headers, owner = auth_as(role="business_admin")
_, other = auth_as(role="business_admin")
mine = _make_soundmark(db_session, name="Mine", business_owner_id=owner.id)
_make_soundmark(db_session, name="Theirs", business_owner_id=other.id)
mine = _make_soundmark(db_session, name="Mine", tier="business", business_owner_id=owner.id)
_make_soundmark(db_session, name="Theirs", tier="business", business_owner_id=other.id)
response = client.get("/soundmarks/mine", headers=headers)
assert response.status_code == 200
......@@ -215,6 +327,155 @@ def test_song_library_search_spans_all_users(client, db_session, auth_as):
assert {"Alpha Song", "Beta Song"}.issubset(titles)
# ---- Suggestions & review queue (major/business tier only) ----
def test_any_user_can_suggest_a_song_for_a_major_location(client, db_session, auth_as):
headers, user = auth_as()
super_headers, _ = auth_as(role="super_admin")
sm = _make_soundmark(db_session, tier="major")
song, _ = _make_library_song(db_session, user.id)
response = client.post(f"/soundmarks/{sm.id}/suggestions", json={"song_id": song.id}, headers=headers)
assert response.status_code == 201
body = response.json()["suggestion"]
assert body["status"] == "pending"
assert body["song"]["id"] == song.id
# A pending suggestion must not have taken effect yet.
soundmarks_after = client.get("/soundmarks", headers=super_headers).json()["soundmarks"]
assert next(s for s in soundmarks_after if s["id"] == sm.id)["song"] is None
def test_suggestions_are_rejected_for_community_soundmarks(client, db_session, auth_as):
headers, user = auth_as()
sm = _make_soundmark(db_session, tier="community")
song, _ = _make_library_song(db_session, user.id)
response = client.post(f"/soundmarks/{sm.id}/suggestions", json={"song_id": song.id}, headers=headers)
assert response.status_code == 400
def test_business_admin_sees_only_their_own_businesses_queue(client, db_session, auth_as):
biz_headers, biz_owner = auth_as(role="business_admin")
_, other_owner = auth_as(role="business_admin")
suggester_headers, suggester = auth_as()
mine = _make_soundmark(db_session, name="Mine", tier="business", business_owner_id=biz_owner.id)
theirs = _make_soundmark(db_session, name="Theirs", tier="business", business_owner_id=other_owner.id)
song, _ = _make_library_song(db_session, suggester.id)
client.post(f"/soundmarks/{mine.id}/suggestions", json={"song_id": song.id}, headers=suggester_headers)
client.post(f"/soundmarks/{theirs.id}/suggestions", json={"song_id": song.id}, headers=suggester_headers)
response = client.get("/soundmarks/suggestions", headers=biz_headers)
assert response.status_code == 200
soundmark_ids = {s["soundmark_id"] for s in response.json()["suggestions"]}
assert mine.id in soundmark_ids
assert theirs.id not in soundmark_ids
def test_super_admin_sees_every_pending_suggestion(client, db_session, auth_as):
super_headers, _ = auth_as(role="super_admin")
_, biz_owner = auth_as(role="business_admin")
suggester_headers, suggester = auth_as()
major = _make_soundmark(db_session, tier="major")
business = _make_soundmark(db_session, tier="business", business_owner_id=biz_owner.id)
song, _ = _make_library_song(db_session, suggester.id)
client.post(f"/soundmarks/{major.id}/suggestions", json={"song_id": song.id}, headers=suggester_headers)
client.post(f"/soundmarks/{business.id}/suggestions", json={"song_id": song.id}, headers=suggester_headers)
response = client.get("/soundmarks/suggestions", headers=super_headers)
assert response.status_code == 200
soundmark_ids = {s["soundmark_id"] for s in response.json()["suggestions"]}
assert {major.id, business.id}.issubset(soundmark_ids)
def test_approving_a_suggestion_for_a_major_location_sets_its_song(client, db_session, auth_as):
super_headers, _ = auth_as(role="super_admin")
suggester_headers, suggester = auth_as()
sm = _make_soundmark(db_session, tier="major")
song, _ = _make_library_song(db_session, suggester.id)
suggestion = client.post(
f"/soundmarks/{sm.id}/suggestions", json={"song_id": song.id}, headers=suggester_headers
).json()["suggestion"]
response = client.post(f"/soundmarks/suggestions/{suggestion['id']}/approve", headers=super_headers)
assert response.status_code == 200
assert response.json()["suggestion"]["status"] == "approved"
sm_after = client.get("/soundmarks", headers=super_headers).json()["soundmarks"]
assert next(s for s in sm_after if s["id"] == sm.id)["song"]["id"] == song.id
def test_approving_a_suggestion_for_a_business_adds_it_to_the_playlist(client, db_session, auth_as):
biz_headers, biz_owner = auth_as(role="business_admin")
suggester_headers, suggester = auth_as()
sm = _make_soundmark(db_session, tier="business", business_owner_id=biz_owner.id)
song, _ = _make_library_song(db_session, suggester.id)
suggestion = client.post(
f"/soundmarks/{sm.id}/suggestions", json={"song_id": song.id}, headers=suggester_headers
).json()["suggestion"]
response = client.post(f"/soundmarks/suggestions/{suggestion['id']}/approve", headers=biz_headers)
assert response.status_code == 200
mine = client.get("/soundmarks/mine", headers=biz_headers).json()["soundmarks"]
assert song.id in [t["id"] for t in next(s for s in mine if s["id"] == sm.id)["playlist"]]
def test_rejecting_a_suggestion_does_not_apply_it(client, db_session, auth_as):
super_headers, _ = auth_as(role="super_admin")
suggester_headers, suggester = auth_as()
sm = _make_soundmark(db_session, tier="major")
song, _ = _make_library_song(db_session, suggester.id)
suggestion = client.post(
f"/soundmarks/{sm.id}/suggestions", json={"song_id": song.id}, headers=suggester_headers
).json()["suggestion"]
response = client.post(f"/soundmarks/suggestions/{suggestion['id']}/reject", headers=super_headers)
assert response.status_code == 200
assert response.json()["suggestion"]["status"] == "rejected"
sm_after = client.get("/soundmarks", headers=super_headers).json()["soundmarks"]
assert next(s for s in sm_after if s["id"] == sm.id)["song"] is None
def test_business_admin_cannot_review_someone_elses_suggestion(client, db_session, auth_as):
headers, _ = auth_as(role="business_admin")
_, other_owner = auth_as(role="business_admin")
suggester_headers, suggester = auth_as()
sm = _make_soundmark(db_session, tier="business", business_owner_id=other_owner.id)
song, _ = _make_library_song(db_session, suggester.id)
suggestion = client.post(
f"/soundmarks/{sm.id}/suggestions", json={"song_id": song.id}, headers=suggester_headers
).json()["suggestion"]
response = client.post(f"/soundmarks/suggestions/{suggestion['id']}/approve", headers=headers)
assert response.status_code == 403
def test_reviewing_an_already_reviewed_suggestion_fails(client, db_session, auth_as):
super_headers, _ = auth_as(role="super_admin")
_, suggester = auth_as()
sm = _make_soundmark(db_session, tier="major")
song, _ = _make_library_song(db_session, suggester.id)
suggester_headers = auth_as()[0]
suggestion = client.post(
f"/soundmarks/{sm.id}/suggestions", json={"song_id": song.id}, headers=suggester_headers
).json()["suggestion"]
client.post(f"/soundmarks/suggestions/{suggestion['id']}/approve", headers=super_headers)
response = client.post(f"/soundmarks/suggestions/{suggestion['id']}/reject", headers=super_headers)
assert response.status_code == 400
# ---- Nearby detection ----
......@@ -222,7 +483,9 @@ def test_nearby_matches_within_radius(client, db_session, auth_as):
headers, _ = auth_as()
song, _ = _make_library_song(db_session, 1)
# ~10 meters north of the soundmark's center - well within a 200m radius.
_make_soundmark(db_session, name="Close Mark", latitude=37.7749, longitude=-122.4194, radius_meters=200, song_id=song.id)
_make_soundmark(
db_session, name="Close Mark", tier="major", latitude=37.7749, longitude=-122.4194, radius_meters=200, song_id=song.id
)
response = client.get("/soundmarks/nearby", params={"lat": 37.77499, "lon": -122.4194}, headers=headers)
assert response.status_code == 200
......@@ -235,7 +498,9 @@ def test_nearby_excludes_marks_outside_their_radius(client, db_session, auth_as)
headers, _ = auth_as()
song, _ = _make_library_song(db_session, 1)
# Roughly 1000km away - well outside any reasonable radius.
_make_soundmark(db_session, name="Far Mark", latitude=48.8566, longitude=2.3522, radius_meters=200, song_id=song.id)
_make_soundmark(
db_session, name="Far Mark", tier="major", latitude=48.8566, longitude=2.3522, radius_meters=200, song_id=song.id
)
response = client.get("/soundmarks/nearby", params={"lat": 37.7749, "lon": -122.4194}, headers=headers)
assert response.status_code == 200
......@@ -245,9 +510,9 @@ def test_nearby_excludes_marks_outside_their_radius(client, db_session, auth_as)
def test_nearby_includes_soundmarks_with_no_anthem_yet(client, db_session, auth_as):
"""Discoverable with song=None rather than hidden entirely - otherwise nobody could ever
make the first proposal for a brand new soundmark."""
make the first proposal/suggestion for a brand new soundmark."""
headers, _ = auth_as()
_make_soundmark(db_session, name="Empty Mark", latitude=37.7749, longitude=-122.4194, radius_meters=200, song_id=None)
_make_soundmark(db_session, name="Empty Mark", tier="community", latitude=37.7749, longitude=-122.4194, radius_meters=200)
response = client.get("/soundmarks/nearby", params={"lat": 37.7749, "lon": -122.4194}, headers=headers)
assert response.status_code == 200
......@@ -263,7 +528,7 @@ def test_stream_soundmark_anthem_works_regardless_of_song_owner(client, db_sessi
listener_headers, _ = auth_as()
_, uploader = auth_as()
song, path = _make_library_song(db_session, uploader.id)
sm = _make_soundmark(db_session, song_id=song.id)
sm = _make_soundmark(db_session, tier="major", song_id=song.id)
try:
response = client.get(f"/soundmarks/{sm.id}/stream", headers=listener_headers)
......@@ -275,11 +540,25 @@ def test_stream_soundmark_anthem_works_regardless_of_song_owner(client, db_sessi
def test_stream_soundmark_with_no_anthem_404s(client, db_session, auth_as):
headers, _ = auth_as()
sm = _make_soundmark(db_session, song_id=None)
sm = _make_soundmark(db_session, tier="major", song_id=None)
response = client.get(f"/soundmarks/{sm.id}/stream", headers=headers)
assert response.status_code == 404
def test_stream_business_soundmark_plays_the_featured_playlist_track(client, db_session, auth_as):
headers, owner = auth_as(role="business_admin")
sm = _make_soundmark(db_session, tier="business", business_owner_id=owner.id)
song, path = _make_library_song(db_session, owner.id)
try:
client.post(f"/soundmarks/{sm.id}/playlist", json={"song_id": song.id}, headers=headers)
response = client.get(f"/soundmarks/{sm.id}/stream", headers=headers)
assert response.status_code == 200
assert response.content == b"fake mp3 bytes for soundmark stream test"
finally:
os.remove(path)
# ---- User role management ----
......@@ -310,12 +589,12 @@ def test_role_update_rejects_invalid_role(client, auth_as):
assert response.status_code == 422
# ---- Song proposals & voting ----
# ---- Song proposals & voting (community tier only) ----
def test_proposing_a_song_creates_it_with_the_proposers_own_vote(client, db_session, auth_as):
headers, user = auth_as()
sm = _make_soundmark(db_session)
sm = _make_soundmark(db_session, tier="community")
song, _ = _make_library_song(db_session, user.id)
response = client.post(f"/soundmarks/{sm.id}/proposals", json={"song_id": song.id}, headers=headers)
......@@ -326,10 +605,21 @@ def test_proposing_a_song_creates_it_with_the_proposers_own_vote(client, db_sess
assert body["song"]["id"] == song.id
def test_proposals_are_rejected_for_major_and_business_tiers(client, db_session, auth_as):
headers, user = auth_as()
song, _ = _make_library_song(db_session, user.id)
major = _make_soundmark(db_session, tier="major")
business = _make_soundmark(db_session, tier="business", business_owner_id=user.id)
assert client.post(f"/soundmarks/{major.id}/proposals", json={"song_id": song.id}, headers=headers).status_code == 400
assert client.post(f"/soundmarks/{business.id}/proposals", json={"song_id": song.id}, headers=headers).status_code == 400
assert client.get(f"/soundmarks/{major.id}/proposals", headers=headers).status_code == 400
def test_proposing_the_same_song_twice_by_different_users_merges_into_one_proposal(client, db_session, auth_as):
headers_a, user_a = auth_as()
headers_b, _ = auth_as()
sm = _make_soundmark(db_session)
sm = _make_soundmark(db_session, tier="community")
song, _ = _make_library_song(db_session, user_a.id)
client.post(f"/soundmarks/{sm.id}/proposals", json={"song_id": song.id}, headers=headers_a)
......@@ -343,7 +633,7 @@ def test_proposing_the_same_song_twice_by_different_users_merges_into_one_propos
def test_voting_moves_a_users_vote_between_proposals_for_the_same_soundmark(client, db_session, auth_as):
headers, user = auth_as()
sm = _make_soundmark(db_session)
sm = _make_soundmark(db_session, tier="community")
song_a, _ = _make_library_song(db_session, user.id, title="A")
song_b, _ = _make_library_song(db_session, user.id, title="B")
......@@ -358,9 +648,9 @@ def test_voting_moves_a_users_vote_between_proposals_for_the_same_soundmark(clie
def test_removing_a_vote(client, db_session, auth_as):
headers, user = auth_as()
sm = _make_soundmark(db_session)
sm = _make_soundmark(db_session, tier="community")
song, _ = _make_library_song(db_session, user.id)
proposal = client.post(f"/soundmarks/{sm.id}/proposals", json={"song_id": song.id}, headers=headers).json()["proposal"]
client.post(f"/soundmarks/{sm.id}/proposals", json={"song_id": song.id}, headers=headers)
response = client.delete(f"/soundmarks/{sm.id}/proposals/vote", headers=headers)
assert response.status_code == 200
......@@ -370,30 +660,28 @@ def test_removing_a_vote(client, db_session, auth_as):
assert proposals[0]["has_voted"] is False
def test_most_voted_proposal_overrides_the_admin_set_fallback_song(client, db_session, auth_as):
"""The core "most popular is displayed" rule - once a proposal earns more votes than the
admin's original pick, the popular one is what's actually shown/streamed."""
admin_headers, admin = auth_as(role="business_admin")
voter1, voter1_user = auth_as()
voter2, voter2_user = auth_as()
sm = _make_soundmark(db_session, business_owner_id=admin.id)
official_song, _ = _make_library_song(db_session, admin.id, title="Official Pick")
popular_song, path = _make_library_song(db_session, admin.id, title="Popular Upstart")
# Admin sets the official anthem directly - this seeds one proposal with the admin's vote.
client.patch(f"/soundmarks/{sm.id}/song", json={"song_id": official_song.id}, headers=admin_headers)
def test_most_voted_proposal_wins_on_a_community_soundmark(client, db_session, auth_as):
"""The core "top song is played" rule for community soundmarks."""
_, first_proposer = auth_as()
voter1 = auth_as()[0]
voter2 = auth_as()[0]
listener_headers = auth_as()[0]
sm = _make_soundmark(db_session, tier="community")
less_popular_song, _ = _make_library_song(db_session, first_proposer.id, title="Less Popular")
popular_song, path = _make_library_song(db_session, first_proposer.id, title="Popular Pick")
# Two different users propose/vote for a different song - now it has more votes (2 vs 1).
first_proposer_headers = auth_as()[0]
client.post(f"/soundmarks/{sm.id}/proposals", json={"song_id": less_popular_song.id}, headers=first_proposer_headers)
client.post(f"/soundmarks/{sm.id}/proposals", json={"song_id": popular_song.id}, headers=voter1)
client.post(f"/soundmarks/{sm.id}/proposals", json={"song_id": popular_song.id}, headers=voter2)
try:
response = client.get("/soundmarks/mine", headers=admin_headers)
response = client.get("/soundmarks/nearby", params={"lat": sm.latitude, "lon": sm.longitude}, headers=listener_headers)
assert response.status_code == 200
sm_body = next(s for s in response.json()["soundmarks"] if s["id"] == sm.id)
assert sm_body["song"]["id"] == popular_song.id
stream_response = client.get(f"/soundmarks/{sm.id}/stream", headers=voter1)
stream_response = client.get(f"/soundmarks/{sm.id}/stream", headers=listener_headers)
assert stream_response.status_code == 200
finally:
os.remove(path)
......@@ -401,7 +689,7 @@ def test_most_voted_proposal_overrides_the_admin_set_fallback_song(client, db_se
def test_proposal_requires_soundmark_and_song_to_exist(client, db_session, auth_as):
headers, user = auth_as()
sm = _make_soundmark(db_session)
sm = _make_soundmark(db_session, tier="community")
song, _ = _make_library_song(db_session, user.id)
assert client.post("/soundmarks/999999/proposals", json={"song_id": song.id}, headers=headers).status_code == 404
......@@ -410,7 +698,7 @@ def test_proposal_requires_soundmark_and_song_to_exist(client, db_session, auth_
def test_voting_for_unknown_proposal_404s(client, db_session, auth_as):
headers, _ = auth_as()
sm = _make_soundmark(db_session)
sm = _make_soundmark(db_session, tier="community")
response = client.post(f"/soundmarks/{sm.id}/proposals/999999/vote", headers=headers)
assert response.status_code == 404
......
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