From 8677e6e8f4befb88a514dfbd9d63d92447fccd70 Mon Sep 17 00:00:00 2001 From: Natalie Boedecker Date: Mon, 2 Nov 2026 17:52:30 -0500 Subject: [PATCH] feat: add tags and shelves to the web interface Let people tag copies and organize them on shelves from the browser, as thin layers over the existing service functions. - Add a tags form to the copy page, and list a library's tags. - Add pages to create, view, rename, and delete shelves, and to put copies on shelves and take them off. - Add an API operation that lists the shelves holding a copy. Assisted-by: Claude Code Signed-off-by: Natalie Boedecker --- CHANGELOG.md | 2 + openapi/openapi.json | 94 ++++ src/librelibrary/api/v1/libraries.py | 9 + src/librelibrary/app.py | 2 + src/librelibrary/services/libraries.py | 19 + src/librelibrary/ui/copies.py | 123 ++++- src/librelibrary/ui/libraries.py | 10 + src/librelibrary/ui/shelves.py | 248 ++++++++++ src/librelibrary/ui/static/style.css | 7 + src/librelibrary/ui/support.py | 7 + src/librelibrary/ui/templates/copy.html | 42 ++ src/librelibrary/ui/templates/library.html | 13 + src/librelibrary/ui/templates/shelf.html | 40 ++ src/librelibrary/ui/templates/shelf_form.html | 41 ++ src/librelibrary/ui/templating.py | 10 +- tests/test_api.py | 42 ++ tests/test_contract.py | 1 + tests/test_ui_parity.py | 1 + tests/test_ui_shelves.py | 430 ++++++++++++++++++ tests/test_ui_tags.py | 318 +++++++++++++ tests/ui_support.py | 45 ++ 21 files changed, 1496 insertions(+), 8 deletions(-) create mode 100644 src/librelibrary/ui/shelves.py create mode 100644 src/librelibrary/ui/templates/shelf.html create mode 100644 src/librelibrary/ui/templates/shelf_form.html create mode 100644 tests/test_ui_shelves.py create mode 100644 tests/test_ui_tags.py diff --git a/CHANGELOG.md b/CHANGELOG.md index bd8694a..bb79d75 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -24,3 +24,5 @@ The format is based on [Keep a Changelog 1.1.0](https://keepachangelog.com/en/1. - A web interface foundation: browser sign-in and sign-out with server-side cookie sessions, CSRF protection, a searchable, paged list of works, and work pages to view, add, edit, and delete. - Web pages for libraries, copies, and editions: list and open the libraries you belong to, add and change a library and its settings, add copies from an edition, and edit or delete a copy. Each page offers only what your role allows. - Library member lists in the API now include each member's display name. +- Web pages for tags and shelves: set a copy's tags from its page, create, rename, and delete shelves, put copies on shelves and take them off, and see a library's shelves and tags. +- An API operation, `GET /api/v1/copies/{copy_id}/shelves`, that lists the shelves holding a copy. Only members of the copy's library see them. diff --git a/openapi/openapi.json b/openapi/openapi.json index c5aee4b..2c462ad 100644 --- a/openapi/openapi.json +++ b/openapi/openapi.json @@ -4555,6 +4555,100 @@ ] } }, + "/api/v1/copies/{copy_id}/shelves": { + "get": { + "description": "List the shelves that hold a copy. Only members of its library see them.", + "operationId": "copy_shelves_list", + "parameters": [ + { + "in": "path", + "name": "copy_id", + "required": true, + "schema": { + "maximum": 2147483647, + "minimum": 1, + "title": "Copy Id", + "type": "integer" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "items": { + "$ref": "#/components/schemas/ShelfOut" + }, + "title": "Response Copy Shelves List", + "type": "array" + } + } + }, + "description": "Successful Response" + }, + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorOut" + } + } + }, + "description": "Unauthorized" + }, + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorOut" + } + } + }, + "description": "Forbidden" + }, + "404": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorOut" + } + } + }, + "description": "Not Found" + }, + "409": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorOut" + } + } + }, + "description": "Conflict" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + "description": "Validation Error" + } + }, + "security": [ + { + "HTTPBearer": [] + } + ], + "summary": "List Copy Shelves", + "tags": [ + "libraries" + ] + } + }, "/api/v1/copies/{copy_id}/tags": { "get": { "description": "List a copy's tags.", diff --git a/src/librelibrary/api/v1/libraries.py b/src/librelibrary/api/v1/libraries.py index 1ae723d..af91c0c 100644 --- a/src/librelibrary/api/v1/libraries.py +++ b/src/librelibrary/api/v1/libraries.py @@ -206,6 +206,15 @@ def set_copy_tags( return [TagOut.model_validate(tag) for tag in tags] +@router.get("/copies/{copy_id}/shelves", operation_id="copy_shelves_list") +def list_copy_shelves( + copy_id: PathId, session: DbSession, actor: CurrentActor +) -> list[ShelfOut]: + """List the shelves that hold a copy. Only members of its library see them.""" + shelves = libraries.list_copy_shelves(session, actor, copy_id) + return [ShelfOut.model_validate(shelf) for shelf in shelves] + + @router.get("/libraries/{library_id}/tags", operation_id="tags_list") def list_tags( library_id: PathId, diff --git a/src/librelibrary/app.py b/src/librelibrary/app.py index 554c87d..5a4f682 100644 --- a/src/librelibrary/app.py +++ b/src/librelibrary/app.py @@ -28,6 +28,7 @@ from librelibrary.ui import copies as copy_pages from librelibrary.ui import libraries as library_pages from librelibrary.ui import pages, works +from librelibrary.ui import shelves as shelf_pages from librelibrary.ui.deps import LoginRequired from librelibrary.ui.templating import UI_DIRECTORY, templates @@ -164,6 +165,7 @@ async def lifespan(_app: FastAPI) -> AsyncIterator[None]: app.include_router(works.router) app.include_router(library_pages.router) app.include_router(copy_pages.router) + app.include_router(shelf_pages.router) app.mount("/static", StaticFiles(directory=UI_DIRECTORY / "static"), name="static") @app.middleware("http") diff --git a/src/librelibrary/services/libraries.py b/src/librelibrary/services/libraries.py index cee46c3..8a86d11 100644 --- a/src/librelibrary/services/libraries.py +++ b/src/librelibrary/services/libraries.py @@ -302,6 +302,25 @@ def list_copy_tags(session: Session, actor: Actor, copy_id: int) -> list[Tag]: return list(session.scalars(statement)) +@policy_action(Action.COPY_READ) +def list_copy_shelves(session: Session, actor: Actor, copy_id: int) -> list[Shelf]: + """List the shelves that hold a visible copy. + + Shelf names belong to a library's members, so someone who can see the copy + only because it is shared more widely gets an empty list. + """ + copy = _visible_copy(session, actor, copy_id) + if library_role(session, actor, copy.library_id) is None: + return [] + statement = ( + select(Shelf) + .join(ShelfItem, ShelfItem.shelf_id == Shelf.id) + .where(ShelfItem.copy_id == copy_id) + .order_by(Shelf.name) + ) + return list(session.scalars(statement)) + + @policy_action(Action.LIBRARY_EDIT) def set_copy_tags( session: Session, actor: Actor, copy_id: int, names: list[str] diff --git a/src/librelibrary/ui/copies.py b/src/librelibrary/ui/copies.py index b2d8051..3e16f57 100644 --- a/src/librelibrary/ui/copies.py +++ b/src/librelibrary/ui/copies.py @@ -8,7 +8,16 @@ from librelibrary.api.deps import DbSession, PathId from librelibrary.authz.policy import Action, LibraryResource, require -from librelibrary.schemas import CopyIn, CopyOut, CopyPatch, LibraryOut, Page +from librelibrary.schemas import ( + CopyIn, + CopyOut, + CopyPatch, + LibraryOut, + Page, + ShelfOut, + TagNamesIn, + TagOut, +) from librelibrary.services import libraries from librelibrary.ui import ui_route from librelibrary.ui.deps import CsrfChecked, CurrentUser @@ -18,6 +27,7 @@ router = APIRouter() ALL = 200 +MAX_TAGS = 50 _SEE_OTHER = 303 _ID = Annotated[int, Form(ge=1, le=2_147_483_647)] _LABELS = { @@ -188,19 +198,41 @@ def create_copy( # noqa: PLR0913 return RedirectResponse(f"/copies/{copy.id}", status_code=_SEE_OTHER) -@ui_route(router, "GET", "/copies/{copy_id}", api="copies_get") -def copy_detail( - request: Request, copy_id: PathId, session: DbSession, user: CurrentUser +def _detail( # noqa: PLR0913 + request: Request, + session: DbSession, + user: CurrentUser, + copy: CopyOut, + *, + tag_text: str | None = None, + errors: list[str] | None = None, + status_code: int = 200, ) -> Response: - """Show a copy I can see.""" - copy = CopyOut.model_validate(libraries.get_copy(session, user.actor, copy_id)) + copy_id = copy.id label = edition_labels(session, user.actor, [copy.edition_id])[copy.edition_id] role = libraries.my_roles(session, user.actor).get(copy.library_id) + can_edit = allowed(user.actor, Action.LIBRARY_EDIT, LibraryResource(role)) + tags = [ + TagOut.model_validate(tag) + for tag in libraries.list_copy_tags(session, user.actor, copy_id) + ] library = None + shelves: list[ShelfOut] = [] + shelf_choices: list[ShelfOut] = [] if role is not None: library = LibraryOut.model_validate( libraries.get_library(session, user.actor, copy.library_id) ) + shelves = [ + ShelfOut.model_validate(shelf) + for shelf in libraries.list_copy_shelves(session, user.actor, copy_id) + ] + if can_edit: + on = {shelf.id for shelf in shelves} + every = Page[ShelfOut].model_validate( + libraries.list_shelves(session, user.actor, copy.library_id, ALL, 0) + ) + shelf_choices = [shelf for shelf in every.items if shelf.id not in on] return templates.TemplateResponse( request, "copy.html", @@ -210,11 +242,88 @@ def copy_detail( "copy": copy, "label": label, "library": library, - "can_edit": allowed(user.actor, Action.LIBRARY_EDIT, LibraryResource(role)), + "can_edit": can_edit, + "tags": tags, + "tag_text": ( + tag_text + if tag_text is not None + else ", ".join(tag.name for tag in tags) + ), + "shelves": shelves, + "shelf_choices": shelf_choices, + "errors": errors or [], }, + status_code=status_code, ) +@ui_route(router, "GET", "/copies/{copy_id}", api="copies_get") +def copy_detail( + request: Request, copy_id: PathId, session: DbSession, user: CurrentUser +) -> Response: + """Show a copy I can see, with its tags and shelves.""" + copy = CopyOut.model_validate(libraries.get_copy(session, user.actor, copy_id)) + return _detail(request, session, user, copy) + + +def _parse_tags(text: str) -> list[str]: + """Split a comma list into tag names, dropping blanks and repeats.""" + names: list[str] = [] + for part in text.split(","): + name = part.strip() + if name and name not in names: + names.append(name) + return names + + +@ui_route(router, "POST", "/copies/{copy_id}/tags", api="copy_tags_set") +def set_copy_tags( # noqa: PLR0913 + request: Request, + copy_id: PathId, + session: DbSession, + user: CurrentUser, + _csrf: None = CsrfChecked, + tags: FormText = "", +) -> Response: + """Replace a copy's tags with the comma list from the form.""" + names = _parse_tags(tags) + payload = None + errors: list[str] = [] + if len(names) > MAX_TAGS: + errors = [f"Use at most {MAX_TAGS} tags."] + else: + try: + payload = TagNamesIn(names=names) + except ValidationError as error: + errors = problems(error, {"names": "the tags"}) + if payload is None: + copy = CopyOut.model_validate(libraries.get_copy(session, user.actor, copy_id)) + return _detail( + request, + session, + user, + copy, + tag_text=tags, + errors=errors, + status_code=422, + ) + libraries.set_copy_tags(session, user.actor, copy_id, payload.names) + return RedirectResponse(f"/copies/{copy_id}", status_code=_SEE_OTHER) + + +@ui_route(router, "POST", "/copies/{copy_id}/shelves", api="shelf_copies_add") +def add_copy_to_shelf( + copy_id: PathId, + session: DbSession, + user: CurrentUser, + shelf_id: _ID, + _csrf: None = CsrfChecked, +) -> Response: + """Put a copy on one of its library's shelves.""" + libraries.add_to_shelf(session, user.actor, shelf_id, copy_id) + return RedirectResponse(f"/copies/{copy_id}", status_code=_SEE_OTHER) + + @ui_route(router, "GET", "/copies/{copy_id}/edit", api="copies_get") def edit_copy_form( request: Request, copy_id: PathId, session: DbSession, user: CurrentUser diff --git a/src/librelibrary/ui/libraries.py b/src/librelibrary/ui/libraries.py index 284b56c..50a5fe4 100644 --- a/src/librelibrary/ui/libraries.py +++ b/src/librelibrary/ui/libraries.py @@ -15,6 +15,8 @@ LibraryPatch, MemberOut, Page, + ShelfOut, + TagOut, ) from librelibrary.services import libraries from librelibrary.ui import ui_route @@ -142,6 +144,12 @@ def library_detail( ) ) labels = edition_labels(session, user.actor, [c.edition_id for c in copies.items]) + shelves = Page[ShelfOut].model_validate( + libraries.list_shelves(session, user.actor, library_id, ALL, 0) + ) + tags = Page[TagOut].model_validate( + libraries.list_tags(session, user.actor, library_id, ALL, 0) + ) return templates.TemplateResponse( request, "library.html", @@ -153,6 +161,8 @@ def library_detail( "can_manage": allowed(user.actor, Action.LIBRARY_MANAGE, resource), "can_edit": allowed(user.actor, Action.LIBRARY_EDIT, resource), "members": members, + "shelves": shelves, + "tags": tags, "copies": copies, "labels": labels, "page": page, diff --git a/src/librelibrary/ui/shelves.py b/src/librelibrary/ui/shelves.py new file mode 100644 index 0000000..8ad6052 --- /dev/null +++ b/src/librelibrary/ui/shelves.py @@ -0,0 +1,248 @@ +"""Page routes for shelves: create, view, edit, delete, and remove a copy.""" + +from typing import Annotated, Any + +from fastapi import APIRouter, Form, Query, Request +from fastapi.responses import RedirectResponse, Response +from pydantic import ValidationError + +from librelibrary.api.deps import DbSession, PathId +from librelibrary.authz.policy import Action, LibraryResource, require +from librelibrary.schemas import ( + CopyOut, + LibraryOut, + Page, + ShelfIn, + ShelfOut, + ShelfPatch, +) +from librelibrary.services import libraries +from librelibrary.ui import ui_route +from librelibrary.ui.deps import CsrfChecked, CurrentUser +from librelibrary.ui.forms import FormText, blank_to_none, problems +from librelibrary.ui.support import KIND_LABELS, allowed, edition_labels +from librelibrary.ui.templating import templates + +router = APIRouter() +PAGE_SIZE = 25 +_SEE_OTHER = 303 +_LABELS = {"name": "the name", "kind": "the kind"} + + +def _fields(name: str, kind: str) -> dict[str, str | None]: + return {"name": blank_to_none(name), "kind": kind.strip() or "shelf"} + + +def _check(values: dict[str, str | None]) -> tuple[ShelfIn | None, list[str]]: + """Validate the form, and refuse a kind the page doesn't offer.""" + errors: list[str] = [] + payload = None + try: + payload = ShelfIn(**values) # type: ignore[arg-type] + except ValidationError as error: + errors = problems(error, _LABELS) + if values["kind"] not in KIND_LABELS and "Check the kind." not in errors: + errors = [*errors, "Check the kind."] + return (None if errors else payload), errors + + +def _form( # noqa: PLR0913 + request: Request, + user: CurrentUser, + *, + library: LibraryOut, + shelf: ShelfOut | None, + values: dict[str, Any], + errors: list[str], + status_code: int = 200, +) -> Response: + return templates.TemplateResponse( + request, + "shelf_form.html", + { + "user": user, + "nav": "libraries", + "library": library, + "shelf": shelf, + "values": values, + "errors": errors, + }, + status_code=status_code, + ) + + +def _library(session: DbSession, user: CurrentUser, library_id: int) -> LibraryOut: + return LibraryOut.model_validate( + libraries.get_library(session, user.actor, library_id) + ) + + +def _require_edit(session: DbSession, user: CurrentUser, library_id: int) -> None: + role = libraries.my_roles(session, user.actor).get(library_id) + require(user.actor, Action.LIBRARY_EDIT, LibraryResource(role)) + + +@ui_route(router, "GET", "/libraries/{library_id}/shelves/new", api=None) +def new_shelf_form( + request: Request, library_id: PathId, session: DbSession, user: CurrentUser +) -> Response: + """Show the form for a new shelf; editors and owners only.""" + library = _library(session, user, library_id) + _require_edit(session, user, library_id) + return _form( + request, user, library=library, shelf=None, values={"kind": "shelf"}, errors=[] + ) + + +@ui_route(router, "POST", "/libraries/{library_id}/shelves/new", api="shelves_create") +def create_shelf( # noqa: PLR0913 + request: Request, + library_id: PathId, + session: DbSession, + user: CurrentUser, + _csrf: None = CsrfChecked, + name: FormText = "", + kind: FormText = "", +) -> Response: + """Create a shelf from the form.""" + values = _fields(name, kind) + payload, errors = _check(values) + if payload is None: + return _form( + request, + user, + library=_library(session, user, library_id), + shelf=None, + values=values, + errors=errors, + status_code=422, + ) + shelf = libraries.create_shelf(session, user.actor, library_id, payload) + return RedirectResponse(f"/shelves/{shelf.id}", status_code=_SEE_OTHER) + + +@ui_route(router, "GET", "/shelves/{shelf_id}", api="shelves_get") +def shelf_detail( + request: Request, + shelf_id: PathId, + session: DbSession, + user: CurrentUser, + page: Annotated[int, Query(ge=1, le=1_000_000)] = 1, +) -> Response: + """Show a shelf with the copies on it that I can see.""" + shelf = ShelfOut.model_validate(libraries.get_shelf(session, user.actor, shelf_id)) + library = _library(session, user, shelf.library_id) + role = libraries.my_roles(session, user.actor).get(shelf.library_id) + copies = Page[CopyOut].model_validate( + libraries.list_shelf_copies( + session, user.actor, shelf_id, PAGE_SIZE, (page - 1) * PAGE_SIZE + ) + ) + labels = edition_labels(session, user.actor, [c.edition_id for c in copies.items]) + return templates.TemplateResponse( + request, + "shelf.html", + { + "user": user, + "nav": "libraries", + "shelf": shelf, + "library": library, + "can_edit": allowed(user.actor, Action.LIBRARY_EDIT, LibraryResource(role)), + "copies": copies, + "labels": labels, + "page": page, + "last_page": max(1, -(-copies.total // PAGE_SIZE)), + }, + ) + + +@ui_route(router, "GET", "/shelves/{shelf_id}/edit", api="shelves_get") +def edit_shelf_form( + request: Request, shelf_id: PathId, session: DbSession, user: CurrentUser +) -> Response: + """Show the form to change a shelf; editors and owners only.""" + shelf = ShelfOut.model_validate(libraries.get_shelf(session, user.actor, shelf_id)) + _require_edit(session, user, shelf.library_id) + return _form( + request, + user, + library=_library(session, user, shelf.library_id), + shelf=shelf, + values={"name": shelf.name, "kind": shelf.kind}, + errors=[], + ) + + +@ui_route(router, "POST", "/shelves/{shelf_id}/edit", api="shelves_update") +def update_shelf( # noqa: PLR0913 + request: Request, + shelf_id: PathId, + session: DbSession, + user: CurrentUser, + _csrf: None = CsrfChecked, + name: FormText = "", + kind: FormText = "", +) -> Response: + """Change a shelf from the form.""" + values = _fields(name, kind) + payload, errors = _check(values) + if payload is None: + shelf = ShelfOut.model_validate( + libraries.get_shelf(session, user.actor, shelf_id) + ) + return _form( + request, + user, + library=_library(session, user, shelf.library_id), + shelf=shelf, + values=values, + errors=errors, + status_code=422, + ) + libraries.update_shelf( + session, user.actor, shelf_id, ShelfPatch(**payload.model_dump()) + ) + return RedirectResponse(f"/shelves/{shelf_id}", status_code=_SEE_OTHER) + + +@ui_route(router, "POST", "/shelves/{shelf_id}/delete", api="shelves_delete") +def delete_shelf( # noqa: PLR0913 + request: Request, + shelf_id: PathId, + session: DbSession, + user: CurrentUser, + _csrf: None = CsrfChecked, + confirm: Annotated[str, Form(max_length=10)] = "", +) -> Response: + """Delete a shelf, once the box is ticked. Its copies stay in the library.""" + shelf = ShelfOut.model_validate(libraries.get_shelf(session, user.actor, shelf_id)) + if confirm != "yes": + return _form( + request, + user, + library=_library(session, user, shelf.library_id), + shelf=shelf, + values={"name": shelf.name, "kind": shelf.kind}, + errors=["Tick the box to confirm the delete."], + status_code=422, + ) + libraries.delete_shelf(session, user.actor, shelf_id) + return RedirectResponse(f"/libraries/{shelf.library_id}", status_code=_SEE_OTHER) + + +@ui_route( + router, + "POST", + "/shelves/{shelf_id}/copies/{copy_id}/remove", + api="shelf_copies_remove", +) +def remove_copy_from_shelf( + shelf_id: PathId, + copy_id: PathId, + session: DbSession, + user: CurrentUser, + _csrf: None = CsrfChecked, +) -> Response: + """Take a copy off a shelf. The copy stays in the library.""" + libraries.remove_from_shelf(session, user.actor, shelf_id, copy_id) + return RedirectResponse(f"/shelves/{shelf_id}", status_code=_SEE_OTHER) diff --git a/src/librelibrary/ui/static/style.css b/src/librelibrary/ui/static/style.css index 95a0372..a683675 100644 --- a/src/librelibrary/ui/static/style.css +++ b/src/librelibrary/ui/static/style.css @@ -140,3 +140,10 @@ select { color: var(--fg); } ul.hint { padding-left: 1.25rem; } + +ul.tags { display: flex; flex-wrap: wrap; gap: 0.5rem; padding: 0; list-style: none; } +ul.tags li { + padding: 0.125rem 0.625rem; + border: 1px solid var(--border); + border-radius: 999px; +} diff --git a/src/librelibrary/ui/support.py b/src/librelibrary/ui/support.py index 68e7029..9db5ffb 100644 --- a/src/librelibrary/ui/support.py +++ b/src/librelibrary/ui/support.py @@ -23,6 +23,8 @@ ("server", "Server", "Everyone signed in to this server."), ] PRIVACY_LABELS = {value: label for value, label, _hint in PRIVACY_CHOICES} +KIND_CHOICES = [("shelf", "Shelf"), ("collection", "Collection")] +KIND_LABELS = dict(KIND_CHOICES) def allowed(actor: Actor, action: Action, resource: Resource | None = None) -> bool: @@ -42,6 +44,11 @@ def privacy_label(value: str) -> str: return PRIVACY_LABELS.get(value, value) +def kind_label(value: str) -> str: + """Return the name of a shelf kind.""" + return KIND_LABELS.get(value, value) + + def money(value: object) -> str: """Show a price with two decimal places.""" return "" if value is None else f"{value:.2f}" diff --git a/src/librelibrary/ui/templates/copy.html b/src/librelibrary/ui/templates/copy.html index d21d9b9..f93fe1a 100644 --- a/src/librelibrary/ui/templates/copy.html +++ b/src/librelibrary/ui/templates/copy.html @@ -17,4 +17,46 @@

{{ label.work_title }}

{% if copy.price is not none %}
Price
{{ copy.price | money }}{% if copy.currency %} {{ copy.currency }}{% endif %}
{% endif %} {% if can_edit %}

Edit this copy

{% endif %} +

Tags

+{% if errors %} + +{% endif %} +{% if tags %} + +{% else %} +

No tags yet.

+{% endif %} +{% if can_edit %} +
+ + + +

Separate tags with commas. Saving replaces this copy's tags.

+ +
+{% endif %} +{% if library %} +

Shelves

+{% if shelves %} + +{% else %} +

This copy isn't on a shelf.

+{% endif %} +{% if can_edit and shelf_choices %} +
+ + + + +
+{% elif can_edit %} +

Add a shelf to organize this library's copies.

+{% endif %} +{% endif %} {% endblock %} diff --git a/src/librelibrary/ui/templates/library.html b/src/librelibrary/ui/templates/library.html index ee47a67..56998bd 100644 --- a/src/librelibrary/ui/templates/library.html +++ b/src/librelibrary/ui/templates/library.html @@ -19,6 +19,19 @@

Members

{% endfor %} +

Shelves

+{% if can_edit %}

Add a shelf

{% endif %} +{% if shelves.items %} + +{% else %} +

There are no shelves yet.

+{% endif %} +

Tags

+{% if tags.items %} + +{% else %} +

There are no tags yet. Add tags on a copy's page.

+{% endif %}

Copies

{% if can_edit %}

To add a copy, find the work, then choose “Add a copy” on one of its editions.

diff --git a/src/librelibrary/ui/templates/shelf.html b/src/librelibrary/ui/templates/shelf.html new file mode 100644 index 0000000..0a2424c --- /dev/null +++ b/src/librelibrary/ui/templates/shelf.html @@ -0,0 +1,40 @@ +{% extends "base.html" %} +{% from "_fields.html" import pager %} +{% block title %}{{ shelf.name }}{% endblock %} +{% block content %} +

← {{ library.name }}

+

{{ shelf.name }}

+ +{% if can_edit %}

Edit this {{ shelf.kind | kind_label | lower }}

{% endif %} +{% if copies.items %} + + + + + + {% if can_edit %}{% endif %} + + + {% for copy in copies.items %} + {% set label = labels[copy.edition_id] %} + + + + + {% if can_edit %} + + {% endif %} + + {% endfor %} + +
Copies on this {{ shelf.kind | kind_label | lower }}, page {{ page }} of {{ last_page }}
WorkEditionLocationActions
{{ label.work_title }}{{ label.edition_title or "" }}{{ copy.location or "" }} +
+ + +
+
+{{ pager("/shelves/%d" % shelf.id, page, last_page) }} +{% else %} +

There is nothing on this {{ shelf.kind | kind_label | lower }} that you can see yet.{% if can_edit %} Open a copy and choose “Add to shelf”.{% endif %}

+{% endif %} +{% endblock %} diff --git a/src/librelibrary/ui/templates/shelf_form.html b/src/librelibrary/ui/templates/shelf_form.html new file mode 100644 index 0000000..e47e6e9 --- /dev/null +++ b/src/librelibrary/ui/templates/shelf_form.html @@ -0,0 +1,41 @@ +{% extends "base.html" %} +{% set heading = "Edit shelf" if shelf else "Add a shelf" %} +{% block title %}{{ heading }}{% endblock %} +{% block content %} +

{{ heading }}

+

in {{ library.name }}

+{% if errors %} + +{% endif %} +
+ + + + + +
+ + Cancel +
+
+{% if shelf %} +
+

Delete this {{ shelf.kind | kind_label | lower }}

+

The copies on it stay in the library.

+
+ + + +
+
+{% endif %} +{% endblock %} diff --git a/src/librelibrary/ui/templating.py b/src/librelibrary/ui/templating.py index a6ca676..f1c9007 100644 --- a/src/librelibrary/ui/templating.py +++ b/src/librelibrary/ui/templating.py @@ -4,7 +4,13 @@ from fastapi.templating import Jinja2Templates -from librelibrary.ui.support import PRIVACY_CHOICES, money, privacy_label +from librelibrary.ui.support import ( + KIND_CHOICES, + PRIVACY_CHOICES, + kind_label, + money, + privacy_label, +) UI_DIRECTORY = Path(__file__).parent @@ -12,4 +18,6 @@ templates = Jinja2Templates(directory=UI_DIRECTORY / "templates") templates.env.filters["privacy_label"] = privacy_label templates.env.filters["money"] = money +templates.env.filters["kind_label"] = kind_label +templates.env.globals["KIND_CHOICES"] = KIND_CHOICES templates.env.globals["PRIVACY_CHOICES"] = PRIVACY_CHOICES diff --git a/tests/test_api.py b/tests/test_api.py index d1fa171..bfd0c4e 100644 --- a/tests/test_api.py +++ b/tests/test_api.py @@ -928,6 +928,48 @@ def test_an_editor_who_cannot_see_a_copy_cannot_probe_a_shelf_for_it( assert api.call(owner, "GET", f"/shelves/{shelf['id']}/copies")["total"] == 1 +def test_a_copy_lists_the_shelves_it_is_on(api: Api, owner: Account) -> None: + """Members can ask which shelves hold a copy.""" + library = make_library(api, owner) + copy = make_copy(api, owner, library) + first = api.call(owner, "POST", f"/libraries/{library}/shelves", {"name": "B"}, 201) + second = api.call( + owner, "POST", f"/libraries/{library}/shelves", {"name": "A"}, 201 + ) + api.call(owner, "POST", f"/libraries/{library}/shelves", {"name": "C"}, 201) + for shelf in (first, second): + api.call(owner, "PUT", f"/shelves/{shelf['id']}/copies/{copy}", expect=204) + + shelves = api.call(owner, "GET", f"/copies/{copy}/shelves") + + assert [shelf["name"] for shelf in shelves] == ["A", "B"] + + +def test_a_non_member_sees_no_shelves_of_a_server_wide_copy( + api: Api, owner: Account, make_account: MakeAccount +) -> None: + """Shelf names belong to the library's members.""" + stranger = make_account() + library = make_library(api, owner) + copy = make_copy(api, owner, library, "server") + shelf = api.call(owner, "POST", f"/libraries/{library}/shelves", {"name": "S"}, 201) + api.call(owner, "PUT", f"/shelves/{shelf['id']}/copies/{copy}", expect=204) + + assert api.call(stranger, "GET", f"/copies/{copy}")["id"] == copy + assert api.call(stranger, "GET", f"/copies/{copy}/shelves") == [] + + +def test_a_hidden_copys_shelves_are_a_404( + api: Api, owner: Account, make_account: MakeAccount +) -> None: + """A personal copy looks like it doesn't exist.""" + stranger = make_account() + library = make_library(api, owner) + copy = make_copy(api, owner, library) + + api.call(stranger, "GET", f"/copies/{copy}/shelves", expect=404) + + def test_copy_tags_replace_and_stay_in_their_library(api: Api, owner: Account) -> None: """Tags are per library, and a set replaces the old one.""" library = make_library(api, owner) diff --git a/tests/test_contract.py b/tests/test_contract.py index 4ee3f2d..a646d2c 100644 --- a/tests/test_contract.py +++ b/tests/test_contract.py @@ -76,6 +76,7 @@ "tags_list": ("GET", "/libraries/1/tags", None), "tags_create": ("POST", "/libraries/1/tags", {"name": "fiction"}), "tags_delete": ("DELETE", "/tags/1", None), + "copy_shelves_list": ("GET", "/copies/1/shelves", None), "shelves_list": ("GET", "/libraries/1/shelves", None), "shelves_create": ("POST", "/libraries/1/shelves", {"name": "Top"}), "shelves_get": ("GET", "/shelves/1", None), diff --git a/tests/test_ui_parity.py b/tests/test_ui_parity.py index 2baa71b..61de96a 100644 --- a/tests/test_ui_parity.py +++ b/tests/test_ui_parity.py @@ -31,6 +31,7 @@ "new_edition_form", "new_library_form", "new_copy_form", + "new_shelf_form", } SERVICE_MODULES = { module.name for module in pkgutil.iter_modules(librelibrary.services.__path__) diff --git a/tests/test_ui_shelves.py b/tests/test_ui_shelves.py new file mode 100644 index 0000000..e49ffe4 --- /dev/null +++ b/tests/test_ui_shelves.py @@ -0,0 +1,430 @@ +"""Test the shelf pages: create, view, edit, delete, and remove a copy.""" + +import pytest +from fastapi import FastAPI +from sqlalchemy import select +from sqlalchemy.orm import Session + +from librelibrary.models import Copy, Library, Shelf, ShelfItem + +from .ui_support import Scene, add_copy, add_shelf, new_browser, put_on_shelf + + +def routes(scene: Scene, shelf: int) -> dict[str, str]: + """Name each shelf page's path for a scene.""" + return { + "new": f"/libraries/{scene.library_id}/shelves/new", + "detail": f"/shelves/{shelf}", + "edit": f"/shelves/{shelf}/edit", + "delete": f"/shelves/{shelf}/delete", + "remove": f"/shelves/{shelf}/copies/{scene.copy_id}/remove", + "tags": f"/copies/{scene.copy_id}/tags", + "to_shelf": f"/copies/{scene.copy_id}/shelves", + } + + +@pytest.fixture +def shelf(scene: Scene, session: Session) -> int: + """Give a test an empty shelf in the scene's library.""" + return add_shelf(session, scene.library_id) + + +@pytest.mark.parametrize("name", ["new", "detail", "edit"]) +def test_pages_need_a_session( + app: FastAPI, scene: Scene, shelf: int, name: str +) -> None: + """A visitor with no session is sent to sign in.""" + visitor = new_browser(app) + + response = visitor.get(routes(scene, shelf)[name]) + + assert response.status_code == 303 + assert response.headers["location"] == "/login" + + +@pytest.mark.parametrize( + "name", ["new", "edit", "delete", "remove", "tags", "to_shelf"] +) +def test_forms_need_a_session( + app: FastAPI, scene: Scene, shelf: int, name: str +) -> None: + """A form from a visitor with no session is sent to sign in.""" + visitor = new_browser(app) + + response = visitor.post(routes(scene, shelf)[name], data={"name": "Forged"}) + + assert response.status_code == 303 + assert response.headers["location"] == "/login" + + +@pytest.mark.parametrize( + "name", ["new", "edit", "delete", "remove", "tags", "to_shelf"] +) +def test_forms_need_the_session_token(scene: Scene, shelf: int, name: str) -> None: + """A cross-site form is refused, whatever the page.""" + response = scene.owner.browser.post( + routes(scene, shelf)[name], data={"name": "Forged"} + ) + + assert response.status_code == 403 + + +@pytest.mark.parametrize( + ("who", "status"), [("owner", 200), ("editor", 200), ("viewer", 403)] +) +def test_the_new_shelf_form_is_for_editors(scene: Scene, who: str, status: int) -> None: + """The form needs the editor role, and the server enforces it.""" + person = getattr(scene, who) + + response = person.browser.get(f"/libraries/{scene.library_id}/shelves/new") + + assert response.status_code == status + + +def test_the_new_shelf_form_hides_the_library_from_outsiders(scene: Scene) -> None: + """An outsider gets the answer for a library that isn't there.""" + real = scene.stranger.browser.get(f"/libraries/{scene.library_id}/shelves/new") + missing = scene.stranger.browser.get("/libraries/99999/shelves/new") + + assert real.status_code == missing.status_code == 404 + assert real.text == missing.text + + +def test_an_editor_creates_a_shelf(scene: Scene, session: Session) -> None: + """A valid form creates the shelf with a trimmed name.""" + response = scene.editor.browser.post( + f"/libraries/{scene.library_id}/shelves/new", + data={ + "csrf_token": scene.editor.csrf, + "name": " Sci-fi ", + "kind": "collection", + }, + ) + + created = session.scalars(select(Shelf).where(Shelf.name == "Sci-fi")).one() + assert response.status_code == 303 + assert response.headers["location"] == f"/shelves/{created.id}" + assert created.kind == "collection" + assert created.library_id == scene.library_id + + +def test_a_blank_kind_means_shelf(scene: Scene, session: Session) -> None: + """The kind defaults to a plain shelf.""" + scene.owner.browser.post( + f"/libraries/{scene.library_id}/shelves/new", + data={"csrf_token": scene.owner.csrf, "name": "Plain"}, + ) + + created = session.scalars(select(Shelf).where(Shelf.name == "Plain")).one() + assert created.kind == "shelf" + + +@pytest.mark.parametrize( + ("data", "message"), + [ + ({"name": " "}, "Check the name."), + ({"name": "x" * 201}, "Check the name."), + ({"name": "Ok", "kind": "bookcase"}, "Check the kind."), + ], +) +def test_a_bad_shelf_form_explains_and_creates_nothing( + scene: Scene, session: Session, data: dict[str, str], message: str +) -> None: + """The form is shown again with a reason.""" + response = scene.owner.browser.post( + f"/libraries/{scene.library_id}/shelves/new", + data={"csrf_token": scene.owner.csrf, **data}, + ) + + assert response.status_code == 422 + assert message in response.text + assert session.scalars(select(Shelf)).all() == [] + + +def test_a_viewer_cannot_create_a_shelf(scene: Scene, session: Session) -> None: + """The server refuses what the form never offered.""" + response = scene.viewer.browser.post( + f"/libraries/{scene.library_id}/shelves/new", + data={"csrf_token": scene.viewer.csrf, "name": "Sneaky"}, + ) + + assert response.status_code == 403 + assert session.scalars(select(Shelf)).all() == [] + + +def test_a_stranger_cannot_create_a_shelf(scene: Scene, session: Session) -> None: + """An outsider is told the library doesn't exist.""" + response = scene.stranger.browser.post( + f"/libraries/{scene.library_id}/shelves/new", + data={"csrf_token": scene.stranger.csrf, "name": "Sneaky"}, + ) + + assert response.status_code == 404 + assert session.scalars(select(Shelf)).all() == [] + + +def test_a_shelf_lists_only_copies_the_reader_may_see( + scene: Scene, session: Session, shelf: int +) -> None: + """A shelf follows each copy's sharing level.""" + shared = add_copy(session, scene, "library", "Spare room") + put_on_shelf(session, shelf, scene.copy_id) + put_on_shelf(session, shelf, shared) + + owner_page = scene.owner.browser.get(f"/shelves/{shelf}").text + viewer_page = scene.viewer.browser.get(f"/shelves/{shelf}").text + + assert "Hall shelf" in owner_page + assert "Spare room" in owner_page + assert "Hall shelf" not in viewer_page + assert "Spare room" in viewer_page + + +def test_a_shelf_page_shows_its_name_and_kind(scene: Scene, session: Session) -> None: + """The page names the shelf, its kind, and its library.""" + collection = add_shelf(session, scene.library_id, "Reread soon", "collection") + + page = scene.viewer.browser.get(f"/shelves/{collection}").text + + assert "Reread soon" in page + assert "Collection" in page + assert f'href="/libraries/{scene.library_id}"' in page + + +def test_an_empty_shelf_says_so(scene: Scene, shelf: int) -> None: + """The page explains what to do.""" + page = scene.owner.browser.get(f"/shelves/{shelf}").text + + assert "nothing on this shelf" in page + + +def test_a_stranger_gets_the_same_page_for_a_shelf_as_for_a_missing_one( + scene: Scene, shelf: int +) -> None: + """An outsider can't tell a real shelf from one that doesn't exist.""" + real = scene.stranger.browser.get(f"/shelves/{shelf}") + missing = scene.stranger.browser.get("/shelves/99999") + + assert real.status_code == missing.status_code == 404 + assert real.text == missing.text + + +def test_a_shelf_name_is_escaped(scene: Scene, session: Session) -> None: + """Typed text can't add markup.""" + tricky = add_shelf(session, scene.library_id, "") + + page = scene.owner.browser.get(f"/shelves/{tricky}").text + + assert "