Move search result member into its own object

This commit is contained in:
Tanner Collin 2020-01-14 00:52:15 +00:00
parent f52ee5532d
commit 579966e7aa
6 changed files with 105 additions and 58 deletions

View File

@ -42,24 +42,31 @@ def process_image(upload):
return small, medium, large return small, medium, large
# member viewing member list or other member
class OtherMemberSerializer(serializers.ModelSerializer):
q = serializers.CharField(write_only=True, max_length=64)
seq = serializers.IntegerField(write_only=True)
class Meta:
model = models.Member
fields = ['q', 'seq', 'id', 'preferred_name', 'last_name', 'status', 'current_start_date', 'photo_small', 'photo_large']
class UserEmailField(serializers.ModelField): class UserEmailField(serializers.ModelField):
def to_representation(self, obj): def to_representation(self, obj):
return getattr(obj.user, 'email', obj.old_email) return getattr(obj.user, 'email', obj.old_email)
def to_internal_value(self, data): def to_internal_value(self, data):
return serializers.EmailField().run_validation(data) return serializers.EmailField().run_validation(data)
# member viewing himself
class AdminCardSerializer(serializers.ModelSerializer):
card_number = serializers.CharField()
class Meta:
model = models.Card
fields = '__all__'
read_only_fields = ['last_seen_at']
# member viewing other members
class OtherMemberSerializer(serializers.ModelSerializer):
class Meta:
model = models.Member
fields = ['id', 'preferred_name', 'last_name', 'status', 'current_start_date', 'photo_small', 'photo_large']
# member viewing his own details
class MemberSerializer(serializers.ModelSerializer): class MemberSerializer(serializers.ModelSerializer):
photo = serializers.ImageField(write_only=True, required=False) photo = serializers.ImageField(write_only=True, required=False)
email = UserEmailField(serializers.EmailField) email = UserEmailField(serializers.EmailField)
@ -85,12 +92,15 @@ class MemberSerializer(serializers.ModelSerializer):
'photo_medium', 'photo_medium',
'photo_small', 'photo_small',
'user', 'user',
'old_email',
] ]
def update(self, instance, validated_data): def update(self, instance, validated_data):
if instance.user: if instance.user:
instance.user.email = validated_data.get('email', instance.user.email) instance.user.email = validated_data.get('email', instance.user.email)
instance.user.save() instance.user.save()
else:
instance.old_email = validated_data.get('email', instance.old_email)
photo = validated_data.get('photo', None) photo = validated_data.get('photo', None)
if photo: if photo:
@ -101,7 +111,7 @@ class MemberSerializer(serializers.ModelSerializer):
return super().update(instance, validated_data) return super().update(instance, validated_data)
# adming viewing member # admin viewing member details
class AdminMemberSerializer(MemberSerializer): class AdminMemberSerializer(MemberSerializer):
class Meta: class Meta:
model = models.Member model = models.Member
@ -113,10 +123,41 @@ class AdminMemberSerializer(MemberSerializer):
'photo_medium', 'photo_medium',
'photo_small', 'photo_small',
'user', 'user',
'old_email',
] ]
# member viewing member list or search result
class SearchSerializer(serializers.Serializer):
q = serializers.CharField(write_only=True, max_length=64)
seq = serializers.IntegerField(write_only=True)
member = serializers.SerializerMethodField()
def get_member(self, obj):
serializer = OtherMemberSerializer(obj)
return serializer.data
# admin viewing search result
class AdminSearchSerializer(serializers.Serializer):
cards = serializers.SerializerMethodField()
member = serializers.SerializerMethodField()
def get_member(self, obj):
serializer = AdminMemberSerializer(obj)
return serializer.data
def get_cards(self, obj):
if obj.user:
queryset = obj.user.cards
else:
queryset = models.Card.objects.filter(member_id=obj.id)
serializer = AdminCardSerializer(data=queryset, many=True)
serializer.is_valid()
return serializer.data
class UserTrainingSerializer(serializers.ModelSerializer): class UserTrainingSerializer(serializers.ModelSerializer):
class Meta: class Meta:
model = models.Training model = models.Training
@ -174,6 +215,7 @@ class AdminCourseSerializer(serializers.ModelSerializer):
fields = '__all__' fields = '__all__'
class RegistrationSerializer(RegisterSerializer): class RegistrationSerializer(RegisterSerializer):
first_name = serializers.CharField(max_length=32) first_name = serializers.CharField(max_length=32)
last_name = serializers.CharField(max_length=32) last_name = serializers.CharField(max_length=32)

View File

@ -21,6 +21,7 @@ class IsOwnerOrAdmin(BasePermission):
def has_object_permission(self, request, view, obj): def has_object_permission(self, request, view, obj):
return obj.user == request.user or is_admin_director(request.user) return obj.user == request.user or is_admin_director(request.user)
class RetrieveUpdateViewSet( class RetrieveUpdateViewSet(
viewsets.GenericViewSet, viewsets.GenericViewSet,
mixins.RetrieveModelMixin, mixins.RetrieveModelMixin,
@ -41,12 +42,20 @@ 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 | IsAuthenticated] permission_classes = [AllowMetadata | IsAuthenticated]
serializer_class = serializers.OtherMemberSerializer
def get_serializer_class(self):
if is_admin_director(self.request.user) and self.action == 'retrieve':
return serializers.AdminSearchSerializer
else:
return serializers.SearchSerializer
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()
if not search_strings:
gen_search_strings() # init cache
if len(search): if len(search):
choices = search_strings.keys() choices = search_strings.keys()
@ -68,7 +77,7 @@ class SearchViewSet(viewsets.GenericViewSet, mixins.RetrieveModelMixin):
queryset = result_objects queryset = result_objects
else: else:
gen_search_strings() gen_search_strings() # update cache
queryset = queryset.order_by('-vetted_date') queryset = queryset.order_by('-vetted_date')
return queryset return queryset
@ -81,7 +90,7 @@ class SearchViewSet(viewsets.GenericViewSet, mixins.RetrieveModelMixin):
seq = 0 seq = 0
queryset = self.get_queryset()[:NUM_SEARCH_RESULTS] queryset = self.get_queryset()[:NUM_SEARCH_RESULTS]
serializer = self.serializer_class(queryset, many=True) serializer = serializers.SearchSerializer(queryset, many=True)
return Response({'seq': seq, 'results': serializer.data}) return Response({'seq': seq, 'results': serializer.data})

View File

@ -17,7 +17,7 @@ function ChangePasswordForm(props) {
const handleSubmit = (e) => { const handleSubmit = (e) => {
setLoading(true); setLoading(true);
requester('/rest-auth/password/change/', 'POST', props.token, input) requester('/password/change/', 'POST', props.token, input)
.then(res => { .then(res => {
setError({}); setError({});
history.push('/'); history.push('/');
@ -32,7 +32,7 @@ function ChangePasswordForm(props) {
const makeProps = (name) => ({ const makeProps = (name) => ({
name: name, name: name,
onChange: handleChange, onChange: handleChange,
value: input[name], value: input[name] || '',
error: error[name], error: error[name],
}); });
@ -43,16 +43,19 @@ function ChangePasswordForm(props) {
<Form.Input <Form.Input
label='Old Password' label='Old Password'
type='password' type='password'
required
{...makeProps('old_password')} {...makeProps('old_password')}
/> />
<Form.Input <Form.Input
label='New Password' label='New Password'
type='password' type='password'
required
{...makeProps('new_password1')} {...makeProps('new_password1')}
/> />
<Form.Input <Form.Input
label='Confirm Password' label='Confirm Password'
type='password' type='password'
required
{...makeProps('new_password2')} {...makeProps('new_password2')}
/> />
@ -139,6 +142,11 @@ export function AccountForm(props) {
required required
{...makeProps('city')} {...makeProps('city')}
/> />
<Form.Input
label='Postal Code'
required
{...makeProps('postal_code')}
/>
<Form.Field> <Form.Field>
<label>Are you under 18 years old?</label> <label>Are you under 18 years old?</label>

View File

@ -5,7 +5,7 @@ import { Container, Checkbox, Divider, Dropdown, Form, Grid, Header, Icon, Image
import { BasicTable, staticUrl, requester } from './utils.js'; import { BasicTable, staticUrl, requester } from './utils.js';
export function AdminMemberForm(props) { export function AdminMemberForm(props) {
const [input, setInput] = useState(false); const [input, setInput] = useState(props.result.member);
const [error, setError] = useState(false); const [error, setError] = useState(false);
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
const [success, setSuccess] = useState(false); const [success, setSuccess] = useState(false);
@ -16,17 +16,6 @@ export function AdminMemberForm(props) {
const handleChange = (e) => handleValues(e, e.currentTarget); const handleChange = (e) => handleValues(e, e.currentTarget);
const handleCheck = (e, v) => setInput({ ...input, [v.name]: v.checked }); const handleCheck = (e, v) => setInput({ ...input, [v.name]: v.checked });
useEffect(() => {
requester('/members/'+id+'/', 'GET', props.token)
.then(res => {
setInput(res);
})
.catch(err => {
console.log(err);
setError(true);
});
}, []);
const handleSubmit = (e) => { const handleSubmit = (e) => {
setLoading(true); setLoading(true);
setSuccess(false); setSuccess(false);
@ -35,6 +24,7 @@ export function AdminMemberForm(props) {
setLoading(false); setLoading(false);
setSuccess(true); setSuccess(true);
setError(false); setError(false);
props.setResult({ ...props.result, member: res });
}) })
.catch(err => { .catch(err => {
setLoading(false); setLoading(false);
@ -57,6 +47,11 @@ export function AdminMemberForm(props) {
<Form onSubmit={handleSubmit}> <Form onSubmit={handleSubmit}>
<Header size='medium'>Edit Member Details</Header> <Header size='medium'>Edit Member Details</Header>
<Form.Input
label='Email'
{...makeProps('email')}
/>
<Form.Input <Form.Input
label='Application Date' label='Application Date'
{...makeProps('application_date')} {...makeProps('application_date')}
@ -117,21 +112,10 @@ export function AdminMemberForm(props) {
}; };
export function AdminMemberInfo(props) { export function AdminMemberInfo(props) {
const [member, setMember] = useState(false); const member = props.result.member;
const [error, setError] = useState(false); const [error, setError] = useState(false);
const { id } = useParams(); const { id } = useParams();
useEffect(() => {
requester('/members/'+id+'/', 'GET', props.token)
.then(res => {
setMember(res);
})
.catch(err => {
console.log(err);
setError(true);
});
}, []);
return ( return (
<div> <div>
{!error ? {!error ?

View File

@ -8,7 +8,7 @@ import { NotFound, PleaseLogin } from './Misc.js';
import { AdminMemberInfo, AdminMemberForm } from './Admin.js'; import { AdminMemberInfo, AdminMemberForm } from './Admin.js';
export function Members(props) { export function Members(props) {
const [members, setMembers] = useState(false); const [response, setResponse] = useState(false);
const searchDefault = {seq: 0, q: ''}; const searchDefault = {seq: 0, q: ''};
const [search, setSearch] = useState(searchDefault); const [search, setSearch] = useState(searchDefault);
const { token } = props; const { token } = props;
@ -16,8 +16,8 @@ export function Members(props) {
useEffect(() => { useEffect(() => {
requester('/search/', 'POST', token, search) requester('/search/', 'POST', token, search)
.then(res => { .then(res => {
if (!search.seq || res.seq > members.seq) { if (!search.seq || res.seq > response.seq) {
setMembers(res); setResponse(res);
} }
}) })
.catch(err => { .catch(err => {
@ -48,16 +48,16 @@ export function Members(props) {
{search.q.length ? 'Search Results' : 'Newest Vetted Members'} {search.q.length ? 'Search Results' : 'Newest Vetted Members'}
</Header> </Header>
{members ? {response ?
<Item.Group divided> <Item.Group divided>
{members.results.length ? {response.results.length ?
members.results.map((x, i) => response.results.map((x, i) =>
<Item key={i} as={Link} to={'/members/'+x.id}> <Item key={i} as={Link} to={'/members/'+x.member.id}>
<Item.Image size='tiny' src={x.photo_small ? staticUrl + '/' + x.photo_small : '/nophoto.png'} /> <Item.Image size='tiny' src={x.member.photo_small ? staticUrl + '/' + x.member.photo_small : '/nophoto.png'} />
<Item.Content verticalAlign='top'> <Item.Content verticalAlign='top'>
<Item.Header>{x.preferred_name} {x.last_name}</Item.Header> <Item.Header>{x.member.preferred_name} {x.member.last_name}</Item.Header>
<Item.Description>Status: {x.status || 'Unknown'}</Item.Description> <Item.Description>Status: {x.member.status || 'Unknown'}</Item.Description>
<Item.Description>Joined: {x.current_start_date || 'Unknown'}</Item.Description> <Item.Description>Joined: {x.member.current_start_date || 'Unknown'}</Item.Description>
</Item.Content> </Item.Content>
</Item> </Item>
) )
@ -74,7 +74,7 @@ export function Members(props) {
}; };
export function MemberDetail(props) { export function MemberDetail(props) {
const [member, setMember] = useState(false); const [result, setResult] = useState(false);
const [error, setError] = useState(false); const [error, setError] = useState(false);
const { token, user } = props; const { token, user } = props;
const { id } = useParams(); const { id } = useParams();
@ -82,7 +82,7 @@ export function MemberDetail(props) {
useEffect(() => { useEffect(() => {
requester('/search/'+id+'/', 'GET', token) requester('/search/'+id+'/', 'GET', token)
.then(res => { .then(res => {
setMember(res); setResult(res);
}) })
.catch(err => { .catch(err => {
console.log(err); console.log(err);
@ -90,6 +90,8 @@ export function MemberDetail(props) {
}); });
}, []); }, []);
const member = result.member || false;
return ( return (
<Container> <Container>
{!error ? {!error ?
@ -104,7 +106,7 @@ export function MemberDetail(props) {
</p> </p>
{isAdmin(user) ? {isAdmin(user) ?
<AdminMemberInfo {...props} /> <AdminMemberInfo result={result} setResult={setResult} {...props} />
: :
<BasicTable> <BasicTable>
<Table.Body> <Table.Body>
@ -122,7 +124,9 @@ export function MemberDetail(props) {
</Grid.Column> </Grid.Column>
<Grid.Column> <Grid.Column>
{isAdmin(user) && <Segment padded><AdminMemberForm {...props} /></Segment>} {isAdmin(user) && <Segment padded>
<AdminMemberForm result={result} setResult={setResult} {...props} />
</Segment>}
</Grid.Column> </Grid.Column>
</Grid> </Grid>

View File

@ -51,7 +51,7 @@ export const requester = (route, method, token, data) => {
return response.json(); return response.json();
}) })
.catch(error => { .catch(error => {
const code = error.data.status; const code = error.data ? error.data.status : null;
if (code == 413) { if (code == 413) {
throw customError({non_field_errors: ['File too big']}); throw customError({non_field_errors: ['File too big']});
} else if (code >= 400 && code < 500) { } else if (code >= 400 && code < 500) {