Platform v2 step 1.1 (APPS_PLATFORM D-11, §7, D-24). - core/timeutil.py: utcnow, venue_tz (venue.timezone, cached, invalidated on change - no restart), to_venue/venue_date/venue_strftime, parse_api_datetime (offset -> UTC; naive = venue-local; date = venue midnight), business_date_of /business_date_window (rollover hour, default 06:00), LocalClock + is_within, UTCDateTime column type (naive writes raise, reads are aware UTC), iso_z - every model column is UTCDateTime; Pydantic UTCDatetime emits "...Z" - business_days.business_date set at open; revision 0002 adds it (backfilled) and makes sync_events.created_at a UTCDateTime (AUTOINCREMENT restated) - tz.py deleted; system.timezone setting replaced by venue.timezone (validated) + business_day.rollover_hour; manager timezone picker writes venue.timezone - fixes: price-group schedules/time_range used the container's zone (happy hour bug); traffic report bucketed by UTC hour; reports' "date" meant the UTC calendar day, now the business date; reservations stored venue-local naive times (no-show check 2-3 h off) and listed by func.date; schedule week used UTC midnights; fiscal file names used container-local time - seed.py/demo_seed.py create store_manager with role permissions (regression from step 1.0: v1's startup ALTER list used to rename/grant role 'manager') - tzdata dependency; guard tests/guards/test_no_naive_time.py (AST scan); tests/test_timeutil.py covers the §7.3 DST cases and the API checks Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
174 lines
5.8 KiB
Python
174 lines
5.8 KiB
Python
from core.timeutil import utcnow, venue_day_window
|
|
from fastapi import APIRouter, Depends, HTTPException, status, Query
|
|
from sqlalchemy.orm import Session
|
|
from typing import List, Optional
|
|
from datetime import datetime, timezone
|
|
|
|
from database import get_db
|
|
from models.reservation import Reservation
|
|
from models.table import Table
|
|
from schemas.reservation import (
|
|
ReservationCreate, ReservationUpdate, ReservationStatusUpdate, ReservationOut,
|
|
)
|
|
from routers.deps import get_current_user, require_manager
|
|
from models.user import User
|
|
|
|
router = APIRouter()
|
|
|
|
VALID_STATUSES = {"pending", "arrived", "cancelled", "no_show"}
|
|
|
|
|
|
def _enrich(r: Reservation) -> ReservationOut:
|
|
out = ReservationOut.model_validate(r)
|
|
if r.table:
|
|
out.table_label = r.table.label or f"T{r.table.number}"
|
|
if r.created_by:
|
|
out.created_by_name = (
|
|
r.created_by.full_name or r.created_by.nickname or r.created_by.username
|
|
)
|
|
return out
|
|
|
|
|
|
@router.post("/", response_model=ReservationOut, status_code=status.HTTP_201_CREATED)
|
|
def create_reservation(
|
|
body: ReservationCreate,
|
|
db: Session = Depends(get_db),
|
|
user: User = Depends(get_current_user),
|
|
):
|
|
if body.table_id:
|
|
if not db.query(Table).filter(Table.id == body.table_id, Table.is_active == True).first():
|
|
raise HTTPException(status_code=400, detail="Table not found or inactive")
|
|
|
|
r = Reservation(
|
|
guest_name=body.guest_name,
|
|
party_size=body.party_size,
|
|
phone=body.phone,
|
|
email=body.email,
|
|
note=body.note,
|
|
reserved_for=body.reserved_for,
|
|
table_id=body.table_id,
|
|
source=body.source,
|
|
online_customer_id=body.online_customer_id,
|
|
created_by_user_id=user.id,
|
|
status="pending",
|
|
)
|
|
db.add(r)
|
|
db.commit()
|
|
db.refresh(r)
|
|
return _enrich(r)
|
|
|
|
|
|
@router.get("/", response_model=List[ReservationOut])
|
|
def list_reservations(
|
|
tab: Optional[str] = Query(None), # "upcoming" | "history" — if omitted returns all
|
|
date: Optional[str] = Query(None), # ISO date string YYYY-MM-DD to filter by day
|
|
db: Session = Depends(get_db),
|
|
user: User = Depends(get_current_user),
|
|
):
|
|
q = db.query(Reservation)
|
|
|
|
if date:
|
|
try:
|
|
day = datetime.fromisoformat(date).date()
|
|
except ValueError:
|
|
raise HTTPException(status_code=400, detail="Invalid date format")
|
|
# The venue's calendar day, as a UTC window (D-11; 23 h / 25 h on DST days)
|
|
start, end = venue_day_window(day)
|
|
q = q.filter(Reservation.reserved_for >= start, Reservation.reserved_for < end)
|
|
|
|
if tab == "upcoming":
|
|
# pending + no_show (actionable), ordered soonest first
|
|
q = q.filter(Reservation.status.in_(["pending", "no_show"]))
|
|
q = q.order_by(Reservation.reserved_for.asc())
|
|
elif tab == "history":
|
|
# arrived, cancelled, plus no_show/pending that are clearly in the past
|
|
now = utcnow()
|
|
q = q.filter(
|
|
(Reservation.status.in_(["arrived", "cancelled"])) |
|
|
(
|
|
Reservation.status.in_(["no_show", "pending"]) &
|
|
(Reservation.reserved_for < now)
|
|
)
|
|
)
|
|
q = q.order_by(Reservation.reserved_for.desc())
|
|
else:
|
|
q = q.order_by(Reservation.reserved_for.asc())
|
|
|
|
reservations = q.all()
|
|
return [_enrich(r) for r in reservations]
|
|
|
|
|
|
@router.get("/{reservation_id}", response_model=ReservationOut)
|
|
def get_reservation(
|
|
reservation_id: int,
|
|
db: Session = Depends(get_db),
|
|
user: User = Depends(get_current_user),
|
|
):
|
|
r = db.query(Reservation).filter(Reservation.id == reservation_id).first()
|
|
if not r:
|
|
raise HTTPException(status_code=404, detail="Reservation not found")
|
|
return _enrich(r)
|
|
|
|
|
|
@router.patch("/{reservation_id}", response_model=ReservationOut)
|
|
def update_reservation(
|
|
reservation_id: int,
|
|
body: ReservationUpdate,
|
|
db: Session = Depends(get_db),
|
|
user: User = Depends(get_current_user),
|
|
):
|
|
r = db.query(Reservation).filter(Reservation.id == reservation_id).first()
|
|
if not r:
|
|
raise HTTPException(status_code=404, detail="Reservation not found")
|
|
|
|
updates = body.model_dump(exclude_none=True)
|
|
|
|
if "table_id" in updates and updates["table_id"] is not None:
|
|
if not db.query(Table).filter(Table.id == updates["table_id"], Table.is_active == True).first():
|
|
raise HTTPException(status_code=400, detail="Table not found or inactive")
|
|
|
|
if "status" in updates and updates["status"] not in VALID_STATUSES:
|
|
raise HTTPException(status_code=400, detail=f"Invalid status: {updates['status']}")
|
|
|
|
for field, value in updates.items():
|
|
setattr(r, field, value)
|
|
|
|
r.updated_at = utcnow()
|
|
db.commit()
|
|
db.refresh(r)
|
|
return _enrich(r)
|
|
|
|
|
|
@router.patch("/{reservation_id}/status", response_model=ReservationOut)
|
|
def update_reservation_status(
|
|
reservation_id: int,
|
|
body: ReservationStatusUpdate,
|
|
db: Session = Depends(get_db),
|
|
user: User = Depends(get_current_user),
|
|
):
|
|
if body.status not in VALID_STATUSES:
|
|
raise HTTPException(status_code=400, detail=f"Invalid status: {body.status}")
|
|
|
|
r = db.query(Reservation).filter(Reservation.id == reservation_id).first()
|
|
if not r:
|
|
raise HTTPException(status_code=404, detail="Reservation not found")
|
|
|
|
r.status = body.status
|
|
r.updated_at = utcnow()
|
|
db.commit()
|
|
db.refresh(r)
|
|
return _enrich(r)
|
|
|
|
|
|
@router.delete("/{reservation_id}", status_code=status.HTTP_204_NO_CONTENT)
|
|
def delete_reservation(
|
|
reservation_id: int,
|
|
db: Session = Depends(get_db),
|
|
user: User = Depends(require_manager),
|
|
):
|
|
r = db.query(Reservation).filter(Reservation.id == reservation_id).first()
|
|
if not r:
|
|
raise HTTPException(status_code=404, detail="Reservation not found")
|
|
db.delete(r)
|
|
db.commit()
|