Add api route and webclient page for account settings

This commit is contained in:
Tanner Collin 2020-01-12 08:16:09 +00:00
parent 82dfa132e7
commit e256e32341
8 changed files with 200 additions and 89 deletions

View File

@ -11,6 +11,8 @@ class Member(models.Model):
last_name = models.CharField(max_length=32) last_name = models.CharField(max_length=32)
set_details = models.BooleanField(default=False) set_details = models.BooleanField(default=False)
is_director = models.BooleanField(default=False)
is_instructor = models.BooleanField(default=False)
preferred_name = models.CharField(max_length=32, blank=True) preferred_name = models.CharField(max_length=32, blank=True)
status = models.CharField(max_length=32, blank=True) status = models.CharField(max_length=32, blank=True)
phone = models.CharField(max_length=32, blank=True) phone = models.CharField(max_length=32, blank=True)

View File

@ -12,8 +12,8 @@ from . import models, old_models
STATIC_FOLDER = 'data/static/' STATIC_FOLDER = 'data/static/'
LARGE_SIZE = 1080 LARGE_SIZE = 1080
MEDIUM_SIZE = 150 MEDIUM_SIZE = 220
SMALL_SIZE = 80 SMALL_SIZE = 110
def process_image(upload): def process_image(upload):
try: try:
@ -74,17 +74,49 @@ class OtherMemberSerializer(serializers.ModelSerializer):
# member viewing himself # member viewing himself
class MemberSerializer(serializers.ModelSerializer): class MemberSerializer(serializers.ModelSerializer):
photo = serializers.ImageField(write_only=True, required=False)
class Meta: class Meta:
model = models.Member model = models.Member
fields = '__all__' fields = '__all__'
read_only_fields = ['user', 'application_date', 'current_start_date', 'vetted_date', 'monthly_fees', 'old_member_id'] read_only_fields = [
'id',
'is_director',
'is_instructor',
'status',
'expire_date',
'current_start_date',
'application_date',
'vetted_date',
'monthly_fees',
'photo_large',
'photo_medium',
'photo_small',
'user',
]
def update(self, instance, validated_data):
photo = validated_data.get('photo', None)
if photo:
small, medium, large = process_image(photo)
instance.photo_small = small
instance.photo_medium = medium
instance.photo_large = large
return super().update(instance, validated_data)
# adming viewing member # adming viewing member
class AdminMemberSerializer(serializers.ModelSerializer): class AdminMemberSerializer(MemberSerializer):
class Meta: class Meta:
model = models.Member model = models.Member
fields = '__all__' fields = '__all__'
read_only_fields = ['id', 'user'] read_only_fields = [
'id',
'photo_large',
'photo_medium',
'photo_small',
'user',
]
class TransactionSerializer(serializers.ModelSerializer): class TransactionSerializer(serializers.ModelSerializer):

View File

@ -1,6 +1,7 @@
from django.contrib.auth.models import User, Group from django.contrib.auth.models import User, Group
from django.db.models import Max from django.db.models import Max
from rest_framework import viewsets, views, permissions, mixins from rest_framework import viewsets, views, mixins, generics, exceptions
from rest_framework.permissions import BasePermission, IsAuthenticated
from rest_framework.response import Response from rest_framework.response import Response
from rest_auth.registration.views import RegisterView from rest_auth.registration.views import RegisterView
from fuzzywuzzy import fuzz, process from fuzzywuzzy import fuzz, process
@ -8,10 +9,23 @@ from collections import OrderedDict
from . import models, serializers from . import models, serializers
class AllowMetadata(permissions.BasePermission): class AllowMetadata(BasePermission):
def has_permission(self, request, view): def has_permission(self, request, view):
return request.method in ['OPTIONS', 'HEAD'] return request.method in ['OPTIONS', 'HEAD']
def is_admin_director(user):
return user.is_staff or user.member.is_director
class IsOwnerOrAdmin(BasePermission):
def has_object_permission(self, request, view, obj):
return obj.user == request.user or is_admin_director(request.user)
class RetrieveUpdateViewSet(
viewsets.GenericViewSet,
mixins.RetrieveModelMixin,
mixins.UpdateModelMixin):
def list(self, request):
raise exceptions.PermissionDenied
search_strings = {} search_strings = {}
@ -25,11 +39,10 @@ def gen_search_strings():
NUM_SEARCH_RESULTS = 10 NUM_SEARCH_RESULTS = 10
class SearchViewSet(viewsets.GenericViewSet, mixins.RetrieveModelMixin): class SearchViewSet(viewsets.GenericViewSet, mixins.RetrieveModelMixin):
permission_classes = [AllowMetadata | permissions.IsAuthenticated] permission_classes = [AllowMetadata | IsAuthenticated]
serializer_class = serializers.OtherMemberSerializer serializer_class = serializers.OtherMemberSerializer
def get_queryset(self): def get_queryset(self):
queryset = models.Member.objects.all() queryset = models.Member.objects.all()
search = self.request.data.get('q', '').lower() search = self.request.data.get('q', '').lower()
@ -71,26 +84,19 @@ class SearchViewSet(viewsets.GenericViewSet, mixins.RetrieveModelMixin):
return Response({'seq': seq, 'results': serializer.data}) return Response({'seq': seq, 'results': serializer.data})
class MemberViewSet(viewsets.ModelViewSet): class MemberViewSet(RetrieveUpdateViewSet):
permission_classes = [AllowMetadata | permissions.IsAuthenticated] permission_classes = [AllowMetadata | IsAuthenticated, IsOwnerOrAdmin]
http_method_names = ['options', 'head', 'get', 'put', 'patch'] queryset = models.Member.objects.all()
def get_queryset(self):
objects = models.Member.objects.all()
if self.request.user.is_staff:
return objects.order_by('id')
else:
return objects.filter(user=self.request.user)
def get_serializer_class(self): def get_serializer_class(self):
if self.request.user.is_staff: if is_admin_director(self.request.user):
return serializers.AdminMemberSerializer return serializers.AdminMemberSerializer
else: else:
return serializers.MemberSerializer return serializers.MemberSerializer
class CourseViewSet(viewsets.ModelViewSet): class CourseViewSet(viewsets.ModelViewSet):
permission_classes = [AllowMetadata | permissions.IsAuthenticated] permission_classes = [AllowMetadata | IsAuthenticated]
queryset = models.Course.objects.annotate(date=Max('sessions__datetime')).order_by('-date') queryset = models.Course.objects.annotate(date=Max('sessions__datetime')).order_by('-date')
def get_serializer_class(self): def get_serializer_class(self):
@ -101,7 +107,7 @@ class CourseViewSet(viewsets.ModelViewSet):
class SessionViewSet(viewsets.ModelViewSet): class SessionViewSet(viewsets.ModelViewSet):
permission_classes = [AllowMetadata | permissions.IsAuthenticated] permission_classes = [AllowMetadata | IsAuthenticated]
def get_queryset(self): def get_queryset(self):
if self.action == 'list': if self.action == 'list':
@ -117,7 +123,7 @@ class SessionViewSet(viewsets.ModelViewSet):
class MyUserView(views.APIView): class MyUserView(views.APIView):
permission_classes = [AllowMetadata | permissions.IsAuthenticated] permission_classes = [AllowMetadata | IsAuthenticated]
def get(self, request): def get(self, request):
serializer = serializers.UserSerializer(request.user) serializer = serializers.UserSerializer(request.user)

View File

@ -7,7 +7,7 @@ from .api import views
router = routers.DefaultRouter() router = routers.DefaultRouter()
#router.register(r'users', views.UserViewSet) #router.register(r'users', views.UserViewSet)
router.register(r'members', views.MemberViewSet, basename='member') router.register(r'members', views.MemberViewSet, basename='members')
router.register(r'courses', views.CourseViewSet, basename='course') router.register(r'courses', views.CourseViewSet, basename='course')
router.register(r'sessions', views.SessionViewSet, basename='session') router.register(r'sessions', views.SessionViewSet, basename='session')
router.register(r'search', views.SearchViewSet, basename='search') router.register(r'search', views.SearchViewSet, basename='search')

94
webclient/src/Account.js Normal file
View File

@ -0,0 +1,94 @@
import React, { useState, useEffect } from 'react';
import { BrowserRouter as Router, Switch, Route, Link, useParams, useHistory } from 'react-router-dom';
import './light.css';
import { Container, Divider, Dropdown, Form, Grid, Header, Icon, Image, Menu, Message, Segment, Table } from 'semantic-ui-react';
import { BasicTable, staticUrl, requester } from './utils.js';
import { LoginForm, SignupForm } from './LoginSignup.js';
function AccountForm(props) {
const member = props.user.member;
const [input, setInput] = useState({ ...member, set_details: true });
const [error, setError] = useState({});
const [loading, setLoading] = useState(false);
const history = useHistory();
const handleValues = (e, v) => setInput({ ...input, [v.name]: v.value });
const handleUpload = (e, v) => setInput({ ...input, [v.name]: e.target.files[0] });
const handleChange = (e) => handleValues(e, e.currentTarget);
const handleSubmit = (e) => {
setLoading(true);
requester('/members/' + member.id + '/', 'PATCH', props.token, input)
.then(res => {
console.log(res);
setError({});
props.setUserCache({...props.user, member: res});
history.push('/');
})
.catch(err => {
setLoading(false);
console.log(err);
setError(err.data);
});
};
const makeProps = (name) => ({
name: name,
onChange: handleChange,
value: input[name],
error: error[name],
});
return (
<Form onSubmit={handleSubmit}>
<Header size='medium'>Member Details</Header>
<Form.Input
label='First Name'
{...makeProps('first_name')}
/>
<Form.Input
label='Last Name'
{...makeProps('last_name')}
/>
<Form.Input
label='Preferred First Name'
{...makeProps('preferred_name')}
/>
<Form.Input
label='Phone Number (999) 555-1234'
{...makeProps('phone')}
/>
<Form.Input
label='Emergency Contact Name'
{...makeProps('emergency_contact_name')}
/>
<Form.Input
label='Emergency Contact Phone'
{...makeProps('emergency_contact_phone')}
/>
<Form.Input
label='Member Photo'
name='photo'
type='file'
accept='image/*'
onChange={handleUpload}
/>
<Form.Button loading={loading} error={error.non_field_errors}>
Submit
</Form.Button>
</Form>
);
};
export function Account(props) {
return (
<Container>
<Header size='large'>Account Settings</Header>
<AccountForm {...props} />
</Container>
);
};

View File

@ -3,6 +3,7 @@ import { BrowserRouter as Router, Switch, Route, Link, useParams } from 'react-r
import './light.css'; import { Container, Divider, Dropdown, Form, Grid, Header, Icon, Image, Menu, Message, Segment, Table } from 'semantic-ui-react'; import './light.css'; import { Container, Divider, Dropdown, Form, Grid, Header, Icon, Image, Menu, Message, Segment, Table } from 'semantic-ui-react';
import { requester } from './utils.js'; import { requester } from './utils.js';
import { Home } from './Home.js'; import { Home } from './Home.js';
import { Account } from './Account.js';
import { Transactions, TransactionDetail } from './Transactions.js'; import { Transactions, TransactionDetail } from './Transactions.js';
import { Cards } from './Cards.js'; import { Cards } from './Cards.js';
import { Training } from './Training.js'; import { Training } from './Training.js';
@ -39,9 +40,9 @@ function App() {
}, [token]); }, [token]);
function logout() { function logout() {
window.location = '/';
setTokenCache(''); setTokenCache('');
setUserCache(false); setUserCache(false);
window.location = '/';
} }
return ( return (
@ -65,9 +66,9 @@ function App() {
<Dropdown item text='Member' id='ps-menu'> <Dropdown item text='Member' id='ps-menu'>
<Dropdown.Menu> <Dropdown.Menu>
<Dropdown.Item <Dropdown.Item
content='Profile' content='Account'
as={Link} as={Link}
to='/transactions' to='/account'
/> />
<Dropdown.Item <Dropdown.Item
content='Transactions' content='Transactions'
@ -84,11 +85,6 @@ function App() {
as={Link} as={Link}
to='/cards' to='/cards'
/> />
<Dropdown.Item
content='Account'
as={Link}
to='/cards'
/>
</Dropdown.Menu> </Dropdown.Menu>
</Dropdown> </Dropdown>
@ -130,6 +126,10 @@ function App() {
<div className='topPadding'> <div className='topPadding'>
{user ? {user ?
<Switch> <Switch>
<Route path='/account'>
<Account token={token} user={user} setUserCache={setUserCache} />
</Route>
<Route path='/transactions/:id'> <Route path='/transactions/:id'>
<TransactionDetail user={user} /> <TransactionDetail user={user} />
</Route> </Route>

View File

@ -7,21 +7,11 @@ import { LoginForm, SignupForm } from './LoginSignup.js';
function SignupDetailsForm(props) { function SignupDetailsForm(props) {
const member = props.user.member; const member = props.user.member;
const [input, setInput] = useState({ const [input, setInput] = useState({ ...member, set_details: true });
preferred_name: member.preferred_name,
phone: member.phone,
emergency_contact_name: member.emergency_contact_name,
emergency_contact_phone: member.emergency_contact_phone,
set_details: true,
});
const [error, setError] = useState({}); const [error, setError] = useState({});
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
const handleValues = (e, v) => setInput({ const handleValues = (e, v) => setInput({ ...input, [v.name]: v.value });
...input,
[v.name]: v.value
});
const handleChange = (e) => handleValues(e, e.currentTarget); const handleChange = (e) => handleValues(e, e.currentTarget);
const handleSubmit = (e) => { const handleSubmit = (e) => {
@ -39,36 +29,31 @@ function SignupDetailsForm(props) {
}); });
}; };
const makeProps = (name) => ({
name: name,
onChange: handleChange,
value: input[name],
error: error[name],
});
return ( return (
<Form onSubmit={handleSubmit}> <Form onSubmit={handleSubmit}>
<Header size='medium'>Enter Member Details</Header> <Header size='medium'>Enter Member Details</Header>
<Form.Input <Form.Input
label='Preferred Name' label='Preferred First Name'
name='preferred_name' {...makeProps('preferred_name')}
onChange={handleChange}
value={input.preferred_name}
error={error.preferred_name}
/> />
<Form.Input <Form.Input
label='Phone Number (999) 555-1234' label='Phone Number (999) 555-1234'
name='phone' {...makeProps('phone')}
onChange={handleChange}
value={input.phone}
error={error.phone}
/> />
<Form.Input <Form.Input
label='Emergency Contact Name' label='Emergency Contact Name'
name='emergency_contact_name' {...makeProps('emergency_contact_name')}
onChange={handleChange}
value={input.emergency_contact_name}
error={error.emergency_contact_name}
/> />
<Form.Input <Form.Input
label='Emergency Contact Phone' label='Emergency Contact Phone'
name='emergency_contact_phone' {...makeProps('emergency_contact_phone')}
onChange={handleChange}
value={input.emergency_contact_phone}
error={error.emergency_contact_phone}
/> />
<Form.Button loading={loading} error={error.non_field_errors}> <Form.Button loading={loading} error={error.non_field_errors}>
@ -107,7 +92,7 @@ function MemberInfo(props) {
<Table.Body> <Table.Body>
<Table.Row> <Table.Row>
<Table.Cell>Status:</Table.Cell> <Table.Cell>Status:</Table.Cell>
<Table.Cell>{member.status}</Table.Cell> <Table.Cell>{member.status || 'Unknown'}</Table.Cell>
</Table.Row> </Table.Row>
<Table.Row> <Table.Row>
<Table.Cell>Expiry:</Table.Cell> <Table.Cell>Expiry:</Table.Cell>
@ -123,11 +108,11 @@ function MemberInfo(props) {
<Table.Body> <Table.Body>
<Table.Row> <Table.Row>
<Table.Cell>Application:</Table.Cell> <Table.Cell>Application:</Table.Cell>
<Table.Cell>{member.application_date || '???'}</Table.Cell> <Table.Cell>{member.application_date || 'Unknown'}</Table.Cell>
</Table.Row> </Table.Row>
<Table.Row> <Table.Row>
<Table.Cell>Start:</Table.Cell> <Table.Cell>Start:</Table.Cell>
<Table.Cell>{member.current_start_date || '???'}</Table.Cell> <Table.Cell>{member.current_start_date || 'Unknown'}</Table.Cell>
</Table.Row> </Table.Row>
<Table.Row> <Table.Row>
<Table.Cell>Vetted:</Table.Cell> <Table.Cell>Vetted:</Table.Cell>
@ -135,7 +120,7 @@ function MemberInfo(props) {
</Table.Row> </Table.Row>
<Table.Row> <Table.Row>
<Table.Cell>Monthly:</Table.Cell> <Table.Cell>Monthly:</Table.Cell>
<Table.Cell>${member.monthly_fees || '???'}</Table.Cell> <Table.Cell>${member.monthly_fees || 'Unknown'}</Table.Cell>
</Table.Row> </Table.Row>
<Table.Row> <Table.Row>
<Table.Cell>Card Number:</Table.Cell> <Table.Cell>Card Number:</Table.Cell>

View File

@ -9,11 +9,7 @@ export function LoginForm(props) {
const [error, setError] = useState({}); const [error, setError] = useState({});
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
const handleValues = (e, v) => setInput({ const handleValues = (e, v) => setInput({ ...input, [v.name]: v.value });
...input,
[v.name]: v.value
});
const handleChange = (e) => handleValues(e, e.currentTarget); const handleChange = (e) => handleValues(e, e.currentTarget);
const handleSubmit = (e) => { const handleSubmit = (e) => {
@ -60,11 +56,7 @@ export function SignupForm(props) {
const [error, setError] = useState({}); const [error, setError] = useState({});
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
const handleValues = (e, v) => setInput({ const handleValues = (e, v) => setInput({ ...input, [v.name]: v.value });
...input,
[v.name]: v.value
});
const handleChange = (e) => handleValues(e, e.currentTarget); const handleChange = (e) => handleValues(e, e.currentTarget);
const genUsername = () => ( const genUsername = () => (
@ -93,26 +85,26 @@ export function SignupForm(props) {
return ( return (
<Form onSubmit={handleSubmit}> <Form onSubmit={handleSubmit}>
<Header size='medium'>Sign Up</Header> <Header size='medium'>Sign Up</Header>
<Form.Group widths='equal'>
<Form.Input <Form.Input
label='First Name' label='First Name'
name='first_name' name='first_name'
onChange={handleChange} onChange={handleChange}
error={error.first_name} error={error.first_name}
/> />
<Form.Input <Form.Input
label='Last Name' label='Last Name'
name='last_name' name='last_name'
onChange={handleChange} onChange={handleChange}
error={error.last_name} error={error.last_name}
/> />
</Form.Group>
<Form.Input <Form.Input
label='Username' label='Username'
name='username' name='username'
value={genUsername()} value={genUsername()}
error={error.username} error={error.username}
readOnly
/> />
<Form.Input <Form.Input
label='Email' label='Email'