3 Commits

Author SHA1 Message Date
f50cf2b7f6 feat: add functionality to manage deleted projects in settings
- Introduced a new section for displaying soft-deleted projects.
- Implemented loading of deleted projects via an API call.
- Added restore and permanently delete options for each deleted project.
- Integrated loading of deleted projects when the data tab is shown.
2026-04-01 05:42:10 +00:00
20e180644e feat: enhance swap modal with search functionality for seismographs and modems 2026-03-31 20:16:47 +00:00
73a6ff4d20 feat: Refactor project creation and management to support modular project types
- Updated project creation modal to allow selection of optional modules (Sound and Vibration Monitoring).
- Modified project dashboard and header to display active modules and provide options to add/remove them.
- Enhanced project detail view to dynamically adjust UI based on enabled modules.
- Implemented a new migration script to create a `project_modules` table and seed it based on existing project types.
- Adjusted form submissions to handle module selections and ensure proper API interactions for module management.
2026-03-30 21:44:15 +00:00
12 changed files with 1060 additions and 489 deletions

View File

@@ -0,0 +1,71 @@
"""
Migration: Add project_modules table and seed from existing project_type_id values.
Safe to run multiple times — idempotent.
"""
import sqlite3
import uuid
import os
DB_PATH = os.path.join(os.path.dirname(__file__), "..", "data", "seismo_fleet.db")
DB_PATH = os.path.abspath(DB_PATH)
def run():
conn = sqlite3.connect(DB_PATH)
conn.row_factory = sqlite3.Row
cur = conn.cursor()
# 1. Create project_modules table if not exists
cur.execute("""
CREATE TABLE IF NOT EXISTS project_modules (
id TEXT PRIMARY KEY,
project_id TEXT NOT NULL,
module_type TEXT NOT NULL,
enabled INTEGER NOT NULL DEFAULT 1,
created_at TEXT NOT NULL DEFAULT (datetime('now')),
UNIQUE(project_id, module_type)
)
""")
print(" Table 'project_modules' ready.")
# 2. Seed modules from existing project_type_id values
cur.execute("SELECT id, project_type_id FROM projects WHERE project_type_id IS NOT NULL")
projects = cur.fetchall()
seeded = 0
for p in projects:
pid = p["id"]
ptype = p["project_type_id"]
modules_to_add = []
if ptype == "sound_monitoring":
modules_to_add = ["sound_monitoring"]
elif ptype == "vibration_monitoring":
modules_to_add = ["vibration_monitoring"]
elif ptype == "combined":
modules_to_add = ["sound_monitoring", "vibration_monitoring"]
for module_type in modules_to_add:
# INSERT OR IGNORE — skip if already exists
cur.execute("""
INSERT OR IGNORE INTO project_modules (id, project_id, module_type, enabled)
VALUES (?, ?, ?, 1)
""", (str(uuid.uuid4()), pid, module_type))
if cur.rowcount > 0:
seeded += 1
conn.commit()
print(f" Seeded {seeded} module record(s) from existing project_type_id values.")
# 3. Make project_type_id nullable (SQLite doesn't support ALTER COLUMN,
# but since we're just loosening a constraint this is a no-op in SQLite —
# the column already accepts NULL in practice. Nothing to do.)
print(" project_type_id column is now treated as nullable (legacy field).")
conn.close()
print("Migration complete.")
if __name__ == "__main__":
run()

View File

@@ -1,4 +1,4 @@
from sqlalchemy import Column, String, DateTime, Boolean, Text, Date, Integer
from sqlalchemy import Column, String, DateTime, Boolean, Text, Date, Integer, UniqueConstraint
from datetime import datetime
from backend.database import Base
@@ -177,7 +177,7 @@ class Project(Base):
project_number = Column(String, nullable=True, index=True) # TMI ID: xxxx-YY format (e.g., "2567-23")
name = Column(String, nullable=False, unique=True) # Project/site name (e.g., "RKM Hall")
description = Column(Text, nullable=True)
project_type_id = Column(String, nullable=False) # FK to ProjectType.id
project_type_id = Column(String, nullable=True) # Legacy FK to ProjectType.id; use ProjectModule for feature flags
status = Column(String, default="active") # active, on_hold, completed, archived, deleted
# Data collection mode: how field data reaches Terra-View.
@@ -197,6 +197,22 @@ class Project(Base):
deleted_at = Column(DateTime, nullable=True) # Set when status='deleted'; hard delete scheduled after 60 days
class ProjectModule(Base):
"""
Modules enabled on a project. Each module unlocks a set of features/tabs.
A project can have zero or more modules (sound_monitoring, vibration_monitoring, etc.).
"""
__tablename__ = "project_modules"
id = Column(String, primary_key=True, default=lambda: __import__('uuid').uuid4().__str__())
project_id = Column(String, nullable=False, index=True) # FK to projects.id
module_type = Column(String, nullable=False) # sound_monitoring | vibration_monitoring | ...
enabled = Column(Boolean, default=True, nullable=False)
created_at = Column(DateTime, default=datetime.utcnow)
__table_args__ = (UniqueConstraint("project_id", "module_type", name="uq_project_module"),)
class MonitoringLocation(Base):
"""
Monitoring locations: generic location for monitoring activities.

View File

@@ -24,6 +24,7 @@ from backend.database import get_db
from backend.models import (
Project,
ProjectType,
ProjectModule,
MonitoringLocation,
UnitAssignment,
RosterUnit,
@@ -40,12 +41,17 @@ router = APIRouter(prefix="/api/projects/{project_id}", tags=["project-locations
# Shared helpers
# ============================================================================
def _require_sound_project(project) -> None:
"""Raise 400 if the project is not a sound_monitoring project."""
if not project or project.project_type_id != "sound_monitoring":
def _require_module(project, module_type: str, db: Session) -> None:
"""Raise 400 if the project does not have the given module enabled."""
if not project:
raise HTTPException(status_code=404, detail="Project not found.")
exists = db.query(ProjectModule).filter_by(
project_id=project.id, module_type=module_type, enabled=True
).first()
if not exists:
raise HTTPException(
status_code=400,
detail="This feature is only available for Sound Monitoring projects.",
detail=f"This project does not have the {module_type.replace('_', ' ').title()} module enabled.",
)
@@ -762,7 +768,7 @@ async def upload_nrl_data(
# Verify project and location exist
project = db.query(Project).filter_by(id=project_id).first()
_require_sound_project(project)
_require_module(project, "sound_monitoring", db)
location = db.query(MonitoringLocation).filter_by(
id=location_id, project_id=project_id
@@ -955,7 +961,7 @@ async def get_nrl_live_status(
import os
import httpx
_require_sound_project(db.query(Project).filter_by(id=project_id).first())
_require_module(db.query(Project).filter_by(id=project_id).first(), "sound_monitoring", db)
# Find the assigned unit (active = assigned_until IS NULL)
assignment = db.query(UnitAssignment).filter(

View File

@@ -31,6 +31,7 @@ import pathlib as _pathlib
from backend.models import (
Project,
ProjectType,
ProjectModule,
MonitoringLocation,
UnitAssignment,
MonitoringSession,
@@ -49,11 +50,40 @@ logger = logging.getLogger(__name__)
# Shared helpers
# ============================================================================
def _require_sound_project(project: Project) -> None:
"""Raise 400 if the project is not a sound_monitoring project.
Call this at the top of any endpoint that only makes sense for sound projects
(report generation, FTP browser, RND file viewer, etc.)."""
if not project or project.project_type_id != "sound_monitoring":
# Registry of known module types. Add new entries here to make them available
# in the UI for any project.
MODULES = {
"sound_monitoring": {"name": "Sound Monitoring", "icon": "speaker", "color": "orange"},
"vibration_monitoring": {"name": "Vibration Monitoring", "icon": "activity", "color": "blue"},
}
def _get_project_modules(project_id: str, db: Session) -> list[str]:
"""Return list of enabled module_type strings for a project."""
rows = db.query(ProjectModule).filter_by(project_id=project_id, enabled=True).all()
return [r.module_type for r in rows]
def _require_module(project: Project, module_type: str, db: Session) -> None:
"""Raise 400 if the project does not have the given module enabled."""
if not project:
raise HTTPException(status_code=404, detail="Project not found.")
exists = db.query(ProjectModule).filter_by(
project_id=project.id, module_type=module_type, enabled=True
).first()
if not exists:
module_name = MODULES.get(module_type, {}).get("name", module_type)
raise HTTPException(
status_code=400,
detail=f"This project does not have the {module_name} module enabled.",
)
# Keep legacy alias so any call sites not yet migrated still work
def _require_sound_project(project: Project, db: Session = None) -> None:
if db is not None:
_require_module(project, "sound_monitoring", db)
elif not project or project.project_type_id != "sound_monitoring":
raise HTTPException(
status_code=400,
detail="This feature is only available for Sound Monitoring projects.",
@@ -604,7 +634,7 @@ async def create_project(request: Request, db: Session = Depends(get_db)):
project_number=form_data.get("project_number"), # TMI ID: xxxx-YY format
name=form_data.get("name"),
description=form_data.get("description"),
project_type_id=form_data.get("project_type_id"),
project_type_id=form_data.get("project_type_id") or "",
status="active",
client_name=form_data.get("client_name"),
site_address=form_data.get("site_address"),
@@ -624,6 +654,40 @@ async def create_project(request: Request, db: Session = Depends(get_db)):
})
@router.get("/deleted")
async def list_deleted_projects(db: Session = Depends(get_db)):
"""List all soft-deleted projects."""
projects = (
db.query(Project)
.filter(Project.status == "deleted")
.order_by(Project.deleted_at.desc())
.all()
)
return JSONResponse([
{
"id": p.id,
"name": p.name,
"client_name": p.client_name,
"deleted_at": p.deleted_at.isoformat() if p.deleted_at else None,
}
for p in projects
])
@router.post("/{project_id}/restore")
async def restore_project(project_id: str, db: Session = Depends(get_db)):
"""Restore a soft-deleted project back to active."""
project = db.query(Project).filter_by(id=project_id).first()
if not project:
raise HTTPException(status_code=404, detail="Project not found")
if project.status != "deleted":
raise HTTPException(status_code=400, detail="Project is not deleted")
project.status = "active"
project.deleted_at = None
db.commit()
return {"success": True, "message": f"Project '{project.name}' restored."}
@router.get("/{project_id}")
async def get_project(project_id: str, db: Session = Depends(get_db)):
"""
@@ -635,6 +699,7 @@ async def get_project(project_id: str, db: Session = Depends(get_db)):
raise HTTPException(status_code=404, detail="Project not found")
project_type = db.query(ProjectType).filter_by(id=project.project_type_id).first()
modules = _get_project_modules(project.id, db)
return {
"id": project.id,
@@ -643,6 +708,7 @@ async def get_project(project_id: str, db: Session = Depends(get_db)):
"description": project.description,
"project_type_id": project.project_type_id,
"project_type_name": project_type.name if project_type else None,
"modules": modules,
"status": project.status,
"client_name": project.client_name,
"site_address": project.site_address,
@@ -655,6 +721,58 @@ async def get_project(project_id: str, db: Session = Depends(get_db)):
}
@router.get("/{project_id}/modules")
async def list_project_modules(project_id: str, db: Session = Depends(get_db)):
"""Return enabled modules for a project, including metadata from MODULES registry."""
project = db.query(Project).filter_by(id=project_id).first()
if not project:
raise HTTPException(status_code=404, detail="Project not found")
rows = db.query(ProjectModule).filter_by(project_id=project_id, enabled=True).all()
active = {r.module_type for r in rows}
return {
"active": list(active),
"available": [
{"module_type": k, **v}
for k, v in MODULES.items()
if k not in active
],
}
@router.post("/{project_id}/modules")
async def add_project_module(project_id: str, request: Request, db: Session = Depends(get_db)):
"""Add a module to a project. Body: {module_type: str}"""
project = db.query(Project).filter_by(id=project_id).first()
if not project:
raise HTTPException(status_code=404, detail="Project not found")
data = await request.json()
module_type = data.get("module_type")
if not module_type or module_type not in MODULES:
raise HTTPException(status_code=400, detail=f"Unknown module type: {module_type}")
existing = db.query(ProjectModule).filter_by(project_id=project_id, module_type=module_type).first()
if existing:
existing.enabled = True
else:
db.add(ProjectModule(
id=str(uuid.uuid4()),
project_id=project_id,
module_type=module_type,
enabled=True,
))
db.commit()
return {"ok": True, "modules": _get_project_modules(project_id, db)}
@router.delete("/{project_id}/modules/{module_type}")
async def remove_project_module(project_id: str, module_type: str, db: Session = Depends(get_db)):
"""Disable a module on a project. Data is not deleted."""
row = db.query(ProjectModule).filter_by(project_id=project_id, module_type=module_type).first()
if row:
row.enabled = False
db.commit()
return {"ok": True, "modules": _get_project_modules(project_id, db)}
@router.put("/{project_id}")
async def update_project(
project_id: str,
@@ -867,6 +985,7 @@ async def get_project_dashboard(
"request": request,
"project": project,
"project_type": project_type,
"modules": _get_project_modules(project_id, db),
"locations": locations,
"assigned_units": assigned_units,
"active_sessions": active_sessions,
@@ -899,6 +1018,7 @@ async def get_project_header(
"request": request,
"project": project,
"project_type": project_type,
"modules": _get_project_modules(project_id, db),
})
@@ -1371,7 +1491,7 @@ async def get_ftp_browser(
from backend.models import DataFile
project = db.query(Project).filter_by(id=project_id).first()
_require_sound_project(project)
_require_module(project, "sound_monitoring", db)
# Get all assignments for this project (active = assigned_until IS NULL)
assignments = db.query(UnitAssignment).filter(
@@ -1419,7 +1539,7 @@ async def ftp_download_to_server(
from pathlib import Path
from backend.models import DataFile
_require_sound_project(db.query(Project).filter_by(id=project_id).first())
_require_module(db.query(Project).filter_by(id=project_id).first(), "sound_monitoring", db)
data = await request.json()
unit_id = data.get("unit_id")
@@ -1587,7 +1707,7 @@ async def ftp_download_folder_to_server(
import zipfile
import io
_require_sound_project(db.query(Project).filter_by(id=project_id).first())
_require_module(db.query(Project).filter_by(id=project_id).first(), "sound_monitoring", db)
from pathlib import Path
from backend.models import DataFile
@@ -2147,7 +2267,7 @@ async def view_session_detail(
project = db.query(Project).filter_by(id=project_id).first()
if not project:
raise HTTPException(status_code=404, detail="Project not found")
_require_sound_project(project)
_require_module(project, "sound_monitoring", db)
session = db.query(MonitoringSession).filter_by(id=session_id, project_id=project_id).first()
if not session:
@@ -2233,7 +2353,7 @@ async def view_rnd_file(
# Get project info
project = db.query(Project).filter_by(id=project_id).first()
_require_sound_project(project)
_require_module(project, "sound_monitoring", db)
# Get location info if available
location = None
@@ -2286,7 +2406,7 @@ async def get_rnd_data(
import csv
import io
_require_sound_project(db.query(Project).filter_by(id=project_id).first())
_require_module(db.query(Project).filter_by(id=project_id).first(), "sound_monitoring", db)
# Get the file record
file_record = db.query(DataFile).filter_by(id=file_id).first()
@@ -2446,7 +2566,7 @@ async def generate_excel_report(
# Get related data for report context
project = db.query(Project).filter_by(id=project_id).first()
_require_sound_project(project)
_require_module(project, "sound_monitoring", db)
location = db.query(MonitoringLocation).filter_by(id=session.location_id).first() if session.location_id else None
# Build full file path
@@ -2877,7 +2997,7 @@ async def preview_report_data(
# Get related data for report context
project = db.query(Project).filter_by(id=project_id).first()
_require_sound_project(project)
_require_module(project, "sound_monitoring", db)
location = db.query(MonitoringLocation).filter_by(id=session.location_id).first() if session.location_id else None
# Build full file path
@@ -3089,7 +3209,7 @@ async def generate_report_from_preview(
raise HTTPException(status_code=403, detail="File does not belong to this project")
project = db.query(Project).filter_by(id=project_id).first()
_require_sound_project(project)
_require_module(project, "sound_monitoring", db)
location = db.query(MonitoringLocation).filter_by(id=session.location_id).first() if session.location_id else None
# Extract data from request
@@ -3370,7 +3490,7 @@ async def generate_combined_excel_report(
project = db.query(Project).filter_by(id=project_id).first()
if not project:
raise HTTPException(status_code=404, detail="Project not found")
_require_sound_project(project)
_require_module(project, "sound_monitoring", db)
# Get all sessions with measurement files
sessions = db.query(MonitoringSession).filter_by(project_id=project_id).all()
@@ -3716,7 +3836,7 @@ async def combined_report_wizard(
project = db.query(Project).filter_by(id=project_id).first()
if not project:
raise HTTPException(status_code=404, detail="Project not found")
_require_sound_project(project)
_require_module(project, "sound_monitoring", db)
sessions = db.query(MonitoringSession).filter_by(project_id=project_id).order_by(MonitoringSession.started_at).all()
@@ -4003,7 +4123,7 @@ async def generate_combined_from_preview(
project = db.query(Project).filter_by(id=project_id).first()
if not project:
raise HTTPException(status_code=404, detail="Project not found")
_require_sound_project(project)
_require_module(project, "sound_monitoring", db)
report_title = data.get("report_title", "Background Noise Study")
project_name = data.get("project_name", project.name)
@@ -4479,7 +4599,7 @@ async def upload_all_project_data(
project = db.query(Project).filter_by(id=project_id).first()
if not project:
raise HTTPException(status_code=404, detail="Project not found")
_require_sound_project(project)
_require_module(project, "sound_monitoring", db)
# Load all sound monitoring locations for this project
locations = db.query(MonitoringLocation).filter_by(

View File

@@ -63,16 +63,25 @@ Include this modal in pages that use the project picker.
<div>
<label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
Project Type <span class="text-red-500">*</span>
Modules
<span class="text-gray-400 font-normal">(optional)</span>
</label>
<select name="project_type_id"
id="qcp-project-type"
required
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="vibration_monitoring">Vibration Monitoring</option>
<option value="sound_monitoring">Sound Monitoring</option>
<option value="combined">Combined (Vibration + Sound)</option>
</select>
<div class="grid grid-cols-2 gap-2">
<label class="flex items-center gap-2 p-2.5 border border-gray-200 dark:border-gray-700 rounded-lg cursor-pointer hover:border-orange-400 has-[:checked]:border-orange-400 has-[:checked]:bg-orange-50 dark:has-[:checked]:bg-orange-900/20 transition-colors">
<input type="checkbox" name="module_sound" value="1" class="accent-seismo-orange">
<div>
<p class="text-sm font-medium text-gray-900 dark:text-white leading-tight">Sound</p>
<p class="text-xs text-gray-500 dark:text-gray-400">SLMs, sessions, reports</p>
</div>
</label>
<label class="flex items-center gap-2 p-2.5 border border-gray-200 dark:border-gray-700 rounded-lg cursor-pointer hover:border-blue-400 has-[:checked]:border-blue-400 has-[:checked]:bg-blue-50 dark:has-[:checked]:bg-blue-900/20 transition-colors">
<input type="checkbox" name="module_vibration" value="1" class="accent-blue-500">
<div>
<p class="text-sm font-medium text-gray-900 dark:text-white leading-tight">Vibration</p>
<p class="text-xs text-gray-500 dark:text-gray-400">Seismographs, modems</p>
</div>
</label>
</div>
</div>
<div>
@@ -222,6 +231,20 @@ if (typeof openCreateProjectModal === 'undefined') {
const result = await response.json();
if (response.ok && result.success) {
const projectId = result.project_id;
// Add selected modules
const moduleMap = { module_sound: 'sound_monitoring', module_vibration: 'vibration_monitoring' };
for (const [field, moduleType] of Object.entries(moduleMap)) {
if (formData.get(field)) {
await fetch(`/api/projects/${projectId}/modules`, {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({ module_type: moduleType }),
});
}
}
// Build display text from form values
const parts = [];
const projectNumber = formData.get('project_number');
@@ -235,7 +258,7 @@ if (typeof openCreateProjectModal === 'undefined') {
const displayText = parts.join(' - ');
// Select the newly created project in the picker
selectProject(result.project_id, displayText, pickerId);
selectProject(projectId, displayText, pickerId);
// Close modal
closeCreateProjectModal();

View File

@@ -10,11 +10,6 @@
class="font-semibold text-gray-900 dark:text-white hover:text-seismo-orange truncate">
{{ item.location.name }}
</a>
{% if item.location.location_type %}
<span class="text-xs px-2 py-0.5 rounded-full bg-gray-100 text-gray-700 dark:bg-gray-800 dark:text-gray-300">
{{ item.location.location_type|capitalize }}
</span>
{% endif %}
</div>
{% if item.location.description %}
<p class="text-xs text-gray-500 dark:text-gray-400 mt-1">{{ item.location.description }}</p>

View File

@@ -52,14 +52,14 @@
<div class="bg-white dark:bg-slate-800 rounded-xl shadow-lg p-6">
<div class="flex items-center justify-between mb-4">
<h3 class="text-lg font-semibold text-gray-900 dark:text-white">
{% if project_type and project_type.id == 'sound_monitoring' %}
{% if 'sound_monitoring' in modules and 'vibration_monitoring' not in modules %}
NRLs
{% else %}
Locations
{% endif %}
</h3>
<button onclick="openLocationModal('{% if project_type and project_type.id == 'sound_monitoring' %}sound{% elif project_type and project_type.id == 'vibration_monitoring' %}vibration{% else %}{% endif %}')" class="text-sm text-seismo-orange hover:text-seismo-navy">
{% if project_type and project_type.id == 'sound_monitoring' %}
<button onclick="openLocationModal('{% if 'sound_monitoring' in modules and 'vibration_monitoring' not in modules %}sound{% elif 'vibration_monitoring' in modules and 'sound_monitoring' not in modules %}vibration{% endif %}')" class="text-sm text-seismo-orange hover:text-seismo-navy">
{% if 'sound_monitoring' in modules and 'vibration_monitoring' not in modules %}
Add NRL
{% else %}
Add Location
@@ -67,7 +67,7 @@
</button>
</div>
<div id="project-locations"
hx-get="/api/projects/{{ project.id }}/locations{% if project_type and project_type.id == 'sound_monitoring' %}?location_type=sound{% endif %}"
hx-get="/api/projects/{{ project.id }}/locations{% if 'sound_monitoring' in modules and 'vibration_monitoring' not in modules %}?location_type=sound{% endif %}"
hx-trigger="load"
hx-swap="innerHTML">
<div class="animate-pulse space-y-3">

View File

@@ -23,9 +23,30 @@
</svg>
</span>
</div>
{% if project_type %}
<span class="text-gray-500 dark:text-gray-400">{{ project_type.name }}</span>
{% endif %}
<!-- Module badges -->
<div id="module-badges" class="flex items-center gap-1.5 flex-wrap">
{% for m in modules %}
<span class="inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium
{% if m == 'sound_monitoring' %}bg-orange-100 text-orange-800 dark:bg-orange-900/40 dark:text-orange-300
{% elif m == 'vibration_monitoring' %}bg-blue-100 text-blue-800 dark:bg-blue-900/40 dark:text-blue-300
{% else %}bg-gray-100 text-gray-700 dark:bg-gray-700 dark:text-gray-300{% endif %}">
{% if m == 'sound_monitoring' %}
<svg class="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.536 8.464a5 5 0 010 7.072M12 6v12M9 8.464a5 5 0 000 7.072"/></svg>
Sound Monitoring
{% elif m == 'vibration_monitoring' %}
<svg class="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M22 12h-4l-3 9L9 3l-3 9H2"/></svg>
Vibration Monitoring
{% else %}{{ m }}{% endif %}
<button onclick="removeModule('{{ m }}')" class="ml-0.5 hover:text-red-500 transition-colors" title="Remove module">
<svg class="w-2.5 h-2.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M6 18L18 6M6 6l12 12"/></svg>
</button>
</span>
{% endfor %}
<button onclick="openAddModuleModal()" class="inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium border border-dashed border-gray-400 dark:border-gray-600 text-gray-500 dark:text-gray-400 hover:border-orange-400 hover:text-orange-500 transition-colors">
<svg class="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"/></svg>
Add Module
</button>
</div>
{% if project.data_collection_mode == 'remote' %}
<span class="inline-flex items-center gap-1 px-2.5 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800 dark:bg-blue-900/40 dark:text-blue-300">
<svg class="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
@@ -45,7 +66,7 @@
</div>
<!-- Project Actions -->
<div class="flex items-center gap-3">
{% if project_type and project_type.id == 'sound_monitoring' %}
{% if 'sound_monitoring' in modules %}
<a href="/api/projects/{{ project.id }}/combined-report-wizard"
class="px-4 py-2 bg-emerald-600 text-white rounded-lg hover:bg-emerald-700 transition-colors flex items-center gap-2 text-sm">
<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
@@ -57,3 +78,69 @@
</div>
</div>
</div>
<!-- Add Module Modal -->
<div id="add-module-modal" class="hidden fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm">
<div class="bg-white dark:bg-slate-800 rounded-xl shadow-2xl w-full max-w-sm mx-4 p-6">
<div class="flex items-center justify-between mb-4">
<h3 class="text-lg font-semibold text-gray-900 dark:text-white">Add Module</h3>
<button onclick="closeAddModuleModal()" class="text-gray-400 hover:text-gray-600 dark:hover:text-gray-200">
<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="M6 18L18 6M6 6l12 12"/></svg>
</button>
</div>
<div id="add-module-options" class="space-y-2">
<!-- Populated by JS -->
</div>
<p id="add-module-none" class="hidden text-sm text-gray-500 dark:text-gray-400 text-center py-4">All available modules are already enabled.</p>
</div>
</div>
<script>
const _MODULE_META = {
sound_monitoring: { name: "Sound Monitoring", color: "orange", icon: "M15.536 8.464a5 5 0 010 7.072M12 6v12M9 8.464a5 5 0 000 7.072" },
vibration_monitoring: { name: "Vibration Monitoring", color: "blue", icon: "M22 12h-4l-3 9L9 3l-3 9H2" },
};
async function openAddModuleModal() {
const resp = await fetch(`/api/projects/${projectId}/modules`);
const data = await resp.json();
const container = document.getElementById('add-module-options');
const none = document.getElementById('add-module-none');
container.innerHTML = '';
if (!data.available || data.available.length === 0) {
none.classList.remove('hidden');
} else {
none.classList.add('hidden');
data.available.forEach(m => {
const meta = _MODULE_META[m.module_type] || { name: m.module_type, color: 'gray' };
const btn = document.createElement('button');
btn.className = `w-full text-left px-4 py-3 rounded-lg border border-gray-200 dark:border-gray-700 hover:border-${meta.color}-400 hover:bg-${meta.color}-50 dark:hover:bg-${meta.color}-900/20 transition-colors flex items-center gap-3`;
btn.innerHTML = `<span class="flex-1 font-medium text-gray-900 dark:text-white">${meta.name}</span>`;
btn.onclick = () => addModule(m.module_type);
container.appendChild(btn);
});
}
document.getElementById('add-module-modal').classList.remove('hidden');
}
function closeAddModuleModal() {
document.getElementById('add-module-modal').classList.add('hidden');
}
async function addModule(moduleType) {
await fetch(`/api/projects/${projectId}/modules`, {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({ module_type: moduleType }),
});
closeAddModuleModal();
window.location.reload();
}
async function removeModule(moduleType) {
const meta = _MODULE_META[moduleType] || { name: moduleType };
if (!confirm(`Remove the ${meta.name} module? The data will not be deleted, but the related tabs will be hidden.`)) return;
await fetch(`/api/projects/${projectId}/modules/${moduleType}`, { method: 'DELETE' });
window.location.reload();
}
</script>

View File

@@ -35,30 +35,21 @@
class="tab-button px-4 py-3 border-b-2 font-medium text-sm transition-colors border-seismo-orange text-seismo-orange whitespace-nowrap">
Overview
</button>
<button onclick="switchTab('locations')"
data-tab="locations"
class="tab-button px-4 py-3 border-b-2 border-transparent font-medium text-sm text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white hover:border-gray-300 dark:hover:border-gray-600 transition-colors whitespace-nowrap">
<span id="locations-tab-label">Locations</span>
<button id="vibration-tab-btn" onclick="switchTab('vibration')"
data-tab="vibration"
class="tab-button hidden px-4 py-3 border-b-2 border-transparent font-medium text-sm text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white hover:border-gray-300 dark:hover:border-gray-600 transition-colors whitespace-nowrap">
<svg class="w-4 h-4 inline mr-1.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 10V3L4 14h7v7l9-11h-7z"/>
</svg>
Vibration
</button>
<button id="units-tab-btn" onclick="switchTab('units')"
data-tab="units"
class="tab-button px-4 py-3 border-b-2 border-transparent font-medium text-sm text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white hover:border-gray-300 dark:hover:border-gray-600 transition-colors whitespace-nowrap">
Assigned Units
</button>
<button id="schedules-tab-btn" onclick="switchTab('schedules')"
data-tab="schedules"
class="tab-button px-4 py-3 border-b-2 border-transparent font-medium text-sm text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white hover:border-gray-300 dark:hover:border-gray-600 transition-colors whitespace-nowrap">
Schedules
</button>
<button id="sessions-tab-btn" onclick="switchTab('sessions')"
data-tab="sessions"
class="tab-button px-4 py-3 border-b-2 border-transparent font-medium text-sm text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white hover:border-gray-300 dark:hover:border-gray-600 transition-colors whitespace-nowrap">
Monitoring Sessions
</button>
<button id="data-tab-btn" onclick="switchTab('data')"
data-tab="data"
class="tab-button px-4 py-3 border-b-2 border-transparent font-medium text-sm text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white hover:border-gray-300 dark:hover:border-gray-600 transition-colors whitespace-nowrap">
Data Files
<button id="sound-tab-btn" onclick="switchTab('sound')"
data-tab="sound"
class="tab-button hidden px-4 py-3 border-b-2 border-transparent font-medium text-sm text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white hover:border-gray-300 dark:hover:border-gray-600 transition-colors whitespace-nowrap">
<svg class="w-4 h-4 inline mr-1.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.536 8.464a5 5 0 010 7.072M12 6a7 7 0 010 14M8.464 8.464a5 5 0 000 7.072"/>
</svg>
Sound
</button>
<button onclick="switchTab('settings')"
data-tab="settings"
@@ -86,111 +77,93 @@
</div>
</div>
<!-- Locations Tab -->
<div id="locations-tab" class="tab-panel hidden">
<div class="bg-white dark:bg-slate-800 rounded-xl shadow-lg p-6">
<div class="flex items-center justify-between mb-6">
<h2 class="text-xl font-semibold text-gray-900 dark:text-white">
<span id="locations-header">Locations</span>
</h2>
<button onclick="openLocationModal()" id="add-location-btn"
class="px-4 py-2 bg-seismo-orange text-white rounded-lg hover:bg-seismo-navy transition-colors">
<svg class="w-5 h-5 inline mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"></path>
</svg>
<span id="add-location-label">Add Location</span>
</button>
</div>
<!-- Vibration Tab -->
<div id="vibration-tab" class="tab-panel hidden">
<!-- Vibration sub-nav -->
<div class="flex gap-0 mb-5 border-b border-gray-200 dark:border-gray-700">
<button id="vib-sub-locations-btn" onclick="switchVibSubTab('locations')"
class="vib-sub-tab px-4 py-2 text-sm font-medium border-b-2 border-seismo-orange text-seismo-orange -mb-px transition-colors whitespace-nowrap">
Locations
</button>
<!-- Future sub-tabs: Sessions, Data Files -->
</div>
<div id="project-locations"
hx-get="/api/projects/{{ project_id }}/locations"
hx-trigger="load"
hx-swap="innerHTML">
<div class="text-center py-8 text-gray-500">Loading locations...</div>
<!-- Vibration Locations sub-panel -->
<div id="vib-sub-locations" class="vib-sub-panel">
<div class="bg-white dark:bg-slate-800 rounded-xl shadow-lg p-6">
<div class="flex items-center justify-between mb-6">
<h2 class="text-xl font-semibold text-gray-900 dark:text-white">Monitoring Locations</h2>
<button onclick="openLocationModal('vibration')"
class="px-4 py-2 bg-seismo-orange text-white rounded-lg hover:bg-seismo-navy transition-colors">
<svg class="w-5 h-5 inline mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"></path>
</svg>
Add Location
</button>
</div>
<div id="vibration-locations"
hx-get="/api/projects/{{ project_id }}/locations?location_type=vibration"
hx-trigger="load"
hx-swap="innerHTML">
<div class="text-center py-8 text-gray-500">Loading locations...</div>
</div>
</div>
</div>
</div>
<!-- Units Tab -->
<div id="units-tab" class="tab-panel hidden">
<div class="bg-white dark:bg-slate-800 rounded-xl shadow-lg p-6">
<div class="flex items-center justify-between mb-6">
<h2 class="text-xl font-semibold text-gray-900 dark:text-white">Assigned Units</h2>
<div class="text-sm text-gray-500">
Units currently assigned to this project's locations
</div>
</div>
<div id="project-units"
hx-get="/api/projects/{{ project_id }}/units"
hx-trigger="load, every 30s"
hx-swap="innerHTML">
<div class="text-center py-8 text-gray-500">Loading units...</div>
</div>
<!-- Sound Tab -->
<div id="sound-tab" class="tab-panel hidden">
<!-- Sound sub-nav -->
<div class="flex gap-0 mb-5 border-b border-gray-200 dark:border-gray-700">
<button id="sound-sub-locations-btn" onclick="switchSoundSubTab('locations')"
class="sound-sub-tab px-4 py-2 text-sm font-medium border-b-2 border-seismo-orange text-seismo-orange -mb-px transition-colors whitespace-nowrap">
NRLs
</button>
<button id="sound-sub-sessions-btn" onclick="switchSoundSubTab('sessions')"
class="sound-sub-tab px-4 py-2 text-sm font-medium border-b-2 border-transparent text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-200 -mb-px transition-colors whitespace-nowrap">
Sessions
</button>
<button id="sound-sub-data-btn" onclick="switchSoundSubTab('data')"
class="sound-sub-tab px-4 py-2 text-sm font-medium border-b-2 border-transparent text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-200 -mb-px transition-colors whitespace-nowrap">
Data Files
</button>
<button id="sound-sub-units-btn" onclick="switchSoundSubTab('units')"
class="sound-sub-tab hidden px-4 py-2 text-sm font-medium border-b-2 border-transparent text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-200 -mb-px transition-colors whitespace-nowrap">
Assigned Units
</button>
<button id="sound-sub-schedules-btn" onclick="switchSoundSubTab('schedules')"
class="sound-sub-tab hidden px-4 py-2 text-sm font-medium border-b-2 border-transparent text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-200 -mb-px transition-colors whitespace-nowrap">
Schedules
</button>
</div>
</div>
<!-- Schedules Tab -->
<div id="schedules-tab" class="tab-panel hidden">
<!-- Recurring Schedules Section -->
<div class="bg-white dark:bg-slate-800 rounded-xl shadow-lg p-6 mb-6">
<div class="flex items-center justify-between mb-6">
<div>
<h2 class="text-xl font-semibold text-gray-900 dark:text-white">Recurring Schedules</h2>
<p class="text-sm text-gray-500 dark:text-gray-400 mt-1">
Automated patterns that generate scheduled actions
</p>
<!-- NRLs sub-panel -->
<div id="sound-sub-locations" class="sound-sub-panel">
<div class="bg-white dark:bg-slate-800 rounded-xl shadow-lg p-6">
<div class="flex items-center justify-between mb-6">
<h2 class="text-xl font-semibold text-gray-900 dark:text-white">Noise Recording Locations</h2>
<button onclick="openLocationModal('sound')"
class="px-4 py-2 bg-seismo-orange text-white rounded-lg hover:bg-seismo-navy transition-colors">
<svg class="w-5 h-5 inline mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"></path>
</svg>
Add NRL
</button>
</div>
<div id="sound-locations"
hx-get="/api/projects/{{ project_id }}/locations?location_type=sound"
hx-trigger="load"
hx-swap="innerHTML">
<div class="text-center py-8 text-gray-500">Loading locations...</div>
</div>
<button onclick="openScheduleModal()"
class="px-4 py-2 bg-seismo-orange text-white rounded-lg hover:bg-seismo-navy transition-colors">
<svg class="w-5 h-5 inline mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"></path>
</svg>
Create Schedule
</button>
</div>
<div id="recurring-schedule-list"
hx-get="/api/projects/{{ project_id }}/recurring-schedules/partials/list"
hx-trigger="load, refresh from:#recurring-schedule-list"
hx-swap="innerHTML">
<div class="text-center py-8 text-gray-500">Loading recurring schedules...</div>
</div>
</div>
<!-- Scheduled Actions Section -->
<div class="bg-white dark:bg-slate-800 rounded-xl shadow-lg p-6">
<div class="flex items-center justify-between mb-6">
<div>
<h2 id="schedules-title" class="text-xl font-semibold text-gray-900 dark:text-white">Upcoming Actions</h2>
<p id="schedules-subtitle" class="text-sm text-gray-500 dark:text-gray-400 mt-1">
Scheduled start/stop/download actions
</p>
</div>
<select id="schedules-filter" onchange="filterScheduledActions()"
class="px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white text-sm">
<option value="pending">Pending</option>
<option value="all">All</option>
<option value="completed">Completed</option>
<option value="failed">Failed</option>
</select>
</div>
<div id="project-schedules"
hx-get="/api/projects/{{ project_id }}/schedules?status=pending"
hx-trigger="load, every 30s, refresh from:#project-schedules"
hx-swap="innerHTML">
<div class="text-center py-8 text-gray-500">Loading scheduled actions...</div>
</div>
</div>
</div>
<!-- Monitoring Sessions Tab -->
<div id="sessions-tab" class="tab-panel hidden">
<div class="bg-white dark:bg-slate-800 rounded-xl shadow-lg p-6">
<div class="flex items-center justify-between mb-6">
<h2 class="text-xl font-semibold text-gray-900 dark:text-white">Monitoring Sessions</h2>
<div class="flex items-center gap-4">
<!-- Sessions sub-panel -->
<div id="sound-sub-sessions" class="sound-sub-panel hidden">
<div class="bg-white dark:bg-slate-800 rounded-xl shadow-lg p-6">
<div class="flex items-center justify-between mb-6">
<h2 class="text-xl font-semibold text-gray-900 dark:text-white">Monitoring Sessions</h2>
<select id="sessions-filter" onchange="filterSessions()"
class="px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white text-sm">
<option value="all">All Sessions</option>
@@ -199,116 +172,167 @@
<option value="failed">Failed</option>
</select>
</div>
<div id="project-sessions"
hx-get="/api/projects/{{ project_id }}/sessions"
hx-trigger="load, every 30s"
hx-swap="innerHTML">
<div class="text-center py-8 text-gray-500">Loading sessions...</div>
</div>
</div>
<div id="project-sessions"
hx-get="/api/projects/{{ project_id }}/sessions"
hx-trigger="load, every 30s"
hx-swap="innerHTML">
<div class="text-center py-8 text-gray-500">Loading sessions...</div>
<!-- Monthly Calendar -->
<div class="mt-6 bg-white dark:bg-slate-800 rounded-xl shadow-lg p-6">
<h3 class="text-lg font-semibold text-gray-900 dark:text-white mb-4">Calendar View</h3>
<div id="sessions-calendar"
hx-get="/api/projects/{{ project_id }}/sessions-calendar"
hx-trigger="load"
hx-swap="innerHTML">
<div class="text-center py-6 text-gray-400 text-sm">Loading calendar…</div>
</div>
</div>
</div>
<!-- Monthly Calendar -->
<div class="mt-6 bg-white dark:bg-slate-800 rounded-xl shadow-lg p-6">
<div class="flex items-center justify-between mb-4">
<h3 class="text-lg font-semibold text-gray-900 dark:text-white">Calendar View</h3>
</div>
<div id="sessions-calendar"
hx-get="/api/projects/{{ project_id }}/sessions-calendar"
<!-- Data Files sub-panel -->
<div id="sound-sub-data" class="sound-sub-panel hidden">
<!-- FTP File Browser (remote projects only) -->
<div id="ftp-browser" class="mb-6"
hx-get="/api/projects/{{ project_id }}/ftp-browser"
hx-trigger="load"
hx-swap="innerHTML">
<div class="text-center py-6 text-gray-400 text-sm">Loading calendar…</div>
<div class="bg-white dark:bg-slate-800 rounded-xl shadow-lg p-6">
<div class="text-center py-8 text-gray-500">Loading FTP browser...</div>
</div>
</div>
<!-- Unified Files View -->
<div class="bg-white dark:bg-slate-800 rounded-xl shadow-lg">
<div class="px-6 py-4 border-b border-gray-200 dark:border-gray-700">
<div class="flex items-center justify-between">
<h2 class="text-xl font-semibold text-gray-900 dark:text-white">Project Files</h2>
<div class="flex items-center gap-3">
<button onclick="toggleUploadAll()"
class="px-3 py-2 text-sm bg-seismo-orange text-white rounded-lg hover:bg-seismo-navy transition-colors flex items-center gap-1.5">
<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="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-8l-4-4m0 0L8 8m4-4v12"></path>
</svg>
Upload Data
</button>
<button onclick="htmx.trigger('#unified-files', 'refresh')"
class="px-3 py-2 text-sm bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300 rounded-lg hover:bg-gray-200 dark:hover:bg-gray-600 transition-colors">
<svg class="w-4 h-4 inline mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"></path>
</svg>
Refresh
</button>
</div>
</div>
</div>
<!-- Upload Data Panel -->
<div id="upload-all-panel" class="hidden border-b border-gray-200 dark:border-gray-700">
<div class="px-6 py-4 bg-gray-50 dark:bg-gray-800/50">
<p class="text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Bulk Import — Select Folder</p>
<p class="text-xs text-gray-500 dark:text-gray-400 mb-3">
Select your data folder directly — no zipping needed. Expected structure:
<code class="bg-gray-200 dark:bg-gray-700 px-1 rounded">[date]/[NRL name]/[Auto_####]/</code>.
NRL folders are matched to locations by name. MP3s are stored; Excel exports are skipped.
</p>
<div class="flex flex-wrap items-center gap-3">
<input type="file" id="upload-all-input"
webkitdirectory directory multiple
class="block text-sm text-gray-500 dark:text-gray-400
file:mr-3 file:py-1.5 file:px-3 file:rounded-lg file:border-0
file:text-sm file:font-medium file:bg-seismo-orange file:text-white
hover:file:bg-seismo-navy file:cursor-pointer" />
<span id="upload-all-file-count" class="text-xs text-gray-500 dark:text-gray-400 hidden"></span>
<button id="upload-all-btn" onclick="submitUploadAll()"
class="px-4 py-1.5 text-sm bg-green-600 text-white rounded-lg hover:bg-green-700 transition-colors">
Import
</button>
<button id="upload-all-cancel-btn" onclick="toggleUploadAll()"
class="px-4 py-1.5 text-sm text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white transition-colors">
Cancel
</button>
<span id="upload-all-status" class="text-sm hidden"></span>
</div>
<div id="upload-all-progress-wrap" class="hidden mt-3">
<div class="flex justify-between text-xs text-gray-500 dark:text-gray-400 mb-1">
<span id="upload-all-progress-label">Uploading…</span>
</div>
<div class="w-full bg-gray-200 dark:bg-gray-700 rounded-full h-2">
<div id="upload-all-progress-bar"
class="bg-green-500 h-2 rounded-full transition-all duration-300"
style="width: 0%"></div>
</div>
</div>
<div id="upload-all-results" class="hidden mt-3 text-sm space-y-1"></div>
</div>
</div>
<div id="unified-files"
hx-get="/api/projects/{{ project_id }}/files-unified"
hx-trigger="load, refresh from:#unified-files"
hx-swap="innerHTML">
<div class="px-6 py-12 text-center text-gray-500">Loading files...</div>
</div>
</div>
</div>
</div>
<!-- Data Files Tab -->
<div id="data-tab" class="tab-panel hidden">
<!-- FTP File Browser (Download from Devices) -->
<div id="ftp-browser" class="mb-6"
hx-get="/api/projects/{{ project_id }}/ftp-browser"
hx-trigger="load"
hx-swap="innerHTML">
<!-- Assigned Units sub-panel (remote only) -->
<div id="sound-sub-units" class="sound-sub-panel hidden">
<div class="bg-white dark:bg-slate-800 rounded-xl shadow-lg p-6">
<div class="text-center py-8 text-gray-500">Loading FTP browser...</div>
<div class="flex items-center justify-between mb-6">
<h2 class="text-xl font-semibold text-gray-900 dark:text-white">Assigned Units</h2>
<div class="text-sm text-gray-500">Units currently assigned to this project's NRLs</div>
</div>
<div id="project-units"
hx-get="/api/projects/{{ project_id }}/units"
hx-trigger="load, every 30s"
hx-swap="innerHTML">
<div class="text-center py-8 text-gray-500">Loading units...</div>
</div>
</div>
</div>
<!-- Unified Files View (Database + Filesystem) -->
<div class="bg-white dark:bg-slate-800 rounded-xl shadow-lg">
<div class="px-6 py-4 border-b border-gray-200 dark:border-gray-700">
<div class="flex items-center justify-between">
<h2 class="text-xl font-semibold text-gray-900 dark:text-white">
Project Files
</h2>
<div class="flex items-center gap-3">
<button onclick="toggleUploadAll()"
class="px-3 py-2 text-sm bg-seismo-orange text-white rounded-lg hover:bg-seismo-navy transition-colors flex items-center gap-1.5">
<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="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-8l-4-4m0 0L8 8m4-4v12"></path>
</svg>
Upload Data
</button>
<button onclick="htmx.trigger('#unified-files', 'refresh')"
class="px-3 py-2 text-sm bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300 rounded-lg hover:bg-gray-200 dark:hover:bg-gray-600 transition-colors">
<svg class="w-4 h-4 inline mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"></path>
</svg>
Refresh
</button>
<!-- Schedules sub-panel (remote only) -->
<div id="sound-sub-schedules" class="sound-sub-panel hidden">
<div class="bg-white dark:bg-slate-800 rounded-xl shadow-lg p-6 mb-6">
<div class="flex items-center justify-between mb-6">
<div>
<h2 class="text-xl font-semibold text-gray-900 dark:text-white">Recurring Schedules</h2>
<p class="text-sm text-gray-500 dark:text-gray-400 mt-1">Automated patterns that generate scheduled actions</p>
</div>
<button onclick="openScheduleModal()"
class="px-4 py-2 bg-seismo-orange text-white rounded-lg hover:bg-seismo-navy transition-colors">
<svg class="w-5 h-5 inline mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"></path>
</svg>
Create Schedule
</button>
</div>
<div id="recurring-schedule-list"
hx-get="/api/projects/{{ project_id }}/recurring-schedules/partials/list"
hx-trigger="load, refresh from:#recurring-schedule-list"
hx-swap="innerHTML">
<div class="text-center py-8 text-gray-500">Loading recurring schedules...</div>
</div>
</div>
<!-- Upload Data Panel -->
<div id="upload-all-panel" class="hidden border-b border-gray-200 dark:border-gray-700">
<div class="px-6 py-4 bg-gray-50 dark:bg-gray-800/50">
<p class="text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Bulk Import — Select Folder</p>
<p class="text-xs text-gray-500 dark:text-gray-400 mb-3">
Select your data folder directly — no zipping needed. Expected structure:
<code class="bg-gray-200 dark:bg-gray-700 px-1 rounded">[date]/[NRL name]/[Auto_####]/</code>.
NRL folders are matched to locations by name. MP3s are stored; Excel exports are skipped.
</p>
<div class="flex flex-wrap items-center gap-3">
<input type="file" id="upload-all-input"
webkitdirectory directory multiple
class="block text-sm text-gray-500 dark:text-gray-400
file:mr-3 file:py-1.5 file:px-3 file:rounded-lg file:border-0
file:text-sm file:font-medium file:bg-seismo-orange file:text-white
hover:file:bg-seismo-navy file:cursor-pointer" />
<span id="upload-all-file-count" class="text-xs text-gray-500 dark:text-gray-400 hidden"></span>
<button id="upload-all-btn" onclick="submitUploadAll()"
class="px-4 py-1.5 text-sm bg-green-600 text-white rounded-lg hover:bg-green-700 transition-colors">
Import
</button>
<button id="upload-all-cancel-btn" onclick="toggleUploadAll()"
class="px-4 py-1.5 text-sm text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white transition-colors">
Cancel
</button>
<span id="upload-all-status" class="text-sm hidden"></span>
<div class="bg-white dark:bg-slate-800 rounded-xl shadow-lg p-6">
<div class="flex items-center justify-between mb-6">
<div>
<h2 id="schedules-title" class="text-xl font-semibold text-gray-900 dark:text-white">Upcoming Actions</h2>
<p id="schedules-subtitle" class="text-sm text-gray-500 dark:text-gray-400 mt-1">Scheduled start/stop/download actions</p>
</div>
<!-- Progress bar -->
<div id="upload-all-progress-wrap" class="hidden mt-3">
<div class="flex justify-between text-xs text-gray-500 dark:text-gray-400 mb-1">
<span id="upload-all-progress-label">Uploading…</span>
</div>
<div class="w-full bg-gray-200 dark:bg-gray-700 rounded-full h-2">
<div id="upload-all-progress-bar"
class="bg-green-500 h-2 rounded-full transition-all duration-300"
style="width: 0%"></div>
</div>
</div>
<!-- Result summary -->
<div id="upload-all-results" class="hidden mt-3 text-sm space-y-1"></div>
<select id="schedules-filter" onchange="filterScheduledActions()"
class="px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white text-sm">
<option value="pending">Pending</option>
<option value="all">All</option>
<option value="completed">Completed</option>
<option value="failed">Failed</option>
</select>
</div>
<div id="project-schedules"
hx-get="/api/projects/{{ project_id }}/schedules?status=pending"
hx-trigger="load, every 30s, refresh from:#project-schedules"
hx-swap="innerHTML">
<div class="text-center py-8 text-gray-500">Loading scheduled actions...</div>
</div>
</div>
<div id="unified-files"
hx-get="/api/projects/{{ project_id }}/files-unified"
hx-trigger="load, refresh from:#unified-files"
hx-swap="innerHTML">
<div class="px-6 py-12 text-center text-gray-500">Loading files...</div>
</div>
</div>
</div>
@@ -350,30 +374,6 @@
</div>
</div>
<div>
<label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Data Collection</label>
<div class="grid grid-cols-2 gap-3">
<label class="flex items-start gap-3 p-3 border-2 rounded-lg cursor-pointer" id="settings-mode-manual-label">
<input type="radio" name="data_collection_mode" id="settings-mode-manual" value="manual"
onchange="settingsUpdateModeStyles()"
class="mt-0.5 accent-seismo-orange shrink-0">
<div>
<p class="text-sm font-medium text-gray-900 dark:text-white">Manual</p>
<p class="text-xs text-gray-500 dark:text-gray-400">SD card retrieved daily</p>
</div>
</label>
<label class="flex items-start gap-3 p-3 border-2 rounded-lg cursor-pointer" id="settings-mode-remote-label">
<input type="radio" name="data_collection_mode" id="settings-mode-remote" value="remote"
onchange="settingsUpdateModeStyles()"
class="mt-0.5 accent-seismo-orange shrink-0">
<div>
<p class="text-sm font-medium text-gray-900 dark:text-white">Remote</p>
<p class="text-xs text-gray-500 dark:text-gray-400">Modem, data pulled via FTP</p>
</div>
</label>
</div>
</div>
<div>
<label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Site Address</label>
<input type="text" name="site_address" id="settings-site-address"
@@ -400,6 +400,40 @@
</div>
</div>
<div id="sound-settings-section" class="hidden">
<div class="border-t border-gray-200 dark:border-gray-700 pt-5 mb-4">
<h3 class="text-base font-semibold text-gray-900 dark:text-white flex items-center gap-2">
<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="M15.536 8.464a5 5 0 010 7.072M12 6a7 7 0 010 14M8.464 8.464a5 5 0 000 7.072"/>
</svg>
Sound Monitoring
</h3>
</div>
<div>
<label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Data Collection</label>
<div class="grid grid-cols-2 gap-3">
<label class="flex items-start gap-3 p-3 border-2 rounded-lg cursor-pointer" id="settings-mode-manual-label">
<input type="radio" name="data_collection_mode" id="settings-mode-manual" value="manual"
onchange="settingsUpdateModeStyles()"
class="mt-0.5 accent-seismo-orange shrink-0">
<div>
<p class="text-sm font-medium text-gray-900 dark:text-white">Manual</p>
<p class="text-xs text-gray-500 dark:text-gray-400">SD card retrieved daily</p>
</div>
</label>
<label class="flex items-start gap-3 p-3 border-2 rounded-lg cursor-pointer" id="settings-mode-remote-label">
<input type="radio" name="data_collection_mode" id="settings-mode-remote" value="remote"
onchange="settingsUpdateModeStyles()"
class="mt-0.5 accent-seismo-orange shrink-0">
<div>
<p class="text-sm font-medium text-gray-900 dark:text-white">Remote</p>
<p class="text-xs text-gray-500 dark:text-gray-400">Modem, data pulled via FTP</p>
</div>
</label>
</div>
</div>
</div>
<div id="settings-success" class="hidden text-sm text-green-600 dark:text-green-400"></div>
<div id="settings-error" class="hidden text-sm text-red-600"></div>
@@ -770,7 +804,7 @@
<script>
const projectId = "{{ project_id }}";
let editingLocationId = null;
let projectTypeId = null;
let projectModules = []; // list of enabled module_type strings, e.g. ['sound_monitoring']
async function quickUpdateStatus(newStatus) {
try {
@@ -792,34 +826,52 @@ async function quickUpdateStatus(newStatus) {
// Tab switching
function switchTab(tabName) {
// Hide all tab panels
document.querySelectorAll('.tab-panel').forEach(panel => {
panel.classList.add('hidden');
});
// Reset all tab buttons
document.querySelectorAll('.tab-panel').forEach(panel => panel.classList.add('hidden'));
document.querySelectorAll('.tab-button').forEach(button => {
button.classList.remove('border-seismo-orange', 'text-seismo-orange');
button.classList.add('border-transparent', 'text-gray-600', 'dark:text-gray-400');
});
// Show selected tab panel
const panel = document.getElementById(`${tabName}-tab`);
if (panel) {
panel.classList.remove('hidden');
}
if (panel) panel.classList.remove('hidden');
// Highlight selected tab button
const button = document.querySelector(`[data-tab="${tabName}"]`);
if (button) {
button.classList.remove('border-transparent', 'text-gray-600', 'dark:text-gray-400');
button.classList.add('border-seismo-orange', 'text-seismo-orange');
}
// Persist active tab in URL hash so refresh stays on this tab
history.replaceState(null, '', `#${tabName}`);
}
function switchVibSubTab(name) {
document.querySelectorAll('.vib-sub-panel').forEach(p => p.classList.add('hidden'));
document.querySelectorAll('.vib-sub-tab').forEach(b => {
b.classList.remove('border-seismo-orange', 'text-seismo-orange');
b.classList.add('border-transparent', 'text-gray-500', 'dark:text-gray-400');
});
document.getElementById(`vib-sub-${name}`)?.classList.remove('hidden');
const btn = document.getElementById(`vib-sub-${name}-btn`);
if (btn) {
btn.classList.remove('border-transparent', 'text-gray-500', 'dark:text-gray-400');
btn.classList.add('border-seismo-orange', 'text-seismo-orange');
}
}
function switchSoundSubTab(name) {
document.querySelectorAll('.sound-sub-panel').forEach(p => p.classList.add('hidden'));
document.querySelectorAll('.sound-sub-tab').forEach(b => {
b.classList.remove('border-seismo-orange', 'text-seismo-orange');
b.classList.add('border-transparent', 'text-gray-500', 'dark:text-gray-400');
});
document.getElementById(`sound-sub-${name}`)?.classList.remove('hidden');
const btn = document.getElementById(`sound-sub-${name}-btn`);
if (btn) {
btn.classList.remove('border-transparent', 'text-gray-500', 'dark:text-gray-400');
btn.classList.add('border-seismo-orange', 'text-seismo-orange');
}
}
// Load project details
async function loadProjectDetails() {
try {
@@ -828,7 +880,7 @@ async function loadProjectDetails() {
throw new Error('Failed to load project details');
}
const data = await response.json();
projectTypeId = data.project_type_id || null;
projectModules = data.modules || [];
// Update breadcrumb
document.getElementById('project-name-breadcrumb').textContent = data.name || 'Project';
@@ -849,23 +901,20 @@ async function loadProjectDetails() {
if (modeRadio) modeRadio.checked = true;
settingsUpdateModeStyles();
// Update tab labels and visibility based on project type
const isSoundProject = projectTypeId === 'sound_monitoring';
const isVibrationProject = projectTypeId === 'vibration_monitoring';
if (isSoundProject) {
document.getElementById('locations-tab-label').textContent = 'NRLs';
document.getElementById('locations-header').textContent = 'Noise Recording Locations';
document.getElementById('add-location-label').textContent = 'Add NRL';
}
// Monitoring Sessions and Data Files tabs are sound-only
// Data Files also hides the FTP browser section for manual projects
// Show/hide module tabs based on active modules
const hasSoundModule = projectModules.includes('sound_monitoring');
const hasVibrationModule = projectModules.includes('vibration_monitoring');
const isRemote = mode === 'remote';
document.getElementById('sessions-tab-btn').classList.toggle('hidden', !isSoundProject);
document.getElementById('data-tab-btn').classList.toggle('hidden', !isSoundProject);
// Schedules and Assigned Units: hidden for vibration; for sound, only show if remote
document.getElementById('schedules-tab-btn')?.classList.toggle('hidden', isVibrationProject || (isSoundProject && !isRemote));
document.getElementById('units-tab-btn')?.classList.toggle('hidden', isVibrationProject || (isSoundProject && !isRemote));
// FTP browser within Data Files tab
document.getElementById('vibration-tab-btn').classList.toggle('hidden', !hasVibrationModule);
document.getElementById('sound-tab-btn').classList.toggle('hidden', !hasSoundModule);
document.getElementById('sound-settings-section')?.classList.toggle('hidden', !hasSoundModule);
// Within Sound: show Assigned Units + Schedules sub-tabs only for remote projects
document.getElementById('sound-sub-units-btn')?.classList.toggle('hidden', !isRemote);
document.getElementById('sound-sub-schedules-btn')?.classList.toggle('hidden', !isRemote);
// FTP browser: only show for remote projects
document.getElementById('ftp-browser')?.classList.toggle('hidden', !isRemote);
document.getElementById('settings-error').classList.add('hidden');
@@ -983,7 +1032,14 @@ function updateModeLabels() {
}
}
// Tracks the active location type tab so "Add Location" opens with the right type
let _activeLocationType = null;
function setActiveLocationType(type) {
_activeLocationType = type;
}
function openLocationModal(defaultType) {
defaultType = defaultType || _activeLocationType || defaultType;
editingLocationId = null;
document.getElementById('location-modal-title').textContent = 'Add Location';
document.getElementById('location-id').value = '';
@@ -996,11 +1052,13 @@ function openLocationModal(defaultType) {
if (connectedRadio) { connectedRadio.checked = true; updateModeLabels(); }
const locationTypeSelect = document.getElementById('location-type');
const locationTypeWrapper = locationTypeSelect.closest('div');
if (projectTypeId === 'sound_monitoring') {
const hasSoundMod = projectModules.includes('sound_monitoring');
const hasVibMod = projectModules.includes('vibration_monitoring');
if (hasSoundMod && !hasVibMod) {
locationTypeSelect.value = 'sound';
locationTypeSelect.disabled = true;
if (locationTypeWrapper) locationTypeWrapper.classList.add('hidden');
} else if (projectTypeId === 'vibration_monitoring') {
} else if (hasVibMod && !hasSoundMod) {
locationTypeSelect.value = 'vibration';
locationTypeSelect.disabled = true;
if (locationTypeWrapper) locationTypeWrapper.classList.add('hidden');
@@ -1030,11 +1088,13 @@ function openEditLocationModal(button) {
if (modeRadio) { modeRadio.checked = true; updateModeLabels(); }
const locationTypeSelect = document.getElementById('location-type');
const locationTypeWrapper = locationTypeSelect.closest('div');
if (projectTypeId === 'sound_monitoring') {
const hasSoundModE = projectModules.includes('sound_monitoring');
const hasVibModE = projectModules.includes('vibration_monitoring');
if (hasSoundModE && !hasVibModE) {
locationTypeSelect.value = 'sound';
locationTypeSelect.disabled = true;
if (locationTypeWrapper) locationTypeWrapper.classList.add('hidden');
} else if (projectTypeId === 'vibration_monitoring') {
} else if (hasVibModE && !hasSoundModE) {
locationTypeSelect.value = 'vibration';
locationTypeSelect.disabled = true;
if (locationTypeWrapper) locationTypeWrapper.classList.add('hidden');
@@ -1060,9 +1120,9 @@ document.getElementById('location-form').addEventListener('submit', async functi
const address = document.getElementById('location-address').value.trim();
const coordinates = document.getElementById('location-coordinates').value.trim();
let locationType = document.getElementById('location-type').value;
if (projectTypeId === 'sound_monitoring') {
if (projectModules.includes('sound_monitoring') && !projectModules.includes('vibration_monitoring')) {
locationType = 'sound';
} else if (projectTypeId === 'vibration_monitoring') {
} else if (projectModules.includes('vibration_monitoring') && !projectModules.includes('sound_monitoring')) {
locationType = 'vibration';
}
@@ -1106,12 +1166,8 @@ document.getElementById('location-form').addEventListener('submit', async functi
}
closeLocationModal();
refreshLocationLists();
refreshProjectDashboard();
// Refresh locations tab if visible
htmx.ajax('GET', `/api/projects/${projectId}/locations`, {
target: '#project-locations',
swap: 'innerHTML'
});
} catch (err) {
const errorEl = document.getElementById('location-error');
errorEl.textContent = err.message || 'Failed to save location.';
@@ -1119,6 +1175,15 @@ document.getElementById('location-form').addEventListener('submit', async functi
}
});
function refreshLocationLists() {
htmx.ajax('GET', `/api/projects/${projectId}/locations?location_type=sound`, {
target: '#sound-locations', swap: 'innerHTML'
});
htmx.ajax('GET', `/api/projects/${projectId}/locations?location_type=vibration`, {
target: '#vibration-locations', swap: 'innerHTML'
});
}
async function deleteLocation(locationId) {
if (!confirm('Delete this location?')) return;
@@ -1130,11 +1195,8 @@ async function deleteLocation(locationId) {
const data = await response.json().catch(() => ({}));
throw new Error(data.detail || 'Failed to delete location');
}
refreshLocationLists();
refreshProjectDashboard();
htmx.ajax('GET', `/api/projects/${projectId}/locations`, {
target: '#project-locations',
swap: 'innerHTML'
});
} catch (err) {
alert(err.message || 'Failed to delete location.');
}
@@ -1208,11 +1270,8 @@ document.getElementById('assign-form').addEventListener('submit', async function
throw new Error(data.detail || 'Failed to assign unit');
}
closeAssignModal();
refreshLocationLists();
refreshProjectDashboard();
htmx.ajax('GET', `/api/projects/${projectId}/locations`, {
target: '#project-locations',
swap: 'innerHTML'
});
} catch (err) {
const errorEl = document.getElementById('assign-error');
errorEl.textContent = err.message || 'Failed to assign unit.';
@@ -1231,11 +1290,8 @@ async function unassignUnit(assignmentId) {
const data = await response.json().catch(() => ({}));
throw new Error(data.detail || 'Failed to unassign unit');
}
refreshLocationLists();
refreshProjectDashboard();
htmx.ajax('GET', `/api/projects/${projectId}/locations`, {
target: '#project-locations',
swap: 'innerHTML'
});
} catch (err) {
alert(err.message || 'Failed to unassign unit.');
}
@@ -1835,11 +1891,21 @@ function submitUploadAll() {
document.addEventListener('DOMContentLoaded', function() {
loadProjectDetails();
// Restore tab from URL hash (e.g. #schedules, #settings)
// Restore tab from URL hash
const hash = window.location.hash.replace('#', '');
const validTabs = ['overview', 'locations', 'units', 'schedules', 'sessions', 'data', 'settings'];
if (hash && validTabs.includes(hash)) {
switchTab(hash);
const validTabs = ['overview', 'vibration', 'sound', 'settings'];
// Backwards compat: map old tab names to new ones
const hashMap = { locations: 'sound', units: 'sound', schedules: 'sound', sessions: 'sound', data: 'sound' };
const subTabMap = { units: 'units', schedules: 'schedules', sessions: 'sessions', data: 'data' };
if (hash) {
const mappedTab = hashMap[hash] || hash;
if (validTabs.includes(mappedTab)) {
switchTab(mappedTab);
// Open the relevant sub-tab for backwards compat
if (subTabMap[hash]) {
switchSoundSubTab(subTabMap[hash]);
}
}
}
});

View File

@@ -96,124 +96,122 @@
</div>
<div class="p-6" id="createProjectContent">
<!-- Step 1: Project Type Selection (initially shown) -->
<div id="projectTypeSelection">
<h3 class="text-lg font-semibold text-gray-900 dark:text-white mb-4">Choose Project Type</h3>
<div class="grid grid-cols-1 md:grid-cols-3 gap-4"
hx-get="/api/projects/types/list"
hx-trigger="load"
hx-target="this"
hx-swap="innerHTML">
<!-- Project type cards will be loaded here -->
<div class="animate-pulse bg-gray-200 dark:bg-gray-700 h-48 rounded-lg"></div>
<div class="animate-pulse bg-gray-200 dark:bg-gray-700 h-48 rounded-lg"></div>
<div class="animate-pulse bg-gray-200 dark:bg-gray-700 h-48 rounded-lg"></div>
</div>
<div class="mt-6 flex justify-end">
<button type="button" onclick="hideCreateProjectModal()"
class="px-6 py-2 border border-gray-300 dark:border-gray-600 rounded-lg text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700">
Cancel
</button>
</div>
</div>
<form id="createProjectFormElement">
<div class="space-y-4">
<div>
<label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
Project Name <span class="text-red-500">*</span>
</label>
<input type="text"
name="name"
required
class="w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-seismo-orange">
</div>
<!-- Step 2: Project Details Form (hidden initially) -->
<div id="projectDetailsForm" class="hidden">
<button onclick="backToTypeSelection()"
class="mb-4 text-seismo-orange hover:text-seismo-navy">
← Back to project types
</button>
<form id="createProjectFormElement"
hx-post="/api/projects/create"
hx-swap="none">
<input type="hidden" id="project_type_id" name="project_type_id">
<div class="space-y-4">
<div class="grid grid-cols-1 md:grid-cols-2 gap-4">
<div>
<label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
Project Name *
Project Number
<span class="text-gray-400 font-normal">(xxxx-YY)</span>
</label>
<input type="text"
name="name"
required
class="w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white">
name="project_number"
pattern="\d{4}-\d{2}"
placeholder="2567-23"
class="w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-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">
Description
Client Name
</label>
<textarea name="description"
rows="3"
class="w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white"></textarea>
<input type="text"
name="client_name"
class="w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-seismo-orange">
</div>
</div>
<div class="grid grid-cols-1 md:grid-cols-2 gap-4">
<div>
<label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
Client Name
</label>
<input type="text"
name="client_name"
class="w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white">
</div>
<div>
<label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
Site Address
</label>
<input type="text"
name="site_address"
class="w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white">
</div>
</div>
<div class="grid grid-cols-1 md:grid-cols-2 gap-4">
<div>
<label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
Start Date
</label>
<input type="date"
name="start_date"
class="w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white">
</div>
<div>
<label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
End Date (Optional)
</label>
<input type="date"
name="end_date"
class="w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white">
</div>
</div>
<div>
<label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
Description
</label>
<textarea name="description"
rows="2"
class="w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-seismo-orange"></textarea>
</div>
<div class="grid grid-cols-1 md:grid-cols-2 gap-4">
<div>
<label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
Site Coordinates (Optional)
Site Address
</label>
<input type="text"
name="site_address"
class="w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-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">
Site Coordinates
<span class="text-gray-400 font-normal">(optional)</span>
</label>
<input type="text"
name="site_coordinates"
placeholder="40.7128,-74.0060"
class="w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white">
<p class="text-xs text-gray-500 mt-1">Format: latitude,longitude</p>
class="w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-seismo-orange">
</div>
</div>
<div class="mt-6 flex justify-end space-x-3">
<button type="button"
onclick="hideCreateProjectModal()"
class="px-6 py-2 border border-gray-300 dark:border-gray-600 rounded-lg text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700">
Cancel
</button>
<button type="submit"
class="px-6 py-2 bg-seismo-orange hover:bg-seismo-navy text-white rounded-lg font-medium">
Create Project
</button>
<div class="grid grid-cols-1 md:grid-cols-2 gap-4">
<div>
<label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Start Date</label>
<input type="date" name="start_date"
class="w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-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">End Date <span class="text-gray-400 font-normal">(optional)</span></label>
<input type="date" name="end_date"
class="w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-seismo-orange">
</div>
</div>
</form>
</div>
<!-- Modules -->
<div class="border-t border-gray-200 dark:border-gray-700 pt-4">
<label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
Add Modules
<span class="text-gray-400 font-normal">(optional — can be added later)</span>
</label>
<div class="grid grid-cols-2 gap-3">
<label class="flex items-center gap-3 p-3 border border-gray-200 dark:border-gray-700 rounded-lg cursor-pointer hover:border-orange-400 has-[:checked]:border-orange-400 has-[:checked]:bg-orange-50 dark:has-[:checked]:bg-orange-900/20 transition-colors">
<input type="checkbox" id="ov-module-sound" class="accent-seismo-orange">
<div>
<p class="text-sm font-medium text-gray-900 dark:text-white">Sound Monitoring</p>
<p class="text-xs text-gray-500 dark:text-gray-400">SLMs, sessions, reports</p>
</div>
</label>
<label class="flex items-center gap-3 p-3 border border-gray-200 dark:border-gray-700 rounded-lg cursor-pointer hover:border-blue-400 has-[:checked]:border-blue-400 has-[:checked]:bg-blue-50 dark:has-[:checked]:bg-blue-900/20 transition-colors">
<input type="checkbox" id="ov-module-vibration" class="accent-blue-500">
<div>
<p class="text-sm font-medium text-gray-900 dark:text-white">Vibration Monitoring</p>
<p class="text-xs text-gray-500 dark:text-gray-400">Seismographs, modems</p>
</div>
</label>
</div>
</div>
</div>
<div id="ov-create-error" class="hidden mt-3 p-3 bg-red-100 dark:bg-red-900/30 text-red-700 dark:text-red-300 rounded-lg text-sm"></div>
<div class="mt-6 flex justify-end space-x-3">
<button type="button"
onclick="hideCreateProjectModal()"
class="px-6 py-2 border border-gray-300 dark:border-gray-600 rounded-lg text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700">
Cancel
</button>
<button type="submit" id="ov-submit-btn"
class="px-6 py-2 bg-seismo-orange hover:bg-seismo-navy text-white rounded-lg font-medium transition-colors">
Create Project
</button>
</div>
</form>
</div>
</div>
</div>
@@ -241,31 +239,58 @@ function showCreateProjectModal() {
document.getElementById('createProjectModal').classList.remove('hidden');
}
function showCreateProjectModal() {
document.getElementById('createProjectModal').classList.remove('hidden');
document.getElementById('createProjectFormElement').reset();
document.getElementById('ov-create-error').classList.add('hidden');
}
function hideCreateProjectModal() {
document.getElementById('createProjectModal').classList.add('hidden');
document.getElementById('projectTypeSelection').classList.remove('hidden');
document.getElementById('projectDetailsForm').classList.add('hidden');
}
function selectProjectType(typeId, typeName) {
document.getElementById('project_type_id').value = typeId;
document.getElementById('projectTypeSelection').classList.add('hidden');
document.getElementById('projectDetailsForm').classList.remove('hidden');
}
document.getElementById('createProjectFormElement').addEventListener('submit', async function(e) {
e.preventDefault();
const submitBtn = document.getElementById('ov-submit-btn');
const errorDiv = document.getElementById('ov-create-error');
errorDiv.classList.add('hidden');
submitBtn.disabled = true;
submitBtn.textContent = 'Creating...';
function backToTypeSelection() {
document.getElementById('projectTypeSelection').classList.remove('hidden');
document.getElementById('projectDetailsForm').classList.add('hidden');
}
const formData = new FormData(this);
// project_type_id no longer required — send empty string so backend accepts it
formData.set('project_type_id', '');
// Handle form submission success
document.body.addEventListener('htmx:afterRequest', function(event) {
if (event.detail.elt.id === 'createProjectFormElement' && event.detail.successful) {
try {
const resp = await fetch('/api/projects/create', { method: 'POST', body: formData });
const result = await resp.json();
if (!resp.ok || !result.success) {
errorDiv.textContent = result.detail || result.message || 'Failed to create project';
errorDiv.classList.remove('hidden');
return;
}
const projectId = result.project_id;
// Add selected modules
if (document.getElementById('ov-module-sound').checked) {
await fetch(`/api/projects/${projectId}/modules`, {
method: 'POST', headers: {'Content-Type':'application/json'},
body: JSON.stringify({ module_type: 'sound_monitoring' }),
});
}
if (document.getElementById('ov-module-vibration').checked) {
await fetch(`/api/projects/${projectId}/modules`, {
method: 'POST', headers: {'Content-Type':'application/json'},
body: JSON.stringify({ module_type: 'vibration_monitoring' }),
});
}
hideCreateProjectModal();
// Refresh project list
htmx.ajax('GET', '/api/projects/list', {target: '#projects-list'});
// Show success message
alert('Project created successfully!');
} catch(err) {
errorDiv.textContent = `Error: ${err.message}`;
errorDiv.classList.remove('hidden');
} finally {
submitBtn.disabled = false;
submitBtn.textContent = 'Create Project';
}
});
</script>

View File

@@ -355,6 +355,25 @@
</form>
<div id="uploadResult" class="hidden mt-3"></div>
</div>
<!-- Deleted Projects -->
<div class="bg-white dark:bg-slate-800 rounded-xl shadow-lg p-6">
<div class="flex items-center justify-between mb-4">
<div>
<h2 class="text-xl font-semibold text-gray-900 dark:text-white">Deleted Projects</h2>
<p class="text-sm text-gray-500 dark:text-gray-400 mt-1">Projects that have been soft-deleted. Restore them or permanently remove them.</p>
</div>
<button onclick="loadDeletedProjects()" class="px-4 py-2 text-sm text-gray-600 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors flex items-center gap-2">
<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="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"></path>
</svg>
Refresh
</button>
</div>
<div id="deletedProjectsList">
<p class="text-sm text-gray-400 dark:text-gray-500 italic">Loading...</p>
</div>
</div>
</div>
</div>
@@ -584,6 +603,67 @@
</style>
<script>
// ========== DELETED PROJECTS ==========
async function loadDeletedProjects() {
const container = document.getElementById('deletedProjectsList');
container.innerHTML = '<p class="text-sm text-gray-400 dark:text-gray-500 italic">Loading...</p>';
try {
const resp = await fetch('/api/projects/deleted');
const projects = await resp.json();
if (!projects.length) {
container.innerHTML = '<p class="text-sm text-gray-400 dark:text-gray-500 italic">No deleted projects.</p>';
return;
}
container.innerHTML = `
<div class="divide-y divide-gray-100 dark:divide-gray-700 border border-gray-200 dark:border-gray-700 rounded-lg overflow-hidden">
${projects.map(p => `
<div class="flex items-center justify-between px-4 py-3 bg-gray-50 dark:bg-gray-900/30">
<div>
<div class="font-medium text-gray-900 dark:text-white">${p.name}</div>
<div class="text-xs text-gray-500 dark:text-gray-400 mt-0.5">
${p.client_name ? p.client_name + ' &middot; ' : ''}Deleted ${new Date(p.deleted_at).toLocaleDateString()}
</div>
</div>
<div class="flex items-center gap-2 ml-4">
<button onclick="restoreProject('${p.id}', '${p.name.replace(/'/g, "\\'")}')"
class="px-3 py-1 text-xs bg-green-600 text-white rounded-lg hover:bg-green-700 transition-colors">
Restore
</button>
<button onclick="permanentlyDeleteProject('${p.id}', '${p.name.replace(/'/g, "\\'")}')"
class="px-3 py-1 text-xs bg-red-600 text-white rounded-lg hover:bg-red-700 transition-colors">
Delete Permanently
</button>
</div>
</div>`).join('')}
</div>`;
} catch (e) {
container.innerHTML = '<p class="text-sm text-red-500">Failed to load deleted projects.</p>';
}
}
async function restoreProject(projectId, name) {
if (!confirm(`Restore "${name}"?`)) return;
const resp = await fetch(`/api/projects/${projectId}/restore`, { method: 'POST' });
if (resp.ok) {
loadDeletedProjects();
} else {
const d = await resp.json();
alert('Failed to restore: ' + (d.detail || 'Unknown error'));
}
}
async function permanentlyDeleteProject(projectId, name) {
if (!confirm(`Permanently delete "${name}" and all its data? This cannot be undone.`)) return;
const resp = await fetch(`/api/projects/${projectId}/permanent`, { method: 'DELETE' });
if (resp.ok) {
loadDeletedProjects();
} else {
const d = await resp.json();
alert('Failed to delete: ' + (d.detail || 'Unknown error'));
}
}
// ========== TAB MANAGEMENT ==========
function showTab(tabName) {
@@ -609,9 +689,10 @@ function showTab(tabName) {
// Save last active tab to localStorage
localStorage.setItem('settings-last-tab', tabName);
// Load roster table when data tab is shown
// Load roster table and deleted projects when data tab is shown
if (tabName === 'data') {
loadRosterTable();
loadDeletedProjects();
}
}

View File

@@ -249,22 +249,36 @@
</button>
</div>
<form id="swap-form" class="p-6 space-y-4">
<form id="swap-form" class="p-6 space-y-5">
<!-- Seismograph picker -->
<div>
<label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Seismograph <span class="text-red-500">*</span></label>
<select id="swap-unit-id" name="unit_id"
class="w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white" required>
<option value="">Loading units...</option>
</select>
<label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
Seismograph <span class="text-red-500">*</span>
</label>
<input id="swap-unit-search" type="text" placeholder="Search by ID or model..."
oninput="filterSwapList('unit')"
class="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white text-sm mb-2 focus:ring-2 focus:ring-seismo-orange">
<div id="swap-unit-list"
class="max-h-48 overflow-y-auto rounded-lg border border-gray-200 dark:border-gray-700 divide-y divide-gray-100 dark:divide-gray-700 bg-white dark:bg-gray-700">
<div class="px-3 py-6 text-center text-sm text-gray-400">Loading...</div>
</div>
<input type="hidden" id="swap-unit-id" name="unit_id" required>
<p id="swap-units-empty" class="hidden text-xs text-gray-500 mt-1">No available seismographs.</p>
</div>
<!-- Modem picker -->
<div>
<label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Modem <span class="text-xs text-gray-400">(optional)</span></label>
<select id="swap-modem-id" name="modem_id"
class="w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white">
<option value="">No modem</option>
</select>
<label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
Modem <span class="text-xs text-gray-400">(optional)</span>
</label>
<input id="swap-modem-search" type="text" placeholder="Search by ID, model, or IP..."
oninput="filterSwapList('modem')"
class="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white text-sm mb-2 focus:ring-2 focus:ring-seismo-orange">
<div id="swap-modem-list"
class="max-h-40 overflow-y-auto rounded-lg border border-gray-200 dark:border-gray-700 divide-y divide-gray-100 dark:divide-gray-700 bg-white dark:bg-gray-700">
<div class="px-3 py-6 text-center text-sm text-gray-400">Loading...</div>
</div>
<input type="hidden" id="swap-modem-id" name="modem_id">
</div>
<div>
@@ -350,6 +364,10 @@ async function openSwapModal() {
document.getElementById('swap-submit-btn').textContent = hasAssignment ? 'Swap' : 'Assign';
document.getElementById('swap-error').classList.add('hidden');
document.getElementById('swap-notes').value = '';
document.getElementById('swap-unit-search').value = '';
document.getElementById('swap-modem-search').value = '';
document.getElementById('swap-unit-id').value = '';
document.getElementById('swap-modem-id').value = '';
await Promise.all([loadSwapUnits(), loadSwapModems()]);
}
@@ -357,26 +375,94 @@ function closeSwapModal() {
document.getElementById('swap-modal').classList.add('hidden');
}
let _swapUnits = [];
let _swapModems = [];
function _fuzzyMatch(query, text) {
if (!query) return true;
const q = query.toLowerCase();
const t = text.toLowerCase();
// Substring match first (fast), then character-sequence fuzzy
if (t.includes(q)) return true;
let qi = 0;
for (let i = 0; i < t.length && qi < q.length; i++) {
if (t[i] === q[qi]) qi++;
}
return qi === q.length;
}
function _renderSwapList(type, items, selectedId, noSelectionLabel) {
const listEl = document.getElementById(`swap-${type}-list`);
if (!items.length) {
listEl.innerHTML = `<div class="px-3 py-4 text-center text-sm text-gray-400">No results</div>`;
return;
}
listEl.innerHTML = items.map(item => {
const isSelected = item.value === selectedId;
return `<button type="button"
onclick="selectSwapItem('${type}', '${item.value}', this)"
class="w-full text-left px-3 py-2.5 flex items-center justify-between hover:bg-gray-50 dark:hover:bg-gray-600 transition-colors ${isSelected ? 'bg-orange-50 dark:bg-orange-900/20' : ''}">
<div>
<span class="font-medium text-gray-900 dark:text-white text-sm">${item.primary}</span>
${item.secondary ? `<span class="ml-2 text-xs text-gray-500 dark:text-gray-400">${item.secondary}</span>` : ''}
</div>
<div class="w-4 h-4 rounded-full border-2 shrink-0 ml-3 ${isSelected ? 'border-seismo-orange bg-seismo-orange' : 'border-gray-400 dark:border-gray-500'}"></div>
</button>`;
}).join('');
}
function selectSwapItem(type, value, btn) {
document.getElementById(`swap-${type}-id`).value = value;
// Update visual state
const list = document.getElementById(`swap-${type}-list`);
list.querySelectorAll('button').forEach(b => {
b.classList.remove('bg-orange-50', 'dark:bg-orange-900/20');
b.querySelector('.rounded-full').className = 'w-4 h-4 rounded-full border-2 shrink-0 ml-3 border-gray-400 dark:border-gray-500';
});
btn.classList.add('bg-orange-50', 'dark:bg-orange-900/20');
btn.querySelector('.rounded-full').className = 'w-4 h-4 rounded-full border-2 shrink-0 ml-3 border-seismo-orange bg-seismo-orange';
}
function filterSwapList(type) {
const query = document.getElementById(`swap-${type}-search`).value;
const items = type === 'unit' ? _swapUnits : _swapModems;
const selectedId = document.getElementById(`swap-${type}-id`).value;
const filtered = items.filter(item =>
_fuzzyMatch(query, item.primary + ' ' + (item.secondary || '') + ' ' + (item.searchText || ''))
);
_renderSwapList(type, filtered, selectedId, type === 'modem' ? 'No modem' : null);
// Re-add "No modem" option for modems
if (type === 'modem') {
const listEl = document.getElementById('swap-modem-list');
const noModemBtn = `<button type="button"
onclick="selectSwapItem('modem', '', this)"
class="w-full text-left px-3 py-2.5 flex items-center justify-between hover:bg-gray-50 dark:hover:bg-gray-600 transition-colors ${!selectedId ? 'bg-orange-50 dark:bg-orange-900/20' : ''}">
<span class="text-sm text-gray-500 dark:text-gray-400 italic">No modem</span>
<div class="w-4 h-4 rounded-full border-2 shrink-0 ml-3 ${!selectedId ? 'border-seismo-orange bg-seismo-orange' : 'border-gray-400 dark:border-gray-500'}"></div>
</button>`;
listEl.insertAdjacentHTML('afterbegin', noModemBtn);
}
}
async function loadSwapUnits() {
try {
const response = await fetch(`/api/projects/${projectId}/available-units?location_type=vibration`);
if (!response.ok) throw new Error('Failed to load units');
const data = await response.json();
const select = document.getElementById('swap-unit-id');
select.innerHTML = '<option value="">Select a seismograph</option>';
if (!data.length) {
document.getElementById('swap-units-empty').classList.remove('hidden');
} else {
document.getElementById('swap-units-empty').classList.add('hidden');
document.getElementById('swap-unit-list').innerHTML = '<div class="px-3 py-4 text-center text-sm text-gray-400">No available seismographs.</div>';
return;
}
data.forEach(unit => {
const option = document.createElement('option');
option.value = unit.id;
option.textContent = unit.id + (unit.model ? ` \u2022 ${unit.model}` : '') + (unit.location ? ` \u2014 ${unit.location}` : '');
select.appendChild(option);
});
document.getElementById('swap-units-empty').classList.add('hidden');
_swapUnits = data.map(u => ({
value: u.id,
primary: u.id,
secondary: [u.model, u.location].filter(Boolean).join(' — '),
searchText: u.model + ' ' + u.location,
}));
_renderSwapList('unit', _swapUnits, document.getElementById('swap-unit-id').value);
} catch (err) {
document.getElementById('swap-error').textContent = 'Failed to load seismographs.';
document.getElementById('swap-error').classList.remove('hidden');
@@ -388,21 +474,16 @@ async function loadSwapModems() {
const response = await fetch(`/api/projects/${projectId}/available-modems`);
if (!response.ok) throw new Error('Failed to load modems');
const data = await response.json();
const select = document.getElementById('swap-modem-id');
select.innerHTML = '<option value="">No modem</option>';
data.forEach(modem => {
const option = document.createElement('option');
option.value = modem.id;
let label = modem.id;
if (modem.hardware_model) label += ` \u2022 ${modem.hardware_model}`;
if (modem.ip_address) label += ` \u2014 ${modem.ip_address}`;
option.textContent = label;
select.appendChild(option);
});
_swapModems = data.map(m => ({
value: m.id,
primary: m.id,
secondary: [m.hardware_model, m.ip_address].filter(Boolean).join(' — '),
searchText: (m.hardware_model || '') + ' ' + (m.ip_address || ''),
}));
filterSwapList('modem'); // renders with "No modem" prepended
} catch (err) {
// Modem list failure is non-fatal — just leave blank
console.warn('Failed to load modems:', err);
document.getElementById('swap-modem-list').innerHTML = '<div class="px-3 py-4 text-center text-sm text-gray-400">Could not load modems.</div>';
}
}