Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[#855] 3) request flow backend start #1131

Closed
Closed
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
@@ -0,0 +1,104 @@
/*
* This file is part of Invenio.
* Copyright (C) 2024 CERN.
* Copyright (C) 2024 Northwestern University.
*
* Invenio is free software; you can redistribute it and/or modify it
* under the terms of the MIT License; see LICENSE file for more details.
*/

import { i18next } from "@translations/invenio_communities/i18next";
import { Formik } from "formik";
import PropTypes from "prop-types";
import React, { useState } from "react";
import { TextAreaField } from "react-invenio-forms";
import { Button, Form, Modal } from "semantic-ui-react";

export function RequestMembershipModal(props) {
const { isOpen, onClose } = props;

const onSubmit = async (values, { setSubmitting, setFieldError }) => {
// TODO: implement me
console.log("RequestMembershipModal.onSubmit(args) called");
console.log("TODO: implement me", arguments);
};

let confirmed = true;

return (
<Formik
initialValues={{
requestMembershipComment: "",
}}
onSubmit={onSubmit}
>
{({ values, isSubmitting, handleSubmit }) => (
<Modal
open={isOpen}
onClose={onClose}
size="small"
closeIcon
closeOnDimmerClick={false}
>
<Modal.Header>{i18next.t("Request Membership")}</Modal.Header>
<Modal.Content>
<Form>
<TextAreaField
fieldPath="requestMembershipComment"
label={i18next.t("Message to managers (optional)")}
/>
</Form>
</Modal.Content>
<Modal.Actions>
<Button onClick={onClose} floated="left">
{i18next.t("Cancel")}
</Button>
<Button
onClick={(event) => {
// TODO: Implement me
console.log("RequestMembershipModal button clicked.");
}}
positive={confirmed}
primary
>
{i18next.t("Request Membership")}
</Button>
</Modal.Actions>
</Modal>
)}
</Formik>
);
}

RequestMembershipModal.propTypes = {
isOpen: PropTypes.bool.isRequired,
onClose: PropTypes.func.isRequired,
};

export function RequestMembershipButton(props) {
const [isModalOpen, setModalOpen] = useState(false);

const handleClick = () => {
setModalOpen(true);
};

const handleClose = () => {
setModalOpen(false);
};

return (
<>
<Button
name="request-membership"
onClick={handleClick}
positive
icon="sign-in"
labelPosition="left"
content={i18next.t("Request Membership")}
/>
{isModalOpen && (
<RequestMembershipModal isOpen={isModalOpen} onClose={handleClose} />
)}
</>
);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
/*
* This file is part of Invenio.
* Copyright (C) 2024 Northwestern University.
*
* Invenio is free software; you can redistribute it and/or modify it
* under the terms of the MIT License; see LICENSE file for more details.
*/

import ReactDOM from "react-dom";

import React from "react";

import { RequestMembershipButton } from "./RequestMembershipButton";

const domContainer = document.getElementById("request-membership-app");

const community = JSON.parse(domContainer.dataset.community);

if (domContainer) {
ReactDOM.render(<RequestMembershipButton community={community} />, domContainer);
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
import { i18next } from "@translations/invenio_communities/i18next";
import { CommunitySettingsForm } from "..//components/CommunitySettingsForm";
import _get from "lodash/get";
import _isEmpty from "lodash/isEmpty";
import { useField } from "formik";
import React, { Component } from "react";
import { RadioField } from "react-invenio-forms";
Expand All @@ -18,17 +19,31 @@ import PropTypes from "prop-types";

const VisibilityField = ({ label, formConfig, ...props }) => {
const [field] = useField(props);
const fieldPath = "access.visibility";

function createHandleChange(radioValue) {
function handleChange({ event, data, formikProps }) {
formikProps.form.setFieldValue(fieldPath, radioValue);
// dependent fields
if (radioValue === "restricted") {
formikProps.form.setFieldValue("access.member_policy", "closed");
}
}
return handleChange;
}

return (
<>
{formConfig.access.visibility.map((item) => (
<React.Fragment key={item.value}>
<RadioField
key={item.value}
fieldPath="access.visibility"
fieldPath={fieldPath}
label={item.text}
labelIcon={item.icon}
checked={_get(field.value, "access.visibility") === item.value}
checked={_get(field.value, fieldPath) === item.value}
value={item.value}
onChange={createHandleChange(item.value)}
/>
<label className="helptext">{item.helpText}</label>
</React.Fragment>
Expand Down Expand Up @@ -76,14 +91,47 @@ MembersVisibilityField.defaultProps = {
label: "",
};

const MemberPolicyField = ({ label, formConfig, ...props }) => {
const [field] = useField(props);
const isDisabled = _get(field.value, "access.visibility") === "restricted";

return (
<>
{formConfig.access.member_policy.map((item) => (
<React.Fragment key={item.value}>
<RadioField
key={item.value}
fieldPath="access.member_policy"
label={item.text}
labelIcon={item.icon}
checked={item.value === _get(field.value, "access.member_policy")}
value={item.value}
disabled={isDisabled}
/>
<label className="helptext">{item.helpText}</label>
</React.Fragment>
))}
</>
);
};

MemberPolicyField.propTypes = {
label: PropTypes.string,
formConfig: PropTypes.object.isRequired,
};

MemberPolicyField.defaultProps = {
label: "",
};

class CommunityPrivilegesForm extends Component {
getInitialValues = () => {
return {
access: {
visibility: "public",
members_visibility: "public",
member_policy: "closed",
// TODO: Re-enable once properly integrated to be displayed
// member_policy: "open",
// record_policy: "open",
},
};
Expand All @@ -105,6 +153,7 @@ class CommunityPrivilegesForm extends Component {
</Header.Subheader>
</Header>
<VisibilityField formConfig={formConfig} />

<Header as="h2" size="small">
{i18next.t("Members visibility")}
<Header.Subheader className="mt-5">
Expand All @@ -114,6 +163,19 @@ class CommunityPrivilegesForm extends Component {
</Header.Subheader>
</Header>
<MembersVisibilityField formConfig={formConfig} />

{!_isEmpty(formConfig.access.member_policy) && (
<>
<Header as="h2" size="small">
{i18next.t("Membership Policy")}
<Header.Subheader className="mt-5">
{i18next.t("Controls if anyone can request to join your community.")}
</Header.Subheader>
</Header>
<MemberPolicyField formConfig={formConfig} />
</>
)}

{/* TODO: Re-enable once properly integrated to be displayed */}
{/*
<Grid.Column width={6}>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import CommunityPrivilegesForm from "./CommunityPriviledgesForm";
import CommunityPrivilegesForm from "./CommunityPrivilegesForm";
import ReactDOM from "react-dom";
import React from "react";

Expand Down
3 changes: 3 additions & 0 deletions invenio_communities/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -314,3 +314,6 @@

COMMUNITIES_ALWAYS_SHOW_CREATE_LINK = False
"""Controls visibility of 'New Community' btn based on user's permission when set to True."""

COMMUNITIES_ALLOW_MEMBERSHIP_REQUESTS = False
"""Feature flag for membership request."""
24 changes: 23 additions & 1 deletion invenio_communities/generators.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
from itertools import chain

from flask_principal import UserNeed
from invenio_access.permissions import any_user, system_process
from invenio_access.permissions import any_user, authenticated_user, system_process
from invenio_records_permissions.generators import Generator
from invenio_search.engine import dsl

Expand Down Expand Up @@ -199,6 +199,28 @@ def query_filter(self, **kwargs):
#
# Community membership generators
#


class AuthenticatedButNotCommunityMembers(Generator):
"""Authenticated user not part of community."""

def needs(self, record=None, **kwargs):
"""Required needs."""
return [authenticated_user]

def excludes(self, record=None, **kwargs):
"""Exluding needs.

Excludes identities with a role in the community. This assumes all roles at
this point mean valid memberships. This is the same assumption as
`CommunityMembers` below.
"""
if not record:
return []
community_id = str(record.id)
return [CommunityRoleNeed(community_id, r.name) for r in current_roles]


class CommunityRoles(Generator):
"""Base class for community roles generators."""

Expand Down
3 changes: 2 additions & 1 deletion invenio_communities/members/resources/config.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# -*- coding: utf-8 -*-
#
# Copyright (C) 2022 KTH Royal Institute of Technology
# Copyright (C) 2022 Northwestern University.
# Copyright (C) 2022-2024 Northwestern University.
# Copyright (C) 2022 CERN.
# Copyright (C) 2023 TU Wien.
#
Expand Down Expand Up @@ -29,6 +29,7 @@ class MemberResourceConfig(RecordResourceConfig):
"members": "/communities/<pid_value>/members",
"publicmembers": "/communities/<pid_value>/members/public",
"invitations": "/communities/<pid_value>/invitations",
"membership_requests": "/communities/<pid_value>/membership-requests",
}
request_view_args = {
"pid_value": ma.fields.UUID(),
Expand Down
14 changes: 13 additions & 1 deletion invenio_communities/members/resources/resource.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,10 +31,11 @@ def create_url_rules(self):
route("DELETE", routes["members"], self.delete),
route("PUT", routes["members"], self.update),
route("GET", routes["members"], self.search),
route("POST", routes["invitations"], self.invite),
route("GET", routes["publicmembers"], self.search_public),
route("POST", routes["invitations"], self.invite),
route("PUT", routes["invitations"], self.update_invitations),
route("GET", routes["invitations"], self.search_invitations),
route("POST", routes["membership_requests"], self.request_membership),
]

@request_view_args
Expand Down Expand Up @@ -98,6 +99,17 @@ def invite(self):
)
return "", 204

@request_view_args
@request_data
def request_membership(self):
"""Request membership."""
request = self.service.request_membership(
g.identity,
resource_requestctx.view_args["pid_value"],
resource_requestctx.data,
)
return request.to_dict(), 201

@request_view_args
@request_extra_args
@request_data
Expand Down
18 changes: 18 additions & 0 deletions invenio_communities/members/services/request.py
Original file line number Diff line number Diff line change
Expand Up @@ -124,3 +124,21 @@ class CommunityInvitation(RequestType):
"manager",
]
}


class MembershipRequestRequestType(RequestType):
"""Request type for membership requests."""

type_id = "community-membership-request"
name = _("Membership request")

create_action = "create"
available_actions = {
"create": actions.CreateAndSubmitAction,
}

creator_can_be_none = False
topic_can_be_none = False
allowed_creator_ref_types = ["user"]
allowed_receiver_ref_types = ["community"]
allowed_topic_ref_types = ["community"]
6 changes: 6 additions & 0 deletions invenio_communities/members/services/schemas.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,12 @@ class DeleteBulkSchema(MembersSchema):
"""Delete bulk schema."""


class RequestMembershipSchema(Schema):
"""Schema used for requesting membership."""

message = SanitizedUnicode()


#
# Schemas used for dumping a single member
#
Expand Down
Loading
Loading