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 @@
The tags weren't saved.
+No tags yet.
+{% endif %} +{% if can_edit %} + +{% endif %} +{% if library %} +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 @@There are no shelves yet.
+{% endif %} +There are no tags yet. Add tags on a copy's page.
+{% endif %}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 %} + +Edit this {{ shelf.kind | kind_label | lower }}
{% endif %} +{% if copies.items %} +| Work | Edition | +Location | + {% if can_edit %}Actions | {% endif %}
|---|---|---|---|
| {{ label.work_title }} | +{{ label.edition_title or "" }} | +{{ copy.location or "" }} | + {% if can_edit %} ++ + | + {% endif %} +
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 %} +The shelf wasn't saved.
+The copies on it stay in the library.
+ +