Commit a57cf516 authored by Aryan Noshirvnai's avatar Aryan Noshirvnai

Redesign Soundmarks: ephemeral user drops + business applications

Full replacement of the major/community tiers and propose+vote mechanism
with: any user drops a song at their current location (24h TTL via a
read-time cutoff filter, clustered within 25m via union-find at query
time), and businesses become persistent, playlist-owning soundmarks only
through a self-service application a super admin approves - replacing the
old admin-picks-an-existing-owner flow entirely.

- Soundmark splits into two tables: soundmarks (business-only now, owner
  required) and the new SoundmarkDrop/BusinessApplication.
- SoundmarkProposal/SoundmarkProposalVote retired outright.
- New endpoints: POST /drop, POST/GET /business-applications(/mine),
  approve/reject. /nearby now returns {businesses, drop_clusters}.
- Migration wipes existing major/community rows (kept business ones,
  per the user's explicit direction), tightens business_owner_id to
  NOT NULL - verified both directions against a scratch DB copy.
- tests/test_soundmarks.py rewritten for the new shape; full backend
  suite green (506 passed).
parent eb82e2ab
Pipeline #1328 failed with stage
in 23 seconds
"""redesign soundmarks: drops and business applications
Revision ID: 33120d763567
Revises: 499ebec0825d
Create Date: 2026-12-03 19:58:00.000000
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision: str = '33120d763567'
down_revision: Union[str, Sequence[str], None] = '499ebec0825d'
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None:
"""Upgrade schema."""
# Retiring the major/community tiers entirely (full replacement, confirmed with the user -
# see Soundmark's docstring in database.py). Wipe their data first, while `tier` still
# exists to filter on - children before parents.
op.execute("DELETE FROM soundmark_proposal_votes")
op.execute("DELETE FROM soundmark_suggestions WHERE soundmark_id IN (SELECT id FROM soundmarks WHERE tier != 'business')")
op.execute("DELETE FROM soundmark_playlist_tracks WHERE soundmark_id IN (SELECT id FROM soundmarks WHERE tier != 'business')")
op.execute("DELETE FROM soundmarks WHERE tier != 'business'")
op.drop_index(op.f('ix_soundmark_proposal_votes_user_id'), table_name='soundmark_proposal_votes')
op.drop_index(op.f('ix_soundmark_proposal_votes_proposal_id'), table_name='soundmark_proposal_votes')
op.drop_index(op.f('ix_soundmark_proposal_votes_id'), table_name='soundmark_proposal_votes')
op.drop_table('soundmark_proposal_votes')
op.drop_index(op.f('ix_soundmark_proposals_soundmark_id'), table_name='soundmark_proposals')
op.drop_index(op.f('ix_soundmark_proposals_id'), table_name='soundmark_proposals')
op.drop_table('soundmark_proposals')
# song_id carries a FK to library_songs - SQLite's native ALTER TABLE DROP COLUMN can't drop
# a column involved in a foreign key, so this needs batch mode (table-rebuild) rather than a
# plain op.drop_column, unlike tier (no FK). Bundled with tightening business_owner_id in
# the same batch - every surviving row is business-tier and already has an owner (enforced
# by the old _validate_tier_and_owner at the API layer), so this is safe.
with op.batch_alter_table('soundmarks') as batch_op:
batch_op.drop_column('tier')
batch_op.drop_column('song_id')
batch_op.alter_column('business_owner_id', existing_type=sa.Integer(), nullable=False)
op.create_table('soundmark_drops',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('song_id', sa.Integer(), nullable=False),
sa.Column('dropped_by_user_id', sa.Integer(), nullable=False),
sa.Column('latitude', sa.Float(), nullable=False),
sa.Column('longitude', sa.Float(), nullable=False),
sa.Column('created_at', sa.DateTime(), nullable=True),
sa.ForeignKeyConstraint(['song_id'], ['library_songs.id'], ),
sa.ForeignKeyConstraint(['dropped_by_user_id'], ['users.id'], ),
sa.PrimaryKeyConstraint('id'),
)
op.create_index(op.f('ix_soundmark_drops_id'), 'soundmark_drops', ['id'], unique=False)
op.create_index(op.f('ix_soundmark_drops_song_id'), 'soundmark_drops', ['song_id'], unique=False)
op.create_index(op.f('ix_soundmark_drops_dropped_by_user_id'), 'soundmark_drops', ['dropped_by_user_id'], unique=False)
op.create_index(op.f('ix_soundmark_drops_created_at'), 'soundmark_drops', ['created_at'], unique=False)
op.create_table('business_applications',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('business_name', sa.String(), nullable=False),
sa.Column('phone_number', sa.String(), nullable=False),
sa.Column('latitude', sa.Float(), nullable=False),
sa.Column('longitude', sa.Float(), nullable=False),
sa.Column('submitted_by_user_id', sa.Integer(), nullable=False),
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(['submitted_by_user_id'], ['users.id'], ),
sa.ForeignKeyConstraint(['reviewed_by_user_id'], ['users.id'], ),
sa.PrimaryKeyConstraint('id'),
)
op.create_index(op.f('ix_business_applications_id'), 'business_applications', ['id'], unique=False)
op.create_index(op.f('ix_business_applications_submitted_by_user_id'), 'business_applications', ['submitted_by_user_id'], unique=False)
op.create_index(op.f('ix_business_applications_status'), 'business_applications', ['status'], unique=False)
def downgrade() -> None:
"""Downgrade schema. Wiped tier/song data is not recoverable - same as any destructive
migration in this repo."""
op.drop_index(op.f('ix_business_applications_status'), table_name='business_applications')
op.drop_index(op.f('ix_business_applications_submitted_by_user_id'), table_name='business_applications')
op.drop_index(op.f('ix_business_applications_id'), table_name='business_applications')
op.drop_table('business_applications')
op.drop_index(op.f('ix_soundmark_drops_created_at'), table_name='soundmark_drops')
op.drop_index(op.f('ix_soundmark_drops_dropped_by_user_id'), table_name='soundmark_drops')
op.drop_index(op.f('ix_soundmark_drops_song_id'), table_name='soundmark_drops')
op.drop_index(op.f('ix_soundmark_drops_id'), table_name='soundmark_drops')
op.drop_table('soundmark_drops')
with op.batch_alter_table('soundmarks') as batch_op:
batch_op.alter_column('business_owner_id', existing_type=sa.Integer(), nullable=True)
batch_op.add_column(sa.Column('song_id', sa.Integer(), nullable=True))
batch_op.add_column(sa.Column('tier', sa.String(), nullable=False, server_default='business'))
batch_op.create_foreign_key('fk_soundmarks_song_id_library_songs', 'library_songs', ['song_id'], ['id'])
op.create_table('soundmark_proposals',
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('proposed_by_user_id', sa.Integer(), nullable=True),
sa.Column('created_at', sa.DateTime(), nullable=True),
sa.ForeignKeyConstraint(['proposed_by_user_id'], ['users.id'], ),
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_proposal_song'),
)
op.create_index(op.f('ix_soundmark_proposals_id'), 'soundmark_proposals', ['id'], unique=False)
op.create_index(op.f('ix_soundmark_proposals_soundmark_id'), 'soundmark_proposals', ['soundmark_id'], unique=False)
op.create_table('soundmark_proposal_votes',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('proposal_id', sa.Integer(), nullable=True),
sa.Column('user_id', sa.Integer(), nullable=True),
sa.Column('created_at', sa.DateTime(), nullable=True),
sa.ForeignKeyConstraint(['proposal_id'], ['soundmark_proposals.id'], ),
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('proposal_id', 'user_id', name='uq_soundmark_proposal_vote'),
)
op.create_index(op.f('ix_soundmark_proposal_votes_id'), 'soundmark_proposal_votes', ['id'], unique=False)
op.create_index(op.f('ix_soundmark_proposal_votes_proposal_id'), 'soundmark_proposal_votes', ['proposal_id'], unique=False)
op.create_index(op.f('ix_soundmark_proposal_votes_user_id'), 'soundmark_proposal_votes', ['user_id'], unique=False)
# Soundmarks API changes — for Android client wiring
Backend repo: stax_backend_api, router: `src/api/routers/soundmarks.py`, prefix `/soundmarks`.
All authenticated endpoints use the same Bearer-token auth as every other endpoint in this API.
## Removed endpoints (delete any client code calling these)
- `POST /soundmarks` (old admin create-soundmark-with-tier)
- `PATCH /soundmarks/{id}/song` (major-tier "set anthem")
- `GET /soundmarks/{id}/proposals`
- `POST /soundmarks/{id}/proposals`
- `POST /soundmarks/{id}/proposals/{proposal_id}/vote`
- `DELETE /soundmarks/{id}/proposals/vote`
The whole three-tier (`major`/`community`/`business`) model is gone. There are now
only two kinds of map pin: **business** (persistent, admin-approved) and **drop
cluster** (ephemeral, user-generated, 1+ songs).
## Changed: `GET /soundmarks/nearby?lat={lat}&lon={lon}&drop_radius_km={km}`
Response shape changes from a flat `soundmarks: [...]` array to:
```json
{
"businesses": [
{
"id": 1,
"name": "Cafe Example",
"description": "...",
"latitude": 0.0,
"longitude": 0.0,
"radius_meters": 200.0,
"business_owner_username": "owner123",
"current_song": { "...song object..." } ,
"playlist": [ { "...song object...", "position": 0 } ]
}
],
"drop_clusters": [
{
"id": 123,
"latitude": 0.0,
"longitude": 0.0,
"distance_meters": 12.3,
"drops": [
{ "id": 1, "song": { "...song object..." }, "dropped_by_username": "alice", "created_at": "2026-12-03T12:00:00Z" },
{ "id": 2, "song": { "...song object..." }, "dropped_by_username": "bob", "created_at": "2026-12-03T12:05:00Z" }
]
}
]
}
```
- `businesses` entries no longer have `tier` or `proposal_count` — drop any UI/model
code keyed on tier.
- `drop_clusters` is new: each entry groups one or more individually-attributed song
drops that are within 25 meters of each other. **Render one pin per cluster, not
one pin per drop.** Tapping a cluster pin should list every entry in `drops` (song +
`dropped_by_username` + `created_at`), even when there's only one.
- Drops older than 24 hours are already excluded server-side — the client needs no
expiry/TTL logic, just re-fetch `/nearby` periodically (e.g. on map move/refresh) to
pick up both new drops and ones that have aged out.
- `drop_radius_km` is optional (default `1.0`) — same role as whatever radius param
the client previously used for the old flat `nearby` call.
## Changed: `PATCH /soundmarks/{id}` (business soundmark edit)
Request body no longer accepts `tier`, `business_owner_id`, or `song_id` — only
`name`, `description`, `latitude`, `longitude`, `radius_meters`.
## New: `POST /soundmarks/drop`
Auth required.
Request:
```json
{ "song_id": 42, "latitude": 0.0, "longitude": 0.0 }
```
Response:
```json
{
"status": "success",
"drop": { "id": 1, "song": {...}, "dropped_by_username": "alice", "latitude": 0.0, "longitude": 0.0, "created_at": "..." }
}
```
404 if `song_id` doesn't exist. This is the "drop a song at my current location"
action: read device GPS, let the user pick a song (reuse whatever song-search/picker
UI already existed for the old propose/suggest flows), POST here. No tier/owner
concept involved.
## New: Business application flow (replaces old admin-only business creation)
- **`POST /soundmarks/business-applications`** — auth required.
Request: `{ "business_name": "...", "phone_number": "...", "latitude": 0.0, "longitude": 0.0 }`
Returns the created application. 409 if the caller already has a `pending`
application.
- **`GET /soundmarks/business-applications/mine`** — auth required. Returns the
caller's own applications (`status`: `pending`/`approved`/`rejected`), newest first.
Check this before showing the application form, to instead show "pending review" /
"approved — manage your business" / re-show-the-form states.
- **`GET /soundmarks/business-applications?status=pending`** — super admin only.
Lists applications for review.
- **`POST /soundmarks/business-applications/{id}/approve`** — super admin only.
Returns `{ "status": "success", "application": {...}, "soundmark": {...} }` — the
newly created business soundmark.
- **`POST /soundmarks/business-applications/{id}/reject`** — super admin only.
Approving an application automatically promotes the submitter's role to
`business_admin` server-side — no extra client call needed, just re-fetch the current
user's role/profile afterward so any role-gated nav updates.
## Unchanged, still valid as-is
- `GET /soundmarks/mine`, `GET /soundmarks/song-library`, `GET /soundmarks/geocode`,
`GET /soundmarks/reverse-geocode`
- All `/soundmarks/admin/users*` endpoints
- `GET /soundmarks/suggestions`, `POST /soundmarks/suggestions/{id}/approve|reject`
- `POST /soundmarks/{id}/playlist`, `DELETE /soundmarks/{id}/playlist/{song_id}`
- `GET /soundmarks/{id}/stream`
- `POST /soundmarks/{id}/suggestions` (suggest a song for a business soundmark's playlist)
- `DELETE /soundmarks/{id}`
- "Add song to my library" — reuse whatever endpoint the client already calls for
that elsewhere (backend: `POST /library/shared/claim` with `{title, artist}`) for
the business-pin "add to my library" action; nothing new was added for this
specifically.
## Map/UI behavior summary
- Two pin types now (not three): **business** (persistent, admin-approved) and **drop
cluster** (ephemeral, 1+ user drops within 25m of each other). No more
"major"/"community" distinction.
- Business pin tap → show playlist, current song, "suggest a song," "add to my
library."
- Drop-cluster pin tap → list each drop (song + dropper username + time dropped).
- A floating "drop a song here" action, always available when location is known →
opens song picker → `POST /soundmarks/drop` → refresh `/nearby`.
- A "become a business" entry point (form: name, phone, map pin) → `POST
/business-applications`, then poll/check `/business-applications/mine` for status.
......@@ -11,34 +11,35 @@ from src.core.config import logger
from src.services.media_stream import stream_audio_file
from src.core.database import (
get_db,
BusinessApplication,
LibrarySong,
Soundmark,
SoundmarkDrop,
SoundmarkPlaylistTrack,
SoundmarkProposal,
SoundmarkProposalVote,
SoundmarkSuggestion,
User,
)
from src.core.security import get_current_business_admin, get_current_super_admin, get_current_user, get_current_user_for_stream, hash_password, is_super_admin
from src.services.geo import haversine_meters as _haversine_meters
from src.services.geo import cluster_by_proximity, haversine_meters as _haversine_meters
router = APIRouter(prefix="/soundmarks", tags=["Soundmarks"])
VALID_ROLES = {"user", "business_admin", "super_admin"}
VALID_TIERS = {"major", "business", "community"}
# How close (in meters) two user-dropped songs need to be to show as one map pin instead of two.
CLUSTER_RADIUS_METERS = 25.0
# A dropped song stops appearing in /nearby once it's this old - see the module docstring-style
# note on SoundmarkDrop in database.py for why this is a read-time filter, not a reaper job.
DROP_EXPIRES_AFTER = timedelta(hours=24)
# 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.
NOMINATIM_USER_AGENT = "StaxSoundmarks/1.0 (location picker for the Stax soundmarks feature)"
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 _serialize_song_brief(song: Optional[LibrarySong]) -> Optional[dict]:
if not song:
return None
return {"id": song.id, "title": song.title, "artist": song.artist, "album": song.album, "coverart": song.coverart}
def _get_playlist(sm: Soundmark, db: Session) -> list:
......@@ -52,21 +53,13 @@ def _get_playlist(sm: Soundmark, db: Session) -> list:
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}
)
songs.append(_serialize_song_brief(song))
return songs
def _resolve_active_song_id(sm: Soundmark, db: Session) -> Optional[int]:
"""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":
"""What actually plays at a business soundmark: the first track in the owner's playlist, by
position then recency."""
featured = (
db.query(SoundmarkPlaylistTrack)
.filter(SoundmarkPlaylistTrack.soundmark_id == sm.id)
......@@ -74,75 +67,38 @@ def _resolve_active_song_id(sm: Soundmark, db: Session) -> Optional[int]:
.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
scored = [
(db.query(SoundmarkProposalVote).filter(SoundmarkProposalVote.proposal_id == p.id).count(), p)
for p in proposals
]
scored.sort(key=lambda pair: (-pair[0], pair[1].created_at))
return scored[0][1].song_id
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()
if sm.tier == "community"
else 0
)
owner = db.query(User).filter(User.id == sm.business_owner_id).first()
return {
"id": sm.id,
"name": sm.name,
"description": sm.description,
"tier": sm.tier,
"latitude": sm.latitude,
"longitude": sm.longitude,
"radius_meters": sm.radius_meters,
"business_owner_id": sm.business_owner_id,
"business_owner_username": owner.username if owner else None,
"song": (
{
"id": song.id,
"title": song.title,
"artist": song.artist,
"album": song.album,
"coverart": song.coverart,
}
if song
else None
),
"playlist": _get_playlist(sm, db) if sm.tier == "business" else [],
"proposal_count": proposal_count,
"song": _serialize_song_brief(song),
"playlist": _get_playlist(sm, db),
"created_at": sm.created_at,
"updated_at": sm.updated_at,
}
def _serialize_proposal(p: SoundmarkProposal, db: Session, current_user_id: int) -> dict:
song = db.query(LibrarySong).filter(LibrarySong.id == p.song_id).first()
vote_count = db.query(SoundmarkProposalVote).filter(SoundmarkProposalVote.proposal_id == p.id).count()
has_voted = (
db.query(SoundmarkProposalVote)
.filter(SoundmarkProposalVote.proposal_id == p.id, SoundmarkProposalVote.user_id == current_user_id)
.first()
is not None
)
proposer = db.query(User).filter(User.id == p.proposed_by_user_id).first()
def _serialize_drop(d: SoundmarkDrop, db: Session) -> dict:
song = db.query(LibrarySong).filter(LibrarySong.id == d.song_id).first()
dropper = db.query(User).filter(User.id == d.dropped_by_user_id).first()
return {
"id": p.id,
"song": (
{"id": song.id, "title": song.title, "artist": song.artist, "album": song.album, "coverart": song.coverart}
if song
else None
),
"vote_count": vote_count,
"has_voted": has_voted,
"proposed_by_username": proposer.username if proposer else None,
"created_at": p.created_at,
"id": d.id,
"song": _serialize_song_brief(song),
"dropped_by_username": dropper.username if dropper else None,
"latitude": d.latitude,
"longitude": d.longitude,
"created_at": d.created_at,
}
......@@ -154,47 +110,24 @@ def _serialize_suggestion(s: SoundmarkSuggestion, db: Session) -> dict:
"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
),
"song": _serialize_song_brief(song),
"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."""
existing = (
db.query(SoundmarkProposalVote)
.join(SoundmarkProposal, SoundmarkProposal.id == SoundmarkProposalVote.proposal_id)
.filter(SoundmarkProposal.soundmark_id == soundmark_id, SoundmarkProposalVote.user_id == user_id)
.first()
)
if existing:
if existing.proposal_id == proposal_id:
return
db.delete(existing)
db.flush()
db.add(SoundmarkProposalVote(proposal_id=proposal_id, user_id=user_id))
def _propose_and_vote(soundmark_id: int, song_id: int, user_id: int, db: Session) -> SoundmarkProposal:
proposal = (
db.query(SoundmarkProposal)
.filter(SoundmarkProposal.soundmark_id == soundmark_id, SoundmarkProposal.song_id == song_id)
.first()
)
if not proposal:
proposal = SoundmarkProposal(soundmark_id=soundmark_id, song_id=song_id, proposed_by_user_id=user_id)
db.add(proposal)
db.flush() # need proposal.id before voting for it
_cast_vote(soundmark_id, proposal.id, user_id, db)
return proposal
def _serialize_application(a: BusinessApplication) -> dict:
return {
"id": a.id,
"business_name": a.business_name,
"phone_number": a.phone_number,
"latitude": a.latitude,
"longitude": a.longitude,
"status": a.status,
"created_at": a.created_at,
"reviewed_at": a.reviewed_at,
}
def _maybe_promote_to_business_admin(owner: User, db: Session) -> None:
......@@ -213,30 +146,12 @@ def _check_owns_soundmark(sm: Soundmark, current_user: User) -> None:
# ---- Schemas ----
class SoundmarkCreate(BaseModel):
name: str
description: Optional[str] = None
tier: str = "community"
latitude: float
longitude: float
radius_meters: float = 200.0
business_owner_id: Optional[int] = None
song_id: Optional[int] = None
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
business_owner_id: Optional[int] = None
song_id: Optional[int] = None
class SongAssign(BaseModel):
song_id: Optional[int] = None # null clears the anthem
class PlaylistAdd(BaseModel):
......@@ -247,6 +162,19 @@ class SuggestSong(BaseModel):
song_id: int
class DropCreate(BaseModel):
song_id: int
latitude: float
longitude: float
class BusinessApplicationCreate(BaseModel):
business_name: str
phone_number: str
latitude: float
longitude: float
class RoleUpdate(BaseModel):
role: str
......@@ -270,16 +198,19 @@ class PasswordResetReq(BaseModel):
@router.get("/nearby")
def get_nearby_soundmarks(
lat: float, lon: float, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)
lat: float,
lon: float,
drop_radius_km: float = 1.0,
db: Session = Depends(get_db),
current_user: User = Depends(get_current_user),
):
"""Soundmarks whose own trigger radius currently contains (lat, lon), closest first - this
is what the webapp polls as the user moves, to find 'the anthem playing here' rather than
a caller-supplied search radius. Includes soundmarks with no active song at all (no
admin-set fallback, no proposals yet) so they're still discoverable - otherwise nobody
could ever be the first to propose a song for a brand new soundmark; the webapp shows those
with a "propose one" prompt instead of a play button."""
"""Businesses: closest-in-range match against each soundmark's own trigger radius, exactly
as before. Drop clusters: every non-expired drop (last 24h) is grouped by mutual 25m
proximity first - clustering must not depend on the caller's own location, or the same two
drops could appear as one cluster to one caller and two to another - then only clusters
whose nearest member is within drop_radius_km of the caller are returned."""
all_marks = db.query(Soundmark).all()
matches = []
businesses = []
for sm in all_marks:
if sm.latitude is None or sm.longitude is None:
continue
......@@ -287,9 +218,56 @@ def get_nearby_soundmarks(
if dist <= sm.radius_meters:
entry = _serialize(sm, db)
entry["distance_meters"] = dist
matches.append(entry)
matches.sort(key=lambda m: m["distance_meters"])
return {"status": "success", "soundmarks": matches}
businesses.append(entry)
businesses.sort(key=lambda m: m["distance_meters"])
cutoff = datetime.now(timezone.utc) - DROP_EXPIRES_AFTER
active_drops = db.query(SoundmarkDrop).filter(SoundmarkDrop.created_at >= cutoff).all()
points = [(d.latitude, d.longitude) for d in active_drops]
groups = cluster_by_proximity(points, CLUSTER_RADIUS_METERS)
drop_clusters = []
for group in groups:
members = [active_drops[i] for i in group]
nearest_dist = min(_haversine_meters(lat, lon, d.latitude, d.longitude) for d in members)
if nearest_dist > drop_radius_km * 1000:
continue
drop_clusters.append(
{
"id": min(d.id for d in members),
"latitude": sum(d.latitude for d in members) / len(members),
"longitude": sum(d.longitude for d in members) / len(members),
"distance_meters": nearest_dist,
"drops": [_serialize_drop(d, db) for d in members],
}
)
drop_clusters.sort(key=lambda c: c["distance_meters"])
return {"status": "success", "businesses": businesses, "drop_clusters": drop_clusters}
@router.post("/drop", status_code=201)
def drop_song(
body: DropCreate,
db: Session = Depends(get_db),
current_user: User = Depends(get_current_user),
):
"""Any user drops a song at their current location - no tier, no owner, no review step.
Expires after DROP_EXPIRES_AFTER (filtered out of /nearby, never explicitly deleted here -
see database.py's SoundmarkDrop docstring)."""
song = db.query(LibrarySong).filter(LibrarySong.id == body.song_id).first()
if not song:
raise HTTPException(status_code=404, detail="Song not found")
drop = SoundmarkDrop(
song_id=body.song_id,
dropped_by_user_id=current_user.id,
latitude=body.latitude,
longitude=body.longitude,
)
db.add(drop)
db.commit()
db.refresh(drop)
return {"status": "success", "drop": _serialize_drop(drop, db)}
@router.get("/mine")
......@@ -385,10 +363,9 @@ def list_users(
db: Session = Depends(get_db),
current_user: User = Depends(get_current_super_admin),
):
"""Lets the super admin panel find/list users to promote to business_admin, assign as a
soundmark's owner, or manage directly (edit/deactivate/suspend/reset password below). `q`
is a plain substring match against username - good enough at this app's scale, no need for
a real search index."""
"""Lets the super admin panel find/list users to manage directly (edit/deactivate/suspend/
reset password below). `q` is a plain substring match against username - good enough at this
app's scale, no need for a real search index."""
query = db.query(User)
if role:
query = query.filter(User.role == role)
......@@ -472,6 +449,114 @@ def admin_reset_password(
return {"status": "success"}
# ---- Business applications (self-service, super-admin-reviewed) ----
@router.post("/business-applications", status_code=201)
def submit_business_application(
body: BusinessApplicationCreate,
db: Session = Depends(get_db),
current_user: User = Depends(get_current_user),
):
existing_pending = (
db.query(BusinessApplication)
.filter(BusinessApplication.submitted_by_user_id == current_user.id, BusinessApplication.status == "pending")
.first()
)
if existing_pending:
raise HTTPException(status_code=409, detail="You already have a pending business application")
application = BusinessApplication(
business_name=body.business_name,
phone_number=body.phone_number,
latitude=body.latitude,
longitude=body.longitude,
submitted_by_user_id=current_user.id,
)
db.add(application)
db.commit()
db.refresh(application)
return {"status": "success", "application": _serialize_application(application)}
@router.get("/business-applications/mine")
def get_my_business_applications(db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
applications = (
db.query(BusinessApplication)
.filter(BusinessApplication.submitted_by_user_id == current_user.id)
.order_by(BusinessApplication.created_at.desc())
.all()
)
return {"status": "success", "applications": [_serialize_application(a) for a in applications]}
@router.get("/business-applications")
def get_business_applications(
status: str = "pending",
db: Session = Depends(get_db),
current_user: User = Depends(get_current_super_admin),
):
applications = (
db.query(BusinessApplication)
.filter(BusinessApplication.status == status)
.order_by(BusinessApplication.created_at)
.all()
)
return {"status": "success", "applications": [_serialize_application(a) for a in applications]}
@router.post("/business-applications/{application_id}/approve")
def approve_business_application(
application_id: int,
db: Session = Depends(get_db),
current_user: User = Depends(get_current_super_admin),
):
application = db.query(BusinessApplication).filter(BusinessApplication.id == application_id).first()
if not application:
raise HTTPException(status_code=404, detail="Application not found")
if application.status != "pending":
raise HTTPException(status_code=400, detail="This application has already been reviewed")
submitter = db.query(User).filter(User.id == application.submitted_by_user_id).first()
sm = Soundmark(
name=application.business_name,
description=None,
latitude=application.latitude,
longitude=application.longitude,
radius_meters=200.0,
business_owner_id=application.submitted_by_user_id,
)
db.add(sm)
if submitter:
_maybe_promote_to_business_admin(submitter, db)
application.status = "approved"
application.reviewed_by_user_id = current_user.id
application.reviewed_at = datetime.now(timezone.utc)
db.commit()
db.refresh(application)
db.refresh(sm)
return {"status": "success", "application": _serialize_application(application), "soundmark": _serialize(sm, db)}
@router.post("/business-applications/{application_id}/reject")
def reject_business_application(
application_id: int,
db: Session = Depends(get_db),
current_user: User = Depends(get_current_super_admin),
):
application = db.query(BusinessApplication).filter(BusinessApplication.id == application_id).first()
if not application:
raise HTTPException(status_code=404, detail="Application not found")
if application.status != "pending":
raise HTTPException(status_code=400, detail="This application has already been reviewed")
application.status = "rejected"
application.reviewed_by_user_id = current_user.id
application.reviewed_at = datetime.now(timezone.utc)
db.commit()
db.refresh(application)
return {"status": "success", "application": _serialize_application(application)}
# ---- Review queue (business_admin+, scoped to what they can moderate) ----
......@@ -481,10 +566,9 @@ def get_review_queue(
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)."""
"""Suggestions waiting on a decision. Super admins see every soundmark's queue; business
admins only see suggestions for soundmarks they themselves own (every soundmark has an
owner now, so this scoping falls out naturally)."""
query = db.query(SoundmarkSuggestion).filter(SoundmarkSuggestion.status == status)
if not is_super_admin(current_user):
owned_ids = [
......@@ -509,9 +593,6 @@ def approve_suggestion(
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)
......@@ -551,7 +632,7 @@ def reject_suggestion(
return {"status": "success", "suggestion": _serialize_suggestion(suggestion, db)}
# ---- Super admin CRUD ----
# ---- Super admin management ----
@router.get("")
......@@ -560,59 +641,6 @@ def list_all_soundmarks(db: Session = Depends(get_db), current_user: User = Depe
return {"status": "success", "soundmarks": [_serialize(sm, db) for sm in marks]}
@router.post("", status_code=201)
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")
sm = Soundmark(**body.dict())
db.add(sm)
if owner:
_maybe_promote_to_business_admin(owner, db)
db.commit()
db.refresh(sm)
return {"status": "success", "soundmark": _serialize(sm, db)}
@router.patch("/{soundmark_id}/song")
def set_soundmark_song(
soundmark_id: int,
body: SongAssign,
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 != "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
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,
......@@ -623,8 +651,6 @@ def add_playlist_track(
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:
......@@ -653,8 +679,6 @@ def remove_playlist_track(
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 = (
......@@ -680,28 +704,9 @@ def update_soundmark(
sm = db.query(Soundmark).filter(Soundmark.id == soundmark_id).first()
if not sm:
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")
for key, value in data.items():
setattr(sm, key, value)
if owner:
_maybe_promote_to_business_admin(owner, db)
db.commit()
db.refresh(sm)
return {"status": "success", "soundmark": _serialize(sm, db)}
......@@ -738,7 +743,7 @@ def stream_soundmark_anthem(
return stream_audio_file(song.file_path, request)
# ---- Suggestions (major/business tier - any authenticated user proposes, owner reviews) ----
# ---- Suggestions (any authenticated user proposes, owner reviews) ----
@router.post("/{soundmark_id}/suggestions", status_code=201)
......@@ -751,11 +756,6 @@ def suggest_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.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")
......@@ -764,78 +764,3 @@ def suggest_song(
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")
def get_proposals(soundmark_id: int, 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")
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"])
return {"status": "success", "proposals": serialized}
@router.post("/{soundmark_id}/proposals", status_code=201)
def propose_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="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")
proposal = _propose_and_vote(soundmark_id, body.song_id, current_user.id, db)
db.commit()
db.refresh(proposal)
return {"status": "success", "proposal": _serialize_proposal(proposal, db, current_user.id)}
@router.post("/{soundmark_id}/proposals/{proposal_id}/vote")
def vote_for_proposal(
soundmark_id: int,
proposal_id: int,
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)
.first()
)
if not proposal:
raise HTTPException(status_code=404, detail="Proposal not found")
_cast_vote(soundmark_id, proposal_id, current_user.id, db)
db.commit()
return {"status": "success", "proposal": _serialize_proposal(proposal, db, current_user.id)}
@router.delete("/{soundmark_id}/proposals/vote")
def remove_vote(soundmark_id: int, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
existing = (
db.query(SoundmarkProposalVote)
.join(SoundmarkProposal, SoundmarkProposal.id == SoundmarkProposalVote.proposal_id)
.filter(SoundmarkProposal.soundmark_id == soundmark_id, SoundmarkProposalVote.user_id == current_user.id)
.first()
)
if existing:
db.delete(existing)
db.commit()
return {"status": "success"}
......@@ -257,36 +257,57 @@ class LiveLocation(Base):
updated_at = Column(DateTime, default=lambda: datetime.now(timezone.utc), onupdate=lambda: datetime.now(timezone.utc))
class Soundmark(Base):
"""A curated 'anthem' tied to a real-world place - distinct from LiveLocation (a live
per-user broadcast of wherever they currently are, not a persistent place). 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)."""
"""A persistent, business-owned location with a playlist - distinct from LiveLocation (a
live per-user broadcast of wherever they currently are) and from SoundmarkDrop (an
ephemeral, user-dropped song with no owner - see below). Created only by approving a
BusinessApplication (see soundmarks.py); always has an owner (business_owner_id) and a
*playlist* (SoundmarkPlaylistTrack) the owner adds/removes tracks from directly
(auto-applied) - everyone else's picks go through SoundmarkSuggestion's review queue
instead."""
__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" -
# this is what /soundmarks/nearby matches against, not a caller-supplied search radius.
radius_meters = Column(Float, default=200.0, nullable=False)
business_owner_id = Column(Integer, ForeignKey("users.id"), nullable=True, index=True)
song_id = Column(Integer, ForeignKey("library_songs.id"), nullable=True)
business_owner_id = Column(Integer, ForeignKey("users.id"), nullable=False, index=True)
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 SoundmarkDrop(Base):
"""One song a user dropped at their current location - ephemeral (no owner, nothing ever
edits a row after creation) and ungoverned (no review step). soundmarks.py filters these to
the last 24h at read time (DROP_EXPIRES_AFTER) and groups nearby drops into clusters at
query time (CLUSTER_RADIUS_METERS, via services/geo.py's cluster_by_proximity) rather than
persisting any cluster/group relationship here."""
__tablename__ = "soundmark_drops"
id = Column(Integer, primary_key=True, index=True)
song_id = Column(Integer, ForeignKey("library_songs.id"), nullable=False, index=True)
dropped_by_user_id = Column(Integer, ForeignKey("users.id"), nullable=False, index=True)
latitude = Column(Float, nullable=False)
longitude = Column(Float, nullable=False)
created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc), index=True)
class BusinessApplication(Base):
"""A user's self-service request for a location to become a business Soundmark. Reviewed
manually by a super admin (soundmarks.py's approve/reject endpoints) - approving creates the
actual Soundmark row (owner=submitted_by_user_id) and promotes the submitter to
business_admin via the existing _maybe_promote_to_business_admin helper."""
__tablename__ = "business_applications"
id = Column(Integer, primary_key=True, index=True)
business_name = Column(String, nullable=False)
phone_number = Column(String, nullable=False)
latitude = Column(Float, nullable=False)
longitude = Column(Float, nullable=False)
submitted_by_user_id = Column(Integer, ForeignKey("users.id"), nullable=False, index=True)
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 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
......@@ -300,12 +321,9 @@ class SoundmarkPlaylistTrack(Base):
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."""
"""A song someone other than the owner suggested for a business soundmark - sits in a
review queue until the owner (or a super admin) approves or rejects it. Approving adds a
SoundmarkPlaylistTrack."""
__tablename__ = "soundmark_suggestions"
id = Column(Integer, primary_key=True, index=True)
soundmark_id = Column(Integer, ForeignKey("soundmarks.id"), index=True)
......@@ -316,29 +334,6 @@ class SoundmarkSuggestion(Base):
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 "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)
soundmark_id = Column(Integer, ForeignKey("soundmarks.id"), index=True)
song_id = Column(Integer, ForeignKey("library_songs.id"))
proposed_by_user_id = Column(Integer, ForeignKey("users.id"))
created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc))
class SoundmarkProposalVote(Base):
"""One row per (proposal, voter). A voter switching their pick for a soundmark deletes
their old vote row (on whichever proposal it was) and inserts a new one - enforced in
soundmarks.py, not by a DB constraint, since "one vote per soundmark" spans proposals."""
__tablename__ = "soundmark_proposal_votes"
__table_args__ = (UniqueConstraint("proposal_id", "user_id", name="uq_soundmark_proposal_vote"),)
id = Column(Integer, primary_key=True, index=True)
proposal_id = Column(Integer, ForeignKey("soundmark_proposals.id"), index=True)
user_id = Column(Integer, ForeignKey("users.id"), index=True)
created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc))
class LiveRoom(Base):
__tablename__ = "live_rooms"
id = Column(Integer, primary_key=True, index=True)
......
......@@ -10,3 +10,33 @@ def haversine_meters(lat1: float, lon1: float, lat2: float, lon2: float) -> floa
dlon = math.radians(lon2 - lon1)
a = math.sin(dlat / 2) ** 2 + math.cos(math.radians(lat1)) * math.cos(math.radians(lat2)) * math.sin(dlon / 2) ** 2
return R * 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))
def cluster_by_proximity(points: list[tuple[float, float]], radius_meters: float) -> list[list[int]]:
"""Groups point indices into clusters via union-find, merging two points whenever they're
within radius_meters of each other - so a transitive chain (A near B, B near C, A far from
C) still ends up in one cluster, not split by naive pairwise grouping. Used by Soundmarks'
/nearby to group ephemeral SoundmarkDrops - recomputed fresh every call (no persisted
cluster identity), matching this file's existing all-pairs-haversine complexity bar."""
parent = list(range(len(points)))
def find(i: int) -> int:
while parent[i] != i:
parent[i] = parent[parent[i]]
i = parent[i]
return i
def union(i: int, j: int) -> None:
ri, rj = find(i), find(j)
if ri != rj:
parent[ri] = rj
for i in range(len(points)):
for j in range(i + 1, len(points)):
if haversine_meters(points[i][0], points[i][1], points[j][0], points[j][1]) <= radius_meters:
union(i, j)
groups: dict[int, list[int]] = {}
for i in range(len(points)):
groups.setdefault(find(i), []).append(i)
return list(groups.values())
......@@ -3,7 +3,7 @@ import tempfile
import httpx
from src.core.database import LibrarySong, Soundmark, SoundmarkSuggestion
from src.core.database import LibrarySong, Soundmark, SoundmarkDrop
def _make_library_song(db_session, user_id, **overrides):
......@@ -21,10 +21,10 @@ def _make_library_song(db_session, user_id, **overrides):
return song, path
def _make_soundmark(db_session, **overrides):
defaults = dict(name="Test Soundmark", tier="community", latitude=37.7749, longitude=-122.4194, radius_meters=200.0)
def _make_soundmark(db_session, business_owner_id, **overrides):
defaults = dict(name="Joe's Cafe", latitude=37.7749, longitude=-122.4194, radius_meters=200.0)
defaults.update(overrides)
sm = Soundmark(**defaults)
sm = Soundmark(business_owner_id=business_owner_id, **defaults)
db_session.add(sm)
db_session.commit()
db_session.refresh(sm)
......@@ -48,20 +48,13 @@ 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", "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", "tier": "major", "latitude": 0, "longitude": 0}, headers=headers).status_code
== 403
)
assert client.delete("/soundmarks/1", headers=headers).status_code == 403
assert client.get("/soundmarks/business-applications", headers=headers).status_code == 403
def test_super_admin_can_access_business_endpoints_too(client, db_session, auth_as):
......@@ -71,176 +64,318 @@ def test_super_admin_can_access_business_endpoints_too(client, db_session, auth_
assert response.status_code == 200
# ---- Super admin CRUD + tier validation ----
# ---- Dropping a song ----
def test_super_admin_creates_a_major_location(client, auth_as):
headers, _ = auth_as(role="super_admin")
def test_drop_song_requires_auth(client):
response = client.post("/soundmarks/drop", json={"song_id": 1, "latitude": 0, "longitude": 0})
assert response.status_code == 401
def test_drop_song_creates_a_drop_attributed_to_the_caller(client, db_session, auth_as):
headers, user = auth_as()
song, _ = _make_library_song(db_session, user.id)
response = client.post(
"/soundmarks",
json={
"name": "Landmark Plaza",
"description": "Historic square",
"tier": "major",
"latitude": 1.0,
"longitude": 2.0,
"radius_meters": 100,
},
headers=headers,
"/soundmarks/drop", json={"song_id": song.id, "latitude": 1.0, "longitude": 2.0}, 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
body = response.json()["drop"]
assert body["song"]["id"] == song.id
assert body["dropped_by_username"] == user.username
assert body["latitude"] == 1.0
assert body["longitude"] == 2.0
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
def test_drop_song_404s_for_unknown_song(client, auth_as):
headers, _ = auth_as()
response = client.post("/soundmarks/drop", json={"song_id": 999999, "latitude": 0, "longitude": 0}, headers=headers)
assert response.status_code == 404
# ---- Nearby: businesses + drop clusters ----
def test_nearby_matches_business_within_radius(client, db_session, auth_as):
headers, owner = auth_as(role="business_admin")
_make_soundmark(db_session, owner.id, name="Close Mark", latitude=37.7749, longitude=-122.4194, radius_meters=200)
response = client.get("/soundmarks/nearby", params={"lat": 37.77499, "lon": -122.4194}, headers=headers)
assert response.status_code == 200
businesses = response.json()["businesses"]
assert any(m["name"] == "Close Mark" for m in businesses)
assert businesses[0]["distance_meters"] < 200
def test_nearby_excludes_businesses_outside_their_radius(client, db_session, auth_as):
headers, owner = auth_as(role="business_admin")
_make_soundmark(db_session, owner.id, name="Far Mark", latitude=48.8566, longitude=2.3522, radius_meters=200)
response = client.get("/soundmarks/nearby", params={"lat": 37.7749, "lon": -122.4194}, headers=headers)
assert response.status_code == 200
names = {m["name"] for m in response.json()["businesses"]}
assert "Far Mark" not in names
def test_nearby_includes_a_single_drop_as_its_own_cluster(client, db_session, auth_as):
headers, user = auth_as()
song, _ = _make_library_song(db_session, user.id)
client.post("/soundmarks/drop", json={"song_id": song.id, "latitude": 1.0, "longitude": 1.0}, headers=headers)
response = client.get("/soundmarks/nearby", params={"lat": 1.0, "lon": 1.0}, headers=headers)
assert response.status_code == 200
clusters = response.json()["drop_clusters"]
assert len(clusters) == 1
assert len(clusters[0]["drops"]) == 1
assert clusters[0]["drops"][0]["song"]["id"] == song.id
def test_nearby_clusters_drops_within_25_meters(client, db_session, auth_as):
headers, user = auth_as()
song_a, _ = _make_library_song(db_session, user.id, title="A")
song_b, _ = _make_library_song(db_session, user.id, title="B")
# ~0.0001 degrees of latitude is roughly 11 meters - well within the 25m cluster radius.
client.post("/soundmarks/drop", json={"song_id": song_a.id, "latitude": 10.0, "longitude": 10.0}, headers=headers)
client.post("/soundmarks/drop", json={"song_id": song_b.id, "latitude": 10.0001, "longitude": 10.0}, headers=headers)
response = client.get("/soundmarks/nearby", params={"lat": 10.0, "lon": 10.0}, headers=headers)
clusters = response.json()["drop_clusters"]
assert len(clusters) == 1
titles = {d["song"]["title"] for d in clusters[0]["drops"]}
assert titles == {"A", "B"}
def test_nearby_keeps_drops_over_25_meters_apart_as_separate_clusters(client, db_session, auth_as):
headers, user = auth_as()
song_a, _ = _make_library_song(db_session, user.id, title="A")
song_b, _ = _make_library_song(db_session, user.id, title="B")
# ~0.01 degrees of latitude is roughly 1.1km - well outside the 25m cluster radius.
client.post("/soundmarks/drop", json={"song_id": song_a.id, "latitude": 20.0, "longitude": 20.0}, headers=headers)
client.post("/soundmarks/drop", json={"song_id": song_b.id, "latitude": 20.01, "longitude": 20.0}, headers=headers)
response = client.get("/soundmarks/nearby", params={"lat": 20.0, "lon": 20.0, "drop_radius_km": 5}, headers=headers)
clusters = response.json()["drop_clusters"]
assert len(clusters) == 2
def test_nearby_clustering_is_transitive_across_a_chain(client, db_session, auth_as):
"""A-B within 25m, B-C within 25m, A-C just over 25m - still one cluster (union-find), not
split by naive pairwise grouping."""
headers, user = auth_as()
song_a, _ = _make_library_song(db_session, user.id, title="A")
song_b, _ = _make_library_song(db_session, user.id, title="B")
song_c, _ = _make_library_song(db_session, user.id, title="C")
client.post("/soundmarks/drop", json={"song_id": song_a.id, "latitude": 30.0, "longitude": 30.0}, headers=headers)
client.post("/soundmarks/drop", json={"song_id": song_b.id, "latitude": 30.0002, "longitude": 30.0}, headers=headers)
client.post("/soundmarks/drop", json={"song_id": song_c.id, "latitude": 30.0004, "longitude": 30.0}, headers=headers)
response = client.get("/soundmarks/nearby", params={"lat": 30.0, "lon": 30.0, "drop_radius_km": 5}, headers=headers)
clusters = response.json()["drop_clusters"]
assert len(clusters) == 1
assert len(clusters[0]["drops"]) == 3
def test_nearby_excludes_drops_older_than_24_hours(client, db_session, auth_as):
from datetime import datetime, timedelta, timezone
headers, user = auth_as()
song, _ = _make_library_song(db_session, user.id)
stale = SoundmarkDrop(
song_id=song.id,
dropped_by_user_id=user.id,
latitude=5.0,
longitude=5.0,
created_at=datetime.now(timezone.utc) - timedelta(hours=25),
)
assert response.status_code == 422
db_session.add(stale)
db_session.commit()
response = client.get("/soundmarks/nearby", params={"lat": 5.0, "lon": 5.0}, headers=headers)
assert response.json()["drop_clusters"] == []
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,
def test_nearby_excludes_clusters_outside_the_callers_drop_radius(client, db_session, auth_as):
headers, user = auth_as()
song, _ = _make_library_song(db_session, user.id)
client.post("/soundmarks/drop", json={"song_id": song.id, "latitude": 40.0, "longitude": 40.0}, headers=headers)
response = client.get(
"/soundmarks/nearby", params={"lat": 41.0, "lon": 40.0, "drop_radius_km": 1}, headers=headers
)
assert response.status_code == 422
assert response.json()["drop_clusters"] == []
def test_creating_soundmark_with_invalid_tier_fails(client, auth_as):
headers, _ = auth_as(role="super_admin")
# ---- Business applications (self-service, super-admin-reviewed) ----
def test_submit_business_application_requires_auth(client):
response = client.post(
"/soundmarks", json={"name": "x", "tier": "galactic", "latitude": 0, "longitude": 0}, headers=headers
"/soundmarks/business-applications",
json={"business_name": "x", "phone_number": "123", "latitude": 0, "longitude": 0},
)
assert response.status_code == 422
assert response.status_code == 401
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},
def test_submit_business_application_succeeds(client, auth_as):
headers, _ = auth_as()
response = client.post(
"/soundmarks/business-applications",
json={"business_name": "Joe's Cafe", "phone_number": "555-0100", "latitude": 1.0, "longitude": 2.0},
headers=headers,
)
assert song_response.status_code == 422
assert response.status_code == 201
body = response.json()["application"]
assert body["business_name"] == "Joe's Cafe"
assert body["status"] == "pending"
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"
def test_submitting_a_second_application_while_one_is_pending_409s(client, auth_as):
headers, _ = auth_as()
body = {"business_name": "x", "phone_number": "123", "latitude": 0, "longitude": 0}
client.post("/soundmarks/business-applications", json=body, headers=headers)
response = client.post("/soundmarks/business-applications", json=body, headers=headers)
assert response.status_code == 409
response = client.post(
"/soundmarks",
json={"name": "Joe's Cafe", "tier": "business", "latitude": 1.0, "longitude": 2.0, "business_owner_id": owner.id},
def test_get_my_business_applications_returns_only_the_callers_own(client, auth_as):
headers, _ = auth_as()
other_headers, _ = auth_as()
client.post(
"/soundmarks/business-applications",
json={"business_name": "Mine", "phone_number": "1", "latitude": 0, "longitude": 0},
headers=headers,
)
assert response.status_code == 201
client.post(
"/soundmarks/business-applications",
json={"business_name": "Theirs", "phone_number": "2", "latitude": 0, "longitude": 0},
headers=other_headers,
)
db_session.refresh(owner)
assert owner.role == "business_admin"
response = client.get("/soundmarks/business-applications/mine", headers=headers)
assert response.status_code == 200
names = {a["business_name"] for a in response.json()["applications"]}
assert names == {"Mine"}
def test_creating_soundmark_with_unknown_owner_fails(client, auth_as):
headers, _ = auth_as(role="super_admin")
response = client.post(
"/soundmarks",
json={"name": "x", "tier": "business", "latitude": 0, "longitude": 0, "business_owner_id": 999999},
def test_non_admin_cannot_list_or_review_applications(client, auth_as):
headers, user = auth_as()
app = client.post(
"/soundmarks/business-applications",
json={"business_name": "x", "phone_number": "1", "latitude": 0, "longitude": 0},
headers=headers,
)
assert response.status_code == 404
).json()["application"]
assert client.get("/soundmarks/business-applications", headers=headers).status_code == 403
assert client.post(f"/soundmarks/business-applications/{app['id']}/approve", headers=headers).status_code == 403
assert client.post(f"/soundmarks/business-applications/{app['id']}/reject", headers=headers).status_code == 403
def test_super_admin_updates_and_deletes_soundmark(client, db_session, auth_as):
headers, _ = auth_as(role="super_admin")
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
assert response.json()["soundmark"]["name"] == "Renamed"
assert response.json()["soundmark"]["radius_meters"] == 50
def test_approving_an_application_creates_a_soundmark_and_promotes_the_submitter(client, db_session, auth_as):
super_headers, _ = auth_as(role="super_admin")
applicant_headers, applicant = auth_as()
assert applicant.role == "user"
response = client.delete(f"/soundmarks/{sm.id}", headers=headers)
app = client.post(
"/soundmarks/business-applications",
json={"business_name": "Joe's Cafe", "phone_number": "555-0100", "latitude": 1.0, "longitude": 2.0},
headers=applicant_headers,
).json()["application"]
response = client.post(f"/soundmarks/business-applications/{app['id']}/approve", headers=super_headers)
assert response.status_code == 200
assert db_session.query(Soundmark).filter(Soundmark.id == sm.id).first() is None
body = response.json()
assert body["application"]["status"] == "approved"
assert body["soundmark"]["name"] == "Joe's Cafe"
assert body["soundmark"]["business_owner_id"] == applicant.id
db_session.refresh(applicant)
assert applicant.role == "business_admin"
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")
created = db_session.query(Soundmark).filter(Soundmark.business_owner_id == applicant.id).first()
assert created is not None
assert created.latitude == 1.0
# 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_rejecting_an_application_creates_no_soundmark(client, db_session, auth_as):
super_headers, _ = auth_as(role="super_admin")
applicant_headers, applicant = auth_as()
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", tier="major")
_make_soundmark(db_session, name="Mark B", tier="major")
app = client.post(
"/soundmarks/business-applications",
json={"business_name": "x", "phone_number": "1", "latitude": 0, "longitude": 0},
headers=applicant_headers,
).json()["application"]
response = client.get("/soundmarks", headers=headers)
response = client.post(f"/soundmarks/business-applications/{app['id']}/reject", headers=super_headers)
assert response.status_code == 200
names = {sm["name"] for sm in response.json()["soundmarks"]}
assert {"Mark A", "Mark B"}.issubset(names)
assert response.json()["application"]["status"] == "rejected"
assert db_session.query(Soundmark).filter(Soundmark.business_owner_id == applicant.id).first() is None
# ---- Major tier: direct single-song assignment ----
def test_reviewing_an_already_reviewed_application_fails(client, auth_as):
super_headers, _ = auth_as(role="super_admin")
applicant_headers, _ = auth_as()
app = client.post(
"/soundmarks/business-applications",
json={"business_name": "x", "phone_number": "1", "latitude": 0, "longitude": 0},
headers=applicant_headers,
).json()["application"]
client.post(f"/soundmarks/business-applications/{app['id']}/approve", headers=super_headers)
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.post(f"/soundmarks/business-applications/{app['id']}/reject", headers=super_headers)
assert response.status_code == 400
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_approving_an_application_lets_the_submitter_resubmit_if_rejected_first(client, db_session, auth_as):
"""A rejected application shouldn't block a future one (only a pending one does)."""
super_headers, _ = auth_as(role="super_admin")
applicant_headers, _ = auth_as()
body = {"business_name": "x", "phone_number": "1", "latitude": 0, "longitude": 0}
def test_business_admin_cannot_set_song_on_a_major_location(client, db_session, auth_as):
headers, _ = auth_as(role="business_admin")
sm = _make_soundmark(db_session, tier="major")
song, _ = _make_library_song(db_session, 1)
first = client.post("/soundmarks/business-applications", json=body, headers=applicant_headers).json()["application"]
client.post(f"/soundmarks/business-applications/{first['id']}/reject", headers=super_headers)
response = client.post("/soundmarks/business-applications", json=body, headers=applicant_headers)
assert response.status_code == 201
response = client.patch(f"/soundmarks/{sm.id}/song", json={"song_id": song.id}, headers=headers)
assert response.status_code == 403
# ---- Super admin CRUD ----
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."""
def test_super_admin_updates_and_deletes_soundmark(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)
super_headers, _ = auth_as(role="super_admin")
sm = _make_soundmark(db_session, owner.id)
response = client.patch(f"/soundmarks/{sm.id}/song", json={"song_id": song.id}, headers=headers)
assert response.status_code == 400
response = client.patch(f"/soundmarks/{sm.id}", json={"name": "Renamed", "radius_meters": 50}, headers=super_headers)
assert response.status_code == 200
assert response.json()["soundmark"]["name"] == "Renamed"
assert response.json()["soundmark"]["radius_meters"] == 50
response = client.delete(f"/soundmarks/{sm.id}", headers=super_headers)
assert response.status_code == 200
assert db_session.query(Soundmark).filter(Soundmark.id == sm.id).first() is None
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
def test_super_admin_lists_all_soundmarks(client, db_session, auth_as):
headers, owner = auth_as(role="business_admin")
super_headers, _ = auth_as(role="super_admin")
_make_soundmark(db_session, owner.id, name="Mark A")
_make_soundmark(db_session, owner.id, name="Mark B")
response = client.get("/soundmarks", headers=super_headers)
assert response.status_code == 200
names = {sm["name"] for sm in response.json()["soundmarks"]}
assert {"Mark A", "Mark B"}.issubset(names)
# ---- Business tier: playlist management ----
# ---- Playlist management ----
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)
sm = _make_soundmark(db_session, owner.id)
song, _ = _make_library_song(db_session, owner.id)
response = client.post(f"/soundmarks/{sm.id}/playlist", json={"song_id": song.id}, headers=headers)
......@@ -255,7 +390,7 @@ def test_business_admin_adds_and_removes_playlist_tracks(client, db_session, aut
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)
sm = _make_soundmark(db_session, owner.id)
song_a, _ = _make_library_song(db_session, owner.id, title="A")
song_b, _ = _make_library_song(db_session, owner.id, title="B")
......@@ -271,25 +406,16 @@ def test_playlist_keeps_insertion_order_and_first_track_is_featured(client, db_s
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)
sm = _make_soundmark(db_session, 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_playlist_endpoints_reject_non_business_tier(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.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)
sm = _make_soundmark(db_session, owner.id)
song, _ = _make_library_song(db_session, owner.id)
client.post(f"/soundmarks/{sm.id}/playlist", json={"song_id": song.id}, headers=headers)
......@@ -301,8 +427,8 @@ def test_adding_the_same_song_to_a_playlist_twice_is_idempotent(client, db_sessi
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", tier="business", business_owner_id=owner.id)
_make_soundmark(db_session, name="Theirs", tier="business", business_owner_id=other.id)
mine = _make_soundmark(db_session, owner.id, name="Mine")
_make_soundmark(db_session, other.id, name="Theirs")
response = client.get("/soundmarks/mine", headers=headers)
assert response.status_code == 200
......@@ -342,13 +468,13 @@ def test_song_library_search_works_for_any_authenticated_user(client, db_session
assert response.status_code == 401
# ---- Suggestions & review queue (major/business tier only) ----
# ---- Suggestions & review queue ----
def test_any_user_can_suggest_a_song_for_a_major_location(client, db_session, auth_as):
def test_any_user_can_suggest_a_song_for_a_business(client, db_session, auth_as):
headers, user = auth_as()
super_headers, _ = auth_as(role="super_admin")
sm = _make_soundmark(db_session, tier="major")
owner_headers, owner = auth_as(role="business_admin")
sm = _make_soundmark(db_session, owner.id)
song, _ = _make_library_song(db_session, user.id)
response = client.post(f"/soundmarks/{sm.id}/suggestions", json={"song_id": song.id}, headers=headers)
......@@ -357,17 +483,8 @@ def test_any_user_can_suggest_a_song_for_a_major_location(client, db_session, au
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
mine = client.get("/soundmarks/mine", headers=owner_headers).json()["soundmarks"]
assert next(s for s in mine if s["id"] == sm.id)["song"] is None
def test_business_admin_sees_only_their_own_businesses_queue(client, db_session, auth_as):
......@@ -375,8 +492,8 @@ def test_business_admin_sees_only_their_own_businesses_queue(client, db_session,
_, 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)
mine = _make_soundmark(db_session, biz_owner.id, name="Mine")
theirs = _make_soundmark(db_session, other_owner.id, name="Theirs")
song, _ = _make_library_song(db_session, suggester.id)
client.post(f"/soundmarks/{mine.id}/suggestions", json={"song_id": song.id}, headers=suggester_headers)
......@@ -391,44 +508,27 @@ def test_business_admin_sees_only_their_own_businesses_queue(client, db_session,
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")
_, biz_owner_a = auth_as(role="business_admin")
_, biz_owner_b = 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)
a = _make_soundmark(db_session, biz_owner_a.id, name="A")
b = _make_soundmark(db_session, biz_owner_b.id, name="B")
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)
client.post(f"/soundmarks/{a.id}/suggestions", json={"song_id": song.id}, headers=suggester_headers)
client.post(f"/soundmarks/{b.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"
assert {a.id, b.id}.issubset(soundmark_ids)
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):
def test_approving_a_suggestion_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)
sm = _make_soundmark(db_session, biz_owner.id)
song, _ = _make_library_song(db_session, suggester.id)
suggestion = client.post(
......@@ -443,28 +543,28 @@ def test_approving_a_suggestion_for_a_business_adds_it_to_the_playlist(client, d
def test_rejecting_a_suggestion_does_not_apply_it(client, db_session, auth_as):
super_headers, _ = auth_as(role="super_admin")
biz_headers, biz_owner = auth_as(role="business_admin")
suggester_headers, suggester = auth_as()
sm = _make_soundmark(db_session, tier="major")
sm = _make_soundmark(db_session, 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']}/reject", headers=super_headers)
response = client.post(f"/soundmarks/suggestions/{suggestion['id']}/reject", headers=biz_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
mine = client.get("/soundmarks/mine", headers=biz_headers).json()["soundmarks"]
assert next(s for s in mine if s["id"] == sm.id)["playlist"] == []
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)
sm = _make_soundmark(db_session, other_owner.id)
song, _ = _make_library_song(db_session, suggester.id)
suggestion = client.post(
......@@ -476,76 +576,52 @@ def test_business_admin_cannot_review_someone_elses_suggestion(client, db_sessio
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")
biz_headers, biz_owner = auth_as(role="business_admin")
suggester_headers, suggester = auth_as()
sm = _make_soundmark(db_session, biz_owner.id)
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)
client.post(f"/soundmarks/suggestions/{suggestion['id']}/approve", headers=biz_headers)
response = client.post(f"/soundmarks/suggestions/{suggestion['id']}/reject", headers=super_headers)
response = client.post(f"/soundmarks/suggestions/{suggestion['id']}/reject", headers=biz_headers)
assert response.status_code == 400
# ---- Nearby detection ----
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", 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
marks = response.json()["soundmarks"]
assert any(m["name"] == "Close Mark" for m in marks)
assert marks[0]["distance_meters"] < 200
# ---- Streaming (cross-user, unlike /library/stream) ----
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", 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
names = {m["name"] for m in response.json()["soundmarks"]}
assert "Far Mark" not in names
def test_stream_soundmark_with_no_anthem_404s(client, db_session, auth_as):
headers, owner = auth_as(role="business_admin")
sm = _make_soundmark(db_session, owner.id)
response = client.get(f"/soundmarks/{sm.id}/stream", headers=headers)
assert response.status_code == 404
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/suggestion for a brand new soundmark."""
headers, _ = auth_as()
_make_soundmark(db_session, name="Empty Mark", tier="community", latitude=37.7749, longitude=-122.4194, radius_meters=200)
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, owner.id)
song, path = _make_library_song(db_session, owner.id)
response = client.get("/soundmarks/nearby", params={"lat": 37.7749, "lon": -122.4194}, headers=headers)
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
matches = {m["name"]: m for m in response.json()["soundmarks"]}
assert "Empty Mark" in matches
assert matches["Empty Mark"]["song"] is None
# ---- Streaming (cross-user, unlike /library/stream) ----
assert response.content == b"fake mp3 bytes for soundmark stream test"
finally:
os.remove(path)
def test_stream_soundmark_anthem_works_regardless_of_song_owner(client, db_session, auth_as):
listener_headers, _ = auth_as()
_, uploader = auth_as()
song, path = _make_library_song(db_session, uploader.id)
sm = _make_soundmark(db_session, tier="major", song_id=song.id)
headers, owner = auth_as(role="business_admin")
sm = _make_soundmark(db_session, 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=listener_headers)
assert response.status_code == 200
assert response.content == b"fake mp3 bytes for soundmark stream test"
......@@ -556,35 +632,15 @@ def test_stream_soundmark_anthem_works_regardless_of_song_owner(client, db_sessi
def test_stream_soundmark_anthem_accepts_token_query_param(client, db_session, auth_as):
# <audio src="..."> can't send a custom Authorization header.
listener_headers, _ = auth_as()
_, uploader = auth_as()
song, path = _make_library_song(db_session, uploader.id)
sm = _make_soundmark(db_session, tier="major", song_id=song.id)
try:
raw_token = listener_headers["Authorization"].split(" ", 1)[1]
response = client.get(f"/soundmarks/{sm.id}/stream?token={raw_token}")
assert response.status_code == 200
finally:
os.remove(path)
def test_stream_soundmark_with_no_anthem_404s(client, db_session, auth_as):
headers, _ = auth_as()
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)
sm = _make_soundmark(db_session, 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)
raw_token = listener_headers["Authorization"].split(" ", 1)[1]
response = client.get(f"/soundmarks/{sm.id}/stream?token={raw_token}")
assert response.status_code == 200
assert response.content == b"fake mp3 bytes for soundmark stream test"
finally:
os.remove(path)
......@@ -711,120 +767,6 @@ def test_admin_edit_user_404_for_unknown_id(client, auth_as):
assert response.status_code == 404
# ---- 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, 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)
assert response.status_code == 201
body = response.json()["proposal"]
assert body["vote_count"] == 1
assert body["has_voted"] is True
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, 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)
response = client.post(f"/soundmarks/{sm.id}/proposals", json={"song_id": song.id}, headers=headers_b)
assert response.status_code == 201
assert response.json()["proposal"]["vote_count"] == 2
proposals = client.get(f"/soundmarks/{sm.id}/proposals", headers=headers_a).json()["proposals"]
assert len(proposals) == 1
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, tier="community")
song_a, _ = _make_library_song(db_session, user.id, title="A")
song_b, _ = _make_library_song(db_session, user.id, title="B")
prop_a = client.post(f"/soundmarks/{sm.id}/proposals", json={"song_id": song_a.id}, headers=headers).json()["proposal"]
prop_b_res = client.post(f"/soundmarks/{sm.id}/proposals", json={"song_id": song_b.id}, headers=headers)
# Proposing B moved this user's one vote from A to B - A should now have 0 votes.
proposals = {p["id"]: p for p in client.get(f"/soundmarks/{sm.id}/proposals", headers=headers).json()["proposals"]}
assert proposals[prop_a["id"]]["vote_count"] == 0
assert proposals[prop_b_res.json()["proposal"]["id"]]["vote_count"] == 1
def test_removing_a_vote(client, db_session, auth_as):
headers, user = auth_as()
sm = _make_soundmark(db_session, tier="community")
song, _ = _make_library_song(db_session, user.id)
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
proposals = client.get(f"/soundmarks/{sm.id}/proposals", headers=headers).json()["proposals"]
assert proposals[0]["vote_count"] == 0
assert proposals[0]["has_voted"] is False
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")
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/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=listener_headers)
assert stream_response.status_code == 200
finally:
os.remove(path)
def test_proposal_requires_soundmark_and_song_to_exist(client, db_session, auth_as):
headers, user = auth_as()
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
assert client.post(f"/soundmarks/{sm.id}/proposals", json={"song_id": 999999}, headers=headers).status_code == 404
def test_voting_for_unknown_proposal_404s(client, db_session, auth_as):
headers, _ = auth_as()
sm = _make_soundmark(db_session, tier="community")
response = client.post(f"/soundmarks/{sm.id}/proposals/999999/vote", headers=headers)
assert response.status_code == 404
# ---- Geocode proxy ----
......
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