Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changelog.d/v2-published-reports.added.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Authors and admins can publish one of their saved reports as a public, read-only page (`POST /v2/user-reports/{id}/publication`), edit it, move it to a newer succeeded run as a new version, and withdraw it; anyone reads a published report, with no credential, at `GET /v2/published-reports/{id}`.
2 changes: 1 addition & 1 deletion docs/engineering/migration-contracts.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ Generated from `policyengine_api/migration_registry.py` and `tests/contract/regi
| `household` | `household`, `households`, `household-calculations`, `user-household`, `user-households`, `calculate`, `calculate-full` | `household` | `household` |
| `economy` | `economy` | `simulation` | `economy` |
| `simulation` | `simulation`, `simulations`, `user-simulations` | `simulation` | `economy` |
| `report` | `report`, `reports`, `user-reports`, `shared-reports` | `report` | `report` |
| `report` | `report`, `reports`, `user-reports`, `shared-reports`, `published-reports` | `report` | `report` |
| `user_profile` | `user-profile`, `me`, `admin` | `user` | `none` |

## App V2 Workflow Contracts
Expand Down
39 changes: 39 additions & 0 deletions docs/engineering/skills/alembic-migrations.md
Original file line number Diff line number Diff line change
Expand Up @@ -1798,3 +1798,42 @@ compares the revision and its downgrade with the parent schema built from
the base, and checks that rows survive, the new index, a downgrade through
`7f7335f0eb31` and back, what a row still naming a dynamic becomes, and the
deploy's privilege steps.

### API v2 published reports

Revision `8c867f67f87f` (parent `1c651058fac5`) was autogenerated after the
models gained `PublishedReport` and `PublishedReportVersion`
(`policyengine_api/data/v2/models/published_reports.py`) and
`UserReportAssociation` a unique constraint on `(id, report_id)`. It adds:

- `published_reports`, one row per saved report an author published as a
public page, keyed by the saved report's ID (`user_report_id`). Its
composite foreign key `fk_published_reports_user_report_report`
(`(user_report_id, report_id)` to `user_report_associations (id,
report_id)`, `ON DELETE CASCADE`, `ON UPDATE RESTRICT`) deletes the page
with its saved report, and so with its owner's account, and refuses to
repoint a published saved report;
- `published_report_versions`, one row per run a page has shown, naming
exactly one of `report_run_id` and `budget_window_run_id`
(`ck_published_report_versions_one_run`), both `ON DELETE RESTRICT`, and
each at most once per page; deleting the page deletes its versions;
- `uq_user_report_associations_id_report_id`, the unique constraint the
composite key references.

Three names are given in the model, because the naming convention's are
longer than PostgreSQL's 63-character limit:
`fk_published_reports_user_report_report`,
`uq_published_report_versions_user_report_window_run` and
`fk_published_report_versions_window_run_budget_window_runs`.

**One post-generation correction**, for an objectively incorrect order:
Alembic generated `uq_user_report_associations_id_report_id` after
`published_reports`, whose foreign key references it, and PostgreSQL
refuses a foreign key to columns without a unique constraint. The upgrade
creates the constraint first, and the downgrade drops it after the tables.
The operations are otherwise as generated. The downgrade drops both tables
with their rows. `tests/integration/test_v2_published_reports.py` downgrades
to the parent and upgrades again, and checks the keys and the refusals as
API v1's runtime role, which holds `SELECT, INSERT, UPDATE, DELETE` on
`published_reports` and `SELECT, INSERT, DELETE` on
`published_report_versions`.
3 changes: 2 additions & 1 deletion docs/generated/migration_contracts.json
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,8 @@
"report",
"reports",
"user-reports",
"shared-reports"
"shared-reports",
"published-reports"
],
"sim_flow": "report"
},
Expand Down
59 changes: 59 additions & 0 deletions docs/migration/stage-12a-user-login.md
Original file line number Diff line number Diff line change
Expand Up @@ -607,6 +607,65 @@ budget_window_years, baseline_reform, last_run_at, created_at, updated_at}`:
provisions. There is no shared list or search, and the owner routes stay
owner-scoped.

### Published reports

An author or admin publishes one of their saved reports as a public,
read-only page that research posts can link to (D6 · 1). The page is linked
by the saved report's ID and shows one succeeded run of the detailed-save
report the saved report names. Every route takes `country_id`.

| Route | Who | What it does |
| --- | --- | --- |
| `POST /v2/user-reports/{id}/publication` | The owner, author or admin (403 below author) | Publishes: `run_id`, `summary`, `author_ids`, `tags`, `content`, `show_past_versions`. 201. |
| `GET /v2/user-reports/{id}/publication` | The owner, any type | The page with every version, newest first. |
| `PATCH /v2/user-reports/{id}/publication` | The owner, author or admin | Sets the fields sent; none may be null. |
| `POST /v2/user-reports/{id}/publication/versions` | The owner, author or admin | Moves the page to another succeeded run of its report, as a new version. 201. |
| `DELETE /v2/user-reports/{id}/publication` | The owner, any type | Withdraws the page, deleting its versions. 204. |
| `GET /v2/published-reports/{id}` | Anyone, no credential | The published report, with `version_id` to read an earlier version. |

- **Runs:** a version names one run: a report run of an economy or household
report, or a budget-window run of a budget window. It must have succeeded
(409 otherwise) and be one of the report's runs (404 otherwise). A page
shows each run at most once (409). Running the report again never moves
the page.
- **Fields:** `summary` is 1 to 300 characters; `author_ids` are 1 to 10 IDs
from the website's `authors.json`, and `tags` up to 20 of its topic and
location tags, both lower-case words joined by hyphens and checked for
form only. `content` is an ordered list of at most 100 blocks, Markdown
(`{"type": "markdown", "markdown": ...}`, at most 20,000 characters,
rendered without raw HTML) or an output card
(`{"type": "output", "output": <key>}`, by v3's key, each at most once);
a card left out is removed. One content serves every version. Request
bodies are at most 16 MiB.
- **Past versions:** with `show_past_versions`, readers may open the page's
earlier versions; turned off, those stay stored and only the newest can
be read.
- **Refusals:** a saved report is published once (409). One that names only
a v1 report output, or has no name (the page's title) or only blanks,
can't be published (409). An edit sends at least one field, none as null.
- **The public read** answers the page's title (the saved report's name),
summary, author IDs, tags and content; the saved report's source note,
provisions, validation, budget window and the name of the reform it was
compared with; the version read and the versions a reader may open, each
with its run's versions and when the page moved to it; and the report
with that version's run, as `GET /v2/reports/{id}?run_id=` answers it,
labelled with the title. The owner, the saved report's `description` (the
owner's notes), the owner's saved-reform IDs and `last_run_at` are left
out. It never provisions a user.
- **Deletes and repointing:** `published_reports` has a composite foreign
key `(user_report_id, report_id)` to `user_report_associations (id,
report_id)`, `ON DELETE CASCADE`, `ON UPDATE RESTRICT`. Deleting the saved
report, or its owner's account, deletes the page. Repointing a published
saved report to another report, or clearing or blanking its name (the
page's title),
is refused (409) until the page is withdrawn. A run a page has shown can't
be deleted.
- **Locks:** a publish and the saved report's PATCH lock the saved report's
row, and a page's edit, move and withdrawal lock the page's, so each waits
for another write of the same row to finish.
- **Not yet in the export:** `GET /v2/me/export` and admins' saved-items read
don't include published pages.

### Saved detailed-save simulations and reports

`POST` and `PATCH` on `/v2/user-simulations` and `/v2/user-reports` take a
Expand Down
79 changes: 79 additions & 0 deletions migrations/v2/versions/8c867f67f87f_add_published_reports.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
"""add published reports

Revision ID: 8c867f67f87f
Revises: 1c651058fac5
Create Date: 2026-11-28 01:56:33.390946
Generation: uv run alembic -c alembic-v2.ini revision --autogenerate

Adds the tables of saved reports published as public pages (D6 · 1):
published_reports, one row per published saved report, keyed by the saved
report's ID, and published_report_versions, one row per run a page has
shown. A published report's composite foreign key names its saved report
with the report that saved report names, on a new unique constraint on
user_report_associations (id, report_id): deleting the saved report deletes
the page, and repointing a published saved report is refused.

One correction to the generated operations, for an objectively incorrect
order: Alembic generated the unique constraint after the table whose
foreign key references it, which PostgreSQL refuses, so the upgrade creates
it first, and the downgrade drops it after the table. The operations are
otherwise exactly as generated. The downgrade drops both tables with their
rows.
"""

from typing import Sequence, Union

from alembic import op
import sqlalchemy as sa
import sqlmodel
from sqlalchemy.dialects import postgresql

revision: str = '8c867f67f87f'
down_revision: Union[str, None] = '1c651058fac5'
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def upgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
op.create_unique_constraint(op.f('uq_user_report_associations_id_report_id'), 'user_report_associations', ['id', 'report_id'])
op.create_table('published_reports',
sa.Column('user_report_id', sa.Uuid(), nullable=False),
sa.Column('report_id', sa.Uuid(), nullable=False),
sa.Column('summary', sqlmodel.sql.sqltypes.AutoString(length=300), nullable=False),
sa.Column('author_ids', sa.JSON().with_variant(postgresql.JSONB(astext_type=sa.Text()), 'postgresql'), nullable=False),
sa.Column('tags', sa.JSON().with_variant(postgresql.JSONB(astext_type=sa.Text()), 'postgresql'), nullable=False),
sa.Column('content', sa.JSON().with_variant(postgresql.JSONB(astext_type=sa.Text()), 'postgresql'), nullable=False),
sa.Column('show_past_versions', sa.Boolean(), server_default=sa.text('false'), nullable=False),
sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=False),
sa.Column('updated_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=False),
sa.ForeignKeyConstraint(['user_report_id', 'report_id'], ['user_report_associations.id', 'user_report_associations.report_id'], name='fk_published_reports_user_report_report', onupdate='RESTRICT', ondelete='CASCADE'),
sa.PrimaryKeyConstraint('user_report_id', name=op.f('pk_published_reports'))
)
op.create_table('published_report_versions',
sa.Column('id', sa.Uuid(), nullable=False),
sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=False),
sa.Column('user_report_id', sa.Uuid(), nullable=False),
sa.Column('report_run_id', sa.Uuid(), nullable=True),
sa.Column('budget_window_run_id', sa.Uuid(), nullable=True),
sa.CheckConstraint('(report_run_id IS NULL) <> (budget_window_run_id IS NULL)', name=op.f('ck_published_report_versions_one_run')),
sa.ForeignKeyConstraint(['budget_window_run_id'], ['budget_window_runs.id'], name='fk_published_report_versions_window_run_budget_window_runs', ondelete='RESTRICT'),
sa.ForeignKeyConstraint(['report_run_id'], ['report_runs.id'], name=op.f('fk_published_report_versions_report_run_id_report_runs'), ondelete='RESTRICT'),
sa.ForeignKeyConstraint(['user_report_id'], ['published_reports.user_report_id'], name=op.f('fk_published_report_versions_user_report_id_published_reports'), ondelete='CASCADE'),
sa.PrimaryKeyConstraint('id', name=op.f('pk_published_report_versions')),
sa.UniqueConstraint('user_report_id', 'budget_window_run_id', name='uq_published_report_versions_user_report_window_run'),
sa.UniqueConstraint('user_report_id', 'report_run_id', name=op.f('uq_published_report_versions_user_report_id_report_run_id'))
)
op.create_index(op.f('ix_published_report_versions_budget_window_run_id'), 'published_report_versions', ['budget_window_run_id'], unique=False)
op.create_index(op.f('ix_published_report_versions_report_run_id'), 'published_report_versions', ['report_run_id'], unique=False)
# ### end Alembic commands ###


def downgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
op.drop_index(op.f('ix_published_report_versions_report_run_id'), table_name='published_report_versions')
op.drop_index(op.f('ix_published_report_versions_budget_window_run_id'), table_name='published_report_versions')
op.drop_table('published_report_versions')
op.drop_table('published_reports')
op.drop_constraint(op.f('uq_user_report_associations_id_report_id'), 'user_report_associations', type_='unique')
# ### end Alembic commands ###
6 changes: 6 additions & 0 deletions policyengine_api/data/v2/models/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,10 @@
LegacyUserMapping,
LegacyUserPolicyMapping,
)
from policyengine_api.data.v2.models.published_reports import ( # noqa: E402 # tables declared after the naming convention above
PublishedReport,
PublishedReportVersion,
)
from policyengine_api.data.v2.models.reports import ( # noqa: E402
BudgetWindowRun,
Report,
Expand Down Expand Up @@ -170,6 +174,8 @@
"Policy",
"Poverty",
"ProgramStatistics",
"PublishedReport",
"PublishedReportVersion",
"Region",
"RegionType",
"Report",
Expand Down
7 changes: 6 additions & 1 deletion policyengine_api/data/v2/models/associations.py
Original file line number Diff line number Diff line change
Expand Up @@ -301,7 +301,9 @@ class UserReportAssociation(TimestampedModel, table=True):
report that names a missing report, and a report a saved one names can't
be deleted. ``legacy_report_id`` is the requested v1 report output
identifier. The optional ``user_policy_id`` links a v3 report to the same
owner's saved reform and is cleared when that reform is deleted.
owner's saved reform and is cleared when that reform is deleted. A saved
report an author published (``published_reports``) can't be repointed
to another report, and deleting it deletes the published page.
"""

__tablename__ = "user_report_associations"
Expand All @@ -311,6 +313,9 @@ class UserReportAssociation(TimestampedModel, table=True):
"country_id",
name="uq_user_report_associations_id_country",
),
# A published report's key names the saved report with its report,
# so repointing a published saved report is refused.
sa.UniqueConstraint("id", "report_id"),
sa.CheckConstraint(
"report_id IS NOT NULL OR legacy_report_id IS NOT NULL",
name="ck_user_report_associations_report_ref",
Expand Down
121 changes: 121 additions & 0 deletions policyengine_api/data/v2/models/published_reports.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
"""Canonical SQLModel tables for saved reports published as public pages.

An author or admin publishes one of their saved reports as a public,
read-only page, linked by the saved report's ID. The page has its own
summary, authors, tags and content, and shows one succeeded run of the
report: each run it has shown is a version, and the newest is the one it
shows. API v1 writes both tables; nothing else reads them.
"""

from datetime import datetime
from typing import Any
from uuid import UUID

import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
from sqlmodel import Field, SQLModel

from policyengine_api.data.v2.models.base import IdentifiedModel, utc_now

# The longest card summary a page may have.
MAXIMUM_PUBLISHED_SUMMARY_LENGTH = 300


def _jsonb_type() -> sa.types.TypeEngine[Any]:
# Typed JSON storage is one of the reviewed direct-SQLAlchemy exceptions.
return sa.JSON().with_variant(postgresql.JSONB(), "postgresql")


class PublishedReport(SQLModel, table=True):
"""A saved report published as a public page, keyed by the saved report's ID.

``report_id`` is the report the saved report names, and the composite
foreign key ``(user_report_id, report_id)`` to
``user_report_associations (id, report_id)`` holds it to that: deleting
the saved report, or its owner's account, deletes the page, and the
database refuses to repoint a published saved report to another report.
``summary``, ``author_ids`` (IDs from the website's ``authors.json``),
``tags`` (the website's topic and location tags) and ``content`` (an
ordered list of Markdown and output-card blocks; a card left out is
removed) are the page's own; one content serves every version.
``show_past_versions`` says whether readers may open earlier versions.
"""

__tablename__ = "published_reports"
__table_args__ = (
# Named here: the naming convention's name is longer than PostgreSQL's
# 63-character limit.
sa.ForeignKeyConstraint(
["user_report_id", "report_id"],
["user_report_associations.id", "user_report_associations.report_id"],
name="fk_published_reports_user_report_report",
ondelete="CASCADE",
onupdate="RESTRICT",
),
)

user_report_id: UUID = Field(primary_key=True)
report_id: UUID
summary: str = Field(max_length=MAXIMUM_PUBLISHED_SUMMARY_LENGTH)
author_ids: list[str] = Field(sa_type=_jsonb_type())
tags: list[str] = Field(sa_type=_jsonb_type())
content: list[dict[str, Any]] = Field(sa_type=_jsonb_type())
show_past_versions: bool = Field(
default=False, sa_column_kwargs={"server_default": sa.false()}
)
# Kept as the base models declare them, without the base's ``id``: the
# saved report's ID is this row's.
created_at: datetime = Field(
default_factory=utc_now,
sa_type=sa.DateTime(timezone=True),
sa_column_kwargs={"server_default": sa.func.now()},
)
updated_at: datetime = Field(
default_factory=utc_now,
sa_type=sa.DateTime(timezone=True),
sa_column_kwargs={"server_default": sa.func.now(), "onupdate": sa.func.now()},
)


class PublishedReportVersion(IdentifiedModel, table=True):
"""One run a published report has shown; the newest is the one it shows.

A version names exactly one run: a report run of an economy or household
report, or a budget-window run of a budget window. Its ``created_at`` is
when the page moved to that run. A run a page has shown can't be
deleted, and a page shows each run at most once. Deleting the page
deletes its versions.
"""

__tablename__ = "published_report_versions"
__table_args__ = (
sa.CheckConstraint(
"(report_run_id IS NULL) <> (budget_window_run_id IS NULL)",
name="ck_published_report_versions_one_run",
),
sa.UniqueConstraint("user_report_id", "report_run_id"),
# These two are named here: the naming convention's names are longer
# than PostgreSQL's 63-character limit.
sa.UniqueConstraint(
"user_report_id",
"budget_window_run_id",
name="uq_published_report_versions_user_report_window_run",
),
sa.ForeignKeyConstraint(
["budget_window_run_id"],
["budget_window_runs.id"],
name="fk_published_report_versions_window_run_budget_window_runs",
ondelete="RESTRICT",
),
)

user_report_id: UUID = Field(
foreign_key="published_reports.user_report_id", ondelete="CASCADE"
)
report_run_id: UUID | None = Field(
default=None,
foreign_key="report_runs.id",
ondelete="RESTRICT",
index=True,
)
budget_window_run_id: UUID | None = Field(default=None, index=True)
Loading
Loading