Adjustments to the Devices Layout
This commit is contained in:
@@ -75,6 +75,7 @@ class DeviceAttributes(BaseModel):
|
||||
networkSettings: DeviceNetworkSettings = DeviceNetworkSettings()
|
||||
serialLogLevel: int = 0
|
||||
sdLogLevel: int = 0
|
||||
mqttLogLevel: int = 0
|
||||
|
||||
|
||||
class DeviceSubInformation(BaseModel):
|
||||
@@ -151,3 +152,16 @@ class DeviceInDB(DeviceCreate):
|
||||
class DeviceListResponse(BaseModel):
|
||||
devices: List[DeviceInDB]
|
||||
total: int
|
||||
|
||||
|
||||
class DeviceUserInfo(BaseModel):
|
||||
"""User info resolved from device_users sub-collection or user_list."""
|
||||
user_id: str = ""
|
||||
display_name: str = ""
|
||||
email: str = ""
|
||||
role: str = ""
|
||||
|
||||
|
||||
class DeviceUsersResponse(BaseModel):
|
||||
users: List[DeviceUserInfo]
|
||||
total: int
|
||||
|
||||
@@ -4,6 +4,7 @@ from auth.models import TokenPayload
|
||||
from auth.dependencies import require_device_access, require_viewer
|
||||
from devices.models import (
|
||||
DeviceCreate, DeviceUpdate, DeviceInDB, DeviceListResponse,
|
||||
DeviceUsersResponse, DeviceUserInfo,
|
||||
)
|
||||
from devices import service
|
||||
|
||||
@@ -33,6 +34,16 @@ async def get_device(
|
||||
return service.get_device(device_id)
|
||||
|
||||
|
||||
@router.get("/{device_id}/users", response_model=DeviceUsersResponse)
|
||||
async def get_device_users(
|
||||
device_id: str,
|
||||
_user: TokenPayload = Depends(require_viewer),
|
||||
):
|
||||
users_data = service.get_device_users(device_id)
|
||||
users = [DeviceUserInfo(**u) for u in users_data]
|
||||
return DeviceUsersResponse(users=users, total=len(users))
|
||||
|
||||
|
||||
@router.post("", response_model=DeviceInDB, status_code=201)
|
||||
async def create_device(
|
||||
body: DeviceCreate,
|
||||
|
||||
@@ -165,6 +165,94 @@ def update_device(device_doc_id: str, data: DeviceUpdate) -> DeviceInDB:
|
||||
return _doc_to_device(updated_doc)
|
||||
|
||||
|
||||
def get_device_users(device_doc_id: str) -> list[dict]:
|
||||
"""Get users assigned to a device from the device_users sub-collection.
|
||||
|
||||
Falls back to the user_list field on the device document if the
|
||||
sub-collection is empty.
|
||||
"""
|
||||
db = get_db()
|
||||
doc_ref = db.collection(COLLECTION).document(device_doc_id)
|
||||
doc = doc_ref.get()
|
||||
if not doc.exists:
|
||||
raise NotFoundError("Device")
|
||||
|
||||
# Try sub-collection first
|
||||
sub_docs = list(doc_ref.collection("device_users").stream())
|
||||
users = []
|
||||
|
||||
if sub_docs:
|
||||
for sub_doc in sub_docs:
|
||||
sub_data = sub_doc.to_dict()
|
||||
role = sub_data.get("role", "")
|
||||
user_ref = sub_data.get("user_reference")
|
||||
|
||||
# Resolve user reference
|
||||
user_id = ""
|
||||
display_name = ""
|
||||
email = ""
|
||||
|
||||
if isinstance(user_ref, DocumentReference):
|
||||
try:
|
||||
user_doc = user_ref.get()
|
||||
if user_doc.exists:
|
||||
user_data = user_doc.to_dict()
|
||||
user_id = user_doc.id
|
||||
display_name = user_data.get("display_name", "")
|
||||
email = user_data.get("email", "")
|
||||
except Exception as e:
|
||||
print(f"[devices] Error resolving user reference: {e}")
|
||||
continue
|
||||
elif isinstance(user_ref, str):
|
||||
# String path like "users/abc123"
|
||||
try:
|
||||
ref_doc = db.document(user_ref).get()
|
||||
if ref_doc.exists:
|
||||
user_data = ref_doc.to_dict()
|
||||
user_id = ref_doc.id
|
||||
display_name = user_data.get("display_name", "")
|
||||
email = user_data.get("email", "")
|
||||
except Exception as e:
|
||||
print(f"[devices] Error resolving user path: {e}")
|
||||
continue
|
||||
|
||||
users.append({
|
||||
"user_id": user_id,
|
||||
"display_name": display_name,
|
||||
"email": email,
|
||||
"role": role,
|
||||
})
|
||||
else:
|
||||
# Fallback to user_list field
|
||||
device_data = doc.to_dict()
|
||||
user_list = device_data.get("user_list", [])
|
||||
for entry in user_list:
|
||||
try:
|
||||
if isinstance(entry, DocumentReference):
|
||||
user_doc = entry.get()
|
||||
elif isinstance(entry, str) and entry.strip():
|
||||
# Could be a path like "users/abc" or a raw doc ID
|
||||
if "/" in entry:
|
||||
user_doc = db.document(entry).get()
|
||||
else:
|
||||
user_doc = db.collection("users").document(entry).get()
|
||||
else:
|
||||
continue
|
||||
|
||||
if user_doc.exists:
|
||||
user_data = user_doc.to_dict()
|
||||
users.append({
|
||||
"user_id": user_doc.id,
|
||||
"display_name": user_data.get("display_name", ""),
|
||||
"email": user_data.get("email", ""),
|
||||
"role": "",
|
||||
})
|
||||
except Exception as e:
|
||||
print(f"[devices] Error resolving user_list entry: {e}")
|
||||
|
||||
return users
|
||||
|
||||
|
||||
def delete_device(device_doc_id: str) -> None:
|
||||
"""Delete a device document from Firestore."""
|
||||
db = get_db()
|
||||
|
||||
@@ -44,16 +44,19 @@ def _resolve_names(db, device_id: str | None, user_id: str | None) -> tuple[str,
|
||||
device_name = ""
|
||||
user_name = ""
|
||||
|
||||
if device_id:
|
||||
device_doc = db.collection("devices").document(device_id).get()
|
||||
if device_doc.exists:
|
||||
device_name = device_doc.to_dict().get("device_name", "")
|
||||
try:
|
||||
if device_id and isinstance(device_id, str) and device_id.strip():
|
||||
device_doc = db.collection("devices").document(device_id.strip()).get()
|
||||
if device_doc.exists:
|
||||
device_name = device_doc.to_dict().get("device_name", "")
|
||||
|
||||
if user_id:
|
||||
user_doc = db.collection("users").document(user_id).get()
|
||||
if user_doc.exists:
|
||||
user_doc_data = user_doc.to_dict()
|
||||
user_name = user_doc_data.get("display_name", "") or user_doc_data.get("email", "")
|
||||
if user_id and isinstance(user_id, str) and user_id.strip():
|
||||
user_doc = db.collection("users").document(user_id.strip()).get()
|
||||
if user_doc.exists:
|
||||
user_doc_data = user_doc.to_dict()
|
||||
user_name = user_doc_data.get("display_name", "") or user_doc_data.get("email", "")
|
||||
except Exception as e:
|
||||
print(f"[equipment] Error resolving names (device_id={device_id}, user_id={user_id}): {e}")
|
||||
|
||||
return device_name, user_name
|
||||
|
||||
|
||||
33
frontend/package-lock.json
generated
33
frontend/package-lock.json
generated
@@ -8,8 +8,10 @@
|
||||
"name": "frontend",
|
||||
"version": "0.0.0",
|
||||
"dependencies": {
|
||||
"leaflet": "^1.9.4",
|
||||
"react": "^19.2.0",
|
||||
"react-dom": "^19.2.0",
|
||||
"react-leaflet": "^5.0.0",
|
||||
"react-router-dom": "^7.13.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
@@ -1009,6 +1011,17 @@
|
||||
"@jridgewell/sourcemap-codec": "^1.4.14"
|
||||
}
|
||||
},
|
||||
"node_modules/@react-leaflet/core": {
|
||||
"version": "3.0.0",
|
||||
"resolved": "https://registry.npmjs.org/@react-leaflet/core/-/core-3.0.0.tgz",
|
||||
"integrity": "sha512-3EWmekh4Nz+pGcr+xjf0KNyYfC3U2JjnkWsh0zcqaexYqmmB5ZhH37kz41JXGmKzpaMZCnPofBBm64i+YrEvGQ==",
|
||||
"license": "Hippocratic-2.1",
|
||||
"peerDependencies": {
|
||||
"leaflet": "^1.9.0",
|
||||
"react": "^19.0.0",
|
||||
"react-dom": "^19.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@rolldown/pluginutils": {
|
||||
"version": "1.0.0-rc.3",
|
||||
"resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.0-rc.3.tgz",
|
||||
@@ -2614,6 +2627,12 @@
|
||||
"json-buffer": "3.0.1"
|
||||
}
|
||||
},
|
||||
"node_modules/leaflet": {
|
||||
"version": "1.9.4",
|
||||
"resolved": "https://registry.npmjs.org/leaflet/-/leaflet-1.9.4.tgz",
|
||||
"integrity": "sha512-nxS1ynzJOmOlHp+iL3FyWqK89GtNL8U8rvlMOsQdTTssxZwCXh8N2NB3GDQOL+YR3XnWyZAxwQixURb+FA74PA==",
|
||||
"license": "BSD-2-Clause"
|
||||
},
|
||||
"node_modules/levn": {
|
||||
"version": "0.4.1",
|
||||
"resolved": "https://registry.npmjs.org/levn/-/levn-0.4.1.tgz",
|
||||
@@ -3158,6 +3177,20 @@
|
||||
"react": "^19.2.4"
|
||||
}
|
||||
},
|
||||
"node_modules/react-leaflet": {
|
||||
"version": "5.0.0",
|
||||
"resolved": "https://registry.npmjs.org/react-leaflet/-/react-leaflet-5.0.0.tgz",
|
||||
"integrity": "sha512-CWbTpr5vcHw5bt9i4zSlPEVQdTVcML390TjeDG0cK59z1ylexpqC6M1PJFjV8jD7CF+ACBFsLIDs6DRMoLEofw==",
|
||||
"license": "Hippocratic-2.1",
|
||||
"dependencies": {
|
||||
"@react-leaflet/core": "^3.0.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"leaflet": "^1.9.0",
|
||||
"react": "^19.0.0",
|
||||
"react-dom": "^19.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/react-refresh": {
|
||||
"version": "0.18.0",
|
||||
"resolved": "https://registry.npmjs.org/react-refresh/-/react-refresh-0.18.0.tgz",
|
||||
|
||||
@@ -10,8 +10,10 @@
|
||||
"preview": "vite preview"
|
||||
},
|
||||
"dependencies": {
|
||||
"leaflet": "^1.9.4",
|
||||
"react": "^19.2.0",
|
||||
"react-dom": "^19.2.0",
|
||||
"react-leaflet": "^5.0.0",
|
||||
"react-router-dom": "^7.13.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
|
||||
@@ -1,17 +1,27 @@
|
||||
import { useState, useEffect } from "react";
|
||||
import { useParams, useNavigate } from "react-router-dom";
|
||||
import { MapContainer, TileLayer, Marker } from "react-leaflet";
|
||||
import "leaflet/dist/leaflet.css";
|
||||
import L from "leaflet";
|
||||
import api from "../api/client";
|
||||
import { useAuth } from "../auth/AuthContext";
|
||||
import ConfirmDialog from "../components/ConfirmDialog";
|
||||
import NotesPanel from "../equipment/NotesPanel";
|
||||
|
||||
// Fix default Leaflet marker icon
|
||||
delete L.Icon.Default.prototype._getIconUrl;
|
||||
L.Icon.Default.mergeOptions({
|
||||
iconRetinaUrl: "https://unpkg.com/leaflet@1.9.4/dist/images/marker-icon-2x.png",
|
||||
iconUrl: "https://unpkg.com/leaflet@1.9.4/dist/images/marker-icon.png",
|
||||
shadowUrl: "https://unpkg.com/leaflet@1.9.4/dist/images/marker-shadow.png",
|
||||
});
|
||||
|
||||
// --- Helper components ---
|
||||
|
||||
function Field({ label, children }) {
|
||||
return (
|
||||
<div>
|
||||
<dt
|
||||
className="text-xs font-medium uppercase tracking-wide"
|
||||
style={{ color: "var(--text-muted)" }}
|
||||
>
|
||||
<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)" }}>
|
||||
@@ -36,6 +46,122 @@ function BoolBadge({ value, yesLabel = "Yes", noLabel = "No" }) {
|
||||
);
|
||||
}
|
||||
|
||||
function SectionCard({ title, children }) {
|
||||
return (
|
||||
<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)" }}>{title}</h2>
|
||||
{children}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
function Subsection({ title, children, isFirst = false }) {
|
||||
return (
|
||||
<div className={isFirst ? "" : "mt-4 pt-4 border-t"} style={isFirst ? {} : { borderColor: "var(--border-secondary)" }}>
|
||||
<h3 className="text-sm font-semibold mb-3" style={{ color: "var(--text-primary)" }}>{title}</h3>
|
||||
<dl className="grid grid-cols-2 md:grid-cols-3 gap-4">{children}</dl>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// --- Date / time helpers ---
|
||||
|
||||
function parseFirestoreDate(str) {
|
||||
if (!str) return null;
|
||||
const cleaned = str.replace(" at ", " ").replace("UTC+0000", "UTC").replace(/UTC\+(\d{4})/, "UTC");
|
||||
const d = new Date(cleaned);
|
||||
return isNaN(d.getTime()) ? null : d;
|
||||
}
|
||||
|
||||
function formatDate(str) {
|
||||
const d = parseFirestoreDate(str);
|
||||
if (!d) return str || "-";
|
||||
const day = d.getUTCDate().toString().padStart(2, "0");
|
||||
const month = (d.getUTCMonth() + 1).toString().padStart(2, "0");
|
||||
const year = d.getUTCFullYear();
|
||||
return `${day}-${month}-${year}`;
|
||||
}
|
||||
|
||||
function addDays(date, days) {
|
||||
return new Date(date.getTime() + days * 86400000);
|
||||
}
|
||||
|
||||
function formatDateNice(d) {
|
||||
if (!d) return "-";
|
||||
const months = ["January","February","March","April","May","June","July","August","September","October","November","December"];
|
||||
return `${d.getUTCDate()} ${months[d.getUTCMonth()]} ${d.getUTCFullYear()}`;
|
||||
}
|
||||
|
||||
function daysUntil(targetDate) {
|
||||
const now = new Date();
|
||||
const diff = targetDate.getTime() - now.getTime();
|
||||
return Math.ceil(diff / 86400000);
|
||||
}
|
||||
|
||||
function formatRelativeTime(days) {
|
||||
if (days < 0) return null;
|
||||
if (days === 0) return "today";
|
||||
if (days === 1) return "in 1 day";
|
||||
if (days < 30) return `in ${days} days`;
|
||||
const months = Math.floor(days / 30);
|
||||
const remainDays = days % 30;
|
||||
if (remainDays === 0) return `in ${months} month${months > 1 ? "s" : ""}`;
|
||||
return `in ${months} month${months > 1 ? "s" : ""} and ${remainDays} day${remainDays > 1 ? "s" : ""}`;
|
||||
}
|
||||
|
||||
function daysToDisplay(days) {
|
||||
if (days >= 365 && days % 365 === 0) return `${days / 365} year${days / 365 > 1 ? "s" : ""} (${days} days)`;
|
||||
if (days >= 30) {
|
||||
const months = Math.floor(days / 30);
|
||||
const rem = days % 30;
|
||||
if (rem === 0) return `${months} month${months > 1 ? "s" : ""} (${days} days)`;
|
||||
return `${days} days (~${months} month${months > 1 ? "s" : ""})`;
|
||||
}
|
||||
return `${days} days`;
|
||||
}
|
||||
|
||||
function formatTimestamp(str) {
|
||||
// Try to parse as a Firestore timestamp and return HH:MM
|
||||
if (!str) return "-";
|
||||
const d = parseFirestoreDate(str);
|
||||
if (d) {
|
||||
return `${d.getUTCHours().toString().padStart(2, "0")}:${d.getUTCMinutes().toString().padStart(2, "0")}`;
|
||||
}
|
||||
// Maybe it's already a time string like "14:00"
|
||||
if (/^\d{1,2}:\d{2}/.test(str)) return str;
|
||||
// Try to extract time from the string
|
||||
const match = str.match(/(\d{1,2}):(\d{2})/);
|
||||
if (match) return `${match[1].padStart(2, "0")}:${match[2]}`;
|
||||
return str;
|
||||
}
|
||||
|
||||
function msToSeconds(ms) {
|
||||
if (ms == null) return "-";
|
||||
return `${(ms / 1000).toFixed(1)}s`;
|
||||
}
|
||||
|
||||
// --- Coordinates helpers ---
|
||||
|
||||
function parseCoordinates(coordStr) {
|
||||
if (!coordStr) return null;
|
||||
// Handle "lat,lng" or "lat° N, lng° E" or similar
|
||||
const cleaned = coordStr.replace(/°\s*[NSEW]/gi, "").trim();
|
||||
const parts = cleaned.split(",").map((s) => parseFloat(s.trim()));
|
||||
if (parts.length === 2 && !isNaN(parts[0]) && !isNaN(parts[1])) {
|
||||
return { lat: parts[0], lng: parts[1] };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function formatCoordinates(coords) {
|
||||
if (!coords) return "-";
|
||||
const latDir = coords.lat >= 0 ? "N" : "S";
|
||||
const lngDir = coords.lng >= 0 ? "E" : "W";
|
||||
return `${Math.abs(coords.lat).toFixed(7)}° ${latDir}, ${Math.abs(coords.lng).toFixed(7)}° ${lngDir}`;
|
||||
}
|
||||
|
||||
// --- Main component ---
|
||||
|
||||
export default function DeviceDetail() {
|
||||
const { id } = useParams();
|
||||
const navigate = useNavigate();
|
||||
@@ -46,6 +172,10 @@ export default function DeviceDetail() {
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState("");
|
||||
const [showDelete, setShowDelete] = useState(false);
|
||||
const [mqttStatus, setMqttStatus] = useState(null);
|
||||
const [locationName, setLocationName] = useState(null);
|
||||
const [deviceUsers, setDeviceUsers] = useState([]);
|
||||
const [usersLoading, setUsersLoading] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
loadData();
|
||||
@@ -54,8 +184,41 @@ export default function DeviceDetail() {
|
||||
const loadData = async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const d = await api.get(`/devices/${id}`);
|
||||
const [d, mqttData] = await Promise.all([
|
||||
api.get(`/devices/${id}`),
|
||||
api.get("/mqtt/status").catch(() => null),
|
||||
]);
|
||||
setDevice(d);
|
||||
|
||||
// Match MQTT status by serial number
|
||||
if (mqttData?.devices && d.device_id) {
|
||||
const match = mqttData.devices.find((s) => s.device_serial === d.device_id);
|
||||
setMqttStatus(match || null);
|
||||
}
|
||||
|
||||
// Load device users
|
||||
setUsersLoading(true);
|
||||
api.get(`/devices/${id}/users`).then((data) => {
|
||||
setDeviceUsers(data.users || []);
|
||||
}).catch(() => {
|
||||
setDeviceUsers([]);
|
||||
}).finally(() => setUsersLoading(false));
|
||||
|
||||
// Reverse geocode
|
||||
const coords = parseCoordinates(d.device_location_coordinates);
|
||||
if (coords) {
|
||||
fetch(`https://nominatim.openstreetmap.org/reverse?lat=${coords.lat}&lon=${coords.lng}&format=json&zoom=10`)
|
||||
.then((r) => r.json())
|
||||
.then((data) => {
|
||||
const addr = data.address || {};
|
||||
const name = addr.city || addr.town || addr.village || addr.hamlet || addr.municipality || data.display_name?.split(",")[0] || "";
|
||||
const region = addr.state || addr.county || "";
|
||||
const country = addr.country || "";
|
||||
const parts = [name, region, country].filter(Boolean);
|
||||
setLocationName(parts.join(", "));
|
||||
})
|
||||
.catch(() => setLocationName(null));
|
||||
}
|
||||
} catch (err) {
|
||||
setError(err.message);
|
||||
} finally {
|
||||
@@ -73,29 +236,12 @@ export default function DeviceDetail() {
|
||||
}
|
||||
};
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="text-center py-8" style={{ color: "var(--text-muted)" }}>
|
||||
Loading...
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (error) {
|
||||
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 (loading) return <div className="text-center py-8" style={{ color: "var(--text-muted)" }}>Loading...</div>;
|
||||
if (error) 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 (!device) return null;
|
||||
|
||||
const attr = device.device_attributes || {};
|
||||
@@ -103,48 +249,49 @@ export default function DeviceDetail() {
|
||||
const net = attr.networkSettings || {};
|
||||
const sub = device.device_subscription || {};
|
||||
const stats = device.device_stats || {};
|
||||
const coords = parseCoordinates(device.device_location_coordinates);
|
||||
const isOnline = mqttStatus ? mqttStatus.online : device.is_Online;
|
||||
|
||||
// Subscription computed fields
|
||||
const subscrStart = parseFirestoreDate(sub.subscrStart);
|
||||
const subscrEnd = subscrStart && sub.subscrDuration ? addDays(subscrStart, sub.subscrDuration) : null;
|
||||
const subscrDaysLeft = subscrEnd ? daysUntil(subscrEnd) : null;
|
||||
|
||||
// Warranty computed fields
|
||||
const warrantyStart = parseFirestoreDate(stats.warrantyStart);
|
||||
const warrantyEnd = warrantyStart && stats.warrantyPeriod ? addDays(warrantyStart, stats.warrantyPeriod) : null;
|
||||
const warrantyDaysLeft = warrantyEnd ? daysUntil(warrantyEnd) : null;
|
||||
|
||||
// Maintenance computed fields
|
||||
const maintainedOn = parseFirestoreDate(stats.maintainedOn);
|
||||
const nextMaintenance = maintainedOn && stats.maintainancePeriod ? addDays(maintainedOn, stats.maintainancePeriod) : null;
|
||||
const maintenanceDaysLeft = nextMaintenance ? daysUntil(nextMaintenance) : null;
|
||||
|
||||
return (
|
||||
<div>
|
||||
{/* Header */}
|
||||
<div className="flex items-center justify-between mb-6">
|
||||
<div>
|
||||
<button
|
||||
onClick={() => navigate("/devices")}
|
||||
className="text-sm hover:underline mb-2 inline-block"
|
||||
style={{ color: "var(--accent)" }}
|
||||
>
|
||||
<button onClick={() => navigate("/devices")} className="text-sm hover:underline mb-2 inline-block" style={{ color: "var(--accent)" }}>
|
||||
← Back to Devices
|
||||
</button>
|
||||
<div className="flex items-center gap-3">
|
||||
<h1
|
||||
className="text-2xl font-bold"
|
||||
style={{ color: "var(--text-heading)" }}
|
||||
>
|
||||
<h1 className="text-2xl font-bold" style={{ color: "var(--text-heading)" }}>
|
||||
{device.device_name || "Unnamed Device"}
|
||||
</h1>
|
||||
<span
|
||||
className={`inline-block w-3 h-3 rounded-full ${
|
||||
device.is_Online ? "bg-green-500" : ""
|
||||
}`}
|
||||
style={!device.is_Online ? { backgroundColor: "var(--border-primary)" } : undefined}
|
||||
title={device.is_Online ? "Online" : "Offline"}
|
||||
className={`inline-block w-3 h-3 rounded-full ${isOnline ? "bg-green-500" : ""}`}
|
||||
style={!isOnline ? { backgroundColor: "var(--border-primary)" } : undefined}
|
||||
title={isOnline ? "Online" : "Offline"}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
{canEdit && (
|
||||
<div className="flex gap-2">
|
||||
<button
|
||||
onClick={() => navigate(`/devices/${id}/edit`)}
|
||||
className="px-4 py-2 text-sm rounded-md transition-colors"
|
||||
style={{ backgroundColor: "var(--text-link)", color: "var(--text-white)" }}
|
||||
>
|
||||
<button onClick={() => navigate(`/devices/${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)" }}
|
||||
>
|
||||
<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>
|
||||
@@ -154,232 +301,281 @@ export default function DeviceDetail() {
|
||||
<div className="grid grid-cols-1 xl:grid-cols-2 gap-6">
|
||||
{/* Left column */}
|
||||
<div className="space-y-6">
|
||||
{/* Basic 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)" }}
|
||||
>
|
||||
Basic Information
|
||||
</h2>
|
||||
{/* Basic Information */}
|
||||
<SectionCard title="Basic Information">
|
||||
<dl className="grid grid-cols-2 md:grid-cols-3 gap-4">
|
||||
<Field label="Serial Number">
|
||||
<span className="font-mono">{device.device_id}</span>
|
||||
</Field>
|
||||
<Field label="Document ID">
|
||||
<span className="font-mono text-xs" style={{ color: "var(--text-muted)" }}>
|
||||
{device.id}
|
||||
</span>
|
||||
</Field>
|
||||
<Field label="Status">
|
||||
<BoolBadge value={device.is_Online} yesLabel="Online" noLabel="Offline" />
|
||||
<BoolBadge value={isOnline} yesLabel="Online" noLabel="Offline" />
|
||||
{mqttStatus && (
|
||||
<span className="ml-2 text-xs" style={{ color: "var(--text-muted)" }}>
|
||||
(MQTT {mqttStatus.seconds_since_heartbeat}s ago)
|
||||
</span>
|
||||
)}
|
||||
</Field>
|
||||
<div className="col-span-2 md:col-span-3">
|
||||
<Field label="Location">{device.device_location}</Field>
|
||||
</div>
|
||||
<Field label="Coordinates">{device.device_location_coordinates}</Field>
|
||||
<Field label="Events On">
|
||||
<BoolBadge value={device.events_on} />
|
||||
</Field>
|
||||
<Field label="WebSocket URL">{device.websocket_url}</Field>
|
||||
<div className="col-span-2 md:col-span-3">
|
||||
<Field label="Church Assistant URL">{device.churchAssistantURL}</Field>
|
||||
</div>
|
||||
<Field label="Document ID">
|
||||
<span className="font-mono text-xs" style={{ color: "var(--text-muted)" }}>{device.id}</span>
|
||||
</Field>
|
||||
</dl>
|
||||
</section>
|
||||
</SectionCard>
|
||||
|
||||
{/* Device Attributes */}
|
||||
<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)" }}
|
||||
>
|
||||
Device Attributes
|
||||
</h2>
|
||||
{/* Location */}
|
||||
<SectionCard title="Location">
|
||||
<dl className="grid grid-cols-1 md:grid-cols-2 gap-4 mb-4">
|
||||
<Field label="Location">{device.device_location}</Field>
|
||||
<Field label="Coordinates">
|
||||
<div>
|
||||
{coords ? formatCoordinates(coords) : device.device_location_coordinates || "-"}
|
||||
{coords && (
|
||||
<a
|
||||
href={`https://www.google.com/maps?q=${coords.lat},${coords.lng}`}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="ml-2 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)", height: 200 }}>
|
||||
<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>
|
||||
)}
|
||||
</SectionCard>
|
||||
|
||||
{/* Subscription */}
|
||||
<SectionCard title="Subscription">
|
||||
<dl className="grid grid-cols-2 md:grid-cols-3 gap-4">
|
||||
<Field label="Has Assistant"><BoolBadge value={attr.hasAssistant} /></Field>
|
||||
<Field label="Has Clock"><BoolBadge value={attr.hasClock} /></Field>
|
||||
<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>
|
||||
|
||||
{/* Device Settings (combined) */}
|
||||
<SectionCard title="Device Settings">
|
||||
{/* Subsection 1: Basic Attributes */}
|
||||
<Subsection title="Basic Attributes" isFirst>
|
||||
<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>
|
||||
</Subsection>
|
||||
|
||||
{/* Subsection 2: Bell Settings */}
|
||||
<Subsection title="Bell Settings">
|
||||
<Field label="Has Bells"><BoolBadge value={attr.hasBells} /></Field>
|
||||
<Field label="Total Bells">{attr.totalBells}</Field>
|
||||
<Field label="Bell Guard"><BoolBadge value={attr.bellGuardOn} /></Field>
|
||||
<Field label="Bell Guard Safety"><BoolBadge value={attr.bellGuardSafetyOn} /></Field>
|
||||
<Field label="Warnings On"><BoolBadge value={attr.warningsOn} /></Field>
|
||||
<Field label="Device Locale">
|
||||
<span className="capitalize">{attr.deviceLocale}</span>
|
||||
</Field>
|
||||
<Field label="Bell Outputs">{attr.bellOutputs?.length > 0 ? attr.bellOutputs.join(", ") : "-"}</Field>
|
||||
<Field label="Hammer Timings">{attr.hammerTimings?.length > 0 ? attr.hammerTimings.join(", ") : "-"}</Field>
|
||||
</Subsection>
|
||||
|
||||
{/* Subsection 3.1: Clock Settings */}
|
||||
<Subsection title="Clock Settings">
|
||||
<Field label="Has Clock"><BoolBadge value={attr.hasClock} /></Field>
|
||||
<Field label="Odd Output">{clock.clockOutputs?.[0] ?? "-"}</Field>
|
||||
<Field label="Even Output">{clock.clockOutputs?.[1] ?? "-"}</Field>
|
||||
<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>
|
||||
<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>
|
||||
<Field label="Hour Bell">{clock.hourAlertsBell}</Field>
|
||||
<Field label="Half-Hour Bell">{clock.halfhourAlertsBell}</Field>
|
||||
<Field label="Quarter Bell">{clock.quarterAlertsBell}</Field>
|
||||
<Field label="Daytime Silence"><BoolBadge value={clock.isDaySilenceOn} yesLabel="ON" noLabel="OFF" /></Field>
|
||||
{clock.isDaySilenceOn && (
|
||||
<Field label="Daytime Period">
|
||||
{formatTimestamp(clock.daySilenceFrom)} - {formatTimestamp(clock.daySilenceTo)}
|
||||
</Field>
|
||||
)}
|
||||
<Field label="Nighttime Silence"><BoolBadge value={clock.isNightSilenceOn} yesLabel="ON" noLabel="OFF" /></Field>
|
||||
{clock.isNightSilenceOn && (
|
||||
<Field label="Nighttime Period">
|
||||
{formatTimestamp(clock.nightSilenceFrom)} - {formatTimestamp(clock.nightSilenceTo)}
|
||||
</Field>
|
||||
)}
|
||||
</Subsection>
|
||||
|
||||
{/* Subsection 3.2: Backlight Settings */}
|
||||
<Subsection title="Backlight Settings">
|
||||
<Field label="Auto Backlight"><BoolBadge value={clock.isBacklightAutomationOn} yesLabel="ON" noLabel="OFF" /></Field>
|
||||
<Field label="Backlight Output">{clock.backlightOutput}</Field>
|
||||
<Field label="On Time">{formatTimestamp(clock.backlightTurnOnTime)}</Field>
|
||||
<Field label="Off Time">{formatTimestamp(clock.backlightTurnOffTime)}</Field>
|
||||
</Subsection>
|
||||
|
||||
{/* Subsection 4: Network */}
|
||||
<Subsection title="Network">
|
||||
<Field label="Hostname">{net.hostname}</Field>
|
||||
<Field label="Has Static IP"><BoolBadge value={net.useStaticIP} /></Field>
|
||||
</Subsection>
|
||||
|
||||
{/* Subsection 5: Logging */}
|
||||
<Subsection title="Logging">
|
||||
<Field label="Serial Log Level">{attr.serialLogLevel}</Field>
|
||||
<Field label="SD Log Level">{attr.sdLogLevel}</Field>
|
||||
<Field label="Bell Outputs">
|
||||
{attr.bellOutputs?.length > 0 ? attr.bellOutputs.join(", ") : "-"}
|
||||
</Field>
|
||||
<Field label="Hammer Timings">
|
||||
{attr.hammerTimings?.length > 0 ? attr.hammerTimings.join(", ") : "-"}
|
||||
</Field>
|
||||
</dl>
|
||||
</section>
|
||||
|
||||
{/* Network */}
|
||||
<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)" }}
|
||||
>
|
||||
Network Settings
|
||||
</h2>
|
||||
<dl className="grid grid-cols-2 md:grid-cols-3 gap-4">
|
||||
<Field label="Hostname">{net.hostname}</Field>
|
||||
<Field label="Static IP"><BoolBadge value={net.useStaticIP} /></Field>
|
||||
</dl>
|
||||
</section>
|
||||
<Field label="MQTT Log Level">{attr.mqttLogLevel ?? 0}</Field>
|
||||
</Subsection>
|
||||
</SectionCard>
|
||||
</div>
|
||||
|
||||
{/* Right column */}
|
||||
<div className="space-y-6">
|
||||
{/* Subscription */}
|
||||
<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)" }}
|
||||
>
|
||||
Subscription
|
||||
</h2>
|
||||
{/* Misc */}
|
||||
<SectionCard title="Misc">
|
||||
<dl className="grid grid-cols-2 md:grid-cols-3 gap-4">
|
||||
<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">{sub.subscrStart}</Field>
|
||||
<Field label="Duration">{sub.subscrDuration} months</Field>
|
||||
<Field label="Max Users">{sub.maxUsers}</Field>
|
||||
<Field label="Max Outputs">{sub.maxOutputs}</Field>
|
||||
</dl>
|
||||
</section>
|
||||
|
||||
{/* Clock Settings */}
|
||||
<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)" }}
|
||||
>
|
||||
Clock Settings
|
||||
</h2>
|
||||
<dl className="grid grid-cols-2 md:grid-cols-3 gap-4">
|
||||
<Field label="Ring Alerts Master"><BoolBadge value={clock.ringAlertsMasterOn} /></Field>
|
||||
<Field label="Ring Alerts">
|
||||
<span className="capitalize">{clock.ringAlerts}</span>
|
||||
</Field>
|
||||
<Field label="Ring Intervals">{clock.ringIntervals}</Field>
|
||||
<Field label="Hour Alerts Bell">{clock.hourAlertsBell}</Field>
|
||||
<Field label="Half-hour Bell">{clock.halfhourAlertsBell}</Field>
|
||||
<Field label="Quarter Bell">{clock.quarterAlertsBell}</Field>
|
||||
<Field label="Backlight Output">{clock.backlightOutput}</Field>
|
||||
<Field label="Backlight Auto"><BoolBadge value={clock.isBacklightAutomationOn} /></Field>
|
||||
<Field label="Clock Outputs">
|
||||
{clock.clockOutputs?.length > 0 ? clock.clockOutputs.join(", ") : "-"}
|
||||
</Field>
|
||||
<Field label="Clock Timings">
|
||||
{clock.clockTimings?.length > 0 ? clock.clockTimings.join(", ") : "-"}
|
||||
</Field>
|
||||
</dl>
|
||||
{(clock.isDaySilenceOn || clock.isNightSilenceOn) && (
|
||||
<div
|
||||
className="mt-4 pt-4 border-t"
|
||||
style={{ borderColor: "var(--border-secondary)" }}
|
||||
>
|
||||
<h3
|
||||
className="text-sm font-semibold mb-3"
|
||||
style={{ color: "var(--text-primary)" }}
|
||||
>
|
||||
Silence Periods
|
||||
</h3>
|
||||
<dl className="grid grid-cols-2 md:grid-cols-3 gap-4">
|
||||
{clock.isDaySilenceOn && (
|
||||
<>
|
||||
<Field label="Day Silence">
|
||||
{clock.daySilenceFrom} - {clock.daySilenceTo}
|
||||
</Field>
|
||||
</>
|
||||
)}
|
||||
{clock.isNightSilenceOn && (
|
||||
<>
|
||||
<Field label="Night Silence">
|
||||
{clock.nightSilenceFrom} - {clock.nightSilenceTo}
|
||||
</Field>
|
||||
</>
|
||||
)}
|
||||
</dl>
|
||||
<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 className="col-span-2 md:col-span-3">
|
||||
<Field label="Church Assistant URL">{device.churchAssistantURL}</Field>
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
</dl>
|
||||
</SectionCard>
|
||||
|
||||
{/* Statistics */}
|
||||
<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)" }}
|
||||
>
|
||||
Statistics & Warranty
|
||||
</h2>
|
||||
<dl className="grid grid-cols-2 md:grid-cols-3 gap-4">
|
||||
{/* Warranty & Maintenance & Statistics */}
|
||||
<SectionCard title="Warranty, Maintenance & Statistics">
|
||||
{/* Subsection 1: Warranty */}
|
||||
<Subsection title="Warranty Information" isFirst>
|
||||
<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>
|
||||
</Subsection>
|
||||
|
||||
{/* Subsection 2: Maintenance */}
|
||||
<Subsection title="Maintenance">
|
||||
<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>
|
||||
</Subsection>
|
||||
|
||||
{/* Subsection 3: Statistics */}
|
||||
<Subsection title="Statistics">
|
||||
<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="Per-Bell Strikes">
|
||||
{stats.perBellStrikes?.length > 0 ? stats.perBellStrikes.join(", ") : "-"}
|
||||
</Field>
|
||||
<Field label="Warranty Active"><BoolBadge value={stats.warrantyActive} /></Field>
|
||||
<Field label="Warranty Start">{stats.warrantyStart}</Field>
|
||||
<Field label="Warranty Period">{stats.warrantyPeriod} months</Field>
|
||||
<Field label="Last Maintained">{stats.maintainedOn}</Field>
|
||||
<Field label="Maintenance Period">{stats.maintainancePeriod} months</Field>
|
||||
</dl>
|
||||
</section>
|
||||
<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 className="col-span-2 md:col-span-3">
|
||||
<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>
|
||||
)}
|
||||
</Subsection>
|
||||
</SectionCard>
|
||||
|
||||
{/* Melodies & Users summary */}
|
||||
<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)" }}
|
||||
>
|
||||
Melodies & Users
|
||||
</h2>
|
||||
<dl className="grid grid-cols-2 gap-4">
|
||||
<Field label="Total Melodies">
|
||||
{device.device_melodies_all?.length ?? 0}
|
||||
</Field>
|
||||
<Field label="Favorite Melodies">
|
||||
{device.device_melodies_favorites?.length ?? 0}
|
||||
</Field>
|
||||
<Field label="Assigned Users">
|
||||
{device.user_list?.length ?? 0}
|
||||
</Field>
|
||||
</dl>
|
||||
</section>
|
||||
{/* Users */}
|
||||
<SectionCard title={`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} />
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useState, useEffect } from "react";
|
||||
import { useState, useEffect, useRef } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import api from "../api/client";
|
||||
import { useAuth } from "../auth/AuthContext";
|
||||
@@ -7,20 +7,125 @@ import ConfirmDialog from "../components/ConfirmDialog";
|
||||
|
||||
const TIER_OPTIONS = ["", "basic", "small", "mini", "premium", "vip", "custom"];
|
||||
|
||||
// All available columns with their defaults
|
||||
const ALL_COLUMNS = [
|
||||
{ key: "status", label: "Status", defaultOn: true },
|
||||
{ key: "name", label: "Name", defaultOn: true, alwaysOn: true },
|
||||
{ key: "serialNumber", label: "Serial Number", defaultOn: true },
|
||||
{ key: "location", label: "Location", defaultOn: true },
|
||||
{ key: "subscrTier", label: "Subscr Tier", defaultOn: true },
|
||||
{ key: "maxOutputs", label: "Max Outputs", defaultOn: false },
|
||||
{ key: "hasClock", label: "Has Clock", defaultOn: false },
|
||||
{ key: "hasBells", label: "Has Bells", defaultOn: false },
|
||||
{ key: "totalBells", label: "Total Bells", defaultOn: true },
|
||||
{ key: "bellGuard", label: "Bell Guard", defaultOn: false },
|
||||
{ key: "warningsOn", label: "Warnings On", defaultOn: false },
|
||||
{ key: "serialLogLevel", label: "Serial Log Level", defaultOn: false },
|
||||
{ key: "sdLogLevel", label: "SD Log Level", defaultOn: false },
|
||||
{ key: "bellOutputs", label: "Bell Outputs", defaultOn: false },
|
||||
{ key: "hammerTimings", label: "Hammer Timings", defaultOn: false },
|
||||
{ key: "ringAlertsMaster", label: "Ring Alerts Master", defaultOn: false },
|
||||
{ key: "totalPlaybacks", label: "Total Playbacks", defaultOn: false },
|
||||
{ key: "totalHammerStrikes", label: "Total Hammer Strikes", defaultOn: false },
|
||||
{ key: "totalWarnings", label: "Total Warnings", defaultOn: false },
|
||||
{ key: "warrantyActive", label: "Warranty Active", defaultOn: false },
|
||||
{ key: "totalMelodies", label: "Total Melodies", defaultOn: false },
|
||||
{ key: "assignedUsers", label: "Assigned Users", defaultOn: true },
|
||||
];
|
||||
|
||||
function getDefaultVisibleColumns() {
|
||||
const saved = localStorage.getItem("deviceListColumns");
|
||||
if (saved) {
|
||||
try {
|
||||
return JSON.parse(saved);
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
return ALL_COLUMNS.filter((c) => c.defaultOn).map((c) => c.key);
|
||||
}
|
||||
|
||||
function BoolBadge({ value, yesLabel = "Yes", noLabel = "No" }) {
|
||||
return (
|
||||
<span
|
||||
className="px-2 py-0.5 text-xs rounded-full"
|
||||
style={
|
||||
value
|
||||
? { backgroundColor: "var(--success-bg)", color: "var(--success-text)" }
|
||||
: { backgroundColor: "var(--bg-card-hover)", color: "var(--text-muted)" }
|
||||
}
|
||||
>
|
||||
{value ? yesLabel : noLabel}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
function isSubscriptionActive(device) {
|
||||
const sub = device.device_subscription;
|
||||
if (!sub?.subscrStart || !sub?.subscrDuration) return false;
|
||||
try {
|
||||
const start = parseFirestoreDate(sub.subscrStart);
|
||||
if (!start) return false;
|
||||
const end = new Date(start.getTime() + sub.subscrDuration * 86400000);
|
||||
return end > new Date();
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function isWarrantyActive(device) {
|
||||
const stats = device.device_stats;
|
||||
if (!stats?.warrantyStart || !stats?.warrantyPeriod) return !!stats?.warrantyActive;
|
||||
try {
|
||||
const start = parseFirestoreDate(stats.warrantyStart);
|
||||
if (!start) return !!stats?.warrantyActive;
|
||||
const end = new Date(start.getTime() + stats.warrantyPeriod * 86400000);
|
||||
return end > new Date();
|
||||
} catch {
|
||||
return !!stats?.warrantyActive;
|
||||
}
|
||||
}
|
||||
|
||||
function parseFirestoreDate(str) {
|
||||
if (!str) return null;
|
||||
// Handle format like "22 December 2025 at 16:35:56 UTC+0000"
|
||||
const cleaned = str.replace(" at ", " ").replace("UTC+0000", "UTC").replace(/UTC\+(\d{4})/, "UTC");
|
||||
const d = new Date(cleaned);
|
||||
return isNaN(d.getTime()) ? null : d;
|
||||
}
|
||||
|
||||
export default function DeviceList() {
|
||||
const [devices, setDevices] = useState([]);
|
||||
const [total, setTotal] = useState(0);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState("");
|
||||
const [search, setSearch] = useState("");
|
||||
const [onlineFilter, setOnlineFilter] = useState("");
|
||||
const [tierFilter, setTierFilter] = useState("");
|
||||
const [subscrStatusFilter, setSubscrStatusFilter] = useState("");
|
||||
const [warrantyStatusFilter, setWarrantyStatusFilter] = useState("");
|
||||
const [hasClockFilter, setHasClockFilter] = useState("");
|
||||
const [hasBellsFilter, setHasBellsFilter] = useState("");
|
||||
const [deleteTarget, setDeleteTarget] = useState(null);
|
||||
const [hoveredRow, setHoveredRow] = useState(null);
|
||||
const [visibleColumns, setVisibleColumns] = useState(getDefaultVisibleColumns);
|
||||
const [showColumnPicker, setShowColumnPicker] = useState(false);
|
||||
const columnPickerRef = useRef(null);
|
||||
const navigate = useNavigate();
|
||||
const { hasRole } = useAuth();
|
||||
const canEdit = hasRole("superadmin", "device_manager");
|
||||
|
||||
// Close column picker on outside click
|
||||
useEffect(() => {
|
||||
const handleClick = (e) => {
|
||||
if (columnPickerRef.current && !columnPickerRef.current.contains(e.target)) {
|
||||
setShowColumnPicker(false);
|
||||
}
|
||||
};
|
||||
if (showColumnPicker) {
|
||||
document.addEventListener("mousedown", handleClick);
|
||||
return () => document.removeEventListener("mousedown", handleClick);
|
||||
}
|
||||
}, [showColumnPicker]);
|
||||
|
||||
const fetchDevices = async () => {
|
||||
setLoading(true);
|
||||
setError("");
|
||||
@@ -33,7 +138,6 @@ export default function DeviceList() {
|
||||
const qs = params.toString();
|
||||
const data = await api.get(`/devices${qs ? `?${qs}` : ""}`);
|
||||
setDevices(data.devices);
|
||||
setTotal(data.total);
|
||||
} catch (err) {
|
||||
setError(err.message);
|
||||
} finally {
|
||||
@@ -57,6 +161,115 @@ export default function DeviceList() {
|
||||
}
|
||||
};
|
||||
|
||||
const toggleColumn = (key) => {
|
||||
const col = ALL_COLUMNS.find((c) => c.key === key);
|
||||
if (col?.alwaysOn) return;
|
||||
setVisibleColumns((prev) => {
|
||||
const next = prev.includes(key)
|
||||
? prev.filter((k) => k !== key)
|
||||
: [...prev, key];
|
||||
localStorage.setItem("deviceListColumns", JSON.stringify(next));
|
||||
return next;
|
||||
});
|
||||
};
|
||||
|
||||
const isVisible = (key) => visibleColumns.includes(key);
|
||||
|
||||
const renderCellValue = (key, device) => {
|
||||
const attr = device.device_attributes || {};
|
||||
const clock = attr.clockSettings || {};
|
||||
const sub = device.device_subscription || {};
|
||||
const stats = device.device_stats || {};
|
||||
|
||||
switch (key) {
|
||||
case "status":
|
||||
return (
|
||||
<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"}
|
||||
/>
|
||||
);
|
||||
case "name":
|
||||
return (
|
||||
<span className="font-medium" style={{ color: "var(--text-heading)" }}>
|
||||
{device.device_name || "Unnamed Device"}
|
||||
</span>
|
||||
);
|
||||
case "serialNumber":
|
||||
return <span className="font-mono text-xs" style={{ color: "var(--text-muted)" }}>{device.device_id || "-"}</span>;
|
||||
case "location":
|
||||
return device.device_location || "-";
|
||||
case "subscrTier":
|
||||
return (
|
||||
<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 || "basic"}
|
||||
</span>
|
||||
);
|
||||
case "maxOutputs":
|
||||
return sub.maxOutputs ?? "-";
|
||||
case "hasClock":
|
||||
return <BoolBadge value={attr.hasClock} />;
|
||||
case "hasBells":
|
||||
return <BoolBadge value={attr.hasBells} />;
|
||||
case "totalBells":
|
||||
return attr.totalBells ?? 0;
|
||||
case "bellGuard":
|
||||
return <BoolBadge value={attr.bellGuardOn} />;
|
||||
case "warningsOn":
|
||||
return <BoolBadge value={attr.warningsOn} />;
|
||||
case "serialLogLevel":
|
||||
return attr.serialLogLevel ?? 0;
|
||||
case "sdLogLevel":
|
||||
return attr.sdLogLevel ?? 0;
|
||||
case "bellOutputs":
|
||||
return attr.bellOutputs?.length > 0 ? attr.bellOutputs.join(", ") : "-";
|
||||
case "hammerTimings":
|
||||
return attr.hammerTimings?.length > 0 ? attr.hammerTimings.join(", ") : "-";
|
||||
case "ringAlertsMaster":
|
||||
return <BoolBadge value={clock.ringAlertsMasterOn} yesLabel="ON" noLabel="OFF" />;
|
||||
case "totalPlaybacks":
|
||||
return stats.totalPlaybacks ?? 0;
|
||||
case "totalHammerStrikes":
|
||||
return stats.totalHammerStrikes ?? 0;
|
||||
case "totalWarnings":
|
||||
return stats.totalWarningsGiven ?? 0;
|
||||
case "warrantyActive":
|
||||
return <BoolBadge value={stats.warrantyActive} yesLabel="Active" noLabel="Expired" />;
|
||||
case "totalMelodies":
|
||||
return device.device_melodies_all?.length ?? 0;
|
||||
case "assignedUsers":
|
||||
return device.user_list?.length ?? 0;
|
||||
default:
|
||||
return "-";
|
||||
}
|
||||
};
|
||||
|
||||
// Apply client-side filters
|
||||
const filteredDevices = devices.filter((device) => {
|
||||
if (subscrStatusFilter === "active" && !isSubscriptionActive(device)) return false;
|
||||
if (subscrStatusFilter === "expired" && isSubscriptionActive(device)) return false;
|
||||
if (warrantyStatusFilter === "active" && !isWarrantyActive(device)) return false;
|
||||
if (warrantyStatusFilter === "expired" && isWarrantyActive(device)) return false;
|
||||
if (hasClockFilter === "yes" && !device.device_attributes?.hasClock) return false;
|
||||
if (hasClockFilter === "no" && device.device_attributes?.hasClock) return false;
|
||||
if (hasBellsFilter === "yes" && !device.device_attributes?.hasBells) return false;
|
||||
if (hasBellsFilter === "no" && device.device_attributes?.hasBells) return false;
|
||||
return true;
|
||||
});
|
||||
|
||||
const activeColumns = ALL_COLUMNS.filter((c) => isVisible(c.key));
|
||||
|
||||
const selectClass = "px-3 py-2 rounded-md text-sm cursor-pointer border";
|
||||
const selectStyle = {
|
||||
backgroundColor: "var(--bg-card)",
|
||||
color: "var(--text-primary)",
|
||||
borderColor: "var(--border-primary)",
|
||||
};
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className="flex items-center justify-between mb-6">
|
||||
@@ -78,39 +291,86 @@ export default function DeviceList() {
|
||||
placeholder="Search by name, location, or serial number..."
|
||||
/>
|
||||
<div className="flex flex-wrap gap-3 items-center">
|
||||
<select
|
||||
value={onlineFilter}
|
||||
onChange={(e) => setOnlineFilter(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)",
|
||||
}}
|
||||
>
|
||||
<select value={onlineFilter} onChange={(e) => setOnlineFilter(e.target.value)} className={selectClass} style={selectStyle}>
|
||||
<option value="">All Status</option>
|
||||
<option value="true">Online</option>
|
||||
<option value="false">Offline</option>
|
||||
</select>
|
||||
<select
|
||||
value={tierFilter}
|
||||
onChange={(e) => setTierFilter(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)",
|
||||
}}
|
||||
>
|
||||
<select value={tierFilter} onChange={(e) => setTierFilter(e.target.value)} className={selectClass} style={selectStyle}>
|
||||
<option value="">All Tiers</option>
|
||||
{TIER_OPTIONS.filter(Boolean).map((t) => (
|
||||
<option key={t} value={t}>
|
||||
{t.charAt(0).toUpperCase() + t.slice(1)}
|
||||
</option>
|
||||
<option key={t} value={t}>{t.charAt(0).toUpperCase() + t.slice(1)}</option>
|
||||
))}
|
||||
</select>
|
||||
<select value={subscrStatusFilter} onChange={(e) => setSubscrStatusFilter(e.target.value)} className={selectClass} style={selectStyle}>
|
||||
<option value="">Subscr Status</option>
|
||||
<option value="active">Active</option>
|
||||
<option value="expired">Expired</option>
|
||||
</select>
|
||||
<select value={warrantyStatusFilter} onChange={(e) => setWarrantyStatusFilter(e.target.value)} className={selectClass} style={selectStyle}>
|
||||
<option value="">Warranty Status</option>
|
||||
<option value="active">Active</option>
|
||||
<option value="expired">Expired</option>
|
||||
</select>
|
||||
<select value={hasClockFilter} onChange={(e) => setHasClockFilter(e.target.value)} className={selectClass} style={selectStyle}>
|
||||
<option value="">Has Clock</option>
|
||||
<option value="yes">Yes</option>
|
||||
<option value="no">No</option>
|
||||
</select>
|
||||
<select value={hasBellsFilter} onChange={(e) => setHasBellsFilter(e.target.value)} className={selectClass} style={selectStyle}>
|
||||
<option value="">Has Bells</option>
|
||||
<option value="yes">Yes</option>
|
||||
<option value="no">No</option>
|
||||
</select>
|
||||
|
||||
{/* Column visibility dropdown */}
|
||||
<div className="relative" ref={columnPickerRef}>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowColumnPicker((prev) => !prev)}
|
||||
className="px-3 py-2 rounded-md text-sm transition-colors cursor-pointer flex items-center gap-1.5 border"
|
||||
style={{
|
||||
borderColor: "var(--border-primary)",
|
||||
color: "var(--text-secondary)",
|
||||
}}
|
||||
>
|
||||
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 17V7m0 10a2 2 0 01-2 2H5a2 2 0 01-2-2V7a2 2 0 012-2h2a2 2 0 012 2m0 10a2 2 0 002 2h2a2 2 0 002-2M9 7a2 2 0 012-2h2a2 2 0 012 2m0 10V7m0 10a2 2 0 002 2h2a2 2 0 002-2V7a2 2 0 00-2-2h-2a2 2 0 00-2 2" />
|
||||
</svg>
|
||||
Columns
|
||||
</button>
|
||||
{showColumnPicker && (
|
||||
<div
|
||||
className="absolute right-0 top-full mt-1 z-20 rounded-lg shadow-lg py-2 w-52 border max-h-80 overflow-y-auto"
|
||||
style={{
|
||||
backgroundColor: "var(--bg-card)",
|
||||
borderColor: "var(--border-primary)",
|
||||
}}
|
||||
>
|
||||
{ALL_COLUMNS.map((col) => (
|
||||
<label
|
||||
key={col.key}
|
||||
className="flex items-center gap-2 px-3 py-1.5 text-sm cursor-pointer"
|
||||
style={{
|
||||
color: col.alwaysOn ? "var(--text-muted)" : "var(--text-primary)",
|
||||
}}
|
||||
>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={isVisible(col.key)}
|
||||
onChange={() => toggleColumn(col.key)}
|
||||
disabled={col.alwaysOn}
|
||||
className="h-3.5 w-3.5 rounded cursor-pointer"
|
||||
/>
|
||||
{col.label}
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<span className="flex items-center text-sm" style={{ color: "var(--text-muted)" }}>
|
||||
{total} {total === 1 ? "device" : "devices"}
|
||||
{filteredDevices.length} {filteredDevices.length === 1 ? "device" : "devices"}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
@@ -130,7 +390,7 @@ export default function DeviceList() {
|
||||
|
||||
{loading ? (
|
||||
<div className="text-center py-8" style={{ color: "var(--text-muted)" }}>Loading...</div>
|
||||
) : devices.length === 0 ? (
|
||||
) : filteredDevices.length === 0 ? (
|
||||
<div
|
||||
className="rounded-lg p-8 text-center text-sm border"
|
||||
style={{
|
||||
@@ -153,63 +413,39 @@ export default function DeviceList() {
|
||||
<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)" }}>Serial Number</th>
|
||||
<th className="px-4 py-3 text-left font-medium" style={{ color: "var(--text-secondary)" }}>Location</th>
|
||||
<th className="px-4 py-3 text-left font-medium" style={{ color: "var(--text-secondary)" }}>Tier</th>
|
||||
<th className="px-4 py-3 text-left font-medium" style={{ color: "var(--text-secondary)" }}>Bells</th>
|
||||
<th className="px-4 py-3 text-left font-medium" style={{ color: "var(--text-secondary)" }}>Users</th>
|
||||
{activeColumns.map((col) => (
|
||||
<th
|
||||
key={col.key}
|
||||
className={`px-4 py-3 text-left font-medium ${col.key === "status" ? "w-10" : ""}`}
|
||||
style={{ color: "var(--text-secondary)" }}
|
||||
>
|
||||
{col.key === "status" ? "" : col.label}
|
||||
</th>
|
||||
))}
|
||||
{canEdit && (
|
||||
<th className="px-4 py-3 text-left font-medium w-24" style={{ color: "var(--text-secondary)" }} />
|
||||
)}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{devices.map((device, index) => (
|
||||
{filteredDevices.map((device) => (
|
||||
<tr
|
||||
key={device.id}
|
||||
onClick={() => navigate(`/devices/${device.id}`)}
|
||||
className="cursor-pointer"
|
||||
style={{
|
||||
borderBottom: index < devices.length - 1 ? "1px solid var(--border-primary)" : "none",
|
||||
backgroundColor: hoveredRow === device.id ? "var(--bg-card-hover)" : "transparent",
|
||||
}}
|
||||
onMouseEnter={() => setHoveredRow(device.id)}
|
||||
onMouseLeave={() => setHoveredRow(null)}
|
||||
className="cursor-pointer transition-colors"
|
||||
style={{ borderBottom: "1px solid var(--border-secondary)" }}
|
||||
onMouseEnter={(e) => (e.currentTarget.style.backgroundColor = "var(--bg-card-hover)")}
|
||||
onMouseLeave={(e) => (e.currentTarget.style.backgroundColor = "transparent")}
|
||||
>
|
||||
<td className="px-4 py-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"}
|
||||
/>
|
||||
</td>
|
||||
<td className="px-4 py-3 font-medium" style={{ color: "var(--text-heading)" }}>
|
||||
{device.device_name || "Unnamed Device"}
|
||||
</td>
|
||||
<td className="px-4 py-3 font-mono text-xs" style={{ color: "var(--text-muted)" }}>
|
||||
{device.device_id || "-"}
|
||||
</td>
|
||||
<td className="px-4 py-3" style={{ color: "var(--text-primary)" }}>
|
||||
{device.device_location || "-"}
|
||||
</td>
|
||||
<td className="px-4 py-3">
|
||||
<span
|
||||
className="px-2 py-0.5 text-xs rounded-full capitalize"
|
||||
style={{ backgroundColor: "var(--badge-blue-bg)", color: "var(--badge-blue-text)" }}
|
||||
{activeColumns.map((col) => (
|
||||
<td
|
||||
key={col.key}
|
||||
className={`px-4 py-3 ${col.key === "status" ? "w-10" : ""}`}
|
||||
style={{ color: "var(--text-primary)" }}
|
||||
>
|
||||
{device.device_subscription?.subscrTier || "basic"}
|
||||
</span>
|
||||
</td>
|
||||
<td className="px-4 py-3" style={{ color: "var(--text-primary)" }}>
|
||||
{device.device_attributes?.totalBells ?? 0}
|
||||
</td>
|
||||
<td className="px-4 py-3" style={{ color: "var(--text-primary)" }}>
|
||||
{device.user_list?.length ?? 0}
|
||||
</td>
|
||||
{renderCellValue(col.key, device)}
|
||||
</td>
|
||||
))}
|
||||
{canEdit && (
|
||||
<td className="px-4 py-3">
|
||||
<div
|
||||
|
||||
Reference in New Issue
Block a user