From c1ef901e8b36fd81841f954e6ea8445f5ac888c4 Mon Sep 17 00:00:00 2001 From: Panna Liptak Date: Fri, 6 Nov 2026 11:39:49 +0100 Subject: [PATCH] feat(config): move committee approval to admin panel --- .../committee_approval_enrollments.py | 228 ++++++++++++++++++ ...ate_committee_approval_enrollment_table.py | 108 +++++++++ site/cds_rdm/cli.py | 59 +++++ .../__init__.py | 8 + .../committee_approval_enrollments/models.py | 205 ++++++++++++++++ .../resources/__init__.py | 8 + .../resources/config.py | 34 +++ .../resources/errors.py | 41 ++++ .../resources/resource.py | 77 ++++++ .../services/__init__.py | 8 + .../services/config.py | 33 +++ .../services/errors.py | 22 ++ .../services/permissions.py | 22 ++ .../services/results.py | 49 ++++ .../services/schema.py | 75 ++++++ .../services/service.py | 82 +++++++ .../committee_approval_enrollments/utils.py | 43 ++++ site/cds_rdm/components.py | 18 +- site/cds_rdm/config.py | 22 ++ site/cds_rdm/ext.py | 23 ++ site/cds_rdm/generators.py | 12 +- .../transform/mappers/identifiers.py | 13 +- site/cds_rdm/notifications/generators.py | 8 +- site/cds_rdm/requests/committee_approval.py | 60 ++--- .../requests/committee_approval_state.py | 41 ++-- site/cds_rdm/requests/views.py | 12 +- site/cds_rdm/views.py | 6 + site/pyproject.toml | 6 + site/tests/conftest.py | 47 ++-- .../inspire_harvester/test_transformer.py | 40 +-- .../tests/inspire_harvester/test_validator.py | 13 +- site/tests/test_committee_approval.py | 75 +++--- 32 files changed, 1324 insertions(+), 174 deletions(-) create mode 100644 site/cds_rdm/administration/committee_approval_enrollments.py create mode 100644 site/cds_rdm/alembic/1778000000_create_committee_approval_enrollment_table.py create mode 100644 site/cds_rdm/committee_approval_enrollments/__init__.py create mode 100644 site/cds_rdm/committee_approval_enrollments/models.py create mode 100644 site/cds_rdm/committee_approval_enrollments/resources/__init__.py create mode 100644 site/cds_rdm/committee_approval_enrollments/resources/config.py create mode 100644 site/cds_rdm/committee_approval_enrollments/resources/errors.py create mode 100644 site/cds_rdm/committee_approval_enrollments/resources/resource.py create mode 100644 site/cds_rdm/committee_approval_enrollments/services/__init__.py create mode 100644 site/cds_rdm/committee_approval_enrollments/services/config.py create mode 100644 site/cds_rdm/committee_approval_enrollments/services/errors.py create mode 100644 site/cds_rdm/committee_approval_enrollments/services/permissions.py create mode 100644 site/cds_rdm/committee_approval_enrollments/services/results.py create mode 100644 site/cds_rdm/committee_approval_enrollments/services/schema.py create mode 100644 site/cds_rdm/committee_approval_enrollments/services/service.py create mode 100644 site/cds_rdm/committee_approval_enrollments/utils.py diff --git a/site/cds_rdm/administration/committee_approval_enrollments.py b/site/cds_rdm/administration/committee_approval_enrollments.py new file mode 100644 index 00000000..59dfdcdb --- /dev/null +++ b/site/cds_rdm/administration/committee_approval_enrollments.py @@ -0,0 +1,228 @@ +# -*- coding: utf-8 -*- +# +# Copyright (C) 2026 CERN. +# +# CDS-RDM is free software; you can redistribute it and/or modify it +# under the terms of the GPL-2.0 License; see LICENSE file for more details. + +"""Administration views for committee approval communities.""" + +from flask import request +from invenio_administration.views.base import ( + AdminResourceCreateView, + AdminResourceDetailView, + AdminResourceEditView, + AdminResourceListView, +) +from invenio_communities.communities.records.models import CommunityMetadata +from invenio_i18n import lazy_gettext as _ + +from cds_rdm.committee_approval_enrollments.models import CommitteeApprovalEnrollment + + +def _community_options(include=None): + """Return dropdown options for communities not yet enrolled. + + ``include`` is the id of a community to list even though it is enrolled + (the one being edited). + + The option text includes slug, title and UUID so the search box matches + on any of them. + """ + enrolled = {entry.community_id for entry in CommitteeApprovalEnrollment.get_all()} + options = [] + for community in CommunityMetadata.query.order_by(CommunityMetadata.slug): + if str(community.id) != include and ( + community.id in enrolled or community.is_deleted + ): + continue + title = (community.json or {}).get("metadata", {}).get("title", "") + options.append( + { + "id": str(community.id), + "title_l10n": f"{community.slug} — {title} ({community.id})", + } + ) + return options + + +class CommitteeApprovalEnrollmentAdminMixin: + """Common admin properties.""" + + api_endpoint = "/committee-approval-enrollments" + resource_config = "committee_approval_enrollments_resource" + pid_path = "id" + # Access is restricted to ``administration-access`` (the base class default). + + +_form_fields = { + "community_id": { + "order": 1, + "text": _("Community ID"), + "description": _( + "UUID of the community to enrol in the approval workflow " + "(not the slug, as slugs can be renamed)." + ), + }, + "label": { + "order": 2, + "text": _("Label"), + "description": _("Shown in request buttons/headings, e.g. 'EP approval'."), + }, + "committee_name": { + "order": 3, + "text": _("Committee name"), + "description": _("Shown in review-step labels/text, e.g. 'EP Board'."), + }, + "referee_group": { + "order": 4, + "text": _("Referee group"), + "description": _( + "Id of the group whose members act as referees, i.e. the CERN " + "e-group name. Must be an existing group." + ), + }, + "read_only": { + "order": 5, + "text": _("Read only"), + "description": _("Only allow read-only access to the workflow."), + }, + "report_number_prefix": { + "order": 6, + "text": _("Report number prefix"), + "description": _("Fixed prefix, e.g. 'CERN-EP'."), + }, + "report_number_include_year": { + "order": 7, + "text": _("Include year"), + "description": _("Append the current year after the prefix."), + }, + "report_number_counter_digits": { + "order": 8, + "text": _("Counter digits"), + "description": _("Zero-padding width of the counter, e.g. 3 gives '001'."), + }, +} + + +class CommitteeApprovalEnrollmentListView( + CommitteeApprovalEnrollmentAdminMixin, AdminResourceListView +): + """List view.""" + + name = "committee-approval-enrollments" + title = _("Committee approval") + menu_label = _("Committee approval") + category = _("Communities") + icon = "check circle" + search_request_headers = {"Accept": "application/vnd.inveniordm.v1+json"} + + display_search = True + display_create = True + display_edit = True + display_delete = True + + create_view_name = "committee-approval-enrollment-create" + + search_config_name = "COMMITTEE_APPROVAL_ENROLLMENTS_SEARCH" + search_facets_config_name = "COMMITTEE_APPROVAL_ENROLLMENTS_FACETS" + search_sort_config_name = "COMMITTEE_APPROVAL_ENROLLMENTS_SORT_OPTIONS" + + item_field_list = { + "community_title": {"text": _("Community"), "order": 1, "width": 3}, + "community_slug": {"text": _("Slug"), "order": 2, "width": 2}, + "label": {"text": _("Label"), "order": 3, "width": 2}, + "committee_name": {"text": _("Committee"), "order": 4, "width": 2}, + "referee_group_name": {"text": _("Referee group"), "order": 5, "width": 3}, + "report_number_prefix": {"text": _("Prefix"), "order": 6, "width": 2}, + "read_only": {"text": _("Read only"), "order": 7, "width": 1}, + } + + +class CommitteeApprovalEnrollmentCreateView( + CommitteeApprovalEnrollmentAdminMixin, AdminResourceCreateView +): + """Create view.""" + + name = "committee-approval-enrollment-create" + url = "/committee-approval-enrollments/create" + title = _("Enrol community in committee approval") + list_view_name = "committee-approval-enrollments" + + @property + def form_fields(self): + """Form fields, with the community picker populated at request time.""" + return { + **_form_fields, + "community_id": { + **_form_fields["community_id"], + "text": _("Community"), + "description": _( + "Search by slug, title or UUID. Communities that are already " + "enrolled are not listed." + ), + "options": _community_options(), + "search": True, + "placeholder": _("Select a community"), + }, + } + + +class CommitteeApprovalEnrollmentEditView( + CommitteeApprovalEnrollmentAdminMixin, AdminResourceEditView +): + """Edit view.""" + + name = "committee-approval-enrollment-edit" + url = "/committee-approval-enrollments//edit" + title = _("Edit committee approval community") + list_view_name = "committee-approval-enrollments" + + @property + def form_fields(self): + """Form fields, with the (read-only) community picker for this entry.""" + entry = CommitteeApprovalEnrollment.get_by_id( + (request.view_args or {}).get("pid_value") + ) + current = str(entry.community_id) if entry else None + return { + **_form_fields, + "community_id": { + **_form_fields["community_id"], + "text": _("Community"), + "description": _("The enrolled community cannot be changed."), + "options": _community_options(include=current), + "search": True, + }, + "created": {"order": 9}, + "updated": {"order": 10}, + } + + +class CommitteeApprovalEnrollmentDetailView( + CommitteeApprovalEnrollmentAdminMixin, AdminResourceDetailView +): + """Detail view.""" + + name = "committee-approval-enrollment-details" + url = "/committee-approval-enrollments/" + title = _("Committee approval community") + list_view_name = "committee-approval-enrollments" + display_edit = True + display_delete = True + request_headers = {"Accept": "application/vnd.inveniordm.v1+json"} + + item_field_list = { + "community_id": {"text": _("Community ID"), "order": 1}, + "community_title": {"text": _("Community"), "order": 2}, + "community_slug": {"text": _("Slug"), "order": 3}, + "label": {"text": _("Label"), "order": 4}, + "committee_name": {"text": _("Committee name"), "order": 5}, + "referee_group_name": {"text": _("Referee group"), "order": 6}, + "read_only": {"text": _("Read only"), "order": 7}, + "report_number_prefix": {"text": _("Report number prefix"), "order": 8}, + "report_number_include_year": {"text": _("Include year"), "order": 9}, + "report_number_counter_digits": {"text": _("Counter digits"), "order": 10}, + "created": {"text": _("Created"), "order": 11}, + "updated": {"text": _("Updated"), "order": 12}, + } diff --git a/site/cds_rdm/alembic/1778000000_create_committee_approval_enrollment_table.py b/site/cds_rdm/alembic/1778000000_create_committee_approval_enrollment_table.py new file mode 100644 index 00000000..eb402e98 --- /dev/null +++ b/site/cds_rdm/alembic/1778000000_create_committee_approval_enrollment_table.py @@ -0,0 +1,108 @@ +# -*- coding: utf-8 -*- +# +# Copyright (C) 2026 CERN. +# +# CDS-RDM is free software; you can redistribute it and/or modify it +# under the terms of the GPL-2.0 License; see LICENSE file for more details. + +"""Create committee approval enrollment table.""" + +import sqlalchemy as sa +import sqlalchemy_utils +from alembic import op + +# revision identifiers, used by Alembic. +revision = "1778000000" +down_revision = "1771314900" +branch_labels = () +depends_on = "de9c14cbb0b2" # invenio-communities: communities tables + + +def upgrade(): + """Upgrade database.""" + op.create_table( + "cds_committee_approval_enrollment", + sa.Column("id", sqlalchemy_utils.types.uuid.UUIDType(), nullable=False), + sa.Column( + "community_id", + sqlalchemy_utils.types.uuid.UUIDType(), + nullable=False, + comment="The enrolled community", + ), + sa.Column( + "label", + sa.String(length=255), + nullable=False, + comment="Workflow label shown in the UI, e.g. 'EP approval'", + ), + sa.Column( + "committee_name", + sa.String(length=255), + nullable=True, + comment="Reviewer/board name shown in review-step labels, e.g. 'EP Board'", + ), + sa.Column( + "referee_group", + sa.String(length=80), + nullable=False, + comment="Id of the group (role) whose members act as referees", + ), + sa.Column( + "read_only", + sa.Boolean(), + nullable=False, + comment="Only allow read-only access to the workflow in this community", + ), + sa.Column( + "report_number_prefix", + sa.String(length=255), + nullable=False, + comment="Fixed prefix, e.g. 'CERN-EP'", + ), + sa.Column( + "report_number_include_year", + sa.Boolean(), + nullable=False, + comment="Append the current year after the prefix", + ), + sa.Column( + "report_number_counter_digits", + sa.Integer(), + nullable=False, + comment="Zero-padding width of the counter", + ), + sa.Column( + "created", + sa.DateTime(timezone=True), + nullable=False, + ), + sa.Column( + "updated", + sa.DateTime(timezone=True), + nullable=False, + ), + sa.ForeignKeyConstraint( + ["community_id"], + ["communities_metadata.id"], + name=op.f("fk_cds_committee_approval_enrollment_community_id_commu_d461"), + ondelete="CASCADE", + ), + sa.ForeignKeyConstraint( + ["referee_group"], + ["accounts_role.id"], + name=op.f("fk_cds_committee_approval_enrollment_referee_group_acco_7c22"), + ondelete="RESTRICT", + ), + sa.PrimaryKeyConstraint( + "id", name=op.f("pk_cds_committee_approval_enrollment") + ), + sa.UniqueConstraint( + "community_id", + name=op.f("uq_cds_committee_approval_enrollment_community_id"), + ), + ) + + +def downgrade(): + """Downgrade database.""" + op.drop_table("cds_committee_approval_enrollment") diff --git a/site/cds_rdm/cli.py b/site/cds_rdm/cli.py index cbc094de..d60d430b 100644 --- a/site/cds_rdm/cli.py +++ b/site/cds_rdm/cli.py @@ -248,3 +248,62 @@ def delete_record(recid): for req in requests: current_requests_service.indexer.delete(req) + + +@cds_admin.command("seed-committee-approval-enrollments") +@click.option( + "--config-key", + default="CDS_COMMITTEE_APPROVAL_COMMUNITIES", + show_default=True, + help="Config dict (community UUID -> workflow config) to import.", +) +@click.option( + "--community-id", + "community_ids", + multiple=True, + help="Only import this community UUID (repeatable). Default: all entries.", +) +@with_appcontext +def seed_committee_approval_enrollments(config_key, community_ids): + """Import committee approval communities from the legacy config dict. + + Only creates entries for communities that are not yet enrolled; existing + entries (e.g. edited from the admin panel) are never overwritten. + """ + from flask import current_app + from invenio_accounts.models import Role + + from cds_rdm.committee_approval_enrollments.models import ( + CommitteeApprovalEnrollment, + ) + + created = skipped = 0 + for community_id, cfg in current_app.config.get(config_key, {}).items(): + if community_ids and community_id not in community_ids: + continue + if CommitteeApprovalEnrollment.get_by_community_id(community_id): + skipped += 1 + continue + if not Role.query.get(cfg["referee_group"]): + click.secho( + f"Skipping {community_id}: group '{cfg['referee_group']}' not found.", + fg="yellow", + ) + skipped += 1 + continue + rn = cfg.get("report_number", {}) + CommitteeApprovalEnrollment.create( + { + "community_id": community_id, + "label": cfg["label"], + "committee_name": cfg.get("committee_name"), + "referee_group": cfg["referee_group"], + "read_only": cfg.get("read_only", False), + "report_number_prefix": rn["prefix"], + "report_number_include_year": rn.get("include_year", True), + "report_number_counter_digits": rn.get("counter_digits", 3), + } + ) + created += 1 + db.session.commit() + click.secho(f"Created {created}, skipped {skipped} existing.", fg="green") diff --git a/site/cds_rdm/committee_approval_enrollments/__init__.py b/site/cds_rdm/committee_approval_enrollments/__init__.py new file mode 100644 index 00000000..89ccf2c4 --- /dev/null +++ b/site/cds_rdm/committee_approval_enrollments/__init__.py @@ -0,0 +1,8 @@ +# -*- coding: utf-8 -*- +# +# Copyright (C) 2026 CERN. +# +# CDS-RDM is free software; you can redistribute it and/or modify it +# under the terms of the GPL-2.0 License; see LICENSE file for more details. + +"""Committee approval communities.""" diff --git a/site/cds_rdm/committee_approval_enrollments/models.py b/site/cds_rdm/committee_approval_enrollments/models.py new file mode 100644 index 00000000..57f988c4 --- /dev/null +++ b/site/cds_rdm/committee_approval_enrollments/models.py @@ -0,0 +1,205 @@ +# -*- coding: utf-8 -*- +# +# Copyright (C) 2026 CERN. +# +# CDS-RDM is free software; you can redistribute it and/or modify it +# under the terms of the GPL-2.0 License; see LICENSE file for more details. + +"""Committee approval community model.""" + +import uuid +from datetime import date + +from invenio_communities.communities.records.models import CommunityMetadata +from invenio_db import db +from invenio_db.shared import Timestamp +from sqlalchemy import func, or_ +from sqlalchemy.dialects.postgresql import JSONB +from sqlalchemy_utils.types import UUIDType + + +class CommitteeApprovalEnrollment(db.Model, Timestamp): + """A community enrolled in the publication approval workflow.""" + + __tablename__ = "cds_committee_approval_enrollment" + + id = db.Column(UUIDType, primary_key=True, default=uuid.uuid4) + + community_id = db.Column( + UUIDType, + db.ForeignKey("communities_metadata.id", ondelete="CASCADE"), + nullable=False, + unique=True, + comment="The enrolled community", + ) + + label = db.Column( + db.String(255), + nullable=False, + comment="Workflow label shown in the UI, e.g. 'EP approval'", + ) + committee_name = db.Column( + db.String(255), + nullable=True, + comment="Reviewer/board name shown in review-step labels, e.g. 'EP Board'", + ) + referee_group = db.Column( + db.String(80), + db.ForeignKey("accounts_role.id", ondelete="RESTRICT"), + nullable=False, + comment="Id of the group (role) whose members act as referees", + ) + read_only = db.Column( + db.Boolean, + nullable=False, + default=False, + comment="Only allow read-only access to the workflow in this community", + ) + + report_number_prefix = db.Column( + db.String(255), + nullable=False, + comment="Fixed prefix, e.g. 'CERN-EP'", + ) + report_number_include_year = db.Column( + db.Boolean, + nullable=False, + default=True, + comment="Append the current year after the prefix", + ) + report_number_counter_digits = db.Column( + db.Integer, + nullable=False, + default=3, + comment="Zero-padding width of the counter", + ) + + community = db.relationship("CommunityMetadata", lazy="joined") + referee_role = db.relationship("Role", lazy="joined") + + def report_number_scan_prefix(self, year=None): + """Return the prefix shared by this community's report numbers. + + E.g. ``CERN-EP-2026-`` (or ``CERN-EP-`` if the year is not included). + """ + if not self.report_number_include_year: + return f"{self.report_number_prefix}-" + year = year or date.today().year + return f"{self.report_number_prefix}-{year}-" + + def format_report_number(self, sequence, year=None): + """Return the report number for the given counter value.""" + digits = self.report_number_counter_digits + return f"{self.report_number_scan_prefix(year)}{sequence:0{digits}d}" + + @classmethod + def get_by_id(cls, id): + """Get entry by its id.""" + return db.session.get(cls, id) + + @classmethod + def get_by_community_id(cls, community_id): + """Get entry by community id.""" + return cls.query.filter_by(community_id=community_id).one_or_none() + + @classmethod + def get_report_number_prefixes(cls): + """Return the set of report number prefixes of all enrolled communities.""" + return { + prefix + for (prefix,) in db.session.query(cls.report_number_prefix).distinct() + } + + @classmethod + def get_all(cls): + """Return all entries.""" + return cls.query.all() + + @classmethod + def create(cls, data): + """Create an entry.""" + with db.session.begin_nested(): + obj = cls(**data) + db.session.add(obj) + return obj + + @classmethod + def update(cls, obj, data): + """Update an entry.""" + with db.session.begin_nested(): + for key, value in data.items(): + setattr(obj, key, value) + return obj + + @classmethod + def delete(cls, obj): + """Delete an entry.""" + with db.session.begin_nested(): + db.session.delete(obj) + + @classmethod + def _filtered_query(cls, params, skip_facet=None): + """Build the query for the free-text search and the active facet filters. + + ``skip_facet`` leaves out one facet's own filter, so that its counts + still show the other available values. + """ + query = cls.query + if q := params.get("q"): + community_title = func.jsonb_extract_path_text( + db.cast(CommunityMetadata.json, JSONB), "metadata", "title" + ) + query = query.join(cls.community).filter( + or_( + CommunityMetadata.slug.ilike(f"%{q}%"), + community_title.ilike(f"%{q}%"), + cls.referee_group.ilike(f"%{q}%"), + cls.report_number_prefix.ilike(f"%{q}%"), + ) + ) + facets = params.get("facets") or {} + if facets.get("read_only") and skip_facet != "read_only": + values = [v.lower() == "true" for v in facets["read_only"]] + query = query.filter(cls.read_only.in_(values)) + return query + + @classmethod + def _aggregations(cls, params): + """Compute the facet buckets.""" + read_only_rows = ( + cls._filtered_query(params, skip_facet="read_only") + .with_entities(cls.read_only, func.count(cls.id)) + .group_by(cls.read_only) + .all() + ) + return { + "read_only": { + "buckets": [ + { + "key": "true" if value else "false", + "doc_count": count, + "label": "Yes" if value else "No", + } + for value, count in read_only_rows + ], + }, + } + + @classmethod + def search(cls, params): + """Search entries.""" + query = cls._filtered_query(params) + sort = params.get("sort") + if sort in ("label", "created", "referee_group", "report_number_prefix"): + query = query.order_by(getattr(cls, sort)) + else: + query = query.order_by(cls.created) + size = int(params.get("size", 25)) + page = int(params.get("page", 1)) + total = query.count() + hits = query.offset((page - 1) * size).limit(size).all() + return { + "hits": hits, + "total": total, + "aggregations": cls._aggregations(params), + } diff --git a/site/cds_rdm/committee_approval_enrollments/resources/__init__.py b/site/cds_rdm/committee_approval_enrollments/resources/__init__.py new file mode 100644 index 00000000..74790b50 --- /dev/null +++ b/site/cds_rdm/committee_approval_enrollments/resources/__init__.py @@ -0,0 +1,8 @@ +# -*- coding: utf-8 -*- +# +# Copyright (C) 2026 CERN. +# +# CDS-RDM is free software; you can redistribute it and/or modify it +# under the terms of the GPL-2.0 License; see LICENSE file for more details. + +"""Committee approval communities resources.""" diff --git a/site/cds_rdm/committee_approval_enrollments/resources/config.py b/site/cds_rdm/committee_approval_enrollments/resources/config.py new file mode 100644 index 00000000..6465f349 --- /dev/null +++ b/site/cds_rdm/committee_approval_enrollments/resources/config.py @@ -0,0 +1,34 @@ +# -*- coding: utf-8 -*- +# +# Copyright (C) 2026 CERN. +# +# CDS-RDM is free software; you can redistribute it and/or modify it +# under the terms of the GPL-2.0 License; see LICENSE file for more details. + +"""Committee approval communities resource config.""" + +import marshmallow as ma +from flask_resources import JSONDeserializer, RequestBodyParser +from invenio_records_resources.resources import RecordResourceConfig + + +class CommitteeApprovalEnrollmentResourceConfig(RecordResourceConfig): + """Resource configuration.""" + + blueprint_name = "committee-approval-enrollments" + url_prefix = "/committee-approval-enrollments" + routes = { + "item": "/", + "list": "/", + } + + request_view_args = {"item_id": ma.fields.String()} + request_body_parsers = {"application/json": RequestBodyParser(JSONDeserializer())} + default_content_type = "application/json" + + response_handlers = { + "application/vnd.inveniordm.v1+json": RecordResourceConfig.response_handlers[ + "application/json" + ], + **RecordResourceConfig.response_handlers, + } diff --git a/site/cds_rdm/committee_approval_enrollments/resources/errors.py b/site/cds_rdm/committee_approval_enrollments/resources/errors.py new file mode 100644 index 00000000..2e7e1597 --- /dev/null +++ b/site/cds_rdm/committee_approval_enrollments/resources/errors.py @@ -0,0 +1,41 @@ +# -*- coding: utf-8 -*- +# +# Copyright (C) 2026 CERN. +# +# CDS-RDM is free software; you can redistribute it and/or modify it +# under the terms of the GPL-2.0 License; see LICENSE file for more details. + +"""Committee approval communities resource errors.""" + +import marshmallow as ma +from flask_resources import HTTPJSONException, create_error_handler +from invenio_records_resources.errors import validation_error_to_list_errors +from invenio_records_resources.resources.errors import ( + ErrorHandlersMixin as BaseErrorHandlersMixin, +) + +from ..services.errors import ( + CommitteeApprovalEnrollmentAlreadyExistsError, + CommitteeApprovalEnrollmentNotFoundError, +) + + +class ErrorHandlersMixin: + """Mixin to define error handlers.""" + + error_handlers = { + **BaseErrorHandlersMixin.error_handlers, + CommitteeApprovalEnrollmentNotFoundError: create_error_handler( + lambda e: HTTPJSONException(code=404, description=str(e.description)) + ), + CommitteeApprovalEnrollmentAlreadyExistsError: create_error_handler( + lambda e: HTTPJSONException(code=409, description=str(e.description)) + ), + ma.ValidationError: create_error_handler( + lambda e: HTTPJSONException( + code=400, + description="A validation error occurred.", + errors=validation_error_to_list_errors(e), + ) + ), + } diff --git a/site/cds_rdm/committee_approval_enrollments/resources/resource.py b/site/cds_rdm/committee_approval_enrollments/resources/resource.py new file mode 100644 index 00000000..120a3830 --- /dev/null +++ b/site/cds_rdm/committee_approval_enrollments/resources/resource.py @@ -0,0 +1,77 @@ +# -*- coding: utf-8 -*- +# +# Copyright (C) 2026 CERN. +# +# CDS-RDM is free software; you can redistribute it and/or modify it +# under the terms of the GPL-2.0 License; see LICENSE file for more details. + +"""Committee approval communities resource.""" + +from flask import g +from flask_resources import Resource, resource_requestctx, response_handler, route +from invenio_records_resources.resources.records.resource import ( + request_data, + request_search_args, + request_view_args, +) + +from .errors import ErrorHandlersMixin + + +class CommitteeApprovalEnrollmentResource(ErrorHandlersMixin, Resource): + """Committee approval communities resource.""" + + def __init__(self, config, service): + """Constructor.""" + super().__init__(config) + self.service = service + + def create_url_rules(self): + """Create the URL rules.""" + routes = self.config.routes + return [ + route("GET", routes["list"], self.search), + route("POST", routes["list"], self.create), + route("GET", routes["item"], self.read), + route("PUT", routes["item"], self.update), + route("DELETE", routes["item"], self.delete), + ] + + @request_search_args + @response_handler(many=True) + def search(self): + """Search entries.""" + items = self.service.search(g.identity, params=resource_requestctx.args) + return items.to_dict(), 200 + + @request_data + @response_handler() + def create(self): + """Create an entry.""" + item = self.service.create(g.identity, resource_requestctx.data or {}) + return item.to_dict(), 201 + + @request_view_args + @response_handler() + def read(self): + """Read an entry.""" + item = self.service.read(g.identity, resource_requestctx.view_args["item_id"]) + return item.to_dict(), 200 + + @request_view_args + @request_data + @response_handler() + def update(self): + """Update an entry.""" + item = self.service.update( + g.identity, + resource_requestctx.view_args["item_id"], + resource_requestctx.data or {}, + ) + return item.to_dict(), 200 + + @request_view_args + def delete(self): + """Delete an entry.""" + self.service.delete(g.identity, resource_requestctx.view_args["item_id"]) + return "", 204 diff --git a/site/cds_rdm/committee_approval_enrollments/services/__init__.py b/site/cds_rdm/committee_approval_enrollments/services/__init__.py new file mode 100644 index 00000000..3e62ceb6 --- /dev/null +++ b/site/cds_rdm/committee_approval_enrollments/services/__init__.py @@ -0,0 +1,8 @@ +# -*- coding: utf-8 -*- +# +# Copyright (C) 2026 CERN. +# +# CDS-RDM is free software; you can redistribute it and/or modify it +# under the terms of the GPL-2.0 License; see LICENSE file for more details. + +"""Committee approval communities services.""" diff --git a/site/cds_rdm/committee_approval_enrollments/services/config.py b/site/cds_rdm/committee_approval_enrollments/services/config.py new file mode 100644 index 00000000..0f6565db --- /dev/null +++ b/site/cds_rdm/committee_approval_enrollments/services/config.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# +# Copyright (C) 2026 CERN. +# +# CDS-RDM is free software; you can redistribute it and/or modify it +# under the terms of the GPL-2.0 License; see LICENSE file for more details. + +"""Committee approval communities service config.""" + +from invenio_records_resources.services import EndpointLink, RecordServiceConfig + +from ..models import CommitteeApprovalEnrollment +from .permissions import CommitteeApprovalEnrollmentPermissionPolicy +from .results import CommitteeApprovalEnrollmentItem, CommitteeApprovalEnrollmentList +from .schema import CommitteeApprovalEnrollmentSchema + + +class CommitteeApprovalEnrollmentServiceConfig(RecordServiceConfig): + """Service configuration.""" + + result_item_cls = CommitteeApprovalEnrollmentItem + result_list_cls = CommitteeApprovalEnrollmentList + permission_policy_cls = CommitteeApprovalEnrollmentPermissionPolicy + schema = CommitteeApprovalEnrollmentSchema + record_cls = CommitteeApprovalEnrollment + + links_item = { + "self": EndpointLink( + "committee-approval-enrollments.read", + params=["item_id"], + vars=lambda obj, vars: vars.update(item_id=str(obj.id)), + ), + } diff --git a/site/cds_rdm/committee_approval_enrollments/services/errors.py b/site/cds_rdm/committee_approval_enrollments/services/errors.py new file mode 100644 index 00000000..31e5cc31 --- /dev/null +++ b/site/cds_rdm/committee_approval_enrollments/services/errors.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# +# Copyright (C) 2026 CERN. +# +# CDS-RDM is free software; you can redistribute it and/or modify it +# under the terms of the GPL-2.0 License; see LICENSE file for more details. + +"""Committee approval communities errors.""" + +from invenio_i18n import lazy_gettext as _ + + +class CommitteeApprovalEnrollmentNotFoundError(Exception): + """Entry does not exist.""" + + description = _("Committee approval community not found.") + + +class CommitteeApprovalEnrollmentAlreadyExistsError(Exception): + """Community is already enrolled.""" + + description = _("This community is already enrolled in the approval workflow.") diff --git a/site/cds_rdm/committee_approval_enrollments/services/permissions.py b/site/cds_rdm/committee_approval_enrollments/services/permissions.py new file mode 100644 index 00000000..736e9a7a --- /dev/null +++ b/site/cds_rdm/committee_approval_enrollments/services/permissions.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# +# Copyright (C) 2026 CERN. +# +# CDS-RDM is free software; you can redistribute it and/or modify it +# under the terms of the GPL-2.0 License; see LICENSE file for more details. + +"""Committee approval communities permissions.""" + +from invenio_administration.generators import Administration +from invenio_records_permissions import BasePermissionPolicy +from invenio_records_permissions.generators import SystemProcess + + +class CommitteeApprovalEnrollmentPermissionPolicy(BasePermissionPolicy): + """Only administrators (``administration-access``) can manage entries.""" + + can_create = [Administration(), SystemProcess()] + can_read = [Administration(), SystemProcess()] + can_search = [Administration(), SystemProcess()] + can_update = [Administration(), SystemProcess()] + can_delete = [Administration(), SystemProcess()] diff --git a/site/cds_rdm/committee_approval_enrollments/services/results.py b/site/cds_rdm/committee_approval_enrollments/services/results.py new file mode 100644 index 00000000..f02b3e40 --- /dev/null +++ b/site/cds_rdm/committee_approval_enrollments/services/results.py @@ -0,0 +1,49 @@ +# -*- coding: utf-8 -*- +# +# Copyright (C) 2026 CERN. +# +# CDS-RDM is free software; you can redistribute it and/or modify it +# under the terms of the GPL-2.0 License; see LICENSE file for more details. + +"""Committee approval communities results.""" + +from invenio_records_resources.services.records.results import RecordItem, RecordList + + +class CommitteeApprovalEnrollmentItem(RecordItem): + """Single entry result.""" + + @property + def data(self): + """Dump the entry.""" + if self._data is None: + self._data = self._schema.dump( + self._record, context={"identity": self._identity} + ) + if self._links_tpl: + # the admin UI uses ``links.self`` for edit/delete actions + self._data["links"] = self.links + return self._data + + +class CommitteeApprovalEnrollmentList(RecordList): + """List result.""" + + @property + def total(self): + """Total number of hits.""" + return self._results.get("total", 0) + + @property + def aggregations(self): + """Facet buckets.""" + return self._results.get("aggregations") + + @property + def hits(self): + """Iterate over the hits.""" + for hit in self._results["hits"]: + projection = self._schema.dump(hit, context={"identity": self._identity}) + if self._links_item_tpl: + projection["links"] = self._links_item_tpl.expand(self._identity, hit) + yield projection diff --git a/site/cds_rdm/committee_approval_enrollments/services/schema.py b/site/cds_rdm/committee_approval_enrollments/services/schema.py new file mode 100644 index 00000000..f97b52b5 --- /dev/null +++ b/site/cds_rdm/committee_approval_enrollments/services/schema.py @@ -0,0 +1,75 @@ +# -*- coding: utf-8 -*- +# +# Copyright (C) 2026 CERN. +# +# CDS-RDM is free software; you can redistribute it and/or modify it +# under the terms of the GPL-2.0 License; see LICENSE file for more details. + +"""Committee approval communities schema.""" + +from invenio_accounts.models import Role +from invenio_communities.communities.records.models import CommunityMetadata +from invenio_db import db +from marshmallow import EXCLUDE, Schema, ValidationError, fields, validate, validates + + +class CommitteeApprovalEnrollmentSchema(Schema): + """Schema for a committee approval community entry.""" + + class Meta: + """Meta attributes.""" + + unknown = EXCLUDE + + id = fields.String(dump_only=True) + community_id = fields.String(required=True) + community_slug = fields.Method("get_community_slug", dump_only=True) + community_title = fields.Method("get_community_title", dump_only=True) + label = fields.String(required=True, validate=validate.Length(min=1, max=255)) + committee_name = fields.String( + allow_none=True, validate=validate.Length(max=255), load_default=None + ) + referee_group = fields.String( + required=True, validate=validate.Length(min=1, max=80) + ) + referee_group_name = fields.Method("get_referee_group_name", dump_only=True) + read_only = fields.Boolean(load_default=False) + report_number_prefix = fields.String( + required=True, validate=validate.Length(min=1, max=255) + ) + report_number_include_year = fields.Boolean(load_default=True) + report_number_counter_digits = fields.Integer( + load_default=3, validate=validate.Range(min=1, max=10) + ) + created = fields.DateTime(dump_only=True) + updated = fields.DateTime(dump_only=True) + + def get_community_slug(self, obj): + """Return the slug of the enrolled community.""" + return obj.community.slug if obj.community else None + + def get_referee_group_name(self, obj): + """Return the name of the referee group.""" + return obj.referee_role.name if obj.referee_role else None + + def get_community_title(self, obj): + """Return the title of the enrolled community.""" + if not obj.community: + return None + return (obj.community.json or {}).get("metadata", {}).get("title") + + @validates("referee_group") + def validate_referee_group(self, value, **kwargs): + """Check that the group exists.""" + if db.session.get(Role, value) is None: + raise ValidationError("Group does not exist.") + + @validates("community_id") + def validate_community_id(self, value, **kwargs): + """Check that the community exists.""" + try: + exists = db.session.get(CommunityMetadata, value) is not None + except Exception: + exists = False + if not exists: + raise ValidationError("Community does not exist.") diff --git a/site/cds_rdm/committee_approval_enrollments/services/service.py b/site/cds_rdm/committee_approval_enrollments/services/service.py new file mode 100644 index 00000000..bd4369af --- /dev/null +++ b/site/cds_rdm/committee_approval_enrollments/services/service.py @@ -0,0 +1,82 @@ +# -*- coding: utf-8 -*- +# +# Copyright (C) 2026 CERN. +# +# CDS-RDM is free software; you can redistribute it and/or modify it +# under the terms of the GPL-2.0 License; see LICENSE file for more details. + +"""Committee approval communities service.""" + +from invenio_db.uow import unit_of_work +from invenio_records_resources.services import RecordService +from sqlalchemy.exc import IntegrityError + +from .errors import ( + CommitteeApprovalEnrollmentAlreadyExistsError, + CommitteeApprovalEnrollmentNotFoundError, +) + + +class CommitteeApprovalEnrollmentService(RecordService): + """CRUD service for committee approval communities.""" + + def _get(self, id): + obj = self.record_cls.get_by_id(id) + if obj is None: + raise CommitteeApprovalEnrollmentNotFoundError(id) + return obj + + def _item(self, identity, obj): + return self.result_item(self, identity, obj, links_tpl=self.links_item_tpl) + + def read(self, identity, id, **kwargs): + """Read an entry.""" + self.require_permission(identity, "read") + return self._item(identity, self._get(id)) + + def search(self, identity, params=None, **kwargs): + """Search entries.""" + self.require_permission(identity, "search") + results = self.record_cls.search(params or {}) + return self.result_list( + self, identity, results, links_item_tpl=self.links_item_tpl + ) + + @unit_of_work() + def create(self, identity, data, uow=None, **kwargs): + """Create an entry.""" + self.require_permission(identity, "create") + valid, _ = self.schema.load( + data, context={"identity": identity}, raise_errors=True + ) + if self.record_cls.get_by_community_id(valid["community_id"]): + raise CommitteeApprovalEnrollmentAlreadyExistsError(valid["community_id"]) + try: + obj = self.record_cls.create(valid) + except IntegrityError as e: + raise CommitteeApprovalEnrollmentAlreadyExistsError( + valid["community_id"] + ) from e + return self._item(identity, obj) + + @unit_of_work() + def update(self, identity, id, data, uow=None, **kwargs): + """Update an entry.""" + self.require_permission(identity, "update") + obj = self._get(id) + # the enrolled community cannot be changed once created + data = {**data, "community_id": str(obj.community_id)} + valid, _ = self.schema.load( + data, context={"identity": identity}, raise_errors=True + ) + valid.pop("community_id") + self.record_cls.update(obj, valid) + return self._item(identity, obj) + + @unit_of_work() + def delete(self, identity, id, uow=None, **kwargs): + """Delete an entry.""" + self.require_permission(identity, "delete") + obj = self._get(id) + self.record_cls.delete(obj) + return self._item(identity, obj) diff --git a/site/cds_rdm/committee_approval_enrollments/utils.py b/site/cds_rdm/committee_approval_enrollments/utils.py new file mode 100644 index 00000000..4b6c11a6 --- /dev/null +++ b/site/cds_rdm/committee_approval_enrollments/utils.py @@ -0,0 +1,43 @@ +# -*- coding: utf-8 -*- +# +# Copyright (C) 2026 CERN. +# +# CDS-RDM is free software; you can redistribute it and/or modify it +# under the terms of the GPL-2.0 License; see LICENSE file for more details. + +"""Committee approval communities utilities.""" + +from flask import g, has_request_context + +from .models import CommitteeApprovalEnrollment + +_CACHE_ATTR = "_cds_committee_approval_enrollment" + + +def _load_community(community_id): + try: + return CommitteeApprovalEnrollment.get_by_community_id(community_id) + except (ValueError, AttributeError): # malformed UUID + return None + + +def get_committee_approval_enrollment(community_id): + """Return the ``CommitteeApprovalEnrollment`` entry, or ``None``. + + ``None`` means the community is not enrolled in the committee approval + workflow. The lookup is cached for the duration of a request. + """ + if not community_id: + return None + community_id = str(community_id) + if not has_request_context(): + return _load_community(community_id) + cache = g.setdefault(_CACHE_ATTR, {}) + if community_id not in cache: + cache[community_id] = _load_community(community_id) + return cache[community_id] + + +def get_report_number_prefixes(): + """Return the report number prefixes of all enrolled communities.""" + return CommitteeApprovalEnrollment.get_report_number_prefixes() diff --git a/site/cds_rdm/components.py b/site/cds_rdm/components.py index 26719e13..6577cbaa 100644 --- a/site/cds_rdm/components.py +++ b/site/cds_rdm/components.py @@ -20,6 +20,8 @@ from invenio_records_resources.services.uow import TaskOp from marshmallow import ValidationError +from cds_rdm.committee_approval_enrollments.utils import get_report_number_prefixes + from .tasks import ( sync_alternate_identifiers, # submit_community_inclusion_request temporarily disabled ) @@ -144,20 +146,6 @@ class CommitteeApprovalComponent(ServiceComponent): on its parent, so it never carries the apprn identifier. """ - def _committee_approval_prefixes(self): - """Return the set of fixed prefixes from all configured committee communities. - - E.g. config ``{"prefix": "CERN-EP"}`` → prefix ``"CERN-EP"``. - Used to detect cdsrn values that collide with committee report numbers. - """ - communities = current_app.config.get("CDS_COMMITTEE_APPROVAL_COMMUNITIES", {}) - prefixes = set() - for cfg in communities.values(): - prefix = cfg.get("report_number", {}).get("prefix") - if prefix: - prefixes.add(prefix) - return prefixes - def _validate_identifier_changes(self, identity, data, record, errors): """Raise ValidationError if a non-system identity modifies apprn.""" if identity.id == system_user_id: @@ -200,7 +188,7 @@ def _validate_identifier_changes(self, identity, data, record, errors): raise ValidationErrorWithMessageAsList(errors) # Block cdsrn values that look like committee report numbers. - ep_prefixes = self._committee_approval_prefixes() + ep_prefixes = get_report_number_prefixes() if ep_prefixes: errors = [] for index, ident in enumerate(incoming_identifiers): diff --git a/site/cds_rdm/config.py b/site/cds_rdm/config.py index 4d2cfc33..c712c0b0 100644 --- a/site/cds_rdm/config.py +++ b/site/cds_rdm/config.py @@ -45,6 +45,28 @@ } """CLC user sync search configuration.""" +COMMITTEE_APPROVAL_ENROLLMENTS_SORT_OPTIONS = { + "created": dict(title=_("Created"), fields=["created"]), + "label": dict(title=_("Label"), fields=["label"]), + "referee_group": dict(title=_("Referee group"), fields=["referee_group"]), + "report_number_prefix": dict(title=_("Prefix"), fields=["report_number_prefix"]), +} +"""Sort options for the approval communities admin list.""" + +COMMITTEE_APPROVAL_ENROLLMENTS_FACETS = { + "read_only": { + "facet": TermsFacet(field="read_only", label=_("Read only")), + "ui": {"field": "read_only"}, + }, +} +"""Facets for the committee approval admin list (computed in SQL).""" + +COMMITTEE_APPROVAL_ENROLLMENTS_SEARCH = { + "facets": ["read_only"], + "sort": ["created", "label", "referee_group", "report_number_prefix"], +} +"""Search configuration for the approval communities admin list.""" + CLC_SYNC_ALLOWED_RESOURCE_TYPES = [ "publication", ] diff --git a/site/cds_rdm/ext.py b/site/cds_rdm/ext.py index 81eb77ef..9a917782 100644 --- a/site/cds_rdm/ext.py +++ b/site/cds_rdm/ext.py @@ -12,6 +12,18 @@ from cds_rdm.clc_sync.resources.utils import get_clc_sync_entry from cds_rdm.clc_sync.services.config import CLCSyncServiceConfig from cds_rdm.clc_sync.services.service import CLCSyncService +from cds_rdm.committee_approval_enrollments.resources.config import ( + CommitteeApprovalEnrollmentResourceConfig, +) +from cds_rdm.committee_approval_enrollments.resources.resource import ( + CommitteeApprovalEnrollmentResource, +) +from cds_rdm.committee_approval_enrollments.services.config import ( + CommitteeApprovalEnrollmentServiceConfig, +) +from cds_rdm.committee_approval_enrollments.services.service import ( + CommitteeApprovalEnrollmentService, +) from cds_rdm.custom_fields.publishing import OA_FUNDING_MODEL_FIELD_CFG from cds_rdm.inspire_harvester.reports.download.resources import ( HarvesterDownloadResource, @@ -57,6 +69,11 @@ def init_app(self, app): def init_services(self, app): """Initialize the services for banners.""" self.clc_sync_service = CLCSyncService(config=CLCSyncServiceConfig) + self.committee_approval_enrollments_service = ( + CommitteeApprovalEnrollmentService( + config=CommitteeApprovalEnrollmentServiceConfig + ) + ) def init_resources(self, app): """Initialize the resources for banners.""" @@ -64,6 +81,12 @@ def init_resources(self, app): service=self.clc_sync_service, config=CLCSyncResourceConfig, ) + self.committee_approval_enrollments_resource = ( + CommitteeApprovalEnrollmentResource( + service=self.committee_approval_enrollments_service, + config=CommitteeApprovalEnrollmentResourceConfig, + ) + ) self.harvester_download_resource = HarvesterDownloadResource( config=HarvesterDownloadResourceConfig, ) diff --git a/site/cds_rdm/generators.py b/site/cds_rdm/generators.py index 2f022ca5..f08500a5 100644 --- a/site/cds_rdm/generators.py +++ b/site/cds_rdm/generators.py @@ -23,6 +23,10 @@ from invenio_search.engine import dsl from invenio_users_resources.proxies import current_users_service +from cds_rdm.committee_approval_enrollments.utils import ( + get_committee_approval_enrollment, +) + from .administration.permissions import harvester_admin_access_action archiver_read_all_role = RoleNeed("archiver-read-all") @@ -183,8 +187,7 @@ def needs(self, **kwargs): class EPWorkflowCommunityManager(Generator): """Allows community managers of EP-workflow-enrolled communities. - A community is enrolled by having its UUID listed as a key in the - ``CDS_COMMITTEE_APPROVAL_COMMUNITIES`` config dict. + A community is enrolled by having a ``CommitteeApprovalEnrollment`` entry. """ def needs(self, record=None, **kwargs): @@ -195,15 +198,12 @@ def needs(self, record=None, **kwargs): """ from invenio_communities.generators import CommunityRoleNeed - ep_communities = current_app.config.get( - "CDS_COMMITTEE_APPROVAL_COMMUNITIES", {} - ) if record is None: return [] default_community_id = record.parent.get("communities", {}).get("default") needs = [] - if default_community_id in ep_communities: + if get_committee_approval_enrollment(default_community_id): needs.append(CommunityRoleNeed(default_community_id, "manager")) needs.append(CommunityRoleNeed(default_community_id, "owner")) return needs diff --git a/site/cds_rdm/inspire_harvester/transform/mappers/identifiers.py b/site/cds_rdm/inspire_harvester/transform/mappers/identifiers.py index 91632d93..3070433e 100644 --- a/site/cds_rdm/inspire_harvester/transform/mappers/identifiers.py +++ b/site/cds_rdm/inspire_harvester/transform/mappers/identifiers.py @@ -16,6 +16,7 @@ from idutils.validators import is_doi, is_url, is_urn from cds_rdm import schemes +from cds_rdm.committee_approval_enrollments.utils import get_report_number_prefixes from cds_rdm.inspire_harvester.transform.mappers.config import ( INSPIRE_CORRECTION_MATERIALS, ) @@ -65,16 +66,6 @@ def _related_identifier(schema, value, ctx): return related -def _committee_approval_prefixes(): - """Return configured committee approval report-number prefixes.""" - communities = current_app.config.get("CDS_COMMITTEE_APPROVAL_COMMUNITIES", {}) - return { - cfg.get("report_number", {}).get("prefix") - for cfg in communities.values() - if cfg.get("report_number", {}).get("prefix") - } - - def _is_approval_report_number(value): """Return True if value is a valid EP/approval report number. @@ -89,7 +80,7 @@ def _is_approval_report_number(value): # Prefix then a digit (the year), not another word like DRAFT. return any( re.match(rf"^{re.escape(prefix)}-\d", value) - for prefix in _committee_approval_prefixes() + for prefix in get_report_number_prefixes() ) diff --git a/site/cds_rdm/notifications/generators.py b/site/cds_rdm/notifications/generators.py index 8e0ad2fa..741342fa 100644 --- a/site/cds_rdm/notifications/generators.py +++ b/site/cds_rdm/notifications/generators.py @@ -10,7 +10,6 @@ from __future__ import annotations -from flask import current_app from invenio_communities.notifications.generators import CommunityMembersRecipient from invenio_notifications.models import Notification, Recipient from invenio_notifications.services.generators import RecipientGenerator @@ -18,6 +17,10 @@ from invenio_rdm_records.records.api import RDMRecord from invenio_records.dictutils import dict_lookup +from cds_rdm.committee_approval_enrollments.utils import ( + get_committee_approval_enrollment, +) + class GroupEmailRecipientGenerator(RecipientGenerator): """Recipient generator that sends to the CERN e-group mailing address. @@ -80,8 +83,7 @@ def __call__( """Add the community managers and owners to ``recipients``.""" record = dict_lookup(notification.context, self.key) community_id = self._default_community_id(record) - enrolled = current_app.config.get("CDS_COMMITTEE_APPROVAL_COMMUNITIES", {}) - if not community_id or community_id not in enrolled: + if not community_id or not get_committee_approval_enrollment(community_id): return recipients notification.context["_ep_community"] = {"id": community_id} diff --git a/site/cds_rdm/requests/committee_approval.py b/site/cds_rdm/requests/committee_approval.py index 825f4b77..13c2cb47 100644 --- a/site/cds_rdm/requests/committee_approval.py +++ b/site/cds_rdm/requests/committee_approval.py @@ -13,7 +13,6 @@ from datetime import date, datetime, timezone from typing import Final -from flask import current_app from flask_principal import Identity from invenio_access.permissions import system_identity from invenio_db import db @@ -30,6 +29,10 @@ from invenio_requests.proxies import current_requests_service from marshmallow import ValidationError, fields +from cds_rdm.committee_approval_enrollments.utils import ( + get_committee_approval_enrollment, +) + from ..generators import ( COMMITTEE_APPROVAL_GRANT_PERMISSION, EPWorkflowCommunityManager, @@ -51,12 +54,12 @@ # --------------------------------------------------------------------------- -def _resolve_community_config(request): - """Resolve the committee approval config for the request's topic record. +def _resolve_enrollment(request): + """Resolve the enrollment (approval settings) of the request's topic record community. Validates that: - the topic record belongs to at least one community, and - - that community is enrolled in CDS_COMMITTEE_APPROVAL_COMMUNITIES. + - that community is enrolled (see ``get_committee_approval_enrollment``). Raises ``ValueError`` with a descriptive message if either condition fails. """ @@ -67,17 +70,14 @@ def _resolve_community_config(request): "The record is not part of any community. " "It must belong to a committee-approval-enabled community before submitting." ) - committee_communities = current_app.config.get( - "CDS_COMMITTEE_APPROVAL_COMMUNITIES", {} - ) - if default_community_id in committee_communities: - config = committee_communities[default_community_id] - if config.get("read_only"): + enrollment = get_committee_approval_enrollment(default_community_id) + if enrollment: + if enrollment.read_only: raise ValidationError( "This community's approval workflow is read-only. " "No new committee approval requests can be submitted." ) - return config + return enrollment raise ValidationError( # TODO: do we need i18n for these errors? "The record's community is not enrolled in the committee approval workflow. " @@ -103,7 +103,7 @@ def execute(self, identity: Identity, uow: UnitOfWork) -> None: # Fail fast: ensure the record belongs to an enrolled community before # the request is persisted as submitted. - config = _resolve_community_config(self.request) + enrollment = _resolve_enrollment(self.request) # Reject if the parent already carries an approval report number. if ( @@ -154,7 +154,7 @@ def execute(self, identity: Identity, uow: UnitOfWork) -> None: # referees can always see the version they approved. topic.parent.access.grants.create( subject_type="role", - subject_id=config["referee_group"], + subject_id=enrollment.referee_group, permission=COMMITTEE_APPROVAL_GRANT_PERMISSION, # `topic.id` = uuid and `topic["id"]` = the PID 🙃 origin=committee_approval_grant_origin(topic["id"], topic.versions.index), @@ -180,28 +180,18 @@ def execute(self, identity: Identity, uow: UnitOfWork) -> None: class CommitteeApprovalAcceptAction(actions.AcceptAction): """Accept action — auto-generate the approval report number and assign it.""" - def _community_config(self): - """Resolve the community config for this request (guaranteed enrolled at submit).""" - return _resolve_community_config(self.request) + def _enrollment(self): + """Resolve the enrollment for this request (guaranteed at submit).""" + return _resolve_enrollment(self.request) - def _next_report_number(self, rn: dict) -> str: + def _next_report_number(self, enrollment) -> str: """Return the next report number for this community without minting a PID. - Builds the scan prefix directly from the structured ``report_number`` - config — no string-format parsing needed. - Args: - rn: the ``report_number`` sub-dict from the community config, with keys: - - ``prefix`` (str): fixed prefix, e.g. ``"CERN-EP"`` - - ``include_year`` (bool, default ``True``): append ``-{year}`` - - ``counter_digits`` (int, default ``3``): zero-padding width + enrollment: the ``CommitteeApprovalEnrollment`` entry, which defines the + prefix, whether the year is included, and the counter width. """ - prefix = rn["prefix"] - digits = rn.get("counter_digits", 3) - year = date.today().year - scan_prefix = ( - f"{prefix}-{year}-" if rn.get("include_year", True) else f"{prefix}-" - ) + scan_prefix = enrollment.report_number_scan_prefix() existing = PersistentIdentifier.query.filter( PersistentIdentifier.pid_type == APPRN_PID_TYPE, @@ -215,15 +205,15 @@ def _next_report_number(self, rn: dict) -> str: ), default=0, ) - return f"{scan_prefix}{max_seq + 1:0{digits}d}" + return enrollment.format_report_number(max_seq + 1) - def _issue_report_number(self, config: dict, record_uuid: str) -> str: + def _issue_report_number(self, enrollment, record_uuid: str) -> str: """Generate the next report number and mint its PID. Delegates number generation to ``_next_report_number`` (testable independently) then registers the result in pidstore. """ - report_number = self._next_report_number(config["report_number"]) + report_number = self._next_report_number(enrollment) PersistentIdentifier.create( pid_type=APPRN_PID_TYPE, pid_value=report_number, @@ -242,9 +232,9 @@ def execute(self, identity: Identity, uow: UnitOfWork) -> None: CommitteeApprovalComponent when the public approved record is created (detected by the presence of source_internal_version on the public parent). """ - config = self._community_config() + enrollment = self._enrollment() topic = self.request.topic.resolve() - report_number = self._issue_report_number(config, str(topic.id)) + report_number = self._issue_report_number(enrollment, str(topic.id)) # Write committee_approval into permission_flags — single source of truth. pf = topic.parent.get("permission_flags") or {} diff --git a/site/cds_rdm/requests/committee_approval_state.py b/site/cds_rdm/requests/committee_approval_state.py index 76a966d9..6772f882 100644 --- a/site/cds_rdm/requests/committee_approval_state.py +++ b/site/cds_rdm/requests/committee_approval_state.py @@ -14,24 +14,17 @@ from invenio_rdm_records.requests.record_deletion import current_rdm_records_service from invenio_requests.proxies import current_requests_service +from cds_rdm.committee_approval_enrollments.utils import ( + get_committee_approval_enrollment, +) -def _approval_label(community_config=None): - """Return the UI label for this workflow.""" - return (community_config or {}).get("label") - -def _committee_name(community_config=None): - """Return the configured reviewer/board name for this workflow.""" - return (community_config or {}).get("committee_name") - - -def _get_enrolled_community(record_ui): - """Return (community_id, community_config) for enrolled communities, else (None, None).""" - ep_communities = current_app.config.get("CDS_COMMITTEE_APPROVAL_COMMUNITIES", {}) +def _get_enrollment(record_ui): + """Return (community_id, enrollment) if the community is enrolled, else (None, None).""" parent = record_ui.get("parent", {}) if record_ui else {} default_community_id = parent.get("communities", {}).get("default") - config = ep_communities.get(default_community_id) if default_community_id else None - return (default_community_id, config) if config else (None, None) + enrollment = get_committee_approval_enrollment(default_community_id) + return (default_community_id, enrollment) if enrollment else (None, None) def _get_parent_committee_approval(record): @@ -162,7 +155,7 @@ def get_committee_approval_state(record_ui, record=None): """ # Read committee_approval from the parent. ea = _get_parent_committee_approval(record) - community_id, community_config = _get_enrolled_community(record_ui) + community_id, enrollment = _get_enrollment(record_ui) # Early exit: this IS the public committee-approved copy. # The public record's parent has source_internal_version set. @@ -180,8 +173,8 @@ def get_committee_approval_state(record_ui, record=None): return { "can_submit": False, "can_create_public": False, - "approval_label": _approval_label(community_config), - "committee_name": _committee_name(community_config), + "approval_label": enrollment.label if enrollment else None, + "committee_name": enrollment.committee_name if enrollment else None, "community_enrolled": False, "is_public_approved_record": True, "open_request": None, @@ -199,7 +192,7 @@ def get_committee_approval_state(record_ui, record=None): return { "can_submit": False, "can_create_public": False, - "approval_label": _approval_label(), + "approval_label": None, "committee_name": None, "community_enrolled": False, "is_public_approved_record": False, @@ -224,14 +217,14 @@ def get_committee_approval_state(record_ui, record=None): open_request = _get_open_request(record_id, parent_record) approved_report_number = ea.get("reportnumber") - community_read_only = community_config.get("read_only", False) + community_read_only = enrollment.read_only if community_read_only: if not approved_report_number: return { "can_submit": False, "can_create_public": False, - "approval_label": _approval_label(community_config), - "committee_name": _committee_name(community_config), + "approval_label": enrollment.label, + "committee_name": enrollment.committee_name, "community_enrolled": False, "is_public_approved_record": False, "open_request": None, @@ -255,8 +248,8 @@ def get_committee_approval_state(record_ui, record=None): return { "can_submit": can_submit, "can_create_public": can_create_public, - "approval_label": _approval_label(community_config), - "committee_name": _committee_name(community_config), + "approval_label": enrollment.label, + "committee_name": enrollment.committee_name, "community_enrolled": True, "is_public_approved_record": False, "open_request": open_request, @@ -265,6 +258,6 @@ def get_committee_approval_state(record_ui, record=None): "committee_approval": ea, "draft_record_id": None, "can_view_reviewed_version": False, - "receiver_group": community_config.get("referee_group"), + "receiver_group": enrollment.referee_group, "cern_scientific_community_id": cern_scientific_community_id, } diff --git a/site/cds_rdm/requests/views.py b/site/cds_rdm/requests/views.py index bca54717..d26b8453 100644 --- a/site/cds_rdm/requests/views.py +++ b/site/cds_rdm/requests/views.py @@ -27,6 +27,10 @@ from invenio_requests.proxies import current_requests_service from invenio_requests.resolvers.registry import ResolverRegistry +from cds_rdm.committee_approval_enrollments.utils import ( + get_committee_approval_enrollment, +) + from .committee_approval import CommitteeApprovalRequest @@ -62,12 +66,8 @@ def submit_committee_approval(pid_value): default_community_id = ( record._record.parent.get("communities", {}) or {} ).get("default") - approval_label = ( - current_app.config.get("CDS_COMMITTEE_APPROVAL_COMMUNITIES", {}) - .get(default_community_id, {}) - .get("label") - or "Committee approval" - ) + enrollment = get_committee_approval_enrollment(default_community_id) + approval_label = (enrollment and enrollment.label) or "Committee approval" payload["approval_label"] = approval_label req = current_requests_service.create( identity=g.identity, diff --git a/site/cds_rdm/views.py b/site/cds_rdm/views.py index 37fbfba7..d245f955 100644 --- a/site/cds_rdm/views.py +++ b/site/cds_rdm/views.py @@ -44,6 +44,12 @@ def create_cds_clc_sync_bp(app): return ext.clc_sync_resource.as_blueprint() +def create_committee_approval_enrollments_bp(app): + """Create committee approval communities blueprint.""" + ext = app.extensions["cds-rdm"] + return ext.committee_approval_enrollments_resource.as_blueprint() + + def create_harvester_download_bp(app): """Create harvester log download blueprint.""" ext = app.extensions["cds-rdm"] diff --git a/site/pyproject.toml b/site/pyproject.toml index 3f0e3253..900b330f 100644 --- a/site/pyproject.toml +++ b/site/pyproject.toml @@ -19,6 +19,7 @@ harvester_report = "cds_rdm.administration.harvester_reports:create_harvester_re [project.entry-points."invenio_base.api_blueprints"] clc_sync = "cds_rdm.views:create_cds_clc_sync_bp" committee_approval = "cds_rdm.requests.views:create_committee_approval_bp" +committee_approval_enrollments = "cds_rdm.views:create_committee_approval_enrollments_bp" [project.entry-points."invenio_celery.tasks"] cds_rdm_tasks = "cds_rdm.tasks" @@ -52,10 +53,15 @@ cds_rdm = "cds_rdm:alembic" [project.entry-points."invenio_db.models"] cds_migration_models = "cds_rdm.legacy.models" cds_clc_sync_model = "cds_rdm.clc_sync.models" +cds_committee_approval_enrollments_model = "cds_rdm.committee_approval_enrollments.models" [project.entry-points."invenio_administration.views"] clc_sync_list = "cds_rdm.administration.clc_sync:CLCSyncListView" clc_sync_detail = "cds_rdm.administration.clc_sync:CLCSyncDetailView" +committee_approval_enrollments_list = "cds_rdm.administration.committee_approval_enrollments:CommitteeApprovalEnrollmentListView" +committee_approval_enrollments_create = "cds_rdm.administration.committee_approval_enrollments:CommitteeApprovalEnrollmentCreateView" +committee_approval_enrollments_edit = "cds_rdm.administration.committee_approval_enrollments:CommitteeApprovalEnrollmentEditView" +committee_approval_enrollments_detail = "cds_rdm.administration.committee_approval_enrollments:CommitteeApprovalEnrollmentDetailView" harvester_reports = "cds_rdm.administration.harvester_reports:HarvesterReportsView" [project.entry-points."invenio_access.actions"] diff --git a/site/tests/conftest.py b/site/tests/conftest.py index 15498a81..1ddb9585 100644 --- a/site/tests/conftest.py +++ b/site/tests/conftest.py @@ -66,6 +66,7 @@ from cds_rdm import schemes from cds_rdm.api import CDSRDMDraft, CDSRDMRecord +from cds_rdm.committee_approval_enrollments.models import CommitteeApprovalEnrollment from cds_rdm.components import CommitteeApprovalComponent from cds_rdm.custom_fields import CUSTOM_FIELDS, CUSTOM_FIELDS_UI, NAMESPACES from cds_rdm.inspire_harvester.reader import InspireHTTPReader @@ -353,11 +354,6 @@ def app_config(app_config, mock_datacite_client, mock_crossref_client): CommunityInclusionSubmittedNotificationBuilder.type: DummyNotificationBuilder, } - # Committee Approval communities — static dummy UUIDs for config-lookup tests. - # Tests that run the full accept action add their real community UUID at - # fixture time by mutating this dict directly (see committee_enrolled_community fixture). - app_config["CDS_COMMITTEE_APPROVAL_COMMUNITIES"] = {} - app_config["RDM_RECORDS_SERVICE_COMPONENTS"] = [ CommitteeApprovalComponent, *DefaultRecordsComponents, @@ -1872,8 +1868,21 @@ def _publish_record_in_community(identity, record_data, community, service): @pytest.fixture() -def committee_enrolled_community(community_service, running_app): - """Community enrolled in CDS_COMMITTEE_APPROVAL_COMMUNITIES.""" +def ep_referee_group(app, db): + """Create the EP referee role/group in the DB.""" + ds = app.extensions["invenio-accounts"].datastore + role = ds.create_role( + id="cds-ph-ep-publication", + name="cds-ph-ep-publication", + description="EP publication committee", + ) + db.session.commit() + return role + + +@pytest.fixture() +def committee_enrolled_community(community_service, running_app, db, ep_referee_group): + """Community enrolled in the committee approval workflow (DB entry).""" community_data = { "access": { "visibility": "public", @@ -1885,21 +1894,23 @@ def committee_enrolled_community(community_service, running_app): } community = community_service.create(system_identity, community_data) Community.index.refresh() - current_app.config["CDS_COMMITTEE_APPROVAL_COMMUNITIES"][str(community.id)] = { - "label": "Committee approval", - "referee_group": "cds-ph-ep-publication", - "report_number": { - "prefix": "CERN-EP", - "include_year": True, - "counter_digits": 3, - }, - } + CommitteeApprovalEnrollment.create( + { + "community_id": community.id, + "label": "Committee approval", + "referee_group": ep_referee_group.id, + "report_number_prefix": "CERN-EP", + "report_number_include_year": True, + "report_number_counter_digits": 3, + } + ) + db.session.commit() return community._record @pytest.fixture() def committee_non_enrolled_community(community_service, running_app): - """Community NOT enrolled in CDS_COMMITTEE_APPROVAL_COMMUNITIES.""" + """Community NOT enrolled in the committee approval workflow.""" community_data = { "access": { "visibility": "public", @@ -1911,7 +1922,7 @@ def committee_non_enrolled_community(community_service, running_app): } community = community_service.create(system_identity, community_data) Community.index.refresh() - # Deliberately not added to CDS_COMMITTEE_APPROVAL_COMMUNITIES. + # Deliberately not enrolled (no CommitteeApprovalEnrollment entry). return community._record diff --git a/site/tests/inspire_harvester/test_transformer.py b/site/tests/inspire_harvester/test_transformer.py index f40b9fa8..fa57fa2e 100644 --- a/site/tests/inspire_harvester/test_transformer.py +++ b/site/tests/inspire_harvester/test_transformer.py @@ -11,6 +11,7 @@ import pytest from edtf.parser.grammar import ParseException +from cds_rdm.committee_approval_enrollments.models import CommitteeApprovalEnrollment from cds_rdm.inspire_harvester.logger import Logger from cds_rdm.inspire_harvester.transform.context import MetadataSerializationContext from cds_rdm.inspire_harvester.transform.mappers.article import ArticleFilesMapper @@ -191,9 +192,7 @@ def test_transform_related_identifiers_dedupes_urls(running_app): "metadata": {"urls": [{"value": url}, {"value": url}]}, "created": "2023-01-01", } - ctx = MetadataSerializationContext( - resource_type=ResourceType.OTHER, inspire_id="1" - ) + ctx = MetadataSerializationContext(resource_type=ResourceType.OTHER, inspire_id="1") logger = Logger(inspire_id="1") result = RelatedIdentifiersMapper().map_value(src_record, ctx, logger) @@ -272,9 +271,7 @@ def test_transform_funding_funder_only(): """Map funding_info with agency only when no grant number is present.""" from cds_rdm.inspire_harvester.transform.mappers.funding import FundingMapper - src_metadata = { - "funding_info": [{"agency": "Agence Nationale de la Recherche"}] - } + src_metadata = {"funding_info": [{"agency": "Agence Nationale de la Recherche"}]} ctx = MetadataSerializationContext( resource_type=ResourceType.OTHER, inspire_id="12345" ) @@ -293,9 +290,7 @@ def test_transform_funding_missing_funder_errors(): """Raise curator error when agency cannot be resolved to a funder id.""" from cds_rdm.inspire_harvester.transform.mappers.funding import FundingMapper - src_metadata = { - "funding_info": [{"agency": "Unknown Funding Agency XYZ"}] - } + src_metadata = {"funding_info": [{"agency": "Unknown Funding Agency XYZ"}]} ctx = MetadataSerializationContext( resource_type=ResourceType.OTHER, inspire_id="12345" ) @@ -341,15 +336,13 @@ def test_transform_funding_missing_award_errors(): assert "Award not found in vocabulary" in ctx.errors[0] -def test_transform_report_numbers_as_identifiers(running_app): +def test_transform_report_numbers_as_identifiers(running_app, monkeypatch): """CERN- report numbers go to identifiers; EP prefixes use apprn.""" - from flask import current_app - - current_app.config["CDS_COMMITTEE_APPROVAL_COMMUNITIES"] = { - "ep-community": { - "report_number": {"prefix": "CERN-EP"}, - } - } + monkeypatch.setattr( + CommitteeApprovalEnrollment, + "get_report_number_prefixes", + classmethod(lambda cls: {"CERN-EP"}), + ) src_metadata = { "report_numbers": [ {"value": "CERN-EP-2026-001"}, @@ -373,7 +366,10 @@ def test_transform_report_numbers_as_identifiers(running_app): assert {"identifier": "CERN-EP-2026-001", "scheme": "apprn"} in identifiers assert {"identifier": "CERN-EP-DRAFT-2026-001", "scheme": "cdsrn"} in identifiers assert {"identifier": "CERN-THESIS-2010-364", "scheme": "cdsrn"} in identifiers - assert not any(i.get("scheme") == "cdsrn" and i.get("identifier") == "CERN-EP-2026-001" for i in identifiers) + assert not any( + i.get("scheme") == "cdsrn" and i.get("identifier") == "CERN-EP-2026-001" + for i in identifiers + ) assert any( i.get("scheme") == "cdsrn" and i.get("identifier") == "DESY-24-001" for i in related @@ -416,7 +412,9 @@ def test_matcher_includes_approval_report_number(running_app): ) assert any( q.to_dict() - == {"term": {"metadata.related_identifiers.relation_type.id": "isvariantformof"}} + == { + "term": {"metadata.related_identifiers.relation_type.id": "isvariantformof"} + } for q in by_type[RelatedReportNumberMatchFilter].query ) @@ -568,7 +566,9 @@ def test_transform_related_identifiers_includes_extra_dois(mock_is_doi, running_ logger = Logger(inspire_id="12345") mapper = RelatedIdentifiersMapper() src_record = { - "metadata": {"dois": [{"value": "10.1000/test1"}, {"value": "10.1000/external"}]}, + "metadata": { + "dois": [{"value": "10.1000/test1"}, {"value": "10.1000/external"}] + }, "created": "2023-01-01", } diff --git a/site/tests/inspire_harvester/test_validator.py b/site/tests/inspire_harvester/test_validator.py index 3dbef6cc..f296d1ee 100644 --- a/site/tests/inspire_harvester/test_validator.py +++ b/site/tests/inspire_harvester/test_validator.py @@ -12,6 +12,7 @@ from flask import current_app from invenio_pidstore.models import PersistentIdentifier, PIDStatus +from cds_rdm.committee_approval_enrollments.models import CommitteeApprovalEnrollment from cds_rdm.inspire_harvester.load.validator import ( EpApprovalPidstoreRule, RecordValidator, @@ -33,13 +34,13 @@ def _entry_with_apprn(number): ) -def test_mapper_stores_ep_report_number_as_apprn(running_app): +def test_mapper_stores_ep_report_number_as_apprn(running_app, monkeypatch): """EP report numbers from INSPIRE are mapped with scheme apprn for the rule.""" - current_app.config["CDS_COMMITTEE_APPROVAL_COMMUNITIES"] = { - "ep-community": { - "report_number": {"prefix": "CERN-EP"}, - } - } + monkeypatch.setattr( + CommitteeApprovalEnrollment, + "get_report_number_prefixes", + classmethod(lambda cls: {"CERN-EP"}), + ) number = "CERN-EP-2099-001" identifiers = IdentifiersMapper().map_value( { diff --git a/site/tests/test_committee_approval.py b/site/tests/test_committee_approval.py index 60dd0560..a3113af3 100644 --- a/site/tests/test_committee_approval.py +++ b/site/tests/test_committee_approval.py @@ -31,6 +31,7 @@ from invenio_users_resources.records.api import UserAggregate from marshmallow import ValidationError +from cds_rdm.committee_approval_enrollments.models import CommitteeApprovalEnrollment from cds_rdm.generators import ( COMMITTEE_APPROVAL_GRANT_PERMISSION, committee_approval_grant_origin, @@ -50,8 +51,16 @@ # --------------------------------------------------------------------------- YEAR = date.today().year -EP_RN_CONFIG = {"prefix": "CERN-EP", "include_year": True, "counter_digits": 3} -TH_RN_CONFIG = {"prefix": "CERN-TH", "include_year": True, "counter_digits": 3} +EP_RN_CONFIG = CommitteeApprovalEnrollment( + report_number_prefix="CERN-EP", + report_number_include_year=True, + report_number_counter_digits=3, +) +TH_RN_CONFIG = CommitteeApprovalEnrollment( + report_number_prefix="CERN-TH", + report_number_include_year=True, + report_number_counter_digits=3, +) EP_GROUP_NAME = "cds-ph-ep-publication" @@ -60,19 +69,6 @@ # --------------------------------------------------------------------------- -@pytest.fixture() -def ep_referee_group(app, db): - """Create the EP referee role/group in the DB.""" - ds = app.extensions["invenio-accounts"].datastore - role = ds.create_role( - id=EP_GROUP_NAME, - name=EP_GROUP_NAME, - description="EP publication committee", - ) - db.session.commit() - return role - - @pytest.fixture() def ep_request_payload(): """Minimal valid EP approval request payload.""" @@ -216,10 +212,15 @@ def __call__(self, notification, recipients): monkeypatch.setattr( generators, "CommunityMembersRecipient", FakeCommunityMembersRecipient ) - config = { - "CDS_COMMITTEE_APPROVAL_COMMUNITIES": {"community-1": {}} if enrolled else {} - } - monkeypatch.setattr(generators, "current_app", SimpleNamespace(config=config)) + monkeypatch.setattr( + generators, + "get_committee_approval_enrollment", + lambda community_id: ( + SimpleNamespace(label="EP approval") + if enrolled and community_id == "community-1" + else None + ), + ) record = SimpleNamespace(parent={"communities": {"default": "community-1"}}) notification = Notification( @@ -1007,7 +1008,8 @@ def test_apprn_identifier_cannot_be_manually_changed( service.edit(system_identity, id_=record_a.id) draft_data = service.read_draft(uploader.identity, id_=record_a.id).data identifiers_without_apprn = [ - i for i in draft_data["metadata"].get("identifiers", []) + i + for i in draft_data["metadata"].get("identifiers", []) if i.get("scheme") != "apprn" ] @@ -1016,8 +1018,13 @@ def test_apprn_identifier_cannot_be_manually_changed( service.update_draft( uploader.identity, id_=record_a.id, - data={**draft_data, "metadata": {**draft_data["metadata"], - "identifiers": identifiers_without_apprn}}, + data={ + **draft_data, + "metadata": { + **draft_data["metadata"], + "identifiers": identifiers_without_apprn, + }, + }, ) # Non-system: add a different apprn → rejected. @@ -1025,10 +1032,14 @@ def test_apprn_identifier_cannot_be_manually_changed( service.update_draft( uploader.identity, id_=record_a.id, - data={**draft_data, "metadata": {**draft_data["metadata"], - "identifiers": identifiers_without_apprn + [ - {"scheme": "apprn", "identifier": "CERN-EP-2099-999"} - ]}}, + data={ + **draft_data, + "metadata": { + **draft_data["metadata"], + "identifiers": identifiers_without_apprn + + [{"scheme": "apprn", "identifier": "CERN-EP-2099-999"}], + }, + }, ) # --- Record B: no committee_approval; system tries to add apprn --- @@ -1041,8 +1052,12 @@ def test_apprn_identifier_cannot_be_manually_changed( service.update_draft( system_identity, id_=sys_draft_b.id, - data={**draft_b_data, "metadata": {**draft_b_data["metadata"], - "identifiers": draft_b_data["metadata"].get("identifiers", []) + [ - {"scheme": "apprn", "identifier": report_number} - ]}}, + data={ + **draft_b_data, + "metadata": { + **draft_b_data["metadata"], + "identifiers": draft_b_data["metadata"].get("identifiers", []) + + [{"scheme": "apprn", "identifier": report_number}], + }, + }, )