Phase 2 Complete by Claude Code

This commit is contained in:
2026-02-17 00:10:37 +02:00
parent 5e2d4b6b1b
commit 2b48426fe5
17 changed files with 1671 additions and 14 deletions

View File

@@ -3,7 +3,9 @@
"allow": [
"Bash(npm create:*)",
"Bash(npm install:*)",
"Bash(npm run build:*)"
"Bash(npm run build:*)",
"Bash(python -c:*)",
"Bash(npx vite build:*)"
]
}
}

View File

@@ -1,5 +1,6 @@
# Firebase
FIREBASE_SERVICE_ACCOUNT_PATH=./firebase-service-account.json
FIREBASE_STORAGE_BUCKET=your-project-id.appspot.com
# JWT
JWT_SECRET_KEY=your-secret-key-here

View File

@@ -6,6 +6,7 @@ import json
class Settings(BaseSettings):
# Firebase
firebase_service_account_path: str = "./firebase-service-account.json"
firebase_storage_bucket: str = ""
# JWT
jwt_secret_key: str = "change-me-in-production"

View File

@@ -3,6 +3,7 @@ from fastapi.middleware.cors import CORSMiddleware
from config import settings
from shared.firebase import init_firebase, firebase_initialized
from auth.router import router as auth_router
from melodies.router import router as melodies_router
app = FastAPI(
title="BellSystems Admin Panel",
@@ -20,6 +21,7 @@ app.add_middleware(
)
app.include_router(auth_router)
app.include_router(melodies_router)
@app.on_event("startup")

View File

@@ -1 +1,70 @@
# TODO: Melody Pydantic schemas
from pydantic import BaseModel
from typing import List, Optional
from enum import Enum
class MelodyType(str, Enum):
orthodox = "orthodox"
catholic = "catholic"
all = "all"
class MelodyTone(str, Enum):
normal = "normal"
festive = "festive"
cheerful = "cheerful"
lamentation = "lamentation"
class MelodyInfo(BaseModel):
name: str
description: str = ""
melodyTone: MelodyTone = MelodyTone.normal
customTags: List[str] = []
minSpeed: int = 0
maxSpeed: int = 0
totalNotes: int = 1
steps: int = 0
color: str = ""
isTrueRing: bool = False
previewURL: str = ""
notes: List[int] = []
class MelodyAttributes(BaseModel):
speed: int = 0
duration: int = 0
totalRunDuration: int = 0
pauseDuration: int = 0
infiniteLoop: bool = False
echoRing: List[int] = []
noteAssignments: List[int] = []
# --- Request / Response schemas ---
class MelodyCreate(BaseModel):
information: MelodyInfo
default_settings: MelodyAttributes
type: MelodyType = MelodyType.all
url: str = ""
uid: str = ""
pid: str = ""
class MelodyUpdate(BaseModel):
information: Optional[MelodyInfo] = None
default_settings: Optional[MelodyAttributes] = None
type: Optional[MelodyType] = None
url: Optional[str] = None
uid: Optional[str] = None
pid: Optional[str] = None
class MelodyInDB(MelodyCreate):
id: str
class MelodyListResponse(BaseModel):
melodies: List[MelodyInDB]
total: int

View File

@@ -1 +1,118 @@
# TODO: CRUD endpoints for melodies
from fastapi import APIRouter, Depends, UploadFile, File, Query, HTTPException
from typing import Optional
from auth.models import TokenPayload
from auth.dependencies import require_melody_access, require_viewer
from melodies.models import (
MelodyCreate, MelodyUpdate, MelodyInDB, MelodyListResponse, MelodyInfo,
)
from melodies import service
router = APIRouter(prefix="/api/melodies", tags=["melodies"])
@router.get("", response_model=MelodyListResponse)
async def list_melodies(
search: Optional[str] = Query(None),
type: Optional[str] = Query(None),
tone: Optional[str] = Query(None),
total_notes: Optional[int] = Query(None),
_user: TokenPayload = Depends(require_viewer),
):
melodies = service.list_melodies(
search=search,
melody_type=type,
tone=tone,
total_notes=total_notes,
)
return MelodyListResponse(melodies=melodies, total=len(melodies))
@router.get("/{melody_id}", response_model=MelodyInDB)
async def get_melody(
melody_id: str,
_user: TokenPayload = Depends(require_viewer),
):
return service.get_melody(melody_id)
@router.post("", response_model=MelodyInDB, status_code=201)
async def create_melody(
body: MelodyCreate,
_user: TokenPayload = Depends(require_melody_access),
):
return service.create_melody(body)
@router.put("/{melody_id}", response_model=MelodyInDB)
async def update_melody(
melody_id: str,
body: MelodyUpdate,
_user: TokenPayload = Depends(require_melody_access),
):
return service.update_melody(melody_id, body)
@router.delete("/{melody_id}", status_code=204)
async def delete_melody(
melody_id: str,
_user: TokenPayload = Depends(require_melody_access),
):
service.delete_melody(melody_id)
@router.post("/{melody_id}/upload/{file_type}")
async def upload_file(
melody_id: str,
file_type: str,
file: UploadFile = File(...),
_user: TokenPayload = Depends(require_melody_access),
):
"""Upload a binary or preview file. file_type must be 'binary' or 'preview'."""
if file_type not in ("binary", "preview"):
raise HTTPException(status_code=400, detail="file_type must be 'binary' or 'preview'")
# Verify melody exists
melody = service.get_melody(melody_id)
contents = await file.read()
content_type = file.content_type or "application/octet-stream"
if file_type == "binary":
content_type = "application/octet-stream"
url = service.upload_file(melody_id, contents, file.filename, content_type)
# Update the melody document with the new URL if it's a preview
if file_type == "preview":
service.update_melody(melody_id, MelodyUpdate(
information=MelodyInfo(
name=melody.information.name,
previewURL=url,
)
))
return {"url": url, "file_type": file_type}
@router.delete("/{melody_id}/files/{file_type}", status_code=204)
async def delete_file(
melody_id: str,
file_type: str,
_user: TokenPayload = Depends(require_melody_access),
):
"""Delete a binary or preview file. file_type must be 'binary' or 'preview'."""
if file_type not in ("binary", "preview"):
raise HTTPException(status_code=400, detail="file_type must be 'binary' or 'preview'")
service.get_melody(melody_id)
service.delete_file(melody_id, file_type)
@router.get("/{melody_id}/files")
async def get_files(
melody_id: str,
_user: TokenPayload = Depends(require_viewer),
):
"""Get storage file URLs for a melody."""
service.get_melody(melody_id)
return service.get_storage_files(melody_id)

View File

@@ -1 +1,174 @@
# TODO: Melody Firestore operations
from shared.firebase import get_db, get_bucket
from shared.exceptions import NotFoundError
from melodies.models import MelodyCreate, MelodyUpdate, MelodyInDB
COLLECTION = "melodies"
def _doc_to_melody(doc) -> MelodyInDB:
"""Convert a Firestore document snapshot to a MelodyInDB model."""
data = doc.to_dict()
return MelodyInDB(id=doc.id, **data)
def list_melodies(
search: str | None = None,
melody_type: str | None = None,
tone: str | None = None,
total_notes: int | None = None,
) -> list[MelodyInDB]:
"""List melodies with optional filters."""
db = get_db()
ref = db.collection(COLLECTION)
# Firestore doesn't support full-text search, so we fetch and filter in-memory
# for the name search. Type/tone/totalNotes can be queried server-side.
query = ref
if melody_type:
query = query.where("type", "==", melody_type)
docs = query.stream()
results = []
for doc in docs:
melody = _doc_to_melody(doc)
# Client-side filters
if tone and melody.information.melodyTone.value != tone:
continue
if total_notes is not None and melody.information.totalNotes != total_notes:
continue
if search:
search_lower = search.lower()
name_match = search_lower in melody.information.name.lower()
desc_match = search_lower in melody.information.description.lower()
tag_match = any(search_lower in t.lower() for t in melody.information.customTags)
if not (name_match or desc_match or tag_match):
continue
results.append(melody)
return results
def get_melody(melody_id: str) -> MelodyInDB:
"""Get a single melody by document ID."""
db = get_db()
doc = db.collection(COLLECTION).document(melody_id).get()
if not doc.exists:
raise NotFoundError("Melody")
return _doc_to_melody(doc)
def create_melody(data: MelodyCreate) -> MelodyInDB:
"""Create a new melody document in Firestore."""
db = get_db()
doc_data = data.model_dump()
_, doc_ref = db.collection(COLLECTION).add(doc_data)
return MelodyInDB(id=doc_ref.id, **doc_data)
def update_melody(melody_id: str, data: MelodyUpdate) -> MelodyInDB:
"""Update an existing melody document. Only provided fields are updated."""
db = get_db()
doc_ref = db.collection(COLLECTION).document(melody_id)
doc = doc_ref.get()
if not doc.exists:
raise NotFoundError("Melody")
update_data = data.model_dump(exclude_none=True)
# For nested structs, merge with existing data rather than replacing
existing = doc.to_dict()
for key in ("information", "default_settings"):
if key in update_data and key in existing:
merged = {**existing[key], **update_data[key]}
update_data[key] = merged
doc_ref.update(update_data)
updated_doc = doc_ref.get()
return _doc_to_melody(updated_doc)
def delete_melody(melody_id: str) -> None:
"""Delete a melody document and its associated storage files."""
db = get_db()
doc_ref = db.collection(COLLECTION).document(melody_id)
doc = doc_ref.get()
if not doc.exists:
raise NotFoundError("Melody")
# Delete associated storage files
_delete_storage_files(melody_id)
doc_ref.delete()
def upload_file(melody_id: str, file_bytes: bytes, filename: str, content_type: str) -> str:
"""Upload a file to Firebase Storage under melodies/{melody_id}/."""
bucket = get_bucket()
if not bucket:
raise RuntimeError("Firebase Storage not initialized")
# Determine subfolder based on content type
if content_type in ("application/octet-stream", "application/macbinary"):
storage_path = f"melodies/{melody_id}/binary.bin"
else:
# Audio preview files
ext = filename.rsplit(".", 1)[-1] if "." in filename else "mp3"
storage_path = f"melodies/{melody_id}/preview.{ext}"
blob = bucket.blob(storage_path)
blob.upload_from_string(file_bytes, content_type=content_type)
blob.make_public()
return blob.public_url
def delete_file(melody_id: str, file_type: str) -> None:
"""Delete a specific file from storage. file_type is 'binary' or 'preview'."""
bucket = get_bucket()
if not bucket:
return
prefix = f"melodies/{melody_id}/"
blobs = list(bucket.list_blobs(prefix=prefix))
for blob in blobs:
if file_type == "binary" and "binary" in blob.name:
blob.delete()
elif file_type == "preview" and "preview" in blob.name:
blob.delete()
def _delete_storage_files(melody_id: str) -> None:
"""Delete all storage files for a melody."""
bucket = get_bucket()
if not bucket:
return
prefix = f"melodies/{melody_id}/"
blobs = list(bucket.list_blobs(prefix=prefix))
for blob in blobs:
blob.delete()
def get_storage_files(melody_id: str) -> dict:
"""List storage files for a melody, returning URLs."""
bucket = get_bucket()
if not bucket:
return {"binary_url": None, "preview_url": None}
prefix = f"melodies/{melody_id}/"
blobs = list(bucket.list_blobs(prefix=prefix))
result = {"binary_url": None, "preview_url": None}
for blob in blobs:
blob.make_public()
if "binary" in blob.name:
result["binary_url"] = blob.public_url
elif "preview" in blob.name:
result["preview_url"] = blob.public_url
return result

View File

@@ -1,18 +1,22 @@
import firebase_admin
from firebase_admin import credentials, firestore
from firebase_admin import credentials, firestore, storage
from config import settings
db = None
bucket = None
firebase_initialized = False
def init_firebase():
"""Initialize Firebase Admin SDK. Call once at app startup."""
global db, firebase_initialized
global db, bucket, firebase_initialized
try:
cred = credentials.Certificate(settings.firebase_service_account_path)
firebase_admin.initialize_app(cred)
firebase_admin.initialize_app(cred, {
"storageBucket": settings.firebase_storage_bucket,
})
db = firestore.client()
bucket = storage.bucket()
firebase_initialized = True
except Exception as e:
print(f"[WARNING] Firebase init failed: {e}")
@@ -22,3 +26,8 @@ def init_firebase():
def get_db():
"""Return the Firestore client. None if Firebase is not initialized."""
return db
def get_bucket():
"""Return the Firebase Storage bucket. None if Firebase is not initialized."""
return bucket

View File

@@ -2,6 +2,9 @@ import { Routes, Route, Navigate } from "react-router-dom";
import { useAuth } from "./auth/AuthContext";
import LoginPage from "./auth/LoginPage";
import MainLayout from "./layout/MainLayout";
import MelodyList from "./melodies/MelodyList";
import MelodyDetail from "./melodies/MelodyDetail";
import MelodyForm from "./melodies/MelodyForm";
function ProtectedRoute({ children }) {
const { user, loading } = useAuth();
@@ -46,8 +49,11 @@ export default function App() {
}
>
<Route index element={<DashboardPage />} />
{/* Phase 2+ routes:
<Route path="melodies" element={<MelodyList />} />
<Route path="melodies/new" element={<MelodyForm />} />
<Route path="melodies/:id" element={<MelodyDetail />} />
<Route path="melodies/:id/edit" element={<MelodyForm />} />
{/* Phase 3+ routes:
<Route path="devices" element={<DeviceList />} />
<Route path="users" element={<UserList />} />
<Route path="mqtt" element={<MqttDashboard />} />

View File

@@ -57,6 +57,39 @@ class ApiClient {
delete(endpoint) {
return this.request(endpoint, { method: "DELETE" });
}
async upload(endpoint, file) {
const url = `${API_BASE}${endpoint}`;
const token = this.getToken();
const formData = new FormData();
formData.append("file", file);
const headers = {};
if (token) {
headers["Authorization"] = `Bearer ${token}`;
}
const response = await fetch(url, {
method: "POST",
headers,
body: formData,
});
if (response.status === 401) {
localStorage.removeItem("access_token");
localStorage.removeItem("user");
window.location.href = "/login";
throw new Error("Session expired");
}
if (!response.ok) {
const error = await response.json().catch(() => ({}));
throw new Error(error.detail || `Upload failed: ${response.status}`);
}
return response.json();
}
}
const api = new ApiClient();

View File

@@ -1 +1,31 @@
// TODO: Confirmation dialog component
export default function ConfirmDialog({ open, title, message, onConfirm, onCancel }) {
if (!open) return null;
return (
<div className="fixed inset-0 z-50 flex items-center justify-center">
<div className="fixed inset-0 bg-black/50" onClick={onCancel} />
<div className="relative bg-white rounded-lg shadow-xl p-6 w-full max-w-sm mx-4">
<h3 className="text-lg font-semibold text-gray-900 mb-2">
{title || "Confirm"}
</h3>
<p className="text-sm text-gray-600 mb-6">
{message || "Are you sure?"}
</p>
<div className="flex justify-end gap-3">
<button
onClick={onCancel}
className="px-4 py-2 text-sm text-gray-700 bg-gray-100 rounded-md hover:bg-gray-200 transition-colors"
>
Cancel
</button>
<button
onClick={onConfirm}
className="px-4 py-2 text-sm text-white bg-red-600 rounded-md hover:bg-red-700 transition-colors"
>
Delete
</button>
</div>
</div>
</div>
);
}

View File

@@ -1 +1,48 @@
// TODO: Reusable table component
export default function DataTable({ columns, data, onRowClick, emptyMessage = "No data found." }) {
if (!data || data.length === 0) {
return (
<div className="bg-white rounded-lg border border-gray-200 p-8 text-center text-gray-500 text-sm">
{emptyMessage}
</div>
);
}
return (
<div className="bg-white rounded-lg border border-gray-200 overflow-hidden">
<div className="overflow-x-auto">
<table className="w-full text-sm">
<thead>
<tr className="bg-gray-50 border-b border-gray-200">
{columns.map((col) => (
<th
key={col.key}
className="px-4 py-3 text-left font-medium text-gray-600"
style={col.width ? { width: col.width } : {}}
>
{col.label}
</th>
))}
</tr>
</thead>
<tbody>
{data.map((row, idx) => (
<tr
key={row.id || idx}
onClick={() => onRowClick?.(row)}
className={`border-b border-gray-100 last:border-0 ${
onRowClick ? "cursor-pointer hover:bg-gray-50" : ""
}`}
>
{columns.map((col) => (
<td key={col.key} className="px-4 py-3 text-gray-700">
{col.render ? col.render(row) : row[col.key]}
</td>
))}
</tr>
))}
</tbody>
</table>
</div>
</div>
);
}

View File

@@ -1 +1,44 @@
// TODO: Search bar component
import { useState } from "react";
export default function SearchBar({ onSearch, placeholder = "Search..." }) {
const [value, setValue] = useState("");
const handleSubmit = (e) => {
e.preventDefault();
onSearch(value);
};
const handleClear = () => {
setValue("");
onSearch("");
};
return (
<form onSubmit={handleSubmit} className="flex gap-2">
<div className="relative flex-1">
<input
type="text"
value={value}
onChange={(e) => setValue(e.target.value)}
placeholder={placeholder}
className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent text-sm"
/>
{value && (
<button
type="button"
onClick={handleClear}
className="absolute right-2 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600"
>
&times;
</button>
)}
</div>
<button
type="submit"
className="px-4 py-2 bg-blue-600 text-white text-sm rounded-md hover:bg-blue-700 transition-colors"
>
Search
</button>
</form>
);
}

View File

@@ -1 +1,278 @@
// TODO: Melody detail view
import { useState, useEffect } from "react";
import { useParams, useNavigate } from "react-router-dom";
import api from "../api/client";
import { useAuth } from "../auth/AuthContext";
import ConfirmDialog from "../components/ConfirmDialog";
function Field({ label, children }) {
return (
<div>
<dt className="text-xs font-medium text-gray-500 uppercase tracking-wide">
{label}
</dt>
<dd className="mt-1 text-sm text-gray-900">{children || "-"}</dd>
</div>
);
}
export default function MelodyDetail() {
const { id } = useParams();
const navigate = useNavigate();
const { hasRole } = useAuth();
const canEdit = hasRole("superadmin", "melody_editor");
const [melody, setMelody] = useState(null);
const [files, setFiles] = useState({});
const [loading, setLoading] = useState(true);
const [error, setError] = useState("");
const [showDelete, setShowDelete] = useState(false);
useEffect(() => {
loadData();
}, [id]);
const loadData = async () => {
setLoading(true);
try {
const [m, f] = await Promise.all([
api.get(`/melodies/${id}`),
api.get(`/melodies/${id}/files`),
]);
setMelody(m);
setFiles(f);
} catch (err) {
setError(err.message);
} finally {
setLoading(false);
}
};
const handleDelete = async () => {
try {
await api.delete(`/melodies/${id}`);
navigate("/melodies");
} catch (err) {
setError(err.message);
setShowDelete(false);
}
};
if (loading) {
return <div className="text-center py-8 text-gray-500">Loading...</div>;
}
if (error) {
return (
<div className="bg-red-50 border border-red-200 text-red-700 text-sm rounded-md p-3">
{error}
</div>
);
}
if (!melody) return null;
const info = melody.information || {};
const settings = melody.default_settings || {};
return (
<div className="max-w-3xl">
<div className="flex items-center justify-between mb-6">
<div>
<button
onClick={() => navigate("/melodies")}
className="text-sm text-blue-600 hover:text-blue-800 mb-2 inline-block"
>
&larr; Back to Melodies
</button>
<h1 className="text-2xl font-bold text-gray-900">
{info.name || "Untitled Melody"}
</h1>
</div>
{canEdit && (
<div className="flex gap-2">
<button
onClick={() => navigate(`/melodies/${id}/edit`)}
className="px-4 py-2 bg-blue-600 text-white text-sm rounded-md hover:bg-blue-700 transition-colors"
>
Edit
</button>
<button
onClick={() => setShowDelete(true)}
className="px-4 py-2 bg-red-600 text-white text-sm rounded-md hover:bg-red-700 transition-colors"
>
Delete
</button>
</div>
)}
</div>
{/* Melody Information */}
<section className="bg-white rounded-lg border border-gray-200 p-6 mb-6">
<h2 className="text-lg font-semibold text-gray-800 mb-4">
Melody Information
</h2>
<dl className="grid grid-cols-2 md:grid-cols-3 gap-4">
<Field label="Type">
<span className="capitalize">{melody.type}</span>
</Field>
<Field label="Tone">
<span className="capitalize">{info.melodyTone}</span>
</Field>
<Field label="Total Notes">{info.totalNotes}</Field>
<Field label="Steps">{info.steps}</Field>
<Field label="Min Speed">{info.minSpeed}</Field>
<Field label="Max Speed">{info.maxSpeed}</Field>
<Field label="Color">
{info.color ? (
<span className="inline-flex items-center gap-2">
<span
className="w-4 h-4 rounded border border-gray-300 inline-block"
style={{ backgroundColor: info.color.startsWith("0x") ? `#${info.color.slice(4)}` : info.color }}
/>
{info.color}
</span>
) : (
"-"
)}
</Field>
<Field label="True Ring">
<span
className={`px-2 py-0.5 text-xs rounded-full ${
info.isTrueRing
? "bg-green-100 text-green-700"
: "bg-gray-100 text-gray-500"
}`}
>
{info.isTrueRing ? "Yes" : "No"}
</span>
</Field>
<div className="col-span-2 md:col-span-3">
<Field label="Description">{info.description}</Field>
</div>
<div className="col-span-2 md:col-span-3">
<Field label="Notes">
{info.notes?.length > 0 ? info.notes.join(", ") : "-"}
</Field>
</div>
<div className="col-span-2 md:col-span-3">
<Field label="Custom Tags">
{info.customTags?.length > 0 ? (
<div className="flex flex-wrap gap-1 mt-1">
{info.customTags.map((tag) => (
<span
key={tag}
className="px-2 py-0.5 bg-blue-50 text-blue-700 text-xs rounded-full"
>
{tag}
</span>
))}
</div>
) : (
"-"
)}
</Field>
</div>
</dl>
</section>
{/* Default Settings */}
<section className="bg-white rounded-lg border border-gray-200 p-6 mb-6">
<h2 className="text-lg font-semibold text-gray-800 mb-4">
Default Settings
</h2>
<dl className="grid grid-cols-2 md:grid-cols-3 gap-4">
<Field label="Speed">{settings.speed}</Field>
<Field label="Duration">{settings.duration}</Field>
<Field label="Total Run Duration">{settings.totalRunDuration}</Field>
<Field label="Pause Duration">{settings.pauseDuration}</Field>
<Field label="Infinite Loop">
<span
className={`px-2 py-0.5 text-xs rounded-full ${
settings.infiniteLoop
? "bg-green-100 text-green-700"
: "bg-gray-100 text-gray-500"
}`}
>
{settings.infiniteLoop ? "Yes" : "No"}
</span>
</Field>
<div className="col-span-2 md:col-span-3">
<Field label="Echo Ring">
{settings.echoRing?.length > 0
? settings.echoRing.join(", ")
: "-"}
</Field>
</div>
<div className="col-span-2 md:col-span-3">
<Field label="Note Assignments">
{settings.noteAssignments?.length > 0
? settings.noteAssignments.join(", ")
: "-"}
</Field>
</div>
</dl>
</section>
{/* Identifiers */}
<section className="bg-white rounded-lg border border-gray-200 p-6 mb-6">
<h2 className="text-lg font-semibold text-gray-800 mb-4">
Identifiers
</h2>
<dl className="grid grid-cols-2 md:grid-cols-3 gap-4">
<Field label="Document ID">{melody.id}</Field>
<Field label="UID">{melody.uid}</Field>
<Field label="PID">{melody.pid}</Field>
<div className="col-span-2 md:col-span-3">
<Field label="URL">{melody.url}</Field>
</div>
</dl>
</section>
{/* Files */}
<section className="bg-white rounded-lg border border-gray-200 p-6 mb-6">
<h2 className="text-lg font-semibold text-gray-800 mb-4">Files</h2>
<dl className="space-y-4">
<Field label="Binary File">
{files.binary_url ? (
<a
href={files.binary_url}
target="_blank"
rel="noopener noreferrer"
className="text-blue-600 hover:text-blue-800 underline"
>
Download binary
</a>
) : (
<span className="text-gray-400">Not uploaded</span>
)}
</Field>
<Field label="Audio Preview">
{files.preview_url ? (
<div className="space-y-1">
<audio controls src={files.preview_url} className="h-8" />
<a
href={files.preview_url}
target="_blank"
rel="noopener noreferrer"
className="text-blue-600 hover:text-blue-800 underline text-xs"
>
Download preview
</a>
</div>
) : (
<span className="text-gray-400">Not uploaded</span>
)}
</Field>
</dl>
</section>
<ConfirmDialog
open={showDelete}
title="Delete Melody"
message={`Are you sure you want to delete "${info.name}"? This will also delete any uploaded files. This action cannot be undone.`}
onConfirm={handleDelete}
onCancel={() => setShowDelete(false)}
/>
</div>
);
}

View File

@@ -1 +1,631 @@
// TODO: Add / Edit melody form
import { useState, useEffect } from "react";
import { useNavigate, useParams } from "react-router-dom";
import api from "../api/client";
const MELODY_TYPES = ["orthodox", "catholic", "all"];
const MELODY_TONES = ["normal", "festive", "cheerful", "lamentation"];
const defaultInfo = {
name: "",
description: "",
melodyTone: "normal",
customTags: [],
minSpeed: 0,
maxSpeed: 0,
totalNotes: 1,
steps: 0,
color: "",
isTrueRing: false,
previewURL: "",
notes: [],
};
const defaultSettings = {
speed: 0,
duration: 0,
totalRunDuration: 0,
pauseDuration: 0,
infiniteLoop: false,
echoRing: [],
noteAssignments: [],
};
export default function MelodyForm() {
const { id } = useParams();
const isEdit = Boolean(id);
const navigate = useNavigate();
const [information, setInformation] = useState({ ...defaultInfo });
const [settings, setSettings] = useState({ ...defaultSettings });
const [type, setType] = useState("all");
const [url, setUrl] = useState("");
const [uid, setUid] = useState("");
const [pid, setPid] = useState("");
const [binaryFile, setBinaryFile] = useState(null);
const [previewFile, setPreviewFile] = useState(null);
const [existingFiles, setExistingFiles] = useState({});
const [uploading, setUploading] = useState(false);
const [loading, setLoading] = useState(false);
const [saving, setSaving] = useState(false);
const [error, setError] = useState("");
// Tag input state
const [tagInput, setTagInput] = useState("");
useEffect(() => {
if (isEdit) {
loadMelody();
}
}, [id]);
const loadMelody = async () => {
setLoading(true);
try {
const [melody, files] = await Promise.all([
api.get(`/melodies/${id}`),
api.get(`/melodies/${id}/files`),
]);
setInformation({ ...defaultInfo, ...melody.information });
setSettings({ ...defaultSettings, ...melody.default_settings });
setType(melody.type || "all");
setUrl(melody.url || "");
setUid(melody.uid || "");
setPid(melody.pid || "");
setExistingFiles(files);
} catch (err) {
setError(err.message);
} finally {
setLoading(false);
}
};
const updateInfo = (field, value) => {
setInformation((prev) => ({ ...prev, [field]: value }));
};
const updateSettings = (field, value) => {
setSettings((prev) => ({ ...prev, [field]: value }));
};
const addTag = () => {
const tag = tagInput.trim();
if (tag && !information.customTags.includes(tag)) {
updateInfo("customTags", [...information.customTags, tag]);
}
setTagInput("");
};
const removeTag = (tag) => {
updateInfo(
"customTags",
information.customTags.filter((t) => t !== tag)
);
};
// Parse comma-separated integers for list fields
const parseIntList = (str) => {
if (!str.trim()) return [];
return str
.split(",")
.map((s) => parseInt(s.trim(), 10))
.filter((n) => !isNaN(n));
};
const handleSubmit = async (e) => {
e.preventDefault();
setSaving(true);
setError("");
try {
const body = {
information,
default_settings: settings,
type,
url,
uid,
pid,
};
let melodyId = id;
if (isEdit) {
await api.put(`/melodies/${id}`, body);
} else {
const created = await api.post("/melodies", body);
melodyId = created.id;
}
// Upload files if selected
if (binaryFile || previewFile) {
setUploading(true);
if (binaryFile) {
await api.upload(`/melodies/${melodyId}/upload/binary`, binaryFile);
}
if (previewFile) {
await api.upload(`/melodies/${melodyId}/upload/preview`, previewFile);
}
setUploading(false);
}
navigate(`/melodies/${melodyId}`);
} catch (err) {
setError(err.message);
setUploading(false);
} finally {
setSaving(false);
}
};
if (loading) {
return <div className="text-center py-8 text-gray-500">Loading...</div>;
}
return (
<div className="max-w-3xl">
<h1 className="text-2xl font-bold text-gray-900 mb-6">
{isEdit ? "Edit Melody" : "Add Melody"}
</h1>
{error && (
<div className="bg-red-50 border border-red-200 text-red-700 text-sm rounded-md p-3 mb-4">
{error}
</div>
)}
<form onSubmit={handleSubmit} className="space-y-8">
{/* --- Melody Info Section --- */}
<section className="bg-white rounded-lg border border-gray-200 p-6">
<h2 className="text-lg font-semibold text-gray-800 mb-4">
Melody Information
</h2>
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<div className="md:col-span-2">
<label className="block text-sm font-medium text-gray-700 mb-1">
Name *
</label>
<input
type="text"
required
value={information.name}
onChange={(e) => updateInfo("name", e.target.value)}
className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent text-sm"
/>
</div>
<div className="md:col-span-2">
<label className="block text-sm font-medium text-gray-700 mb-1">
Description
</label>
<textarea
value={information.description}
onChange={(e) => updateInfo("description", e.target.value)}
rows={3}
className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent text-sm"
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">
Melody Tone
</label>
<select
value={information.melodyTone}
onChange={(e) => updateInfo("melodyTone", e.target.value)}
className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 text-sm"
>
{MELODY_TONES.map((t) => (
<option key={t} value={t}>
{t.charAt(0).toUpperCase() + t.slice(1)}
</option>
))}
</select>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">
Type
</label>
<select
value={type}
onChange={(e) => setType(e.target.value)}
className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 text-sm"
>
{MELODY_TYPES.map((t) => (
<option key={t} value={t}>
{t.charAt(0).toUpperCase() + t.slice(1)}
</option>
))}
</select>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">
Total Notes
</label>
<input
type="number"
min="1"
value={information.totalNotes}
onChange={(e) =>
updateInfo("totalNotes", parseInt(e.target.value, 10) || 1)
}
className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 text-sm"
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">
Steps
</label>
<input
type="number"
min="0"
value={information.steps}
onChange={(e) =>
updateInfo("steps", parseInt(e.target.value, 10) || 0)
}
className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 text-sm"
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">
Min Speed
</label>
<input
type="number"
min="0"
value={information.minSpeed}
onChange={(e) =>
updateInfo("minSpeed", parseInt(e.target.value, 10) || 0)
}
className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 text-sm"
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">
Max Speed
</label>
<input
type="number"
min="0"
value={information.maxSpeed}
onChange={(e) =>
updateInfo("maxSpeed", parseInt(e.target.value, 10) || 0)
}
className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 text-sm"
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">
Color
</label>
<input
type="text"
value={information.color}
onChange={(e) => updateInfo("color", e.target.value)}
placeholder="e.g. #FF5733 or 0xFF5733"
className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 text-sm"
/>
</div>
<div className="flex items-center gap-2 pt-6">
<input
type="checkbox"
id="isTrueRing"
checked={information.isTrueRing}
onChange={(e) => updateInfo("isTrueRing", e.target.checked)}
className="h-4 w-4 text-blue-600 rounded border-gray-300"
/>
<label
htmlFor="isTrueRing"
className="text-sm font-medium text-gray-700"
>
True Ring
</label>
</div>
<div className="md:col-span-2">
<label className="block text-sm font-medium text-gray-700 mb-1">
Notes (comma-separated integers)
</label>
<input
type="text"
value={information.notes.join(", ")}
onChange={(e) => updateInfo("notes", parseIntList(e.target.value))}
placeholder="e.g. 1, 2, 3, 4"
className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 text-sm"
/>
</div>
<div className="md:col-span-2">
<label className="block text-sm font-medium text-gray-700 mb-1">
Custom Tags
</label>
<div className="flex gap-2 mb-2">
<input
type="text"
value={tagInput}
onChange={(e) => setTagInput(e.target.value)}
onKeyDown={(e) => {
if (e.key === "Enter") {
e.preventDefault();
addTag();
}
}}
placeholder="Add a tag and press Enter"
className="flex-1 px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 text-sm"
/>
<button
type="button"
onClick={addTag}
className="px-3 py-2 bg-gray-100 text-gray-700 text-sm rounded-md hover:bg-gray-200 transition-colors"
>
Add
</button>
</div>
{information.customTags.length > 0 && (
<div className="flex flex-wrap gap-2">
{information.customTags.map((tag) => (
<span
key={tag}
className="inline-flex items-center gap-1 px-2 py-1 bg-blue-50 text-blue-700 text-xs rounded-full"
>
{tag}
<button
type="button"
onClick={() => removeTag(tag)}
className="text-blue-400 hover:text-blue-600"
>
&times;
</button>
</span>
))}
</div>
)}
</div>
</div>
</section>
{/* --- Default Settings Section --- */}
<section className="bg-white rounded-lg border border-gray-200 p-6">
<h2 className="text-lg font-semibold text-gray-800 mb-4">
Default Settings
</h2>
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">
Speed
</label>
<input
type="number"
min="0"
value={settings.speed}
onChange={(e) =>
updateSettings("speed", parseInt(e.target.value, 10) || 0)
}
className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 text-sm"
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">
Duration
</label>
<input
type="number"
min="0"
value={settings.duration}
onChange={(e) =>
updateSettings("duration", parseInt(e.target.value, 10) || 0)
}
className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 text-sm"
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">
Total Run Duration
</label>
<input
type="number"
min="0"
value={settings.totalRunDuration}
onChange={(e) =>
updateSettings(
"totalRunDuration",
parseInt(e.target.value, 10) || 0
)
}
className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 text-sm"
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">
Pause Duration
</label>
<input
type="number"
min="0"
value={settings.pauseDuration}
onChange={(e) =>
updateSettings(
"pauseDuration",
parseInt(e.target.value, 10) || 0
)
}
className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 text-sm"
/>
</div>
<div className="flex items-center gap-2 pt-6">
<input
type="checkbox"
id="infiniteLoop"
checked={settings.infiniteLoop}
onChange={(e) =>
updateSettings("infiniteLoop", e.target.checked)
}
className="h-4 w-4 text-blue-600 rounded border-gray-300"
/>
<label
htmlFor="infiniteLoop"
className="text-sm font-medium text-gray-700"
>
Infinite Loop
</label>
</div>
<div className="md:col-span-2">
<label className="block text-sm font-medium text-gray-700 mb-1">
Echo Ring (comma-separated integers)
</label>
<input
type="text"
value={settings.echoRing.join(", ")}
onChange={(e) =>
updateSettings("echoRing", parseIntList(e.target.value))
}
placeholder="e.g. 0, 1, 0, 1"
className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 text-sm"
/>
</div>
<div className="md:col-span-2">
<label className="block text-sm font-medium text-gray-700 mb-1">
Note Assignments (comma-separated integers)
</label>
<input
type="text"
value={settings.noteAssignments.join(", ")}
onChange={(e) =>
updateSettings(
"noteAssignments",
parseIntList(e.target.value)
)
}
placeholder="e.g. 1, 2, 3"
className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 text-sm"
/>
</div>
</div>
</section>
{/* --- Identifiers Section --- */}
<section className="bg-white rounded-lg border border-gray-200 p-6">
<h2 className="text-lg font-semibold text-gray-800 mb-4">
Identifiers
</h2>
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">
UID
</label>
<input
type="text"
value={uid}
onChange={(e) => setUid(e.target.value)}
className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 text-sm"
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">
PID
</label>
<input
type="text"
value={pid}
onChange={(e) => setPid(e.target.value)}
className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 text-sm"
/>
</div>
<div className="md:col-span-2">
<label className="block text-sm font-medium text-gray-700 mb-1">
URL
</label>
<input
type="text"
value={url}
onChange={(e) => setUrl(e.target.value)}
className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 text-sm"
/>
</div>
</div>
</section>
{/* --- File Upload Section --- */}
<section className="bg-white rounded-lg border border-gray-200 p-6">
<h2 className="text-lg font-semibold text-gray-800 mb-4">
Files
</h2>
<div className="space-y-4">
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">
Binary File (.bin)
</label>
{existingFiles.binary_url && (
<p className="text-xs text-green-600 mb-1">
Current file uploaded. Selecting a new file will replace it.
</p>
)}
<input
type="file"
accept=".bin"
onChange={(e) => setBinaryFile(e.target.files[0] || null)}
className="w-full text-sm text-gray-500 file:mr-4 file:py-2 file:px-4 file:rounded-md file:border-0 file:text-sm file:bg-blue-50 file:text-blue-700 hover:file:bg-blue-100"
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">
Audio Preview (.mp3)
</label>
{existingFiles.preview_url && (
<div className="mb-1">
<p className="text-xs text-green-600 mb-1">
Current preview uploaded. Selecting a new file will replace it.
</p>
<audio controls src={existingFiles.preview_url} className="h-8" />
</div>
)}
<input
type="file"
accept=".mp3,.wav,.ogg"
onChange={(e) => setPreviewFile(e.target.files[0] || null)}
className="w-full text-sm text-gray-500 file:mr-4 file:py-2 file:px-4 file:rounded-md file:border-0 file:text-sm file:bg-blue-50 file:text-blue-700 hover:file:bg-blue-100"
/>
</div>
</div>
</section>
{/* --- Actions --- */}
<div className="flex gap-3">
<button
type="submit"
disabled={saving || uploading}
className="px-6 py-2 bg-blue-600 text-white text-sm rounded-md hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
>
{uploading
? "Uploading files..."
: saving
? "Saving..."
: isEdit
? "Update Melody"
: "Create Melody"}
</button>
<button
type="button"
onClick={() => navigate(isEdit ? `/melodies/${id}` : "/melodies")}
className="px-6 py-2 bg-gray-100 text-gray-700 text-sm rounded-md hover:bg-gray-200 transition-colors"
>
Cancel
</button>
</div>
</form>
</div>
);
}

View File

@@ -1 +1,212 @@
// TODO: Melody list component
import { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import api from "../api/client";
import { useAuth } from "../auth/AuthContext";
import SearchBar from "../components/SearchBar";
import DataTable from "../components/DataTable";
import ConfirmDialog from "../components/ConfirmDialog";
const MELODY_TYPES = ["", "orthodox", "catholic", "all"];
const MELODY_TONES = ["", "normal", "festive", "cheerful", "lamentation"];
export default function MelodyList() {
const [melodies, setMelodies] = useState([]);
const [total, setTotal] = useState(0);
const [loading, setLoading] = useState(true);
const [error, setError] = useState("");
const [search, setSearch] = useState("");
const [typeFilter, setTypeFilter] = useState("");
const [toneFilter, setToneFilter] = useState("");
const [deleteTarget, setDeleteTarget] = useState(null);
const navigate = useNavigate();
const { hasRole } = useAuth();
const canEdit = hasRole("superadmin", "melody_editor");
const fetchMelodies = async () => {
setLoading(true);
setError("");
try {
const params = new URLSearchParams();
if (search) params.set("search", search);
if (typeFilter) params.set("type", typeFilter);
if (toneFilter) params.set("tone", toneFilter);
const qs = params.toString();
const data = await api.get(`/melodies${qs ? `?${qs}` : ""}`);
setMelodies(data.melodies);
setTotal(data.total);
} catch (err) {
setError(err.message);
} finally {
setLoading(false);
}
};
useEffect(() => {
fetchMelodies();
}, [search, typeFilter, toneFilter]);
const handleDelete = async () => {
if (!deleteTarget) return;
try {
await api.delete(`/melodies/${deleteTarget.id}`);
setDeleteTarget(null);
fetchMelodies();
} catch (err) {
setError(err.message);
setDeleteTarget(null);
}
};
const columns = [
{
key: "name",
label: "Name",
render: (row) => (
<span className="font-medium text-gray-900">
{row.information?.name || "Untitled"}
</span>
),
},
{
key: "type",
label: "Type",
render: (row) => (
<span className="capitalize">{row.type}</span>
),
},
{
key: "tone",
label: "Tone",
render: (row) => (
<span className="capitalize">{row.information?.melodyTone || "-"}</span>
),
},
{
key: "totalNotes",
label: "Notes",
render: (row) => row.information?.totalNotes ?? "-",
},
{
key: "steps",
label: "Steps",
render: (row) => row.information?.steps ?? "-",
},
{
key: "isTrueRing",
label: "True Ring",
render: (row) => (
<span
className={`px-2 py-0.5 text-xs rounded-full ${
row.information?.isTrueRing
? "bg-green-100 text-green-700"
: "bg-gray-100 text-gray-500"
}`}
>
{row.information?.isTrueRing ? "Yes" : "No"}
</span>
),
},
...(canEdit
? [
{
key: "actions",
label: "",
width: "100px",
render: (row) => (
<div className="flex gap-2" onClick={(e) => e.stopPropagation()}>
<button
onClick={() => navigate(`/melodies/${row.id}/edit`)}
className="text-blue-600 hover:text-blue-800 text-xs"
>
Edit
</button>
<button
onClick={() => setDeleteTarget(row)}
className="text-red-600 hover:text-red-800 text-xs"
>
Delete
</button>
</div>
),
},
]
: []),
];
return (
<div>
<div className="flex items-center justify-between mb-6">
<h1 className="text-2xl font-bold text-gray-900">Melodies</h1>
{canEdit && (
<button
onClick={() => navigate("/melodies/new")}
className="px-4 py-2 bg-blue-600 text-white text-sm rounded-md hover:bg-blue-700 transition-colors"
>
Add Melody
</button>
)}
</div>
<div className="mb-4 space-y-3">
<SearchBar
onSearch={setSearch}
placeholder="Search by name, description, or tags..."
/>
<div className="flex gap-3">
<select
value={typeFilter}
onChange={(e) => setTypeFilter(e.target.value)}
className="px-3 py-2 border border-gray-300 rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
>
<option value="">All Types</option>
{MELODY_TYPES.filter(Boolean).map((t) => (
<option key={t} value={t}>
{t.charAt(0).toUpperCase() + t.slice(1)}
</option>
))}
</select>
<select
value={toneFilter}
onChange={(e) => setToneFilter(e.target.value)}
className="px-3 py-2 border border-gray-300 rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
>
<option value="">All Tones</option>
{MELODY_TONES.filter(Boolean).map((t) => (
<option key={t} value={t}>
{t.charAt(0).toUpperCase() + t.slice(1)}
</option>
))}
</select>
<span className="flex items-center text-sm text-gray-500">
{total} {total === 1 ? "melody" : "melodies"}
</span>
</div>
</div>
{error && (
<div className="bg-red-50 border border-red-200 text-red-700 text-sm rounded-md p-3 mb-4">
{error}
</div>
)}
{loading ? (
<div className="text-center py-8 text-gray-500">Loading...</div>
) : (
<DataTable
columns={columns}
data={melodies}
onRowClick={(row) => navigate(`/melodies/${row.id}`)}
emptyMessage="No melodies found."
/>
)}
<ConfirmDialog
open={!!deleteTarget}
title="Delete Melody"
message={`Are you sure you want to delete "${deleteTarget?.information?.name}"? This will also delete any uploaded files.`}
onConfirm={handleDelete}
onCancel={() => setDeleteTarget(null)}
/>
</div>
);
}

View File

@@ -7,5 +7,11 @@ export default defineConfig({
server: {
host: '0.0.0.0',
port: 5173,
proxy: {
'/api': {
target: 'http://localhost:8000',
changeOrigin: true,
},
},
},
})