Skip to content

oarepo_config.workflows

oarepo_config.workflows

Configuration for workflows.

Modules:

Name Description
low_level

Configuration for workflows.

simplified

OARepo application workflow configuration package.

BaseWorkflowSettings dataclass

Shared configuration common to all workflow types.

Source code in oarepo_config/workflows/simplified/base.py
@dataclasses.dataclass
class BaseWorkflowSettings:
    """Shared configuration common to all workflow types."""

    code: str = "undefined"
    """The code of the workflow type."""

    label: LazyString = _("Undefined policy")  # noqa: RUF009
    """The label of the workflow type."""

    base_permission_policy: type[Any] = DefaultRDMWorkflowPermissions
    """The base permission policy class for this workflow that will be configured."""

    base_request_policy: type[WorkflowRequestPolicy] = WorkflowRequestPolicy
    """The base requests policy class for this workflow that will be configured."""

    review_request_states: list[str] = dataclasses.field(default_factory=lambda: ["draft"])
    """Record workflow states in which a review request may be submitted."""

    record_view_permissions: dict[str, list[Generator]] = dataclasses.field(default_factory=dict)
    """View permissions for records in this workflow.

    It is a dictionary, the key is record state and the value is a list of generators.
    """

    publish_after_review: bool = True
    """Publish immediately after reviewer approves the review request."""

    extra_permissions: (
        type[BasePermissionPolicy] | Callable[[type[BasePermissionPolicy]], type[BasePermissionPolicy]] | None
    ) = None
    """Extra permissions to apply to the record permission policy.

    If a callable is provided, it will be called with the generated permission policy
    as an argument and should return a modified permission policy. If a class is provided,
    it will be used as a mixin for the generated permission policy.
    """

    extra_requests: (
        type[WorkflowRequestPolicy] | Callable[[type[WorkflowRequestPolicy]], type[WorkflowRequestPolicy]] | None
    ) = None
    """Extra requests to apply to the workflow request policy.

    If a callable is provided, it will be called with the generated request policy
    as an argument and should return a modified request policy. If a class is provided,
    it will be used as a mixin for the generated request policy.
    """

    authenticated_draft_creation: bool = False
    """Allow authenticated users to create draft records.

    When enabled and no role- or need-based restrictions are configured, any
    authenticated user may create a draft.  Subclasses may override this
    default (e.g. `IndividualWorkflow` sets it to `True`).
    """

    draft_creation_roles: list[str] = dataclasses.field(default_factory=list)
    """Restrict draft creation to users who hold at least one of these site-wide roles.

    When non-empty, takes priority over `authenticated_draft_creation`.
    """

    draft_creation_needs: list[str] = dataclasses.field(default_factory=list)
    """Restrict draft creation to users who hold at least one of these permission needs.

    When non-empty, takes priority over `authenticated_draft_creation`.
    """

    # --- public API -----------------------------------------------------------

    def build_workflow(self) -> Workflow:
        """Build and return the workflow instance."""
        permissions: type[BasePermissionPolicy] = self._build_permission_policy()
        request_policy: type[WorkflowRequestPolicy] = self._build_request_policy()
        if self.extra_permissions:
            if isinstance(self.extra_permissions, type):
                permissions = type(permissions.__name__, (self.extra_permissions, permissions), {})
            elif callable(self.extra_permissions):
                permissions = self.extra_permissions(permissions)
        if self.extra_requests:
            if isinstance(self.extra_requests, type):
                request_policy = type(request_policy.__name__, (self.extra_requests, request_policy), {})
            elif callable(self.extra_requests):
                request_policy = self.extra_requests(request_policy)

        return Workflow(
            code=self.code,
            label=self.label,
            permission_policy_cls=cast("Any", permissions),
            request_policy_cls=request_policy,
        )

    # --- protected helpers ----------------------------------------------------

    def _build_record_view_permissions(self) -> tuple[Generator, ...]:
        """Build per-state view permission generators from `record_view_permissions`.

        Returns:
            A tuple of `IfInState`
            generators - one per entry in `record_view_permissions` - or
            an empty tuple when no overrides are configured.

        """
        if not self.record_view_permissions:
            return ()
        return tuple(IfInState(state, then_=generators) for state, generators in self.record_view_permissions.items())

    def _build_record_create_generators(self) -> tuple[Generator, ...]:
        """Build generators that control who may create a new draft record.

        Applies the following priority order:

        1. **Role-based** - `draft_creation_roles`: users holding any of
           these site-wide roles are allowed.
        2. **Need-based** - `draft_creation_needs`: users possessing any
           of these permission needs are allowed.
        3. **Authenticated fallback** - when neither (1) nor (2) are set and
           `authenticated_draft_creation` is `True`, any authenticated
           user is allowed.

        Subclasses may call `super()._build_record_create_generators()` and
        extend the returned tuple with additional generators.

        Returns:
            A tuple of permission generators for the `can_create` policy action.

        """
        create_generators: list[Generator] = []
        if self.draft_creation_roles:
            create_generators += [UserWithRole(role) for role in self.draft_creation_roles]
        if self.draft_creation_needs:
            create_generators += [HasActionNeed(action) for action in self.draft_creation_needs]
        if not create_generators and self.authenticated_draft_creation:
            create_generators = [AuthenticatedUser()]
        return tuple(create_generators)

    def _create_request_policy(
        self,
        class_name: str,
        requests: dict[str, Any],
    ) -> type[WorkflowRequestPolicy]:
        """Dynamically create a named `WorkflowRequestPolicy` subclass.

        This is a thin convenience wrapper around `type` that removes the
        boilerplate of repeating `(self.base_request_policy,)` in every
        `_build_request_policy` override.

        Args:
            class_name: The `__name__` to assign to the generated class.
            requests: A mapping of request-type IDs to
                `WorkflowRequest` instances
                that will become class-level attributes of the new policy.

        Returns:
            A freshly created subclass of `base_request_policy` with
            *requests* merged in as class attributes.

        """
        return type(class_name, (self.base_request_policy,), requests)

    @abc.abstractmethod
    def _build_permission_policy(self) -> type[BasePermissionPolicy]:
        """Build and return the permission policy class for this workflow."""
        raise NotImplementedError

    @abc.abstractmethod
    def _build_request_policy(self) -> type[WorkflowRequestPolicy]:
        """Build and return the request policy class for this workflow."""
        raise NotImplementedError

code: str = 'undefined' class-attribute instance-attribute

The code of the workflow type.

label: LazyString = _('Undefined policy') class-attribute instance-attribute

The label of the workflow type.

base_permission_policy: type[Any] = DefaultRDMWorkflowPermissions class-attribute instance-attribute

The base permission policy class for this workflow that will be configured.

base_request_policy: type[WorkflowRequestPolicy] = WorkflowRequestPolicy class-attribute instance-attribute

The base requests policy class for this workflow that will be configured.

review_request_states: list[str] = dataclasses.field(default_factory=lambda: ['draft']) class-attribute instance-attribute

Record workflow states in which a review request may be submitted.

record_view_permissions: dict[str, list[Generator]] = dataclasses.field(default_factory=dict) class-attribute instance-attribute

View permissions for records in this workflow.

It is a dictionary, the key is record state and the value is a list of generators.

publish_after_review: bool = True class-attribute instance-attribute

Publish immediately after reviewer approves the review request.

extra_permissions: type[BasePermissionPolicy] | Callable[[type[BasePermissionPolicy]], type[BasePermissionPolicy]] | None = None class-attribute instance-attribute

Extra permissions to apply to the record permission policy.

If a callable is provided, it will be called with the generated permission policy as an argument and should return a modified permission policy. If a class is provided, it will be used as a mixin for the generated permission policy.

extra_requests: type[WorkflowRequestPolicy] | Callable[[type[WorkflowRequestPolicy]], type[WorkflowRequestPolicy]] | None = None class-attribute instance-attribute

Extra requests to apply to the workflow request policy.

If a callable is provided, it will be called with the generated request policy as an argument and should return a modified request policy. If a class is provided, it will be used as a mixin for the generated request policy.

authenticated_draft_creation: bool = False class-attribute instance-attribute

Allow authenticated users to create draft records.

When enabled and no role- or need-based restrictions are configured, any authenticated user may create a draft. Subclasses may override this default (e.g. IndividualWorkflow sets it to True).

draft_creation_roles: list[str] = dataclasses.field(default_factory=list) class-attribute instance-attribute

Restrict draft creation to users who hold at least one of these site-wide roles.

When non-empty, takes priority over authenticated_draft_creation.

draft_creation_needs: list[str] = dataclasses.field(default_factory=list) class-attribute instance-attribute

Restrict draft creation to users who hold at least one of these permission needs.

When non-empty, takes priority over authenticated_draft_creation.

build_workflow() -> Workflow

Build and return the workflow instance.

Source code in oarepo_config/workflows/simplified/base.py
def build_workflow(self) -> Workflow:
    """Build and return the workflow instance."""
    permissions: type[BasePermissionPolicy] = self._build_permission_policy()
    request_policy: type[WorkflowRequestPolicy] = self._build_request_policy()
    if self.extra_permissions:
        if isinstance(self.extra_permissions, type):
            permissions = type(permissions.__name__, (self.extra_permissions, permissions), {})
        elif callable(self.extra_permissions):
            permissions = self.extra_permissions(permissions)
    if self.extra_requests:
        if isinstance(self.extra_requests, type):
            request_policy = type(request_policy.__name__, (self.extra_requests, request_policy), {})
        elif callable(self.extra_requests):
            request_policy = self.extra_requests(request_policy)

    return Workflow(
        code=self.code,
        label=self.label,
        permission_policy_cls=cast("Any", permissions),
        request_policy_cls=request_policy,
    )

CommunityWorkflow dataclass

Bases: BaseWorkflowSettings

Workflow configuration for deposits inside communities.

Source code in oarepo_config/workflows/simplified/community.py
@dataclasses.dataclass
class CommunityWorkflow(BaseWorkflowSettings):
    """Workflow configuration for deposits inside communities."""

    draft_creation_community_roles: list[str] = dataclasses.field(
        default_factory=lambda: ["submitter", "curator", "owner"]
    )
    """Restrict draft creation to community members with at least one of these roles.

    If not specified (empty list), any member of the community can create a
    draft.  Used in addition to the site-wide
    `draft_creation_roles` /
    `draft_creation_needs` restrictions.
    """

    read_restricted_community_roles: list[str] = dataclasses.field(default_factory=lambda: ["curator", "owner"])
    """Community roles that may read restricted (published) records without requesting access.

    If empty, only the record owner can read the content after publishing. By default allowing curators
    and community owners to access restricted records.

    Note:
        Community roles are used instead of
        `RecordCommunitiesAction`
        so that each workflow can have independent read/draft/manage permissions.
    """

    read_draft_community_roles: list[str] = dataclasses.field(default_factory=list)
    """Community roles that may read draft records without requesting access.

    If empty, only the record owner can read the content of a draft.  Curators
    can always read draft records when the record is submitted for review.

    Note:
        Community roles are used instead of
        `RecordCommunitiesAction`
        so that each workflow can have independent read/draft/manage permissions.
    """

    record_manage_community_roles: list[str] = dataclasses.field(default_factory=lambda: ["curator", "owner"])
    """Community roles that may manage (edit, delete, publish) records.

    If empty, only the record owner can manage the record. By default allowing curators
    and community owners to manage all records.

    Note:
        Community roles are used instead of
        `RecordCommunitiesAction`
        so that each workflow can have independent read/draft/manage permissions.
    """

    community_curator_roles: list[str] = dataclasses.field(default_factory=lambda: ["curator"])
    """Community roles that allow users to review and curate records."""

    # --- permission policy ----------------------------------------------------

    def _build_permission_policy(self) -> type[BasePermissionPolicy]:
        class PermissionPolicy(BooleanPermissionPolicyMixin, self.base_permission_policy):  # type: ignore[name-defined]
            """A permission policy for the workflow."""

            can_create = self._build_record_create_generators()
            can_read = self.base_permission_policy.can_read + self._build_record_view_permissions()
            can_rdm_manage = self._build_record_rdm_manage_generators(self.base_permission_policy.can_rdm_manage)  # type: ignore[attr-defined]
            can_rdm_view = self._build_record_rdm_view_permissions(self.base_permission_policy.can_rdm_view)  # type: ignore[attr-defined]
            can_rdm_preview = self._build_record_rdm_preview_generators(self.base_permission_policy.can_rdm_preview)  # type: ignore[attr-defined]
            can_publish = (*self.base_permission_policy.can_publish, RequestActive())  # type: ignore[attr-defined]

        return PermissionPolicy

    def _build_record_create_generators(self) -> tuple[Generator, ...]:
        """Extend base create generators with community membership constraints.

        Calls `_build_record_create_generators` to
        resolve site-wide role- and need-based restrictions, then appends an
        `InAnyCommunity`
        generator for each role listed in `draft_creation_community_roles`.

        Returns:
            A tuple of permission generators for the `can_create` policy action.

        """
        create_generators = list(super()._build_record_create_generators())
        for role in self.draft_creation_community_roles:
            create_generators += [InAnyCommunity(PrimaryCommunityRole(role))]
        return tuple(create_generators)

    # --- RDM permission helpers -----------------------------------------------

    def _replace_communities_action_with_roles(
        self,
        original_permissions: list[Generator],
        community_roles: list[str],
    ) -> list[Generator]:
        """Replace `RecordCommunitiesAction` with explicit community-role generators.

        Filters *original_permissions* to remove any
        `RecordCommunitiesAction`
        instance (which grants access to *all* community members), then appends a
        `CommunityRole`
        generator for each role in *community_roles*.

        This lets each workflow define fine-grained, role-scoped access instead of
        the blanket community-wide access granted by
        `RecordCommunitiesAction`.

        Args:
            original_permissions: The existing generator list from the base
                permission policy (e.g. `can_rdm_view`).
            community_roles: Community role names to grant access to.

        Returns:
            An updated generator list.

        """
        result = [gen for gen in original_permissions if not isinstance(gen, RecordCommunitiesAction)]
        result.extend(CommunityRole(role) for role in community_roles)
        return result

    def _build_record_rdm_view_permissions(self, original_rdm_permissions: list[Generator]) -> list[Generator]:
        """Build `can_rdm_view` generators for this workflow.

        Replaces `RecordCommunitiesAction` with
        `read_restricted_community_roles`-scoped generators so that only
        the listed community roles (rather than all community members) can read
        restricted records.

        Args:
            original_rdm_permissions: The existing `can_rdm_view` generators
                from the base permission policy.

        Returns:
            Updated generator list.

        """
        return self._replace_communities_action_with_roles(
            original_rdm_permissions, self.read_restricted_community_roles
        )

    def _build_record_rdm_preview_generators(self, original_rdm_permissions: list[Generator]) -> list[Generator]:
        """Build `can_rdm_preview` generators for this workflow.

        Replaces `RecordCommunitiesAction` with
        `read_draft_community_roles`-scoped generators so that only the
        listed community roles (rather than all community members) can preview
        draft records.

        Args:
            original_rdm_permissions: The existing `can_rdm_preview` generators
                from the base permission policy.

        Returns:
            Updated generator list.

        """
        return self._replace_communities_action_with_roles(original_rdm_permissions, self.read_draft_community_roles)

    def _build_record_rdm_manage_generators(self, original_rdm_permissions: list[Generator]) -> list[Generator]:
        """Build `can_rdm_manage` generators for this workflow.

        Replaces `RecordCommunitiesAction` with
        `record_manage_community_roles`-scoped generators so that only
        the listed community roles (rather than all community members) can
        manage records.

        Args:
            original_rdm_permissions: The existing `can_rdm_manage` generators
                from the base permission policy.

        Returns:
            Updated generator list.

        """
        return self._replace_communities_action_with_roles(original_rdm_permissions, self.record_manage_community_roles)

    # --- request policy -------------------------------------------------------

    def _build_request_policy(self) -> type[WorkflowRequestPolicy]:
        curator_generators: list[PrimaryCommunityRole] = [
            PrimaryCommunityRole(role) for role in self.community_curator_roles
        ]

        requests = {
            # File modification requests let record owners unlock a published
            # record's files (grace-period feature). Created and accepted by
            # invenio's file_modification service (owner submits, system accepts),
            # so no reviewer and no record state transition.
            FileModification.type_id: WorkflowRequest(
                requesters=[RecordOwners()],
                recipients=[RecordOwnersForRecipients()],
                transitions=WorkflowTransitions(),
            ),
            # Quota increase requests let record owners raise a draft's storage
            # quota from their additional allowance. Created and accepted by
            # invenio's quota_increase service (owner submits, system accepts),
            # so no reviewer and no record state transition.
            QuotaIncrease.type_id: WorkflowRequest(
                requesters=[RecordOwners()],
                recipients=[RecordOwnersForRecipients()],
                transitions=WorkflowTransitions(),
            ),
            CommunitySubmission.type_id: WorkflowRequest(
                requesters=[
                    IfNewRecord(
                        then_=self._build_record_create_generators(),
                        else_=[
                            # Note: this permission check can be called from /review url, that is
                            # inside review service's create method. The problem is that review
                            # service does not pass the original record - it fills the "record"
                            # parameter with a community. That's why we can not use IfInState
                            # and similar permission generators that depend on the record.
                            *[
                                IfRDMRecordPassed(
                                    # the user has called the requests' create method directly
                                    then_=[RequireAll(RecordOwners(), PrimaryCommunityRole(role))],
                                    # the user went through the review flow which did not pass the record
                                    else_=[PrimaryCommunityRole(role)],
                                )
                                for role in self.draft_creation_community_roles
                            ],
                            *curator_generators,
                        ],
                    )
                ],
                recipients=curator_generators,
                transitions=WorkflowTransitions(
                    submitted="submitted",
                    accepted="published",
                    declined="draft",
                    cancelled="draft",
                ),
            ),
            PublishChangedMetadataRequestType.type_id: WorkflowRequest(
                requesters=[
                    IfInState(
                        ["draft", "revision_requested"],
                        [
                            RecordOwners(),
                            *curator_generators,
                        ],
                    )
                ],
                recipients=curator_generators,
                transitions=WorkflowTransitions(
                    submitted="submitted",
                    accepted="published",
                    declined="revision_requested",
                    cancelled="draft",
                ),
            ),
            PublishNewVersionRequestType.type_id: WorkflowRequest(
                requesters=[
                    IfInState(
                        ["draft", "revision_requested"],
                        [
                            RecordOwners(),
                            *curator_generators,
                        ],
                    )
                ],
                recipients=curator_generators,
                transitions=WorkflowTransitions(
                    submitted="submitted",
                    accepted="published",
                    declined="revision_requested",
                    cancelled="draft",
                ),
            ),
            # note: we need to patch https://github.com/inveniosoftware/invenio-rdm-records/blob/master/invenio_rdm_records/services/access/service.py#L784,
            # this will not work without the patch
            UserAccessRequest.type_id: WorkflowRequest(
                requesters=[AuthenticatedUser()],
                recipients=curator_generators,
            ),
        }

        return self._create_request_policy("CommunityReviewRequestPolicy", requests)

draft_creation_community_roles: list[str] = dataclasses.field(default_factory=lambda: ['submitter', 'curator', 'owner']) class-attribute instance-attribute

Restrict draft creation to community members with at least one of these roles.

If not specified (empty list), any member of the community can create a draft. Used in addition to the site-wide draft_creation_roles / draft_creation_needs restrictions.

read_restricted_community_roles: list[str] = dataclasses.field(default_factory=lambda: ['curator', 'owner']) class-attribute instance-attribute

Community roles that may read restricted (published) records without requesting access.

If empty, only the record owner can read the content after publishing. By default allowing curators and community owners to access restricted records.

Note

Community roles are used instead of RecordCommunitiesAction so that each workflow can have independent read/draft/manage permissions.

read_draft_community_roles: list[str] = dataclasses.field(default_factory=list) class-attribute instance-attribute

Community roles that may read draft records without requesting access.

If empty, only the record owner can read the content of a draft. Curators can always read draft records when the record is submitted for review.

Note

Community roles are used instead of RecordCommunitiesAction so that each workflow can have independent read/draft/manage permissions.

record_manage_community_roles: list[str] = dataclasses.field(default_factory=lambda: ['curator', 'owner']) class-attribute instance-attribute

Community roles that may manage (edit, delete, publish) records.

If empty, only the record owner can manage the record. By default allowing curators and community owners to manage all records.

Note

Community roles are used instead of RecordCommunitiesAction so that each workflow can have independent read/draft/manage permissions.

community_curator_roles: list[str] = dataclasses.field(default_factory=lambda: ['curator']) class-attribute instance-attribute

Community roles that allow users to review and curate records.

IndividualWorkflow dataclass

Bases: BaseWorkflowSettings

Workflow configuration for deposits outside of communities.

Source code in oarepo_config/workflows/simplified/individual.py
@dataclasses.dataclass
class IndividualWorkflow(BaseWorkflowSettings):
    """Workflow configuration for deposits outside of communities."""

    code: str = "individual"
    """Unique code identifier for this workflow."""

    label: LazyString = _("Individual Submission Workflow")  # noqa: RUF009
    """Human-readable label for this workflow."""

    authenticated_draft_creation: bool = True
    """Allow authenticated users to create drafts in this workflow.

    Overrides the base-class default of `False`; any authenticated user can
    create a draft unless more-specific role or need restrictions are configured
    via `draft_creation_roles` or
    `draft_creation_needs`.
    """

    publish_without_review: bool = False
    """Allow draft owners to publish without submitting a review request.

    When enabled, draft owners can publish directly, subject to
    `publish_without_review_states`.
    """

    publish_without_review_roles: list[str] = dataclasses.field(default_factory=list)
    """Roles that allow a draft owner to publish without a review request.

    Users must still be owners of the draft record. If the list is non-empty,
    `publish_without_review` is ignored.
    """

    publish_without_review_needs: list[str] = dataclasses.field(default_factory=list)
    """Permission needs that allow a draft owner to publish without a review request.

    Users must still be owners of the draft record. If the list is non-empty,
    `publish_without_review` is ignored.
    """

    publish_without_review_states: list[str] = dataclasses.field(default_factory=lambda: ["draft"])
    """Record workflow states in which publication without review is allowed."""

    review_required: bool = False
    """Require a review request before publication.

    If `publish_without_review` is `False` and `review_required`
    is `False`, records can only be published through a community workflow.
    """

    reviewer_roles: list[str] = dataclasses.field(default_factory=list)
    """Roles that allow users to review and curate records.

    Users with these roles are also granted read access to draft records.
    """

    reviewer_needs: list[str] = dataclasses.field(default_factory=list)
    """Permission needs that allow users to review and curate records.

    Users with these needs are also granted read access to draft records.
    """

    self_review_enabled: bool = False
    """Allow the record owner to approve their own review request.

    Normally, submitting a record for review prevents the owner from approving it
    themselves. When set to `True`, the review request is still created on
    submission, but the owner is permitted to accept it.

    This is primarily useful when `invenio-checks` is active: checks are tied
    to an open request, so the request must exist even when no external reviewer
    is needed. With this option the owner can see and act on the check results
    without waiting for a curator.

    Has no effect when `publish_without_review` is `True`, because in
    that case user can bypass the review request and publish the record directly.
    """

    def _build_permission_policy(self) -> type[BasePermissionPolicy]:
        class PermissionPolicy(BooleanPermissionPolicyMixin, self.base_permission_policy):  # type: ignore[unsupported-base]
            """A permission policy for the workflow."""

            can_create = self._build_record_create_generators()
            can_publish = (
                *add_if_in_state(
                    self.publish_without_review_states,
                    self._build_record_publish_generators(),
                ),
                IfInState("submitted", then_=[RequestActive()]),
            )
            can_read = self.base_permission_policy.can_read + self._build_record_view_permissions()

        return PermissionPolicy

    def _build_record_publish_generators(self) -> tuple[Generator, ...]:
        """Build generators that control who may publish a draft without a review request.

        Applies the following priority order:

        1. **Role-based** - `publish_without_review_roles`: owners who also
           hold any of these roles may publish directly.
        2. **Need-based** - `publish_without_review_needs`: owners who also
           possess any of these permission needs may publish directly.
        3. **Owner fallback** - when neither (1) nor (2) are set and
           `publish_without_review` is `True`, the draft owner may publish
           directly.

        Note:
            `SystemProcess` is added automatically by the base policy; it does
            not need to be included here.

        Returns:
            A tuple of permission generators for the `can_publish` policy action.

        """
        publish_generators: list[Generator] = []
        if self.publish_without_review_roles:
            publish_generators += [
                RequireAll(RecordOwners(), UserWithRole(role_name)) for role_name in self.publish_without_review_roles
            ]
        if self.publish_without_review_needs:
            publish_generators += [
                RequireAll(RecordOwners(), HasActionNeed(action)) for action in self.publish_without_review_needs
            ]
        if not publish_generators and self.publish_without_review:
            publish_generators = [RecordOwners()]
        return tuple(publish_generators)

    def _build_request_policy(self) -> type[WorkflowRequestPolicy]:
        # File modification requests let record owners unlock a published record's
        # files (grace-period feature). Available regardless of review, since it is
        # created and accepted by invenio's file_modification service (owner submits,
        # system accepts) -- no reviewer and no record state transition.
        base_requests = {
            FileModification.type_id: WorkflowRequest(
                requesters=[RecordOwners()],
                recipients=[RecordOwnersForRecipients()],
                transitions=WorkflowTransitions(),
            ),
            # Quota increase requests let record owners raise a draft's storage
            # quota from their additional allowance. Created and accepted by
            # invenio's quota_increase service (owner submits, system accepts),
            # so no reviewer and no record state transition.
            QuotaIncrease.type_id: WorkflowRequest(
                requesters=[RecordOwners()],
                recipients=[RecordOwnersForRecipients()],
                transitions=WorkflowTransitions(),
            ),
        }

        if not self.review_required:
            return self._create_request_policy("IndividualRequestPolicy", base_requests)

        reviewer_generators: list[Generator] = []
        if self.reviewer_roles:
            reviewer_generators = [UserWithRole(role) for role in self.reviewer_roles]
        if self.reviewer_needs:
            reviewer_generators.extend([HasActionNeed(need) for need in self.reviewer_needs])
        if self.self_review_enabled:
            reviewer_generators.extend(self.record_owners_with_correct_roles(RecordOwnersForRecipients()))  # type: ignore[arg-type]
        if not self.publish_after_review:
            raise NotImplementedError(
                "Disabling publish_after_review is not supported in this version, "
                "please ask the maintainers to enable it"
            )
        requestors = [*reviewer_generators]
        if not self.self_review_enabled:
            requestors.extend(self.record_owners_with_correct_roles(RecordOwners()))  # type: ignore[arg-type]

        requests = {
            **base_requests,
            PublishDraftRequestType.type_id: WorkflowRequest(
                requesters=[
                    IfInState(
                        ["draft", "revision_requested"],
                        requestors,
                    )
                ],
                recipients=reviewer_generators,
                transitions=WorkflowTransitions(
                    submitted="submitted",
                    accepted="published",
                    declined="revision_requested",
                    cancelled="draft",
                ),
                events=WorkflowEvents(
                    {CommentEventType.type_id or "C": WorkflowEvent(submitters=[*requestors, *reviewer_generators])}
                ),
            ),
            PublishChangedMetadataRequestType.type_id: WorkflowRequest(
                requesters=[
                    IfInState(
                        ["draft", "revision_requested"],
                        requestors,
                    )
                ],
                recipients=reviewer_generators,
                transitions=WorkflowTransitions(
                    submitted="submitted",
                    accepted="published",
                    declined="revision_requested",
                    cancelled="draft",
                ),
            ),
            PublishNewVersionRequestType.type_id: WorkflowRequest(
                requesters=[
                    IfInState(
                        ["draft", "revision_requested"],
                        requestors,
                    )
                ],
                recipients=reviewer_generators,
                transitions=WorkflowTransitions(
                    submitted="submitted",
                    accepted="published",
                    declined="revision_requested",
                    cancelled="draft",
                ),
            ),
            UserAccessRequest.type_id: WorkflowRequest(
                requesters=[AuthenticatedUser()],
                recipients=[RecordOwnersForRecipients()],
            ),
        }

        return self._create_request_policy("GlobalReviewRequestPolicy", requests)

    def record_owners_with_correct_roles(self, record_owner_generator: RecordOwners) -> list[Generator]:
        """Return the record owner generator with the correct roles/needs."""
        generators: list[Generator] = []
        if self.draft_creation_roles:
            generators += [
                RequireAll(record_owner_generator, UserWithRole(role_name)) for role_name in self.draft_creation_roles
            ]
        if self.draft_creation_needs:
            generators += [RequireAll(RecordOwners(), HasActionNeed(action)) for action in self.draft_creation_needs]
        if not generators:
            generators = [record_owner_generator]
        return generators

code: str = 'individual' class-attribute instance-attribute

Unique code identifier for this workflow.

label: LazyString = _('Individual Submission Workflow') class-attribute instance-attribute

Human-readable label for this workflow.

authenticated_draft_creation: bool = True class-attribute instance-attribute

Allow authenticated users to create drafts in this workflow.

Overrides the base-class default of False; any authenticated user can create a draft unless more-specific role or need restrictions are configured via draft_creation_roles or draft_creation_needs.

publish_without_review: bool = False class-attribute instance-attribute

Allow draft owners to publish without submitting a review request.

When enabled, draft owners can publish directly, subject to publish_without_review_states.

publish_without_review_roles: list[str] = dataclasses.field(default_factory=list) class-attribute instance-attribute

Roles that allow a draft owner to publish without a review request.

Users must still be owners of the draft record. If the list is non-empty, publish_without_review is ignored.

publish_without_review_needs: list[str] = dataclasses.field(default_factory=list) class-attribute instance-attribute

Permission needs that allow a draft owner to publish without a review request.

Users must still be owners of the draft record. If the list is non-empty, publish_without_review is ignored.

publish_without_review_states: list[str] = dataclasses.field(default_factory=lambda: ['draft']) class-attribute instance-attribute

Record workflow states in which publication without review is allowed.

review_required: bool = False class-attribute instance-attribute

Require a review request before publication.

If publish_without_review is False and review_required is False, records can only be published through a community workflow.

reviewer_roles: list[str] = dataclasses.field(default_factory=list) class-attribute instance-attribute

Roles that allow users to review and curate records.

Users with these roles are also granted read access to draft records.

reviewer_needs: list[str] = dataclasses.field(default_factory=list) class-attribute instance-attribute

Permission needs that allow users to review and curate records.

Users with these needs are also granted read access to draft records.

self_review_enabled: bool = False class-attribute instance-attribute

Allow the record owner to approve their own review request.

Normally, submitting a record for review prevents the owner from approving it themselves. When set to True, the review request is still created on submission, but the owner is permitted to accept it.

This is primarily useful when invenio-checks is active: checks are tied to an open request, so the request must exist even when no external reviewer is needed. With this option the owner can see and act on the check results without waiting for a curator.

Has no effect when publish_without_review is True, because in that case user can bypass the review request and publish the record directly.

record_owners_with_correct_roles(record_owner_generator: RecordOwners) -> list[Generator]

Return the record owner generator with the correct roles/needs.

Source code in oarepo_config/workflows/simplified/individual.py
def record_owners_with_correct_roles(self, record_owner_generator: RecordOwners) -> list[Generator]:
    """Return the record owner generator with the correct roles/needs."""
    generators: list[Generator] = []
    if self.draft_creation_roles:
        generators += [
            RequireAll(record_owner_generator, UserWithRole(role_name)) for role_name in self.draft_creation_roles
        ]
    if self.draft_creation_needs:
        generators += [RequireAll(RecordOwners(), HasActionNeed(action)) for action in self.draft_creation_needs]
    if not generators:
        generators = [record_owner_generator]
    return generators

register_workflow(workflow_code: str, workflow_name: str | LazyString, permissions_policy: str | type, requests_policy: str | type, use_low_level_workflows: bool = False) -> None

Register a submission/review workflow that records can go through.

A workflow defines the path a record takes from being created to being published - for example, who may create it, whether it needs review/approval before publishing, and who may perform each of those steps. This adds one such workflow to the repository, so that it can be selected when configuring where records may be submitted (e.g. a community).

This is a low-level, single-workflow building block. Repositories that use the community-based workflow shape provided by the oarepo_app package typically use its higher-level configure_workflows(IndividualWorkflow(...), CommunityWorkflow(...)) helper instead - see this package's README for the difference.

Parameters:

Name Type Description Default
workflow_code str

A short, unique identifier for the workflow, e.g. "default".

required
workflow_name str | LazyString

The human-readable name of the workflow, shown to users, e.g. _("Default workflow").

required
permissions_policy str | type

Who is allowed to do what with records that use this workflow (create, edit, delete, publish, ...). Pass either a permissions policy class or its import path as a string.

required
requests_policy str | type

What review/approval requests are available for records using this workflow (e.g. a publish request that needs a curator's approval). Pass either a request policy class or its import path as a string.

required
use_low_level_workflows bool

Set to True to silence the warning recommending configure_workflows instead, for the (uncommon) cases that genuinely need this low-level, single-workflow API.

False

Requires the optional oarepo_workflows (and, for its defaults, oarepo_requests) package to be installed.

Invenio configuration variables set:

  • WORKFLOWS - the new workflow is appended; workflows already registered (by earlier calls) are kept.
  • REQUESTS_PERMISSION_POLICY - only if not already set by an earlier call; defaults to oarepo_config.requests.RequestsPermissionPolicy (workflow-based, plus creation of community-topic request types).
Example
from oarepo_workflows.services.permissions import (
    DefaultWorkflowPermissions,
)
from oarepo_requests.services.permissions.workflow_policies import (
    CreatorsFromWorkflowRequestsPermissionPolicy,
)

config.register_workflow(
    workflow_code="default",
    workflow_name=_("Default workflow"),
    permissions_policy=DefaultWorkflowPermissions,
    requests_policy=CreatorsFromWorkflowRequestsPermissionPolicy,
)
Source code in oarepo_config/workflows/low_level.py
def register_workflow(
    workflow_code: str,
    workflow_name: str | LazyString,
    permissions_policy: str | type,
    requests_policy: str | type,
    use_low_level_workflows: bool = False,
) -> None:
    """Register a submission/review workflow that records can go through.

    A workflow defines the path a record takes from being created to
    being published - for example, who may create it, whether it needs
    review/approval before publishing, and who may perform each of those
    steps. This adds one such workflow to the repository, so that it can
    be selected when configuring where records may be submitted (e.g. a
    community).

    This is a low-level, single-workflow building block. Repositories
    that use the community-based workflow shape provided by the
    `oarepo_app` package typically use its higher-level
    `configure_workflows(IndividualWorkflow(...), CommunityWorkflow(...))`
    helper instead - see this package's README for the difference.

    Args:
        workflow_code: A short, unique identifier for the workflow, e.g.
            `"default"`.
        workflow_name: The human-readable name of the workflow, shown to
            users, e.g. `_("Default workflow")`.
        permissions_policy: Who is allowed to do what with records that
            use this workflow (create, edit, delete, publish, ...). Pass
            either a permissions policy class or its import path as a
            string.
        requests_policy: What review/approval requests are available for
            records using this workflow (e.g. a publish request that
            needs a curator's approval). Pass either a request policy
            class or its import path as a string.
        use_low_level_workflows: Set to `True` to silence the warning
            recommending [`configure_workflows`][oarepo_config.configure_workflows] instead, for the
            (uncommon) cases that genuinely need this low-level,
            single-workflow API.

    Requires the optional `oarepo_workflows` (and, for its defaults,
    `oarepo_requests`) package to be installed.

    Invenio configuration variables set:

    * `WORKFLOWS` - the new workflow is appended; workflows already
      registered (by earlier calls) are kept.
    * `REQUESTS_PERMISSION_POLICY` - only if not already set by an
      earlier call; defaults to `oarepo_config.requests.RequestsPermissionPolicy`
      (workflow-based, plus creation of community-topic request types).

    Example:
        ```python
        from oarepo_workflows.services.permissions import (
            DefaultWorkflowPermissions,
        )
        from oarepo_requests.services.permissions.workflow_policies import (
            CreatorsFromWorkflowRequestsPermissionPolicy,
        )

        config.register_workflow(
            workflow_code="default",
            workflow_name=_("Default workflow"),
            permissions_policy=DefaultWorkflowPermissions,
            requests_policy=CreatorsFromWorkflowRequestsPermissionPolicy,
        )
        ```

    """
    if not use_low_level_workflows:
        warnings.warn(
            "register_workflow() is a low-level, single-workflow building block. "
            "configure_workflows(IndividualWorkflow(...), CommunityWorkflow(...)) is a "
            "simplified solution that should be used instead for the common case. Pass "
            "use_low_level_workflows=True if you intentionally need the low-level API.",
            stacklevel=2,
        )

    try:
        from oarepo_workflows import Workflow, WorkflowRequestPolicy
        from oarepo_workflows.services.permissions import DefaultWorkflowPermissions
    except ImportError as e:
        raise ImportError("oarepo_workflows package is required for workflow registration.") from e

    WORKFLOWS = get_constant_from_caller("WORKFLOWS", [])
    permission_policy_cls = obj_or_import_string(permissions_policy)
    if not (inspect.isclass(permission_policy_cls) and issubclass(permission_policy_cls, DefaultWorkflowPermissions)):
        raise TypeError("permissions_policy must be a subclass of DefaultWorkflowPermissions")

    requests_policy_cls = obj_or_import_string(requests_policy)
    if not (inspect.isclass(requests_policy_cls) and issubclass(requests_policy_cls, WorkflowRequestPolicy)):
        raise TypeError("requests_policy must be a subclass of WorkflowRequestPolicy")

    WORKFLOWS.append(
        Workflow(
            code=workflow_code,
            label=_(workflow_name),
            permission_policy_cls=permission_policy_cls,
            request_policy_cls=requests_policy_cls,
        )
    )
    from ..requests import RequestsPermissionPolicy

    REQUESTS_PERMISSION_POLICY = get_constant_from_caller("REQUESTS_PERMISSION_POLICY", RequestsPermissionPolicy)
    set_constants_in_caller(locals())

configure_workflows(*workflow_definitions: BaseWorkflowSettings, default_individual_workflow: str = 'individual', default_community_workflow: str = 'community', context: dict | None = None) -> list[Workflow]

Set up workflows based on the provided workflow definitions.

This function is intended to be called from within invenio.cfg and will create a "WORKFLOWS" entry in the invenio.cfg context (in the caller's globals).

Example
# invenio.cfg
from oarepo_app.config import (
    configure_workflows,
    IndividualWorkflow,
    CommunityWorkflow,
)

configure_workflows(
    IndividualWorkflow(
        authenticated_draft_creation=False,
        review_required=True,
        publish_without_review=False,
    ),
    CommunityWorkflow(),
)
# no need to assign the result to WORKFLOWS, that is done automatically

If the workflow definitions are empty, a permissive IndividualWorkflow will be created (authenticated draft creation, publish without review allowed).

If there is no IndividualWorkflow definition in the workflow definitions (but there are other workflow types), a restricted IndividualWorkflow (no deposition allowed) will be created with default settings.

The default_individual_workflow parameter should be the code of the workflow to use as the default one for individual deposits, where no community is involved and the workflow code is not provided by the caller.

If the context is provided, the "WORKFLOWS" entry will be added to it instead of the caller's globals.

See https://nrp-cz.github.io/docs/customize/workflows for more information on how to customize the workflows.

Source code in oarepo_config/workflows/simplified/__init__.py
def configure_workflows(
    *workflow_definitions: BaseWorkflowSettings,
    default_individual_workflow: str = "individual",
    default_community_workflow: str = "community",
    context: dict | None = None,
) -> list[Workflow]:
    """Set up workflows based on the provided workflow definitions.

    This function is intended to be called from within invenio.cfg and will create
    a "WORKFLOWS" entry in the invenio.cfg context (in the caller's globals).

    Example:
        ```python
        # invenio.cfg
        from oarepo_app.config import (
            configure_workflows,
            IndividualWorkflow,
            CommunityWorkflow,
        )

        configure_workflows(
            IndividualWorkflow(
                authenticated_draft_creation=False,
                review_required=True,
                publish_without_review=False,
            ),
            CommunityWorkflow(),
        )
        # no need to assign the result to WORKFLOWS, that is done automatically
        ```

    If the workflow definitions are empty, a permissive IndividualWorkflow will be created
    (authenticated draft creation, publish without review allowed).

    If there is no IndividualWorkflow definition in the workflow definitions (but there are other workflow types), a
    restricted IndividualWorkflow (no deposition allowed) will be created with default settings.

    The default_individual_workflow parameter should be the code of the workflow to use
    as the default one for individual deposits, where no community is involved and the
    workflow code is not provided by the caller.

    If the context is provided, the "WORKFLOWS" entry will be added to it instead of
    the caller's globals.

    See https://nrp-cz.github.io/docs/customize/workflows for more information on how to customize the workflows.

    """
    if not workflow_definitions:
        workflow_definitions = (
            IndividualWorkflow(
                code=default_individual_workflow,
                authenticated_draft_creation=True,
                review_required=False,
                publish_without_review=True,
            ),
        )
    elif not any(isinstance(workflow, IndividualWorkflow) for workflow in workflow_definitions):
        workflow_definitions = (
            *workflow_definitions,
            IndividualWorkflow(
                code=default_individual_workflow,
                authenticated_draft_creation=False,
                review_required=False,
                publish_without_review=False,
            ),
        )
    built_workflows = [workflow.build_workflow() for workflow in workflow_definitions]
    if not any(workflow.code == default_individual_workflow for workflow in workflow_definitions):
        raise ValueError(f"No workflow with code '{default_individual_workflow}' found in workflow definitions")
    # check for duplicated codes
    if len(workflow_definitions) != len({workflow.code for workflow in workflow_definitions}):
        raise ValueError("Duplicate workflow codes found in workflow definitions")

    constants: dict[str, Any] = {
        "WORKFLOWS": built_workflows,
        "WORKFLOWS_DEFAULT_WORKFLOW": default_individual_workflow,
        "OAREPO_COMMUNITIES_DEFAULT_WORKFLOW": default_community_workflow,
    }

    # Default the requests permission policy to the one that also allows creating
    # community-topic request types (membership / invitation / sub-community), which
    # otherwise cannot resolve a workflow and are always denied. Respect an explicit
    # REQUESTS_PERMISSION_POLICY set by the caller.
    if RequestsPermissionPolicy is not None:
        # skipped if oarepo-workflows are not available
        if context:
            constants["REQUESTS_PERMISSION_POLICY"] = context.get(
                "REQUESTS_PERMISSION_POLICY", RequestsPermissionPolicy
            )
        else:
            constants["REQUESTS_PERMISSION_POLICY"] = get_constant_from_caller(
                "REQUESTS_PERMISSION_POLICY", RequestsPermissionPolicy
            )

    if context:
        context.update(constants)
    else:
        set_constants_in_caller(constants)
    return built_workflows