Files
terra-view/templates/unit_detail.html
2025-12-16 04:38:06 +00:00

900 lines
43 KiB
HTML

{% extends "base.html" %}
{% block title %}Unit Detail - Seismo Fleet Manager{% endblock %}
{% block content %}
<div class="mb-6">
<!-- Breadcrumb Navigation -->
<nav class="flex mb-4 text-sm" aria-label="Breadcrumb">
<ol class="inline-flex items-center space-x-1 md:space-x-3">
<li class="inline-flex items-center">
<a href="/" class="text-gray-500 hover:text-seismo-orange dark:text-gray-400">
Dashboard
</a>
</li>
<li>
<div class="flex items-center">
<svg class="w-4 h-4 text-gray-400" fill="currentColor" viewBox="0 0 20 20">
<path fill-rule="evenodd" d="M7.293 14.707a1 1 0 010-1.414L10.586 10 7.293 6.707a1 1 0 011.414-1.414l4 4a1 1 0 010 1.414l-4 4a1 1 0 01-1.414 0z" clip-rule="evenodd"></path>
</svg>
<a href="/roster" class="ml-1 text-gray-500 hover:text-seismo-orange dark:text-gray-400">
Fleet Roster
</a>
</div>
</li>
<li aria-current="page">
<div class="flex items-center">
<svg class="w-4 h-4 text-gray-400" fill="currentColor" viewBox="0 0 20 20">
<path fill-rule="evenodd" d="M7.293 14.707a1 1 0 010-1.414L10.586 10 7.293 6.707a1 1 0 011.414-1.414l4 4a1 1 0 010 1.414l-4 4a1 1 0 01-1.414 0z" clip-rule="evenodd"></path>
</svg>
<span class="ml-1 text-gray-700 dark:text-gray-300 font-medium" id="breadcrumb-unit">Unit</span>
</div>
</li>
</ol>
</nav>
<div class="flex justify-between items-center">
<div class="flex items-center gap-2">
<h1 class="text-3xl font-bold text-gray-900 dark:text-white" id="pageTitle">Loading...</h1>
<button onclick="copyToClipboard(window.currentUnitId, this)" class="text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors p-1" title="Copy Unit ID">
<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z"></path>
</svg>
</button>
</div>
<div class="flex gap-3">
<button id="editButton" onclick="enterEditMode()" class="px-4 py-2 bg-seismo-orange hover:bg-orange-600 text-white rounded-lg transition-colors flex items-center gap-2">
<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"></path>
</svg>
Edit Unit
</button>
<button onclick="deleteUnit()" class="px-4 py-2 bg-red-600 hover:bg-red-700 text-white rounded-lg transition-colors flex items-center gap-2">
<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"></path>
</svg>
Delete Unit
</button>
</div>
</div>
</div>
<!-- Loading state -->
<div id="loadingState" class="rounded-xl shadow-lg bg-white dark:bg-slate-800 p-12 text-center">
<div class="animate-pulse">
<div class="h-4 bg-gray-200 dark:bg-gray-700 rounded w-3/4 mx-auto mb-4"></div>
<div class="h-4 bg-gray-200 dark:bg-gray-700 rounded w-1/2 mx-auto"></div>
</div>
</div>
<!-- Main content (hidden until loaded) -->
<div id="mainContent" class="hidden space-y-6">
<!-- Status Card -->
<div class="rounded-xl shadow-lg bg-white dark:bg-slate-800 p-6">
<div class="flex justify-between items-start mb-6">
<h2 class="text-xl font-semibold text-gray-900 dark:text-white">Status</h2>
<div class="flex items-center space-x-2">
<span id="statusIndicator" class="w-3 h-3 rounded-full"></span>
<span id="statusText" class="font-semibold"></span>
</div>
</div>
<div class="grid grid-cols-2 md:grid-cols-4 gap-4">
<div>
<span class="text-sm text-gray-500 dark:text-gray-400">Last Seen</span>
<p id="lastSeen" class="font-medium text-gray-900 dark:text-white">--</p>
</div>
<div>
<span class="text-sm text-gray-500 dark:text-gray-400">Age</span>
<p id="age" class="font-medium text-gray-900 dark:text-white">--</p>
</div>
<div>
<span class="text-sm text-gray-500 dark:text-gray-400">Deployed</span>
<p id="deployedStatus" class="font-medium text-gray-900 dark:text-white">--</p>
</div>
<div>
<span class="text-sm text-gray-500 dark:text-gray-400">Retired</span>
<p id="retiredStatus" class="font-medium text-gray-900 dark:text-white">--</p>
</div>
</div>
</div>
<!-- Location Map -->
<div id="mapCard" class="rounded-xl shadow-lg bg-white dark:bg-slate-800 p-6 hidden">
<h2 class="text-xl font-semibold text-gray-900 dark:text-white mb-4">Location</h2>
<div id="unit-map" style="height: 400px; width: 100%;" class="rounded-lg mb-4"></div>
<p id="locationText" class="text-sm text-gray-500 dark:text-gray-400"></p>
</div>
<!-- View Mode: Unit Information (Default) -->
<div id="viewMode" class="rounded-xl shadow-lg bg-white dark:bg-slate-800 p-6">
<h2 class="text-xl font-semibold text-gray-900 dark:text-white mb-6">Unit Information</h2>
<div class="space-y-6">
<!-- Basic Info Grid -->
<div class="grid grid-cols-1 md:grid-cols-2 gap-6">
<div>
<label class="text-sm font-medium text-gray-500 dark:text-gray-400">Device Type</label>
<p id="viewDeviceType" class="mt-1 text-gray-900 dark:text-white font-medium">--</p>
</div>
<div>
<label class="text-sm font-medium text-gray-500 dark:text-gray-400">Unit Type</label>
<p id="viewUnitType" class="mt-1 text-gray-900 dark:text-white font-medium">--</p>
</div>
<div>
<label class="text-sm font-medium text-gray-500 dark:text-gray-400">Project ID</label>
<p id="viewProjectId" class="mt-1 text-gray-900 dark:text-white font-medium">--</p>
</div>
<div>
<label class="text-sm font-medium text-gray-500 dark:text-gray-400">Address</label>
<p id="viewAddress" class="mt-1 text-gray-900 dark:text-white font-medium">--</p>
</div>
<div class="md:col-span-2">
<label class="text-sm font-medium text-gray-500 dark:text-gray-400">Coordinates</label>
<p id="viewCoordinates" class="mt-1 text-gray-900 dark:text-white font-medium font-mono text-sm">--</p>
</div>
</div>
<!-- Seismograph Info -->
<div id="viewSeismographFields" class="border-t border-gray-200 dark:border-gray-700 pt-6">
<h3 class="text-lg font-semibold text-gray-900 dark:text-white mb-4">Seismograph Information</h3>
<div class="grid grid-cols-1 md:grid-cols-2 gap-6">
<div>
<label class="text-sm font-medium text-gray-500 dark:text-gray-400">Last Calibrated</label>
<p id="viewLastCalibrated" class="mt-1 text-gray-900 dark:text-white font-medium">--</p>
</div>
<div>
<label class="text-sm font-medium text-gray-500 dark:text-gray-400">Next Calibration Due</label>
<p id="viewNextCalibrationDue" class="mt-1 text-gray-900 dark:text-white font-medium">--</p>
</div>
<div>
<label class="text-sm font-medium text-gray-500 dark:text-gray-400">Deployed With Modem</label>
<p id="viewDeployedWithModemId" class="mt-1 text-gray-900 dark:text-white font-medium">--</p>
</div>
</div>
</div>
<!-- Modem Info -->
<div id="viewModemFields" class="hidden border-t border-gray-200 dark:border-gray-700 pt-6">
<h3 class="text-lg font-semibold text-gray-900 dark:text-white mb-4">Modem Information</h3>
<div class="grid grid-cols-1 md:grid-cols-2 gap-6">
<div>
<label class="text-sm font-medium text-gray-500 dark:text-gray-400">IP Address</label>
<p id="viewIpAddress" class="mt-1 text-gray-900 dark:text-white font-medium">--</p>
</div>
<div>
<label class="text-sm font-medium text-gray-500 dark:text-gray-400">Phone Number</label>
<p id="viewPhoneNumber" class="mt-1 text-gray-900 dark:text-white font-medium">--</p>
</div>
<div>
<label class="text-sm font-medium text-gray-500 dark:text-gray-400">Hardware Model</label>
<p id="viewHardwareModel" class="mt-1 text-gray-900 dark:text-white font-medium">--</p>
</div>
</div>
</div>
<!-- Notes -->
<div class="border-t border-gray-200 dark:border-gray-700 pt-6">
<label class="text-sm font-medium text-gray-500 dark:text-gray-400">Notes</label>
<p id="viewNote" class="mt-1 text-gray-900 dark:text-white whitespace-pre-wrap">--</p>
</div>
<!-- Unit History Timeline -->
<div class="border-t border-gray-200 dark:border-gray-700 pt-6">
<h3 class="text-lg font-semibold text-gray-900 dark:text-white mb-4">Timeline</h3>
<div id="historyTimeline" class="space-y-3">
<p class="text-sm text-gray-500 dark:text-gray-400">Loading history...</p>
</div>
</div>
<!-- Photos -->
<div class="border-t border-gray-200 dark:border-gray-700 pt-6">
<div class="flex justify-between items-start mb-4">
<h3 class="text-lg font-semibold text-gray-900 dark:text-white">Photos</h3>
<div class="flex flex-col sm:flex-row gap-2">
<!-- Take Photo Button (Camera) -->
<label for="photoCameraUpload" class="px-4 py-2 bg-seismo-orange hover:bg-orange-600 text-white rounded-lg transition-colors cursor-pointer flex items-center gap-2 text-sm sm:text-base">
<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 9a2 2 0 012-2h.93a2 2 0 001.664-.89l.812-1.22A2 2 0 0110.07 4h3.86a2 2 0 011.664.89l.812 1.22A2 2 0 0018.07 7H19a2 2 0 012 2v9a2 2 0 01-2 2H5a2 2 0 01-2-2V9z"></path>
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 13a3 3 0 11-6 0 3 3 0 016 0z"></path>
</svg>
<span class="hidden sm:inline">Take Photo</span>
<span class="sm:hidden">Camera</span>
</label>
<!-- Choose from Library Button -->
<label for="photoLibraryUpload" class="px-4 py-2 bg-seismo-navy hover:bg-blue-800 text-white rounded-lg transition-colors cursor-pointer flex items-center gap-2 text-sm sm:text-base">
<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"></path>
</svg>
<span class="hidden sm:inline">Choose Photo</span>
<span class="sm:hidden">Library</span>
</label>
<input type="file" id="photoCameraUpload" accept="image/*" capture="environment" class="hidden" onchange="uploadPhoto(this.files[0])">
<input type="file" id="photoLibraryUpload" accept="image/*" class="hidden" onchange="uploadPhoto(this.files[0])">
</div>
</div>
<div id="photoGallery" class="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4">
<p class="text-sm text-gray-500 dark:text-gray-400 col-span-full">Loading photos...</p>
</div>
<div id="uploadStatus" class="hidden mt-4 p-4 rounded-lg"></div>
</div>
</div>
</div>
<!-- Edit Mode: Unit Information Form (Hidden by default) -->
<div id="editMode" class="hidden rounded-xl shadow-lg bg-white dark:bg-slate-800 p-6">
<div class="flex justify-between items-center mb-6">
<h2 class="text-xl font-semibold text-gray-900 dark:text-white">Edit Unit Information</h2>
<button onclick="cancelEdit()" class="text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200">
<svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
</svg>
</button>
</div>
<form id="editForm" class="space-y-6">
<div class="grid grid-cols-1 md:grid-cols-2 gap-6">
<!-- Device Type -->
<div>
<label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Device Type</label>
<select name="device_type" id="deviceType" onchange="toggleDetailFields()"
class="w-full px-4 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-slate-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-seismo-orange">
<option value="seismograph">Seismograph</option>
<option value="modem">Modem</option>
</select>
</div>
<!-- Unit Type -->
<div>
<label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Unit Type</label>
<input type="text" name="unit_type" id="unitType"
class="w-full px-4 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-slate-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-seismo-orange">
</div>
<!-- Project ID -->
<div>
<label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Project ID</label>
<input type="text" name="project_id" id="projectId"
class="w-full px-4 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-slate-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-seismo-orange">
</div>
<!-- Address -->
<div>
<label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Address</label>
<input type="text" name="address" id="address" placeholder="123 Main St, City, State"
class="w-full px-4 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-slate-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-seismo-orange">
</div>
<!-- Coordinates -->
<div class="md:col-span-2">
<label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Coordinates</label>
<input type="text" name="coordinates" id="coordinates" placeholder="34.0522,-118.2437"
class="w-full px-4 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-slate-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-seismo-orange font-mono">
</div>
</div>
<!-- Seismograph Fields -->
<div id="seismographFields" class="space-y-4 border-t border-gray-200 dark:border-gray-700 pt-4">
<h3 class="text-lg font-semibold text-gray-900 dark:text-white">Seismograph Information</h3>
<div class="grid grid-cols-1 md:grid-cols-2 gap-6">
<div>
<label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Last Calibrated</label>
<input type="date" name="last_calibrated" id="lastCalibrated"
class="w-full px-4 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-slate-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-seismo-orange">
</div>
<div>
<label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Next Calibration Due</label>
<input type="date" name="next_calibration_due" id="nextCalibrationDue"
class="w-full px-4 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-slate-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-seismo-orange">
</div>
<div>
<label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Deployed With Modem</label>
<input type="text" name="deployed_with_modem_id" id="deployedWithModemId" placeholder="Modem ID"
class="w-full px-4 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-slate-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-seismo-orange">
</div>
</div>
</div>
<!-- Modem Fields -->
<div id="modemFields" class="hidden space-y-4 border-t border-gray-200 dark:border-gray-700 pt-4">
<h3 class="text-lg font-semibold text-gray-900 dark:text-white">Modem Information</h3>
<div class="grid grid-cols-1 md:grid-cols-2 gap-6">
<div>
<label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">IP Address</label>
<input type="text" name="ip_address" id="ipAddress" placeholder="192.168.1.100"
class="w-full px-4 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-slate-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-seismo-orange">
</div>
<div>
<label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Phone Number</label>
<input type="text" name="phone_number" id="phoneNumber" placeholder="+1-555-0123"
class="w-full px-4 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-slate-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-seismo-orange">
</div>
<div>
<label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Hardware Model</label>
<input type="text" name="hardware_model" id="hardwareModel" placeholder="e.g., Raven XTV"
class="w-full px-4 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-slate-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-seismo-orange">
</div>
</div>
</div>
<!-- Checkboxes -->
<div class="flex items-center gap-6 border-t border-gray-200 dark:border-gray-700 pt-4">
<label class="flex items-center gap-2 cursor-pointer">
<input type="checkbox" name="deployed" id="deployed" value="true"
class="w-4 h-4 text-seismo-orange focus:ring-seismo-orange rounded">
<span class="text-sm text-gray-700 dark:text-gray-300">Deployed</span>
</label>
<label class="flex items-center gap-2 cursor-pointer">
<input type="checkbox" name="retired" id="retired" value="true"
class="w-4 h-4 text-seismo-orange focus:ring-seismo-orange rounded">
<span class="text-sm text-gray-700 dark:text-gray-300">Retired</span>
</label>
</div>
<!-- Notes -->
<div>
<label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Notes</label>
<textarea name="note" id="note" rows="4"
class="w-full px-4 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-slate-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-seismo-orange"></textarea>
</div>
<!-- Save/Cancel Buttons -->
<div class="flex gap-3">
<button type="submit" class="flex-1 px-6 py-3 bg-seismo-orange hover:bg-orange-600 text-white rounded-lg font-medium transition-colors">
Save Changes
</button>
<button type="button" onclick="cancelEdit()" class="px-6 py-3 bg-gray-300 dark:bg-gray-600 hover:bg-gray-400 dark:hover:bg-gray-500 text-gray-700 dark:text-white rounded-lg font-medium transition-colors">
Cancel
</button>
</div>
</form>
</div>
</div>
<script>
const unitId = "{{ unit_id }}";
let currentUnit = null;
let currentSnapshot = null;
let unitMap = null;
let mapMarker = null;
// Load unit data on page load
async function loadUnitData() {
try {
// Fetch unit roster data
const rosterResponse = await fetch(`/api/roster/${unitId}`);
if (!rosterResponse.ok) {
throw new Error('Unit not found');
}
currentUnit = await rosterResponse.json();
// Fetch snapshot data for status info
const snapshotResponse = await fetch('/api/status-snapshot');
if (snapshotResponse.ok) {
currentSnapshot = await snapshotResponse.json();
}
// Populate views
populateViewMode();
populateEditForm();
// Hide loading, show content
document.getElementById('loadingState').classList.add('hidden');
document.getElementById('mainContent').classList.remove('hidden');
// Initialize map after content is visible
setTimeout(() => {
initUnitMap();
}, 100);
} catch (error) {
alert(`Error loading unit: ${error.message}`);
window.location.href = '/roster';
}
}
// Populate view mode (read-only display)
function populateViewMode() {
// Update page title and store unit ID for copy function
window.currentUnitId = currentUnit.id;
document.getElementById('pageTitle').textContent = `Unit ${currentUnit.id}`;
document.getElementById('breadcrumb-unit').textContent = currentUnit.id;
// Get status info from snapshot
let unitStatus = null;
if (currentSnapshot && currentSnapshot.units) {
unitStatus = currentSnapshot.units[unitId];
}
// Status card
if (unitStatus) {
const statusColors = {
'OK': 'bg-green-500',
'Pending': 'bg-yellow-500',
'Missing': 'bg-red-500'
};
const statusTextColors = {
'OK': 'text-green-600 dark:text-green-400',
'Pending': 'text-yellow-600 dark:text-yellow-400',
'Missing': 'text-red-600 dark:text-red-400'
};
document.getElementById('statusIndicator').className = `w-3 h-3 rounded-full ${statusColors[unitStatus.status] || 'bg-gray-400'}`;
document.getElementById('statusText').className = `font-semibold ${statusTextColors[unitStatus.status] || 'text-gray-600'}`;
document.getElementById('statusText').textContent = unitStatus.status || 'Unknown';
// Format "Last Seen" with timezone-aware formatting
if (unitStatus.last && typeof formatFullTimestamp === 'function') {
document.getElementById('lastSeen').textContent = formatFullTimestamp(unitStatus.last);
} else {
document.getElementById('lastSeen').textContent = unitStatus.last || '--';
}
document.getElementById('age').textContent = unitStatus.age || '--';
} else {
document.getElementById('statusIndicator').className = 'w-3 h-3 rounded-full bg-gray-400';
document.getElementById('statusText').className = 'font-semibold text-gray-600 dark:text-gray-400';
document.getElementById('statusText').textContent = 'No status data';
document.getElementById('lastSeen').textContent = '--';
document.getElementById('age').textContent = '--';
}
document.getElementById('deployedStatus').textContent = currentUnit.deployed ? 'Yes' : 'No';
document.getElementById('retiredStatus').textContent = currentUnit.retired ? 'Yes' : 'No';
// Basic info
document.getElementById('viewDeviceType').textContent = currentUnit.device_type || '--';
document.getElementById('viewUnitType').textContent = currentUnit.unit_type || '--';
document.getElementById('viewProjectId').textContent = currentUnit.project_id || '--';
document.getElementById('viewAddress').textContent = currentUnit.address || '--';
document.getElementById('viewCoordinates').textContent = currentUnit.coordinates || '--';
// Seismograph fields
document.getElementById('viewLastCalibrated').textContent = currentUnit.last_calibrated || '--';
document.getElementById('viewNextCalibrationDue').textContent = currentUnit.next_calibration_due || '--';
document.getElementById('viewDeployedWithModemId').textContent = currentUnit.deployed_with_modem_id || '--';
// Modem fields
document.getElementById('viewIpAddress').textContent = currentUnit.ip_address || '--';
document.getElementById('viewPhoneNumber').textContent = currentUnit.phone_number || '--';
document.getElementById('viewHardwareModel').textContent = currentUnit.hardware_model || '--';
// Notes
document.getElementById('viewNote').textContent = currentUnit.note || '--';
// Show/hide fields based on device type
if (currentUnit.device_type === 'modem') {
document.getElementById('viewSeismographFields').classList.add('hidden');
document.getElementById('viewModemFields').classList.remove('hidden');
} else {
document.getElementById('viewSeismographFields').classList.remove('hidden');
document.getElementById('viewModemFields').classList.add('hidden');
}
}
// Populate edit form
function populateEditForm() {
document.getElementById('deviceType').value = currentUnit.device_type || 'seismograph';
document.getElementById('unitType').value = currentUnit.unit_type || '';
document.getElementById('projectId').value = currentUnit.project_id || '';
document.getElementById('address').value = currentUnit.address || '';
document.getElementById('coordinates').value = currentUnit.coordinates || '';
document.getElementById('deployed').checked = currentUnit.deployed;
document.getElementById('retired').checked = currentUnit.retired;
document.getElementById('note').value = currentUnit.note || '';
// Seismograph fields
document.getElementById('lastCalibrated').value = currentUnit.last_calibrated || '';
document.getElementById('nextCalibrationDue').value = currentUnit.next_calibration_due || '';
document.getElementById('deployedWithModemId').value = currentUnit.deployed_with_modem_id || '';
// Modem fields
document.getElementById('ipAddress').value = currentUnit.ip_address || '';
document.getElementById('phoneNumber').value = currentUnit.phone_number || '';
document.getElementById('hardwareModel').value = currentUnit.hardware_model || '';
// Show/hide fields based on device type
toggleDetailFields();
}
// Toggle device-specific fields
function toggleDetailFields() {
const deviceType = document.getElementById('deviceType').value;
const seismoFields = document.getElementById('seismographFields');
const modemFields = document.getElementById('modemFields');
if (deviceType === 'seismograph') {
seismoFields.classList.remove('hidden');
modemFields.classList.add('hidden');
} else {
seismoFields.classList.add('hidden');
modemFields.classList.remove('hidden');
}
}
// Enter edit mode
function enterEditMode() {
document.getElementById('viewMode').classList.add('hidden');
document.getElementById('editMode').classList.remove('hidden');
document.getElementById('editButton').classList.add('hidden');
}
// Cancel edit mode
function cancelEdit() {
document.getElementById('editMode').classList.add('hidden');
document.getElementById('viewMode').classList.remove('hidden');
document.getElementById('editButton').classList.remove('hidden');
// Reset form to current values
populateEditForm();
}
// Handle form submission
document.getElementById('editForm').addEventListener('submit', async function(e) {
e.preventDefault();
const formData = new FormData(this);
try {
const response = await fetch(`/api/roster/edit/${unitId}`, {
method: 'POST',
body: formData
});
if (response.ok) {
alert('Unit updated successfully!');
// Reload data and return to view mode
await loadUnitData();
cancelEdit();
} else {
const result = await response.json();
alert(`Error: ${result.detail || 'Unknown error'}`);
}
} catch (error) {
alert(`Error: ${error.message}`);
}
});
// Delete unit
async function deleteUnit() {
if (!confirm(`Are you sure you want to PERMANENTLY delete unit ${unitId}?\n\nThis action cannot be undone!`)) {
return;
}
try {
const response = await fetch(`/api/roster/${unitId}`, {
method: 'DELETE'
});
if (response.ok) {
alert('Unit deleted successfully');
window.location.href = '/roster';
} else {
const result = await response.json();
alert(`Error: ${result.detail || 'Unknown error'}`);
}
} catch (error) {
alert(`Error: ${error.message}`);
}
}
// Initialize unit location map (only called once)
function initUnitMap() {
if (!currentUnit.coordinates) {
document.getElementById('mapCard').classList.add('hidden');
return;
}
const coords = parseLocation(currentUnit.coordinates);
if (!coords) {
document.getElementById('mapCard').classList.add('hidden');
return;
}
const [lat, lon] = coords;
// Show the map card
document.getElementById('mapCard').classList.remove('hidden');
// Only initialize map if it doesn't exist
if (!unitMap) {
// Initialize map
unitMap = L.map('unit-map').setView([lat, lon], 13);
// Add OpenStreetMap tiles
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors',
maxZoom: 18
}).addTo(unitMap);
// Force map to update its size
setTimeout(() => {
unitMap.invalidateSize();
}, 100);
}
// Update marker (can be called multiple times)
updateMapMarker(lat, lon);
// Update location text
const locationParts = [];
if (currentUnit.address) {
locationParts.push(currentUnit.address);
}
locationParts.push(`Coordinates: ${lat.toFixed(6)}, ${lon.toFixed(6)}`);
document.getElementById('locationText').textContent = locationParts.join(' • ');
}
// Update map marker with current status
function updateMapMarker(lat, lon) {
// Remove old marker if it exists
if (mapMarker) {
mapMarker.remove();
}
// Get status color
let statusColor = 'gray';
let status = 'Unknown';
if (currentSnapshot && currentSnapshot.units && currentSnapshot.units[unitId]) {
const unitStatus = currentSnapshot.units[unitId];
status = unitStatus.status || 'Unknown';
statusColor = status === 'OK' ? 'green' : status === 'Pending' ? 'orange' : status === 'Missing' ? 'red' : 'gray';
}
// Add new marker
mapMarker = L.circleMarker([lat, lon], {
radius: 10,
fillColor: statusColor,
color: '#fff',
weight: 3,
opacity: 1,
fillOpacity: 0.8
}).addTo(unitMap).bindPopup(`
<div class="p-2">
<h3 class="font-bold text-lg">${currentUnit.id}</h3>
<p class="text-sm">Status: <span style="color: ${statusColor}">${status}</span></p>
<p class="text-sm">Type: ${currentUnit.device_type}</p>
</div>
`).openPopup();
}
function parseLocation(location) {
if (!location) return null;
// Try to parse as "lat,lon" format
const parts = location.split(',').map(s => s.trim());
if (parts.length === 2) {
const lat = parseFloat(parts[0]);
const lon = parseFloat(parts[1]);
if (!isNaN(lat) && !isNaN(lon) && lat >= -90 && lat <= 90 && lon >= -180 && lon <= 180) {
return [lat, lon];
}
}
return null;
}
// Load and display photos
async function loadPhotos() {
try {
const response = await fetch(`/api/unit/${unitId}/photos`);
if (!response.ok) {
throw new Error('Failed to load photos');
}
const data = await response.json();
const gallery = document.getElementById('photoGallery');
if (data.photos && data.photos.length > 0) {
gallery.innerHTML = '';
data.photo_urls.forEach((url, index) => {
const photoDiv = document.createElement('div');
photoDiv.className = 'relative group';
photoDiv.innerHTML = `
<img src="${url}" alt="Unit photo ${index + 1}"
class="w-full h-48 object-cover rounded-lg shadow cursor-pointer hover:shadow-lg transition-shadow"
onclick="window.open('${url}', '_blank')">
${index === 0 ? '<span class="absolute top-2 left-2 bg-seismo-orange text-white text-xs px-2 py-1 rounded">Primary</span>' : ''}
`;
gallery.appendChild(photoDiv);
});
} else {
gallery.innerHTML = '<p class="text-sm text-gray-500 dark:text-gray-400 col-span-full">No photos yet. Add a photo to get started.</p>';
}
} catch (error) {
console.error('Error loading photos:', error);
document.getElementById('photoGallery').innerHTML = '<p class="text-sm text-red-500 col-span-full">Failed to load photos</p>';
}
}
// Upload photo with EXIF metadata extraction
async function uploadPhoto(file) {
if (!file) return;
const statusDiv = document.getElementById('uploadStatus');
statusDiv.className = 'mt-4 p-4 rounded-lg bg-blue-100 dark:bg-blue-900 text-blue-800 dark:text-blue-200';
statusDiv.textContent = 'Uploading photo and extracting metadata...';
statusDiv.classList.remove('hidden');
const formData = new FormData();
formData.append('photo', file);
try {
const response = await fetch(`/api/unit/${unitId}/upload-photo`, {
method: 'POST',
body: formData
});
if (!response.ok) {
throw new Error('Upload failed');
}
const result = await response.json();
// Show success message with metadata info
let message = 'Photo uploaded successfully!';
if (result.metadata && result.metadata.coordinates) {
message += ` GPS location detected: ${result.metadata.coordinates}`;
if (result.coordinates_updated) {
message += ' (Unit coordinates updated automatically)';
}
} else {
message += ' No GPS data found in photo.';
}
statusDiv.className = 'mt-4 p-4 rounded-lg bg-green-100 dark:bg-green-900 text-green-800 dark:text-green-200';
statusDiv.textContent = message;
// Reload photos and unit data
await loadPhotos();
if (result.coordinates_updated) {
await loadUnitData();
}
// Hide status after 5 seconds
setTimeout(() => {
statusDiv.classList.add('hidden');
}, 5000);
// Reset both file inputs
document.getElementById('photoCameraUpload').value = '';
document.getElementById('photoLibraryUpload').value = '';
} catch (error) {
console.error('Error uploading photo:', error);
statusDiv.className = 'mt-4 p-4 rounded-lg bg-red-100 dark:bg-red-900 text-red-800 dark:text-red-200';
statusDiv.textContent = `Error uploading photo: ${error.message}`;
// Hide error after 5 seconds
setTimeout(() => {
statusDiv.classList.add('hidden');
}, 5000);
}
}
// Load and display unit history timeline
async function loadUnitHistory() {
try {
const response = await fetch(`/api/roster/history/${unitId}`);
if (!response.ok) {
throw new Error('Failed to load history');
}
const data = await response.json();
const timeline = document.getElementById('historyTimeline');
if (data.history && data.history.length > 0) {
timeline.innerHTML = '';
data.history.forEach(entry => {
const timelineEntry = createTimelineEntry(entry);
timeline.appendChild(timelineEntry);
});
} else {
timeline.innerHTML = '<p class="text-sm text-gray-500 dark:text-gray-400">No history yet. Changes will appear here.</p>';
}
} catch (error) {
console.error('Error loading history:', error);
document.getElementById('historyTimeline').innerHTML = '<p class="text-sm text-red-500">Failed to load history</p>';
}
}
// Create a timeline entry element
function createTimelineEntry(entry) {
const div = document.createElement('div');
div.className = 'flex gap-3 p-3 rounded-lg bg-gray-50 dark:bg-slate-700/50';
// Icon based on change type
const icons = {
'note_change': `<svg class="w-5 h-5 text-blue-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"></path>
</svg>`,
'deployed_change': `<svg class="w-5 h-5 text-green-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"></path>
</svg>`,
'retired_change': `<svg class="w-5 h-5 text-orange-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"></path>
</svg>`
};
const icon = icons[entry.change_type] || `<svg class="w-5 h-5 text-gray-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path>
</svg>`;
// Format change description
let description = '';
if (entry.change_type === 'note_change') {
description = `<strong>Note changed</strong>`;
if (entry.old_value) {
description += `<br><span class="text-xs text-gray-500 dark:text-gray-400">From: "${entry.old_value}"</span>`;
}
if (entry.new_value) {
description += `<br><span class="text-xs text-gray-600 dark:text-gray-300">To: "${entry.new_value}"</span>`;
}
} else if (entry.change_type === 'deployed_change') {
description = `<strong>Status changed to ${entry.new_value}</strong>`;
} else if (entry.change_type === 'retired_change') {
description = `<strong>Marked as ${entry.new_value}</strong>`;
} else {
description = `<strong>${entry.field_name} changed</strong>`;
if (entry.old_value && entry.new_value) {
description += `<br><span class="text-xs text-gray-500 dark:text-gray-400">${entry.old_value}${entry.new_value}</span>`;
}
}
// Format timestamp
const timestamp = new Date(entry.changed_at).toLocaleString();
div.innerHTML = `
<div class="flex-shrink-0">
${icon}
</div>
<div class="flex-1 min-w-0">
<div class="text-sm text-gray-900 dark:text-white">
${description}
</div>
<div class="text-xs text-gray-500 dark:text-gray-400 mt-1">
${timestamp}
${entry.source !== 'manual' ? `<span class="ml-2 px-2 py-0.5 bg-gray-200 dark:bg-gray-600 rounded text-xs">${entry.source}</span>` : ''}
</div>
</div>
<div class="flex-shrink-0">
<button onclick="deleteHistoryEntry(${entry.id})" class="text-gray-400 hover:text-red-500 transition-colors" title="Delete this history entry">
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"></path>
</svg>
</button>
</div>
`;
return div;
}
// Delete a history entry
async function deleteHistoryEntry(historyId) {
if (!confirm('Are you sure you want to delete this history entry?')) {
return;
}
try {
const response = await fetch(`/api/roster/history/${historyId}`, {
method: 'DELETE'
});
if (response.ok) {
// Reload history
await loadUnitHistory();
} else {
const result = await response.json();
alert(`Error: ${result.detail || 'Unknown error'}`);
}
} catch (error) {
alert(`Error: ${error.message}`);
}
}
// Load data when page loads
loadUnitData().then(() => {
loadPhotos();
loadUnitHistory();
});
</script>
{% endblock %}