Files
ImpTune/imptune/api/clients.py
T
kawa 356c2ee690 feat(03-01): implement printer and client CRUD with HTMX/Alpine.js UI
- imptune/api/printers.py: POST /printers (all form fields, checkbox->bool,
  FK resolution), DELETE /printers/{id}, grouped list renderer with LEFT JOIN
- imptune/api/clients.py: POST /clients with duplicate-name handling
- imptune/api/pages.py: GET /printers and GET /clients page routes
- imptune/main.py: register printers + clients routers; close db on shutdown
- imptune/db/database.py: close existing connection before re-init (test isolation)
- templates: printers.html, clients.html, printer_form.html (Alpine.js port
  auto-derivation), printer_list.html (grouped by client), client_list.html
- tests/conftest.py: close test-thread db connection in fixture teardown
- tests/test_printer_crud.py: updated to use list(select().where()) for DB
  queries (avoids Peewee thread-local cursor caching across test boundaries)

Auto-fix [Rule 1 - Bug]: DB test isolation — Peewee thread-local connections
persisted across tests causing stale DB reads; fixed via conftest teardown and
lifespan db.close() on shutdown.
2026-04-10 12:56:09 +02:00

55 lines
1.6 KiB
Python

"""Client CRUD API — POST /clients, GET /clients."""
from __future__ import annotations
from pathlib import Path
from fastapi import APIRouter, Form, Request
from fastapi.responses import HTMLResponse
from fastapi.templating import Jinja2Templates
from peewee import IntegrityError
from imptune.db.models import Client
router = APIRouter(prefix="/clients")
templates = Jinja2Templates(
directory=str(Path(__file__).parent.parent / "templates")
)
def _error_response(message: str, status_code: int = 400) -> HTMLResponse:
"""Return an HTMX-friendly error fragment swapped into #client-list."""
return HTMLResponse(
content=f"<div id='client-list' class='error'><p>{message}</p></div>",
status_code=status_code,
)
def _render_client_list(request: Request) -> HTMLResponse:
"""Render the client list partial for HTMX swap."""
clients = list(Client.select().order_by(Client.name))
return templates.TemplateResponse(
request=request,
name="partials/client_list.html",
context={"clients": clients},
)
@router.post("", response_class=HTMLResponse)
def create_client(request: Request, name: str = Form(...)) -> HTMLResponse:
"""Create a new client.
Accepts form-encoded `name`. Validates non-empty. Returns HTMX partial
with updated client list on success, or error fragment on failure.
"""
name = name.strip()
if not name:
return _error_response("Client name is required.")
try:
Client.create(name=name)
except IntegrityError:
return _error_response(f"Client '{name}' already exists.", status_code=409)
return _render_client_list(request)