Metadata-Version: 2.4
Name: fastpluggy-crud-tools
Version: 1.0.3
Summary: CRUD Tools plugin for Fastpluggy
Author: FastPluggy Team
License-Expression: MIT
Requires-Python: >=3.11
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: FastPluggy>=0.4.115
Requires-Dist: jinja2
Requires-Dist: SQLAlchemy>=2.0.35
Requires-Dist: WTForms>=3.3
Provides-Extra: tests
Requires-Dist: pytest>=7.0; extra == "tests"
Requires-Dist: pytest-cov>=4.0; extra == "tests"
Requires-Dist: pytest-asyncio>=0.23; extra == "tests"
Provides-Extra: dev
Requires-Dist: fastpluggy-crud-tools[tests]; extra == "dev"
Provides-Extra: e2e
Requires-Dist: fastpluggy-cli; extra == "e2e"
Dynamic: license-file

# CRUD Tools

![CRUD Tools](https://img.shields.io/badge/FastPluggy-CRUD%20Tools-blue)
[![Release](https://gitlab.ggcorp.fr/open/fastpluggy/plugins/crud_tools/-/badges/release.svg)](https://gitlab.ggcorp.fr/open/fastpluggy/plugins/crud_tools/-/releases)
[![Pipeline Status](https://gitlab.ggcorp.fr/open/fastpluggy/plugins/crud_tools/badges/main/pipeline.svg?key_text=CI)](https://gitlab.ggcorp.fr/open/fastpluggy/plugins/crud_tools/-/pipelines?ignore_skipped=true)
[![Coverage](https://gitlab.ggcorp.fr/open/fastpluggy/plugins/crud_tools/badges/main/coverage.svg)](https://gitlab.ggcorp.fr/open/fastpluggy/plugins/crud_tools/-/pipelines)

List, view, create, edit and delete the rows of your SQLAlchemy models, from pages generated out of
the models themselves. One line gives a working back office for a model; a few declarations tune it;
a few methods carry its business rules. The same pages also mount inside your own plugin.

```bash
pip install fastpluggy-crud-tools
```

## Quick start

Register a model where it is defined (or anywhere imported at start-up). Nothing else is needed:
no load order, no hook.

```python
# readme-example: executed by tests/test_readme.py
import enum
from datetime import datetime

from sqlalchemy import ForeignKey, String, Text, func
from sqlalchemy.orm import Mapped, mapped_column, relationship

from fastpluggy.core.database import Base
from fastpluggy_plugin.crud_tools import crud


class Status(enum.Enum):
    draft = "Draft"
    published = "Published"


class Writer(Base):
    __tablename__ = "readme_writer"
    name: Mapped[str] = mapped_column(String(80))

    def __str__(self):  # how a writer is named in lists, links and selects
        return self.name


class Story(Base):
    __tablename__ = "readme_story"
    title: Mapped[str] = mapped_column(String(120))
    body: Mapped[str | None] = mapped_column(Text)
    status: Mapped[Status] = mapped_column(default=Status.draft)
    slug: Mapped[str | None] = mapped_column(String(120))
    writer_id: Mapped[int | None] = mapped_column(ForeignKey("readme_writer.id"))
    writer: Mapped[Writer | None] = relationship()
    published_at: Mapped[datetime | None] = mapped_column(server_default=func.now())


crud.register(Writer)  # level 0: every default


@crud.register  # level 1: declare what differs from the defaults
class StoryAdmin(crud.ModelAdmin[Story]):
    label = "Stories"
    item_label = "Story"

    fields = [
        crud.Field(Story.body, label="Text", help="Markdown is fine."),
        crud.Field(Story.writer, display="name"),
    ]
    list_view = crud.ListView(
        columns=[Story.title, "writer.name", Story.status,
                 crud.Column("words", label="Words", value=lambda s: len((s.body or "").split()))],
        search=[Story.title, Story.body, "writer.name"],
        filters=[Story.status, Story.writer, Story.published_at],
        ordering=[Story.published_at.desc()],
        page_size=25,
    )
    form_view = crud.FormView(
        sections=[
            crud.Section("Content", [Story.title, Story.body]),
            crud.Section("Publishing", [Story.status, Story.writer, Story.slug], columns=2),
        ],
        readonly=[Story.slug],
    )
    actions = crud.ACTIONS - {"delete"}

    # level 2: the rules, as methods that receive the request
    def query(self, request, stmt):
        return stmt  # e.g. stmt.where(Story.tenant_id == request.state.tenant_id)

    def validate(self, request, data, obj):
        if data["status"] == Status.published and not data["body"]:
            return {"body": "A published story needs a text."}
        return {}

    def before_save(self, request, obj, db, *, created):
        obj.slug = obj.title.lower().replace(" ", "-")
```

The back office (sidebar entry **CRUD**) now lists *Writer* and *Stories*, each with a list (search,
filters, sort by column header; the first column links to the row), a detail page, and create, edit
and delete forms.

## What you get for free

Every setting is optional: a field that no setting names gets the defaults of its column. The
*Configuration* page of each admin (`/inspect/<slug>`, from the Models page) shows what it resolved to.

| Column | List | Search / filter | Form | Detail and list display |
|---|---|---|---|---|
| Numbered primary key | shown | | not typed in | shown |
| Other primary key (`String`, `Uuid`…) | shown | | typed in on create, read-only after | |
| `String(n)` | shown | searched | text box, at most `n` characters | cut at 80 characters, full text on hover |
| `Text`, `JSON` | not shown | | text area (JSON checked) | as typed |
| `Integer`, `Numeric`, `Float` | shown | min / max (when named in `filters`) | number box | |
| `Boolean` | shown | Any / Yes / No | check box | Yes / No badge |
| `Date`, `DateTime`, `Time` | shown | from / to (days) | date / date-time / time picker | `2026-01-31 14:05` |
| `Enum` | shown | select of the members | select of the members | badge with the member's value |
| Foreign key | the related row's title | select of the related rows (a search box past 200) | select of the related rows (a search box past 200) | the related row's title, linked to it |
| Many-to-many relationship | not shown | | multiple select (a search box past 200) | the related rows' titles, linked |
| `LargeBinary` | not shown | | not in the form | not shown |
| Set by the database: `created_at`, `updated_at`, `onupdate=`, a date with `server_default=` | shown | from / to | not in the form (read-only when a section names it) | shown |
| Sensitive name: `password`, `secret`, `token`, `api_key`, `…_hash` | **never shown** | **never** | **never in a form** | **never shown** |

By default the list searches its text columns and offers filters for its yes/no, choice, related-row
and date columns; every plain column of the list sorts by a click on its header. Rows are ticked for
bulk actions, and *Export CSV* downloads what the list shows.

A field is required when its column is `NOT NULL` with no default. Labels come from the names
(`published_at` → *Published at*; a foreign key `writer_id` → *Writer*). A row's title is `str(row)`
when the model defines `__str__`, else *Story #12*. Column `doc=` / `comment=` becomes the help text.
A foreign key needs no `relationship()`: without one, its related rows are read by key (one query
per distinct row on the page); declare the relationship to load them with the page in one query.

## Configuring an admin

`class XAdmin(crud.ModelAdmin[X])`, decorated with `@crud.register`. Fields are model attributes
(`Story.title`) or names (`"title"`); a many-to-one relationship (`Story.writer`) means its foreign
key. Every mistake (unknown field, a hidden field in a section, a slug used twice, an unknown action…)
raises `crud.ConfigError` at import time, naming the admin and the field.

| Attribute | Default | Meaning |
|---|---|---|
| `label`, `item_label` | the class name in words | page titles (*Stories*) and one row (*New story*) |
| `slug` | the class name in lower case | URL segment; two admins cannot share one |
| `fields` | `[]` | `crud.Field(ref, label, help, widget, choices, display, format, hidden, readonly, validators)`: one field, on every screen |
| `list_view` | every listable field | `crud.ListView(columns, exclude, search, filters, ordering, page_size)` |
| `form_view` | every editable field | `crud.FormView(sections \| fields, exclude, readonly)` |
| `detail_view` | the form's sections, then the rest, then the related rows | `crud.DetailView(sections \| fields, exclude, related)` |
| `actions` | `crud.ACTIONS` | the built-in actions allowed: `list`, `view`, `create`, `edit`, `delete`, `export` |
| `extra_actions` | `[]` | `crud.Action(name, label, handler, on="row" \| "page" \| "bulk", confirm=None)` |

- `crud.Field(widget=...)`: `text`, `textarea`, `password`, `number`, `checkbox`, `select`, `date`,
  `datetime`. `choices=[(value, label), …]` makes a select. `display="name"` names a foreign key's
  related row by that attribute. `format=callable` turns a value into the text shown; returning
  `Markup('<span class="badge">{}</span>').format(value)` shows HTML, the value still escaped (the CSV
  export keeps its text).
  `hidden=False` shows a field the inference hides as sensitive.
- `crud.ListView(columns=[...])` takes fields, paths through to-one relationships (`"writer.name"`)
  and computed columns (`crud.Column("words", label="Words", value=lambda row: ...)`).
  `search` and `filters` take fields (`search` also paths such as `"writer.name"`); `[]` turns them
  off. `filters` are the controls of the panel; the list URL can filter any shown field. `ordering` takes attributes, expressions (`Story.title.desc()`) or names (`"-published_at"`);
  default: newest primary key first.
- `crud.Section(title, fields, columns=1, collapsed=False, help=None)` groups fields on the form and
  the detail page; a collapsed section opens when one of its fields is wrong.
- `crud.DetailView(related=[Writer.stories])` lists one-to-many relationships on the detail page, as
  links to the related rows' list (filtered on this row) with their count; by default every one-to-many
  relationship whose model is registered, `[]` for none. From that list, *New story* starts with the
  writer filled in.
- Custom actions are POST routes: `on="row"` calls `handler(request, obj, db)` (a button on each row
  and on the detail page), `on="page"` calls `handler(request, db)` (a button above the list),
  `on="bulk"` calls `handler(request, rows, db)` (a button of the bulk bar, for the ticked rows;
  `{n}` in `confirm` is their number). The transaction is committed after the handler; a returned
  response is sent as is.

## Rules: methods with the request

Override what you need on the admin; each one runs on every page and route it concerns.

| Method | Runs | Default |
|---|---|---|
| `can(request, action, obj=None) -> bool` | before every button is shown and on every route (`obj` is set for a row) | the action is in `actions` / `extra_actions` and not in the `disabled_actions` setting |
| `query(request, stmt) -> stmt` | on every read: list, detail, edit, delete, row and bulk actions, export, related selects | all rows |
| `initial(request) -> dict` | prefills the create form (query parameters naming a field prefill it too) | `{}` |
| `validate(request, data, obj) -> {field: message}` | after the field checks; messages show under the fields | `{}` |
| `before_save(request, obj, db, *, created)` | in the transaction, values set, before the flush | nothing |
| `after_save(request, obj, db, *, created)` | in the transaction, after the flush (`obj.id` is set) | nothing |
| `before_delete(request, obj, db)` | in the transaction, before the delete | nothing |
| `title(obj) -> str` | names a row | `str(obj)` or *Story #12* |

A save or a delete is one transaction: raise `crud.Refused("message")` in a hook to roll it back and
show the message; the form keeps what was typed.

## Bulk actions and export

- Ticking rows shows the bulk bar: *Delete* (when `can(request, "delete")`) and the `on="bulk"`
  actions, each confirmed with the number of rows. Ticking the whole page offers *Select all N*: the
  action then runs on every row the list's search and filters match, at most 1 000 at a time.
- The rows are read through `query()`; each one is checked with `can(request, action, row)`, and the
  refused ones are left out and counted. A delete runs `before_delete` per row; everything is one
  transaction, so one `crud.Refused` cancels the lot.
- *Export CSV* streams every row the list shows (search, filters, sort; all pages) with the list's
  columns, in UTF-8 for spreadsheets. A cell starting with `=`, `+`, `-` or `@` gets a leading `'`,
  so a spreadsheet shows it instead of running it. `actions = crud.ACTIONS - {"export"}` removes it.

## Forms

- *Save* goes back to the page the form was opened from (the list as it was filtered, the detail
  page, your plugin's page), else to the saved row. *Save and continue editing* stays on the form;
  *Save and add another* opens an empty create form. A `?next=/path` on the form's URL sets where
  *Save* and *Cancel* go; only paths on this site are followed.
- A foreign key whose related table has more than 200 rows is a search box instead of a select: it
  searches the related admin's `search` columns (else its text columns) and its key, through the
  related admin's `query()`; the saved key is checked through it too.
- A read-only field is shown greyed and ignored when posted.

## In your own plugin's pages

The pages of an admin mount under your plugin, behind your plugin's own access rules:

```python
from fastapi import APIRouter, Depends
from fastpluggy.core.auth import require_authentication

router = APIRouter()
router.include_router(
    crud.router(StoryAdmin, dependencies=[Depends(require_authentication)]),
    prefix="/stories",
)
```

`crud.router(admin, name=None, dependencies=None)` serves `/`, `/create`, `/<pk>`, `/<pk>/edit`,
`/<pk>/delete` and the custom actions; `name` prefixes the route names (default `crud:<slug>`).

A list inside one of your pages, with its search, filters, sort and pages (they use your page's
URL), its rows linked to the back office:

```python
from fastapi import Request
from fastpluggy.core.database import get_db
from fastpluggy.core.dependency import get_view_builder

@router.get("/writers/{writer_id}")
def writer_page(writer_id: int, request: Request, db=Depends(get_db), view_builder=Depends(get_view_builder)):
    stories = crud.list_widget(Story, request, db, filters={"writer_id": writer_id})
    return view_builder.generate(request, title="Stories", widgets=[stories])
```

`filters` narrows the list for good, without a control: a value, a list (any of) or `None` (empty).

A form inside one of your pages: it posts to the back office, which runs the admin's checks and
hooks, then comes back to your page.

```python
    add_story = crud.form_widget(Story, request, db, initial={"writer_id": writer_id})  # create
    edit_story = crud.form_widget(Story, request, db, story)                           # edit
```

Links into the back office, for buttons in your own pages:

```python
crud.url(Story)                           # /plugin-pkg/crud_tools/story/
crud.url(StoryAdmin, "edit", story)       # /plugin-pkg/crud_tools/story/12/edit
crud.url(Story, "create", title="Draft")  # the create form, prefilled
crud.link(Story, "create", request=request)  # {"url", "label", "css_class"} for ButtonListWidget,
                                             # or None when can() refuses
```

## Back office

Under the plugin mount, `/plugin-pkg/crud_tools`:

| Path | Page |
|---|---|
| `/` | Models: the registered admins, grouped by plugin, with their row count |
| `/inspect/<slug>` | An admin's resolved configuration: every field, where it shows and why |
| `/<slug>/` | List (its URL below) |
| `/<slug>/create` | Create form |
| `/<slug>/<pk>` | Detail |
| `/<slug>/<pk>/edit` | Edit form |
| `/<slug>/<pk>/delete` | Delete (POST) |
| `/<slug>/bulk/<action>` | Bulk action on the ticked rows, or `all=1` with the list's filters (POST) |
| `/<slug>/export.csv` | The list as CSV (same parameters as the list) |
| `/<slug>/choices/<field>?q=` | The rows a foreign key may point to, as JSON (search box) |
| `/browse/<table>/` | With `browse_all_models`: a model nobody registered, read-only |

A list URL says what it shows, so it can be bookmarked and shared:

```
/<slug>/?q=lovelace&status=draft&published_at__gte=2026-01-01&writer_id=3&sort=-title&page=2&per_page=25
```

- `q` searches the `search` columns, any of them, ignoring case (`%` and `_` are plain characters).
- A filter is a field name, then an operator: nothing (equals), `__contains`, `__gte`, `__lte`, `__in`
  (comma-separated: `status__in=draft,published`) or `__isnull` (`1` / `0`). A day on a date-time
  column means the whole day.
- `sort` is a list column, `-` first for descending; `per_page` goes up to 200.
- A value that does not fit (`published_at__gte=31/01/2026`) answers 400 with the message under its
  filter, and no rows: a list is never shown as if a filter had not been typed.

Only a signed-in user holding one of the `required_roles` reaches the back office (an `is_admin`
account always passes); without an auth manager the core lets everyone in, and these pages too.
Every write is a POST that must come from one of the application's pages (`Origin` check).

## Settings

| Setting | Default | Effect |
|---|---|---|
| `required_roles` | `["fp_admin"]` | Roles that reach the back office. Read on every request; an empty list means the default. |
| `browse_all_models` | `false` | Also list the models no plugin registered, read-only, under `/browse/<table>/`. |
| `disabled_actions` | `[]` | Actions switched off for every admin, buttons and routes: `["delete"]`, or `["create", "edit", "delete"]` for a read-only back office. |
| `page_size` | `50` | Rows per list page when the admin sets none (at most 200). |

## Forms without a model

crud_tools serves forms about models. For any other form, give the core `FormWidget` WTForms fields:

```python
from wtforms import IntegerField, StringField
from wtforms.validators import DataRequired, Optional

FormWidget(fields={
    "image": StringField("New image", validators=[DataRequired()], render_kw={"placeholder": "nginx:latest"}),
    "replicas": IntegerField("Replicas", default=1, validators=[Optional()]),
}, method="post")
```

## Upgrading from 0.3

| 0.3 | Now |
|---|---|
| Every model of the application served | Only registered models (`crud.register(Model)`), or `browse_all_models` read-only |
| `class XAdmin(CrudAdmin): model = X` + `crud_admin_registry.register(XAdmin)` in `on_load_complete` | `@crud.register class XAdmin(crud.ModelAdmin[X])`, at import |
| `configure_fields`, `get_excluded_fields`, `default_excluded_fields` | `fields`, `form_view`, `list_view`, `detail_view` |
| `get_page_title`, `get_submit_label` | `label`, `item_label`, `title(obj)` |
| `show_create`, `get_actions`, `get_inline_actions` | `actions`, `extra_actions`, `can()` |
| `on_create`, `on_update`, `on_delete` (never called) | `before_save`, `after_save`, `before_delete` |
| `/action/<Model>/list`, `/action/<Model>/view/<id>`… | `/<slug>/`, `/<slug>/<pk>`… |
| `url_for_crud(...)`, `CrudLinkHelper.get_crud_link(Model, action)` | `crud.url(Model, action, obj)`, `crud.link(Model, action, obj)` |
| `base_sqlalchemy_model` setting | gone: register the model, whatever its declarative base |
| `FilteredTableModelWidget`, header filters | the list's search and filter panel; `crud.list_widget(Model, request, db, filters=…)` in your own pages |
| `PanelModelWidget`, `DynamicSelectFieldType` | gone; a foreign key over many rows is a search box |
| `field_types` (`TextFieldType`, `IntegerFieldType`…), `CrudAction` | WTForms fields in the core `FormWidget` (above); `crud.ACTIONS` |

## Development

### Architecture

The plugin is organized into internal modules under `src/`:

- **`_inference`**: Column metadata to field specifications (types, validators, widgets)
- **`_registry`**: Admin registration, binding validation, slug uniqueness
- **`_resolve`**: Typed primary key to database row (via `admin.query()`), 404 handling
- **`_listing`**: List URL parameters (`?q=&status=&sort=`) to SQLAlchemy statements
- **`_forms`**: Form generation and validation
- **`_pages`**: Individual page implementations, mounted by both the back office and `crud.router()`
- **`_backoffice`**: The `/plugin-pkg/crud_tools/` sidebar entry and models index

### Filter validation

A filter whose name is `q`, `sort`, `page`, or `per_page`, or that contains `__`, is rejected at
registration time with a `crud.ConfigError`. This prevents conflicts with the reserved list URL
parameters and the operator syntax (`field__gte`, `field__contains`, etc.).

### Template autoescape pitfall

The core templates that render buttons and form controls do **not** autoescape by default. When
passing user-controlled text to core macros such as `render_button`, always escape it with
`markupsafe.escape()`. Plugin templates that call these macros should wrap their own content in
`{% autoescape true %}...{% endautoescape %}`.

### E2E testing

The end-to-end tests run a live application with sample models:

- **Command**: `uvicorn app:create_app --factory --app-dir e2e` (see `.gitlab-ci.yml`)
- **Models**: `e2e/demo.py` registers `DemoAuthor`, `DemoPost`, and `DemoTopic` the way a plugin would
- **Seed data**: `e2e/seed.py` creates fixtures for screenshots
- **Routes**: `e2e/routes.json` lists the pages to screenshot
- CI runs `e2e/seed.py` (`SETUP_SCRIPT`) once the server is up, since the server creates the tables
