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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ const requestDeclineButtonDefaultPropAriaAttributes = {};
export const RequestDeclineButton = ({
onClick,
loading = false,
disabled = false,
ariaAttributes = requestDeclineButtonDefaultPropAriaAttributes,
size = "mini",
className = "",
Expand All @@ -36,7 +37,7 @@ export const RequestDeclineButton = ({
content={i18next.t("Decline")}
onClick={onClick}
loading={loading}
disabled={loading}
disabled={loading || disabled}
negative
size={size}
className={className}
Expand All @@ -48,6 +49,7 @@ export const RequestDeclineButton = ({
RequestDeclineButton.propTypes = {
onClick: PropTypes.func.isRequired,
loading: PropTypes.bool,
disabled: PropTypes.bool,
ariaAttributes: PropTypes.object,
size: PropTypes.string,
className: PropTypes.string,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,13 @@ export class RequestAction extends Component {

static contextType = RequestActionContext;

openModal = (...args) => {
// Start with an empty comment each time the modal is opened
const { toggleModal } = this.context;
this.setState({ actionComment: "" });
toggleModal(...args);
};

onCommentChange = (event, editor) => {
this.setState({ actionComment: editor.getContent() });
};
Expand All @@ -34,10 +41,17 @@ export class RequestAction extends Component {
};

render() {
const { loading, performAction, toggleModal, error, modalOpen } = this.context;
const { loading, performAction, error, modalOpen } = this.context;
const { action, requestType, size = "medium" } = this.props;
const { actionComment } = this.state;
const modalId = action;
// Blocking users (user moderation) is done without a comment
const commentRequired = action === "decline" && requestType !== "user-moderation";
const declineCommentMissing =
commentRequired &&
!new DOMParser()
.parseFromString(actionComment, "text/html")
.body.textContent.trim();

return (
<Overridable
Expand All @@ -50,7 +64,7 @@ export class RequestAction extends Component {
<RequestActionModalTrigger
action={action}
loading={loading}
toggleModal={toggleModal}
toggleModal={this.openModal}
modalOpen={modalOpen}
requestType={requestType}
size={size}
Expand All @@ -61,6 +75,7 @@ export class RequestAction extends Component {
handleActionClick={this.handleActionClick}
modalId={modalId}
requestType={requestType}
actionDisabled={declineCommentMissing}
>
<Modal.Content>
{error && (
Expand All @@ -69,11 +84,13 @@ export class RequestAction extends Component {
</Message>
)}
<Modal.Description>
{i18next.t("Add comment (optional)")}
{commentRequired
? i18next.t("Add comment (required)")
: i18next.t("Add comment (optional)")}
<Divider hidden />
<RichEditor
inputValue={() => actionComment}
onChange={this.onCommentChange}
onEditorChange={this.onCommentChange}
/>
</Modal.Description>
</Modal.Content>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ export const RequestActionButton = ({
action,
handleActionClick,
loading,
disabled = false,
className = "",
size = "medium",
requestType,
Expand All @@ -21,12 +22,14 @@ export const RequestActionButton = ({
id={`RequestActionButton.${action}`}
onClick={handleActionClick}
loading={loading}
disabled={disabled}
className={className}
size={size}
>
<Button
onClick={handleActionClick}
loading={loading}
disabled={disabled}
className={className}
size={size}
requestType={requestType}
Expand All @@ -41,6 +44,7 @@ RequestActionButton.propTypes = {
action: PropTypes.string.isRequired,
handleActionClick: PropTypes.func.isRequired,
loading: PropTypes.bool.isRequired,
disabled: PropTypes.bool,
className: PropTypes.string,
size: PropTypes.string,
requestType: PropTypes.string.isRequired,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,14 @@ export class RequestActionModal extends Component {
};

render() {
const { action, handleActionClick, modalId, children, requestType } = this.props;
const {
action,
handleActionClick,
modalId,
children,
requestType,
actionDisabled = false,
} = this.props;
const { modalOpen, loading, toggleModal, error, cleanError, className, size } =
this.context;

Expand Down Expand Up @@ -83,6 +90,7 @@ export class RequestActionModal extends Component {
action={action}
handleActionClick={handleActionClick}
loading={loading}
disabled={actionDisabled}
className={className}
size={size}
requestType={requestType}
Expand All @@ -103,6 +111,7 @@ RequestActionModal.propTypes = {
modalId: PropTypes.string.isRequired,
children: PropTypes.node.isRequired,
requestType: PropTypes.string.isRequired,
actionDisabled: PropTypes.bool,
loading: PropTypes.bool,
modalOpen: PropTypes.bool,
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,9 @@ msgstr "Membership request"
msgid "Add comment (optional)"
msgstr "Add comment (optional)"

msgid "Add comment (required)"
msgstr "Add comment (required)"

msgid "{{action}} request"
msgstr "{{action}} request"

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
"Subcommunity invitation": "Subcommunity invitation",
"Membership request": "Membership request",
"Add comment (optional)": "Add comment (optional)",
"Add comment (required)": "Add comment (required)",
"{{action}} request": "{{action}} request",
"Anonymous user": "Anonymous user",
"Email": "Email",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,9 @@ msgstr "Membership request"
msgid "Add comment (optional)"
msgstr "Add comment (optional)"

msgid "Add comment (required)"
msgstr "Add comment (required)"

msgid "{{action}} request"
msgstr "{{action}} request"

Expand Down
4 changes: 4 additions & 0 deletions invenio_requests/customizations/actions.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,9 @@ class RequestAction:
log_event = True
"""Define if the action should be logged through a `LogEventType`."""

comment_required = False
"""Define if the action can only be executed with a non-blank comment."""

def __init__(self, request):
"""Constructor."""
self.request = request
Expand Down Expand Up @@ -131,6 +134,7 @@ class DeclineAction(RequestAction):

status_from = ["submitted"]
status_to = "declined"
comment_required = True


class CancelAction(RequestAction):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@
class DeclineUserAction(actions.DeclineAction):
"""Represents a decline action used to block a user."""

# Blocking is done from the administration panel, which sends no comment
comment_required = False

def execute(self, identity, uow):
"""Executes block action."""
user = self.request.topic.resolve()
Expand Down
13 changes: 13 additions & 0 deletions invenio_requests/services/requests/service.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

"""Requests service."""

from invenio_access.permissions import system_process
from invenio_i18n import lazy_gettext as _
from invenio_records_resources.services import RecordService, ServiceSchemaWrapper
from invenio_records_resources.services.base import LinksTemplate
Expand All @@ -16,6 +17,7 @@
unit_of_work,
)
from invenio_search.engine import dsl
from marshmallow_utils.html import strip_html

from ...customizations import RequestActions
from ...customizations.event_types import CommentEventType
Expand Down Expand Up @@ -266,6 +268,17 @@ def execute_action(
if not action_obj.can_execute():
raise CannotExecuteActionError(action)

# Actions such as decline need a reason, unless run by a system process
content = ((data or {}).get("payload") or {}).get("content") or ""
if (
getattr(action_obj, "comment_required", False)
and system_process not in identity.provides
and not strip_html(str(content)).strip()
):
raise CannotExecuteActionError(
action, _("A comment is required to decline a request.")
)

# Execute action and register request for persistence.
action_obj.execute(identity, uow, **kwargs)
uow.register(RecordCommitOp(request, indexer=self.indexer))
Expand Down
32 changes: 32 additions & 0 deletions tests/resources/requests/test_requests_resources.py
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,38 @@ def test_empty_comment(
assert "submitted" == response.json["status"]


def test_decline_requires_comment(
app, client_logged_as, headers, example_requests, request_action_resource_data
):
"""Declining a request through the REST API requires a comment."""
client = client_logged_as("admin@example.org")
r1, r2, r3 = example_requests
for request in example_requests:
request.status = "submitted"
request.commit()

# With a comment is Ok
response = client.post(
f"/requests/{r1.id}/actions/decline",
headers=headers,
json=request_action_resource_data,
)
assert 200 == response.status_code
assert "declined" == response.json["status"]

# No payload or {} is an error
response = client.post(f"/requests/{r2.id}/actions/decline", headers=headers)
assert 400 == response.status_code
response = client.post(
f"/requests/{r3.id}/actions/decline", headers=headers, json={}
)
assert 400 == response.status_code

for request in (r2, r3):
response = client.get(f"/requests/{request.id}", headers=headers)
assert "submitted" == response.json["status"]


def test_create_is_disallowed(app, client_logged_as, headers, request_resource_data):
"""Test if the user cannot create a new generic request."""
client = client_logged_as("user1@example.org")
Expand Down
10 changes: 5 additions & 5 deletions tests/services/events/test_event_permissions.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
from invenio_records_resources.services.errors import PermissionDeniedError

from invenio_requests.customizations.event_types import CommentEventType, LogEventType
from invenio_requests.errors import RequestLockedError
from invenio_requests.errors import CannotExecuteActionError, RequestLockedError
from invenio_requests.records.api import RequestEvent


Expand Down Expand Up @@ -195,11 +195,11 @@ def test_commenting_on_locked_request(
identity_stranger, request.id, {"payload": {"event": "test"}}, LogEventType
)

# Log events are not blocked by locked request
# For eg. decline action can be executed on locked request
requests_service.execute_action(identity_simple_2, request.id, "decline")
# A locked request cannot be declined without the required comment.
with pytest.raises(CannotExecuteActionError):
requests_service.execute_action(identity_simple_2, request.id, "decline")
RequestEvent.index.refresh()

results = request_events_service.search(identity_simple_2, request.id)
assert 3 == results.total # comment + locked + declined
assert 2 == results.total # comment + locked
# Creation and submission events are not logged because they have log_event=False
25 changes: 25 additions & 0 deletions tests/services/requests/test_requests_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
from invenio_records_resources.services.errors import PermissionDeniedError

from invenio_requests.customizations.event_types import CommentEventType
from invenio_requests.errors import CannotExecuteActionError
from invenio_requests.records.api import Request, RequestEvent, RequestEventFormat


Expand Down Expand Up @@ -130,6 +131,30 @@ def test_decline_request(
assert 3 == results.total # submit comment + decline event + comment


@pytest.mark.parametrize(
"data",
[
None,
{},
{"payload": {}},
{"payload": {"content": "", "format": "html"}},
{"payload": {"content": "<p> </p>", "format": "html"}},
{"payload": {"content": "<p>&nbsp;</p>", "format": "html"}},
{"payload": {"content": "<p><br></p>", "format": "html"}},
],
)
def test_decline_requires_comment(
app, identity_simple, identity_simple_2, submit_request, requests_service, data
):
"""Declining a request requires a non-blank comment."""
request = submit_request(identity_simple)

with pytest.raises(CannotExecuteActionError):
requests_service.execute_action(identity_simple_2, request.id, "decline", data)

assert "submitted" == requests_service.read(identity_simple, request.id)["status"]


def test_update_request(app, identity_simple, submit_request, requests_service):
request = submit_request(identity_simple)
request_id = request.id
Expand Down
Loading