Added Draft Melodies. Further improvements to the UI
This commit is contained in:
@@ -6,7 +6,8 @@
|
|||||||
"Bash(npm run build:*)",
|
"Bash(npm run build:*)",
|
||||||
"Bash(python -c:*)",
|
"Bash(python -c:*)",
|
||||||
"Bash(npx vite build:*)",
|
"Bash(npx vite build:*)",
|
||||||
"Bash(wc:*)"
|
"Bash(wc:*)",
|
||||||
|
"Bash(ls:*)"
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ from equipment.router import router as equipment_router
|
|||||||
from staff.router import router as staff_router
|
from staff.router import router as staff_router
|
||||||
from mqtt.client import mqtt_manager
|
from mqtt.client import mqtt_manager
|
||||||
from mqtt import database as mqtt_db
|
from mqtt import database as mqtt_db
|
||||||
|
from melodies import service as melody_service
|
||||||
|
|
||||||
app = FastAPI(
|
app = FastAPI(
|
||||||
title="BellSystems Admin Panel",
|
title="BellSystems Admin Panel",
|
||||||
@@ -43,6 +44,7 @@ app.include_router(staff_router)
|
|||||||
async def startup():
|
async def startup():
|
||||||
init_firebase()
|
init_firebase()
|
||||||
await mqtt_db.init_db()
|
await mqtt_db.init_db()
|
||||||
|
await melody_service.migrate_from_firestore()
|
||||||
mqtt_manager.start(asyncio.get_event_loop())
|
mqtt_manager.start(asyncio.get_event_loop())
|
||||||
asyncio.create_task(mqtt_db.purge_loop())
|
asyncio.create_task(mqtt_db.purge_loop())
|
||||||
|
|
||||||
|
|||||||
75
backend/melodies/database.py
Normal file
75
backend/melodies/database.py
Normal file
@@ -0,0 +1,75 @@
|
|||||||
|
import json
|
||||||
|
import logging
|
||||||
|
from mqtt.database import get_db
|
||||||
|
|
||||||
|
logger = logging.getLogger("melodies.database")
|
||||||
|
|
||||||
|
|
||||||
|
async def insert_melody(melody_id: str, status: str, data: dict) -> None:
|
||||||
|
db = await get_db()
|
||||||
|
await db.execute(
|
||||||
|
"INSERT INTO melody_drafts (id, status, data) VALUES (?, ?, ?)",
|
||||||
|
(melody_id, status, json.dumps(data)),
|
||||||
|
)
|
||||||
|
await db.commit()
|
||||||
|
|
||||||
|
|
||||||
|
async def update_melody(melody_id: str, data: dict) -> None:
|
||||||
|
db = await get_db()
|
||||||
|
await db.execute(
|
||||||
|
"UPDATE melody_drafts SET data = ?, updated_at = datetime('now') WHERE id = ?",
|
||||||
|
(json.dumps(data), melody_id),
|
||||||
|
)
|
||||||
|
await db.commit()
|
||||||
|
|
||||||
|
|
||||||
|
async def update_status(melody_id: str, status: str) -> None:
|
||||||
|
db = await get_db()
|
||||||
|
await db.execute(
|
||||||
|
"UPDATE melody_drafts SET status = ?, updated_at = datetime('now') WHERE id = ?",
|
||||||
|
(status, melody_id),
|
||||||
|
)
|
||||||
|
await db.commit()
|
||||||
|
|
||||||
|
|
||||||
|
async def get_melody(melody_id: str) -> dict | None:
|
||||||
|
db = await get_db()
|
||||||
|
rows = await db.execute_fetchall(
|
||||||
|
"SELECT * FROM melody_drafts WHERE id = ?", (melody_id,)
|
||||||
|
)
|
||||||
|
if not rows:
|
||||||
|
return None
|
||||||
|
row = dict(rows[0])
|
||||||
|
row["data"] = json.loads(row["data"])
|
||||||
|
return row
|
||||||
|
|
||||||
|
|
||||||
|
async def list_melodies(status: str | None = None) -> list[dict]:
|
||||||
|
db = await get_db()
|
||||||
|
if status and status != "all":
|
||||||
|
rows = await db.execute_fetchall(
|
||||||
|
"SELECT * FROM melody_drafts WHERE status = ? ORDER BY updated_at DESC",
|
||||||
|
(status,),
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
rows = await db.execute_fetchall(
|
||||||
|
"SELECT * FROM melody_drafts ORDER BY updated_at DESC"
|
||||||
|
)
|
||||||
|
results = []
|
||||||
|
for row in rows:
|
||||||
|
r = dict(row)
|
||||||
|
r["data"] = json.loads(r["data"])
|
||||||
|
results.append(r)
|
||||||
|
return results
|
||||||
|
|
||||||
|
|
||||||
|
async def delete_melody(melody_id: str) -> None:
|
||||||
|
db = await get_db()
|
||||||
|
await db.execute("DELETE FROM melody_drafts WHERE id = ?", (melody_id,))
|
||||||
|
await db.commit()
|
||||||
|
|
||||||
|
|
||||||
|
async def count_melodies() -> int:
|
||||||
|
db = await get_db()
|
||||||
|
rows = await db.execute_fetchall("SELECT COUNT(*) FROM melody_drafts")
|
||||||
|
return rows[0][0]
|
||||||
@@ -62,6 +62,7 @@ class MelodyUpdate(BaseModel):
|
|||||||
|
|
||||||
class MelodyInDB(MelodyCreate):
|
class MelodyInDB(MelodyCreate):
|
||||||
id: str
|
id: str
|
||||||
|
status: str = "published"
|
||||||
|
|
||||||
|
|
||||||
class MelodyListResponse(BaseModel):
|
class MelodyListResponse(BaseModel):
|
||||||
|
|||||||
@@ -16,13 +16,15 @@ async def list_melodies(
|
|||||||
type: Optional[str] = Query(None),
|
type: Optional[str] = Query(None),
|
||||||
tone: Optional[str] = Query(None),
|
tone: Optional[str] = Query(None),
|
||||||
total_notes: Optional[int] = Query(None),
|
total_notes: Optional[int] = Query(None),
|
||||||
|
status: Optional[str] = Query(None),
|
||||||
_user: TokenPayload = Depends(require_permission("melodies", "view")),
|
_user: TokenPayload = Depends(require_permission("melodies", "view")),
|
||||||
):
|
):
|
||||||
melodies = service.list_melodies(
|
melodies = await service.list_melodies(
|
||||||
search=search,
|
search=search,
|
||||||
melody_type=type,
|
melody_type=type,
|
||||||
tone=tone,
|
tone=tone,
|
||||||
total_notes=total_notes,
|
total_notes=total_notes,
|
||||||
|
status=status,
|
||||||
)
|
)
|
||||||
return MelodyListResponse(melodies=melodies, total=len(melodies))
|
return MelodyListResponse(melodies=melodies, total=len(melodies))
|
||||||
|
|
||||||
@@ -32,15 +34,16 @@ async def get_melody(
|
|||||||
melody_id: str,
|
melody_id: str,
|
||||||
_user: TokenPayload = Depends(require_permission("melodies", "view")),
|
_user: TokenPayload = Depends(require_permission("melodies", "view")),
|
||||||
):
|
):
|
||||||
return service.get_melody(melody_id)
|
return await service.get_melody(melody_id)
|
||||||
|
|
||||||
|
|
||||||
@router.post("", response_model=MelodyInDB, status_code=201)
|
@router.post("", response_model=MelodyInDB, status_code=201)
|
||||||
async def create_melody(
|
async def create_melody(
|
||||||
body: MelodyCreate,
|
body: MelodyCreate,
|
||||||
|
publish: bool = Query(False),
|
||||||
_user: TokenPayload = Depends(require_permission("melodies", "add")),
|
_user: TokenPayload = Depends(require_permission("melodies", "add")),
|
||||||
):
|
):
|
||||||
return service.create_melody(body)
|
return await service.create_melody(body, publish=publish)
|
||||||
|
|
||||||
|
|
||||||
@router.put("/{melody_id}", response_model=MelodyInDB)
|
@router.put("/{melody_id}", response_model=MelodyInDB)
|
||||||
@@ -49,7 +52,7 @@ async def update_melody(
|
|||||||
body: MelodyUpdate,
|
body: MelodyUpdate,
|
||||||
_user: TokenPayload = Depends(require_permission("melodies", "edit")),
|
_user: TokenPayload = Depends(require_permission("melodies", "edit")),
|
||||||
):
|
):
|
||||||
return service.update_melody(melody_id, body)
|
return await service.update_melody(melody_id, body)
|
||||||
|
|
||||||
|
|
||||||
@router.delete("/{melody_id}", status_code=204)
|
@router.delete("/{melody_id}", status_code=204)
|
||||||
@@ -57,7 +60,23 @@ async def delete_melody(
|
|||||||
melody_id: str,
|
melody_id: str,
|
||||||
_user: TokenPayload = Depends(require_permission("melodies", "delete")),
|
_user: TokenPayload = Depends(require_permission("melodies", "delete")),
|
||||||
):
|
):
|
||||||
service.delete_melody(melody_id)
|
await service.delete_melody(melody_id)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/{melody_id}/publish", response_model=MelodyInDB)
|
||||||
|
async def publish_melody(
|
||||||
|
melody_id: str,
|
||||||
|
_user: TokenPayload = Depends(require_permission("melodies", "edit")),
|
||||||
|
):
|
||||||
|
return await service.publish_melody(melody_id)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/{melody_id}/unpublish", response_model=MelodyInDB)
|
||||||
|
async def unpublish_melody(
|
||||||
|
melody_id: str,
|
||||||
|
_user: TokenPayload = Depends(require_permission("melodies", "edit")),
|
||||||
|
):
|
||||||
|
return await service.unpublish_melody(melody_id)
|
||||||
|
|
||||||
|
|
||||||
@router.post("/{melody_id}/upload/{file_type}")
|
@router.post("/{melody_id}/upload/{file_type}")
|
||||||
@@ -72,7 +91,7 @@ async def upload_file(
|
|||||||
raise HTTPException(status_code=400, detail="file_type must be 'binary' or 'preview'")
|
raise HTTPException(status_code=400, detail="file_type must be 'binary' or 'preview'")
|
||||||
|
|
||||||
# Verify melody exists
|
# Verify melody exists
|
||||||
melody = service.get_melody(melody_id)
|
melody = await service.get_melody(melody_id)
|
||||||
|
|
||||||
contents = await file.read()
|
contents = await file.read()
|
||||||
content_type = file.content_type or "application/octet-stream"
|
content_type = file.content_type or "application/octet-stream"
|
||||||
@@ -84,14 +103,14 @@ async def upload_file(
|
|||||||
|
|
||||||
# Update the melody document with the file URL
|
# Update the melody document with the file URL
|
||||||
if file_type == "preview":
|
if file_type == "preview":
|
||||||
service.update_melody(melody_id, MelodyUpdate(
|
await service.update_melody(melody_id, MelodyUpdate(
|
||||||
information=MelodyInfo(
|
information=MelodyInfo(
|
||||||
name=melody.information.name,
|
name=melody.information.name,
|
||||||
previewURL=url,
|
previewURL=url,
|
||||||
)
|
)
|
||||||
))
|
))
|
||||||
elif file_type == "binary":
|
elif file_type == "binary":
|
||||||
service.update_melody(melody_id, MelodyUpdate(url=url))
|
await service.update_melody(melody_id, MelodyUpdate(url=url))
|
||||||
|
|
||||||
return {"url": url, "file_type": file_type}
|
return {"url": url, "file_type": file_type}
|
||||||
|
|
||||||
@@ -106,7 +125,7 @@ async def delete_file(
|
|||||||
if file_type not in ("binary", "preview"):
|
if file_type not in ("binary", "preview"):
|
||||||
raise HTTPException(status_code=400, detail="file_type must be 'binary' or 'preview'")
|
raise HTTPException(status_code=400, detail="file_type must be 'binary' or 'preview'")
|
||||||
|
|
||||||
service.get_melody(melody_id)
|
await service.get_melody(melody_id)
|
||||||
service.delete_file(melody_id, file_type)
|
service.delete_file(melody_id, file_type)
|
||||||
|
|
||||||
|
|
||||||
@@ -116,5 +135,5 @@ async def get_files(
|
|||||||
_user: TokenPayload = Depends(require_permission("melodies", "view")),
|
_user: TokenPayload = Depends(require_permission("melodies", "view")),
|
||||||
):
|
):
|
||||||
"""Get storage file URLs for a melody."""
|
"""Get storage file URLs for a melody."""
|
||||||
service.get_melody(melody_id)
|
await service.get_melody(melody_id)
|
||||||
return service.get_storage_files(melody_id)
|
return service.get_storage_files(melody_id)
|
||||||
|
|||||||
@@ -1,10 +1,14 @@
|
|||||||
import json
|
import json
|
||||||
|
import uuid
|
||||||
|
import logging
|
||||||
|
|
||||||
from shared.firebase import get_db, get_bucket
|
from shared.firebase import get_db as get_firestore, get_bucket
|
||||||
from shared.exceptions import NotFoundError
|
from shared.exceptions import NotFoundError
|
||||||
from melodies.models import MelodyCreate, MelodyUpdate, MelodyInDB
|
from melodies.models import MelodyCreate, MelodyUpdate, MelodyInDB
|
||||||
|
from melodies import database as melody_db
|
||||||
|
|
||||||
COLLECTION = "melodies"
|
COLLECTION = "melodies"
|
||||||
|
logger = logging.getLogger("melodies.service")
|
||||||
|
|
||||||
|
|
||||||
def _parse_localized_string(value: str) -> dict:
|
def _parse_localized_string(value: str) -> dict:
|
||||||
@@ -26,109 +30,171 @@ def _doc_to_melody(doc) -> MelodyInDB:
|
|||||||
return MelodyInDB(id=doc.id, **data)
|
return MelodyInDB(id=doc.id, **data)
|
||||||
|
|
||||||
|
|
||||||
def list_melodies(
|
def _row_to_melody(row: dict) -> MelodyInDB:
|
||||||
|
"""Convert a SQLite row (with parsed data) to a MelodyInDB model."""
|
||||||
|
data = row["data"]
|
||||||
|
return MelodyInDB(id=row["id"], status=row["status"], **data)
|
||||||
|
|
||||||
|
|
||||||
|
def _matches_filters(melody: MelodyInDB, search: str | None, tone: str | None,
|
||||||
|
total_notes: int | None) -> bool:
|
||||||
|
"""Apply client-side filters to a melody."""
|
||||||
|
if tone and melody.information.melodyTone.value != tone:
|
||||||
|
return False
|
||||||
|
if total_notes is not None and melody.information.totalNotes != total_notes:
|
||||||
|
return False
|
||||||
|
if search:
|
||||||
|
search_lower = search.lower()
|
||||||
|
name_dict = _parse_localized_string(melody.information.name)
|
||||||
|
desc_dict = _parse_localized_string(melody.information.description)
|
||||||
|
name_match = any(
|
||||||
|
search_lower in v.lower() for v in name_dict.values() if isinstance(v, str)
|
||||||
|
)
|
||||||
|
desc_match = any(
|
||||||
|
search_lower in v.lower() for v in desc_dict.values() if isinstance(v, str)
|
||||||
|
)
|
||||||
|
tag_match = any(search_lower in t.lower() for t in melody.information.customTags)
|
||||||
|
if not (name_match or desc_match or tag_match):
|
||||||
|
return False
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
async def list_melodies(
|
||||||
search: str | None = None,
|
search: str | None = None,
|
||||||
melody_type: str | None = None,
|
melody_type: str | None = None,
|
||||||
tone: str | None = None,
|
tone: str | None = None,
|
||||||
total_notes: int | None = None,
|
total_notes: int | None = None,
|
||||||
|
status: str | None = None,
|
||||||
) -> list[MelodyInDB]:
|
) -> list[MelodyInDB]:
|
||||||
"""List melodies with optional filters."""
|
"""List melodies from SQLite with optional filters."""
|
||||||
db = get_db()
|
rows = await melody_db.list_melodies(status=status)
|
||||||
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 = []
|
results = []
|
||||||
|
|
||||||
for doc in docs:
|
for row in rows:
|
||||||
melody = _doc_to_melody(doc)
|
melody = _row_to_melody(row)
|
||||||
|
|
||||||
# Client-side filters
|
# Server-side type filter
|
||||||
if tone and melody.information.melodyTone.value != tone:
|
if melody_type and melody.type.value != melody_type:
|
||||||
continue
|
continue
|
||||||
if total_notes is not None and melody.information.totalNotes != total_notes:
|
|
||||||
|
if not _matches_filters(melody, search, tone, total_notes):
|
||||||
continue
|
continue
|
||||||
if search:
|
|
||||||
search_lower = search.lower()
|
|
||||||
name_dict = _parse_localized_string(melody.information.name)
|
|
||||||
desc_dict = _parse_localized_string(melody.information.description)
|
|
||||||
name_match = any(
|
|
||||||
search_lower in v.lower()
|
|
||||||
for v in name_dict.values()
|
|
||||||
if isinstance(v, str)
|
|
||||||
)
|
|
||||||
desc_match = any(
|
|
||||||
search_lower in v.lower()
|
|
||||||
for v in desc_dict.values()
|
|
||||||
if isinstance(v, str)
|
|
||||||
)
|
|
||||||
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)
|
results.append(melody)
|
||||||
|
|
||||||
return results
|
return results
|
||||||
|
|
||||||
|
|
||||||
def get_melody(melody_id: str) -> MelodyInDB:
|
async def get_melody(melody_id: str) -> MelodyInDB:
|
||||||
"""Get a single melody by document ID."""
|
"""Get a single melody by ID. Checks SQLite first."""
|
||||||
db = get_db()
|
row = await melody_db.get_melody(melody_id)
|
||||||
doc = db.collection(COLLECTION).document(melody_id).get()
|
if row:
|
||||||
if not doc.exists:
|
return _row_to_melody(row)
|
||||||
raise NotFoundError("Melody")
|
raise NotFoundError("Melody")
|
||||||
return _doc_to_melody(doc)
|
|
||||||
|
|
||||||
|
|
||||||
def create_melody(data: MelodyCreate) -> MelodyInDB:
|
async def create_melody(data: MelodyCreate, publish: bool = False) -> MelodyInDB:
|
||||||
"""Create a new melody document in Firestore."""
|
"""Create a new melody. If publish=True, also push to Firestore."""
|
||||||
db = get_db()
|
melody_id = str(uuid.uuid4())
|
||||||
doc_data = data.model_dump()
|
doc_data = data.model_dump()
|
||||||
_, doc_ref = db.collection(COLLECTION).add(doc_data)
|
status = "published" if publish else "draft"
|
||||||
return MelodyInDB(id=doc_ref.id, **doc_data)
|
|
||||||
|
# Always save to SQLite
|
||||||
|
await melody_db.insert_melody(melody_id, status, doc_data)
|
||||||
|
|
||||||
|
# If publishing, also save to Firestore
|
||||||
|
if publish:
|
||||||
|
db = get_firestore()
|
||||||
|
db.collection(COLLECTION).document(melody_id).set(doc_data)
|
||||||
|
|
||||||
|
return MelodyInDB(id=melody_id, status=status, **doc_data)
|
||||||
|
|
||||||
|
|
||||||
def update_melody(melody_id: str, data: MelodyUpdate) -> MelodyInDB:
|
async def update_melody(melody_id: str, data: MelodyUpdate) -> MelodyInDB:
|
||||||
"""Update an existing melody document. Only provided fields are updated."""
|
"""Update an existing melody. If published, also update Firestore."""
|
||||||
db = get_db()
|
row = await melody_db.get_melody(melody_id)
|
||||||
doc_ref = db.collection(COLLECTION).document(melody_id)
|
if not row:
|
||||||
doc = doc_ref.get()
|
|
||||||
if not doc.exists:
|
|
||||||
raise NotFoundError("Melody")
|
raise NotFoundError("Melody")
|
||||||
|
|
||||||
|
existing_data = row["data"]
|
||||||
update_data = data.model_dump(exclude_none=True)
|
update_data = data.model_dump(exclude_none=True)
|
||||||
|
|
||||||
# For nested structs, merge with existing data rather than replacing
|
# Merge nested structs
|
||||||
existing = doc.to_dict()
|
|
||||||
for key in ("information", "default_settings"):
|
for key in ("information", "default_settings"):
|
||||||
if key in update_data and key in existing:
|
if key in update_data and key in existing_data:
|
||||||
merged = {**existing[key], **update_data[key]}
|
merged = {**existing_data[key], **update_data[key]}
|
||||||
update_data[key] = merged
|
update_data[key] = merged
|
||||||
|
|
||||||
doc_ref.update(update_data)
|
merged_data = {**existing_data, **update_data}
|
||||||
|
|
||||||
updated_doc = doc_ref.get()
|
# Update SQLite
|
||||||
return _doc_to_melody(updated_doc)
|
await melody_db.update_melody(melody_id, merged_data)
|
||||||
|
|
||||||
|
# If published, also update Firestore
|
||||||
|
if row["status"] == "published":
|
||||||
|
db = get_firestore()
|
||||||
|
doc_ref = db.collection(COLLECTION).document(melody_id)
|
||||||
|
doc_ref.set(merged_data)
|
||||||
|
|
||||||
|
return MelodyInDB(id=melody_id, status=row["status"], **merged_data)
|
||||||
|
|
||||||
|
|
||||||
def delete_melody(melody_id: str) -> None:
|
async def publish_melody(melody_id: str) -> MelodyInDB:
|
||||||
"""Delete a melody document and its associated storage files."""
|
"""Publish a draft melody to Firestore."""
|
||||||
db = get_db()
|
row = await melody_db.get_melody(melody_id)
|
||||||
doc_ref = db.collection(COLLECTION).document(melody_id)
|
if not row:
|
||||||
doc = doc_ref.get()
|
|
||||||
if not doc.exists:
|
|
||||||
raise NotFoundError("Melody")
|
raise NotFoundError("Melody")
|
||||||
|
|
||||||
# Delete associated storage files
|
doc_data = row["data"]
|
||||||
|
|
||||||
|
# Write to Firestore
|
||||||
|
db = get_firestore()
|
||||||
|
db.collection(COLLECTION).document(melody_id).set(doc_data)
|
||||||
|
|
||||||
|
# Update status in SQLite
|
||||||
|
await melody_db.update_status(melody_id, "published")
|
||||||
|
|
||||||
|
return MelodyInDB(id=melody_id, status="published", **doc_data)
|
||||||
|
|
||||||
|
|
||||||
|
async def unpublish_melody(melody_id: str) -> MelodyInDB:
|
||||||
|
"""Remove melody from Firestore but keep in SQLite as draft."""
|
||||||
|
row = await melody_db.get_melody(melody_id)
|
||||||
|
if not row:
|
||||||
|
raise NotFoundError("Melody")
|
||||||
|
|
||||||
|
# Delete from Firestore
|
||||||
|
db = get_firestore()
|
||||||
|
doc_ref = db.collection(COLLECTION).document(melody_id)
|
||||||
|
doc = doc_ref.get()
|
||||||
|
if doc.exists:
|
||||||
|
doc_ref.delete()
|
||||||
|
|
||||||
|
# Update status in SQLite
|
||||||
|
await melody_db.update_status(melody_id, "draft")
|
||||||
|
|
||||||
|
return MelodyInDB(id=melody_id, status="draft", **row["data"])
|
||||||
|
|
||||||
|
|
||||||
|
async def delete_melody(melody_id: str) -> None:
|
||||||
|
"""Delete a melody from SQLite and Firestore (if published), plus storage files."""
|
||||||
|
row = await melody_db.get_melody(melody_id)
|
||||||
|
if not row:
|
||||||
|
raise NotFoundError("Melody")
|
||||||
|
|
||||||
|
# Delete from Firestore if published
|
||||||
|
if row["status"] == "published":
|
||||||
|
db = get_firestore()
|
||||||
|
doc_ref = db.collection(COLLECTION).document(melody_id)
|
||||||
|
doc = doc_ref.get()
|
||||||
|
if doc.exists:
|
||||||
|
doc_ref.delete()
|
||||||
|
|
||||||
|
# Delete storage files
|
||||||
_delete_storage_files(melody_id)
|
_delete_storage_files(melody_id)
|
||||||
|
|
||||||
doc_ref.delete()
|
# Delete from SQLite
|
||||||
|
await melody_db.delete_melody(melody_id)
|
||||||
|
|
||||||
|
|
||||||
def upload_file(melody_id: str, file_bytes: bytes, filename: str, content_type: str) -> str:
|
def upload_file(melody_id: str, file_bytes: bytes, filename: str, content_type: str) -> str:
|
||||||
@@ -137,11 +203,9 @@ def upload_file(melody_id: str, file_bytes: bytes, filename: str, content_type:
|
|||||||
if not bucket:
|
if not bucket:
|
||||||
raise RuntimeError("Firebase Storage not initialized")
|
raise RuntimeError("Firebase Storage not initialized")
|
||||||
|
|
||||||
# Determine subfolder based on content type
|
|
||||||
if content_type in ("application/octet-stream", "application/macbinary"):
|
if content_type in ("application/octet-stream", "application/macbinary"):
|
||||||
storage_path = f"melodies/{melody_id}/binary.bin"
|
storage_path = f"melodies/{melody_id}/binary.bin"
|
||||||
else:
|
else:
|
||||||
# Audio preview files
|
|
||||||
ext = filename.rsplit(".", 1)[-1] if "." in filename else "mp3"
|
ext = filename.rsplit(".", 1)[-1] if "." in filename else "mp3"
|
||||||
storage_path = f"melodies/{melody_id}/preview.{ext}"
|
storage_path = f"melodies/{melody_id}/preview.{ext}"
|
||||||
|
|
||||||
@@ -197,3 +261,24 @@ def get_storage_files(melody_id: str) -> dict:
|
|||||||
result["preview_url"] = blob.public_url
|
result["preview_url"] = blob.public_url
|
||||||
|
|
||||||
return result
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
async def migrate_from_firestore() -> int:
|
||||||
|
"""One-time migration: import existing Firestore melodies into SQLite as published.
|
||||||
|
Only runs if the melody_drafts table is empty."""
|
||||||
|
count = await melody_db.count_melodies()
|
||||||
|
if count > 0:
|
||||||
|
return 0
|
||||||
|
|
||||||
|
db = get_firestore()
|
||||||
|
docs = db.collection(COLLECTION).stream()
|
||||||
|
imported = 0
|
||||||
|
|
||||||
|
for doc in docs:
|
||||||
|
data = doc.to_dict()
|
||||||
|
await melody_db.insert_melody(doc.id, "published", data)
|
||||||
|
imported += 1
|
||||||
|
|
||||||
|
if imported > 0:
|
||||||
|
logger.info(f"Migrated {imported} melodies from Firestore to SQLite")
|
||||||
|
return imported
|
||||||
|
|||||||
@@ -44,6 +44,15 @@ SCHEMA_STATEMENTS = [
|
|||||||
"CREATE INDEX IF NOT EXISTS idx_heartbeats_serial_time ON heartbeats(device_serial, received_at)",
|
"CREATE INDEX IF NOT EXISTS idx_heartbeats_serial_time ON heartbeats(device_serial, received_at)",
|
||||||
"CREATE INDEX IF NOT EXISTS idx_commands_serial_time ON commands(device_serial, sent_at)",
|
"CREATE INDEX IF NOT EXISTS idx_commands_serial_time ON commands(device_serial, sent_at)",
|
||||||
"CREATE INDEX IF NOT EXISTS idx_commands_status ON commands(status)",
|
"CREATE INDEX IF NOT EXISTS idx_commands_status ON commands(status)",
|
||||||
|
# Melody drafts table
|
||||||
|
"""CREATE TABLE IF NOT EXISTS melody_drafts (
|
||||||
|
id TEXT PRIMARY KEY,
|
||||||
|
status TEXT NOT NULL DEFAULT 'draft',
|
||||||
|
data TEXT NOT NULL,
|
||||||
|
created_at TEXT NOT NULL DEFAULT (datetime('now')),
|
||||||
|
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
|
||||||
|
)""",
|
||||||
|
"CREATE INDEX IF NOT EXISTS idx_melody_drafts_status ON melody_drafts(status)",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -178,7 +178,7 @@ function DeviceLogsPanel({ deviceSerial }) {
|
|||||||
const [searchText, setSearchText] = useState("");
|
const [searchText, setSearchText] = useState("");
|
||||||
const [autoRefresh, setAutoRefresh] = useState(false);
|
const [autoRefresh, setAutoRefresh] = useState(false);
|
||||||
const [liveLogs, setLiveLogs] = useState([]);
|
const [liveLogs, setLiveLogs] = useState([]);
|
||||||
const limit = 15;
|
const limit = 25;
|
||||||
|
|
||||||
const fetchLogs = useCallback(async () => {
|
const fetchLogs = useCallback(async () => {
|
||||||
if (!deviceSerial) return;
|
if (!deviceSerial) return;
|
||||||
@@ -278,9 +278,9 @@ function DeviceLogsPanel({ deviceSerial }) {
|
|||||||
<p className="text-xs" style={{ color: "var(--text-muted)" }}>No logs found.</p>
|
<p className="text-xs" style={{ color: "var(--text-muted)" }}>No logs found.</p>
|
||||||
) : (
|
) : (
|
||||||
<div className="rounded-md overflow-hidden border" style={{ borderColor: "var(--border-primary)" }}>
|
<div className="rounded-md overflow-hidden border" style={{ borderColor: "var(--border-primary)" }}>
|
||||||
<div className="overflow-x-auto">
|
<div className="overflow-x-auto" style={{ maxHeight: 220, overflowY: "auto" }}>
|
||||||
<table className="w-full text-xs">
|
<table className="w-full text-xs">
|
||||||
<thead>
|
<thead style={{ position: "sticky", top: 0, zIndex: 1 }}>
|
||||||
<tr style={{ backgroundColor: "var(--bg-primary)", borderBottom: "1px solid var(--border-primary)" }}>
|
<tr style={{ backgroundColor: "var(--bg-primary)", borderBottom: "1px solid var(--border-primary)" }}>
|
||||||
<th className="px-3 py-2 text-left font-medium w-40" style={{ color: "var(--text-secondary)" }}>Time</th>
|
<th className="px-3 py-2 text-left font-medium w-40" style={{ color: "var(--text-secondary)" }}>Time</th>
|
||||||
<th className="px-3 py-2 text-left font-medium w-16" style={{ color: "var(--text-secondary)" }}>Level</th>
|
<th className="px-3 py-2 text-left font-medium w-16" style={{ color: "var(--text-secondary)" }}>Level</th>
|
||||||
@@ -322,6 +322,24 @@ function DeviceLogsPanel({ deviceSerial }) {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// --- Breakpoint hook ---
|
||||||
|
|
||||||
|
function useBreakpoint() {
|
||||||
|
const [cols, setCols] = useState(() => {
|
||||||
|
const w = window.innerWidth;
|
||||||
|
return w >= 2100 ? 3 : w >= 900 ? 2 : 1;
|
||||||
|
});
|
||||||
|
useEffect(() => {
|
||||||
|
const onResize = () => {
|
||||||
|
const w = window.innerWidth;
|
||||||
|
setCols(w >= 2100 ? 3 : w >= 900 ? 2 : 1);
|
||||||
|
};
|
||||||
|
window.addEventListener("resize", onResize);
|
||||||
|
return () => window.removeEventListener("resize", onResize);
|
||||||
|
}, []);
|
||||||
|
return cols;
|
||||||
|
}
|
||||||
|
|
||||||
// --- Main component ---
|
// --- Main component ---
|
||||||
|
|
||||||
export default function DeviceDetail() {
|
export default function DeviceDetail() {
|
||||||
@@ -429,6 +447,456 @@ export default function DeviceDetail() {
|
|||||||
const nextMaintenance = maintainedOn && stats.maintainancePeriod ? addDays(maintainedOn, stats.maintainancePeriod) : null;
|
const nextMaintenance = maintainedOn && stats.maintainancePeriod ? addDays(maintainedOn, stats.maintainancePeriod) : null;
|
||||||
const maintenanceDaysLeft = nextMaintenance ? daysUntil(nextMaintenance) : null;
|
const maintenanceDaysLeft = nextMaintenance ? daysUntil(nextMaintenance) : null;
|
||||||
|
|
||||||
|
const cols = useBreakpoint();
|
||||||
|
|
||||||
|
// ===== Section definitions =====
|
||||||
|
|
||||||
|
const deviceInfoSection = (
|
||||||
|
<section className="rounded-lg border p-5" style={{ backgroundColor: "var(--bg-card)", borderColor: "var(--border-primary)" }}>
|
||||||
|
<div className="device-info-row">
|
||||||
|
{/* Status */}
|
||||||
|
<div className="device-info-item">
|
||||||
|
<div
|
||||||
|
className="w-10 h-10 rounded-full flex items-center justify-center shrink-0"
|
||||||
|
style={{ backgroundColor: isOnline ? "var(--success-bg)" : "var(--bg-card-hover)" }}
|
||||||
|
>
|
||||||
|
<span
|
||||||
|
className="w-3 h-3 rounded-full inline-block"
|
||||||
|
style={{ backgroundColor: isOnline ? "var(--success-text)" : "var(--text-muted)" }}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<div className="text-xs font-medium uppercase tracking-wide" style={{ color: "var(--text-muted)" }}>Status</div>
|
||||||
|
<div className="text-sm font-semibold" style={{ color: isOnline ? "var(--success-text)" : "var(--text-muted)" }}>
|
||||||
|
{isOnline ? "Online" : "Offline"}
|
||||||
|
{mqttStatus && (
|
||||||
|
<span className="ml-2 text-xs font-normal" style={{ color: "var(--text-muted)" }}>
|
||||||
|
{mqttStatus.seconds_since_heartbeat}s ago
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Serial + Hardware Variant */}
|
||||||
|
<div className="device-info-item">
|
||||||
|
<div>
|
||||||
|
<div className="text-xs font-medium uppercase tracking-wide" style={{ color: "var(--text-muted)" }}>Serial Number</div>
|
||||||
|
<div className="text-sm font-mono mt-0.5" style={{ color: "var(--text-primary)" }}>{device.device_id}</div>
|
||||||
|
<div className="text-xs mt-0.5" style={{ color: "var(--text-muted)" }}>HW: VesperCore</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Admin Note */}
|
||||||
|
<div className="device-info-item">
|
||||||
|
<div>
|
||||||
|
<div className="text-xs font-medium uppercase tracking-wide" style={{ color: "var(--text-muted)" }}>Admin Note</div>
|
||||||
|
<div className="text-sm mt-0.5" style={{ color: "var(--text-muted)" }}>-</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Document ID */}
|
||||||
|
<div className="device-info-item">
|
||||||
|
<div>
|
||||||
|
<div className="text-xs font-medium uppercase tracking-wide" style={{ color: "var(--text-muted)" }}>Document ID</div>
|
||||||
|
<div className="text-xs font-mono mt-0.5" style={{ color: "var(--text-muted)" }}>{device.id}</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
);
|
||||||
|
|
||||||
|
const subscriptionSection = (
|
||||||
|
<SectionCard title="Subscription">
|
||||||
|
<dl className="grid gap-4" style={{ gridTemplateColumns: "repeat(auto-fill, minmax(150px, 1fr))" }}>
|
||||||
|
<Field label="Tier">
|
||||||
|
<span className="px-2 py-0.5 text-xs rounded-full capitalize" style={{ backgroundColor: "var(--badge-blue-bg)", color: "var(--badge-blue-text)" }}>
|
||||||
|
{sub.subscrTier}
|
||||||
|
</span>
|
||||||
|
</Field>
|
||||||
|
<Field label="Start Date">{formatDate(sub.subscrStart)}</Field>
|
||||||
|
<Field label="Duration">{sub.subscrDuration ? daysToDisplay(sub.subscrDuration) : "-"}</Field>
|
||||||
|
<Field label="Expiration Date">{subscrEnd ? formatDateNice(subscrEnd) : "-"}</Field>
|
||||||
|
<Field label="Time Left">
|
||||||
|
{subscrDaysLeft === null ? "-" : subscrDaysLeft <= 0 ? (
|
||||||
|
<span className="px-2 py-0.5 text-xs rounded-full" style={{ backgroundColor: "var(--danger-bg)", color: "var(--danger-text)" }}>
|
||||||
|
Subscription Expired
|
||||||
|
</span>
|
||||||
|
) : (
|
||||||
|
<span className="px-2 py-0.5 text-xs rounded-full" style={{ backgroundColor: "var(--success-bg)", color: "var(--success-text)" }}>
|
||||||
|
{subscrDaysLeft} days left
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</Field>
|
||||||
|
<Field label="Max Users">{sub.maxUsers}</Field>
|
||||||
|
<Field label="Max Outputs">{sub.maxOutputs}</Field>
|
||||||
|
</dl>
|
||||||
|
</SectionCard>
|
||||||
|
);
|
||||||
|
|
||||||
|
const locationSection = (
|
||||||
|
<SectionCard title="Location">
|
||||||
|
{coords ? (
|
||||||
|
<div className="location-split">
|
||||||
|
<div className="location-fields">
|
||||||
|
<dl className="space-y-4">
|
||||||
|
<Field label="Location">{device.device_location}</Field>
|
||||||
|
<Field label="Coordinates">
|
||||||
|
<div className="flex flex-wrap items-center gap-2">
|
||||||
|
<span>{formatCoordinates(coords)}</span>
|
||||||
|
<a
|
||||||
|
href={`https://www.google.com/maps?q=${coords.lat},${coords.lng}`}
|
||||||
|
target="_blank"
|
||||||
|
rel="noopener noreferrer"
|
||||||
|
className="px-2 py-0.5 text-xs rounded-md inline-block"
|
||||||
|
style={{ backgroundColor: "var(--badge-blue-bg)", color: "var(--badge-blue-text)" }}
|
||||||
|
onClick={(e) => e.stopPropagation()}
|
||||||
|
>
|
||||||
|
Open in Maps
|
||||||
|
</a>
|
||||||
|
</div>
|
||||||
|
</Field>
|
||||||
|
{locationName && <Field label="Nearest Place">{locationName}</Field>}
|
||||||
|
</dl>
|
||||||
|
</div>
|
||||||
|
<div className="location-map">
|
||||||
|
<div className="rounded-md overflow-hidden border w-full" style={{ borderColor: "var(--border-primary)", height: 250 }}>
|
||||||
|
<MapContainer center={[coords.lat, coords.lng]} zoom={13} style={{ height: "100%", width: "100%" }} scrollWheelZoom={false}>
|
||||||
|
<TileLayer
|
||||||
|
attribution='© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a>'
|
||||||
|
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
|
||||||
|
/>
|
||||||
|
<Marker position={[coords.lat, coords.lng]} />
|
||||||
|
</MapContainer>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<dl className="space-y-4">
|
||||||
|
<Field label="Location">{device.device_location}</Field>
|
||||||
|
<Field label="Coordinates">{device.device_location_coordinates || "-"}</Field>
|
||||||
|
</dl>
|
||||||
|
)}
|
||||||
|
</SectionCard>
|
||||||
|
);
|
||||||
|
|
||||||
|
const deviceSettingsSection = (
|
||||||
|
<SectionCard title="Device Settings">
|
||||||
|
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
|
||||||
|
{/* Left Column */}
|
||||||
|
<div>
|
||||||
|
<Subsection title="Basic Attributes" isFirst>
|
||||||
|
<FieldRow>
|
||||||
|
<Field label="Bell Guard"><BoolBadge value={attr.bellGuardOn} /></Field>
|
||||||
|
<Field label="Warnings On"><BoolBadge value={attr.warningsOn} /></Field>
|
||||||
|
<Field label="Bell Guard Safety"><BoolBadge value={attr.bellGuardSafetyOn} /></Field>
|
||||||
|
</FieldRow>
|
||||||
|
</Subsection>
|
||||||
|
<Subsection title="Alert Settings">
|
||||||
|
<FieldRow>
|
||||||
|
<Field label="Alerts Status"><BoolBadge value={clock.ringAlertsMasterOn} yesLabel="ON" noLabel="OFF" /></Field>
|
||||||
|
<Field label="Alerts Type"><span className="capitalize">{clock.ringAlerts || "-"}</span></Field>
|
||||||
|
<Field label="Ring Intervals">{clock.ringIntervals}</Field>
|
||||||
|
</FieldRow>
|
||||||
|
<FieldRow>
|
||||||
|
<Field label="Hour Bell">{clock.hourAlertsBell}</Field>
|
||||||
|
<Field label="Half-Hour Bell">{clock.halfhourAlertsBell}</Field>
|
||||||
|
<Field label="Quarter Bell">{clock.quarterAlertsBell}</Field>
|
||||||
|
</FieldRow>
|
||||||
|
<FieldRow>
|
||||||
|
<Field label="Daytime Silence"><BoolBadge value={clock.isDaySilenceOn} yesLabel="ON" noLabel="OFF" /></Field>
|
||||||
|
<Field label="Day-Time Period">
|
||||||
|
{formatTimestamp(clock.daySilenceFrom)} - {formatTimestamp(clock.daySilenceTo)}
|
||||||
|
</Field>
|
||||||
|
</FieldRow>
|
||||||
|
<FieldRow>
|
||||||
|
<Field label="Nighttime Silence"><BoolBadge value={clock.isNightSilenceOn} yesLabel="ON" noLabel="OFF" /></Field>
|
||||||
|
<Field label="Nighttime Period">
|
||||||
|
{formatTimestamp(clock.nightSilenceFrom)} - {formatTimestamp(clock.nightSilenceTo)}
|
||||||
|
</Field>
|
||||||
|
</FieldRow>
|
||||||
|
</Subsection>
|
||||||
|
<Subsection title="Backlight Settings">
|
||||||
|
<FieldRow>
|
||||||
|
<Field label="Auto Backlight"><BoolBadge value={clock.isBacklightAutomationOn} yesLabel="ON" noLabel="OFF" /></Field>
|
||||||
|
<Field label="Backlight Output">{clock.backlightOutput}</Field>
|
||||||
|
<Field label="Period">
|
||||||
|
{formatTimestamp(clock.backlightTurnOnTime)} - {formatTimestamp(clock.backlightTurnOffTime)}
|
||||||
|
</Field>
|
||||||
|
</FieldRow>
|
||||||
|
</Subsection>
|
||||||
|
<Subsection title="Logging">
|
||||||
|
<FieldRow>
|
||||||
|
<Field label="Serial Log Level">{attr.serialLogLevel}</Field>
|
||||||
|
<Field label="SD Log Level">{attr.sdLogLevel}</Field>
|
||||||
|
<Field label="MQTT Log Level">{attr.mqttLogLevel ?? 0}</Field>
|
||||||
|
</FieldRow>
|
||||||
|
</Subsection>
|
||||||
|
</div>
|
||||||
|
{/* Right Column */}
|
||||||
|
<div>
|
||||||
|
<Subsection title="Network" isFirst>
|
||||||
|
<FieldRow>
|
||||||
|
<Field label="Hostname">{net.hostname}</Field>
|
||||||
|
<Field label="Has Static IP"><BoolBadge value={net.useStaticIP} /></Field>
|
||||||
|
</FieldRow>
|
||||||
|
</Subsection>
|
||||||
|
<Subsection title="Clock Settings">
|
||||||
|
<FieldRow>
|
||||||
|
<Field label="Has Clock"><BoolBadge value={attr.hasClock} /></Field>
|
||||||
|
<Field label="Ring Intervals">{clock.ringIntervals}</Field>
|
||||||
|
</FieldRow>
|
||||||
|
<FieldRow>
|
||||||
|
<Field label="Odd Output">{clock.clockOutputs?.[0] ?? "-"}</Field>
|
||||||
|
<Field label="Even Output">{clock.clockOutputs?.[1] ?? "-"}</Field>
|
||||||
|
</FieldRow>
|
||||||
|
<FieldRow>
|
||||||
|
<Field label="Run Pulse">{clock.clockTimings?.[0] != null ? msToSeconds(clock.clockTimings[0]) : "-"}</Field>
|
||||||
|
<Field label="Pause Pulse">{clock.clockTimings?.[1] != null ? msToSeconds(clock.clockTimings[1]) : "-"}</Field>
|
||||||
|
</FieldRow>
|
||||||
|
</Subsection>
|
||||||
|
<Subsection title="Bell Settings">
|
||||||
|
<FieldRow>
|
||||||
|
<Field label="Bells Active"><BoolBadge value={attr.hasBells} /></Field>
|
||||||
|
<Field label="Total">{attr.totalBells ?? "-"}</Field>
|
||||||
|
</FieldRow>
|
||||||
|
{attr.bellOutputs?.length > 0 && (
|
||||||
|
<div className="mt-3">
|
||||||
|
<dt className="text-xs font-medium uppercase tracking-wide mb-2" style={{ color: "var(--text-muted)" }}>
|
||||||
|
Output & Timing Map
|
||||||
|
</dt>
|
||||||
|
<div className="flex flex-wrap gap-2">
|
||||||
|
{attr.bellOutputs.map((output, i) => (
|
||||||
|
<div
|
||||||
|
key={i}
|
||||||
|
className="relative rounded-md border px-4 py-3 text-center overflow-hidden"
|
||||||
|
style={{ borderColor: "var(--border-primary)", backgroundColor: "var(--bg-primary)", minWidth: 90 }}
|
||||||
|
>
|
||||||
|
<span
|
||||||
|
className="absolute inset-0 flex items-center justify-center font-bold pointer-events-none select-none"
|
||||||
|
style={{ fontSize: "3rem", color: "var(--text-heading)", opacity: 0.06 }}
|
||||||
|
>
|
||||||
|
{i + 1}
|
||||||
|
</span>
|
||||||
|
<div className="relative">
|
||||||
|
<div className="text-xs" style={{ color: "var(--text-muted)" }}>
|
||||||
|
Output <span style={{ color: "var(--text-primary)" }}>{output}</span>
|
||||||
|
</div>
|
||||||
|
<div className="text-xs mt-1" style={{ color: "var(--text-muted)" }}>
|
||||||
|
{attr.hammerTimings?.[i] != null ? (
|
||||||
|
<><span style={{ color: "var(--text-primary)" }}>{attr.hammerTimings[i]}</span> ms</>
|
||||||
|
) : "-"}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</Subsection>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</SectionCard>
|
||||||
|
);
|
||||||
|
|
||||||
|
const warrantySection = (
|
||||||
|
<SectionCard title="Warranty, Maintenance & Statistics">
|
||||||
|
<Subsection title="Warranty Information" isFirst>
|
||||||
|
<dl className="grid gap-4" style={{ gridTemplateColumns: "repeat(auto-fill, minmax(150px, 1fr))" }}>
|
||||||
|
<Field label="Warranty Status">
|
||||||
|
{warrantyDaysLeft !== null ? (
|
||||||
|
warrantyDaysLeft > 0 ? (
|
||||||
|
<span className="px-2 py-0.5 text-xs rounded-full" style={{ backgroundColor: "var(--success-bg)", color: "var(--success-text)" }}>Active</span>
|
||||||
|
) : (
|
||||||
|
<span className="px-2 py-0.5 text-xs rounded-full" style={{ backgroundColor: "var(--danger-bg)", color: "var(--danger-text)" }}>Expired</span>
|
||||||
|
)
|
||||||
|
) : (
|
||||||
|
<BoolBadge value={stats.warrantyActive} yesLabel="Active" noLabel="Expired" />
|
||||||
|
)}
|
||||||
|
</Field>
|
||||||
|
<Field label="Start Date">{formatDate(stats.warrantyStart)}</Field>
|
||||||
|
<Field label="Warranty Period">{stats.warrantyPeriod ? daysToDisplay(stats.warrantyPeriod) : "-"}</Field>
|
||||||
|
<Field label="Expiration Date">{warrantyEnd ? formatDateNice(warrantyEnd) : "-"}</Field>
|
||||||
|
<Field label="Remaining">
|
||||||
|
{warrantyDaysLeft === null ? "-" : warrantyDaysLeft <= 0 ? (
|
||||||
|
<span style={{ color: "var(--danger-text)" }}>Expired</span>
|
||||||
|
) : (
|
||||||
|
`${warrantyDaysLeft} days`
|
||||||
|
)}
|
||||||
|
</Field>
|
||||||
|
</dl>
|
||||||
|
</Subsection>
|
||||||
|
<Subsection title="Maintenance">
|
||||||
|
<dl className="grid gap-4" style={{ gridTemplateColumns: "repeat(auto-fill, minmax(150px, 1fr))" }}>
|
||||||
|
<Field label="Last Maintained On">{formatDate(stats.maintainedOn)}</Field>
|
||||||
|
<Field label="Maintenance Period">{stats.maintainancePeriod ? daysToDisplay(stats.maintainancePeriod) : "-"}</Field>
|
||||||
|
<Field label="Next Scheduled">
|
||||||
|
{nextMaintenance ? (
|
||||||
|
<span>
|
||||||
|
{formatDateNice(nextMaintenance)}
|
||||||
|
{maintenanceDaysLeft !== null && (
|
||||||
|
<span className="ml-1 text-xs" style={{ color: maintenanceDaysLeft <= 0 ? "var(--danger-text)" : "var(--text-muted)" }}>
|
||||||
|
({maintenanceDaysLeft <= 0 ? "overdue" : formatRelativeTime(maintenanceDaysLeft)})
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</span>
|
||||||
|
) : "-"}
|
||||||
|
</Field>
|
||||||
|
</dl>
|
||||||
|
</Subsection>
|
||||||
|
<Subsection title="Statistics">
|
||||||
|
<dl className="grid gap-4" style={{ gridTemplateColumns: "repeat(auto-fill, minmax(150px, 1fr))" }}>
|
||||||
|
<Field label="Total Playbacks">{stats.totalPlaybacks}</Field>
|
||||||
|
<Field label="Total Hammer Strikes">{stats.totalHammerStrikes}</Field>
|
||||||
|
<Field label="Total Warnings Given">{stats.totalWarningsGiven}</Field>
|
||||||
|
<Field label="Total Melodies">{device.device_melodies_all?.length ?? 0}</Field>
|
||||||
|
<Field label="Favorite Melodies">{device.device_melodies_favorites?.length ?? 0}</Field>
|
||||||
|
{stats.perBellStrikes?.length > 0 && (
|
||||||
|
<div style={{ gridColumn: "1 / -1" }}>
|
||||||
|
<Field label="Per Bell Strikes">
|
||||||
|
<div className="flex flex-wrap gap-2 mt-1">
|
||||||
|
{stats.perBellStrikes.slice(0, attr.totalBells || stats.perBellStrikes.length).map((count, i) => (
|
||||||
|
<span key={i} className="px-2 py-1 text-xs rounded-md border" style={{ borderColor: "var(--border-primary)", color: "var(--text-primary)" }}>
|
||||||
|
Bell {i + 1}: {count}
|
||||||
|
</span>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</Field>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</dl>
|
||||||
|
</Subsection>
|
||||||
|
</SectionCard>
|
||||||
|
);
|
||||||
|
|
||||||
|
const miscSection = (
|
||||||
|
<SectionCard title="Misc">
|
||||||
|
<dl className="grid gap-4" style={{ gridTemplateColumns: "repeat(auto-fill, minmax(150px, 1fr))" }}>
|
||||||
|
<Field label="Automated Events"><BoolBadge value={device.events_on} yesLabel="ON" noLabel="OFF" /></Field>
|
||||||
|
<Field label="Device Locale"><span className="capitalize">{attr.deviceLocale || "-"}</span></Field>
|
||||||
|
<Field label="WebSocket URL">{device.websocket_url}</Field>
|
||||||
|
<Field label="Has Assistant"><BoolBadge value={attr.hasAssistant} /></Field>
|
||||||
|
<div style={{ gridColumn: "1 / -1" }}>
|
||||||
|
<Field label="Church Assistant URL">{device.churchAssistantURL}</Field>
|
||||||
|
</div>
|
||||||
|
</dl>
|
||||||
|
</SectionCard>
|
||||||
|
);
|
||||||
|
|
||||||
|
const appUsersSection = (
|
||||||
|
<SectionCard title={`App Users (${deviceUsers.length})`}>
|
||||||
|
{usersLoading ? (
|
||||||
|
<p className="text-sm" style={{ color: "var(--text-muted)" }}>Loading users...</p>
|
||||||
|
) : deviceUsers.length === 0 ? (
|
||||||
|
<p className="text-sm" style={{ color: "var(--text-muted)" }}>No users assigned to this device.</p>
|
||||||
|
) : (
|
||||||
|
<div className="space-y-2">
|
||||||
|
{deviceUsers.map((user, i) => (
|
||||||
|
<div
|
||||||
|
key={user.user_id || i}
|
||||||
|
className="p-3 rounded-md border cursor-pointer hover:opacity-90 transition-colors"
|
||||||
|
style={{ backgroundColor: "var(--bg-primary)", borderColor: "var(--border-primary)" }}
|
||||||
|
onClick={() => user.user_id && navigate(`/users/${user.user_id}`)}
|
||||||
|
>
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<div className="min-w-0">
|
||||||
|
<p className="text-sm font-medium truncate" style={{ color: "var(--text-heading)" }}>
|
||||||
|
{user.display_name || user.email || "Unknown User"}
|
||||||
|
</p>
|
||||||
|
{user.email && user.display_name && (
|
||||||
|
<p className="text-xs truncate" style={{ color: "var(--text-muted)" }}>{user.email}</p>
|
||||||
|
)}
|
||||||
|
{user.user_id && (
|
||||||
|
<p className="text-xs font-mono" style={{ color: "var(--text-muted)" }}>{user.user_id}</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
{user.role && (
|
||||||
|
<span className="px-2 py-0.5 text-xs rounded-full capitalize shrink-0 ml-2" style={{ backgroundColor: "var(--badge-blue-bg)", color: "var(--badge-blue-text)" }}>
|
||||||
|
{user.role}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</SectionCard>
|
||||||
|
);
|
||||||
|
|
||||||
|
const notesSection = <NotesPanel deviceId={id} />;
|
||||||
|
const logsSection = <DeviceLogsPanel deviceSerial={device.device_id} />;
|
||||||
|
|
||||||
|
// ===== Layout rendering =====
|
||||||
|
|
||||||
|
const renderSingleColumn = () => (
|
||||||
|
<div className="device-column">
|
||||||
|
{deviceInfoSection}
|
||||||
|
{locationSection}
|
||||||
|
{notesSection}
|
||||||
|
{subscriptionSection}
|
||||||
|
{deviceSettingsSection}
|
||||||
|
{warrantySection}
|
||||||
|
{miscSection}
|
||||||
|
{appUsersSection}
|
||||||
|
{logsSection}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
|
||||||
|
const renderDoubleColumn = () => (
|
||||||
|
<div style={{ display: "flex", flexDirection: "column", gap: "1.5rem" }}>
|
||||||
|
{/* Row 1: Device Info + Subscription — equal height */}
|
||||||
|
<div className="device-equal-row">
|
||||||
|
{deviceInfoSection}
|
||||||
|
{subscriptionSection}
|
||||||
|
</div>
|
||||||
|
{/* Row 2: Device Settings — full width */}
|
||||||
|
{deviceSettingsSection}
|
||||||
|
{/* Row 3: Location+Misc (left) vs Warranty (right) */}
|
||||||
|
<div className="device-columns">
|
||||||
|
<div className="device-flex-fill" style={{ flex: 1, gap: "1.5rem" }}>
|
||||||
|
<div className="flex-grow">{locationSection}</div>
|
||||||
|
{miscSection}
|
||||||
|
</div>
|
||||||
|
<div style={{ flex: 1, minWidth: 0 }}>
|
||||||
|
{warrantySection}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{/* Row 4: Notes vs App Users */}
|
||||||
|
<div className="device-columns">
|
||||||
|
<div style={{ flex: 1, minWidth: 0 }}>{notesSection}</div>
|
||||||
|
<div style={{ flex: 1, minWidth: 0 }}>{appUsersSection}</div>
|
||||||
|
</div>
|
||||||
|
{/* Latest Logs */}
|
||||||
|
{logsSection}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
|
||||||
|
const renderTripleColumn = () => (
|
||||||
|
<div style={{ display: "flex", flexDirection: "column", gap: "1.5rem" }}>
|
||||||
|
{/* Row 1: DevInfo+Subscription (cols 1-2 equal height) + Location (col 3) */}
|
||||||
|
<div className="device-columns">
|
||||||
|
<div className="device-equal-row" style={{ flex: 2 }}>
|
||||||
|
{deviceInfoSection}
|
||||||
|
{subscriptionSection}
|
||||||
|
</div>
|
||||||
|
<div style={{ flex: 1, minWidth: 0 }}>{locationSection}</div>
|
||||||
|
</div>
|
||||||
|
{/* Row 2: Device Settings (cols 1-2) + Warranty (col 3) */}
|
||||||
|
<div className="device-columns">
|
||||||
|
<div style={{ flex: 2, minWidth: 0 }}>{deviceSettingsSection}</div>
|
||||||
|
<div style={{ flex: 1, minWidth: 0 }}>{warrantySection}</div>
|
||||||
|
</div>
|
||||||
|
{/* Row 3: Misc (col1) + Notes (col2) + App Users (col3) */}
|
||||||
|
<div className="device-columns">
|
||||||
|
<div style={{ flex: 1, minWidth: 0 }}>{miscSection}</div>
|
||||||
|
<div style={{ flex: 1, minWidth: 0 }}>{notesSection}</div>
|
||||||
|
<div style={{ flex: 1, minWidth: 0 }}>{appUsersSection}</div>
|
||||||
|
</div>
|
||||||
|
{/* Latest Logs */}
|
||||||
|
{logsSection}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div>
|
<div>
|
||||||
{/* Header */}
|
{/* Header */}
|
||||||
@@ -460,393 +928,7 @@ export default function DeviceDetail() {
|
|||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="device-sections">
|
{cols === 1 ? renderSingleColumn() : cols === 2 ? renderDoubleColumn() : renderTripleColumn()}
|
||||||
{/* ===== BASIC INFORMATION (double-width) ===== */}
|
|
||||||
<div className="section-wide">
|
|
||||||
<section className="rounded-lg border p-5" style={{ backgroundColor: "var(--bg-card)", borderColor: "var(--border-primary)" }}>
|
|
||||||
<div className="flex flex-wrap items-center gap-6 divide-x" style={{ borderColor: "var(--border-secondary)" }}>
|
|
||||||
{/* Status — fancy */}
|
|
||||||
<div className="flex items-center gap-3 pr-6">
|
|
||||||
<div
|
|
||||||
className="w-10 h-10 rounded-full flex items-center justify-center"
|
|
||||||
style={{ backgroundColor: isOnline ? "var(--success-bg)" : "var(--bg-card-hover)" }}
|
|
||||||
>
|
|
||||||
<span
|
|
||||||
className="w-3 h-3 rounded-full inline-block"
|
|
||||||
style={{ backgroundColor: isOnline ? "var(--success-text)" : "var(--text-muted)" }}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<div className="text-xs font-medium uppercase tracking-wide" style={{ color: "var(--text-muted)" }}>Status</div>
|
|
||||||
<div className="text-sm font-semibold" style={{ color: isOnline ? "var(--success-text)" : "var(--text-muted)" }}>
|
|
||||||
{isOnline ? "Online" : "Offline"}
|
|
||||||
{mqttStatus && (
|
|
||||||
<span className="ml-2 text-xs font-normal" style={{ color: "var(--text-muted)" }}>
|
|
||||||
(MQTT {mqttStatus.seconds_since_heartbeat}s ago)
|
|
||||||
</span>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Serial + Hardware Variant */}
|
|
||||||
<div className="pl-6">
|
|
||||||
<div className="text-xs font-medium uppercase tracking-wide" style={{ color: "var(--text-muted)" }}>Serial Number</div>
|
|
||||||
<div className="text-sm font-mono mt-0.5" style={{ color: "var(--text-primary)" }}>
|
|
||||||
{device.device_id}
|
|
||||||
<span className="ml-3 text-xs" style={{ color: "var(--text-muted)" }}>HW: -</span>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Quick Admin Notes */}
|
|
||||||
<div className="pl-6">
|
|
||||||
<div className="text-xs font-medium uppercase tracking-wide" style={{ color: "var(--text-muted)" }}>Admin Notes</div>
|
|
||||||
<div className="text-sm mt-0.5" style={{ color: "var(--text-muted)" }}>-</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Document ID */}
|
|
||||||
<div className="pl-6">
|
|
||||||
<div className="text-xs font-medium uppercase tracking-wide" style={{ color: "var(--text-muted)" }}>Document ID</div>
|
|
||||||
<div className="text-xs font-mono mt-0.5" style={{ color: "var(--text-muted)" }}>{device.id}</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</section>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* ===== DEVICE SETTINGS (double-width) ===== */}
|
|
||||||
<div className="section-wide">
|
|
||||||
<SectionCard title="Device Settings">
|
|
||||||
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
|
|
||||||
{/* Left Column */}
|
|
||||||
<div>
|
|
||||||
{/* Basic Attributes */}
|
|
||||||
<Subsection title="Basic Attributes" isFirst>
|
|
||||||
<FieldRow>
|
|
||||||
<Field label="Bell Guard"><BoolBadge value={attr.bellGuardOn} /></Field>
|
|
||||||
<Field label="Warnings On"><BoolBadge value={attr.warningsOn} /></Field>
|
|
||||||
<Field label="Bell Guard Safety"><BoolBadge value={attr.bellGuardSafetyOn} /></Field>
|
|
||||||
</FieldRow>
|
|
||||||
</Subsection>
|
|
||||||
|
|
||||||
{/* Alert Settings */}
|
|
||||||
<Subsection title="Alert Settings">
|
|
||||||
<FieldRow>
|
|
||||||
<Field label="Alerts Status"><BoolBadge value={clock.ringAlertsMasterOn} yesLabel="ON" noLabel="OFF" /></Field>
|
|
||||||
<Field label="Alerts Type"><span className="capitalize">{clock.ringAlerts || "-"}</span></Field>
|
|
||||||
<Field label="Ring Intervals">{clock.ringIntervals}</Field>
|
|
||||||
</FieldRow>
|
|
||||||
<FieldRow>
|
|
||||||
<Field label="Hour Bell">{clock.hourAlertsBell}</Field>
|
|
||||||
<Field label="Half-Hour Bell">{clock.halfhourAlertsBell}</Field>
|
|
||||||
<Field label="Quarter Bell">{clock.quarterAlertsBell}</Field>
|
|
||||||
</FieldRow>
|
|
||||||
<FieldRow>
|
|
||||||
<Field label="Daytime Silence"><BoolBadge value={clock.isDaySilenceOn} yesLabel="ON" noLabel="OFF" /></Field>
|
|
||||||
<Field label="Day-Time Period">
|
|
||||||
{formatTimestamp(clock.daySilenceFrom)} - {formatTimestamp(clock.daySilenceTo)}
|
|
||||||
</Field>
|
|
||||||
</FieldRow>
|
|
||||||
<FieldRow>
|
|
||||||
<Field label="Nighttime Silence"><BoolBadge value={clock.isNightSilenceOn} yesLabel="ON" noLabel="OFF" /></Field>
|
|
||||||
<Field label="Nighttime Period">
|
|
||||||
{formatTimestamp(clock.nightSilenceFrom)} - {formatTimestamp(clock.nightSilenceTo)}
|
|
||||||
</Field>
|
|
||||||
</FieldRow>
|
|
||||||
</Subsection>
|
|
||||||
|
|
||||||
{/* Backlight Settings */}
|
|
||||||
<Subsection title="Backlight Settings">
|
|
||||||
<FieldRow>
|
|
||||||
<Field label="Auto Backlight"><BoolBadge value={clock.isBacklightAutomationOn} yesLabel="ON" noLabel="OFF" /></Field>
|
|
||||||
<Field label="Backlight Output">{clock.backlightOutput}</Field>
|
|
||||||
<Field label="Period">
|
|
||||||
{formatTimestamp(clock.backlightTurnOnTime)} - {formatTimestamp(clock.backlightTurnOffTime)}
|
|
||||||
</Field>
|
|
||||||
</FieldRow>
|
|
||||||
</Subsection>
|
|
||||||
|
|
||||||
{/* Logging */}
|
|
||||||
<Subsection title="Logging">
|
|
||||||
<FieldRow>
|
|
||||||
<Field label="Serial Log Level">{attr.serialLogLevel}</Field>
|
|
||||||
<Field label="SD Log Level">{attr.sdLogLevel}</Field>
|
|
||||||
<Field label="MQTT Log Level">{attr.mqttLogLevel ?? 0}</Field>
|
|
||||||
</FieldRow>
|
|
||||||
</Subsection>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Right Column */}
|
|
||||||
<div>
|
|
||||||
{/* Network */}
|
|
||||||
<Subsection title="Network" isFirst>
|
|
||||||
<FieldRow>
|
|
||||||
<Field label="Hostname">{net.hostname}</Field>
|
|
||||||
<Field label="Has Static IP"><BoolBadge value={net.useStaticIP} /></Field>
|
|
||||||
</FieldRow>
|
|
||||||
</Subsection>
|
|
||||||
|
|
||||||
{/* Clock Settings */}
|
|
||||||
<Subsection title="Clock Settings">
|
|
||||||
<FieldRow>
|
|
||||||
<Field label="Has Clock"><BoolBadge value={attr.hasClock} /></Field>
|
|
||||||
<Field label="Ring Intervals">{clock.ringIntervals}</Field>
|
|
||||||
</FieldRow>
|
|
||||||
<FieldRow>
|
|
||||||
<Field label="Odd Output">{clock.clockOutputs?.[0] ?? "-"}</Field>
|
|
||||||
<Field label="Even Output">{clock.clockOutputs?.[1] ?? "-"}</Field>
|
|
||||||
</FieldRow>
|
|
||||||
<FieldRow>
|
|
||||||
<Field label="Run Pulse">{clock.clockTimings?.[0] != null ? msToSeconds(clock.clockTimings[0]) : "-"}</Field>
|
|
||||||
<Field label="Pause Pulse">{clock.clockTimings?.[1] != null ? msToSeconds(clock.clockTimings[1]) : "-"}</Field>
|
|
||||||
</FieldRow>
|
|
||||||
</Subsection>
|
|
||||||
|
|
||||||
{/* Bell Settings */}
|
|
||||||
<Subsection title="Bell Settings">
|
|
||||||
<FieldRow>
|
|
||||||
<Field label="Bells Active"><BoolBadge value={attr.hasBells} /></Field>
|
|
||||||
<Field label="Total">{attr.totalBells ?? "-"}</Field>
|
|
||||||
</FieldRow>
|
|
||||||
{/* Bell Output-to-Timing mapping with watermark numbers */}
|
|
||||||
{attr.bellOutputs?.length > 0 && (
|
|
||||||
<div className="mt-3">
|
|
||||||
<dt className="text-xs font-medium uppercase tracking-wide mb-2" style={{ color: "var(--text-muted)" }}>
|
|
||||||
Output & Timing Map
|
|
||||||
</dt>
|
|
||||||
<div className="flex flex-wrap gap-2">
|
|
||||||
{attr.bellOutputs.map((output, i) => (
|
|
||||||
<div
|
|
||||||
key={i}
|
|
||||||
className="relative rounded-md border px-4 py-3 text-center overflow-hidden"
|
|
||||||
style={{ borderColor: "var(--border-primary)", backgroundColor: "var(--bg-primary)", minWidth: 90 }}
|
|
||||||
>
|
|
||||||
{/* Watermark number */}
|
|
||||||
<span
|
|
||||||
className="absolute inset-0 flex items-center justify-center font-bold pointer-events-none select-none"
|
|
||||||
style={{ fontSize: "3rem", color: "var(--text-heading)", opacity: 0.06 }}
|
|
||||||
>
|
|
||||||
{i + 1}
|
|
||||||
</span>
|
|
||||||
{/* Content */}
|
|
||||||
<div className="relative">
|
|
||||||
<div className="text-xs" style={{ color: "var(--text-muted)" }}>
|
|
||||||
Output <span style={{ color: "var(--text-primary)" }}>{output}</span>
|
|
||||||
</div>
|
|
||||||
<div className="text-xs mt-1" style={{ color: "var(--text-muted)" }}>
|
|
||||||
{attr.hammerTimings?.[i] != null ? (
|
|
||||||
<><span style={{ color: "var(--text-primary)" }}>{attr.hammerTimings[i]}</span> ms</>
|
|
||||||
) : "-"}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</Subsection>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</SectionCard>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* ===== SINGLE-WIDTH SECTIONS ===== */}
|
|
||||||
|
|
||||||
{/* Misc */}
|
|
||||||
<SectionCard title="Misc">
|
|
||||||
<dl className="grid gap-4" style={{ gridTemplateColumns: "repeat(auto-fill, minmax(150px, 1fr))" }}>
|
|
||||||
<Field label="Automated Events"><BoolBadge value={device.events_on} yesLabel="ON" noLabel="OFF" /></Field>
|
|
||||||
<Field label="Device Locale"><span className="capitalize">{attr.deviceLocale || "-"}</span></Field>
|
|
||||||
<Field label="WebSocket URL">{device.websocket_url}</Field>
|
|
||||||
<Field label="Has Assistant"><BoolBadge value={attr.hasAssistant} /></Field>
|
|
||||||
<div style={{ gridColumn: "1 / -1" }}>
|
|
||||||
<Field label="Church Assistant URL">{device.churchAssistantURL}</Field>
|
|
||||||
</div>
|
|
||||||
</dl>
|
|
||||||
</SectionCard>
|
|
||||||
|
|
||||||
{/* Subscription */}
|
|
||||||
<SectionCard title="Subscription">
|
|
||||||
<dl className="grid gap-4" style={{ gridTemplateColumns: "repeat(auto-fill, minmax(150px, 1fr))" }}>
|
|
||||||
<Field label="Tier">
|
|
||||||
<span className="px-2 py-0.5 text-xs rounded-full capitalize" style={{ backgroundColor: "var(--badge-blue-bg)", color: "var(--badge-blue-text)" }}>
|
|
||||||
{sub.subscrTier}
|
|
||||||
</span>
|
|
||||||
</Field>
|
|
||||||
<Field label="Start Date">{formatDate(sub.subscrStart)}</Field>
|
|
||||||
<Field label="Duration">{sub.subscrDuration ? daysToDisplay(sub.subscrDuration) : "-"}</Field>
|
|
||||||
<Field label="Expiration Date">{subscrEnd ? formatDateNice(subscrEnd) : "-"}</Field>
|
|
||||||
<Field label="Time Left">
|
|
||||||
{subscrDaysLeft === null ? "-" : subscrDaysLeft <= 0 ? (
|
|
||||||
<span className="px-2 py-0.5 text-xs rounded-full" style={{ backgroundColor: "var(--danger-bg)", color: "var(--danger-text)" }}>
|
|
||||||
Subscription Expired
|
|
||||||
</span>
|
|
||||||
) : (
|
|
||||||
<span className="px-2 py-0.5 text-xs rounded-full" style={{ backgroundColor: "var(--success-bg)", color: "var(--success-text)" }}>
|
|
||||||
{subscrDaysLeft} days left
|
|
||||||
</span>
|
|
||||||
)}
|
|
||||||
</Field>
|
|
||||||
<Field label="Max Users">{sub.maxUsers}</Field>
|
|
||||||
<Field label="Max Outputs">{sub.maxOutputs}</Field>
|
|
||||||
</dl>
|
|
||||||
</SectionCard>
|
|
||||||
|
|
||||||
{/* Location */}
|
|
||||||
<SectionCard title="Location">
|
|
||||||
<div className={coords ? "grid grid-cols-1 md:grid-cols-2 gap-4" : ""}>
|
|
||||||
<dl className="space-y-4">
|
|
||||||
<Field label="Location">{device.device_location}</Field>
|
|
||||||
<Field label="Coordinates">
|
|
||||||
<div className="flex flex-wrap items-center gap-2">
|
|
||||||
<span>{coords ? formatCoordinates(coords) : device.device_location_coordinates || "-"}</span>
|
|
||||||
{coords && (
|
|
||||||
<a
|
|
||||||
href={`https://www.google.com/maps?q=${coords.lat},${coords.lng}`}
|
|
||||||
target="_blank"
|
|
||||||
rel="noopener noreferrer"
|
|
||||||
className="px-2 py-0.5 text-xs rounded-md inline-block"
|
|
||||||
style={{ backgroundColor: "var(--badge-blue-bg)", color: "var(--badge-blue-text)" }}
|
|
||||||
onClick={(e) => e.stopPropagation()}
|
|
||||||
>
|
|
||||||
Open in Maps
|
|
||||||
</a>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</Field>
|
|
||||||
{locationName && (
|
|
||||||
<Field label="Nearest Place">{locationName}</Field>
|
|
||||||
)}
|
|
||||||
</dl>
|
|
||||||
{coords && (
|
|
||||||
<div className="rounded-md overflow-hidden border" style={{ borderColor: "var(--border-primary)", minHeight: 300 }}>
|
|
||||||
<MapContainer center={[coords.lat, coords.lng]} zoom={13} style={{ height: "100%", width: "100%", minHeight: 300 }} scrollWheelZoom={false}>
|
|
||||||
<TileLayer
|
|
||||||
attribution='© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a>'
|
|
||||||
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
|
|
||||||
/>
|
|
||||||
<Marker position={[coords.lat, coords.lng]} />
|
|
||||||
</MapContainer>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</SectionCard>
|
|
||||||
|
|
||||||
{/* Warranty, Maintenance & Statistics */}
|
|
||||||
<SectionCard title="Warranty, Maintenance & Statistics">
|
|
||||||
<Subsection title="Warranty Information" isFirst>
|
|
||||||
<dl className="grid gap-4" style={{ gridTemplateColumns: "repeat(auto-fill, minmax(150px, 1fr))" }}>
|
|
||||||
<Field label="Warranty Status">
|
|
||||||
{warrantyDaysLeft !== null ? (
|
|
||||||
warrantyDaysLeft > 0 ? (
|
|
||||||
<span className="px-2 py-0.5 text-xs rounded-full" style={{ backgroundColor: "var(--success-bg)", color: "var(--success-text)" }}>Active</span>
|
|
||||||
) : (
|
|
||||||
<span className="px-2 py-0.5 text-xs rounded-full" style={{ backgroundColor: "var(--danger-bg)", color: "var(--danger-text)" }}>Expired</span>
|
|
||||||
)
|
|
||||||
) : (
|
|
||||||
<BoolBadge value={stats.warrantyActive} yesLabel="Active" noLabel="Expired" />
|
|
||||||
)}
|
|
||||||
</Field>
|
|
||||||
<Field label="Start Date">{formatDate(stats.warrantyStart)}</Field>
|
|
||||||
<Field label="Warranty Period">{stats.warrantyPeriod ? daysToDisplay(stats.warrantyPeriod) : "-"}</Field>
|
|
||||||
<Field label="Expiration Date">{warrantyEnd ? formatDateNice(warrantyEnd) : "-"}</Field>
|
|
||||||
<Field label="Remaining">
|
|
||||||
{warrantyDaysLeft === null ? "-" : warrantyDaysLeft <= 0 ? (
|
|
||||||
<span style={{ color: "var(--danger-text)" }}>Expired</span>
|
|
||||||
) : (
|
|
||||||
`${warrantyDaysLeft} days`
|
|
||||||
)}
|
|
||||||
</Field>
|
|
||||||
</dl>
|
|
||||||
</Subsection>
|
|
||||||
|
|
||||||
<Subsection title="Maintenance">
|
|
||||||
<dl className="grid gap-4" style={{ gridTemplateColumns: "repeat(auto-fill, minmax(150px, 1fr))" }}>
|
|
||||||
<Field label="Last Maintained On">{formatDate(stats.maintainedOn)}</Field>
|
|
||||||
<Field label="Maintenance Period">{stats.maintainancePeriod ? daysToDisplay(stats.maintainancePeriod) : "-"}</Field>
|
|
||||||
<Field label="Next Scheduled">
|
|
||||||
{nextMaintenance ? (
|
|
||||||
<span>
|
|
||||||
{formatDateNice(nextMaintenance)}
|
|
||||||
{maintenanceDaysLeft !== null && (
|
|
||||||
<span className="ml-1 text-xs" style={{ color: maintenanceDaysLeft <= 0 ? "var(--danger-text)" : "var(--text-muted)" }}>
|
|
||||||
({maintenanceDaysLeft <= 0 ? "overdue" : formatRelativeTime(maintenanceDaysLeft)})
|
|
||||||
</span>
|
|
||||||
)}
|
|
||||||
</span>
|
|
||||||
) : "-"}
|
|
||||||
</Field>
|
|
||||||
</dl>
|
|
||||||
</Subsection>
|
|
||||||
|
|
||||||
<Subsection title="Statistics">
|
|
||||||
<dl className="grid gap-4" style={{ gridTemplateColumns: "repeat(auto-fill, minmax(150px, 1fr))" }}>
|
|
||||||
<Field label="Total Playbacks">{stats.totalPlaybacks}</Field>
|
|
||||||
<Field label="Total Hammer Strikes">{stats.totalHammerStrikes}</Field>
|
|
||||||
<Field label="Total Warnings Given">{stats.totalWarningsGiven}</Field>
|
|
||||||
<Field label="Total Melodies">{device.device_melodies_all?.length ?? 0}</Field>
|
|
||||||
<Field label="Favorite Melodies">{device.device_melodies_favorites?.length ?? 0}</Field>
|
|
||||||
{stats.perBellStrikes?.length > 0 && (
|
|
||||||
<div style={{ gridColumn: "1 / -1" }}>
|
|
||||||
<Field label="Per Bell Strikes">
|
|
||||||
<div className="flex flex-wrap gap-2 mt-1">
|
|
||||||
{stats.perBellStrikes.slice(0, attr.totalBells || stats.perBellStrikes.length).map((count, i) => (
|
|
||||||
<span key={i} className="px-2 py-1 text-xs rounded-md border" style={{ borderColor: "var(--border-primary)", color: "var(--text-primary)" }}>
|
|
||||||
Bell {i + 1}: {count}
|
|
||||||
</span>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
</Field>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</dl>
|
|
||||||
</Subsection>
|
|
||||||
</SectionCard>
|
|
||||||
|
|
||||||
{/* Users */}
|
|
||||||
<SectionCard title={`App Users (${deviceUsers.length})`}>
|
|
||||||
{usersLoading ? (
|
|
||||||
<p className="text-sm" style={{ color: "var(--text-muted)" }}>Loading users...</p>
|
|
||||||
) : deviceUsers.length === 0 ? (
|
|
||||||
<p className="text-sm" style={{ color: "var(--text-muted)" }}>No users assigned to this device.</p>
|
|
||||||
) : (
|
|
||||||
<div className="space-y-2">
|
|
||||||
{deviceUsers.map((user, i) => (
|
|
||||||
<div
|
|
||||||
key={user.user_id || i}
|
|
||||||
className="p-3 rounded-md border cursor-pointer hover:opacity-90 transition-colors"
|
|
||||||
style={{ backgroundColor: "var(--bg-primary)", borderColor: "var(--border-primary)" }}
|
|
||||||
onClick={() => user.user_id && navigate(`/users/${user.user_id}`)}
|
|
||||||
>
|
|
||||||
<div className="flex items-center justify-between">
|
|
||||||
<div className="min-w-0">
|
|
||||||
<p className="text-sm font-medium truncate" style={{ color: "var(--text-heading)" }}>
|
|
||||||
{user.display_name || user.email || "Unknown User"}
|
|
||||||
</p>
|
|
||||||
{user.email && user.display_name && (
|
|
||||||
<p className="text-xs truncate" style={{ color: "var(--text-muted)" }}>{user.email}</p>
|
|
||||||
)}
|
|
||||||
{user.user_id && (
|
|
||||||
<p className="text-xs font-mono" style={{ color: "var(--text-muted)" }}>{user.user_id}</p>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
{user.role && (
|
|
||||||
<span className="px-2 py-0.5 text-xs rounded-full capitalize shrink-0 ml-2" style={{ backgroundColor: "var(--badge-blue-bg)", color: "var(--badge-blue-text)" }}>
|
|
||||||
{user.role}
|
|
||||||
</span>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</SectionCard>
|
|
||||||
|
|
||||||
{/* Equipment Notes */}
|
|
||||||
<NotesPanel deviceId={id} />
|
|
||||||
|
|
||||||
{/* Latest Logs */}
|
|
||||||
<DeviceLogsPanel deviceSerial={device.device_id} />
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<ConfirmDialog
|
<ConfirmDialog
|
||||||
open={showDelete}
|
open={showDelete}
|
||||||
|
|||||||
@@ -145,29 +145,70 @@ input[type="range"]::-moz-range-thumb {
|
|||||||
border: 2px solid var(--bg-primary);
|
border: 2px solid var(--bg-primary);
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Device detail grid layout */
|
/* Device detail column layout */
|
||||||
.device-sections {
|
.device-columns {
|
||||||
display: grid;
|
display: flex;
|
||||||
grid-template-columns: 1fr;
|
|
||||||
gap: 1.5rem;
|
gap: 1.5rem;
|
||||||
align-items: start;
|
align-items: flex-start;
|
||||||
}
|
}
|
||||||
.device-sections > .section-wide {
|
.device-column {
|
||||||
grid-column: 1 / -1;
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 1.5rem;
|
||||||
|
flex: 1;
|
||||||
|
min-width: 0;
|
||||||
}
|
}
|
||||||
@media (min-width: 900px) {
|
.device-full-row {
|
||||||
.device-sections {
|
width: 100%;
|
||||||
grid-template-columns: repeat(2, 1fr);
|
margin-bottom: 1.5rem;
|
||||||
grid-auto-flow: dense;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
@media (min-width: 2100px) {
|
.device-equal-row {
|
||||||
.device-sections {
|
display: flex;
|
||||||
grid-template-columns: repeat(3, 1fr);
|
gap: 1.5rem;
|
||||||
}
|
align-items: stretch;
|
||||||
.device-sections > .section-wide {
|
}
|
||||||
grid-column: span 2;
|
.device-equal-row > * {
|
||||||
}
|
flex: 1;
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
.device-flex-fill {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
}
|
||||||
|
.device-flex-fill > .flex-grow {
|
||||||
|
flex: 1;
|
||||||
|
}
|
||||||
|
/* Device info horizontal subsections */
|
||||||
|
.device-info-row {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: 0;
|
||||||
|
}
|
||||||
|
.device-info-row > .device-info-item {
|
||||||
|
padding: 0 1.5rem;
|
||||||
|
border-left: 1px solid var(--border-secondary);
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.75rem;
|
||||||
|
}
|
||||||
|
.device-info-row > .device-info-item:first-child {
|
||||||
|
padding-left: 0;
|
||||||
|
border-left: none;
|
||||||
|
}
|
||||||
|
/* Location 2-column internal layout */
|
||||||
|
.location-split {
|
||||||
|
display: flex;
|
||||||
|
gap: 1.5rem;
|
||||||
|
align-items: stretch;
|
||||||
|
}
|
||||||
|
.location-split > .location-fields {
|
||||||
|
flex: 0 0 auto;
|
||||||
|
min-width: 200px;
|
||||||
|
}
|
||||||
|
.location-split > .location-map {
|
||||||
|
flex: 1;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* File input */
|
/* File input */
|
||||||
|
|||||||
@@ -32,6 +32,8 @@ export default function MelodyDetail() {
|
|||||||
const [loading, setLoading] = useState(true);
|
const [loading, setLoading] = useState(true);
|
||||||
const [error, setError] = useState("");
|
const [error, setError] = useState("");
|
||||||
const [showDelete, setShowDelete] = useState(false);
|
const [showDelete, setShowDelete] = useState(false);
|
||||||
|
const [showUnpublish, setShowUnpublish] = useState(false);
|
||||||
|
const [actionLoading, setActionLoading] = useState(false);
|
||||||
const [displayLang, setDisplayLang] = useState("en");
|
const [displayLang, setDisplayLang] = useState("en");
|
||||||
const [melodySettings, setMelodySettings] = useState(null);
|
const [melodySettings, setMelodySettings] = useState(null);
|
||||||
|
|
||||||
@@ -72,6 +74,32 @@ export default function MelodyDetail() {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const handlePublish = async () => {
|
||||||
|
setActionLoading(true);
|
||||||
|
try {
|
||||||
|
await api.post(`/melodies/${id}/publish`);
|
||||||
|
await loadData();
|
||||||
|
} catch (err) {
|
||||||
|
setError(err.message);
|
||||||
|
} finally {
|
||||||
|
setActionLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleUnpublish = async () => {
|
||||||
|
setActionLoading(true);
|
||||||
|
try {
|
||||||
|
await api.post(`/melodies/${id}/unpublish`);
|
||||||
|
setShowUnpublish(false);
|
||||||
|
await loadData();
|
||||||
|
} catch (err) {
|
||||||
|
setError(err.message);
|
||||||
|
setShowUnpublish(false);
|
||||||
|
} finally {
|
||||||
|
setActionLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
if (loading) {
|
if (loading) {
|
||||||
return <div className="text-center py-8" style={{ color: "var(--text-muted)" }}>Loading...</div>;
|
return <div className="text-center py-8" style={{ color: "var(--text-muted)" }}>Loading...</div>;
|
||||||
}
|
}
|
||||||
@@ -116,6 +144,15 @@ export default function MelodyDetail() {
|
|||||||
</button>
|
</button>
|
||||||
<div className="flex items-center gap-3">
|
<div className="flex items-center gap-3">
|
||||||
<h1 className="text-2xl font-bold" style={{ color: "var(--text-heading)" }}>{displayName}</h1>
|
<h1 className="text-2xl font-bold" style={{ color: "var(--text-heading)" }}>{displayName}</h1>
|
||||||
|
<span
|
||||||
|
className="px-2.5 py-0.5 text-xs font-semibold rounded-full"
|
||||||
|
style={melody.status === "published"
|
||||||
|
? { backgroundColor: "rgba(22,163,74,0.15)", color: "#22c55e" }
|
||||||
|
: { backgroundColor: "rgba(156,163,175,0.15)", color: "#9ca3af" }
|
||||||
|
}
|
||||||
|
>
|
||||||
|
{melody.status === "published" ? "LIVE" : "DRAFT"}
|
||||||
|
</span>
|
||||||
{languages.length > 1 && (
|
{languages.length > 1 && (
|
||||||
<select
|
<select
|
||||||
value={displayLang}
|
value={displayLang}
|
||||||
@@ -133,6 +170,25 @@ export default function MelodyDetail() {
|
|||||||
</div>
|
</div>
|
||||||
{canEdit && (
|
{canEdit && (
|
||||||
<div className="flex gap-2">
|
<div className="flex gap-2">
|
||||||
|
{melody.status === "draft" ? (
|
||||||
|
<button
|
||||||
|
onClick={handlePublish}
|
||||||
|
disabled={actionLoading}
|
||||||
|
className="px-4 py-2 text-sm rounded-md transition-colors disabled:opacity-50"
|
||||||
|
style={{ backgroundColor: "#16a34a", color: "#fff" }}
|
||||||
|
>
|
||||||
|
{actionLoading ? "Publishing..." : "Publish"}
|
||||||
|
</button>
|
||||||
|
) : (
|
||||||
|
<button
|
||||||
|
onClick={() => setShowUnpublish(true)}
|
||||||
|
disabled={actionLoading}
|
||||||
|
className="px-4 py-2 text-sm rounded-md transition-colors disabled:opacity-50"
|
||||||
|
style={{ backgroundColor: "#ea580c", color: "#fff" }}
|
||||||
|
>
|
||||||
|
Unpublish
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
<button
|
<button
|
||||||
onClick={() => navigate(`/melodies/${id}/edit`)}
|
onClick={() => navigate(`/melodies/${id}/edit`)}
|
||||||
className="px-4 py-2 text-sm rounded-md transition-colors"
|
className="px-4 py-2 text-sm rounded-md transition-colors"
|
||||||
@@ -326,6 +382,14 @@ export default function MelodyDetail() {
|
|||||||
onConfirm={handleDelete}
|
onConfirm={handleDelete}
|
||||||
onCancel={() => setShowDelete(false)}
|
onCancel={() => setShowDelete(false)}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
|
<ConfirmDialog
|
||||||
|
open={showUnpublish}
|
||||||
|
title="Unpublish Melody"
|
||||||
|
message={`This melody may be in use by devices. Unpublishing will remove it from Firestore and devices will no longer have access to "${displayName}". The melody will be kept as a draft. Continue?`}
|
||||||
|
onConfirm={handleUnpublish}
|
||||||
|
onCancel={() => setShowUnpublish(false)}
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -58,6 +58,7 @@ export default function MelodyForm() {
|
|||||||
const [url, setUrl] = useState("");
|
const [url, setUrl] = useState("");
|
||||||
const [uid, setUid] = useState("");
|
const [uid, setUid] = useState("");
|
||||||
const [pid, setPid] = useState("");
|
const [pid, setPid] = useState("");
|
||||||
|
const [melodyStatus, setMelodyStatus] = useState("draft");
|
||||||
|
|
||||||
const [binaryFile, setBinaryFile] = useState(null);
|
const [binaryFile, setBinaryFile] = useState(null);
|
||||||
const [previewFile, setPreviewFile] = useState(null);
|
const [previewFile, setPreviewFile] = useState(null);
|
||||||
@@ -116,6 +117,7 @@ export default function MelodyForm() {
|
|||||||
setUrl(melody.url || "");
|
setUrl(melody.url || "");
|
||||||
setUid(melody.uid || "");
|
setUid(melody.uid || "");
|
||||||
setPid(melody.pid || "");
|
setPid(melody.pid || "");
|
||||||
|
setMelodyStatus(melody.status || "published");
|
||||||
setExistingFiles(files);
|
setExistingFiles(files);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
setError(err.message);
|
setError(err.message);
|
||||||
@@ -150,33 +152,39 @@ export default function MelodyForm() {
|
|||||||
updateInfo(fieldKey, serializeLocalizedString(dict));
|
updateInfo(fieldKey, serializeLocalizedString(dict));
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleSubmit = async (e) => {
|
const buildBody = () => {
|
||||||
e.preventDefault();
|
const { notes, ...infoWithoutNotes } = information;
|
||||||
|
return {
|
||||||
|
information: infoWithoutNotes,
|
||||||
|
default_settings: settings,
|
||||||
|
type, url, uid, pid,
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
const uploadFiles = async (melodyId) => {
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleSave = async (publish) => {
|
||||||
setSaving(true);
|
setSaving(true);
|
||||||
setError("");
|
setError("");
|
||||||
try {
|
try {
|
||||||
const { notes, ...infoWithoutNotes } = information;
|
const body = buildBody();
|
||||||
const body = {
|
|
||||||
information: infoWithoutNotes,
|
|
||||||
default_settings: settings,
|
|
||||||
type, url, uid, pid,
|
|
||||||
};
|
|
||||||
|
|
||||||
let melodyId = id;
|
let melodyId = id;
|
||||||
|
|
||||||
if (isEdit) {
|
if (isEdit) {
|
||||||
await api.put(`/melodies/${id}`, body);
|
await api.put(`/melodies/${id}`, body);
|
||||||
} else {
|
} else {
|
||||||
const created = await api.post("/melodies", body);
|
const created = await api.post(`/melodies?publish=${publish}`, body);
|
||||||
melodyId = created.id;
|
melodyId = created.id;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (binaryFile || previewFile) {
|
await uploadFiles(melodyId);
|
||||||
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}`);
|
navigate(`/melodies/${melodyId}`);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
setError(err.message);
|
setError(err.message);
|
||||||
@@ -186,6 +194,46 @@ export default function MelodyForm() {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const handlePublishAction = async () => {
|
||||||
|
setSaving(true);
|
||||||
|
setError("");
|
||||||
|
try {
|
||||||
|
const body = buildBody();
|
||||||
|
await api.put(`/melodies/${id}`, body);
|
||||||
|
await uploadFiles(id);
|
||||||
|
await api.post(`/melodies/${id}/publish`);
|
||||||
|
navigate(`/melodies/${id}`);
|
||||||
|
} catch (err) {
|
||||||
|
setError(err.message);
|
||||||
|
setUploading(false);
|
||||||
|
} finally {
|
||||||
|
setSaving(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleUnpublishAction = async () => {
|
||||||
|
setSaving(true);
|
||||||
|
setError("");
|
||||||
|
try {
|
||||||
|
await api.post(`/melodies/${id}/unpublish`);
|
||||||
|
navigate(`/melodies/${id}`);
|
||||||
|
} catch (err) {
|
||||||
|
setError(err.message);
|
||||||
|
} finally {
|
||||||
|
setSaving(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleSubmit = async (e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
// Default form submit: save as draft for new, update for existing
|
||||||
|
if (isEdit) {
|
||||||
|
await handleSave(false);
|
||||||
|
} else {
|
||||||
|
await handleSave(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
if (loading) {
|
if (loading) {
|
||||||
return <div className="text-center py-8" style={mutedStyle}>Loading...</div>;
|
return <div className="text-center py-8" style={mutedStyle}>Loading...</div>;
|
||||||
}
|
}
|
||||||
@@ -214,15 +262,70 @@ export default function MelodyForm() {
|
|||||||
>
|
>
|
||||||
Cancel
|
Cancel
|
||||||
</button>
|
</button>
|
||||||
<button
|
{!isEdit ? (
|
||||||
type="submit"
|
<>
|
||||||
form="melody-form"
|
<button
|
||||||
disabled={saving || uploading}
|
type="submit"
|
||||||
className="px-4 py-2 text-sm rounded-md disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
|
form="melody-form"
|
||||||
style={{ backgroundColor: "var(--btn-primary)", color: "var(--text-white)" }}
|
disabled={saving || uploading}
|
||||||
>
|
className="px-4 py-2 text-sm rounded-md disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
|
||||||
{uploading ? "Uploading files..." : saving ? "Saving..." : isEdit ? "Update Melody" : "Create Melody"}
|
style={{ backgroundColor: "var(--bg-card-hover)", color: "var(--text-primary)", border: "1px solid var(--border-primary)" }}
|
||||||
</button>
|
>
|
||||||
|
{saving ? "Saving..." : "Save as Draft"}
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
disabled={saving || uploading}
|
||||||
|
onClick={() => handleSave(true)}
|
||||||
|
className="px-4 py-2 text-sm rounded-md disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
|
||||||
|
style={{ backgroundColor: "var(--btn-primary)", color: "var(--text-white)" }}
|
||||||
|
>
|
||||||
|
{uploading ? "Uploading files..." : "Publish Melody"}
|
||||||
|
</button>
|
||||||
|
</>
|
||||||
|
) : melodyStatus === "draft" ? (
|
||||||
|
<>
|
||||||
|
<button
|
||||||
|
type="submit"
|
||||||
|
form="melody-form"
|
||||||
|
disabled={saving || uploading}
|
||||||
|
className="px-4 py-2 text-sm rounded-md disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
|
||||||
|
style={{ backgroundColor: "var(--bg-card-hover)", color: "var(--text-primary)", border: "1px solid var(--border-primary)" }}
|
||||||
|
>
|
||||||
|
{saving ? "Saving..." : "Update Draft"}
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
disabled={saving || uploading}
|
||||||
|
onClick={handlePublishAction}
|
||||||
|
className="px-4 py-2 text-sm rounded-md disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
|
||||||
|
style={{ backgroundColor: "#16a34a", color: "#fff" }}
|
||||||
|
>
|
||||||
|
{uploading ? "Uploading files..." : "Publish"}
|
||||||
|
</button>
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<button
|
||||||
|
type="submit"
|
||||||
|
form="melody-form"
|
||||||
|
disabled={saving || uploading}
|
||||||
|
className="px-4 py-2 text-sm rounded-md disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
|
||||||
|
style={{ backgroundColor: "var(--btn-primary)", color: "var(--text-white)" }}
|
||||||
|
>
|
||||||
|
{uploading ? "Uploading files..." : saving ? "Saving..." : "Update Melody"}
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
disabled={saving || uploading}
|
||||||
|
onClick={handleUnpublishAction}
|
||||||
|
className="px-4 py-2 text-sm rounded-md disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
|
||||||
|
style={{ backgroundColor: "#ea580c", color: "#fff" }}
|
||||||
|
>
|
||||||
|
Unpublish
|
||||||
|
</button>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
|||||||
@@ -16,6 +16,7 @@ const MELODY_TONES = ["", "normal", "festive", "cheerful", "lamentation"];
|
|||||||
|
|
||||||
// All available columns with their defaults
|
// All available columns with their defaults
|
||||||
const ALL_COLUMNS = [
|
const ALL_COLUMNS = [
|
||||||
|
{ key: "status", label: "Status", defaultOn: true },
|
||||||
{ key: "color", label: "Color", defaultOn: true },
|
{ key: "color", label: "Color", defaultOn: true },
|
||||||
{ key: "name", label: "Name", defaultOn: true, alwaysOn: true },
|
{ key: "name", label: "Name", defaultOn: true, alwaysOn: true },
|
||||||
{ key: "description", label: "Description", defaultOn: false },
|
{ key: "description", label: "Description", defaultOn: false },
|
||||||
@@ -56,9 +57,12 @@ export default function MelodyList() {
|
|||||||
const [search, setSearch] = useState("");
|
const [search, setSearch] = useState("");
|
||||||
const [typeFilter, setTypeFilter] = useState("");
|
const [typeFilter, setTypeFilter] = useState("");
|
||||||
const [toneFilter, setToneFilter] = useState("");
|
const [toneFilter, setToneFilter] = useState("");
|
||||||
|
const [statusFilter, setStatusFilter] = useState("");
|
||||||
const [displayLang, setDisplayLang] = useState("en");
|
const [displayLang, setDisplayLang] = useState("en");
|
||||||
const [melodySettings, setMelodySettings] = useState(null);
|
const [melodySettings, setMelodySettings] = useState(null);
|
||||||
const [deleteTarget, setDeleteTarget] = useState(null);
|
const [deleteTarget, setDeleteTarget] = useState(null);
|
||||||
|
const [unpublishTarget, setUnpublishTarget] = useState(null);
|
||||||
|
const [actionLoading, setActionLoading] = useState(null);
|
||||||
const [visibleColumns, setVisibleColumns] = useState(getDefaultVisibleColumns);
|
const [visibleColumns, setVisibleColumns] = useState(getDefaultVisibleColumns);
|
||||||
const [showColumnPicker, setShowColumnPicker] = useState(false);
|
const [showColumnPicker, setShowColumnPicker] = useState(false);
|
||||||
const columnPickerRef = useRef(null);
|
const columnPickerRef = useRef(null);
|
||||||
@@ -94,6 +98,7 @@ export default function MelodyList() {
|
|||||||
if (search) params.set("search", search);
|
if (search) params.set("search", search);
|
||||||
if (typeFilter) params.set("type", typeFilter);
|
if (typeFilter) params.set("type", typeFilter);
|
||||||
if (toneFilter) params.set("tone", toneFilter);
|
if (toneFilter) params.set("tone", toneFilter);
|
||||||
|
if (statusFilter) params.set("status", statusFilter);
|
||||||
const qs = params.toString();
|
const qs = params.toString();
|
||||||
const data = await api.get(`/melodies${qs ? `?${qs}` : ""}`);
|
const data = await api.get(`/melodies${qs ? `?${qs}` : ""}`);
|
||||||
setMelodies(data.melodies);
|
setMelodies(data.melodies);
|
||||||
@@ -107,7 +112,7 @@ export default function MelodyList() {
|
|||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
fetchMelodies();
|
fetchMelodies();
|
||||||
}, [search, typeFilter, toneFilter]);
|
}, [search, typeFilter, toneFilter, statusFilter]);
|
||||||
|
|
||||||
const handleDelete = async () => {
|
const handleDelete = async () => {
|
||||||
if (!deleteTarget) return;
|
if (!deleteTarget) return;
|
||||||
@@ -121,6 +126,33 @@ export default function MelodyList() {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const handlePublish = async (row) => {
|
||||||
|
setActionLoading(row.id);
|
||||||
|
try {
|
||||||
|
await api.post(`/melodies/${row.id}/publish`);
|
||||||
|
fetchMelodies();
|
||||||
|
} catch (err) {
|
||||||
|
setError(err.message);
|
||||||
|
} finally {
|
||||||
|
setActionLoading(null);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleUnpublish = async () => {
|
||||||
|
if (!unpublishTarget) return;
|
||||||
|
setActionLoading(unpublishTarget.id);
|
||||||
|
try {
|
||||||
|
await api.post(`/melodies/${unpublishTarget.id}/unpublish`);
|
||||||
|
setUnpublishTarget(null);
|
||||||
|
fetchMelodies();
|
||||||
|
} catch (err) {
|
||||||
|
setError(err.message);
|
||||||
|
setUnpublishTarget(null);
|
||||||
|
} finally {
|
||||||
|
setActionLoading(null);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
const toggleColumn = (key) => {
|
const toggleColumn = (key) => {
|
||||||
const col = ALL_COLUMNS.find((c) => c.key === key);
|
const col = ALL_COLUMNS.find((c) => c.key === key);
|
||||||
if (col?.alwaysOn) return;
|
if (col?.alwaysOn) return;
|
||||||
@@ -142,6 +174,18 @@ export default function MelodyList() {
|
|||||||
const info = row.information || {};
|
const info = row.information || {};
|
||||||
const ds = row.default_settings || {};
|
const ds = row.default_settings || {};
|
||||||
switch (key) {
|
switch (key) {
|
||||||
|
case "status":
|
||||||
|
return (
|
||||||
|
<span
|
||||||
|
className="px-2 py-0.5 text-xs font-semibold rounded-full"
|
||||||
|
style={row.status === "published"
|
||||||
|
? { backgroundColor: "rgba(22,163,74,0.15)", color: "#22c55e" }
|
||||||
|
: { backgroundColor: "rgba(156,163,175,0.15)", color: "#9ca3af" }
|
||||||
|
}
|
||||||
|
>
|
||||||
|
{row.status === "published" ? "Live" : "Draft"}
|
||||||
|
</span>
|
||||||
|
);
|
||||||
case "color":
|
case "color":
|
||||||
return info.color ? (
|
return info.color ? (
|
||||||
<span
|
<span
|
||||||
@@ -293,6 +337,15 @@ export default function MelodyList() {
|
|||||||
</option>
|
</option>
|
||||||
))}
|
))}
|
||||||
</select>
|
</select>
|
||||||
|
<select
|
||||||
|
value={statusFilter}
|
||||||
|
onChange={(e) => setStatusFilter(e.target.value)}
|
||||||
|
className={selectClass}
|
||||||
|
>
|
||||||
|
<option value="">All Statuses</option>
|
||||||
|
<option value="published">Published (Live)</option>
|
||||||
|
<option value="draft">Drafts</option>
|
||||||
|
</select>
|
||||||
{languages.length > 1 && (
|
{languages.length > 1 && (
|
||||||
<select
|
<select
|
||||||
value={displayLang}
|
value={displayLang}
|
||||||
@@ -440,6 +493,25 @@ export default function MelodyList() {
|
|||||||
className="flex gap-2"
|
className="flex gap-2"
|
||||||
onClick={(e) => e.stopPropagation()}
|
onClick={(e) => e.stopPropagation()}
|
||||||
>
|
>
|
||||||
|
{row.status === "draft" ? (
|
||||||
|
<button
|
||||||
|
onClick={() => handlePublish(row)}
|
||||||
|
disabled={actionLoading === row.id}
|
||||||
|
className="text-xs cursor-pointer disabled:opacity-50"
|
||||||
|
style={{ color: "#22c55e" }}
|
||||||
|
>
|
||||||
|
{actionLoading === row.id ? "..." : "Publish"}
|
||||||
|
</button>
|
||||||
|
) : (
|
||||||
|
<button
|
||||||
|
onClick={() => setUnpublishTarget(row)}
|
||||||
|
disabled={actionLoading === row.id}
|
||||||
|
className="text-xs cursor-pointer disabled:opacity-50"
|
||||||
|
style={{ color: "#ea580c" }}
|
||||||
|
>
|
||||||
|
Unpublish
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
<button
|
<button
|
||||||
onClick={() => navigate(`/melodies/${row.id}/edit`)}
|
onClick={() => navigate(`/melodies/${row.id}/edit`)}
|
||||||
className="text-xs cursor-pointer"
|
className="text-xs cursor-pointer"
|
||||||
@@ -472,6 +544,14 @@ export default function MelodyList() {
|
|||||||
onConfirm={handleDelete}
|
onConfirm={handleDelete}
|
||||||
onCancel={() => setDeleteTarget(null)}
|
onCancel={() => setDeleteTarget(null)}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
|
<ConfirmDialog
|
||||||
|
open={!!unpublishTarget}
|
||||||
|
title="Unpublish Melody"
|
||||||
|
message={`This melody may be in use by devices. Unpublishing will remove "${getDisplayName(unpublishTarget?.information?.name)}" from Firestore and devices will no longer have access. The melody will be kept as a draft. Continue?`}
|
||||||
|
onConfirm={handleUnpublish}
|
||||||
|
onCancel={() => setUnpublishTarget(null)}
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user