Add scheduled and event-driven printing with a new web UI
The web server now runs a scheduler over schedules kept in SQLite
(~/.local/share/receipt-maker, outside the clone). A schedule is a
trigger, a receipt made of blocks, and options:
- Triggers: once, recurring (rrule-based, DST-safe), sun times,
reminders before calendar (ICS) events, RSS/JSON watchers, webhooks
with per-schedule secrets.
- Blocks, rendered fresh as one job: templated notes ({date},
{days_until:..}, rotating {choice}, trigger vars), QR, saved images,
random image, calendar agenda, feed headlines, dividers.
- Rules: quiet hours (hold/skip/ignore), daily cap, pause, catch-up
window for missed runs (never replayed), retries on connect failure
only; a mid-job drop (new PrinterDropped) is never resent.
receipt.py renders through composable Blocks (render_note/image/qr are
wrappers, output unchanged). Print history persists, with Print again.
The page moves to web/ with Print (note/image/QR + paper preview),
Schedules (presets, editor with live preview and next runs), History
and Settings tabs.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
@@ -0,0 +1,282 @@
|
||||
"""Validated shapes for schedules, receipts and settings (web server only).
|
||||
|
||||
A schedule is a trigger (when), blocks (what: one receipt, printed as one job)
|
||||
and options (what to do about quiet hours, empty receipts, missed runs).
|
||||
Specs are stored as the JSON of these models.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import datetime as dt
|
||||
from typing import Annotated, Literal
|
||||
from urllib.parse import urlparse
|
||||
from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
|
||||
|
||||
import receipt
|
||||
|
||||
MAX_NOTE_CHARS = 4000
|
||||
MAX_CAPTION_CHARS = 500
|
||||
MAX_BLOCKS = 20
|
||||
WEEKDAYS = [0, 1, 2, 3, 4, 5, 6] # Monday first, like datetime.weekday()
|
||||
|
||||
|
||||
class Model(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
|
||||
def http_url(value: str) -> str:
|
||||
value = value.strip()
|
||||
parsed = urlparse(value)
|
||||
if parsed.scheme not in ("http", "https") or not parsed.netloc:
|
||||
raise ValueError("must be an http:// or https:// URL")
|
||||
return value
|
||||
|
||||
|
||||
def weekday_list(value: list[int]) -> list[int]:
|
||||
if any(d not in WEEKDAYS for d in value):
|
||||
raise ValueError("weekdays are 0 (Monday) to 6 (Sunday)")
|
||||
return sorted(set(value))
|
||||
|
||||
|
||||
# --- triggers ---
|
||||
|
||||
|
||||
class OnceTrigger(Model):
|
||||
type: Literal["once"]
|
||||
at: dt.datetime # wall-clock time in the settings timezone
|
||||
|
||||
@field_validator("at")
|
||||
@classmethod
|
||||
def _naive(cls, value: dt.datetime) -> dt.datetime:
|
||||
return value.replace(tzinfo=None, second=0, microsecond=0)
|
||||
|
||||
|
||||
class RecurringTrigger(Model):
|
||||
type: Literal["recurring"]
|
||||
freq: Literal["daily", "weekly", "monthly", "yearly"] = "daily"
|
||||
interval: int = Field(default=1, ge=1, le=365)
|
||||
times: list[dt.time] = Field(min_length=1, max_length=24)
|
||||
weekdays: list[int] = [] # daily: only these days; weekly: these days (default: start's)
|
||||
monthday: int | None = Field(default=None, ge=-1, le=31) # -1 is the last day; not 0
|
||||
setpos: int | None = Field(default=None, ge=-1, le=5) # with weekdays: 1st..5th, -1 last
|
||||
month: int | None = Field(default=None, ge=1, le=12) # yearly
|
||||
start: dt.date | None = None # anchors the interval; filled in on save
|
||||
until: dt.date | None = None
|
||||
rrule: str | None = Field(default=None, max_length=500) # advanced: replaces freq..month
|
||||
|
||||
@field_validator("weekdays")
|
||||
@classmethod
|
||||
def _weekdays(cls, value: list[int]) -> list[int]:
|
||||
return weekday_list(value)
|
||||
|
||||
@field_validator("times")
|
||||
@classmethod
|
||||
def _minutes(cls, value: list[dt.time]) -> list[dt.time]:
|
||||
return sorted({t.replace(second=0, microsecond=0, tzinfo=None) for t in value})
|
||||
|
||||
@model_validator(mode="after")
|
||||
def _consistent(self) -> RecurringTrigger:
|
||||
if self.monthday == 0:
|
||||
raise ValueError("monthday is 1-31, or -1 for the last day")
|
||||
if self.setpos is not None and not self.weekdays:
|
||||
raise ValueError("pick the weekday(s) for 'first/second/last …'")
|
||||
if self.until and self.start and self.until < self.start:
|
||||
raise ValueError("'until' is before the start date")
|
||||
if self.rrule is not None and not self.rrule.strip():
|
||||
self.rrule = None
|
||||
return self
|
||||
|
||||
|
||||
class SunTrigger(Model):
|
||||
type: Literal["sun"]
|
||||
event: Literal["dawn", "sunrise", "noon", "sunset", "dusk"] = "sunrise"
|
||||
offset_minutes: int = Field(default=0, ge=-720, le=720)
|
||||
weekdays: list[int] = WEEKDAYS
|
||||
|
||||
@field_validator("weekdays")
|
||||
@classmethod
|
||||
def _weekdays(cls, value: list[int]) -> list[int]:
|
||||
return weekday_list(value)
|
||||
|
||||
|
||||
class CalendarTrigger(Model):
|
||||
type: Literal["calendar"]
|
||||
source_id: str
|
||||
minutes_before: int = Field(default=15, ge=0, le=7 * 24 * 60)
|
||||
contains: str = Field(default="", max_length=200) # title filter, case-insensitive
|
||||
include_all_day: bool = False
|
||||
|
||||
|
||||
class WatchTrigger(Model):
|
||||
type: Literal["watch"]
|
||||
kind: Literal["rss", "json"] = "rss"
|
||||
url: str = Field(max_length=2000)
|
||||
path: str = Field(default="", max_length=200) # json: dotted path, e.g. "data.price"
|
||||
condition: Literal["changed", "above", "below"] = "changed"
|
||||
threshold: float | None = None
|
||||
every_minutes: int = Field(default=30, ge=5, le=24 * 60)
|
||||
max_items: int = Field(default=3, ge=1, le=10) # rss: new items per receipt
|
||||
|
||||
@field_validator("url")
|
||||
@classmethod
|
||||
def _url(cls, value: str) -> str:
|
||||
return http_url(value)
|
||||
|
||||
@model_validator(mode="after")
|
||||
def _json_needs(self) -> WatchTrigger:
|
||||
if self.kind == "json" and self.condition != "changed" and self.threshold is None:
|
||||
raise ValueError("set a threshold for 'above'/'below'")
|
||||
return self
|
||||
|
||||
|
||||
class WebhookTrigger(Model):
|
||||
type: Literal["webhook"]
|
||||
per_hour: int = Field(default=10, ge=1, le=120)
|
||||
|
||||
|
||||
Trigger = Annotated[
|
||||
OnceTrigger | RecurringTrigger | SunTrigger | CalendarTrigger | WatchTrigger | WebhookTrigger,
|
||||
Field(discriminator="type"),
|
||||
]
|
||||
TIMED = ("once", "recurring", "sun") # next_run_at is a fixed time
|
||||
POLLED = ("calendar", "watch") # checked every tick / every few minutes
|
||||
|
||||
|
||||
# --- receipt blocks ---
|
||||
|
||||
|
||||
class NoteBlock(Model):
|
||||
type: Literal["note"]
|
||||
text: str = Field(default="", max_length=MAX_NOTE_CHARS)
|
||||
size: int = Field(default=1, ge=min(receipt.TEXT_SIZES), le=max(receipt.TEXT_SIZES))
|
||||
timestamp: bool = False
|
||||
bold: bool = False
|
||||
center: bool = False
|
||||
choices: list[Annotated[str, Field(max_length=1000)]] = Field(default=[], max_length=500)
|
||||
pick: Literal["sequential", "random"] = "sequential"
|
||||
|
||||
@model_validator(mode="after")
|
||||
def _something(self) -> NoteBlock:
|
||||
self.choices = [c for c in (c.strip() for c in self.choices) if c]
|
||||
if not self.text.strip() and not self.choices:
|
||||
raise ValueError("a note needs text or a list to pick from")
|
||||
return self
|
||||
|
||||
|
||||
class QrBlock(Model):
|
||||
type: Literal["qr"]
|
||||
content: str = Field(min_length=1, max_length=2000)
|
||||
caption: str = Field(default="", max_length=MAX_CAPTION_CHARS)
|
||||
|
||||
|
||||
class ImageBlock(Model):
|
||||
type: Literal["image"]
|
||||
asset_id: str
|
||||
caption: str = Field(default="", max_length=MAX_CAPTION_CHARS)
|
||||
|
||||
|
||||
class RandomImageBlock(Model):
|
||||
type: Literal["random_image"]
|
||||
|
||||
|
||||
class AgendaBlock(Model):
|
||||
type: Literal["agenda"]
|
||||
source_ids: list[str] = Field(min_length=1, max_length=10)
|
||||
start_day: int = Field(default=0, ge=0, le=7) # 0 today, 1 tomorrow
|
||||
days: int = Field(default=1, ge=1, le=7)
|
||||
include_all_day: bool = True
|
||||
title: str = Field(default="", max_length=100)
|
||||
|
||||
|
||||
class HeadlinesBlock(Model):
|
||||
type: Literal["headlines"]
|
||||
source_ids: list[str] = Field(min_length=1, max_length=10)
|
||||
count: int = Field(default=5, ge=1, le=20)
|
||||
only_new: bool = False
|
||||
qr_first: bool = False
|
||||
title: str = Field(default="", max_length=100)
|
||||
|
||||
|
||||
class DividerBlock(Model):
|
||||
type: Literal["divider"]
|
||||
|
||||
|
||||
Block = Annotated[
|
||||
NoteBlock | QrBlock | ImageBlock | RandomImageBlock | AgendaBlock | HeadlinesBlock
|
||||
| DividerBlock,
|
||||
Field(discriminator="type"),
|
||||
]
|
||||
DYNAMIC_BLOCKS = ("agenda", "headlines") # can come up empty
|
||||
|
||||
|
||||
class Options(Model):
|
||||
quiet: Literal["hold", "skip", "ignore"] = "hold"
|
||||
skip_if_empty: bool = False
|
||||
catch_up_minutes: int = Field(default=15, ge=0, le=24 * 60)
|
||||
retries: int = Field(default=3, ge=0, le=10)
|
||||
|
||||
|
||||
class ScheduleSpec(Model):
|
||||
trigger: Trigger
|
||||
blocks: list[Block] = Field(min_length=1, max_length=MAX_BLOCKS)
|
||||
options: Options = Options()
|
||||
|
||||
|
||||
class ScheduleIn(ScheduleSpec):
|
||||
name: str = Field(min_length=1, max_length=100)
|
||||
enabled: bool = True
|
||||
|
||||
|
||||
# --- settings and sources ---
|
||||
|
||||
|
||||
class Location(Model):
|
||||
latitude: float = Field(ge=-90, le=90)
|
||||
longitude: float = Field(ge=-180, le=180)
|
||||
name: str = Field(default="", max_length=100)
|
||||
|
||||
|
||||
class Settings(Model):
|
||||
timezone: str = "Europe/London"
|
||||
location: Location | None = None
|
||||
quiet_start: dt.time | None = None
|
||||
quiet_end: dt.time | None = None
|
||||
daily_cap: int = Field(default=30, ge=0, le=1000) # automatic prints per day; 0 = no cap
|
||||
paused: bool = False
|
||||
paused_until: dt.date | None = None # resumes at the start of this day
|
||||
|
||||
@field_validator("timezone")
|
||||
@classmethod
|
||||
def _zone(cls, value: str) -> str:
|
||||
try:
|
||||
ZoneInfo(value)
|
||||
except (ZoneInfoNotFoundError, ValueError):
|
||||
raise ValueError(f"unknown timezone {value!r}") from None
|
||||
return value
|
||||
|
||||
@model_validator(mode="after")
|
||||
def _quiet_pair(self) -> Settings:
|
||||
if (self.quiet_start is None) != (self.quiet_end is None):
|
||||
raise ValueError("quiet hours need both a start and an end")
|
||||
return self
|
||||
|
||||
@property
|
||||
def tz(self) -> ZoneInfo:
|
||||
return ZoneInfo(self.timezone)
|
||||
|
||||
|
||||
class SourceIn(Model):
|
||||
name: str = Field(min_length=1, max_length=100)
|
||||
kind: Literal["ics", "rss"]
|
||||
url: str = Field(max_length=2000)
|
||||
|
||||
@field_validator("url")
|
||||
@classmethod
|
||||
def _url(cls, value: str) -> str:
|
||||
# Calendar apps hand out webcal:// links for the same https feed.
|
||||
value = value.strip()
|
||||
if value.startswith("webcal://"):
|
||||
value = "https://" + value.removeprefix("webcal://")
|
||||
return http_url(value)
|
||||
Reference in New Issue
Block a user