M1: implement operational core
Demo auth, seed import/reset, dashboard, vehicle/booking list+detail, audit trail. Backend: 19 tests passing, ruff clean. Frontend: React Router shell, typed API client, responsive pages. Verified end-to-end via curl and browser.
This commit is contained in:
@@ -0,0 +1,47 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from fastapi import APIRouter, Depends, Query
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.api.deps import get_current_user, get_db
|
||||
from app.models.audit import AuditEvent
|
||||
from app.schemas import AuditEventOut, CurrentUser
|
||||
|
||||
router = APIRouter(prefix="/api/v1/audit", tags=["audit"])
|
||||
|
||||
|
||||
@router.get("", response_model=list[AuditEventOut])
|
||||
def list_audit_events(
|
||||
actor_label: str | None = Query(default=None),
|
||||
action: str | None = Query(default=None),
|
||||
entity_type: str | None = Query(default=None),
|
||||
correlation_id: str | None = Query(default=None),
|
||||
limit: int = Query(default=100, le=500),
|
||||
db: Session = Depends(get_db),
|
||||
_user: CurrentUser = Depends(get_current_user),
|
||||
) -> list[AuditEventOut]:
|
||||
stmt = select(AuditEvent).order_by(AuditEvent.occurred_at.desc()).limit(limit)
|
||||
if actor_label:
|
||||
stmt = stmt.where(AuditEvent.actor_label == actor_label)
|
||||
if action:
|
||||
stmt = stmt.where(AuditEvent.action == action)
|
||||
if entity_type:
|
||||
stmt = stmt.where(AuditEvent.entity_type == entity_type)
|
||||
if correlation_id:
|
||||
stmt = stmt.where(AuditEvent.correlation_id == correlation_id)
|
||||
events = db.scalars(stmt).all()
|
||||
return [
|
||||
AuditEventOut(
|
||||
id=str(e.id),
|
||||
actor_type=e.actor_type,
|
||||
actor_label=e.actor_label,
|
||||
action=e.action,
|
||||
entity_type=e.entity_type,
|
||||
entity_id=str(e.entity_id) if e.entity_id else None,
|
||||
correlation_id=str(e.correlation_id),
|
||||
occurred_at=e.occurred_at,
|
||||
metadata=e.metadata_json,
|
||||
)
|
||||
for e in events
|
||||
]
|
||||
@@ -0,0 +1,63 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.api.deps import get_current_user, get_db
|
||||
from app.models.booking import Booking
|
||||
from app.models.customer import Customer
|
||||
from app.models.vehicle import Vehicle
|
||||
from app.schemas import BookingOut, CurrentUser
|
||||
|
||||
router = APIRouter(prefix="/api/v1/bookings", tags=["bookings"])
|
||||
|
||||
|
||||
def _to_out(booking: Booking, customer: Customer, vehicle: Vehicle) -> BookingOut:
|
||||
return BookingOut(
|
||||
public_ref=booking.public_ref,
|
||||
customer_ref=customer.public_ref,
|
||||
vehicle_ref=vehicle.public_ref,
|
||||
starts_at=booking.starts_at,
|
||||
ends_at=booking.ends_at,
|
||||
status=booking.status,
|
||||
start_odometer_km=booking.start_odometer_km,
|
||||
end_odometer_km=booking.end_odometer_km,
|
||||
requirements_complete=booking.requirements_complete,
|
||||
customer_name=f"{customer.first_name} {customer.last_name}",
|
||||
)
|
||||
|
||||
|
||||
@router.get("", response_model=list[BookingOut])
|
||||
def list_bookings(
|
||||
status: str | None = Query(default=None),
|
||||
vehicle_ref: str | None = Query(default=None),
|
||||
db: Session = Depends(get_db),
|
||||
_user: CurrentUser = Depends(get_current_user),
|
||||
) -> list[BookingOut]:
|
||||
stmt = select(Booking).order_by(Booking.starts_at.desc())
|
||||
if status:
|
||||
stmt = stmt.where(Booking.status == status)
|
||||
if vehicle_ref:
|
||||
vehicle = db.scalar(select(Vehicle).where(Vehicle.public_ref == vehicle_ref))
|
||||
if vehicle is None:
|
||||
return []
|
||||
stmt = stmt.where(Booking.vehicle_id == vehicle.id)
|
||||
bookings = db.scalars(stmt).all()
|
||||
customers = {c.id: c for c in db.scalars(select(Customer)).all()}
|
||||
vehicles = {v.id: v for v in db.scalars(select(Vehicle)).all()}
|
||||
return [_to_out(b, customers[b.customer_id], vehicles[b.vehicle_id]) for b in bookings]
|
||||
|
||||
|
||||
@router.get("/{public_ref}", response_model=BookingOut)
|
||||
def get_booking(
|
||||
public_ref: str,
|
||||
db: Session = Depends(get_db),
|
||||
_user: CurrentUser = Depends(get_current_user),
|
||||
) -> BookingOut:
|
||||
booking = db.scalar(select(Booking).where(Booking.public_ref == public_ref))
|
||||
if booking is None:
|
||||
raise HTTPException(status_code=404, detail="Booking not found")
|
||||
customer = db.get(Customer, booking.customer_id)
|
||||
vehicle = db.get(Vehicle, booking.vehicle_id)
|
||||
return _to_out(booking, customer, vehicle)
|
||||
@@ -0,0 +1,136 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date, datetime
|
||||
|
||||
from fastapi import APIRouter, Depends
|
||||
from sqlalchemy import func, select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.api.deps import get_current_user, get_db
|
||||
from app.core.config import get_settings
|
||||
from app.models.booking import Booking
|
||||
from app.models.customer import Customer
|
||||
from app.models.data_quality import DataQualityIssue
|
||||
from app.models.outbox import OutboxEvent
|
||||
from app.models.vehicle import Vehicle
|
||||
from app.schemas import (
|
||||
AttentionItem,
|
||||
AutomationRunOut,
|
||||
CurrentUser,
|
||||
DashboardMetrics,
|
||||
DashboardOut,
|
||||
TodayItem,
|
||||
)
|
||||
|
||||
router = APIRouter(prefix="/api/v1/dashboard", tags=["dashboard"])
|
||||
settings = get_settings()
|
||||
|
||||
_SEVERITY_ORDER = {"high": 0, "medium": 1, "low": 2}
|
||||
|
||||
|
||||
def _today() -> date:
|
||||
return datetime.fromisoformat(settings.demo_today).date()
|
||||
|
||||
|
||||
@router.get("", response_model=DashboardOut)
|
||||
def get_dashboard(
|
||||
db: Session = Depends(get_db),
|
||||
_user: CurrentUser = Depends(get_current_user),
|
||||
) -> DashboardOut:
|
||||
status_counts = dict(
|
||||
db.execute(
|
||||
select(Vehicle.operational_status, func.count()).group_by(Vehicle.operational_status)
|
||||
).all()
|
||||
)
|
||||
open_issues = db.scalar(
|
||||
select(func.count()).select_from(DataQualityIssue).where(DataQualityIssue.status == "open")
|
||||
)
|
||||
pending_or_failed = db.scalar(
|
||||
select(func.count())
|
||||
.select_from(OutboxEvent)
|
||||
.where(OutboxEvent.delivery_status.in_(["pending", "failed"]))
|
||||
)
|
||||
metrics = DashboardMetrics(
|
||||
available=status_counts.get("available", 0),
|
||||
rented=status_counts.get("rented", 0),
|
||||
cleaning=status_counts.get("cleaning", 0),
|
||||
maintenance=status_counts.get("maintenance", 0),
|
||||
blocked=status_counts.get("blocked", 0),
|
||||
open_quality_issues=open_issues or 0,
|
||||
pending_or_failed_workflows=pending_or_failed or 0,
|
||||
)
|
||||
|
||||
vehicles_by_id = {v.id: v for v in db.scalars(select(Vehicle)).all()}
|
||||
customers_by_id = {c.id: c for c in db.scalars(select(Customer)).all()}
|
||||
|
||||
issues = db.scalars(
|
||||
select(DataQualityIssue)
|
||||
.where(DataQualityIssue.status == "open")
|
||||
.order_by(DataQualityIssue.detected_at.asc())
|
||||
).all()
|
||||
attention_items = []
|
||||
for issue in issues:
|
||||
if issue.entity_type == "vehicle":
|
||||
entity = vehicles_by_id.get(issue.entity_id)
|
||||
link_type = "vehicle"
|
||||
else:
|
||||
entity = customers_by_id.get(issue.entity_id)
|
||||
link_type = "customer"
|
||||
link_ref = entity.public_ref if entity else ""
|
||||
title = f"{issue.rule_type.replace('_', ' ').title()} — {link_ref}"
|
||||
attention_items.append(
|
||||
AttentionItem(
|
||||
kind="quality_issue",
|
||||
severity=issue.severity,
|
||||
title=title,
|
||||
detail=issue.evidence_json.get("summary", ""),
|
||||
link_type=link_type,
|
||||
link_ref=link_ref,
|
||||
)
|
||||
)
|
||||
attention_items.sort(key=lambda item: _SEVERITY_ORDER.get(item.severity, 3))
|
||||
|
||||
today = _today()
|
||||
bookings = db.scalars(select(Booking)).all()
|
||||
today_items: list[TodayItem] = []
|
||||
for b in bookings:
|
||||
vehicle = vehicles_by_id.get(b.vehicle_id)
|
||||
vehicle_ref = vehicle.public_ref if vehicle else ""
|
||||
if b.starts_at.date() == today and b.status in ("reserved", "active"):
|
||||
today_items.append(
|
||||
TodayItem(
|
||||
kind="departure", booking_ref=b.public_ref, vehicle_ref=vehicle_ref,
|
||||
scheduled_at=b.starts_at,
|
||||
)
|
||||
)
|
||||
if b.ends_at.date() == today and b.status in ("active", "returned"):
|
||||
today_items.append(
|
||||
TodayItem(
|
||||
kind="return", booking_ref=b.public_ref, vehicle_ref=vehicle_ref,
|
||||
scheduled_at=b.ends_at,
|
||||
)
|
||||
)
|
||||
today_items.sort(key=lambda item: item.scheduled_at)
|
||||
|
||||
recent = db.scalars(
|
||||
select(OutboxEvent).order_by(OutboxEvent.occurred_at.desc()).limit(5)
|
||||
).all()
|
||||
recent_automation = [
|
||||
AutomationRunOut(
|
||||
event_id=str(r.event_id),
|
||||
event_type=r.event_type,
|
||||
aggregate_ref=r.payload_json.get("aggregate_ref", ""),
|
||||
status=r.delivery_status,
|
||||
attempts=r.attempts,
|
||||
last_error=r.last_error,
|
||||
occurred_at=r.occurred_at,
|
||||
)
|
||||
for r in recent
|
||||
]
|
||||
|
||||
return DashboardOut(
|
||||
metrics=metrics,
|
||||
attention_items=attention_items,
|
||||
today=today_items,
|
||||
recent_automation=recent_automation,
|
||||
)
|
||||
@@ -0,0 +1,76 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
|
||||
from fastapi import APIRouter, Depends, Response
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.api.deps import get_db, require_operations_manager
|
||||
from app.core.config import get_settings
|
||||
from app.core.security import SessionPayload, create_session_token
|
||||
from app.models.user import User
|
||||
from app.schemas import CurrentUser, DemoLoginRequest
|
||||
from app.seed_loader import reset_and_seed
|
||||
from app.services.audit import record_audit_event
|
||||
|
||||
router = APIRouter(prefix="/api/v1/demo", tags=["demo"])
|
||||
settings = get_settings()
|
||||
|
||||
|
||||
@router.post("/login", response_model=CurrentUser)
|
||||
def demo_login(
|
||||
body: DemoLoginRequest, response: Response, db: Session = Depends(get_db)
|
||||
) -> CurrentUser:
|
||||
public_ref = "USR-OPS" if body.role == "operations_manager" else "USR-EMP"
|
||||
user = db.scalar(select(User).where(User.public_ref == public_ref))
|
||||
if user is None:
|
||||
raise LookupError("Demo users are missing; run the seed loader first.")
|
||||
|
||||
token = create_session_token(
|
||||
SessionPayload(
|
||||
user_id=str(user.id),
|
||||
public_ref=user.public_ref,
|
||||
role=user.role,
|
||||
display_name=user.display_name,
|
||||
issued_at=int(time.time()),
|
||||
)
|
||||
)
|
||||
response.set_cookie(
|
||||
settings.session_cookie_name,
|
||||
token,
|
||||
httponly=True,
|
||||
samesite="lax",
|
||||
max_age=settings.session_ttl_seconds,
|
||||
)
|
||||
record_audit_event(
|
||||
db,
|
||||
actor_type="user",
|
||||
actor_id=user.id,
|
||||
actor_label=user.display_name,
|
||||
action="demo_login",
|
||||
entity_type="user",
|
||||
entity_id=user.id,
|
||||
)
|
||||
db.commit()
|
||||
return CurrentUser(public_ref=user.public_ref, display_name=user.display_name, role=user.role)
|
||||
|
||||
|
||||
@router.post("/reset")
|
||||
def demo_reset(
|
||||
response: Response,
|
||||
db: Session = Depends(get_db),
|
||||
user: CurrentUser = Depends(require_operations_manager),
|
||||
) -> dict:
|
||||
result = reset_and_seed(db)
|
||||
record_audit_event(
|
||||
db,
|
||||
actor_type="user",
|
||||
actor_label=user.display_name,
|
||||
action="demo_reset",
|
||||
entity_type="system",
|
||||
metadata={"counts": result.counts},
|
||||
)
|
||||
db.commit()
|
||||
response.delete_cookie(settings.session_cookie_name)
|
||||
return {"status": "reset", "counts": result.counts}
|
||||
@@ -0,0 +1,164 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.api.deps import get_current_user, get_db
|
||||
from app.models.booking import Booking
|
||||
from app.models.customer import Customer
|
||||
from app.models.data_quality import DataQualityIssue
|
||||
from app.models.inspection import Inspection
|
||||
from app.models.maintenance import MaintenanceRecord
|
||||
from app.models.vehicle import Vehicle
|
||||
from app.schemas import (
|
||||
BookingSummaryOut,
|
||||
CurrentUser,
|
||||
DataQualityIssueOut,
|
||||
InspectionOut,
|
||||
MaintenanceOut,
|
||||
VehicleDetailOut,
|
||||
VehicleOut,
|
||||
)
|
||||
|
||||
router = APIRouter(prefix="/api/v1/vehicles", tags=["vehicles"])
|
||||
|
||||
|
||||
def _attention_vehicle_ids(db: Session) -> set:
|
||||
rows = db.scalars(
|
||||
select(DataQualityIssue.entity_id).where(
|
||||
DataQualityIssue.entity_type == "vehicle",
|
||||
DataQualityIssue.status == "open",
|
||||
)
|
||||
).all()
|
||||
return set(rows)
|
||||
|
||||
|
||||
@router.get("", response_model=list[VehicleOut])
|
||||
def list_vehicles(
|
||||
status: str | None = Query(default=None),
|
||||
attention_only: bool = Query(default=False),
|
||||
db: Session = Depends(get_db),
|
||||
_user: CurrentUser = Depends(get_current_user),
|
||||
) -> list[VehicleOut]:
|
||||
stmt = select(Vehicle).order_by(Vehicle.public_ref)
|
||||
if status:
|
||||
stmt = stmt.where(Vehicle.operational_status == status)
|
||||
vehicles = db.scalars(stmt).all()
|
||||
attention_ids = _attention_vehicle_ids(db)
|
||||
out = [
|
||||
VehicleOut(
|
||||
public_ref=v.public_ref,
|
||||
make=v.make,
|
||||
model=v.model,
|
||||
model_year=v.model_year,
|
||||
registration_number=v.registration_number,
|
||||
location=v.location,
|
||||
operational_status=v.operational_status,
|
||||
odometer_km=v.odometer_km,
|
||||
next_service_km=v.next_service_km,
|
||||
active=v.active,
|
||||
attention=v.id in attention_ids or v.operational_status == "blocked",
|
||||
)
|
||||
for v in vehicles
|
||||
]
|
||||
if attention_only:
|
||||
out = [v for v in out if v.attention]
|
||||
return out
|
||||
|
||||
|
||||
@router.get("/{public_ref}", response_model=VehicleDetailOut)
|
||||
def get_vehicle(
|
||||
public_ref: str,
|
||||
db: Session = Depends(get_db),
|
||||
_user: CurrentUser = Depends(get_current_user),
|
||||
) -> VehicleDetailOut:
|
||||
vehicle = db.scalar(select(Vehicle).where(Vehicle.public_ref == public_ref))
|
||||
if vehicle is None:
|
||||
raise HTTPException(status_code=404, detail="Vehicle not found")
|
||||
|
||||
bookings = db.scalars(
|
||||
select(Booking).where(Booking.vehicle_id == vehicle.id).order_by(Booking.starts_at.desc())
|
||||
).all()
|
||||
customer_ref_by_id = {c.id: c.public_ref for c in db.scalars(select(Customer)).all()}
|
||||
inspections = db.scalars(
|
||||
select(Inspection)
|
||||
.where(Inspection.vehicle_id == vehicle.id)
|
||||
.order_by(Inspection.completed_at.desc())
|
||||
).all()
|
||||
maintenance = db.scalars(
|
||||
select(MaintenanceRecord)
|
||||
.where(MaintenanceRecord.vehicle_id == vehicle.id)
|
||||
.order_by(MaintenanceRecord.occurred_at.desc())
|
||||
).all()
|
||||
issues = db.scalars(
|
||||
select(DataQualityIssue)
|
||||
.where(DataQualityIssue.entity_type == "vehicle", DataQualityIssue.entity_id == vehicle.id)
|
||||
.order_by(DataQualityIssue.detected_at.desc())
|
||||
).all()
|
||||
|
||||
booking_by_id = {b.id: b.public_ref for b in bookings}
|
||||
|
||||
attention_ids = _attention_vehicle_ids(db)
|
||||
return VehicleDetailOut(
|
||||
public_ref=vehicle.public_ref,
|
||||
make=vehicle.make,
|
||||
model=vehicle.model,
|
||||
model_year=vehicle.model_year,
|
||||
registration_number=vehicle.registration_number,
|
||||
location=vehicle.location,
|
||||
operational_status=vehicle.operational_status,
|
||||
odometer_km=vehicle.odometer_km,
|
||||
next_service_km=vehicle.next_service_km,
|
||||
active=vehicle.active,
|
||||
attention=vehicle.id in attention_ids or vehicle.operational_status == "blocked",
|
||||
bookings=[
|
||||
BookingSummaryOut(
|
||||
public_ref=b.public_ref,
|
||||
customer_ref=customer_ref_by_id.get(b.customer_id, ""),
|
||||
vehicle_ref=vehicle.public_ref,
|
||||
starts_at=b.starts_at,
|
||||
ends_at=b.ends_at,
|
||||
status=b.status,
|
||||
)
|
||||
for b in bookings
|
||||
],
|
||||
inspections=[
|
||||
InspectionOut(
|
||||
public_ref=i.public_ref,
|
||||
booking_ref=booking_by_id.get(i.booking_id, ""),
|
||||
type=i.type,
|
||||
fuel_level_percent=i.fuel_level_percent,
|
||||
cleanliness_ok=i.cleanliness_ok,
|
||||
damage_reported=i.damage_reported,
|
||||
technical_warning=i.technical_warning,
|
||||
odometer_km=i.odometer_km,
|
||||
completed_at=i.completed_at,
|
||||
)
|
||||
for i in inspections
|
||||
],
|
||||
maintenance=[
|
||||
MaintenanceOut(
|
||||
public_ref=m.public_ref,
|
||||
occurred_at=m.occurred_at,
|
||||
odometer_km=m.odometer_km,
|
||||
category=m.category,
|
||||
summary=m.summary,
|
||||
)
|
||||
for m in maintenance
|
||||
],
|
||||
quality_issues=[
|
||||
DataQualityIssueOut(
|
||||
public_ref=q.public_ref,
|
||||
rule_type=q.rule_type,
|
||||
entity_type=q.entity_type,
|
||||
entity_ref=vehicle.public_ref,
|
||||
severity=q.severity,
|
||||
status=q.status,
|
||||
evidence=q.evidence_json,
|
||||
detected_at=q.detected_at,
|
||||
resolved_at=q.resolved_at,
|
||||
)
|
||||
for q in issues
|
||||
],
|
||||
)
|
||||
Reference in New Issue
Block a user