import os import secrets import uuid from passlib.context import CryptContext from fastapi import APIRouter, Depends, HTTPException, UploadFile, File, status from sqlalchemy.orm import Session from auth_utils import get_current_admin from database import get_db from models.site import Site from schemas.site import SiteModulesUpdate, SiteCreate, SiteUpdate, SiteOut, SiteCreatedOut, LockRequest router = APIRouter() _pwd = CryptContext(schemes=["bcrypt"], deprecated="auto") HEADER_IMAGE_DIR = "/app/data/site_headers" def _preset_modules(db: Session, name: str | None) -> dict: if not name: return {} from models.plan_preset import PlanPreset preset = db.query(PlanPreset).filter(PlanPreset.name == name).first() if preset is None: raise HTTPException(status_code=400, detail=f"Unknown preset: {name}") return dict(preset.modules or {}) def _validate_modules(modules: dict) -> dict: """Shape check of a module map; the site ignores keys it doesn't know (newer catalogue).""" from services.license_token import normalize_modules from datetime import datetime as _dt if not isinstance(modules, dict): raise HTTPException(status_code=422, detail="modules must be an object") for key, spec in modules.items(): if not isinstance(key, str) or not key or not isinstance(spec or {}, dict): raise HTTPException(status_code=422, detail=f"bad module entry {key!r}") for lk, lv in ((spec or {}).get("limits") or {}).items(): if lv is not None and (not isinstance(lv, int) or lv < 0): raise HTTPException(status_code=422, detail=f"{key}.{lk}: limit must be a whole number >= 0 or null") if (spec or {}).get("exp"): try: _dt.fromisoformat(str(spec["exp"]).replace("Z", "+00:00")) except ValueError: raise HTTPException(status_code=422, detail=f"{key}: exp must be an ISO date-time") return normalize_modules(modules) @router.get("/", response_model=list[SiteOut]) def list_sites(db: Session = Depends(get_db), _=Depends(get_current_admin)): return db.query(Site).all() @router.post("/", response_model=SiteCreatedOut, status_code=status.HTTP_201_CREATED) def create_site(body: SiteCreate, db: Session = Depends(get_db), _=Depends(get_current_admin)): raw_key = secrets.token_urlsafe(32) site = Site( site_id=str(uuid.uuid4()), name=body.name, owner_name=body.owner_name, contact_email=body.contact_email, secret_key_hash=_pwd.hash(raw_key), license_expires_at=body.license_expires_at, modules=_preset_modules(db, body.preset), ) db.add(site) db.commit() db.refresh(site) data = SiteOut.model_validate(site).model_dump() data["secret_key"] = raw_key return SiteCreatedOut(**data) @router.get("/{site_id}", response_model=SiteOut) def get_site(site_id: str, db: Session = Depends(get_db), _=Depends(get_current_admin)): site = db.query(Site).filter(Site.site_id == site_id).first() if not site: raise HTTPException(status_code=404, detail="Site not found") return site @router.put("/{site_id}", response_model=SiteOut) def update_site(site_id: str, body: SiteUpdate, db: Session = Depends(get_db), _=Depends(get_current_admin)): site = db.query(Site).filter(Site.site_id == site_id).first() if not site: raise HTTPException(status_code=404, detail="Site not found") if body.menu_mode is not None and body.menu_mode not in ("order", "view_only"): raise HTTPException(status_code=400, detail="menu_mode must be 'order' or 'view_only'") for field, value in body.model_dump(exclude_none=True).items(): setattr(site, field, value) db.commit() db.refresh(site) return site @router.post("/{site_id}/header-image", response_model=SiteOut) async def upload_header_image(site_id: str, file: UploadFile = File(...), db: Session = Depends(get_db), _=Depends(get_current_admin)): site = db.query(Site).filter(Site.site_id == site_id).first() if not site: raise HTTPException(status_code=404, detail="Site not found") if not file.content_type or not file.content_type.startswith("image/"): raise HTTPException(status_code=400, detail="File must be an image") os.makedirs(HEADER_IMAGE_DIR, exist_ok=True) if site.menu_header_image_url: old_path = os.path.join(HEADER_IMAGE_DIR, os.path.basename(site.menu_header_image_url)) if os.path.exists(old_path): os.remove(old_path) filename = f"{site.site_id}_{uuid.uuid4().hex[:8]}.png" filepath = os.path.join(HEADER_IMAGE_DIR, filename) contents = await file.read() with open(filepath, "wb") as f: f.write(contents) site.menu_header_image_url = f"/static/site_headers/{filename}" db.commit() db.refresh(site) return site @router.delete("/{site_id}/header-image", response_model=SiteOut) def delete_header_image(site_id: str, db: Session = Depends(get_db), _=Depends(get_current_admin)): site = db.query(Site).filter(Site.site_id == site_id).first() if not site: raise HTTPException(status_code=404, detail="Site not found") if site.menu_header_image_url: old_path = os.path.join(HEADER_IMAGE_DIR, os.path.basename(site.menu_header_image_url)) if os.path.exists(old_path): os.remove(old_path) site.menu_header_image_url = None db.commit() db.refresh(site) return site @router.post("/{site_id}/lock", response_model=SiteOut) def lock_site(site_id: str, body: LockRequest, db: Session = Depends(get_db), _=Depends(get_current_admin)): site = db.query(Site).filter(Site.site_id == site_id).first() if not site: raise HTTPException(status_code=404, detail="Site not found") site.is_locked = True site.lock_reason = body.reason db.commit() db.refresh(site) return site @router.post("/{site_id}/unlock", response_model=SiteOut) def unlock_site(site_id: str, db: Session = Depends(get_db), _=Depends(get_current_admin)): site = db.query(Site).filter(Site.site_id == site_id).first() if not site: raise HTTPException(status_code=404, detail="Site not found") site.is_locked = False site.lock_reason = None db.commit() db.refresh(site) return site @router.delete("/{site_id}", status_code=status.HTTP_204_NO_CONTENT) def delete_site(site_id: str, db: Session = Depends(get_db), _=Depends(get_current_admin)): site = db.query(Site).filter(Site.site_id == site_id).first() if not site: raise HTTPException(status_code=404, detail="Site not found") db.delete(site) db.commit() # ── Licensed modules (APPS_PLATFORM D-3, §5.2) ───────────────────────────────── @router.put("/{site_id}/modules", response_model=SiteOut) def set_site_modules(site_id: str, body: SiteModulesUpdate, db: Session = Depends(get_db), _=Depends(get_current_admin)): """Replace the site's module map. The site gets it in its next heartbeat (signed token).""" site = db.query(Site).filter(Site.site_id == site_id).first() if not site: raise HTTPException(status_code=404, detail="Site not found") site.modules = _validate_modules(body.modules) db.commit() db.refresh(site) return site @router.post("/{site_id}/apply-preset/{preset_id}", response_model=SiteOut) def apply_preset(site_id: str, preset_id: int, db: Session = Depends(get_db), _=Depends(get_current_admin)): """Copy a preset's module map into the site (then editable per site).""" from models.plan_preset import PlanPreset site = db.query(Site).filter(Site.site_id == site_id).first() preset = db.get(PlanPreset, preset_id) if not site or not preset: raise HTTPException(status_code=404, detail="Site or preset not found") site.modules = dict(preset.modules or {}) db.commit() db.refresh(site) return site