diff --git a/assets/js/components/deposit/overrides/PublishModal.js b/assets/js/components/deposit/overrides/PublishModal.js index cfa433ad..bd3f4250 100644 --- a/assets/js/components/deposit/overrides/PublishModal.js +++ b/assets/js/components/deposit/overrides/PublishModal.js @@ -4,14 +4,108 @@ // 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. -import React from "react"; +import React, { useEffect, useState } from "react"; +import PropTypes from "prop-types"; import { i18next } from "@translations/invenio_rdm_records/i18next"; import { SubmitReviewModal, PublishModal } from "@js/invenio_rdm_records"; -import { parametrize } from "react-overridable"; +import { useFormikContext } from "formik"; +import { useSelector } from "react-redux"; +import { http } from "react-invenio-forms"; +import _get from "lodash/get"; +import { Message, Icon } from "semantic-ui-react"; + +/** + * Informs the user about the CERN Research Community side effects of publishing. + * The decision (include / remove / nothing) is made by the backend + * (`get_community_inclusion_action`), so the rules live in a single place. + * + * Wraps the base modal so that the *deposit form* values (outer formik context) + * can be read; the modal renders its own inner formik context. + */ +const withCommunityInclusionMessages = (Modal) => { + // Render the original (non-overridable) modal: the registry maps the modal's + // container id to this very component, so using the overridable one recurses. + // `parametrize` is not used because its params win over props, which would + // discard the conditional `extraCheckboxes` below. + const ModalComponent = Modal.originalComponent || Modal; + + const Wrapped = (props) => { + const { values } = useFormikContext(); + const pid = useSelector((state) => state.deposit.record?.id); + const [action, setAction] = useState(null); + + const access = _get(values, "access.record"); + const resourceType = _get(values, "metadata.resource_type.id"); + + useEffect(() => { + let active = true; + http + .post("/api/cds/community-inclusion", { + pid, + access, + resource_type: resourceType, + }) + .then((response) => active && setAction(response.data?.action)) + .catch(() => active && setAction(null)); + return () => { + active = false; + }; + }, [pid, access, resourceType]); + + let beforeContent = props.beforeContent; + if (action === "remove") { + beforeContent = () => ( + +

+ + {i18next.t( + "You are making this record restricted. The record, including all its versions, will be removed from the CERN Research Community (or its pending inclusion request will be cancelled). Do you want to continue?" + )} +

+
+ ); + } + + const includesInCommunity = action === "include"; + return ( + + ); + }; + Wrapped.propTypes = { + beforeContent: PropTypes.func, + }; + + Wrapped.defaultProps = { + beforeContent: undefined, + }; + + return Wrapped; +}; + +const communityInclusionCheckbox = { + id: "accept-community-inclusion-checkbox", + fieldPath: "acceptCommunityInclusion", + text: i18next.t( + "I understand that once published, this record will also be submitted for inclusion in the CERN Research Community." + ), +}; export const parameters = { extraCheckboxes: [ { + id: "accept-terms-of-service-checkbox", fieldPath: "acceptTermsOfService", text: ( <> @@ -46,6 +140,7 @@ export const parameters = { ], }; -export const SubmitReviewModalComponent = parametrize(SubmitReviewModal, parameters); +export const SubmitReviewModalComponent = + withCommunityInclusionMessages(SubmitReviewModal); -export const PublishModalComponent = parametrize(PublishModal, parameters); +export const PublishModalComponent = withCommunityInclusionMessages(PublishModal); diff --git a/invenio.cfg b/invenio.cfg index 2f61b483..781e80fe 100644 --- a/invenio.cfg +++ b/invenio.cfg @@ -84,7 +84,7 @@ from invenio_app_rdm.config import \ from invenio_app_rdm.config import \ VOCABULARIES_DATASTREAM_WRITERS as DEFAULT_VOCABULARIES_DATASTREAM_WRITERS from cds_rdm.clc_sync.services.components import ClcSyncComponent -from cds_rdm.components import CDSResourcePublication, CommitteeApprovalComponent, MintAlternateIdentifierComponent, SubjectsValidationComponent # PublicationInclusionComponent temporarily disabled +from cds_rdm.components import CDSResourcePublication, CommitteeApprovalComponent, MintAlternateIdentifierComponent, SubjectsValidationComponent, PublicationInclusionComponent from cds_rdm.pids import validate_optional_doi_transitions from cds_rdm.views import archive_link_render, frontpage_view_function, inspire_link_render from cds_rdm.reviews.policy import CDSRecordVersionReviewPolicy @@ -810,7 +810,7 @@ RDM_RECORDS_SERVICE_COMPONENTS = [ CDSResourcePublication, ClcSyncComponent, MintAlternateIdentifierComponent, - # PublicationInclusionComponent, # temporarily disabled + PublicationInclusionComponent, VCSComponent, ] diff --git a/site/cds_rdm/components.py b/site/cds_rdm/components.py index 26719e13..683cd782 100644 --- a/site/cds_rdm/components.py +++ b/site/cds_rdm/components.py @@ -21,7 +21,10 @@ from marshmallow import ValidationError from .tasks import ( - sync_alternate_identifiers, # submit_community_inclusion_request temporarily disabled + find_open_inclusion_request_ids, + remove_from_scientific_community, + submit_community_inclusion_request, + sync_alternate_identifiers, ) @@ -377,58 +380,110 @@ def publish(self, identity, draft=None, record=None): ) -# PublicationInclusionComponent temporarily disabled -# class PublicationInclusionComponent(ServiceComponent): -# """Auto-submit a community inclusion request to the CERN Scientific Community. -# -# Triggers on publish for public records whose resource type is listed in -# `CDS_CERN_SCIENTIFIC_RESOURCE_TYPES`. The request is created asynchronously -# after the publish transaction commits. -# """ -# -# def _is_eligible(self, draft, record): -# """Return True when the record should be auto-submitted for community inclusion.""" -# if not is_record_public(draft): -# return False -# -# resource_type = draft["metadata"]["resource_type"]["id"] -# research_resource_types = current_app.config.get( -# "CDS_CERN_SCIENTIFIC_RESOURCE_TYPES", set() -# ) -# if resource_type not in research_resource_types: -# return False -# -# # Skip if the record is in the Scientific Community or the Related Research Community already -# # IMPORTANT: -# # 1. For thesis, we have the component CDSResourcePublication to validate the community selection -# # 2. For other resource types, it is highly unlikely that the record is NOT eligible for inclusion -# # in the CERN Research Community, since these works typically belong to CERN -# # On the off chance if there is a rare case, it will be dealt via support on case by case basis -# communities_to_skip = [ -# current_app.config["CDS_CERN_SCIENTIFIC_COMMUNITY_ID"], -# current_app.config["CDS_CERN_RELATED_RESEARCH_COMMUNITY_ID"], -# ] -# for community_id in communities_to_skip: -# if not community_id: -# current_app.logger.error( -# f"Scientific Community IDs are not configured; " -# "skipping auto community inclusion for record %s.", -# record.pid.pid_value, -# ) -# return False -# if community_id in record.parent.communities.ids: -# return False -# -# return True -# -# def publish(self, identity, draft=None, record=None, **kwargs): -# """Schedule community inclusion request after the record is published.""" -# if not self._is_eligible(draft, record): -# return -# -# self.uow.register( -# TaskOp( -# submit_community_inclusion_request, -# record_id=record.pid.pid_value, -# ) -# ) +COMMUNITY_INCLUSION_INCLUDE = "include" +COMMUNITY_INCLUSION_REMOVE = "remove" + + +def _get_record_community_ids(parent): + """Return the communities of a record, including the ones it is about to join. + + Besides the communities the record belongs to, this covers the selected + (default) community and the receiver of a pending review, since records + submitted to a community are published only when the review is accepted. + """ + if not parent: + return set() + community_ids = set(parent.communities.ids) + default = parent.get("communities", {}).get("default") + if default: + community_ids.add(default) + review_community = ( + parent.review is not None + and parent.review.receiver.reference_dict.get("community") + ) + if review_community: + community_ids.add(review_community) + return community_ids + + +def get_community_inclusion_action(is_public, resource_type, parent=None): + """Decide what happens with the CERN Scientific Community on publish. + + Single source of truth, used by `PublicationInclusionComponent` and by the + deposit form (through the API) to inform the user before publishing. + + :param is_public: whether the record will be public. + :param resource_type: resource type id of the record. + :param parent: parent of the record (None if not created yet). Communities + and inclusion requests are shared by all the versions of a record, so + the outcome applies to every version. + :returns: ``COMMUNITY_INCLUSION_INCLUDE``, ``COMMUNITY_INCLUSION_REMOVE`` + or ``None``. + """ + scientific_id = current_app.config.get("CDS_CERN_SCIENTIFIC_COMMUNITY_ID") + if not scientific_id: + current_app.logger.error( + "Scientific Community ID is not configured; " + "skipping auto community inclusion." + ) + return None + + community_ids = _get_record_community_ids(parent) + has_open_request = bool( + parent and find_open_inclusion_request_ids(scientific_id, parent) + ) + + if not is_public: + # Only public records can be part of (or be pending for) the community. + if scientific_id in community_ids or has_open_request: + return COMMUNITY_INCLUSION_REMOVE + return None + + research_resource_types = current_app.config.get( + "CDS_CERN_SCIENTIFIC_RESOURCE_TYPES", set() + ) + if resource_type not in research_resource_types or has_open_request: + return None + + # Skip if the record is in the Scientific Community or the Related Research Community already + # IMPORTANT: + # 1. For thesis, we have the component CDSResourcePublication to validate the community selection + # 2. For other resource types, it is highly unlikely that the record is NOT eligible for inclusion + # in the CERN Research Community, since these works typically belong to CERN + # On the off chance if there is a rare case, it will be dealt via support on case by case basis + communities_to_skip = [ + scientific_id, + # The related research community is optional (may not be configured). + current_app.config.get("CDS_CERN_RELATED_RESEARCH_COMMUNITY_ID"), + ] + if any(c and c in community_ids for c in communities_to_skip): + return None + + return COMMUNITY_INCLUSION_INCLUDE + + +class PublicationInclusionComponent(ServiceComponent): + """Auto-submit a community inclusion request to the CERN Scientific Community. + + On publish, public records whose resource type is listed in + `CDS_CERN_SCIENTIFIC_RESOURCE_TYPES` are submitted to the community, and + records made restricted are removed from it (see + `get_community_inclusion_action`). The work is done asynchronously after the + publish transaction commits. + """ + + def publish(self, identity, draft=None, record=None, **kwargs): + """Schedule community inclusion (or removal) after the record is published.""" + action = get_community_inclusion_action( + is_record_public(draft), + draft["metadata"]["resource_type"]["id"], + record.parent, + ) + if action == COMMUNITY_INCLUSION_INCLUDE: + task = submit_community_inclusion_request + elif action == COMMUNITY_INCLUSION_REMOVE: + task = remove_from_scientific_community + else: + return + + self.uow.register(TaskOp(task, record_id=record.pid.pid_value)) diff --git a/site/cds_rdm/requests/views.py b/site/cds_rdm/requests/views.py index bca54717..a79008c6 100644 --- a/site/cds_rdm/requests/views.py +++ b/site/cds_rdm/requests/views.py @@ -27,6 +27,7 @@ from invenio_requests.proxies import current_requests_service from invenio_requests.resolvers.registry import ResolverRegistry +from ..components import get_community_inclusion_action from .committee_approval import CommitteeApprovalRequest @@ -34,6 +35,45 @@ def create_committee_approval_bp(app): """Create committee approval API blueprint.""" bp = Blueprint("cds_committee_approval", __name__) + @bp.route("/cds/community-inclusion", methods=["POST"]) + @login_required + def community_inclusion(): + """Tell what publishing does with the CERN Scientific Community. + + Used by the deposit form (``pid`` + the possibly unsaved ``access`` and + ``resource_type``) and by the community submission request page + (``request_id``), to inform the user before publishing. + Returns ``{"action": "include"|"remove"|null}``. + """ + body = request.get_json(force=True) or {} + pid_value = body.get("pid") + + try: + if body.get("request_id"): + req = current_requests_service.read(g.identity, body["request_id"]) + pid_value = req.data.get("topic", {}).get("record") + draft = ( + current_rdm_records_service.read_draft(g.identity, pid_value) + if pid_value + else None + ) + except (PIDDoesNotExistError, PermissionDeniedError): + return jsonify({"message": "Record not found."}), 404 + + access = body.get("access") + resource_type = body.get("resource_type") + if draft is not None and (access is None or resource_type is None): + # Not given by the client: use the saved draft. + access = access or draft.data["access"]["record"] + resource_type = resource_type or draft.data["metadata"]["resource_type"]["id"] + + action = get_community_inclusion_action( + access == "public", + resource_type, + draft._record.parent if draft is not None else None, + ) + return jsonify({"action": action}) + @bp.route("/records//committee-approval", methods=["POST"]) @login_required def submit_committee_approval(pid_value): diff --git a/site/cds_rdm/tasks.py b/site/cds_rdm/tasks.py index 949e5350..5df43e2d 100644 --- a/site/cds_rdm/tasks.py +++ b/site/cds_rdm/tasks.py @@ -20,6 +20,7 @@ from invenio_rdm_records.records.api import RDMRecord from invenio_records_resources.proxies import current_service_registry from invenio_records_resources.services.uow import UnitOfWork +from invenio_requests.proxies import current_requests_service from invenio_search.engine import dsl from invenio_users_resources.services.groups.tasks import reindex_groups from invenio_users_resources.services.users.tasks import reindex_users @@ -354,3 +355,80 @@ def submit_community_inclusion_request(record_id): record_id, processed[0].get("community_id"), ) + + +def find_open_inclusion_request_ids(community_id, parent): + """Return the ids of the open community inclusion requests of any version of a record. + + A request is bound to the version it was created for, but it concerns the + whole record (all versions share the parent and its communities). + """ + version_uuids = list( + RDMRecord.get_records_by_parent(parent, with_deleted=False, ids_only=True) + ) + record_ids = [ + pid.pid_value + for pid in PersistentIdentifier.query.filter( + PersistentIdentifier.pid_type == "recid", + PersistentIdentifier.object_type == "rec", + PersistentIdentifier.object_uuid.in_(version_uuids), + ) + ] + if not record_ids: + return [] + results = current_requests_service.search( + system_identity, + extra_filter=dsl.query.Bool( + "must", + must=[ + dsl.Q("term", **{"receiver.community": community_id}), + dsl.Q("terms", **{"topic.record": record_ids}), + dsl.Q("term", **{"type": "community-inclusion"}), + dsl.Q("term", **{"is_open": True}), + ], + ), + ) + return [hit["id"] for hit in results.hits] + + +@shared_task(ignore_result=True) +def remove_from_scientific_community(record_id): + """Remove a record from the CERN Scientific Community, or cancel its pending inclusion request. + + Used when a record is made restricted: only public records can be part of + (or be submitted to) the CERN Scientific Community. This applies to the whole + record, i.e. all its versions. + """ + community_id = current_app.config.get("CDS_CERN_SCIENTIFIC_COMMUNITY_ID") + if not community_id: + return + + record = RDMRecord.pid.resolve(record_id) + + if community_id in record.parent.communities.ids: + _, errors = current_record_communities_service.remove( + system_identity, record_id, {"communities": [{"id": community_id}]} + ) + if errors: + current_app.logger.error( + "Could not remove restricted record %s from community %s: %s", + record_id, + community_id, + errors, + ) + else: + current_app.logger.info( + "Removed restricted record %s from community %s.", + record_id, + community_id, + ) + return + + # Not a member (yet): cancel any open inclusion request. + for request_id in find_open_inclusion_request_ids(community_id, record.parent): + current_requests_service.execute_action(system_identity, request_id, "cancel") + current_app.logger.info( + "Cancelled community inclusion request %s for restricted record %s.", + request_id, + record_id, + )