Phase 4 Complete by Claude Code
This commit is contained in:
@@ -6,6 +6,7 @@ from auth.router import router as auth_router
|
|||||||
from melodies.router import router as melodies_router
|
from melodies.router import router as melodies_router
|
||||||
from devices.router import router as devices_router
|
from devices.router import router as devices_router
|
||||||
from settings.router import router as settings_router
|
from settings.router import router as settings_router
|
||||||
|
from users.router import router as users_router
|
||||||
|
|
||||||
app = FastAPI(
|
app = FastAPI(
|
||||||
title="BellSystems Admin Panel",
|
title="BellSystems Admin Panel",
|
||||||
@@ -26,6 +27,7 @@ app.include_router(auth_router)
|
|||||||
app.include_router(melodies_router)
|
app.include_router(melodies_router)
|
||||||
app.include_router(devices_router)
|
app.include_router(devices_router)
|
||||||
app.include_router(settings_router)
|
app.include_router(settings_router)
|
||||||
|
app.include_router(users_router)
|
||||||
|
|
||||||
|
|
||||||
@app.on_event("startup")
|
@app.on_event("startup")
|
||||||
|
|||||||
@@ -1 +1,43 @@
|
|||||||
# TODO: User Pydantic schemas
|
from pydantic import BaseModel
|
||||||
|
from typing import List, Optional
|
||||||
|
|
||||||
|
|
||||||
|
# --- Request / Response schemas ---
|
||||||
|
|
||||||
|
class UserCreate(BaseModel):
|
||||||
|
email: str = ""
|
||||||
|
display_name: str = ""
|
||||||
|
photo_url: str = ""
|
||||||
|
uid: str = ""
|
||||||
|
phone_number: str = ""
|
||||||
|
status: str = ""
|
||||||
|
bio: str = ""
|
||||||
|
userTitle: str = ""
|
||||||
|
settingsPIN: str = ""
|
||||||
|
quickSettingsPIN: str = ""
|
||||||
|
|
||||||
|
|
||||||
|
class UserUpdate(BaseModel):
|
||||||
|
email: Optional[str] = None
|
||||||
|
display_name: Optional[str] = None
|
||||||
|
photo_url: Optional[str] = None
|
||||||
|
phone_number: Optional[str] = None
|
||||||
|
status: Optional[str] = None
|
||||||
|
bio: Optional[str] = None
|
||||||
|
userTitle: Optional[str] = None
|
||||||
|
settingsPIN: Optional[str] = None
|
||||||
|
quickSettingsPIN: Optional[str] = None
|
||||||
|
|
||||||
|
|
||||||
|
class UserInDB(UserCreate):
|
||||||
|
id: str
|
||||||
|
created_time: str = ""
|
||||||
|
lastActive: str = ""
|
||||||
|
createdAt: str = ""
|
||||||
|
friendsList: List[str] = []
|
||||||
|
friendsInvited: List[str] = []
|
||||||
|
|
||||||
|
|
||||||
|
class UserListResponse(BaseModel):
|
||||||
|
users: List[UserInDB]
|
||||||
|
total: int
|
||||||
|
|||||||
@@ -1 +1,95 @@
|
|||||||
# TODO: CRUD endpoints for users
|
from fastapi import APIRouter, Depends, Query
|
||||||
|
from typing import Optional, List
|
||||||
|
from auth.models import TokenPayload
|
||||||
|
from auth.dependencies import require_user_access, require_viewer
|
||||||
|
from users.models import (
|
||||||
|
UserCreate, UserUpdate, UserInDB, UserListResponse,
|
||||||
|
)
|
||||||
|
from users import service
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/api/users", tags=["users"])
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("", response_model=UserListResponse)
|
||||||
|
async def list_users(
|
||||||
|
search: Optional[str] = Query(None),
|
||||||
|
status: Optional[str] = Query(None),
|
||||||
|
_user: TokenPayload = Depends(require_viewer),
|
||||||
|
):
|
||||||
|
users = service.list_users(search=search, status=status)
|
||||||
|
return UserListResponse(users=users, total=len(users))
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/{user_id}", response_model=UserInDB)
|
||||||
|
async def get_user(
|
||||||
|
user_id: str,
|
||||||
|
_user: TokenPayload = Depends(require_viewer),
|
||||||
|
):
|
||||||
|
return service.get_user(user_id)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("", response_model=UserInDB, status_code=201)
|
||||||
|
async def create_user(
|
||||||
|
body: UserCreate,
|
||||||
|
_user: TokenPayload = Depends(require_user_access),
|
||||||
|
):
|
||||||
|
return service.create_user(body)
|
||||||
|
|
||||||
|
|
||||||
|
@router.put("/{user_id}", response_model=UserInDB)
|
||||||
|
async def update_user(
|
||||||
|
user_id: str,
|
||||||
|
body: UserUpdate,
|
||||||
|
_user: TokenPayload = Depends(require_user_access),
|
||||||
|
):
|
||||||
|
return service.update_user(user_id, body)
|
||||||
|
|
||||||
|
|
||||||
|
@router.delete("/{user_id}", status_code=204)
|
||||||
|
async def delete_user(
|
||||||
|
user_id: str,
|
||||||
|
_user: TokenPayload = Depends(require_user_access),
|
||||||
|
):
|
||||||
|
service.delete_user(user_id)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/{user_id}/block", response_model=UserInDB)
|
||||||
|
async def block_user(
|
||||||
|
user_id: str,
|
||||||
|
_user: TokenPayload = Depends(require_user_access),
|
||||||
|
):
|
||||||
|
return service.block_user(user_id)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/{user_id}/unblock", response_model=UserInDB)
|
||||||
|
async def unblock_user(
|
||||||
|
user_id: str,
|
||||||
|
_user: TokenPayload = Depends(require_user_access),
|
||||||
|
):
|
||||||
|
return service.unblock_user(user_id)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/{user_id}/devices", response_model=List[dict])
|
||||||
|
async def get_user_devices(
|
||||||
|
user_id: str,
|
||||||
|
_user: TokenPayload = Depends(require_viewer),
|
||||||
|
):
|
||||||
|
return service.get_user_devices(user_id)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/{user_id}/devices/{device_id}", response_model=UserInDB)
|
||||||
|
async def assign_device(
|
||||||
|
user_id: str,
|
||||||
|
device_id: str,
|
||||||
|
_user: TokenPayload = Depends(require_user_access),
|
||||||
|
):
|
||||||
|
return service.assign_device(user_id, device_id)
|
||||||
|
|
||||||
|
|
||||||
|
@router.delete("/{user_id}/devices/{device_id}", response_model=UserInDB)
|
||||||
|
async def unassign_device(
|
||||||
|
user_id: str,
|
||||||
|
device_id: str,
|
||||||
|
_user: TokenPayload = Depends(require_user_access),
|
||||||
|
):
|
||||||
|
return service.unassign_device(user_id, device_id)
|
||||||
|
|||||||
@@ -1 +1,252 @@
|
|||||||
# TODO: User Firestore operations
|
from datetime import datetime
|
||||||
|
|
||||||
|
from google.cloud.firestore_v1 import DocumentReference
|
||||||
|
|
||||||
|
from shared.firebase import get_db
|
||||||
|
from shared.exceptions import NotFoundError
|
||||||
|
from users.models import UserCreate, UserUpdate, UserInDB
|
||||||
|
|
||||||
|
COLLECTION = "users"
|
||||||
|
|
||||||
|
|
||||||
|
def _convert_firestore_value(val):
|
||||||
|
"""Convert Firestore-specific types (Timestamp, DocumentReference) to strings."""
|
||||||
|
if isinstance(val, datetime):
|
||||||
|
return val.strftime("%d %B %Y at %H:%M:%S UTC%z")
|
||||||
|
if isinstance(val, DocumentReference):
|
||||||
|
return val.path
|
||||||
|
return val
|
||||||
|
|
||||||
|
|
||||||
|
def _sanitize_dict(d: dict) -> dict:
|
||||||
|
"""Recursively convert Firestore-native types in a dict to plain strings."""
|
||||||
|
result = {}
|
||||||
|
for k, v in d.items():
|
||||||
|
if isinstance(v, dict):
|
||||||
|
result[k] = _sanitize_dict(v)
|
||||||
|
elif isinstance(v, list):
|
||||||
|
result[k] = [
|
||||||
|
_sanitize_dict(item) if isinstance(item, dict)
|
||||||
|
else _convert_firestore_value(item)
|
||||||
|
for item in v
|
||||||
|
]
|
||||||
|
else:
|
||||||
|
result[k] = _convert_firestore_value(v)
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
def _doc_to_user(doc) -> UserInDB:
|
||||||
|
"""Convert a Firestore document snapshot to a UserInDB model."""
|
||||||
|
data = _sanitize_dict(doc.to_dict())
|
||||||
|
return UserInDB(id=doc.id, **data)
|
||||||
|
|
||||||
|
|
||||||
|
def list_users(
|
||||||
|
search: str | None = None,
|
||||||
|
status: str | None = None,
|
||||||
|
) -> list[UserInDB]:
|
||||||
|
"""List users with optional filters."""
|
||||||
|
db = get_db()
|
||||||
|
ref = db.collection(COLLECTION)
|
||||||
|
query = ref
|
||||||
|
|
||||||
|
if status:
|
||||||
|
query = query.where("status", "==", status)
|
||||||
|
|
||||||
|
docs = query.stream()
|
||||||
|
results = []
|
||||||
|
|
||||||
|
for doc in docs:
|
||||||
|
user = _doc_to_user(doc)
|
||||||
|
|
||||||
|
if search:
|
||||||
|
search_lower = search.lower()
|
||||||
|
name_match = search_lower in (user.display_name or "").lower()
|
||||||
|
email_match = search_lower in (user.email or "").lower()
|
||||||
|
phone_match = search_lower in (user.phone_number or "").lower()
|
||||||
|
uid_match = search_lower in (user.uid or "").lower()
|
||||||
|
if not (name_match or email_match or phone_match or uid_match):
|
||||||
|
continue
|
||||||
|
|
||||||
|
results.append(user)
|
||||||
|
|
||||||
|
return results
|
||||||
|
|
||||||
|
|
||||||
|
def get_user(user_doc_id: str) -> UserInDB:
|
||||||
|
"""Get a single user by Firestore document ID."""
|
||||||
|
db = get_db()
|
||||||
|
doc = db.collection(COLLECTION).document(user_doc_id).get()
|
||||||
|
if not doc.exists:
|
||||||
|
raise NotFoundError("User")
|
||||||
|
return _doc_to_user(doc)
|
||||||
|
|
||||||
|
|
||||||
|
def create_user(data: UserCreate) -> UserInDB:
|
||||||
|
"""Create a new user document in Firestore."""
|
||||||
|
db = get_db()
|
||||||
|
doc_data = data.model_dump()
|
||||||
|
doc_data["friendsList"] = []
|
||||||
|
doc_data["friendsInvited"] = []
|
||||||
|
|
||||||
|
_, doc_ref = db.collection(COLLECTION).add(doc_data)
|
||||||
|
|
||||||
|
return UserInDB(id=doc_ref.id, **doc_data)
|
||||||
|
|
||||||
|
|
||||||
|
def update_user(user_doc_id: str, data: UserUpdate) -> UserInDB:
|
||||||
|
"""Update an existing user document. Only provided fields are updated."""
|
||||||
|
db = get_db()
|
||||||
|
doc_ref = db.collection(COLLECTION).document(user_doc_id)
|
||||||
|
doc = doc_ref.get()
|
||||||
|
if not doc.exists:
|
||||||
|
raise NotFoundError("User")
|
||||||
|
|
||||||
|
update_data = data.model_dump(exclude_none=True)
|
||||||
|
doc_ref.update(update_data)
|
||||||
|
|
||||||
|
updated_doc = doc_ref.get()
|
||||||
|
return _doc_to_user(updated_doc)
|
||||||
|
|
||||||
|
|
||||||
|
def delete_user(user_doc_id: str) -> None:
|
||||||
|
"""Delete a user document from Firestore."""
|
||||||
|
db = get_db()
|
||||||
|
doc_ref = db.collection(COLLECTION).document(user_doc_id)
|
||||||
|
doc = doc_ref.get()
|
||||||
|
if not doc.exists:
|
||||||
|
raise NotFoundError("User")
|
||||||
|
|
||||||
|
doc_ref.delete()
|
||||||
|
|
||||||
|
|
||||||
|
def block_user(user_doc_id: str) -> UserInDB:
|
||||||
|
"""Block a user by setting their status to 'blocked'."""
|
||||||
|
db = get_db()
|
||||||
|
doc_ref = db.collection(COLLECTION).document(user_doc_id)
|
||||||
|
doc = doc_ref.get()
|
||||||
|
if not doc.exists:
|
||||||
|
raise NotFoundError("User")
|
||||||
|
|
||||||
|
doc_ref.update({"status": "blocked"})
|
||||||
|
updated_doc = doc_ref.get()
|
||||||
|
return _doc_to_user(updated_doc)
|
||||||
|
|
||||||
|
|
||||||
|
def unblock_user(user_doc_id: str) -> UserInDB:
|
||||||
|
"""Unblock a user by setting their status to 'active'."""
|
||||||
|
db = get_db()
|
||||||
|
doc_ref = db.collection(COLLECTION).document(user_doc_id)
|
||||||
|
doc = doc_ref.get()
|
||||||
|
if not doc.exists:
|
||||||
|
raise NotFoundError("User")
|
||||||
|
|
||||||
|
doc_ref.update({"status": "active"})
|
||||||
|
updated_doc = doc_ref.get()
|
||||||
|
return _doc_to_user(updated_doc)
|
||||||
|
|
||||||
|
|
||||||
|
def assign_device(user_doc_id: str, device_doc_id: str) -> UserInDB:
|
||||||
|
"""Assign a device to a user by adding user ref to device's user_list."""
|
||||||
|
db = get_db()
|
||||||
|
|
||||||
|
# Verify user exists
|
||||||
|
user_ref = db.collection(COLLECTION).document(user_doc_id)
|
||||||
|
user_doc = user_ref.get()
|
||||||
|
if not user_doc.exists:
|
||||||
|
raise NotFoundError("User")
|
||||||
|
|
||||||
|
# Verify device exists
|
||||||
|
device_ref = db.collection("devices").document(device_doc_id)
|
||||||
|
device_doc = device_ref.get()
|
||||||
|
if not device_doc.exists:
|
||||||
|
raise NotFoundError("Device")
|
||||||
|
|
||||||
|
# Add user path to device's user_list if not already there
|
||||||
|
device_data = device_doc.to_dict()
|
||||||
|
user_list = device_data.get("user_list", [])
|
||||||
|
user_path = f"users/{user_doc_id}"
|
||||||
|
|
||||||
|
# Check if already assigned (handle both string paths and DocumentReferences)
|
||||||
|
already_assigned = False
|
||||||
|
for entry in user_list:
|
||||||
|
if isinstance(entry, DocumentReference):
|
||||||
|
if entry.path == user_path:
|
||||||
|
already_assigned = True
|
||||||
|
break
|
||||||
|
elif entry == user_path:
|
||||||
|
already_assigned = True
|
||||||
|
break
|
||||||
|
|
||||||
|
if not already_assigned:
|
||||||
|
user_list.append(user_path)
|
||||||
|
device_ref.update({"user_list": user_list})
|
||||||
|
|
||||||
|
return _doc_to_user(user_ref.get())
|
||||||
|
|
||||||
|
|
||||||
|
def unassign_device(user_doc_id: str, device_doc_id: str) -> UserInDB:
|
||||||
|
"""Remove a user from a device's user_list."""
|
||||||
|
db = get_db()
|
||||||
|
|
||||||
|
# Verify user exists
|
||||||
|
user_ref = db.collection(COLLECTION).document(user_doc_id)
|
||||||
|
user_doc = user_ref.get()
|
||||||
|
if not user_doc.exists:
|
||||||
|
raise NotFoundError("User")
|
||||||
|
|
||||||
|
# Verify device exists
|
||||||
|
device_ref = db.collection("devices").document(device_doc_id)
|
||||||
|
device_doc = device_ref.get()
|
||||||
|
if not device_doc.exists:
|
||||||
|
raise NotFoundError("Device")
|
||||||
|
|
||||||
|
# Remove user from device's user_list
|
||||||
|
device_data = device_doc.to_dict()
|
||||||
|
user_list = device_data.get("user_list", [])
|
||||||
|
user_path = f"users/{user_doc_id}"
|
||||||
|
|
||||||
|
new_list = []
|
||||||
|
for entry in user_list:
|
||||||
|
if isinstance(entry, DocumentReference):
|
||||||
|
if entry.path != user_path:
|
||||||
|
new_list.append(entry)
|
||||||
|
elif entry != user_path:
|
||||||
|
new_list.append(entry)
|
||||||
|
|
||||||
|
device_ref.update({"user_list": new_list})
|
||||||
|
|
||||||
|
return _doc_to_user(user_ref.get())
|
||||||
|
|
||||||
|
|
||||||
|
def get_user_devices(user_doc_id: str) -> list[dict]:
|
||||||
|
"""Get all devices assigned to a user."""
|
||||||
|
db = get_db()
|
||||||
|
|
||||||
|
# Verify user exists
|
||||||
|
user_ref = db.collection(COLLECTION).document(user_doc_id)
|
||||||
|
user_doc = user_ref.get()
|
||||||
|
if not user_doc.exists:
|
||||||
|
raise NotFoundError("User")
|
||||||
|
|
||||||
|
user_path = f"users/{user_doc_id}"
|
||||||
|
|
||||||
|
# Search all devices for this user in their user_list
|
||||||
|
devices = []
|
||||||
|
for doc in db.collection("devices").stream():
|
||||||
|
data = doc.to_dict()
|
||||||
|
user_list = data.get("user_list", [])
|
||||||
|
|
||||||
|
for entry in user_list:
|
||||||
|
entry_path = entry.path if isinstance(entry, DocumentReference) else entry
|
||||||
|
if entry_path == user_path:
|
||||||
|
devices.append({
|
||||||
|
"id": doc.id,
|
||||||
|
"device_name": data.get("device_name", ""),
|
||||||
|
"device_id": data.get("device_id", ""),
|
||||||
|
"device_location": data.get("device_location", ""),
|
||||||
|
"is_Online": data.get("is_Online", False),
|
||||||
|
})
|
||||||
|
break
|
||||||
|
|
||||||
|
return devices
|
||||||
|
|||||||
@@ -9,6 +9,9 @@ import MelodySettings from "./melodies/MelodySettings";
|
|||||||
import DeviceList from "./devices/DeviceList";
|
import DeviceList from "./devices/DeviceList";
|
||||||
import DeviceDetail from "./devices/DeviceDetail";
|
import DeviceDetail from "./devices/DeviceDetail";
|
||||||
import DeviceForm from "./devices/DeviceForm";
|
import DeviceForm from "./devices/DeviceForm";
|
||||||
|
import UserList from "./users/UserList";
|
||||||
|
import UserDetail from "./users/UserDetail";
|
||||||
|
import UserForm from "./users/UserForm";
|
||||||
|
|
||||||
function ProtectedRoute({ children }) {
|
function ProtectedRoute({ children }) {
|
||||||
const { user, loading } = useAuth();
|
const { user, loading } = useAuth();
|
||||||
@@ -62,8 +65,11 @@ export default function App() {
|
|||||||
<Route path="devices/new" element={<DeviceForm />} />
|
<Route path="devices/new" element={<DeviceForm />} />
|
||||||
<Route path="devices/:id" element={<DeviceDetail />} />
|
<Route path="devices/:id" element={<DeviceDetail />} />
|
||||||
<Route path="devices/:id/edit" element={<DeviceForm />} />
|
<Route path="devices/:id/edit" element={<DeviceForm />} />
|
||||||
{/* Phase 4+ routes:
|
|
||||||
<Route path="users" element={<UserList />} />
|
<Route path="users" element={<UserList />} />
|
||||||
|
<Route path="users/new" element={<UserForm />} />
|
||||||
|
<Route path="users/:id" element={<UserDetail />} />
|
||||||
|
<Route path="users/:id/edit" element={<UserForm />} />
|
||||||
|
{/* Phase 5+ routes:
|
||||||
<Route path="mqtt" element={<MqttDashboard />} />
|
<Route path="mqtt" element={<MqttDashboard />} />
|
||||||
*/}
|
*/}
|
||||||
<Route path="*" element={<Navigate to="/" replace />} />
|
<Route path="*" element={<Navigate to="/" replace />} />
|
||||||
|
|||||||
@@ -18,8 +18,8 @@
|
|||||||
--text-secondary: #9ca3af;
|
--text-secondary: #9ca3af;
|
||||||
--text-muted: #9ca3af;
|
--text-muted: #9ca3af;
|
||||||
--text-heading: #e3e5ea;
|
--text-heading: #e3e5ea;
|
||||||
--text-white: #fbfbfb;
|
--text-white: #ffffff;
|
||||||
--text-link: #93befa;
|
--text-link: #589cfa;
|
||||||
|
|
||||||
--accent: #74b816;
|
--accent: #74b816;
|
||||||
--accent-hover: #82c91e;
|
--accent-hover: #82c91e;
|
||||||
@@ -114,6 +114,35 @@ input[type="checkbox"] {
|
|||||||
/* Range slider */
|
/* Range slider */
|
||||||
input[type="range"] {
|
input[type="range"] {
|
||||||
accent-color: var(--accent) !important;
|
accent-color: var(--accent) !important;
|
||||||
|
-webkit-appearance: none;
|
||||||
|
appearance: none;
|
||||||
|
height: 6px;
|
||||||
|
border-radius: 4px;
|
||||||
|
background: var(--border-primary);
|
||||||
|
outline: none;
|
||||||
|
}
|
||||||
|
input[type="range"]::-webkit-slider-thumb {
|
||||||
|
-webkit-appearance: none;
|
||||||
|
appearance: none;
|
||||||
|
width: 18px;
|
||||||
|
height: 18px;
|
||||||
|
border-radius: 50%;
|
||||||
|
background: var(--accent);
|
||||||
|
cursor: pointer;
|
||||||
|
border: 2px solid var(--bg-primary);
|
||||||
|
}
|
||||||
|
input[type="range"]::-moz-range-track {
|
||||||
|
height: 6px;
|
||||||
|
border-radius: 4px;
|
||||||
|
background: var(--border-primary);
|
||||||
|
}
|
||||||
|
input[type="range"]::-moz-range-thumb {
|
||||||
|
width: 18px;
|
||||||
|
height: 18px;
|
||||||
|
border-radius: 50%;
|
||||||
|
background: var(--accent);
|
||||||
|
cursor: pointer;
|
||||||
|
border: 2px solid var(--bg-primary);
|
||||||
}
|
}
|
||||||
|
|
||||||
/* File input */
|
/* File input */
|
||||||
|
|||||||
@@ -1 +1,488 @@
|
|||||||
// TODO: User 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 uppercase tracking-wide"
|
||||||
|
style={{ color: "var(--text-muted)" }}
|
||||||
|
>
|
||||||
|
{label}
|
||||||
|
</dt>
|
||||||
|
<dd className="mt-1 text-sm" style={{ color: "var(--text-primary)" }}>
|
||||||
|
{children || "-"}
|
||||||
|
</dd>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function UserDetail() {
|
||||||
|
const { id } = useParams();
|
||||||
|
const navigate = useNavigate();
|
||||||
|
const { hasRole } = useAuth();
|
||||||
|
const canEdit = hasRole("superadmin", "user_manager");
|
||||||
|
|
||||||
|
const [user, setUser] = useState(null);
|
||||||
|
const [devices, setDevices] = useState([]);
|
||||||
|
const [allDevices, setAllDevices] = useState([]);
|
||||||
|
const [loading, setLoading] = useState(true);
|
||||||
|
const [error, setError] = useState("");
|
||||||
|
const [showDelete, setShowDelete] = useState(false);
|
||||||
|
const [blocking, setBlocking] = useState(false);
|
||||||
|
const [assigningDevice, setAssigningDevice] = useState(false);
|
||||||
|
const [selectedDeviceId, setSelectedDeviceId] = useState("");
|
||||||
|
const [showAssignPanel, setShowAssignPanel] = useState(false);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
loadData();
|
||||||
|
}, [id]);
|
||||||
|
|
||||||
|
const loadData = async () => {
|
||||||
|
setLoading(true);
|
||||||
|
try {
|
||||||
|
const [u, d] = await Promise.all([
|
||||||
|
api.get(`/users/${id}`),
|
||||||
|
api.get(`/users/${id}/devices`),
|
||||||
|
]);
|
||||||
|
setUser(u);
|
||||||
|
setDevices(d);
|
||||||
|
} catch (err) {
|
||||||
|
setError(err.message);
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const loadAllDevices = async () => {
|
||||||
|
try {
|
||||||
|
const data = await api.get("/devices");
|
||||||
|
setAllDevices(data.devices || []);
|
||||||
|
} catch (err) {
|
||||||
|
setError(err.message);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleDelete = async () => {
|
||||||
|
try {
|
||||||
|
await api.delete(`/users/${id}`);
|
||||||
|
navigate("/users");
|
||||||
|
} catch (err) {
|
||||||
|
setError(err.message);
|
||||||
|
setShowDelete(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleBlockToggle = async () => {
|
||||||
|
setBlocking(true);
|
||||||
|
setError("");
|
||||||
|
try {
|
||||||
|
const endpoint = user.status === "blocked"
|
||||||
|
? `/users/${id}/unblock`
|
||||||
|
: `/users/${id}/block`;
|
||||||
|
const updated = await api.post(endpoint);
|
||||||
|
setUser(updated);
|
||||||
|
} catch (err) {
|
||||||
|
setError(err.message);
|
||||||
|
} finally {
|
||||||
|
setBlocking(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleAssignDevice = async () => {
|
||||||
|
if (!selectedDeviceId) return;
|
||||||
|
setAssigningDevice(true);
|
||||||
|
setError("");
|
||||||
|
try {
|
||||||
|
await api.post(`/users/${id}/devices/${selectedDeviceId}`);
|
||||||
|
setSelectedDeviceId("");
|
||||||
|
setShowAssignPanel(false);
|
||||||
|
const d = await api.get(`/users/${id}/devices`);
|
||||||
|
setDevices(d);
|
||||||
|
} catch (err) {
|
||||||
|
setError(err.message);
|
||||||
|
} finally {
|
||||||
|
setAssigningDevice(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleUnassignDevice = async (deviceId) => {
|
||||||
|
setError("");
|
||||||
|
try {
|
||||||
|
await api.delete(`/users/${id}/devices/${deviceId}`);
|
||||||
|
const d = await api.get(`/users/${id}/devices`);
|
||||||
|
setDevices(d);
|
||||||
|
} catch (err) {
|
||||||
|
setError(err.message);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const openAssignPanel = () => {
|
||||||
|
setShowAssignPanel(true);
|
||||||
|
loadAllDevices();
|
||||||
|
};
|
||||||
|
|
||||||
|
if (loading) {
|
||||||
|
return (
|
||||||
|
<div className="text-center py-8" style={{ color: "var(--text-muted)" }}>
|
||||||
|
Loading...
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (error && !user) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
className="text-sm rounded-md p-3 border"
|
||||||
|
style={{
|
||||||
|
backgroundColor: "var(--danger-bg)",
|
||||||
|
borderColor: "var(--danger)",
|
||||||
|
color: "var(--danger-text)",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{error}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!user) return null;
|
||||||
|
|
||||||
|
const isBlocked = user.status === "blocked";
|
||||||
|
|
||||||
|
const assignedDeviceIds = new Set(devices.map((d) => d.id));
|
||||||
|
const availableDevices = allDevices.filter((d) => !assignedDeviceIds.has(d.id));
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
<div className="flex items-center justify-between mb-6">
|
||||||
|
<div>
|
||||||
|
<button
|
||||||
|
onClick={() => navigate("/users")}
|
||||||
|
className="text-sm hover:underline mb-2 inline-block"
|
||||||
|
style={{ color: "var(--accent)" }}
|
||||||
|
>
|
||||||
|
← Back to Users
|
||||||
|
</button>
|
||||||
|
<div className="flex items-center gap-3">
|
||||||
|
<h1
|
||||||
|
className="text-2xl font-bold"
|
||||||
|
style={{ color: "var(--text-heading)" }}
|
||||||
|
>
|
||||||
|
{user.display_name || "Unnamed User"}
|
||||||
|
</h1>
|
||||||
|
<span
|
||||||
|
className="px-2 py-0.5 text-xs rounded-full"
|
||||||
|
style={
|
||||||
|
isBlocked
|
||||||
|
? { backgroundColor: "var(--danger-bg)", color: "var(--danger-text)" }
|
||||||
|
: user.status === "active"
|
||||||
|
? { backgroundColor: "var(--success-bg)", color: "var(--success-text)" }
|
||||||
|
: { backgroundColor: "var(--bg-card-hover)", color: "var(--text-muted)" }
|
||||||
|
}
|
||||||
|
>
|
||||||
|
{user.status || "unknown"}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{canEdit && (
|
||||||
|
<div className="flex gap-2">
|
||||||
|
<button
|
||||||
|
onClick={handleBlockToggle}
|
||||||
|
disabled={blocking}
|
||||||
|
className="px-4 py-2 text-sm rounded-md transition-colors disabled:opacity-50"
|
||||||
|
style={
|
||||||
|
isBlocked
|
||||||
|
? { backgroundColor: "var(--success)", color: "var(--text-white)" }
|
||||||
|
: { backgroundColor: "var(--warning, #f59e0b)", color: "var(--text-white)" }
|
||||||
|
}
|
||||||
|
>
|
||||||
|
{blocking ? "..." : isBlocked ? "Unblock" : "Block"}
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={() => navigate(`/users/${id}/edit`)}
|
||||||
|
className="px-4 py-2 text-sm rounded-md transition-colors"
|
||||||
|
style={{ backgroundColor: "var(--text-link)", color: "var(--text-white)" }}
|
||||||
|
>
|
||||||
|
Edit
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={() => setShowDelete(true)}
|
||||||
|
className="px-4 py-2 text-sm rounded-md transition-colors"
|
||||||
|
style={{ backgroundColor: "var(--danger)", color: "var(--text-white)" }}
|
||||||
|
>
|
||||||
|
Delete
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{error && (
|
||||||
|
<div
|
||||||
|
className="text-sm rounded-md p-3 mb-4 border"
|
||||||
|
style={{
|
||||||
|
backgroundColor: "var(--danger-bg)",
|
||||||
|
borderColor: "var(--danger)",
|
||||||
|
color: "var(--danger-text)",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{error}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<div className="grid grid-cols-1 xl:grid-cols-2 gap-6">
|
||||||
|
{/* Left column */}
|
||||||
|
<div className="space-y-6">
|
||||||
|
{/* Account Info */}
|
||||||
|
<section
|
||||||
|
className="rounded-lg border p-6"
|
||||||
|
style={{ backgroundColor: "var(--bg-card)", borderColor: "var(--border-primary)" }}
|
||||||
|
>
|
||||||
|
<h2
|
||||||
|
className="text-lg font-semibold mb-4"
|
||||||
|
style={{ color: "var(--text-heading)" }}
|
||||||
|
>
|
||||||
|
Account Information
|
||||||
|
</h2>
|
||||||
|
<dl className="grid grid-cols-2 md:grid-cols-3 gap-4">
|
||||||
|
<Field label="Document ID">
|
||||||
|
<span className="font-mono text-xs" style={{ color: "var(--text-muted)" }}>
|
||||||
|
{user.id}
|
||||||
|
</span>
|
||||||
|
</Field>
|
||||||
|
<Field label="UID">
|
||||||
|
<span className="font-mono text-xs">{user.uid}</span>
|
||||||
|
</Field>
|
||||||
|
<Field label="Status">
|
||||||
|
<span
|
||||||
|
className="px-2 py-0.5 text-xs rounded-full"
|
||||||
|
style={
|
||||||
|
isBlocked
|
||||||
|
? { backgroundColor: "var(--danger-bg)", color: "var(--danger-text)" }
|
||||||
|
: user.status === "active"
|
||||||
|
? { backgroundColor: "var(--success-bg)", color: "var(--success-text)" }
|
||||||
|
: { backgroundColor: "var(--bg-card-hover)", color: "var(--text-muted)" }
|
||||||
|
}
|
||||||
|
>
|
||||||
|
{user.status || "unknown"}
|
||||||
|
</span>
|
||||||
|
</Field>
|
||||||
|
<Field label="Email">{user.email}</Field>
|
||||||
|
<Field label="Phone">{user.phone_number}</Field>
|
||||||
|
<Field label="Title">{user.userTitle}</Field>
|
||||||
|
</dl>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
{/* Profile */}
|
||||||
|
<section
|
||||||
|
className="rounded-lg border p-6"
|
||||||
|
style={{ backgroundColor: "var(--bg-card)", borderColor: "var(--border-primary)" }}
|
||||||
|
>
|
||||||
|
<h2
|
||||||
|
className="text-lg font-semibold mb-4"
|
||||||
|
style={{ color: "var(--text-heading)" }}
|
||||||
|
>
|
||||||
|
Profile
|
||||||
|
</h2>
|
||||||
|
<dl className="grid grid-cols-1 gap-4">
|
||||||
|
<Field label="Bio">{user.bio}</Field>
|
||||||
|
<Field label="Photo URL">{user.photo_url}</Field>
|
||||||
|
</dl>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
{/* Timestamps */}
|
||||||
|
<section
|
||||||
|
className="rounded-lg border p-6"
|
||||||
|
style={{ backgroundColor: "var(--bg-card)", borderColor: "var(--border-primary)" }}
|
||||||
|
>
|
||||||
|
<h2
|
||||||
|
className="text-lg font-semibold mb-4"
|
||||||
|
style={{ color: "var(--text-heading)" }}
|
||||||
|
>
|
||||||
|
Activity
|
||||||
|
</h2>
|
||||||
|
<dl className="grid grid-cols-2 md:grid-cols-3 gap-4">
|
||||||
|
<Field label="Created Time">{user.created_time}</Field>
|
||||||
|
<Field label="Created At">{user.createdAt}</Field>
|
||||||
|
<Field label="Last Active">{user.lastActive}</Field>
|
||||||
|
</dl>
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Right column */}
|
||||||
|
<div className="space-y-6">
|
||||||
|
{/* Security */}
|
||||||
|
<section
|
||||||
|
className="rounded-lg border p-6"
|
||||||
|
style={{ backgroundColor: "var(--bg-card)", borderColor: "var(--border-primary)" }}
|
||||||
|
>
|
||||||
|
<h2
|
||||||
|
className="text-lg font-semibold mb-4"
|
||||||
|
style={{ color: "var(--text-heading)" }}
|
||||||
|
>
|
||||||
|
Security
|
||||||
|
</h2>
|
||||||
|
<dl className="grid grid-cols-2 gap-4">
|
||||||
|
<Field label="Settings PIN">{user.settingsPIN ? "****" : "-"}</Field>
|
||||||
|
<Field label="Quick Settings PIN">{user.quickSettingsPIN ? "****" : "-"}</Field>
|
||||||
|
</dl>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
{/* Friends */}
|
||||||
|
<section
|
||||||
|
className="rounded-lg border p-6"
|
||||||
|
style={{ backgroundColor: "var(--bg-card)", borderColor: "var(--border-primary)" }}
|
||||||
|
>
|
||||||
|
<h2
|
||||||
|
className="text-lg font-semibold mb-4"
|
||||||
|
style={{ color: "var(--text-heading)" }}
|
||||||
|
>
|
||||||
|
Friends
|
||||||
|
</h2>
|
||||||
|
<dl className="grid grid-cols-2 gap-4">
|
||||||
|
<Field label="Friends">
|
||||||
|
{user.friendsList?.length ?? 0}
|
||||||
|
</Field>
|
||||||
|
<Field label="Friends Invited">
|
||||||
|
{user.friendsInvited?.length ?? 0}
|
||||||
|
</Field>
|
||||||
|
</dl>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
{/* Assigned Devices */}
|
||||||
|
<section
|
||||||
|
className="rounded-lg border p-6"
|
||||||
|
style={{ backgroundColor: "var(--bg-card)", borderColor: "var(--border-primary)" }}
|
||||||
|
>
|
||||||
|
<div className="flex items-center justify-between mb-4">
|
||||||
|
<h2
|
||||||
|
className="text-lg font-semibold"
|
||||||
|
style={{ color: "var(--text-heading)" }}
|
||||||
|
>
|
||||||
|
Assigned Devices ({devices.length})
|
||||||
|
</h2>
|
||||||
|
{canEdit && (
|
||||||
|
<button
|
||||||
|
onClick={openAssignPanel}
|
||||||
|
className="px-3 py-1.5 text-xs rounded-md hover:opacity-90 transition-colors cursor-pointer"
|
||||||
|
style={{ backgroundColor: "var(--btn-primary)", color: "var(--text-white)" }}
|
||||||
|
>
|
||||||
|
Assign Device
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{showAssignPanel && (
|
||||||
|
<div
|
||||||
|
className="mb-4 p-3 rounded-md border"
|
||||||
|
style={{ backgroundColor: "var(--bg-primary)", borderColor: "var(--border-primary)" }}
|
||||||
|
>
|
||||||
|
<div className="flex gap-2 items-end">
|
||||||
|
<div className="flex-1">
|
||||||
|
<label className="block text-xs font-medium mb-1" style={{ color: "var(--text-secondary)" }}>
|
||||||
|
Select Device
|
||||||
|
</label>
|
||||||
|
<select
|
||||||
|
value={selectedDeviceId}
|
||||||
|
onChange={(e) => setSelectedDeviceId(e.target.value)}
|
||||||
|
className="w-full px-3 py-2 rounded-md text-sm border"
|
||||||
|
style={{
|
||||||
|
backgroundColor: "var(--bg-card)",
|
||||||
|
color: "var(--text-primary)",
|
||||||
|
borderColor: "var(--border-primary)",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<option value="">Choose a device...</option>
|
||||||
|
{availableDevices.map((d) => (
|
||||||
|
<option key={d.id} value={d.id}>
|
||||||
|
{d.device_name || "Unnamed"} ({d.device_id || d.id})
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
onClick={handleAssignDevice}
|
||||||
|
disabled={!selectedDeviceId || assigningDevice}
|
||||||
|
className="px-3 py-2 text-sm rounded-md hover:opacity-90 disabled:opacity-50 transition-colors"
|
||||||
|
style={{ backgroundColor: "var(--btn-primary)", color: "var(--text-white)" }}
|
||||||
|
>
|
||||||
|
{assigningDevice ? "..." : "Assign"}
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={() => { setShowAssignPanel(false); setSelectedDeviceId(""); }}
|
||||||
|
className="px-3 py-2 text-sm rounded-md hover:opacity-80 transition-colors"
|
||||||
|
style={{ backgroundColor: "var(--bg-card-hover)", color: "var(--text-primary)" }}
|
||||||
|
>
|
||||||
|
Cancel
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{devices.length === 0 ? (
|
||||||
|
<p className="text-sm" style={{ color: "var(--text-muted)" }}>
|
||||||
|
No devices assigned.
|
||||||
|
</p>
|
||||||
|
) : (
|
||||||
|
<div className="space-y-2">
|
||||||
|
{devices.map((device) => (
|
||||||
|
<div
|
||||||
|
key={device.id}
|
||||||
|
className="flex items-center justify-between p-3 rounded-md border"
|
||||||
|
style={{ backgroundColor: "var(--bg-primary)", borderColor: "var(--border-primary)" }}
|
||||||
|
>
|
||||||
|
<div className="flex items-center gap-3">
|
||||||
|
<span
|
||||||
|
className={`inline-block w-2.5 h-2.5 rounded-full ${
|
||||||
|
device.is_Online ? "bg-green-500" : ""
|
||||||
|
}`}
|
||||||
|
style={!device.is_Online ? { backgroundColor: "var(--border-primary)" } : undefined}
|
||||||
|
title={device.is_Online ? "Online" : "Offline"}
|
||||||
|
/>
|
||||||
|
<div>
|
||||||
|
<button
|
||||||
|
onClick={() => navigate(`/devices/${device.id}`)}
|
||||||
|
className="text-sm font-medium hover:underline"
|
||||||
|
style={{ color: "var(--text-link)" }}
|
||||||
|
>
|
||||||
|
{device.device_name || "Unnamed Device"}
|
||||||
|
</button>
|
||||||
|
<p className="text-xs font-mono" style={{ color: "var(--text-muted)" }}>
|
||||||
|
{device.device_id || device.id}
|
||||||
|
</p>
|
||||||
|
{device.device_location && (
|
||||||
|
<p className="text-xs" style={{ color: "var(--text-muted)" }}>
|
||||||
|
{device.device_location}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{canEdit && (
|
||||||
|
<button
|
||||||
|
onClick={() => handleUnassignDevice(device.id)}
|
||||||
|
className="text-xs hover:opacity-80 cursor-pointer"
|
||||||
|
style={{ color: "var(--danger)" }}
|
||||||
|
>
|
||||||
|
Remove
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<ConfirmDialog
|
||||||
|
open={showDelete}
|
||||||
|
title="Delete User"
|
||||||
|
message={`Are you sure you want to delete "${user.display_name || "this user"}" (${user.email})? This action cannot be undone.`}
|
||||||
|
onConfirm={handleDelete}
|
||||||
|
onCancel={() => setShowDelete(false)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|||||||
@@ -1 +1,296 @@
|
|||||||
// TODO: Add / Edit user form
|
import { useState, useEffect } from "react";
|
||||||
|
import { useNavigate, useParams } from "react-router-dom";
|
||||||
|
import api from "../api/client";
|
||||||
|
|
||||||
|
export default function UserForm() {
|
||||||
|
const { id } = useParams();
|
||||||
|
const isEdit = Boolean(id);
|
||||||
|
const navigate = useNavigate();
|
||||||
|
|
||||||
|
const [email, setEmail] = useState("");
|
||||||
|
const [displayName, setDisplayName] = useState("");
|
||||||
|
const [photoUrl, setPhotoUrl] = useState("");
|
||||||
|
const [uid, setUid] = useState("");
|
||||||
|
const [phoneNumber, setPhoneNumber] = useState("");
|
||||||
|
const [status, setStatus] = useState("");
|
||||||
|
const [bio, setBio] = useState("");
|
||||||
|
const [userTitle, setUserTitle] = useState("");
|
||||||
|
const [settingsPIN, setSettingsPIN] = useState("");
|
||||||
|
const [quickSettingsPIN, setQuickSettingsPIN] = useState("");
|
||||||
|
|
||||||
|
const [loading, setLoading] = useState(false);
|
||||||
|
const [saving, setSaving] = useState(false);
|
||||||
|
const [error, setError] = useState("");
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (isEdit) loadUser();
|
||||||
|
}, [id]);
|
||||||
|
|
||||||
|
const loadUser = async () => {
|
||||||
|
setLoading(true);
|
||||||
|
try {
|
||||||
|
const user = await api.get(`/users/${id}`);
|
||||||
|
setEmail(user.email || "");
|
||||||
|
setDisplayName(user.display_name || "");
|
||||||
|
setPhotoUrl(user.photo_url || "");
|
||||||
|
setUid(user.uid || "");
|
||||||
|
setPhoneNumber(user.phone_number || "");
|
||||||
|
setStatus(user.status || "");
|
||||||
|
setBio(user.bio || "");
|
||||||
|
setUserTitle(user.userTitle || "");
|
||||||
|
setSettingsPIN(user.settingsPIN || "");
|
||||||
|
setQuickSettingsPIN(user.quickSettingsPIN || "");
|
||||||
|
} catch (err) {
|
||||||
|
setError(err.message);
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleSubmit = async (e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
setSaving(true);
|
||||||
|
setError("");
|
||||||
|
|
||||||
|
try {
|
||||||
|
const body = {
|
||||||
|
email,
|
||||||
|
display_name: displayName,
|
||||||
|
photo_url: photoUrl,
|
||||||
|
uid,
|
||||||
|
phone_number: phoneNumber,
|
||||||
|
status,
|
||||||
|
bio,
|
||||||
|
userTitle,
|
||||||
|
settingsPIN,
|
||||||
|
quickSettingsPIN,
|
||||||
|
};
|
||||||
|
|
||||||
|
let userId = id;
|
||||||
|
if (isEdit) {
|
||||||
|
await api.put(`/users/${id}`, body);
|
||||||
|
} else {
|
||||||
|
const created = await api.post("/users", body);
|
||||||
|
userId = created.id;
|
||||||
|
}
|
||||||
|
|
||||||
|
navigate(`/users/${userId}`);
|
||||||
|
} catch (err) {
|
||||||
|
setError(err.message);
|
||||||
|
} finally {
|
||||||
|
setSaving(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
if (loading) {
|
||||||
|
return <div className="text-center py-8" style={{ color: "var(--text-muted)" }}>Loading...</div>;
|
||||||
|
}
|
||||||
|
|
||||||
|
const inputClass = "w-full px-3 py-2 rounded-md text-sm border";
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
<div className="flex items-center justify-between mb-6">
|
||||||
|
<h1 className="text-2xl font-bold" style={{ color: "var(--text-heading)" }}>
|
||||||
|
{isEdit ? "Edit User" : "Add User"}
|
||||||
|
</h1>
|
||||||
|
<div className="flex gap-3">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => navigate(isEdit ? `/users/${id}` : "/users")}
|
||||||
|
className="px-4 py-2 text-sm rounded-md hover:opacity-80 transition-colors"
|
||||||
|
style={{ backgroundColor: "var(--bg-card-hover)", color: "var(--text-primary)" }}
|
||||||
|
>
|
||||||
|
Cancel
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="submit"
|
||||||
|
form="user-form"
|
||||||
|
disabled={saving}
|
||||||
|
className="px-4 py-2 text-sm rounded-md hover:opacity-90 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
|
||||||
|
style={{ backgroundColor: "var(--btn-primary)", color: "var(--text-white)" }}
|
||||||
|
>
|
||||||
|
{saving ? "Saving..." : isEdit ? "Update User" : "Create User"}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{error && (
|
||||||
|
<div
|
||||||
|
className="text-sm rounded-md p-3 mb-4 border"
|
||||||
|
style={{ backgroundColor: "var(--danger-bg)", borderColor: "var(--danger)", color: "var(--danger-text)" }}
|
||||||
|
>
|
||||||
|
{error}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<form id="user-form" onSubmit={handleSubmit}>
|
||||||
|
<div className="grid grid-cols-1 xl:grid-cols-2 gap-6">
|
||||||
|
{/* ===== Left Column ===== */}
|
||||||
|
<div className="space-y-6">
|
||||||
|
{/* --- Account Info --- */}
|
||||||
|
<section
|
||||||
|
className="rounded-lg border p-6"
|
||||||
|
style={{ backgroundColor: "var(--bg-card)", borderColor: "var(--border-primary)" }}
|
||||||
|
>
|
||||||
|
<h2 className="text-lg font-semibold mb-4" style={{ color: "var(--text-heading)" }}>
|
||||||
|
Account 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 mb-1" style={{ color: "var(--text-secondary)" }}>
|
||||||
|
Display Name *
|
||||||
|
</label>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
required
|
||||||
|
value={displayName}
|
||||||
|
onChange={(e) => setDisplayName(e.target.value)}
|
||||||
|
className={inputClass}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm font-medium mb-1" style={{ color: "var(--text-secondary)" }}>
|
||||||
|
Email *
|
||||||
|
</label>
|
||||||
|
<input
|
||||||
|
type="email"
|
||||||
|
required
|
||||||
|
value={email}
|
||||||
|
onChange={(e) => setEmail(e.target.value)}
|
||||||
|
className={inputClass}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm font-medium mb-1" style={{ color: "var(--text-secondary)" }}>
|
||||||
|
Phone Number
|
||||||
|
</label>
|
||||||
|
<input
|
||||||
|
type="tel"
|
||||||
|
value={phoneNumber}
|
||||||
|
onChange={(e) => setPhoneNumber(e.target.value)}
|
||||||
|
placeholder="e.g. +1234567890"
|
||||||
|
className={inputClass}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm font-medium mb-1" style={{ color: "var(--text-secondary)" }}>
|
||||||
|
UID
|
||||||
|
</label>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
value={uid}
|
||||||
|
onChange={(e) => setUid(e.target.value)}
|
||||||
|
className={inputClass}
|
||||||
|
disabled={isEdit}
|
||||||
|
style={isEdit ? { opacity: 0.5 } : undefined}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm font-medium mb-1" style={{ color: "var(--text-secondary)" }}>
|
||||||
|
Status
|
||||||
|
</label>
|
||||||
|
<select
|
||||||
|
value={status}
|
||||||
|
onChange={(e) => setStatus(e.target.value)}
|
||||||
|
className={inputClass}
|
||||||
|
>
|
||||||
|
<option value="">Select status</option>
|
||||||
|
<option value="active">Active</option>
|
||||||
|
<option value="blocked">Blocked</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
{/* --- Profile --- */}
|
||||||
|
<section
|
||||||
|
className="rounded-lg border p-6"
|
||||||
|
style={{ backgroundColor: "var(--bg-card)", borderColor: "var(--border-primary)" }}
|
||||||
|
>
|
||||||
|
<h2 className="text-lg font-semibold mb-4" style={{ color: "var(--text-heading)" }}>
|
||||||
|
Profile
|
||||||
|
</h2>
|
||||||
|
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm font-medium mb-1" style={{ color: "var(--text-secondary)" }}>
|
||||||
|
Title
|
||||||
|
</label>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
value={userTitle}
|
||||||
|
onChange={(e) => setUserTitle(e.target.value)}
|
||||||
|
placeholder="e.g. Church Administrator"
|
||||||
|
className={inputClass}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm font-medium mb-1" style={{ color: "var(--text-secondary)" }}>
|
||||||
|
Photo URL
|
||||||
|
</label>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
value={photoUrl}
|
||||||
|
onChange={(e) => setPhotoUrl(e.target.value)}
|
||||||
|
className={inputClass}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="md:col-span-2">
|
||||||
|
<label className="block text-sm font-medium mb-1" style={{ color: "var(--text-secondary)" }}>
|
||||||
|
Bio
|
||||||
|
</label>
|
||||||
|
<textarea
|
||||||
|
value={bio}
|
||||||
|
onChange={(e) => setBio(e.target.value)}
|
||||||
|
rows={3}
|
||||||
|
className={inputClass}
|
||||||
|
style={{ resize: "vertical" }}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* ===== Right Column ===== */}
|
||||||
|
<div className="space-y-6">
|
||||||
|
{/* --- Security --- */}
|
||||||
|
<section
|
||||||
|
className="rounded-lg border p-6"
|
||||||
|
style={{ backgroundColor: "var(--bg-card)", borderColor: "var(--border-primary)" }}
|
||||||
|
>
|
||||||
|
<h2 className="text-lg font-semibold mb-4" style={{ color: "var(--text-heading)" }}>
|
||||||
|
Security
|
||||||
|
</h2>
|
||||||
|
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm font-medium mb-1" style={{ color: "var(--text-secondary)" }}>
|
||||||
|
Settings PIN
|
||||||
|
</label>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
value={settingsPIN}
|
||||||
|
onChange={(e) => setSettingsPIN(e.target.value)}
|
||||||
|
placeholder="e.g. 1234"
|
||||||
|
className={inputClass}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm font-medium mb-1" style={{ color: "var(--text-secondary)" }}>
|
||||||
|
Quick Settings PIN
|
||||||
|
</label>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
value={quickSettingsPIN}
|
||||||
|
onChange={(e) => setQuickSettingsPIN(e.target.value)}
|
||||||
|
placeholder="e.g. 0000"
|
||||||
|
className={inputClass}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|||||||
@@ -1 +1,232 @@
|
|||||||
// TODO: User 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 ConfirmDialog from "../components/ConfirmDialog";
|
||||||
|
|
||||||
|
const STATUS_OPTIONS = ["", "active", "blocked"];
|
||||||
|
|
||||||
|
export default function UserList() {
|
||||||
|
const [users, setUsers] = useState([]);
|
||||||
|
const [total, setTotal] = useState(0);
|
||||||
|
const [loading, setLoading] = useState(true);
|
||||||
|
const [error, setError] = useState("");
|
||||||
|
const [search, setSearch] = useState("");
|
||||||
|
const [statusFilter, setStatusFilter] = useState("");
|
||||||
|
const [deleteTarget, setDeleteTarget] = useState(null);
|
||||||
|
const [hoveredRow, setHoveredRow] = useState(null);
|
||||||
|
const navigate = useNavigate();
|
||||||
|
const { hasRole } = useAuth();
|
||||||
|
const canEdit = hasRole("superadmin", "user_manager");
|
||||||
|
|
||||||
|
const fetchUsers = async () => {
|
||||||
|
setLoading(true);
|
||||||
|
setError("");
|
||||||
|
try {
|
||||||
|
const params = new URLSearchParams();
|
||||||
|
if (search) params.set("search", search);
|
||||||
|
if (statusFilter) params.set("status", statusFilter);
|
||||||
|
const qs = params.toString();
|
||||||
|
const data = await api.get(`/users${qs ? `?${qs}` : ""}`);
|
||||||
|
setUsers(data.users);
|
||||||
|
setTotal(data.total);
|
||||||
|
} catch (err) {
|
||||||
|
setError(err.message);
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
fetchUsers();
|
||||||
|
}, [search, statusFilter]);
|
||||||
|
|
||||||
|
const handleDelete = async () => {
|
||||||
|
if (!deleteTarget) return;
|
||||||
|
try {
|
||||||
|
await api.delete(`/users/${deleteTarget.id}`);
|
||||||
|
setDeleteTarget(null);
|
||||||
|
fetchUsers();
|
||||||
|
} catch (err) {
|
||||||
|
setError(err.message);
|
||||||
|
setDeleteTarget(null);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
<div className="flex items-center justify-between mb-6">
|
||||||
|
<h1 className="text-2xl font-bold" style={{ color: "var(--text-heading)" }}>Users</h1>
|
||||||
|
{canEdit && (
|
||||||
|
<button
|
||||||
|
onClick={() => navigate("/users/new")}
|
||||||
|
className="px-4 py-2 text-sm rounded-md hover:opacity-90 transition-colors cursor-pointer"
|
||||||
|
style={{ backgroundColor: "var(--btn-primary)", color: "var(--text-white)" }}
|
||||||
|
>
|
||||||
|
Add User
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="mb-4 space-y-3">
|
||||||
|
<SearchBar
|
||||||
|
onSearch={setSearch}
|
||||||
|
placeholder="Search by name, email, phone, or UID..."
|
||||||
|
/>
|
||||||
|
<div className="flex flex-wrap gap-3 items-center">
|
||||||
|
<select
|
||||||
|
value={statusFilter}
|
||||||
|
onChange={(e) => setStatusFilter(e.target.value)}
|
||||||
|
className="px-3 py-2 rounded-md text-sm cursor-pointer border"
|
||||||
|
style={{
|
||||||
|
backgroundColor: "var(--bg-card)",
|
||||||
|
color: "var(--text-primary)",
|
||||||
|
borderColor: "var(--border-primary)",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<option value="">All Status</option>
|
||||||
|
{STATUS_OPTIONS.filter(Boolean).map((s) => (
|
||||||
|
<option key={s} value={s}>
|
||||||
|
{s.charAt(0).toUpperCase() + s.slice(1)}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
<span className="flex items-center text-sm" style={{ color: "var(--text-muted)" }}>
|
||||||
|
{total} {total === 1 ? "user" : "users"}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{error && (
|
||||||
|
<div
|
||||||
|
className="text-sm rounded-md p-3 mb-4 border"
|
||||||
|
style={{
|
||||||
|
backgroundColor: "var(--danger-bg)",
|
||||||
|
borderColor: "var(--danger)",
|
||||||
|
color: "var(--danger-text)",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{error}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{loading ? (
|
||||||
|
<div className="text-center py-8" style={{ color: "var(--text-muted)" }}>Loading...</div>
|
||||||
|
) : users.length === 0 ? (
|
||||||
|
<div
|
||||||
|
className="rounded-lg p-8 text-center text-sm border"
|
||||||
|
style={{
|
||||||
|
backgroundColor: "var(--bg-card)",
|
||||||
|
borderColor: "var(--border-primary)",
|
||||||
|
color: "var(--text-muted)",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
No users found.
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div
|
||||||
|
className="rounded-lg overflow-hidden border"
|
||||||
|
style={{
|
||||||
|
backgroundColor: "var(--bg-card)",
|
||||||
|
borderColor: "var(--border-primary)",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<div className="overflow-x-auto">
|
||||||
|
<table className="w-full text-sm">
|
||||||
|
<thead>
|
||||||
|
<tr style={{ backgroundColor: "var(--bg-primary)", borderBottom: "1px solid var(--border-primary)" }}>
|
||||||
|
<th className="px-4 py-3 text-left font-medium w-10" style={{ color: "var(--text-secondary)" }}>Status</th>
|
||||||
|
<th className="px-4 py-3 text-left font-medium" style={{ color: "var(--text-secondary)" }}>Name</th>
|
||||||
|
<th className="px-4 py-3 text-left font-medium" style={{ color: "var(--text-secondary)" }}>Email</th>
|
||||||
|
<th className="px-4 py-3 text-left font-medium" style={{ color: "var(--text-secondary)" }}>Phone</th>
|
||||||
|
<th className="px-4 py-3 text-left font-medium" style={{ color: "var(--text-secondary)" }}>Title</th>
|
||||||
|
<th className="px-4 py-3 text-left font-medium" style={{ color: "var(--text-secondary)" }}>Last Active</th>
|
||||||
|
{canEdit && (
|
||||||
|
<th className="px-4 py-3 text-left font-medium w-24" style={{ color: "var(--text-secondary)" }} />
|
||||||
|
)}
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{users.map((user, index) => (
|
||||||
|
<tr
|
||||||
|
key={user.id}
|
||||||
|
onClick={() => navigate(`/users/${user.id}`)}
|
||||||
|
className="cursor-pointer"
|
||||||
|
style={{
|
||||||
|
borderBottom: index < users.length - 1 ? "1px solid var(--border-primary)" : "none",
|
||||||
|
backgroundColor: hoveredRow === user.id ? "var(--bg-card-hover)" : "transparent",
|
||||||
|
}}
|
||||||
|
onMouseEnter={() => setHoveredRow(user.id)}
|
||||||
|
onMouseLeave={() => setHoveredRow(null)}
|
||||||
|
>
|
||||||
|
<td className="px-4 py-3">
|
||||||
|
<span
|
||||||
|
className="px-2 py-0.5 text-xs rounded-full"
|
||||||
|
style={
|
||||||
|
user.status === "blocked"
|
||||||
|
? { backgroundColor: "var(--danger-bg)", color: "var(--danger-text)" }
|
||||||
|
: user.status === "active"
|
||||||
|
? { backgroundColor: "var(--success-bg)", color: "var(--success-text)" }
|
||||||
|
: { backgroundColor: "var(--bg-card-hover)", color: "var(--text-muted)" }
|
||||||
|
}
|
||||||
|
>
|
||||||
|
{user.status || "unknown"}
|
||||||
|
</span>
|
||||||
|
</td>
|
||||||
|
<td className="px-4 py-3 font-medium" style={{ color: "var(--text-heading)" }}>
|
||||||
|
{user.display_name || "Unnamed User"}
|
||||||
|
</td>
|
||||||
|
<td className="px-4 py-3" style={{ color: "var(--text-primary)" }}>
|
||||||
|
{user.email || "-"}
|
||||||
|
</td>
|
||||||
|
<td className="px-4 py-3" style={{ color: "var(--text-primary)" }}>
|
||||||
|
{user.phone_number || "-"}
|
||||||
|
</td>
|
||||||
|
<td className="px-4 py-3" style={{ color: "var(--text-primary)" }}>
|
||||||
|
{user.userTitle || "-"}
|
||||||
|
</td>
|
||||||
|
<td className="px-4 py-3 text-xs" style={{ color: "var(--text-muted)" }}>
|
||||||
|
{user.lastActive || "-"}
|
||||||
|
</td>
|
||||||
|
{canEdit && (
|
||||||
|
<td className="px-4 py-3">
|
||||||
|
<div
|
||||||
|
className="flex gap-2"
|
||||||
|
onClick={(e) => e.stopPropagation()}
|
||||||
|
>
|
||||||
|
<button
|
||||||
|
onClick={() => navigate(`/users/${user.id}/edit`)}
|
||||||
|
className="hover:opacity-80 text-xs cursor-pointer"
|
||||||
|
style={{ color: "var(--text-link)" }}
|
||||||
|
>
|
||||||
|
Edit
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={() => setDeleteTarget(user)}
|
||||||
|
className="hover:opacity-80 text-xs cursor-pointer"
|
||||||
|
style={{ color: "var(--danger)" }}
|
||||||
|
>
|
||||||
|
Delete
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</td>
|
||||||
|
)}
|
||||||
|
</tr>
|
||||||
|
))}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<ConfirmDialog
|
||||||
|
open={!!deleteTarget}
|
||||||
|
title="Delete User"
|
||||||
|
message={`Are you sure you want to delete "${deleteTarget?.display_name || "this user"}" (${deleteTarget?.email || ""})? This action cannot be undone.`}
|
||||||
|
onConfirm={handleDelete}
|
||||||
|
onCancel={() => setDeleteTarget(null)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user