diff --git a/changelog.d/v2-published-reports.added.md b/changelog.d/v2-published-reports.added.md new file mode 100644 index 000000000..684acbb70 --- /dev/null +++ b/changelog.d/v2-published-reports.added.md @@ -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}`. diff --git a/docs/engineering/migration-contracts.md b/docs/engineering/migration-contracts.md index dd585d9d6..3f4f5596e 100644 --- a/docs/engineering/migration-contracts.md +++ b/docs/engineering/migration-contracts.md @@ -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 diff --git a/docs/engineering/skills/alembic-migrations.md b/docs/engineering/skills/alembic-migrations.md index 9ee2c2906..0c79749c2 100644 --- a/docs/engineering/skills/alembic-migrations.md +++ b/docs/engineering/skills/alembic-migrations.md @@ -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`. diff --git a/docs/generated/migration_contracts.json b/docs/generated/migration_contracts.json index 46bb6c6ea..b247e1fbe 100644 --- a/docs/generated/migration_contracts.json +++ b/docs/generated/migration_contracts.json @@ -99,7 +99,8 @@ "report", "reports", "user-reports", - "shared-reports" + "shared-reports", + "published-reports" ], "sim_flow": "report" }, diff --git a/docs/migration/stage-12a-user-login.md b/docs/migration/stage-12a-user-login.md index 585fe23b9..ec27ed91e 100644 --- a/docs/migration/stage-12a-user-login.md +++ b/docs/migration/stage-12a-user-login.md @@ -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": }`, 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 diff --git a/migrations/v2/versions/8c867f67f87f_add_published_reports.py b/migrations/v2/versions/8c867f67f87f_add_published_reports.py new file mode 100644 index 000000000..9933ed5df --- /dev/null +++ b/migrations/v2/versions/8c867f67f87f_add_published_reports.py @@ -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 ### diff --git a/policyengine_api/data/v2/models/__init__.py b/policyengine_api/data/v2/models/__init__.py index 2e0aaa6b2..b2198f255 100644 --- a/policyengine_api/data/v2/models/__init__.py +++ b/policyengine_api/data/v2/models/__init__.py @@ -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, @@ -170,6 +174,8 @@ "Policy", "Poverty", "ProgramStatistics", + "PublishedReport", + "PublishedReportVersion", "Region", "RegionType", "Report", diff --git a/policyengine_api/data/v2/models/associations.py b/policyengine_api/data/v2/models/associations.py index b154f690c..446e473c5 100644 --- a/policyengine_api/data/v2/models/associations.py +++ b/policyengine_api/data/v2/models/associations.py @@ -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" @@ -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", diff --git a/policyengine_api/data/v2/models/published_reports.py b/policyengine_api/data/v2/models/published_reports.py new file mode 100644 index 000000000..d9aa6c699 --- /dev/null +++ b/policyengine_api/data/v2/models/published_reports.py @@ -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) diff --git a/policyengine_api/data/v2/privileges.py b/policyengine_api/data/v2/privileges.py index b210a37dc..2ebebe52b 100644 --- a/policyengine_api/data/v2/privileges.py +++ b/policyengine_api/data/v2/privileges.py @@ -364,6 +364,11 @@ def _run_table( # changes one afterwards. "user_report_run_associations": _access(runtime=READ_INSERT_DELETE), "user_simulation_associations": _access(runtime=READ_WRITE), + # Saved reports their authors published, which API v1 writes, changes + # and deletes, and the runs each has shown: added as a page moves to a + # newer run, never changed, and deleted when the page is withdrawn. + "published_reports": _access(runtime=READ_WRITE), + "published_report_versions": _access(runtime=READ_INSERT_DELETE), "users": _access(runtime=READ_WRITE), # Each change of a signed-in user's type, recorded by the admin routes, # invitations and the type script. Afterwards only the time the user diff --git a/policyengine_api/fastapi_routes/dependencies.py b/policyengine_api/fastapi_routes/dependencies.py index 62be0f0b4..2be8a258b 100644 --- a/policyengine_api/fastapi_routes/dependencies.py +++ b/policyengine_api/fastapi_routes/dependencies.py @@ -22,6 +22,7 @@ V2HouseholdCalculationResourceService, V2HouseholdResourceService, V2PolicyResourceService, + V2PublishedReportResourceService, V2StoredReportResourceService, V2StoredSimulationResourceService, V2UserDynamicResourceService, @@ -81,6 +82,7 @@ "V2HouseholdResourceService", "V2MetadataResourceReader", "V2PolicyResourceService", + "V2PublishedReportResourceService", "V2StoredReportResourceService", "V2StoredSimulationResourceService", "V2UserDynamicResourceService", @@ -488,6 +490,34 @@ def _default_v2_user_report_service_factory() -> V2UserReportResourceService: ) +def _default_v2_published_report_service_factory() -> V2PublishedReportResourceService: + from policyengine_api.data.v2.database import ( + get_v2_session_factory, + ) + from policyengine_api.services.v2.published_reports.database_session import ( + PublishedReportDatabaseSession, + ) + from policyengine_api.services.v2.published_reports.services import ( + V2PublishedReportService, + ) + from policyengine_api.services.v2.stored_reports.database_session import ( + StoredReportDatabaseSession, + ) + from policyengine_api.services.v2.stored_reports.services import ( + V2StoredReportService, + ) + + # The public read reads reports only, so the report service needs no + # submissions or run records. + return V2PublishedReportService( + PublishedReportDatabaseSession(get_v2_session_factory()), + reports=V2StoredReportService( + StoredReportDatabaseSession(get_v2_session_factory()), + current_versions=_current_package_versions, + ), + ) + + def _default_v2_account_service_factory() -> V2AccountResourceService: from policyengine_api.data.v2.database import ( get_v2_session_factory, @@ -611,6 +641,9 @@ class NativeRouteDependencies: v2_user_report_service_factory: Callable[[], V2UserReportResourceService] | None = ( None ) + v2_published_report_service_factory: ( + Callable[[], V2PublishedReportResourceService] | None + ) = None v2_account_service_factory: Callable[[], V2AccountResourceService] | None = None v2_user_type_service_factory: Callable[[], V2UserTypeResourceService] | None = None v2_user_invitation_service_factory: ( @@ -655,6 +688,9 @@ def defaults(cls) -> NativeRouteDependencies: _default_v2_user_simulation_service_factory ), v2_user_report_service_factory=_default_v2_user_report_service_factory, + v2_published_report_service_factory=( + _default_v2_published_report_service_factory + ), v2_account_service_factory=_default_v2_account_service_factory, v2_user_type_service_factory=_default_v2_user_type_service_factory, v2_user_invitation_service_factory=( diff --git a/policyengine_api/fastapi_routes/resource_service_protocols.py b/policyengine_api/fastapi_routes/resource_service_protocols.py index f14ef967a..cba2750a4 100644 --- a/policyengine_api/fastapi_routes/resource_service_protocols.py +++ b/policyengine_api/fastapi_routes/resource_service_protocols.py @@ -44,6 +44,13 @@ NativePolicyCreation, NativePolicyCreationInput, ) + from policyengine_api.services.v2.published_reports.types import ( + PublicationCreateInput, + PublicationRead, + PublicationUpdateInput, + PublicationVersionInput, + PublishedReportRead, + ) from policyengine_api.services.v2.simulation_service.types import ( EconomySimulationCreationInput, ReportCreationInput, @@ -345,6 +352,61 @@ def list_report_runs( ... +class V2PublishedReportResourceService(Protocol): + """Route-independent publishing of saved reports, and their public read.""" + + def publish_report( + self, + *, + principal: AccountPrincipal, + country_id: str, + user_report_id: UUID, + publication_input: PublicationCreateInput, + ) -> PublicationRead: + """Publish the principal's saved report, showing the run the input names.""" + ... + + def get_publication( + self, *, principal: AccountPrincipal, country_id: str, user_report_id: UUID + ) -> PublicationRead: + """Return the principal's published report with every version.""" + ... + + def update_publication( + self, + *, + principal: AccountPrincipal, + country_id: str, + user_report_id: UUID, + publication_input: PublicationUpdateInput, + ) -> PublicationRead: + """Set the fields the edit sends on the principal's published report.""" + ... + + def add_publication_version( + self, + *, + principal: AccountPrincipal, + country_id: str, + user_report_id: UUID, + version_input: PublicationVersionInput, + ) -> PublicationRead: + """Move the principal's published report to another run, as a version.""" + ... + + def withdraw_publication( + self, *, principal: AccountPrincipal, country_id: str, user_report_id: UUID + ) -> None: + """Delete the principal's published report with its versions.""" + ... + + def get_published_report( + self, *, country_id: str, user_report_id: UUID, version_id: UUID | None + ) -> PublishedReportRead: + """Return a published report as anyone reads it, with no credential.""" + ... + + class V2StoredSimulationResourceService(Protocol): """Route-independent simulation operations for one request.""" diff --git a/policyengine_api/fastapi_routes/v2/published_reports/__init__.py b/policyengine_api/fastapi_routes/v2/published_reports/__init__.py new file mode 100644 index 000000000..89eb220ab --- /dev/null +++ b/policyengine_api/fastapi_routes/v2/published_reports/__init__.py @@ -0,0 +1 @@ +"""Native FastAPI routes for v2 published reports.""" diff --git a/policyengine_api/fastapi_routes/v2/published_reports/request_models.py b/policyengine_api/fastapi_routes/v2/published_reports/request_models.py new file mode 100644 index 000000000..65e6b5593 --- /dev/null +++ b/policyengine_api/fastapi_routes/v2/published_reports/request_models.py @@ -0,0 +1,19 @@ +"""Strict HTTP request models for v2 published reports.""" + +from policyengine_api.services.v2.published_reports.types import ( + PublicationCreateInput, + PublicationUpdateInput, + PublicationVersionInput, +) + + +class PublicationCreateRequest(PublicationCreateInput): + """A publication's fields and the run it shows; the owner is the credential's.""" + + +class PublicationPatchRequest(PublicationUpdateInput): + """The published report's fields to change; the others stay.""" + + +class PublicationVersionRequest(PublicationVersionInput): + """The run the published report moves to, as its new version.""" diff --git a/policyengine_api/fastapi_routes/v2/published_reports/response_models.py b/policyengine_api/fastapi_routes/v2/published_reports/response_models.py new file mode 100644 index 000000000..e920404fb --- /dev/null +++ b/policyengine_api/fastapi_routes/v2/published_reports/response_models.py @@ -0,0 +1,197 @@ +"""Strict HTTP response models for v2 published reports.""" + +from __future__ import annotations + +from datetime import datetime +from typing import TYPE_CHECKING, Annotated, Generic, Literal, TypeVar +from uuid import UUID + +from pydantic import BaseModel, ConfigDict, Field + +from policyengine_api.fastapi_routes.v2.reports.response_models import ( + BudgetWindowReportItem, + HouseholdReportItem, + ReportItem, + report_item, +) +from policyengine_api.fastapi_routes.v2.user_reports.response_models import ( + ReportProvisionItem, + ReportValidationItem, + SharedBaselineReformItem, +) +from policyengine_api.query_parameters import CountryId + +if TYPE_CHECKING: + from policyengine_api.services.v2.published_reports.types import ( + PublicationRead, + PublishedReportRead, + ) + + +class StrictPublishedReportAPIModel(BaseModel): + """Base for published-report responses; rejects unknown fields.""" + + model_config = ConfigDict(extra="forbid", from_attributes=True) + + +class MarkdownBlockItem(StrictPublishedReportAPIModel): + """A section of Markdown the author wrote; render it without raw HTML.""" + + type: Literal["markdown"] + markdown: str + + +class OutputBlockItem(StrictPublishedReportAPIModel): + """One of the report's output cards, by v3's key for it.""" + + type: Literal["output"] + output: str + + +ContentBlockItem = Annotated[ + MarkdownBlockItem | OutputBlockItem, Field(discriminator="type") +] + + +class PublicationVersionItem(StrictPublishedReportAPIModel): + """One run the published report has shown. + + ``run_id`` is a report run's ID, or a budget window's budget-window + run's. ``country_package_version`` and ``policyengine_version`` are the + versions it ran on (a budget-window run's are its first year's, and none + without a year), and ``published_at`` is when the page moved to it. + """ + + id: UUID + run_id: UUID + country_package_version: str | None + policyengine_version: str | None + published_at: datetime + + +class PublicationItem(StrictPublishedReportAPIModel): + """A published report as its owner reads it, with every version, newest first. + + ``user_report_id`` is the saved report's ID, the published report's + public link. The newest version is the one the page shows. + ``published_at`` is when it was first published, and ``updated_at`` when + any of it last changed. + """ + + user_report_id: UUID + country_id: CountryId + summary: str + author_ids: list[str] + tags: list[str] + content: list[ContentBlockItem] + show_past_versions: bool + versions: list[PublicationVersionItem] + published_at: datetime + updated_at: datetime + + @classmethod + def from_read(cls, read: PublicationRead) -> PublicationItem: + """Build the item from the service's read.""" + return cls.model_validate(read) + + +class PublishedSavedReportItem(StrictPublishedReportAPIModel): + """The saved report's presentation: as a shared report shows it, without IDs.""" + + source_note: str | None + provisions: list[ReportProvisionItem] | None + validation: ReportValidationItem | None + budget_window_years: int | None + baseline_reform: SharedBaselineReformItem | None + + +class PublishedReportItem(StrictPublishedReportAPIModel): + """A published report as anyone reads it, without its owner. + + ``id`` is the saved report's ID, the page's link, and ``title`` the saved + report's name. ``version`` is the version read, and ``report`` the report + with that version's run, as ``GET /v2/reports/{id}?run_id=`` answers it, + labelled with the title. ``versions`` lists the versions a reader may + open, newest first: every version while ``show_past_versions``, else + only the newest. + """ + + id: UUID + country_id: CountryId + title: str | None + summary: str + author_ids: list[str] + tags: list[str] + content: list[ContentBlockItem] + show_past_versions: bool + saved_report: PublishedSavedReportItem + version: PublicationVersionItem + versions: list[PublicationVersionItem] + published_at: datetime + updated_at: datetime + report: Annotated[ + ReportItem | HouseholdReportItem | BudgetWindowReportItem, + Field(discriminator="kind"), + ] + + @classmethod + def from_read(cls, read: PublishedReportRead) -> PublishedReportItem: + """Build the item from the service's read, with its report's item.""" + return cls.model_validate( + { + "id": read.id, + "country_id": read.country_id, + "title": read.title, + "summary": read.summary, + "author_ids": read.author_ids, + "tags": read.tags, + "content": read.content, + "show_past_versions": read.show_past_versions, + "saved_report": PublishedSavedReportItem.model_validate( + read.saved_report + ), + "version": PublicationVersionItem.model_validate(read.version), + "versions": [ + PublicationVersionItem.model_validate(version) + for version in read.versions + ], + "published_at": read.published_at, + "updated_at": read.updated_at, + "report": report_item(read.report), + } + ) + + +ResultT = TypeVar("ResultT") + + +class PublishedReportSuccessResponse(StrictPublishedReportAPIModel, Generic[ResultT]): + """Success envelope: ``status`` "ok", a null ``message`` and the ``result``.""" + + status: Literal["ok"] = "ok" + message: None = None + result: ResultT + + +class PublicationDetailResult(StrictPublishedReportAPIModel): + """Result holding the owner's published report in ``item``.""" + + item: PublicationItem + + +class PublishedReportDetailResult(StrictPublishedReportAPIModel): + """Result holding a published report in ``item``.""" + + item: PublishedReportItem + + +class PublicationDetailResponse( + PublishedReportSuccessResponse[PublicationDetailResult] +): + """Success response holding the owner's published report.""" + + +class PublishedReportDetailResponse( + PublishedReportSuccessResponse[PublishedReportDetailResult] +): + """Success response holding a published report.""" diff --git a/policyengine_api/fastapi_routes/v2/published_reports/routes.py b/policyengine_api/fastapi_routes/v2/published_reports/routes.py new file mode 100644 index 000000000..f1017faf4 --- /dev/null +++ b/policyengine_api/fastapi_routes/v2/published_reports/routes.py @@ -0,0 +1,478 @@ +"""Native FastAPI routes that publish saved reports, and read them publicly. + +An author or admin publishes one of their saved reports as a public, +read-only page, which shows one succeeded run of its report, with a +summary, authors, tags and content of its own. The owner's routes take the +user-report routes' credentials: publishing, editing and moving the page to +a newer run need author or above (403 below it), and reading the owner's +page and withdrawing it need only ownership, so an author who was demoted +can still withdraw what they published. Anyone reads a published report by +its saved report's ID, with no credential. +""" + +# No postponed annotations: FastAPI resolves each route's dependency +# annotations at runtime, and the author check is a dependency local to the +# router builder. +from collections.abc import Callable +from typing import Annotated, Any +from uuid import UUID + +from fastapi import APIRouter, Depends +from starlette.responses import JSONResponse, Response + +from policyengine_api.data.v2.models import UserType +from policyengine_api.data.v2.settings import V2ConfigurationError +from policyengine_api.fastapi_routes.dependencies import ( + NativeRouteDependencies, + V2PublishedReportResourceService, + V2UserTypeResourceService, + _default_v2_published_report_service_factory, + _default_v2_user_type_service_factory, +) +from policyengine_api.fastapi_routes.query_parameters import query_dependency +from policyengine_api.fastapi_routes.v2.errors_support import ( + V2ErrorMapping, + V2ErrorResponse, +) +from policyengine_api.fastapi_routes.v2.published_reports.request_models import ( + PublicationCreateRequest, + PublicationPatchRequest, + PublicationVersionRequest, +) +from policyengine_api.fastapi_routes.v2.published_reports.response_models import ( + PublicationDetailResponse, + PublicationDetailResult, + PublicationItem, + PublishedReportDetailResponse, + PublishedReportDetailResult, + PublishedReportItem, +) +from policyengine_api.fastapi_routes.v2.simulation_resources_support import ( + simulation_resource_operation, +) +from policyengine_api.fastapi_routes.v2.user_resources_support import ( + USER_RESOURCE_ERROR_RESPONSES, + request_size_limit, + user_resource_operation, +) +from policyengine_api.fastapi_routes.v2.user_type_support import ( + minimum_user_type_dependency, +) +from policyengine_api.query_parameters import CountryQuery, PublishedReportQuery +from policyengine_api.services.v2.identity.types import AccountPrincipal +from policyengine_api.services.v2.published_reports.types import ( + PublicationRead, +) +from policyengine_api.services.v2.published_reports.validators import ( + PublishedReportNotFoundError, + PublishedReportStorageError, + PublishedVersionNotFoundError, +) +from policyengine_api.services.v2.stored_reports.budget_window_results.types import ( + BudgetWindowResultUnreadableError, +) +from policyengine_api.services.v2.stored_reports.economy_results.types import ( + EconomyResultUnreadableError, +) +from policyengine_api.services.v2.stored_reports.household_results.types import ( + HouseholdResultUnreadableError, +) +from policyengine_api.services.v2.stored_reports.validators import ( + ReportStorageError, +) + +# A page's content may hold 100 Markdown blocks of 20,000 characters each: +# up to 8 MB in UTF-8, or 12 MB as JSON that escapes every character outside +# ASCII (6 bytes each, outside supplementary planes), within this limit. +MAXIMUM_PUBLICATION_REQUEST_BYTES = 16 * 1024 * 1024 +enforce_publication_request_size = request_size_limit( + MAXIMUM_PUBLICATION_REQUEST_BYTES, label="16 MiB" +) + +# Every owner route's failures; each write adds its own. +PUBLICATION_ERROR_RESPONSES: dict[int | str, dict[str, Any]] = { + 401: USER_RESOURCE_ERROR_RESPONSES[401], + 403: { + "model": V2ErrorResponse, + "description": "Machine (client-credentials) principals are not permitted.", + }, + 404: { + "model": V2ErrorResponse, + "description": ( + "The saved report does not exist, belongs to another user, or is " + "not published." + ), + }, + 422: { + "model": V2ErrorResponse, + "description": "The ID, the query or the body does not match the schema.", + }, + 500: USER_RESOURCE_ERROR_RESPONSES[500], + 503: USER_RESOURCE_ERROR_RESPONSES[503], +} +_AUTHOR_REQUIRED = { + "model": V2ErrorResponse, + "description": ( + "Publishing, editing and moving a published report need an author or " + "admin; machine (client-credentials) principals are not permitted." + ), +} +_BODY_TOO_LARGE = { + "model": V2ErrorResponse, + "description": "The request body exceeds 16 MiB.", +} +PUBLISH_ERROR_RESPONSES: dict[int | str, dict[str, Any]] = { + 403: _AUTHOR_REQUIRED, + 404: { + "model": V2ErrorResponse, + "description": ( + "The saved report does not exist or belongs to another user, or " + "the run is not one of its report's runs." + ), + }, + 409: { + "model": V2ErrorResponse, + "description": ( + "The saved report is published already, names only a v1 report " + "output or has no name; or the run has not succeeded." + ), + }, + 413: _BODY_TOO_LARGE, +} +EDIT_ERROR_RESPONSES: dict[int | str, dict[str, Any]] = { + 403: _AUTHOR_REQUIRED, + 404: { + "model": V2ErrorResponse, + "description": ( + "The saved report does not exist, belongs to another user, or is " + "not published." + ), + }, + 413: _BODY_TOO_LARGE, +} +MOVE_ERROR_RESPONSES: dict[int | str, dict[str, Any]] = { + 403: _AUTHOR_REQUIRED, + 404: { + "model": V2ErrorResponse, + "description": ( + "The saved report does not exist, belongs to another user or is " + "not published, or the run is not one of its report's runs." + ), + }, + 409: { + "model": V2ErrorResponse, + "description": "The run has not succeeded, or the page has shown it already.", + }, + 413: _BODY_TOO_LARGE, +} + +PUBLISHED_REPORT_ERROR_RESPONSES: dict[int | str, dict[str, Any]] = { + 404: { + "model": V2ErrorResponse, + "description": ( + "No published report has this ID in this country, or it has no " + "version with version_id that readers may open." + ), + }, + 422: { + "model": V2ErrorResponse, + "description": "The ID or the query does not match the schema.", + }, + 500: { + "model": V2ErrorResponse, + "description": "The report's stored result cannot be read.", + }, + 503: { + "model": V2ErrorResponse, + "description": "V2 report storage is unavailable.", + }, +} +PUBLISHED_REPORT_REFUSALS: tuple[type[Exception], ...] = ( + PublishedReportNotFoundError, + PublishedVersionNotFoundError, +) +PUBLISHED_REPORT_ERROR_MAPPINGS = ( + V2ErrorMapping(PUBLISHED_REPORT_REFUSALS, 404), + V2ErrorMapping( + ( + EconomyResultUnreadableError, + HouseholdResultUnreadableError, + BudgetWindowResultUnreadableError, + ), + 500, + "The report's stored result cannot be read", + ), + V2ErrorMapping( + (PublishedReportStorageError, ReportStorageError, V2ConfigurationError), + 503, + "V2 report storage is unavailable", + ), +) + +CountryQueryDependency = Annotated[ + CountryQuery, Depends(query_dependency(CountryQuery)) +] +PublishedReportQueryDependency = Annotated[ + PublishedReportQuery, Depends(query_dependency(PublishedReportQuery)) +] + + +def _service_factory( + dependencies: NativeRouteDependencies, +) -> Callable[[], V2PublishedReportResourceService]: + if dependencies.v2_published_report_service_factory is not None: + return dependencies.v2_published_report_service_factory + return _default_v2_published_report_service_factory + + +def _user_type_service_factory( + dependencies: NativeRouteDependencies, +) -> Callable[[], V2UserTypeResourceService]: + if dependencies.v2_user_type_service_factory is not None: + return dependencies.v2_user_type_service_factory + return _default_v2_user_type_service_factory + + +def _publication_answer( + operation: Callable[[], PublicationRead], +) -> PublicationDetailResponse | JSONResponse: + """Run one owner operation and answer its published report, or its failure.""" + + def answered() -> PublicationDetailResponse: + return PublicationDetailResponse( + result=PublicationDetailResult(item=PublicationItem.from_read(operation())) + ) + + return user_resource_operation(answered) + + +def build_v2_user_report_publication_router( + dependencies: NativeRouteDependencies, +) -> APIRouter: + """Build the owner's publication routes without opening a connection. + + Authentication is a router-level dependency, so a missing or invalid + credential is refused before the author check, the query or the body. + """ + require_user = dependencies.require_user + require_author = minimum_user_type_dependency( + require_user, _user_type_service_factory(dependencies), UserType.AUTHOR + ) + router = APIRouter( + prefix="/v2", + responses=PUBLICATION_ERROR_RESPONSES, + dependencies=[ + Depends(require_user), + Depends(enforce_publication_request_size), + ], + ) + service_factory = _service_factory(dependencies) + path = "/user-reports/{association_id}/publication" + + @router.post( + path, + response_model=PublicationDetailResponse, + status_code=201, + dependencies=[Depends(require_author)], + responses=PUBLISH_ERROR_RESPONSES, + summary="Publish one of the current user's saved reports", + description=( + "Authors and admins only (403 below author). Publishes the saved " + "report as a public, read-only page, linked by the saved report's " + "ID (GET /v2/published-reports/{id}), showing the run run_id of " + "the detailed-save report it names: a report run of an economy or " + "household report, or a budget window's budget-window run, which " + "must have succeeded (409 otherwise; 404 for a run that isn't one " + "of the report's). The page's summary (1 to 300 characters), " + "author_ids (1 to 10 IDs from the website's authors.json) and tags " + "(up to 20 of the website's topic and location tags) show on its " + "card; content is an ordered list of at most 100 blocks, Markdown " + "(at most 20,000 characters each, rendered without raw HTML) or " + "an output card by v3's key, each card at most once; a card left " + "out is removed. With show_past_versions, readers may open the " + "page's earlier versions. A saved report is published once (409); " + "one that names only a v1 report output, or has no name, the " + "page's title, can't be (409). A published saved report can't be " + "repointed to another report until it is withdrawn, and deleting " + "it, or its owner's account, deletes the page." + ), + ) + def publish_report( + association_id: UUID, + body: PublicationCreateRequest, + query: CountryQueryDependency, + principal: Annotated[AccountPrincipal, Depends(require_user)], + ) -> PublicationDetailResponse | JSONResponse: + return _publication_answer( + lambda: service_factory().publish_report( + principal=principal, + country_id=query.country_id, + user_report_id=association_id, + publication_input=body, + ) + ) + + @router.get( + path, + response_model=PublicationDetailResponse, + summary="Read the current user's published report", + description=( + "Any owner, whatever their type. Returns the published report " + "with every version, newest first: the newest is the one the page " + "shows. 404 when the saved report isn't published." + ), + ) + def get_publication( + association_id: UUID, + query: CountryQueryDependency, + principal: Annotated[AccountPrincipal, Depends(require_user)], + ) -> PublicationDetailResponse | JSONResponse: + return _publication_answer( + lambda: service_factory().get_publication( + principal=principal, + country_id=query.country_id, + user_report_id=association_id, + ) + ) + + @router.patch( + path, + response_model=PublicationDetailResponse, + dependencies=[Depends(require_author)], + responses=EDIT_ERROR_RESPONSES, + summary="Edit the current user's published report", + description=( + "Authors and admins only (403 below author). Sets the fields " + "sent, checked as on publishing; none may be null, and the others " + "stay. The content is the whole page's, for every version." + ), + ) + def update_publication( + association_id: UUID, + body: PublicationPatchRequest, + query: CountryQueryDependency, + principal: Annotated[AccountPrincipal, Depends(require_user)], + ) -> PublicationDetailResponse | JSONResponse: + return _publication_answer( + lambda: service_factory().update_publication( + principal=principal, + country_id=query.country_id, + user_report_id=association_id, + publication_input=body, + ) + ) + + @router.delete( + path, + response_model=None, + status_code=204, + response_class=Response, + summary="Withdraw the current user's published report", + description=( + "Any owner, whatever their type, so an author who was demoted can " + "still withdraw it. Deletes the published report with its " + "versions; its public read answers 404 from then on. The saved " + "report stays." + ), + ) + def withdraw_publication( + association_id: UUID, + query: CountryQueryDependency, + principal: Annotated[AccountPrincipal, Depends(require_user)], + ) -> Response | JSONResponse: + def withdraw() -> Response: + service_factory().withdraw_publication( + principal=principal, + country_id=query.country_id, + user_report_id=association_id, + ) + return Response(status_code=204) + + return user_resource_operation(withdraw) + + @router.post( + f"{path}/versions", + response_model=PublicationDetailResponse, + status_code=201, + dependencies=[Depends(require_author)], + responses=MOVE_ERROR_RESPONSES, + summary="Move the current user's published report to another run", + description=( + "Authors and admins only (403 below author). The page shows the " + "run run_id of its report from now on, as its new version, which " + "must have succeeded (409 otherwise; 404 for a run that isn't one " + "of the report's) and which it hasn't shown before (409). Earlier " + "versions stay, and readers may open them while show_past_versions " + "is on. Running the report again never moves the page." + ), + ) + def add_publication_version( + association_id: UUID, + body: PublicationVersionRequest, + query: CountryQueryDependency, + principal: Annotated[AccountPrincipal, Depends(require_user)], + ) -> PublicationDetailResponse | JSONResponse: + return _publication_answer( + lambda: service_factory().add_publication_version( + principal=principal, + country_id=query.country_id, + user_report_id=association_id, + version_input=body, + ) + ) + + return router + + +def build_v2_published_report_router( + dependencies: NativeRouteDependencies, +) -> APIRouter: + """Build the credential-free read of a published report.""" + router = APIRouter(prefix="/v2", responses=PUBLISHED_REPORT_ERROR_RESPONSES) + service_factory = _service_factory(dependencies) + + @router.get( + "/published-reports/{user_report_id}", + response_model=PublishedReportDetailResponse, + summary="Read a published report", + description=( + "Needs no credential and never provisions a user. Returns the " + "published report by its saved report's ID: its 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 (every version while " + "show_past_versions, else only the newest), 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. Without version_id, the newest version " + "is read; version_id names one a reader may open (404 otherwise). " + "The owner, the owner's notes and the owner's saved-reform IDs " + "are left out." + ), + ) + def get_published_report( + user_report_id: UUID, + query: PublishedReportQueryDependency, + ) -> PublishedReportDetailResponse | JSONResponse: + def read() -> PublishedReportDetailResponse: + published = service_factory().get_published_report( + country_id=query.country_id, + user_report_id=user_report_id, + version_id=query.version_id, + ) + return PublishedReportDetailResponse( + result=PublishedReportDetailResult( + item=PublishedReportItem.from_read(published) + ) + ) + + return simulation_resource_operation( + read, + PUBLISHED_REPORT_ERROR_MAPPINGS, + refusals=PUBLISHED_REPORT_REFUSALS, + event="v2_published_report_read_failed", + fallback_message="V2 published report read failed", + ) + + return router diff --git a/policyengine_api/fastapi_routes/v2/routes.py b/policyengine_api/fastapi_routes/v2/routes.py index 2d598654b..6940bfc92 100644 --- a/policyengine_api/fastapi_routes/v2/routes.py +++ b/policyengine_api/fastapi_routes/v2/routes.py @@ -46,6 +46,10 @@ build_v2_metadata_parameter_router, ) from policyengine_api.fastapi_routes.v2.policies.routes import build_v2_policy_router +from policyengine_api.fastapi_routes.v2.published_reports.routes import ( + build_v2_published_report_router, + build_v2_user_report_publication_router, +) from policyengine_api.fastapi_routes.v2.reports.routes import build_v2_report_router from policyengine_api.fastapi_routes.v2.simulations.routes import ( build_v2_simulation_router, @@ -82,6 +86,8 @@ def build_v2_router( router.include_router(build_v2_admin_invitation_router(dependencies)) router.include_router(build_v2_user_report_router(dependencies)) router.include_router(build_v2_shared_report_router(dependencies)) + router.include_router(build_v2_user_report_publication_router(dependencies)) + router.include_router(build_v2_published_report_router(dependencies)) router.include_router(build_v2_user_simulation_router(dependencies)) router.include_router(build_v2_user_household_router(dependencies)) router.include_router(build_v2_user_policy_router(dependencies)) diff --git a/policyengine_api/fastapi_routes/v2/user_reports/routes.py b/policyengine_api/fastapi_routes/v2/user_reports/routes.py index c99bdc0c7..0b5f6784c 100644 --- a/policyengine_api/fastapi_routes/v2/user_reports/routes.py +++ b/policyengine_api/fastapi_routes/v2/user_reports/routes.py @@ -210,7 +210,10 @@ def read() -> UserReportPageResponse: "Updates the fields sent. A saved report that names a detailed-save " "report after the update, and whose report_id or last_run_at the " "request sends, answers last_run_at as the owner's newest request for " - "one of that report's runs through /v2/reports, or null." + "one of that report's runs through /v2/reports, or null. A published " + "saved report (/v2/user-reports/{id}/publication) can't name another " + "report, or have its name, the page's title, cleared, until the page " + "is withdrawn (409)." ), ) def patch_user_report_route( @@ -238,6 +241,10 @@ def patch() -> UserReportDetailResponse: status_code=204, response_class=Response, summary="Delete one of the current user's saved reports", + description=( + "Deletes the saved report; the detailed-save report it names stays. " + "A published saved report's public page is deleted with it." + ), ) def delete_user_report_route( association_id: UUID, diff --git a/policyengine_api/migration_registry.py b/policyengine_api/migration_registry.py index 6adf2da7e..ea4f0b58c 100644 --- a/policyengine_api/migration_registry.py +++ b/policyengine_api/migration_registry.py @@ -96,7 +96,13 @@ class RouteGroupConfig: ), RouteGroupConfig( name="report", - path_segments=("report", "reports", "user-reports", "shared-reports"), + path_segments=( + "report", + "reports", + "user-reports", + "shared-reports", + "published-reports", + ), db_entity="report", sim_flow="report", ), diff --git a/policyengine_api/query_parameters.py b/policyengine_api/query_parameters.py index 6172c0579..972b440f4 100644 --- a/policyengine_api/query_parameters.py +++ b/policyengine_api/query_parameters.py @@ -497,6 +497,23 @@ class ReportDetailQuery(CountryQuery): ) +class PublishedReportQuery(CountryQuery): + """Query contract for reading a published report in a country. + + ``version_id`` names the version to read: the newest, or an earlier one + while its author shows past versions. Without it, the newest is read. + """ + + version_id: ResourceId | None = Field( + default=None, + description=( + "The published report's version to read: its newest, or an " + "earlier one while its author shows past versions. Without it, " + "the newest." + ), + ) + + class ReportRunsQuery(CountryQuery): """Query contract for a report's runs in a country: listing or starting one.""" diff --git a/policyengine_api/services/v2/published_reports/__init__.py b/policyengine_api/services/v2/published_reports/__init__.py new file mode 100644 index 000000000..626f35c31 --- /dev/null +++ b/policyengine_api/services/v2/published_reports/__init__.py @@ -0,0 +1 @@ +"""Publishing saved reports as public pages, and reading them publicly.""" diff --git a/policyengine_api/services/v2/published_reports/database_connectors/__init__.py b/policyengine_api/services/v2/published_reports/database_connectors/__init__.py new file mode 100644 index 000000000..d914e9dcd --- /dev/null +++ b/policyengine_api/services/v2/published_reports/database_connectors/__init__.py @@ -0,0 +1 @@ +"""Database connectors for published reports, one module per operation.""" diff --git a/policyengine_api/services/v2/published_reports/database_connectors/creates.py b/policyengine_api/services/v2/published_reports/database_connectors/creates.py new file mode 100644 index 000000000..4bd7294bc --- /dev/null +++ b/policyengine_api/services/v2/published_reports/database_connectors/creates.py @@ -0,0 +1,55 @@ +"""Database inserts for published reports and their versions.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING, Any + +from policyengine_api.data.v2.models import PublishedReport, PublishedReportVersion + +if TYPE_CHECKING: + from datetime import datetime + from uuid import UUID + + from sqlmodel import Session + + from policyengine_api.services.v2.published_reports.types import PublishedRun + + +def create_publication( + session: Session, + *, + user_report_id: UUID, + report_id: UUID, + values: dict[str, Any], + published_at: datetime, +) -> PublishedReport: + """Insert the saved report's published report, with ``values`` as its fields.""" + publication = PublishedReport( + user_report_id=user_report_id, + report_id=report_id, + created_at=published_at, + updated_at=published_at, + **values, + ) + session.add(publication) + session.flush() + return publication + + +def create_publication_version( + session: Session, + *, + user_report_id: UUID, + run: PublishedRun, + published_at: datetime, +) -> PublishedReportVersion: + """Insert a version of the published report, showing ``run``.""" + version = PublishedReportVersion( + user_report_id=user_report_id, + report_run_id=run.report_run_id, + budget_window_run_id=run.budget_window_run_id, + created_at=published_at, + ) + session.add(version) + session.flush() + return version diff --git a/policyengine_api/services/v2/published_reports/database_connectors/deletes.py b/policyengine_api/services/v2/published_reports/database_connectors/deletes.py new file mode 100644 index 000000000..77f10f0c9 --- /dev/null +++ b/policyengine_api/services/v2/published_reports/database_connectors/deletes.py @@ -0,0 +1,30 @@ +"""Database deletes for published reports.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +from sqlalchemy import delete +from sqlmodel import col + +from policyengine_api.data.v2.models import PublishedReportVersion + +if TYPE_CHECKING: + from sqlmodel import Session + + from policyengine_api.data.v2.models import PublishedReport + + +def delete_publication(session: Session, publication: PublishedReport) -> None: + """Delete the published report's versions, then the published report. + + The versions' foreign key would delete them with it; deleting them + first leaves none behind where foreign keys aren't enforced. + """ + session.execute( + delete(PublishedReportVersion).where( + col(PublishedReportVersion.user_report_id) == publication.user_report_id + ) + ) + session.delete(publication) + session.flush() diff --git a/policyengine_api/services/v2/published_reports/database_connectors/reads.py b/policyengine_api/services/v2/published_reports/database_connectors/reads.py new file mode 100644 index 000000000..2f4a441a9 --- /dev/null +++ b/policyengine_api/services/v2/published_reports/database_connectors/reads.py @@ -0,0 +1,142 @@ +"""Database reads for published reports and the runs they show.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +from sqlalchemy import select +from sqlmodel import Session, col + +from policyengine_api.data.v2.models import ( + BudgetWindowRun, + PublishedReport, + PublishedReportVersion, + Report, + ReportRun, + UserReportAssociation, +) + +if TYPE_CHECKING: + from collections.abc import Sequence + from uuid import UUID + + from policyengine_api.data.v2.models import ReportRunStatus + + +def read_publication_row( + session: Session, *, user_report_id: UUID +) -> PublishedReport | None: + """Return the saved report's published report, or None.""" + return session.get(PublishedReport, user_report_id) + + +def lock_publication_row( + session: Session, *, user_report_id: UUID +) -> PublishedReport | None: + """Return the saved report's published report, locked until the transaction ends. + + An edit, a move and a withdrawal each lock it, so none of them changes a + page another has just withdrawn. + """ + return session.scalar( + select(PublishedReport) + .where(col(PublishedReport.user_report_id) == user_report_id) + .with_for_update() + ) + + +def read_published_report_rows( + session: Session, *, country_id: str, user_report_id: UUID +) -> tuple[PublishedReport, UserReportAssociation] | None: + """Return a published report of the country with its saved report, or None.""" + row = session.execute( + select(PublishedReport, UserReportAssociation) + .join( + UserReportAssociation, + col(UserReportAssociation.id) == col(PublishedReport.user_report_id), + ) + .where( + col(PublishedReport.user_report_id) == user_report_id, + col(UserReportAssociation.country_id) == country_id, + ) + ).one_or_none() + return None if row is None else (row[0], row[1]) + + +def read_publication_version_rows( + session: Session, *, user_report_id: UUID +) -> list[tuple[PublishedReportVersion, ReportRun | None]]: + """Return the published report's versions, newest first, each with its run. + + A version of an economy or household report comes with its report run; + a budget window's comes with None, for ``read_window_first_years``. + """ + rows = session.execute( + select(PublishedReportVersion, ReportRun) + .outerjoin( + ReportRun, + col(ReportRun.id) == col(PublishedReportVersion.report_run_id), + ) + .where(col(PublishedReportVersion.user_report_id) == user_report_id) + .order_by( + col(PublishedReportVersion.created_at).desc(), + col(PublishedReportVersion.id).desc(), + ) + ).all() + return [(row[0], row[1]) for row in rows] + + +def read_window_first_years( + session: Session, *, budget_window_run_ids: Sequence[UUID] +) -> dict[UUID, ReportRun]: + """Return each budget-window run's first year's report run, by window run. + + The simulation service creates every year of a window run on one set of + versions, so its first year's are the window run's. A window run with no + year is left out. + """ + if not budget_window_run_ids: + return {} + years = session.scalars( + select(ReportRun) + .where(col(ReportRun.budget_window_run_id).in_(budget_window_run_ids)) + .order_by(col(ReportRun.budget_window_run_id), col(ReportRun.year)) + ).all() + first_years: dict[UUID, ReportRun] = {} + for year in years: + if year.budget_window_run_id is not None: + first_years.setdefault(year.budget_window_run_id, year) + return first_years + + +def read_report_row(session: Session, *, report_id: UUID) -> Report | None: + """Return the report, or None.""" + return session.get(Report, report_id) + + +def read_report_run_status( + session: Session, *, report_id: UUID, run_id: UUID +) -> ReportRunStatus | None: + """Return the status of the report's own report run, or None. + + A year of a budget-window run is that window run's, not the report's. + """ + return session.scalar( + select(col(ReportRun.status)).where( + col(ReportRun.id) == run_id, + col(ReportRun.report_id) == report_id, + col(ReportRun.budget_window_run_id).is_(None), + ) + ) + + +def read_budget_window_run_status( + session: Session, *, report_id: UUID, run_id: UUID +) -> ReportRunStatus | None: + """Return the status of the report's budget-window run, or None.""" + return session.scalar( + select(col(BudgetWindowRun.status)).where( + col(BudgetWindowRun.id) == run_id, + col(BudgetWindowRun.report_id) == report_id, + ) + ) diff --git a/policyengine_api/services/v2/published_reports/database_connectors/updates.py b/policyengine_api/services/v2/published_reports/database_connectors/updates.py new file mode 100644 index 000000000..25276bca6 --- /dev/null +++ b/policyengine_api/services/v2/published_reports/database_connectors/updates.py @@ -0,0 +1,28 @@ +"""Database updates for published reports.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING, Any + +if TYPE_CHECKING: + from datetime import datetime + + from sqlmodel import Session + + from policyengine_api.data.v2.models import PublishedReport + + +def update_publication( + session: Session, + publication: PublishedReport, + *, + values: dict[str, Any], + updated_at: datetime, +) -> PublishedReport: + """Set ``values`` on the published report, changed at ``updated_at``.""" + for name, value in values.items(): + setattr(publication, name, value) + publication.updated_at = updated_at + session.add(publication) + session.flush() + return publication diff --git a/policyengine_api/services/v2/published_reports/database_session.py b/policyengine_api/services/v2/published_reports/database_session.py new file mode 100644 index 000000000..084272f92 --- /dev/null +++ b/policyengine_api/services/v2/published_reports/database_session.py @@ -0,0 +1,32 @@ +"""Database session lifetime management for v2 published-report services.""" + +from __future__ import annotations + +from contextlib import contextmanager +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from collections.abc import Iterator + + from sqlalchemy.orm import sessionmaker + from sqlmodel import Session + + +class PublishedReportDatabaseSession: + """Open read sessions and transactions for published-report services.""" + + def __init__(self, session_factory: sessionmaker[Session]) -> None: + """Use ``session_factory`` to open every session.""" + self._session_factory = session_factory + + @contextmanager + def read(self) -> Iterator[Session]: + """Yield a session for reads; nothing is committed.""" + with self._session_factory() as session: + yield session + + @contextmanager + def transaction(self) -> Iterator[Session]: + """Yield a session whose transaction commits on exit and rolls back on error.""" + with self._session_factory.begin() as session: + yield session diff --git a/policyengine_api/services/v2/published_reports/services.py b/policyengine_api/services/v2/published_reports/services.py new file mode 100644 index 000000000..47af6627e --- /dev/null +++ b/policyengine_api/services/v2/published_reports/services.py @@ -0,0 +1,509 @@ +"""Publish saved reports as public pages, and read them publicly. + +An author or admin publishes one of their saved reports, showing one +succeeded run of the report it names (a budget window's budget-window run), +with a summary, authors, tags and content of its own. The route requires the +user type; this service requires that the principal owns the saved report, +in the country, and never provisions a signed-out browser's user. The owner +edits the page's fields, moves it to another succeeded run of the report as +a new version, reads it with every version, and withdraws it, which deletes +it with its versions. A saved report is published at most once, and a page +shows each run at most once. + +Anyone reads a published report by its saved report's ID, with no +credential: the page, the saved report's presentation as a shared report +shows it, and the report with the run of its newest version, or of the +version the reader names while the author shows past versions. The report +is read as ``GET /v2/reports/{id}`` reads it for nobody, then labelled with +the saved report's name; the owner, the owner's notes and saved-reform IDs +are never read out. +""" + +from __future__ import annotations + +from contextlib import contextmanager +from typing import TYPE_CHECKING + +from sqlalchemy.exc import SQLAlchemyError + +from policyengine_api.data.v2.models.base import utc_now +from policyengine_api.services.v2.identity.services import ( + resolve_principal_user_for_read_in_session, +) +from policyengine_api.services.v2.published_reports.database_connectors import ( + reads as publication_reads, +) +from policyengine_api.services.v2.published_reports.database_connectors.creates import ( + create_publication, + create_publication_version, +) +from policyengine_api.services.v2.published_reports.database_connectors.deletes import ( + delete_publication, +) +from policyengine_api.services.v2.published_reports.database_connectors.updates import ( + update_publication, +) +from policyengine_api.services.v2.published_reports.transformations import ( + publication_read, + publication_update_values, + publication_values, + publication_version_read, + published_report_read, + published_run, + published_saved_report_read, +) +from policyengine_api.services.v2.published_reports.types import ShownVersions +from policyengine_api.services.v2.published_reports.validators import ( + PublicationNotFoundError, + PublishedReportNotFoundError, + PublishedReportStorageError, + readable_versions, + require_new_run, + require_publication, + require_publishable, + require_published_report, + require_readable_version, + require_report_row, + require_succeeded_run, + require_unpublished, + require_versions, +) +from policyengine_api.services.v2.stored_reports.transformations import report_kind +from policyengine_api.services.v2.user_reports.database_connectors.reads import ( + lock_owned_user_report_row, + read_owned_user_policy_row, + read_owned_user_report_row, +) +from policyengine_api.services.v2.user_reports.transformations import ( + shared_user_report_read, +) +from policyengine_api.services.v2.user_reports.validators import require_user_report + +if TYPE_CHECKING: + from collections.abc import Iterator + from uuid import UUID + + from sqlmodel import Session + + from policyengine_api.data.v2.models import ( + PublishedReport, + UserReportAssociation, + ) + from policyengine_api.services.v2.identity.types import AccountPrincipal + from policyengine_api.services.v2.published_reports.database_session import ( + PublishedReportDatabaseSession, + ) + from policyengine_api.services.v2.published_reports.types import ( + PublicationCreateInput, + PublicationRead, + PublicationUpdateInput, + PublicationVersionInput, + PublicationVersionRead, + PublishedReportRead, + PublishedReportReader, + PublishedRun, + ) + + +@contextmanager +def _storage_failures() -> Iterator[None]: + """Raise PublishedReportStorageError for a failed database read.""" + try: + yield + except SQLAlchemyError as error: + msg = "V2 report storage is unavailable" + raise PublishedReportStorageError(msg) from error + + +def _owned_user_report( + session: Session, + principal: AccountPrincipal, + *, + country_id: str, + user_report_id: UUID, + lock: bool = False, +) -> UserReportAssociation: + """Return the principal's saved report in the country, or raise not found. + + With ``lock``, the row stays locked until the transaction ends, as a + publish needs. A signed-out browser's user is never provisioned: one + not stored yet owns nothing. + """ + owner = resolve_principal_user_for_read_in_session( + session, principal, country_id=country_id + ) + if owner is None: + association = None + else: + read_saved_report = ( + lock_owned_user_report_row if lock else read_owned_user_report_row + ) + association = read_saved_report( + session, + user_id=owner.user_id, + country_id=country_id, + association_id=user_report_id, + ) + return require_user_report(association, association_id=user_report_id) + + +def _versions(session: Session, user_report_id: UUID) -> list[PublicationVersionRead]: + """Return the published report's versions, newest first, with their runs.""" + rows = publication_reads.read_publication_version_rows( + session, user_report_id=user_report_id + ) + window_first_years = publication_reads.read_window_first_years( + session, + budget_window_run_ids=[ + version.budget_window_run_id + for version, _report_run in rows + if version.budget_window_run_id is not None + ], + ) + return [ + publication_version_read(version, report_run, window_first_years) + for version, report_run in rows + ] + + +def _succeeded_run(session: Session, *, report_id: UUID, run_id: UUID) -> PublishedRun: + """Return the report's succeeded run ``run_id``, as a version names it. + + A budget window's runs are its budget-window runs; any other report's, + its own report runs. Raise PublicationRunNotFoundError when the report + has no such run, and PublicationRunNotSucceededError unless it has + succeeded. + """ + kind = report_kind( + require_report_row( + publication_reads.read_report_row(session, report_id=report_id), + report_id=report_id, + ) + ) + read_status = ( + publication_reads.read_budget_window_run_status + if kind == "budget_window" + else publication_reads.read_report_run_status + ) + require_succeeded_run( + read_status(session, report_id=report_id, run_id=run_id), + report_id=report_id, + run_id=run_id, + ) + return published_run(kind, run_id) + + +class V2PublishedReportService: + """Publish the owner's saved reports, and read published reports publicly.""" + + def __init__( + self, + database_session: PublishedReportDatabaseSession, + *, + reports: PublishedReportReader, + ) -> None: + """Open sessions through ``database_session``; read reports through ``reports``. + + ``reports`` reads a report with one of its runs, as the report + service does for ``GET /v2/reports/{id}``. + """ + self._database_session = database_session + self._reports = reports + + def _owned_page( + self, session: Session, publication: PublishedReport, *, country_id: str + ) -> PublicationRead: + """Return the owner's published report with its versions, as read now. + + Raise PublicationNotFoundError when it has none: it was withdrawn + between this read's statements. + """ + return publication_read( + publication, + country_id=country_id, + versions=require_versions( + _versions(session, publication.user_report_id), + missing=PublicationNotFoundError( + f"Saved report {publication.user_report_id} is not published" + ), + ), + ) + + def _owned_publication( + self, + session: Session, + principal: AccountPrincipal, + *, + country_id: str, + user_report_id: UUID, + lock: bool = False, + ) -> tuple[UserReportAssociation, PublishedReport]: + """Return the principal's saved report and its published report. + + With ``lock``, the published report stays locked until the transaction + ends, as an edit, a move and a withdrawal need. Raise + UserReportNotFoundError when the principal has no such saved report in + the country, and PublicationNotFoundError when it isn't published. + """ + association = _owned_user_report( + session, principal, country_id=country_id, user_report_id=user_report_id + ) + read_page = ( + publication_reads.lock_publication_row + if lock + else publication_reads.read_publication_row + ) + publication = require_publication( + read_page(session, user_report_id=user_report_id), + user_report_id=user_report_id, + ) + return association, publication + + def publish_report( + self, + *, + principal: AccountPrincipal, + country_id: str, + user_report_id: UUID, + publication_input: PublicationCreateInput, + ) -> PublicationRead: + """Publish the principal's saved report, showing the run the input names. + + Raise UserReportNotFoundError when the principal has no such saved + report in the country, UnpublishableUserReportError when it names + only a v1 report output or has no name, PublicationExistsError when + it is published already, PublicationRunNotFoundError when the run + isn't one of its report's runs, and PublicationRunNotSucceededError + unless the run has succeeded. + """ + with self._database_session.transaction() as session: + association = _owned_user_report( + session, + principal, + country_id=country_id, + user_report_id=user_report_id, + lock=True, + ) + report_id = require_publishable(association) + require_unpublished( + publication_reads.read_publication_row( + session, user_report_id=user_report_id + ), + user_report_id=user_report_id, + ) + run = _succeeded_run( + session, report_id=report_id, run_id=publication_input.run_id + ) + published_at = utc_now() + publication = create_publication( + session, + user_report_id=user_report_id, + report_id=report_id, + values=publication_values(publication_input), + published_at=published_at, + ) + create_publication_version( + session, + user_report_id=user_report_id, + run=run, + published_at=published_at, + ) + return publication_read( + publication, + country_id=country_id, + versions=_versions(session, user_report_id), + ) + + def get_publication( + self, + *, + principal: AccountPrincipal, + country_id: str, + user_report_id: UUID, + ) -> PublicationRead: + """Return the principal's published report with every version, newest first. + + Raise UserReportNotFoundError when the principal has no such saved + report in the country, and PublicationNotFoundError when it isn't + published. + """ + with self._database_session.transaction() as session: + _association, publication = self._owned_publication( + session, + principal, + country_id=country_id, + user_report_id=user_report_id, + ) + return self._owned_page(session, publication, country_id=country_id) + + def update_publication( + self, + *, + principal: AccountPrincipal, + country_id: str, + user_report_id: UUID, + publication_input: PublicationUpdateInput, + ) -> PublicationRead: + """Set the fields the edit sends on the principal's published report. + + Raise UserReportNotFoundError when the principal has no such saved + report in the country, and PublicationNotFoundError when it isn't + published. + """ + with self._database_session.transaction() as session: + _association, publication = self._owned_publication( + session, + principal, + country_id=country_id, + user_report_id=user_report_id, + lock=True, + ) + update_publication( + session, + publication, + values=publication_update_values(publication_input), + updated_at=utc_now(), + ) + return self._owned_page(session, publication, country_id=country_id) + + def add_publication_version( + self, + *, + principal: AccountPrincipal, + country_id: str, + user_report_id: UUID, + version_input: PublicationVersionInput, + ) -> PublicationRead: + """Move the principal's published report to another run, as its new version. + + Raise UserReportNotFoundError when the principal has no such saved + report in the country, PublicationNotFoundError when it isn't + published, PublicationRunAlreadyShownError when a version shows the + run, PublicationRunNotFoundError when the run isn't one of its + report's runs, and PublicationRunNotSucceededError unless the run + has succeeded. + """ + with self._database_session.transaction() as session: + _association, publication = self._owned_publication( + session, + principal, + country_id=country_id, + user_report_id=user_report_id, + lock=True, + ) + require_new_run( + require_versions( + _versions(session, user_report_id), + missing=PublicationNotFoundError( + f"Saved report {user_report_id} is not published" + ), + ), + run_id=version_input.run_id, + ) + run = _succeeded_run( + session, + report_id=publication.report_id, + run_id=version_input.run_id, + ) + moved_at = utc_now() + create_publication_version( + session, + user_report_id=user_report_id, + run=run, + published_at=moved_at, + ) + update_publication(session, publication, values={}, updated_at=moved_at) + return self._owned_page(session, publication, country_id=country_id) + + def withdraw_publication( + self, + *, + principal: AccountPrincipal, + country_id: str, + user_report_id: UUID, + ) -> None: + """Delete the principal's published report with its versions. + + Raise UserReportNotFoundError when the principal has no such saved + report in the country, and PublicationNotFoundError when it isn't + published. + """ + with self._database_session.transaction() as session: + _association, publication = self._owned_publication( + session, + principal, + country_id=country_id, + user_report_id=user_report_id, + lock=True, + ) + delete_publication(session, publication) + + def get_published_report( + self, + *, + country_id: str, + user_report_id: UUID, + version_id: UUID | None = None, + ) -> PublishedReportRead: + """Return a published report as anyone reads it, with no credential. + + Its run is its newest version's, or ``version_id``'s while the author + shows past versions. Raise PublishedReportNotFoundError when the + country has no such published report, PublishedVersionNotFoundError + when ``version_id`` names none of the versions a reader may open, and + PublishedReportStorageError when the database can't be read; reading + the report raises what the report service's read raises. + """ + with _storage_failures(), self._database_session.read() as session: + publication, association = require_published_report( + publication_reads.read_published_report_rows( + session, country_id=country_id, user_report_id=user_report_id + ), + user_report_id=user_report_id, + country_id=country_id, + ) + page = publication_read( + publication, + country_id=country_id, + versions=require_versions( + _versions(session, user_report_id), + missing=PublishedReportNotFoundError( + f"No published report {user_report_id} in {country_id}" + ), + ), + ) + baseline_user_policy_id = association.baseline_user_policy_id + saved_report = published_saved_report_read( + shared_user_report_read( + association, + baseline_reform=( + None + if baseline_user_policy_id is None + else read_owned_user_policy_row( + session, + user_id=association.user_id, + country_id=country_id, + user_policy_id=baseline_user_policy_id, + ) + ), + ) + ) + title = association.name + report_id = publication.report_id + readable = readable_versions( + page.versions, show_past_versions=page.show_past_versions + ) + version = require_readable_version(readable, version_id=version_id) + report = self._reports.get_report( + country_id=country_id, + report_id=report_id, + run_id=version.run_id, + requester=None, + ) + return published_report_read( + page, + title=title, + saved_report=saved_report, + shown=ShownVersions(version=version, readable=readable), + report=report, + ) diff --git a/policyengine_api/services/v2/published_reports/transformations.py b/policyengine_api/services/v2/published_reports/transformations.py new file mode 100644 index 000000000..2a408d0d6 --- /dev/null +++ b/policyengine_api/services/v2/published_reports/transformations.py @@ -0,0 +1,177 @@ +"""Conversions between published-report rows, inputs and reads.""" + +from __future__ import annotations + +from dataclasses import replace +from datetime import UTC, datetime +from typing import TYPE_CHECKING, Any + +from pydantic import TypeAdapter + +from policyengine_api.services.v2.published_reports.types import ( + ContentBlock, + MarkdownBlock, + OutputBlock, + PublicationRead, + PublicationVersionRead, + PublishedReportRead, + PublishedRun, + PublishedSavedReportRead, +) + +if TYPE_CHECKING: + from collections.abc import Mapping, Sequence + from uuid import UUID + + from policyengine_api.data.v2.models import ( + PublishedReport, + PublishedReportVersion, + ReportRun, + ) + from policyengine_api.services.v2.published_reports.types import ( + PublicationFields, + PublicationUpdateInput, + ShownVersions, + ) + from policyengine_api.services.v2.stored_reports.types import ( + ReportKind, + StoredReportRead, + ) + from policyengine_api.services.v2.user_reports.types import SharedUserReportRead + + +# Stored content is written from checked blocks; reading it back types it. +_STORED_CONTENT = TypeAdapter(list[ContentBlock]) + + +def stored_content(stored: list[dict[str, Any]]) -> list[MarkdownBlock | OutputBlock]: + """Return a published report's stored content as its blocks.""" + return _STORED_CONTENT.validate_python(stored) + + +def _aware(moment: datetime) -> datetime: + """Return a stored time in UTC; SQLite returns it without its zone.""" + return moment if moment.tzinfo is not None else moment.replace(tzinfo=UTC) + + +def publication_values(fields: PublicationFields) -> dict[str, Any]: + """Return a published report's column values from an author's fields.""" + return { + "summary": fields.summary, + "author_ids": list(fields.author_ids), + "tags": list(fields.tags), + "content": [block.model_dump() for block in fields.content], + "show_past_versions": fields.show_past_versions, + } + + +def publication_update_values(edit: PublicationUpdateInput) -> dict[str, Any]: + """Return the column values an edit sets: the fields it sends.""" + values = edit.model_dump(include=edit.model_fields_set) + if "content" in values: + values["content"] = [block.model_dump() for block in edit.content or []] + return values + + +def published_run(kind: ReportKind, run_id: UUID) -> PublishedRun: + """Return the run a version shows: a budget window's is a budget-window run.""" + if kind == "budget_window": + return PublishedRun(budget_window_run_id=run_id) + return PublishedRun(report_run_id=run_id) + + +def publication_version_read( + version: PublishedReportVersion, + report_run: ReportRun | None, + window_first_years: Mapping[UUID, ReportRun], +) -> PublicationVersionRead: + """Return a version with its run's versions. + + A report run's are its own; a budget-window run's are its first year's, + or none for a window run with no year. + """ + run_id = version.report_run_id or version.budget_window_run_id + if run_id is None: + msg = f"Published report version {version.id} names no run" + raise ValueError(msg) + versions_run = ( + report_run + if version.budget_window_run_id is None + else window_first_years.get(version.budget_window_run_id) + ) + return PublicationVersionRead( + id=version.id, + run_id=run_id, + country_package_version=( + None if versions_run is None else versions_run.country_package_version + ), + policyengine_version=( + None if versions_run is None else versions_run.policyengine_version + ), + published_at=_aware(version.created_at), + ) + + +def publication_read( + publication: PublishedReport, + *, + country_id: str, + versions: Sequence[PublicationVersionRead], +) -> PublicationRead: + """Return the published report as its owner reads it.""" + return PublicationRead( + user_report_id=publication.user_report_id, + country_id=country_id, + summary=publication.summary, + author_ids=list(publication.author_ids), + tags=list(publication.tags), + content=stored_content(publication.content), + show_past_versions=publication.show_past_versions, + versions=tuple(versions), + published_at=_aware(publication.created_at), + updated_at=_aware(publication.updated_at), + ) + + +def published_saved_report_read( + shared: SharedUserReportRead, +) -> PublishedSavedReportRead: + """Return the shared view's presentation fields a published report shows.""" + return PublishedSavedReportRead( + source_note=shared.source_note, + provisions=shared.provisions, + validation=shared.validation, + budget_window_years=shared.budget_window_years, + baseline_reform=shared.baseline_reform, + ) + + +def published_report_read( + page: PublicationRead, + *, + title: str | None, + saved_report: PublishedSavedReportRead, + shown: ShownVersions, + report: StoredReportRead, +) -> PublishedReportRead: + """Return the published report as anyone reads it. + + The report is labelled with the page's title, and shows none of the + owner's notes. + """ + return PublishedReportRead( + id=page.user_report_id, + country_id=page.country_id, + title=title, + summary=page.summary, + author_ids=page.author_ids, + tags=page.tags, + content=page.content, + show_past_versions=page.show_past_versions, + saved_report=saved_report, + version=shown.version, + versions=shown.readable, + published_at=page.published_at, + updated_at=page.updated_at, + report=replace(report, label=title, description=None), + ) diff --git a/policyengine_api/services/v2/published_reports/types.py b/policyengine_api/services/v2/published_reports/types.py new file mode 100644 index 000000000..b8b7c0b7e --- /dev/null +++ b/policyengine_api/services/v2/published_reports/types.py @@ -0,0 +1,338 @@ +"""Framework-independent data exchanged by the v2 published-report layers. + +A published report is a saved report its author published as a public +page. The page has a summary, authors, tags and content of its own, and +shows one succeeded run of the saved report's report: each run it has +shown is a version, and the newest is the one it shows. Authors are IDs +from the website's ``authors.json`` and tags the website's topic and +location tags, both lower-case words joined by hyphens, checked for form +only. The content is an ordered list of Markdown blocks and output-card +blocks; a card is named by a key v3 defines, and a card left out is +removed. +""" + +from __future__ import annotations + +from dataclasses import dataclass +from typing import TYPE_CHECKING, Annotated, Any, Literal, Protocol + +from pydantic import ( + AfterValidator, + BaseModel, + ConfigDict, + Field, + StrictBool, + StringConstraints, + model_validator, +) + +from policyengine_api.data.v2.models.published_reports import ( + MAXIMUM_PUBLISHED_SUMMARY_LENGTH, +) +from policyengine_api.query_parameters import ResourceId + +if TYPE_CHECKING: + from datetime import datetime + from uuid import UUID + + from policyengine_api.services.v2.identity.types import AccountPrincipal + from policyengine_api.services.v2.stored_reports.types import StoredReportRead + from policyengine_api.services.v2.user_reports.types import ( + SharedBaselineReformRead, + StoredJSONObject, + ) + +MAXIMUM_PUBLISHED_AUTHORS = 10 +MAXIMUM_PUBLISHED_TAGS = 20 +MAXIMUM_CONTENT_BLOCKS = 100 +MAXIMUM_MARKDOWN_LENGTH = 20_000 +MAXIMUM_NAME_LENGTH = 64 + +# An author or tag ID as the website writes them: lower-case letters and +# digits in words joined by single hyphens, such as ``nikhil-woodruff``. +WebsiteId = Annotated[ + str, + StringConstraints( + pattern=r"^[a-z0-9]+(?:-[a-z0-9]+)*$", max_length=MAXIMUM_NAME_LENGTH + ), +] +# An output card's key as v3 names it, such as ``budgetary_impact``. +OutputKey = Annotated[ + str, + StringConstraints(pattern=r"^[a-z][a-z0-9_]*$", max_length=MAXIMUM_NAME_LENGTH), +] + + +def _without_nul(text: str) -> str: + """Refuse a NUL character (U+0000), which PostgreSQL can't store in text.""" + if "\x00" in text: + msg = "Text can't hold a NUL character (U+0000)" + raise ValueError(msg) + return text + + +PublishedSummary = Annotated[ + str, + StringConstraints(min_length=1, max_length=MAXIMUM_PUBLISHED_SUMMARY_LENGTH), + AfterValidator(_without_nul), +] +AuthorIds = Annotated[ + list[WebsiteId], Field(min_length=1, max_length=MAXIMUM_PUBLISHED_AUTHORS) +] +Tags = Annotated[list[WebsiteId], Field(max_length=MAXIMUM_PUBLISHED_TAGS)] + + +class StrictPublicationModel(BaseModel): + """Reject fields outside the published-report contract.""" + + model_config = ConfigDict(extra="forbid") + + +class MarkdownBlock(StrictPublicationModel): + """A section of Markdown the author wrote, rendered without raw HTML.""" + + type: Literal["markdown"] + markdown: Annotated[ + str, + StringConstraints(min_length=1, max_length=MAXIMUM_MARKDOWN_LENGTH), + AfterValidator(_without_nul), + ] + + +class OutputBlock(StrictPublicationModel): + """One of the report's output cards, named by v3's key for it.""" + + type: Literal["output"] + output: OutputKey + + +ContentBlock = Annotated[MarkdownBlock | OutputBlock, Field(discriminator="type")] +Content = Annotated[list[ContentBlock], Field(max_length=MAXIMUM_CONTENT_BLOCKS)] + + +def _duplicates(values: list[str]) -> list[str]: + """Return the values that appear more than once, in first-seen order.""" + seen: set[str] = set() + repeated: list[str] = [] + for value in values: + if value in seen and value not in repeated: + repeated.append(value) + seen.add(value) + return repeated + + +def require_distinct( + *, + author_ids: list[str] | None, + tags: list[str] | None, + content: list[MarkdownBlock | OutputBlock] | None, +) -> None: + """Raise ValueError when an author, a tag or an output card repeats.""" + output_keys = [ + block.output for block in content or [] if isinstance(block, OutputBlock) + ] + for label, values in ( + ("author_ids", author_ids or []), + ("tags", tags or []), + ("output cards", output_keys), + ): + repeated = _duplicates(values) + if repeated: + msg = f"{label} may name each at most once; repeated: {repeated}" + raise ValueError(msg) + + +class PublicationFields(StrictPublicationModel): + """What a published report shows beside its run.""" + + summary: PublishedSummary + author_ids: AuthorIds + tags: Tags = Field(default_factory=list) + content: Content = Field(default_factory=list) + show_past_versions: StrictBool = False + + @model_validator(mode="after") + def _distinct(self) -> PublicationFields: + require_distinct( + author_ids=self.author_ids, tags=self.tags, content=self.content + ) + return self + + +class PublicationCreateInput(PublicationFields): + """A publication of a saved report: its fields and the run it shows. + + ``run_id`` is one of the report's runs: a report run of an economy or + household report, or a budget-window run of a budget window. + """ + + run_id: ResourceId + + +def _edit_schema(schema: dict[str, Any]) -> None: + """Show an edit's schema as the edit is checked. + + An edit sends at least one field, and may leave a field out but never + send it as null, so each field shows its type alone, without the null + alternative and null default its ``| None`` gives. + """ + schema["minProperties"] = 1 + for name, field in schema.get("properties", {}).items(): + alternatives = [ + alternative + for alternative in field.get("anyOf", []) + if alternative != {"type": "null"} + ] + shown = {key: value for key, value in field.items() if key != "anyOf"} + shown.pop("default", None) + if len(alternatives) == 1: + shown.update(alternatives[0]) + elif alternatives: + shown["anyOf"] = alternatives + schema["properties"][name] = shown + + +class PublicationUpdateInput(StrictPublicationModel): + """The fields of a published report an edit sends; the others stay. + + An edit sends at least one of them, and none as null. + """ + + model_config = ConfigDict(extra="forbid", json_schema_extra=_edit_schema) + + summary: PublishedSummary | None = None + author_ids: AuthorIds | None = None + tags: Tags | None = None + content: Content | None = None + show_past_versions: StrictBool | None = None + + @model_validator(mode="after") + def _checked(self) -> PublicationUpdateInput: + if not self.model_fields_set: + msg = "An edit sends at least one field" + raise ValueError(msg) + cleared = sorted( + name for name in self.model_fields_set if getattr(self, name) is None + ) + if cleared: + msg = f"{', '.join(cleared)} cannot be null" + raise ValueError(msg) + require_distinct( + author_ids=self.author_ids, tags=self.tags, content=self.content + ) + return self + + +class PublicationVersionInput(StrictPublicationModel): + """The run a published report moves to, as its new version.""" + + run_id: ResourceId + + +@dataclass(frozen=True) +class PublishedRun: + """The run a version shows: a report run or a budget-window run, never both.""" + + report_run_id: UUID | None = None + budget_window_run_id: UUID | None = None + + +@dataclass(frozen=True) +class PublicationVersionRead: + """One run a published report has shown, with the versions it ran on. + + ``run_id`` is a report run's or a budget-window run's ID; a budget-window + run recorded before its versions were has none. ``published_at`` is when + the page moved to the run. + """ + + id: UUID + run_id: UUID + country_package_version: str | None + policyengine_version: str | None + published_at: datetime + + +@dataclass(frozen=True) +class PublicationRead: + """A published report as its owner reads it, with every version, newest first. + + ``published_at`` is when it was first published, and ``updated_at`` when + any of it last changed. + """ + + user_report_id: UUID + country_id: str + summary: str + author_ids: list[str] + tags: list[str] + content: list[MarkdownBlock | OutputBlock] + show_past_versions: bool + versions: tuple[PublicationVersionRead, ...] + published_at: datetime + updated_at: datetime + + +@dataclass(frozen=True) +class ShownVersions: + """The version a reader reads, and the versions a reader may open, newest first.""" + + version: PublicationVersionRead + readable: tuple[PublicationVersionRead, ...] + + +@dataclass(frozen=True) +class PublishedSavedReportRead: + """The saved report's presentation a published report shows. + + The same as a shared report's, without its owner, its owner's notes or + its owner's saved-reform IDs; the reform it was compared with is named. + """ + + source_note: str | None + provisions: list[StoredJSONObject] | None + validation: StoredJSONObject | None + budget_window_years: int | None + baseline_reform: SharedBaselineReformRead | None + + +@dataclass(frozen=True) +class PublishedReportRead: + """A published report as anyone reads it. + + ``id`` is the saved report's ID, the page's link, and ``title`` the + saved report's name. ``version`` is the version read, and ``report`` + the report with that version's run, labelled with the title. + ``versions`` lists the versions a reader may open, newest first: every + version while the author shows past versions, else only the newest. + """ + + id: UUID + country_id: str + title: str | None + summary: str + author_ids: list[str] + tags: list[str] + content: list[MarkdownBlock | OutputBlock] + show_past_versions: bool + saved_report: PublishedSavedReportRead + version: PublicationVersionRead + versions: tuple[PublicationVersionRead, ...] + published_at: datetime + updated_at: datetime + report: StoredReportRead + + +class PublishedReportReader(Protocol): + """Read a report with one of its runs, as ``GET /v2/reports/{id}`` does.""" + + def get_report( + self, + *, + country_id: str, + report_id: UUID, + run_id: UUID | None = None, + requester: AccountPrincipal | None = None, + ) -> StoredReportRead: + """Return the country's report with its run ``run_id``.""" + ... diff --git a/policyengine_api/services/v2/published_reports/validators.py b/policyengine_api/services/v2/published_reports/validators.py new file mode 100644 index 000000000..62c7d4e66 --- /dev/null +++ b/policyengine_api/services/v2/published_reports/validators.py @@ -0,0 +1,203 @@ +"""Checks and typed errors for publishing saved reports and reading them publicly. + +The owner's errors extend the saved-item errors the user routes answer: not +found is 404 and a conflict with stored state 409. The public read's are its +own. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +from policyengine_api.data.v2.models import ReportRunStatus +from policyengine_api.services.v2.associations.validators import ( + AssociationConflictError, + AssociationNotFoundError, +) +from policyengine_api.services.v2.user_reports.validators import is_blank_name + +if TYPE_CHECKING: + from collections.abc import Sequence + from uuid import UUID + + from policyengine_api.data.v2.models import ( + PublishedReport, + Report, + UserReportAssociation, + ) + from policyengine_api.services.v2.published_reports.types import ( + PublicationVersionRead, + ) + + +class PublicationNotFoundError(AssociationNotFoundError): + """The owner's saved report is not published (404).""" + + +class PublicationExistsError(AssociationConflictError): + """The saved report is already published (409).""" + + +class UnpublishableUserReportError(AssociationConflictError): + """The saved report names no detailed-save report, or has no name (409).""" + + +class PublicationRunNotFoundError(AssociationNotFoundError): + """The run is not one of the saved report's report's runs (404).""" + + +class PublicationRunNotSucceededError(AssociationConflictError): + """The run has not succeeded, so it has no results to show (409).""" + + +class PublicationRunAlreadyShownError(AssociationConflictError): + """The published report has shown the run already (409).""" + + +class PublishedReportNotFoundError(LookupError): + """No published report has this ID in this country (404).""" + + +class PublishedVersionNotFoundError(LookupError): + """The published report has no version with this ID that readers may open (404).""" + + +class PublishedReportStorageError(RuntimeError): + """The database could not be read for a published report (503).""" + + +def require_publishable(association: UserReportAssociation) -> UUID: + """Return the detailed-save report a saved report names, if it can be published. + + Raise UnpublishableUserReportError for a saved report that names only a + v1 report output, or has no name, the page's title, or only blanks. + """ + if association.report_id is None: + msg = ( + f"Saved report {association.id} names only a v1 report output; " + "only a saved report of a detailed-save report can be published" + ) + raise UnpublishableUserReportError(msg) + if is_blank_name(association.name): + msg = ( + f"Saved report {association.id} has no name, which its published " + "page shows as its title; name it first" + ) + raise UnpublishableUserReportError(msg) + return association.report_id + + +def require_unpublished( + publication: PublishedReport | None, *, user_report_id: UUID +) -> None: + """Raise PublicationExistsError when the saved report is published.""" + if publication is not None: + msg = ( + f"Saved report {user_report_id} is already published; edit it, or " + "move it to another run as a new version" + ) + raise PublicationExistsError(msg) + + +def require_publication( + publication: PublishedReport | None, *, user_report_id: UUID +) -> PublishedReport: + """Return the saved report's publication, or raise PublicationNotFoundError.""" + if publication is None: + msg = f"Saved report {user_report_id} is not published" + raise PublicationNotFoundError(msg) + return publication + + +def require_report_row(report: Report | None, *, report_id: UUID) -> Report: + """Return the saved report's report, or raise PublicationRunNotFoundError. + + A saved report's foreign key keeps its report, so this is never None + unless the database was changed by hand. + """ + if report is None: + msg = f"Report {report_id} was not found, so it has no runs" + raise PublicationRunNotFoundError(msg) + return report + + +def require_succeeded_run( + status: ReportRunStatus | None, *, report_id: UUID, run_id: UUID +) -> None: + """Check a run's status, read from the report's own runs. + + Raise PublicationRunNotFoundError when the report has no such run (None), + and PublicationRunNotSucceededError unless it has succeeded. + """ + if status is None: + msg = f"Report {report_id} has no run {run_id}" + raise PublicationRunNotFoundError(msg) + if status is not ReportRunStatus.SUCCEEDED: + msg = ( + f"Run {run_id} is {status.value}; only a succeeded run, which has " + "results, can be published" + ) + raise PublicationRunNotSucceededError(msg) + + +def require_new_run( + versions: Sequence[PublicationVersionRead], *, run_id: UUID +) -> None: + """Raise PublicationRunAlreadyShownError when a version shows the run.""" + if any(version.run_id == run_id for version in versions): + msg = f"The published report has shown run {run_id} already" + raise PublicationRunAlreadyShownError(msg) + + +def require_published_report( + found: tuple[PublishedReport, UserReportAssociation] | None, + *, + user_report_id: UUID, + country_id: str, +) -> tuple[PublishedReport, UserReportAssociation]: + """Return a published report and its saved report, or raise not found.""" + if found is None: + msg = f"No published report {user_report_id} in {country_id}" + raise PublishedReportNotFoundError(msg) + return found + + +def require_versions( + versions: Sequence[PublicationVersionRead], *, missing: Exception +) -> Sequence[PublicationVersionRead]: + """Return a published report's versions, or raise ``missing`` when there are none. + + A published report always has a version; a read finds none only when the + page was withdrawn, or its saved report deleted, between its statements. + """ + if not versions: + raise missing + return versions + + +def readable_versions( + versions: Sequence[PublicationVersionRead], *, show_past_versions: bool +) -> tuple[PublicationVersionRead, ...]: + """Return the versions a reader may open, newest first. + + That is every version while the author shows past versions, else the + newest alone. ``versions`` is newest first, and never empty. + """ + return tuple(versions) if show_past_versions else (versions[0],) + + +def require_readable_version( + readable: Sequence[PublicationVersionRead], *, version_id: UUID | None +) -> PublicationVersionRead: + """Return the version to read: ``version_id``, else the newest. + + Raise PublishedVersionNotFoundError when ``version_id`` names none of + the versions a reader may open. + """ + if version_id is None: + return readable[0] + for version in readable: + if version.id == version_id: + return version + msg = f"The published report has no version {version_id} that readers may open" + raise PublishedVersionNotFoundError(msg) diff --git a/policyengine_api/services/v2/user_reports/database_connectors/reads.py b/policyengine_api/services/v2/user_reports/database_connectors/reads.py index d0a68bf23..f820bcfc6 100644 --- a/policyengine_api/services/v2/user_reports/database_connectors/reads.py +++ b/policyengine_api/services/v2/user_reports/database_connectors/reads.py @@ -35,6 +35,29 @@ def read_owned_user_report_row( ).one_or_none() +def lock_owned_user_report_row( + session: Session, + *, + user_id: UUID, + country_id: str, + association_id: UUID, +) -> UserReportAssociation | None: + """Return the user's association, locked (FOR UPDATE) until the transaction ends. + + A publish locks the same row, so an edit and a publish of one saved + report run one after the other. + """ + return session.exec( + select(UserReportAssociation) + .where( + UserReportAssociation.id == association_id, + UserReportAssociation.country_id == country_id, + UserReportAssociation.user_id == user_id, + ) + .with_for_update() + ).one_or_none() + + def read_user_report_row( session: Session, *, diff --git a/policyengine_api/services/v2/user_reports/services.py b/policyengine_api/services/v2/user_reports/services.py index 2c356065a..6a4024d6b 100644 --- a/policyengine_api/services/v2/user_reports/services.py +++ b/policyengine_api/services/v2/user_reports/services.py @@ -40,6 +40,9 @@ resolve_principal_user_in_session, ) from policyengine_api.services.v2.legacy_refs.types import LegacyRecordKind +from policyengine_api.services.v2.published_reports.database_connectors.reads import ( + read_publication_row, +) from policyengine_api.services.v2.report_run_records.database_connectors import ( reads as record_reads, ) @@ -50,6 +53,7 @@ delete_user_report, ) from policyengine_api.services.v2.user_reports.database_connectors.reads import ( + lock_owned_user_report_row, read_all_user_report_rows, read_owned_user_policy_exists, read_owned_user_policy_row, @@ -73,6 +77,7 @@ from policyengine_api.services.v2.user_reports.validators import ( require_matching_budget_window, require_owned_user_policy, + require_published_report_kept, require_stored_report, require_user_report, ) @@ -450,8 +455,11 @@ def patch_user_report( Raise AssociationReferenceConflictError when the update would leave the saved report naming both, AssociationBudgetWindowConflictError when it would leave a ``budget_window_years`` that disagrees with the - named report's budget window, and UserReportNotFoundError if the - principal has no such report in this country. A saved report that + named report's budget window, PublishedUserReportRepointError when it + would name another report for a published saved report, + PublishedUserReportNameRequiredError when it would clear a published + saved report's name, the page's title, and UserReportNotFoundError if + the principal has no such report in this country. A saved report that names a detailed-save report after the update, and whose ``report_id`` or ``last_run_at`` the update supplies, takes the owner's newest request for one of that report's runs as ``last_run_at``, or null. @@ -470,13 +478,27 @@ def patch_user_report( owner = resolve_principal_user_in_session( session, principal, country_id=country_id ) - association = read_owned_user_report( - session, - user_id=owner.user_id, - country_id=country_id, + # Locked, so a publish of this saved report, which locks it too, + # can't read its name or report while this changes them. + association = require_user_report( + lock_owned_user_report_row( + session, + user_id=owner.user_id, + country_id=country_id, + association_id=association_id, + ), association_id=association_id, ) require_one_report_after_update(association, association_input) + if {"report_id", "name"} & association_input.model_fields_set: + require_published_report_kept( + association=association, + association_input=association_input, + published=read_publication_row( + session, user_report_id=association.id + ) + is not None, + ) validate_stored_report( session, country_id=country_id, report_id=association_input.report_id ) diff --git a/policyengine_api/services/v2/user_reports/validators.py b/policyengine_api/services/v2/user_reports/validators.py index 6b1770a80..9b4cc403b 100644 --- a/policyengine_api/services/v2/user_reports/validators.py +++ b/policyengine_api/services/v2/user_reports/validators.py @@ -5,6 +5,7 @@ from typing import TYPE_CHECKING from policyengine_api.services.v2.associations.validators import ( + AssociationConflictError, AssociationLinkNotFoundError, AssociationNotFoundError, AssociationReferenceConflictError, @@ -14,6 +15,7 @@ from uuid import UUID from policyengine_api.data.v2.models import UserReportAssociation + from policyengine_api.services.v2.user_reports.types import UserReportUpdateInput class UserReportNotFoundError(AssociationNotFoundError): @@ -28,6 +30,14 @@ class AssociationBudgetWindowConflictError(AssociationReferenceConflictError): """A saved report's budget_window_years disagrees with the report it names.""" +class PublishedUserReportRepointError(AssociationConflictError): + """A published saved report can't name another report until withdrawn (409).""" + + +class PublishedUserReportNameRequiredError(AssociationConflictError): + """A published saved report's name is its page's title, so it stays set (409).""" + + # A saved report stores a window of one year as no window. SMALLEST_SAVED_BUDGET_WINDOW = 2 @@ -107,3 +117,41 @@ def require_owned_user_policy(*, owned: bool, user_policy_id: UUID) -> None: "user and country" ) raise AssociationLinkNotFoundError(msg) + + +def is_blank_name(name: str | None) -> bool: + """Return whether a saved report's name is missing or only blanks. + + A published report's title is its saved report's name, so such a name + can't be published or left on a published saved report. + """ + return not (name or "").strip() + + +def require_published_report_kept( + *, + association: UserReportAssociation, + association_input: UserReportUpdateInput, + published: bool, +) -> None: + """Refuse an update that would change what a published saved report's page shows. + + Raise PublishedUserReportRepointError when ``published`` and the update + names another report, and PublishedUserReportNameRequiredError when it + clears the name, the page's title, or leaves it only blanks. + """ + if not published: + return + supplied = association_input.model_fields_set + if "report_id" in supplied and association_input.report_id != association.report_id: + msg = ( + f"Saved report {association.id} is published, so it can't name " + "another report; withdraw its published page first" + ) + raise PublishedUserReportRepointError(msg) + if "name" in supplied and is_blank_name(association_input.name): + msg = ( + f"Saved report {association.id} is published, and its name is the " + "page's title; give it another name, or withdraw the page first" + ) + raise PublishedUserReportNameRequiredError(msg) diff --git a/pyproject.toml b/pyproject.toml index e9d31ad39..3c76122a4 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -284,6 +284,8 @@ ignore_imports = [ "policyengine_api.data.v2.models.policies -> sqlmodel", "policyengine_api.data.v2.models.policy_mappings -> sqlalchemy", "policyengine_api.data.v2.models.policy_mappings -> sqlmodel", + "policyengine_api.data.v2.models.published_reports -> sqlalchemy", + "policyengine_api.data.v2.models.published_reports -> sqlmodel", "policyengine_api.data.v2.models.reports -> sqlalchemy", "policyengine_api.data.v2.models.reports -> sqlmodel", "policyengine_api.data.v2.models.run_results -> sqlalchemy", @@ -422,6 +424,8 @@ banned-module-level-imports = [ "policyengine_api.services.v2.metadata.services", "policyengine_api.services.v2.policies.database_session", "policyengine_api.services.v2.policies.services", + "policyengine_api.services.v2.published_reports.database_session", + "policyengine_api.services.v2.published_reports.services", "policyengine_api.services.v2.report_run_records.database_session", "policyengine_api.services.v2.report_run_records.services", "policyengine_api.services.v2.simulation_service.services", diff --git a/rules/registry.toml b/rules/registry.toml index f4401b387..efa174f99 100644 --- a/rules/registry.toml +++ b/rules/registry.toml @@ -438,6 +438,8 @@ allowed_ignore_imports = [ "policyengine_api.data.v2.models.policies -> sqlmodel", "policyengine_api.data.v2.models.policy_mappings -> sqlalchemy", "policyengine_api.data.v2.models.policy_mappings -> sqlmodel", + "policyengine_api.data.v2.models.published_reports -> sqlalchemy", + "policyengine_api.data.v2.models.published_reports -> sqlmodel", "policyengine_api.data.v2.models.reports -> sqlalchemy", "policyengine_api.data.v2.models.reports -> sqlmodel", "policyengine_api.data.v2.models.run_results -> sqlalchemy", diff --git a/tests/integration/test_v2_published_reports.py b/tests/integration/test_v2_published_reports.py new file mode 100644 index 000000000..a0114f8f9 --- /dev/null +++ b/tests/integration/test_v2_published_reports.py @@ -0,0 +1,634 @@ +"""Published reports on migrated PostgreSQL, written and read as API v1's runtime role. + +An author publishes a saved report showing one succeeded run of its report, +moves the page to newer runs as versions and withdraws it; anyone reads it. +The database deletes a published report with its saved report, and so with +its owner's account, refuses to repoint a published saved report to another +report, and keeps every run a page has shown. The revision before this one +has none of the published-report tables. +""" + +from __future__ import annotations + +from dataclasses import replace +from datetime import timedelta +from typing import TYPE_CHECKING, Any +from uuid import UUID, uuid4 + +import pytest +from alembic import command +from sqlalchemy import delete, func, select, update +from sqlalchemy.exc import IntegrityError +from sqlmodel import col + +from policyengine_api.data.v2.models import ( + PublishedReport, + PublishedReportVersion, + ReportRun, + User, + UserReportAssociation, +) +from policyengine_api.data.v2.privileges import declared_privileges +from policyengine_api.services.v2.published_reports.database_session import ( + PublishedReportDatabaseSession, +) +from policyengine_api.services.v2.published_reports.services import ( + V2PublishedReportService, +) +from policyengine_api.services.v2.published_reports.types import ( + PublicationCreateInput, + PublicationUpdateInput, + PublicationVersionInput, +) +from policyengine_api.services.v2.stored_reports.database_session import ( + StoredReportDatabaseSession, +) +from policyengine_api.services.v2.stored_reports.services import V2StoredReportService +from policyengine_api.services.v2.user_reports.database_session import ( + UserReportDatabaseSession, +) +from policyengine_api.services.v2.user_reports.services import V2UserReportService +from policyengine_api.services.v2.user_reports.types import UserReportUpdateInput +from tests.fixtures.database_sessions import ( + grant_declared_v2_privileges, + recorded_statements, + schema_inspector, +) +from tests.fixtures.economy_results import us_economy_result +from tests.fixtures.integration.alembic_v2 import alembic_v2_config +from tests.integration.simulation_rows import add_row, refused +from tests.integration.stored_report_rows import ( + STARTED_AT, + BudgetWindowYear, + RunSettings, + delete_catalog, + store_budget_window_run, + store_catalog, + store_report, + store_report_run, +) +from tests.integration.user_report_run_support import ( + CURRENT_VERSIONS, + current_versions, + store_signed_in_user, +) + +if TYPE_CHECKING: + from collections.abc import Callable, Iterator + + from sqlalchemy.orm import sessionmaker + from sqlmodel import Session + + from policyengine_api.services.v2.identity.types import UserPrincipal + from tests.integration.conftest import ManagedV2Roles + from tests.integration.stored_report_rows import CatalogRows, StoredReport + +# The revision before the published-report tables: dropping dynamic_id. +PREVIOUS_REVISION = "1c651058fac5" +NEWER_VERSIONS = {**CURRENT_VERSIONS, "policyengine_version": "4.3.0"} +PUBLISHED_TABLES = ("published_reports", "published_report_versions") +PUBLISHED_REPORT_KEY = "fk_published_reports_user_report_report" + + +@pytest.fixture +def owner_sessions( + v2_owner_sessions: sessionmaker[Session], +) -> Iterator[sessionmaker[Session]]: + """Yield the owner's Session factories on a database at head; leave it at head.""" + command.upgrade(alembic_v2_config(), "head") + try: + yield v2_owner_sessions + finally: + command.upgrade(alembic_v2_config(), "head") + + +@pytest.fixture +def catalog(owner_sessions: sessionmaker[Session]) -> Iterator[CatalogRows]: + with owner_sessions.begin() as session: + stored = store_catalog(session, "us") + yield stored + with owner_sessions.begin() as session: + session.execute( + delete(UserReportAssociation).where( + col(UserReportAssociation.report_id).in_(stored.report_ids) + ) + ) + delete_catalog(session, stored) + + +@pytest.fixture +def runtime_sessions( + managed_v2_roles: ManagedV2Roles, + v2_sessions_as_role: Callable[[str], sessionmaker[Session]], +) -> sessionmaker[Session]: + return v2_sessions_as_role(managed_v2_roles.runtime) + + +@pytest.fixture +def author( + runtime_sessions: sessionmaker[Session], owner_sessions: sessionmaker[Session] +) -> Iterator[tuple[UserPrincipal, UUID]]: + principal, user_id = store_signed_in_user( + runtime_sessions, owner_sessions, user_type="author" + ) + yield principal, user_id + with owner_sessions.begin() as session: + session.execute(delete(User).where(col(User.id) == user_id)) + + +def _service(sessions: sessionmaker[Session]) -> V2PublishedReportService: + return V2PublishedReportService( + PublishedReportDatabaseSession(sessions), + reports=V2StoredReportService( + StoredReportDatabaseSession(sessions), current_versions=current_versions + ), + ) + + +def _store_run( + session: Session, + catalog: CatalogRows, + report: StoredReport, + *, + days_later: int = 0, + versions: dict[str, str] = CURRENT_VERSIONS, +) -> UUID: + return store_report_run( + session, + catalog, + report, + RunSettings( + versions=versions, + status="succeeded", + created_at=STARTED_AT + timedelta(days=days_later), + ), + result=us_economy_result(), + ).report_run_id + + +def _saved_report(session: Session, *, user_id: UUID, report_id: UUID) -> UUID: + saved_report_id = uuid4() + add_row( + session, + UserReportAssociation, + id=saved_report_id, + user_id=user_id, + report_id=report_id, + country_id="us", + name="Expanded child tax credit", + description="My own notes", + ) + return saved_report_id + + +def _publication_input(run_id: UUID) -> PublicationCreateInput: + return PublicationCreateInput.model_validate( + { + "run_id": str(run_id), + "summary": "What a larger child tax credit costs.", + "author_ids": ["nikhil-woodruff"], + "tags": ["us"], + "content": [{"type": "output", "output": "budgetary_impact"}], + } + ) + + +def _row_counts( + owner_sessions: sessionmaker[Session], user_report_id: UUID +) -> tuple[int, int]: + with owner_sessions() as session: + pages = session.scalar( + select(func.count()) + .select_from(PublishedReport) + .where(col(PublishedReport.user_report_id) == user_report_id) + ) + versions = session.scalar( + select(func.count()) + .select_from(PublishedReportVersion) + .where(col(PublishedReportVersion.user_report_id) == user_report_id) + ) + return int(pages or 0), int(versions or 0) + + +@pytest.fixture +def published( + owner_sessions: sessionmaker[Session], + runtime_sessions: sessionmaker[Session], + catalog: CatalogRows, + author: tuple[UserPrincipal, UUID], +) -> dict[str, Any]: + """Publish an author's saved report as the runtime role, with one run of it.""" + principal, user_id = author + with owner_sessions.begin() as session: + report = store_report(session, catalog) + run_id = _store_run(session, catalog, report) + newer_run_id = _store_run( + session, catalog, report, days_later=1, versions=NEWER_VERSIONS + ) + user_report_id = _saved_report( + session, user_id=user_id, report_id=report.report_id + ) + _service(runtime_sessions).publish_report( + principal=principal, + country_id="us", + user_report_id=user_report_id, + publication_input=_publication_input(run_id), + ) + return { + "principal": principal, + "user_id": user_id, + "report": report, + "run_id": run_id, + "newer_run_id": newer_run_id, + "user_report_id": user_report_id, + } + + +def test_an_author_publishes_moves_and_withdraws_a_page( + owner_sessions: sessionmaker[Session], + runtime_sessions: sessionmaker[Session], + published: dict[str, Any], +) -> None: + service = _service(runtime_sessions) + principal = published["principal"] + user_report_id = published["user_report_id"] + + first = service.get_published_report(country_id="us", user_report_id=user_report_id) + moved = service.add_publication_version( + principal=principal, + country_id="us", + user_report_id=user_report_id, + version_input=PublicationVersionInput(run_id=published["newer_run_id"]), + ) + service.update_publication( + principal=principal, + country_id="us", + user_report_id=user_report_id, + publication_input=PublicationUpdateInput(show_past_versions=True), + ) + newest = service.get_published_report( + country_id="us", user_report_id=user_report_id + ) + past = service.get_published_report( + country_id="us", + user_report_id=user_report_id, + version_id=moved.versions[1].id, + ) + service.withdraw_publication( + principal=principal, country_id="us", user_report_id=user_report_id + ) + + assert first.title == "Expanded child tax credit" + assert first.report.label == "Expanded child tax credit" + assert first.report.description is None + assert first.report.run is not None + assert first.report.run.id == published["run_id"] + assert first.report.result is not None + assert [version.policyengine_version for version in moved.versions] == [ + "4.3.0", + "4.2.0", + ] + assert newest.report.run is not None + assert newest.report.run.id == published["newer_run_id"] + assert past.report.run is not None + assert past.report.run.id == published["run_id"] + assert [version.run_id for version in past.versions] == [ + published["newer_run_id"], + published["run_id"], + ] + assert _row_counts(owner_sessions, user_report_id) == (0, 0) + + +def test_deleting_the_saved_report_deletes_its_page( + owner_sessions: sessionmaker[Session], + runtime_sessions: sessionmaker[Session], + published: dict[str, Any], +) -> None: + V2UserReportService(UserReportDatabaseSession(runtime_sessions)).delete_user_report( + principal=published["principal"], + country_id="us", + association_id=published["user_report_id"], + ) + + assert _row_counts(owner_sessions, published["user_report_id"]) == (0, 0) + + +def test_deleting_the_account_deletes_its_page( + owner_sessions: sessionmaker[Session], + runtime_sessions: sessionmaker[Session], + published: dict[str, Any], +) -> None: + # As the account deletion's connector deletes the user. + with runtime_sessions.begin() as session: + session.execute(delete(User).where(col(User.id) == published["user_id"])) + + assert _row_counts(owner_sessions, published["user_report_id"]) == (0, 0) + + +def test_the_database_refuses_to_repoint_a_published_saved_report( + owner_sessions: sessionmaker[Session], + runtime_sessions: sessionmaker[Session], + catalog: CatalogRows, + published: dict[str, Any], +) -> None: + with owner_sessions.begin() as session: + other_report_id = store_report(session, catalog).report_id + + with ( + runtime_sessions.begin() as session, + refused(session, IntegrityError, match=PUBLISHED_REPORT_KEY), + ): + session.execute( + update(UserReportAssociation) + .where(col(UserReportAssociation.id) == published["user_report_id"]) + .values(report_id=other_report_id) + ) + with ( + runtime_sessions.begin() as session, + refused(session, IntegrityError, match=PUBLISHED_REPORT_KEY), + ): + session.execute( + update(UserReportAssociation) + .where(col(UserReportAssociation.id) == published["user_report_id"]) + .values(report_id=None, legacy_report_id=615) + ) + with runtime_sessions.begin() as session: + session.execute( + update(UserReportAssociation) + .where(col(UserReportAssociation.id) == published["user_report_id"]) + .values(name="A new title") + ) + assert _row_counts(owner_sessions, published["user_report_id"]) == (1, 1) + + +def test_a_run_a_page_has_shown_cannot_be_deleted( + owner_sessions: sessionmaker[Session], published: dict[str, Any] +) -> None: + with ( + owner_sessions.begin() as session, + refused( + session, + IntegrityError, + match="fk_published_report_versions_report_run_id_report_runs", + ), + ): + session.execute( + delete(ReportRun).where(col(ReportRun.id) == published["run_id"]) + ) + + with owner_sessions() as session: + assert session.get(ReportRun, published["run_id"]) is not None + + +def test_a_second_page_or_a_second_version_of_one_run_is_refused( + owner_sessions: sessionmaker[Session], published: dict[str, Any] +) -> None: + """The keys hold a page per saved report and a run per page, behind the locks.""" + with ( + owner_sessions.begin() as session, + refused(session, IntegrityError, match="pk_published_reports"), + ): + add_row( + session, + PublishedReport, + user_report_id=published["user_report_id"], + report_id=published["report"].report_id, + summary="A second page", + author_ids=["nikhil-woodruff"], + tags=[], + content=[], + ) + with ( + owner_sessions.begin() as session, + refused( + session, + IntegrityError, + match="uq_published_report_versions_user_report_id_report_run_id", + ), + ): + add_row( + session, + PublishedReportVersion, + id=uuid4(), + user_report_id=published["user_report_id"], + report_run_id=published["run_id"], + ) + + assert _row_counts(owner_sessions, published["user_report_id"]) == (1, 1) + + +@pytest.mark.parametrize("runs", ["none", "both"]) +def test_a_version_names_exactly_one_run( + owner_sessions: sessionmaker[Session], + catalog: CatalogRows, + published: dict[str, Any], + runs: str, +) -> None: + with owner_sessions.begin() as session: + window_run_id = store_budget_window_run( + session, + catalog, + published["report"], + RunSettings( + versions=CURRENT_VERSIONS, status="succeeded", created_at=STARTED_AT + ), + ) + with ( + owner_sessions.begin() as session, + refused(session, IntegrityError, match="ck_published_report_versions_one_run"), + ): + add_row( + session, + PublishedReportVersion, + id=uuid4(), + user_report_id=published["user_report_id"], + report_run_id=None if runs == "none" else published["newer_run_id"], + budget_window_run_id=None if runs == "none" else window_run_id, + ) + + +def test_the_previous_revision_has_no_published_report_tables( + owner_sessions: sessionmaker[Session], + managed_v2_roles: ManagedV2Roles, + disposable_v2_database_url: str, +) -> None: + try: + command.downgrade(alembic_v2_config(), PREVIOUS_REVISION) + with owner_sessions() as session: + inspector = schema_inspector(session) + downgraded_tables = set(inspector.get_table_names()) + downgraded_unique = { + constraint["name"] + for constraint in inspector.get_unique_constraints( + "user_report_associations" + ) + } + finally: + # The upgrade creates the tables afresh, without the roles' grants. + command.upgrade(alembic_v2_config(), "head") + grant_declared_v2_privileges( + disposable_v2_database_url, + declared_privileges(managed_v2_roles.deployment_environment), + ) + with owner_sessions() as session: + inspector = schema_inspector(session) + upgraded_tables = set(inspector.get_table_names()) + upgraded_unique = { + constraint["name"] + for constraint in inspector.get_unique_constraints( + "user_report_associations" + ) + } + foreign_keys = { + key["name"]: ( + key["options"].get("ondelete"), + key["options"].get("onupdate"), + ) + for key in inspector.get_foreign_keys("published_reports") + } + + assert downgraded_tables.isdisjoint(PUBLISHED_TABLES) + assert "uq_user_report_associations_id_report_id" not in downgraded_unique + assert set(PUBLISHED_TABLES) <= upgraded_tables + assert "uq_user_report_associations_id_report_id" in upgraded_unique + assert foreign_keys == { + "fk_published_reports_user_report_report": ("CASCADE", "RESTRICT") + } + + +def _locks(statements: list[str], table: str) -> bool: + """Return whether a statement selected from ``table`` FOR UPDATE.""" + return any( + statement.lstrip().upper().startswith("SELECT") + and f"FROM {table}" in statement + and "FOR UPDATE" in statement + for statement in statements + ) + + +def test_writes_lock_the_rows_they_check( + runtime_sessions: sessionmaker[Session], published: dict[str, Any] +) -> None: + """Each write locks what it checks, so a concurrent write waits for it. + + A publish and a saved report's edit lock the saved report, so a name + can't be cleared while a publish reads it; an edit, a move and a + withdrawal lock the page, so none of them runs on a page another has + just withdrawn. + """ + service = _service(runtime_sessions) + principal = published["principal"] + user_report_id = published["user_report_id"] + owner_operations = { + "edit": lambda: service.update_publication( + principal=principal, + country_id="us", + user_report_id=user_report_id, + publication_input=PublicationUpdateInput(show_past_versions=True), + ), + "move": lambda: service.add_publication_version( + principal=principal, + country_id="us", + user_report_id=user_report_id, + version_input=PublicationVersionInput(run_id=published["newer_run_id"]), + ), + "withdraw": lambda: service.withdraw_publication( + principal=principal, country_id="us", user_report_id=user_report_id + ), + "publish": lambda: service.publish_report( + principal=principal, + country_id="us", + user_report_id=user_report_id, + publication_input=_publication_input(published["run_id"]), + ), + "rename": lambda: V2UserReportService( + UserReportDatabaseSession(runtime_sessions) + ).patch_user_report( + principal=principal, + country_id="us", + association_id=user_report_id, + association_input=UserReportUpdateInput(name="A new title"), + ), + } + locked: dict[str, tuple[bool, bool]] = {} + for name, operation in owner_operations.items(): + with recorded_statements(runtime_sessions) as statements: + operation() + locked[name] = ( + _locks(statements, "published_reports"), + _locks(statements, "user_report_associations"), + ) + + assert locked == { + "edit": (True, False), + "move": (True, False), + "withdraw": (True, False), + "publish": (False, True), + "rename": (False, True), + } + + +def test_a_budget_window_is_published_with_its_window_run( + owner_sessions: sessionmaker[Session], + runtime_sessions: sessionmaker[Session], + catalog: CatalogRows, + author: tuple[UserPrincipal, UUID], +) -> None: + principal, user_id = author + succeeded = RunSettings( + versions=CURRENT_VERSIONS, status="succeeded", created_at=STARTED_AT + ) + with owner_sessions.begin() as session: + window = store_report(session, catalog, budget_window_size=2) + window_run_id = store_budget_window_run(session, catalog, window, succeeded) + for year in (2026, 2027): + store_report_run( + session, + catalog, + window, + replace( + succeeded, + budget_window_year=BudgetWindowYear( + budget_window_run_id=window_run_id, year=year + ), + ), + result=us_economy_result(), + ) + user_report_id = _saved_report( + session, user_id=user_id, report_id=window.report_id + ) + + publication = _service(runtime_sessions).publish_report( + principal=principal, + country_id="us", + user_report_id=user_report_id, + publication_input=_publication_input(window_run_id), + ) + + assert [ + (version.run_id, version.policyengine_version) + for version in publication.versions + ] == [(window_run_id, CURRENT_VERSIONS["policyengine_version"])] + page = _service(runtime_sessions).get_published_report( + country_id="us", user_report_id=user_report_id + ) + assert page.report.kind == "budget_window" + assert page.report.label == "Expanded child tax credit" + assert page.report.run is not None + assert page.report.run.id == window_run_id + assert page.report.result is not None + with ( + owner_sessions.begin() as session, + refused( + session, + IntegrityError, + match="uq_published_report_versions_user_report_window_run", + ), + ): + add_row( + session, + PublishedReportVersion, + id=uuid4(), + user_report_id=user_report_id, + budget_window_run_id=window_run_id, + ) diff --git a/tests/unit/v2/published_report_support.py b/tests/unit/v2/published_report_support.py new file mode 100644 index 000000000..10f4dd473 --- /dev/null +++ b/tests/unit/v2/published_report_support.py @@ -0,0 +1,234 @@ +"""Rows and stand-ins for the published-report service tests on SQLite. + +SQLite doesn't enforce the v2 foreign keys here, so a test stores only the +rows a published report reads: the owner, the saved report, its report and +the report's runs. The PostgreSQL tests check the keys. +""" + +from __future__ import annotations + +from dataclasses import dataclass, field +from datetime import UTC, datetime, timedelta +from typing import TYPE_CHECKING, Any +from uuid import UUID, uuid4 + +from policyengine_api.data.v2.models import ( + BudgetWindowRun, + Report, + ReportRun, + ReportRunStatus, + UserPolicy, + UserReportAssociation, +) +from policyengine_api.services.v2.identity.services import ( + resolve_principal_user_in_session, +) +from policyengine_api.services.v2.identity.types import UserPrincipal +from policyengine_api.services.v2.published_reports.database_session import ( + PublishedReportDatabaseSession, +) +from policyengine_api.services.v2.published_reports.services import ( + V2PublishedReportService, +) +from tests.unit.v2.stored_report_support import report_read, report_run_read + +if TYPE_CHECKING: + from sqlalchemy.orm import sessionmaker + from sqlmodel import Session + + from policyengine_api.services.v2.stored_reports.types import StoredReportRead + +ISSUER = "https://auth.example.test/" +FINISHED_AT = datetime(2026, 11, 20, 9, tzinfo=UTC) +PROVISIONS = [ + { + "path": "gov.irs.credits.ctc.amount", + "breadcrumb": "Child Tax Credit amount", + "unit": "currency-USD", + "baseline_value": 2000, + "value": 3000, + } +] + + +def author_principal() -> UserPrincipal: + """Return a new signed-in user's principal.""" + return UserPrincipal(issuer=ISSUER, subject=f"auth0|{uuid4()}") + + +@dataclass +class RecordingReportReader: + """Answer each report read as the report service would, and record it.""" + + calls: list[dict[str, Any]] = field(default_factory=list) + + def get_report(self, **kwargs: Any) -> StoredReportRead: + self.calls.append(kwargs) + return report_read( + id=kwargs["report_id"], + country_id=kwargs["country_id"], + label=None, + run=report_run_read(id=kwargs["run_id"]), + ) + + +def published_report_service( + sessions: sessionmaker[Session], reports: RecordingReportReader | None = None +) -> V2PublishedReportService: + """Return the service on ``sessions``, reading reports through ``reports``.""" + return V2PublishedReportService( + PublishedReportDatabaseSession(sessions), + reports=RecordingReportReader() if reports is None else reports, + ) + + +@dataclass(frozen=True) +class SavedReportRows: + """A user's saved report of a stored report, and that user's principal.""" + + principal: UserPrincipal + user_id: UUID + user_report_id: UUID + report_id: UUID | None + + +def store_report(session: Session, *, budget_window_size: int | None = None) -> UUID: + """Store a US economy report, or a budget window, and return its ID.""" + report = Report( + country="us", + tax_benefit_model_id=uuid4(), + year=2026, + budget_window_size=budget_window_size, + inputs={}, + ) + session.add(report) + session.flush() + return report.id + + +def store_saved_report( # noqa: PLR0913 # the session, then each column a test varies + session: Session, + *, + principal: UserPrincipal | None = None, + report_id: UUID | None = None, + legacy_report_id: int | None = None, + name: str | None = "Expanded child tax credit", + country_id: str = "us", + baseline_reform_name: str | None = None, +) -> SavedReportRows: + """Save a report for the principal's user, provisioning that user.""" + owner = principal or author_principal() + user_id = resolve_principal_user_in_session( + session, owner, country_id=country_id + ).user_id + baseline_user_policy_id = None + if baseline_reform_name is not None: + baseline = UserPolicy( + user_id=user_id, + policy_id=uuid4(), + country_id=country_id, + name=baseline_reform_name, + ) + session.add(baseline) + session.flush() + baseline_user_policy_id = baseline.id + stored_report_id = ( + store_report(session) + if report_id is None and legacy_report_id is None + else report_id + ) + saved = UserReportAssociation( + user_id=user_id, + report_id=stored_report_id, + legacy_report_id=legacy_report_id, + country_id=country_id, + name=name, + description="My own notes", + source_note="From the chat", + provisions=PROVISIONS, + user_policy_id=uuid4(), + baseline_user_policy_id=baseline_user_policy_id, + last_run_at=FINISHED_AT, + ) + session.add(saved) + session.flush() + return SavedReportRows( + principal=owner, + user_id=user_id, + user_report_id=saved.id, + report_id=stored_report_id, + ) + + +def store_report_run( + session: Session, + report_id: UUID, + *, + status: ReportRunStatus = ReportRunStatus.SUCCEEDED, + days_later: int = 0, + budget_window_run_id: UUID | None = None, +) -> UUID: + """Store a run of the report on .py 4.2.0 and return its ID.""" + finished = status in {ReportRunStatus.SUCCEEDED, ReportRunStatus.FAILED} + created_at = FINISHED_AT + timedelta(days=days_later) + run = ReportRun( + report_id=report_id, + baseline_simulation_run_id=uuid4(), + reform_simulation_run_id=uuid4(), + budget_window_run_id=budget_window_run_id, + year=None if budget_window_run_id is None else 2026 + days_later, + country_package_version="1.5.0", + policyengine_version=f"4.{2 + days_later}.0", + status=status, + created_at=created_at, + completed_at=created_at if finished else None, + ) + session.add(run) + session.flush() + return run.id + + +def store_budget_window_run( + session: Session, + report_id: UUID, + *, + status: ReportRunStatus = ReportRunStatus.SUCCEEDED, +) -> UUID: + """Store a budget-window run of the report, with one year, and return its ID.""" + finished = status in {ReportRunStatus.SUCCEEDED, ReportRunStatus.FAILED} + window_run = BudgetWindowRun( + report_id=report_id, + tax_benefit_model_version_id=uuid4(), + policyengine_version="4.2.0", + status=status, + created_at=FINISHED_AT, + completed_at=FINISHED_AT if finished else None, + ) + session.add(window_run) + session.flush() + store_report_run( + session, report_id, status=status, budget_window_run_id=window_run.id + ) + return window_run.id + + +def publication_body(run_id: UUID, **changes: Any) -> dict[str, Any]: + """Return a publication's fields as an author sends them.""" + body: dict[str, Any] = { + "run_id": str(run_id), + "summary": "What a larger child tax credit costs and who gains.", + "author_ids": ["nikhil-woodruff"], + "tags": ["us", "child-tax-credit"], + "content": [ + {"type": "markdown", "markdown": "## Why this reform"}, + {"type": "output", "output": "budgetary_impact"}, + {"type": "output", "output": "poverty_impact"}, + ], + "show_past_versions": False, + } + return {**body, **changes} + + +def without_run(body: dict[str, Any]) -> dict[str, Any]: + """Return the publication's fields without its run.""" + return {key: value for key, value in body.items() if key != "run_id"} diff --git a/tests/unit/v2/test_metadata_routes.py b/tests/unit/v2/test_metadata_routes.py index 2eb17dd64..cbd2fa58a 100644 --- a/tests/unit/v2/test_metadata_routes.py +++ b/tests/unit/v2/test_metadata_routes.py @@ -360,7 +360,10 @@ def test_openapi_references_explicit_resource_response_schemas() -> None: "/v2/user-simulations/{association_id}", "/v2/user-reports", "/v2/user-reports/{association_id}", + "/v2/user-reports/{association_id}/publication", + "/v2/user-reports/{association_id}/publication/versions", "/v2/shared-reports/{association_id}", + "/v2/published-reports/{user_report_id}", "/v2/me", "/v2/me/export", "/v2/me/upgrade", diff --git a/tests/unit/v2/test_privilege_manifest.py b/tests/unit/v2/test_privilege_manifest.py index 6749cf762..9f724e5ee 100644 --- a/tests/unit/v2/test_privilege_manifest.py +++ b/tests/unit/v2/test_privilege_manifest.py @@ -599,3 +599,20 @@ def test_api_v1_saves_users_dynamics_as_it_saves_their_policies() -> None: for role, tables in declared.items(): if role != RUNTIME_ROLE: assert tables["user_dynamics"] == NO_ACCESS, role + + +def test_api_v1_publishes_saved_reports_and_never_rewrites_a_version() -> None: + """API v1 writes published reports and the runs each has shown. + + It changes and deletes a published report, and deletes its versions + when it is withdrawn, but never changes a version. No other role reads + them. + """ + declared = declared_privileges(TEST_ENVIRONMENT) + + assert declared[RUNTIME_ROLE]["published_reports"] == READ_WRITE + assert declared[RUNTIME_ROLE]["published_report_versions"] == (READ_INSERT_DELETE) + for role, tables in declared.items(): + if role != RUNTIME_ROLE: + assert tables["published_reports"] == NO_ACCESS, role + assert tables["published_report_versions"] == NO_ACCESS, role diff --git a/tests/unit/v2/test_published_report_inputs.py b/tests/unit/v2/test_published_report_inputs.py new file mode 100644 index 000000000..4b0e994f4 --- /dev/null +++ b/tests/unit/v2/test_published_report_inputs.py @@ -0,0 +1,157 @@ +"""What an author may send when publishing a saved report or editing its page. + +Authors and tags are IDs from the website's ``authors.json`` and tag lists, +checked for form only; output cards are named by keys v3 defines, each at +most once. A page holds at most 100 blocks, each Markdown block at most +20,000 characters, and a summary of 1 to 300 characters. +""" + +from __future__ import annotations + +from typing import Any +from uuid import uuid4 + +import pytest +from pydantic import ValidationError + +from policyengine_api.services.v2.published_reports.types import ( + PublicationCreateInput, + PublicationUpdateInput, +) +from tests.unit.v2.published_report_support import publication_body, without_run + + +def _markdown(text: str) -> dict[str, str]: + return {"type": "markdown", "markdown": text} + + +def _output(key: str) -> dict[str, str]: + return {"type": "output", "output": key} + + +def test_a_publication_takes_its_run_fields_and_content() -> None: + run_id = uuid4() + + publication = PublicationCreateInput.model_validate(publication_body(run_id)) + + assert publication.run_id == run_id + assert publication.author_ids == ["nikhil-woodruff"] + assert [block.model_dump() for block in publication.content] == [ + _markdown("## Why this reform"), + _output("budgetary_impact"), + _output("poverty_impact"), + ] + + +def test_tags_content_and_past_versions_have_defaults() -> None: + body = { + key: value + for key, value in publication_body(uuid4()).items() + if key not in {"tags", "content", "show_past_versions"} + } + + publication = PublicationCreateInput.model_validate(body) + + assert publication.tags == [] + assert publication.content == [] + assert publication.show_past_versions is False + + +def test_the_limits_themselves_are_accepted() -> None: + publication = PublicationCreateInput.model_validate( + publication_body( + uuid4(), + summary="s" * 300, + author_ids=[f"author-{number}" for number in range(10)], + tags=[f"tag-{number}" for number in range(20)], + content=[_markdown("m" * 20_000)] + + [_output(f"card_{number}") for number in range(99)], + ) + ) + + assert len(publication.content) == 100 + + +@pytest.mark.parametrize( + "changes", + [ + {"summary": ""}, + {"summary": "s" * 301}, + {"author_ids": []}, + {"author_ids": [f"author-{number}" for number in range(11)]}, + {"author_ids": ["Nikhil-Woodruff"]}, + {"author_ids": ["nikhil woodruff"]}, + {"author_ids": ["nikhil--woodruff"]}, + {"author_ids": ["nikhil-woodruff", "nikhil-woodruff"]}, + {"author_ids": ["a" * 65]}, + {"tags": [f"tag-{number}" for number in range(21)]}, + {"tags": ["us_ca"]}, + {"tags": ["us", "us"]}, + {"content": [_markdown("")]}, + {"summary": "A\x00summary"}, + {"content": [_markdown("Text with a \x00 in it")]}, + {"content": [_markdown("m" * 20_001)]}, + {"content": [_output("budgetary_impact")] * 2}, + {"content": [_output(f"card_{number}") for number in range(101)]}, + {"content": [_output("Budgetary_impact")]}, + {"content": [_output("1_budget")]}, + {"content": [_output("budgetary-impact")]}, + {"content": [_output("c" * 65)]}, + {"content": [{"type": "html", "html": ""}]}, + {"content": [{**_markdown("text"), "style": "bold"}]}, + {"show_past_versions": "yes"}, + {"run_id": "615"}, + {"owner_id": str(uuid4())}, + ], +) +def test_a_malformed_publication_is_refused(changes: dict[str, Any]) -> None: + with pytest.raises(ValidationError): + PublicationCreateInput.model_validate({**publication_body(uuid4()), **changes}) + + +def test_an_edit_takes_only_the_fields_sent() -> None: + edit = PublicationUpdateInput.model_validate( + {"tags": ["uk"], "content": [_markdown("New text")]} + ) + + assert edit.model_fields_set == {"tags", "content"} + assert edit.tags == ["uk"] + + +@pytest.mark.parametrize( + "field", ["summary", "author_ids", "tags", "content", "show_past_versions"] +) +def test_an_edit_cannot_clear_a_field(field: str) -> None: + with pytest.raises(ValidationError, match="cannot be null"): + PublicationUpdateInput.model_validate({field: None}) + + +@pytest.mark.parametrize( + "changes", + [ + {"author_ids": []}, + {"tags": ["us", "us"]}, + {"content": [_output("budgetary_impact")] * 2}, + {"run_id": str(uuid4())}, + ], +) +def test_an_edit_is_checked_as_a_publication_is(changes: dict[str, Any]) -> None: + with pytest.raises(ValidationError): + PublicationUpdateInput.model_validate(changes) + + +def test_an_edit_may_send_every_field_a_publication_has_but_its_run() -> None: + edit = PublicationUpdateInput.model_validate(without_run(publication_body(uuid4()))) + + assert edit.model_fields_set == { + "summary", + "author_ids", + "tags", + "content", + "show_past_versions", + } + + +def test_an_edit_sends_at_least_one_field() -> None: + with pytest.raises(ValidationError, match="at least one field"): + PublicationUpdateInput.model_validate({}) diff --git a/tests/unit/v2/test_published_report_routes.py b/tests/unit/v2/test_published_report_routes.py new file mode 100644 index 000000000..c7fc80d97 --- /dev/null +++ b/tests/unit/v2/test_published_report_routes.py @@ -0,0 +1,606 @@ +"""Routes that publish a saved report, and the public read of a published report. + +The owner's routes take a user credential. Publishing, editing and moving a +page to a newer run need author or above; reading the owner's page and +withdrawing it need only ownership. Anyone reads a published report, with no +credential, by its saved report's ID. +""" + +from __future__ import annotations + +from datetime import UTC, datetime, timedelta +from typing import Any +from uuid import UUID + +import pytest +from sqlalchemy.exc import IntegrityError + +from policyengine_api.data.v2.models import UserType +from policyengine_api.migration_flags import infer_route_group +from policyengine_api.services.v2.published_reports.types import ( + MarkdownBlock, + OutputBlock, + PublicationRead, + PublicationVersionRead, + PublishedReportRead, + PublishedSavedReportRead, +) +from policyengine_api.services.v2.published_reports.validators import ( + PublicationExistsError, + PublicationNotFoundError, + PublicationRunAlreadyShownError, + PublicationRunNotFoundError, + PublicationRunNotSucceededError, + PublishedReportNotFoundError, + PublishedReportStorageError, + PublishedVersionNotFoundError, + UnpublishableUserReportError, +) +from policyengine_api.services.v2.stored_reports.economy_results.types import ( + EconomyResultUnreadableError, +) +from policyengine_api.services.v2.user_reports.types import SharedBaselineReformRead +from policyengine_api.services.v2.user_reports.validators import ( + PublishedUserReportRepointError, + UserReportNotFoundError, +) +from policyengine_api.services.v2.user_types.validators import ( + UserTypeBelowMinimumError, +) +from tests.unit.v2.published_report_support import ( + PROVISIONS, + publication_body, + without_run, +) +from tests.unit.v2.stored_report_support import ( + FakeReportService, + report_read, + report_route_client, + report_run_read, +) +from tests.unit.v2.user_route_support import ( + PRINCIPAL, + RecordingService, + user_route_client, +) + +USER_REPORT_ID = UUID("00000000-0000-0000-0000-000000000063") +RUN_ID = UUID("00000000-0000-0000-0000-000000000064") +VERSION_ID = UUID("00000000-0000-0000-0000-000000000065") +PUBLICATION_PATH = f"/v2/user-reports/{USER_REPORT_ID}/publication" +PUBLIC_PATH = f"/v2/published-reports/{USER_REPORT_ID}" +PUBLISHED_AT = datetime(2026, 11, 28, 9, tzinfo=UTC) +CONTENT = [ + {"type": "markdown", "markdown": "## Why this reform"}, + {"type": "output", "output": "budgetary_impact"}, +] +CONTENT_BLOCKS = [ + MarkdownBlock(type="markdown", markdown="## Why this reform"), + OutputBlock(type="output", output="budgetary_impact"), +] +VERSION = PublicationVersionRead( + id=VERSION_ID, + run_id=RUN_ID, + country_package_version="1.5.0", + policyengine_version="4.2.0", + published_at=PUBLISHED_AT, +) +EXPECTED_VERSION = { + "id": str(VERSION_ID), + "run_id": str(RUN_ID), + "country_package_version": "1.5.0", + "policyengine_version": "4.2.0", + "published_at": "2026-11-28T09:00:00Z", +} + + +def _publication() -> PublicationRead: + return PublicationRead( + user_report_id=USER_REPORT_ID, + country_id="us", + summary="What a larger child tax credit costs.", + author_ids=["nikhil-woodruff"], + tags=["us"], + content=CONTENT_BLOCKS, + show_past_versions=False, + versions=(VERSION,), + published_at=PUBLISHED_AT, + updated_at=PUBLISHED_AT + timedelta(hours=1), + ) + + +EXPECTED_PUBLICATION = { + "user_report_id": str(USER_REPORT_ID), + "country_id": "us", + "summary": "What a larger child tax credit costs.", + "author_ids": ["nikhil-woodruff"], + "tags": ["us"], + "content": CONTENT, + "show_past_versions": False, + "versions": [EXPECTED_VERSION], + "published_at": "2026-11-28T09:00:00Z", + "updated_at": "2026-11-28T10:00:00Z", +} + + +def _published_report() -> PublishedReportRead: + return PublishedReportRead( + id=USER_REPORT_ID, + country_id="us", + title="Expanded child tax credit", + summary="What a larger child tax credit costs.", + author_ids=["nikhil-woodruff"], + tags=["us"], + content=CONTENT_BLOCKS, + show_past_versions=False, + saved_report=PublishedSavedReportRead( + source_note="From the chat", + provisions=PROVISIONS, + validation=None, + budget_window_years=None, + baseline_reform=SharedBaselineReformRead(name="Plan A"), + ), + version=VERSION, + versions=(VERSION,), + published_at=PUBLISHED_AT, + updated_at=PUBLISHED_AT + timedelta(hours=1), + report=report_read( + label="Expanded child tax credit", run=report_run_read(id=RUN_ID) + ), + ) + + +def _client( + publications: RecordingService | None = None, + user_types: RecordingService | None = None, + **client_options: Any, +): + publications = publications or RecordingService(_publication()) + user_types = user_types or RecordingService(UserType.AUTHOR) + client, _flask_calls = user_route_client( + v2_published_report_service_factory=lambda: publications, + v2_user_type_service_factory=lambda: user_types, + **client_options, + ) + return client, publications, user_types + + +AUTHOR_CHECK = ( + "require_minimum_user_type", + {"principal": PRINCIPAL, "minimum": UserType.AUTHOR}, +) + + +def test_an_author_publishes_a_saved_report() -> None: + client, publications, user_types = _client() + + response = client.post( + f"{PUBLICATION_PATH}?country_id=us", json=publication_body(RUN_ID) + ) + + assert response.status_code == 201 + assert response.json() == { + "status": "ok", + "message": None, + "result": {"item": EXPECTED_PUBLICATION}, + } + assert user_types.calls == [AUTHOR_CHECK] + ((method, arguments),) = publications.calls + assert method == "publish_report" + assert arguments["principal"] == PRINCIPAL + assert arguments["country_id"] == "us" + assert arguments["user_report_id"] == USER_REPORT_ID + assert arguments["publication_input"].run_id == RUN_ID + assert arguments["publication_input"].tags == ["us", "child-tax-credit"] + + +def test_the_author_edits_the_page_and_moves_it_to_another_run() -> None: + client, publications, user_types = _client() + + edited = client.patch( + f"{PUBLICATION_PATH}?country_id=us", json={"show_past_versions": True} + ) + moved = client.post( + f"{PUBLICATION_PATH}/versions?country_id=us", json={"run_id": str(RUN_ID)} + ) + + assert edited.status_code == 200 + assert edited.json()["result"]["item"] == EXPECTED_PUBLICATION + assert moved.status_code == 201 + assert moved.json()["result"]["item"] == EXPECTED_PUBLICATION + assert user_types.calls == [AUTHOR_CHECK, AUTHOR_CHECK] + assert [method for method, _arguments in publications.calls] == [ + "update_publication", + "add_publication_version", + ] + edit = publications.calls[0][1]["publication_input"] + assert edit.model_fields_set == {"show_past_versions"} + assert publications.calls[1][1]["version_input"].run_id == RUN_ID + + +@pytest.mark.parametrize( + ("method", "path", "body"), + [ + ("POST", PUBLICATION_PATH, publication_body(RUN_ID)), + ("PATCH", PUBLICATION_PATH, {"tags": []}), + ("POST", f"{PUBLICATION_PATH}/versions", {"run_id": str(RUN_ID)}), + ], +) +def test_publishing_editing_and_moving_need_author_or_above( + method: str, path: str, body: dict[str, Any] +) -> None: + user_types = RecordingService() + user_types.error = UserTypeBelowMinimumError("Only authors and admins may do this") + client, publications, _user_types = _client(user_types=user_types) + + response = client.request(method, f"{path}?country_id=us", json=body) + + assert response.status_code == 403 + assert response.json()["message"] == "Only authors and admins may do this" + assert publications.calls == [] + + +def test_the_owner_reads_and_withdraws_the_page_whatever_their_type() -> None: + client, publications, user_types = _client() + + read = client.get(f"{PUBLICATION_PATH}?country_id=us") + publications.next_result = None + withdrawn = client.delete(f"{PUBLICATION_PATH}?country_id=us") + + assert read.status_code == 200 + assert read.json()["result"]["item"] == EXPECTED_PUBLICATION + assert withdrawn.status_code == 204 + assert withdrawn.content == b"" + assert user_types.calls == [] + assert publications.calls == [ + ( + "get_publication", + { + "principal": PRINCIPAL, + "country_id": "us", + "user_report_id": USER_REPORT_ID, + }, + ), + ( + "withdraw_publication", + { + "principal": PRINCIPAL, + "country_id": "us", + "user_report_id": USER_REPORT_ID, + }, + ), + ] + + +@pytest.mark.parametrize( + ("method", "path"), + [ + ("POST", PUBLICATION_PATH), + ("GET", PUBLICATION_PATH), + ("PATCH", PUBLICATION_PATH), + ("DELETE", PUBLICATION_PATH), + ("POST", f"{PUBLICATION_PATH}/versions"), + ], +) +def test_the_owner_routes_need_a_credential(method: str, path: str) -> None: + client, publications, user_types = _client(require_user=None) + + response = client.request(method, f"{path}?country_id=us", json={}) + + assert response.status_code == 401 + assert publications.calls == [] + assert user_types.calls == [] + + +@pytest.mark.parametrize( + ("error", "status"), + [ + (UserReportNotFoundError("no saved report"), 404), + (PublicationNotFoundError("not published"), 404), + (PublicationRunNotFoundError("not one of its runs"), 404), + (PublicationExistsError("already published"), 409), + (UnpublishableUserReportError("names only a v1 report"), 409), + (PublicationRunNotSucceededError("still running"), 409), + (PublicationRunAlreadyShownError("already shown"), 409), + ], +) +def test_the_services_refusals_answer_their_status( + error: Exception, status: int +) -> None: + publications = RecordingService() + publications.error = error + client, _publications, _user_types = _client(publications) + + response = client.post( + f"{PUBLICATION_PATH}?country_id=us", json=publication_body(RUN_ID) + ) + + assert response.status_code == status + assert response.json()["message"] == str(error) + + +@pytest.mark.parametrize( + ("method", "path", "body"), + [ + ("POST", PUBLICATION_PATH, publication_body(RUN_ID, author_ids=["Ada"])), + ("POST", PUBLICATION_PATH, without_run(publication_body(RUN_ID))), + ("PATCH", PUBLICATION_PATH, {"summary": None}), + ("PATCH", PUBLICATION_PATH, {"run_id": str(RUN_ID)}), + ("POST", f"{PUBLICATION_PATH}/versions", {"run_id": "615"}), + ("POST", f"{PUBLICATION_PATH}/versions", {}), + ], +) +def test_a_malformed_body_is_refused( + method: str, path: str, body: dict[str, Any] +) -> None: + client, publications, _user_types = _client() + + response = client.request(method, f"{path}?country_id=us", json=body) + + assert response.status_code == 422 + assert publications.calls == [] + + +@pytest.mark.parametrize( + "query", + ["", "?country_id=xx", "?country_id=us&country_id=uk", "?country_id=us&user=1"], +) +def test_the_owner_routes_check_their_query(query: str) -> None: + client, publications, _user_types = _client() + + response = client.get(f"{PUBLICATION_PATH}{query}") + + assert response.status_code == 422 + assert publications.calls == [] + + +@pytest.mark.parametrize("character", ["m", "€"]) +def test_a_page_of_the_largest_allowed_size_is_accepted(character: str) -> None: + """The limits hold for Markdown of one-byte and three-byte characters.""" + client, publications, _user_types = _client() + content = [{"type": "markdown", "markdown": character * 20_000}] * 100 + + response = client.post( + f"{PUBLICATION_PATH}?country_id=us", + json=publication_body(RUN_ID, content=content), + ) + + assert response.status_code == 201 + assert len(publications.calls[0][1]["publication_input"].content) == 100 + + +def test_a_body_over_sixteen_mebibytes_is_refused() -> None: + client, publications, _user_types = _client() + + response = client.post( + f"{PUBLICATION_PATH}?country_id=us", + content=b"{" + b" " * (16 * 1024 * 1024) + b"}", + headers={"Content-Type": "application/json"}, + ) + + assert response.status_code == 413 + assert publications.calls == [] + + +def test_a_publication_the_database_refuses_answers_a_conflict() -> None: + """A write the database's keys refuse, behind the row locks, answers 409.""" + publications = RecordingService() + publications.error = IntegrityError( + "INSERT INTO published_report_versions", {}, Exception("duplicate key") + ) + client, _publications, _user_types = _client(publications) + + response = client.post( + f"{PUBLICATION_PATH}/versions?country_id=us", json={"run_id": str(RUN_ID)} + ) + + assert response.status_code == 409 + assert response.json()["message"] == "The record conflicts with stored state" + + +def test_repointing_a_published_saved_report_answers_a_conflict() -> None: + user_reports = RecordingService() + user_reports.error = PublishedUserReportRepointError( + "Withdraw the published report first" + ) + client, _flask_calls = user_route_client( + v2_user_report_service_factory=lambda: user_reports + ) + + response = client.patch( + f"/v2/user-reports/{USER_REPORT_ID}?country_id=us", + json={"report_id": str(RUN_ID)}, + ) + + assert response.status_code == 409 + assert response.json()["message"] == "Withdraw the published report first" + + +def _public_client(publications: RecordingService): + # The default authenticator fails closed: no credential is ever accepted. + client, _publications, user_types = _client(publications, require_user=None) + return client, user_types + + +def _report_as_its_route_answers(published: PublishedReportRead) -> dict[str, Any]: + """Return the report as GET /v2/reports/{id}?run_id= answers it.""" + response = report_route_client( + reports=FakeReportService(report=published.report) + ).get(f"/v2/reports/{published.report.id}?country_id=us&run_id={RUN_ID}") + assert response.status_code == 200 + item: dict[str, Any] = response.json()["result"]["item"] + return item + + +def test_anyone_reads_a_published_report_without_its_owner() -> None: + published = _published_report() + publications = RecordingService(published) + client, user_types = _public_client(publications) + + response = client.get(f"{PUBLIC_PATH}?country_id=us") + + assert response.status_code == 200 + assert response.json() == { + "status": "ok", + "message": None, + "result": { + "item": { + "id": str(USER_REPORT_ID), + "country_id": "us", + "title": "Expanded child tax credit", + "summary": "What a larger child tax credit costs.", + "author_ids": ["nikhil-woodruff"], + "tags": ["us"], + "content": CONTENT, + "show_past_versions": False, + "saved_report": { + "source_note": "From the chat", + "provisions": [{**PROVISIONS[0], "intervals": None}], + "validation": None, + "budget_window_years": None, + "baseline_reform": {"name": "Plan A"}, + }, + "version": EXPECTED_VERSION, + "versions": [EXPECTED_VERSION], + "published_at": "2026-11-28T09:00:00Z", + "updated_at": "2026-11-28T10:00:00Z", + "report": _report_as_its_route_answers(published), + } + }, + } + assert publications.calls == [ + ( + "get_published_report", + {"country_id": "us", "user_report_id": USER_REPORT_ID, "version_id": None}, + ) + ] + assert user_types.calls == [] + + +def test_a_reader_names_the_version_to_read() -> None: + publications = RecordingService(_published_report()) + client, _user_types = _public_client(publications) + + response = client.get(f"{PUBLIC_PATH}?country_id=us&version_id={VERSION_ID}") + + assert response.status_code == 200 + assert publications.calls[0][1]["version_id"] == VERSION_ID + + +@pytest.mark.parametrize( + "path", + [ + PUBLIC_PATH, + f"{PUBLIC_PATH}?country_id=xx", + f"{PUBLIC_PATH}?country_id=us&version_id=615", + f"{PUBLIC_PATH}?country_id=us&run_id={RUN_ID}", + f"{PUBLIC_PATH}?country_id=us&version_id={VERSION_ID}&version_id={RUN_ID}", + "/v2/published-reports/615?country_id=us", + ], +) +def test_the_public_read_checks_its_query_and_id(path: str) -> None: + publications = RecordingService(_published_report()) + client, _user_types = _public_client(publications) + + response = client.get(path) + + assert response.status_code == 422 + assert publications.calls == [] + + +@pytest.mark.parametrize( + ("error", "status", "message"), + [ + (PublishedReportNotFoundError("not published"), 404, "not published"), + (PublishedVersionNotFoundError("no such version"), 404, "no such version"), + ( + PublishedReportStorageError("down"), + 503, + "V2 report storage is unavailable", + ), + ( + EconomyResultUnreadableError("bad rows"), + 500, + "The report's stored result cannot be read", + ), + ], +) +def test_the_public_reads_failures_answer_their_status( + error: Exception, status: int, message: str +) -> None: + publications = RecordingService() + publications.error = error + client, _user_types = _public_client(publications) + + response = client.get(f"{PUBLIC_PATH}?country_id=us") + + assert response.status_code == status + assert response.json()["message"] == message + + +def test_published_reports_are_logged_with_reports() -> None: + assert infer_route_group(PUBLIC_PATH) == "report" + assert infer_route_group(PUBLICATION_PATH) == "report" + + +def test_openapi_documents_the_public_read_with_no_credential() -> None: + client, _publications, _user_types = _client() + + paths = client.get("/v2/openapi.json").json()["paths"] + + public = paths["/v2/published-reports/{user_report_id}"]["get"] + assert set(public["responses"]) == {"200", "404", "422", "500", "503"} + assert [ + (parameter["name"], parameter["in"]) for parameter in public["parameters"] + ] == [("user_report_id", "path"), ("country_id", "query"), ("version_id", "query")] + owner = paths["/v2/user-reports/{association_id}/publication"] + assert set(owner) == {"post", "get", "patch", "delete"} + assert set(paths["/v2/user-reports/{association_id}/publication/versions"]) == { + "post" + } + + +def test_openapi_lists_each_owner_routes_own_failures() -> None: + client, _publications, _user_types = _client() + + paths = client.get("/v2/openapi.json").json()["paths"] + publication = paths["/v2/user-reports/{association_id}/publication"] + versions = paths["/v2/user-reports/{association_id}/publication/versions"] + + for operation in (publication["post"], publication["patch"], versions["post"]): + assert set(operation["responses"]) >= {"401", "403", "404", "413"} + assert "author or admin" in operation["responses"]["403"]["description"] + publish_conflicts = publication["post"]["responses"]["409"]["description"] + move_conflicts = versions["post"]["responses"]["409"]["description"] + assert "published already" in publish_conflicts + assert "shown" not in publish_conflicts + assert "shown" in move_conflicts + assert "published already" not in move_conflicts + assert "409" not in publication["patch"]["responses"] + assert "run" not in publication["patch"]["responses"]["404"]["description"] + assert "run" in versions["post"]["responses"]["404"]["description"] + for operation in (publication["get"], publication["delete"]): + assert {"409", "413"}.isdisjoint(operation["responses"]) + assert "author" not in operation["responses"]["403"]["description"] + for operation in (*publication.values(), versions["post"]): + assert "400" not in operation["responses"] + assert "v1" not in operation["responses"]["422"]["description"] + + +def test_openapi_shows_no_edit_field_as_nullable() -> None: + client, _publications, _user_types = _client() + + schemas = client.get("/v2/openapi.json").json()["components"]["schemas"] + fields = schemas["PublicationPatchRequest"]["properties"] + + assert set(fields) == { + "summary", + "author_ids", + "tags", + "content", + "show_past_versions", + } + for name, field in fields.items(): + alternatives = field.get("anyOf", [field]) + assert {"type": "null"} not in alternatives, name + assert schemas["PublicationPatchRequest"]["minProperties"] == 1 diff --git a/tests/unit/v2/test_published_report_service.py b/tests/unit/v2/test_published_report_service.py new file mode 100644 index 000000000..a55283a89 --- /dev/null +++ b/tests/unit/v2/test_published_report_service.py @@ -0,0 +1,662 @@ +"""Publishing a saved report, and reading it publicly, on SQLite's copy of the schema. + +An author publishes one of their saved reports, showing one succeeded run of +its report; the page has a summary, authors, tags and content of its own, +and moves to newer runs as versions. Anyone reads the published page by the +saved report's ID, with the run of its newest version, or of an earlier one +when the author shows past versions. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING +from uuid import uuid4 + +import pytest + +from policyengine_api.data.v2.models import ( + PublishedReport, + ReportRun, + ReportRunStatus, + User, +) +from policyengine_api.services.v2.identity.types import UnauthenticatedPrincipal +from policyengine_api.services.v2.published_reports.types import ( + OutputBlock, + PublicationCreateInput, + PublicationUpdateInput, + PublicationVersionInput, +) +from policyengine_api.services.v2.published_reports.validators import ( + PublicationExistsError, + PublicationNotFoundError, + PublicationRunAlreadyShownError, + PublicationRunNotFoundError, + PublicationRunNotSucceededError, + PublishedReportNotFoundError, + PublishedVersionNotFoundError, + UnpublishableUserReportError, +) +from policyengine_api.services.v2.user_reports.database_session import ( + UserReportDatabaseSession, +) +from policyengine_api.services.v2.user_reports.services import V2UserReportService +from policyengine_api.services.v2.user_reports.types import UserReportUpdateInput +from policyengine_api.services.v2.user_reports.validators import ( + PublishedUserReportNameRequiredError, + PublishedUserReportRepointError, + UserReportNotFoundError, +) +from tests.fixtures.database_sessions import sqlite_v2_sessions +from tests.unit.v2.published_report_support import ( + PROVISIONS, + RecordingReportReader, + author_principal, + publication_body, + published_report_service, + store_budget_window_run, + store_report, + store_report_run, + store_saved_report, +) + +if TYPE_CHECKING: + from collections.abc import Iterator + from uuid import UUID + + from sqlalchemy.orm import sessionmaker + from sqlmodel import Session + + from policyengine_api.services.v2.published_reports.services import ( + V2PublishedReportService, + ) + from policyengine_api.services.v2.published_reports.types import PublicationRead + from tests.unit.v2.published_report_support import SavedReportRows + + +@pytest.fixture +def sessions() -> Iterator[sessionmaker[Session]]: + with sqlite_v2_sessions() as session_factory: + yield session_factory + + +def _publish( + service: V2PublishedReportService, + saved: SavedReportRows, + run_id: UUID, + **changes: object, +) -> PublicationRead: + return service.publish_report( + principal=saved.principal, + country_id="us", + user_report_id=saved.user_report_id, + publication_input=PublicationCreateInput.model_validate( + publication_body(run_id, **changes) + ), + ) + + +def _saved_report_with_run( + sessions: sessionmaker[Session], **saved_report_columns: object +) -> tuple[SavedReportRows, UUID]: + with sessions.begin() as session: + saved = store_saved_report(session, **saved_report_columns) + assert saved.report_id is not None + run_id = store_report_run(session, saved.report_id) + return saved, run_id + + +def _add_newer_run( + sessions: sessionmaker[Session], + saved: SavedReportRows, + *, + status: ReportRunStatus = ReportRunStatus.SUCCEEDED, +) -> UUID: + assert saved.report_id is not None + with sessions.begin() as session: + return store_report_run(session, saved.report_id, status=status, days_later=1) + + +def _move( + service: V2PublishedReportService, saved: SavedReportRows, run_id: UUID +) -> PublicationRead: + return service.add_publication_version( + principal=saved.principal, + country_id="us", + user_report_id=saved.user_report_id, + version_input=PublicationVersionInput(run_id=run_id), + ) + + +def test_an_author_publishes_a_succeeded_run_of_their_saved_report(sessions) -> None: + saved, run_id = _saved_report_with_run(sessions) + service = published_report_service(sessions) + + publication = _publish(service, saved, run_id) + + assert publication.user_report_id == saved.user_report_id + assert publication.country_id == "us" + assert publication.summary == "What a larger child tax credit costs and who gains." + assert publication.author_ids == ["nikhil-woodruff"] + assert publication.tags == ["us", "child-tax-credit"] + assert [block.model_dump() for block in publication.content] == [ + {"type": "markdown", "markdown": "## Why this reform"}, + {"type": "output", "output": "budgetary_impact"}, + {"type": "output", "output": "poverty_impact"}, + ] + assert publication.show_past_versions is False + assert [ + (version.run_id, version.country_package_version, version.policyengine_version) + for version in publication.versions + ] == [(run_id, "1.5.0", "4.2.0")] + assert publication.versions[0].published_at == publication.published_at + assert ( + service.get_publication( + principal=saved.principal, + country_id="us", + user_report_id=saved.user_report_id, + ) + == publication + ) + + +def test_a_budget_window_is_published_with_its_budget_window_run(sessions) -> None: + with sessions.begin() as session: + report_id = store_report(session, budget_window_size=10) + saved = store_saved_report(session, report_id=report_id) + window_run_id = store_budget_window_run(session, report_id) + service = published_report_service(sessions) + + publication = _publish(service, saved, window_run_id) + + assert [version.run_id for version in publication.versions] == [window_run_id] + assert publication.versions[0].policyengine_version == "4.2.0" + + +def test_a_budget_windows_year_is_not_one_of_its_runs_to_publish(sessions) -> None: + with sessions.begin() as session: + report_id = store_report(session, budget_window_size=10) + saved = store_saved_report(session, report_id=report_id) + window_run_id = store_budget_window_run(session, report_id) + year_run_id = store_report_run( + session, report_id, budget_window_run_id=window_run_id, days_later=1 + ) + + with pytest.raises(PublicationRunNotFoundError): + _publish(published_report_service(sessions), saved, year_run_id) + + +def test_a_run_of_another_report_is_refused(sessions) -> None: + saved, _run_id = _saved_report_with_run(sessions) + with sessions.begin() as session: + other_run_id = store_report_run(session, store_report(session)) + + with pytest.raises(PublicationRunNotFoundError): + _publish(published_report_service(sessions), saved, other_run_id) + + +@pytest.mark.parametrize( + "status", + [ReportRunStatus.PENDING, ReportRunStatus.RUNNING, ReportRunStatus.FAILED], +) +def test_a_run_that_has_not_succeeded_is_refused(sessions, status) -> None: + with sessions.begin() as session: + saved = store_saved_report(session) + assert saved.report_id is not None + run_id = store_report_run(session, saved.report_id, status=status) + + with pytest.raises(PublicationRunNotSucceededError): + _publish(published_report_service(sessions), saved, run_id) + + +def test_a_saved_report_naming_only_a_v1_report_cannot_be_published(sessions) -> None: + with sessions.begin() as session: + saved = store_saved_report(session, legacy_report_id=615) + + with pytest.raises(UnpublishableUserReportError, match="v1 report"): + _publish(published_report_service(sessions), saved, uuid4()) + + +@pytest.mark.parametrize("name", [None, "", " "]) +def test_a_saved_report_without_a_name_cannot_be_published(sessions, name) -> None: + saved, run_id = _saved_report_with_run(sessions, name=name) + + with pytest.raises(UnpublishableUserReportError, match="name"): + _publish(published_report_service(sessions), saved, run_id) + + +def test_another_users_saved_report_is_not_found(sessions) -> None: + saved, run_id = _saved_report_with_run(sessions) + service = published_report_service(sessions) + + with pytest.raises(UserReportNotFoundError): + service.publish_report( + principal=author_principal(), + country_id="us", + user_report_id=saved.user_report_id, + publication_input=PublicationCreateInput.model_validate( + publication_body(run_id) + ), + ) + with pytest.raises(UserReportNotFoundError): + service.publish_report( + principal=saved.principal, + country_id="uk", + user_report_id=saved.user_report_id, + publication_input=PublicationCreateInput.model_validate( + publication_body(run_id) + ), + ) + + +def test_a_saved_report_is_published_once(sessions) -> None: + saved, run_id = _saved_report_with_run(sessions) + service = published_report_service(sessions) + _publish(service, saved, run_id) + + with pytest.raises(PublicationExistsError): + _publish(service, saved, run_id) + + +def test_the_author_edits_the_fields_sent_and_keeps_the_others(sessions) -> None: + saved, run_id = _saved_report_with_run(sessions) + service = published_report_service(sessions) + published = _publish(service, saved, run_id) + + edited = service.update_publication( + principal=saved.principal, + country_id="us", + user_report_id=saved.user_report_id, + publication_input=PublicationUpdateInput.model_validate( + { + "summary": "A shorter summary.", + "content": [{"type": "output", "output": "budgetary_impact"}], + "show_past_versions": True, + } + ), + ) + + assert edited.summary == "A shorter summary." + assert edited.content == [OutputBlock(type="output", output="budgetary_impact")] + assert edited.show_past_versions is True + assert edited.author_ids == published.author_ids + assert edited.tags == published.tags + assert edited.versions == published.versions + assert edited.published_at == published.published_at + + +def test_editing_or_moving_an_unpublished_report_is_not_found(sessions) -> None: + saved, run_id = _saved_report_with_run(sessions) + service = published_report_service(sessions) + + with pytest.raises(PublicationNotFoundError): + service.update_publication( + principal=saved.principal, + country_id="us", + user_report_id=saved.user_report_id, + publication_input=PublicationUpdateInput.model_validate({"tags": []}), + ) + with pytest.raises(PublicationNotFoundError): + _move(service, saved, run_id) + with pytest.raises(PublicationNotFoundError): + service.get_publication( + principal=saved.principal, + country_id="us", + user_report_id=saved.user_report_id, + ) + + +def test_moving_to_a_newer_run_adds_a_version_newest_first(sessions) -> None: + saved, run_id = _saved_report_with_run(sessions) + service = published_report_service(sessions) + published = _publish(service, saved, run_id) + newer_run_id = _add_newer_run(sessions, saved) + + moved = _move(service, saved, newer_run_id) + + assert [ + (version.run_id, version.policyengine_version) for version in moved.versions + ] == [(newer_run_id, "4.3.0"), (run_id, "4.2.0")] + assert moved.versions[1] == published.versions[0] + assert moved.updated_at >= published.updated_at + assert moved.content == published.content + + +def test_moving_to_a_run_the_page_has_shown_is_refused(sessions) -> None: + saved, run_id = _saved_report_with_run(sessions) + service = published_report_service(sessions) + _publish(service, saved, run_id) + + with pytest.raises(PublicationRunAlreadyShownError): + _move(service, saved, run_id) + + +def test_moving_to_a_run_that_has_not_succeeded_is_refused(sessions) -> None: + saved, run_id = _saved_report_with_run(sessions) + service = published_report_service(sessions) + _publish(service, saved, run_id) + pending_run_id = _add_newer_run(sessions, saved, status=ReportRunStatus.PENDING) + + with pytest.raises(PublicationRunNotSucceededError): + _move(service, saved, pending_run_id) + + +def test_withdrawing_removes_the_page_and_it_can_be_published_again(sessions) -> None: + saved, run_id = _saved_report_with_run(sessions) + service = published_report_service(sessions) + _publish(service, saved, run_id) + + service.withdraw_publication( + principal=saved.principal, + country_id="us", + user_report_id=saved.user_report_id, + ) + + with pytest.raises(PublicationNotFoundError): + service.get_publication( + principal=saved.principal, + country_id="us", + user_report_id=saved.user_report_id, + ) + with pytest.raises(PublishedReportNotFoundError): + service.get_published_report( + country_id="us", user_report_id=saved.user_report_id + ) + with pytest.raises(PublicationNotFoundError): + service.withdraw_publication( + principal=saved.principal, + country_id="us", + user_report_id=saved.user_report_id, + ) + republished = _publish(service, saved, run_id) + assert [version.run_id for version in republished.versions] == [run_id] + + +def test_only_the_owner_withdraws_a_page(sessions) -> None: + saved, run_id = _saved_report_with_run(sessions) + service = published_report_service(sessions) + _publish(service, saved, run_id) + + with pytest.raises(UserReportNotFoundError): + service.withdraw_publication( + principal=author_principal(), + country_id="us", + user_report_id=saved.user_report_id, + ) + assert service.get_published_report( + country_id="us", user_report_id=saved.user_report_id + ) + + +def test_anyone_reads_the_page_with_its_newest_run_and_no_owner(sessions) -> None: + saved, run_id = _saved_report_with_run(sessions, baseline_reform_name="Plan A") + reports = RecordingReportReader() + service = published_report_service(sessions, reports) + published = _publish(service, saved, run_id) + + page = service.get_published_report( + country_id="us", user_report_id=saved.user_report_id + ) + + assert page.id == saved.user_report_id + assert page.country_id == "us" + assert page.title == "Expanded child tax credit" + assert page.summary == published.summary + assert page.author_ids == published.author_ids + assert page.tags == published.tags + assert page.content == published.content + assert page.show_past_versions is False + assert page.saved_report.source_note == "From the chat" + assert page.saved_report.provisions == PROVISIONS + assert page.saved_report.budget_window_years is None + assert page.saved_report.baseline_reform is not None + assert page.saved_report.baseline_reform.name == "Plan A" + assert page.version == published.versions[0] + assert page.versions == published.versions + assert page.published_at == published.published_at + assert reports.calls == [ + { + "country_id": "us", + "report_id": saved.report_id, + "run_id": run_id, + "requester": None, + } + ] + # The report reads with the saved report's name and none of its notes. + assert page.report.label == "Expanded child tax credit" + assert page.report.description is None + assert page.report.run is not None + assert page.report.run.id == run_id + + +def test_past_versions_are_readable_only_while_the_author_shows_them(sessions) -> None: + saved, run_id = _saved_report_with_run(sessions) + reports = RecordingReportReader() + service = published_report_service(sessions, reports) + first_version = _publish(service, saved, run_id).versions[0] + newer_run_id = _add_newer_run(sessions, saved) + moved = _move(service, saved, newer_run_id) + + hidden = service.get_published_report( + country_id="us", user_report_id=saved.user_report_id + ) + with pytest.raises(PublishedVersionNotFoundError): + service.get_published_report( + country_id="us", + user_report_id=saved.user_report_id, + version_id=first_version.id, + ) + service.update_publication( + principal=saved.principal, + country_id="us", + user_report_id=saved.user_report_id, + publication_input=PublicationUpdateInput(show_past_versions=True), + ) + past = service.get_published_report( + country_id="us", + user_report_id=saved.user_report_id, + version_id=first_version.id, + ) + + assert hidden.version.run_id == newer_run_id + assert hidden.versions == (moved.versions[0],) + assert past.version == first_version + assert past.versions == moved.versions + assert past.report.run is not None + assert past.report.run.id == run_id + assert [call["run_id"] for call in reports.calls] == [newer_run_id, run_id] + + +def test_the_newest_version_is_readable_by_its_id(sessions) -> None: + saved, run_id = _saved_report_with_run(sessions) + service = published_report_service(sessions) + newest = _publish(service, saved, run_id).versions[0] + + page = service.get_published_report( + country_id="us", user_report_id=saved.user_report_id, version_id=newest.id + ) + + assert page.version == newest + + +def test_a_version_of_no_page_is_not_found(sessions) -> None: + saved, run_id = _saved_report_with_run(sessions) + service = published_report_service(sessions) + _publish(service, saved, run_id, show_past_versions=True) + + with pytest.raises(PublishedVersionNotFoundError): + service.get_published_report( + country_id="us", user_report_id=saved.user_report_id, version_id=uuid4() + ) + + +def test_an_unpublished_or_other_countrys_page_is_not_found(sessions) -> None: + saved, run_id = _saved_report_with_run(sessions) + service = published_report_service(sessions) + + with pytest.raises(PublishedReportNotFoundError): + service.get_published_report( + country_id="us", user_report_id=saved.user_report_id + ) + _publish(service, saved, run_id) + with pytest.raises(PublishedReportNotFoundError): + service.get_published_report( + country_id="uk", user_report_id=saved.user_report_id + ) + + +def test_a_published_saved_report_cannot_be_repointed(sessions) -> None: + saved, run_id = _saved_report_with_run(sessions) + _publish(published_report_service(sessions), saved, run_id) + with sessions.begin() as session: + other_report_id = store_report(session) + user_reports = V2UserReportService(UserReportDatabaseSession(sessions)) + + with pytest.raises(PublishedUserReportRepointError): + user_reports.patch_user_report( + principal=saved.principal, + country_id="us", + association_id=saved.user_report_id, + association_input=UserReportUpdateInput(report_id=other_report_id), + ) + renamed = user_reports.patch_user_report( + principal=saved.principal, + country_id="us", + association_id=saved.user_report_id, + association_input=UserReportUpdateInput( + name="A new title", report_id=saved.report_id + ), + ) + + assert renamed.name == "A new title" + assert renamed.report_id == saved.report_id + + +def test_an_unpublished_saved_report_can_be_repointed(sessions) -> None: + saved, _run_id = _saved_report_with_run(sessions) + with sessions.begin() as session: + other_report_id = store_report(session) + + repointed = V2UserReportService( + UserReportDatabaseSession(sessions) + ).patch_user_report( + principal=saved.principal, + country_id="us", + association_id=saved.user_report_id, + association_input=UserReportUpdateInput(report_id=other_report_id), + ) + + assert repointed.report_id == other_report_id + + +def test_a_succeeded_forced_run_can_be_published(sessions) -> None: + saved, _run_id = _saved_report_with_run(sessions) + assert saved.report_id is not None + with sessions.begin() as session: + forced_run_id = store_report_run(session, saved.report_id, days_later=1) + forced_run = session.get(ReportRun, forced_run_id) + assert forced_run is not None + forced_run.forced = True + + publication = _publish(published_report_service(sessions), saved, forced_run_id) + + assert [version.run_id for version in publication.versions] == [forced_run_id] + + +def test_a_page_read_with_no_versions_is_not_found(sessions) -> None: + """A withdrawal committed between a read's statements leaves it no versions.""" + saved, _run_id = _saved_report_with_run(sessions) + with sessions.begin() as session: + session.add( + PublishedReport( + user_report_id=saved.user_report_id, + report_id=saved.report_id, + summary="Withdrawn while it was read.", + author_ids=["nikhil-woodruff"], + tags=[], + content=[], + ) + ) + service = published_report_service(sessions) + + with pytest.raises(PublishedReportNotFoundError): + service.get_published_report( + country_id="us", user_report_id=saved.user_report_id + ) + with pytest.raises(PublicationNotFoundError): + service.get_publication( + principal=saved.principal, + country_id="us", + user_report_id=saved.user_report_id, + ) + + +@pytest.mark.parametrize("name", [None, "", " "]) +def test_a_published_saved_reports_name_cannot_be_cleared(sessions, name) -> None: + saved, run_id = _saved_report_with_run(sessions) + _publish(published_report_service(sessions), saved, run_id) + user_reports = V2UserReportService(UserReportDatabaseSession(sessions)) + + with pytest.raises(PublishedUserReportNameRequiredError): + user_reports.patch_user_report( + principal=saved.principal, + country_id="us", + association_id=saved.user_report_id, + association_input=UserReportUpdateInput(name=name), + ) + renamed = user_reports.patch_user_report( + principal=saved.principal, + country_id="us", + association_id=saved.user_report_id, + association_input=UserReportUpdateInput(name="A new title"), + ) + + assert renamed.name == "A new title" + + +def test_an_unpublished_saved_reports_name_can_be_cleared(sessions) -> None: + saved, _run_id = _saved_report_with_run(sessions) + + unnamed = V2UserReportService( + UserReportDatabaseSession(sessions) + ).patch_user_report( + principal=saved.principal, + country_id="us", + association_id=saved.user_report_id, + association_input=UserReportUpdateInput(name=None), + ) + + assert unnamed.name is None + + +def test_a_signed_out_browser_owns_no_page_and_is_not_provisioned(sessions) -> None: + saved, run_id = _saved_report_with_run(sessions) + service = published_report_service(sessions) + _publish(service, saved, run_id) + browser = UnauthenticatedPrincipal(user_id=uuid4()) + + for owner_operation in ( + service.get_publication, + service.withdraw_publication, + ): + with pytest.raises(UserReportNotFoundError): + owner_operation( + principal=browser, + country_id="us", + user_report_id=saved.user_report_id, + ) + with pytest.raises(UserReportNotFoundError): + service.publish_report( + principal=browser, + country_id="us", + user_report_id=saved.user_report_id, + publication_input=PublicationCreateInput.model_validate( + publication_body(run_id) + ), + ) + + with sessions() as session: + assert session.get(User, browser.user_id) is None + assert service.get_published_report( + country_id="us", user_report_id=saved.user_report_id + )