218 lines
6.3 KiB
Python
218 lines
6.3 KiB
Python
"""Creating, editing and querying events. Shared by the device API, the JSON
|
|
API and the dashboard, so a button press and a tap on the website behave the same."""
|
|
|
|
from datetime import datetime, timedelta
|
|
|
|
from sqlalchemy import or_, select
|
|
from sqlalchemy.orm import Session
|
|
|
|
from ..models import Device, Event, Kind
|
|
from ..timeutil import utcnow
|
|
|
|
# Longest session the queries look back for when a range starts mid-session.
|
|
LOOKBACK = timedelta(days=1)
|
|
|
|
|
|
def live() -> object:
|
|
"""WHERE clause for events that haven't been deleted."""
|
|
return Event.deleted_at.is_(None)
|
|
|
|
|
|
def find_open_session(db: Session, kind: Kind, at: datetime) -> Event | None:
|
|
"""The unfinished session of `kind` that a press at `at` would end, if any."""
|
|
q = (
|
|
select(Event)
|
|
.where(live(), Event.kind_slug == kind.slug, Event.ended_at.is_(None), Event.started_at <= at)
|
|
.order_by(Event.started_at.desc())
|
|
.limit(1)
|
|
)
|
|
if kind.max_duration:
|
|
q = q.where(Event.started_at >= at - kind.max_duration)
|
|
return db.scalars(q).first()
|
|
|
|
|
|
def apply_press(
|
|
db: Session,
|
|
kind: Kind,
|
|
at: datetime,
|
|
*,
|
|
source: str,
|
|
device: Device | None = None,
|
|
button: int | None = None,
|
|
note: str | None = None,
|
|
clock_corrected: bool = False,
|
|
) -> tuple[Event, str]:
|
|
"""Record one press of `kind` at `at`. Returns (event, role).
|
|
|
|
Instant kinds: a new event (role "instant").
|
|
Duration kinds: ends the open session if there is one ("end"), otherwise
|
|
starts a new one ("start").
|
|
"""
|
|
if kind.is_duration:
|
|
open_ev = find_open_session(db, kind, at)
|
|
if open_ev is not None:
|
|
open_ev.ended_at = at
|
|
db.flush()
|
|
return open_ev, "end"
|
|
|
|
ev = Event(
|
|
kind=kind,
|
|
started_at=at,
|
|
source=source,
|
|
device_id=device.id if device else None,
|
|
button=button,
|
|
note=note,
|
|
clock_corrected=clock_corrected,
|
|
)
|
|
db.add(ev)
|
|
db.flush()
|
|
return ev, "start" if kind.is_duration else "instant"
|
|
|
|
|
|
def events_between(
|
|
db: Session,
|
|
start: datetime,
|
|
end: datetime,
|
|
*,
|
|
categories: set[str] | None = None,
|
|
) -> list[Event]:
|
|
"""Live events that overlap [start, end), oldest first."""
|
|
q = (
|
|
select(Event)
|
|
.join(Event.kind)
|
|
.where(live(), Event.started_at < end, Event.started_at >= start - LOOKBACK)
|
|
.order_by(Event.started_at)
|
|
)
|
|
if categories:
|
|
q = q.where(Kind.category.in_(categories))
|
|
out = []
|
|
for ev in db.scalars(q):
|
|
if ev.started_at >= start or effective_end(ev) > start:
|
|
out.append(ev)
|
|
return out
|
|
|
|
|
|
def effective_end(ev: Event, now: datetime | None = None) -> datetime:
|
|
"""Where to draw/count a session up to. Open sessions run until now, capped
|
|
at the kind's maximum so a forgotten stop doesn't count as 3 days of sleep."""
|
|
if ev.ended_at is not None:
|
|
return ev.ended_at
|
|
if not ev.kind.is_duration:
|
|
return ev.started_at
|
|
end = now or utcnow()
|
|
if ev.kind.max_duration:
|
|
end = min(end, ev.started_at + ev.kind.max_duration)
|
|
return max(end, ev.started_at)
|
|
|
|
|
|
def is_stale(ev: Event, now: datetime | None = None) -> bool:
|
|
"""An open session that has run past its kind's maximum: probably a forgotten stop."""
|
|
if not ev.is_open or not ev.kind.max_duration:
|
|
return False
|
|
return (now or utcnow()) - ev.started_at > ev.kind.max_duration
|
|
|
|
|
|
def open_sessions(db: Session) -> list[Event]:
|
|
q = (
|
|
select(Event)
|
|
.join(Event.kind)
|
|
.where(live(), Event.ended_at.is_(None), Kind.mode == "duration")
|
|
.order_by(Event.started_at.desc())
|
|
)
|
|
return list(db.scalars(q))
|
|
|
|
|
|
def recent_events(db: Session, limit: int = 10) -> list[Event]:
|
|
q = select(Event).where(live()).order_by(Event.started_at.desc()).limit(limit)
|
|
return list(db.scalars(q))
|
|
|
|
|
|
def search_events(
|
|
db: Session,
|
|
*,
|
|
before: datetime | None = None,
|
|
after: datetime | None = None,
|
|
categories: set[str] | None = None,
|
|
kinds: set[str] | None = None,
|
|
include_deleted: bool = False,
|
|
limit: int = 200,
|
|
) -> list[Event]:
|
|
"""Newest first."""
|
|
q = select(Event).join(Event.kind).order_by(Event.started_at.desc()).limit(limit)
|
|
if not include_deleted:
|
|
q = q.where(live())
|
|
if before:
|
|
q = q.where(Event.started_at < before)
|
|
if after:
|
|
q = q.where(or_(Event.started_at >= after, Event.ended_at >= after))
|
|
if categories:
|
|
q = q.where(Kind.category.in_(categories))
|
|
if kinds:
|
|
q = q.where(Event.kind_slug.in_(kinds))
|
|
return list(db.scalars(q))
|
|
|
|
|
|
class EventError(ValueError):
|
|
"""Invalid input from a form or the API; the message is shown to the user."""
|
|
|
|
|
|
def validate_times(kind: Kind, started_at: datetime, ended_at: datetime | None) -> None:
|
|
now = utcnow()
|
|
if started_at > now + timedelta(minutes=5):
|
|
raise EventError("That time is in the future.")
|
|
if ended_at is not None:
|
|
if not kind.is_duration:
|
|
raise EventError(f"{kind.label} doesn't have an end time.")
|
|
if ended_at < started_at:
|
|
raise EventError("The end is before the start.")
|
|
if ended_at > now + timedelta(minutes=5):
|
|
raise EventError("The end time is in the future.")
|
|
|
|
|
|
def create_manual(
|
|
db: Session, kind: Kind, started_at: datetime, ended_at: datetime | None, note: str | None
|
|
) -> Event:
|
|
validate_times(kind, started_at, ended_at)
|
|
ev = Event(kind=kind, started_at=started_at, ended_at=ended_at, note=note or None, source="manual")
|
|
db.add(ev)
|
|
db.commit()
|
|
return ev
|
|
|
|
|
|
def update_event(
|
|
db: Session,
|
|
ev: Event,
|
|
*,
|
|
kind: Kind,
|
|
started_at: datetime,
|
|
ended_at: datetime | None,
|
|
note: str | None,
|
|
) -> Event:
|
|
if not kind.is_duration:
|
|
ended_at = None
|
|
validate_times(kind, started_at, ended_at)
|
|
ev.kind = kind
|
|
ev.started_at = started_at
|
|
ev.ended_at = ended_at
|
|
ev.note = note or None
|
|
db.commit()
|
|
return ev
|
|
|
|
|
|
def end_session(db: Session, ev: Event, at: datetime | None = None) -> Event:
|
|
if not ev.is_open:
|
|
raise EventError("That event is already finished.")
|
|
ev.ended_at = max(at or utcnow(), ev.started_at)
|
|
db.commit()
|
|
return ev
|
|
|
|
|
|
def delete_event(db: Session, ev: Event) -> None:
|
|
ev.deleted_at = utcnow()
|
|
db.commit()
|
|
|
|
|
|
def restore_event(db: Session, ev: Event) -> None:
|
|
ev.deleted_at = None
|
|
db.commit()
|