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

Member role add (fixes: #405) #406

Open
wants to merge 16 commits into
base: main
Choose a base branch
from
Open
52 changes: 50 additions & 2 deletions api/src/controllers/communityUserController.js
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ const getAllMembers = async (req, res) => {
const data = await db.CommunityUser.findAll(
{
where: { communityId: req.params.id, active: true },
attributes: ['userId'],
attributes: ['userId', 'role'],
include: [{
model: db.User,
attributes: ['firstName']
Expand All @@ -101,6 +101,54 @@ const getAllMembers = async (req, res) => {
}
}

// @desc Get the community-users
// @route GET /api/community-users/community/:id/details
// @access Public

const getAllMemberDetails = async (req, res) => {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

seems like getAllMemberDetails, getAllMembers, getCommunityUsers can be single function

try {
const data = await db.CommunityUser.findAll(
{
where: { communityId: req.params.id, active: true },
attributes: ['id', 'userId', 'role'],
include: [{
model: db.User,
attributes: ['firstName', 'lastName', 'email', 'phone', 'dateOfBirth']
}],
required: true
}
)

// flattening the array to show only one object
const newArray = data.map(item => {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

it could just be nested to after findall

const {userId, role, id} = item.dataValues
const {...rest} = item.user
return {id, userId, role, ...rest.dataValues}
}
)

res.json({
results: newArray
})
} catch (error) {
res.status(400).json({ error })
}
}

// @desc Update the community users
// @route PUT /api/community-users/:memberId/community/:id/
// @access Public

const updateMemberRole = async (req, res) => {
try {
const {role} = req.body
await db.CommunityUser.update({role}, {where: {id: parseInt(req.params.memberId)}})
res.json({message: 'Successfully role updated'})
} catch (error) {
res.status(400).json({error})
}
}

// @desc Search Name
// @route POST /api/news/community/:id/search
// @access Private
Expand Down Expand Up @@ -129,4 +177,4 @@ const searchMemberName = (req, res) => {
.catch(err => res.json({ error: err }).status(400))
}

module.exports = { getCommunityUsers, followCommunity, getAllMembers, searchMemberName }
module.exports = { getCommunityUsers, followCommunity, getAllMembers, searchMemberName, getAllMemberDetails, updateMemberRole }
15 changes: 15 additions & 0 deletions api/src/middleware/memberPermit.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
const db = require("../models")
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

move this to permission file so that we don't have lot of permission files


const memberPermit = (role) => {

return async (req, res, next) => {
const member = await db.CommunityUser.findOne({where: {userId: req.user.id, communityId: req.params.id}, attributes: ['role']});
if (member.dataValues.role === role) {
next()
} else {
res.json({ error: 'Sorry, You don\'t have permission' })
}
}
}

module.exports = memberPermit
14 changes: 14 additions & 0 deletions api/src/migrations/20210728085949-alter_community_user.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
'use strict';

module.exports = {
up: async (queryInterface, Sequelize) => {
queryInterface.addColumn('communities_users', 'role', {
type: Sequelize.STRING,
defaultValue: 'member'
})
},

down: async (queryInterface, Sequelize) => {
queryInterface.removeColumn('communities_users', 'role')
}
};
4 changes: 4 additions & 0 deletions api/src/models/communityUserModel.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,10 @@ module.exports = (sequelize, DataTypes) => {
active: {
type: DataTypes.INTEGER,
defaultValue: true
},
role: {
type: DataTypes.STRING,
defaultValue: 'member'
}
},
{ timestamps: true }
Expand Down
8 changes: 5 additions & 3 deletions api/src/routes/communityUserRouter.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
const { getCommunityUsers, followCommunity, getAllMembers, searchMemberName } = require('../controllers/communityUserController')
const { getCommunityUsers, followCommunity, getAllMembers, searchMemberName, getAllMemberDetails, updateMemberRole } = require('../controllers/communityUserController')
const protect = require('../middleware/authMiddleware')
const memberPermit = require('../middleware/memberPermit')
const router = require('express').Router()

router.get('/', getCommunityUsers)
router.post('/follow', protect, followCommunity)
router.get('/community/:id', getAllMembers)
router.get('/community/:id', protect, memberPermit('manager'), getAllMembers)
router.get('/community/:id/search', searchMemberName)
router.put('/:memberId/community/:id/', protect, memberPermit('manager'), updateMemberRole)
// router.put('/:id', updateCommunityUsers);

router.get('/community/:id/details', protect, memberPermit('manager'), getAllMemberDetails)
module.exports = router
2 changes: 2 additions & 0 deletions src/App.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ import AddTest from './screens/addTest/AddTest'
import LogoutUser from './screens/logoutUser/LogoutUser'
import Category from './screens/category/Category'
import PageNotFound from './screens/pageNotFound/PageNotFound'
import CommunityMemberAdmin from './screens/admin/CommunityMemberAdmin'

function App () {
return (
Expand All @@ -78,6 +79,7 @@ function App () {
<PrivateRoute component={CommunityNewsViewPage} path='/community-page-news-view' exact />
<PrivateRoute component={AllCommunitiesCard} path='/community-switching' exact />
<PrivateRoute component={CommunityMembers} path='/community-members/:id' exact />
<PrivateRoute component={CommunityMemberAdmin} path='/admin/community-members' exact />
<PrivateRoute component={CommunityMembersProfile} path='/community-members-profile/:id' exact />
<PrivateRoute component={CommunityGroup} path='/community-group/:id' exact />
<PrivateRoute component={CommunityGroup} path='/your-community-group/:id' exact />
Expand Down
73 changes: 73 additions & 0 deletions src/screens/admin/CommunityMemberAdmin.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
import axios from 'axios';
import React, { useEffect, useState } from 'react'
import { useDispatch } from 'react-redux'
import DashboardLayout from '../../layout/dashboardLayout/DashboardLayout'
import { getApi, getCommunity, putApi } from '../../utils/apiFunc'
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

there was already another function to get current community

import './CommunityMemberAdmin.scss';

const ComMemberAdmin = () => {
const [data, setData] = useState([]);
const [success, setSuccess] = useState(null);

const dispatch = useDispatch();

// getting current community from localstorage
const currentCommunity = getCommunity();

useEffect(() => {
getMemberDetails()
}, [success])

const getMemberDetails = async () => {
const { data } = await getApi(
dispatch,
`${process.env.REACT_APP_API_BASE_URL}/api/communities-users/community/${currentCommunity.id}/details`
)
setData(data.results)
}

const allowAccess = async (id) => {
// const {data} = await axios.put(`${process.env.REACT_APP_API_BASE_URL}/api/communities-users/${id}/community/${currentCommunity.id}`,
// {role: "manager"}, config)
const {data} = await putApi(
dispatch,
`${process.env.REACT_APP_API_BASE_URL}/api/communities-users/${id}/community/${currentCommunity.id}`,
{role: 'manager'}
)
setSuccess(data)
}

return (
<DashboardLayout title={currentCommunity.name}>
<div className="com-member-container">
<div className="com-member-header">
{
["firstName", "lastName", "email", "phone", "dateOfBirth", "role", "options"].map(el => {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

do manual lint fix
whole file needs to fix linting seems like its using 4 spaces instead of 2

return (
<p>{el}</p>
)
})
}
</div>
{
data.map(item => {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

use table.jsx from main branch

const {firstName, lastName, email, phone, dateOfBirth, role} = item
return (
<div className="com-member-item">
<p>{firstName ? firstName : 'name'}</p>
<p>{lastName ? lastName : 'lastname'}</p>
<p>{email ? email : 'email'}</p>
<p>{phone ? phone : 'phone'}</p>
<p>{dateOfBirth ? dateOfBirth : 'dateOfBirth'}</p>
<p>{role ? role : 'role'}</p>
<p className="access-btn"><img src="/img/edit-icon.svg" onClick={() => allowAccess(item.id)} /></p>
</div>
)
})
}
</div>
</DashboardLayout>
)
}

export default ComMemberAdmin
38 changes: 38 additions & 0 deletions src/screens/admin/CommunityMemberAdmin.scss
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
.com-member-container {
width: 100%;
display: flex;
flex-direction: column;
color: #fff;
}

.com-member-header {
width: 100%;
display: flex;
align-items: center;
justify-content: space-between;
background: var(--primary-color);
padding: 12px;
text-align: center;

p {
flex: 1;
}
}

.com-member-item {
width: 100%;
display: flex;
align-items: center;
justify-content: space-between;
padding: 8px;
text-align: center;
background: var(--dropdowns);

p {
flex: 1;
}
}

.access-btn {
cursor: pointer;
}
4 changes: 4 additions & 0 deletions src/utils/apiFunc.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,3 +15,7 @@ export const getApi = async (dispatch, url, config) => {
export const postApi = async (dispatch, url, data, config) => {
return await axios.post(url, data, configFunc(config))
}

export const putApi = async (dispatch, url, data, config) => {
return await axios.put(url, data, configFunc(config))
}